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
2e013370d0c85907c4af9e942f216990601a5764
984
h
C
src/RTreeController.h
CristobalM/logaritmos_tarea1
7d270e4ff310640c780ed30b23edc3577300d583
[ "MIT" ]
null
null
null
src/RTreeController.h
CristobalM/logaritmos_tarea1
7d270e4ff310640c780ed30b23edc3577300d583
[ "MIT" ]
null
null
null
src/RTreeController.h
CristobalM/logaritmos_tarea1
7d270e4ff310640c780ed30b23edc3577300d583
[ "MIT" ]
null
null
null
// // Created by Cristobal M on 10/3/17. // #ifndef LOGARITMOS_TAREA1_RTREECONTROLLER_H #define LOGARITMOS_TAREA1_RTREECONTROLLER_H #include "RTree.h" #include "SplitHeuristic.h" class RTreeController { int rootFilenameIndex; int memorySize; SplitHeuristic *splitHeuristic; std::string controllerPrefix; void insertRec(Rectangle &rectangle); void Rsearch(std::shared_ptr<RTree> rtree, Rectangle &rectangle, std::vector<int> &found); public: std::shared_ptr<RTree> currentNode; CachingRTree Cached; explicit RTreeController(int rootFilenameIndex, SplitHeuristic *heuristic); RTreeController(int rootFilenameIndex, int memorySize, SplitHeuristic *); void insert(Rectangle &rectangle); std::vector<int> search(Rectangle &rectangle); int getRootFilenameIndex() const; std::string getControllerPrefix(); void beginAtRoot(); vRect extractDataMBRS(); void extractDataMBRSRec(vRect &partial); }; #endif //LOGARITMOS_TAREA1_RTREECONTROLLER_H
21.391304
92
0.771341
[ "vector" ]
2e12ec08ccea37eeef3f35be2b8c1bdc915ed34f
4,421
h
C
ustore_home/include/net/net.h
ooibc88/Hyperledger-Fabric-
b6011f90c41b79d670fc52d6ee6f92f8046c6674
[ "Apache-2.0" ]
103
2019-08-23T05:59:14.000Z
2022-02-16T08:53:08.000Z
ustore_home/include/net/net.h
ooibc88/Hyperledger-Fabric-
b6011f90c41b79d670fc52d6ee6f92f8046c6674
[ "Apache-2.0" ]
18
2020-04-29T19:25:54.000Z
2022-03-14T15:27:15.000Z
ustore_home/include/net/net.h
ooibc88/Hyperledger-Fabric-
b6011f90c41b79d670fc52d6ee6f92f8046c6674
[ "Apache-2.0" ]
40
2019-09-03T10:22:20.000Z
2022-03-05T12:30:14.000Z
// Copyright (c) 2017 The Ustore Authors. #ifndef USTORE_NET_NET_H_ #define USTORE_NET_NET_H_ #include <string> #include <unordered_map> #include <vector> #include "types/type.h" #include "utils/noncopyable.h" #include "utils/logging.h" namespace ustore { using node_id_t = std::string; const char kCloseMsg[] = "+close"; /** * Callback functor that is invoked on receiving of a message. * The network thread will free the message after calling this, so if * the message is to be processed asynchronously, a copy must be made. * handler: is the pointer to the object that processes the message * it is "registered" via the Net object (RegisterRecv) * source: extracted from the received socket */ class CallBack { public: explicit CallBack(void* handler): handler_(handler) {} ~CallBack() {} virtual void operator()(const void* msg, int size, const node_id_t& source) = 0; protected: void* handler_; }; class NetContext; /** * Wrapper to all network connections. This should be created only once for each network * implementation (either TCP or RDMA). */ class Net : private Noncopyable { public: virtual ~Net(); // create the NetContext of idth node virtual NetContext* CreateNetContext(const node_id_t& id) = 0; // delete the NetContext virtual void DeleteNetContext(NetContext* ctx); inline void DeleteNetContext(const node_id_t& id) { // CHECK(ContainNetContext(id)); if (netmap_.count(id)) { DeleteNetContext(netmap_.at(id)); netmap_.erase(id); DLOG(INFO) << "Delete NetContext " << id; } } // create the NetContexts of all the nodes void CreateNetContexts(const std::vector<node_id_t>& nodes); virtual void Start() = 0; // start the listening service virtual void Stop() = 0; // stop the listening service inline bool IsRunning() const noexcept { return is_running_; } // get the NetContext of the idth node inline const node_id_t& GetNodeID() const { return cur_node_; } inline NetContext* GetNetContext(const node_id_t& id) const { return netmap_.at(id); } inline bool ContainNetContext(const node_id_t& id) const { return netmap_.count(id) == 1 ? true : false; } /** * Register the callback function that will be called whenever there is new * data is received * func: the callback function * handler: pointer to a object that handle this request * * anh: originally this is a member of NetContext. But moved here to make * it cleaner. First, it needs to registered only once, instead of for as many as * the number of connections. Second, there is no concurrency problem, because the * received socket is read by only one (the main) thread. */ inline void RegisterRecv(CallBack* cb) { cb_ = cb; } protected: Net() {} explicit Net(const node_id_t& id) : cur_node_(id) {} node_id_t cur_node_; std::unordered_map<node_id_t, NetContext*> netmap_; CallBack* cb_ = nullptr; volatile bool is_running_; }; /** * Generic network context representing one end-to-end connection. */ class NetContext { public: NetContext() = default; // Initialize connection to another node NetContext(const node_id_t& src, const node_id_t& dest) : src_id_(src), dest_id_(dest) {} virtual ~NetContext() = default; // Non-blocking APIs /* * send the data stored in ptr[0, len-1] * ptr: the starting pointer to send * len: size of the buffer * func: callback function after send completion (not supported) * handler: the application-provided handler that will be used in the callback * function (not supported) */ virtual ssize_t Send(const void* ptr, size_t len, CallBack* func = nullptr) = 0; // Blocking APIs (not supported) virtual ssize_t SyncSend(const void* ptr, size_t len); virtual ssize_t SyncRecv(const void* ptr, size_t len); // methods to access private variables inline const node_id_t& srcID() const noexcept { return src_id_; } inline const node_id_t& destID() const noexcept { return dest_id_; } protected: node_id_t src_id_, dest_id_; }; namespace net { // create network instance, caller is responsible for the allocated instance Net* CreateServerNetwork(const node_id_t& id, int n_threads = 1); Net* CreateClientNetwork(int n_threads = 1); } // namespace net } // namespace ustore #endif // USTORE_NET_NET_H_
30.07483
88
0.700294
[ "object", "vector" ]
2e1f577a7258a90d52c40c5edff5b85a4bab3b42
1,132
h
C
JLJSONMapping/Category/NSError+JLJSONMapping.h
taquitos/JLObjectMapping
0f869b79e19c9b7527f07b7f2533816dbd3e9668
[ "MIT" ]
3
2015-01-20T03:31:50.000Z
2021-02-28T05:37:37.000Z
JLJSONMapping/Category/NSError+JLJSONMapping.h
taquitos/JLObjectMapping
0f869b79e19c9b7527f07b7f2533816dbd3e9668
[ "MIT" ]
6
2015-01-14T04:24:01.000Z
2015-06-26T17:29:49.000Z
JLJSONMapping/Category/NSError+JLJSONMapping.h
taquitos/JLObjectMapping
0f869b79e19c9b7527f07b7f2533816dbd3e9668
[ "MIT" ]
1
2015-04-10T14:23:15.000Z
2015-04-10T14:23:15.000Z
// // NSError+JLJSONMapping.h // JLJSONMapping // // Created by Joshua Liebowitz on 1/16/15. // Copyright (c) 2015 Joshua Liebowitz. All rights reserved. // #import <Foundation/Foundation.h> FOUNDATION_EXPORT NSString * const kObjectMappingDomain; FOUNDATION_EXPORT NSString * const kObjectMappingDescriptionKey; FOUNDATION_EXPORT NSString * const kObjectMappingFailureReasonKey; typedef NS_ENUM(NSInteger, JLDeserializationError) { JLDeserializationErrorInvalidJSON, //Malformed JSON or other general NSJSONSerialization Error JLDeserializationErrorNoPropertiesInClass, //Couldn't find any properties on Object JLDeserializationErrorPropertyTypeMapNeeded, //Object has Array/Dict as property but missing definition of jl_propertyTypeMap JLDeserializationErrorMorePropertiesExpected //JSON to Object mismatch, JSON has extra fields (not a show stopping error for deserializer) }; void linkErrorCategory(void); @interface NSError (JLJSONMapping) + (NSError *)errorWithReason:(JLDeserializationError)reason reasonText:(NSString *)reasonText description:(NSString *)description; @end
39.034483
145
0.79682
[ "object" ]
2e3027dfa544d23851b7eb09a457e187cfec0e3c
1,870
h
C
CommandLib/include/CommandMonitor.h
efieleke/CommandLibForCPP
b44a32247be709cfc4642d5b1e9b8178d90b6952
[ "MIT" ]
null
null
null
CommandLib/include/CommandMonitor.h
efieleke/CommandLibForCPP
b44a32247be709cfc4642d5b1e9b8178d90b6952
[ "MIT" ]
null
null
null
CommandLib/include/CommandMonitor.h
efieleke/CommandLibForCPP
b44a32247be709cfc4642d5b1e9b8178d90b6952
[ "MIT" ]
null
null
null
#pragma once #include <exception> #include <memory> namespace CommandLib { class Command; /// <summary> /// This is a callback interface for <see cref="Command"/> starting and finishing events. Its intended use is for logging and diagnostics. /// </summary> /// <remarks> /// <see cref="CommandTracer"/> and <see cref="CommandLogger"/> are available implementations. /// You may add a monitor via the static <see cref="Command::sm_monitors"/> member of <see cref="Command"/>. Monitors added to that /// member will be called for every Command object that executes. To receive callbacks only for commands dispatched via /// a <see cref="CommandDispatcher"/>, use <see cref="CommandDispatcher::AddMonitor(CommandMonitor*)"/>. /// </remarks> class CommandMonitor { public: virtual ~CommandMonitor(); /// <summary> /// Invoked when a <see cref="Command"/> (including owned commands) starts execution /// </summary> /// <param name="command"> /// The command that is starting execution. /// </param> /// <remarks> /// Implementations of this method must not throw. /// </remarks> virtual void CommandStarting(const Command& command) = 0; /// <summary> /// Invoked by the framework whenever a <see cref="Command"/> (including owned commands) is finishing execution, for whatever reason (success, fail, or abort). /// </summary> /// <param name="command"> /// The command that is finishing execution. /// </param> /// <param name="exc"> /// Will be null if the command succeeded. Otherwise will be a <see cref="CommandAbortedException"/> if the command was aborted, or some other /// Exception type if the command failed. /// </param> /// <remarks> /// Implementations of this method must not throw. /// </remarks> virtual void CommandFinished(const Command& command, const std::exception* exc) = 0; }; }
37.4
161
0.687701
[ "object" ]
2e3e6eb237af3da1ef3c4010d48573c72fdf1266
3,674
c
C
src/boot/flashconfig.c
RenaKunisaki/micron
08a17aca0a5ad52cd08a7c8716ba6f9f0b814070
[ "MIT" ]
null
null
null
src/boot/flashconfig.c
RenaKunisaki/micron
08a17aca0a5ad52cd08a7c8716ba6f9f0b814070
[ "MIT" ]
null
null
null
src/boot/flashconfig.c
RenaKunisaki/micron
08a17aca0a5ad52cd08a7c8716ba6f9f0b814070
[ "MIT" ]
null
null
null
/** Flash config settings for the MK20 chip. * ******************************************************************************* * _ //` `\ * * _,-"\% // /``\`\ DANGER! * * ~^~ >__^ |% // / } `\`\ * * HERE ) )%// / } } }`\`\ * * BE / (%/'/.\_/\_/\_/\`/ * * DRAGONS! ( ' `-._` * * \ , ( \ _`-.__.-;%> * * /_`\ \ `\ \." `-..-'` * * ``` /_/`"-=-'`/_/ * * ``` ``` art by jgs * ******************************************************************************* * This section defines the flash protection (security) settings, which can be * used to lock sectors of flash memory, rendering them unreadable by external * means and unprivileged code. Incorrect settings could render your flash * memory unusable! * * DO NOT CHANGE THESE SETTINGS UNLESS YOU'RE SURE YOU KNOW WHAT YOU'RE DOING. */ #include "startup.h" #ifdef __cplusplus extern "C" { #endif SECTION(".flashconfig") USED_SYMBOL const struct { uint8_t KEY[8]; //secret Backdoor Key that can be used (when enabled in //FSEC) to reset flash security settings, if using those. uint8_t FPROT[4]; //Program Flash Protection bytes //each bit corresponds to 1/32 of Program Flash memory //0 = protected (read-only) //1 = not protected (rewritable/erasable) //in privileged mode (NVM Special mode), the protection flags can be //changed (at memory address 0x4002001n if I'm reading this correctly), so it's possible to unprotect //so it's possible to unprotect and rewrite the Flash Config area. uint8_t FSEC; //Flash Security Byte //bits 7-6: KEYEN: Backdoor Key Enable // 00 = disable // 01 = disable (preferred value) // 10 = enable // 11 = disable //bits 5-4: MEEN: Mass Erase Enable // 10 = disable, else = enable //bits 3-2: FSLACC (Freescale Failure Analysis Access Code) // 00 or 11 = granted, else = denied //bits 1-0: SEC (Flash Security) // 10 = unsecure, else = secure uint8_t FOPT; //Flash Nonvolatile Option Byte //bits 7-3: reserved //bit 2: NMI_DIS: 0=disable NMI interrupts //bit 1: EZPORT_DIS: 0=disable EzPort //bit 0: LPBOOT: whether to boot in low-power mode. controls default //states of some clock dividers (SIM_CLKDIV1) at reset: // 0 (low power mode): // OUTDIV1 (core clock divider) = 0x7 (divide by 8) // OUTDIV2 (bus clock divider) = 0x7 (divide by 8) // OUTDIV4 (flash clock divider) = 0xF (divide by 16) // 1 (normal mode): // OUTDIV1 (core clock divider) = 0x0 (divide by 1) // OUTDIV2 (bus clock divider) = 0x0 (divide by 1) // OUTDIV4 (flash clock divider) = 0x1 (divide by 2) uint8_t FEPROT; //EEPROM Protection Byte (same as FPROT but for EEPROM) uint8_t FDPROT; //Data Flash Protection byte (FPROT but for Data Flash) } PACKED flashConfig = { //default settings: disable all security features. //you might change these if you're building some gadget that you want to //try to protect the contents of. .KEY = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, .FPROT = {0xFF, 0xFF, 0xFF, 0xFF}, .FSEC = 0xFE, .FOPT = 0xFF, .FEPROT = 0xFF, .FDPROT = 0xFF, }; #ifdef __cplusplus } //extern "C" #endif
45.358025
103
0.518508
[ "render" ]
2e43c5fec9bf5dbd7328a73eeeff461ac71283ad
57,357
h
C
Util/llvm/tools/clang/include/clang/AST/ExprCXX.h
ianloic/unladen-swallow
28148f4ddbb3d519042de1f9fc9f1356fdd31e31
[ "PSF-2.0" ]
5
2020-06-30T05:06:40.000Z
2021-05-24T08:38:33.000Z
Util/llvm/tools/clang/include/clang/AST/ExprCXX.h
ianloic/unladen-swallow
28148f4ddbb3d519042de1f9fc9f1356fdd31e31
[ "PSF-2.0" ]
null
null
null
Util/llvm/tools/clang/include/clang/AST/ExprCXX.h
ianloic/unladen-swallow
28148f4ddbb3d519042de1f9fc9f1356fdd31e31
[ "PSF-2.0" ]
2
2015-10-01T18:28:20.000Z
2020-09-09T16:25:27.000Z
//===--- ExprCXX.h - Classes for representing expressions -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Expr interface and subclasses for C++ expressions. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_EXPRCXX_H #define LLVM_CLANG_AST_EXPRCXX_H #include "clang/Basic/TypeTraits.h" #include "clang/AST/Expr.h" #include "clang/AST/Decl.h" namespace clang { class CXXConstructorDecl; class CXXDestructorDecl; class CXXMethodDecl; class CXXTemporary; //===--------------------------------------------------------------------===// // C++ Expressions. //===--------------------------------------------------------------------===// /// \brief A call to an overloaded operator written using operator /// syntax. /// /// Represents a call to an overloaded operator written using operator /// syntax, e.g., "x + y" or "*p". While semantically equivalent to a /// normal call, this AST node provides better information about the /// syntactic representation of the call. /// /// In a C++ template, this expression node kind will be used whenever /// any of the arguments are type-dependent. In this case, the /// function itself will be a (possibly empty) set of functions and /// function templates that were found by name lookup at template /// definition time. class CXXOperatorCallExpr : public CallExpr { /// \brief The overloaded operator. OverloadedOperatorKind Operator; public: CXXOperatorCallExpr(ASTContext& C, OverloadedOperatorKind Op, Expr *fn, Expr **args, unsigned numargs, QualType t, SourceLocation operatorloc) : CallExpr(C, CXXOperatorCallExprClass, fn, args, numargs, t, operatorloc), Operator(Op) {} explicit CXXOperatorCallExpr(ASTContext& C, EmptyShell Empty) : CallExpr(C, CXXOperatorCallExprClass, Empty) { } /// getOperator - Returns the kind of overloaded operator that this /// expression refers to. OverloadedOperatorKind getOperator() const { return Operator; } void setOperator(OverloadedOperatorKind Kind) { Operator = Kind; } /// getOperatorLoc - Returns the location of the operator symbol in /// the expression. When @c getOperator()==OO_Call, this is the /// location of the right parentheses; when @c /// getOperator()==OO_Subscript, this is the location of the right /// bracket. SourceLocation getOperatorLoc() const { return getRParenLoc(); } virtual SourceRange getSourceRange() const; static bool classof(const Stmt *T) { return T->getStmtClass() == CXXOperatorCallExprClass; } static bool classof(const CXXOperatorCallExpr *) { return true; } }; /// CXXMemberCallExpr - Represents a call to a member function that /// may be written either with member call syntax (e.g., "obj.func()" /// or "objptr->func()") or with normal function-call syntax /// ("func()") within a member function that ends up calling a member /// function. The callee in either case is a MemberExpr that contains /// both the object argument and the member function, while the /// arguments are the arguments within the parentheses (not including /// the object argument). class CXXMemberCallExpr : public CallExpr { public: CXXMemberCallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t, SourceLocation rparenloc) : CallExpr(C, CXXMemberCallExprClass, fn, args, numargs, t, rparenloc) {} /// getImplicitObjectArgument - Retrieves the implicit object /// argument for the member call. For example, in "x.f(5)", this /// operation would return "x". Expr *getImplicitObjectArgument(); virtual SourceRange getSourceRange() const; static bool classof(const Stmt *T) { return T->getStmtClass() == CXXMemberCallExprClass; } static bool classof(const CXXMemberCallExpr *) { return true; } }; /// CXXNamedCastExpr - Abstract class common to all of the C++ "named" /// casts, @c static_cast, @c dynamic_cast, @c reinterpret_cast, or @c /// const_cast. /// /// This abstract class is inherited by all of the classes /// representing "named" casts, e.g., CXXStaticCastExpr, /// CXXDynamicCastExpr, CXXReinterpretCastExpr, and CXXConstCastExpr. class CXXNamedCastExpr : public ExplicitCastExpr { private: SourceLocation Loc; // the location of the casting op protected: CXXNamedCastExpr(StmtClass SC, QualType ty, CastKind kind, Expr *op, QualType writtenTy, SourceLocation l) : ExplicitCastExpr(SC, ty, kind, op, writtenTy), Loc(l) {} public: const char *getCastName() const; /// \brief Retrieve the location of the cast operator keyword, e.g., /// "static_cast". SourceLocation getOperatorLoc() const { return Loc; } void setOperatorLoc(SourceLocation L) { Loc = L; } virtual SourceRange getSourceRange() const { return SourceRange(Loc, getSubExpr()->getSourceRange().getEnd()); } static bool classof(const Stmt *T) { switch (T->getStmtClass()) { case CXXNamedCastExprClass: case CXXStaticCastExprClass: case CXXDynamicCastExprClass: case CXXReinterpretCastExprClass: case CXXConstCastExprClass: return true; default: return false; } } static bool classof(const CXXNamedCastExpr *) { return true; } }; /// CXXStaticCastExpr - A C++ @c static_cast expression (C++ [expr.static.cast]). /// /// This expression node represents a C++ static cast, e.g., /// @c static_cast<int>(1.0). class CXXStaticCastExpr : public CXXNamedCastExpr { public: CXXStaticCastExpr(QualType ty, CastKind kind, Expr *op, QualType writtenTy, SourceLocation l) : CXXNamedCastExpr(CXXStaticCastExprClass, ty, kind, op, writtenTy, l) {} static bool classof(const Stmt *T) { return T->getStmtClass() == CXXStaticCastExprClass; } static bool classof(const CXXStaticCastExpr *) { return true; } }; /// CXXDynamicCastExpr - A C++ @c dynamic_cast expression /// (C++ [expr.dynamic.cast]), which may perform a run-time check to /// determine how to perform the type cast. /// /// This expression node represents a dynamic cast, e.g., /// @c dynamic_cast<Derived*>(BasePtr). class CXXDynamicCastExpr : public CXXNamedCastExpr { public: CXXDynamicCastExpr(QualType ty, CastKind kind, Expr *op, QualType writtenTy, SourceLocation l) : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, kind, op, writtenTy, l) {} static bool classof(const Stmt *T) { return T->getStmtClass() == CXXDynamicCastExprClass; } static bool classof(const CXXDynamicCastExpr *) { return true; } }; /// CXXReinterpretCastExpr - A C++ @c reinterpret_cast expression (C++ /// [expr.reinterpret.cast]), which provides a differently-typed view /// of a value but performs no actual work at run time. /// /// This expression node represents a reinterpret cast, e.g., /// @c reinterpret_cast<int>(VoidPtr). class CXXReinterpretCastExpr : public CXXNamedCastExpr { public: CXXReinterpretCastExpr(QualType ty, CastKind kind, Expr *op, QualType writtenTy, SourceLocation l) : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, kind, op, writtenTy, l) {} static bool classof(const Stmt *T) { return T->getStmtClass() == CXXReinterpretCastExprClass; } static bool classof(const CXXReinterpretCastExpr *) { return true; } }; /// CXXConstCastExpr - A C++ @c const_cast expression (C++ [expr.const.cast]), /// which can remove type qualifiers but does not change the underlying value. /// /// This expression node represents a const cast, e.g., /// @c const_cast<char*>(PtrToConstChar). class CXXConstCastExpr : public CXXNamedCastExpr { public: CXXConstCastExpr(QualType ty, Expr *op, QualType writtenTy, SourceLocation l) : CXXNamedCastExpr(CXXConstCastExprClass, ty, CK_NoOp, op, writtenTy, l) {} static bool classof(const Stmt *T) { return T->getStmtClass() == CXXConstCastExprClass; } static bool classof(const CXXConstCastExpr *) { return true; } }; /// CXXBoolLiteralExpr - [C++ 2.13.5] C++ Boolean Literal. /// class CXXBoolLiteralExpr : public Expr { bool Value; SourceLocation Loc; public: CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l) : Expr(CXXBoolLiteralExprClass, Ty), Value(val), Loc(l) {} bool getValue() const { return Value; } virtual SourceRange getSourceRange() const { return SourceRange(Loc); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXBoolLiteralExprClass; } static bool classof(const CXXBoolLiteralExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXNullPtrLiteralExpr - [C++0x 2.14.7] C++ Pointer Literal class CXXNullPtrLiteralExpr : public Expr { SourceLocation Loc; public: CXXNullPtrLiteralExpr(QualType Ty, SourceLocation l) : Expr(CXXNullPtrLiteralExprClass, Ty), Loc(l) {} virtual SourceRange getSourceRange() const { return SourceRange(Loc); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXNullPtrLiteralExprClass; } static bool classof(const CXXNullPtrLiteralExpr *) { return true; } virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXTypeidExpr - A C++ @c typeid expression (C++ [expr.typeid]), which gets /// the type_info that corresponds to the supplied type, or the (possibly /// dynamic) type of the supplied expression. /// /// This represents code like @c typeid(int) or @c typeid(*objPtr) class CXXTypeidExpr : public Expr { private: bool isTypeOp : 1; union { void *Ty; Stmt *Ex; } Operand; SourceRange Range; public: CXXTypeidExpr(bool isTypeOp, void *op, QualType Ty, const SourceRange r) : Expr(CXXTypeidExprClass, Ty, // typeid is never type-dependent (C++ [temp.dep.expr]p4) false, // typeid is value-dependent if the type or expression are dependent (isTypeOp ? QualType::getFromOpaquePtr(op)->isDependentType() : static_cast<Expr*>(op)->isValueDependent())), isTypeOp(isTypeOp), Range(r) { if (isTypeOp) Operand.Ty = op; else // op was an Expr*, so cast it back to that to be safe Operand.Ex = static_cast<Expr*>(op); } bool isTypeOperand() const { return isTypeOp; } QualType getTypeOperand() const { assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)"); return QualType::getFromOpaquePtr(Operand.Ty); } Expr* getExprOperand() const { assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)"); return static_cast<Expr*>(Operand.Ex); } virtual SourceRange getSourceRange() const { return Range; } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXTypeidExprClass; } static bool classof(const CXXTypeidExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXThisExpr - Represents the "this" expression in C++, which is a /// pointer to the object on which the current member function is /// executing (C++ [expr.prim]p3). Example: /// /// @code /// class Foo { /// public: /// void bar(); /// void test() { this->bar(); } /// }; /// @endcode class CXXThisExpr : public Expr { SourceLocation Loc; public: CXXThisExpr(SourceLocation L, QualType Type) : Expr(CXXThisExprClass, Type, // 'this' is type-dependent if the class type of the enclosing // member function is dependent (C++ [temp.dep.expr]p2) Type->isDependentType(), Type->isDependentType()), Loc(L) { } virtual SourceRange getSourceRange() const { return SourceRange(Loc); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXThisExprClass; } static bool classof(const CXXThisExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXThrowExpr - [C++ 15] C++ Throw Expression. This handles /// 'throw' and 'throw' assignment-expression. When /// assignment-expression isn't present, Op will be null. /// class CXXThrowExpr : public Expr { Stmt *Op; SourceLocation ThrowLoc; public: // Ty is the void type which is used as the result type of the // exepression. The l is the location of the throw keyword. expr // can by null, if the optional expression to throw isn't present. CXXThrowExpr(Expr *expr, QualType Ty, SourceLocation l) : Expr(CXXThrowExprClass, Ty, false, false), Op(expr), ThrowLoc(l) {} const Expr *getSubExpr() const { return cast_or_null<Expr>(Op); } Expr *getSubExpr() { return cast_or_null<Expr>(Op); } void setSubExpr(Expr *E) { Op = E; } SourceLocation getThrowLoc() const { return ThrowLoc; } void setThrowLoc(SourceLocation L) { ThrowLoc = L; } virtual SourceRange getSourceRange() const { if (getSubExpr() == 0) return SourceRange(ThrowLoc, ThrowLoc); return SourceRange(ThrowLoc, getSubExpr()->getSourceRange().getEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXThrowExprClass; } static bool classof(const CXXThrowExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXDefaultArgExpr - C++ [dcl.fct.default]. This wraps up a /// function call argument that was created from the corresponding /// parameter's default argument, when the call did not explicitly /// supply arguments for all of the parameters. class CXXDefaultArgExpr : public Expr { ParmVarDecl *Param; protected: CXXDefaultArgExpr(StmtClass SC, ParmVarDecl *param) : Expr(SC, param->hasUnparsedDefaultArg() ? param->getType().getNonReferenceType() : param->getDefaultArg()->getType()), Param(param) { } public: // Param is the parameter whose default argument is used by this // expression. static CXXDefaultArgExpr *Create(ASTContext &C, ParmVarDecl *Param) { return new (C) CXXDefaultArgExpr(CXXDefaultArgExprClass, Param); } // Retrieve the parameter that the argument was created from. const ParmVarDecl *getParam() const { return Param; } ParmVarDecl *getParam() { return Param; } // Retrieve the actual argument to the function call. const Expr *getExpr() const { return Param->getDefaultArg(); } Expr *getExpr() { return Param->getDefaultArg(); } virtual SourceRange getSourceRange() const { // Default argument expressions have no representation in the // source, so they have an empty source range. return SourceRange(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXDefaultArgExprClass; } static bool classof(const CXXDefaultArgExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXTemporary - Represents a C++ temporary. class CXXTemporary { /// Destructor - The destructor that needs to be called. const CXXDestructorDecl *Destructor; CXXTemporary(const CXXDestructorDecl *destructor) : Destructor(destructor) { } ~CXXTemporary() { } public: static CXXTemporary *Create(ASTContext &C, const CXXDestructorDecl *Destructor); void Destroy(ASTContext &Ctx); const CXXDestructorDecl *getDestructor() const { return Destructor; } }; /// CXXBindTemporaryExpr - Represents binding an expression to a temporary, /// so its destructor can be called later. class CXXBindTemporaryExpr : public Expr { CXXTemporary *Temp; Stmt *SubExpr; CXXBindTemporaryExpr(CXXTemporary *temp, Expr* subexpr) : Expr(CXXBindTemporaryExprClass, subexpr->getType()), Temp(temp), SubExpr(subexpr) { } ~CXXBindTemporaryExpr() { } protected: virtual void DoDestroy(ASTContext &C); public: static CXXBindTemporaryExpr *Create(ASTContext &C, CXXTemporary *Temp, Expr* SubExpr); CXXTemporary *getTemporary() { return Temp; } const CXXTemporary *getTemporary() const { return Temp; } const Expr *getSubExpr() const { return cast<Expr>(SubExpr); } Expr *getSubExpr() { return cast<Expr>(SubExpr); } void setSubExpr(Expr *E) { SubExpr = E; } virtual SourceRange getSourceRange() const { return SubExpr->getSourceRange(); } // Implement isa/cast/dyncast/etc. static bool classof(const Stmt *T) { return T->getStmtClass() == CXXBindTemporaryExprClass; } static bool classof(const CXXBindTemporaryExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXConstructExpr - Represents a call to a C++ constructor. class CXXConstructExpr : public Expr { CXXConstructorDecl *Constructor; bool Elidable; Stmt **Args; unsigned NumArgs; protected: CXXConstructExpr(ASTContext &C, StmtClass SC, QualType T, CXXConstructorDecl *d, bool elidable, Expr **args, unsigned numargs); ~CXXConstructExpr() { } virtual void DoDestroy(ASTContext &C); public: /// \brief Construct an empty C++ construction expression that will store /// \p numargs arguments. CXXConstructExpr(EmptyShell Empty, ASTContext &C, unsigned numargs); static CXXConstructExpr *Create(ASTContext &C, QualType T, CXXConstructorDecl *D, bool Elidable, Expr **Args, unsigned NumArgs); CXXConstructorDecl* getConstructor() const { return Constructor; } void setConstructor(CXXConstructorDecl *C) { Constructor = C; } /// \brief Whether this construction is elidable. bool isElidable() const { return Elidable; } void setElidable(bool E) { Elidable = E; } typedef ExprIterator arg_iterator; typedef ConstExprIterator const_arg_iterator; arg_iterator arg_begin() { return Args; } arg_iterator arg_end() { return Args + NumArgs; } const_arg_iterator arg_begin() const { return Args; } const_arg_iterator arg_end() const { return Args + NumArgs; } unsigned getNumArgs() const { return NumArgs; } /// getArg - Return the specified argument. Expr *getArg(unsigned Arg) { assert(Arg < NumArgs && "Arg access out of range!"); return cast<Expr>(Args[Arg]); } const Expr *getArg(unsigned Arg) const { assert(Arg < NumArgs && "Arg access out of range!"); return cast<Expr>(Args[Arg]); } /// setArg - Set the specified argument. void setArg(unsigned Arg, Expr *ArgExpr) { assert(Arg < NumArgs && "Arg access out of range!"); Args[Arg] = ArgExpr; } virtual SourceRange getSourceRange() const { // FIXME: Should we know where the parentheses are, if there are any? if (NumArgs == 0) return SourceRange(); return SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXConstructExprClass || T->getStmtClass() == CXXTemporaryObjectExprClass; } static bool classof(const CXXConstructExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXFunctionalCastExpr - Represents an explicit C++ type conversion /// that uses "functional" notion (C++ [expr.type.conv]). Example: @c /// x = int(0.5); class CXXFunctionalCastExpr : public ExplicitCastExpr { SourceLocation TyBeginLoc; SourceLocation RParenLoc; public: CXXFunctionalCastExpr(QualType ty, QualType writtenTy, SourceLocation tyBeginLoc, CastKind kind, Expr *castExpr, SourceLocation rParenLoc) : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, kind, castExpr, writtenTy), TyBeginLoc(tyBeginLoc), RParenLoc(rParenLoc) {} SourceLocation getTypeBeginLoc() const { return TyBeginLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } virtual SourceRange getSourceRange() const { return SourceRange(TyBeginLoc, RParenLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXFunctionalCastExprClass; } static bool classof(const CXXFunctionalCastExpr *) { return true; } }; /// @brief Represents a C++ functional cast expression that builds a /// temporary object. /// /// This expression type represents a C++ "functional" cast /// (C++[expr.type.conv]) with N != 1 arguments that invokes a /// constructor to build a temporary object. If N == 0 but no /// constructor will be called (because the functional cast is /// performing a value-initialized an object whose class type has no /// user-declared constructors), CXXZeroInitValueExpr will represent /// the functional cast. Finally, with N == 1 arguments the functional /// cast expression will be represented by CXXFunctionalCastExpr. /// Example: /// @code /// struct X { X(int, float); } /// /// X create_X() { /// return X(1, 3.14f); // creates a CXXTemporaryObjectExpr /// }; /// @endcode class CXXTemporaryObjectExpr : public CXXConstructExpr { SourceLocation TyBeginLoc; SourceLocation RParenLoc; public: CXXTemporaryObjectExpr(ASTContext &C, CXXConstructorDecl *Cons, QualType writtenTy, SourceLocation tyBeginLoc, Expr **Args,unsigned NumArgs, SourceLocation rParenLoc); ~CXXTemporaryObjectExpr() { } SourceLocation getTypeBeginLoc() const { return TyBeginLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } virtual SourceRange getSourceRange() const { return SourceRange(TyBeginLoc, RParenLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXTemporaryObjectExprClass; } static bool classof(const CXXTemporaryObjectExpr *) { return true; } }; /// CXXZeroInitValueExpr - [C++ 5.2.3p2] /// Expression "T()" which creates a value-initialized rvalue of type /// T, which is either a non-class type or a class type without any /// user-defined constructors. /// class CXXZeroInitValueExpr : public Expr { SourceLocation TyBeginLoc; SourceLocation RParenLoc; public: CXXZeroInitValueExpr(QualType ty, SourceLocation tyBeginLoc, SourceLocation rParenLoc ) : Expr(CXXZeroInitValueExprClass, ty, false, false), TyBeginLoc(tyBeginLoc), RParenLoc(rParenLoc) {} SourceLocation getTypeBeginLoc() const { return TyBeginLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } /// @brief Whether this initialization expression was /// implicitly-generated. bool isImplicit() const { return TyBeginLoc.isInvalid() && RParenLoc.isInvalid(); } virtual SourceRange getSourceRange() const { return SourceRange(TyBeginLoc, RParenLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXZeroInitValueExprClass; } static bool classof(const CXXZeroInitValueExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXConditionDeclExpr - Condition declaration of a if/switch/while/for /// statement, e.g: "if (int x = f()) {...}". /// The main difference with DeclRefExpr is that CXXConditionDeclExpr owns the /// decl that it references. /// class CXXConditionDeclExpr : public DeclRefExpr { public: CXXConditionDeclExpr(SourceLocation startLoc, SourceLocation eqLoc, VarDecl *var) : DeclRefExpr(CXXConditionDeclExprClass, var, var->getType().getNonReferenceType(), startLoc, var->getType()->isDependentType(), /*FIXME:integral constant?*/ var->getType()->isDependentType()) {} SourceLocation getStartLoc() const { return getLocation(); } VarDecl *getVarDecl() { return cast<VarDecl>(getDecl()); } const VarDecl *getVarDecl() const { return cast<VarDecl>(getDecl()); } virtual SourceRange getSourceRange() const { return SourceRange(getStartLoc(), getVarDecl()->getInit()->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXConditionDeclExprClass; } static bool classof(const CXXConditionDeclExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXNewExpr - A new expression for memory allocation and constructor calls, /// e.g: "new CXXNewExpr(foo)". class CXXNewExpr : public Expr { // Was the usage ::new, i.e. is the global new to be used? bool GlobalNew : 1; // Was the form (type-id) used? Otherwise, it was new-type-id. bool ParenTypeId : 1; // Is there an initializer? If not, built-ins are uninitialized, else they're // value-initialized. bool Initializer : 1; // Do we allocate an array? If so, the first SubExpr is the size expression. bool Array : 1; // The number of placement new arguments. unsigned NumPlacementArgs : 14; // The number of constructor arguments. This may be 1 even for non-class // types; use the pseudo copy constructor. unsigned NumConstructorArgs : 14; // Contains an optional array size expression, any number of optional // placement arguments, and any number of optional constructor arguments, // in that order. Stmt **SubExprs; // Points to the allocation function used. FunctionDecl *OperatorNew; // Points to the deallocation function used in case of error. May be null. FunctionDecl *OperatorDelete; // Points to the constructor used. Cannot be null if AllocType is a record; // it would still point at the default constructor (even an implicit one). // Must be null for all other types. CXXConstructorDecl *Constructor; SourceLocation StartLoc; SourceLocation EndLoc; public: CXXNewExpr(bool globalNew, FunctionDecl *operatorNew, Expr **placementArgs, unsigned numPlaceArgs, bool ParenTypeId, Expr *arraySize, CXXConstructorDecl *constructor, bool initializer, Expr **constructorArgs, unsigned numConsArgs, FunctionDecl *operatorDelete, QualType ty, SourceLocation startLoc, SourceLocation endLoc); ~CXXNewExpr() { delete[] SubExprs; } QualType getAllocatedType() const { assert(getType()->isPointerType()); return getType()->getAs<PointerType>()->getPointeeType(); } FunctionDecl *getOperatorNew() const { return OperatorNew; } FunctionDecl *getOperatorDelete() const { return OperatorDelete; } CXXConstructorDecl *getConstructor() const { return Constructor; } bool isArray() const { return Array; } Expr *getArraySize() { return Array ? cast<Expr>(SubExprs[0]) : 0; } const Expr *getArraySize() const { return Array ? cast<Expr>(SubExprs[0]) : 0; } unsigned getNumPlacementArgs() const { return NumPlacementArgs; } Expr *getPlacementArg(unsigned i) { assert(i < NumPlacementArgs && "Index out of range"); return cast<Expr>(SubExprs[Array + i]); } const Expr *getPlacementArg(unsigned i) const { assert(i < NumPlacementArgs && "Index out of range"); return cast<Expr>(SubExprs[Array + i]); } bool isGlobalNew() const { return GlobalNew; } bool isParenTypeId() const { return ParenTypeId; } bool hasInitializer() const { return Initializer; } unsigned getNumConstructorArgs() const { return NumConstructorArgs; } Expr *getConstructorArg(unsigned i) { assert(i < NumConstructorArgs && "Index out of range"); return cast<Expr>(SubExprs[Array + NumPlacementArgs + i]); } const Expr *getConstructorArg(unsigned i) const { assert(i < NumConstructorArgs && "Index out of range"); return cast<Expr>(SubExprs[Array + NumPlacementArgs + i]); } typedef ExprIterator arg_iterator; typedef ConstExprIterator const_arg_iterator; arg_iterator placement_arg_begin() { return SubExprs + Array; } arg_iterator placement_arg_end() { return SubExprs + Array + getNumPlacementArgs(); } const_arg_iterator placement_arg_begin() const { return SubExprs + Array; } const_arg_iterator placement_arg_end() const { return SubExprs + Array + getNumPlacementArgs(); } arg_iterator constructor_arg_begin() { return SubExprs + Array + getNumPlacementArgs(); } arg_iterator constructor_arg_end() { return SubExprs + Array + getNumPlacementArgs() + getNumConstructorArgs(); } const_arg_iterator constructor_arg_begin() const { return SubExprs + Array + getNumPlacementArgs(); } const_arg_iterator constructor_arg_end() const { return SubExprs + Array + getNumPlacementArgs() + getNumConstructorArgs(); } virtual SourceRange getSourceRange() const { return SourceRange(StartLoc, EndLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXNewExprClass; } static bool classof(const CXXNewExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// CXXDeleteExpr - A delete expression for memory deallocation and destructor /// calls, e.g. "delete[] pArray". class CXXDeleteExpr : public Expr { // Is this a forced global delete, i.e. "::delete"? bool GlobalDelete : 1; // Is this the array form of delete, i.e. "delete[]"? bool ArrayForm : 1; // Points to the operator delete overload that is used. Could be a member. FunctionDecl *OperatorDelete; // The pointer expression to be deleted. Stmt *Argument; // Location of the expression. SourceLocation Loc; public: CXXDeleteExpr(QualType ty, bool globalDelete, bool arrayForm, FunctionDecl *operatorDelete, Expr *arg, SourceLocation loc) : Expr(CXXDeleteExprClass, ty, false, false), GlobalDelete(globalDelete), ArrayForm(arrayForm), OperatorDelete(operatorDelete), Argument(arg), Loc(loc) { } bool isGlobalDelete() const { return GlobalDelete; } bool isArrayForm() const { return ArrayForm; } FunctionDecl *getOperatorDelete() const { return OperatorDelete; } Expr *getArgument() { return cast<Expr>(Argument); } const Expr *getArgument() const { return cast<Expr>(Argument); } virtual SourceRange getSourceRange() const { return SourceRange(Loc, Argument->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXDeleteExprClass; } static bool classof(const CXXDeleteExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// \brief Represents a C++ pseudo-destructor (C++ [expr.pseudo]). /// /// Example: /// /// \code /// template<typename T> /// void destroy(T* ptr) { /// ptr->~T(); /// } /// \endcode /// /// When the template is parsed, the expression \c ptr->~T will be stored as /// a member reference expression. If it then instantiated with a scalar type /// as a template argument for T, the resulting expression will be a /// pseudo-destructor expression. class CXXPseudoDestructorExpr : public Expr { /// \brief The base expression (that is being destroyed). Stmt *Base; /// \brief Whether the operator was an arrow ('->'); otherwise, it was a /// period ('.'). bool IsArrow : 1; /// \brief The location of the '.' or '->' operator. SourceLocation OperatorLoc; /// \brief The nested-name-specifier that follows the operator, if present. NestedNameSpecifier *Qualifier; /// \brief The source range that covers the nested-name-specifier, if /// present. SourceRange QualifierRange; /// \brief The type being destroyed. QualType DestroyedType; /// \brief The location of the type after the '~'. SourceLocation DestroyedTypeLoc; public: CXXPseudoDestructorExpr(ASTContext &Context, Expr *Base, bool isArrow, SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, QualType DestroyedType, SourceLocation DestroyedTypeLoc) : Expr(CXXPseudoDestructorExprClass, Context.getPointerType(Context.getFunctionType(Context.VoidTy, 0, 0, false, 0)), /*isTypeDependent=*/false, /*isValueDependent=*/Base->isValueDependent()), Base(static_cast<Stmt *>(Base)), IsArrow(isArrow), OperatorLoc(OperatorLoc), Qualifier(Qualifier), QualifierRange(QualifierRange), DestroyedType(DestroyedType), DestroyedTypeLoc(DestroyedTypeLoc) { } void setBase(Expr *E) { Base = E; } Expr *getBase() const { return cast<Expr>(Base); } /// \brief Determines whether this member expression actually had /// a C++ nested-name-specifier prior to the name of the member, e.g., /// x->Base::foo. bool hasQualifier() const { return Qualifier != 0; } /// \brief If the member name was qualified, retrieves the source range of /// the nested-name-specifier that precedes the member name. Otherwise, /// returns an empty source range. SourceRange getQualifierRange() const { return QualifierRange; } /// \brief If the member name was qualified, retrieves the /// nested-name-specifier that precedes the member name. Otherwise, returns /// NULL. NestedNameSpecifier *getQualifier() const { return Qualifier; } /// \brief Determine whether this pseudo-destructor expression was written /// using an '->' (otherwise, it used a '.'). bool isArrow() const { return IsArrow; } void setArrow(bool A) { IsArrow = A; } /// \brief Retrieve the location of the '.' or '->' operator. SourceLocation getOperatorLoc() const { return OperatorLoc; } /// \brief Retrieve the type that is being destroyed. QualType getDestroyedType() const { return DestroyedType; } /// \brief Retrieve the location of the type being destroyed. SourceLocation getDestroyedTypeLoc() const { return DestroyedTypeLoc; } virtual SourceRange getSourceRange() const { return SourceRange(Base->getLocStart(), DestroyedTypeLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXPseudoDestructorExprClass; } static bool classof(const CXXPseudoDestructorExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// \brief Represents the name of a function that has not been /// resolved to any declaration. /// /// Unresolved function names occur when a function name is /// encountered prior to an open parentheses ('(') in a C++ function /// call, and the function name itself did not resolve to a /// declaration. These function names can only be resolved when they /// form the postfix-expression of a function call, so that /// argument-dependent lookup finds declarations corresponding to /// these functions. /// @code /// template<typename T> void f(T x) { /// g(x); // g is an unresolved function name (that is also a dependent name) /// } /// @endcode class UnresolvedFunctionNameExpr : public Expr { /// The name that was present in the source DeclarationName Name; /// The location of this name in the source code SourceLocation Loc; public: UnresolvedFunctionNameExpr(DeclarationName N, QualType T, SourceLocation L) : Expr(UnresolvedFunctionNameExprClass, T, false, false), Name(N), Loc(L) { } /// \brief Retrieves the name that occurred in the source code. DeclarationName getName() const { return Name; } /// getLocation - Retrieves the location in the source code where /// the name occurred. SourceLocation getLocation() const { return Loc; } virtual SourceRange getSourceRange() const { return SourceRange(Loc); } static bool classof(const Stmt *T) { return T->getStmtClass() == UnresolvedFunctionNameExprClass; } static bool classof(const UnresolvedFunctionNameExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// UnaryTypeTraitExpr - A GCC or MS unary type trait, as used in the /// implementation of TR1/C++0x type trait templates. /// Example: /// __is_pod(int) == true /// __is_enum(std::string) == false class UnaryTypeTraitExpr : public Expr { /// UTT - The trait. UnaryTypeTrait UTT; /// Loc - The location of the type trait keyword. SourceLocation Loc; /// RParen - The location of the closing paren. SourceLocation RParen; /// QueriedType - The type we're testing. QualType QueriedType; public: UnaryTypeTraitExpr(SourceLocation loc, UnaryTypeTrait utt, QualType queried, SourceLocation rparen, QualType ty) : Expr(UnaryTypeTraitExprClass, ty, false, queried->isDependentType()), UTT(utt), Loc(loc), RParen(rparen), QueriedType(queried) { } virtual SourceRange getSourceRange() const { return SourceRange(Loc, RParen);} UnaryTypeTrait getTrait() const { return UTT; } QualType getQueriedType() const { return QueriedType; } bool EvaluateTrait(ASTContext&) const; static bool classof(const Stmt *T) { return T->getStmtClass() == UnaryTypeTraitExprClass; } static bool classof(const UnaryTypeTraitExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// \brief A qualified reference to a name whose declaration cannot /// yet be resolved. /// /// DependentScopeDeclRefExpr is similar to eclRefExpr in that /// it expresses a reference to a declaration such as /// X<T>::value. The difference, however, is that an /// DependentScopeDeclRefExpr node is used only within C++ templates when /// the qualification (e.g., X<T>::) refers to a dependent type. In /// this case, X<T>::value cannot resolve to a declaration because the /// declaration will differ from on instantiation of X<T> to the /// next. Therefore, DependentScopeDeclRefExpr keeps track of the /// qualifier (X<T>::) and the name of the entity being referenced /// ("value"). Such expressions will instantiate to a DeclRefExpr once the /// declaration can be found. class DependentScopeDeclRefExpr : public Expr { /// The name of the entity we will be referencing. DeclarationName Name; /// Location of the name of the declaration we're referencing. SourceLocation Loc; /// QualifierRange - The source range that covers the /// nested-name-specifier. SourceRange QualifierRange; /// \brief The nested-name-specifier that qualifies this unresolved /// declaration name. NestedNameSpecifier *NNS; /// \brief Whether this expr is an address of (&) operand. /// FIXME: Stash this bit into NNS! bool IsAddressOfOperand; public: DependentScopeDeclRefExpr(DeclarationName N, QualType T, SourceLocation L, SourceRange R, NestedNameSpecifier *NNS, bool IsAddressOfOperand) : Expr(DependentScopeDeclRefExprClass, T, true, true), Name(N), Loc(L), QualifierRange(R), NNS(NNS), IsAddressOfOperand(IsAddressOfOperand) { } /// \brief Retrieve the name that this expression refers to. DeclarationName getDeclName() const { return Name; } /// \brief Retrieve the location of the name within the expression. SourceLocation getLocation() const { return Loc; } /// \brief Retrieve the source range of the nested-name-specifier. SourceRange getQualifierRange() const { return QualifierRange; } /// \brief Retrieve the nested-name-specifier that qualifies this /// declaration. NestedNameSpecifier *getQualifier() const { return NNS; } /// \brief Retrieve whether this is an address of (&) operand. bool isAddressOfOperand() const { return IsAddressOfOperand; } virtual SourceRange getSourceRange() const { return SourceRange(QualifierRange.getBegin(), getLocation()); } static bool classof(const Stmt *T) { return T->getStmtClass() == DependentScopeDeclRefExprClass; } static bool classof(const DependentScopeDeclRefExpr *) { return true; } virtual StmtIterator child_begin(); virtual StmtIterator child_end(); }; /// \brief An expression that refers to a C++ template-id, such as /// @c isa<FunctionDecl>. class TemplateIdRefExpr : public Expr { /// \brief If this template-id was qualified-id, e.g., @c std::sort<int>, /// this nested name specifier contains the @c std::. NestedNameSpecifier *Qualifier; /// \brief If this template-id was a qualified-id, e.g., @c std::sort<int>, /// this covers the source code range of the @c std::. SourceRange QualifierRange; /// \brief The actual template to which this template-id refers. TemplateName Template; /// \brief The source location of the template name. SourceLocation TemplateNameLoc; /// \brief The source location of the left angle bracket ('<'); SourceLocation LAngleLoc; /// \brief The source location of the right angle bracket ('>'); SourceLocation RAngleLoc; /// \brief The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; TemplateIdRefExpr(QualType T, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, TemplateName Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc); virtual void DoDestroy(ASTContext &Context); public: static TemplateIdRefExpr * Create(ASTContext &Context, QualType T, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, TemplateName Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc); /// \brief Retrieve the nested name specifier used to qualify the name of /// this template-id, e.g., the "std::sort" in @c std::sort<int>, or NULL /// if this template-id was an unqualified-id. NestedNameSpecifier *getQualifier() const { return Qualifier; } /// \brief Retrieve the source range describing the nested name specifier /// used to qualified the name of this template-id, if the name was qualified. SourceRange getQualifierRange() const { return QualifierRange; } /// \brief Retrieve the name of the template referenced, e.g., "sort" in /// @c std::sort<int>; TemplateName getTemplateName() const { return Template; } /// \brief Retrieve the location of the name of the template referenced, e.g., /// the location of "sort" in @c std::sort<int>. SourceLocation getTemplateNameLoc() const { return TemplateNameLoc; } /// \brief Retrieve the location of the left angle bracket following the /// template name ('<'). SourceLocation getLAngleLoc() const { return LAngleLoc; } /// \brief Retrieve the template arguments provided as part of this /// template-id. const TemplateArgumentLoc *getTemplateArgs() const { return reinterpret_cast<const TemplateArgumentLoc *>(this + 1); } /// \brief Retrieve the number of template arguments provided as part of this /// template-id. unsigned getNumTemplateArgs() const { return NumTemplateArgs; } /// \brief Retrieve the location of the right angle bracket following the /// template arguments ('>'). SourceLocation getRAngleLoc() const { return RAngleLoc; } virtual SourceRange getSourceRange() const { return SourceRange(Qualifier? QualifierRange.getBegin() : TemplateNameLoc, RAngleLoc); } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); static bool classof(const Stmt *T) { return T->getStmtClass() == TemplateIdRefExprClass; } static bool classof(const TemplateIdRefExpr *) { return true; } }; class CXXExprWithTemporaries : public Expr { Stmt *SubExpr; CXXTemporary **Temps; unsigned NumTemps; bool ShouldDestroyTemps; CXXExprWithTemporaries(Expr *SubExpr, CXXTemporary **Temps, unsigned NumTemps, bool ShouldDestroyTemps); ~CXXExprWithTemporaries(); protected: virtual void DoDestroy(ASTContext &C); public: static CXXExprWithTemporaries *Create(ASTContext &C, Expr *SubExpr, CXXTemporary **Temps, unsigned NumTemps, bool ShouldDestroyTemporaries); unsigned getNumTemporaries() const { return NumTemps; } CXXTemporary *getTemporary(unsigned i) { assert(i < NumTemps && "Index out of range"); return Temps[i]; } const CXXTemporary *getTemporary(unsigned i) const { assert(i < NumTemps && "Index out of range"); return Temps[i]; } bool shouldDestroyTemporaries() const { return ShouldDestroyTemps; } void removeLastTemporary() { NumTemps--; } Expr *getSubExpr() { return cast<Expr>(SubExpr); } const Expr *getSubExpr() const { return cast<Expr>(SubExpr); } void setSubExpr(Expr *E) { SubExpr = E; } virtual SourceRange getSourceRange() const { return SubExpr->getSourceRange(); } // Implement isa/cast/dyncast/etc. static bool classof(const Stmt *T) { return T->getStmtClass() == CXXExprWithTemporariesClass; } static bool classof(const CXXExprWithTemporaries *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// \brief Describes an explicit type conversion that uses functional /// notion but could not be resolved because one or more arguments are /// type-dependent. /// /// The explicit type conversions expressed by /// CXXUnresolvedConstructExpr have the form \c T(a1, a2, ..., aN), /// where \c T is some type and \c a1, a2, ..., aN are values, and /// either \C T is a dependent type or one or more of the \c a's is /// type-dependent. For example, this would occur in a template such /// as: /// /// \code /// template<typename T, typename A1> /// inline T make_a(const A1& a1) { /// return T(a1); /// } /// \endcode /// /// When the returned expression is instantiated, it may resolve to a /// constructor call, conversion function call, or some kind of type /// conversion. class CXXUnresolvedConstructExpr : public Expr { /// \brief The starting location of the type SourceLocation TyBeginLoc; /// \brief The type being constructed. QualType Type; /// \brief The location of the left parentheses ('('). SourceLocation LParenLoc; /// \brief The location of the right parentheses (')'). SourceLocation RParenLoc; /// \brief The number of arguments used to construct the type. unsigned NumArgs; CXXUnresolvedConstructExpr(SourceLocation TyBegin, QualType T, SourceLocation LParenLoc, Expr **Args, unsigned NumArgs, SourceLocation RParenLoc); public: static CXXUnresolvedConstructExpr *Create(ASTContext &C, SourceLocation TyBegin, QualType T, SourceLocation LParenLoc, Expr **Args, unsigned NumArgs, SourceLocation RParenLoc); /// \brief Retrieve the source location where the type begins. SourceLocation getTypeBeginLoc() const { return TyBeginLoc; } void setTypeBeginLoc(SourceLocation L) { TyBeginLoc = L; } /// \brief Retrieve the type that is being constructed, as specified /// in the source code. QualType getTypeAsWritten() const { return Type; } void setTypeAsWritten(QualType T) { Type = T; } /// \brief Retrieve the location of the left parentheses ('(') that /// precedes the argument list. SourceLocation getLParenLoc() const { return LParenLoc; } void setLParenLoc(SourceLocation L) { LParenLoc = L; } /// \brief Retrieve the location of the right parentheses (')') that /// follows the argument list. SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } /// \brief Retrieve the number of arguments. unsigned arg_size() const { return NumArgs; } typedef Expr** arg_iterator; arg_iterator arg_begin() { return reinterpret_cast<Expr**>(this + 1); } arg_iterator arg_end() { return arg_begin() + NumArgs; } Expr *getArg(unsigned I) { assert(I < NumArgs && "Argument index out-of-range"); return *(arg_begin() + I); } virtual SourceRange getSourceRange() const { return SourceRange(TyBeginLoc, RParenLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXUnresolvedConstructExprClass; } static bool classof(const CXXUnresolvedConstructExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; /// \brief Represents a C++ member access expression where the actual member /// referenced could not be resolved, e.g., because the base expression or the /// member name was dependent. class CXXDependentScopeMemberExpr : public Expr { /// \brief The expression for the base pointer or class reference, /// e.g., the \c x in x.f. Stmt *Base; /// \brief Whether this member expression used the '->' operator or /// the '.' operator. bool IsArrow : 1; /// \brief Whether this member expression has explicitly-specified template /// arguments. bool HasExplicitTemplateArgumentList : 1; /// \brief The location of the '->' or '.' operator. SourceLocation OperatorLoc; /// \brief The nested-name-specifier that precedes the member name, if any. NestedNameSpecifier *Qualifier; /// \brief The source range covering the nested name specifier. SourceRange QualifierRange; /// \brief In a qualified member access expression such as t->Base::f, this /// member stores the resolves of name lookup in the context of the member /// access expression, to be used at instantiation time. /// /// FIXME: This member, along with the Qualifier and QualifierRange, could /// be stuck into a structure that is optionally allocated at the end of /// the CXXDependentScopeMemberExpr, to save space in the common case. NamedDecl *FirstQualifierFoundInScope; /// \brief The member to which this member expression refers, which /// can be name, overloaded operator, or destructor. /// FIXME: could also be a template-id DeclarationName Member; /// \brief The location of the member name. SourceLocation MemberLoc; /// \brief Retrieve the explicit template argument list that followed the /// member template name, if any. ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() { if (!HasExplicitTemplateArgumentList) return 0; return reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1); } /// \brief Retrieve the explicit template argument list that followed the /// member template name, if any. const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const { return const_cast<CXXDependentScopeMemberExpr *>(this) ->getExplicitTemplateArgumentList(); } CXXDependentScopeMemberExpr(ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, NamedDecl *FirstQualifierFoundInScope, DeclarationName Member, SourceLocation MemberLoc, bool HasExplicitTemplateArgs, SourceLocation LAngleLoc, const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc); public: CXXDependentScopeMemberExpr(ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, NamedDecl *FirstQualifierFoundInScope, DeclarationName Member, SourceLocation MemberLoc) : Expr(CXXDependentScopeMemberExprClass, C.DependentTy, true, true), Base(Base), IsArrow(IsArrow), HasExplicitTemplateArgumentList(false), OperatorLoc(OperatorLoc), Qualifier(Qualifier), QualifierRange(QualifierRange), FirstQualifierFoundInScope(FirstQualifierFoundInScope), Member(Member), MemberLoc(MemberLoc) { } static CXXDependentScopeMemberExpr * Create(ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, NamedDecl *FirstQualifierFoundInScope, DeclarationName Member, SourceLocation MemberLoc, bool HasExplicitTemplateArgs, SourceLocation LAngleLoc, const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc); /// \brief Retrieve the base object of this member expressions, /// e.g., the \c x in \c x.m. Expr *getBase() { return cast<Expr>(Base); } void setBase(Expr *E) { Base = E; } /// \brief Determine whether this member expression used the '->' /// operator; otherwise, it used the '.' operator. bool isArrow() const { return IsArrow; } void setArrow(bool A) { IsArrow = A; } /// \brief Retrieve the location of the '->' or '.' operator. SourceLocation getOperatorLoc() const { return OperatorLoc; } void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } /// \brief Retrieve the nested-name-specifier that qualifies the member /// name. NestedNameSpecifier *getQualifier() const { return Qualifier; } /// \brief Retrieve the source range covering the nested-name-specifier /// that qualifies the member name. SourceRange getQualifierRange() const { return QualifierRange; } /// \brief Retrieve the first part of the nested-name-specifier that was /// found in the scope of the member access expression when the member access /// was initially parsed. /// /// This function only returns a useful result when member access expression /// uses a qualified member name, e.g., "x.Base::f". Here, the declaration /// returned by this function describes what was found by unqualified name /// lookup for the identifier "Base" within the scope of the member access /// expression itself. At template instantiation time, this information is /// combined with the results of name lookup into the type of the object /// expression itself (the class type of x). NamedDecl *getFirstQualifierFoundInScope() const { return FirstQualifierFoundInScope; } /// \brief Retrieve the name of the member that this expression /// refers to. DeclarationName getMember() const { return Member; } void setMember(DeclarationName N) { Member = N; } // \brief Retrieve the location of the name of the member that this // expression refers to. SourceLocation getMemberLoc() const { return MemberLoc; } void setMemberLoc(SourceLocation L) { MemberLoc = L; } /// \brief Determines whether this member expression actually had a C++ /// template argument list explicitly specified, e.g., x.f<int>. bool hasExplicitTemplateArgumentList() { return HasExplicitTemplateArgumentList; } /// \brief Retrieve the location of the left angle bracket following the /// member name ('<'), if any. SourceLocation getLAngleLoc() const { if (!HasExplicitTemplateArgumentList) return SourceLocation(); return getExplicitTemplateArgumentList()->LAngleLoc; } /// \brief Retrieve the template arguments provided as part of this /// template-id. const TemplateArgumentLoc *getTemplateArgs() const { if (!HasExplicitTemplateArgumentList) return 0; return getExplicitTemplateArgumentList()->getTemplateArgs(); } /// \brief Retrieve the number of template arguments provided as part of this /// template-id. unsigned getNumTemplateArgs() const { if (!HasExplicitTemplateArgumentList) return 0; return getExplicitTemplateArgumentList()->NumTemplateArgs; } /// \brief Retrieve the location of the right angle bracket following the /// template arguments ('>'). SourceLocation getRAngleLoc() const { if (!HasExplicitTemplateArgumentList) return SourceLocation(); return getExplicitTemplateArgumentList()->RAngleLoc; } virtual SourceRange getSourceRange() const { if (HasExplicitTemplateArgumentList) return SourceRange(Base->getSourceRange().getBegin(), getRAngleLoc()); return SourceRange(Base->getSourceRange().getBegin(), MemberLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXDependentScopeMemberExprClass; } static bool classof(const CXXDependentScopeMemberExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); }; } // end namespace clang #endif
35.983061
81
0.690256
[ "object" ]
2e4e3575411240ae3dd2d6c1ad65bf18c5028e76
8,504
h
C
src/cyclops/CyclicCoordinateDescent.h
cran/Cyclops
081ae5868cdc63cf1918a0c17828f101ff1de14f
[ "Zlib", "Apache-2.0" ]
32
2015-01-16T07:41:40.000Z
2021-10-03T09:15:37.000Z
src/cyclops/CyclicCoordinateDescent.h
cran/Cyclops
081ae5868cdc63cf1918a0c17828f101ff1de14f
[ "Zlib", "Apache-2.0" ]
47
2015-01-01T18:59:09.000Z
2022-03-31T13:21:10.000Z
src/cyclops/CyclicCoordinateDescent.h
cran/Cyclops
081ae5868cdc63cf1918a0c17828f101ff1de14f
[ "Zlib", "Apache-2.0" ]
31
2015-01-23T18:17:29.000Z
2022-03-13T20:22:33.000Z
/* * CyclicCoordinateDescent.h * * Created on: May-June, 2010 * Author: msuchard */ #ifndef CYCLICCOORDINATEDESCENT_H_ #define CYCLICCOORDINATEDESCENT_H_ #include "CcdInterface.h" #include "CompressedDataMatrix.h" #include "ModelData.h" #include "engine/AbstractModelSpecifics.h" #include "priors/JointPrior.h" #include "io/ProgressLogger.h" #include <Eigen/Dense> #include <deque> #include "Types.h" namespace bsccs { // TODO Remove 'using' from headers using std::cout; using std::cerr; using std::endl; using std::ostream; using std::ofstream; using std::string; //#define DEBUG #define TEST_SPARSE // New sparse updates are great //#define TEST_ROW_INDEX #define BETTER_LOOPS #define MERGE_TRANSFORMATION #define NEW_NUMERATOR #define SPARSE_PRODUCT #define USE_ITER //#define NO_FUSE class CyclicCoordinateDescent { public: typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Matrix; CyclicCoordinateDescent( const AbstractModelData& modelData, AbstractModelSpecifics& specifics, priors::JointPriorPtr prior, loggers::ProgressLoggerPtr logger, loggers::ErrorHandlerPtr error ); // CyclicCoordinateDescent( // int inN, // CompressedDataMatrix* inX, // int* inEta, // int* inOffs, // int* inNEvents, // int* inPid // ); CyclicCoordinateDescent* clone(); void logResults(const char* fileName, bool withASE); virtual ~CyclicCoordinateDescent(); double getLogLikelihood(void); //double getPredictiveLogLikelihood(double* weights); double getNewPredictiveLogLikelihood(double* weights); void getPredictiveEstimates(double* y, double* weights) const; double getLogPrior(void); virtual double getObjectiveFunction(int convergenceType); double getBeta(int i); int getBetaSize(void); bool getIsRegularized(int i) const; int getPredictionSize(void) const; bool getFixedBeta(int i); void setFixedBeta(int i, bool value); double getHessianDiagonal(int index); double getAsymptoticVariance(int i, int j); double getAsymptoticPrecision(int i, int j); // void setZeroBetaFixed(void); void update(const ModeFindingArguments& arguments); virtual void resetBeta(void); // Setters void setPrior(priors::JointPriorPtr newPrior); void setHyperprior(double value); // TODO depricate void setHyperprior(int index, double value); void setClassHyperprior(double value); void setPriorType(int priorType); void setWeights(double* weights); void setCensorWeights(double* weights); // ESK: New function std::vector<double> getWeights(); std::vector<double> getCensorWeights(); // ESK: void setLogisticRegression(bool idoLR); // template <typename T> void setBeta(const std::vector<double>& beta); void setBeta(int i, double beta); // void double getHessianComponent(int i, int j); // Getters std::vector<double> getHyperprior(void) const; string getPriorInfo() const; string getCrossValidationInfo() const; void setCrossValidationInfo(string info); string getConditionId() const { return conditionId; } int getUpdateCount() const { return updateCount; } int getLikelihoodCount() const { return likelihoodCount; } UpdateReturnFlags getUpdateReturnFlag() const { return lastReturnFlag; } int getIterationCount() const { return lastIterationCount; } void setNoiseLevel(NoiseLevels); void makeDirty(void); void setInitialBound(double bound); Matrix computeFisherInformation(const std::vector<IdType>& indices) const; loggers::ProgressLogger& getProgressLogger() const { return *logger; } loggers::ErrorHandler& getErrorHandler() const { return *error; } protected: bsccs::unique_ptr<AbstractModelSpecifics> privateModelSpecifics; AbstractModelSpecifics& modelSpecifics; priors::JointPriorPtr jointPrior; const AbstractModelData& hXI; CyclicCoordinateDescent(const CyclicCoordinateDescent& copy); void init(bool offset); void resetBounds(void); void computeXBeta(void); void saveXBeta(void); void computeFixedTermsInLogLikelihood(void); void computeFixedTermsInGradientAndHessian(void); void findMode(const int maxIterations, const int convergenceType, const double epsilon, const AlgorithmType algorithmType, const int qQN); template <typename Iterator> void findMode(Iterator begin, Iterator end, const int maxIterations, const int convergenceType, const double epsilon, const AlgorithmType algorithmType, const int qQN); template <typename Container> void computeKktConditions(Container& set); void kktSwindle(const ModeFindingArguments& arguments); void computeSufficientStatistics(void); void updateSufficientStatistics(double delta, int index); void computeNumeratorForGradient(int index); void computeAsymptoticPrecisionMatrix(void); void computeAsymptoticVarianceMatrix(void); template <class IteratorType> void incrementNumeratorForGradientImpl(int index); virtual void computeNEvents(void); virtual void updateXBeta(double delta, int index); template <class IteratorType> void updateXBetaImpl(double delta, int index); virtual void computeRemainingStatistics(bool skip, int index); virtual void computeRatiosForGradientAndHessian(int index); virtual void computeGradientAndHessian( int index, double *gradient, double *hessian); template <class IteratorType> void computeGradientAndHessianImpl( int index, double *gradient, double *hessian); void computeGradientAndHessianImplHand( int index, double *gradient, double *hessian); template <class IteratorType> void axpy(double* y, const double alpha, const int index); void axpyXBeta(const double beta, const int index); virtual void getDenominators(void); double computeLogLikelihood(void); void checkAllLazyFlags(void); double ccdUpdateBeta(int index); void mmUpdateAllBeta(std::vector<double>& allDelta, const std::vector<bool>& fixedBeta); double applyBounds( double inDelta, int index); bool performCheckConvergence(int convergenceType, double epsilon, int maxIterations, int iteration, double* lastObjFunc); double computeConvergenceCriterion(double newObjFxn, double oldObjFxn); virtual double computeZhangOlesConvergenceCriterion(void); template <class T> void fillVector(T* vector, const int length, const T& value) { for (int i = 0; i < length; i++) { vector[i] = value; } } template <class T> void zeroVector(T* vector, const int length) { for (int i = 0; i < length; i++) { vector[i] = 0; } } int getAlignedLength(int N); void testDimension(int givenValue, int trueValue, const char *parameterName); template <class T> void printVector(T* vector, const int length, ostream &os); template <typename Real> double oneNorm(Real* vector, const int length); template <typename Real> double twoNormSquared(Real * vector, const int length); int sign(double x); template <class T> T* readVector(const char *fileName, int *length); // Local variables ofstream outLog; bool hasLog; const double* hY; // K-vector const int* hPid; int** hXColumnRowIndicators; // J-vector typedef std::vector<double> DoubleVector; DoubleVector hBeta; // DoubleVector& hXBeta; // TODO Delegate to ModelSpecifics // DoubleVector& hXBetaSave; // Delegate DoubleVector hDelta; std::vector<bool> fixBeta; int N; // Number of patients int K; // Number of exposure levels int J; // Number of drugs string conditionId; bool computeMLE; int priorType; double initialBound; bool sufficientStatisticsKnown; bool xBetaKnown; bool fisherInformationKnown; bool varianceKnown; bool validWeights; bool useCrossValidation; bool doLogisticRegression; DoubleVector hWeights; // Make DoubleVector and delegate to ModelSpecifics DoubleVector cWeights; // ESK int updateCount; int likelihoodCount; NoiseLevels noiseLevel; UpdateReturnFlags lastReturnFlag; int lastIterationCount; Matrix hessianMatrix; Matrix varianceMatrix; typedef std::map<int, int> IndexMap; IndexMap hessianIndexMap; typedef std::pair<int, double> SetBetaEntry; typedef std::deque<SetBetaEntry> SetBetaContainer; SetBetaContainer setBetaList; string crossValidationInfo; loggers::ProgressLoggerPtr logger; loggers::ErrorHandlerPtr error; }; double convertVarianceToHyperparameter(double variance); } // namespace #endif /* CYCLICCOORDINATEDESCENT_H_ */
21.97416
88
0.748236
[ "vector" ]
2e4f6eee9d0560d184d82568b59966188151169e
245
h
C
Solution/Project/FileBrowser.h
Ilygos/sprite_editor
30c8ffdc7b133396f3a8ce255be03824374ac135
[ "MIT" ]
null
null
null
Solution/Project/FileBrowser.h
Ilygos/sprite_editor
30c8ffdc7b133396f3a8ce255be03824374ac135
[ "MIT" ]
null
null
null
Solution/Project/FileBrowser.h
Ilygos/sprite_editor
30c8ffdc7b133396f3a8ce255be03824374ac135
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <string> #include <experimental/filesystem> #include <filesystem> // With Visual Studio compiler, filesystem is still "experimental" namespace fs = std::experimental::filesystem; class FileBrowser { };
17.5
66
0.763265
[ "vector" ]
2e5b3322dd65fb1afc32a844241d2517575e6516
85,795
c
C
src/ospusageind.c
TransNexus/osptoolkit
dd27b342bb5b972590f6c3f1a99705d296dd6beb
[ "BSD-3-Clause" ]
1
2018-05-07T18:30:21.000Z
2018-05-07T18:30:21.000Z
src/ospusageind.c
TransNexus/osptoolkit
dd27b342bb5b972590f6c3f1a99705d296dd6beb
[ "BSD-3-Clause" ]
2
2019-01-07T02:17:56.000Z
2019-05-16T16:47:38.000Z
src/ospusageind.c
TransNexus/osptoolkit
dd27b342bb5b972590f6c3f1a99705d296dd6beb
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** *** COPYRIGHT (c) 2002 by TransNexus, Inc. *** *** *** *** This software is property of TransNexus, Inc. *** *** This software is freely available under license from TransNexus. *** *** The license terms and conditions for free use of this software by *** *** third parties are defined in the OSP Toolkit Software License *** *** Agreement (LICENSE.txt). Any use of this software by third *** *** parties, which does not comply with the terms and conditions of the *** *** OSP Toolkit Software License Agreement is prohibited without *** *** the prior, express, written consent of TransNexus, Inc. *** *** *** *** Thank you for using the OSP ToolKit(TM). Please report any bugs, *** *** suggestions or feedback to support@transnexus.com *** *** *** **************************************************************************/ /* ospusageind.c - OSP usage indication functions */ #include "osp/osp.h" #include "osp/osperrno.h" #include "osp/ospbfr.h" #include "osp/osplist.h" #include "osp/ospxmlattr.h" #include "osp/ospxmlelem.h" #include "osp/ospmsgattr.h" #include "osp/ospmsgelem.h" #include "osp/ospcallid.h" #include "osp/ospusage.h" #include "osp/ospusageind.h" #include "osp/ospstatistics.h" #include "osp/osputils.h" #include "osp/osptrans.h" /* * OSPPUsageIndHasTimestamp() - is the timestamp set ? */ OSPTBOOL OSPPUsageIndHasTimestamp( /* returns non-zero if number exists */ OSPT_USAGE_IND *ospvUsageInd) /* Usage Indication effected */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = (ospvUsageInd->Timestamp != 0); } return has; } /* * OSPPUsageIndSetTimestamp() - set the timestamp */ void OSPPUsageIndSetTimestamp( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ OSPTTIME ospvTimestamp) /* timestamp to set to */ { if (ospvUsageInd != OSPC_OSNULL) { if (ospvTimestamp != 0) { ospvUsageInd->Timestamp = ospvTimestamp; } } } /* * OSPPUsageIndGetTimestamp() - returns the timestamp for a usage ind */ OSPTTIME OSPPUsageIndGetTimestamp( OSPT_USAGE_IND *ospvUsageInd) /* usage ind */ { OSPTTIME time = 0; if (ospvUsageInd != OSPC_OSNULL) { time = ospvUsageInd->Timestamp; } return time; } /* * OSPPUsageIndHasRole() - Does usage indication have role set? */ OSPTBOOL OSPPUsageIndHasRole( /* returns non-zero if time */ OSPT_USAGE_IND *ospvUsageInd) /* usage indication in question */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = ospvUsageInd->HasRole; } return has; } /* * OSPPUsageIndGetRole() - returns role for an usage indication */ OSPE_ROLE OSPPUsageIndGetRole( /* returns the role (OGW/TGW) */ OSPT_USAGE_IND *ospvUsageInd) /* usage indication */ { OSPE_ROLE role = OSPC_ROLE_UNDEFINED; if (ospvUsageInd != OSPC_OSNULL) { role = ospvUsageInd->Role; } return role; } /* * OSPPUsageIndSetRole() - sets the role for an usage indication */ void OSPPUsageIndSetRole( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, OSPE_ROLE ospvRole) { if (ospvUsageInd != OSPC_OSNULL) { ospvUsageInd->Role = ospvRole; ospvUsageInd->HasRole = OSPC_TRUE; } } /* * OSPPUsageIndHasComponentId() - is the component id set ? */ OSPTBOOL OSPPUsageIndHasComponentId( /* returns non-zero if component id is set */ OSPT_USAGE_IND *ospvUsageInd) { return(ospvUsageInd->ComponentId != OSPC_OSNULL); } /* * OSPPUsageIndGetComponentId() - returns a new copy of the component id. */ const char *OSPPUsageIndGetComponentId( OSPT_USAGE_IND *ospvUsageInd) { const char *componentstring = OSPC_OSNULL; int len = 0; if (OSPPUsageIndHasComponentId(ospvUsageInd)) { len = OSPM_STRLEN(ospvUsageInd->ComponentId); OSPM_MALLOC(componentstring, char, len + 1); OSPM_MEMSET(componentstring, 0, len + 1); OSPM_MEMCPY(componentstring, ospvUsageInd->ComponentId, len); } return componentstring; } /* * OSPPUsageIndHasTransactionId() - is the transaction id set ? */ OSPTBOOL OSPPUsageIndHasTransactionId( /* returns non-zero if number exists */ OSPT_USAGE_IND *ospvUsageInd) /* Usage Indication effected */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = (ospvUsageInd->TransactionId != 0); } return has; } /* * OSPPUsageIndSetTransactionId() - set the transaction id */ void OSPPUsageIndSetTransactionId( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ OSPTTRXID ospvTransactionId) /* transaction id to set to */ { if (ospvUsageInd != OSPC_OSNULL) { if (ospvTransactionId != 0) { ospvUsageInd->TransactionId = ospvTransactionId; } } } /* * OSPPUsageIndGetTransactionId() - returns the trans id for a usage ind */ OSPTTRXID OSPPUsageIndGetTransactionId( OSPT_USAGE_IND *ospvUsageInd) /* usage ind */ { OSPTTRXID trxid = 0; if (ospvUsageInd != OSPC_OSNULL) { trxid = ospvUsageInd->TransactionId; } return trxid; } /* * OSPPUsageIndHasCallId() - does an usage indication have a Call ID? */ OSPTBOOL OSPPUsageIndHasCallId( /* returns non-zero if exists */ OSPT_USAGE_IND *ospvUsageInd) /* usage indication */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = (ospvUsageInd->CallId != OSPC_OSNULL); } return has; } /* * OSPPUsageIndGetCallId() - gets the call ID for an usage indication */ OSPT_CALL_ID *OSPPUsageIndGetCallId( /* returns call ID pointer */ OSPT_USAGE_IND *ospvUsageInd) /* usage indication */ { OSPT_CALL_ID *callid = OSPC_OSNULL; if (ospvUsageInd != OSPC_OSNULL) { callid = ospvUsageInd->CallId; } return callid; } /* * OSPPUsageIndSetSourceNumber() - set the source number */ void OSPPUsageIndSetSourceNumber( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ const char *ospvSourceNumber) /* source number to set to */ { if (ospvUsageInd != OSPC_OSNULL) { if (ospvSourceNumber != OSPC_OSNULL) { OSPM_STRNCPY(ospvUsageInd->SourceNumber, ospvSourceNumber, OSPM_MIN(OSPM_STRLEN(ospvSourceNumber) + 1, OSPC_SIZE_E164NUM)); } } } /* * OSPPUsageIndGetSourceNumber() - returns the source number for usage ind */ const char *OSPPUsageIndGetSourceNumber( OSPT_USAGE_IND *ospvUsageInd) /* usage ind */ { const char *num = OSPC_OSNULL; if (ospvUsageInd != OSPC_OSNULL) { num = ospvUsageInd->SourceNumber; } return num; } /* * OSPPUsageIndSetConferenceId() - set the conference id */ void OSPPUsageIndSetConferenceId( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ const char *ospvConferenceId) /* conference id to set to */ { if (ospvUsageInd != OSPC_OSNULL) { if (ospvConferenceId != OSPC_OSNULL) { OSPM_STRCPY(ospvUsageInd->ConferenceId, ospvConferenceId); } } } /* * OSPPUsageIndGetHasConfId() - Checks if conf id is present. */ int OSPPUsageIndGetHasConfId( OSPT_USAGE_IND *ospvUsageInd) /* usage ind */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { if (ospvUsageInd->ConferenceId[0] != '\0') { has = OSPC_TRUE; } } return has; } /* * OSPPUsageIndGetConferenceId() - returns the conf id */ const char *OSPPUsageIndGetConferenceId( OSPT_USAGE_IND *ospvUsageInd) /* usage ind */ { const char *conferenceid = OSPC_OSNULL; if (ospvUsageInd != OSPC_OSNULL) { conferenceid = ospvUsageInd->ConferenceId; } return conferenceid; } /* * OSPPUsageIndSetDestNumber() - set the destination number */ void OSPPUsageIndSetDestNumber( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ const char *ospvDestNumber) /* destination number to set to */ { if (ospvUsageInd != OSPC_OSNULL) { if (ospvDestNumber != OSPC_OSNULL) { OSPM_STRNCPY(ospvUsageInd->DestinationNumber, ospvDestNumber, OSPM_MIN(OSPM_STRLEN(ospvDestNumber) + 1, OSPC_SIZE_E164NUM)); } } } /* * OSPPUsageIndGetDestNumber() - returns the destination number for a usage ind */ const char *OSPPUsageIndGetDestNumber( OSPT_USAGE_IND *ospvUsageInd) /* usage ind */ { const char *num = OSPC_OSNULL; if (ospvUsageInd != OSPC_OSNULL) { num = ospvUsageInd->DestinationNumber; } return num; } /* * OSPPUsageIndHasDuration() - is the duration set ? */ OSPTBOOL OSPPUsageIndHasDuration( /* returns non-zero if number exists */ OSPT_USAGE_IND *ospvUsageInd) /* Usage Indication effected */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = (ospvUsageInd->Duration >= 0); } return has; } /* * OSPPUsageIndSetDuration() - set the duration */ void OSPPUsageIndSetDuration( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ int ospvDuration) /* duration to set to */ { if (ospvUsageInd != OSPC_OSNULL) { if (ospvDuration >= 0) { ospvUsageInd->Duration = ospvDuration; } } } /* * OSPPUsageIndGetDuration() - returns the duration for a usage ind */ int OSPPUsageIndGetDuration( OSPT_USAGE_IND *ospvUsageInd) /* usage ind */ { int duration = 0; if (ospvUsageInd != OSPC_OSNULL) { duration = ospvUsageInd->Duration; } return duration; } /* * OSPPUsageIndSetHasPDDInfo() - set the IsPDDInfoPResent variable */ void OSPPUsageIndSetHasPDDInfo( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ OSPTBOOL HasPDDInfo) /* duration to set to */ { if (ospvUsageInd != OSPC_OSNULL) { ospvUsageInd->HasPDD = HasPDDInfo; } } /* * OSPPUsageIndHasPDD() - gets the HasPDD variable. */ OSPTBOOL OSPPUsageIndHasPDD( OSPT_USAGE_IND *ospvUsageInd) /* usage ind */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = ospvUsageInd->HasPDD; } return has; } /* * OSPPUsageIndSetReleaseSource() - set the Rel Src */ void OSPPUsageIndSetReleaseSource( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ OSPE_RELEASE ospvReleaseSource) /* Rel Src to set to */ { if (ospvUsageInd != OSPC_OSNULL) { if ((ospvReleaseSource == OSPC_RELEASE_UNKNOWN) || ((ospvReleaseSource >= OSPC_RELEASE_START) && (ospvReleaseSource < OSPC_RELEASE_NUMBER))) { ospvUsageInd->ReleaseSource = ospvReleaseSource; } else { ospvUsageInd->ReleaseSource = OSPC_RELEASE_UNDEFINED; } } } /* * OSPPUsageIndGetReleaseSource() - returns the Rel Src for a usage ind */ OSPE_RELEASE OSPPUsageIndGetReleaseSource( OSPT_USAGE_IND *ospvUsageInd) /* usage ind */ { OSPE_RELEASE ospvReleaseSource = OSPC_RELEASE_UNDEFINED; if (ospvUsageInd != OSPC_OSNULL) { if ((ospvUsageInd->ReleaseSource == OSPC_RELEASE_UNKNOWN) || ((ospvUsageInd->ReleaseSource >= OSPC_RELEASE_START) && (ospvUsageInd->ReleaseSource < OSPC_RELEASE_NUMBER))) { ospvReleaseSource = ospvUsageInd->ReleaseSource; } } return ospvReleaseSource; } /* * OSPPUsageIndSetPostDialDelay() - set the PDD */ void OSPPUsageIndSetPostDialDelay( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ unsigned ospvPostDialDelay) /* PDD in milliseconds */ { if (ospvUsageInd != OSPC_OSNULL) { ospvUsageInd->PostDialDelay = ospvPostDialDelay; ospvUsageInd->HasPDD = OSPC_TRUE; } } /* * OSPPUsageIndGetPostDialDelay() - returns the PDD for a usage ind in milliseconds */ unsigned OSPPUsageIndGetPostDialDelay( OSPT_USAGE_IND *ospvUsageInd) /* usage ind */ { int pdd = 0; if (ospvUsageInd != OSPC_OSNULL) { pdd = ospvUsageInd->PostDialDelay; } return pdd; } /* * OSPPUsageIndHasCustId() - Does usage have a Customer Id? */ OSPTBOOL OSPPUsageIndHasCustId( /* returns non-zero if time */ OSPT_USAGE_IND *ospvUsageInd) /* usage in question */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = (ospvUsageInd->CustomerId != 0L); } return has; } /* * OSPPUsageIndSetCustId() - Set Customer Id */ void OSPPUsageIndSetCustId( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, unsigned long ospvCustId) { if (ospvUsageInd != OSPC_OSNULL) { ospvUsageInd->CustomerId = ospvCustId; } } /* * OSPPUsageIndGetCustId() - returns Customer Id for an usage request */ unsigned long OSPPUsageIndGetCustId( /* returns the time value */ OSPT_USAGE_IND *ospvUsageInd) /* usage request */ { unsigned long ospvCustId = 0L; if (ospvUsageInd != OSPC_OSNULL) { ospvCustId = ospvUsageInd->CustomerId; } return ospvCustId; } /* * OSPPUsageIndHasDeviceId() - Does request have a Device Id? */ OSPTBOOL OSPPUsageIndHasDeviceId( /* returns non-zero if time */ OSPT_USAGE_IND *ospvUsageInd) /* usage request in question */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = (ospvUsageInd->DeviceId != 0L); } return has; } /* * OSPPUsageIndSetDeviceId() - Set Device Id */ void OSPPUsageIndSetDeviceId( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, unsigned long ospvDeviceId) { if (ospvUsageInd != OSPC_OSNULL) { ospvUsageInd->DeviceId = ospvDeviceId; } } /* * OSPPUsageIndGetDeviceId() - returns Device Id for an usage request */ unsigned long OSPPUsageIndGetDeviceId( /* returns the time value */ OSPT_USAGE_IND *ospvUsageInd) /* usage request */ { unsigned long deviceid = 0L; if (ospvUsageInd != OSPC_OSNULL) { deviceid = ospvUsageInd->DeviceId; } return deviceid; } /* * OSPPUsageIndHasTermCause() - Does request have a Fail Reason */ OSPTBOOL OSPPUsageIndHasTermCause( /* returns non-zero if time */ OSPT_USAGE_IND *ospvUsageInd, /* usage request in question */ OSPE_TERM_CAUSE ospvType) /* termination cause type */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = OSPPHasTermCause(&ospvUsageInd->TermCause, ospvType); } return has; } /* * OSPPUsageIndCopyTermCause() - Copy Fail Reason */ void OSPPUsageIndCopyTermCause( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, OSPT_TERM_CAUSE *ospvTermCause) { if ((ospvUsageInd != OSPC_OSNULL) && (ospvTermCause != OSPC_OSNULL)) { OSPM_MEMCPY(&ospvUsageInd->TermCause, ospvTermCause, sizeof(OSPT_TERM_CAUSE)); } } /* * OSPPUsageIndSetTermCause() - Set Fail Reason */ void OSPPUsageIndSetTermCause( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, OSPE_TERM_CAUSE ospvType, unsigned ospvTCCode, const char *ospvTCDesc) { if (ospvUsageInd != OSPC_OSNULL) { OSPPSetTermCause(&ospvUsageInd->TermCause, ospvType, ospvTCCode, ospvTCDesc); } } /* * OSPPUsageIndGetTCCode() - returns Fail Reason value for an usage request */ unsigned OSPPUsageIndGetTCCode( OSPT_USAGE_IND *ospvUsageInd, /* usage request */ OSPE_TERM_CAUSE ospvType) /* fail reason type */ { unsigned tccode = 0; if (ospvUsageInd != OSPC_OSNULL) { tccode = OSPPGetTCCode(&ospvUsageInd->TermCause, ospvType); } return tccode; } /* * OSPPUsageIndGetTCDesc() - returns Fail Reason description for an usage request */ const char *OSPPUsageIndGetTCDesc( OSPT_USAGE_IND *ospvUsageInd, /* usage request */ OSPE_TERM_CAUSE ospvType) /* fail reasion type */ { const char *tcdesc = OSPC_OSNULL; if (ospvUsageInd != OSPC_OSNULL) { tcdesc = OSPPGetTCDesc(&ospvUsageInd->TermCause, ospvType); } return tcdesc; } /* * OSPPUsageIndHasSourceAlt() - does an usage indication have a * Source Alternate? */ OSPTBOOL OSPPUsageIndHasSourceAlt( /* returns non-zero if exists */ OSPT_USAGE_IND *ospvUsageInd) /* usage indication */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = (OSPPUsageIndFirstSourceAlt(ospvUsageInd) != OSPC_OSNULL); } return has; } /* * OSPPUsageIndFirstSourceAlt() - gets the First Source alternate for an * usage indication */ OSPT_ALTINFO *OSPPUsageIndFirstSourceAlt( /* returns alt info pointer */ OSPT_USAGE_IND *ospvUsageInd) /* usage indication */ { OSPT_ALTINFO *altinfo = OSPC_OSNULL; if (ospvUsageInd != OSPC_OSNULL) { altinfo = (OSPT_ALTINFO *)OSPPListFirst(&(ospvUsageInd->SourceAlternate)); } return altinfo; } /* * OSPPUsageIndNextSourceAlt() - gets the next source alternate for an * usage indication */ OSPT_ALTINFO *OSPPUsageIndNextSourceAlt( /* returns alt info pointer */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication */ OSPT_ALTINFO *ospvAltInfo) { OSPT_ALTINFO *altinfo = OSPC_OSNULL; if (ospvUsageInd != OSPC_OSNULL) { altinfo = (OSPT_ALTINFO *)OSPPListNext(&(ospvUsageInd->SourceAlternate), ospvAltInfo); } return altinfo; } /* * OSPPUsageIndHasDestinationAlt() - does an usage indication have a * Destination Alternate? */ OSPTBOOL OSPPUsageIndHasDestinationAlt( /* returns non-zero if exists */ OSPT_USAGE_IND *ospvUsageInd) /* usage indication */ { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { has = (OSPPUsageIndFirstDestinationAlt(ospvUsageInd) != OSPC_OSNULL); } return has; } /* * OSPPUsageIndFirstDestinationAlt() - gets the First Destination alternate for an * usage indication */ OSPT_ALTINFO *OSPPUsageIndFirstDestinationAlt( /* returns altinfo pointer */ OSPT_USAGE_IND *ospvUsageInd) /* usage indication */ { OSPT_ALTINFO *ospvAltInfo = OSPC_OSNULL; if (ospvUsageInd != OSPC_OSNULL) { ospvAltInfo = (OSPT_ALTINFO *)OSPPListFirst(&(ospvUsageInd->DestinationAlternate)); } return ospvAltInfo; } /* * OSPPUsageIndNextDestinationAlt() - gets the next Destination alternate for an * usage indication */ OSPT_ALTINFO *OSPPUsageIndNextDestinationAlt( /* returns altinfo pointer */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication */ OSPT_ALTINFO *ospvAltInfo) { OSPT_ALTINFO *altinfo = OSPC_OSNULL; if (ospvUsageInd != OSPC_OSNULL) { altinfo = (OSPT_ALTINFO *)OSPPListNext(&(ospvUsageInd->DestinationAlternate), ospvAltInfo); } return altinfo; } /* * OSPPUsageIndGetDestinationAltSize() - gets the Destination alternate size * for an altinfo */ unsigned OSPPUsageIndGetDestinationAltSize( /* returns altinfo size */ OSPT_ALTINFO *ospvAltInfo) /* altinfo ptr */ { unsigned ospvAltInfoSize = 0; if (ospvAltInfo != OSPC_OSNULL) { ospvAltInfoSize = OSPPAltInfoGetSize(ospvAltInfo); } return ospvAltInfoSize; } /* * OSPPUsageIndSetStartTime() - Set Call Start Time */ void OSPPUsageIndSetStartTime( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, OSPTTIME ospvStartTime) { if (ospvUsageInd != OSPC_OSNULL) { ospvUsageInd->StartTime = ospvStartTime; } } /* * OSPPUsageGetGetStartTime() - Set Call Start Time */ OSPTTIME OSPPUsageIndGetStartTime( /* call start time */ OSPT_USAGE_IND *ospvUsageInd) { OSPTTIME ospvStartTime = 0; if (ospvUsageInd != OSPC_OSNULL) { ospvStartTime = ospvUsageInd->StartTime; } return ospvStartTime; } /* * OSPPUsageIndSetEndTime() - Set Call End Time */ void OSPPUsageIndSetEndTime( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, OSPTTIME ospvEndTime) { if (ospvUsageInd != OSPC_OSNULL) { ospvUsageInd->EndTime = ospvEndTime; } } /* * OSPPUsageGetGetEndTime() - Get Call End Time */ OSPTTIME OSPPUsageIndGetEndTime( /* call end time */ OSPT_USAGE_IND *ospvUsageInd) { OSPTTIME time = 0; if (ospvUsageInd != OSPC_OSNULL) { time = ospvUsageInd->EndTime; } return time; } /* * OSPPUsageIndSetConnectTime() - Set Call Connect Time */ void OSPPUsageIndSetConnectTime( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, OSPTTIME ospvConnectTime) { if (ospvUsageInd != OSPC_OSNULL) { ospvUsageInd->ConnectTime = ospvConnectTime; } } /* * OSPPUsageIndGetConnectTime() - Get Call Connect Time */ OSPTTIME OSPPUsageIndGetConnectTime( /* call connect time */ OSPT_USAGE_IND *ospvUsageInd) { OSPTTIME time = 0; if (ospvUsageInd != OSPC_OSNULL) { time = ospvUsageInd->ConnectTime; } return time; } /* * OSPPUsageIndSetAlertTime() - Set Call Alert Time */ void OSPPUsageIndSetAlertTime( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, OSPTTIME ospvAlertTime) { if (ospvUsageInd != OSPC_OSNULL) { ospvUsageInd->AlertTime = ospvAlertTime; } } /* * OSPPUsageGetGetAlertTime() - Get Call Alert Time */ OSPTTIME OSPPUsageIndGetAlertTime( /* call alert time */ OSPT_USAGE_IND *ospvUsageInd) { OSPTTIME time = 0; if (ospvUsageInd != OSPC_OSNULL) { time = ospvUsageInd->AlertTime; } return time; } /* * OSPPUsageIndSetComponentId() - creates space and copies in the string. */ void OSPPUsageIndSetComponentId( OSPT_USAGE_IND *ospvUsageInd, /* In - pointer to Usage Indication struct */ const char *ospvComponentId) /* In - pointer to component id string */ { int len = OSPM_STRLEN(ospvComponentId); if (ospvUsageInd != OSPC_OSNULL) { if (ospvUsageInd->ComponentId != OSPC_OSNULL) { OSPM_FREE(ospvUsageInd->ComponentId); } OSPM_MALLOC(ospvUsageInd->ComponentId, char, len + 1); OSPM_MEMSET(ospvUsageInd->ComponentId, 0, len + 1); OSPM_MEMCPY(ospvUsageInd->ComponentId, ospvComponentId, len); } } /* * OSPPUsageIndMoveDeviceinfo() - move the device info list from list */ void OSPPUsageIndMoveDeviceInfo( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ OSPTLIST *ospvList) /* list to move */ { if ((ospvUsageInd != OSPC_OSNULL) && (ospvList != OSPC_OSNULL)) { OSPPListNew(&(ospvUsageInd->DeviceInfo)); OSPPListMove(&(ospvUsageInd->DeviceInfo), ospvList); } } /* * OSPPUsageIndMoveSourceAlt() - move the source alt list from list */ void OSPPUsageIndMoveSourceAlt( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ OSPTLIST *ospvList /* list to move */ ) { if ((ospvUsageInd != OSPC_OSNULL) && (ospvList != OSPC_OSNULL)) { OSPPListNew(&(ospvUsageInd->SourceAlternate)); OSPPListMove(&(ospvUsageInd->SourceAlternate), ospvList); } } /* * OSPPUsageIndCopyDeviceInfo() - Copy the device info list */ void OSPPUsageIndCopyDeviceInfo( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ OSPTLIST *ospvList) /* list to move */ { OSPT_ALTINFO *altinfo1 = OSPC_OSNULL, *altinfo2 = OSPC_OSNULL; if ((ospvUsageInd != OSPC_OSNULL) && (ospvList != OSPC_OSNULL)) { OSPPListNew(&(ospvUsageInd->DeviceInfo)); for (altinfo1 = (OSPT_ALTINFO *)OSPPListFirst(ospvList); altinfo1 != OSPC_OSNULL; altinfo1 = (OSPT_ALTINFO *)OSPPListNext(ospvList, altinfo1)) { altinfo2 = OSPPAltInfoNew(OSPPAltInfoGetSize(altinfo1), OSPPAltInfoGetValue(altinfo1), OSPPAltInfoGetPart(altinfo1)); if (altinfo2 != OSPC_OSNULL) { OSPPListAppend(&ospvUsageInd->DeviceInfo, altinfo2); } altinfo2 = OSPC_OSNULL; } } if (altinfo2 != OSPC_OSNULL) { OSPPAltInfoDelete(&altinfo2); } } /* * OSPPUsageIndMergeSourceAlt() - Merges the source alt list * The list (ospmAuthReqSourceAlternate) could contain - NetworkId, SrcAddr, * or the Subscriber Info. We need to copy everything from list1, except * the SrcAddr. The 2nd list contains the Updated SrcAddr that we just * append to the list. */ void OSPPUsageIndMergeSourceAlt( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, OSPTLIST *ospvList1, OSPTLIST *ospvList2) { OSPT_ALTINFO *altinfo1 = OSPC_OSNULL, *altinfo2 = OSPC_OSNULL; if ((ospvUsageInd != OSPC_OSNULL) && ((ospvList1 != OSPC_OSNULL) || (ospvList2 != OSPC_OSNULL))) { OSPPListNew(&(ospvUsageInd->SourceAlternate)); } /* * Copy the node from List 2. */ if ((ospvUsageInd != OSPC_OSNULL) && (ospvList2 != OSPC_OSNULL)) { for (altinfo1 = (OSPT_ALTINFO *)OSPPListFirst(ospvList2); altinfo1 != OSPC_OSNULL; altinfo1 = (OSPT_ALTINFO *)OSPPListNext(ospvList2, altinfo1)) { altinfo2 = OSPPAltInfoNew(OSPPAltInfoGetSize(altinfo1), OSPPAltInfoGetValue(altinfo1), OSPPAltInfoGetPart(altinfo1)); if (altinfo2 != OSPC_OSNULL) { OSPPListAppend(&ospvUsageInd->SourceAlternate, altinfo2); } altinfo2 = OSPC_OSNULL; } } if (altinfo2 != OSPC_OSNULL) { OSPPAltInfoDelete(&altinfo2); } /* * Now copy the nodes for Network/Subscriber Info */ if ((ospvUsageInd != OSPC_OSNULL) && (ospvList1 != OSPC_OSNULL)) { for (altinfo1 = (OSPT_ALTINFO *)OSPPListFirst(ospvList1); altinfo1 != OSPC_OSNULL; altinfo1 = (OSPT_ALTINFO *)OSPPListNext(ospvList1, altinfo1)) { if (OSPPAltInfoGetPart(altinfo1) != OSPC_ALTINFO_TRANSPORT) { altinfo2 = OSPPAltInfoNew(OSPPAltInfoGetSize(altinfo1), OSPPAltInfoGetValue(altinfo1), OSPPAltInfoGetPart(altinfo1)); if (altinfo2 != OSPC_OSNULL) { OSPPListAppend(&ospvUsageInd->SourceAlternate, altinfo2); } altinfo2 = OSPC_OSNULL; } } } if (altinfo2 != OSPC_OSNULL) { OSPPAltInfoDelete(&altinfo2); } } /* * OSPPUsageIndCopySourceAlt() - Copy the source alt list */ void OSPPUsageIndCopySourceAlt( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ OSPTLIST *ospvList) /* list to move */ { OSPT_ALTINFO *altinfo1 = OSPC_OSNULL, *altinfo2 = OSPC_OSNULL; if ((ospvUsageInd != OSPC_OSNULL) && (ospvList != OSPC_OSNULL)) { OSPPListNew(&(ospvUsageInd->SourceAlternate)); for (altinfo1 = (OSPT_ALTINFO *)OSPPListFirst(ospvList); altinfo1 != OSPC_OSNULL; altinfo1 = (OSPT_ALTINFO *)OSPPListNext(ospvList, altinfo1)) { altinfo2 = OSPPAltInfoNew(OSPPAltInfoGetSize(altinfo1), OSPPAltInfoGetValue(altinfo1), OSPPAltInfoGetPart(altinfo1)); if (altinfo2 != OSPC_OSNULL) { OSPPListAppend(&ospvUsageInd->SourceAlternate, altinfo2); } altinfo2 = OSPC_OSNULL; } } if (altinfo2 != OSPC_OSNULL) { OSPPAltInfoDelete(&altinfo2); } } /* * OSPPUsageIndMoveDestinationAlt() - move the destination alt list from * a list */ void OSPPUsageIndMoveDestinationAlt( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication to set */ OSPTLIST *ospvList) /* list to move */ { if ((ospvUsageInd != OSPC_OSNULL) && (ospvList != OSPC_OSNULL)) { OSPPListNew(&(ospvUsageInd->DestinationAlternate)); OSPPListMove(&(ospvUsageInd->DestinationAlternate), ospvList); } } /* * OSPPUsageIndNew() - creates a new (empty) usage indication */ OSPT_USAGE_IND *OSPPUsageIndNew(void) /* returns pointer or NULL */ { OSPT_USAGE_IND *usageind = OSPC_OSNULL; OSPE_TERM_CAUSE cause; OSPE_PROTOCOL_TYPE prot; OSPE_SERVICE svc; OSPE_CODEC_TYPE codec; OSPE_SESSION_ID sess; OSPM_MALLOC(usageind, OSPT_USAGE_IND, sizeof(OSPT_USAGE_IND)); if (usageind != OSPC_OSNULL) { OSPM_MEMSET(usageind, 0, sizeof(OSPT_USAGE_IND)); OSPPListLinkNew(&(usageind->Link)); usageind->Timestamp = (OSPTTIME) 0; usageind->StartTime = (OSPTTIME) 0; usageind->AlertTime = (OSPTTIME) 0; usageind->EndTime = (OSPTTIME) 0; usageind->ConnectTime = (OSPTTIME) 0; usageind->HasPDD = OSPC_FALSE; usageind->PostDialDelay = 0; usageind->ProviderPDD = -1; usageind->ReleaseSource = OSPC_RELEASE_UNDEFINED; usageind->ConferenceId[0] = '\0'; usageind->Role = OSPC_ROLE_UNDEFINED; usageind->HasRole = OSPC_FALSE; usageind->TransactionId = 0; usageind->CallId = OSPC_OSNULL; usageind->SourceNumber[0] = '\0'; usageind->DestinationNumber[0] = '\0'; usageind->Duration = -1; usageind->CustomerId = 0L; usageind->DeviceId = 0L; for (cause = OSPC_TCAUSE_START; cause < OSPC_TCAUSE_NUMBER; cause++) { usageind->TermCause.hastermcause[cause] = OSPC_FALSE; } OSPPListNew(&(usageind->SourceAlternate)); OSPPListNew(&(usageind->DestinationAlternate)); OSPPListNew(&(usageind->DeviceInfo)); usageind->Stats = OSPC_OSNULL; usageind->ComponentId = OSPC_OSNULL; usageind->MessageId = OSPC_OSNULL; usageind->HasPricingInfo = OSPC_FALSE; usageind->HasServiceInfo = OSPC_FALSE; usageind->DestinationCount = OSPC_OSNULL; usageind->SetupAttempt = -1; for (prot = OSPC_PROTTYPE_START; prot < OSPC_PROTTYPE_NUMBER; prot++) { usageind->Protocol[prot] = OSPC_PROTNAME_UNKNOWN; } for (svc = OSPC_SERVICE_START; svc < OSPC_SERVICE_NUMBER; svc++) { for (codec = OSPC_CODEC_START; codec < OSPC_CODEC_NUMBER; codec++) { usageind->Codec[svc][codec][0] = '\0'; } } for (sess = OSPC_SESSIONID_START; sess < OSPC_SESSIONID_NUMBER; sess++) { usageind->SessionId[sess] = OSPC_OSNULL; } usageind->RoleState = OSPC_RSTATE_UNKNOWN; usageind->RoleFormat = OSPC_RFORMAT_UNKNOWN; usageind->RoleVendor = OSPC_RVENDOR_UNKNOWN; usageind->TransferId[0] = '\0'; usageind->TransferStatus = OSPC_TSTATUS_UNKNOWN; } return usageind; } /* * OSPPUsageIndDelete() - deletes a usage indication */ void OSPPUsageIndDelete( OSPT_USAGE_IND **ospvUsageInd) { OSPT_ALTINFO *altinfo = OSPC_OSNULL; unsigned cnt; if (*ospvUsageInd) { if (OSPPUsageIndHasCallId(*ospvUsageInd)) { OSPPCallIdDelete(&((*ospvUsageInd)->CallId)); } if (OSPPUsageIndHasComponentId(*ospvUsageInd)) { OSPM_FREE((*ospvUsageInd)->ComponentId); } while (!OSPPListEmpty(&((*ospvUsageInd)->SourceAlternate))) { altinfo = (OSPT_ALTINFO *)OSPPListRemove(&((*ospvUsageInd)->SourceAlternate)); OSPM_FREE(altinfo); altinfo = OSPC_OSNULL; } OSPPListDelete(&((*ospvUsageInd)->SourceAlternate)); while (!OSPPListEmpty(&((*ospvUsageInd)->DeviceInfo))) { altinfo = (OSPT_ALTINFO *)OSPPListRemove(&((*ospvUsageInd)->DeviceInfo)); OSPM_FREE(altinfo); altinfo = OSPC_OSNULL; } OSPPListDelete(&((*ospvUsageInd)->DeviceInfo)); while (!OSPPListEmpty(&((*ospvUsageInd)->DestinationAlternate))) { altinfo = (OSPT_ALTINFO *)OSPPListRemove(&((*ospvUsageInd)->DestinationAlternate)); OSPM_FREE(altinfo); altinfo = OSPC_OSNULL; } if (OSPPUsageIndHasStatistics(*ospvUsageInd)) { OSPPStatsDelete(&((*ospvUsageInd)->Stats)); } if (OSPPUsageIndHasComponentId(*ospvUsageInd)) { OSPM_FREE((*ospvUsageInd)->ComponentId); } if (OSPPUsageIndHasMessageId(*ospvUsageInd)) { OSPM_FREE((*ospvUsageInd)->MessageId); } if (OSPPUsageIndGetDestinationCount(*ospvUsageInd) != OSPC_OSNULL) { OSPM_FREE((*ospvUsageInd)->DestinationCount); } OSPPListDelete(&((*ospvUsageInd)->DestinationAlternate)); for (cnt = OSPC_SESSIONID_START; cnt < OSPC_SESSIONID_NUMBER; cnt++) { if (OSPPUsageIndHasSessionId(*ospvUsageInd, cnt)) { OSPPCallIdDelete(&((*ospvUsageInd)->SessionId[cnt])); } } OSPM_FREE(*ospvUsageInd); *ospvUsageInd = OSPC_OSNULL; } } /* * OSPPUsageIndSetCallId() - sets the call ID for an usage */ void OSPPUsageIndSetCallId( /* nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* usage indication */ OSPT_CALL_ID *ospvCallId) /* call ID */ { if (ospvUsageInd != OSPC_OSNULL) { if ((ospvCallId) != OSPC_OSNULL) { if (ospvUsageInd->CallId != OSPC_OSNULL) { OSPPCallIdDelete(&(ospvUsageInd->CallId)); } ospvUsageInd->CallId = OSPPCallIdNew(ospvCallId->Length, ospvCallId->Value); } } } /* * OSPPUsageIndHasStatistics() - does usageind have statistics? */ OSPTBOOL OSPPUsageIndHasStatistics( OSPT_USAGE_IND *ospvUsageInd) { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { if (ospvUsageInd->Stats != OSPC_OSNULL) { has = OSPC_TRUE; } } return has; } /* * OSPPUsageIndSetStatistics() - set values for statistics in usageind */ void OSPPUsageIndSetStatistics( OSPT_USAGE_IND *ospvUsageInd, /* In - ptr to usage ind */ OSPT_STATS *ospvStats) /* In - ptr to completed stats struct */ { if ((ospvUsageInd != OSPC_OSNULL) && (ospvStats != OSPC_OSNULL)) { ospvUsageInd->Stats = OSPPStatsNew(); OSPM_MEMCPY(ospvUsageInd->Stats, ospvStats, sizeof(OSPT_STATS)); } } /* * OSPPUsageIndToElement() - create an XML element from a usage ind */ int OSPPUsageIndToElement( /* returns error code */ OSPTLIST *ospvUsageInd, /* usage ind list */ OSPT_XML_ELEM **ospvElem, /* where to put XML element pointer */ void *ospvtrans) { int errcode = OSPC_ERR_NO_ERROR; OSPT_XML_ELEM *usageindelem = OSPC_OSNULL; OSPT_XML_ELEM *usagedetailelem = OSPC_OSNULL; OSPT_XML_ELEM *roleinfoelem = OSPC_OSNULL; OSPT_XML_ELEM *callpartyelem = OSPC_OSNULL; OSPT_XML_ELEM *cdrproxyelem = OSPC_OSNULL; OSPT_XML_ELEM *subelem = OSPC_OSNULL; OSPT_XML_ATTR *attr = OSPC_OSNULL; OSPTTRXID trxid = 0; OSPT_ALTINFO *altinfo = OSPC_OSNULL; OSPT_USAGE_IND *usage = OSPC_OSNULL; char random[OSPC_MAX_RANDOM]; OSPTBOOL isbase64 = OSPC_TRUE; OSPTTRANS *trans = (OSPTTRANS *)ospvtrans; OSPE_MSG_ELEM elemtype; OSPE_MSG_ATTR attrtype[OSPC_MAX_ATTR]; OSPE_ALTINFO attrvalue[OSPC_MAX_ATTR]; OSPE_TERM_CAUSE tctype; int index; OSPE_SERVICE svc; OSPE_CALL_PARTY party; OSPE_PROTOCOL_TYPE prot; OSPE_SIP_HEADER header; OSPE_NUMBER_FORMAT format; OSPE_CODEC_TYPE codec; OSPE_SESSION_ID sess; OSPT_SDP_FINGERPRINT *fingerprint = OSPC_OSNULL; OSPM_MEMSET(random, 0, OSPC_MAX_RANDOM); if (ospvElem == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ELEMENT; } if (errcode == OSPC_ERR_NO_ERROR) { if (ospvUsageInd == OSPC_OSNULL) { errcode = OSPC_ERR_DATA_NO_USAGEIND; } } if (errcode == OSPC_ERR_NO_ERROR) { /* create the "Message" element as the parent */ *ospvElem = OSPPXMLElemNew(OSPPMsgElemGetName(OSPC_MELEM_MESSAGE), ""); if (*ospvElem == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ELEMENT; } } if (errcode == OSPC_ERR_NO_ERROR) { /* Add the Message attribute */ usage = (OSPT_USAGE_IND *)OSPPListFirst(ospvUsageInd); attr = OSPPXMLAttrNew(OSPPMsgAttrGetName(OSPC_MATTR_MESSAGEID), OSPPUsageIndHasMessageId(usage) ? (const char *)(usage->MessageId) : "NULL"); if (attr == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ATTR; } else { OSPPXMLElemAddAttr(*ospvElem, attr); attr = OSPC_OSNULL; } } if (errcode == OSPC_ERR_NO_ERROR) { /* random */ if (OSPPUtilGetRandom(random, 0) > 0) { attr = OSPPXMLAttrNew(OSPPMsgAttrGetName(OSPC_MATTR_RANDOM), (const char *)random); if (attr == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ATTR; } else { OSPPXMLElemAddAttr(*ospvElem, attr); attr = OSPC_OSNULL; } } } if (errcode == OSPC_ERR_NO_ERROR) { /* Build multiple usage ind if there are more than one */ for (usage = (OSPT_USAGE_IND *)OSPPListFirst(ospvUsageInd); (usage != OSPC_OSNULL) && (errcode == OSPC_ERR_NO_ERROR); usage = (OSPT_USAGE_IND *)OSPPListNext(ospvUsageInd, usage)) { /* create the usage element */ usageindelem = OSPPXMLElemNew(OSPPMsgElemGetName(OSPC_MELEM_USAGEIND), ""); if (usageindelem == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ELEMENT; } /* now add the attributes to the parent -- in this case the component id */ if (errcode == OSPC_ERR_NO_ERROR) { attr = OSPPXMLAttrNew(OSPPMsgAttrGetName(OSPC_MATTR_COMPONENTID), OSPPUsageIndHasComponentId(usage) ? (const char *)(usage->ComponentId) : "NULL"); if (attr == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ATTR; } else { OSPPXMLElemAddAttr(usageindelem, attr); attr = OSPC_OSNULL; } } /* now add the children - start with timestamp */ if ((errcode == OSPC_ERR_NO_ERROR) && OSPPUsageIndHasTimestamp(usage)) { errcode = OSPPMsgTimeToElement(OSPPUsageIndGetTimestamp(usage), OSPPMsgElemGetName(OSPC_MELEM_TIMESTAMP), &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* add role */ if ((errcode == OSPC_ERR_NO_ERROR) && OSPPUsageIndHasRole(usage)) { errcode = OSPPStringToElement(OSPC_MELEM_ROLE, OSPPRoleGetName(OSPPUsageIndGetRole(usage)), 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add role additional info */ if ((errcode == OSPC_ERR_NO_ERROR) && (((usage->RoleState >= OSPC_RSTATE_START) && (usage->RoleState < OSPC_RSTATE_NUMBER)) || ((usage->RoleFormat >= OSPC_RFORMAT_START) && (usage->RoleFormat < OSPC_RFORMAT_NUMBER)) || ((usage->RoleVendor >= OSPC_RVENDOR_START) && (usage->RoleVendor < OSPC_RVENDOR_NUMBER)))) { roleinfoelem = OSPPXMLElemNew(OSPPMsgElemGetName(OSPC_MELEM_ROLEINFO), ""); if (roleinfoelem == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ELEMENT; } } if ((errcode == OSPC_ERR_NO_ERROR) && ((usage->RoleState >= OSPC_RSTATE_START) && (usage->RoleState < OSPC_RSTATE_NUMBER))) { errcode = OSPPStringToElement(OSPC_MELEM_ROLESTATE, OSPPRoleStateGetName(usage->RoleState), 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(roleinfoelem, subelem); subelem = OSPC_OSNULL; } else { OSPPXMLElemDelete(&roleinfoelem); roleinfoelem = OSPC_OSNULL; } } if ((errcode == OSPC_ERR_NO_ERROR) && ((usage->RoleFormat >= OSPC_RFORMAT_START) && (usage->RoleFormat < OSPC_RFORMAT_NUMBER))) { errcode = OSPPStringToElement(OSPC_MELEM_ROLEFORMAT, OSPPRoleFormatGetName(usage->RoleFormat), 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(roleinfoelem, subelem); subelem = OSPC_OSNULL; } else { OSPPXMLElemDelete(&roleinfoelem); roleinfoelem = OSPC_OSNULL; } } if ((errcode == OSPC_ERR_NO_ERROR) && ((usage->RoleVendor >= OSPC_RVENDOR_START) && (usage->RoleVendor < OSPC_RVENDOR_NUMBER))) { errcode = OSPPStringToElement(OSPC_MELEM_ROLEVENDOR, OSPPRoleVendorGetName(usage->RoleVendor), 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(roleinfoelem, subelem); subelem = OSPC_OSNULL; } else { OSPPXMLElemDelete(&roleinfoelem); roleinfoelem = OSPC_OSNULL; } } if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, roleinfoelem); roleinfoelem = OSPC_OSNULL; } /* add the transaction ID */ if ((errcode == OSPC_ERR_NO_ERROR) && OSPPUsageIndHasTransactionId(usage)) { trxid = OSPPUsageIndGetTransactionId(usage); errcode = OSPPMsgTXToElement(trxid, OSPPMsgElemGetName(OSPC_MELEM_TRANSID), &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* add the call ID */ if ((errcode == OSPC_ERR_NO_ERROR) && OSPPUsageIndHasCallId(usage)) { errcode = OSPPCallIdToElement(OSPPUsageIndGetCallId(usage), &subelem, isbase64); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* add the source number */ if (errcode == OSPC_ERR_NO_ERROR) { errcode = OSPPCallPartyNumToElement(OSPC_MELEM_SRCINFO, OSPPUsageIndGetSourceNumber(usage), trans->CallingNumberFormat, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* add the device info */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->DeviceInfo != NULL)) { for (altinfo = (OSPT_ALTINFO *)OSPPListFirst(&(usage->DeviceInfo)); altinfo != OSPC_OSNULL; altinfo = (OSPT_ALTINFO *)OSPPListNext(&(usage->DeviceInfo), altinfo)) { errcode = OSPPAltInfoToElement(altinfo, &subelem, OSPC_MELEM_DEVICEINFO); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } } /* add the source alternates */ if ((errcode == OSPC_ERR_NO_ERROR) && OSPPUsageIndHasSourceAlt(usage)) { for (altinfo = (OSPT_ALTINFO *)OSPPUsageIndFirstSourceAlt(usage); ((altinfo != OSPC_OSNULL) && (errcode == OSPC_ERR_NO_ERROR)); altinfo = (OSPT_ALTINFO *)OSPPUsageIndNextSourceAlt(usage, altinfo)) { errcode = OSPPAltInfoToElement(altinfo, &subelem, OSPC_MELEM_SRCALT); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } } /* add the destination number */ if (errcode == OSPC_ERR_NO_ERROR) { errcode = OSPPCallPartyNumToElement(OSPC_MELEM_DESTINFO, OSPPUsageIndGetDestNumber(usage), trans->CalledNumberFormat, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* add the routing number */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->NPRn[0] != '\0')) { errcode = OSPPNPRnToElement(trans->NPRn, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* add the carrier identification code */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->NPCic[0] != '\0')) { errcode = OSPPNPCicToElement(trans->NPCic, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* add the npdi flag */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->NPNpdi == OSPC_TRUE)) { errcode = OSPPNPNpdiToElement(OSPC_TRUE, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* add the operator names */ for (index = 0; index < OSPC_OPNAME_NUMBER; index++) { if ((errcode == OSPC_ERR_NO_ERROR) && trans->OpName[index][0] != '\0') { errcode = OSPPOperatorNameToElement(index, trans->OpName[index], &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } } /* add the destination alternates */ if ((errcode == OSPC_ERR_NO_ERROR) && OSPPUsageIndHasDestinationAlt(usage)) { for (altinfo = (OSPT_ALTINFO *)OSPPUsageIndFirstDestinationAlt(usage); ((altinfo != OSPC_OSNULL) && (errcode == OSPC_ERR_NO_ERROR)); altinfo = (OSPT_ALTINFO *)OSPPUsageIndNextDestinationAlt(usage, altinfo)) { errcode = OSPPAltInfoToElement(altinfo, &subelem, OSPC_MELEM_DESTALT); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } } /* add destination count */ if ((errcode == OSPC_ERR_NO_ERROR) && (OSPPUsageIndGetDestinationCount(usage) != OSPC_OSNULL)) { altinfo = OSPPUsageIndGetDestinationCount(usage); errcode = OSPPAltInfoToElement(altinfo, &subelem, OSPC_MELEM_DESTALT); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } if ((errcode == OSPC_ERR_NO_ERROR) && (usage->SetupAttempt >= 0)) { OSPPMsgNumToElement(usage->SetupAttempt, OSPPMsgElemGetName(OSPC_MELEM_SETUPATTEMPT), &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } // add total setup attempts if ((errcode == OSPC_ERR_NO_ERROR) && (trans->TotalSetupAttempts >= 0)) { OSPPMsgNumToElement(trans->TotalSetupAttempts, OSPPMsgElemGetName(OSPC_MELEM_TOTALSETUPATTEMPTS), &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add Pricing Info */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->HasPricingInfo == OSPC_TRUE)) { errcode = OSPPPricingInfoToElement(&(usage->PricingInfo), &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add Service Info */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->HasServiceInfo == OSPC_TRUE)) { errcode = OSPPServiceTypeToElement(usage->ServiceType, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add conference id if present */ if ((errcode == OSPC_ERR_NO_ERROR) && (OSPPUsageIndGetHasConfId(usage))) { errcode = OSPPAddConfIdToUsageElement(OSPPUsageIndGetConferenceId(usage), &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add user-defined info */ for (index = 0; index < OSPC_MAX_INDEX; index++) { if ((errcode == OSPC_ERR_NO_ERROR) && (trans->CustomInfo[index] != OSPC_OSNULL) && (trans->CustomInfo[index][0] != '\0')) { errcode = OSPPCustomInfoToElement(index, trans->CustomInfo[index], &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } } /* Add call party info */ for (party = OSPC_CPARTY_START; party < OSPC_CPARTY_NUMBER; party++) { OSPT_CALL_PARTY *cparty = &(usage->CallParty[party]); if ((errcode == OSPC_ERR_NO_ERROR) && ((cparty->UserName[0] != '\0') || (cparty->UserId[0] != '\0') || (cparty->UserGroup[0] != '\0'))) { if (party == OSPC_CPARTY_SOURCE) { elemtype = OSPC_MELEM_CALLINGPARTYINFO; } else if (party == OSPC_CPARTY_DESTINATION) { elemtype = OSPC_MELEM_CALLEDPARTYINFO; } else { continue; } callpartyelem = OSPPXMLElemNew(OSPPMsgElemGetName(elemtype), ""); if (callpartyelem == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ELEMENT; } } if ((errcode == OSPC_ERR_NO_ERROR) && (cparty->UserName[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_USERNAME, cparty->UserName, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(callpartyelem, subelem); subelem = OSPC_OSNULL; } else { OSPPXMLElemDelete(&callpartyelem); callpartyelem = OSPC_OSNULL; } } if ((errcode == OSPC_ERR_NO_ERROR) && (cparty->UserId[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_USERID, cparty->UserId, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(callpartyelem, subelem); subelem = OSPC_OSNULL; } else { OSPPXMLElemDelete(&callpartyelem); callpartyelem = OSPC_OSNULL; } } if ((errcode == OSPC_ERR_NO_ERROR) && (cparty->UserGroup[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_USERGROUP, cparty->UserGroup, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(callpartyelem, subelem); subelem = OSPC_OSNULL; } else { OSPPXMLElemDelete(&callpartyelem); callpartyelem = OSPC_OSNULL; } } if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, callpartyelem); callpartyelem = OSPC_OSNULL; } } /* Transfer ID */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->TransferId[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_TRANSFERID, usage->TransferId, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Transfer Status */ if ((errcode == OSPC_ERR_NO_ERROR) && ((usage->TransferStatus >= OSPC_TSTATUS_START) && (usage->TransferStatus < OSPC_TSTATUS_NUMBER))) { errcode = OSPPStringToElement(OSPC_MELEM_TRANSFERSTATUS, OSPPTransferStatusGetName(usage->TransferStatus), 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Create usage detail element */ if (errcode == OSPC_ERR_NO_ERROR) { usagedetailelem = OSPPXMLElemNew(OSPPMsgElemGetName(OSPC_MELEM_USAGEDETAIL), ""); if (usagedetailelem == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ELEMENT; } } /* Failure reason */ if (errcode == OSPC_ERR_NO_ERROR) { for (tctype = OSPC_TCAUSE_START; tctype < OSPC_TCAUSE_NUMBER; tctype++) { if (OSPPUsageIndHasTermCause(usage, tctype)) { errcode = OSPPTermCauseToElement(tctype, OSPPUsageIndGetTCCode(usage, tctype), OSPPUsageIndGetTCDesc(usage, tctype), &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usagedetailelem, subelem); subelem = OSPC_OSNULL; } else { break; } } } } /* Protocol */ for (prot = OSPC_PROTTYPE_START; prot < OSPC_PROTTYPE_NUMBER; prot++) { if ((errcode == OSPC_ERR_NO_ERROR) && (OSPPUsageIndHasProtocol(usage, prot))) { attrtype[0] = OSPC_MATTR_TYPE; switch (prot) { case OSPC_PROTTYPE_SOURCE: attrvalue[0] = OSPC_ALTINFO_SOURCE; break; case OSPC_PROTTYPE_DESTINATION: attrvalue[0] = OSPC_ALTINFO_DESTINATION; break; case OSPC_PROTTYPE_NA: attrvalue[0] = OSPC_ALTINFO_NA; break; default: continue; } errcode = OSPPStringToElement(OSPC_MELEM_PROTOCOL, OSPPDestProtocolGetName(OSPPUsageIndGetProtocol(usage, prot)), 1, attrtype, attrvalue, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usagedetailelem, subelem); subelem = OSPC_OSNULL; } } } /* Codecs */ for (svc = OSPC_SERVICE_START; svc < OSPC_SERVICE_NUMBER; svc++) { attrtype[0] = OSPC_MATTR_SERVICE; switch (svc) { case OSPC_SERVICE_VOICE: attrvalue[0] = OSPC_ALTINFO_VOICE; break; case OSPC_SERVICE_VIDEO: attrvalue[0] = OSPC_ALTINFO_VIDEO; break; default: continue; } for (codec = OSPC_CODEC_START; codec < OSPC_CODEC_NUMBER; codec++) { attrtype[1] = OSPC_MATTR_TYPE; switch (codec) { case OSPC_CODEC_SOURCE: attrvalue[1] = OSPC_ALTINFO_SOURCE; break; case OSPC_CODEC_DESTINATION: attrvalue[1] = OSPC_ALTINFO_DESTINATION; break; default: continue; } if ((errcode == OSPC_ERR_NO_ERROR) && (OSPPUsageIndHasCodec(usage, svc, codec))) { errcode = OSPPStringToElement(OSPC_MELEM_CODEC, OSPPUsageIndGetCodec(usage, svc, codec), 2, attrtype, attrvalue, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usagedetailelem, subelem); subelem = OSPC_OSNULL; } } } } /* Add Session IDs */ for (sess = OSPC_SESSIONID_START; sess < OSPC_SESSIONID_NUMBER; sess ++) { if ((errcode == OSPC_ERR_NO_ERROR) && OSPPUsageIndHasSessionId(usage, sess)) { errcode = OSPPSessionIdToElement(OSPPUsageIndGetSessionId(usage, sess), sess, isbase64, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usagedetailelem, subelem); subelem = OSPC_OSNULL; } } } /* Add Provider Post Dial Delay */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->ProviderPDD >= 0)) { errcode = OSPPMsgFloatToElement((float)(usage->ProviderPDD) / 1000, OSPPMsgElemGetName(OSPC_MELEM_POSTDIALDELAY), &subelem); if (errcode == OSPC_ERR_NO_ERROR) { attr = OSPPXMLAttrNew(OSPPMsgAttrGetName(OSPC_MATTR_TYPE), OSPPAltInfoTypeGetName(OSPC_ALTINFO_DESTINATION)); if (attr == OSPC_OSNULL) { OSPPXMLElemDelete(&subelem); } else { OSPPXMLElemAddAttr(subelem, attr); attr = OSPC_OSNULL; OSPPXMLElemAddChild(usagedetailelem, subelem); subelem = OSPC_OSNULL; } } } /* add usage detail (if appropriate) */ if (errcode == OSPC_ERR_NO_ERROR) { if (OSPPUsageIndHasDuration(usage)) { errcode = OSPPUsageToElement( (unsigned)OSPPUsageIndGetDuration(usage), OSPPUsageIndGetStartTime(usage), OSPPUsageIndGetEndTime(usage), OSPPUsageIndGetAlertTime(usage), OSPPUsageIndGetConnectTime(usage), OSPPUsageIndHasPDD(usage), OSPPUsageIndGetPostDialDelay(usage), OSPPUsageIndGetReleaseSource(usage), usagedetailelem); } } /* Statistics */ if (errcode == OSPC_ERR_NO_ERROR) { if (OSPPUsageIndHasStatistics(usage)) { errcode = OSPPStatsToElement(usage->Stats, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usagedetailelem, subelem); subelem = OSPC_OSNULL; } } } /* Add source audio address */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->SrcAudioAddr[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_SRCAUDIOADDR, trans->SrcAudioAddr, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usagedetailelem, subelem); subelem = OSPC_OSNULL; } } /* Add source video address */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->SrcVideoAddr[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_SRCVIDEOADDR, trans->SrcVideoAddr, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usagedetailelem, subelem); subelem = OSPC_OSNULL; } } /* Add destination audio address */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->DestAudioAddr[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_DESTAUDIOADDR, usage->DestAudioAddr, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usagedetailelem, subelem); subelem = OSPC_OSNULL; } } /* Add destination video address */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->DestVideoAddr[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_DESTVIDEOADDR, usage->DestVideoAddr, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usagedetailelem, subelem); subelem = OSPC_OSNULL; } } if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, usagedetailelem); usagedetailelem = OSPC_OSNULL; } /* now add the transnexus extensions (if available) */ if (errcode == OSPC_ERR_NO_ERROR) { if (OSPPUsageIndHasCustId(usage)) { errcode = OSPPMsgNumToElement(OSPPUsageIndGetCustId(usage), OSPPMsgElemGetName(OSPC_MELEM_CUSTID), &subelem); /*add attribute critical = "False" since not all servers understand */ if (errcode == OSPC_ERR_NO_ERROR) { attr = OSPPXMLAttrNew(OSPPMsgAttrGetName(OSPC_MATTR_CRITICAL), OSPPAltInfoTypeGetName(OSPC_ALTINFO_FALSE)); if (attr == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ATTR; } else { OSPPXMLElemAddAttr(subelem, attr); attr = OSPC_OSNULL; OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } if (OSPPUsageIndHasDeviceId(usage)) { errcode = OSPPMsgNumToElement(OSPPUsageIndGetDeviceId(usage), OSPPMsgElemGetName(OSPC_MELEM_DEVICEID), &subelem); /*add attribute critical = "False" since not all servers understand */ if (errcode == OSPC_ERR_NO_ERROR) { attr = OSPPXMLAttrNew(OSPPMsgAttrGetName(OSPC_MATTR_CRITICAL), OSPPAltInfoTypeGetName(OSPC_ALTINFO_FALSE)); if (attr == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ATTR; } else { OSPPXMLElemAddAttr(subelem, attr); attr = OSPC_OSNULL; OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } } } } /* Add source realm info */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->SrcRealm[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_SRCREALM, trans->SrcRealm, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add destination realm info */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->DestRealm[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_DESTREALM, trans->DestRealm, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add SIP headers */ for (header = OSPC_SIPHEADER_START; header < OSPC_SIPHEADER_NUMBER; header++) { for (format = OSPC_NFORMAT_START; format < OSPC_NFORMAT_NUMBER; format++) { if ((errcode == OSPC_ERR_NO_ERROR) && (trans->SipHeader[header][format][0] != '\0')) { errcode = OSPPCallPartyNumToElement(OSPV_MELEM_SIPHEADER[header], trans->SipHeader[header][format], format, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } } } /* add diversion device info */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->DivDevInfo[0] != '\0')) { attrtype[0] = OSPC_MATTR_TYPE; attrvalue[0] = OSPC_ALTINFO_TRANSPORT; errcode = OSPPStringToElement(OSPC_MELEM_DIVDEVINFO, trans->DivDevInfo, 1, attrtype, attrvalue, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add application ID */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->ApplicationId[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_APPLID, trans->ApplicationId, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* add network translated called number */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->NetworkTranslatedCalled[0] != '\0')) { errcode = OSPPCallPartyNumToElement(OSPC_MELEM_NETTRANSCALLED, trans->NetworkTranslatedCalled, trans->NetworkTranslatedCalledFormat, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add source service provider */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->SrcServiceProvider[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_SERVICEPROVIDER, trans->SrcServiceProvider, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add destination service provider */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->DestServiceProvider[0] != '\0')) { attrtype[0] = OSPC_MATTR_TYPE; attrvalue[0] = OSPC_ALTINFO_DESTINATION; errcode = OSPPStringToElement(OSPC_MELEM_SERVICEPROVIDER, usage->DestServiceProvider, 1, attrtype, attrvalue, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add system ID */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->SystemId[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_SYSTEMID, trans->SystemId, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add related reason */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->RelatedReason[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_RELATEDREASON, trans->RelatedReason, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add CDR proxy */ if ((errcode == OSPC_ERR_NO_ERROR) && ((trans->CDRProxyHost[0] != '\0') || (trans->CDRProxyFolder[0] != '\0') || (trans->CDRProxySubfolder[0] != '\0'))) { cdrproxyelem = OSPPXMLElemNew(OSPPMsgElemGetName(OSPC_MELEM_CDRPROXY), ""); if (cdrproxyelem == OSPC_OSNULL) { errcode = OSPC_ERR_XML_NO_ELEMENT; } } if ((errcode == OSPC_ERR_NO_ERROR) && (trans->CDRProxyHost[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_CDRPROXYHOST, trans->CDRProxyHost, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(cdrproxyelem, subelem); subelem = OSPC_OSNULL; } else { OSPPXMLElemDelete(&cdrproxyelem); roleinfoelem = OSPC_OSNULL; } } if ((errcode == OSPC_ERR_NO_ERROR) && (trans->CDRProxyFolder[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_CDRPROXYFOLDER, trans->CDRProxyFolder, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(cdrproxyelem, subelem); subelem = OSPC_OSNULL; } else { OSPPXMLElemDelete(&cdrproxyelem); roleinfoelem = OSPC_OSNULL; } } if ((errcode == OSPC_ERR_NO_ERROR) && (trans->CDRProxySubfolder[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_CDRPROXYSUBFOLDER, trans->CDRProxySubfolder, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(cdrproxyelem, subelem); subelem = OSPC_OSNULL; } else { OSPPXMLElemDelete(&cdrproxyelem); roleinfoelem = OSPC_OSNULL; } } if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, cdrproxyelem); cdrproxyelem = OSPC_OSNULL; } /* Add Jurisdiction Information Parameter */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->JIP[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_JIP, trans->JIP, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add call type */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->CallType[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_CALLTYPE, usage->CallType, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add call category */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->CallCategory[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_CALLCATEGORY, usage->CallCategory, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add network type */ if ((errcode == OSPC_ERR_NO_ERROR) && (usage->NetworkType[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_NETWORKTYPE, usage->NetworkType, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add SIP request Date */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->RequestDate != OSPC_TIMEMIN)) { errcode = OSPPMsgTimeToElement(trans->RequestDate, OSPPMsgElemGetName(OSPC_MELEM_REQUESTDATE), &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } if (errcode == OSPC_ERR_NO_ERROR) { /* Add SDP finger print */ if (OSPPHasFingerprint(trans->SDPFingerprint)) { for (fingerprint = OSPPFirstFingerprint(trans->SDPFingerprint); ((fingerprint != OSPC_OSNULL) && (errcode == OSPC_ERR_NO_ERROR)); fingerprint = OSPPNextFingerprint(trans->SDPFingerprint, fingerprint)) { errcode = OSPPFingerprintToElement(fingerprint, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } } } /* Add charging vector */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->PCVICID[0] != '\0')) { attrtype[0] = OSPC_MATTR_TYPE; attrvalue[0] = OSPC_ALTINFO_ICID; errcode = OSPPStringToElement(OSPC_MELEM_CHARGINGVECTOR, trans->PCVICID, 1, attrtype, attrvalue, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add user rate plan */ for (index = 0; index < OSPC_CPARTY_NUMBER; index++) { attrtype[0] = OSPC_MATTR_TYPE; if (trans->UserRatePlan[index][0] != '\0') { if (index == OSPC_CPARTY_SOURCE) { attrvalue[0] = OSPC_ALTINFO_SOURCE; } else { attrvalue[0] = OSPC_ALTINFO_DESTINATION; } errcode = OSPPStringToElement(OSPC_MELEM_USERRATEPLAN, trans->UserRatePlan[index], 1, attrtype, attrvalue, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } } /* Add User-Agnet */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->UserAgent[0] != '\0')) { errcode = OSPPStringToElement(OSPC_MELEM_USERAGENT, trans->UserAgent, 0, OSPC_OSNULL, OSPC_OSNULL, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } /* Add STIR info */ if ((errcode == OSPC_ERR_NO_ERROR) && (trans->StiAsStatus[0] != '\0')) { errcode = OSPPStiAsToElement(trans->StiAsStatus, trans->StiAsAttest, trans->StiAsOrigId, trans->StiAsCpsLatency, trans->StiAsCpsRspCode, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } if ((errcode == OSPC_ERR_NO_ERROR) && (trans->StiVsStatus[0] != '\0')) { errcode = OSPPStiVsToElement(trans->StiVsStatus, trans->StiVsAttest, trans->StiVsOrigId, trans->StiVsCertCached, trans->StiVsCertLatency, trans->StiVsCertUrl, trans->StiVsCpsLatency, trans->StiVsCpsRspCode, &subelem); if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(usageindelem, subelem); subelem = OSPC_OSNULL; } } if (errcode == OSPC_ERR_NO_ERROR) { OSPPXMLElemAddChild(*ospvElem, usageindelem); usageindelem = OSPC_OSNULL; } } /* end for */ } /* if for any reason we found an error - destroy any elements created */ if (errcode != OSPC_ERR_NO_ERROR) { if (*ospvElem != OSPC_OSNULL) { OSPPXMLElemDelete(ospvElem); } if (usageindelem != OSPC_OSNULL) { OSPPXMLElemDelete(&usageindelem); } if (usagedetailelem != OSPC_OSNULL) { OSPPXMLElemDelete(&usagedetailelem); } if (subelem != OSPC_OSNULL) { OSPPXMLElemDelete(&subelem); } if (attr != OSPC_OSNULL) { OSPPXMLAttrDelete(&attr); } } return errcode; } /* * OSPPUsageIndAddSourceAlt() - add a source alt to list a list */ void OSPPUsageIndAddSourceAlt( OSPT_USAGE_IND *ospvUsageInd, /* authorization indication */ OSPT_ALTINFO *ospvAltInfo) /* altinfo to add */ { if ((ospvUsageInd != OSPC_OSNULL) && (ospvAltInfo != OSPC_OSNULL)) { OSPPListAppend(&(ospvUsageInd->SourceAlternate), ospvAltInfo); } } /* * OSPPUsageIndAddDestinationAlt() - add a destination alt to list a list */ void OSPPUsageIndAddDestinationAlt( OSPT_USAGE_IND *ospvUsageInd, /* authorization indication */ OSPT_ALTINFO *ospvAltInfo) /* altinfo to add */ { if ((ospvUsageInd != OSPC_OSNULL) && (ospvAltInfo != OSPC_OSNULL)) { OSPPListAppend(&(ospvUsageInd->DestinationAlternate), ospvAltInfo); } } /* * OSPPUsageIndHasMessageId() - is the message id set ? */ OSPTBOOL OSPPUsageIndHasMessageId( /* returns non-zero if message id is set */ OSPT_USAGE_IND *ospvUsageInd) { if (ospvUsageInd != OSPC_OSNULL) { return(ospvUsageInd->MessageId != OSPC_OSNULL); } else { return OSPC_FALSE; } } /* * OSPPUsageIndGetMessageId() - returns a new copy of the message id. */ const char *OSPPUsageIndGetMessageId( OSPT_USAGE_IND *ospvUsageInd) { const char *messagestring = OSPC_OSNULL; int len = 0; if (OSPPUsageIndHasMessageId(ospvUsageInd)) { len = OSPM_STRLEN(ospvUsageInd->MessageId); OSPM_MALLOC(messagestring, char, len + 1); OSPM_MEMSET(messagestring, 0, len + 1); OSPM_MEMCPY(messagestring, ospvUsageInd->MessageId, len); } return messagestring; } void OSPPUsageIndSetDestinationCount( OSPT_USAGE_IND *ospvUsageInd, unsigned ospvDestinationCount) { char buf[64]; if (ospvDestinationCount >= 0) { sprintf(buf, "%d", ospvDestinationCount); ospvUsageInd->DestinationCount = OSPPAltInfoNew(OSPM_STRLEN(buf), buf, OSPC_ALTINFO_DEVICEID); ospvUsageInd->SetupAttempt = ospvDestinationCount; } } OSPT_ALTINFO *OSPPUsageIndGetDestinationCount( OSPT_USAGE_IND *ospvUsageInd) { if (ospvUsageInd != OSPC_OSNULL) { return ospvUsageInd->DestinationCount; } else { return OSPC_OSNULL; } } OSPTBOOL OSPPUsageIndHasProtocol( OSPT_USAGE_IND *ospvUsageInd, OSPE_PROTOCOL_TYPE ospvType) { OSPTBOOL has = OSPC_FALSE; if (ospvUsageInd != OSPC_OSNULL) { if (OSPM_VALIDATE_PROTTYPE(ospvType) && ((ospvUsageInd->Protocol[ospvType] >= OSPC_PROTNAME_START) && (ospvUsageInd->Protocol[ospvType] < OSPC_PROTNAME_NUMBER))) { has = OSPC_TRUE; } } return has; } OSPE_PROTOCOL_NAME OSPPUsageIndGetProtocol( OSPT_USAGE_IND *ospvUsageInd, OSPE_PROTOCOL_TYPE ospvType) { OSPE_PROTOCOL_NAME protocol = OSPC_PROTNAME_UNKNOWN; if ((ospvUsageInd != OSPC_OSNULL) && OSPM_VALIDATE_PROTTYPE(ospvType)) { protocol = ospvUsageInd->Protocol[ospvType]; } return protocol; } void OSPPUsageIndSetProtocol( OSPT_USAGE_IND *ospvUsageInd, OSPE_PROTOCOL_TYPE ospvType, OSPE_PROTOCOL_NAME ospvName) { if ((ospvUsageInd != OSPC_OSNULL) && OSPM_VALIDATE_PROTTYPE(ospvType) && OSPM_VALIDATE_PROTNAME(ospvName)) { ospvUsageInd->Protocol[ospvType] = ospvName; } } OSPTBOOL OSPPUsageIndHasCodec( OSPT_USAGE_IND *ospvUsageInd, OSPE_SERVICE ospvService, OSPE_CODEC_TYPE ospvType) { OSPTBOOL has = OSPC_FALSE; if ((ospvUsageInd != OSPC_OSNULL) && ((ospvService >= OSPC_SERVICE_START) && (ospvService < OSPC_SERVICE_NUMBER)) && ((ospvType >= OSPC_CODEC_START) && (ospvType < OSPC_CODEC_NUMBER))) { has = (ospvUsageInd->Codec[ospvService][ospvType][0] != '\0'); } return has; } const char *OSPPUsageIndGetCodec( OSPT_USAGE_IND *ospvUsageInd, OSPE_SERVICE ospvService, OSPE_CODEC_TYPE ospvType) { const char *ospvCodec = OSPC_OSNULL; if ((ospvUsageInd != OSPC_OSNULL) && ((ospvService >= OSPC_SERVICE_START) && (ospvService < OSPC_SERVICE_NUMBER)) && ((ospvType >= OSPC_CODEC_START) && (ospvType < OSPC_CODEC_NUMBER))) { ospvCodec = ospvUsageInd->Codec[ospvService][ospvType]; } return ospvCodec; } void OSPPUsageIndSetCodec( OSPT_USAGE_IND *ospvUsageInd, OSPE_SERVICE ospvService, OSPE_CODEC_TYPE ospvType, const char *ospvCodec) { if ((ospvUsageInd != OSPC_OSNULL) && ((ospvService >= OSPC_SERVICE_START) && (ospvService < OSPC_SERVICE_NUMBER)) && ((ospvType >= OSPC_CODEC_START) && (ospvType < OSPC_CODEC_NUMBER)) && (ospvCodec != OSPC_OSNULL)) { OSPM_STRNCPY(ospvUsageInd->Codec[ospvService][ospvType], ospvCodec, sizeof(ospvUsageInd->Codec[ospvService][ospvType])); } } /* * OSPPUsageIndHasSessionId() - does an usage indication have session ID? */ OSPTBOOL OSPPUsageIndHasSessionId( /* Returns non-zero if exists */ OSPT_USAGE_IND *ospvUsageInd, /* Usage indication */ OSPE_SESSION_ID ospvType) /* Session id type */ { OSPTBOOL has = OSPC_FALSE; if ((ospvUsageInd != OSPC_OSNULL) && ((ospvType >= OSPC_SESSIONID_START) && (ospvType < OSPC_SESSIONID_NUMBER))) { has = (ospvUsageInd->SessionId[ospvType] != OSPC_OSNULL); } return has; } /* * OSPPUsageIndGetSessionId() - gets session ID for an usage indication */ OSPT_CALL_ID *OSPPUsageIndGetSessionId( /* Returns session ID pointer */ OSPT_USAGE_IND *ospvUsageInd, /* Usage indication */ OSPE_SESSION_ID ospvType) /* Session id type */ { OSPT_CALL_ID *ospvSessionId = OSPC_OSNULL; if ((ospvUsageInd != OSPC_OSNULL) && ((ospvType >= OSPC_SESSIONID_START) && (ospvType < OSPC_SESSIONID_NUMBER))) { ospvSessionId = ospvUsageInd->SessionId[ospvType]; } return ospvSessionId; } /* * OSPPUsageIndSetSessionId() - sets session ID for an usage */ void OSPPUsageIndSetSessionId( /* Nothing returned */ OSPT_USAGE_IND *ospvUsageInd, /* Usage indication */ OSPE_SESSION_ID ospvType, /* Session ID type */ OSPT_CALL_ID *ospvSessionId) /* Session ID */ { if ((ospvUsageInd != OSPC_OSNULL) && ((ospvType >= OSPC_SESSIONID_START) && (ospvType < OSPC_SESSIONID_NUMBER)) && (ospvSessionId != OSPC_OSNULL)) { if (ospvUsageInd->SessionId[ospvType] != OSPC_OSNULL) { OSPPCallIdDelete(&(ospvUsageInd->SessionId[ospvType])); } ospvUsageInd->SessionId[ospvType] = OSPPCallIdNew(ospvSessionId->Length, ospvSessionId->Value); } }
36.048319
233
0.581526
[ "vector" ]
446ec35381076ac7f5fc5cfa1d628047f03dfb49
4,832
h
C
third_party/webcc/body.h
sprinfall/webcc-integration
1abfccd75d43f0ec981a1b31a977c68f757b8994
[ "MIT" ]
1
2020-09-11T09:57:30.000Z
2020-09-11T09:57:30.000Z
third_party/webcc/body.h
sprinfall/webcc-integration
1abfccd75d43f0ec981a1b31a977c68f757b8994
[ "MIT" ]
null
null
null
third_party/webcc/body.h
sprinfall/webcc-integration
1abfccd75d43f0ec981a1b31a977c68f757b8994
[ "MIT" ]
null
null
null
#ifndef WEBCC_BODY_H_ #define WEBCC_BODY_H_ #include <memory> #include <string> #include <utility> #include "webcc/common.h" #include "webcc/fs.h" namespace webcc { // ----------------------------------------------------------------------------- class Body { public: Body() = default; virtual ~Body() = default; // Get the size in bytes of the body. virtual std::size_t GetSize() const { return 0; } bool IsEmpty() const { return GetSize() == 0; } #if WEBCC_ENABLE_GZIP // Compress the data with Gzip. // If data size <= threshold (1400 bytes), no compression will be taken // and false will be simply returned. virtual bool Compress() { return false; } // Decompress the data. virtual bool Decompress() { return false; } #endif // WEBCC_ENABLE_GZIP // Initialize the payload for iteration. // Usage: // InitPayload(); // for (auto p = NextPayload(); !p.empty(); p = NextPayload()) { // } virtual void InitPayload() { } // Get the next payload. // An empty payload returned indicates the end. virtual Payload NextPayload(bool free_previous = false) { return {}; } // Dump to output stream for logging purpose. virtual void Dump(std::ostream& os, const std::string& prefix) const { } }; using BodyPtr = std::shared_ptr<Body>; // ----------------------------------------------------------------------------- class StringBody : public Body { public: explicit StringBody(const std::string& data, bool compressed) : data_(data), compressed_(compressed) { } explicit StringBody(std::string&& data, bool compressed) : data_(std::move(data)), compressed_(compressed) { } std::size_t GetSize() const override { return data_.size(); } const std::string& data() const { return data_; } bool compressed() const { return compressed_; } #if WEBCC_ENABLE_GZIP bool Compress() override; bool Decompress() override; #endif // WEBCC_ENABLE_GZIP void InitPayload() override; Payload NextPayload(bool free_previous = false) override; void Dump(std::ostream& os, const std::string& prefix) const override; private: std::string data_; // Is the data compressed? bool compressed_; // Index for (not really) iterating the payload. std::size_t index_ = 0; }; // ----------------------------------------------------------------------------- // Multi-part form body for request. class FormBody : public Body { public: FormBody(const std::vector<FormPartPtr>& parts, const std::string& boundary); std::size_t GetSize() const override; const std::vector<FormPartPtr>& parts() const { return parts_; } void InitPayload() override; Payload NextPayload(bool free_previous = false) override; void Dump(std::ostream& os, const std::string& prefix) const override; private: void AddBoundary(Payload* payload); void AddBoundaryEnd(Payload* payload); void Free(std::size_t index); private: std::vector<FormPartPtr> parts_; std::string boundary_; // Index for iterating the payload. std::size_t index_ = 0; }; // ----------------------------------------------------------------------------- // File body for server to serve a file without loading the whole of it into // the memory. class FileBody : public Body { public: // For message to be sent out. FileBody(const fs::path& path, std::size_t chunk_size); // For message received. // No |chunk_size| is needed since you don't iterate the payload of a // received message. // If |auto_delete| is true, the file will be deleted on destructor unless it // is moved to another path (see Move()). FileBody(const fs::path& path, bool auto_delete = false); ~FileBody() override; std::size_t GetSize() const override { return size_; } void InitPayload() override; Payload NextPayload(bool free_previous = false) override; void Dump(std::ostream& os, const std::string& prefix) const override; const fs::path& path() const { return path_; } // Move (or rename) the file. // Used to move the streamed file of the received message to a new place. // Applicable to both client and server. // After move, the original path will be reset to empty. // If |new_path| and |path_| resolve to the same file, do nothing and just // return false. // If |new_path| resolves to an existing non-directory file, it is removed. // If |new_path| resolves to an existing directory, it is removed if empty // on ISO/IEC 9945 but is an error on Windows. // See fs::rename() for more details. bool Move(const fs::path& new_path); private: fs::path path_; std::size_t chunk_size_; bool auto_delete_; std::size_t size_; // File size in bytes fs::ifstream ifstream_; std::string chunk_; }; } // namespace webcc #endif // WEBCC_BODY_H_
23.570732
80
0.637624
[ "vector" ]
447dc466d5498c04120e0b2204d0e4e2f6acfa99
8,440
h
C
libAfterStep/freestor.h
trofi/afterstep
5e9e897cf8c455390dd6f5b27fec49707f6b9088
[ "MIT" ]
25
2018-09-18T13:05:15.000Z
2022-01-30T21:08:51.000Z
libAfterStep/freestor.h
trofi/afterstep
5e9e897cf8c455390dd6f5b27fec49707f6b9088
[ "MIT" ]
5
2016-07-14T13:06:10.000Z
2021-12-05T17:47:35.000Z
libAfterStep/freestor.h
trofi/afterstep
5e9e897cf8c455390dd6f5b27fec49707f6b9088
[ "MIT" ]
7
2016-10-14T02:49:23.000Z
2021-11-20T10:14:01.000Z
#ifndef FREESTOR_H_HEADER_INCLUDED #define FREESTOR_H_HEADER_INCLUDED #ifdef __cplusplus extern "C" { #endif struct SyntaxDef; struct TermDef; struct ASHashTable; struct ConfigDef; struct ASCursor ; typedef struct FreeStorageElem { struct FreeStorageElem *next; struct FreeStorageElem *sub; /* points to the chain of sub-elements, for representation of the complex config constructs. for example if following is encountered : MyStyle "some_style" BackPixmap "some_pixmap" ForeColor blue ~MyStyle it will be read in to the following : ...->{MyStyle_term,"some_style", sub, next->}... | --------------------------------- | V { BackPixmap_term,"some_pixmap", sub=NULL, next } | --------------------------------------------- | V { ForeColor_term,"blue", sub=NULL, next=NULL } */ struct TermDef *term; unsigned long flags; /* see current_flags for possible values */ char **argv; /* space separated words from the source data will be placed here unless DONT_SPLIT_WORDS defined for the term */ int argc; /* number of words */ } FreeStorageElem; #define SPECIAL_BREAK (0x01<<0) #define SPECIAL_SKIP (0x01<<1) #define SPECIAL_STORAGE_ADDED (0x01<<2) void init_asgeometry (ASGeometry * geometry); int parse_modifier( char *tline ); int parse_win_context (char *tline); char *parse_modifier_str( char *tline, int *mods_ret ); char *parse_win_context_str (char *tline, int *ctxs_ret); /* pelem must be preinitialized with pointer to particular term */ void args2FreeStorage (FreeStorageElem * pelem, char *data, int data_len); /* utility functions for writing config */ void ReverseFreeStorageOrder (FreeStorageElem ** storage); FreeStorageElem *DupFreeStorageElem (FreeStorageElem * source); FreeStorageElem *AddFreeStorageElem (struct SyntaxDef * syntax, FreeStorageElem ** tail, struct TermDef * pterm, int id, ...); void CopyFreeStorage (FreeStorageElem ** to, FreeStorageElem * from); void DestroyFreeStorage (FreeStorageElem ** storage); void StorageCleanUp (FreeStorageElem ** storage, FreeStorageElem ** garbadge_bin, unsigned long mask); void freestorage_print(char *myname, struct SyntaxDef *syntax, FreeStorageElem * storage, int level); struct FunctionData; /* freestorage post processing stuff */ struct FunctionData *free_storage2func (FreeStorageElem * stored, int *ppos); char *free_storage2quoted_text (FreeStorageElem * stored, int *ppos); int *free_storage2int_array (FreeStorageElem * stored, int *ppos); #define SET_CONFIG_FLAG(flags,mask,val) do{set_flags(flags,val);set_flags(mask,val);}while(0) typedef struct ConfigItem { void *memory; /* this one holds pointer to entire block of allocated memory */ int ok_to_free; /* must be set in order to free memory allocated before and stored in [memory] member */ int type; int index; /* valid only for those that has TF_INDEXED set */ union { ASGeometry geometry; long integer; Bool flag; struct { int size; int *array; } int_array; char *string; struct FunctionData *function; struct ASButton *button; ASBox box; struct { char *sym ; int context ; int mods ; }binding; struct ASCursor *cursor ; } data; }ConfigItem; typedef struct flag_options_xref { unsigned long flag; int id_on, id_off; ptrdiff_t flag_field_offset ; ptrdiff_t set_flag_field_offset ; } flag_options_xref; /* this functions return 1 on success - 0 otherwise */ int ReadConfigItem (ConfigItem * item, FreeStorageElem * stored); Bool ReadConfigItemToStruct( void *struct_ptr, ptrdiff_t set_flags_offset, FreeStorageElem * stored ); Bool ReadCompositeFlagsConfigItem( void *struct_ptr, ptrdiff_t flags_field_offset, FreeStorageElem * stored ); /* indexed flags cannot be handled by ReadFlagItem - it will return 0 for those - handle them manually using ReadConfigItem */ int ReadFlagItem (unsigned long *set_flags, unsigned long *flags, FreeStorageElem * stored, flag_options_xref * xref); int ReadFlagItemAuto (void *config_struct, ptrdiff_t default_set_flags_offset, FreeStorageElem * stored, flag_options_xref * xref); /* really defined in libAfterBase/mystring.h (unsigned long*)*/ void set_string (char **target, char *string); #define set_string_value(ptarget,string,pset_flags,flag) \ do {ASFlagType *_fp_ = (pset_flags);set_string(ptarget,string); if(_fp_)set_flags(*_fp_,(flag));}while(0) #define set_scalar_value(ptarget,val,pset_flags,flag) \ do {*(ptarget)=(val); if(pset_flags)set_flags(*(pset_flags),(flag));}while(0) #define set_size_geometry(pw,ph,pitem,pset_flags,flag) \ do { *(pw) = get_flags ((pitem)->data.geometry.flags, WidthValue)?(pitem)->data.geometry.width:0; \ *(ph) = get_flags ((pitem)->data.geometry.flags, HeightValue)?(pitem)->data.geometry.height:0; \ if(pset_flags)set_flags(*(pset_flags),(flag));}while(0) /* string array manipulation functions */ /* StringArray is an array of pointers to continuous block of memory, * holding several zero terminated strings. * When such array is to be deallocated - only the first pointer from it needs to be * deallocated - that will deallocate entire storage. * and when it needs to be created - first pointer should be allocated entire block of memory * to hold all strings and terminating zeros */ char **CreateStringArray (size_t elem_num); size_t GetStringArraySize (int argc, char **argv); char *CompressStringArray (int argc, char **argv); char **DupStringArray (int argc, char **argv); void AddStringToArray (int *argc, char ***argv, char *new_string); #define REPLACE_STRING(str1,str2) {if(str1)free(str1);str1=str2;} /* they all return pointer to the storage's tail */ FreeStorageElem **Flag2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, int id); /* you can add all your flags at once : */ FreeStorageElem **Flags2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, flag_options_xref * xref, unsigned long set_flags, unsigned long flags); #define ADD_SET_FLAG(syntax,tail,flags,flag,id) \ ((get_flags((flags),(flag)))?Flag2FreeStorage((syntax),(tail),(id)):(tail)) FreeStorageElem **Integer2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, int *index, int value, int id); FreeStorageElem **Strings2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, char **strings, unsigned int num, int id); #define String2FreeStorage(syntax,t,s,id) Strings2FreeStorage(syntax,t,&(s), 1, id) FreeStorageElem **QuotedString2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, int *index, char *string, int id); FreeStorageElem **StringArray2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, char **strings, int index1, int index2, int id, char *iformat); FreeStorageElem **Path2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, int *index, char *string, int id); FreeStorageElem **Geometry2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, ASGeometry * geometry, int id); FreeStorageElem **ASButton2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, int index, ASButton * b, int id); FreeStorageElem **Box2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, ASBox * box, int id); FreeStorageElem **Binding2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, char *sym, int context, int mods, int id); FreeStorageElem **ASCursor2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, int index, struct ASCursor *c, int id); FreeStorageElem **Bitlist2FreeStorage (struct SyntaxDef * syntax, FreeStorageElem ** tail, long bits, int id); /* the following function automagically creates FreeStorage for the data structure and Syntax, it returns created storage and flags will be set in handled_return for any item handled */ FreeStorageElem *StructToFreeStorage (void *struct_ptr, ptrdiff_t set_flags_offset, struct SyntaxDef *syntax, ASFlagType *handled_return ); FreeStorageElem *StructFlags2FreeStorage (void *struct_ptr, ptrdiff_t default_set_flags_offset, struct SyntaxDef *syntax, flag_options_xref * xref, ASFlagType *handled_return); #define ADVANCE_LINKED_LIST_TAIL(ptail) while (*(ptail)) (ptail) = &((*(ptail))->next) #ifdef __cplusplus } #endif #endif
35.914894
131
0.729384
[ "geometry" ]
44877d6d14ff5f773c3361061635094fdbfa46f4
2,834
h
C
B2G/gecko/netwerk/ipc/RemoteOpenFileChild.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/netwerk/ipc/RemoteOpenFileChild.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/netwerk/ipc/RemoteOpenFileChild.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: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set sw=2 ts=8 et tw=80 : */ /* 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/. */ #ifndef _RemoteOpenFileChild_h #define _RemoteOpenFileChild_h #include "mozilla/dom/TabChild.h" #include "mozilla/net/PRemoteOpenFileChild.h" #include "nsILocalFile.h" #include "nsIRemoteOpenFileListener.h" namespace mozilla { namespace net { /** * RemoteOpenFileChild: a thin wrapper around regular nsIFile classes that does * IPC to open a file handle on parent instead of child. Used when we can't * open file handle on child (don't have permission), but we don't want the * overhead of shipping all I/O traffic across IPDL. Example: JAR files. * * To open a file handle with this class, AsyncRemoteFileOpen() must be called * first. After the listener's OnRemoteFileOpenComplete() is called, if the * result is NS_OK, nsIFile.OpenNSPRFileDesc() may be called--once--to get the * file handle. * * Note that calling Clone() on this class results in the filehandle ownership * being passed on to the new RemoteOpenFileChild. I.e. if * OnRemoteFileOpenComplete is called and then Clone(), OpenNSPRFileDesc() will * work in the cloned object, but not in the original. * * This class should only be instantiated in a child process. * */ class RemoteOpenFileChild MOZ_FINAL : public PRemoteOpenFileChild , public nsIFile , public nsIHashable { public: RemoteOpenFileChild() : mNSPRFileDesc(nullptr) , mAsyncOpenCalled(false) , mNSPROpenCalled(false) {} virtual ~RemoteOpenFileChild(); NS_DECL_ISUPPORTS NS_DECL_NSIFILE NS_DECL_NSIHASHABLE // URI must be scheme 'remoteopenfile://': otherwise looks like a file:// uri. nsresult Init(nsIURI* aRemoteOpenUri); void AddIPDLReference(); void ReleaseIPDLReference(); // Send message to parent to tell it to open file handle for file. // TabChild is required, for IPC security. // Note: currently only PR_RDONLY is supported for 'flags' nsresult AsyncRemoteFileOpen(int32_t aFlags, nsIRemoteOpenFileListener* aListener, nsITabChild* aTabChild); private: RemoteOpenFileChild(const RemoteOpenFileChild& other); protected: virtual bool RecvFileOpened(const FileDescriptor&); virtual bool RecvFileDidNotOpen(); // regular nsIFile object, that we forward most calls to. nsCOMPtr<nsIFile> mFile; nsCOMPtr<nsIURI> mURI; nsCOMPtr<nsIRemoteOpenFileListener> mListener; PRFileDesc* mNSPRFileDesc; bool mAsyncOpenCalled; bool mNSPROpenCalled; }; } // namespace net } // namespace mozilla #endif // _RemoteOpenFileChild_h
32.204545
80
0.730064
[ "object" ]
44a13da5f796c6e650e947b3cbc410529d57d665
8,408
h
C
include/http/http.h
Skifary/http
a051b73583913e9e1d113c347c68cdef2e7a9555
[ "MIT" ]
2
2018-11-17T03:08:11.000Z
2021-04-16T23:40:20.000Z
include/http/http.h
Skifary/http
a051b73583913e9e1d113c347c68cdef2e7a9555
[ "MIT" ]
null
null
null
include/http/http.h
Skifary/http
a051b73583913e9e1d113c347c68cdef2e7a9555
[ "MIT" ]
null
null
null
#pragma once /*************************************************************************** * * Copyright (C) 2018, Skifary, <gskifary@outlook.com>. * ***************************************************************************/ #include <memory> #include <functional> #include <initializer_list> #include <string> #include <fstream> #include <unordered_map> #include <sstream> #include <algorithm> #include <iostream> #include <vector> #include <future> #include <curl/curl.h> namespace http { // http status code #define HTTP_OK 200 // common #define HTTP_FWD(...) ::std::forward<decltype(__VA_ARGS__)>(__VA_ARGS__) #define HTTP_MOVE(...) ::std::move(__VA_ARGS__) #define HTTP_ASSERT(expr) assert((expr)) #define HTTP_STATIC_ASSERT(expr, msg) static_assert(expr,msg) // class wrapper #define ClassWrapper(cls, type) class cls\ {\ public:\ cls() = default;\ cls(type& value):value_(value){};\ cls(type&& value):value_(HTTP_MOVE(value)){};\ public:\ type value_;\ }; // declare wrapper class ClassWrapper(DownloadFilePath, std::string) ClassWrapper(URL, std::string) ClassWrapper(Progress, std::function<void(double)>) ClassWrapper(Payload, std::string) using byte_t = unsigned char; struct Field { template <typename T> Field(std::string key, T value) :key_(HTTP_MOVE(key)) { std::ostringstream stream; stream << value; value_ = stream.str(); }; public: std::string key_; std::string value_; }; class Headers { public: Headers() = default; Headers(std::string&& header_string); Headers(std::string& header_string); Headers(std::unordered_map<std::string, std::string>& map); Headers(const std::initializer_list<Field>& headers); // field template <typename T> T GetField(std::string field) { // avoid inserting a null value T t{}; auto itr = _storage_headers.find(field); if (itr == _storage_headers.end()) { return t; } std::istringstream stream(itr->second); stream >> t; return HTTP_MOVE(t); }; // GetField template specialization for std::string template <> std::string GetField(std::string field) { // avoid inserting a null value auto itr = _storage_headers.find(field); if (itr == _storage_headers.end()) { return ""; } return _storage_headers[field]; }; template <> bool GetField(std::string field) { // avoid inserting a null value auto itr = _storage_headers.find(field); if (itr == _storage_headers.end()) { return false; } // compatible both "0&&1" and "true&&false" if (_storage_headers[field] == "true") { return true; } bool b; std::istringstream stream(itr->second); stream >> b; return HTTP_MOVE(b); }; template <typename T> void SetField(std::string field, T value) { std::ostringstream stream; stream << value; _storage_headers[field] = stream.str(); }; curl_slist* Chunk(); Headers& Merge(Headers& other); private: void __parse_http_header(std::string& header_string); private: std::unordered_map<std::string, std::string> _storage_headers; }; // response class Response { public: Response() = default; Response(int&& code, std::string&& body, Headers&& headers, std::string&& error); public: int code_; std::string body_; Headers headers_; std::string error_; }; // ---------------------------------------------------------------------------------- // // CURLHandle // // ---------------------------------------------------------------------------------- class CURLHandle { public: CURL * curl_; curl_slist *chunk_; curl_mime *mime_; }; // ---------------------------------------------------------------------------------- // // Parameter // // ---------------------------------------------------------------------------------- class Parameters { public: Parameters() = default; Parameters(const std::initializer_list<Field>& parameters); void AddParameter(const Field& parameter); public: std::string format_value_; }; // ---------------------------------------------------------------------------------- // // Multipart // // ---------------------------------------------------------------------------------- class Part { public: Part() = default; Part(std::string type, byte_t* data, std::string name = "") :type_(HTTP_MOVE(type)), is_file_{ false }, data_((char*)data), name_(name) {}; Part(std::string filepath, std::string name = "") : is_file_{ true }, data_(filepath), name_(name) {}; public: std::string type_; bool is_file_; std::string data_; std::string name_; }; class Multipart { public: Multipart(const std::initializer_list<Part>& parts); curl_mime* Add2Curl(CURL *curl); private: std::vector<Part> _parts; }; // ---------------------------------------------------------------------------------- // // Session // // ---------------------------------------------------------------------------------- class Session { public: Session(); // options void SetOption(URL& url); void SetOption(Parameters& parameters); void SetOption(Headers& headers); void SetOption(DownloadFilePath& filepath); void SetOption(Progress& progress); void SetOption(Multipart& multipart); void SetOption(Payload& payload); // method Response Get(); Response Post(); Response Head(); private: // options void __set_url(URL& url); void __set_parameters(Parameters& parameters); void __set_headers(Headers& headers); void __set_download_filepath(DownloadFilePath& filepath); void __set_progress(Progress& progress); void __set_multipart(Multipart& multipart); void __set_payload(Payload& payload); // core request Response __request(CURL *curl); // curl life manager CURLHandle* __curl_handle_init(); static void __curl_handle_free(CURLHandle* handle); // resp custom deleter static void __resp_data_deleter(struct __write_data_t *ptr); // curl write callback static size_t __write_function(void* ptr, size_t size, size_t nmemb, struct __write_data_t *data); // curl progress callback static int __xfer_info(void *data, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow); private: URL _url; Parameters _parameters; Progress _progress; std::unique_ptr<CURLHandle, std::function<void(CURLHandle *)>> _curl_handle_ptr; std::shared_ptr<struct __write_data_t> _response_data_ptr; }; // private namespace priv { template <typename T> void __set_option(Session& session, T&& t) { session.SetOption(HTTP_FWD(t)); } template <typename T, typename... Ts> void __set_option(Session& session, T&& t, Ts&&... ts) { __set_option(session, HTTP_FWD(t)); __set_option(session, HTTP_FWD(ts)...); } } // namespace priv // ---------------------------------------------------------------------------------- // // public api // // ---------------------------------------------------------------------------------- // Get template <typename... Ts> Response Get(Ts&&... ts) { Session session; priv::__set_option(session, HTTP_FWD(ts)...); return session.Get(); } // Get Async template <typename... Ts> std::future<void> GetAsync(std::function<void(Response)> complete, Ts... ts) { return std::async(std::launch::async, [complete](Ts... ts) { auto resp = Get(HTTP_MOVE(ts)...); complete(HTTP_MOVE(resp)); }, HTTP_MOVE(ts)...); } // Post template <typename... Ts> Response Post(Ts&&... ts) { Session session; priv::__set_option(session, HTTP_FWD(ts)...); return session.Post(); } // Post Async template <typename... Ts> std::future<void> PostAsync(std::function<void(Response)> complete, Ts... ts) { return std::async(std::launch::async, [complete](Ts... ts) { auto resp = Post(HTTP_MOVE(ts)...); complete(HTTP_MOVE(resp)); }, HTTP_MOVE(ts)...); } // Head template <typename... Ts> Response Head(Ts&&... ts) { Session session; priv::__set_option(session, HTTP_FWD(ts)...); return session.Post(); } // Head Async template <typename... Ts> std::future<void> HeadAsync(std::function<void(Response)> complete, Ts... ts) { return std::async(std::launch::async, [complete](Ts... ts) { auto resp = Head(HTTP_MOVE(ts)...); complete(HTTP_MOVE(resp)); }, HTTP_MOVE(ts)...); } } // namespace http
21.44898
141
0.585514
[ "vector" ]
44a90693c534f411b6fe5242bc3196567e09d823
5,850
h
C
TRTCSDK/Windows/DuilibDemo/uicontrol/TXLiveAvVideoView.h
aliyunvideo/Queen_SDK_Android
e46e32e16f8a6ecf3746a5c397a6a1f36189e93c
[ "Apache-2.0" ]
2
2021-07-06T03:32:25.000Z
2021-12-17T02:24:16.000Z
TRTCSDK/Windows/DuilibDemo/uicontrol/TXLiveAvVideoView.h
aliyunvideo/Queen_SDK_Android
e46e32e16f8a6ecf3746a5c397a6a1f36189e93c
[ "Apache-2.0" ]
null
null
null
TRTCSDK/Windows/DuilibDemo/uicontrol/TXLiveAvVideoView.h
aliyunvideo/Queen_SDK_Android
e46e32e16f8a6ecf3746a5c397a6a1f36189e93c
[ "Apache-2.0" ]
1
2022-03-31T09:07:26.000Z
2022-03-31T09:07:26.000Z
/** * Module: TXLiveAvVideoView @ liteav * * Author: kmais @ 2018/10/1 * * Function: SDK 视频渲染View,可直接拷贝使用,接口非线程安装,在主线程调用。 * * Modify: 创建 by kmais @ 2018/10/1 * */ #pragma once #include "ITRTCCloud.h" #include "UIlib.h" using namespace DuiLib; #include <vector> class CCriticalSection { public: CCriticalSection() { ::InitializeCriticalSection(&m_Cs); } ~CCriticalSection() { ::DeleteCriticalSection(&m_Cs); } public: void Enter() { ::EnterCriticalSection(&m_Cs); } void Leave() { ::LeaveCriticalSection(&m_Cs); } protected: CRITICAL_SECTION m_Cs; }; class CCSGuard { public: CCSGuard(CCriticalSection &Cs) : m_Cs(Cs) { m_Cs.Enter(); }; ~CCSGuard() { m_Cs.Leave(); }; protected: CCriticalSection &m_Cs; }; class CTXLiveAvVideoViewMgr; class CDNLivePlayerViewMgr; extern CTXLiveAvVideoViewMgr* getShareViewMgrInstance(); extern CDNLivePlayerViewMgr* getCDNLivePlayerViewMgr(); class TXLiveAvVideoView : public CControlUI, public IMessageFilterUI { DECLARE_DUICONTROL(TXLiveAvVideoView) public: enum ViewRenderModeEnum { EVideoRenderModeFill = 0, // 图像铺满屏幕,超出显示视窗的视频部分将被截掉 EVideoRenderModeFit = 1, // 图像长边填满屏幕,短边区域会被填充黑色,图像居中 }; enum ViewDashboardStyleEnum { EViewDashboardNoVisible = 0, // 不显示仪表盘 EViewDashboardShowDashboard = 1, // 只显示仪表盘 EViewDashboardRenderAll = 2, // 显示仪表盘和事件 }; public: TXLiveAvVideoView(); ~TXLiveAvVideoView(); public: /** * \brief:设置View绑定参数 * \param:userId - 需要渲染画面的userid,如果是本地画面,则传空字符串。 * \param:type - 需要渲染的视频流类型。 * \param:bLocal - 渲染本地画面,SDK返回的userID为"" */ bool SetRenderInfo(const std::string& userId, TRTCVideoStreamType type, bool bLocal = false); /** * \brief:移除View绑定参数 * \param:userId - 需要渲染画面的userid */ void RemoveRenderInfo(); /** * \brief:判断view是否被占用 */ bool IsViewOccupy(); /** * \brief:设置View的渲染模式 * \param:mode - 参考<ViewRenderModeEnum>定义 */ void SetRenderMode(ViewRenderModeEnum mode); /** * \brief:暂停渲染,显示默认图片 * \param:bPause */ void SetPause(bool bPause); /** * \brief:清除所有映射信息 * \param:bPause */ static void RemoveAllRegEngine(); public: /** * \brief:view层 显示仪表盘和事件信息。 */ static void appendDashboardLogText(const std::string& userId, TRTCVideoStreamType steamType, const std::wstring& logText); static void appendEventLogText(const std::string& userId, TRTCVideoStreamType steamType, const std::wstring& logText, bool bAllFilter = false); static void clearUserEventLogText(const std::string& userId); static void clearAllLogText(); static void switchViewDashboardStyle(ViewDashboardStyleEnum style); static std::multimap<std::pair<std::string, TRTCVideoStreamType>, std::vector<std::wstring>> g_mapEventLogText; static std::multimap<std::pair<std::string, TRTCVideoStreamType>, std::wstring> g_mapDashboardLogText; static ViewDashboardStyleEnum g_nStyleDashboard; //0 关闭, 1打开, 2暂定 //* 支持rbga数据处理,如需自定义数据,需重载此函数。 virtual bool AppendVideoFrame(unsigned char * data, uint32_t length, uint32_t width, uint32_t height, TRTCVideoPixelFormat videoFormat, TRTCVideoRotation rotation); public: void GetVideoResolution(int& width, int& height); UINT GetPaintMsgID(); std::string getUserId(); HWND getWnd() { return m_hWnd; } protected: //IMessageFilterUI virtual LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, bool& bHandled); //CControlUI virtual bool DoPaint(HDC hDC, const RECT& rcPaint, CControlUI* pStopControl = NULL); virtual void DoEvent(TEventUI& event); protected: struct AVFrameBufferInfo { unsigned char* frameBuf = nullptr; int width = 0; int height = 0; bool newFrame = false; TRTCVideoRotation rotation = TRTCVideoRotation0; }; private: bool DoPaintText(HDC hDC, const RECT& rcText, const RECT& rcLog, bool bDrawAVFrame); void calFullScreenPos(const RECT& rcView, int & x, int & y, int & dstWidth, int & dstHeight); void calAdaptPos(const RECT& rcView, int & dstX, int & dstY, int & dstWidth, int & dstHeight); std::wstring UTF82Wide(const std::string& strAnsi); int GetNameFontSize(const RECT& rcImage); int GetPauseNameFontSize(const RECT& rcImage); int GetLogFontSize(const RECT& rcImage); int getRotationAngle(TRTCVideoRotation rotatio); bool resetBuffer(int srcWidth, int srcHeight, int& dstWidth, int& dstHeight, unsigned char ** dstBuffer); void releaseBuffer(AVFrameBufferInfo &info); void renderFitMode(HDC hDC, unsigned char* buffer, int width, int height, RECT& rcImage); void renderFillMode(HDC hDC, unsigned char* buffer, int width, int height, RECT& rcImage); private: friend CTXLiveAvVideoViewMgr; ViewRenderModeEnum m_renderMode = EVideoRenderModeFit; //1 填充 2 适应 AVFrameBufferInfo m_argbSrcFrame; AVFrameBufferInfo m_argbRotationFrame; AVFrameBufferInfo m_argbRenderFrame; BITMAPINFO m_bmi; bool m_bPause = false; std::string m_userId; TRTCVideoStreamType m_type; private: UINT m_nDefineMsg = 0; //自定义win32消息,用来通知主线程刷新 HWND m_hWnd = nullptr; bool m_bRegMsgFilter = false; bool m_bOccupy = false; bool m_bLocalView = false; private: //统计 bool bFirstFrame = false; //UINT m_nTimerID = 0; int nCntSDKFps = 0; int nCntPaintFps = 0; int nCntPaint = 0; DWORD dwLastCntTicket = 0; DWORD dwLastAppendFrameTicket = 0; uint64_t m_i64TotalFrame; uint64_t m_i64TotalTicketTime; CCriticalSection m_viewCs; };
32.320442
169
0.674701
[ "vector" ]
44abfcf374d0d9ca8b6461c80149c134906b1314
2,416
h
C
include/rdc_lib/RdcWatchTable.h
RadeonOpenCompute/rdc
bb11a0abf5bea0ca8ad3d17bd687379c45149ed9
[ "MIT" ]
2
2020-09-10T02:04:00.000Z
2020-12-03T10:55:38.000Z
include/rdc_lib/RdcWatchTable.h
RadeonOpenCompute/rdc
bb11a0abf5bea0ca8ad3d17bd687379c45149ed9
[ "MIT" ]
2
2022-03-29T00:32:43.000Z
2022-03-31T18:09:36.000Z
include/rdc_lib/RdcWatchTable.h
RadeonOpenCompute/rdc
bb11a0abf5bea0ca8ad3d17bd687379c45149ed9
[ "MIT" ]
2
2020-09-15T08:05:43.000Z
2021-09-02T03:06:41.000Z
/* Copyright (c) 2020 - present Advanced Micro Devices, Inc. All rights reserved. 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 INCLUDE_RDC_LIB_RDCWATCHTABLE_H_ #define INCLUDE_RDC_LIB_RDCWATCHTABLE_H_ #include <memory> #include <vector> #include "rdc_lib/rdc_common.h" #include "rdc/rdc.h" namespace amd { namespace rdc { class RdcWatchTable { public: virtual rdc_status_t rdc_field_update_all() = 0; virtual rdc_status_t rdc_field_listen_notif(uint32_t timeout_ms) = 0; virtual rdc_status_t rdc_job_start_stats(rdc_gpu_group_t group_id, const char job_id[64], uint64_t update_freq, const rdc_gpu_gauges_t& gpu_gauge) = 0; virtual rdc_status_t rdc_job_stop_stats(const char job_id[64], const rdc_gpu_gauges_t& gpu_gauge) = 0; virtual rdc_status_t rdc_job_remove(const char job_id[64]) = 0; virtual rdc_status_t rdc_job_remove_all() = 0; virtual rdc_status_t rdc_field_watch(rdc_gpu_group_t group_id, rdc_field_grp_t field_group_id, uint64_t update_freq, double max_keep_age, uint32_t max_keep_samples) = 0; virtual rdc_status_t rdc_field_unwatch(rdc_gpu_group_t group_id, rdc_field_grp_t field_group_id) = 0; virtual ~RdcWatchTable() {} }; typedef std::shared_ptr<RdcWatchTable> RdcWatchTablePtr; } // namespace rdc } // namespace amd #endif // INCLUDE_RDC_LIB_RDCWATCHTABLE_H_
38.967742
78
0.763659
[ "vector" ]
44c4c5fe4a59c1822f0e5199046721dfff61188d
507
h
C
include/CGeomUtil3D.h
colinw7/CGeometry3D
15c009b57bfcdcc5ca13ef2acfe94b6831a4c865
[ "MIT" ]
1
2021-12-23T02:21:22.000Z
2021-12-23T02:21:22.000Z
include/CGeomUtil3D.h
colinw7/CGeometry3D
15c009b57bfcdcc5ca13ef2acfe94b6831a4c865
[ "MIT" ]
null
null
null
include/CGeomUtil3D.h
colinw7/CGeometry3D
15c009b57bfcdcc5ca13ef2acfe94b6831a4c865
[ "MIT" ]
null
null
null
#ifndef CGEOM_UTIL_3D_H #define CGEOM_UTIL_3D_H #include <CPoint3D.h> #include <CVector3D.h> #include <CTriangle3D.h> #include <CGeomVertex3D.h> #include <vector> #include <list> class CGeomUtil3D { public: static CPoint3D getMidPoint(const std::vector<CGeomVertex3D *> &vertices); static CVector3D getNormal (const std::vector<CGeomVertex3D *> &vertices); static void triangulate(const std::list<CPoint3D> &points, std::vector<CTriangle3D> &triangle_list); }; #endif
24.142857
77
0.719921
[ "vector" ]
44c656435f2a10a7358afdf530c7c66186766adf
17,854
h
C
include/json_util/property.h
bridgerrholt/cl_glitcher
48fc2a81dc7724698b462efe18e60d8feb1d3b36
[ "MIT" ]
null
null
null
include/json_util/property.h
bridgerrholt/cl_glitcher
48fc2a81dc7724698b462efe18e60d8feb1d3b36
[ "MIT" ]
null
null
null
include/json_util/property.h
bridgerrholt/cl_glitcher
48fc2a81dc7724698b462efe18e60d8feb1d3b36
[ "MIT" ]
null
null
null
// // Created by bridg on 1/18/2021. // #ifndef CL_GLITCHER_INCLUDE_JSON_UTIL_PROPERTY_H #define CL_GLITCHER_INCLUDE_JSON_UTIL_PROPERTY_H #include <tuple> #include <rapidjson/document.h> #include <vector> #include "json_option.h" namespace json_util { /// Used for storing JSON metadata /// \tparam Owner The owner of the variable in question /// \tparam T The type of variable in question template <class Owner, class T, JsonOption Options = JsonOption::None> class JsonProperty { public: using Type = T; /// Pointer to the variable T Owner::*member; /// Name of the variable for JSON serialization and deserialization char const * name; constexpr JsonProperty(T Owner::*member, char const * name) : member {member}, name {name} {} }; /// Used for storing JSON metadata /// \tparam Owner The owner of the variable in question /// \tparam T The type of variable in question template < class Owner, class T, class Func, JsonOption Options = JsonOption::None> class JsonPropertyCustom { public: using Type = T; /// Pointer to the variable T Owner::*member; /// Name of the variable for JSON serialization and deserialization char const * name; Func f; constexpr JsonPropertyCustom(T Owner::*member, char const * name, Func f) : member {member}, name {name}, f {f} {} void execute(Owner & obj, rapidjson::Value const & value) const { f(obj, obj.*(member), value); } /*void execute(Owner & obj, rapidjson::Value const & value) { execute(f, obj, value); } private: template <class F> void execute(F const & func, Owner & obj, rapidjson::Value const & value) { func(obj, obj.*(member), value); } template <class F> void execute(F Owner::* const & func, Owner & obj, rapidjson::Value const & value) { obj.*func(obj.*member, value); }*/ }; /// Alternate syntax constructor for JsonProperty. /// Only for non-optional properties. See makeOptionalProp below. template <class Owner, class T> constexpr JsonProperty<Owner, T, JsonOption::None> makeProp(T Owner::*member, char const * name) { return {member, name}; } /// Alternate syntax constructor for JsonProperty. /// Only for optional properties. See makeProp above. template <class Owner, class T> constexpr JsonProperty<Owner, T, JsonOption::Optional> makeOptionalProp(T Owner::*member, char const * name) { return {member, name}; } /// Alternate syntax constructor for JsonProperty. /// Only for non-optional properties. See makeOptionalProp below. template <class Owner, class T, class Func> constexpr JsonPropertyCustom<Owner, T, Func, JsonOption::None> makeCustomProp(T Owner::*member, char const * name, Func f) { return {member, name, f}; } /// Alternate syntax constructor for JsonProperty. /// Only for optional properties. See makeProp above. template <class Owner, class T, class Func> constexpr JsonPropertyCustom<Owner, T, Func, JsonOption::Optional> makeCustomOptionalProp(T Owner::*member, char const * name, Func f) { return {member, name, f}; } /*/// Alternate syntax constructor for JsonProperty. /// Only for non-optional properties. See makeOptionalProp below. template <class Owner, class T, class Func Owner::*> constexpr JsonPropertyCustom<Owner, T, Func Owner::*, JsonOption::None> makeCustomProp(T Owner::*member, char const * name, Func Owner::*f) { return {member, name, f}; } /// Alternate syntax constructor for JsonProperty. /// Only for optional properties. See makeProp above. template <class Owner, class T, class Func> constexpr JsonPropertyCustom<Owner, T, Func Owner::*, JsonOption::Optional> makeCustomOptionalProp(T Owner::*member, char const * name, Func Owner::*f) { return {member, name, f}; }*/ /*#define JSON_UTIL_DECLARE_PROP_LIST(...) \ static constexpr auto jsonProps = std::make_tuple( \ __VA_ARGS__ \ );*/ #define JSON_UTIL_DECLARE_PROP_LIST(...) \ static constexpr auto jsonProps() \ { \ return std::make_tuple(__VA_ARGS__); \ } /// Convenient macro for when the member variable has the same name as the JSON /// property. #define JSON_UTIL_MAKE_PROP(owner, name) \ (json_util::makeProp(&owner::name, #name)) #define JSON_UTIL_MAKE_PROP2(ownerAndName, name) \ (json_util::makeProp(ownerAndName, #name)) #define JSON_UTIL_MAKE_OPTIONAL_PROP(owner, name) \ (json_util::makeOptionalProp(&owner::name, #name)) #define JSON_UTIL_MAKE_CUSTOM_PROP(owner, name, func) \ (json_util::makeCustomProp(&owner::name, #name, func)) #define JSON_UTIL_MAKE_CUSTOM_OPTIONAL_PROP(owner, name, func) \ (json_util::makeCustomOptionalProp(&owner::name, #name, func)) // --- verifyPropList --- /// Used for ensuring an arg list contains only JsonProperty objects. template <class Owner, class T, JsonOption Options> constexpr void verifyPropList(JsonProperty<Owner, T, Options> const & first) { } template <class Owner, class T, JsonOption Options, class ... ArgPack> constexpr void verifyPropList( JsonProperty<Owner, T, Options> const & first, ArgPack && ... args) { verifyPropList(std::forward<ArgPack>(args)...); } // --- propList --- /// Convenient function for creating correct JsonProperty tuples. /// All arguments must be JsonProperty objects. /// @return A tuple of the JsonProperty objects template <class Owner, class T, JsonOption Options, class ... ArgPack> constexpr std::tuple<JsonProperty<Owner, T, Options>, ArgPack...> propList(JsonProperty<Owner, T, Options> && first, ArgPack && ... args) { //verifyPropList(first, std::forward<ArgPack>(args)...); return {first, std::forward<ArgPack>(args)...}; } /// Used for template deduction template <class GenericJson, class Owner> void deserialize2( GenericJson const & json, Owner & obj); #define __JSON_UTIL_DESERIALIZE_GENERIC(json, obj, prop, getFunc)\ (obj).*((prop).member) = (json)[(prop).name].getFunc(); #define __JSON_UTIL_DESERIALIZE_GENERIC_OPTIONAL(json, obj, prop, getFunc)\ {\ auto it = (json).FindMember((prop).name);\ if (it != (json).MemberEnd())\ (obj).*((prop).member) = it->value.getFunc();\ } #define __JSON_UTIL_PROP_MEMBER(obj, prop)\ ((obj).*((prop).member)) /// Deserialization template <class GenericJson, class Owner, class T, JsonOption options> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, T, options> const & prop); /// Deserialize using custom func template <class GenericJson, class Owner, class T, class Func> void deserialize( GenericJson const & json, Owner & obj, JsonPropertyCustom<Owner, T, Func> const & prop) { prop.execute(obj, json[prop.name]); //prop.f(obj, obj.*(prop.member), json[prop.name]); } template <class GenericJson, class Owner, class T, class Func> void deserialize( GenericJson const & json, Owner & obj, JsonPropertyCustom<Owner, T, Func, JsonOption::Optional> const & prop) { auto it = json.FindMember(prop.name); if (it != json.MemberEnd()) { prop.execute(obj, it->value); //prop.f(obj, obj.*(prop.member), it->value); } } /// Deserialize into JSON object (recurse) template <class GenericJson, class Owner, class T> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, T> const & prop) { deserialize2(json[prop.name].GetObject(), obj.*(prop.member)); } template <class GenericJson, class Owner, class T> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, T, JsonOption::Optional> const & prop) { auto it = json.FindMember(prop.name); if (it != json.MemberEnd()) { deserialize2(it->value.GetObject(), obj.*(prop.member)); } } // bool template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, bool> const & prop) { //obj.*(prop.member) = json[prop.name].GetBool(); __JSON_UTIL_DESERIALIZE_GENERIC(json, obj, prop, GetBool); } template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, bool, JsonOption::Optional> const & prop) { //obj.*(prop.member) = json[prop.name].GetBool(); __JSON_UTIL_DESERIALIZE_GENERIC_OPTIONAL(json, obj, prop, GetBool); } template <class JsonBool> void deserialize( JsonBool const & jsonBool, bool & outBool) { outBool = jsonBool.GetBool(); } // int template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, int> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC(json, obj, prop, GetInt); } template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, int, JsonOption::Optional> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC_OPTIONAL(json, obj, prop, GetInt); } template <class JsonInt> void deserialize( JsonInt const & jsonInt, int & outInt) { outInt = jsonInt.GetInt(); } // unsigned template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, unsigned> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC(json, obj, prop, GetUint); } template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, unsigned, JsonOption::Optional> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC_OPTIONAL(json, obj, prop, GetUint); } template <class JsonUInt> void deserialize( JsonUInt const & jsonUInt, unsigned & outUInt) { outUInt = jsonUInt.GetUint(); } // int64_t template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, int64_t> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC(json, obj, prop, GetInt64); } template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, int64_t, JsonOption::Optional> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC_OPTIONAL(json, obj, prop, GetInt64); } template <class JsonInt64> void deserialize( JsonInt64 const & jsonInt64, int64_t & outInt64) { outInt64 = jsonInt64.GetInt64(); } // uint64_t template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, uint64_t> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC(json, obj, prop, GetUint64); } template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, uint64_t, JsonOption::Optional> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC_OPTIONAL(json, obj, prop, GetUint64); } template <class JsonUInt64> void deserialize( JsonUInt64 const & jsonUInt64, uint64_t & outUInt64) { outUInt64 = jsonUInt64.GetUint64(); } // float template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, float> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC(json, obj, prop, GetFloat); } template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, float, JsonOption::Optional> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC_OPTIONAL(json, obj, prop, GetFloat); } template <class JsonFloat> void deserialize( JsonFloat const & jsonFloat, float & outFloat) { outFloat = jsonFloat.GetFloat(); } // double template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, double> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC(json, obj, prop, GetDouble); } template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, double, JsonOption::Optional> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC_OPTIONAL(json, obj, prop, GetDouble); } template <class JsonDouble> void deserialize( JsonDouble const & jsonDouble, double & outDouble) { outDouble = jsonDouble.GetDouble(); } // std::string template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, std::string> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC(json, obj, prop, GetString); } template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, std::string, JsonOption::Optional> const & prop) { __JSON_UTIL_DESERIALIZE_GENERIC_OPTIONAL(json, obj, prop, GetString); } template <class JsonString> void deserialize( JsonString const & jsonString, std::string & outString) { outString = jsonString.GetString(); } // object declaration template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj); // array template <class GenericJson, class Owner, class T> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, std::vector<T>> const & prop) { auto const & arr = json[prop.name].GetArray(); std::vector<T> & vec = obj.*(prop.member); vec.reserve(arr.Size()); for (auto const & el : arr) { T & t = vec.emplace_back(); deserialize(el, t); } } template <class GenericJson, class Owner, class T> void deserialize( GenericJson const & json, Owner & obj, JsonProperty<Owner, std::vector<T>, JsonOption::Optional> const & prop) { auto it = json.FindMember(prop.name); if (it != json.MemberEnd()) { auto const & arr = it->value.GetArray(); std::vector<T> & vec = obj.*(prop.member); vec.reserve(arr.Size()); for (auto const & el : arr) { T & t = vec.emplace_back(); deserialize(el, t); } } } template <class JsonArray, class T> void deserialize( JsonArray const & jsonArray, std::vector<T> & outVector) { auto const & arr = jsonArray.GetArray(); outVector.reserve(arr.Size()); for (auto const & el : arr) { T & t = outVector.emplace_back(); deserialize(el, t); } } template <class Owner, class GenericJson> Owner deserialize( GenericJson const & json) { Owner o; deserialize(json, o); return o; } template <class GenericJson, class Owner> void deserialize( GenericJson const & json, Owner & obj) { deserialize<0>(json, obj, obj.jsonProps()); } template <class GenericJson, class Owner> void deserialize2( GenericJson const & json, Owner & obj) { deserialize<0>(json, obj, obj.jsonProps()); } /// Deserialize all elements of the props tuple starting from the given index. template <std::size_t index, class GenericJson, class Owner, class Tuple> void deserialize( GenericJson const & json, Owner & obj, Tuple const & props) { if constexpr (index < std::tuple_size<Tuple>::value) { deserialize(json, obj, std::get<index>(props)); deserialize<index + 1>(json, obj, props); } } // rapidjson-specific: /* // object template <class Encoding, class Allocator, class Owner, class T> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj, JsonProperty<Owner, T> const & prop) { deserialize2(value[prop.name].GetObject(), obj.*(prop.member)); } // bool template <class Encoding, class Allocator, class Owner> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj, JsonProperty<Owner, bool> const & prop) { obj.*(prop.member) = value[prop.name].GetBool(); } // int template <class Encoding, class Allocator, class Owner> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj, JsonProperty<Owner, int> const & prop) { obj.*(prop.member) = value[prop.name].GetInt(); } // unsigned template <class Encoding, class Allocator, class Owner> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj, JsonProperty<Owner, unsigned> const & prop) { obj.*(prop.member) = value[prop.name].GetUint(); } // int64_t template <class Encoding, class Allocator, class Owner> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj, JsonProperty<Owner, int64_t> const & prop) { obj.*(prop.member) = value[prop.name].GetInt64(); } // uint64_t template <class Encoding, class Allocator, class Owner> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj, JsonProperty<Owner, uint64_t> const & prop) { obj.*(prop.member) = value[prop.name].GetUint64(); } // float template <class Encoding, class Allocator, class Owner> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj, JsonProperty<Owner, float> const & prop) { obj.*(prop.member) = value[prop.name].GetUint64(); } // double template <class Encoding, class Allocator, class Owner> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj, JsonProperty<Owner, double> const & prop) { obj.*(prop.member) = value[prop.name].GetUint64(); } // std::string template <class Encoding, class Allocator, class Owner> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj, JsonProperty<Owner, std::string> const & prop) { obj.*(prop.member) = value[prop.name].GetString(); } template <class Encoding, class Allocator, class Owner> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj) { deserialize<0>(value, obj, obj.jsonProps); } template <std::size_t index, class Encoding, class Allocator, class Owner, class Tuple> void deserialize( rapidjson::GenericValue<Encoding, Allocator> const & value, Owner & obj, Tuple const & props) { if constexpr (index < std::tuple_size<Tuple>::value) { deserialize(value, obj, std::get<index>(props)); deserialize<index + 1>(value, obj, props); } }*/ } #endif //CL_GLITCHER_INCLUDE_JSON_UTIL_PROPERTY_H
23.585205
87
0.708413
[ "object", "vector" ]
44c70dec22bc2252ca47315879658c7f0f0a02f5
20,024
h
C
snapgear_linux/user/gdbserver/gdb/value.h
impedimentToProgress/UCI-BlueChip
53e5d48b79079eaf60d42f7cb65bb795743d19fc
[ "MIT" ]
null
null
null
snapgear_linux/user/gdbserver/gdb/value.h
impedimentToProgress/UCI-BlueChip
53e5d48b79079eaf60d42f7cb65bb795743d19fc
[ "MIT" ]
null
null
null
snapgear_linux/user/gdbserver/gdb/value.h
impedimentToProgress/UCI-BlueChip
53e5d48b79079eaf60d42f7cb65bb795743d19fc
[ "MIT" ]
3
2016-06-13T13:20:56.000Z
2019-12-05T02:31:23.000Z
/* Definitions for values of C expressions, for GDB. Copyright 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996 Free Software Foundation, Inc. This file is part of GDB. 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. */ #if !defined (VALUE_H) #define VALUE_H 1 /* * The structure which defines the type of a value. It should never * be possible for a program lval value to survive over a call to the inferior * (ie to be put into the history list or an internal variable). */ enum lval_type { /* Not an lval. */ not_lval, /* In memory. Could be a saved register. */ lval_memory, /* In a register. */ lval_register, /* In a gdb internal variable. */ lval_internalvar, /* Part of a gdb internal variable (structure field). */ lval_internalvar_component, /* In a register series in a frame not the current one, which may have been partially saved or saved in different places (otherwise would be lval_register or lval_memory). */ lval_reg_frame_relative }; struct value { /* Type of value; either not an lval, or one of the various different possible kinds of lval. */ enum lval_type lval; /* Is it modifiable? Only relevant if lval != not_lval. */ int modifiable; /* Location of value (if lval). */ union { /* Address in inferior or byte of registers structure. */ CORE_ADDR address; /* Pointer to internal variable. */ struct internalvar *internalvar; /* Number of register. Only used with lval_reg_frame_relative. */ int regnum; } location; /* Describes offset of a value within lval of a structure in bytes. This is used in retrieving contents from target memory. [Note also the member embedded_offset below.] */ int offset; /* Only used for bitfields; number of bits contained in them. */ int bitsize; /* Only used for bitfields; position of start of field. For BITS_BIG_ENDIAN=0 targets, it is the position of the LSB. For BITS_BIG_ENDIAN=1 targets, it is the position of the MSB. */ int bitpos; /* Frame value is relative to. In practice, this address is only used if the value is stored in several registers in other than the current frame, and these registers have not all been saved at the same place in memory. This will be described in the lval enum above as "lval_reg_frame_relative". */ CORE_ADDR frame_addr; /* Type of the value. */ struct type *type; /* Type of the enclosing object if this is an embedded subobject. The member embedded_offset gives the real position of the subobject if type is not the same as enclosing_type. If the type field is a pointer type, then enclosing_type is a pointer type pointing to the real (enclosing) type of the target object. */ struct type *enclosing_type; /* Values are stored in a chain, so that they can be deleted easily over calls to the inferior. Values assigned to internal variables or put into the value history are taken off this list. */ struct value *next; /* ??? When is this used? */ union { CORE_ADDR memaddr; char *myaddr; } substring_addr; /* Register number if the value is from a register. Is not kept if you take a field of a structure that is stored in a register. Shouldn't it be? */ short regno; /* If zero, contents of this value are in the contents field. If nonzero, contents are in inferior memory at address in the location.address field plus the offset field (and the lval field should be lval_memory). */ char lazy; /* If nonzero, this is the value of a variable which does not actually exist in the program. */ char optimized_out; /* If this value represents an object that is embedded inside a larger object (e.g., a base subobject in C++), this gives the offset (in bytes) from the start of the contents buffer where the embedded object begins. This is required because some C++ runtime implementations lay out objects (especially virtual bases with possibly negative offsets to ancestors). Note: This may be positive or negative! Also note that this offset is not used when retrieving contents from target memory; the entire enclosing object has to be retrieved always, and the offset for that is given by the member offset above. */ int embedded_offset; /* If this value represents a pointer to an object that is embedded in another object, this gives the embedded_offset of the object that is pointed to. */ int pointed_to_offset; /* The BFD section associated with this value. */ asection *bfd_section; /* Actual contents of the value. For use of this value; setting it uses the stuff above. Not valid if lazy is nonzero. Target byte-order. We force it to be aligned properly for any possible value. Note that a value therefore extends beyond what is declared here. */ union { long contents[1]; double force_double_align; LONGEST force_longlong_align; char *literal_data; } aligner; /* Do not add any new members here -- contents above will trash them */ }; typedef struct value *value_ptr; #define VALUE_TYPE(val) (val)->type #define VALUE_ENCLOSING_TYPE(val) (val)->enclosing_type #define VALUE_LAZY(val) (val)->lazy /* VALUE_CONTENTS and VALUE_CONTENTS_RAW both return the address of the gdb buffer used to hold a copy of the contents of the lval. VALUE_CONTENTS is used when the contents of the buffer are needed -- it uses value_fetch_lazy() to load the buffer from the process being debugged if it hasn't already been loaded. VALUE_CONTENTS_RAW is used when data is being stored into the buffer, or when it is certain that the contents of the buffer are valid. Note: The contents pointer is adjusted by the offset required to get to the real subobject, if the value happens to represent something embedded in a larger run-time object. */ #define VALUE_CONTENTS_RAW(val) ((char *) (val)->aligner.contents + (val)->embedded_offset) #define VALUE_CONTENTS(val) ((void)(VALUE_LAZY(val) && value_fetch_lazy(val)),\ VALUE_CONTENTS_RAW(val)) /* The ALL variants of the above two macros do not adjust the returned pointer by the embedded_offset value. */ #define VALUE_CONTENTS_ALL_RAW(val) ((char *) (val)->aligner.contents) #define VALUE_CONTENTS_ALL(val) ((void) (VALUE_LAZY(val) && value_fetch_lazy(val)),\ VALUE_CONTENTS_ALL_RAW(val)) extern int value_fetch_lazy PARAMS ((value_ptr val)); #define VALUE_LVAL(val) (val)->lval #define VALUE_ADDRESS(val) (val)->location.address #define VALUE_INTERNALVAR(val) (val)->location.internalvar #define VALUE_FRAME_REGNUM(val) ((val)->location.regnum) #define VALUE_FRAME(val) ((val)->frame_addr) #define VALUE_OFFSET(val) (val)->offset #define VALUE_BITSIZE(val) (val)->bitsize #define VALUE_BITPOS(val) (val)->bitpos #define VALUE_NEXT(val) (val)->next #define VALUE_REGNO(val) (val)->regno #define VALUE_OPTIMIZED_OUT(val) ((val)->optimized_out) #define VALUE_EMBEDDED_OFFSET(val) ((val)->embedded_offset) #define VALUE_POINTED_TO_OFFSET(val) ((val)->pointed_to_offset) #define VALUE_BFD_SECTION(val) ((val)->bfd_section) /* Convert a REF to the object referenced. */ #define COERCE_REF(arg) \ do { struct type *value_type_arg_tmp = check_typedef (VALUE_TYPE (arg));\ if (TYPE_CODE (value_type_arg_tmp) == TYPE_CODE_REF) \ arg = value_at_lazy (TYPE_TARGET_TYPE (value_type_arg_tmp), \ unpack_long (VALUE_TYPE (arg), \ VALUE_CONTENTS (arg)), \ VALUE_BFD_SECTION (arg)); \ } while (0) /* If ARG is an array, convert it to a pointer. If ARG is an enum, convert it to an integer. If ARG is a function, convert it to a function pointer. References are dereferenced. */ #define COERCE_ARRAY(arg) \ do { COERCE_REF(arg); \ if (current_language->c_style_arrays \ && TYPE_CODE (VALUE_TYPE (arg)) == TYPE_CODE_ARRAY) \ arg = value_coerce_array (arg); \ if (TYPE_CODE (VALUE_TYPE (arg)) == TYPE_CODE_FUNC) \ arg = value_coerce_function (arg); \ } while (0) #define COERCE_NUMBER(arg) \ do { COERCE_ARRAY(arg); COERCE_ENUM(arg); } while (0) #define COERCE_VARYING_ARRAY(arg, real_arg_type) \ { if (chill_varying_type (real_arg_type)) \ arg = varying_to_slice (arg), real_arg_type = VALUE_TYPE (arg); } /* If ARG is an enum, convert it to an integer. */ #define COERCE_ENUM(arg) { \ if (TYPE_CODE (check_typedef (VALUE_TYPE (arg))) == TYPE_CODE_ENUM) \ arg = value_cast (builtin_type_unsigned_int, arg); \ } /* Internal variables (variables for convenience of use of debugger) are recorded as a chain of these structures. */ struct internalvar { struct internalvar *next; char *name; value_ptr value; }; /* Pointer to member function. Depends on compiler implementation. */ #define METHOD_PTR_IS_VIRTUAL(ADDR) ((ADDR) & 0x80000000) #define METHOD_PTR_FROM_VOFFSET(OFFSET) (0x80000000 + (OFFSET)) #define METHOD_PTR_TO_VOFFSET(ADDR) (~0x80000000 & (ADDR)) #include "symtab.h" #include "gdbtypes.h" #include "expression.h" #ifdef __STDC__ struct frame_info; struct fn_field; #endif extern void print_address_demangle PARAMS ((CORE_ADDR, GDB_FILE *, int)); extern LONGEST value_as_long PARAMS ((value_ptr val)); extern DOUBLEST value_as_double PARAMS ((value_ptr val)); extern CORE_ADDR value_as_pointer PARAMS ((value_ptr val)); extern LONGEST unpack_long PARAMS ((struct type *type, char *valaddr)); extern DOUBLEST unpack_double PARAMS ((struct type *type, char *valaddr, int *invp)); extern CORE_ADDR unpack_pointer PARAMS ((struct type *type, char *valaddr)); extern LONGEST unpack_field_as_long PARAMS ((struct type *type, char *valaddr, int fieldno)); extern value_ptr value_from_longest PARAMS ((struct type *type, LONGEST num)); extern value_ptr value_from_double PARAMS ((struct type *type, DOUBLEST num)); extern value_ptr value_at PARAMS ((struct type *type, CORE_ADDR addr, asection *sect)); extern value_ptr value_at_lazy PARAMS ((struct type *type, CORE_ADDR addr, asection *sect)); extern value_ptr value_from_register PARAMS ((struct type *type, int regnum, struct frame_info * frame)); extern value_ptr value_of_variable PARAMS ((struct symbol *var, struct block *b)); extern value_ptr value_of_register PARAMS ((int regnum)); extern int symbol_read_needs_frame PARAMS ((struct symbol *)); extern value_ptr read_var_value PARAMS ((struct symbol *var, struct frame_info *frame)); extern value_ptr locate_var_value PARAMS ((struct symbol *var, struct frame_info *frame)); extern value_ptr allocate_value PARAMS ((struct type *type)); extern value_ptr allocate_repeat_value PARAMS ((struct type *type, int count)); extern value_ptr value_mark PARAMS ((void)); extern void value_free_to_mark PARAMS ((value_ptr mark)); extern value_ptr value_string PARAMS ((char *ptr, int len)); extern value_ptr value_bitstring PARAMS ((char *ptr, int len)); extern value_ptr value_array PARAMS ((int lowbound, int highbound, value_ptr *elemvec)); extern value_ptr value_concat PARAMS ((value_ptr arg1, value_ptr arg2)); extern value_ptr value_binop PARAMS ((value_ptr arg1, value_ptr arg2, enum exp_opcode op)); extern value_ptr value_add PARAMS ((value_ptr arg1, value_ptr arg2)); extern value_ptr value_sub PARAMS ((value_ptr arg1, value_ptr arg2)); extern value_ptr value_coerce_array PARAMS ((value_ptr arg1)); extern value_ptr value_coerce_function PARAMS ((value_ptr arg1)); extern value_ptr value_ind PARAMS ((value_ptr arg1)); extern value_ptr value_addr PARAMS ((value_ptr arg1)); extern value_ptr value_assign PARAMS ((value_ptr toval, value_ptr fromval)); extern value_ptr value_neg PARAMS ((value_ptr arg1)); extern value_ptr value_complement PARAMS ((value_ptr arg1)); extern value_ptr value_struct_elt PARAMS ((value_ptr *argp, value_ptr *args, char *name, int *static_memfuncp, char *err)); extern value_ptr value_struct_elt_for_reference PARAMS ((struct type *domain, int offset, struct type *curtype, char *name, struct type *intype)); extern value_ptr value_static_field PARAMS ((struct type *type, int fieldno)); extern struct fn_field * value_find_oload_method_list PARAMS ((value_ptr *, char *, int, int *, int *, struct type **, int *)); extern value_ptr value_field PARAMS ((value_ptr arg1, int fieldno)); extern value_ptr value_primitive_field PARAMS ((value_ptr arg1, int offset, int fieldno, struct type *arg_type)); extern struct type * value_rtti_type PARAMS ((value_ptr, int *, int *, int *)); extern struct type * value_rtti_target_type PARAMS ((value_ptr, int *, int *, int *)); extern value_ptr value_full_object PARAMS ((value_ptr, struct type *, int, int, int)); extern value_ptr value_cast PARAMS ((struct type *type, value_ptr arg2)); extern value_ptr value_zero PARAMS ((struct type *type, enum lval_type lv)); extern value_ptr value_repeat PARAMS ((value_ptr arg1, int count)); extern value_ptr value_subscript PARAMS ((value_ptr array, value_ptr idx)); extern value_ptr value_from_vtable_info PARAMS ((value_ptr arg, struct type *type)); extern value_ptr value_being_returned PARAMS ((struct type *valtype, char retbuf[REGISTER_BYTES], int struct_return)); extern value_ptr value_in PARAMS ((value_ptr element, value_ptr set)); extern int value_bit_index PARAMS ((struct type *type, char *addr, int index)); extern int using_struct_return PARAMS ((value_ptr function, CORE_ADDR funcaddr, struct type *value_type, int gcc_p)); extern void set_return_value PARAMS ((value_ptr val)); extern value_ptr evaluate_expression PARAMS ((struct expression *exp)); extern value_ptr evaluate_type PARAMS ((struct expression *exp)); extern value_ptr evaluate_subexp_with_coercion PARAMS ((struct expression *, int *, enum noside)); extern value_ptr parse_and_eval PARAMS ((char *exp)); extern value_ptr parse_to_comma_and_eval PARAMS ((char **expp)); extern struct type *parse_and_eval_type PARAMS ((char *p, int length)); extern CORE_ADDR parse_and_eval_address PARAMS ((char *exp)); extern CORE_ADDR parse_and_eval_address_1 PARAMS ((char **expptr)); extern value_ptr access_value_history PARAMS ((int num)); extern value_ptr value_of_internalvar PARAMS ((struct internalvar *var)); extern void set_internalvar PARAMS ((struct internalvar *var, value_ptr val)); extern void set_internalvar_component PARAMS ((struct internalvar *var, int offset, int bitpos, int bitsize, value_ptr newvalue)); extern struct internalvar *lookup_internalvar PARAMS ((char *name)); extern int value_equal PARAMS ((value_ptr arg1, value_ptr arg2)); extern int value_less PARAMS ((value_ptr arg1, value_ptr arg2)); extern int value_logical_not PARAMS ((value_ptr arg1)); /* C++ */ extern value_ptr value_of_this PARAMS ((int complain)); extern value_ptr value_x_binop PARAMS ((value_ptr arg1, value_ptr arg2, enum exp_opcode op, enum exp_opcode otherop, enum noside noside)); extern value_ptr value_x_unop PARAMS ((value_ptr arg1, enum exp_opcode op, enum noside noside)); extern value_ptr value_fn_field PARAMS ((value_ptr *arg1p, struct fn_field *f, int j, struct type* type, int offset)); extern value_ptr value_virtual_fn_field PARAMS ((value_ptr *arg1p, struct fn_field *f, int j, struct type *type, int offset)); extern int binop_user_defined_p PARAMS ((enum exp_opcode op, value_ptr arg1, value_ptr arg2)); extern int unop_user_defined_p PARAMS ((enum exp_opcode op, value_ptr arg1)); extern int destructor_name_p PARAMS ((const char *name, const struct type *type)); #define value_free(val) free ((PTR)val) extern void free_all_values PARAMS ((void)); extern void release_value PARAMS ((value_ptr val)); extern int record_latest_value PARAMS ((value_ptr val)); extern void registers_changed PARAMS ((void)); extern void read_register_bytes PARAMS ((int regbyte, char *myaddr, int len)); extern void write_register_bytes PARAMS ((int regbyte, char *myaddr, int len)); extern void read_register_gen PARAMS ((int regno, char *myaddr)); extern CORE_ADDR read_register PARAMS ((int regno)); extern CORE_ADDR read_register_pid PARAMS ((int regno, int pid)); extern void write_register PARAMS ((int regno, LONGEST val)); extern void write_register_pid PARAMS ((int regno, CORE_ADDR val, int pid)); extern void supply_register PARAMS ((int regno, char *val)); extern void get_saved_register PARAMS ((char *raw_buffer, int *optimized, CORE_ADDR *addrp, struct frame_info *frame, int regnum, enum lval_type *lval)); extern void modify_field PARAMS ((char *addr, LONGEST fieldval, int bitpos, int bitsize)); extern void type_print PARAMS ((struct type *type, char *varstring, GDB_FILE *stream, int show)); extern char *baseclass_addr PARAMS ((struct type *type, int index, char *valaddr, value_ptr *valuep, int *errp)); extern void print_longest PARAMS ((GDB_FILE *stream, int format, int use_local, LONGEST val)); extern void print_floating PARAMS ((char *valaddr, struct type *type, GDB_FILE *stream)); extern int value_print PARAMS ((value_ptr val, GDB_FILE *stream, int format, enum val_prettyprint pretty)); extern void value_print_array_elements PARAMS ((value_ptr val, GDB_FILE* stream, int format, enum val_prettyprint pretty)); extern value_ptr value_release_to_mark PARAMS ((value_ptr mark)); extern int val_print PARAMS ((struct type *type, char *valaddr, int embedded_offset, CORE_ADDR address, GDB_FILE *stream, int format, int deref_ref, int recurse, enum val_prettyprint pretty)); extern int val_print_string PARAMS ((CORE_ADDR addr, int len, int width, GDB_FILE *stream)); extern void print_variable_value PARAMS ((struct symbol *var, struct frame_info *frame, GDB_FILE *stream)); extern int check_field PARAMS ((value_ptr, const char *)); extern void c_typedef_print PARAMS ((struct type *type, struct symbol *news, GDB_FILE *stream)); extern char * internalvar_name PARAMS ((struct internalvar *var)); extern void clear_value_history PARAMS ((void)); extern void clear_internalvars PARAMS ((void)); /* From values.c */ extern value_ptr value_copy PARAMS ((value_ptr)); extern int baseclass_offset PARAMS ((struct type *, int, char *, CORE_ADDR)); /* From valops.c */ extern value_ptr varying_to_slice PARAMS ((value_ptr)); extern value_ptr value_slice PARAMS ((value_ptr, int, int)); extern value_ptr call_function_by_hand PARAMS ((value_ptr, int, value_ptr *)); extern value_ptr value_literal_complex PARAMS ((value_ptr, value_ptr, struct type*)); extern void find_rt_vbase_offset PARAMS ((struct type *, struct type *, char *, int, int *, int *)); extern value_ptr find_function_in_inferior PARAMS ((char *)); extern value_ptr value_allocate_space_in_inferior PARAMS ((int)); #endif /* !defined (VALUE_H) */
35.191564
102
0.722982
[ "object" ]
44dd8b8afd882b2e0315d02c5c008f11fe580a26
5,355
h
C
server/server-websocket/non-blocking/ssl/cpp/externalLib/protocol/inter/http/httpconsumer.h
akinaru/socket-multiplatform-impl
49f82f10ebf6d3bcadede0bb831bcec7fbec2a69
[ "MIT" ]
3
2015-05-18T20:45:31.000Z
2015-05-24T17:10:53.000Z
server/server-websocket/non-blocking/ssl/cpp/externalLib/protocol/inter/http/httpconsumer.h
akinaru/socket-multiplatform-impl
49f82f10ebf6d3bcadede0bb831bcec7fbec2a69
[ "MIT" ]
null
null
null
server/server-websocket/non-blocking/ssl/cpp/externalLib/protocol/inter/http/httpconsumer.h
akinaru/socket-multiplatform-impl
49f82f10ebf6d3bcadede0bb831bcec7fbec2a69
[ "MIT" ]
null
null
null
/** httpconsumer.cpp HTTP Consumer client This object permits to store http life cycle into your own design and monitor your parsing in a blocking or non-blocking socket configuration @author Bertrand Martel @version 1.0 */ #ifndef HTTPCONSUMER_H #define HTTPCONSUMER_H #include "string" #include "QByteArray" #include "map" #include "IhttpFrame.h" #include "vector" /** * @brief httpConsumer::httpConsumer * Consumer client of http decoder<br/> * This object permits to store http life cycle into your own design and monitor your parsing in a blocking or non-blocking socket configuration */ class httpconsumer { public: ~httpconsumer(); /** * @brief httpConsumer::httpConsumer * Consumer client of http decoder<br/> * This object permits to store http life cycle into your own design and monitor your parsing in a blocking or non-blocking socket configuration */ httpconsumer(); /** * @brief httpConsumer::clearBuffer * clear current buffer */ void clearBuffer(); /** * @brief httpConsumer::appendToBuffer * append some data to buffer *@param data * data to be appended * @return * pointer to data */ int appendToBuffer(QByteArray* data); /** * @brief httpConsumer::getBuffer * retrieve current buffer *@return */ QByteArray getBuffer(); /** * @brief httpConsumer::getProcessState * retrieve true if all data has been processed in current buffer * @return * */ bool isFinishedProcessing(); /** * @brief setFinishedProcessing * set processing frame state * @param processing */ void setFinishedProcessing(bool processing); /** * @brief setDebug * set debug mode for consumer * @param debug */ void setDebug(bool debug); /** * @brief bodyIndex * index of body in buffer element */ int getBodyIndex(); /** * @brief setBodyIndex * set body index * @param bodyIndexArg */ void setBodyIndex(int bodyIndexArg); /** * @brief bodyProcess * get to know if HTTP body is to be parsed or not */ bool getBodyProcess(); /** * @brief setBodyProcess * set HTTP body parsing state * @param processArg */ void setBodyProcess(bool processArg); /** * @brief bodyLength * length of body */ int getBodyLength(); /** * @brief setBodyLength * set body length * @param length */ void setBodyLength(int length); /** * @brief httpState * http parser current state */ int getHttpState(); /** * @brief setHttpState * set http parser state * @param http_state */ void setHttpState(int http_state); /** * @brief isDebug * debug state * @return */ bool isDebug(); /** * @brief getHttpFrameList * retrieve http frame object list * @return */ std::vector<Ihttpframe*> getHttpFrameList(); /** * @brief httpConsumer::addNewHttpFrame * add a new http frame in the list * @param frame */ void addNewHttpFrame(Ihttpframe * frame); /** * @brief getCurrentHttpFrame * retrieve current http frame object * @return */ Ihttpframe* getCurrentHttpFrame(); /** * @brief setHttpFrameList * set http frame list object * @param list * pointer to vector of IHttp frames */ void setHttpFrameList(std::vector<Ihttpframe*> *list); private: /** * @brief buffer * buffer used to store current unfinished http stream data (unfinished => not terminating with carriage return) */ QByteArray buffer; /** * @brief bodyIndex * index of body in buffer element */ int bodyIndex; /** * @brief bodyProcess * get to know if HTTP body is to be parsed or not */ bool bodyProcess; /** * @brief bodyLength * length of body */ int bodyLength; /** * @brief httpState * http parser current state */ int httpState; /** * @brief processFrame * indicate that HTTP frame has finished processing */ bool finishedProcessing; /** * @brief debug * debug activation */ bool debug; /** * @brief httpFrameList * list of http frames */ std::vector<Ihttpframe*> httpFrameList; }; #endif // HTTPCONSUMER_H
24.121622
157
0.511485
[ "object", "vector" ]
44e2b7c6e7b919c31c45302b25c7881ec6dcd232
24,478
c
C
c/ac2rc.c
erikedwards4/dsp
28880ede8ca715c2a5a9b596742070f9bda9830e
[ "BSD-3-Clause" ]
1
2020-08-26T09:22:40.000Z
2020-08-26T09:22:40.000Z
c/ac2rc.c
erikedwards4/dsp
28880ede8ca715c2a5a9b596742070f9bda9830e
[ "BSD-3-Clause" ]
null
null
null
c/ac2rc.c
erikedwards4/dsp
28880ede8ca715c2a5a9b596742070f9bda9830e
[ "BSD-3-Clause" ]
1
2021-10-05T13:50:32.000Z
2021-10-05T13:50:32.000Z
//Gets reflection coefficients (RCs) from the autocorrelation (AC) function for each vector in X. //Uses a Levinson-Durbin recursion from the AC values. //This adopts levinson.m from Octave's signal package as the correct answer, including the sign convention. //This even matches Octave for some pathological cases giving Inf and/or NaN. //The function from the tsa package may be wrong for the complex case! #include <stdio.h> #include <stdlib.h> #include <math.h> #ifdef __cplusplus namespace codee { extern "C" { #endif int ac2rc_s (float *Y, float *E, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim); int ac2rc_d (double *Y, double *E, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim); int ac2rc_c (float *Y, float *E, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim); int ac2rc_z (double *Y, double *E, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim); int ac2rc_s (float *Y, float *E, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim) { if (dim>3u) { fprintf(stderr,"error in ac2rc_s: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (Lx<2u) { fprintf(stderr,"error in ac2rc_s: ACF must have length > 1\n"); return 1; } if (N==0u) {} else { const size_t P = Lx - 1u; float *A1, *A2, a, e; if (!(A1=(float *)malloc(P*sizeof(float)))) { fprintf(stderr,"error in ac2rc_s: problem with malloc. "); perror("malloc"); return 1; } if (!(A2=(float *)malloc((P-1u)*sizeof(float)))) { fprintf(stderr,"error in ac2rc_s: problem with malloc. "); perror("malloc"); return 1; } if (Lx==N) { e = *X++; a = -*X / e; *Y++ = *A1 = a; e += a * *X++; for (size_t p=1u; p<P-1u; ++p, X+=p) { a = *X; for (size_t q=p; q>0u; --q, ++A1) { --X; a += *X * *A1; } a /= -e; *A1 = a; *Y++ = a; for (size_t q=p; q>0u; --q, ++A2) { --A1; *A2 = *A1; } A1 += p; for (size_t q=p; q>0u; --q) { --A2; --A1; *A1 += a * *A2; } e *= 1.0f - a*a; } a = *X; for (size_t q=P; q>0u; --q, ++A1) { --X; a += *X * *A1; } A1 -= P; a /= -e; *Y = a; *E = e * (1.0f-a*a); //This has approx. same speed, but assembly code definitely longer // A1[0] = 1.0f; // A1[1] = A2[0] = a = -X[1]/X[0]; // Y[0] = -a; // e = fmaf(X[1],a,X[0]); // for (size_t p=2u; p<P; ++p) // { // a = X[p]; // for (size_t q=1u; q<p; ++q) { a = fmaf(X[q],A1[p-q],a); } // A1[p] = a = -a/e; // Y[p-1u] = -a; // for (size_t q=1u; q<p; ++q) { A1[q] = fmaf(a,A2[p-q-1u],A1[q]); } // for (size_t q=p; q>0u; --q) { A2[q] = A1[q+1u]; } // e *= fmaf(a,-a,1.0f); // } // a = X[P]; // for (size_t q=1u; q<P; ++q) { a = fmaf(X[q],A1[P-q],a); } // Y[P-1u] = a/e; E[0] = e*fmaf(a,-a,1.0f); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, X+=Lx, ++Y, ++E) { e = *X++; a = -*X / e; *Y++ = *A1 = a; e += a * *X++; for (size_t p=1u; p<P-1u; ++p, X+=p) { a = *X; for (size_t q=p; q>0u; --q, ++A1) { --X; a += *X * *A1; } a /= -e; *A1 = a; *Y++ = a; for (size_t q=p; q>0u; --q, ++A2) { --A1; *A2 = *A1; } A1 += p; for (size_t q=p; q>0u; --q) { --A2; --A1; *A1 += a * *A2; } e *= 1.0f - a*a; } a = *X; for (size_t q=P; q>0u; --q, ++A1) { --X; a += *X * *A1; } A1 -= P; a /= -e; *Y = a; *E = e * (1.0f-a*a); } } else { for (size_t g=G; g>0u; --g, X+=B*(Lx-1u), Y+=B*(P-1u)) { for (size_t b=B; b>0u; --b, ++X, Y-=K*P-K-1u, ++E) { e = *X; X += K; a = -*X / e; *Y = *A1 = a; Y += K; e += a * *X; X += K; for (size_t p=1u; p<P-1u; ++p, X+=p*K) { a = *X; for (size_t q=p; q>0u; --q, ++A1) { X-=K; a += *X * *A1; } a /= -e; *A1 = a; *Y = a; Y += K; for (size_t q=p; q>0u; --q, ++A2) { --A1; *A2 = *A1; } A1 += p; for (size_t q=p; q>0u; --q) { --A2; --A1; *A1 += a * *A2; } e *= 1.0f - a*a; } a = *X; for (size_t q=P; q>0u; --q, ++A1) { X-=K; a += *X * *A1; } A1 -= P; a /= -e; *Y = a; *E = e * (1.0f-a*a); } } } } free(A1); free(A2); } return 0; } int ac2rc_d (double *Y, double *E, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim) { if (dim>3u) { fprintf(stderr,"error in ac2rc_d: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (Lx<2u) { fprintf(stderr,"error in ac2rc_d: ACF must have length > 1\n"); return 1; } if (N==0u) {} else { const size_t P = Lx - 1u; double *A1, *A2, a, e; if (!(A1=(double *)malloc(P*sizeof(double)))) { fprintf(stderr,"error in ac2rc_d: problem with malloc. "); perror("malloc"); return 1; } if (!(A2=(double *)malloc((P-1u)*sizeof(double)))) { fprintf(stderr,"error in ac2rc_d: problem with malloc. "); perror("malloc"); return 1; } if (Lx==N) { e = *X++; a = -*X / e; *Y++ = *A1 = a; e += a * *X++; for (size_t p=1u; p<P-1u; ++p, X+=p) { a = *X; for (size_t q=p; q>0u; --q, ++A1) { --X; a += *X * *A1; } a /= -e; *A1 = a; *Y++ = a; for (size_t q=p; q>0u; --q, ++A2) { --A1; *A2 = *A1; } A1 += p; for (size_t q=p; q>0u; --q) { --A2; --A1; *A1 += a * *A2; } e *= 1.0 - a*a; } a = *X; for (size_t q=P; q>0u; --q, ++A1) { --X; a += *X * *A1; } A1 -= P; a /= -e; *Y = a; *E = e * (1.0-a*a); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, X+=Lx, ++Y, ++E) { e = *X++; a = -*X / e; *Y++ = *A1 = a; e += a * *X++; for (size_t p=1u; p<P-1u; ++p, X+=p) { a = *X; for (size_t q=p; q>0u; --q, ++A1) { --X; a += *X * *A1; } a /= -e; *A1 = a; *Y++ = a; for (size_t q=p; q>0u; --q, ++A2) { --A1; *A2 = *A1; } A1 += p; for (size_t q=p; q>0u; --q) { --A2; --A1; *A1 += a * *A2; } e *= 1.0 - a*a; } a = *X; for (size_t q=P; q>0u; --q, ++A1) { --X; a += *X * *A1; } A1 -= P; a /= -e; *Y = a; *E = e * (1.0-a*a); } } else { for (size_t g=G; g>0u; --g, X+=B*(Lx-1u), Y+=B*(P-1u)) { for (size_t b=B; b>0u; --b, ++X, Y-=K*P-K-1u, ++E) { e = *X; X += K; a = -*X / e; *Y = *A1 = a; Y += K; e += a * *X; X += K; for (size_t p=1u; p<P-1u; ++p, X+=p*K) { a = *X; for (size_t q=p; q>0u; --q, ++A1) { X-=K; a += *X * *A1; } a /= -e; *A1 = a; *Y = a; Y += K; for (size_t q=p; q>0u; --q, ++A2) { --A1; *A2 = *A1; } A1 += p; for (size_t q=p; q>0u; --q) { --A2; --A1; *A1 += a * *A2; } e *= 1.0 - a*a; } a = *X; for (size_t q=P; q>0u; --q, ++A1) { X-=K; a += *X * *A1; } A1 -= P; a /= -e; *Y = a; *E = e * (1.0-a*a); } } } } free(A1); free(A2); } return 0; } int ac2rc_c (float *Y, float *E, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim) { if (dim>3u) { fprintf(stderr,"error in ac2rc_c: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (Lx<2u) { fprintf(stderr,"error in ac2rc_c: ACF must have length > 1\n"); return 1; } if (N==0u) {} else { const size_t P = Lx - 1u; float *A1, *A2, ar, ai, e, den; if (!(A1=(float *)malloc(2u*P*sizeof(float)))) { fprintf(stderr,"error in ac2rc_c: problem with malloc. "); perror("malloc"); return 1; } if (!(A2=(float *)malloc(2u*(P-1u)*sizeof(float)))) { fprintf(stderr,"error in ac2rc_c: problem with malloc. "); perror("malloc"); return 1; } if (Lx==N) { den = *X**X + *(X+1)**(X+1); ar = -(*(X+2)**X + *(X+3)**(X+1)) / den; ai = (*(X+1)**(X+2) - *(X+3)**X) / den; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; e = *X * (1.0f - (ar*ar+ai*ai)); X += 4; Y += 2; for (size_t p=1u; p<P-1u; ++p, X+=2u*p, Y+=2) { ar = *X; ai = *(X+1); for (size_t q=p; q>0u; --q, A1+=2) { X -= 2; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } ar /= -e; ai /= -e; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; for (size_t q=p; q>0u; --q, A2+=2) { A1-=2; *A2 = *A1; *(A2+1) = -*(A1+1); } A1 += 2u*p; for (size_t q=p; q>0u; --q) { A2 -= 2; A1 -= 2; *A1 += ar**A2 - ai**(A2+1); *(A1+1) += ar**(A2+1) + ai**A2; } e *= 1.0f - (ar*ar + ai*ai); } ar = *X; ai = *(X+1); for (size_t q=P; q>0u; --q, A1+=2) { X -= 2; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } A1 -= 2u*P; ar /= -e; ai /= -e; *Y++ = ar; *Y = ai; *E = e * (1.0f-ar*ar-ai*ai); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, X+=2u*Lx, ++E) { den = *X**X + *(X+1)**(X+1); ar = -(*(X+2)**X + *(X+3)**(X+1)) / den; ai = (*(X+1)**(X+2) - *(X+3)**X) / den; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; e = *X * (1.0f - (ar*ar+ai*ai)); X += 4; Y += 2; for (size_t p=1u; p<P-1u; ++p, X+=2u*p, Y+=2) { ar = *X; ai = *(X+1); for (size_t q=p; q>0u; --q, A1+=2) { X -= 2; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } ar /= -e; ai /= -e; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; for (size_t q=p; q>0u; --q, A2+=2) { A1-=2; *A2 = *A1; *(A2+1) = -*(A1+1); } A1 += 2u*p; for (size_t q=p; q>0u; --q) { A2 -= 2; A1 -= 2; *A1 += ar**A2 - ai**(A2+1); *(A1+1) += ar**(A2+1) + ai**A2; } e *= 1.0f - (ar*ar + ai*ai); } ar = *X; ai = *(X+1); for (size_t q=P; q>0u; --q, A1+=2) { X -= 2; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } A1 -= 2u*P; ar /= -e; ai /= -e; *Y++ = ar; *Y++ = ai; *E = e * (1.0f-ar*ar-ai*ai); } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(P-1u)) { for (size_t b=B; b>0u; --b, X+=2, Y-=2u*(K*P-K-1u), ++E) { den = *X**X + *(X+1)**(X+1); ar = -(*(X+2u*K)**X + *(X+2u*K+1u)**(X+1)) / den; ai = (*(X+1)**(X+2u*K) - *(X+2u*K+1u)**X) / den; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; e = *X * (1.0f - (ar*ar+ai*ai)); X += 4u*K; Y += 2u*K; for (size_t p=1u; p<P-1u; ++p, X+=2u*p*K, Y+=2u*K) { ar = *X; ai = *(X+1); for (size_t q=p; q>0u; --q, A1+=2) { X -= 2u*K; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } ar /= -e; ai /= -e; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; for (size_t q=p; q>0u; --q, A2+=2) { A1-=2; *A2 = *A1; *(A2+1) = -*(A1+1); } A1 += 2u*p; for (size_t q=p; q>0u; --q) { A2 -= 2; A1 -= 2; *A1 += ar**A2 - ai**(A2+1); *(A1+1) += ar**(A2+1) + ai**A2; } e *= 1.0f - (ar*ar + ai*ai); } ar = *X; ai = *(X+1); for (size_t q=P; q>0u; --q, A1+=2) { X -= 2u*K; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } A1 -= 2u*P; ar /= -e; ai /= -e; *Y = ar; *(Y+1) = ai; *E = e * (1.0f-ar*ar-ai*ai); } } } } free(A1); free(A2); } return 0; } int ac2rc_z (double *Y, double *E, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim) { if (dim>3u) { fprintf(stderr,"error in ac2rc_z: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (Lx<2u) { fprintf(stderr,"error in ac2rc_z: ACF must have length > 1\n"); return 1; } if (N==0u) {} else { const size_t P = Lx - 1u; double *A1, *A2, ar, ai, e, den; if (!(A1=(double *)malloc(2u*P*sizeof(double)))) { fprintf(stderr,"error in ac2rc_z: problem with malloc. "); perror("malloc"); return 1; } if (!(A2=(double *)malloc(2u*(P-1u)*sizeof(double)))) { fprintf(stderr,"error in ac2rc_z: problem with malloc. "); perror("malloc"); return 1; } if (Lx==N) { den = *X**X + *(X+1)**(X+1); ar = -(*(X+2)**X + *(X+3)**(X+1)) / den; ai = (*(X+1)**(X+2) - *(X+3)**X) / den; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; e = *X * (1.0 - (ar*ar+ai*ai)); X += 4; Y += 2; for (size_t p=1u; p<P-1u; ++p, X+=2u*p, Y+=2) { ar = *X; ai = *(X+1); for (size_t q=p; q>0u; --q, A1+=2) { X -= 2; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } ar /= -e; ai /= -e; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; for (size_t q=p; q>0u; --q, A2+=2) { A1-=2; *A2 = *A1; *(A2+1) = -*(A1+1); } A1 += 2u*p; for (size_t q=p; q>0u; --q) { A2 -= 2; A1 -= 2; *A1 += ar**A2 - ai**(A2+1); *(A1+1) += ar**(A2+1) + ai**A2; } e *= 1.0 - (ar*ar + ai*ai); } ar = *X; ai = *(X+1); for (size_t q=P; q>0u; --q, A1+=2) { X -= 2; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } A1 -= 2u*P; ar /= -e; ai /= -e; *Y++ = ar; *Y = ai; *E = e * (1.0-ar*ar-ai*ai); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, X+=2u*Lx, ++E) { den = *X**X + *(X+1)**(X+1); ar = -(*(X+2)**X + *(X+3)**(X+1)) / den; ai = (*(X+1)**(X+2) - *(X+3)**X) / den; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; e = *X * (1.0 - (ar*ar+ai*ai)); X += 4; Y += 2; for (size_t p=1u; p<P-1u; ++p, X+=2u*p, Y+=2) { ar = *X; ai = *(X+1); for (size_t q=p; q>0u; --q, A1+=2) { X -= 2; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } ar /= -e; ai /= -e; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; for (size_t q=p; q>0u; --q, A2+=2) { A1-=2; *A2 = *A1; *(A2+1) = -*(A1+1); } A1 += 2u*p; for (size_t q=p; q>0u; --q) { A2 -= 2; A1 -= 2; *A1 += ar**A2 - ai**(A2+1); *(A1+1) += ar**(A2+1) + ai**A2; } e *= 1.0 - (ar*ar + ai*ai); } ar = *X; ai = *(X+1); for (size_t q=P; q>0u; --q, A1+=2) { X -= 2; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } A1 -= 2u*P; ar /= -e; ai /= -e; *Y++ = ar; *Y++ = ai; *E = e * (1.0-ar*ar-ai*ai); } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(P-1u)) { for (size_t b=B; b>0u; --b, X+=2, Y-=2u*(K*P-K-1u), ++E) { den = *X**X + *(X+1)**(X+1); ar = -(*(X+2u*K)**X + *(X+2u*K+1u)**(X+1)) / den; ai = (*(X+1)**(X+2u*K) - *(X+2u*K+1u)**X) / den; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; e = *X * (1.0 - (ar*ar+ai*ai)); X += 4u*K; Y += 2u*K; for (size_t p=1u; p<P-1u; ++p, X+=2u*p*K, Y+=2u*K) { ar = *X; ai = *(X+1); for (size_t q=p; q>0u; --q, A1+=2) { X -= 2u*K; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } ar /= -e; ai /= -e; *A1 = ar; *(A1+1) = ai; *Y = ar; *(Y+1) = ai; for (size_t q=p; q>0u; --q, A2+=2) { A1-=2; *A2 = *A1; *(A2+1) = -*(A1+1); } A1 += 2u*p; for (size_t q=p; q>0u; --q) { A2 -= 2; A1 -= 2; *A1 += ar**A2 - ai**(A2+1); *(A1+1) += ar**(A2+1) + ai**A2; } e *= 1.0 - (ar*ar + ai*ai); } ar = *X; ai = *(X+1); for (size_t q=P; q>0u; --q, A1+=2) { X -= 2u*K; ar += *X**A1 - *(X+1)**(A1+1); ai += *(X+1)**A1 + *X**(A1+1); } A1 -= 2u*P; ar /= -e; ai /= -e; *Y = ar; *(Y+1) = ai; *E = e * (1.0-ar*ar-ai*ai); } } } } free(A1); free(A2); } return 0; } #ifdef __cplusplus } } #endif
40.93311
164
0.287156
[ "vector" ]
6d0b56e1a6f182aa3c40efa105534720df260653
6,281
h
C
mitielib/include/mitie/conll_parser.h
maxmert/nlp-mitie
ec3153ef2fe7a80e7cf3d80d14b388b8cd679343
[ "Unlicense" ]
2,695
2015-01-01T21:13:47.000Z
2022-03-31T04:45:32.000Z
mitielib/include/mitie/conll_parser.h
maxmert/nlp-mitie
ec3153ef2fe7a80e7cf3d80d14b388b8cd679343
[ "Unlicense" ]
208
2015-01-23T19:29:07.000Z
2022-02-08T02:55:17.000Z
mitielib/include/mitie/conll_parser.h
maxmert/nlp-mitie
ec3153ef2fe7a80e7cf3d80d14b388b8cd679343
[ "Unlicense" ]
567
2015-01-06T19:22:19.000Z
2022-03-21T17:01:04.000Z
// Copyright (C) 2013 Massachusetts Institute of Technology, Lincoln Laboratory // License: Boost Software License See LICENSE.txt for the full license. // Authors: Davis E. King (davis@dlib.net) #ifndef MIT_LL_CONLL_PaRSER_H_ #define MIT_LL_CONLL_PaRSER_H_ #include <vector> #include <string> namespace mitie { // ---------------------------------------------------------------------------------------- typedef unsigned long BIO_label; const unsigned long I_PER = 0; const unsigned long B_PER = 1; const unsigned long O = 2; const unsigned long B_LOC = 3; const unsigned long B_ORG = 4; const unsigned long B_MISC = 5; const unsigned long I_ORG = 6; const unsigned long I_LOC = 7; const unsigned long I_MISC = 8; // BILOU extension const unsigned long L_PER = 9; const unsigned long L_ORG = 10; const unsigned long L_LOC = 11; const unsigned long L_MISC = 12; const unsigned long U_PER = 13; const unsigned long U_ORG = 14; const unsigned long U_LOC = 15; const unsigned long U_MISC = 16; // chunk labels const unsigned long PER = 0; const unsigned long LOC = 1; const unsigned long ORG = 2; const unsigned long MISC = 3; const unsigned long NOT_ENTITY = 4; // ---------------------------------------------------------------------------------------- typedef std::vector<std::pair<std::string, BIO_label> > labeled_sentence; // ---------------------------------------------------------------------------------------- void parse_conll_data ( const std::string& filename, std::vector<std::vector<std::string> >& sentences, std::vector<std::vector<std::pair<unsigned long, unsigned long> > >& chunks, std::vector<std::vector<unsigned long> >& chunk_labels ); /*! ensures - reads the given file and parses it as a CONLL 2003 NER data file. The output is the set of sentences where each has been annotated with its named entity chunk boundaries and chunk labels. - #sentences.size() == chunks.size() == chunk_labels.size() - for all valid i: - #sentences[i] == The tokens in the i-th sentence in the CONLL dataset file. - #chunks[i].size() == #chunk_labels[i].size() - #chunks[i] == the named entity chunks in #sentences[i]. Moreover, #chunks[i][j] has a label of #chunk_labels[i][j]. - #chunks[i][j] specifies a half open range of words within sentences[i]. This range contains a named entity. The range starts with sentences[i][chunks[i][j].first] and ends at sentences[i][chunks[i][j].second-1]. - #chunk_labels[i][j] is equal to either PER, ORG, LOC, or MISC. !*/ void parse_conll_data ( const std::string& filename, std::vector<std::vector<std::string> >& sentences, std::vector<std::vector<std::pair<unsigned long, unsigned long> > >& chunks, std::vector<std::vector<std::string> >& chunk_labels ); /*! ensures - This function is identical to the version above except instead of using integer chunk labels (i.e. PER, LOC, ORG, and MISC) it uses strings of "PERSON", "LOCATION", "ORGANIZATION", and "MISC". !*/ // ---------------------------------------------------------------------------------------- std::vector<labeled_sentence> parse_conll_data ( const std::string& filename ); /*! ensures - reads the given file and parses it as a CONLL 2003 NER data file. We return the set of sentences with each token labeled with it's NER label. !*/ // ---------------------------------------------------------------------------------------- void print_conll_data ( const std::vector<labeled_sentence>& data ); /*! ensures - prints the given data in the CONLL 2003 format. Since data only has tokens and NER tags the POS and Chunk tags are filled in with X. !*/ // ---------------------------------------------------------------------------------------- void print_conll_data ( const std::vector<labeled_sentence>& data, const std::vector<std::vector<BIO_label> >& extra_labels ); /*! requires - data.size() == extra_labels.size() - for all valid i: - data[i].size() == extra_labels[i].size() ensures - prints the given data int he CONLL 2003 format. Since data only has tokens and NER tags the POS and Chunk tags are filled in with X. We also print extra_labels as the 5th column. Therefore, extra_labels should contain predicted labels for each token. !*/ // ---------------------------------------------------------------------------------------- void separate_labels_from_tokens ( const std::vector<labeled_sentence>& data, std::vector<std::vector<std::string> >& tokens, std::vector<std::vector<BIO_label> >& labels ); /*! ensures - Splits the labeled data given to this function into two vectors, one containing the tokens and another the labels - #tokens.size() == data.size() - #labels.size() == data.size() - for all valid i: - #tokens[i].size() == data[i].size() - #labels[i].size() == data[i].size() !*/ // ---------------------------------------------------------------------------------------- std::string lookup_conll_label ( const BIO_label& label ); void convert_from_BIO_to_BILOU ( std::vector<BIO_label>& labels ); void convert_from_BILOU_to_BIO ( std::vector<BIO_label>& labels ); void convert_from_BIO_to_BILOU ( std::vector<std::vector<BIO_label> >& labels ); void convert_from_BILOU_to_BIO ( std::vector<std::vector<BIO_label> >& labels ); // ---------------------------------------------------------------------------------------- } #endif // MIT_LL_CONLL_PaRSER_H_
36.517442
109
0.523324
[ "vector" ]
6d0cc093fc4a52507e0639439f2f282693fdba81
3,270
h
C
src/org.xtuml.bp.welcome/models/MicrowaveOven/src/MicrowaveOven_MO_MT_class.h
FMAY-Software/bridgepoint
90d95f21441dfc90568a2e88ccc221f06a2480db
[ "Apache-2.0" ]
29
2015-04-08T04:02:08.000Z
2022-03-16T07:32:13.000Z
src/org.xtuml.bp.welcome/models/MicrowaveOven/src/MicrowaveOven_MO_MT_class.h
FMAY-Software/bridgepoint
90d95f21441dfc90568a2e88ccc221f06a2480db
[ "Apache-2.0" ]
92
2015-03-24T21:05:19.000Z
2021-09-24T01:48:33.000Z
src/org.xtuml.bp.welcome/models/MicrowaveOven/src/MicrowaveOven_MO_MT_class.h
FMAY-Software/bridgepoint
90d95f21441dfc90568a2e88ccc221f06a2480db
[ "Apache-2.0" ]
82
2015-01-09T16:50:50.000Z
2022-03-25T03:16:16.000Z
/*---------------------------------------------------------------------------- * File: MicrowaveOven_MO_MT_class.h * * Class: Magnetron Tube (MO_MT) * Component: MicrowaveOven * * your copyright statement can go here (from te_copyright.body) *--------------------------------------------------------------------------*/ #ifndef MICROWAVEOVEN_MO_MT_CLASS_H #define MICROWAVEOVEN_MO_MT_CLASS_H #ifdef __cplusplus extern "C" { #endif /* * Structural representation of application analysis class: * Magnetron Tube (MO_MT) */ struct MicrowaveOven_MO_MT { Escher_StateNumber_t current_state; /* application analysis class attributes */ Escher_UniqueID_t TubeID; /* * TubeID */ MicrowaveOven_tube_wattage_t current_power_output; /* - current_power_output */ /* relationship storage */ /* Note: No storage needed for MO_MT->MO_O[R1] */ }; #define MicrowaveOven_MO_MT_MAX_EXTENT_SIZE 10 extern Escher_Extent_t pG_MicrowaveOven_MO_MT_extent; /* * instance event: MO_MT1:'increase_power' */ typedef struct { EVENT_BASE_ATTRIBUTE_LIST /* base attributes of all event classes */ /* Note: no supplemental data for this event */ } MicrowaveOven_MO_MTevent1; extern const Escher_xtUMLEventConstant_t MicrowaveOven_MO_MTevent1c; /* * instance event: MO_MT2:'decrease_power' */ typedef struct { EVENT_BASE_ATTRIBUTE_LIST /* base attributes of all event classes */ /* Note: no supplemental data for this event */ } MicrowaveOven_MO_MTevent2; extern const Escher_xtUMLEventConstant_t MicrowaveOven_MO_MTevent2c; /* * instance event: MO_MT3:'power_on' */ typedef struct { EVENT_BASE_ATTRIBUTE_LIST /* base attributes of all event classes */ /* Note: no supplemental data for this event */ } MicrowaveOven_MO_MTevent3; extern const Escher_xtUMLEventConstant_t MicrowaveOven_MO_MTevent3c; /* * instance event: MO_MT4:'power_off' */ typedef struct { EVENT_BASE_ATTRIBUTE_LIST /* base attributes of all event classes */ /* Note: no supplemental data for this event */ } MicrowaveOven_MO_MTevent4; extern const Escher_xtUMLEventConstant_t MicrowaveOven_MO_MTevent4c; /* * union of events targeted towards 'MO_MT' state machine */ typedef union { MicrowaveOven_MO_MTevent1 mo_mt1_1; MicrowaveOven_MO_MTevent2 mo_mt2_2; MicrowaveOven_MO_MTevent3 mo_mt3_3; MicrowaveOven_MO_MTevent4 mo_mt4_4; } MicrowaveOven_MO_MT_Events_u; /* * enumeration of state model states for class */ #define MicrowaveOven_MO_MT_STATE_1 1 /* state [1]: (Output Power Stable and OFF) */ #define MicrowaveOven_MO_MT_STATE_2 2 /* state [2]: (Reducing Output Power) */ #define MicrowaveOven_MO_MT_STATE_3 3 /* state [3]: (Raising Output Power) */ #define MicrowaveOven_MO_MT_STATE_4 4 /* state [4]: (Output Power Stable and ON) */ /* * enumeration of state model event numbers */ #define MICROWAVEOVEN_MO_MTEVENT1NUM 0 /* MO_MT1:'increase_power' */ #define MICROWAVEOVEN_MO_MTEVENT2NUM 1 /* MO_MT2:'decrease_power' */ #define MICROWAVEOVEN_MO_MTEVENT3NUM 2 /* MO_MT3:'power_on' */ #define MICROWAVEOVEN_MO_MTEVENT4NUM 3 /* MO_MT4:'power_off' */ extern void MicrowaveOven_MO_MT_Dispatch( Escher_xtUMLEvent_t * ); #ifdef __cplusplus } #endif #endif /* MICROWAVEOVEN_MO_MT_CLASS_H */
33.71134
86
0.722018
[ "model" ]
6d1a39b29c15c41ecca1e3c4e26fce452a02e34e
415
h
C
core/include/VirtualKeyboard.h
Marklous/free-virtual-keyboard
0a49f3fe7907a6a2c5c4964c32cbdf4055b4ad99
[ "Beerware" ]
null
null
null
core/include/VirtualKeyboard.h
Marklous/free-virtual-keyboard
0a49f3fe7907a6a2c5c4964c32cbdf4055b4ad99
[ "Beerware" ]
null
null
null
core/include/VirtualKeyboard.h
Marklous/free-virtual-keyboard
0a49f3fe7907a6a2c5c4964c32cbdf4055b4ad99
[ "Beerware" ]
null
null
null
#pragma once #include "VirtualKeyboardModel.h" #include "QtUtils/ModelHolder.h" #include <QQuickView> #include <Poco/SharedPtr.h> class VirtualKeyboard : public QObject{ Q_OBJECT public: typedef Poco::SharedPtr <VirtualKeyboard> Ptr; VirtualKeyboard(QQuickView * view, QQmlContext * ctx); ~VirtualKeyboard(); private: ModelHolder<VirtualKeyboardModel>::Ptr model; QQuickView * _view; };
20.75
58
0.737349
[ "model" ]
6d2f595c7bfbee9899c4b7f03feb4ba663bde98b
56,546
c
C
pygame/src/base.c
CiubucAlexandra/Theremine-Projet-Micriprocesseurs
7670d9cb468b060135dc5f057b734db970da0f0c
[ "BSD-3-Clause" ]
4
2018-09-07T15:35:24.000Z
2019-03-27T09:48:12.000Z
pygame/src/base.c
CiubucAlexandra/Theremine-Projet-Micriprocesseurs
7670d9cb468b060135dc5f057b734db970da0f0c
[ "BSD-3-Clause" ]
371
2020-03-04T21:51:56.000Z
2022-03-31T20:59:11.000Z
pygame/src/base.c
CiubucAlexandra/Theremine-Projet-Micriprocesseurs
7670d9cb468b060135dc5f057b734db970da0f0c
[ "BSD-3-Clause" ]
3
2019-06-18T19:57:17.000Z
2020-11-06T03:55:08.000Z
/* pygame - Python Game Library Copyright (C) 2000-2001 Pete Shinners This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Pete Shinners pete@shinners.org */ #define NO_PYGAME_C_API #define PYGAMEAPI_BASE_INTERNAL #include "pygame.h" #include "pgarrinter.h" #include "pgcompat.h" #include "doc/pygame_doc.h" #include <signal.h> /* This file controls all the initialization of * the module and the various SDL subsystems */ /*platform specific init stuff*/ #ifdef MS_WIN32 /*python gives us MS_WIN32*/ #define WIN32_LEAN_AND_MEAN #define VC_EXTRALEAN #include<windows.h> extern int SDL_RegisterApp (char*, Uint32, void*); #endif #if defined(macintosh) #if(!defined(__MWERKS__) && !TARGET_API_MAC_CARBON) QDGlobals qd; #endif #endif #if SDL_BYTEORDER == SDL_LIL_ENDIAN #define PAI_MY_ENDIAN '<' #define PAI_OTHER_ENDIAN '>' #define BUF_OTHER_ENDIAN '>' #else #define PAI_MY_ENDIAN '>' #define PAI_OTHER_ENDIAN '<' #define BUF_OTHER_ENDIAN '<' #endif #define BUF_MY_ENDIAN '=' #if PY3 #define INT_CHECK(o) PyLong_Check(o) #else #define INT_CHECK(o) (PyInt_Check(o) || PyLong_Check(o)) #endif /* Extended array struct */ typedef struct capsule_interface_s { PyArrayInterface inter; Py_intptr_t imem[1]; } CapsuleInterface; /* Py_buffer internal data for an array interface/struct */ typedef struct view_internals_s { char format[4]; /* make 4 byte word sized */ Py_ssize_t imem[1]; } ViewInternals; /* Custom exceptions */ static PyObject* PgExc_BufferError = NULL; /* Only one instance of the state per process. */ static PyObject* quitfunctions = NULL; static int sdl_was_init = 0; static void install_parachute (void); static void uninstall_parachute (void); static void _quit (void); static void atexit_quit (void); static int PyGame_Video_AutoInit (void); static void PyGame_Video_AutoQuit (void); static int GetArrayStruct (PyObject*, PyObject**, PyArrayInterface**); static PyObject* ArrayStructAsDict (PyArrayInterface*); static PyObject* PgBuffer_AsArrayInterface (Py_buffer*); static PyObject* PgBuffer_AsArrayStruct (Py_buffer*); static int _buffer_is_byteswapped (Py_buffer*); static void PgBuffer_Release (Pg_buffer*); static int PgObject_GetBuffer (PyObject*, Pg_buffer*, int); static int GetArrayInterface (PyObject**, PyObject*); static int PgArrayStruct_AsBuffer (Pg_buffer*, PyObject*, PyArrayInterface*, int); static int _arraystruct_as_buffer (Py_buffer*, PyObject*, PyArrayInterface*, int); static int _arraystruct_to_format (char*, PyArrayInterface*, int); static int PgDict_AsBuffer (Pg_buffer*, PyObject*, int); static int _pyshape_check (PyObject*); static int _pytypestr_check (PyObject*); static int _pystrides_check (PyObject*); static int _pydata_check (PyObject*); static int _is_inttuple (PyObject*); static int _pyvalues_as_buffer(Py_buffer*, int, PyObject*, PyObject*, PyObject*, PyObject*); static int _pyinttuple_as_ssize_arr (PyObject*, Py_ssize_t*); static int _pytypestr_as_format (PyObject*, char*, Py_ssize_t*); static PyObject* view_get_typestr_obj (Py_buffer*); static PyObject* view_get_shape_obj (Py_buffer*); static PyObject* view_get_strides_obj (Py_buffer*); static PyObject* view_get_data_obj (Py_buffer*); static char _as_arrayinter_typekind (Py_buffer*); static char _as_arrayinter_byteorder (Py_buffer*); static int _as_arrayinter_flags (Py_buffer*); static CapsuleInterface* _new_capsuleinterface (Py_buffer*); #if PY3 static void _capsule_PyMem_Free (PyObject*); #endif static PyObject* _shape_as_tuple (PyArrayInterface*); static PyObject* _typekind_as_str (PyArrayInterface*); static PyObject* _strides_as_tuple (PyArrayInterface*); static PyObject* _data_as_tuple (PyArrayInterface*); static PyObject* get_array_interface (PyObject*, PyObject*); static void _release_buffer_array (Py_buffer*); static void _release_buffer_generic (Py_buffer*); #if PY_VERSION_HEX < 0x02060000 static int _IsFortranContiguous(Py_buffer *view) { Py_ssize_t sd, dim; int i; if (view->ndim == 0) return 1; if (view->strides == NULL) return (view->ndim == 1); sd = view->itemsize; if (view->ndim == 1) return (view->shape[0] == 1 || sd == view->strides[0]); for (i=0; i<view->ndim; i++) { dim = view->shape[i]; if (dim == 0) return 1; if (view->strides[i] != sd) return 0; sd *= dim; } return 1; } static int _IsCContiguous(Py_buffer *view) { Py_ssize_t sd, dim; int i; if (view->ndim == 0) return 1; if (view->strides == NULL) return 1; sd = view->itemsize; if (view->ndim == 1) return (view->shape[0] == 1 || sd == view->strides[0]); for (i=view->ndim-1; i>=0; i--) { dim = view->shape[i]; if (dim == 0) return 1; if (view->strides[i] != sd) return 0; sd *= dim; } return 1; } static int PyBuffer_IsContiguous(Py_buffer *view, char fort) { if (view->suboffsets != NULL) return 0; if (fort == 'C') return _IsCContiguous(view); else if (fort == 'F') return _IsFortranContiguous(view); else if (fort == 'A') return (_IsCContiguous(view) || _IsFortranContiguous(view)); return 0; } #endif /* #if PY_VERSION_HEX < 0x02060000 */ static int CheckSDLVersions (void) /*compare compiled to linked*/ { SDL_version compiled; const SDL_version* linked; SDL_VERSION (&compiled); linked = SDL_Linked_Version (); /*only check the major and minor version numbers. we will relax any differences in 'patch' version.*/ if (compiled.major != linked->major || compiled.minor != linked->minor) { PyErr_Format(PyExc_RuntimeError, "SDL compiled with version %d.%d.%d, linked to %d.%d.%d", compiled.major, compiled.minor, compiled.patch, linked->major, linked->minor, linked->patch); return 0; } return 1; } void PyGame_RegisterQuit (void(*func)(void)) { PyObject* obj; if (!quitfunctions) { quitfunctions = PyList_New (0); if (!quitfunctions) return; } if (func) { obj = PyCapsule_New (func, "quit", NULL); PyList_Append (quitfunctions, obj); Py_DECREF (obj); } } static PyObject* register_quit (PyObject* self, PyObject* value) { if (!quitfunctions) { quitfunctions = PyList_New (0); if (!quitfunctions) return NULL; } PyList_Append (quitfunctions, value); Py_RETURN_NONE; } static PyObject* init (PyObject* self) { PyObject *allmodules, *moduleslist, *dict, *func, *result, *mod; int loop, num; int success=0, fail=0; if (!CheckSDLVersions ()) return NULL; /*nice to initialize timer, so startup time will reflec init() time*/ sdl_was_init = SDL_Init ( #if defined(WITH_THREAD) && !defined(MS_WIN32) && defined(SDL_INIT_EVENTTHREAD) SDL_INIT_EVENTTHREAD | #endif SDL_INIT_TIMER | SDL_INIT_NOPARACHUTE) == 0; /* initialize all pygame modules */ allmodules = PyImport_GetModuleDict (); moduleslist = PyDict_Values (allmodules); if (!allmodules || !moduleslist) return Py_BuildValue ("(ii)", 0, 0); if (PyGame_Video_AutoInit ()) ++success; else ++fail; num = PyList_Size (moduleslist); for (loop = 0; loop < num; ++loop) { mod = PyList_GET_ITEM (moduleslist, loop); if (!mod || !PyModule_Check (mod)) continue; dict = PyModule_GetDict (mod); func = PyDict_GetItemString (dict, "__PYGAMEinit__"); if(func && PyCallable_Check (func)) { result = PyObject_CallObject (func, NULL); if (result && PyObject_IsTrue (result)) ++success; else { PyErr_Clear (); ++fail; } Py_XDECREF (result); } } Py_DECREF (moduleslist); return Py_BuildValue ("(ii)", success, fail); } static void atexit_quit (void) { PyGame_Video_AutoQuit (); /* Maybe it is safe to call SDL_quit more than once after an SDL_Init, but this is undocumented. So play it safe and only call after a successful SDL_Init. */ if (sdl_was_init) { sdl_was_init = 0; SDL_Quit (); } } static PyObject* get_sdl_version (PyObject* self) { const SDL_version *v; v = SDL_Linked_Version (); return Py_BuildValue ("iii", v->major, v->minor, v->patch); } static PyObject* get_sdl_byteorder (PyObject *self) { return PyLong_FromLong (SDL_BYTEORDER); } static PyObject* quit (PyObject* self) { _quit (); Py_RETURN_NONE; } static void _quit (void) { PyObject* quit; PyObject* privatefuncs; int num; if (!quitfunctions) { return; } privatefuncs = quitfunctions; quitfunctions = NULL; uninstall_parachute (); num = PyList_Size (privatefuncs); while (num--) /*quit in reverse order*/ { quit = PyList_GET_ITEM (privatefuncs, num); if (PyCallable_Check (quit)) PyObject_CallObject (quit, NULL); else if (PyCapsule_CheckExact (quit)) { void* ptr = PyCapsule_GetPointer (quit, "quit"); (*(void(*)(void)) ptr) (); } } Py_DECREF (privatefuncs); atexit_quit (); } /* internal C API utility functions */ static int IntFromObj (PyObject* obj, int* val) { int tmp_val; tmp_val = PyInt_AsLong (obj); if (tmp_val == -1 && PyErr_Occurred ()) { PyErr_Clear (); return 0; } *val = tmp_val; return 1; } static int IntFromObjIndex (PyObject* obj, int _index, int* val) { int result = 0; PyObject* item; item = PySequence_GetItem (obj, _index); if (item) { result = IntFromObj (item, val); Py_DECREF (item); } return result; } static int TwoIntsFromObj (PyObject* obj, int* val1, int* val2) { if (PyTuple_Check (obj) && PyTuple_Size (obj) == 1) return TwoIntsFromObj (PyTuple_GET_ITEM (obj, 0), val1, val2); if (!PySequence_Check (obj) || PySequence_Length (obj) != 2) return 0; if (!IntFromObjIndex (obj, 0, val1) || !IntFromObjIndex (obj, 1, val2)) return 0; return 1; } static int FloatFromObj (PyObject* obj, float* val) { float f= (float)PyFloat_AsDouble (obj); if (f==-1 && PyErr_Occurred()) { PyErr_Clear (); return 0; } *val = f; return 1; } static int FloatFromObjIndex (PyObject* obj, int _index, float* val) { int result = 0; PyObject* item; item = PySequence_GetItem (obj, _index); if (item) { result = FloatFromObj (item, val); Py_DECREF (item); } return result; } static int TwoFloatsFromObj (PyObject* obj, float* val1, float* val2) { if (PyTuple_Check (obj) && PyTuple_Size (obj) == 1) return TwoFloatsFromObj (PyTuple_GET_ITEM (obj, 0), val1, val2); if (!PySequence_Check (obj) || PySequence_Length (obj) != 2) return 0; if (!FloatFromObjIndex (obj, 0, val1) || !FloatFromObjIndex (obj, 1, val2)) return 0; return 1; } static int UintFromObj (PyObject* obj, Uint32* val) { PyObject* longobj; if (PyNumber_Check (obj)) { if (!(longobj = PyNumber_Long (obj))) return 0; *val = (Uint32) PyLong_AsUnsignedLong (longobj); Py_DECREF (longobj); return 1; } return 0; } static int UintFromObjIndex (PyObject* obj, int _index, Uint32* val) { int result = 0; PyObject* item; item = PySequence_GetItem (obj, _index); if (item) { result = UintFromObj (item, val); Py_DECREF (item); } return result; } static int RGBAFromObj (PyObject* obj, Uint8* RGBA) { int length; Uint32 val; if (PyTuple_Check (obj) && PyTuple_Size (obj) == 1) return RGBAFromObj (PyTuple_GET_ITEM (obj, 0), RGBA); if (!PySequence_Check (obj)) return 0; length = PySequence_Length (obj); if (length < 3 || length > 4) return 0; if (!UintFromObjIndex (obj, 0, &val) || val > 255) return 0; RGBA[0] = (Uint8) val; if (!UintFromObjIndex (obj, 1, &val) || val > 255) return 0; RGBA[1] = (Uint8) val; if (!UintFromObjIndex (obj, 2, &val) || val > 255) return 0; RGBA[2] = (Uint8) val; if (length == 4) { if (!UintFromObjIndex (obj, 3, &val) || val > 255) return 0; RGBA[3] = (Uint8) val; } else RGBA[3] = (Uint8) 255; return 1; } static PyObject* get_error (PyObject* self) { return Text_FromUTF8 (SDL_GetError ()); } static PyObject* set_error (PyObject *s, PyObject *args) { char *errstring = NULL; if (!PyArg_ParseTuple (args, "s", &errstring)) return NULL; SDL_SetError(errstring); Py_RETURN_NONE; } /*video init needs to be here, because of it's *important init order priority */ static void PyGame_Video_AutoQuit (void) { if (SDL_WasInit (SDL_INIT_VIDEO)) SDL_QuitSubSystem (SDL_INIT_VIDEO); } static int PyGame_Video_AutoInit (void) { if (!SDL_WasInit (SDL_INIT_VIDEO)) { int status; #if defined(__APPLE__) && defined(darwin) PyObject *module; PyObject *rval; module = PyImport_ImportModule ("pygame.macosx"); if (!module) { printf("ERROR: pygame.macosx import FAILED\n"); return -1; } rval = PyObject_CallMethod (module, "Video_AutoInit", ""); Py_DECREF (module); if (!rval) { printf("ERROR: pygame.macosx.Video_AutoInit() call FAILED\n"); return -1; } status = PyObject_IsTrue (rval); Py_DECREF (rval); if (status != 1) return 0; #endif status = SDL_InitSubSystem (SDL_INIT_VIDEO); if (status) return 0; SDL_EnableUNICODE (1); /*we special case the video quit to last now*/ /*PyGame_RegisterQuit(PyGame_Video_AutoQuit);*/ } return 1; } /*array interface*/ static int GetArrayStruct (PyObject* obj, PyObject** cobj_p, PyArrayInterface** inter_p) { PyObject* cobj = PyObject_GetAttrString (obj, "__array_struct__"); PyArrayInterface* inter = NULL; if (cobj == NULL) { if (PyErr_ExceptionMatches (PyExc_AttributeError)) { PyErr_Clear (); PyErr_SetString (PyExc_ValueError, "no C-struct array interface"); } return -1; } #if PG_HAVE_COBJECT if (PyCObject_Check (cobj)) { inter = (PyArrayInterface *)PyCObject_AsVoidPtr (cobj); } #endif #if PG_HAVE_CAPSULE if (PyCapsule_IsValid (cobj, NULL)) { inter = (PyArrayInterface*)PyCapsule_GetPointer (cobj, NULL); } #endif if (inter == NULL || inter->two != 2 /* conditional or */) { Py_DECREF (cobj); PyErr_SetString (PyExc_ValueError, "invalid array interface"); return -1; } *cobj_p = cobj; *inter_p = inter; return 0; } static PyObject* ArrayStructAsDict (PyArrayInterface* inter_p) { PyObject *dictobj = Py_BuildValue ("{sisNsNsNsN}", "version", (int)3, "typestr", _typekind_as_str (inter_p), "shape", _shape_as_tuple (inter_p), "strides", _strides_as_tuple (inter_p), "data", _data_as_tuple (inter_p)); if (!dictobj) { return 0; } if (inter_p->flags & PAI_ARR_HAS_DESCR) { if (!inter_p->descr) { Py_DECREF (dictobj); PyErr_SetString (PyExc_ValueError, "Array struct has descr flag set" " but no descriptor"); return 0; } if (PyDict_SetItemString (dictobj, "descr", inter_p->descr)) { Py_DECREF (dictobj); return 0; } } return dictobj; } static PyObject* PgBuffer_AsArrayInterface (Py_buffer* view_p) { return Py_BuildValue ("{sisNsNsNsN}", "version", (int)3, "typestr", view_get_typestr_obj (view_p), "shape", view_get_shape_obj (view_p), "strides", view_get_strides_obj (view_p), "data", view_get_data_obj (view_p)); } static PyObject* PgBuffer_AsArrayStruct (Py_buffer* view_p) { void *cinter_p = _new_capsuleinterface (view_p); PyObject *capsule; if (!cinter_p) { return 0; } #if PY3 capsule = PyCapsule_New (cinter_p, 0, _capsule_PyMem_Free); #else capsule = PyCObject_FromVoidPtr (cinter_p, PyMem_Free); #endif if (!capsule) { PyMem_Free (cinter_p); return 0; } return capsule; } static CapsuleInterface* _new_capsuleinterface (Py_buffer *view_p) { int ndim = view_p->ndim; Py_ssize_t cinter_size; CapsuleInterface *cinter_p; int i; cinter_size = (sizeof (CapsuleInterface) + sizeof (Py_intptr_t) * (2 * ndim - 1)); cinter_p = (CapsuleInterface *)PyMem_Malloc (cinter_size); if (!cinter_p) { PyErr_NoMemory (); return 0; } cinter_p->inter.two = 2; cinter_p->inter.nd = ndim; cinter_p->inter.typekind = _as_arrayinter_typekind (view_p); cinter_p->inter.itemsize = view_p->itemsize; cinter_p->inter.flags = _as_arrayinter_flags (view_p); if (view_p->shape) { cinter_p->inter.shape = cinter_p->imem; for (i = 0; i < ndim; ++i) { cinter_p->inter.shape[i] = (Py_intptr_t)view_p->shape[i]; } } if (view_p->strides) { cinter_p->inter.strides = cinter_p->imem + ndim; for (i = 0; i < ndim; ++i) { cinter_p->inter.strides[i] = (Py_intptr_t)view_p->strides[i]; } } cinter_p->inter.data = view_p->buf; cinter_p->inter.descr = 0; return cinter_p; } #if PY3 static void _capsule_PyMem_Free (PyObject *capsule) { PyMem_Free (PyCapsule_GetPointer (capsule, 0)); } #endif static int _as_arrayinter_flags (Py_buffer* view_p) { int inter_flags = PAI_ALIGNED; /* atomic int types always aligned */ if (!view_p->readonly) { inter_flags |= PAI_WRITEABLE; } inter_flags |= _buffer_is_byteswapped (view_p) ? 0 : PAI_NOTSWAPPED; if (PyBuffer_IsContiguous (view_p, 'C')) { inter_flags |= PAI_CONTIGUOUS; } if (PyBuffer_IsContiguous (view_p, 'F')) { inter_flags |= PAI_FORTRAN; } return inter_flags; } static PyObject* view_get_typestr_obj (Py_buffer* view) { return Text_FromFormat ("%c%c%i", _as_arrayinter_byteorder (view), _as_arrayinter_typekind (view), (int)view->itemsize); } static PyObject* view_get_shape_obj (Py_buffer* view) { PyObject *shapeobj = PyTuple_New (view->ndim); PyObject *lengthobj; Py_ssize_t i; if (!shapeobj) { return 0; } for (i = 0; i < view->ndim; ++i) { lengthobj = PyInt_FromLong ((long)view->shape[i]); if (!lengthobj) { Py_DECREF (shapeobj); return 0; } PyTuple_SET_ITEM (shapeobj, i, lengthobj); } return shapeobj; } static PyObject* view_get_strides_obj (Py_buffer* view) { PyObject *shapeobj = PyTuple_New (view->ndim); PyObject *lengthobj; Py_ssize_t i; if (!shapeobj) { return 0; } for (i = 0; i < view->ndim; ++i) { lengthobj = PyInt_FromLong ((long)view->strides[i]); if (!lengthobj) { Py_DECREF (shapeobj); return 0; } PyTuple_SET_ITEM (shapeobj, i, lengthobj); } return shapeobj; } static PyObject* view_get_data_obj (Py_buffer* view) { return Py_BuildValue ("NN", PyLong_FromVoidPtr (view->buf), PyBool_FromLong ((long)view->readonly)); } static char _as_arrayinter_typekind (Py_buffer* view) { char type = view->format ? view->format[0] : 'B'; char typekind = 'V'; switch (type) { case '<': case '>': case '=': case '@': case '!': type = view->format[1]; } switch (type) { case 'b': case 'h': case 'i': case 'l': case 'q': typekind = 'i'; break; case 'B': case 'H': case 'I': case 'L': case 'Q': typekind = 'u'; break; case 'f': case 'd': typekind = 'f'; break; default: /* Unknown type */ typekind = 'V'; } return typekind; } static char _as_arrayinter_byteorder (Py_buffer* view) { char format_0 = view->format ? view->format[0] : 'B'; char byteorder; if (view->itemsize == 1) { byteorder = '|'; } else { switch (format_0) { case '<': case '>': byteorder = format_0; break; case '!': byteorder = '>'; break; case 'c': case 's': case 'p': case 'b': case 'B': byteorder = '|'; break; default: byteorder = PAI_MY_ENDIAN; } } return byteorder; } static PyObject* _shape_as_tuple (PyArrayInterface* inter_p) { PyObject *shapeobj = PyTuple_New ((Py_ssize_t)inter_p->nd); PyObject *lengthobj; Py_ssize_t i; if (!shapeobj) { return 0; } for (i = 0; i < inter_p->nd; ++i) { lengthobj = PyInt_FromLong ((long)inter_p->shape[i]); if (!lengthobj) { Py_DECREF (shapeobj); return 0; } PyTuple_SET_ITEM (shapeobj, i, lengthobj); } return shapeobj; } static PyObject* _typekind_as_str (PyArrayInterface* inter_p) { return Text_FromFormat ("%c%c%i", inter_p->itemsize > 1 ? (inter_p->flags & PAI_NOTSWAPPED ? PAI_MY_ENDIAN : PAI_OTHER_ENDIAN) : '|', inter_p->typekind, inter_p->itemsize); } static PyObject* _strides_as_tuple (PyArrayInterface* inter_p) { PyObject *stridesobj = PyTuple_New ((Py_ssize_t)inter_p->nd); PyObject *lengthobj; Py_ssize_t i; if (!stridesobj) { return 0; } for (i = 0; i < inter_p->nd; ++i) { lengthobj = PyInt_FromLong ((long)inter_p->strides[i]); if (!lengthobj) { Py_DECREF (stridesobj); return 0; } PyTuple_SET_ITEM (stridesobj, i, lengthobj); } return stridesobj; } static PyObject* _data_as_tuple (PyArrayInterface* inter_p) { long readonly = (inter_p->flags & PAI_WRITEABLE) == 0; return Py_BuildValue ("NN", PyLong_FromVoidPtr (inter_p->data), PyBool_FromLong (readonly)); } static PyObject* get_array_interface (PyObject* self, PyObject* arg) { PyObject *cobj; PyArrayInterface *inter_p; PyObject *dictobj; if (GetArrayStruct (arg, &cobj, &inter_p)) { return 0; } dictobj = ArrayStructAsDict (inter_p); Py_DECREF (cobj); return dictobj; } static int PgObject_GetBuffer (PyObject* obj, Pg_buffer* pg_view_p, int flags) { Py_buffer* view_p = (Py_buffer*)pg_view_p; PyObject* cobj = 0; PyObject* dict = 0; PyArrayInterface* inter_p = 0; char *fchar_p; int success = 0; pg_view_p->release_buffer = _release_buffer_generic; view_p->len = 0; #ifndef NDEBUG /* Allow a callback to assert that it recieved a Pg_buffer, not a Py_buffer */ flags |= PyBUF_PYGAME; #endif #if PG_ENABLE_NEWBUF if (PyObject_CheckBuffer (obj)) { if (PyObject_GetBuffer (obj, view_p, flags)) { return -1; } pg_view_p->release_buffer = PyBuffer_Release; /* Check the format is a numeric type or pad bytes */ fchar_p = view_p->format; /* Skip valid size/byte order code */ switch (*fchar_p) { case '@': case '=': case '<': case '>': case '!': ++fchar_p; break; /* default: assume it is a format type character or item count */ } /* Skip a leading digit */ switch (*fchar_p) { case '1': /* valid count for all item types */ ++fchar_p; break; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* only valid as a pad byte count */ if (*(fchar_p + 1) == 'x') { ++fchar_p; } break; /* default: assume it is a format character */ } /* verify is a format type character */ switch (*fchar_p) { case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'x': ++fchar_p; break; default: PgBuffer_Release (pg_view_p); PyErr_SetString (PyExc_ValueError, "Unsupported array element type"); return -1; } if (*fchar_p != '\0') { PgBuffer_Release (pg_view_p); PyErr_SetString (PyExc_ValueError, "Arrays of records are unsupported"); return -1; } success = 1; } #endif if (!success && GetArrayStruct (obj, &cobj, &inter_p) == 0) { if (PgArrayStruct_AsBuffer (pg_view_p, cobj, inter_p, flags)) { Py_DECREF (cobj); return -1; } Py_INCREF (obj); view_p->obj = obj; Py_DECREF (cobj); success = 1; } else if (!success) { PyErr_Clear (); } if (!success && GetArrayInterface (&dict, obj) == 0) { if (PgDict_AsBuffer (pg_view_p, dict, flags)) { Py_DECREF (dict); return -1; } Py_INCREF (obj); view_p->obj = obj; Py_DECREF (dict); success = 1; } else if (!success) { PyErr_Clear (); } if (!success) { PyErr_Format (PyExc_ValueError, "%s object does not export an array buffer", Py_TYPE (obj)->tp_name); return -1; } return 0; } static void PgBuffer_Release (Pg_buffer* pg_view_p) { assert(pg_view_p && pg_view_p->release_buffer); pg_view_p->release_buffer ((Py_buffer*)pg_view_p); } static void _release_buffer_generic (Py_buffer* view_p) { if (view_p->obj) { Py_XDECREF (view_p->obj); view_p->obj = 0; } } static void _release_buffer_array (Py_buffer* view_p) { /* This is deliberately made safe for use on an unitialized *view_p */ if (view_p->internal) { PyMem_Free (view_p->internal); view_p->internal = 0; } _release_buffer_generic (view_p); } static int _buffer_is_byteswapped (Py_buffer* view) { if (view->format) { switch (view->format[0]) { case '<': return SDL_BYTEORDER != SDL_LIL_ENDIAN; case '>': case '!': return SDL_BYTEORDER != SDL_BIG_ENDIAN; } } return 0; } static int GetArrayInterface (PyObject **dict, PyObject *obj) { PyObject* inter = PyObject_GetAttrString (obj, "__array_interface__"); if (inter == NULL) { if (PyErr_ExceptionMatches (PyExc_AttributeError)) { PyErr_Clear (); PyErr_SetString (PyExc_ValueError, "no array interface"); } return -1; } if (!PyDict_Check (inter)) { PyErr_Format (PyExc_ValueError, "expected '__array_interface__' to return a dict: got %s", Py_TYPE (dict)->tp_name); Py_DECREF (inter); return -1; } *dict = inter; return 0; } static int PgArrayStruct_AsBuffer (Pg_buffer* pg_view_p, PyObject* cobj, PyArrayInterface* inter_p, int flags) { pg_view_p->release_buffer = _release_buffer_array; if (_arraystruct_as_buffer ((Py_buffer*)pg_view_p, cobj, inter_p, flags)) { PgBuffer_Release (pg_view_p); return -1; } return 0; } static int _arraystruct_as_buffer (Py_buffer* view_p, PyObject* cobj, PyArrayInterface* inter_p, int flags) { ViewInternals* internal_p; ssize_t sz = (sizeof (ViewInternals) + (2 * inter_p->nd - 1) * sizeof (Py_ssize_t)); int readonly = inter_p->flags & PAI_WRITEABLE ? 0 : 1; Py_ssize_t i; view_p->obj = 0; view_p->internal = 0; if (PyBUF_HAS_FLAG (flags, PyBUF_WRITABLE) && readonly) { PyErr_SetString (PgExc_BufferError, "require writable buffer, but it is read-only"); return -1; } if (PyBUF_HAS_FLAG (flags, PyBUF_ANY_CONTIGUOUS)) { if (!(inter_p->flags & (PAI_CONTIGUOUS | PAI_FORTRAN))) { PyErr_SetString (PgExc_BufferError, "buffer data is not contiguous"); return -1; } } else if (PyBUF_HAS_FLAG (flags, PyBUF_C_CONTIGUOUS)) { if (!(inter_p->flags & PAI_CONTIGUOUS)) { PyErr_SetString (PgExc_BufferError, "buffer data is not C contiguous"); return -1; } } else if (PyBUF_HAS_FLAG (flags, PyBUF_F_CONTIGUOUS)) { if (!(inter_p->flags & PAI_FORTRAN)) { PyErr_SetString (PgExc_BufferError, "buffer data is not F contiguous"); return -1; } } internal_p = (ViewInternals*)PyMem_Malloc (sz); if (!internal_p) { PyErr_NoMemory (); return -1; } view_p->internal = internal_p; if (PyBUF_HAS_FLAG (flags, PyBUF_FORMAT)) { if (_arraystruct_to_format(internal_p->format, inter_p, sizeof (internal_p->format))) { return -1; } view_p->format = internal_p->format; } else { view_p->format = 0; } view_p->buf = inter_p->data; view_p->itemsize = (Py_ssize_t)inter_p->itemsize; view_p->readonly = readonly; if (PyBUF_HAS_FLAG (flags, PyBUF_ND)) { view_p->ndim = (Py_ssize_t)inter_p->nd; view_p->shape = internal_p->imem; for (i = 0; i < view_p->ndim; ++i) { view_p->shape[i] = (Py_ssize_t)inter_p->shape[i]; } } else if (inter_p->flags & PAI_CONTIGUOUS) { view_p->ndim = 0; view_p->shape = 0; } else { PyErr_SetString (PgExc_BufferError, "buffer data is not C contiguous, shape needed"); return -1; } if (PyBUF_HAS_FLAG (flags, PyBUF_STRIDES)) { view_p->strides = view_p->shape + inter_p->nd; for (i = 0; i < view_p->ndim; ++i) { view_p->strides[i] = (Py_ssize_t)inter_p->strides[i]; } } else if (inter_p->flags & (PAI_CONTIGUOUS | PAI_FORTRAN)) { view_p->strides = 0; } else { PyErr_SetString (PgExc_BufferError, "buffer is not contiguous, strides needed"); return -1; } view_p->suboffsets = 0; view_p->len = view_p->itemsize; for (i = 0; i < inter_p->nd; ++i) { view_p->len *= (Py_ssize_t)inter_p->shape[i]; } return 0; } static int _arraystruct_to_format (char* format, PyArrayInterface* inter_p, int max_format_len) { char* fchar_p = format; assert (max_format_len >= 4); switch (inter_p->typekind) { case 'i': *fchar_p = (inter_p->flags & PAI_NOTSWAPPED ? BUF_MY_ENDIAN : BUF_OTHER_ENDIAN); ++fchar_p; switch (inter_p->itemsize) { case 1: *fchar_p = 'b'; break; case 2: *fchar_p = 'h'; break; case 4: *fchar_p = 'i'; break; case 8: *fchar_p = 'q'; break; default: PyErr_Format (PyExc_ValueError, "Unsupported signed integer size %d", (int)inter_p->itemsize); return -1; } break; case 'u': *fchar_p = (inter_p->flags & PAI_NOTSWAPPED ? BUF_MY_ENDIAN : BUF_OTHER_ENDIAN); ++fchar_p; switch (inter_p->itemsize) { case 1: *fchar_p = 'B'; break; case 2: *fchar_p = 'H'; break; case 4: *fchar_p = 'I'; break; case 8: *fchar_p = 'Q'; break; default: PyErr_Format (PyExc_ValueError, "Unsupported unsigned integer size %d", (int)inter_p->itemsize); return -1; } break; case 'f': *fchar_p = (inter_p->flags & PAI_NOTSWAPPED ? BUF_MY_ENDIAN : BUF_OTHER_ENDIAN); ++fchar_p; switch (inter_p->itemsize) { case 4: *fchar_p = 'f'; break; case 8: *fchar_p = 'd'; break; default: PyErr_Format (PyExc_ValueError, "Unsupported float size %d", (int)inter_p->itemsize); return -1; } break; case 'V': if (inter_p->itemsize > 9) { PyErr_Format (PyExc_ValueError, "Unsupported void size %d", (int)inter_p->itemsize); return -1; } switch (inter_p->itemsize) { case 1: *fchar_p = '1'; break; case 2: *fchar_p = '2'; break; case 3: *fchar_p = '3'; break; case 4: *fchar_p = '4'; break; case 5: *fchar_p = '5'; break; case 6: *fchar_p = '6'; break; case 7: *fchar_p = '7'; break; case 8: *fchar_p = '8'; break; case 9: *fchar_p = '9'; break; default: PyErr_Format (PyExc_ValueError, "Unsupported void size %d", (int)inter_p->itemsize); return -1; } ++fchar_p; *fchar_p = 'x'; break; default: PyErr_Format (PyExc_ValueError, "Unsupported value type '%c'", (int)inter_p->typekind); return -1; } ++fchar_p; *fchar_p = '\0'; return 0; } static int PgDict_AsBuffer (Pg_buffer* pg_view_p, PyObject* dict, int flags) { PyObject* pyshape = PyDict_GetItemString (dict, "shape"); PyObject* pytypestr = PyDict_GetItemString (dict, "typestr"); PyObject* pydata = PyDict_GetItemString (dict, "data"); PyObject* pystrides = PyDict_GetItemString (dict, "strides"); if (_pyshape_check (pyshape)) { return -1; } if (_pytypestr_check (pytypestr)) { return -1; } if (_pydata_check (pydata)) { return -1; } if (_pystrides_check (pystrides)) { return -1; } pg_view_p->release_buffer = _release_buffer_array; if (_pyvalues_as_buffer ((Py_buffer*)pg_view_p, flags, pytypestr, pyshape, pydata, pystrides)) { PgBuffer_Release (pg_view_p); return -1; } return 0; } static int _pyshape_check(PyObject* op) { if (!op) { PyErr_SetString (PyExc_ValueError, "required 'shape' item is missing"); return -1; } if (!_is_inttuple (op)) { PyErr_SetString (PyExc_ValueError, "expected a tuple of ints for 'shape'"); return -1; } if (PyTuple_GET_SIZE (op) == 0) { PyErr_SetString (PyExc_ValueError, "expected 'shape' to be at least one-dimensional"); return -1; } return 0; } static int _pytypestr_check(PyObject *op) { if (!op) { PyErr_SetString (PyExc_ValueError, "required 'typestr' item is missing"); return -1; } if (PyUnicode_Check (op)) { if (PyUnicode_GET_SIZE (op) != 3) { PyErr_SetString (PyExc_ValueError, "expected 'typestr' to be length 3"); return -1; } } else if (Bytes_Check (op)) { if (Bytes_GET_SIZE (op) != 3) { PyErr_SetString (PyExc_ValueError, "expected 'typestr' to be length 3"); return -1; } } else { PyErr_SetString (PyExc_ValueError, "expected a string for 'typestr'"); return -1; } return 0; } static int _pydata_check(PyObject *op) { PyObject* item; if (!op) { PyErr_SetString (PyExc_ValueError, "required 'data' item is missing"); return -1; } if (!PyTuple_Check (op)) { PyErr_SetString (PyExc_ValueError, "expected a tuple for 'data'"); return -1; } if (PyTuple_GET_SIZE (op) != 2) { PyErr_SetString (PyExc_ValueError, "expected a length 2 tuple for 'data'"); return -1; } item = PyTuple_GET_ITEM (op, 0); if (!INT_CHECK (item)) { PyErr_SetString (PyExc_ValueError, "expected an int for item 0 of 'data'"); return -1; } return 0; } static int _pystrides_check (PyObject *op) { if (op && !_is_inttuple (op) /* Conditional && */) { PyErr_SetString (PyExc_ValueError, "expected a tuple of ints for 'strides'"); return -1; } return 0; } static int _is_inttuple (PyObject* op) { Py_ssize_t i; Py_ssize_t n; PyObject* ip; if (!PyTuple_Check (op)) { return 0; } n = PyTuple_GET_SIZE (op); for (i = 0; i != n; ++i) { ip = PyTuple_GET_ITEM (op, i); if (!INT_CHECK (ip)) { return 0; } } return 1; } static int _pyvalues_as_buffer(Py_buffer* view_p, int flags, PyObject* pytypestr, PyObject* pyshape, PyObject* pydata, PyObject* pystrides) { Py_ssize_t ndim = PyTuple_GET_SIZE (pyshape); ViewInternals* internal_p; ssize_t sz; int i; assert (ndim > 0); view_p->obj = 0; view_p->internal = 0; if (pystrides && PyTuple_GET_SIZE (pystrides) != ndim /* Cond. && */) { PyErr_SetString (PyExc_ValueError, "'shape' and 'strides' are not the same length"); return -1; } view_p->ndim = ndim; view_p->buf = PyLong_AsVoidPtr (PyTuple_GET_ITEM (pydata, 0)); if (!view_p->buf && PyErr_Occurred ()) { return -1; } view_p->readonly = PyObject_IsTrue (PyTuple_GET_ITEM (pydata, 1)); if (view_p->readonly == -1) { return -1; } if (PyBUF_HAS_FLAG (flags, PyBUF_WRITABLE) && view_p->readonly) { PyErr_SetString (PgExc_BufferError, "require writable buffer, but it is read-only"); return -1; } sz = sizeof (ViewInternals) + (2 * ndim - 1) * sizeof (Py_ssize_t); internal_p = (ViewInternals*)PyMem_Malloc (sz); if (!internal_p) { PyErr_NoMemory (); return -1; } view_p->internal = internal_p; view_p->format = internal_p->format; view_p->shape = internal_p->imem; view_p->strides = internal_p->imem + ndim; if (_pytypestr_as_format (pytypestr, view_p->format, &view_p->itemsize)) { return -1; } if (_pyinttuple_as_ssize_arr (pyshape, view_p->shape)) { return -1; } if (pystrides) { if (_pyinttuple_as_ssize_arr (pystrides, view_p->strides)) { return -1; } } else if (PyBUF_HAS_FLAG (flags, PyBUF_STRIDES)) { view_p->strides[ndim - 1] = view_p->itemsize; for (i = ndim - 1; i != 0; --i) { view_p->strides[i - 1] = view_p->shape[i] * view_p->strides[i]; } } else { view_p->strides = 0; } view_p->suboffsets = 0; view_p->len = view_p->itemsize; for (i = 0; i < view_p->ndim; ++i) { view_p->len *= view_p->shape[i]; } if (PyBUF_HAS_FLAG (flags, PyBUF_ANY_CONTIGUOUS)) { if (!PyBuffer_IsContiguous (view_p, 'A')) { PyErr_SetString (PgExc_BufferError, "buffer data is not contiguous"); return -1; } } else if (PyBUF_HAS_FLAG (flags, PyBUF_C_CONTIGUOUS)) { if (!PyBuffer_IsContiguous (view_p, 'C')) { PyErr_SetString (PgExc_BufferError, "buffer data is not C contiguous"); return -1; } } else if (PyBUF_HAS_FLAG (flags, PyBUF_F_CONTIGUOUS)) { if (!PyBuffer_IsContiguous (view_p, 'F')) { PyErr_SetString (PgExc_BufferError, "buffer data is not F contiguous"); return -1; } } if (!PyBUF_HAS_FLAG (flags, PyBUF_STRIDES)) { if (PyBuffer_IsContiguous (view_p, 'C')) { view_p->strides = 0; } else { PyErr_SetString (PgExc_BufferError, "buffer data is not C contiguous, strides needed"); return -1; } } if (!PyBUF_HAS_FLAG (flags, PyBUF_ND)) { if (PyBuffer_IsContiguous (view_p, 'C')) { view_p->shape = 0; } else { PyErr_SetString (PgExc_BufferError, "buffer data is not C contiguous, shape needed"); return -1; } } if (!PyBUF_HAS_FLAG (flags, PyBUF_FORMAT)) { view_p->format = 0; } if (!PyBUF_HAS_FLAG (flags, PyBUF_ND)) { view_p->ndim = 0; } return 0; } static int _pyinttuple_as_ssize_arr (PyObject *tp, Py_ssize_t* arr) { Py_ssize_t i; Py_ssize_t n = PyTuple_GET_SIZE (tp); for (i = 0; i != n; ++i) { arr[i] = PyInt_AsSsize_t (PyTuple_GET_ITEM (tp, i)); if (arr[i] == -1 && PyErr_Occurred ()) { return -1; } } return 0; } static int _pytypestr_as_format (PyObject* sp, char* format, Py_ssize_t* itemsize_p) { const char* typestr; char *fchar_p = format; int is_swapped = 0; Py_ssize_t itemsize = 0; if (PyUnicode_Check (sp)) { sp = PyUnicode_AsASCIIString (sp); if (!sp) { return -1; } } else { Py_INCREF (sp); } typestr = Bytes_AsString (sp); switch (typestr[0]) { case PAI_MY_ENDIAN: case '|': break; case PAI_OTHER_ENDIAN: is_swapped = 1; break; default: PyErr_Format (PyExc_ValueError, "unsupported typestr %s", typestr); Py_DECREF (sp); return -1; } switch (typestr[1]) { case 'i': case 'u': switch (typestr[2]) { case '1': *fchar_p = 'B'; itemsize = 1; break; case '2': *fchar_p = is_swapped ? BUF_OTHER_ENDIAN : BUF_MY_ENDIAN; ++fchar_p; *fchar_p = 'H'; itemsize = 2; break; case '3': *fchar_p = '3'; ++fchar_p; *fchar_p = 'x'; itemsize = 3; break; case '4': *fchar_p = is_swapped ? BUF_OTHER_ENDIAN : BUF_MY_ENDIAN; ++fchar_p; *fchar_p = 'I'; itemsize = 4; break; case '5': *fchar_p = '5'; ++fchar_p; *fchar_p = 'x'; itemsize = 5; break; case '6': *fchar_p = '6'; ++fchar_p; *fchar_p = 'x'; itemsize = 6; break; case '7': *fchar_p = '7'; ++fchar_p; *fchar_p = 'x'; itemsize = 7; break; case '8': *fchar_p = is_swapped ? BUF_OTHER_ENDIAN : BUF_MY_ENDIAN; ++fchar_p; *fchar_p = 'Q'; itemsize = 8; break; case '9': *fchar_p = '9'; ++fchar_p; *fchar_p = 'x'; itemsize = 9; break; default: PyErr_Format (PyExc_ValueError, "unsupported typestr %s", typestr); Py_DECREF (sp); return -1; } if (typestr[1] == 'i') { /* This leaves 'x' uneffected. */ *fchar_p = tolower(*fchar_p); } break; case 'f': *fchar_p = is_swapped ? BUF_OTHER_ENDIAN : BUF_MY_ENDIAN; ++fchar_p; switch (typestr[2]) { case '4': *fchar_p = 'f'; itemsize = 4; break; case '8': *fchar_p = 'd'; itemsize = 8; break; default: PyErr_Format (PyExc_ValueError, "unsupported typestr %s", typestr); Py_DECREF (sp); return -1; } break; case 'V': switch (typestr[2]) { case '1': *fchar_p = '1'; itemsize = 1; break; case '2': *fchar_p = '2'; itemsize = 2; break; case '3': *fchar_p = '3'; itemsize = 3; break; case '4': *fchar_p = '4'; itemsize = 4; break; case '5': *fchar_p = '5'; itemsize = 5; break; case '6': *fchar_p = '6'; itemsize = 6; break; case '7': *fchar_p = '7'; itemsize = 7; break; case '8': *fchar_p = '8'; itemsize = 8; break; case '9': *fchar_p = '9'; itemsize = 9; break; default: PyErr_Format (PyExc_ValueError, "unsupported typestr %s", typestr); Py_DECREF (sp); return -1; } ++fchar_p; *fchar_p = 'x'; break; default: PyErr_Format (PyExc_ValueError, "unsupported typestr %s", typestr); Py_DECREF (sp); return -1; } Py_DECREF (sp); ++fchar_p; *fchar_p = '\0'; *itemsize_p = itemsize; return 0; } /*error signal handlers (replacing SDL parachute)*/ static void pygame_parachute (int sig) { #ifdef HAVE_SIGNAL_H char* signaltype; signal (sig, SIG_DFL); switch (sig) { case SIGSEGV: signaltype = "(pygame parachute) Segmentation Fault"; break; #ifdef SIGBUS #if SIGBUS != SIGSEGV case SIGBUS: signaltype = "(pygame parachute) Bus Error"; break; #endif #endif #ifdef SIGFPE case SIGFPE: signaltype = "(pygame parachute) Floating Point Exception"; break; #endif #ifdef SIGQUIT case SIGQUIT: signaltype = "(pygame parachute) Keyboard Abort"; break; #endif default: signaltype = "(pygame parachute) Unknown Signal"; break; } _quit (); Py_FatalError (signaltype); #endif } static int fatal_signals[] = { SIGSEGV, #ifdef SIGBUS SIGBUS, #endif #ifdef SIGFPE SIGFPE, #endif #ifdef SIGQUIT SIGQUIT, #endif 0 /*end of list*/ }; static int parachute_installed = 0; static void install_parachute (void) { #ifdef HAVE_SIGNAL_H int i; void (*ohandler)(int); if (parachute_installed) return; parachute_installed = 1; /* Set a handler for any fatal signal not already handled */ for (i = 0; fatal_signals[i]; ++i) { ohandler = (void(*)(int))signal (fatal_signals[i], pygame_parachute); if (ohandler != SIG_DFL) signal (fatal_signals[i], ohandler); } #if defined(SIGALRM) && defined(HAVE_SIGACTION) {/* Set SIGALRM to be ignored -- necessary on Solaris */ struct sigaction action, oaction; /* Set SIG_IGN action */ memset (&action, 0, (sizeof action)); action.sa_handler = SIG_IGN; sigaction (SIGALRM, &action, &oaction); /* Reset original action if it was already being handled */ if (oaction.sa_handler != SIG_DFL) sigaction (SIGALRM, &oaction, NULL); } #endif #endif return; } static void uninstall_parachute (void) { #ifdef HAVE_SIGNAL_H int i; void (*ohandler)(int); if (!parachute_installed) return; parachute_installed = 0; /* Remove a handler for any fatal signal handled */ for (i = 0; fatal_signals[i]; ++i) { ohandler = (void(*)(int))signal (fatal_signals[i], SIG_DFL); if (ohandler != pygame_parachute) signal (fatal_signals[i], ohandler); } #endif } /* bind functions to python */ static PyObject* do_segfault (PyObject* self) { //force crash *((int*)1) = 45; memcpy ((char*)2, (char*)3, 10); Py_RETURN_NONE; } static PyMethodDef _base_methods[] = { { "init", (PyCFunction) init, METH_NOARGS, DOC_PYGAMEINIT }, { "quit", (PyCFunction) quit, METH_NOARGS, DOC_PYGAMEQUIT }, { "register_quit", register_quit, METH_O, DOC_PYGAMEREGISTERQUIT }, { "get_error", (PyCFunction) get_error, METH_NOARGS, DOC_PYGAMEGETERROR }, { "set_error", (PyCFunction) set_error, METH_VARARGS, DOC_PYGAMESETERROR }, { "get_sdl_version", (PyCFunction) get_sdl_version, METH_NOARGS, DOC_PYGAMEGETSDLVERSION }, { "get_sdl_byteorder", (PyCFunction) get_sdl_byteorder, METH_NOARGS, DOC_PYGAMEGETSDLBYTEORDER }, { "get_array_interface", (PyCFunction) get_array_interface, METH_O, "return an array struct interface as an interface dictionary" }, { "segfault", (PyCFunction) do_segfault, METH_NOARGS, "crash" }, { NULL, NULL, 0, NULL } }; MODINIT_DEFINE(base) { static int is_loaded = 0; PyObject *module, *dict, *apiobj; PyObject *atexit, *atexit_register = NULL, *quit, *rval; PyObject *PyExc_SDLError; int ecode; static void* c_api[PYGAMEAPI_BASE_NUMSLOTS]; #if PY3 static struct PyModuleDef _module = { PyModuleDef_HEAD_INIT, "base", "", -1, _base_methods, NULL, NULL, NULL, NULL }; #endif if (!is_loaded) { /* import need modules. Do this first so if there is an error the module is not loaded. */ atexit = PyImport_ImportModule ("atexit"); if (!atexit) { MODINIT_ERROR; } atexit_register = PyObject_GetAttrString (atexit, "register"); Py_DECREF (atexit); if (!atexit_register) { MODINIT_ERROR; } } /* create the module */ #if PY3 module = PyModule_Create (&_module); #else module = Py_InitModule3 (MODPREFIX "base", _base_methods, DOC_PYGAME); #endif if (module == NULL) { MODINIT_ERROR; } dict = PyModule_GetDict (module); /* create the exceptions */ PyExc_SDLError = PyErr_NewException ("pygame.error", PyExc_RuntimeError, NULL); if (PyExc_SDLError == NULL) { Py_XDECREF (atexit_register); DECREF_MOD (module); MODINIT_ERROR; } ecode = PyDict_SetItemString (dict, "error", PyExc_SDLError); Py_DECREF (PyExc_SDLError); if (ecode) { Py_XDECREF (atexit_register); DECREF_MOD (module); MODINIT_ERROR; } #if PG_ENABLE_NEWBUF PgExc_BufferError = PyErr_NewException ("pygame.BufferError", PyExc_BufferError, NULL); #else PgExc_BufferError = PyErr_NewException ("pygame.BufferError", PyExc_RuntimeError, NULL); #endif if (PyExc_SDLError == NULL) { Py_XDECREF (atexit_register); DECREF_MOD (module); MODINIT_ERROR; } ecode = PyDict_SetItemString (dict, "BufferError", PgExc_BufferError); if (ecode) { Py_DECREF (PgExc_BufferError); Py_XDECREF (atexit_register); DECREF_MOD (module); MODINIT_ERROR; } /* export the c api */ #if PYGAMEAPI_BASE_NUMSLOTS != 19 #error export slot count mismatch #endif c_api[0] = PyExc_SDLError; c_api[1] = PyGame_RegisterQuit; c_api[2] = IntFromObj; c_api[3] = IntFromObjIndex; c_api[4] = TwoIntsFromObj; c_api[5] = FloatFromObj; c_api[6] = FloatFromObjIndex; c_api[7] = TwoFloatsFromObj; c_api[8] = UintFromObj; c_api[9] = UintFromObjIndex; c_api[10] = PyGame_Video_AutoQuit; c_api[11] = PyGame_Video_AutoInit; c_api[12] = RGBAFromObj; c_api[13] = PgBuffer_AsArrayInterface; c_api[14] = PgBuffer_AsArrayStruct; c_api[15] = PgObject_GetBuffer; c_api[16] = PgBuffer_Release; c_api[17] = PgDict_AsBuffer; c_api[18] = PgExc_BufferError; apiobj = encapsulate_api (c_api, "base"); if (apiobj == NULL) { Py_XDECREF (atexit_register); Py_DECREF (PgExc_BufferError); DECREF_MOD (module); MODINIT_ERROR; } ecode = PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj); Py_DECREF (apiobj); if (ecode) { Py_XDECREF (atexit_register); Py_DECREF (PgExc_BufferError); DECREF_MOD (module); MODINIT_ERROR; } if (PyModule_AddIntConstant (module, "HAVE_NEWBUF", PG_ENABLE_NEWBUF)) { Py_XDECREF (atexit_register); Py_DECREF (PgExc_BufferError); DECREF_MOD (module); MODINIT_ERROR; } if (!is_loaded) { /*some intialization*/ quit = PyObject_GetAttrString (module, "quit"); if (quit == NULL) { /* assertion */ Py_DECREF (atexit_register); Py_DECREF (PgExc_BufferError); DECREF_MOD (module); MODINIT_ERROR; } rval = PyObject_CallFunctionObjArgs (atexit_register, quit, NULL); Py_DECREF (atexit_register); Py_DECREF (quit); if (rval == NULL) { DECREF_MOD (module); Py_DECREF (PgExc_BufferError); MODINIT_ERROR; } Py_DECREF (rval); Py_AtExit (atexit_quit); #ifdef HAVE_SIGNAL_H install_parachute (); #endif #ifdef MS_WIN32 SDL_RegisterApp ("pygame", 0, GetModuleHandle (NULL)); #endif #if defined(macintosh) #if(!defined(__MWERKS__) && !TARGET_API_MAC_CARBON) SDL_InitQuickDraw (&qd); #endif #endif } is_loaded = 1; MODINIT_RETURN (module); }
25.85551
80
0.553815
[ "object", "shape" ]
6d325c6a2e5f2047bd880b91a8922d8999717cf3
1,430
h
C
tests/framework/ge_running_env/include/ge_running_env/ge_running_env_faker.h
mindspore-ai/graphengine
460406cbd691b963d125837f022be5d8abd1a637
[ "Apache-2.0" ]
207
2020-03-28T02:12:50.000Z
2021-11-23T18:27:45.000Z
tests/framework/ge_running_env/include/ge_running_env/ge_running_env_faker.h
mindspore-ai/graphengine
460406cbd691b963d125837f022be5d8abd1a637
[ "Apache-2.0" ]
4
2020-04-17T07:32:44.000Z
2021-06-26T04:55:03.000Z
tests/framework/ge_running_env/include/ge_running_env/ge_running_env_faker.h
mindspore-ai/graphengine
460406cbd691b963d125837f022be5d8abd1a637
[ "Apache-2.0" ]
13
2020-03-28T02:52:26.000Z
2021-07-03T23:12:54.000Z
/** * Copyright 2021 Huawei Technologies 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 H99C11FC4_700E_4D4D_B073_7808FA88BEBC #define H99C11FC4_700E_4D4D_B073_7808FA88BEBC #include "ge_running_env/fake_engine.h" #include "fake_ns.h" #include "opskernel_manager/ops_kernel_manager.h" #include "register/ops_kernel_builder_registry.h" FAKE_NS_BEGIN struct GeRunningEnvFaker { GeRunningEnvFaker(); GeRunningEnvFaker &Reset(); GeRunningEnvFaker &Install(const EnvInstaller &); GeRunningEnvFaker &InstallDefault(); static void BackupEnv(); private: void flush(); private: std::map<string, vector<OpInfo>> &op_kernel_info_; std::map<string, OpsKernelInfoStorePtr> &ops_kernel_info_stores_; std::map<string, GraphOptimizerPtr> &ops_kernel_optimizers_; std::map<string, OpsKernelBuilderPtr> &ops_kernel_builders_; }; FAKE_NS_END #endif /* H99C11FC4_700E_4D4D_B073_7808FA88BEBC */
31.086957
75
0.776923
[ "vector" ]
6d33dc01f25251837938ae596b0172a2ceef33cf
959
c
C
llvm-gcc-4.2-2.9/libjava/testsuite/libjava.jni/iface.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
1
2016-04-09T02:58:13.000Z
2016-04-09T02:58:13.000Z
llvm-gcc-4.2-2.9/libjava/testsuite/libjava.jni/iface.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
llvm-gcc-4.2-2.9/libjava/testsuite/libjava.jni/iface.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include <iface.h> void check (JNIEnv *); void check(JNIEnv *env) { if ((*env)->ExceptionCheck(env) != JNI_FALSE) { fprintf(stderr, "UNEXPECTED EXCEPTION\n"); exit(-1); } } void Java_iface_doCalls (JNIEnv *env, jobject self, jobject other) { jclass iface_class, comparable_class; jmethodID iface_meth, comparable_meth; jvalue args[1]; iface_class = (*env)->FindClass(env, "iface"); check (env); comparable_class = (*env)->FindClass (env, "mycomp"); check (env); iface_meth = (*env)->GetMethodID (env, iface_class, "compareTo", "(Ljava/lang/Object;)I"); check (env); comparable_meth = (*env)->GetMethodID (env, comparable_class, "compareTo", "(Ljava/lang/Object;)I"); check (env); args[0].l = other; (*env)->CallObjectMethodA (env, self, iface_meth, args); check (env); (*env)->CallObjectMethodA (env, self, comparable_meth, args); check (env); }
23.390244
76
0.650678
[ "object" ]
6d3c12e873297cfe33d54db0b25f402777becd86
3,774
h
C
include/agi/framebuffer.h
magnusl/agi
9a38917583bc29cdcac0a1f1a23590b1661f8d9d
[ "Apache-2.0" ]
null
null
null
include/agi/framebuffer.h
magnusl/agi
9a38917583bc29cdcac0a1f1a23590b1661f8d9d
[ "Apache-2.0" ]
null
null
null
include/agi/framebuffer.h
magnusl/agi
9a38917583bc29cdcac0a1f1a23590b1661f8d9d
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include <stdint.h> #include <array> #include <assert.h> #include <iostream> namespace agi { using Points = std::vector<uint8_t>; enum Color { kBlack = 0, kBlue = 1, kGreen = 2, kCyan = 3, kRed = 4, kMagenta = 5, kBrown = 6, kLightgrey = 7, kDarkGrey = 8, kLightBlue = 9, kLightGreen = 10, kLightCyan = 11, kLightRed = 12, kLightMagenta = 13, kYellow = 14, kWhite = 15 }; /** * \class Framebuffer */ class Framebuffer { public: enum { kWidth = 160, kHeight = 200, kPixelPitch = 320 }; Framebuffer(); void Clear(); void SetPictureColor(uint8_t); void DisablePictureDraw(); void SetPriorityColor(uint8_t); void DisablePriorityDraw(); void DrawYCorner(const Points&); void DrawXCorner(const Points&); void AbsoluteLine(const Points&); void RelativeLine(const Points&); void Fill(uint8_t x, uint8_t y); void Display(uint8_t row, uint8_t col, const char* text); void ClearLines(uint8_t start, uint8_t stop, uint8_t color); const std::array<uint8_t, 64000>& GetPictureBuffer() const noexcept { return picture_; } const std::array<uint8_t, 32000>& GetPriorityBuffer() const noexcept { return priority_; } /** * \brief Sets a pixel if the new pixel has higher priority */ inline void SetPixelIfHigherPriority(uint8_t x, uint8_t y, uint8_t color, uint8_t priority) { if ((x < kWidth) && (y < kHeight)) { if (priority >= GetPriorityPixel(x, y)) { const size_t colorOffset = (y * kPixelPitch) + (x * 2); const size_t priorityOffset = (y * kWidth) + x; picture_[colorOffset] = color; picture_[colorOffset + 1] = color; priority_[priorityOffset] = priority; } } } inline void SetHiDPIPixel(size_t x, size_t y, uint8_t color) { if ((x < kPixelPitch) && (y < kHeight)) { size_t offset = (y * kPixelPitch) + x; picture_[offset] = color; } } private: inline void SetPixel(uint8_t x, uint8_t y) { if ((x < kWidth) && (y < kHeight)) { if (pictureDraw_) { size_t offset = (y * kPixelPitch) + (x * 2); picture_[offset] = pictureColor_; picture_[offset + 1] = pictureColor_; } if (priorityDraw_) { size_t offset = (y * kWidth) + x; priority_[offset] = priorityColor_; } } } inline uint8_t GetPicturePixel(uint8_t x, uint8_t y) const noexcept { if ((x < kWidth) && (y < kHeight)) { size_t offset = (y * kPixelPitch) + (x * 2); return picture_[offset]; } else { return 4; } } inline uint8_t GetPriorityPixel(uint8_t x, uint8_t y) const noexcept { if ((x < kWidth) && (y < kHeight)) { size_t offset = (y * kWidth) + x; return priority_[offset]; } else { return 4; } } bool CanFill(uint8_t x, uint8_t y); void DrawLine(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2); private: // the actual visible pixels std::array<uint8_t, 64000> picture_; // the priority screen std::array<uint8_t, 32000> priority_; // the picture color uint8_t pictureColor_; // the priority color uint8_t priorityColor_; // flags uint8_t pictureDraw_ : 1; uint8_t priorityDraw_ : 1; }; } // namespace agi
26.577465
97
0.540806
[ "vector" ]
6d50f917e1a1b6564ea2174fb8b99feef09a1491
5,960
h
C
utils/AdmissibilityChecker.h
Multi-Agent-Research-Group/hog2
544d7c0e933fd69025944a0a3abcf9a40e59f0be
[ "MIT" ]
5
2020-08-03T09:43:26.000Z
2022-01-11T08:28:30.000Z
utils/AdmissibilityChecker.h
Multi-Agent-Research-Group/hog2
544d7c0e933fd69025944a0a3abcf9a40e59f0be
[ "MIT" ]
null
null
null
utils/AdmissibilityChecker.h
Multi-Agent-Research-Group/hog2
544d7c0e933fd69025944a0a3abcf9a40e59f0be
[ "MIT" ]
7
2017-07-31T13:01:28.000Z
2021-05-16T10:15:49.000Z
//============================================================================== // AdmissibilityChecker //============================================================================== #ifndef __AdmissibilityChecker__ #define __AdmissibilityChecker__ #include <stdint.h> #include <stdio.h> #include <vector> #include <algorithm> #include <string> #include <queue> #include <limits> #include <iostream> #include <string.h> #include "AStarOpenClosed.h" #include "NN.h" template <typename state, typename action, typename environment> class AdmissibilityChecker { private: struct Container{ Container():depth(0){} Container(int d, state const& ss):depth(d),s(ss){} int depth; state s; }; struct Comparator{ bool operator()(const AStarOpenClosedData<Container> &ci1, const AStarOpenClosedData<Container> &ci2) const { return fgreater(ci1.g+ci1.h, ci2.g+ci2.h); } }; public: bool check(environment& env, std::vector<state> startStates, double radius, int depthLimit){ double gap(0.0); unsigned total(0); //std::cout << "x<-matrix(c(0,0,0,0,0),1,5);y<-c(0)\n"; for(state const& start: startStates){ AStarOpenClosed<Container,Comparator> q; env.setStart(start); uint64_t hash(env.GetStateHash(start)); Container temp(0,start); q.AddOpenNode(temp,hash,0.0,0.0,0); while(q.OpenSize()){ uint64_t nodeid(q.Close()); double G(q.Lookup(nodeid).g); env.setGoal(q.Lookup(nodeid).data.s); Container node(q.Lookup(nodeid).data); double h(env.HCost(start,node.s)); gap=std::max(gap,h); if(fgreater(h,G)){ std::cout << "FAIL: HCost: " << start<<"-->"<<node.s <<"=" << h << " Greater than actual: "<< G << std::endl; std::vector<state> thePath; do{ thePath.push_back(q.Lookup(nodeid).data.s); nodeid=q.Lookup(nodeid).parentID; }while(q.Lookup(nodeid).parentID!=nodeid); state const* prev(0); double t(0.0); for(auto const& s: thePath){ std::cout << s; if(prev){std::cout << " " << env.GCost(*prev,s)<<"="<<(t+=env.GCost(*prev,s));} std::cout << "\n"; prev=&s; } return false; } if(node.depth > depthLimit || env.GetRadius(start,node.s)>radius) continue; std::vector<state> succ; env.GetSuccessors(node.s,succ); for(state s: succ){ uint64_t hash(env.GetStateHash(s)); uint64_t theID; switch(q.Lookup(hash,theID)){ case kClosedList: case kOpenList: if(fgreater(q.Lookup(theID).g,G+env.GCost(node.s,s))){ q.Lookup(theID).g=G+env.GCost(node.s,s); } break; case kNotFound: default: Container current(node.depth+1,s); q.AddOpenNode(current,hash,G+env.GCost(node.s,s),0,nodeid); break; } } } total+=q.ClosedSize(); } std::cout << "Forward admissibility check PASSED on depth/radius of " << depthLimit << "/" << radius << ", checked " << total << " states.\n Largest gap: " << gap <<std::endl; return true; } bool checkReverse(environment& env, std::vector<state> startStates, double radius, int depthLimit){ double gap(0.0); unsigned total(0); //std::cout << "x<-matrix(c(0,0,0,0,0),1,5);y<-c(0)\n"; for(state const& start: startStates){ AStarOpenClosed<Container,Comparator> q; env.setGoal(start); uint64_t hash(env.GetStateHash(start)); Container temp(0,start); q.AddOpenNode(temp,hash,0.0,0.0,0); while(q.OpenSize()){ uint64_t nodeid(q.Close()); env.setStart(q.Lookup(nodeid).data.s); double G(q.Lookup(nodeid).g); Container node(q.Lookup(nodeid).data); double h(env.HCost(node.s,start)); if(fgreater(h,G)){ std::cout << "FAIL: HCost: " << node.s<<"-->"<<start <<"=" << h << " Greater than actual: "<< G << std::endl; std::vector<state> thePath; do{ thePath.push_back(q.Lookup(nodeid).data.s); nodeid=q.Lookup(nodeid).parentID; }while(q.Lookup(nodeid).parentID!=nodeid); std::reverse(thePath.begin(),thePath.end()); state const* prev(0); double t(0.0); for(auto const& s: thePath){ std::cout << s; if(prev){std::cout << " " << env.GCost(*prev,s)<<"="<<(t+=env.GCost(*prev,s));} std::cout << "\n"; prev=&s; } return false; } if(node.depth > depthLimit || env.GetRadius(node.s,start)>radius) continue; std::vector<state> succ; env.GetReverseSuccessors(node.s,succ); for(state s: succ){ uint64_t hash(env.GetStateHash(s)); uint64_t theID; switch(q.Lookup(hash,theID)){ case kClosedList: case kOpenList: if(fgreater(q.Lookup(theID).g,G+env.GCost(s,node.s))){ q.Lookup(theID).g=G+env.GCost(s,node.s); } break; case kNotFound: default: Container current(node.depth+1,s); q.AddOpenNode(current,hash,G+env.GCost(s,node.s),0,nodeid); break; } } } total+=q.ClosedSize(); } std::cout << "Reverse admissibility check PASSED on depth/radius of " << depthLimit << "/" << radius << ", checked " << total << " states.\n Largest gap: " << gap <<std::endl; return true; } private: NN* model=0; }; # endif
34.853801
181
0.513423
[ "vector", "model" ]
6d5313d325262b2bcc6ac2c93b8674f858ab1be4
3,626
h
C
modules/core/include/statismo/core/ReducedVarianceModelBuilder.h
skn123/statismo-1
a380f33cf070d1c4ba624db8b0c6d946d2aecabf
[ "BSD-3-Clause" ]
14
2020-04-28T17:24:01.000Z
2021-07-20T11:54:59.000Z
modules/core/include/statismo/core/ReducedVarianceModelBuilder.h
latimagine/statismo
a380f33cf070d1c4ba624db8b0c6d946d2aecabf
[ "BSD-3-Clause" ]
8
2020-01-22T09:05:00.000Z
2021-06-29T10:10:24.000Z
modules/core/include/statismo/core/ReducedVarianceModelBuilder.h
latimagine/statismo
a380f33cf070d1c4ba624db8b0c6d946d2aecabf
[ "BSD-3-Clause" ]
6
2020-03-11T19:41:06.000Z
2021-09-07T12:57:20.000Z
/* * This file is part of the statismo library. * * Author: Marcel Luethi (marcel.luethi@unibas.ch) * * Copyright (c) 2011 University of Basel * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the project's author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * 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. * */ #ifndef __STATIMO_CORE_REDUCED_VARIANCE_MODEL_BUILDER_H_ #define __STATIMO_CORE_REDUCED_VARIANCE_MODEL_BUILDER_H_ #include "statismo/core/Config.h" #include "statismo/core/CommonTypes.h" #include "statismo/core/DataManager.h" #include "statismo/core/ModelBuilder.h" #include "statismo/core/ModelInfo.h" #include "statismo/core/Utils.h" #include "statismo/core/StatisticalModel.h" #include <vector> #include <memory> namespace statismo { /** * \brief Create a StatisticalModel which retains only the specified total variance * \ingroup ModelBuilders * \ingroup Core */ template <typename Representer> class ReducedVarianceModelBuilder : public ModelBuilderBase<Representer, ReducedVarianceModelBuilder<Representer>> { public: using Superclass = ModelBuilderBase<Representer, ReducedVarianceModelBuilder<Representer>>; using StatisticalModelType = typename Superclass::StatisticalModelType; friend typename Superclass::ObjectFactoryType; /** * \brief Build a new model from the given model, which retains only the leading principal components * \param model statistical model * \param numberOfPrincipalComponents number of components to keep */ UniquePtrType<StatisticalModelType> BuildNewModelWithLeadingComponents(const StatisticalModelType * model, unsigned numberOfPrincipalComponents) const; /** * \brief Build a new model from the given model, which retains only the specified variance * \param model statistical model. * \param totalVariance fraction of the variance to be retained */ UniquePtrType<StatisticalModelType> BuildNewModelWithVariance(const StatisticalModelType * model, double totalVariance) const; [[deprecated]] UniquePtrType<StatisticalModelType> BuildNewModelFromModel(const StatisticalModelType * model, double totalVariance) const; private: ReducedVarianceModelBuilder() = default; }; } // namespace statismo #include "ReducedVarianceModelBuilder.hxx" #endif
36.26
117
0.785163
[ "vector", "model" ]
6d64225feeed0746252fd14c7574ad1ed2e19076
9,973
c
C
ext/image_convolution.c
ender672/ruby-vips
020a38bf92ff18b286fcce0993ec035d25a4610b
[ "MIT" ]
3
2015-11-05T01:31:54.000Z
2016-05-31T00:01:24.000Z
ext/image_convolution.c
ender672/ruby-vips
020a38bf92ff18b286fcce0993ec035d25a4610b
[ "MIT" ]
null
null
null
ext/image_convolution.c
ender672/ruby-vips
020a38bf92ff18b286fcce0993ec035d25a4610b
[ "MIT" ]
null
null
null
#include "ruby_vips.h" #include "image.h" #include "mask.h" #include "image_convolution.h" /* * call-seq: * im.conv(mask) -> image * * Convolve *self* with <i>mask</i>. The output image always has the same band format * as *self*. Non-complex images only. * * Each output pixel is calculated as sigma[i]{pixel[i] * <i>mask</i>[i]} / * scale + offset, where scale and offset are part of <i>mask</i>. For integer * *self*, the division by scale includes round-to-nearest. * * <i>mask</i> can be an array in which case scale defaults to 1 and offset * defaults to zero. <i>mask</i> can also be a Mask object. */ VALUE img_conv(VALUE obj, VALUE m) { DOUBLEMASK *dmask; INTMASK *imask; GetImg(obj, data, im); OutImg2(obj, m, new, data_new, im_new); mask_arg2mask(m, &imask, &dmask); if (imask) { if (im_conv(im, im_new, imask)) vips_lib_error(); } else if (im_conv_f(im, im_new, dmask)) vips_lib_error(); return new; } /* * call-seq: * im.convsep(mask) -> image * * Perform a separable convolution of *self* with <i>mask</i> using integer * arithmetic. * * <i>mask</i> must be 1xn or nx1 elements. * * The output image always has the same band format as *self*. Non-complex * images only. * * The image is convolved twice: once with <i>mask</i> and then again with * <i>mask</i> rotated by 90 degrees. This is much faster for certain types of * mask (gaussian blur, for example) than doing a full 2D convolution. * * Each output pixel is calculated as sigma[i]{pixel[i] * <i>mask</i>[i]} / * scale + offset, where scale and offset are part of <i>mask</i>. For integer * *self*, the division by scale includes round-to-nearest. * * <i>mask</i> can be an array in which case scale defaults to 1 and offset * defaults to zero. <i>mask</i> can also be a Mask object. */ VALUE img_convsep(VALUE obj, VALUE mask) { DOUBLEMASK *dmask; INTMASK *imask; GetImg(obj, data, im); OutImg2(obj, mask, new, data_new, im_new); mask_arg2mask(mask, &imask, &dmask); if(imask) { if (im_convsep(im, im_new, imask)) vips_lib_error(); } else if (im_convsep_f(im, im_new, dmask)) vips_lib_error(); return new; } /* * call-seq: * im.compass(mask) -> image * * *self* is convolved 8 times with <i>mask</i>, each time <i>mask</i> is * rotated by 45 degrees. Each output pixel is the largest absolute value of * the 8 convolutions. * * <i>mask</i> can be an array or a Mask object. */ VALUE img_compass(VALUE obj, VALUE mask) { INTMASK *imask; GetImg(obj, data, im); OutImg2(obj, mask, new, data_new, im_new); mask_arg2mask(mask, &imask, NULL); if (im_compass(im, im_new, imask)) vips_lib_error(); return new; } /* * call-seq: * im.gradient(mask) -> image * * *self* is convolved with <i>mask</i> and with <i>mask</i> after a 90 degree * rotation. The result is the sum of the absolute value of the two * convolutions. * * <i>mask</i> can be an array or a Mask object. */ VALUE img_gradient(VALUE obj, VALUE mask) { INTMASK *imask; GetImg(obj, data, im); OutImg2(obj, mask, new, data_new, im_new); mask_arg2mask(mask, &imask, NULL); if (im_gradient(im, im_new, imask) ) vips_lib_error(); return new; } /* * call-seq: * im.lindetect(mask) -> image * * *self* is convolved four times with @mask, each time @mask is rotated by 45 * degrees. Each output pixel is the largest absolute value of the four * convolutions. * * <i>mask</i> can be an array or a Mask object. */ VALUE img_lindetect(VALUE obj, VALUE mask) { INTMASK *imask; GetImg(obj, data, im); OutImg2(obj, mask, new, data_new, im_new); mask_arg2mask(mask, &imask, NULL); if (im_lindetect(im, im_new, imask)) vips_lib_error(); return new; } /* * call-seq: * im.sharpen(mask_size, x1, y2, y3, m1, m2) -> image * * Selectively sharpen the L channel of a LAB image. Works for :LABQ coding and * LABS images. * * The operation performs a gaussian blur of size <i>mask_size</i> and * subtract from *self* to generate a high-frequency signal. This signal is * passed through a lookup table formed from the five parameters and added back * to *self*. * * * For printing, we recommend the following settings: * * mask_size == 7 * x1 == 1.5 * y2 == 20 (don't brighten by more than 20 L*) * y3 == 50 (can darken by up to 50 L*) * * m1 == 1 (some sharpening in flat areas) * m2 == 2 (more sharpening in jaggy areas) * * If you want more or less sharpening, we suggest you just change the * <i>m1</i> and <i>m2</i> parameters. * * The <i>mask_size</i> parameter changes the width of the fringe and can be * adjusted according to the output printing resolution. As an approximate * guideline, use 3 for 4 pixels/mm (CRT display resolution), 5 for 8 * pixels/mm, 7 for 12 pixels/mm and 9 for 16 pixels/mm (300 dpi == 12 * pixels/mm). These figures refer to the image raster, not the half-tone * resolution. */ VALUE img_sharpen(VALUE obj, VALUE mask_size, VALUE x1, VALUE y2, VALUE y3, VALUE m1, VALUE m2) { GetImg(obj, data, im); OutImg(obj, new, data_new, im_new); if (im_sharpen(im, im_new, NUM2INT(mask_size), NUM2DBL(x1), NUM2DBL(y2), NUM2DBL(y3), NUM2DBL(m1), NUM2DBL(m2))) vips_lib_error(); return new; } /* * call-seq: * im.grad_x -> image * * Find horizontal differences between adjacent pixels. * * Generates an image where the value of each pixel is the difference between * it and the pixel to its right. The output has the same height as the input * and one pixel less width. One-band integer formats only. The result is * always band format :INT. * * This operation is much faster than (though equivalent to) Image#conv with * the mask [[-1, 1]]. */ VALUE img_grad_x(VALUE obj) { RUBY_VIPS_UNARY(im_grad_x); } /* * call-seq: * im.grad_y -> image * * Find vertical differences between adjacent pixels. * * Generates an image where the value of each pixel is the difference between * it and the pixel below it. The output has the same width as the input * and one pixel less height. One-band integer formats only. The result is * always band format :INT. * * This operation is much faster than (though equivalent to) Image#conv with * the mask [[-1], [1]]. */ VALUE img_grad_y(VALUE obj) { RUBY_VIPS_UNARY(im_grad_y); } /* * call-seq: * im.fastcor(other_image) -> image * * Calculate a fast correlation surface. * * <i>other_image</i> is placed at every position in *self* and the sum of * squares of differences calculated. One-band, 8-bit unsigned images only. The * output image is always band format :UINT. <i>other_image</i> must be smaller * than or equal to *self*. The output image is the same size as the input. */ VALUE img_fastcor(VALUE obj, VALUE obj2) { RUBY_VIPS_BINARY(im_fastcor); } /* * call-seq: * im.spcor(other_image) -> image * * Calculate a correlation surface. * * <i>other_image</i> is placed at every position in *self* and the correlation * coefficient calculated. One-band, 8 or 16-bit images only. *self* and * <i>other_image</i> must have the same band format.. The output image is * always band format :FLOAT. <i>other_image</i> must be smaller than or equal * to *self*. The output image is the same size as *self*. * * The correlation coefficient is calculated as: * * sumij (ref(i,j)-mean(ref))(inkl(i,j)-mean(inkl)) * c(k,l) = ------------------------------------------------ * sqrt(sumij (ref(i,j)-mean(ref))^2) * * sqrt(sumij (inkl(i,j)-mean(inkl))^2) * * where inkl is the area of *self* centred at position (k,l). * * from Niblack "An Introduction to Digital Image Processing", Prentice/Hall, * pp 138. */ VALUE img_spcor(VALUE obj, VALUE obj2) { RUBY_VIPS_BINARY(im_spcor); } /* * call-seq: * im.gradcor(other_image) -> image * * Calculate a correlation surface. * * <i>other_image</i> is placed at every position in *self* and a correlation * coefficient calculated. One-band, integer images only. *self* and * <i>other_image</i> must have the same band format. The output image is * always band format :FLOAT. <i>other_image</i> must be smaller than *self*. * The output image is the same size as the input. * * The method takes the gradient images of the two images then takes the * dot-product correlation of the two vector images. The vector expression of * this method is my (tcv) own creation. It is equivalent to the complex-number * method of: * * ARGYRIOU, V. et al. 2003. Estimation of sub-pixel motion using gradient * cross correlation. Electronics Letters, 39 (13). */ VALUE img_gradcor(VALUE obj, VALUE obj2) { RUBY_VIPS_BINARY(im_gradcor); } /* * call-seq: * im.contrast_surface(half_win_size, spacing) -> image * * Generate an image where the value of each pixel represents the contrast * within a window of half_win_size from the corresponsing point in the input * image. Sub-sample by a factor of spacing. */ VALUE img_contrast_surface(VALUE obj, VALUE half_win_size, VALUE spacing) { GetImg(obj, data, im); OutImg(obj, new, data_new, im_new); if (im_contrast_surface(im, im_new, NUM2INT(half_win_size), NUM2INT(spacing))) vips_lib_error(); return new; } /* * call-seq: * im.addgnoise(sigma) -> image * * Add gaussian noise with mean 0 and variance sigma to *self*. The noise is * generated by averaging 12 random numbers, see page 78, PIETGEN, 1989. */ VALUE img_addgnoise(VALUE obj, VALUE sigma) { GetImg(obj, data, im); OutImg(obj, new, data_new, im_new); if (im_addgnoise(im, im_new, NUM2INT(sigma))) vips_lib_error(); return new; }
26.80914
86
0.656573
[ "object", "vector" ]
6d67c773f9e5be7d7de731727aa31f15a4a70291
4,509
h
C
ryanwc/crypto_lib/uint64_bits.h
ryanwc/classix-crypto
e65ffb96c8a4d93ed0041357ea2347d38f43abc8
[ "MIT" ]
null
null
null
ryanwc/crypto_lib/uint64_bits.h
ryanwc/classix-crypto
e65ffb96c8a4d93ed0041357ea2347d38f43abc8
[ "MIT" ]
null
null
null
ryanwc/crypto_lib/uint64_bits.h
ryanwc/classix-crypto
e65ffb96c8a4d93ed0041357ea2347d38f43abc8
[ "MIT" ]
null
null
null
#ifndef UINT64_BITS_H__ #define UINT64_BITS_H__ #include <iostream> #include <memory> #include <vector> namespace CustomCrypto { // Represent a source string as bits in a series of uint64_t. // Assumes total number of bits represented by given source string fits in int data type. // (Dev note: could refactor for factory pattern and/or subclassing, but seems OK for now.) class Uint64Bits { public: Uint64Bits(std::string sourceString, std::string sourceType, bool preserveLeadingZeros = false); Uint64Bits(std::unique_ptr<uint64_t[]> bits, int numBits, int numUint64s, int numPaddingBits, bool preserveLeadingZeros = false); ~Uint64Bits(); // Get the total number of bits this Uint64Bits represents int GetNumBits() const; // number of padding bits in the "last" uint64_t int GetNumPaddingBits() const; // Get the total number of Uint64s used for the internal bit representation. // Could be more than strictly needed to facilitate, e.g., base64 operations. int GetNumUint64s() const; // get whether leading zeroes (if any) were preserved when constructing these bits. bool GetAnyLeadingZeroesWerePreserved() const; // Get a base64 string representation of the bits std::string GetBase64Representation(); // Get a hex string representation of the bits std::string GetHexRepresentation(); // Get a bit string representation of the bits std::string GetBitRepresentation(); // Get a pointer to an array of uint64_t which is a representation of these bits. // Right aligned, so padded with zeroes in most signifcant bits. Use GetNumBits() // and GetNumUint64s() to calculate how much padding. It's a copy of the internal // representation, client is sole owner. std::unique_ptr<uint64_t[]> GetBits() const; // Get XOR of this with some other bits. std::unique_ptr<Uint64Bits> XOR(const Uint64Bits & otherBits, bool preserveLeadingZeroes = false); // TODO // Comparator(otherBits, bool takeIntoAccountLeadingZeroes); private: // whether we preserved the leading zeroes when this was initially created // e.g. if this was true, bits constructed from hex string "0001" would be represented like // 0b0000 0000 0000 0001, but if false, then represented like // 0b1 bool _preserveLeadingZeroes; // the hex representation of these bits char* _hexRepresentation; // the base64 representaton of these bits char* _base64Representation; // the bit string representation of these bits char* _bitRepresentation; // the number of bits this represents int _numBits; // the total number of Uint64s used for the internal bit representation. // could be more than strictly needed to facilitate, e.g., base64 operations. int _numUint64s; // number of padding bits in the "last" uint64_t int _numPaddingBits; // the internal representation of the bits uint64_t* _bits; // sets internal vars from source string/type void _initInternalsFromSource(std::string sourceString, std::string sourceType); // sets the internal bits representation from the source string (treating as hex) void _setInternalsFromHex(std::string sourceString); // sets the internal bits representation from the source string (treating as base64) void _setInternalsFromBase64(std::string sourceString); void _setInternalsFromBits(std::string sourceString); // convenience func used during translations void _setBase64CharFromBits(int bitArrayStartPos, int uintStartPos, int base64Index); // set the base64 string representation from internal bits void _setBase64StrFromBits(); // set the bit string representation from internal bits void _setBitStrFromBits(); // set the hex string representation from internal bits void _setHexStrFromBits(); // get a base64 char from the given int char _getBase64CharFromBitVal(uint8_t bitVal); }; } #endif // UINT64_BITS_H__
41.75
141
0.65092
[ "vector" ]
6d67d984d745abe06f9fb90d733a51d52b49e690
4,250
h
C
src/esp/physics/PhysicsObjectBase.h
rutadesai/habitat-sim
851dc67c8ea3dd380f03542da73d627dc4ec9685
[ "MIT" ]
null
null
null
src/esp/physics/PhysicsObjectBase.h
rutadesai/habitat-sim
851dc67c8ea3dd380f03542da73d627dc4ec9685
[ "MIT" ]
null
null
null
src/esp/physics/PhysicsObjectBase.h
rutadesai/habitat-sim
851dc67c8ea3dd380f03542da73d627dc4ec9685
[ "MIT" ]
null
null
null
// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #ifndef ESP_PHYSICS_PHYSICSOBJECTBASE_H_ #define ESP_PHYSICS_PHYSICSOBJECTBASE_H_ #include <Corrade/Containers/Optional.h> #include <Corrade/Containers/Reference.h> #include "esp/assets/ResourceManager.h" /** @file * @brief Class @ref esp::physics::PhysicsObjectBase is the base class for any * physics-based construct, and holds basic accounting info and accessors, along * with scene node access. */ namespace esp { namespace physics { /** @brief Motion type of a @ref RigidObject. Defines its treatment by the simulator and operations which can be performed on it. */ enum class MotionType { /** * Refers to an error (such as a query to non-existing object) or an * unknown/unspecified value. */ UNDEFINED = -1, /** * The object is not expected to move and should not allow kinematic updates. * Likely treated as static collision geometry. See @ref * RigidObjectType::SCENE. */ STATIC, /** * The object is expected to move kinematically, but is not simulated. Default * behavior of @ref RigidObject with no physics simulator defined. */ KINEMATIC, /** * The object is simulated and can, but should not be, updated kinematically . * Default behavior of @ref RigidObject with a physics simulator defined. See * @ref BulletRigidObject. */ DYNAMIC }; class PhysicsObjectBase : public Magnum::SceneGraph::AbstractFeature3D { public: PhysicsObjectBase(scene::SceneNode* bodyNode, int objectId, const assets::ResourceManager& resMgr) : Magnum::SceneGraph::AbstractFeature3D(*bodyNode), objectId_(objectId), resMgr_(resMgr) {} ~PhysicsObjectBase() override = default; /** * @brief Get the scene node being attached to. */ scene::SceneNode& node() { return object(); } const scene::SceneNode& node() const { return object(); } // Overloads to avoid confusion scene::SceneNode& object() { return static_cast<scene::SceneNode&>( Magnum::SceneGraph::AbstractFeature3D::object()); } const scene::SceneNode& object() const { return static_cast<const scene::SceneNode&>( Magnum::SceneGraph::AbstractFeature3D::object()); } /** * @brief Get the @ref MotionType of the object. See @ref setMotionType. * @return The object's current @ref MotionType. */ MotionType getMotionType() const { return objectMotionType_; } /** * @brief Set the @ref MotionType of the object. If the object is @ref * ObjectType::SCENE it can only be @ref MotionType::STATIC. If the object is * @ref ObjectType::OBJECT is can also be set to @ref MotionType::KINEMATIC. * Only if a dervied @ref PhysicsManager implementing dynamics is in use can * the object be set to @ref MotionType::DYNAMIC. * @param mt The desirved @ref MotionType. */ virtual void setMotionType(MotionType mt) = 0; /** * @brief Get object's ID */ int getObjectID() const { return objectId_; } /** * @brief Object name, to faciliate access. */ const std::string getObjectName() const { return objectName_; } void setObjectName(const std::string& name) { objectName_ = name; } /** * @brief Get a const reference to this physica object's root SceneNode for * info query purposes. * @return Const reference to the object's scene node. */ const scene::SceneNode& getSceneNode() const { return node(); } protected: /** @brief An assignable name for this object. */ std::string objectName_; /** @brief The @ref MotionType of the object. Determines what operations can * be performed on this object. */ MotionType objectMotionType_{MotionType::UNDEFINED}; /** @brief Access for the object to its own PhysicsManager id. */ int objectId_; /** @brief Reference to the ResourceManager for internal access to the * object's asset data. */ const assets::ResourceManager& resMgr_; public: ESP_SMART_POINTERS(PhysicsObjectBase) }; // class PhysicsObjectBase } // namespace physics } // namespace esp #endif // ESP_PHYSICS_PHYSICSOBJECTBASE_H_
29.929577
80
0.698588
[ "geometry", "object" ]
cd1797de95f7e997373eeb55ed9597386281fe93
1,246
h
C
docker/water/epanet/tags/ooten/ooten/ONValve.h
liujiamingustc/phd
4f815a738abad43531d02ac66f5bd0d9a1def52a
[ "Apache-2.0" ]
3
2021-01-06T03:01:18.000Z
2022-03-21T03:02:55.000Z
docker/water/epanet/tags/ooten/ooten/ONValve.h
liujiamingustc/phd
4f815a738abad43531d02ac66f5bd0d9a1def52a
[ "Apache-2.0" ]
null
null
null
docker/water/epanet/tags/ooten/ooten/ONValve.h
liujiamingustc/phd
4f815a738abad43531d02ac66f5bd0d9a1def52a
[ "Apache-2.0" ]
null
null
null
/* ******************************************************************* OOTEN: Object Oriented Toolkit for Epanet ONVALVE.H - Definition of OOTEN ONValve class VERSION: 1.00beta DATE: 13 June 2003 AUTHOR: JE van Zyl Rand Afrikaans University Johannesburg South Africa jevz@ing.rau.ac.za ******************************************************************* */ //--------------------------------------------------------------------------- #ifndef ONValveH #define ONValveH //--------------------------------------------------------------------------- #include "ONLink.h" using namespace std; class ONValve: public ONLink { public: //constructors and destructors ONValve(void); ONValve(int enIndex, ONSystem* parent, ONNode* startNode, ONNode* endNode); ONValve(const ONValve &o); virtual ONLink* clone(void); virtual ~ONValve(void); //methods virtual elementTpe type(void) const; bool initialSetting(void) const; void setInitialSetting(bool setting); bool setting(void) const; void setSetting(bool setting); }; #endif
26.510638
83
0.453451
[ "object" ]
cd1c3b8fe5dbcec0f9b85a6cd08e688af7b08bf5
5,371
h
C
slack/types.h
DEGoodmanWilson/plaidapi
ae993f45865811b8480e74466c3de88954f25b69
[ "MIT" ]
29
2015-12-21T21:46:10.000Z
2021-05-03T19:09:27.000Z
slack/types.h
DEGoodmanWilson/cpp-slack-client
ae993f45865811b8480e74466c3de88954f25b69
[ "MIT" ]
4
2016-07-10T04:22:25.000Z
2018-02-08T18:33:40.000Z
slack/types.h
DEGoodmanWilson/cpp-slack-client
ae993f45865811b8480e74466c3de88954f25b69
[ "MIT" ]
7
2017-08-16T17:00:11.000Z
2019-09-20T05:53:31.000Z
// // engine // // Copyright © 2015–2016 D.E. Goodman-Wilson. All rights reserved. // #pragma once #include <slack/fwd.h> #include <slack/set_option.h> #include <string> #include <vector> #include <map> #include <slack/optional.hpp> #define SLACK_MAKE_STRING_LIKE(x) class x : public std::string \ { \ public: \ x() = default; \ x(const x &rhs) = default; \ x(x &&rhs) = default; \ x &operator=(const x &rhs) = default; \ x &operator=(x &&rhs) = default; \ x(const char *raw_string) : std::string(raw_string) {} \ x(const char *raw_string, size_t length) : std::string(raw_string, length) {} \ explicit x(size_t to_fill, char character) : std::string(to_fill, character) {} \ x(const std::string &std_string) : std::string(std_string) {} \ x(const std::string &std_string, size_t position, size_t length = std::string::npos) \ : std::string(std_string, position, length) {} \ explicit x(std::initializer_list<char> il) : std::string(il) {} \ template<class InputIterator> \ explicit x(InputIterator first, InputIterator last) \ : std::string(first, last) {} \ } #define SLACK_MAKE_BOOL_LIKE(x) class x \ { \ public: \ x() = default; \ x(const x &rhs) = default; \ x(x &&rhs) = default; \ x &operator=(const x &rhs) = default; \ x &operator=(x &&rhs) = default; \ x(bool new_val) : value{new_val} {} \ x & operator=(bool && new_value) {std::swap(value, new_value); return *this;} \ x & operator=(const bool & new_value) {value = new_value; return *this;} \ explicit operator bool() {return value;} \ private: \ bool value; \ } #define SLACK_MAKE_LONG_LONG_LIKE(x) class x\ { \ public: \ x() = default; \ x(const x &rhs) = default; \ x(x &&rhs) = default; \ x &operator=(const x &rhs) = default; \ x &operator=(x &&rhs) = default; \ x(long long new_val) : value{new_val} {} \ x & operator=(long long && new_value) {std::swap(value, new_value); return *this;} \ x & operator=(const long long & new_value) {value = new_value; return *this;} \ explicit operator long long() {return value;} \ private: \ long long value; \ } namespace slack { //TODO NONE of these things should be just strings. SLACK_MAKE_STRING_LIKE(team_id); SLACK_MAKE_STRING_LIKE(user_id); SLACK_MAKE_STRING_LIKE(bot_id); SLACK_MAKE_STRING_LIKE(app_id); SLACK_MAKE_STRING_LIKE(ts); SLACK_MAKE_STRING_LIKE(channel_id); SLACK_MAKE_STRING_LIKE(verification_token); SLACK_MAKE_STRING_LIKE(access_token); SLACK_MAKE_STRING_LIKE(scope); struct profile { profile() = default; template<class json> profile(const json &parsed_json); std::string first_name; std::string last_name; std::string real_name; std::string email; std::string skype; std::string phone; std::map<uint16_t, std::string> images; std::experimental::optional<struct bot_id> bot_id; std::experimental::optional<app_id> api_app_id; }; struct user { user() = default; template<class json> user(const json &parsed_json); user_id id; std::string name; bool deleted; std::string color; //TODO would be nice to have a color class! slack::profile profile; bool is_admin; bool is_onwer; bool is_primary_owner; bool is_restricted; bool is_ultra_restricted; bool is_bot; bool has_2fa; }; //This is the data type that is returned from a slash command struct command { command() = default; command(const std::map<std::string, std::string> &params); std::string token; // gIkuvaNzQIHg97ATvDxqgjtO slack::team_id team_id; // T0001 std::string team_domain; // example slack::channel_id channel_id; // C2147483705 std::string channel_name; // test slack::user_id user_id; // U2147483697 std::string user_name; // Steve std::string command_name; // /weather std::string text; // 94070 std::string response_url; // https://hooks.slack.com/commands/1234/5678 }; struct reaction { reaction() = default; template<class json> reaction(const json &parsed_json); std::string name; int64_t count; std::vector<user_id> users; }; struct message { message() = default; template<class json> message(const json &parsed_json); slack::channel_id channel; slack::user_id user; std::string text; slack::ts ts; bool is_starred; std::vector<channel_id> pinned_to; std::vector<reaction> reactions; }; struct channel { channel() = default; template<class json> channel(const json &parsed_json); struct topic { std::string value; user_id creator; int64_t last_set; }; struct purpose { std::string value; user_id creator; int64_t last_set; }; channel_id id; std::string name; bool is_channel; int64_t created; user_id creator; bool is_archived; bool is_general; std::vector<user_id> members; topic topic; purpose purpose; bool is_member; ts last_read; slack::message latest; int64_t unread_count; int64_t unread_display_count; }; struct token { slack::team_id team_id; slack::access_token access_token; slack::user_id user_id; slack::access_token bot_token; slack::user_id bot_user_id; slack::bot_id bot_id; }; }
23.765487
90
0.653696
[ "vector" ]
cd2104f63ada4494464541696198fa4292712f76
13,644
c
C
Dmf/Modules.Library.Tests/Dmf_Tests_AlertableSleep.c
williambernardet/DMF
225c72d5434400409487db3803328a0e51c3a7cf
[ "MIT" ]
130
2018-08-07T11:36:38.000Z
2019-04-12T00:17:37.000Z
Dmf/Modules.Library.Tests/Dmf_Tests_AlertableSleep.c
QPC-database/DMF
3a532fd30abf1f37d8d02c2f9ee84e065200c8fa
[ "MIT" ]
32
2019-05-20T17:04:44.000Z
2022-03-30T20:40:18.000Z
Dmf/Modules.Library.Tests/Dmf_Tests_AlertableSleep.c
QPC-database/DMF
3a532fd30abf1f37d8d02c2f9ee84e065200c8fa
[ "MIT" ]
50
2019-06-06T09:20:13.000Z
2022-03-23T04:23:23.000Z
/*++ Copyright (c) Microsoft Corporation. All rights reserved. Module Name: Dmf_Tests_AlertableSleep.c Abstract: Functional tests for Dmf_AlertableSleep Module. Environment: Kernel-mode Driver Framework User-mode Driver Framework --*/ // DMF and this Module's Library specific definitions. // #include "DmfModule.h" #include "DmfModules.Library.Tests.h" #include "DmfModules.Library.Tests.Trace.h" #if defined(DMF_INCLUDE_TMH) #include "Dmf_Tests_AlertableSleep.tmh" #endif /////////////////////////////////////////////////////////////////////////////////////////////////////// // Module Private Enumerations and Structures /////////////////////////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////////////////////////// // Module Private Context /////////////////////////////////////////////////////////////////////////////////////////////////////// // typedef struct _DMF_CONTEXT_Tests_AlertableSleep { // AlertableSleep Module. (Test Module) // DMFMODULE DmfModuleAlertableSleepTest; // AlertableSleep Module. (Internal Use) // DMFMODULE DmfModuleAlertableSleepInternal; // Thread that sleep. // DMFMODULE DmfModuleThreadSleep; // Thread that interrupts. // DMFMODULE DmfModuleThreadInterrupt; // Indicates Module has started started running or is stopping. // When it is stopping, all sleeps are interrupted. // BOOLEAN Closing; } DMF_CONTEXT_Tests_AlertableSleep; // This macro declares the following function: // DMF_CONTEXT_GET() // DMF_MODULE_DECLARE_CONTEXT(Tests_AlertableSleep) // This Module has no Config. // DMF_MODULE_DECLARE_NO_CONFIG(Tests_AlertableSleep) /////////////////////////////////////////////////////////////////////////////////////////////////////// // DMF Module Support Code /////////////////////////////////////////////////////////////////////////////////////////////////////// // #define TIMEOUT_MS_MAXIMUM 15000 #pragma code_seg("PAGE") _Function_class_(EVT_DMF_Thread_Function) _IRQL_requires_max_(PASSIVE_LEVEL) static VOID Tests_AlertableSleep_WorkThreadSleep( _In_ DMFMODULE DmfModuleThread ) { DMFMODULE dmfModule; DMF_CONTEXT_Tests_AlertableSleep* moduleContext; ULONG timeout; NTSTATUS ntStatus; PAGED_CODE(); dmfModule = DMF_ParentModuleGet(DmfModuleThread); moduleContext = DMF_CONTEXT_GET(dmfModule); timeout = TestsUtility_GenerateRandomNumber(0, TIMEOUT_MS_MAXIMUM); // Wait for a while. The wait may or may not be interrupted based on what the // other thread does. // ntStatus = DMF_AlertableSleep_Sleep(moduleContext->DmfModuleAlertableSleepTest, 0, timeout); // Reset from previous iteration. // DMF_AlertableSleep_ResetForReuse(moduleContext->DmfModuleAlertableSleepTest, 0); // Repeat the test, until stop is signaled or the function stopped because the // driver is stopping. // if ((! DMF_Thread_IsStopPending(DmfModuleThread)) && (! moduleContext->Closing)) { DMF_Thread_WorkReady(DmfModuleThread); } TestsUtility_YieldExecution(); } #pragma code_seg() #pragma code_seg("PAGE") _Function_class_(EVT_DMF_Thread_Function) _IRQL_requires_max_(PASSIVE_LEVEL) static VOID Tests_AlertableSleep_WorkThreadInterrupt( _In_ DMFMODULE DmfModuleThread ) { DMFMODULE dmfModule; DMF_CONTEXT_Tests_AlertableSleep* moduleContext; ULONG timeout; NTSTATUS ntStatus; PAGED_CODE(); dmfModule = DMF_ParentModuleGet(DmfModuleThread); moduleContext = DMF_CONTEXT_GET(dmfModule); timeout = TestsUtility_GenerateRandomNumber(0, TIMEOUT_MS_MAXIMUM); // Wait for a while. // TraceEvents(TRACE_LEVEL_INFORMATION, DMF_TRACE, "Waiting to interrupt..."); ntStatus = DMF_AlertableSleep_Sleep(moduleContext->DmfModuleAlertableSleepInternal, 0, timeout); if (NT_SUCCESS(ntStatus)) { // Reset for next time. // TraceEvents(TRACE_LEVEL_INFORMATION, DMF_TRACE, "RESET Wait to interrupt..."); DMF_AlertableSleep_ResetForReuse(moduleContext->DmfModuleAlertableSleepInternal, 0); } else { TraceEvents(TRACE_LEVEL_INFORMATION, DMF_TRACE, "INTERRUPTED Wait to interrupt..."); } // Abort the current sleep. // TraceEvents(TRACE_LEVEL_INFORMATION, DMF_TRACE, "Interrupt..."); DMF_AlertableSleep_Abort(moduleContext->DmfModuleAlertableSleepTest, 0); // Repeat the test, until stop is signaled or the function stopped because the // driver is stopping. // if ((! DMF_Thread_IsStopPending(DmfModuleThread)) && (! moduleContext->Closing)) { DMF_Thread_WorkReady(DmfModuleThread); } TestsUtility_YieldExecution(); } #pragma code_seg() /////////////////////////////////////////////////////////////////////////////////////////////////////// // WDF Module Callbacks /////////////////////////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////////////////////////// // DMF Module Callbacks /////////////////////////////////////////////////////////////////////////////////////////////////////// // #pragma code_seg("PAGE") _Function_class_(DMF_Open) _IRQL_requires_max_(PASSIVE_LEVEL) _Must_inspect_result_ static NTSTATUS DMF_Tests_AlertableSleep_Open( _In_ DMFMODULE DmfModule ) /*++ Routine Description: Initialize an instance of a DMF Module of type Test_AlertableSleep. Arguments: DmfModule - This Module's handle. Return Value: STATUS_SUCCESS --*/ { NTSTATUS ntStatus; DMF_CONTEXT_Tests_AlertableSleep* moduleContext; PAGED_CODE(); FuncEntry(DMF_TRACE); moduleContext = DMF_CONTEXT_GET(DmfModule); // Start the threads. // ntStatus = DMF_Thread_Start(moduleContext->DmfModuleThreadSleep); ntStatus = DMF_Thread_Start(moduleContext->DmfModuleThreadInterrupt); // Tell the threads they have work to do. // DMF_Thread_WorkReady(moduleContext->DmfModuleThreadSleep); DMF_Thread_WorkReady(moduleContext->DmfModuleThreadInterrupt); FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus); return ntStatus; } #pragma code_seg() #pragma code_seg("PAGE") _Function_class_(DMF_Close) _IRQL_requires_max_(PASSIVE_LEVEL) static VOID DMF_Tests_AlertableSleep_Close( _In_ DMFMODULE DmfModule ) /*++ Routine Description: Close an instance of a DMF Module of type Test_AlertableSleep. Arguments: DmfModule - This Module's handle. Return Value: STATUS_SUCCESS --*/ { DMF_CONTEXT_Tests_AlertableSleep* moduleContext; PAGED_CODE(); FuncEntry(DMF_TRACE); moduleContext = DMF_CONTEXT_GET(DmfModule); moduleContext->Closing = TRUE; DMF_AlertableSleep_Abort(moduleContext->DmfModuleAlertableSleepInternal, 0); DMF_AlertableSleep_Abort(moduleContext->DmfModuleAlertableSleepTest, 0); DMF_Thread_Stop(moduleContext->DmfModuleThreadSleep); DMF_Thread_Stop(moduleContext->DmfModuleThreadInterrupt); FuncExitVoid(DMF_TRACE); } #pragma code_seg() #pragma code_seg("PAGE") _Function_class_(DMF_ChildModulesAdd) _IRQL_requires_max_(PASSIVE_LEVEL) VOID DMF_Tests_AlertableSleep_ChildModulesAdd( _In_ DMFMODULE DmfModule, _In_ DMF_MODULE_ATTRIBUTES* DmfParentModuleAttributes, _In_ PDMFMODULE_INIT DmfModuleInit ) /*++ Routine Description: Configure and add the required Child Modules to the given Parent Module. Arguments: DmfModule - The given Parent Module. DmfParentModuleAttributes - Pointer to the parent DMF_MODULE_ATTRIBUTES structure. DmfModuleInit - Opaque structure to be passed to DMF_DmfModuleAdd. Return Value: None --*/ { DMF_MODULE_ATTRIBUTES moduleAttributes; DMF_CONTEXT_Tests_AlertableSleep* moduleContext; DMF_CONFIG_Thread moduleConfigThread; DMF_CONFIG_AlertableSleep moduleConfigAlertableSleep; UNREFERENCED_PARAMETER(DmfParentModuleAttributes); PAGED_CODE(); FuncEntry(DMF_TRACE); moduleContext = DMF_CONTEXT_GET(DmfModule); // AlertableSleep (Test) // --------------------- // DMF_CONFIG_AlertableSleep_AND_ATTRIBUTES_INIT(&moduleConfigAlertableSleep, &moduleAttributes); moduleConfigAlertableSleep.EventCount = 1; DMF_DmfModuleAdd(DmfModuleInit, &moduleAttributes, WDF_NO_OBJECT_ATTRIBUTES, &moduleContext->DmfModuleAlertableSleepTest); // AlertableSleep (Internal) // ------------------------- // DMF_CONFIG_AlertableSleep_AND_ATTRIBUTES_INIT(&moduleConfigAlertableSleep, &moduleAttributes); moduleConfigAlertableSleep.EventCount = 1; DMF_DmfModuleAdd(DmfModuleInit, &moduleAttributes, WDF_NO_OBJECT_ATTRIBUTES, &moduleContext->DmfModuleAlertableSleepInternal); // Thread (Sleeps) // --------------- // DMF_CONFIG_Thread_AND_ATTRIBUTES_INIT(&moduleConfigThread, &moduleAttributes); moduleConfigThread.ThreadControlType = ThreadControlType_DmfControl; moduleConfigThread.ThreadControl.DmfControl.EvtThreadWork = Tests_AlertableSleep_WorkThreadSleep; DMF_DmfModuleAdd(DmfModuleInit, &moduleAttributes, WDF_NO_OBJECT_ATTRIBUTES, &moduleContext->DmfModuleThreadSleep); // Thread (Interrupts) // ------------------- // DMF_CONFIG_Thread_AND_ATTRIBUTES_INIT(&moduleConfigThread, &moduleAttributes); moduleConfigThread.ThreadControlType = ThreadControlType_DmfControl; moduleConfigThread.ThreadControl.DmfControl.EvtThreadWork = Tests_AlertableSleep_WorkThreadInterrupt; DMF_DmfModuleAdd(DmfModuleInit, &moduleAttributes, WDF_NO_OBJECT_ATTRIBUTES, &moduleContext->DmfModuleThreadInterrupt); FuncExitVoid(DMF_TRACE); } #pragma code_seg() /////////////////////////////////////////////////////////////////////////////////////////////////////// // Public Calls by Client /////////////////////////////////////////////////////////////////////////////////////////////////////// // #pragma code_seg("PAGE") _IRQL_requires_max_(PASSIVE_LEVEL) _Must_inspect_result_ NTSTATUS DMF_Tests_AlertableSleep_Create( _In_ WDFDEVICE Device, _In_ DMF_MODULE_ATTRIBUTES* DmfModuleAttributes, _In_ WDF_OBJECT_ATTRIBUTES* ObjectAttributes, _Out_ DMFMODULE* DmfModule ) /*++ Routine Description: Create an instance of a DMF Module of type Test_AlertableSleep. Arguments: Device - Client driver's WDFDEVICE object. DmfModuleAttributes - Opaque structure that contains parameters DMF needs to initialize the Module. ObjectAttributes - WDF object attributes for DMFMODULE. DmfModule - Address of the location where the created DMFMODULE handle is returned. Return Value: NTSTATUS --*/ { NTSTATUS ntStatus; DMF_MODULE_DESCRIPTOR dmfModuleDescriptor_Tests_AlertableSleep; DMF_CALLBACKS_DMF dmfCallbacksDmf_Tests_AlertableSleep; PAGED_CODE(); DMF_CALLBACKS_DMF_INIT(&dmfCallbacksDmf_Tests_AlertableSleep); dmfCallbacksDmf_Tests_AlertableSleep.ChildModulesAdd = DMF_Tests_AlertableSleep_ChildModulesAdd; dmfCallbacksDmf_Tests_AlertableSleep.DeviceOpen = DMF_Tests_AlertableSleep_Open; dmfCallbacksDmf_Tests_AlertableSleep.DeviceClose = DMF_Tests_AlertableSleep_Close; DMF_MODULE_DESCRIPTOR_INIT_CONTEXT_TYPE(dmfModuleDescriptor_Tests_AlertableSleep, Tests_AlertableSleep, DMF_CONTEXT_Tests_AlertableSleep, DMF_MODULE_OPTIONS_PASSIVE, DMF_MODULE_OPEN_OPTION_OPEN_Create); dmfModuleDescriptor_Tests_AlertableSleep.CallbacksDmf = &dmfCallbacksDmf_Tests_AlertableSleep; ntStatus = DMF_ModuleCreate(Device, DmfModuleAttributes, ObjectAttributes, &dmfModuleDescriptor_Tests_AlertableSleep, DmfModule); if (!NT_SUCCESS(ntStatus)) { TraceEvents(TRACE_LEVEL_ERROR, DMF_TRACE, "DMF_ModuleCreate fails: ntStatus=%!STATUS!", ntStatus); } return(ntStatus); } #pragma code_seg() // Module Methods // // eof: Dmf_Tests_AlertableSleep.c //
30.185841
107
0.598871
[ "object" ]
cd2399f5f20d2ba56897bdf12c19a9747228b719
8,551
h
C
inc/VShowerParameters.h
GernotMaier/Eventdisplay
b244d65856ddc26ea8ef88af53d2b247e8d5936c
[ "BSD-3-Clause" ]
11
2019-12-10T13:34:46.000Z
2021-08-24T15:39:35.000Z
inc/VShowerParameters.h
Eventdisplay/Eventdisplay
01ef380cf53a44f95351960a297a2d4f271a4160
[ "BSD-3-Clause" ]
53
2019-11-19T13:14:36.000Z
2022-02-16T14:22:27.000Z
inc/VShowerParameters.h
pivosb/Eventdisplay
6b299a1d3f77ddb641f98a511a37a5045ddd6b47
[ "BSD-3-Clause" ]
3
2020-05-07T13:52:46.000Z
2021-06-25T09:49:21.000Z
//! VShowerParameters storage class for shower data #ifndef VSHOWERPARAMETERS_H #define VSHOWERPARAMETERS_H #include "VGlobalRunParameter.h" #include "TTree.h" #include <iostream> #include <stdint.h> #include <string> #include <vector> using namespace std; class VShowerParameters { private: bool fDebug; bool fMC; TTree* fTreeSC; //!< output tree unsigned int fNTel; //!< number of telescopes unsigned int fShortTree; void resetDispVectors(); public: int runNumber; int eventNumber; int MJD; double time; unsigned int eventStatus; // geometry and run parameters unsigned int fNTelescopes; //!< number of telescopes // pointing information (array pointing) float fArrayPointing_Elevation; float fArrayPointing_Azimuth; float fArrayPointing_deRotationAngle_deg; // pointing information per telescope // calculated from time and source position float fTelElevation[VDST_MAXTELESCOPES]; float fTelAzimuth[VDST_MAXTELESCOPES]; // from vbf float fTelElevationVBF[VDST_MAXTELESCOPES]; float fTelAzimuthVBF[VDST_MAXTELESCOPES]; // difference between calculation and vbf float fTelPointingMismatch[VDST_MAXTELESCOPES]; float fTelDec[VDST_MAXTELESCOPES]; float fTelRA[VDST_MAXTELESCOPES]; float fTelPointingErrorX[VDST_MAXTELESCOPES]; float fTelPointingErrorY[VDST_MAXTELESCOPES]; unsigned int fNMethods; // array reconstruction method uint16_t fMethodID[VDST_MAXRECMETHODS]; // trigger information unsigned int fNTrig; //!< number of telescopes with local triggers ULong64_t fLTrig; //!< local trigger vector, bit coded //!< list of telescopes with local triggers (length of array is fNTrig) unsigned short int fTrig_list[VDST_MAXTELESCOPES]; unsigned short int fTrig_type[VDST_MAXTELESCOPES]; // reconstruction parameters unsigned int fNumImages; //!< total number of images // C. Duke 19Oct06 //!< images selected bitcoded ULong64_t fTelIDImageSelected_bitcode[VDST_MAXRECMETHODS]; //!< list of telescopes with images selected (length of array is fNMethods) uint8_t fTelIDImageSelected_list[VDST_MAXRECMETHODS][VDST_MAXTELESCOPES]; float fTel_x_SC[VDST_MAXTELESCOPES]; //!< array of telescope x location in array plane float fTel_y_SC[VDST_MAXTELESCOPES]; //!< array of telescope x location in array plane float fTel_z_SC[VDST_MAXTELESCOPES]; //!< array of telescope x location in array plane float fiangdiff[VDST_MAXRECMETHODS]; //!< true, if image of telescope is used for the reconstruction (one for each method) vector< vector< bool > > fTelIDImageSelected; //!< number of images used for shower reconstruction uint16_t fShowerNumImages[VDST_MAXRECMETHODS]; float fShowerZe[VDST_MAXRECMETHODS]; //!< shower zenith angle in [deg] float fShowerAz[VDST_MAXRECMETHODS]; //!< shower azimuth angle in [deg] //------------------------------ float fWobbleNorth; float fWobbleEast; //---------------------------- float fDec[VDST_MAXRECMETHODS]; //!< declination of shower [deg] float fRA[VDST_MAXRECMETHODS]; //!< right ascension of shower [deg] float fShower_Xoffset[VDST_MAXRECMETHODS];//!< offset of direction from camera center [deg] float fShower_Yoffset[VDST_MAXRECMETHODS];//!< offset of direction from camera center [deg] vector< vector< float > > fShower_Xoff_DISP; vector< vector< float > > fShower_Yoff_DISP; vector< vector< float > > fShower_Weight_DISP; // (debug use only) unsigned int fShower_NPair; //! number of pairs float fShower_PairXS[VDST_MAXRECMETHODS]; //! pairwise X (observe: debugging only) (geo) float fShower_PairYS[VDST_MAXRECMETHODS]; //! pairwise Y (observe: debugging only) (geo) float fShower_PairXD[VDST_MAXRECMETHODS]; //! pairwise X (observe: debugging only) (disp) float fShower_PairYD[VDST_MAXRECMETHODS]; //! pairwise Y (observe: debugging only) (disp) float fShower_PairAngDiff[VDST_MAXRECMETHODS]; //! pairwise angdiff (observe: debugging only) float fShower_PairDispWeight[VDST_MAXRECMETHODS]; //! pairwise disp weight (observe: debugging only) // (end debug use only) //!< offset of direction from camera center [deg] (derotated) float fShower_XoffsetDeRot[VDST_MAXRECMETHODS]; //!< offset of direction from camera center [deg] (derotated); float fShower_YoffsetDeRot[VDST_MAXRECMETHODS]; float fShower_stdS[VDST_MAXRECMETHODS]; //!< std (radius) about source point float fShowerXcore[VDST_MAXRECMETHODS]; //!< shower core in ground coordinates float fShowerYcore[VDST_MAXRECMETHODS]; //!< shower core in ground coordinates float fShowerXcore_SC[VDST_MAXRECMETHODS];//!< shower core in shower coordinates float fShowerYcore_SC[VDST_MAXRECMETHODS];//!< shower core in shower coordinates float fShower_stdP[VDST_MAXRECMETHODS]; //!< std (radius) about impact point float fShower_Chi2[VDST_MAXRECMETHODS]; //!< chi2 value where appropriate, < 0. for no reconstruction (-99. or angle between lines for two-images events) float fDispDiff[VDST_MAXRECMETHODS]; //!< difference in disp event direction between telescopes int MCprimary; float MCenergy; //!< MC energy in [TeV] float MCxcore; //!< MC core position in ground coordinates (x) float MCycore; //!< MC core position in ground coordinates (y) float MCzcore; //!< MC core position in ground coordinates (z) float MCxcos; float MCycos; float MCaz; float MCze; float MCTel_Xoff; //!< MC source offset in MC in deg (grisudet telescope coordinate system) float MCTel_Yoff; //!< MC source offset in MC in deg (grisudet telescope coordinate system) float MCxcore_SC; //!< MC core position in shower coordinates float MCycore_SC; //!< MC core position in shower coordinates float MCzcore_SC; //!< MC core position in shower coordinates int MCCorsikaRunID; int MCCorsikaShowerID; float MCFirstInteractionHeight; float MCFirstInteractionDepth; VShowerParameters( int iNTel = 4, unsigned int iShortTree = 0, unsigned int iNMethods = 1 ); ~VShowerParameters(); void addDISPPoint( unsigned int iTelID, unsigned int iMethod, float x, float y, float idispw = -999. ); void fill() { if( fTreeSC ) { fTreeSC->Fill(); } } unsigned int getMaxNTelescopes() const { return VDST_MAXTELESCOPES; } unsigned int getNArrayReconstructionMethods() const { return fNMethods; } unsigned int getNArrayMaxReconstructionMethods() const { return VDST_MAXRECMETHODS; } TTree* getTree() { return fTreeSC; } void initTree( string, string, bool ); bool isMC() //!< is data Monte Carlo? { return fMC; } void printParameters(); //!< write tree parameters to standard output void reset(); //!< reset all tree variable to standard values void reset( unsigned int iNTel ); //!< reset all tree variable to standard values void setMC() { fMC = true; } void setNArrayReconstructionMethods( unsigned int iNMethods ) { fNMethods = iNMethods; } }; #endif
45.243386
164
0.601801
[ "geometry", "vector" ]
cd3b27e2460bc211bf79eb126d23085568d2349b
939
h
C
sim/firesim-lib/src/main/cc/bridges/tracerv/tracerv_processing.h
GaloisInc/BESSPIN-firesim
0da74414291708563f9b512634d1315d53077e91
[ "Apache-2.0" ]
2
2021-07-18T06:04:44.000Z
2022-02-19T21:23:55.000Z
sim/firesim-lib/src/main/cc/bridges/tracerv/tracerv_processing.h
GaloisInc/BESSPIN-firesim
0da74414291708563f9b512634d1315d53077e91
[ "Apache-2.0" ]
null
null
null
sim/firesim-lib/src/main/cc/bridges/tracerv/tracerv_processing.h
GaloisInc/BESSPIN-firesim
0da74414291708563f9b512634d1315d53077e91
[ "Apache-2.0" ]
null
null
null
#ifndef TRACERV_PROCESSING_GUARD #define TRACERV_PROCESSING_GUARD #include <inttypes.h> #include <vector> #include <string> #include <iostream> #include <fstream> #include <ctype.h> class Instr { public: std::string instval; uint64_t addr; std::string label; std::string function_name; bool is_fn_entry; bool is_callsite; bool in_asm_sequence; Instr() { is_callsite = false; is_fn_entry = false; in_asm_sequence = false; } void printMe() { printf("%s, %" PRIx64 ", %s\n", label.c_str(), addr, instval.c_str()); } void printMeFile(FILE * printfile, std::string prefix) { } }; class ObjdumpedBinary { // base address subtracted before lookup into array uint64_t baseaddr; std::vector<Instr *> progtext; public: ObjdumpedBinary(std::string binaryWithDwarf); Instr* getInstrFromAddr(uint64_t lookupaddress); }; #endif
17.388889
78
0.657082
[ "vector" ]
cd4163a338be42137ca47d9d6c48e9f0da54391a
1,983
h
C
drivers/NVMSIM/test/bandwidth-1.9.3/OOC/Console.h
huqianshan/OperatingSystemAndCompiler
2117263d39e9166cfc5c32014ca2b875c7f97de2
[ "Unlicense" ]
1
2020-03-22T10:37:05.000Z
2020-03-22T10:37:05.000Z
code/NVMSIM/test/bandwidth-1.9.3/OOC/Console.h
huqianshan/linux-drivers-study
cb39f4e3821184abc46e46f9f0bfed7187ee11fa
[ "MIT" ]
null
null
null
code/NVMSIM/test/bandwidth-1.9.3/OOC/Console.h
huqianshan/linux-drivers-study
cb39f4e3821184abc46e46f9f0bfed7187ee11fa
[ "MIT" ]
null
null
null
/*============================================================================ Console, an object-oriented C console I/O class. Copyright (C) 2019 by Zack T Smith. Object-Oriented C is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Object-Oriented C 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 software. If not, see <http://www.gnu.org/licenses/>. The author may be reached at 1@zsmith.co. *===========================================================================*/ #ifndef _OOC_CONSOLE_H #define _OOC_CONSOLE_H #include <stdbool.h> #include <math.h> #include "Object.h" #define DECLARE_CONSOLE_INSTANCE_VARS(FOO) #define DECLARE_CONSOLE_METHODS(TYPE_POINTER) \ void (*newline) (TYPE_POINTER); \ void (*flush) (TYPE_POINTER); \ void (*println) (TYPE_POINTER, const char*); \ void (*print) (TYPE_POINTER, const char*); \ void (*print_int) (TYPE_POINTER, int); \ void (*print_unsigned) (TYPE_POINTER, unsigned); \ void (*printf) (TYPE_POINTER, const char* fmt, ...); struct console; typedef struct consoleclass { DECLARE_OBJECT_CLASS_VARS DECLARE_OBJECT_METHODS(struct console*) DECLARE_CONSOLE_METHODS(struct console*) } ConsoleClass; extern ConsoleClass *_ConsoleClass; typedef struct console { ConsoleClass *is_a; DECLARE_OBJECT_INSTANCE_VARS(struct console*) DECLARE_CONSOLE_INSTANCE_VARS(struct console*) } Console; extern Console *Console_singleton (); extern Console *Console_new (); extern Console *Console_init (Console *self); #endif
32.508197
79
0.692385
[ "object" ]
cd45691b4b74d0f2ad65384600de7a35006e3626
2,027
h
C
lib/disk.h
noamran/atlas-system-agent
117025feedaa3108f7c6d2bb5c3628036a918fb0
[ "Apache-2.0" ]
6
2018-07-21T01:03:11.000Z
2020-04-16T03:39:51.000Z
lib/disk.h
noamran/atlas-system-agent
117025feedaa3108f7c6d2bb5c3628036a918fb0
[ "Apache-2.0" ]
13
2018-05-02T23:27:29.000Z
2021-09-21T20:45:44.000Z
lib/disk.h
noamran/atlas-system-agent
117025feedaa3108f7c6d2bb5c3628036a918fb0
[ "Apache-2.0" ]
7
2018-04-17T20:30:03.000Z
2021-08-16T21:30:20.000Z
#pragma once #include "monotonic_timer.h" #include "tagging_registry.h" #include <string> #include <sys/types.h> #include <unordered_map> #include <vector> namespace atlasagent { struct MountPoint { unsigned device_major; unsigned device_minor; std::string mount_point; std::string device; std::string fs_type; }; struct DiskIo { int major; int minor; std::string device; u_long reads_completed; u_long reads_merged; u_long rsect; u_long ms_reading; u_long writes_completed; u_long writes_merged; u_long wsect; u_long ms_writing; u_long ios_in_progress; u_long ms_doing_io; u_long weighted_ms_doing_io; }; template <typename Reg = TaggingRegistry> class Disk { public: explicit Disk(Reg* registry, std::string path_prefix = "") noexcept : registry_(registry), path_prefix_(std::move(path_prefix)) {} void titus_disk_stats() noexcept; void disk_stats() noexcept; void set_prefix(const std::string& new_prefix) noexcept; // for testing private: Reg* registry_; std::string path_prefix_; absl::Time last_updated_{absl::UnixEpoch()}; std::unordered_map<std::string, u_long> last_ms_doing_io{}; std::unordered_map<spectator::IdPtr, std::shared_ptr<MonotonicTimer<Reg>>> monotonic_timers_{}; protected: // protected for testing void do_disk_stats(absl::Time start) noexcept; void stats_for_interesting_mps(std::function<void(Disk*, const MountPoint&)> stats_fn) noexcept; [[nodiscard]] std::vector<MountPoint> filter_interesting_mount_points( const std::vector<MountPoint>& mount_points) const noexcept; [[nodiscard]] std::vector<MountPoint> get_mount_points() const noexcept; [[nodiscard]] std::vector<DiskIo> get_disk_stats() const noexcept; void update_titus_stats_for(const MountPoint& mp) noexcept; void update_stats_for(const MountPoint& mp) noexcept; void diskio_stats(absl::Time start) noexcept; void set_last_updated(absl::Time updated) { last_updated_ = updated; } }; } // namespace atlasagent #include "internal/disk.inc"
29.808824
98
0.75333
[ "vector" ]
cd4d463e916ef36d063c40b1f0153fd11be8dccf
751
c
C
mptcore/object/object_foreach.c
becm/mpt-base
49e8b2022b975b5e159088b5dd052d6b5e7afe6e
[ "0BSD" ]
3
2018-08-31T22:04:49.000Z
2020-06-12T07:00:25.000Z
mptcore/object/object_foreach.c
becm/mpt-base
49e8b2022b975b5e159088b5dd052d6b5e7afe6e
[ "0BSD" ]
null
null
null
mptcore/object/object_foreach.c
becm/mpt-base
49e8b2022b975b5e159088b5dd052d6b5e7afe6e
[ "0BSD" ]
null
null
null
/*! * call function for all object properties */ #include "object.h" static int get_property(void *ptr, MPT_STRUCT(property) *pr) { const MPT_INTERFACE(object) *obj = ptr; return obj->_vptr->property(obj, pr); } /*! * \ingroup mptObject * \brief process properties * * Process object properties matching traverse types. * * \param obj property source * \param proc process retreived properties * \param data argumernt for property processing * \param match properties to process * * \return index of requested property */ extern int mpt_object_foreach(const MPT_INTERFACE(object) *obj, MPT_TYPE(property_handler) proc, void *data, int match) { return mpt_properties_foreach(get_property, (void *) obj, proc, data, match); }
25.033333
119
0.729694
[ "object" ]
cd5bf1308c5068346619a5f2624003773a4638f8
6,671
h
C
Common_3/ThirdParty/OpenSource/hlslparser/Parser/Parser/GLSLGenerator.h
RemiArnaud/The-Forge
70f5f4b544831ea3a51de2ad4a7f341fb1b971c5
[ "Apache-2.0" ]
18
2020-05-05T18:11:59.000Z
2021-12-16T07:07:46.000Z
Common_3/ThirdParty/OpenSource/hlslparser/Parser/Parser/GLSLGenerator.h
RemiArnaud/The-Forge
70f5f4b544831ea3a51de2ad4a7f341fb1b971c5
[ "Apache-2.0" ]
null
null
null
Common_3/ThirdParty/OpenSource/hlslparser/Parser/Parser/GLSLGenerator.h
RemiArnaud/The-Forge
70f5f4b544831ea3a51de2ad4a7f341fb1b971c5
[ "Apache-2.0" ]
6
2020-05-23T21:42:12.000Z
2021-08-09T13:44:02.000Z
//============================================================================= // // Render/GLSLGenerator.h // // Created by Max McGuire (max@unknownworlds.com) // Copyright (c) 2013, Unknown Worlds Entertainment, Inc. // //============================================================================= #ifndef GLSL_GENERATOR_H #define GLSL_GENERATOR_H #include "CodeWriter.h" #include "HLSLTree.h" #include "Parser.h" class StringLibrary; class GLSLGenerator { public: enum Target { Target_VertexShader, Target_FragmentShader, Target_HullShader, Target_DomainShader, Target_GeometryShader, Target_ComputeShader, }; enum Version { Version_110, // OpenGL 2.0 Version_140, // OpenGL 3.1 Version_150, // OpenGL 3.2 Version_450, // OpenGL 4.5 Version_100_ES, // OpenGL ES 2.0 Version_300_ES, // OpenGL ES 3.0 }; enum Flags { Flag_FlipPositionOutput = 1 << 0, Flag_EmulateConstantBuffer = 1 << 1, Flag_PackMatrixRowMajor = 1 << 2, Flag_LowerMatrixMultiplication = 1 << 3, }; struct Options { unsigned int flags; const char* constantBufferPrefix; eastl::vector < BindingShift >shiftVec; Options() { flags = 0; constantBufferPrefix = ""; } }; GLSLGenerator(); bool Generate(StringLibrary * stringLibrary, HLSLTree* tree, Target target, Version versiom, const char* entryName, const Options& options = Options()); const char* GetResult() const; private: enum AttributeModifier { AttributeModifier_In, AttributeModifier_Out, AttributeModifier_Inout, }; void OutputExpressionList(const eastl::vector<HLSLExpression*>& expressions, size_t i = 0); void OutputExpression(HLSLExpression* expression, const HLSLType* dstType = NULL, bool allowCast = true); void OutputExpressionForBufferArray(HLSLExpression* expression, const HLSLType* dstType = NULL); void OutputIdentifier(const CachedString & name); void OutputIdentifierExpression(HLSLIdentifierExpression* pIdentExpr); void OutputArguments(const eastl::vector < HLSLArgument* > & arguments); void OutputAttributes(int indent, HLSLAttribute* attribute); /** * If the statements are part of a function, then returnType can be used to specify the type * that a return statement is expected to produce so that correct casts will be generated. */ void OutputStatements(int indent, HLSLStatement* statement, const HLSLType* returnType = NULL); void OutputAttribute(const HLSLType& type, const CachedString & semantic, AttributeModifier modifier, int *counter); void OutputAttributes(HLSLFunction* entryFunction); void OutputEntryCaller(HLSLFunction* entryFunction); void OutputDeclaration(HLSLDeclaration* declaration); void OutputDeclarationType( const HLSLType& type ); void OutputDeclarationBody( const HLSLType& type, const CachedString & name); void OutputDeclaration(const HLSLType& type, const CachedString & name); void OutputCast(const HLSLType& type); void OutputSetOutAttribute(const char* semantic, const CachedString & resultName); void LayoutBuffer(HLSLBuffer* buffer, unsigned int& offset); void LayoutBuffer(const HLSLType& type, unsigned int& offset); void LayoutBufferElement(const HLSLType& type, unsigned int& offset); void LayoutBufferAlign(const HLSLType& type, unsigned int& offset); HLSLBuffer* GetBufferAccessExpression(HLSLExpression* expression); void OutputBufferAccessExpression(HLSLBuffer* buffer, HLSLExpression* expression, const HLSLType& type, unsigned int postOffset); unsigned int OutputBufferAccessIndex(HLSLExpression* expression, unsigned int postOffset); void OutputArrayExpression(int arrayDimension, HLSLExpression* (&arrayDimExpression)[MAX_DIM]); void OutputBuffer(int indent, HLSLBuffer* buffer); HLSLFunction* FindFunction(HLSLRoot* root, const CachedString & name); HLSLStruct* FindStruct(HLSLRoot* root, const CachedString & name); void Error(const char* format, ...); /** GLSL contains some reserved words that don't exist in HLSL. This function will * sanitize those names. */ CachedString GetSafeIdentifierName(const CachedString & name) const; /** Generates a name of the format "base+n" where n is an integer such that the name * isn't used in the syntax tree. */ bool ChooseUniqueName(const char* base, CachedString & dstName) const; CachedString GetBuiltInSemantic(const CachedString & semantic, AttributeModifier modifier, int* outputIndex = 0); CachedString GetBuiltInSemantic(const CachedString & semantic, AttributeModifier modifier, const HLSLType& type, int* outputIndex = 0); CachedString GetAttribQualifier(AttributeModifier modifier); CachedString MakeCached(const char * str); private: static const int s_numReservedWords = 7; static const char* s_reservedWord[s_numReservedWords]; CodeWriter m_writer; HLSLTree* m_tree; CachedString m_entryName; Target m_target; Version m_version; bool m_versionLegacy; Options m_options; bool m_outputPosition; eastl::vector < HLSLBaseType > m_outputTypes; CachedString m_outAttribPrefix; CachedString m_inAttribPrefix; CachedString m_matrixRowFunction; CachedString m_matrixCtorFunction; CachedString m_matrixMulFunction; CachedString m_clipFunction; CachedString m_tex2DlodFunction; CachedString m_tex2DbiasFunction; CachedString m_tex2DgradFunction; CachedString m_tex3DlodFunction; CachedString m_texCUBEbiasFunction; CachedString m_texCUBElodFunction; CachedString m_textureLodOffsetFunction; CachedString m_scalarSwizzle2Function; CachedString m_scalarSwizzle3Function; CachedString m_scalarSwizzle4Function; CachedString m_sinCosFunction; CachedString m_bvecTernary; CachedString m_f16tof32Function; CachedString m_f32tof16Function; CachedString m_getDimensions; CachedString m_mulMatFunction; bool m_error; CachedString m_reservedWord[s_numReservedWords]; eastl::vector < CachedString> m_StructuredBufferNames; eastl::vector < HLSLBuffer*> m_PushConstantBuffers; CachedString m_outputGeometryType; CachedString m_domain; CachedString m_partitioning; CachedString m_outputtopology; CachedString m_patchconstantfunc; CachedString m_geoInputdataType; CachedString m_geoOutputdataType; StringLibrary * m_stringLibrary; }; #endif
33.691919
156
0.714586
[ "render", "vector" ]
cd60039274b22cc1d286bf66fd564b47cdee7071
2,994
h
C
third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2018-07-04T00:29:09.000Z
2020-07-05T09:24:59.000Z
third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NavigatorKeyboardLock_h #define NavigatorKeyboardLock_h #include "bindings/core/v8/ScriptPromise.h" #include "core/frame/Navigator.h" #include "platform/Supplementable.h" #include "platform/heap/Handle.h" #include "platform/heap/Member.h" #include "platform/wtf/Forward.h" #include "public/platform/modules/keyboard_lock/keyboard_lock.mojom-blink.h" namespace blink { class ScriptPromiseResolver; // The supplement of Navigator to process navigator.requestKeyboardLock() and // navigator.cancelKeyboardLock() web APIs. This class forwards both requests // directly to the browser process through mojo. class NavigatorKeyboardLock final : public GarbageCollectedFinalized<NavigatorKeyboardLock>, public Supplement<Navigator> { USING_GARBAGE_COLLECTED_MIXIN(NavigatorKeyboardLock); public: // Requests to receive a set of key codes // (https://w3c.github.io/uievents/#dom-keyboardevent-code) in string format. // The Promise will be rejected if the user or browser do not allow the web // page to use this API. Otherwise, web page should expect to receive the key // presses once the Promise has been resolved. This API does best effort to // deliver the key codes: due to the platform restrictions, some keys or key // combinations may not be able to receive or intercept by the user agent. // - Making two requests concurrently without waiting for one Promise to // finish is disallowed, the second Promise will be rejected immediately. // - Making a second request after the Promise of the first one has finished // is allowed; the second request will overwrite the key codes reserved. // - Passing in an empty keyCodes array will reserve all keys. static ScriptPromise requestKeyboardLock(ScriptState*, Navigator&, const Vector<String>&); // Removes all reserved keys. This function is also asynchronized, the web // page may still receive reserved keys after this function has finished. Once // the web page is closed, the user agent implicitly executes this API. static void cancelKeyboardLock(Navigator&); DECLARE_TRACE(); private: explicit NavigatorKeyboardLock(Navigator&); static const char* SupplementName(); static NavigatorKeyboardLock& From(Navigator&); ScriptPromise requestKeyboardLock(ScriptState*, const Vector<String>&); void cancelKeyboardLock(); // Ensures the |service_| is correctly initialized. In case of the |service_| // cannot be initialized, this function returns false. bool EnsureServiceConnected(); void LockRequestFinished(mojom::KeyboardLockRequestResult); mojom::blink::KeyboardLockServicePtr service_; Member<ScriptPromiseResolver> request_keylock_resolver_; }; } // namespace blink #endif // NavigatorKeyboardLock_h
40.459459
80
0.755177
[ "vector" ]
cd6acda07dfd2e38ac17304a7f97694645b0bb31
5,912
h
C
openmi/core/ops/cwise_ops_binary.h
ComputationalAdvertising/openmi
1d986ada6c57fecf482f4b8dc4d2488cb0189a3e
[ "Apache-2.0" ]
null
null
null
openmi/core/ops/cwise_ops_binary.h
ComputationalAdvertising/openmi
1d986ada6c57fecf482f4b8dc4d2488cb0189a3e
[ "Apache-2.0" ]
null
null
null
openmi/core/ops/cwise_ops_binary.h
ComputationalAdvertising/openmi
1d986ada6c57fecf482f4b8dc4d2488cb0189a3e
[ "Apache-2.0" ]
null
null
null
#ifndef OPENMI_CORE_OPS_CWISE_OPS_BINARY_H_ #define OPENMI_CORE_OPS_CWISE_OPS_BINARY_H_ #include "cwise_ops_binary_functor.h" #include "tensor_types.h" #include "numeric_op.h" namespace openmi { extern void UpdateOneVectorReshape(Tensor& t, uint64_t* reshape, int dim_size); extern void UpdateMultiDimReshape(Tensor& t, uint64_t* reshape, int dim_size); extern void ReshapeTensor(Tensor& t, uint64_t* reshape, int dims); template <typename Device, typename FUNCTOR, typename T, int NDIMS> inline void BinaryOperate(OpKernelContext* context, Tensor& in0, Tensor& in1, Tensor& out) { } template <typename Device, typename FUNCTOR, typename T> struct BinaryElementWiseOp : public BinaryOp<T, BinaryElementWiseOp<Device, FUNCTOR, T>> { template <int NDIMS> void Operate(OpKernelContext* context, Tensor& in0, Tensor& in1, Tensor& out) { uint64_t lreshape[NDIMS], rreshape[NDIMS], lbcast[NDIMS], rbcast[NDIMS]; const bool in0_vec = in0.IsVector(); const bool in1_vec = in1.IsVector(); if (in0_vec && in1_vec) { lreshape[0] = in0.shape().DimSize(0); rreshape[0] = in1.shape().DimSize(0); } else if (in0_vec && !in1_vec) { UpdateOneVectorReshape(in0, lreshape, NDIMS); UpdateMultiDimReshape(in1, rreshape, NDIMS); } else if (!in0_vec && in1_vec) { UpdateMultiDimReshape(in0, lreshape, NDIMS); UpdateOneVectorReshape(in1, rreshape, NDIMS); } else { UpdateMultiDimReshape(in0, lreshape, NDIMS); UpdateMultiDimReshape(in1, rreshape, NDIMS); } DLOG(INFO) << "lreshape: " << lreshape[0]; DLOG(INFO) << "rreshape: " << rreshape[0]; TensorShape out_shape; bool is_lbcast = false, is_rbcast = false; for (int i = 0; i < NDIMS; ++i) { lbcast[i] = lreshape[i] == 1 ? rreshape[i] : 1; if (lbcast[i] != 1) { is_lbcast = true; } rbcast[i] = rreshape[i] == 1 ? lreshape[i] : 1; if (rbcast[i] != 1) { is_rbcast = true; } out_shape.AddDim(lreshape[i] != 1 ? lreshape[i] : rreshape[i]); if (lreshape[i] != 1 && rreshape[i] != 1 && lreshape[i] != rreshape[i]) { LOG(INFO) << "left: " << in0.shape().DebugString(); LOG(INFO) << "right: " << in1.shape().DebugString(); std::runtime_error("Dim error."); } } LOG(INFO) << "out_shape: " << out_shape.DebugString(); if (!out.IsInitialized() || out.shape() != out_shape) { out.AllocateTensor(out_shape); } auto X0 = in0.tensor<T, NDIMS>(); auto X1 = in1.tensor<T, NDIMS>(); auto Y = out.tensor<T, NDIMS>(); DLOG(INFO) << "X0: " << context->inputs().at(0) << ", value:\n" << X0; DLOG(INFO) << "X1: " << context->inputs().at(1) << ", value:\n" << X1; Eigen::array<Eigen::DenseIndex, NDIMS> lreshape_dims, rreshape_dims, lbcast_dims, rbcast_dims; for (int i = 0; i < NDIMS; ++i) { lreshape_dims[i] = lreshape[i]; rreshape_dims[i] = rreshape[i]; lbcast_dims[i] = lbcast[i]; rbcast_dims[i] = rbcast[i]; } DLOG(INFO) << "is_lbcast: " << is_lbcast << ", is_rbcast: " << is_rbcast; typename FUNCTOR::func func; auto d = context->eigen_device<Device>(); if (is_lbcast && is_rbcast) { Y.device(d) = X0.reshape(lreshape_dims).broadcast(lbcast_dims).binaryExpr( X1.reshape(rreshape_dims).broadcast(rbcast_dims), func); } else if (is_lbcast && !is_rbcast) { Y.device(d) = X0.reshape(lreshape_dims).broadcast(lbcast_dims).binaryExpr( X1.reshape(rreshape_dims), func); } else if (!is_lbcast && is_rbcast) { Y.device(d) = X0.reshape(lreshape_dims).binaryExpr( X1.reshape(rreshape_dims).broadcast(rbcast_dims), func); } else { Y.device(d) = X0.reshape(lreshape_dims).binaryExpr( X1.reshape(rreshape_dims), func); } /* auto X00 = X0.reshape(lreshape_dims); if (is_lbcast) { X00 = X00.broadcast(lbcast_dims); } auto X11 = X1.reshape(rreshape_dims); if (is_rbcast) { X11 = X11.broadcast(rbcast_dims); } Y.device(d) = X00.binaryExpr(X11, typename FUNCTOR::func()); */ DLOG(INFO) << "Y:\n" << Y; } }; // struct BinaryElementWiseOp // 'a+b' template <typename T> struct AddFunctor : BaseFunctor<T, Eigen::internal::scalar_sum_op<T>> { static const bool use_bcast_optimization = true; }; // 'a-b' template <typename T> struct SubFunctor : BaseFunctor<T, Eigen::internal::scalar_difference_op<T>> { static const bool use_bcast_optimization = true; }; // 'a*b' template <typename T> struct MulFunctor : BaseFunctor<T, Eigen::internal::scalar_product_op<T>> {}; // 'a/b' template <typename T> struct DivFunctor : BaseFunctor<T, Eigen::internal::scalar_quotient_op<T>> {}; // '2^' //template <typename T> //struct PowFunctor : BaseFunctor<T, Eigen::internal::scalar_binary_pow_op_google<T, T>> {}; // 'a > b ? a : b' template <typename T> struct MaxFunctor : BaseFunctor<T, Eigen::internal::scalar_max_op<T>> {}; // 'a < b ? a : b' template <typename T> struct MinFunctor : BaseFunctor<T, Eigen::internal::scalar_min_op<T>> {}; template <typename T> struct AddFunctorCustomOp { EIGEN_EMPTY_STRUCT_CTOR(AddFunctorCustomOp) EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const T operator()(const T& x1, const T& x2) const { return x1 + x2; } }; template <typename T> struct AddFunctorCustom : BaseFunctor<T, AddFunctorCustomOp<T>> { }; template <typename T> struct SigmoidGradOp : BaseFunctor<T, SigmoidGradFunctor<T>> { }; } // namespace openmi #define OPENMI_REGISTER_BINARY_ELEMENT_WISE_OP_TYPE(name, functor, T) \ OPENMI_REGISTER_OP_KERNEL(name, \ ::openmi::BinaryOp<T, openmi::BinaryElementWiseOp<CpuDevice, functor<T>, T>>) \ .Device("CPU") \ .TypeConstraint<T>(); #define OPENMI_REGISTER_BINARY_ELEMENT_WISE_OP(name, functor) \ OPENMI_REGISTER_BINARY_ELEMENT_WISE_OP_TYPE(name, functor, float) \ OPENMI_REGISTER_BINARY_ELEMENT_WISE_OP_TYPE(name, functor, double) \ OPENMI_REGISTER_BINARY_ELEMENT_WISE_OP_TYPE(name, functor, int) #endif // OPENMI_CORE_OPS_CWISE_OPS_BINARY_H_
33.213483
96
0.679635
[ "shape" ]
289eed52299ccac5bb48470ac46cd1d388812796
1,807
h
C
ui/ui_playerinfo.h
kugelrund/Elite-Reinforce
a2fe0c0480ff2d9cdc241b9e5416ee7f298f00ca
[ "DOC" ]
10
2017-07-04T14:38:48.000Z
2022-03-08T22:46:39.000Z
ui/ui_playerinfo.h
UberGames/SP-Mod-Source-Code
04e0e618d1ee57a2919f1a852a688c03b1aa155d
[ "DOC" ]
null
null
null
ui/ui_playerinfo.h
UberGames/SP-Mod-Source-Code
04e0e618d1ee57a2919f1a852a688c03b1aa155d
[ "DOC" ]
2
2017-04-23T18:24:44.000Z
2021-11-19T23:27:03.000Z
#ifndef __UI_PLAYERINFO_H__ #define __UI_PLAYERINFO_H__ #include "../game/bg_public.h" #include "../game/anims.h" //FIXME ripped from cg_local.h typedef struct { int oldFrame; int oldFrameTime; // time when ->oldFrame was exactly on int frame; int frameTime; // time when ->frame will be exactly on float backlerp; float yawAngle; qboolean yawing; float pitchAngle; qboolean pitching; int animationNumber; // may include ANIM_TOGGLEBIT animation_t *animation; int animationTime; // time when the first frame of the animation will be exact } lerpFrame_t; typedef struct { // model info qhandle_t legsModel; qhandle_t legsSkin; lerpFrame_t legs; qhandle_t torsoModel; qhandle_t torsoSkin; lerpFrame_t torso; qhandle_t headModel; qhandle_t headSkin; animation_t animations[MAX_ANIMATIONS]; qhandle_t weaponModel; qhandle_t flashModel; vec3_t flashDlightColor; int muzzleFlashTime; // currently in use drawing parms vec3_t viewAngles; vec3_t moveAngles; weapon_t currentWeapon; int legsAnim; int torsoAnim; // animation vars weapon_t weapon; weapon_t lastWeapon; weapon_t pendingWeapon; int weaponTimer; int pendingLegsAnim; int torsoAnimationTimer; int pendingTorsoAnim; int legsAnimationTimer; qboolean chat; qboolean looking; } playerInfo_t; void UI_DrawPlayer( float x, float y, float w, float h, playerInfo_t *pi, int time ); void UI_PlayerInfo_SetModel( playerInfo_t *pi, const char *model, const char* headmodel ); void UI_PlayerInfo_SetInfo( playerInfo_t *pi, int legsAnim, int torsoAnim, vec3_t viewAngles, vec3_t moveAngles, weapon_t weaponNum, qboolean chat ); qboolean UI_RegisterClientModelname( playerInfo_t *pi, const char *modelSkinName ); #endif //__UI_PLAYERINFO_H__
24.093333
149
0.752075
[ "model" ]
28a08b35d03f8899205793e6a604f9d17fc4ea3d
889
h
C
Engine/src/Gameplay/Systems/DestroyableWallSystem.h
venCjin/GameEngineProject
d8bdc8fc7236d74f6ecb5e8a8a5211699cc84d22
[ "Apache-2.0" ]
1
2020-03-04T20:46:40.000Z
2020-03-04T20:46:40.000Z
Engine/src/Gameplay/Systems/DestroyableWallSystem.h
venCjin/GameEngineProject
d8bdc8fc7236d74f6ecb5e8a8a5211699cc84d22
[ "Apache-2.0" ]
null
null
null
Engine/src/Gameplay/Systems/DestroyableWallSystem.h
venCjin/GameEngineProject
d8bdc8fc7236d74f6ecb5e8a8a5211699cc84d22
[ "Apache-2.0" ]
null
null
null
#pragma once #include <ECS/SystemManager.h> #include <ECS/EventManager.h> #include <Gameplay/Components/DestroyableWall.h> #include <Gameplay/Components/Transform.h> namespace sixengine { SYSTEM(DestroyableWallSystem, DestroyableWall) { public: void OnStart(EventManager & eventManager) override { } void Update(EventManager & eventManager, float dt) override { if (m_DestroyableWall->m_Destroyed) { for (auto child : m_DestroyableWall->m_GameObject->GetComponent<Transform>()->GetChildren()) { auto pos = child->GetWorldPosition(); if (pos.y <= 0.0f) { continue; } auto v = glm::normalize(child->GetLocalPosition()) * (float)Timer::Instance()->DeltaTime() * 0.75f; v.y = 0.0f; pos += v; pos.y = max(0.0f, pos.y - Timer::Instance()->DeltaTime() * 5.0f); child->SetWorldPosition(pos); } } } }; }
20.674419
104
0.652418
[ "transform" ]
28b0979fa7ac1298d0adc49e94bcb947bfd5fcfa
4,585
h
C
sensorscheme/tos/lib/SensorScheme/SensorScheme.h
tinyos-io/tinyos-3.x-contrib
3aaf036722a2afc0c0aad588459a5c3e00bd3c01
[ "BSD-3-Clause", "MIT" ]
1
2020-02-28T20:35:09.000Z
2020-02-28T20:35:09.000Z
sensorscheme/tos/lib/SensorScheme/SensorScheme.h
tinyos-io/tinyos-3.x-contrib
3aaf036722a2afc0c0aad588459a5c3e00bd3c01
[ "BSD-3-Clause", "MIT" ]
null
null
null
sensorscheme/tos/lib/SensorScheme/SensorScheme.h
tinyos-io/tinyos-3.x-contrib
3aaf036722a2afc0c0aad588459a5c3e00bd3c01
[ "BSD-3-Clause", "MIT" ]
null
null
null
#ifndef SENSORSCHEME_H #define SENSORSCHEME_H #include "Types.h" #include "Macros.h" #include "SensorSchemeMsg.h" enum { AM_SSCOLLECT_MSG = 8, CL_SSCOLLECT_MSG = 9, CL_SSINTERCEPT_MSG = 10, COLLECTION_ROOTNODE = 0, }; enum { POOL_SIZE = 8, ROOT_QUEUE_SIZE = 8, SS_TICKS_PER_SECOND = 16, }; enum entrypoint_t { SS_INIT, SS_RECEIVE, SS_STARTREAD, SS_SENDDONE, SS_SENDLAST, SS_CONTINUE, SS_TIMER } entrypoint_t; /* the possible error values */ enum errorcode_t { ERROR_NULL, ERROR_NONE, ERROR_OUT_OF_MEMORY, ERROR_ILLEGAL_WRITE, ERROR_SYMBOL_NOT_FOUND, ERROR_TOO_FEW_ARGS, ERROR_TOO_MANY_ARGS, ERROR_ILLEGAL_CLOSURE, ERROR_NOT_CALLABLE, ERROR_UNKNOWN_PRIMTIIVE, ERROR_SYMBOL_NOT_BOUND, ERROR_PRIMITIVE_ARGUMENT_COUNT, ERROR_MESSAGE_FORMAT, ERROR_ARG_NOT_PAIR, ERROR_ARG_NOT_SYMBOL, ERROR_ARG_NOT_NUMBER, ERROR_MSG_ENDMARKER, ERROR_MSG_TERMINATION, ERROR_MSG_CONTENT_END, } errorcode_t; char const* error_str[] = { [ERROR_NULL] = "NULL error, should not occur", [ERROR_NONE] = "Terminated normally", [ERROR_OUT_OF_MEMORY] = "Out of memory!", [ERROR_ILLEGAL_WRITE] = "Illegal write", [ERROR_SYMBOL_NOT_FOUND] = "Symbol not found", [ERROR_TOO_FEW_ARGS] = "Too few arguments to closure", [ERROR_TOO_MANY_ARGS] = "Too many arguments to closure", [ERROR_ILLEGAL_CLOSURE] = "Illegal closure format", [ERROR_NOT_CALLABLE] = "calling an object that is not callable", [ERROR_UNKNOWN_PRIMTIIVE] = "Unknwn primitive", [ERROR_SYMBOL_NOT_BOUND] = "Symbol not bound", [ERROR_PRIMITIVE_ARGUMENT_COUNT] = "Wrong number of arguments to primitive", [ERROR_MESSAGE_FORMAT] = "Message format", [ERROR_ARG_NOT_PAIR] = "Argument is not a pair", [ERROR_ARG_NOT_SYMBOL] = "Argument is not a symbol", [ERROR_ARG_NOT_NUMBER] = "Argument is not a number", [ERROR_MSG_ENDMARKER] = "Message has no end marker", [ERROR_MSG_TERMINATION] = "Message not terminated properly", [ERROR_MSG_CONTENT_END] = "Message content not finished yet", }; #define LABEL_LIST(_) \ _(OP_EXIT) \ _(OP_HANDLEMSG) \ _(OP_HANDLEINIT) \ _(OP_IF_CONT) \ _(OP_SET_CONT) \ _(OP_DEF_CONT) \ _(OP_ARGEVAL_CONT) \ _(OP_APPLY) \ _(OP_APPLY_CONT) \ _(RD_BITS_CONT) \ _(RD_WORD_CONT1) \ _(RD_WORD_CONT2) \ _(RD_DWORD_CONT1) \ _(RD_DWORD_CONT2) \ _(RD_SEXPR_CONT1) \ _(RD_LIST) \ _(RD_DOT) \ _(RD_SEXPR_SYM) \ _(RD_SYM_NIBBLE1) \ _(RD_SYM_NIBBLE2) \ _(RD_SYM_STRING) \ _(RD_SEXPR_NUM) \ _(RD_SEXPR_NIBBLE1) \ _(RD_SEXPR_NIBBLE2) \ _(RD_SEXPR_BYTE) \ _(WR_NUMBER_NIBBLE1) \ _(WR_NUMBER_NIBBLE2) \ _(WR_NUMBER_BYTE) \ _(WR_NUMBER_WORD) \ _(WR_NUMBER_DWORD) \ _(WR_SEXPR_NIL) \ _(WR_SEXPR_SYM) \ _(WR_NUMBER) \ _(WR_SEXPR_LIST) \ _(WR_LIST) \ _(WR_LIST_DOT) \ _(WR_FINISH) \ /* Symbol definitions */ #define SYM_LIST(_) \ _(_NIL, 0) \ _(_TRUE, 0) \ _(_FALSE, 0) \ /* read symbols */ \ _(STRING, 0) \ _(DOT, 0) \ /* the special forms */ \ _(LAMBDA, 0) \ _(IF, 0) \ _(QUOTE, 0) \ _(DEFINE, 0) \ _(SET, 0) \ _(CLOSURE, 0) \ _(CONTINUATION, 0) \ _(PRIMITIVE, 0) \ /* special case ID */ \ _(ID, 0) \ #define JUMP_SWITCH(name) case name: goto name; #define SENDER_BOOT(name, pr) call Sender.start[name](); #define RECEIVER_BOOT(name, pr) call Receiver.start[name](); #define LABEL_ENUM(name) name, #define PRIM_ENUM(name, fn) name, enum jumptarget_t { LABEL_LIST(LABEL_ENUM) } jumptarget_t; enum symbols { SYM_LIST(PRIM_ENUM) SIMPLE_PRIM_LIST(PRIM_ENUM) EVAL_PRIM_LIST(PRIM_ENUM) APPLY_PRIM_LIST(PRIM_ENUM) SEND_PRIM_LIST(PRIM_ENUM) } symbols_t; enum receivers { _dummy_receiver, RECEIVER_LIST(PRIM_ENUM) } receivers_t; #define COUNT_ITEMS(name, fn) +1 #define NUM_SYMS (0 SYM_LIST(COUNT_ITEMS)) #define NUM_SIMPLEPRIMS (NUM_SYMS SIMPLE_PRIM_LIST(COUNT_ITEMS)) #define NUM_EVALPRIMS (NUM_SIMPLEPRIMS EVAL_PRIM_LIST(COUNT_ITEMS)) #define NUM_APPLYPRIMS (NUM_EVALPRIMS APPLY_PRIM_LIST(COUNT_ITEMS)) #define NUM_PRIMS (NUM_APPLYPRIMS SEND_PRIM_LIST(COUNT_ITEMS)) #define FIRST_SEND_PRIM (NUM_APPLYPRIMS) #define LAST_PRIM (NUM_PRIMS - 1) #define LAST_LOCAL (256-8) #endif
26.051136
77
0.649945
[ "object" ]
28d115f3858cf171a3bbb878f184bbd4014a2b67
1,927
h
C
dev/Gems/WhiteBox/Code/Source/Asset/WhiteBoxMeshAssetUndoCommand.h
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/WhiteBox/Code/Source/Asset/WhiteBoxMeshAssetUndoCommand.h
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/WhiteBox/Code/Source/Asset/WhiteBoxMeshAssetUndoCommand.h
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once #include "WhiteBoxMeshAsset.h" #include <AzToolsFramework/Undo/UndoSystem.h> namespace WhiteBox { //! Records undo/redo states when modifying an asset. class WhiteBoxMeshAssetUndoCommand : public AzToolsFramework::UndoSystem::URSequencePoint { public: AZ_CLASS_ALLOCATOR_DECL AZ_RTTI( WhiteBoxMeshAssetUndoCommand, "{C99CD86C-035A-4FC9-AADC-4C746C38F119}", AzToolsFramework::UndoSystem::URSequencePoint) explicit WhiteBoxMeshAssetUndoCommand(AzToolsFramework::UndoSystem::URCommandID id); WhiteBoxMeshAssetUndoCommand(const WhiteBoxMeshAssetUndoCommand& other) = delete; WhiteBoxMeshAssetUndoCommand& operator=(const WhiteBoxMeshAssetUndoCommand& other) = delete; virtual ~WhiteBoxMeshAssetUndoCommand() = default; void SetAsset(AZ::Data::Asset<Pipeline::WhiteBoxMeshAsset> asset); void SetUndoState(const AZStd::vector<AZ::u8>& undoState); void SetRedoState(const AZStd::vector<AZ::u8>& redoState); // AzToolsFramework::UndoSystem::URSequencePoint ... void Undo() override; void Redo() override; bool Changed() const override; protected: AZ::Data::Asset<Pipeline::WhiteBoxMeshAsset> m_asset; AZStd::vector<AZ::u8> m_undoState; AZStd::vector<AZ::u8> m_redoState; }; } // namespace WhiteBox
37.784314
100
0.714063
[ "vector" ]
28e3ebeb209d7761e859f319309cc9aee434ca9d
2,916
h
C
Native/iOS/Smartface/smflibs/SMFCore.framework/Versions/Current/Headers/Core/SpBrParcelable.h
smartface/sf-plugin-instabug
e1fdcd2c21f9bd1bc32ad6a303522426e1aa4c1a
[ "MIT" ]
1
2021-04-26T04:41:08.000Z
2021-04-26T04:41:08.000Z
Native/iOS/Smartface/smflibs/SMFCore.framework/Versions/A/Headers/Core/SpBrParcelable.h
smartface/sf-plugin-instabug
e1fdcd2c21f9bd1bc32ad6a303522426e1aa4c1a
[ "MIT" ]
null
null
null
Native/iOS/Smartface/smflibs/SMFCore.framework/Versions/A/Headers/Core/SpBrParcelable.h
smartface/sf-plugin-instabug
e1fdcd2c21f9bd1bc32ad6a303522426e1aa4c1a
[ "MIT" ]
2
2018-03-14T07:33:09.000Z
2019-05-07T07:12:07.000Z
/* * SpBrParcelable.h * * Created on: 28 Tem 2011 * Author: ugur */ #ifndef SPBRPARCELABLE_H_ #define SPBRPARCELABLE_H_ #include <vector> #include <pthread.h> #include "SpDefs.h" #include "SpEventGroup.h" #include "SpBrObject.h" #include "SpRefCounted.h" #include <pthread.h> #include "SpJsEngine/Core/SpJsEngine.h" class SpDataSource; class SpBrString; class SpBrBase; class SpBrParcelable : public SpBrObject, public SpRefCounted { protected: SpBrString *name; SpBrString *fullname; bool isContainer; bool isWebObject; public: SpBrParcelable(); SpBrParcelable(SpBrParcelable* objectToCopy); virtual ~SpBrParcelable(); SpBrString* GetName(); SpBrString* GetFullName(); void SetName(SpBrString*); bool IsContainer(); bool IsWebObject(); /** * keeps type of object. it is assinged when object is creating. * you can see all types in SpBrNuiFactory.h */ int typeOfObject; /** * smf id that represt order of this item in whole project. */ int smfId; virtual void Protect(); virtual void Unprotect(); // important note: // 1. static objects grabbed on parse // 2. dynamic objects grabbed in constructor // 3. dynamic clones grabbed after constructor in factory //void grab(); void release(); //updated to use SpRefCounted. It will automatically grab on object creation public: virtual void Parse(SpDataSource **datasourcePtr, std::vector<SpBrParcelable*> *objects) {}; virtual void CloneCompleted(){}; virtual void Reset(bool invalidate = true) {}; void ChangeObjectValue(const char* targetAttribute, const char* value); virtual void ChangeObjectValue(SpBrString* targetAttribute, SpBrString* value); virtual bool ChangeObjectValuev2(const char *attribute, SpJsValue valueRef); virtual SpBrString* getObjectValue(SpBrString* targetAttribute){ return NULL; }; virtual void UpdateNativeValue(const char *attribute) {} ; /** * this function called when some event fires ending point. * dont fire again any SpEventGroup.fireEvent * * just process events comes from ui to core * * @param eventID Id of events. eventIDs listed under SpEventGroup.TEventID * @param eventCode code of processed events. this keeps additiona info about this event. such as which number pressed * * @author adem.cayir */ virtual void firedEventOnThis(int eventID,int eventCode) { } virtual void CreateJSObject(bool protect = true); SpJsObject GetJSObjectRef(); void UnloadJSObjectRef(); void SetJSObjectRef(SpJsObject objRef); SpEventGroup* GetEventGroup(); public: int mRefCount; bool isDynamicObject; pthread_mutex_t refMutex; void *externalData; protected: SpEventGroup *eventGroup; }; #endif /* SPBRPARCELABLE_H_ */
28.871287
123
0.692387
[ "object", "vector" ]
28e4115a3b5ccde8c52a15e2d33431fadea0a0fe
1,750
h
C
src/ModelField.h
fvutils/libvsc
1e52ad16fe3ca39e7807eee11e38ca30cb23f827
[ "Apache-2.0" ]
4
2021-08-04T07:42:55.000Z
2022-03-23T05:08:03.000Z
src/ModelField.h
fvutils/libvsc
1e52ad16fe3ca39e7807eee11e38ca30cb23f827
[ "Apache-2.0" ]
null
null
null
src/ModelField.h
fvutils/libvsc
1e52ad16fe3ca39e7807eee11e38ca30cb23f827
[ "Apache-2.0" ]
1
2020-11-20T02:36:49.000Z
2020-11-20T02:36:49.000Z
/* * ModelField.h * * Created on: Sep 24, 2021 * Author: mballance */ #pragma once #include <memory> #include <string> #include <vector> #include "IAccept.h" #include "ModelConstraint.h" #include "ModelVal.h" #include "TypeField.h" namespace vsc { using ModelFieldFlags=uint32_t; static const uint32_t ModelFieldFlag_DeclRand = (1 << 0); static const uint32_t ModelFieldFlag_UsedRand = (1 << 1); static const uint32_t ModelFieldFlag_Resoved = (1 << 2); static const uint32_t ModelFieldFlag_VecSize = (1 << 3); class ModelField; using ModelFieldUP=std::unique_ptr<ModelField>; class ModelField : public IAccept { public: ModelField(DataType *type); ModelField(); virtual ~ModelField(); virtual const std::string &name() const = 0; virtual DataType *datatype() const = 0; ModelField *parent() const { return m_parent; } void parent(ModelField *p) { m_parent = p; } const std::vector<ModelConstraintUP> &constraints() const { return m_constraints; } void add_constraint(ModelConstraint *c); const std::vector<ModelFieldUP> &fields() const { return m_fields; } void add_field(ModelField *field); const ModelVal &val() const { return m_val; } ModelVal &val() { return m_val; } ModelFieldFlags flags() const { return m_flags; } void clear_flag(ModelFieldFlags flags) { m_flags &= (~flags); } void set_flag(ModelFieldFlags flags) { m_flags |= flags; } bool is_flag_set(ModelFieldFlags flags) const { return ((m_flags & flags) == flags); } protected: ModelField *m_parent; // Typically only really used for scalar fields ModelVal m_val; std::vector<ModelFieldUP> m_fields; std::vector<ModelConstraintUP> m_constraints; ModelFieldFlags m_flags; }; } /* namespace vsc */
20.588235
69
0.711429
[ "vector" ]
28e5adb7865128b232f66826602448d11ea92209
2,170
h
C
ElectromagnetismProject/ElectromagnetismProjectComp/Renderer.h
psobolew-co/ElectromagneticsApp
078c94b710dc97c6e55df5388266d243e20c7462
[ "MIT" ]
1
2017-04-27T02:55:37.000Z
2017-04-27T02:55:37.000Z
ElectromagnetismProject/ElectromagnetismProjectComp/Renderer.h
psobolew-co/ElectromagneticsApp
078c94b710dc97c6e55df5388266d243e20c7462
[ "MIT" ]
null
null
null
ElectromagnetismProject/ElectromagnetismProjectComp/Renderer.h
psobolew-co/ElectromagneticsApp
078c94b710dc97c6e55df5388266d243e20c7462
[ "MIT" ]
null
null
null
#pragma once #include "Direct3DUtilities/Direct3DBase.h" #include "Board/VectorBoard.h" // Includes VectorCell.h #include "UI/Slider.h" #include "Enums/AppState.h" #include "ChargedObjects/ElectricObjectManager.h" #include "ChargedObjects/MagneticObject.h" #include "ChargedObjects/Puck.h" #include <map> static int SWIPE = 5; ref class Renderer sealed : public Direct3DBase { public: Renderer(); // Direct3DBase methods. virtual void CreateDeviceResources() override; virtual void CreateWindowSizeDependentResources() override; virtual void Render() override; // Method for updating time-dependent objects. void Update(float timeTotal, float timeDelta); // For handling touch input. void HandlePressInput(Windows::UI::Input::PointerPoint^ currentPoint); // called when pointer is down, alters state void HandleReleaseInput(Windows::UI::Input::PointerPoint^ currentPoint); // called when pointer is released, alters state void HandleMoveInput(Windows::UI::Input::PointerPoint^ currentPoint); private: AppState appState; float scale; // Scale for the screen (VERY IMPORTANT) unique_ptr<SpriteBatch> m_spriteBatch; ID3D11ShaderResourceView* arrowTexture; Sprite* arrow; VectorBoard* vectorBoard; ID3D11ShaderResourceView* posChargeTexture; ElectricObject* posCharge; ID3D11ShaderResourceView* negChargeTexture; ElectricObject* negCharge; ID3D11ShaderResourceView* chargeBoxTexture; ID3D11ShaderResourceView* negChargeBoxTexture; Sprite* chargeBox; Sprite* negChargeBox; ElectricObjectManager* objectManager; map<Sprite*, ID3D11ShaderResourceView*> textures; Puck* puck; ID3D11ShaderResourceView* puckTexture; ID3D11ShaderResourceView* resetButtonTexture; Sprite* resetButton; ID3D11ShaderResourceView* startButtonTexture; Sprite* startButton; ID3D11ShaderResourceView* pauseButtonTexture; Sprite* pauseButton; Windows::Foundation::Rect* puckBounds; ID3D11ShaderResourceView* wireTexture; ID3D11ShaderResourceView* wireBoxTexture; Sprite* wireBox; MagneticObject* wire; //vector<ElectricObject*> electricObjects; bool onSprite(Sprite* thing, XMFLOAT2 point); void reset(); // Test variables XMFLOAT2 previousPoint; };
31.449275
122
0.803226
[ "render", "vector" ]
93a3445cc064b8407c231f6815175544ef647450
7,074
h
C
apps/moterm/moterm_driver.h
zbowling/mojo
4d2ed40dc2390ca98a6fea0580e840535878f11c
[ "BSD-3-Clause" ]
1
2020-04-28T14:35:10.000Z
2020-04-28T14:35:10.000Z
apps/moterm/moterm_driver.h
zbowling/mojo
4d2ed40dc2390ca98a6fea0580e840535878f11c
[ "BSD-3-Clause" ]
null
null
null
apps/moterm/moterm_driver.h
zbowling/mojo
4d2ed40dc2390ca98a6fea0580e840535878f11c
[ "BSD-3-Clause" ]
1
2020-04-28T14:35:11.000Z
2020-04-28T14:35:11.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. // |MotermDriver| is a class providing a |mojo.files.File| interface, // implementing termios-type features (e.g., line editing; TODO(vtl): lots to do // here), and appropriately processing bytes to/from the terminal (which gets // and sends "raw" data). In essence, this class includes what would // traditionally be called the terminal driver in a Unix kernel. #ifndef APPS_MOTERM_MOTERM_DRIVER_H_ #define APPS_MOTERM_MOTERM_DRIVER_H_ #include <stddef.h> #include <stdint.h> #include <deque> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "mojo/services/files/interfaces/file.mojom.h" #include "mojo/services/files/interfaces/types.mojom.h" // TODO(vtl): Maybe we should Mojo-fy the driver and run it as a separate app? class MotermDriver : public mojo::files::File { public: // The |Client| is basically the terminal implementation itself, to which // processed output (from an application, to the "file", through the driver) // is sent. It also receives other notifications (e.g., when the "file" is // closed or otherwise "broken"). class Client { public: // Called when we receive data (for the client to "display"). // TODO(vtl): Maybe add a way to throttle (e.g., for the client to not // accept all the data). // TODO(vtl): It's "probably OK" to call |Detach()| from inside this method, // but not verified. virtual void OnDataReceived(const void* bytes, size_t num_bytes) = 0; // Called when the terminal "file" is closed (via |Close()|). (The client // may optionally call |Detach()| in response.) virtual void OnClosed() = 0; // Called when this object is destroyed (which will happen if the other end // of the message pipe is closed). The client must not call |Detach()| in // response. (Obviously, this will only be called if the client has not // called |Detach()|.) virtual void OnDestroyed() = 0; }; // Static factory method. |client| must either outlive us, or if not call // |Detach()| before being destroyed. static base::WeakPtr<MotermDriver> Create( Client* client, mojo::InterfaceRequest<mojo::files::File> request); // Called by the client when it wishes to detach (i.e., no longer receive // calls). This will terminate the connection and us. void Detach(); // Called by the client when it has data to send. // TODO(vtl): Add a way to throttle. (We could do this via an |OnDataSent()| // ack, or in other ways as well, e.g., reporting how much data we have // enqueued.) For now, just queue data infinitely. // TODO(vtl): This is misnamed -- it's really "here's some input". void SendData(const void* bytes, size_t num_bytes); private: struct PendingRead { PendingRead(uint32_t num_bytes, const ReadCallback& callback); ~PendingRead(); uint32_t num_bytes; ReadCallback callback; }; MotermDriver(Client* client, mojo::InterfaceRequest<mojo::files::File> request); // We should only be deleted by "ourself" (via the strong binding). friend class mojo::StrongBinding<mojo::files::File>; ~MotermDriver() override; void HandleCanonicalModeInput(uint8_t ch); void CompletePendingReads(); void FlushInputLine(); void HandleOutput(const uint8_t* bytes, size_t num_bytes); // |mojo::files::File| implementation: void Close(const CloseCallback& callback) override; void Read(uint32_t num_bytes_to_read, int64_t offset, mojo::files::Whence whence, const ReadCallback& callback) override; void Write(mojo::Array<uint8_t> bytes_to_write, int64_t offset, mojo::files::Whence whence, const WriteCallback& callback) override; void ReadToStream(mojo::ScopedDataPipeProducerHandle source, int64_t offset, mojo::files::Whence whence, int64_t num_bytes_to_read, const ReadToStreamCallback& callback) override; void WriteFromStream(mojo::ScopedDataPipeConsumerHandle sink, int64_t offset, mojo::files::Whence whence, const WriteFromStreamCallback& callback) override; void Tell(const TellCallback& callback) override; void Seek(int64_t offset, mojo::files::Whence whence, const SeekCallback& callback) override; void Stat(const StatCallback& callback) override; void Truncate(int64_t size, const TruncateCallback& callback) override; void Touch(mojo::files::TimespecOrNowPtr atime, mojo::files::TimespecOrNowPtr mtime, const TouchCallback& callback) override; void Dup(mojo::InterfaceRequest<mojo::files::File> file, const DupCallback& callback) override; void Reopen(mojo::InterfaceRequest<mojo::files::File> file, uint32_t open_flags, const ReopenCallback& callback) override; void AsBuffer(const AsBufferCallback& callback) override; void Ioctl(uint32_t request, mojo::Array<uint32_t> in_values, const IoctlCallback& callback) override; // Helpers for |Ioctl()|: void IoctlGetSettings(mojo::Array<uint32_t> in_values, const IoctlCallback& callback); void IoctlSetSettings(mojo::Array<uint32_t> in_values, const IoctlCallback& callback); mojo::files::Error IoctlSetSettingsHelper(mojo::Array<uint32_t> in_values); Client* client_; // Set until |Detach()| is called. bool is_closed_; std::deque<uint8_t> send_data_queue_; // For canonical mode. Feeds into |send_data_queue_|. std::deque<uint8_t> input_line_queue_; std::deque<PendingRead> pending_read_queue_; // Note: This binding must be after |pending_read_queue_|, so that it gets // torn down before the callbacks in |pending_read_queue_| are destroyed // (otherwise we'll get |DCHECK()| failures). mojo::StrongBinding<mojo::files::File> binding_; // Terminal driver settings: // (Names roughly correspond to termios names.) // TODO(vtl): Add a way to set/change settings (including using ioctls). // TODO(vtl): Our support for termios requirements is very far from complete. // Input settings: // Canonical, a.k.a. "cooked", mode. If true, will echo, line buffer, etc. If // false, no input processing is done (other than perhaps to slightly // time-delay the availability of input -- we don't do this). bool icanon_; // If true, will convert input CRs to NLs (in canonical mode). bool icrnl_; uint8_t veof_; uint8_t verase_; // Output settings: // If true, will convert output CRs to CR-NL pairs. bool onlcr_; base::WeakPtrFactory<MotermDriver> weak_factory_; DISALLOW_COPY_AND_ASSIGN(MotermDriver); }; #endif // APPS_MOTERM_MOTERM_DRIVER_H_
39.741573
80
0.694091
[ "object" ]
93a4f1587eaeda53798252442c82786b4872a405
6,504
h
C
Osiris/InventoryChanger/GameItems/Storage.h
real-Shigure/Osiris
758c5aa1532a9e3d855941c382edaf899a88dc76
[ "MIT" ]
null
null
null
Osiris/InventoryChanger/GameItems/Storage.h
real-Shigure/Osiris
758c5aa1532a9e3d855941c382edaf899a88dc76
[ "MIT" ]
null
null
null
Osiris/InventoryChanger/GameItems/Storage.h
real-Shigure/Osiris
758c5aa1532a9e3d855941c382edaf899a88dc76
[ "MIT" ]
null
null
null
#pragma once #include <string_view> #include <vector> #include "Item.h" #include "../StaticData.h" namespace game_items { class Storage { public: void addPatch(int id, ItemName name, EconRarity rarity, std::string_view inventoryImage) { patchKits.emplace_back(id, name); addItem(Item::patch(rarity, patchKits.size() - 1, inventoryImage)); } void addGraffiti(int id, ItemName name, EconRarity rarity, std::string_view inventoryImage) { graffitiKits.emplace_back(id, name); const auto index = graffitiKits.size() - 1; addItem(Item::graffiti(rarity, index, inventoryImage)); addItem(Item::sealedGraffiti(rarity, index, inventoryImage)); } void addSticker(int id, ItemName name, EconRarity rarity, std::string_view inventoryImage, std::uint32_t tournamentID, TournamentTeam tournamentTeam, int tournamentPlayerID, bool isGoldenSticker) { stickerKits.emplace_back(id, name, tournamentID, tournamentTeam, tournamentPlayerID, isGoldenSticker); addItem(Item::sticker(rarity, stickerKits.size() - 1, inventoryImage)); } void addMusic(int musicID, ItemName name, std::string_view inventoryImage) { musicKits.emplace_back(musicID, name); addItem(Item::musicKit(EconRarity::Blue, musicKits.size() - 1, inventoryImage)); } void addVanillaKnife(WeaponId weaponID, std::string_view inventoryImage) { addItem(Item::skin(EconRarity::Red, weaponID, vanillaPaintIndex, inventoryImage)); } void addCollectible(EconRarity rarity, WeaponId weaponID, bool isOriginal, std::string_view inventoryImage) { addItem(Item::collectible(rarity, weaponID, static_cast<std::size_t>(isOriginal), inventoryImage)); } void addVanillaSkin(WeaponId weaponID, std::string_view inventoryImage) { addItem(Item::skin(EconRarity::Default, weaponID, vanillaPaintIndex, inventoryImage)); } void addServiceMedal(EconRarity rarity, std::uint32_t year, WeaponId weaponID, std::string_view inventoryImage) { addItem(Item::serviceMedal(rarity, weaponID, static_cast<std::size_t>(year), inventoryImage)); } void addTournamentCoin(EconRarity rarity, WeaponId weaponID, std::uint32_t tournamentEventID, std::string_view iconPath) { addItem(Item::tournamentCoin(rarity, weaponID, static_cast<std::size_t>(tournamentEventID), iconPath)); } void addPaintKit(int id, ItemName name, float wearRemapMin, float wearRemapMax) { paintKits.emplace_back(id, name, wearRemapMin, wearRemapMax); } void addGlovesWithLastPaintKit(EconRarity rarity, WeaponId weaponID, std::string_view iconPath) { addItem(Item::gloves(rarity, weaponID, paintKits.size() - 1, iconPath)); } void addSkinWithLastPaintKit(EconRarity rarity, WeaponId weaponID, std::string_view iconPath) { addItem(Item::skin(rarity, weaponID, paintKits.size() - 1, iconPath)); } void addNameTag(EconRarity rarity, WeaponId weaponID, std::string_view iconPath) { addItem(Item::nameTag(rarity, weaponID, 0, iconPath)); } void addAgent(EconRarity rarity, WeaponId weaponID, std::string_view iconPath) { addItem(Item::agent(rarity, weaponID, 0, iconPath)); } void addCase(EconRarity rarity, WeaponId weaponID, std::size_t descriptorIndex, std::string_view iconPath) { addItem(Item::crate(rarity, weaponID, descriptorIndex, iconPath)); } void addCaseKey(EconRarity rarity, WeaponId weaponID, std::string_view iconPath) { addItem(Item::caseKey(rarity, weaponID, 0, iconPath)); } void addOperationPass(EconRarity rarity, WeaponId weaponID, std::string_view iconPath) { addItem(Item::operationPass(rarity, weaponID, 0, iconPath)); } void addStatTrakSwapTool(EconRarity rarity, WeaponId weaponID, std::string_view iconPath) { addItem(Item::statTrakSwapTool(rarity, weaponID, 0, iconPath)); } void addSouvenirToken(EconRarity rarity, WeaponId weaponID, std::uint32_t tournamentEventID, std::string_view iconPath) { addItem(Item::souvenirToken(rarity, weaponID, static_cast<std::size_t>(tournamentEventID), iconPath)); } void addViewerPass(EconRarity rarity, WeaponId weaponID, std::uint32_t tournamentEventID, std::string_view iconPath) { addItem(Item::viewerPass(rarity, weaponID, static_cast<std::size_t>(tournamentEventID), iconPath)); } const auto& getStickerKit(const Item& item) const { assert(item.isSticker()); return stickerKits[item.getDataIndex()]; } const auto& getMusicKit(const Item& item) const { assert(item.isMusic()); return musicKits[item.getDataIndex()]; } const auto& getPaintKit(const Item& item) const { assert(item.isSkin() || item.isGloves()); return paintKits[item.getDataIndex()]; } const auto& getGraffitiKit(const Item& item) const { assert(item.isGraffiti() || item.isSealedGraffiti()); return graffitiKits[item.getDataIndex()]; } const auto& getPatchKit(const Item& item) const { assert(item.isPatch()); return patchKits[item.getDataIndex()]; } auto& getGameItems() { return gameItems; } const auto& getGameItems() const { return gameItems; } [[nodiscard]] std::uint16_t getServiceMedalYear(const Item& serviceMedal) const noexcept { assert(serviceMedal.isServiceMedal()); return static_cast<std::uint16_t>(serviceMedal.getDataIndex()); } [[nodiscard]] bool isCollectibleGenuine(const Item& collectible) const noexcept { assert(collectible.isCollectible()); return static_cast<bool>(collectible.getDataIndex()); } void compress() { paintKits.shrink_to_fit(); stickerKits.shrink_to_fit(); musicKits.shrink_to_fit(); graffitiKits.shrink_to_fit(); patchKits.shrink_to_fit(); gameItems.shrink_to_fit(); } private: void addItem(const Item& item) { gameItems.push_back(item); } static constexpr auto vanillaPaintIndex = 0; std::vector<PaintKit> paintKits{ { 0, { "", L"" }, 0.0f, 1.0f } }; std::vector<StickerKit> stickerKits; std::vector<MusicKit> musicKits; std::vector<GraffitiKit> graffitiKits; std::vector<PatchKit> patchKits; std::vector<Item> gameItems; }; }
32.683417
199
0.685578
[ "vector" ]
93a697fbeb393664c20502f22f63e5997b15ebe2
1,324
h
C
mlir/include/mlir/Dialect/Linalg/ComprehensiveBufferize/ComprehensiveBufferize.h
yuriykoch/llvm
c4ce4f0feb46ec7dd4235fa2709609be06fb2153
[ "Apache-2.0" ]
605
2019-10-18T01:15:54.000Z
2022-03-31T14:31:04.000Z
mlir/include/mlir/Dialect/Linalg/ComprehensiveBufferize/ComprehensiveBufferize.h
yuriykoch/llvm
c4ce4f0feb46ec7dd4235fa2709609be06fb2153
[ "Apache-2.0" ]
3,180
2019-10-18T01:21:21.000Z
2022-03-31T23:25:41.000Z
mlir/include/mlir/Dialect/Linalg/ComprehensiveBufferize/ComprehensiveBufferize.h
yuriykoch/llvm
c4ce4f0feb46ec7dd4235fa2709609be06fb2153
[ "Apache-2.0" ]
275
2019-10-18T05:27:22.000Z
2022-03-30T09:04:21.000Z
//===- ComprehensiveBufferize.h - Linalg bufferization pass -----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef MLIR_DIALECT_LINALG_COMPREHENSIVEBUFFERIZE_COMPREHENSIVE_BUFFERIZE_H #define MLIR_DIALECT_LINALG_COMPREHENSIVEBUFFERIZE_COMPREHENSIVE_BUFFERIZE_H #include "mlir/IR/BuiltinOps.h" namespace mlir { namespace linalg { namespace comprehensive_bufferize { struct BufferizationOptions; class BufferizationState; struct PostAnalysisStep; /// Bufferize the given operation. Reuses an existing BufferizationState object. LogicalResult runComprehensiveBufferize( Operation *op, const BufferizationOptions &options, BufferizationState &state, const std::vector<std::unique_ptr<PostAnalysisStep>> &extraSteps); /// Bufferize the given operation. LogicalResult runComprehensiveBufferize(Operation *op, const BufferizationOptions &options); } // namespace comprehensive_bufferize } // namespace linalg } // namespace mlir #endif // MLIR_DIALECT_LINALG_COMPREHENSIVEBUFFERIZE_COMPREHENSIVE_BUFFERIZE_H
34.842105
80
0.730363
[ "object", "vector" ]
93bc88b171891621c61cb074f1c5789e4f10b65e
17,342
h
C
Src/LFramework/COM/ComObject.h
L-proger/LFramework
e43cd53c091465e015b2aef22f4b855e22308455
[ "MIT" ]
3
2020-07-25T18:39:29.000Z
2021-11-07T08:36:19.000Z
Src/LFramework/COM/ComObject.h
L-proger/LFramework
e43cd53c091465e015b2aef22f4b855e22308455
[ "MIT" ]
null
null
null
Src/LFramework/COM/ComObject.h
L-proger/LFramework
e43cd53c091465e015b2aef22f4b855e22308455
[ "MIT" ]
null
null
null
#pragma once #include <LFramework/Detect/DetectOS.h> #include <LFramework/Guid.h> #include <LFramework/TypeTraits/FunctionTraits.h> #include <cstdint> #include <type_traits> #include <atomic> #include <string> #include <vector> #if (LF_TARGET_OS == LF_OS_WINDOWS) || (LF_TARGET_OS == LF_OS_CYGWIN) #define LFRAMEWORK_COM_CALL __stdcall #else #define LFRAMEWORK_COM_CALL #endif namespace LFramework { using InterfaceID = Guid; //IUnknown class IUnknown; template<class TInterface, class TImplementer> struct InterfaceRemap {}; template<typename Remap> struct RemapTraits { }; template<class TInterface, class TImplementer> struct RemapTraits<InterfaceRemap<TInterface, TImplementer>> { using InterfaceType = TInterface; using ImplementerType = TImplementer; }; template<class Interface> struct InterfaceAbi {}; template<class InterfaceAbi> bool InterfaceAbiInterfaceSupported(const InterfaceID& id) { if (InterfaceAbi::ID() == id) { return true; } if constexpr (!std::is_same_v<typename InterfaceAbi::Base, void>) { return InterfaceAbiInterfaceSupported<typename InterfaceAbi::Base>(id); } return false; }; struct RemapChainItemBase { using InterfaceAbiInterfaceSupportedPtr = bool(*)(const InterfaceID&); RemapChainItemBase* next = nullptr; InterfaceAbiInterfaceSupportedPtr isSupported = nullptr; void* getRemapPtr() { return reinterpret_cast<std::uint8_t*>(&isSupported) + sizeof(isSupported); } }; template<typename TRemap> struct RemapChainItem : RemapChainItemBase { RemapChainItem(typename RemapTraits<TRemap>::ImplementerType* implementer) { remap._implementer = implementer; this->isSupported = &InterfaceAbiInterfaceSupported<InterfaceAbi<typename RemapTraits<TRemap>::InterfaceType>>; implementer->registerRemap(this); } TRemap remap; }; template<class Implementer, class FirstInterface, class ... Interfaces> struct ComRemapList : ComRemapList<Implementer, Interfaces...> { using Base = ComRemapList<Implementer, Interfaces...>; ComRemapList(Implementer* _this) : Base(_this), remapContainer{ _this } {} RemapChainItem<InterfaceRemap<FirstInterface, Implementer>> remapContainer; }; template<class Implementer, class FirstInterface> struct ComRemapList<Implementer, FirstInterface> { ComRemapList(Implementer* _this) : remapContainer{ _this } {} RemapChainItem<InterfaceRemap<FirstInterface, Implementer>> remapContainer; }; template<class T> struct IsInterface : std::conditional_t<std::is_base_of_v<InterfaceAbi<IUnknown>, InterfaceAbi<T>>, std::true_type, std::false_type> {}; template<class...T> struct IsAllInterfaces : std::conjunction<IsInterface<T>...> {}; template<class TImplementer, class TBase, class ... TInterfaceList> struct ComImplement : public TBase { using ComImplement_BaseType = TBase; using ComImplement_SelfType = ComImplement; using Implementer = TImplementer; ComRemapList<TImplementer, TInterfaceList...> _remaps = { reinterpret_cast<TImplementer*>(this) }; }; template<class T, class = void> struct IsComImplement : std::false_type {}; template<class T> struct IsComImplement<T, std::void_t<typename T::ComImplement_SelfType>> : std::true_type {}; template<class...T> struct IsAllComImplement : std::conjunction<IsComImplement<T>...> {}; template<class TInterface, class ... TInterfaceList> struct HasInterface : std::disjunction<std::is_base_of<InterfaceAbi<TInterface>, InterfaceAbi<TInterfaceList>>...> {}; template<class TImplementer, class TInterface> class ComDelegate; template<class T> struct IsComDelegate : std::false_type {}; template<class TImplementer, class TInterface> struct IsComDelegate<ComDelegate<TImplementer, TInterface>> : std::true_type {}; enum class Result : uint32_t { Ok = 0, NotImplemented = 0x80004001L, NoInterface = 0x80004002L, ErrorPointer = 0x80004003L, UnknownFailure = 0x80004005L, OutOfMemory = 0x8007000EL, InvalidArg = 0x80070057L, Pending = 0x8000000AL, AsyncOperationNotStarted = 0x80000019L, RpcTimeout = 0x8001011FL, RpcDisconnected = 0x80010108L }; struct ComException : std::exception { ComException(Result code) : _errorCode(code) { } ComException() : ComException(Result::UnknownFailure) { } ComException(Result code, std::string message) :_errorCode(code), _message(std::move(message)) { } ComException(std::string message) : ComException(Result::UnknownFailure, std::move(message)) { } Result code() const { return _errorCode; } char const* what() const noexcept override { return _message.c_str(); } const std::string& message() const { return _message; } private: Result _errorCode; std::string _message; }; template<> struct InterfaceAbi<IUnknown> { public: using Base = void; static constexpr InterfaceID ID() { return { 0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46} }; } template<class TInterface> friend class ComPtr; friend class ComObject; private: virtual Result LFRAMEWORK_COM_CALL queryInterface(const InterfaceID& riid, void** ppvObject) = 0; virtual std::uint32_t LFRAMEWORK_COM_CALL addRef() = 0; virtual std::uint32_t LFRAMEWORK_COM_CALL release() = 0; ~InterfaceAbi() = delete; }; template<class TImplementer> struct InterfaceRemap<IUnknown, TImplementer> { virtual Result LFRAMEWORK_COM_CALL queryInterface(const InterfaceID& riid, void** ppvObject) { return _implementer->queryInterface(riid, ppvObject); } virtual std::uint32_t LFRAMEWORK_COM_CALL addRef() { return _implementer->addRef(); } virtual std::uint32_t LFRAMEWORK_COM_CALL release() { return _implementer->release(); } inline auto implementer() { if constexpr (IsComDelegate<TImplementer>::value) { return _implementer->getImplementer(); } else { return _implementer; } } TImplementer* _implementer; ~InterfaceRemap() = default; }; template <class TInterface, class TComImplement> struct IsComImplementSupportsInterface : std::false_type {}; template <class TInterface, class TImplementer, class TBase, class ... TInterfaceList> struct IsComImplementSupportsInterface<TInterface, ComImplement<TImplementer, TBase, TInterfaceList...>> : HasInterface<TInterface, TInterfaceList...> {}; class RefCountedObject { public: virtual ~RefCountedObject() = default; std::uint32_t addRef() { return _refCount.fetch_add(1) + 1; } std::uint32_t release() { auto result = _refCount.fetch_sub(1); if (result == 1) { delete this; } return result - 1; } private: std::atomic<unsigned long> _refCount{}; }; template<class TInterface> class ComPtr; class ComObject : public RefCountedObject { public: template<typename TRemap> friend struct RemapChainItem; ComObject() { _headRemap.next = &_headRemap; } template<typename TInterface> ComPtr<TInterface> queryInterface() { void* result = nullptr; if(queryInterface(InterfaceAbi<TInterface>::ID(), &result) == Result::Ok){ auto abiPtr = reinterpret_cast<InterfaceAbi<TInterface>*>(result); ComPtr<TInterface> result; result.attach(abiPtr); return result; } return nullptr; } Result queryInterface(const InterfaceID& riid, void** ppvObject) { if (ppvObject == nullptr) { return Result::ErrorPointer; } findInterface(riid, ppvObject); if (*ppvObject == nullptr) { return Result::NoInterface; } else { auto obj = (reinterpret_cast<InterfaceAbi<IUnknown>*>(*ppvObject)); obj->addRef(); return Result::Ok; } } private: void findInterface(const InterfaceID& id, void** result) { RemapChainItemBase* current = &_headRemap; do { if (current->isSupported(id)) { *result = current->getRemapPtr(); return; } current = current->next; } while (current != &_headRemap); *result = nullptr; } void registerRemap(RemapChainItemBase* remap) { remap->next = _headRemap.next; _headRemap.next = remap; } RemapChainItem<InterfaceRemap<IUnknown, ComObject>> _headRemap{ this }; }; template<class TImplementer, class TInterface> constexpr bool IsInterfaceSupported() { if constexpr(!LFramework::IsInterface<TInterface>::value || !IsComImplement<TImplementer>::value){ return false; }else{ if constexpr(std::is_same_v<TImplementer, ComObject> && std::is_same_v<TInterface, LFramework::IUnknown>){ return true; }else{ if constexpr (LFramework::IsComImplementSupportsInterface<TInterface, typename TImplementer::ComImplement_SelfType>::value){ return true; }else{ return IsInterfaceSupported<typename TImplementer::ComImplement_BaseType, TInterface>(); } } } } template<class TInterface> class InterfaceWrapper { public: using NotSpecialized = bool; }; template<class TInterface, class = void> class HasInterfaceWrapper : public std::true_type {}; template<class TInterface> class HasInterfaceWrapper<TInterface, std::void_t<typename LFramework::InterfaceWrapper<TInterface>::NotSpecialized>> : public std::false_type {}; template<class TInterface> class ComPtr { public: using InterfacePtr = InterfaceAbi<TInterface>*; using PublicInterfacePtr = std::conditional_t<HasInterfaceWrapper<TInterface>::value, InterfaceWrapper<TInterface>*, InterfacePtr>; ComPtr() = default; ComPtr(InterfacePtr ptr) : _interface(ptr){ if(_interface != nullptr){ _interface->addRef(); } } template<class U, class = std::enable_if_t<std::is_base_of_v<InterfaceAbi<TInterface>, InterfaceAbi<U>>>> ComPtr(ComPtr<U> ptr) : _interface(ptr._interface) { _interface->addRef(); } ComPtr(const ComPtr& ptr) : _interface(ptr._interface) { if(_interface != nullptr){ _interface->addRef(); } } template<class U> ComPtr<U> queryInterface(){ ComPtr<U> result; if(_interface->queryInterface(InterfaceAbi<U>::ID(), result.put()) == Result::Ok){ return result; } return {}; } ~ComPtr() { reset(); } PublicInterfacePtr operator ->() { if constexpr(HasInterfaceWrapper<TInterface>::value){ return reinterpret_cast<PublicInterfacePtr>(&_interface); }else{ return reinterpret_cast<InterfacePtr>(_interface); } } template<class U, class = std::enable_if_t<std::is_base_of_v<InterfaceAbi<TInterface>, InterfaceAbi<U>>>> operator ComPtr<U>(){ return ComPtr<U>(_interface); } ComPtr operator = (std::nullptr_t) { reset(); return *this; } ComPtr operator = (const ComPtr& other) { reset(); auto ptr = other._interface; if (ptr != nullptr) { ptr->addRef(); } _interface = ptr; return *this; } bool operator == (const ComPtr& other) const { return _interface == other._interface; } bool operator != (const ComPtr& other) const { return _interface != other._interface; } bool operator == (std::nullptr_t) const { return _interface == nullptr; } bool operator != (std::nullptr_t) const { return _interface != nullptr; } InterfacePtr operator*() { return _interface; } const InterfacePtr operator*() const { return _interface; } operator bool() const { return (_interface != nullptr); } InterfacePtr get() const { return _interface; } void** put() { return reinterpret_cast<void**>(&_interface); } InterfacePtr detach() { auto result = _interface; _interface = nullptr; return result; } void attach(InterfacePtr ptr) { reset(); _interface = ptr; } void reset() { auto ptr = _interface; if (ptr != nullptr) { _interface = nullptr; ptr->release(); } } template<class TImplementer, class ... TArgs> static ComPtr create(TArgs&& ... args) { if constexpr(IsInterfaceSupported<TImplementer, TInterface>()){ auto obj = new TImplementer(std::forward<TArgs>(args)...); return obj->template queryInterface<TInterface>(); }else{ static_assert(IsInterfaceSupported<TImplementer, TInterface>(), "Interface not supported"); } } private: InterfacePtr _interface = nullptr; }; template<class TImplementer, class TInterface> class ComDelegate : public ComImplement<ComDelegate<TImplementer, TInterface>, ComObject, TInterface> { public: using DelegatedImplementer = TImplementer; typedef void (TImplementer::*DelegateDestroyCallback)(); ComDelegate(TImplementer* implementer, DelegateDestroyCallback destroyCallback) : _implementer(implementer), _destroyCallback(destroyCallback) { if constexpr (std::is_base_of_v<RefCountedObject, TImplementer>) { _implementer->addRef(); } } ~ComDelegate() { if (_destroyCallback != nullptr) { ((_implementer)->*(_destroyCallback))(); } if constexpr (std::is_base_of_v<RefCountedObject, TImplementer>) { _implementer->release(); } } TImplementer* getImplementer() { return _implementer; } private: DelegateDestroyCallback _destroyCallback; TImplementer* _implementer; }; template<class TInterface, class TImplementer> ComPtr<TInterface> makeComDelegate(TImplementer* implementer, typename ComDelegate<TImplementer, TInterface>::DelegateDestroyCallback delegateDestroyCallback = nullptr) { return ComPtr<TInterface>::template create<ComDelegate<TImplementer, TInterface>>(implementer, delegateDestroyCallback); } class ArrayOutMarshaler { public: using SizeType = std::uint32_t; typedef void* ContextPtr; typedef void* (LFRAMEWORK_COM_CALL *ContainerResizeCallback)(ContextPtr context, SizeType size); ContextPtr context; ContainerResizeCallback callback; template<typename T> ArrayOutMarshaler(std::vector<T>& buffer) { context = &buffer; callback = &ArrayOutMarshaler::resizeCallback<T>; } ArrayOutMarshaler(std::string& buffer) { context = &buffer; callback = &ArrayOutMarshaler::resizeCallback; } template<typename T> void operator = (const std::vector<T>& source) { void* data = callback(context, static_cast<SizeType>(source.size())); if (data != nullptr && !source.empty()) { memcpy(data, source.data(), sizeof(T) * source.size()); } } void operator = (const std::string& source) { void* data = callback(context, static_cast<SizeType>(source.size())); if (data != nullptr && !source.empty()) { memcpy(data, source.data(), source.size()); } } private: template<typename T> static void* LFRAMEWORK_COM_CALL resizeCallback(ContextPtr context, SizeType size) { auto container = reinterpret_cast<std::vector<T>*>(context); container->resize(size); return size == 0 ? nullptr : container->data(); } static void* LFRAMEWORK_COM_CALL resizeCallback(ContextPtr context, SizeType size) { auto container = reinterpret_cast<std::string*>(context); container->resize(size); return size == 0 ? nullptr : container->data(); } ArrayOutMarshaler() = delete; }; class ArrayInMarshaler { public: using SizeType = std::uint32_t; const void* data; SizeType itemsCount; ArrayInMarshaler(const std::string& source) { data = source.data(); itemsCount = static_cast<SizeType>(source.size()); } template<typename T> ArrayInMarshaler(const std::vector<T>& source) { data = source.data(); itemsCount = static_cast<SizeType>(source.size()); } operator std::string() const { return std::string(reinterpret_cast<const char*>(data), itemsCount); } template<typename T> operator std::vector<T>() const { std::vector<T> result; if (itemsCount != 0) { result.resize(itemsCount); memcpy(result.data(), data, sizeof(T) * itemsCount); } return result; } private: ArrayInMarshaler() = delete; }; template<> class InterfaceWrapper<IUnknown> { public: template<typename TInterface, typename = typename std::enable_if<std::is_base_of<InterfaceAbi<IUnknown>, InterfaceAbi<TInterface>>::value>::type> ComPtr<TInterface> queryInterface() { if (_abi == nullptr) { return {}; } ComPtr<TInterface> result{}; reinterpret_cast<InterfaceAbi<IUnknown>*>(_abi)->queryInterface(TInterface::VMT::ID(), reinterpret_cast<void**>(&result)); return result; } protected: void* _abi = nullptr; }; }
29.343486
170
0.666128
[ "vector" ]
93cd9cf3d882d6b40ea69d106a2fed75aefcf717
2,597
h
C
include/IzSQLUtilities/SQLFunctions.h
Izowiuz/iz-sql-utilities
307a5c791f4e83b13e9a54dfec60fcd4c24b2ca3
[ "MIT" ]
1
2019-07-11T07:05:03.000Z
2019-07-11T07:05:03.000Z
include/IzSQLUtilities/SQLFunctions.h
Izowiuz/iz-sql-utilities
307a5c791f4e83b13e9a54dfec60fcd4c24b2ca3
[ "MIT" ]
null
null
null
include/IzSQLUtilities/SQLFunctions.h
Izowiuz/iz-sql-utilities
307a5c791f4e83b13e9a54dfec60fcd4c24b2ca3
[ "MIT" ]
null
null
null
#pragma once #include "IzSQLUtilities/IzSQLUtilities_Enums.h" #include "IzSQLUtilities/IzSQLUtilities_Global.h" #include <QObject> #include <QSharedPointer> #include <QSqlError> #include <QVariantMap> namespace IzSQLUtilities { class IZSQLUTILITIESSHARED_EXPORT SQLFunctions : public QObject { Q_OBJECT Q_DISABLE_COPY(SQLFunctions) public: // ctor explicit SQLFunctions(QObject* parent = nullptr); // dtor ~SQLFunctions() = default; // directly calls sql procedure Q_INVOKABLE bool callProcedure(const QString& functionName, const QString& sqlDefinition, const QVariantMap& parameters, bool emitStatusSignals = true); Q_INVOKABLE bool callProcedure(const char* functionName, const char* sqlDefinition, const QVariantMap& parameters, bool emitStatusSignals = true); // static, state less variant of the callProcedure function static bool callProcedureStatic(const char* functionName, const char* sqlDefinition, const QVariantMap& parameters, DatabaseType databaseType = DatabaseType::MSSQL, const QVariantMap& connectionParameters = {}); // checks for SQL object avability in given table and column Q_INVOKABLE bool objectNameAvailable(const QString& table, const QString& column, const QString& object); // checks for SQL object avability in given table and column Q_INVOKABLE bool objectNameAvailableWithConstrain(const QString& table, const QString& column, const QString& object, const QString& type, int typeID); // m_connectionParameters setter / getter QVariantMap connectionParameters() const; void setConnectionParameters(const QVariantMap& connectionParameters); // m_databaseType setter / getter IzSQLUtilities::DatabaseType databaseType() const; void setDatabaseType(const IzSQLUtilities::DatabaseType& databaseType); // sql database type IzSQLUtilities::DatabaseType m_databaseType{ IzSQLUtilities::DatabaseType::MSSQL }; // sql connection parameters QVariantMap m_connectionParameters; private: // tries to sanitize sql parameter for dynamic queries QString sanitize(const QString& parameter) const; signals: // emited when procedure successfully finished void success(QString operation); // emited when function have started void operationStarted(QString operation); // emited when function have ended void operationEnded(QString operation); }; } // namespace IzSQLUtilities
38.761194
219
0.722757
[ "object" ]
93d861bc7b5c66148fd45e1b203456bfc0ef7e3c
2,125
h
C
arch/dev/RPC_unix.h
svp-dev/mgsim
0abd708f3c48723fc233f6c53f3e638129d070fa
[ "MIT" ]
7
2016-03-01T13:16:59.000Z
2021-08-20T07:41:43.000Z
arch/dev/RPC_unix.h
svp-dev/mgsim
0abd708f3c48723fc233f6c53f3e638129d070fa
[ "MIT" ]
null
null
null
arch/dev/RPC_unix.h
svp-dev/mgsim
0abd708f3c48723fc233f6c53f3e638129d070fa
[ "MIT" ]
5
2015-04-20T14:29:38.000Z
2018-12-29T11:09:17.000Z
// -*- c++ -*- #ifndef RPC_UNIX_H #define RPC_UNIX_H #include <arch/dev/RPC.h> #include <sim/inspect.h> #include <vector> #include <dirent.h> namespace Simulator { class UnixInterface : public Object, public IRPCServiceProvider, public Inspect::Interface<Inspect::Info> { typedef int HostFD; typedef size_t VirtualFD; struct VirtualDescriptor { bool active; HostFD hfd; DIR *dir; CycleNo cycle_open; CycleNo cycle_use; std::string fname; VirtualDescriptor() : active(false), hfd(-1), dir(NULL), cycle_open(0), cycle_use(0), fname() {} VirtualDescriptor(const VirtualDescriptor&) = default; VirtualDescriptor& operator=(const VirtualDescriptor&) = default; }; std::vector<VirtualDescriptor> m_vfds; VirtualDescriptor* GetEntry(VirtualFD vfd); VirtualFD GetNewVFD(HostFD new_hfd); VirtualFD DuplicateVFD(VirtualFD original, HostFD new_hfd); VirtualDescriptor* DuplicateVFD2(VirtualFD original, VirtualFD target); // statistics DefineSampleVariable(uint64_t, nrequests); DefineSampleVariable(uint64_t, nfailures); DefineSampleVariable(uint64_t, nstats); DefineSampleVariable(uint64_t, nreads); DefineSampleVariable(uint64_t, nread_bytes); DefineSampleVariable(uint64_t, nwrites); DefineSampleVariable(uint64_t, nwrite_bytes); public: UnixInterface(const std::string& name, Object& parent); void Service(uint32_t procedure_id, std::vector<char>& res1, size_t res1_maxsize, std::vector<char>& res2, size_t res2_maxsize, const std::vector<char>& arg1, const std::vector<char>& arg2, uint32_t arg3, uint32_t arg4) override; const std::string& GetName() const override; void Cmd_Info(std::ostream& out, const std::vector<std::string>& /*args*/) const override; }; } #endif
30.357143
109
0.616
[ "object", "vector" ]
93e172b82fc7ddd94eb3d22bf670245781e1631b
4,640
h
C
include/EarlyAnalysis/OilAllusionResolution.h
OutOfTheVoid/OakC
773934cc52bd4433f95c8c2de1ee231b8de4d0ad
[ "MIT" ]
1
2017-04-11T16:33:37.000Z
2017-04-11T16:33:37.000Z
include/EarlyAnalysis/OilAllusionResolution.h
OutOfTheVoid/OakC
773934cc52bd4433f95c8c2de1ee231b8de4d0ad
[ "MIT" ]
null
null
null
include/EarlyAnalysis/OilAllusionResolution.h
OutOfTheVoid/OakC
773934cc52bd4433f95c8c2de1ee231b8de4d0ad
[ "MIT" ]
null
null
null
#ifndef EARLYANALYSIS_OILALLUSIONRESOLUTION_H #define EARLYANALYSIS_OILALLUSIONRESOLUTION_H #include <vector> #include <unordered_map> #include <string> class OilNamespaceDefinition; class OilBindingStatement; class OilConstStatement; class OilTypeDefinition; class OilFunctionDefinition; class OilTraitDefinition; class OilTypeAlias; class IOilLoop; class OilFunctionParameter; class OilMatchBranch; class OilMemberDestructure; class OilEnum; class OilAllusionResolution_NameMapStack { public: enum NameContextType { kNameContext_Namespace, kNameContext_Function, kNameContext_Template, kNameContext_Match, kNameContext_MatchBranch, kNameContext_StatementBlock, }; enum MappingType { kMappingType_None, kMappingType_Namespace, kMappingType_BindingStatement, kMappingType_ConstantStatement, kMappingType_TypeDefinition, kMappingType_FunctionDefinition, kMappingType_TraitDefinition, kMappingType_TypeAlias, kMappingType_LabledLoop, kMappingType_FunctionParameter, kMappingType_MatchBranchValue, kMappingType_MemberDestructure, kMappingType_Enum }; typedef struct NameMapping_Struct { NameMapping_Struct (); NameMapping_Struct ( OilNamespaceDefinition * Namespace ); NameMapping_Struct ( OilBindingStatement * BindingStatement ); NameMapping_Struct ( OilConstStatement * ConstantStatement ); NameMapping_Struct ( OilTypeDefinition * TypeDefinition ); NameMapping_Struct ( OilFunctionDefinition * FunctionDefintiion ); NameMapping_Struct ( OilTraitDefinition * TraitDefinition ); NameMapping_Struct ( OilTypeAlias * TypeAlias ); NameMapping_Struct ( IOilLoop * LabledLoop ); NameMapping_Struct ( OilFunctionParameter * Parameter ); NameMapping_Struct ( OilMatchBranch * MatchBranchValue ); NameMapping_Struct ( OilMemberDestructure * MemberDestructure ); NameMapping_Struct ( OilEnum * Enum ); ~NameMapping_Struct (); MappingType Type; union { OilNamespaceDefinition * Namespace; OilBindingStatement * BindingStatement; OilConstStatement * ConstantStatement; OilTypeDefinition * TypeDefinition; OilFunctionDefinition * FunctionDefintiion; OilTraitDefinition * TraitDefinition; OilTypeAlias * TypeAlias; IOilLoop * LabledLoop; OilFunctionParameter * FunctionParameter; OilMatchBranch * MatchBranchValue; OilMemberDestructure * MemberDestructure; }; } NameMapping; OilAllusionResolution_NameMapStack ( OilNamespaceDefinition & GlobalNamespace ); ~OilAllusionResolution_NameMapStack (); void PushContext ( NameContextType Context ); void PopContext (); void AddNamespaceMapping ( const std :: u32string & Name, OilNamespaceDefinition * Namespace ); void AddBindingStatementMapping ( const std :: u32string & Name, OilBindingStatement * BindingStatement ); void AddConstStatementMapping ( const std :: u32string & Name, OilConstStatement * ConstantStatement ); void AddTypeMapping ( const std :: u32string & Name, OilTypeDefinition * TypeDefinition ); void AddFunctionMapping ( const std :: u32string & Name, OilFunctionDefinition * FunctionDefintiion ); void AddTraitMapping ( const std :: u32string & Name, OilTraitDefinition * TraitDefinition ); void AddTypeAliasMapping ( const std :: u32string & Name, OilTypeAlias * TypeAlias ); void AddLabledLoopMapping ( const std :: u32string & Label, IOilLoop * Loop ); void AddFunctionParameterMapping ( const std :: u32string & Name, OilFunctionParameter * Parameter ); void AddMatchBranchValueMapping ( const std :: u32string & Name, OilMatchBranch * MatchBranchValue ); void AddMemberDestructureMapping ( const std :: u32string & Name, OilMemberDestructure * MemberDestructure ); NameMapping LookupName ( const std :: u32string Name ); void ReadInScopeNames ( std :: vector <std :: u32string> & Out ); OilNamespaceDefinition & GetGlobalNamespace (); private: typedef struct NameContext_Struct { NameContext_Struct ( NameContextType Type ); NameContext_Struct ( const NameContext_Struct & CopyFrom ); ~NameContext_Struct (); NameContextType Type; std :: vector <std :: u32string> Names; } NameContext; std :: vector <NameContext *> Contexts; std :: unordered_map <std :: u32string, std :: vector <NameMapping>> NameMap; OilNamespaceDefinition & GlobalNamespace; }; enum AllusionResolutionResult { kAllusionResolutionResult_Success_Complete, kAllusionResolutionResult_Success_Progress, kAllusionResolutionResult_Success_NoProgress, kAllusionResolutionResult_Error }; AllusionResolutionResult OilAllusionResolution_Root ( OilNamespaceDefinition & RootNS ); #endif
30.12987
110
0.787931
[ "vector" ]
93ed57e8be1245a53679d9b4fa96fec48a96902f
11,202
c
C
libs/r3d/r3d.c
ands/libr3d
d421d44757e14b8120086a6b1912bc6bea0f6998
[ "MIT" ]
11
2016-07-19T02:30:26.000Z
2020-04-10T20:21:55.000Z
libs/r3d/r3d.c
ands/libr3d
d421d44757e14b8120086a6b1912bc6bea0f6998
[ "MIT" ]
null
null
null
libs/r3d/r3d.c
ands/libr3d
d421d44757e14b8120086a6b1912bc6bea0f6998
[ "MIT" ]
null
null
null
/********************************* * r3d -- 3D rendering library * * author: Andreas Mantler (ands) * *********************************/ #include <string.h> #include <r3d.h> typedef void (*r3d_primitive_rasterizer_func)(const float *in); static void r3d_points_rasterizer(const float *in); static void r3d_lines_rasterizer(const float *in); static void r3d_line_strip_rasterizer(const float *in); static void r3d_line_fan_rasterizer(const float *in); static void r3d_triangles_rasterizer(const float *in); static void r3d_triangle_strip_rasterizer(const float *in); static void r3d_triangle_fan_rasterizer(const float *in); //static void r3d_quads_rasterizer(const float *in); //static void r3d_quad_strip_rasterizer(const float *in); // public variables r3d_switch_t r3d_backface_culling = R3D_DISABLE; r3d_primitive_winding_t r3d_primitive_winding = R3D_PRIMITIVE_WINDING_CCW; r3d_shader_t r3d_shader = {0}; // private variables static vec2_t r3d_viewport_position = {0}; static vec2_t r3d_viewport_half_size = {0}; static int r3d_viewport_width = 0; static int r3d_viewport_height = 0; static float *r3d_primitive_vertex_buffer; static uint8_t r3d_primitive_vertex_index = 0; static r3d_primitive_rasterizer_func r3d_primitive_rasterizers[R3D_PRIMITIVE_TYPE_NUM] = { r3d_points_rasterizer, r3d_lines_rasterizer, r3d_line_strip_rasterizer, // line_loop: differentiation happens in r3d_draw. r3d_line_strip_rasterizer, r3d_line_fan_rasterizer, r3d_triangles_rasterizer, r3d_triangle_strip_rasterizer, r3d_triangle_fan_rasterizer, //r3d_quads_rasterizer, //r3d_quad_strip_rasterizer }; void r3d_viewport(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) { r3d_viewport_position.x = x0; r3d_viewport_position.y = y0; r3d_viewport_half_size.x = (float)(x1 - x0) * 0.5f; r3d_viewport_half_size.y = (float)(y1 - y0) * 0.5f; r3d_viewport_width = x1 - x0; r3d_viewport_height = y1 - y0; } void r3d_draw(const r3d_drawcall_t *drawcall) { const void *vs_in; float vs_out[R3D_VERTEX_ELEMENTS_MAX]; // initialize rasterizer float primitive_buffer[R3D_PRIMITIVE_VERTEX_BUFFER * R3D_VERTEX_ELEMENTS_MAX]; r3d_primitive_rasterizer_func rasterizer = r3d_primitive_rasterizers[drawcall->primitive_type]; r3d_primitive_vertex_buffer = primitive_buffer; r3d_primitive_vertex_index = 0; if(drawcall->indices == 0) { // rasterize vertex arrays vs_in = drawcall->vertices; const void *vs_end = vs_in + drawcall->count * drawcall->stride; if(drawcall->primitive_type == R3D_PRIMITIVE_TYPE_LINE_LOOP) { r3d_shader.vertexshader(vs_end - drawcall->stride, vs_out); rasterizer(vs_out); } while(vs_in != vs_end) { r3d_shader.vertexshader(vs_in, vs_out); rasterizer(vs_out); vs_in += drawcall->stride; } } else { // rasterize indexed arrays if(drawcall->primitive_type == R3D_PRIMITIVE_TYPE_LINE_LOOP) { vs_in = drawcall->vertices + drawcall->indices[drawcall->count - 1] * drawcall->stride; r3d_shader.vertexshader(vs_in, vs_out); rasterizer(vs_out); } for(uint32_t i = 0; i < drawcall->count; i++) { vs_in = drawcall->vertices + drawcall->indices[i] * drawcall->stride; r3d_shader.vertexshader(vs_in, vs_out); rasterizer(vs_out); } } } // interpolators static inline void r3d_primitive_linear_interpolate(const float *in0, const float *in1, float *out, float x) { float xr = 1.0f - x; for(int i = 0; i < r3d_shader.vertex_out_elements; i++) out[i] = in0[i] * xr + in1[i] * x; } static inline void r3d_primitive_barycentric_interpolate(const float *in0, const float *in1, const float *in2, float *out, float t0, float t1, float t2) { for(int i = 0; i < r3d_shader.vertex_out_elements; i++) out[i] = in0[i] * t0 + in1[i] * t1 + in2[i] * t2; } // temporary buffer access #define r3d_primitive_vertex_buffer(i) (r3d_primitive_vertex_buffer + (i) * r3d_shader.vertex_out_elements) #define r3d_primitive_vertex_buffer_put(i, in) memcpy(r3d_primitive_vertex_buffer(i), in, r3d_shader.vertex_out_elements * sizeof(float)); static inline void r3d_fragment_rasterizer(const float *in, uint16_t x, uint16_t y) { // TODO: alpha test float z = (in[2] - 1.0f) *-0.5f; if(z > r3d_get_depth(x, y)) { vec4_t color = r3d_shader.fragmentshader(in); color.r = float_clamp(color.r, 0.0f, 1.0f); color.g = float_clamp(color.g, 0.0f, 1.0f); color.b = float_clamp(color.b, 0.0f, 1.0f); r3d_set_pixel(x, y, z, color.rgb); } } static void r3d_points_rasterizer(const float *in) { if(in[0] < -1.0f || in[0] > 1.0f || in[1] < -1.0f || in[1] > 1.0f || in[2] < -1.0f || in[2] > 1.0f) return; uint16_t x = (uint16_t)((in[0] + 1.0f) * r3d_viewport_half_size.x + r3d_viewport_position.x); uint16_t y = (uint16_t)((in[1] - 1.0f) *-r3d_viewport_half_size.y + r3d_viewport_position.y); r3d_fragment_rasterizer(in, x, y); } static void r3d_line_rasterizer(const float *v0, const float *v1) { // bresenham int x0 = (int)((v0[0] + 1.0f) * r3d_viewport_half_size.x + r3d_viewport_position.x); int y0 = (int)((v0[1] - 1.0f) *-r3d_viewport_half_size.y + r3d_viewport_position.y); int x1 = (int)((v1[0] + 1.0f) * r3d_viewport_half_size.x + r3d_viewport_position.x); int y1 = (int)((v1[1] - 1.0f) *-r3d_viewport_half_size.y + r3d_viewport_position.y); int dx = x1 - x0, sx = x0 < x1 ? 1 : -1; int dy = y1 - y0, sy = y0 < y1 ? 1 : -1; if(dx < 0) dx = -dx; if(dy < 0) dy = -dy; int cur = 0, len = dx < dy ? dy : dx; int err = (dx > dy ? dx : -dy) / 2, e2; float t; float *vi = r3d_primitive_vertex_buffer(1); for(;;) { t = (float)(cur++) / (float)len; // TODO: incremental? r3d_primitive_linear_interpolate(v0, v1, vi, t); r3d_fragment_rasterizer(vi, x0, y0); if (x0 == x1 && y0 == y1) break; e2 = err; if (e2 >-dx) { err -= dy; x0 += sx; } if (e2 < dy) { err += dx; y0 += sy; } } } static void r3d_lines_rasterizer(const float *in) { if(r3d_primitive_vertex_index == 1) { r3d_line_rasterizer(r3d_primitive_vertex_buffer(0), in); r3d_primitive_vertex_index = 0; } else { r3d_primitive_vertex_buffer_put(0, in); r3d_primitive_vertex_index = 1; } } static void r3d_line_strip_rasterizer(const float *in) { if(r3d_primitive_vertex_index == 1) { r3d_line_rasterizer(r3d_primitive_vertex_buffer(0), in); r3d_primitive_vertex_buffer_put(0, in); } else { r3d_primitive_vertex_buffer_put(0, in); r3d_primitive_vertex_index = 1; } } static void r3d_line_fan_rasterizer(const float *in) { if(r3d_primitive_vertex_index == 1) { r3d_line_rasterizer(r3d_primitive_vertex_buffer(0), in); } else { r3d_primitive_vertex_buffer_put(0, in); r3d_primitive_vertex_index = 1; } } // screen orientations: cw vs ccw static inline float r3d_orientation2f(const float *i0, const float *i1, const float *i2) { return (i1[0] - i0[0]) * (i2[1] - i0[1]) - (i1[1] - i0[1]) * (i2[0] - i0[0]); } static inline int r3d_orientation2i(const int *i0, const int *i1, const int *i2) { return (i1[0] - i0[0]) * (i2[1] - i0[1]) - (i1[1] - i0[1]) * (i2[0] - i0[0]); } // triangle front face rasterizer static void r3d_triangle_front_rasterizer(const float *v0, const float *v1, const float *v2) { int i0[2], i1[2], i2[2]; i0[0] = (int)((v0[0] + 1.0f) * r3d_viewport_half_size.x + r3d_viewport_position.x); i0[1] = (int)((v0[1] - 1.0f) *-r3d_viewport_half_size.y + r3d_viewport_position.y); i1[0] = (int)((v1[0] + 1.0f) * r3d_viewport_half_size.x + r3d_viewport_position.x); i1[1] = (int)((v1[1] - 1.0f) *-r3d_viewport_half_size.y + r3d_viewport_position.y); i2[0] = (int)((v2[0] + 1.0f) * r3d_viewport_half_size.x + r3d_viewport_position.x); i2[1] = (int)((v2[1] - 1.0f) *-r3d_viewport_half_size.y + r3d_viewport_position.y); int minX = int_max(int_min(i0[0], int_min(i1[0], i2[0])), (int)r3d_viewport_position.x); // bounding box int minY = int_max(int_min(i0[1], int_min(i1[1], i2[1])), (int)r3d_viewport_position.y); int maxX = int_min(int_max(i0[0], int_max(i1[0], i2[0])), (int)r3d_viewport_position.x + r3d_viewport_width - 1); int maxY = int_min(int_max(i0[1], int_max(i1[1], i2[1])), (int)r3d_viewport_position.y + r3d_viewport_height - 1); int A01 = i0[1] - i1[1], B01 = i1[0] - i0[0]; // triangle setup int A12 = i1[1] - i2[1], B12 = i2[0] - i1[0]; int A20 = i2[1] - i0[1], B20 = i0[0] - i2[0]; int p[2] = { minX, minY }; // barycentric coordinates at minX/minY corner int w0_row = r3d_orientation2i(i1, i2, p); int w1_row = r3d_orientation2i(i2, i0, p); int w2_row = r3d_orientation2i(i0, i1, p); float vi[R3D_VERTEX_ELEMENTS_MAX]; // interpolated vertex for (p[1] = minY; p[1] <= maxY; p[1]++) { int w0 = w0_row; // barycentric coordinates at start of row int w1 = w1_row; int w2 = w2_row; for (p[0] = minX; p[0] <= maxX; p[0]++) { if ((w0 | w1 | w2) >= 0) // if p is on or inside all edges, render pixel. { float wai = 1.0f / (float)(w0 + w1 + w2); r3d_primitive_barycentric_interpolate(v0, v1, v2, vi, w0 * wai, w1 * wai, w2 * wai); r3d_fragment_rasterizer(vi, p[0], p[1]); } w0 += A12; // one step to the right w1 += A20; w2 += A01; } w0_row += B12; // one row step w1_row += B20; w2_row += B01; } } static void r3d_triangle_rasterizer(const float *v0, const float *v1, const float *v2) { if(r3d_primitive_winding == R3D_PRIMITIVE_WINDING_CCW) { if(r3d_orientation2f(v0, v1, v2) > 0.0f) r3d_triangle_front_rasterizer(v0, v2, v1); // ccw front face else if(!r3d_backface_culling) r3d_triangle_front_rasterizer(v0, v1, v2); // ccw back face } else { if(r3d_orientation2f(v0, v1, v2) < 0.0f) r3d_triangle_front_rasterizer(v0, v1, v2); // cw front face else if(!r3d_backface_culling) r3d_triangle_front_rasterizer(v0, v2, v1); // cw back face } } static void r3d_triangles_rasterizer(const float *in) { if(r3d_primitive_vertex_index == 2) { r3d_triangle_rasterizer(r3d_primitive_vertex_buffer(0), r3d_primitive_vertex_buffer(1), in); r3d_primitive_vertex_index = 0; } else { r3d_primitive_vertex_buffer_put(r3d_primitive_vertex_index, in); r3d_primitive_vertex_index++; } } static void r3d_triangle_strip_rasterizer(const float *in) { if(r3d_primitive_vertex_index == 2) { r3d_triangle_rasterizer(r3d_primitive_vertex_buffer(0), r3d_primitive_vertex_buffer(1), in); r3d_primitive_vertex_buffer_put(r3d_primitive_vertex_index, in); r3d_primitive_vertex_index++; } else if(r3d_primitive_vertex_index == 3) { r3d_triangle_rasterizer(r3d_primitive_vertex_buffer(2), r3d_primitive_vertex_buffer(1), in); r3d_primitive_vertex_buffer_put(0, r3d_primitive_vertex_buffer(2)); r3d_primitive_vertex_buffer_put(1, in); r3d_primitive_vertex_index = 2; } else { r3d_primitive_vertex_buffer_put(r3d_primitive_vertex_index, in); r3d_primitive_vertex_index++; } } static void r3d_triangle_fan_rasterizer(const float *in) { if(r3d_primitive_vertex_index == 2) { r3d_triangle_rasterizer(r3d_primitive_vertex_buffer(0), r3d_primitive_vertex_buffer(1), in); r3d_primitive_vertex_buffer_put(1, in); } else { r3d_primitive_vertex_buffer_put(r3d_primitive_vertex_index, in); r3d_primitive_vertex_index++; } } /*static void r3d_quads_rasterizer(const float *in) { } static void r3d_quad_strip_rasterizer(const float *in) { }*/
31.55493
152
0.707552
[ "render", "3d" ]
93f2ae3863266feab594f80f0794aed69d39d9f1
2,147
h
C
daemon/src/pipeline/pipeline_ops.h
strykeforce/deadeye
09d791e5fe0677f4d1890c7fc86ab2075725cca7
[ "MIT" ]
1
2020-01-30T05:21:37.000Z
2020-01-30T05:21:37.000Z
daemon/src/pipeline/pipeline_ops.h
strykeforce/deadeye
09d791e5fe0677f4d1890c7fc86ab2075725cca7
[ "MIT" ]
31
2019-10-14T10:11:02.000Z
2022-03-27T20:05:45.000Z
daemon/src/pipeline/pipeline_ops.h
strykeforce/deadeye
09d791e5fe0677f4d1890c7fc86ab2075725cca7
[ "MIT" ]
null
null
null
#pragma once #include <opencv2/imgproc.hpp> namespace deadeye { inline void MaskFrame(const cv::Mat& frame, cv::Mat& output, const cv::Scalar& low, const cv::Scalar& high) { cv::cvtColor(frame, output, cv::COLOR_BGR2HSV); cv::inRange(output, (low), (high), output); } using Contours = std::vector<std::vector<cv::Point>>; inline void FindContours(const cv::Mat& mask, Contours& contours) { contours.clear(); cv::findContours(mask, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); } /** * Filters according to filter; dest is copy of src if filters not enabled; */ inline void GeometricContoursFilter(const FilterConfig& filter, const Contours& src, Contours& dest) { dest.clear(); #ifndef NDEBUG if (filter.IsAreaEnabled()) assert(filter.frame_area > 0); #endif for (const auto& contour : src) { // set these to true if filter is skipped, false otherwise bool area_ok{true}; bool solidity_ok{true}; bool aspect_ok{true}; double area = cv::contourArea(contour); cv::Rect bb = cv::boundingRect(contour); if (filter.IsAreaEnabled()) { double bb_area = static_cast<double>(bb.area()); double ratio = bb_area / filter.frame_area; area_ok = ratio >= filter.area[0] && ratio <= filter.area[1]; // spdlog::debug("bb = {}, frame = {}, ratio = {}", bb.area(), // filter.frame_area, ratio); } if (filter.IsSolidityEnabled()) { std::vector<cv::Point> hull; cv::convexHull(contour, hull); double hull_area = cv::contourArea(hull); double solidity = area / hull_area; solidity_ok = solidity >= filter.solidity[0] && solidity <= filter.solidity[1]; // spdlog::debug("solidity = {}", solidity); } if (filter.IsAspectEnabled()) { double aspect = static_cast<double>(bb.width) / bb.height; aspect_ok = aspect >= filter.aspect[0] && aspect <= filter.aspect[1]; // spdlog::debug("aspect = {}", aspect); } if (area_ok && solidity_ok && aspect_ok) { dest.push_back(contour); } } } } // namespace deadeye
31.115942
79
0.623661
[ "vector" ]
75c97c0cc2fb046e8499f137ecbb9c326d4454ea
1,178
c
C
third_party/python/Python/initsite.c
appotry/cosmopolitan
af4687cc3f2331a23dc336183ab58fe001cda082
[ "ISC" ]
null
null
null
third_party/python/Python/initsite.c
appotry/cosmopolitan
af4687cc3f2331a23dc336183ab58fe001cda082
[ "ISC" ]
null
null
null
third_party/python/Python/initsite.c
appotry/cosmopolitan
af4687cc3f2331a23dc336183ab58fe001cda082
[ "ISC" ]
null
null
null
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ /* PYTHON_YOINK("site"); */ /* PYTHON_YOINK("_sysconfigdata_m_cosmo_x86_64_cosmo"); */ void _Py_InitSite(void) { PyObject *m; m = PyImport_ImportModule("site"); if (m == NULL) { fputs("Failed to import the site module\n", stderr); PyErr_Print(); Py_Finalize(); exit(1); } else { Py_DECREF(m); } }
34.647059
80
0.497453
[ "object" ]
75eb7e877d0e9a956672a1849303882c7262cfc7
2,430
h
C
gnuradio-3.7.13.4/gr-dtv/lib/atsc/atsc_deinterleaver_impl.h
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
1
2021-03-09T07:32:37.000Z
2021-03-09T07:32:37.000Z
gnuradio-3.7.13.4/gr-dtv/lib/atsc/atsc_deinterleaver_impl.h
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
null
null
null
gnuradio-3.7.13.4/gr-dtv/lib/atsc/atsc_deinterleaver_impl.h
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
null
null
null
/* -*- c++ -*- */ /* * Copyright 2014 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DTV_ATSC_DEINTERLEAVER_IMPL_H #define INCLUDED_DTV_ATSC_DEINTERLEAVER_IMPL_H #include <gnuradio/dtv/atsc_deinterleaver.h> #include "atsc_types.h" #include "interleaver_fifo.h" namespace gr { namespace dtv { class atsc_deinterleaver_impl : public atsc_deinterleaver { private: //! transform a single symbol unsigned char transform(unsigned char input) { unsigned char retval = m_fifo[m_commutator]->stuff(input); m_commutator++; if (m_commutator >= 52) m_commutator = 0; return retval; } /*! * Note: The use of the alignment_fifo keeps the encoder and decoder * aligned if both are synced to a field boundary. There may be other * ways to implement this function. This is a best guess as to how * this should behave, as we have no test vectors for either the * interleaver or deinterleaver. */ interleaver_fifo<unsigned char> alignment_fifo; int m_commutator; std::vector<interleaver_fifo<unsigned char> *> m_fifo; public: atsc_deinterleaver_impl(); ~atsc_deinterleaver_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); //! reset interleaver (flushes contents and resets commutator) void reset(); //! sync interleaver (resets commutator, but doesn't flush fifos) void sync() { m_commutator = 0; } }; } /* namespace dtv */ } /* namespace gr */ #endif /* INCLUDED_DTV_ATSC_DEINTERLEAVER_IMPL_H */
31.973684
76
0.687243
[ "vector", "transform" ]
2f04363266a3f0b047f69f86fdb135a910868729
1,015
h
C
MegamanX3/MegamanX3/Sprite.h
quangnghiauit/game
3c0537f96342c6fcb89cf5f3541acfef75b558f1
[ "MIT" ]
null
null
null
MegamanX3/MegamanX3/Sprite.h
quangnghiauit/game
3c0537f96342c6fcb89cf5f3541acfef75b558f1
[ "MIT" ]
null
null
null
MegamanX3/MegamanX3/Sprite.h
quangnghiauit/game
3c0537f96342c6fcb89cf5f3541acfef75b558f1
[ "MIT" ]
null
null
null
#pragma once #ifndef Sprite_H_ #define Sprite_H_ #include <d3d9.h> #include<d3dx9.h> #include<vector> using namespace std; #include"MyTexture.h" class Sprite { public: MyTexture* texture; int current_frame; int number_of_frame; int animation_time; int animation_count_time; vector<RECT*> List_source_rect; public: Sprite(); ~Sprite(); Sprite(const Sprite &sprite); Sprite(MyTexture* texture,vector<RECT*> List_source_rect, int animation_t); //sang frame tiếp theo void Next(); //trở về frame đầu tiên void Reset(); //chọn 1 frame nào đó void Set_current_frame(int index); // Render current sprite at location (X,Y) at the target surface void Draw(int x, int y); //Render with scale (-1, 1) void DrawFlipX(int x, int y); //render with scale (1, -1) void DrawFlipY(int x, int y); //Render Rect of texture at (x,y) void DrawRect(int X, int Y, RECT SrcRect); void DrawCurrentFrame(int index, int X, int Y); int GetCurrentFrame(); bool IsFinalFrame(); }; #endif // !Sprite_H_
17.5
76
0.71133
[ "render", "vector" ]
2f06ac984831db14adc5e5cde9b4fbd4b941f097
10,318
c
C
src/libgrate/vertex_disasm.c
Decatf/grate
d09cc85f849a1b3d0430abbf016b47dcad24cfef
[ "MIT" ]
64
2015-01-09T02:29:09.000Z
2022-03-30T19:45:07.000Z
src/libgrate/vertex_disasm.c
Decatf/grate
d09cc85f849a1b3d0430abbf016b47dcad24cfef
[ "MIT" ]
48
2015-01-23T17:01:46.000Z
2020-05-18T14:29:04.000Z
src/libgrate/vertex_disasm.c
Decatf/grate
d09cc85f849a1b3d0430abbf016b47dcad24cfef
[ "MIT" ]
13
2015-01-23T15:26:00.000Z
2021-03-23T17:21:28.000Z
/* * Copyright (c) 2016 Dmitry Osipenko <digetx@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "vpe_vliw.h" static char swizzle(unsigned swzl) { switch (swzl) { case SWIZZLE_X: return 'x'; case SWIZZLE_Y: return 'y'; case SWIZZLE_Z: return 'z'; case SWIZZLE_W: return 'w'; default: break; } return '!'; } static const char * vector_opcode(unsigned opcode) { switch (opcode) { case VECTOR_OPCODE_NOP: return "NOP"; case VECTOR_OPCODE_MOV: return "MOV"; case VECTOR_OPCODE_MUL: return "MUL"; case VECTOR_OPCODE_ADD: return "ADD"; case VECTOR_OPCODE_MAD: return "MAD"; case VECTOR_OPCODE_DP3: return "DP3"; case VECTOR_OPCODE_DPH: return "DPH"; case VECTOR_OPCODE_DP4: return "DP4"; case VECTOR_OPCODE_DST: return "DST"; case VECTOR_OPCODE_MIN: return "MIN"; case VECTOR_OPCODE_MAX: return "MAX"; case VECTOR_OPCODE_SLT: return "SLT"; case VECTOR_OPCODE_SGE: return "SGE"; case VECTOR_OPCODE_ARL: return "ARL"; case VECTOR_OPCODE_FRC: return "FRC"; case VECTOR_OPCODE_FLR: return "FLR"; case VECTOR_OPCODE_SEQ: return "SEQ"; case VECTOR_OPCODE_SGT: return "SGT"; case VECTOR_OPCODE_SLE: return "SLE"; case VECTOR_OPCODE_SNE: return "SNE"; case VECTOR_OPCODE_STR: return "STR"; case VECTOR_OPCODE_SSG: return "SSG"; case VECTOR_OPCODE_ARR: return "ARR"; case VECTOR_OPCODE_ARA: return "ARA"; case VECTOR_OPCODE_TXL: return "TXL"; case VECTOR_OPCODE_PUSHA: return "PUSHA"; case VECTOR_OPCODE_POPA: return "POPA"; case 28: return "OPCODE-28"; case 29: return "OPCODE-29"; case 30: return "OPCODE-30"; case 31: return "OPCODE-31"; default: break; } return "INVALID!"; } static const char * scalar_opcode(unsigned opcode) { switch (opcode) { case SCALAR_OPCODE_NOP: return "NOP"; case SCALAR_OPCODE_MOV: return "MOV"; case SCALAR_OPCODE_RCP: return "RCP"; case SCALAR_OPCODE_RCC: return "RCC"; case SCALAR_OPCODE_RSQ: return "RSQ"; case SCALAR_OPCODE_EXP: return "EXP"; case SCALAR_OPCODE_LOG: return "LOG"; case SCALAR_OPCODE_LIT: return "LIT"; case SCALAR_OPCODE_BRA: return "BRA"; case SCALAR_OPCODE_CAL: return "CAL"; case SCALAR_OPCODE_RET: return "RET"; case SCALAR_OPCODE_LG2: return "LG2"; case SCALAR_OPCODE_EX2: return "EX2"; case SCALAR_OPCODE_SIN: return "SIN"; case SCALAR_OPCODE_COS: return "COS"; case SCALAR_OPCODE_PUSHA: return "PUSHA"; case SCALAR_OPCODE_POPA: return "POPA"; case 17: return "OPCODE-17"; case 18: return "OPCODE-18"; case 21: return "OPCODE-21"; case 22: return "OPCODE-22"; case 23: return "OPCODE-23"; case 24: return "OPCODE-24"; case 25: return "OPCODE-25"; case 26: return "OPCODE-26"; case 27: return "OPCODE-27"; case 28: return "OPCODE-28"; case 29: return "OPCODE-29"; case 30: return "OPCODE-30"; case 31: return "OPCODE-31"; default: break; } return "INVALID!"; } static char address_register(int index) { switch (index) { case 0: return 'x'; case 1: return 'y'; case 2: return 'z'; case 3: return 'w'; default: break; } return '!'; } #define A 0 #define B 1 #define C 2 static const char * r(int reg, const vpe_instr128 *ins) { static char ret[3][32]; char *buf = ret[reg]; int index; int absolute_value; int type; int negate; int swizzle_x; int swizzle_y; int swizzle_z; int swizzle_w; switch (reg) { case A: index = ins->rA_index; absolute_value = ins->rA_absolute_value; type = ins->rA_type; negate = ins->rA_negate; swizzle_x = ins->rA_swizzle_x; swizzle_y = ins->rA_swizzle_y; swizzle_z = ins->rA_swizzle_z; swizzle_w = ins->rA_swizzle_w; break; case B: index = ins->rB_index; absolute_value = ins->rB_absolute_value; type = ins->rB_type; negate = ins->rB_negate; swizzle_x = ins->rB_swizzle_x; swizzle_y = ins->rB_swizzle_y; swizzle_z = ins->rB_swizzle_z; swizzle_w = ins->rB_swizzle_w; break; case C: index = ins->rC_index; absolute_value = ins->rC_absolute_value; type = ins->rC_type; negate = ins->rC_negate; swizzle_x = ins->rC_swizzle_x; swizzle_y = ins->rC_swizzle_y; swizzle_z = ins->rC_swizzle_z; swizzle_w = ins->rC_swizzle_w; break; default: return "!"; } memset(ret[reg], 0, 32); if (negate) buf += sprintf(buf, "-"); if (absolute_value) buf += sprintf(buf, "abs("); switch (type) { case REG_TYPE_UNDEFINED: buf += sprintf(buf, "u"); break; case REG_TYPE_TEMPORARY: buf += sprintf(buf, "r"); break; case REG_TYPE_ATTRIBUTE: buf += sprintf(buf, "a["); if (ins->attribute_relative_addressing_enable) { buf += sprintf(buf, "A0.%c + ", address_register(ins->address_register_select)); } break; case REG_TYPE_UNIFORM: buf += sprintf(buf, "c["); if (ins->constant_relative_addressing_enable) { buf += sprintf(buf, "A0.%c + ", address_register(ins->address_register_select)); } break; default: return "!"; } switch (type) { case REG_TYPE_TEMPORARY: buf += sprintf(buf, "%d", index); break; case REG_TYPE_ATTRIBUTE: buf += sprintf(buf, "%d]", ins->attribute_fetch_index); break; case REG_TYPE_UNIFORM: buf += sprintf(buf, "%d]", ins->uniform_fetch_index); break; default: break; } buf += sprintf(buf, ".%c%c%c%c", swizzle(swizzle_x), swizzle(swizzle_y), swizzle(swizzle_z), swizzle(swizzle_w)); if (absolute_value) sprintf(buf, ")"); return ret[reg]; } static const char * vec_rD(const vpe_instr128 *ins) { static char ret[9]; char *buf = ret; buf += sprintf(buf, "r%d.", ins->vector_rD_index); buf[0] = ins->vector_op_write_x_enable ? 'x' : '*'; buf[1] = ins->vector_op_write_y_enable ? 'y' : '*'; buf[2] = ins->vector_op_write_z_enable ? 'z' : '*'; buf[3] = ins->vector_op_write_w_enable ? 'w' : '*'; buf[4] = '\0'; return ret; } static const char * sca_rD(const vpe_instr128 *ins) { static char ret[9]; char *buf = ret; buf += sprintf(buf, "r%d.", ins->scalar_rD_index); buf[0] = ins->scalar_op_write_x_enable ? 'x' : '*'; buf[1] = ins->scalar_op_write_y_enable ? 'y' : '*'; buf[2] = ins->scalar_op_write_z_enable ? 'z' : '*'; buf[3] = ins->scalar_op_write_w_enable ? 'w' : '*'; buf[4] = '\0'; return ret; } const char * vpe_vliw_disassemble(const vpe_instr128 *ins) { static char ret[256]; char *buf = ret; memset(ret, 0, sizeof(ret)); buf += sprintf(buf, ins->end_of_program ? "EXEC_END" : "EXEC"); buf += sprintf(buf, "(export["); if (ins->export_relative_addressing_enable) { buf += sprintf(buf, "A0.%c + ", address_register(ins->address_register_select)); } buf += sprintf(buf, "%d]=%s)", ins->export_write_index, ins->export_vector_write_enable ? "vector" : "scalar"); if (ins->saturate_result) buf += sprintf(buf, "(saturate)"); buf += sprintf(buf, "(cr=%d)", ins->condition_register_index); if (ins->condition_set) buf += sprintf(buf, "(cs)"); if (ins->condition_check) buf += sprintf(buf, "(cc)"); if (ins->condition_flags_write_enable) buf += sprintf(buf, "(cwr)"); if (ins->predicate_lt) buf += sprintf(buf, "(lt)"); if (ins->predicate_eq) buf += sprintf(buf, "(eq)"); if (ins->predicate_gt) buf += sprintf(buf, "(gt)"); buf += sprintf(buf, "(p.%c%c%c%c)", swizzle(ins->predicate_swizzle_x), swizzle(ins->predicate_swizzle_y), swizzle(ins->predicate_swizzle_z), swizzle(ins->predicate_swizzle_w)); buf += sprintf(buf, "\n"); buf += sprintf(buf, "\t"); buf += sprintf(buf, "%sv ", vector_opcode(ins->vector_opcode)); switch (ins->vector_opcode) { case VECTOR_OPCODE_NOP: case VECTOR_OPCODE_PUSHA: case VECTOR_OPCODE_POPA: buf += sprintf(buf, "\n"); break; case VECTOR_OPCODE_ADD: buf += sprintf(buf, "%s, %s, %s\n", vec_rD(ins), r(A, ins), r(C, ins)); break; case VECTOR_OPCODE_MUL: case VECTOR_OPCODE_DP3: case VECTOR_OPCODE_DPH: case VECTOR_OPCODE_DP4: case VECTOR_OPCODE_DST: case VECTOR_OPCODE_MIN: case VECTOR_OPCODE_MAX: case VECTOR_OPCODE_SLT: case VECTOR_OPCODE_SGE: case VECTOR_OPCODE_SEQ: case VECTOR_OPCODE_SGT: case VECTOR_OPCODE_SLE: case VECTOR_OPCODE_SNE: buf += sprintf(buf, "%s, %s, %s\n", vec_rD(ins), r(A, ins), r(B, ins)); break; case VECTOR_OPCODE_STR: case VECTOR_OPCODE_ARA: buf += sprintf(buf, "%s\n", vec_rD(ins)); break; case VECTOR_OPCODE_MOV: case VECTOR_OPCODE_ARL: case VECTOR_OPCODE_FRC: case VECTOR_OPCODE_FLR: case VECTOR_OPCODE_SSG: case VECTOR_OPCODE_ARR: case VECTOR_OPCODE_TXL: buf += sprintf(buf, "%s, %s\n", vec_rD(ins), r(A, ins)); break; case VECTOR_OPCODE_MAD: default: buf += sprintf(buf, "%s, %s, %s, %s\n", vec_rD(ins), r(A, ins), r(B, ins), r(C, ins)); break; } buf += sprintf(buf, "\t"); buf += sprintf(buf, "%ss ", scalar_opcode(ins->scalar_opcode)); switch (ins->scalar_opcode) { case SCALAR_OPCODE_NOP: case SCALAR_OPCODE_PUSHA: case SCALAR_OPCODE_POPA: case SCALAR_OPCODE_RET: buf += sprintf(buf, "\n"); break; case SCALAR_OPCODE_BRA: case SCALAR_OPCODE_CAL: buf += sprintf(buf, "%d\n", ins->iaddr); break; default: buf += sprintf(buf, "%s, %s\n", sca_rD(ins), r(C, ins)); break; } sprintf(buf, ";"); return ret; }
21.860169
77
0.67736
[ "vector" ]
2f0f30944c4de45d02feb89c8c13d984e510f7e5
2,960
h
C
include/entities/MeshGeometry_t.h
guillaumetousignant/another_path_tracer
2738b32f91443ce15d1e7ab8ab77903bdfca695b
[ "MIT" ]
1
2019-08-08T12:19:45.000Z
2019-08-08T12:19:45.000Z
include/entities/MeshGeometry_t.h
guillaumetousignant/another_path_tracer
2738b32f91443ce15d1e7ab8ab77903bdfca695b
[ "MIT" ]
38
2019-07-11T16:18:00.000Z
2021-09-16T14:54:36.000Z
include/entities/MeshGeometry_t.h
guillaumetousignant/another_path_tracer
2738b32f91443ce15d1e7ab8ab77903bdfca695b
[ "MIT" ]
null
null
null
#ifndef APTRACER_MESHGEOMETRY_T_H #define APTRACER_MESHGEOMETRY_T_H #include "entities/Vec3f.h" #include <string> #include <vector> namespace APTracer { namespace Entities { /** * @brief The mesh geometry class represents a geometry made up of points and triangular faces. * * Mesh geometries represent a single geometry without any transformation. Multiple meshes can point to the same mesh geometry * while using different transformations, enabling instanciating and saving ressources. This class is constructed from geometry * input files. Currently, .obj and .su2 files are supported. */ class MeshGeometry_t { public: /** * @brief Construct a new MeshGeometry_t object from a geometry input file. * * The input file can have non-triangular faces, as those are triangularised. For .su2 files, the faces in the 'WALL' MARKER_TAG * sections will be used. * * @param filename Path to a geometry file of either .obj or .su2 format. */ MeshGeometry_t(const std::string &filename); size_t n_tris_; /**< @brief Number of triangular faces held by the mesh geometry.*/ std::vector<std::string> mat_; /**< @brief Array of strings representing each face's material's name. Size: n_tris_.*/ std::vector<Vec3f> v_; /**< @brief Array of points representing the triangular faces. Size: 3*n_tris_. Face i has the points v_[3*i], v_[3*i + 1], v_[3*i + 2].*/ std::vector<double> vt_; /**< @brief Array of uv coordinates representing the triangular faces' texture coordinates. Size: 6*n_tris_. Face i has the uvs [vt_[6*i], vt_[6*i+1]], [vt_[6*i+2], vt_[6*i+3]], [vt_[6*i+4], vt_[6*i+5]].*/ std::vector<Vec3f> vn_; /**< @brief Array of normals representing the triangular faces' normals. Size: 3*n_tris_. Face i has the normals vn_[3*i], vn_[3*i + 1], vn_[3*i + 2].*/ private: /** * @brief Fills the class' members form a .obj file. * * @param filename Path to a geometry file in .obj format. */ auto readObj(const std::string &filename) -> void; /** * @brief Fills the class' members form a .su2 file. * * The faces in the 'WALL' MARKER_TAG sections will be used. * * @param filename Path to a geometry file in .su2 format. */ auto readSU2(const std::string &filename) -> void; /** * @brief Constructs the face normals from the face points when none are supplied in the file. * * This will give a facetted look, as the faces will have the same normal at all points. */ auto deNan() -> void; }; }} #endif
48.52459
243
0.588176
[ "mesh", "geometry", "object", "vector" ]
2f1df46b5734a7b8cde52be32eb8cda4e95b7d6b
3,198
h
C
DEM/Src/nebula2/inc/deformers/nmeshdeformer.h
moltenguy1/deusexmachina
134f4ca4087fff791ec30562cb250ccd50b69ee1
[ "MIT" ]
2
2017-04-30T20:24:29.000Z
2019-02-12T08:36:26.000Z
DEM/Src/nebula2/inc/deformers/nmeshdeformer.h
moltenguy1/deusexmachina
134f4ca4087fff791ec30562cb250ccd50b69ee1
[ "MIT" ]
null
null
null
DEM/Src/nebula2/inc/deformers/nmeshdeformer.h
moltenguy1/deusexmachina
134f4ca4087fff791ec30562cb250ccd50b69ee1
[ "MIT" ]
null
null
null
#ifndef N_MESHDEFORMER_H #define N_MESHDEFORMER_H //------------------------------------------------------------------------------ /** @class nMeshDeformer @ingroup Deformers @brief Base class for mesh deformers running on the CPU. While using vertex shaders for mesh deformation is a good thing, it is not always an option, and may be too inflexible. Mesh deformers take one or more input meshes, plus deformer-specific and write their result to one output mesh. (C) 2004 RadonLabs GmbH */ #include "kernel/ntypes.h" #include "util/narray.h" #include "gfx2/nmesh2.h" //------------------------------------------------------------------------------ class nMeshDeformer { public: /// constructor nMeshDeformer(); /// destructor virtual ~nMeshDeformer(); /// set single input mesh void SetInputMesh(nMesh2* mesh); /// get single input mesh nMesh2* GetInputMesh() const; /// set single output mesh void SetOutputMesh(nMesh2* mesh); /// get single output mesh nMesh2* GetOutputMesh() const; /// set source start index void SetStartVertex(int i); /// get start index int GetStartVertex() const; /// get number of vertices to process void SetNumVertices(int n); /// get number of vertices to process int GetNumVertices() const; /// perform mesh deformation virtual void Compute(); protected: nRef<nMesh2> refInputMesh; nRef<nMesh2> refOutputMesh; int startVertex; int numVertices; }; //------------------------------------------------------------------------------ /** */ inline void nMeshDeformer::SetInputMesh(nMesh2* mesh) { this->refInputMesh = mesh; } //------------------------------------------------------------------------------ /** */ inline nMesh2* nMeshDeformer::GetInputMesh() const { return this->refInputMesh.get_unsafe(); } //------------------------------------------------------------------------------ /** */ inline void nMeshDeformer::SetOutputMesh(nMesh2* mesh) { this->refOutputMesh = mesh; } //------------------------------------------------------------------------------ /** */ inline nMesh2* nMeshDeformer::GetOutputMesh() const { return this->refOutputMesh.get_unsafe(); } //------------------------------------------------------------------------------ /** */ inline void nMeshDeformer::SetStartVertex(int i) { n_assert(i >= 0); this->startVertex = i; } //------------------------------------------------------------------------------ /** */ inline int nMeshDeformer::GetStartVertex() const { return this->startVertex; } //------------------------------------------------------------------------------ /** */ inline void nMeshDeformer::SetNumVertices(int n) { n_assert(n > 0); this->numVertices = n; } //------------------------------------------------------------------------------ /** */ inline int nMeshDeformer::GetNumVertices() const { return this->numVertices; } //------------------------------------------------------------------------------ #endif
23.514706
81
0.462164
[ "mesh" ]
2f1e05c672d3dd1d06f7f62d2dfc7e4ee11db984
8,724
c
C
tests/test-vector.c
sonaljain067/cap-containers
aced38c009e37444aeac50fa99d31097c55414cc
[ "MIT" ]
7
2021-03-27T07:54:14.000Z
2022-02-14T14:57:12.000Z
tests/test-vector.c
sonaljain067/cap-containers
aced38c009e37444aeac50fa99d31097c55414cc
[ "MIT" ]
27
2021-03-25T04:46:26.000Z
2021-09-17T17:09:38.000Z
tests/test-vector.c
sonaljain067/cap-containers
aced38c009e37444aeac50fa99d31097c55414cc
[ "MIT" ]
3
2021-05-08T18:06:41.000Z
2021-08-31T14:55:15.000Z
#include "internal/test-helper.h" #include <vector.h> #define _print_number(foo, val) printf("%s: %d\n", foo, val) #define _print_all_numbers(vector, size) \ for (size_t i = 0; i < size; i++) { printf("%d\n", *(int *)vector[i]); } bool predicate_fn_one(void *data) { if (*(int *)data == 20) { return true; } else { return false; } } bool predicate_fn_two(void *data) { if (*(int *)data == 30) { return true; } else { return false; } } void test_vector(void) { { cap_vector *vector_one = cap_vector_init(5); CAP_ASSERT_TRUE(cap_vector_empty(vector_one), "VECTOR empty"); int one = 10; // [10] cap_vector_push_back(vector_one, &one); CAP_ASSERT_TRUE(*(int *)cap_vector_front(vector_one) == one, "VECTOR front"); CAP_ASSERT_TRUE(*(int *)cap_vector_back(vector_one) == one, "VECTOR back"); int two = 20; // [10] [20] cap_vector_push_back(vector_one, &two); CAP_ASSERT_TRUE(*(int *)cap_vector_back(vector_one) == two && *(int *)cap_vector_front(vector_one) == one && !cap_vector_empty(vector_one), "VECTOR back, front, empty"); CAP_ASSERT_EQ(cap_vector_size(vector_one), 2, "VECTOR size"); CAP_ASSERT_EQ(cap_vector_capacity(vector_one), 5, "VECTOR capacity"); CAP_ASSERT_EQ(cap_vector_remaining_space(vector_one), 3, "VECTOR remaining space"); CAP_ASSERT_EQ(*(int *)cap_vector_pop_back(vector_one), two, "VETOR pop-back"); // [10] // [10] [20] cap_vector_push_back(vector_one, &two); int three = 30; // [10] [20] [30] cap_vector_push_back(vector_one, &three); void *find_two = cap_vector_find_if(vector_one, predicate_fn_one); CAP_ASSERT_TRUE(find_two != NULL, "VECTOR find_if return"); CAP_ASSERT_TRUE(*(int *)find_two == two, "VECTOR find_if return value check"); // [20] [30] CAP_ASSERT_EQ(*(int *)cap_vector_pop_front(vector_one), one, "VECTOR pop-front"); CAP_ASSERT_EQ(cap_vector_size(vector_one), 2, "VECTOR size"); CAP_ASSERT_EQ(*(int *)cap_vector_front(vector_one), two, "VECTOR front after pop"); CAP_ASSERT_EQ(*(int *)cap_vector_back(vector_one), three, "VETOR back after pop"); // [20] [30] [30] cap_vector_push_back(vector_one, &three); int four = 40; int five = 50; int six = 60; // [20] [30] [30] [40] [50] [60] cap_vector_push_back(vector_one, &four); cap_vector_push_back(vector_one, &five); cap_vector_push_back(vector_one, &six); CAP_ASSERT_EQ(cap_vector_capacity(vector_one), 10, "VECTOR capacity new"); CAP_ASSERT_EQ(cap_vector_size(vector_one), 6, "VECTOR new size"); // [20] [40] [50] [60] CAP_ASSERT_TRUE( cap_vector_remove_if(vector_one, predicate_fn_two), "VECTOR remove 30"); CAP_ASSERT_TRUE(*(int *)cap_vector_front(vector_one) == two && *(int *)cap_vector_back(vector_one) == six, "VECTOR front & back check"); CAP_ASSERT_TRUE(cap_vector_size(vector_one) == 4, "VECTOR size after remove"); CAP_ASSERT_EQ(cap_vector_capacity(vector_one), 10, "VECTOR capacity before resize"); CAP_ASSERT_TRUE(cap_vector_resize(vector_one, 12), "VECTOR resize"); CAP_ASSERT_EQ(cap_vector_capacity(vector_one), 12, "VECTOR after resize"); CAP_ASSERT_TRUE(cap_vector_shrink_to_fit(vector_one), "VECTOR shrink to fit"); CAP_ASSERT_TRUE(cap_vector_size(vector_one) == 4 && cap_vector_capacity(vector_one) == 4, "VECTOR size & capacity after shrink to fit"); cap_vector *vector_two = cap_vector_init(30); int seven = 70; cap_vector_push_back(vector_two, &seven); cap_vector_push_back(vector_two, &six); cap_vector_push_back(vector_two, &five); cap_vector_push_back(vector_two, &four); cap_vector_push_back(vector_two, &three); cap_vector_push_back(vector_two, &two); cap_vector_push_back(vector_two, &one); CAP_ASSERT_TRUE( cap_vector_size(vector_two) == 7 && cap_vector_capacity(vector_two) == 30 && *(int *)cap_vector_front(vector_two) == seven && *(int *)cap_vector_back(vector_two) == one, "VECTOR vector-two checks after init & push-back"); cap_vector_swap(vector_one, vector_two); CAP_ASSERT_TRUE(cap_vector_size(vector_one) == 7 && cap_vector_capacity(vector_one) == 30 && *(int *)cap_vector_front(vector_one) == seven && *(int *)cap_vector_back(vector_one) == one, "VECTOR vector-one checks after swap"); CAP_ASSERT_TRUE(cap_vector_size(vector_two) == 4 && cap_vector_capacity(vector_two) == 4 && *(int *)cap_vector_front(vector_two) == two && *(int *)cap_vector_back(vector_two) == six, "VECTOR vector-one checks after swap"); cap_vector_free(vector_one); cap_vector_free(vector_two); } { // Tests focused on Iterators cap_vector *vector = cap_vector_init(5); int one = 10; int two = 20; int three = 30; int four = 40; int five = 50; int six = 60; // [10] [20] [30] [40] [50] [60] cap_vector_push_back(vector, &one); cap_vector_push_back(vector, &two); cap_vector_push_back(vector, &three); cap_vector_push_back(vector, &four); cap_vector_push_back(vector, &five); cap_vector_push_back(vector, &six); cap_vector_iterator *vector_iterator = cap_vector_iterator_init(vector); CAP_ASSERT_TRUE(*(int *)vector_iterator->data == one, "VECTOR Iterator init check"); cap_vector_iterator_decrement(vector_iterator); CAP_ASSERT_TRUE(vector_iterator->data == NULL, "VECTOR Iterator dec NULL check"); cap_vector_iterator_increment(vector_iterator); CAP_ASSERT_TRUE(*(int *)vector_iterator->data == one, "VECTOR Iterator data check after error"); cap_vector_iterator_increment(vector_iterator); CAP_ASSERT_TRUE(*(int *)vector_iterator->data == two, "VECTOR Iterator incr"); cap_vector_iterator_increment(vector_iterator); // three cap_vector_iterator_decrement(vector_iterator); // two CAP_ASSERT_TRUE(*(int *)vector_iterator->data == two, "VECTOR Iterator incr"); CAP_ASSERT_TRUE(*(int *)cap_vector_iterator_next( vector_iterator) == three && *(int *)vector_iterator->data == two, "VECTOR Iterator next"); CAP_ASSERT_TRUE(*(int *)cap_vector_iterator_previous( vector_iterator) == one && *(int *)vector_iterator->data == two, "VECTOR Iterator previous"); cap_vector_iterator *tmp_iter = cap_vector_iterator_init(vector); CAP_ASSERT_FALSE( cap_vector_iterator_equals(vector_iterator, tmp_iter), "VECTOR Iterator equals"); cap_vector_iterator_increment(tmp_iter); // two CAP_ASSERT_EQ(*(int *)tmp_iter->data, two, "VECTOR increment after init"); CAP_ASSERT_TRUE( cap_vector_iterator_equals(vector_iterator, tmp_iter), "VECTOR Iterator equals"); cap_vector_iterator_free(tmp_iter); CAP_ASSERT_TRUE(cap_vector_iterator_equals_predicate( vector_iterator, predicate_fn_one), "VECTOR Iterator true prediate"); CAP_ASSERT_FALSE(cap_vector_iterator_equals_predicate( vector_iterator, predicate_fn_two), "VECTOR Iterator false predicate"); cap_vector_iterator_increment(vector_iterator); // three CAP_ASSERT_EQ(cap_vector_iterator_index(vector_iterator), 2, "VECTOR Iterator index"); cap_vector_iterator *tmp_begin_iter = cap_vector_begin(vector); cap_vector_iterator *tmp_end_iter = cap_vector_end(vector); CAP_ASSERT_TRUE(*(int *)tmp_end_iter->data == *(int *)cap_vector_back(vector) && *(int *)tmp_begin_iter->data == *(int *)cap_vector_front(vector) && tmp_end_iter->_current_index == cap_vector_size(vector) - 1 && tmp_begin_iter->_current_index == 0, "VECTOR Iterator begin & end checks"); cap_vector_iterator_free(tmp_begin_iter); cap_vector_iterator_free(tmp_end_iter); CAP_ASSERT_EQ(*(int *)vector_iterator->data, three, "VECTOR Iterator before remove"); cap_vector_iterator_remove( vector_iterator); // remove three, currently four CAP_ASSERT_EQ(*(int *)vector_iterator->data, four, "VECTOR Iterator after removing only element"); CAP_ASSERT_EQ(*(int *)cap_vector_iterator_next(vector_iterator), five, "VECTOR Iterator next after remove"); cap_vector_iterator_increment(vector_iterator); // five CAP_ASSERT_EQ(*(int *)vector_iterator->data, five, "VECTOR Iterator remove check"); int seven = 70; size_t _tmp_current_index = vector_iterator->_current_index; cap_vector_iterator_insert(vector_iterator, &seven); CAP_ASSERT_TRUE(*(int *)vector_iterator->data == seven && vector_iterator->_current_index == _tmp_current_index, "VECTOR Iterator insert"); cap_vector_free(vector); cap_vector_iterator_free(vector_iterator); } }
38.263158
80
0.698991
[ "vector" ]
2f25abcd22c6988cf5faecfc48488a7cdb3f6116
8,080
h
C
pdb/src/computations/headers/Computation.h
yuxineverforever/plinycompute
c639d5307a438a850ad00f87880e7be4f17cbb2d
[ "Apache-2.0" ]
1
2020-02-21T06:11:13.000Z
2020-02-21T06:11:13.000Z
pdb/src/computations/headers/Computation.h
yuxineverforever/plinycompute
c639d5307a438a850ad00f87880e7be4f17cbb2d
[ "Apache-2.0" ]
null
null
null
pdb/src/computations/headers/Computation.h
yuxineverforever/plinycompute
c639d5307a438a850ad00f87880e7be4f17cbb2d
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * * Copyright 2018 Rice University * * * * 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 COMPUTATION_H #define COMPUTATION_H #include "Object.h" #include "Lambda.h" #include "ComputeSource.h" #include "ComputeSink.h" #include "PageProcessor.h" #include "InputTupleSetSpecifier.h" #include "PDBString.h" #include "PDBAbstractPageSet.h" #include <map> namespace pdb { // predefine the buffer manager interface class PDBBufferManagerInterface; using PDBBufferManagerInterfacePtr = std::shared_ptr<PDBBufferManagerInterface>; // predefine the logical plan struct LogicalPlan; using LogicalPlanPtr = std::shared_ptr<LogicalPlan>; // the compute plan class ComputePlan; // all nodes in a user-supplied computation are descended from this class Computation : public Object { public: // if this particular computation can be used as a compute source in a pipeline, this // method will return the compute source object associated with the computation... // // In the general case, this method accepts the logical plan that this guy is a part of, // as well as the actual TupleSpec that this guy is supposed to produce, and then returns // a pointer to a ComputeSource object that can actually produce TupleSet objects corresponding // to that particular TupleSpec virtual ComputeSourcePtr getComputeSource(const PDBAbstractPageSetPtr &pageSet, size_t chunkSize, uint64_t workerID, std::map<ComputeInfoType, ComputeInfoPtr> &params) { return nullptr; } // likewise, if this particular computation can be used as a compute sink in a pipeline, this // method will return the compute sink object associated with the computation. It requires the // TupleSpec that should be processed, as well as the projection of that TupleSpec that will // be put into the sink virtual ComputeSinkPtr getComputeSink(TupleSpec &consumeMe, TupleSpec &whichAttsToOpOn, TupleSpec &projection, uint64_t numberOfPartitions, std::map<ComputeInfoType, ComputeInfoPtr> &params, pdb::LogicalPlanPtr &plan) { return nullptr; } // returns the type of this Computation virtual std::string getComputationType() = 0; //JiaNote: below function returns a TCAP string for this Computation virtual std::string toTCAPString(std::vector<InputTupleSetSpecifier> inputTupleSets, int computationLabel) = 0; // gets the name of the i^th input type... virtual std::string getInputType(int i) = 0; // get the number of inputs to this query type virtual int getNumInputs() = 0; /** * gets the output type of this query as a string * @return */ virtual std::string getOutputType() = 0; /** * set the first pos, by default * @param toMe * @return */ bool setInput(const Handle<Computation>& toMe) { return setInput(0, toMe); } /** * sets the i^th input to be the output of a specific query... returns * true if this is OK, false if it is not * @param whichSlot * @param toMe * @return */ bool setInput(int whichSlot, const Handle<Computation>& toMe) { // set the array of inputs if it is a nullptr if (inputs == nullptr) { inputs = makeObject<Vector<Handle<Computation>>>(getNumInputs()); for (int i = 0; i < getNumInputs(); i++) { inputs->push_back(nullptr); } } // if we are adding this query to a valid pos if (whichSlot < getNumInputs()) { //make sure the output type of the guy we are accepting meets the input type if (getInputType(whichSlot) != toMe->getOutputType()) { std::cout << "Cannot set output of query node with output of type " << toMe->getOutputType() << " to be the input"; std::cout << " of a query with input type " << getInputType(whichSlot) << ".\n"; return false; } (*inputs)[whichSlot] = toMe; } else { return false; } return true; } /** * this is implemented by the actual computation object... as the name implies, it is used * to extract the lambdas from the computation * @param returnVal */ virtual void extractLambdas(std::map<std::string, LambdaObjectPtr> &returnVal) {} /** * to traverse from a graph sink recursively and generate TCAP * @param tcapStrings * @param computations * @param inputTupleSets * @param computationLabel */ virtual void traverse(std::vector<std::string> &tcapStrings, Vector<Handle<Computation>> &computations, const std::vector<InputTupleSetSpecifier>& inputTupleSets, int &computationLabel) { // so if the computation is not a scan set, meaning it has at least one input process the children first // go through each child and traverse them std::vector<InputTupleSetSpecifier> inputTupleSetsForMe; for (int i = 0; i < this->getNumInputs(); i++) { // get the child computation Handle<Computation> childComp = (*inputs)[i]; // if we have not visited this computation visit it if (!childComp->traversed) { // go traverse the child computation childComp->traverse(tcapStrings, computations, inputTupleSets, computationLabel); // mark the computation as transversed childComp->traversed = true; // add the child computation computations.push_back(childComp); } // we met a computation that we have visited just grab the name of the output tuple set and the columns it has InputTupleSetSpecifier curOutput(childComp->outputTupleSetName, { childComp->outputColumnToApply }, { childComp->outputColumnToApply }); inputTupleSetsForMe.push_back(curOutput); } // generate the TCAP string for this computation std::string curTCAPString = this->toTCAPString(inputTupleSetsForMe, computationLabel); // store the TCAP string generated tcapStrings.push_back(curTCAPString); // go to the next computation computationLabel++; } /** * */ void clearGraph() { // mark the we are not traversed traversed = false; // clear all children for (int i = 0; i < getNumInputs(); i++) { (*inputs)[i]->clearGraph(); } } protected: /** * The computations that are inputs to this computation */ Handle<Vector<Handle<Computation>>> inputs = nullptr; /** * */ bool traversed = false; /** * */ String outputTupleSetName = ""; /** * */ String outputColumnToApply = ""; }; } #endif
34.678112
142
0.594307
[ "object", "vector" ]
2f25f1768db011ba1b14a09dc63aad340de2c060
5,634
h
C
gameanalytics/include/GameAnalyticsDefold.h
BigButtonCo/GA-SDK-DEFOLD
4e6d663de5483aa7c4758c573fe32cc52f36423f
[ "MIT" ]
null
null
null
gameanalytics/include/GameAnalyticsDefold.h
BigButtonCo/GA-SDK-DEFOLD
4e6d663de5483aa7c4758c573fe32cc52f36423f
[ "MIT" ]
null
null
null
gameanalytics/include/GameAnalyticsDefold.h
BigButtonCo/GA-SDK-DEFOLD
4e6d663de5483aa7c4758c573fe32cc52f36423f
[ "MIT" ]
1
2021-07-05T16:08:47.000Z
2021-07-05T16:08:47.000Z
#pragma once #include <dmsdk/script/script.h> #include <vector> #include "CharArray.h" namespace gameanalytics { namespace defold { enum EGAResourceFlowType { Source = 1, Sink = 2 }; enum EGAProgressionStatus { Start = 1, Complete = 2, Fail = 3 }; enum EGAErrorSeverity { Debug = 1, Info = 2, Warning = 3, Error = 4, Critical = 5 }; enum EGAAdAction { Clicked = 1, Show = 2, FailedShow = 3, RewardReceived = 4 }; enum EGAAdType { Video = 1, RewardedVideo = 2, Playable = 3, Interstitial = 4, OfferWall = 5, Banner = 6 }; enum EGAAdError { Unknown = 1, Offline = 2, NoFill = 3, InternalError = 4, InvalidRequest = 5, UnableToPrecache = 6 }; class GameAnalytics { public: static void configureAvailableCustomDimensions01(const char* list); static void configureAvailableCustomDimensions02(const char* list); static void configureAvailableCustomDimensions03(const char* list); static void configureAvailableResourceCurrencies(const char* list); static void configureAvailableResourceItemTypes(const char* list); static void configureBuild(const char *build); static void configureAutoDetectAppVersion(bool flag); static void configureUserId(const char *userId); static void configureSdkGameEngineVersion(const char *gameEngineSdkVersion); static void configureGameEngineVersion(const char *gameEngineVersion); static void configureWritablePath(const char *writablePath); static void initialize(const char *gameKey, const char *gameSecret, bool use_imei_android); #if defined(DM_PLATFORM_IOS) static void addBusinessEvent(const char *currency, int amount, const char *itemType, const char *itemId, const char *cartType, const char *receipt, const char *fields); static void addBusinessEventAndAutoFetchReceipt(const char *currency, int amount, const char *itemType, const char *itemId, const char *cartType, const char *fields); #elif defined(DM_PLATFORM_ANDROID) static void addBusinessEvent(const char *currency, int amount, const char *itemType, const char *itemId, const char *cartType, const char *receipt, const char *signature, const char *fields); #endif static void addBusinessEvent(const char *currency, int amount, const char *itemType, const char *itemId, const char *cartType, const char *fields); static void addResourceEvent(EGAResourceFlowType flowType, const char *currency, float amount, const char *itemType, const char *itemId, const char *fields); static void addProgressionEvent(EGAProgressionStatus progressionStatus, const char *progression01, const char *progression02, const char *progression03, const char *fields); static void addProgressionEvent(EGAProgressionStatus progressionStatus, const char *progression01, const char *progression02, const char *progression03, int score, const char *fields); static void addDesignEvent(const char *eventId, const char *fields); static void addDesignEvent(const char *eventId, float value, const char *fields); static void addErrorEvent(EGAErrorSeverity severity, const char *message, const char *fields); static void addAdEvent(EGAAdAction adAction, EGAAdType adType, const char *adSdkName, const char *adPlacement, const char *fields); static void addAdEventWithDuration(EGAAdAction adAction, EGAAdType adType, const char *adSdkName, const char *adPlacement, int duration, const char *fields); static void addAdEventWithNoAdReason(EGAAdAction adAction, EGAAdType adType, const char *adSdkName, const char *adPlacement, EGAAdError noAdReason, const char *fields); static void setEnabledInfoLog(bool flag); static void setEnabledVerboseLog(bool flag); static void setEnabledManualSessionHandling(bool flag); static void setEnabledEventSubmission(bool flag); static void setEnabledErrorReporting(bool flag); static void setCustomDimension01(const char *customDimension); static void setCustomDimension02(const char *customDimension); static void setCustomDimension03(const char *customDimension); static void startSession(); static void endSession(); static void onQuit(); static std::vector<char> getRemoteConfigsValueAsString(const char *key); static std::vector<char> getRemoteConfigsValueAsString(const char *key, const char *defaultValue); static bool isRemoteConfigsReady(); static void setRemoteConfigsListener(dmScript::LuaCallbackInfo* listener); static std::vector<char> getRemoteConfigsContentAsString(); private: #if defined(DM_PLATFORM_HTML5) static void runHtml5Code(const char* code); static std::vector<char> runHtml5CodeWithReturnString(const char* code); static bool runHtml5CodeWithReturnBool(const char* code); #endif static std::vector<CharArray> split(char* str, const char* delimiter); }; } }
45.435484
203
0.65513
[ "vector" ]
2f28ed6ecae9fbdc3841ffcf38fcef654ec0d143
790
h
C
src/tools.h
mpavezb/CarND-Extended-Kalman-Filter-Project
15678e1c8889ec90e78722f2025aad585e01920d
[ "MIT" ]
null
null
null
src/tools.h
mpavezb/CarND-Extended-Kalman-Filter-Project
15678e1c8889ec90e78722f2025aad585e01920d
[ "MIT" ]
null
null
null
src/tools.h
mpavezb/CarND-Extended-Kalman-Filter-Project
15678e1c8889ec90e78722f2025aad585e01920d
[ "MIT" ]
null
null
null
#ifndef TOOLS_H_ #define TOOLS_H_ #include <vector> #include "Eigen/Dense" class Tools { public: /** * Constructor. */ Tools(); /** * Destructor. */ virtual ~Tools(); /** * A helper method to calculate RMSE. */ Eigen::VectorXd CalculateRMSE( const std::vector<Eigen::VectorXd> &estimations, const std::vector<Eigen::VectorXd> &ground_truth); /** * A helper method to calculate Jacobians. */ Eigen::MatrixXd CalculateJacobian(const Eigen::VectorXd &x_state); /** * Projects state vector to radar space (rho, phi, rho_dot). */ static Eigen::VectorXd ProjectStateToRadar(const Eigen::VectorXd &z); /** * Normalizes angle between -PI, PI */ static float normalize_angle(const float value); }; #endif // TOOLS_H_
18.372093
71
0.648101
[ "vector" ]
2f2d68099ded348c5c75a0a8ba8ffcf0f4970e66
3,865
h
C
gpslam/slam/RangeBearingFactor2DLinear.h
mmattamala/gpslam
09446606bf8867fc601b40778ff1923a7e9be400
[ "BSD-3-Clause" ]
102
2017-08-31T13:15:33.000Z
2022-03-18T16:01:42.000Z
gpslam/slam/RangeBearingFactor2DLinear.h
SUQIGUANG/gpslam
2c15aacd2000ac2358c0f87c9f7b38cf658fe47d
[ "BSD-3-Clause" ]
2
2018-10-13T11:55:58.000Z
2020-09-18T09:21:15.000Z
gpslam/slam/RangeBearingFactor2DLinear.h
SUQIGUANG/gpslam
2c15aacd2000ac2358c0f87c9f7b38cf658fe47d
[ "BSD-3-Clause" ]
48
2017-08-31T03:46:02.000Z
2021-12-28T12:35:33.000Z
/** * @file RangeBearingFactor2DLinear.h * @brief range + bearing factor for 2D linear pose * @author Xinyan Yan, Jing Dong * @date Nov 3, 2015 **/ #pragma once #include <gtsam/geometry/Pose2.h> #include <gtsam/nonlinear/NonlinearFactor.h> #include <gtsam/base/Vector.h> namespace gpslam { /** * range and bearing measurement, 2D linear pose version */ class RangeBearingFactor2DLinear: public gtsam::NoiseModelFactor2<gtsam::Vector3, gtsam::Point2> { private: // measurements double range_; gtsam::Rot2 bearing_; typedef RangeBearingFactor2DLinear This; typedef gtsam::NoiseModelFactor2<gtsam::Vector3, gtsam::Point2> Base; public: RangeBearingFactor2DLinear() {} /* Default constructor */ RangeBearingFactor2DLinear(gtsam::Key poseKey, gtsam::Key pointKey, double range, const gtsam::Rot2& bearing, const gtsam::SharedNoiseModel& model) : Base(model, poseKey, pointKey), range_(range), bearing_(bearing) { } virtual ~RangeBearingFactor2DLinear() {} /// @return a deep copy of this factor virtual gtsam::NonlinearFactor::shared_ptr clone() const { return boost::static_pointer_cast<gtsam::NonlinearFactor>( gtsam::NonlinearFactor::shared_ptr(new This(*this))); } /** h(x)-z */ gtsam::Vector evaluateError(const gtsam::Vector3& pose, const gtsam::Point2& point, boost::optional<gtsam::Matrix&> H1 = boost::none, boost::optional<gtsam::Matrix&> H2 = boost::none) const { using namespace gtsam; Pose2 pose2(pose(0), pose(1), pose(2)); Point2 rel_point = pose2.transform_to(point); Rot2 expect_rot = Rot2::atan2(rel_point.y(), rel_point.x()); Matrix12 Hnorm; double expect_d = Point2(point - pose2.t()).norm(Hnorm); // jacobians if (H1 || H2) { Matrix12 tmp; if (expect_d > 1e-5) { double expect_d2 = expect_d * expect_d; tmp = (Matrix12() << -rel_point.y()/expect_d2, rel_point.x()/expect_d2).finished(); } else { tmp = Matrix12::Zero(); } Matrix13 H11, H21; Matrix12 H12, H22; if (H1) { Vector2 t(rel_point.y(), -rel_point.x()); H11 = tmp * (Matrix23() << -pose2.r().transpose(), t).finished(); H21 = (Matrix13() << -Hnorm, 0.0).finished(); *H1 = (Matrix23() << H11, H21).finished(); } if (H2) { H12 = tmp * pose2.r().transpose(); H22 = Hnorm; *H2 = (Matrix2() << H12, H22).finished(); } } return (Vector(2) << Rot2::Logmap(bearing_.between(expect_rot)), expect_d - range_).finished(); } /** return the measured */ double range() const { return range_; } const gtsam::Rot2& bearing() const { return bearing_; } /** equals specialized to this factor */ virtual bool equals(const gtsam::NonlinearFactor& expected, double tol=1e-9) const { const This *e = dynamic_cast<const This*> (&expected); return e != NULL && Base::equals(*e, tol) && fabs(this->range_ - e->range_) < tol && this->bearing_.equals(e->bearing_, tol); } /** print contents */ void print(const std::string& s="", const gtsam::KeyFormatter& keyFormatter = gtsam::DefaultKeyFormatter) const { std::cout << s << "RangeBearingFactor, range = " << range_ << ", bearing = "; bearing_.print(); Base::print("", keyFormatter); } private: /** Serialization function */ friend class boost::serialization::access; template<class ARCHIVE> void serialize(ARCHIVE & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Base); ar & BOOST_SERIALIZATION_NVP(range_); ar & BOOST_SERIALIZATION_NVP(bearing_); } }; // RangeBearingFactor2DLinear } // namespace gpslam /// traits namespace gtsam { template<> struct traits<gpslam::RangeBearingFactor2DLinear> : public Testable<gpslam::RangeBearingFactor2DLinear> {}; }
29.503817
115
0.649677
[ "geometry", "vector", "model" ]
2f3970bfe409f61edca1702a28141590e12b3eae
1,369
h
C
include/algotradingAPI.h
kknet/JSTrader
22e280275ca98216ad0ab05c0ec4a471dd9545fd
[ "MIT" ]
33
2017-08-25T09:27:53.000Z
2021-04-11T06:20:44.000Z
include/algotradingAPI.h
mcFore/JSTrader
ad7eeafa097a2e6564efa5be6c63718f0d1515ea
[ "MIT" ]
null
null
null
include/algotradingAPI.h
mcFore/JSTrader
ad7eeafa097a2e6564efa5be6c63718f0d1515ea
[ "MIT" ]
24
2017-07-11T04:18:53.000Z
2021-06-14T01:46:41.000Z
#ifndef ALGOTRADINGAPI_H #define ALGOTRADINGAPI_H #include<vector> #include<string> #include<memory> #include"json11/json11.h" #include"structs.hpp" #include"mongocxx.hpp" #include"strategytemplate.h" class StrategyTemplate; class AlgoTradingAPI { public: virtual std::vector<std::string> sendOrder(const std::string &symbol, const std::string &orderType, double price, double volume, StrategyTemplate* Strategy)=0; virtual void cancelOrder(const std::string &orderID, const std::string &gatewayName)=0; virtual void writeAlgoTradingLog(const std::string &msg)=0; virtual void writeTradingReason(const std::shared_ptr<Event_Tick> &tick, const std::string &msg, StrategyTemplate *strategy) = 0; virtual void writeTradingReason(const jsstructs::BarData &bar, const std::string &msg, StrategyTemplate *strategy) = 0; virtual void PutBarChart(const jsstructs::BarData &bar, const jsstructs::BacktestGodData&data, bool inited) {}; virtual void PutEvent(std::shared_ptr<Event>e) = 0; virtual std::vector<std::shared_ptr<Event_Tick>>loadTick(const std::string &tickDbName, const std::string &symbol, int days) = 0; virtual std::vector<jsstructs::BarData>loadBar(const std::string &BarDbName, const std::string &symbol, int days) = 0; mongoc_client_pool_t *pool=NULL; mongoc_uri_t *uri=NULL; MongoCxx *mongocxx=nullptr; }; #endif
48.892857
161
0.759679
[ "vector" ]
2f423ce7709ab54fde909a4ae16d64b33a2ae213
7,923
h
C
Server/Shared/include/InfoCoordinatePacket.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
4
2015-08-17T20:12:22.000Z
2020-05-30T19:53:26.000Z
Server/Shared/include/InfoCoordinatePacket.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
Server/Shared/include/InfoCoordinatePacket.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef INFO_COORDINATE_PACKET_H #define INFO_COORDINATE_PACKET_H #include "config.h" #include "MC2Coordinate.h" #include "Packet.h" /** * Represents a single coordinate-angle pair included in a * InfoCoordinateRequestPacket. */ class InfoCoordinate { public: /** @name Constructors */ //@{ /** * Default constructor. Sets the member variable coord to the * default value for a MC2Coordinate, and the angle member variable * to MAX_INT32. */ InfoCoordinate() :coord(), angle(MAX_INT32) {} /** * Constructor. * @param pCoord The coordinate value. * @param pAngle The angle value. */ InfoCoordinate(const MC2Coordinate& pCoord, uint32 pAngle) : coord(pCoord), angle(pAngle) {} //@} /** * @name Reading and writing to a packet. * 4 bytes lat * 4 bytes lon * 4 bytes angle */ //@{ /** * Write itself into a packet. * @param packet The packet to write into. * @param pos The position of the packet to start writing at. Will * be updated to point to after the written data. */ void save(Packet* packet, int& pos) const; /** * Update itself with data read from a packet. * @param packet The packet to read from * @param pos The position of the packet to start reading from. Will * be updated to point to after the read data. */ void load( const Packet* packet, int& pos) ; //@} /**@name Member data */ //@{ /** The coordinate data */ MC2Coordinate coord; /** The angle */ uint32 angle; //@} }; /** * Requests information regarding coordinate-angle pairs. */ class InfoCoordinateRequestPacket: public RequestPacket { public: /** The container for coordinate-angle pairs. */ typedef std::vector<InfoCoordinate> InfoCoordCont; /** @name Constructors. */ //@{ /** * Constructor for a packet requesting information about a single * coordinate-angle pair. * @param The map this packet pertains. * @param coord The coordinate. * @param angle The angle. Defaults to MAX_INT16. */ InfoCoordinateRequestPacket(uint32 mapID, const MC2Coordinate& coord, uint32 angle = MAX_INT16); /** * Constructor for a packet requesting information about several * coordinate-angle pair. * @param The map this packet pertains. * @param coords The coordinate-angle pairs. */ InfoCoordinateRequestPacket(uint32 mapID, const InfoCoordCont& coords); //@} /** * Reads the data encoded in the packet into a InfoCoordsCont. * @param coords The container that the read InfoCoordinates will be stored. * @return The number of InfoCoordinate objects that was read. */ InfoCoordCont::size_type readData(InfoCoordCont& coords) const; private: /** * Writes the InfoCoordinates from a InfoCoordCont into this * packet. * @param coords The InfoCoordCont. */ void encodeRequest(const InfoCoordCont& coords); }; /** * Objects of this class are stored in the InfoCoordinateReplyPacket. */ class InfoCoordinateReplyData { public: /** @name Constuctors. */ //@{ /** * Default constructor. Sets all member variables to MAX_UINT32, * which represents an invalid object. */ InfoCoordinateReplyData() : mapID(MAX_UINT32), nodeID0(MAX_UINT32), nodeID1(MAX_UINT32), distance(MAX_UINT32), offset(MAX_UINT32) {} /** * Constructor. */ InfoCoordinateReplyData(uint32 mapID, uint32 nodeID0, uint32 nodeID1, uint32 distance, uint32 offset) : mapID(mapID), nodeID0(nodeID0), nodeID1(nodeID1), distance(distance), offset(offset) {} /** * Stores this object in a packet. * @param packet The Packet to write into. * @param pos The position to start writing at. Will be updated to * point past the written data. */ void save(Packet* packet, int& pos) const; /** * Updates this object from a packet. * @param packet The Packet to read from. * @param pos The position to start reading from. Will be updated to * point past the read data. */ void load(Packet* packet, int& pos); /** * Compares this object with the argument, and updates this object * with the best of the two. * If the distance member variable is lower in the parameter object * the data from that object will be copied into this object. * @param data The object to compare to and maybe copy from. */ void merge( const InfoCoordinateReplyData& data ); /** The id of the map this info is from */ uint32 mapID; /** The first node ID */ uint32 nodeID0; /** The second node ID */ uint32 nodeID1; /** The distance to the segment?*/ uint32 distance; /** The offset into the segment?*/ uint32 offset; }; ostream& operator<<(ostream& stream, const InfoCoordinateReplyData& icrd); /** * The reply packet for InfoCoordinateRequestPacket. */ class InfoCoordinateReplyPacket: public ReplyPacket { public: /** * The container type used to collect the InfoCoordinateReplyData * objects contained in the packet. */ typedef std::vector<InfoCoordinateReplyData> InfoReplyCont; /** * Constructor. * @param request The packet the new object is a reply to. * @param status The status of the packet. * @param data The objects to store in the packet. */ InfoCoordinateReplyPacket( const InfoCoordinateRequestPacket* request, uint32 status, const InfoReplyCont& data ); /** * Merge the InfoCoordinateReplyData objects in this packet with * the ones stored in the InfoReplyCont parameter. The merge is * done by replacing any invalid objects in the parameter with * valid from this packet, or if this packet contains better * matches they will replace the ones in the parameter see * InfoCoordinateReplyData::merge. * @param data The container to merge into. */ void mergeData(InfoReplyCont& data); private: /** * Write a set of InfoCoordinateReplyData objects into this packet. * @param data The objects to write. */ void encodeReply(const InfoReplyCont& data); }; #endif
34.75
755
0.679162
[ "object", "vector" ]
920f9bef3e05e993519c08ed65e1534945469e5a
2,328
c
C
hw/ip/prim/dv/prim_present/crypto_dpi_present/crypto_dpi_present.c
GregAC/opentitan
40b607b776d7b10cfc2899cc0d724d00dc0c91a2
[ "Apache-2.0" ]
1,375
2019-11-05T15:11:00.000Z
2022-03-28T17:50:43.000Z
hw/ip/prim/dv/prim_present/crypto_dpi_present/crypto_dpi_present.c
GregAC/opentitan
40b607b776d7b10cfc2899cc0d724d00dc0c91a2
[ "Apache-2.0" ]
7,045
2019-11-05T16:05:45.000Z
2022-03-31T23:08:08.000Z
hw/ip/prim/dv/prim_present/crypto_dpi_present/crypto_dpi_present.c
GregAC/opentitan
40b607b776d7b10cfc2899cc0d724d00dc0c91a2
[ "Apache-2.0" ]
428
2019-11-05T15:00:20.000Z
2022-03-28T15:34:57.000Z
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include "present.inc" #include "svdpi.h" typedef unsigned long long int ull_t; // Helper function used only by this C file. // Returns the key schedule corresponding to the input key. uint64_t *get_key_schedule(uint64_t key_high, uint64_t key_low, uint8_t num_rounds, uint8_t key_size_80) { return key_schedule(key_high, key_low, num_rounds, (_Bool)key_size_80, 0); } extern void c_dpi_key_schedule(uint64_t key_high, uint64_t key_low, uint8_t num_rounds, uint8_t key_size_80, svBitVecVal *key_array) { uint64_t *key_schedule = (uint64_t *)malloc(num_rounds * sizeof(uint64_t)); uint64_t key; svBitVecVal key_hi; svBitVecVal key_lo; // get the key schedule from the C model key_schedule = get_key_schedule(key_high, key_low, num_rounds, key_size_80); // write the key schedule to simulation int i; for (i = 0; i < num_rounds; i++) { key = key_schedule[i]; key_hi = (svBitVecVal)(key >> 32); key_lo = (svBitVecVal)(key & 0xFFFFFFFF); key_array[i * 2] = key_lo; key_array[i * 2 + 1] = key_hi; } // free allocated memory free(key_schedule); } extern uint64_t c_dpi_encrypt(uint64_t plaintext, uint64_t key_high, uint64_t key_low, uint8_t num_rounds, uint8_t key_size_80) { uint64_t encrypt_result; uint64_t *key_schedule = (uint64_t *)malloc(num_rounds * sizeof(uint64_t)); key_schedule = get_key_schedule(key_high, key_low, num_rounds, key_size_80); encrypt_result = (uint64_t)encrypt(plaintext, key_schedule, num_rounds, 0); free(key_schedule); return encrypt_result; } extern uint64_t c_dpi_decrypt(uint64_t ciphertext, uint64_t key_high, uint64_t key_low, uint8_t num_rounds, uint8_t key_size_80) { uint64_t decrypt_result; uint64_t *key_schedule = (uint64_t *)malloc(sizeof(uint64_t)); key_schedule = get_key_schedule(key_high, key_low, num_rounds, key_size_80); decrypt_result = (uint64_t)decrypt(ciphertext, key_schedule, num_rounds, 0); free(key_schedule); return decrypt_result; }
35.815385
78
0.687715
[ "model" ]
92100d2149bd0031a53b2aaef06834f5a67c66ab
432
h
C
BaiDuMusic/BaiDuMusic/Classes/Tools/Category/UIImage+Shape.h
Spacecup/BaiDuMusicDemo
c48da7ddccb23687a7ddcff9f60ae19569356ea6
[ "MIT" ]
1
2016-04-02T15:42:13.000Z
2016-04-02T15:42:13.000Z
BaiDuMusic/BaiDuMusic/Classes/Tools/Category/UIImage+Shape.h
Spacecup/BaiDuMusicDemo
c48da7ddccb23687a7ddcff9f60ae19569356ea6
[ "MIT" ]
null
null
null
BaiDuMusic/BaiDuMusic/Classes/Tools/Category/UIImage+Shape.h
Spacecup/BaiDuMusicDemo
c48da7ddccb23687a7ddcff9f60ae19569356ea6
[ "MIT" ]
null
null
null
// // UIImage+Shape.h // BaiDuMusic // // Created by 余丽丽 on 15/10/31. // Copyright © 2015年 余丽丽. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (Shape) /// 根据图片信息,返回圆形的图片 /// /// @param name 图片名称 /// @param borderWidth 边框宽度 /// @param borderColor 边框颜色 /// /// @return +(instancetype)circelImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor; @end
19.636364
120
0.673611
[ "shape" ]
9215f86b13c80e9deefe699cdf823e769f4ae534
1,208
h
C
kernel/include/cpu/interrupts.h
zhiayang/nx
0d9da881f67ec351244abd72e1f3884816b48f5b
[ "Apache-2.0" ]
16
2019-03-14T19:45:02.000Z
2022-02-06T19:18:08.000Z
kernel/include/cpu/interrupts.h
zhiayang/nx
0d9da881f67ec351244abd72e1f3884816b48f5b
[ "Apache-2.0" ]
1
2020-05-08T08:40:02.000Z
2020-05-08T13:27:59.000Z
kernel/include/cpu/interrupts.h
zhiayang/nx
0d9da881f67ec351244abd72e1f3884816b48f5b
[ "Apache-2.0" ]
2
2021-01-16T20:42:05.000Z
2021-12-01T23:37:18.000Z
// interrupts.h // Copyright (c) 2019, zhiayang // Licensed under the Apache License Version 2.0. #pragma once #include <stddef.h> #include "stdint.h" namespace nx { namespace scheduler { struct Thread; struct Process; } namespace interrupts { void init(); void enable(); void disable(); void resetNesting(); void init_arch(); void maskIRQ(int num); void unmaskIRQ(int num); // note: 'num' is in IRQ space! (0 => IRQ_BASE_VECTOR) void sendEOI(int num); bool hasIOAPIC(); bool hasLocalAPIC(); // note: 'vector' is in IRQ space! (0 => IRQ_BASE_VECTOR) void mapIRQVector(int irq, int vector, int apicId); void addIRQHandler(int irq, scheduler::Thread* thr); void addIRQHandler(int irq, scheduler::Process* proc); // returns true if there was at least one target to handle the IRQ. bool processIRQ(int num, void* data); // tells the interrupt "manager" that one of the signalled processes did not process // the irq successfully (eg. it was not from that particular device) void signalIRQIgnored(int num); // tells the interrupt "manager" that somebody successfully handled the device irq. void signalIRQHandled(int num); } }
16.777778
86
0.692053
[ "vector" ]
921f69839d046555cce7fcaa6b3d58cc2af51bb2
23,543
c
C
benchmarks/source/superh/ALPBench/Ray_Trace/tachyon/src/camera.c
rhudson2802/sunflower-simulator
9f55e03c9d80c024a75029d0e842cc5c92f31c82
[ "BSD-3-Clause" ]
7
2016-05-07T13:38:33.000Z
2019-07-08T03:42:24.000Z
benchmarks/source/superh/ALPBench/Ray_Trace/tachyon/src/camera.c
rhudson2802/sunflower-simulator
9f55e03c9d80c024a75029d0e842cc5c92f31c82
[ "BSD-3-Clause" ]
80
2019-08-27T14:43:46.000Z
2020-12-16T11:56:19.000Z
benchmarks/source/superh/ALPBench/Ray_Trace/tachyon/src/camera.c
rhudson2802/sunflower-simulator
9f55e03c9d80c024a75029d0e842cc5c92f31c82
[ "BSD-3-Clause" ]
98
2019-08-30T14:29:16.000Z
2020-11-21T18:22:13.000Z
/* * camera.c - This file contains all of the functions for doing camera work. * * $Id: camera.c,v 1.45 2004/05/31 03:56:23 johns Exp $ */ #include "machine.h" #include "types.h" #include "macros.h" #include "vector.h" #include "camera.h" #include "util.h" #include "intersect.h" /* * camera_init() * take camera parameters stored in scene definition and do all * necessary initialization and whatever pre-calculation can be done. */ void camera_init(scenedef *scene) { flt sx, sy; /* setup function pointer for camera ray generation */ switch (scene->camera.projection) { case RT_PROJECTION_PERSPECTIVE: if (scene->antialiasing > 0) { scene->camera.cam_ray = (color (*)(void *,flt,flt)) cam_aa_perspective_ray; } else { scene->camera.cam_ray = (color (*)(void *,flt,flt)) cam_perspective_ray; } break; case RT_PROJECTION_PERSPECTIVE_DOF: scene->camera.cam_ray = (color (*)(void *,flt,flt)) cam_aa_dof_ray; break; case RT_PROJECTION_ORTHOGRAPHIC: if (scene->antialiasing > 0) { scene->camera.cam_ray = (color (*)(void *,flt,flt)) cam_aa_orthographic_ray; } else { scene->camera.cam_ray = (color (*)(void *,flt,flt)) cam_orthographic_ray; } break; case RT_PROJECTION_FISHEYE: if (scene->antialiasing > 0) { scene->camera.cam_ray = (color (*)(void *,flt,flt)) cam_aa_fisheye_ray; } else { scene->camera.cam_ray = (color (*)(void *,flt,flt)) cam_fisheye_ray; } break; } sx = (flt) scene->hres; sy = (flt) scene->vres; /* assuming viewvec is a unit vector, then the center of the */ /* image plane is the camera center + vievec */ switch (scene->camera.projection) { case RT_PROJECTION_ORTHOGRAPHIC: scene->camera.projcent = scene->camera.center; /* assuming viewvec is a unit vector, then the lower left */ /* corner of the image plane is calculated below */ scene->camera.lowleft.x = scene->camera.projcent.x + (scene->camera.left * scene->camera.rightvec.x) + (scene->camera.bottom * scene->camera.upvec.x); scene->camera.lowleft.y = scene->camera.projcent.y + (scene->camera.left * scene->camera.rightvec.y) + (scene->camera.bottom * scene->camera.upvec.y); scene->camera.lowleft.z = scene->camera.projcent.z + (scene->camera.left * scene->camera.rightvec.z) + (scene->camera.bottom * scene->camera.upvec.z); break; case RT_PROJECTION_PERSPECTIVE_DOF: scene->camera.projcent.x = scene->camera.center.x + (scene->camera.focallength * scene->camera.viewvec.x); scene->camera.projcent.y = scene->camera.center.y + (scene->camera.focallength * scene->camera.viewvec.y); scene->camera.projcent.z = scene->camera.center.z + (scene->camera.focallength * scene->camera.viewvec.z); /* assuming viewvec is a unit vector, then the lower left */ /* corner of the image plane is calculated below */ scene->camera.lowleft.x = scene->camera.projcent.x + (scene->camera.left * scene->camera.rightvec.x) + (scene->camera.bottom * scene->camera.upvec.x); scene->camera.lowleft.y = scene->camera.projcent.y + (scene->camera.left * scene->camera.rightvec.y) + (scene->camera.bottom * scene->camera.upvec.y); scene->camera.lowleft.z = scene->camera.projcent.z + (scene->camera.left * scene->camera.rightvec.z) + (scene->camera.bottom * scene->camera.upvec.z); break; case RT_PROJECTION_FISHEYE: scene->camera.projcent.x = scene->camera.center.x + (scene->camera.focallength * scene->camera.viewvec.x); scene->camera.projcent.y = scene->camera.center.y + (scene->camera.focallength * scene->camera.viewvec.y); scene->camera.projcent.z = scene->camera.center.z + (scene->camera.focallength * scene->camera.viewvec.z); break; case RT_PROJECTION_PERSPECTIVE: default: scene->camera.projcent.x = scene->camera.center.x + (scene->camera.focallength * scene->camera.viewvec.x); scene->camera.projcent.y = scene->camera.center.y + (scene->camera.focallength * scene->camera.viewvec.y); scene->camera.projcent.z = scene->camera.center.z + (scene->camera.focallength * scene->camera.viewvec.z); /* assuming viewvec is a unit vector, then the lower left */ /* corner of the image plane is calculated below */ /* for normal perspective rays, we are really storing the */ /* direction to the lower left, not the lower left itself, */ /* since this allows us to eliminate a subtraction per pixel */ scene->camera.lowleft.x = scene->camera.projcent.x + (scene->camera.left * scene->camera.rightvec.x) + (scene->camera.bottom * scene->camera.upvec.x) - scene->camera.center.x; scene->camera.lowleft.y = scene->camera.projcent.y + (scene->camera.left * scene->camera.rightvec.y) + (scene->camera.bottom * scene->camera.upvec.y) - scene->camera.center.y; scene->camera.lowleft.z = scene->camera.projcent.z + (scene->camera.left * scene->camera.rightvec.z) + (scene->camera.bottom * scene->camera.upvec.z) - scene->camera.center.z; break; } /* size of image plane */ scene->camera.px = scene->camera.right - scene->camera.left; scene->camera.py = scene->camera.top - scene->camera.bottom; scene->camera.psx = scene->camera.px / scene->hres; scene->camera.psy = scene->camera.py / scene->vres; scene->camera.iplaneright.x = scene->camera.px * scene->camera.rightvec.x / sx; scene->camera.iplaneright.y = scene->camera.px * scene->camera.rightvec.y / sx; scene->camera.iplaneright.z = scene->camera.px * scene->camera.rightvec.z / sx; scene->camera.iplaneup.x = scene->camera.py * scene->camera.upvec.x / sy; scene->camera.iplaneup.y = scene->camera.py * scene->camera.upvec.y / sy; scene->camera.iplaneup.z = scene->camera.py * scene->camera.upvec.z / sy; } /* * camray_init() * initializes a camera ray which will be reused over and over * by the current worker thread. This includes attaching thread-specific * data to this ray. */ void camray_init(scenedef *scene, ray *primary, unsigned long serial, unsigned long * mbox) { /* setup the right function pointer depending on what features are in use */ if (scene->flags & RT_SHADE_CLIPPING) { primary->add_intersection = add_clipped_intersection; } else { primary->add_intersection = add_regular_intersection; } primary->serial = serial; primary->mbox = mbox; primary->scene = scene; primary->depth = scene->raydepth; primary->randval = 12345678; /* random number seed */ /* orthographic ray direction is always coaxial with view direction */ primary->d = scene->camera.viewvec; /* for perspective rendering without depth of field */ primary->o = scene->camera.center; } #if 0 /* * cam_aa_dof_ray() * Generate a perspective camera ray incorporating * antialiasing and depth-of-field. */ color cam_aa_dof_ray(ray * ry, flt x, flt y) { color col, sample; color colsum, colsumsq, colvar; int samples, samplegroup; scenedef * scene=ry->scene; flt dx, dy, rnsamples, ftmp; flt maxvar; sample=cam_dof_ray(ry, x, y); /* generate primary ray */ colsum = sample; /* accumulate first sample */ colsumsq.r = colsum.r * colsum.r; /* accumulate first squared sample */ colsumsq.g = colsum.g * colsum.g; colsumsq.b = colsum.b * colsum.b; /* perform antialiasing if enabled. */ /* samples are run through a very simple box filter averaging */ /* each of the sample pixel colors to produce a final result */ /* No special weighting is done based on the jitter values in */ /* the circle of confusion nor for the jitter within the */ /* pixel in the image plane. */ samples = 1; /* only one ray cast so far */ while (samples < scene->antialiasing) { #if 0 samplegroup = scene->antialiasing; #else if (samples > 32) { samplegroup = samples + 1; } else { samplegroup = samples + 32; } #endif for (; samples <= samplegroup; samples++) { /* calculate random eye aperture offset */ dx = ((rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5) * ry->scene->camera.aperture * ry->scene->hres; dy = ((rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5) * ry->scene->camera.aperture * ry->scene->vres; /* perturb the eye center by the random aperture offset */ ry->o.x = ry->scene->camera.center.x + dx * ry->scene->camera.iplaneright.x + dy * ry->scene->camera.iplaneup.x; ry->o.y = ry->scene->camera.center.y + dx * ry->scene->camera.iplaneright.y + dy * ry->scene->camera.iplaneup.y; ry->o.z = ry->scene->camera.center.z + dx * ry->scene->camera.iplaneright.z + dy * ry->scene->camera.iplaneup.z; /* shoot the ray, jittering the pixel position in the image plane */ sample=cam_dof_ray(ry, x + (rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5, y + (rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5); colsum.r += sample.r; /* accumulate samples */ colsum.g += sample.g; colsum.b += sample.b; colsumsq.r += sample.r * sample.r; /* accumulate squared samples */ colsumsq.g += sample.g * sample.g; colsumsq.b += sample.b * sample.b; } /* calculate the variance for the color samples we've taken so far */ rnsamples = 1.0 / samples; ftmp = colsum.r * rnsamples; colvar.r = ((colsumsq.r * rnsamples) - ftmp*ftmp) * rnsamples; ftmp = colsum.g * rnsamples; colvar.g = ((colsumsq.g * rnsamples) - ftmp*ftmp) * rnsamples; ftmp = colsum.b * rnsamples; colvar.b = ((colsumsq.b * rnsamples) - ftmp*ftmp) * rnsamples; maxvar = 0.002; /* default maximum color variance to accept */ /* early exit antialiasing if we're below maximum allowed variance */ if ((colvar.r < maxvar) && (colvar.g < maxvar) && (colvar.b < maxvar)) { break; /* no more samples should be needed, we are happy now */ } } /* average sample colors, back to range 0.0 - 1.0 */ col.r = colsum.r * rnsamples; col.g = colsum.g * rnsamples; col.b = colsum.b * rnsamples; return col; } #else /* * cam_aa_dof_ray() * Generate a perspective camera ray incorporating * antialiasing and depth-of-field. */ color cam_aa_dof_ray(ray * ry, flt x, flt y) { color col, avcol; int alias; scenedef * scene=ry->scene; float scale; flt dx, dy; col=cam_dof_ray(ry, x, y); /* generate ray */ /* perform antialiasing if enabled. */ /* samples are run through a very simple box filter averaging */ /* each of the sample pixel colors to produce a final result */ /* No special weighting is done based on the jitter values in */ /* the circle of confusion nor for the jitter within the */ /* pixel in the image plane. */ for (alias=1; alias <= scene->antialiasing; alias++) { /* calculate random eye aperture offset */ dx = ((rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5) * ry->scene->camera.aperture * ry->scene->hres; dy = ((rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5) * ry->scene->camera.aperture * ry->scene->vres; /* perturb the eye center by the random aperture offset */ ry->o.x = ry->scene->camera.center.x + dx * ry->scene->camera.iplaneright.x + dy * ry->scene->camera.iplaneup.x; ry->o.y = ry->scene->camera.center.y + dx * ry->scene->camera.iplaneright.y + dy * ry->scene->camera.iplaneup.y; ry->o.z = ry->scene->camera.center.z + dx * ry->scene->camera.iplaneright.z + dy * ry->scene->camera.iplaneup.z; /* shoot the ray, jittering the pixel position in the image plane */ avcol=cam_dof_ray(ry, x + (rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5, y + (rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5); col.r += avcol.r; /* accumulate antialiasing samples */ col.g += avcol.g; col.b += avcol.b; } /* average sample colors, back to range 0.0 - 1.0 */ scale = 1.0f / (scene->antialiasing + 1.0f); col.r *= scale; col.g *= scale; col.b *= scale; return col; } #endif /* * cam_dof_ray() * Generate a perspective camera ray for depth-of-field rendering */ color cam_dof_ray(ray * ry, flt x, flt y) { flt rdx, rdy, rdz, len; scenedef * scene=ry->scene; /* starting from the lower left corner of the image plane, we move the */ /* center of the pel we're calculating: */ /* lowerleft + (rightvec * X_distance) + (upvec * Y_distance) */ /* rdx/y/z are the ray directions (unnormalized) */ rdx = scene->camera.lowleft.x + (x * scene->camera.iplaneright.x) + (y * scene->camera.iplaneup.x) - ry->o.x; rdy = scene->camera.lowleft.y + (x * scene->camera.iplaneright.y) + (y * scene->camera.iplaneup.y) - ry->o.y; rdz = scene->camera.lowleft.z + (x * scene->camera.iplaneright.z) + (y * scene->camera.iplaneup.z) - ry->o.z; /* normalize the ray direction vector */ len = 1.0 / sqrt(rdx*rdx + rdy*rdy + rdz*rdz); ry->d.x = rdx * len; ry->d.y = rdy * len; ry->d.z = rdz * len; /* initialize ray attributes for a primary ray */ ry->maxdist = FHUGE; /* unbounded ray */ ry->opticdist = 0.0; /* ray is just starting */ ry->flags = RT_RAY_REGULAR; /* camera only generates primary rays */ ry->serial++; /* increment the ray serial number */ intersect_objects(ry); /* trace the ray */ return scene->shader(ry); /* shade the hit point */ } /* * cam_aa_perspective_ray() * Generate a perspective camera ray incorporating antialiasing. */ color cam_aa_perspective_ray(ray * ry, flt x, flt y) { color col, avcol; int alias; scenedef * scene=ry->scene; float scale; col=cam_perspective_ray(ry, x, y); /* generate ray */ /* perform antialiasing if enabled. */ /* samples are run through a very simple box filter averaging */ /* each of the sample pixel colors to produce a final result */ for (alias=1; alias <= scene->antialiasing; alias++) { avcol=cam_perspective_ray(ry, x + (rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5, y + (rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5); col.r += avcol.r; /* accumulate antialiasing samples */ col.g += avcol.g; col.b += avcol.b; } /* average sample colors, back to range 0.0 - 1.0 */ scale = 1.0f / (scene->antialiasing + 1.0f); col.r *= scale; col.g *= scale; col.b *= scale; return col; } /* * cam_perspective_ray() * Generate a perspective camera ray, no antialiasing */ color cam_perspective_ray(ray * ry, flt x, flt y) { flt rdx, rdy, rdz, len; scenedef * scene=ry->scene; /* starting from the lower left corner of the image plane, we move the */ /* center of the pel we're calculating: */ /* lowerleft + (rightvec * X_distance) + (upvec * Y_distance) */ /* rdx/y/z are the ray directions (unnormalized) */ rdx = scene->camera.lowleft.x + (x * scene->camera.iplaneright.x) + (y * scene->camera.iplaneup.x); rdy = scene->camera.lowleft.y + (x * scene->camera.iplaneright.y) + (y * scene->camera.iplaneup.y); rdz = scene->camera.lowleft.z + (x * scene->camera.iplaneright.z) + (y * scene->camera.iplaneup.z); /* normalize the ray direction vector */ len = 1.0 / sqrt(rdx*rdx + rdy*rdy + rdz*rdz); ry->d.x = rdx * len; ry->d.y = rdy * len; ry->d.z = rdz * len; /* initialize ray attributes for a primary ray */ ry->maxdist = FHUGE; /* unbounded ray */ ry->opticdist = 0.0; /* ray is just starting */ ry->flags = RT_RAY_REGULAR; /* camera only generates primary rays */ ry->serial++; /* increment the ray serial number */ intersect_objects(ry); /* trace the ray */ return scene->shader(ry); /* shade the hit point */ } /* * cam_aa_orthographic_ray() * Generate an orthographic camera ray, potentially incorporating * antialiasing. */ color cam_aa_orthographic_ray(ray * ry, flt x, flt y) { color col, avcol; int alias; scenedef * scene=ry->scene; float scale; col=cam_orthographic_ray(ry, x, y); /* generate ray */ /* perform antialiasing if enabled. */ /* samples are run through a very simple box filter averaging */ /* each of the sample pixel colors to produce a final result */ for (alias=1; alias <= scene->antialiasing; alias++) { avcol=cam_orthographic_ray(ry, x + (rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5, y + (rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5); col.r += avcol.r; /* accumulate antialiasing samples */ col.g += avcol.g; col.b += avcol.b; } /* average sample colors, back to range 0.0 - 1.0 */ scale = 1.0f / (scene->antialiasing + 1.0f); col.r *= scale; col.g *= scale; col.b *= scale; return col; } /* * cam_orthographic_ray() * Generate an orthographic camera ray, no antialiasing */ color cam_orthographic_ray(ray * ry, flt x, flt y) { scenedef * scene=ry->scene; /* starting from the lower left corner of the image plane, we move the */ /* center of the pel we're calculating: */ /* lowerleft + (rightvec * X_distance) + (upvec * Y_distance) */ ry->o.x = scene->camera.lowleft.x + (x * scene->camera.iplaneright.x) + (y * scene->camera.iplaneup.x); ry->o.y = scene->camera.lowleft.y + (x * scene->camera.iplaneright.y) + (y * scene->camera.iplaneup.y); ry->o.z = scene->camera.lowleft.z + (x * scene->camera.iplaneright.z) + (y * scene->camera.iplaneup.z); /* initialize ray attributes for a primary ray */ ry->maxdist = FHUGE; /* unbounded ray */ ry->opticdist = 0.0; /* ray is just starting */ ry->flags = RT_RAY_REGULAR; /* camera only generates primary rays */ ry->serial++; /* increment the ray serial number */ intersect_objects(ry); /* trace the ray */ return scene->shader(ry); /* shade the hit point */ } /* * cam_fisheye_ray() * Generate a perspective camera ray, no antialiasing */ color cam_fisheye_ray(ray * ry, flt x, flt y) { flt ax, ay; scenedef * scene=ry->scene; ax = scene->camera.left + x * scene->camera.psx; ay = scene->camera.bottom + y * scene->camera.psy; ry->d.x = cos(ay) * (cos(ax) * scene->camera.viewvec.x + sin(ax) * scene->camera.rightvec.x) + sin(ay) * scene->camera.upvec.x; ry->d.y = cos(ay) * (cos(ax) * scene->camera.viewvec.y + sin(ax) * scene->camera.rightvec.y) + sin(ay) * scene->camera.upvec.y; ry->d.z = cos(ay) * (cos(ax) * scene->camera.viewvec.z + sin(ax) * scene->camera.rightvec.z) + sin(ay) * scene->camera.upvec.z; /* initialize ray attributes for a primary ray */ ry->maxdist = FHUGE; /* unbounded ray */ ry->opticdist = 0.0; /* ray is just starting */ ry->flags = RT_RAY_REGULAR; /* camera only generates primary rays */ ry->serial++; /* increment the ray serial number */ intersect_objects(ry); /* trace the ray */ return scene->shader(ry); /* shade the hit point */ } /* * cam_aa_fisheye_ray() * Generate a fisheye camera ray, potentially incorporating * antialiasing. */ color cam_aa_fisheye_ray(ray * ry, flt x, flt y) { color col, avcol; int alias; scenedef * scene=ry->scene; float scale; col=cam_fisheye_ray(ry, x, y); /* generate ray */ /* perform antialiasing if enabled. */ /* samples are run through a very simple box filter averaging */ /* each of the sample pixel colors to produce a final result */ for (alias=1; alias <= scene->antialiasing; alias++) { avcol=cam_fisheye_ray(ry, x + (rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5, y + (rt_rand(&ry->randval) / RT_RAND_MAX) - 0.5); col.r += avcol.r; /* accumulate antialiasing samples */ col.g += avcol.g; col.b += avcol.b; } /* average sample colors, back to range 0.0 - 1.0 */ scale = 1.0f / (scene->antialiasing + 1.0f); col.r *= scale; col.g *= scale; col.b *= scale; return col; } void cameraprojection(camdef * camera, int mode) { camera->projection=mode; } void camerafrustum(camdef * camera, flt left, flt right, flt bottom, flt top) { camera->left = left; camera->right = right; camera->bottom = bottom; camera->top = top; } void cameradof(camdef * camera, flt focallength, flt aperture) { camera->focallength=focallength; camera->aperture=aperture; } void camerasetup(scenedef * scene, flt zoom, vector center, vector viewvec, vector upvec) { flt sx, sy; camdef * camera = &scene->camera; vector newupvec; vector newviewvec; vector newrightvec; VCross(&upvec, &viewvec, &newrightvec); VNorm(&newrightvec); VCross(&viewvec, &newrightvec, &newupvec); VNorm(&newupvec); newviewvec=viewvec; VNorm(&newviewvec); camera->camzoom=zoom; camera->center=center; camera->viewvec=newviewvec; camera->rightvec=newrightvec; camera->upvec=newupvec; sx = (flt) scene->hres; sy = (flt) scene->vres; /* calculate the width and height of the image plane in world coords */ /* given the aspect ratio, image resolution, and zoom factor */ camera->px=((sx / sy) / scene->aspectratio) / scene->camera.camzoom; camera->py=1.0 / scene->camera.camzoom; camera->psx = camera->px / sx; camera->psy = camera->py / sy; camera->left = -0.5 * camera->px; camera->right = 0.5 * camera->px; camera->bottom = -0.5 * camera->py; camera->top = 0.5 * camera->py; camera->focallength = 1.0; } void cameraposition(camdef * camera, vector center, vector viewvec, vector upvec) { vector newupvec; vector newviewvec; vector newrightvec; VCross(&upvec, &viewvec, &newrightvec); VNorm(&newrightvec); VCross(&viewvec, &newrightvec, &newupvec); VNorm(&newupvec); newviewvec=viewvec; VNorm(&newviewvec); camera->center=center; camera->viewvec=newviewvec; camera->rightvec=newrightvec; camera->upvec=newupvec; } void getcameraposition(camdef * camera, vector * center, vector * viewvec, vector * upvec, vector * rightvec) { *center = camera->center; *viewvec = camera->viewvec; *upvec = camera->upvec; *rightvec = camera->rightvec; }
34.878519
84
0.601538
[ "vector" ]
922b86d5dd6e6d6d3faa919275191d56bf36bceb
2,749
h
C
include/h5geo/h5well.h
kerim371/h5geo
a023d8c667ff002de361e8184165e6d72e510bde
[ "MIT" ]
1
2021-06-17T23:40:52.000Z
2021-06-17T23:40:52.000Z
include/h5geo/h5well.h
tierra-colada/h5geo
1d577f4194c0f7826a3e584742fc9714831ec368
[ "MIT" ]
null
null
null
include/h5geo/h5well.h
tierra-colada/h5geo
1d577f4194c0f7826a3e584742fc9714831ec368
[ "MIT" ]
null
null
null
#ifndef H5WELL_H #define H5WELL_H #include "h5baseobject.h" #include <Eigen/Dense> class H5WellContainer; class H5DevCurve; class H5LogCurve; class H5Well : public H5BaseObject { protected: virtual ~H5Well() = default; public: /// logType maybe empty virtual H5LogCurve* getLogCurve( const std::string &logType, const std::string &logName) = 0; virtual H5LogCurve* getLogCurve( h5gt::Group group) = 0; virtual H5DevCurve* getDevCurve( const std::string &devName) = 0; virtual H5DevCurve* getDevCurve( h5gt::Group group) = 0; /// logType maybe empty virtual H5LogCurve* createLogCurve( std::string& logType, std::string& logName, LogCurveParam& p, h5geo::CreationType createFlag) = 0; virtual H5LogCurve* createLogCurve( h5gt::Group group, LogCurveParam& p, h5geo::CreationType createFlag) = 0; virtual H5DevCurve* createDevCurve( std::string& devName, DevCurveParam& p, h5geo::CreationType createFlag) = 0; virtual H5DevCurve* createDevCurve( h5gt::Group group, DevCurveParam& p, h5geo::CreationType createFlag) = 0; virtual bool setHeadCoord( Eigen::Ref<Eigen::Vector2d> v, const std::string& lengthUnits = "", bool doCoordTransform = false) = 0; virtual bool setKB( double& val, const std::string& lengthUnits = "") = 0; virtual bool setUWI(const std::string& str) = 0; virtual bool setActiveDevCurve(H5DevCurve* curve) = 0; virtual Eigen::VectorXd getHeadCoord( const std::string& lengthUnits = "", bool doCoordTransform = false) = 0; virtual double getKB( const std::string& lengthUnits = "") = 0; virtual std::string getUWI() = 0; virtual H5DevCurve* getActiveDevCurve() = 0; /// Omit active dev curve virtual std::vector<h5gt::Group> getDevCurveGroupList() = 0; virtual std::vector<h5gt::Group> getLogCurveGroupList() = 0; /// Omit active dev curve virtual std::vector<std::string> getDevCurveNameList() = 0; /// return all logCurve names in the form 'TYPE/NAME' virtual std::vector<std::string> getLogCurveNameList() = 0; /// return all objG child group names that are not logCurves virtual std::vector<std::string> getLogTypeNameList() = 0; virtual H5WellContainer* getWellContainer() = 0; virtual std::optional<h5gt::Group> getDevG() = 0; virtual std::optional<h5gt::Group> getActiveDevG() = 0; virtual std::optional<h5gt::Group> getLogG() = 0; virtual std::optional<h5gt::Group> getLogTypeG(const std::string& logType) = 0; }; namespace h5geo { extern "C" { H5GEO_EXPORT H5Well* openWell(h5gt::Group group); } } using H5Well_ptr = std::unique_ptr<H5Well, h5geo::ObjectDeleter>; #endif // H5WELL_H
29.55914
81
0.684976
[ "vector" ]
923e060f0967f2899333a2f5589fbe6e4c7a6b2c
7,318
h
C
camera/hal/intel/ipu6/include/ia_imaging/ia_view_types.h
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
camera/hal/intel/ipu6/include/ia_imaging/ia_view_types.h
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
camera/hal/intel/ipu6/include/ia_imaging/ia_view_types.h
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2017-2020 Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __IA_VIEW_TYPES_H_ #define __IA_VIEW_TYPES_H_ #include <stdint.h> #include "ia_types.h" #ifdef __cplusplus extern "C" { #endif /*!< ia_view_status_t: ia_view enable/disable and configure status */ typedef enum { ia_view_bypass=0, ia_view_user_input_configured, ia_view_resolution_configured, } ia_view_status_t; /*!< ia_view_proc_enabled_t: The processing blocks enabled in GDC. Used in PAL*/ typedef enum { ia_view_proc_enabled_none=0, ia_view_proc_enabled_pre_affine=(1<<0), ia_view_proc_enabled_rotation=(1<<1), ia_view_proc_enabled_post_affine=(1<<2), } ia_view_proc_enabled_t; /*!< ia_view_resolution_params_t: The frame resolutions at various points in the pipe*/ typedef enum { ia_view_resolution_at_sensor_output=0, /*Resolution at sensor output */ ia_view_resolution_at_gdc_input, /*Resolution at gdc input */ ia_view_resolution_at_gdc_output, /*Resolution at gdc output */ ia_view_resolution_at_pipe_output, /*Resolution at pipe output */ ia_view_resolution_max, } ia_view_resolution_params_t; /*!< Invalid coordinate size: Number of color channels possible to be specified.*/ #define IA_VIEW_INVALID_COORD_SIZE (4) /*!< ia_view_projection_type_t: User controllable projection type*/ typedef enum { ia_view_projection_rectilinear, ia_view_projection_conical, ia_view_projection_equirectangular, ia_view_projection_2Dbowl, ia_view_projection_cylindrical } ia_view_projection_type_t; /*!< ia_view_camera_mount_type_t: User controllable camera mount type*/ typedef enum { ia_view_wall_mounted, ia_view_ceiling_mounted, } ia_view_camera_mount_type_t; /*!< ia_view_fine_adjustments_t: Control fine adjustments of the viewing window*/ typedef struct { float horizontal_shift; /*!< Horizontal shift in pixels*/ float vertical_shift; /*!< Vertical shift in pixels*/ float window_rotation; /*!< Rotate the window, angle in degrees*/ float vertical_stretch; /*!< Vertical stretch factor*/ } ia_view_fine_adjustments_t; /*!< ia_view_rotation_t: Set view rotation in x, y, z axis*/ typedef struct { float pitch; /*!< pitch angle in degrees: rotation along X axis*/ float yaw; /*!< yaw angle in degrees: rotation along Y axis*/ float roll; /*!< roll angle in degrees: rotation along Z axis*/ } ia_view_rotation_t; /*!< ia_view_resolution_t: The resolution required for view*/ typedef struct { int width; /*!< Resolution width */ int height; /*!< Resolution height */ int horz_offset; /*!< Horizontal offset */ int vert_offset; /*!< Vertical offset */ float scale_factor; /*!< Scale factor */ } ia_view_resolution_t; /*!< translation array size*/ #define IA_VIEW_3D_TRANSLATION_SIZE (3) /*!< ia_view_config_t: Set view parameters*/ typedef struct { ia_view_projection_type_t type; /*!< type: The projection type desired*/ float zoom; /*!< zoom: Zoom configuration*/ float cone_angle; /*!< cone_angle used only for ia_view_projection_conical*/ double bowl_radius_sqr; /*!< bowl_radius_sqr used only for ia_view_projection_2Dbowl*/ double bowl_scale; /*!< bowl_scale used only for ia_view_projection_2Dbowl*/ ia_view_camera_mount_type_t camera_mount_type; /*! camera mount type: The mounting position of the camera: wall, ceiling*/ int32_t invalid_coordinate_mask[IA_VIEW_INVALID_COORD_SIZE]; /*!< Used to fill for each color channel when coordinates falls out of bounds */ ia_view_rotation_t camera_rotation; /*(< Camera rotation configuration */ ia_view_rotation_t view_rotation; /*!< View rotation configuration */ float translation[IA_VIEW_3D_TRANSLATION_SIZE]; /*!< Translation3D vector for Bowl projection*/ ia_view_fine_adjustments_t fine_adjustments; /*!< Fine adjustment configuration */ } ia_view_config_t, *ia_isp_bxt_view_params_t; /*!< ia_view_mbr_limits_t: Set mbr limits for view parameters*/ typedef struct { /*!< Min Zooming on projection*/ float zoom; /*!< max pitch of view*/ float pitch; /*!< max yaw of view*/ float yaw; /*!< max roll view*/ float roll; /*!< max Window rotation*/ float winrotation; /*!< max vertical scale*/ float vertical_stretch; /*!< max horizontal shift*/ float horizontal_shift; /*!< max vertical shift*/ float vertical_shift; } ia_view_limits_t; typedef struct { ia_view_limits_t cylindrical; ia_view_limits_t equirectangular; ia_view_limits_t rectilinear; ia_view_limits_t conical_m40; ia_view_limits_t conical_m20; ia_view_limits_t conical_p20; ia_view_limits_t conical_p40; }ia_view_mbr_limits_t,ia_isp_bxt_gdc_limits; /*!< ia_view_projection_t: Calculated parameter used in PAL*/ typedef struct { ia_view_projection_type_t type; /*!< type: Projection type to be used*/ double scale_factor_1[2]; /*!< scale_factor_1: Internal scale factor calculated*/ double scale_factor_2[2]; /*!< scale_factor_2: Internal scale factor calculated*/ double inv_f_pi; /*!< inv_f_pi is inverse focal lenght pi: Internal parameter*/ double bowl_radius_sqr; double bowl_scale; } ia_view_projection_t; /*!< ia_view_params_t: Calculated parameter to be used in PAL*/ typedef struct { /*!< Mask indicating what parameters are enabled*/ int32_t enabled_mask; /*!< Projections the view */ ia_view_projection_t projection; /*!< Pre Affine Matrix: Window rotatoin and scale*/ float pre_affine_scale_matrix[2][2]; /*!< Pre Affine Matrix: Translation*/ double pre_affine_translation_matrix[2]; /*!< Rotation Matrix combines camera and view rotations */ float rotation_matrix[3][3]; /*!< Translation3D Matrix for Bowl Projection*/ float translation_matrix[IA_VIEW_3D_TRANSLATION_SIZE]; /*!< Post Affine Matrix */ float post_affine_scale_matrix[2][2]; /*!< Post Affine Matrix */ double post_affine_translation_matrix[2]; /*!< Invalid coordinate mask for each color channel */ int32_t invalid_coordinate_mask[IA_VIEW_INVALID_COORD_SIZE]; } ia_view_params_t; typedef struct { ia_view_status_t is_configured; ia_view_config_t config; ia_view_resolution_t resolution[ia_view_resolution_max]; /*!< View resolution at different stages in the pipe */ float cmc_affine_scale_matrix[2][2]; double cmc_affine_translation_matrix[2]; float cmc_focal_length; ia_view_params_t isp_params; } ia_view_t; typedef ia_view_t* ia_view_handle; #ifdef __cplusplus } #endif #endif /* __IA_VIEW_TYPES_H_ */
33.113122
145
0.723148
[ "vector" ]
92489eb2cd7f9de847da4534da4863132a59f858
6,001
h
C
uuv_world_plugins/uuv_world_ros_plugins/include/uuv_world_ros_plugins/UnderwaterCurrentROSPlugin.h
oKermorgant/Plankton
ce21579792122b05d27f147ab66f515001ccb733
[ "Apache-2.0", "BSD-3-Clause" ]
79
2020-09-30T22:19:07.000Z
2022-03-27T12:30:58.000Z
uuv_world_plugins/uuv_world_ros_plugins/include/uuv_world_ros_plugins/UnderwaterCurrentROSPlugin.h
oKermorgant/Plankton
ce21579792122b05d27f147ab66f515001ccb733
[ "Apache-2.0", "BSD-3-Clause" ]
17
2020-10-05T01:01:49.000Z
2022-03-04T13:58:53.000Z
uuv_world_plugins/uuv_world_ros_plugins/include/uuv_world_ros_plugins/UnderwaterCurrentROSPlugin.h
oKermorgant/Plankton
ce21579792122b05d27f147ab66f515001ccb733
[ "Apache-2.0", "BSD-3-Clause" ]
22
2020-10-27T14:42:48.000Z
2022-03-25T10:41:51.000Z
// Copyright (c) 2020 The Plankton Authors. // All rights reserved. // // This source code is derived from UUV Simulator // (https://github.com/uuvsimulator/uuv_simulator) // Copyright (c) 2016-2019 The UUV Simulator Authors // licensed under the Apache 2 license // cf. 3rd-party-licenses.txt file in the root directory of this source tree. // // 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 UnderwaterCurrentROSPlugin.hh /// \brief Publishes the constant flow velocity in ROS messages and creates a /// service to alter the flow model in runtime #ifndef __UNDERWATER_CURRENT_ROS_PLUGIN_HH__ #define __UNDERWATER_CURRENT_ROS_PLUGIN_HH__ #include <map> #include <string> // Gazebo plugin #include <uuv_world_plugins/UnderwaterCurrentPlugin.h> #include <gazebo/common/Plugin.hh> #include <gazebo/physics/World.hh> #include <gazebo_ros/node.hpp> #include <rclcpp/rclcpp.hpp> #include <geometry_msgs/msg/twist_stamped.hpp> #include <uuv_world_ros_plugins_msgs/srv/set_current_model.hpp> #include <uuv_world_ros_plugins_msgs/srv/get_current_model.hpp> #include <uuv_world_ros_plugins_msgs/srv/set_current_velocity.hpp> #include <uuv_world_ros_plugins_msgs/srv/set_current_direction.hpp> #include <uuv_world_ros_plugins_msgs/srv/set_origin_spherical_coord.hpp> #include <uuv_world_ros_plugins_msgs/srv/get_origin_spherical_coord.hpp> namespace uuv_simulator_ros { class UnderwaterCurrentROSPlugin : public gazebo::UnderwaterCurrentPlugin { /// \brief Class constructor public: UnderwaterCurrentROSPlugin(); /// \brief Class destructor public: virtual ~UnderwaterCurrentROSPlugin(); /// \brief Load module and read parameters from SDF. public: void Load(gazebo::physics::WorldPtr _world, sdf::ElementPtr _sdf); /// \brief Service call to update the parameters for the velocity /// Gauss-Markov process model public: void UpdateCurrentVelocityModel( const uuv_world_ros_plugins_msgs::srv::SetCurrentModel::Request::SharedPtr _req, uuv_world_ros_plugins_msgs::srv::SetCurrentModel::Response::SharedPtr _res); /// \brief Service call to update the parameters for the horizontal angle /// Gauss-Markov process model public: void UpdateCurrentHorzAngleModel( const uuv_world_ros_plugins_msgs::srv::SetCurrentModel::Request::SharedPtr _req, uuv_world_ros_plugins_msgs::srv::SetCurrentModel::Response::SharedPtr _res); /// \brief Service call to update the parameters for the vertical angle /// Gauss-Markov process model public: void UpdateCurrentVertAngleModel( const uuv_world_ros_plugins_msgs::srv::SetCurrentModel::Request::SharedPtr _req, uuv_world_ros_plugins_msgs::srv::SetCurrentModel::Response::SharedPtr _res); /// \brief Service call to read the parameters for the velocity /// Gauss-Markov process model public: void GetCurrentVelocityModel( const uuv_world_ros_plugins_msgs::srv::GetCurrentModel::Request::SharedPtr _req, uuv_world_ros_plugins_msgs::srv::GetCurrentModel::Response::SharedPtr _res); /// \brief Service call to read the parameters for the horizontal angle /// Gauss-Markov process model public: void GetCurrentHorzAngleModel( const uuv_world_ros_plugins_msgs::srv::GetCurrentModel::Request::SharedPtr _req, uuv_world_ros_plugins_msgs::srv::GetCurrentModel::Response::SharedPtr _res); /// \brief Service call to read the parameters for the vertical angle /// Gauss-Markov process model public: void GetCurrentVertAngleModel( const uuv_world_ros_plugins_msgs::srv::GetCurrentModel::Request::SharedPtr _req, uuv_world_ros_plugins_msgs::srv::GetCurrentModel::Response::SharedPtr _res); /// \brief Service call to update the mean value of the flow velocity public: void UpdateCurrentVelocity( const uuv_world_ros_plugins_msgs::srv::SetCurrentVelocity::Request::SharedPtr _req, uuv_world_ros_plugins_msgs::srv::SetCurrentVelocity::Response::SharedPtr _res); /// \brief Service call to update the mean value of the horizontal angle public: void UpdateHorzAngle( const uuv_world_ros_plugins_msgs::srv::SetCurrentDirection::Request::SharedPtr _req, uuv_world_ros_plugins_msgs::srv::SetCurrentDirection::Response::SharedPtr _res); /// \brief Service call to update the mean value of the vertical angle public: void UpdateVertAngle( const uuv_world_ros_plugins_msgs::srv::SetCurrentDirection::Request::SharedPtr _req, uuv_world_ros_plugins_msgs::srv::SetCurrentDirection::Response::SharedPtr _res); /// \brief Publishes ROS topics private: void OnUpdateCurrentVel(); /// \brief All underwater world services private: std::map<std::string, rclcpp::ServiceBase::SharedPtr> worldServices; /// \brief Pointer to this ROS node's handle. private: gazebo_ros::Node::SharedPtr myRosNode; /// \brief Connection for callbacks on update world. private: gazebo::event::ConnectionPtr rosPublishConnection; /// \brief Publisher for the flow velocity in the world frame private: rclcpp::Publisher<geometry_msgs::msg::TwistStamped>::SharedPtr myFlowVelocityPub; /// \brief Period after which we should publish a message via ROS. private: gazebo::common::Time rosPublishPeriod; /// \brief Last time we published a message via ROS. private: gazebo::common::Time lastRosPublishTime; }; } #endif // __UNDERWATER_CURRENT_ROS_PLUGIN_HH__
43.172662
94
0.758374
[ "model" ]
92536c946333fb9ebab184987d6c7ce880a34a7f
2,042
h
C
src/quad.h
Roninkoi/Corium
1b6c9bfa5bbc1ef852c4e2769f80f83a1e9291ef
[ "MIT" ]
1
2018-07-17T06:09:13.000Z
2018-07-17T06:09:13.000Z
src/quad.h
Ronin748/Corium
1b6c9bfa5bbc1ef852c4e2769f80f83a1e9291ef
[ "MIT" ]
2
2019-09-18T19:41:59.000Z
2019-12-10T13:55:01.000Z
src/quad.h
Roninkoi/Corium
1b6c9bfa5bbc1ef852c4e2769f80f83a1e9291ef
[ "MIT" ]
null
null
null
// // Created by Roninkoi on 18.12.2015. // #ifndef CORIUM_QUAD_H #define CORIUM_QUAD_H #include "mesh.h" #include "texture.h" #include "util/quadIsect.h" class Quad : public Mesh { public: Texture tex; Phys phys; void update() { objMatrix = phys.getMatrix(); vertexData = transform(vertexData0, objMatrix); getNormals(); getBoundingSphere(); } void draw(Renderer *renderer) { renderer->draw(&tex, &vertexData, &normalData, &texData, &colData, &indexData); } void loadSprite(std::string tex_path, glm::vec4 tex_sprite, bool load_tex = true) { if (load_tex) { tex.loadTexture(tex_path); } float s_offs = (tex_sprite.s / (float) tex.w) * (tex.w / tex_sprite.p); float t_offs = (tex_sprite.t / (float) tex.h) * (tex.h / tex_sprite.q); float p_scale = tex_sprite.p / (float) tex.w; float q_scale = tex_sprite.q / (float) tex.h; texData = { 0.0f + s_offs, 0.0f + t_offs, p_scale, q_scale, 1.0f + s_offs, 0.0f + t_offs, p_scale, q_scale, 1.0f + s_offs, 1.0f + t_offs, p_scale, q_scale, 0.0f + s_offs, 1.0f + t_offs, p_scale, q_scale }; } Quad() : Mesh() { vertexData0.resize(16); texData.resize(16); colData.resize(16); indexData.resize(6); normalData.resize(6); vertexData0 = { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }; vertexData = { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }; indexData = { 0, 1, 2, 0, 2, 3 }; texData = { 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f }; colData = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; normalData = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f }; getNormals(); phys.update(); } }; #endif //CORIUM_QUAD_H
19.825243
83
0.541136
[ "mesh", "transform" ]
9254adf257cafcfd7021d7443d3e543b1aecf318
668
h
C
tinyember/TinyEmberPlusRouter/TinyEmberPlusRouter/model/model.h
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
78
2015-07-31T14:46:38.000Z
2022-03-28T09:28:28.000Z
tinyember/TinyEmberPlusRouter/TinyEmberPlusRouter/model/model.h
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
81
2015-08-03T07:58:19.000Z
2022-02-28T16:21:19.000Z
tinyember/TinyEmberPlusRouter/TinyEmberPlusRouter/model/model.h
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
49
2015-08-03T12:53:10.000Z
2022-03-17T17:25:49.000Z
/* Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.com). Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef __TINYEMBERROUTER_MODEL_H #define __TINYEMBERROUTER_MODEL_H // convenience header to include the complete model. #include "Node.h" #include "IntegerParameter.h" #include "StringParameter.h" #include "Function.h" #include "matrix/DynamicNToNLinearMatrix.h" #include "matrix/NToNLinearMatrix.h" #include "matrix/NToNNonlinearMatrix.h" #include "matrix/OneToNLinearMatrix.h" #include "ElementVisitor.h" #endif//__TINYEMBERROUTER_MODEL_H
29.043478
91
0.77994
[ "model" ]
925a10fdcc98885eb25529441c6c96ec21946919
2,959
h
C
include/dpp/guild.h
DragonDev15/DPP
633bc18f336c07eda1c7de186f4d5d0744cf1acd
[ "Apache-2.0" ]
null
null
null
include/dpp/guild.h
DragonDev15/DPP
633bc18f336c07eda1c7de186f4d5d0744cf1acd
[ "Apache-2.0" ]
null
null
null
include/dpp/guild.h
DragonDev15/DPP
633bc18f336c07eda1c7de186f4d5d0744cf1acd
[ "Apache-2.0" ]
null
null
null
#pragma once namespace dpp { enum region { r_brazil, r_central_europe, r_hong_kong, r_india, r_japan, r_russia, r_singapore, r_south_africa, r_sydney, r_us_central, r_us_east, r_us_south, r_us_west, r_western_europe }; enum guild_flags { g_large = 0b00000000000000000001, g_unavailable = 0b00000000000000000010, g_widget_enabled = 0b00000000000000000100, g_invite_splash = 0b00000000000000001000, g_vip_regions = 0b00000000000000010000, g_vanity_url = 0b00000000000000100000, g_verified = 0b00000000000001000000, g_partnered = 0b00000000000010000000, g_community = 0b00000000000100000000, g_commerce = 0b00000000001000000000, g_news = 0b00000000010000000000, g_discoverable = 0b00000000100000000000, g_featureable = 0b00000001000000000000, g_animated_icon = 0b00000010000000000000, g_banner = 0b00000100000000000000, g_welcome_screen_enabled = 0b00001000000000000000, g_member_verification_gate = 0b00010000000000000000, g_preview_enabled = 0b00100000000000000000, g_no_join_notifications = 0b01000000000000000000, g_no_boost_notifications = 0b10000000000000000000 }; class guild : public managed { public: uint32_t flags; std::string name; std::string icon; std::string splash; std::string discovery_splash; snowflake owner_id; region voice_region; snowflake afk_channel_id; uint32_t afk_timeout; snowflake widget_channel_id; uint8_t verification_level; uint8_t default_message_notifications; uint8_t explicit_content_filter; uint8_t mfa_level; snowflake application_id; snowflake system_channel_id; snowflake rules_channel_id; uint32_t member_count; std::string vanity_url_code; std::string description; std::string banner; uint8_t premium_tier; uint16_t premium_subscription_count; snowflake public_updates_channel_id; uint32_t max_video_channel_users; std::vector<snowflake> roles; std::vector<snowflake> channels; std::map<snowflake, class guild_member*> members; guild(); ~guild(); void fill_from_json(nlohmann::json* j); bool is_large(); bool is_unavailable(); bool widget_enabled(); bool has_invite_splash(); bool has_vip_regions(); bool has_vanity_url(); bool is_verified(); bool is_partnered(); bool is_community(); bool has_commerce(); bool has_news(); bool is_discoverable(); bool is_featureable(); bool has_animated_icon(); bool has_banner(); bool is_welcome_screen_enabled(); bool has_member_verification_gate(); bool is_preview_enabled(); }; typedef std::unordered_map<snowflake, guild*> guild_map; enum guild_member_flags { gm_deaf = 0b00001, gm_mute = 0b00010, gm_pending = 0b00100 }; class guild_member { public: snowflake guild_id; snowflake user_id; std::string nickname; std::vector<snowflake> roles; time_t joined_at; time_t premium_since; uint8_t flags; guild_member(); ~guild_member(); void fill_from_json(nlohmann::json* j, const class guild* g, const class user* u); }; };
23.299213
83
0.782697
[ "vector" ]
f37483caf8f191a402866dcfeaa16475f9291ba5
16,841
h
C
dc/include/tencentcloud/dc/v20180410/model/InternetAddressDetail.h
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
1
2022-01-27T09:27:34.000Z
2022-01-27T09:27:34.000Z
dc/include/tencentcloud/dc/v20180410/model/InternetAddressDetail.h
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
null
null
null
dc/include/tencentcloud/dc/v20180410/model/InternetAddressDetail.h
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 TENCENTCLOUD_DC_V20180410_MODEL_INTERNETADDRESSDETAIL_H_ #define TENCENTCLOUD_DC_V20180410_MODEL_INTERNETADDRESSDETAIL_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Dc { namespace V20180410 { namespace Model { /** * Internet tunnel’s IP address details */ class InternetAddressDetail : public AbstractModel { public: InternetAddressDetail(); ~InternetAddressDetail() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取Internet tunnel’s IP address ID Note: this field may return `null`, indicating that no valid values can be obtained. * @return InstanceId Internet tunnel’s IP address ID Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string GetInstanceId() const; /** * 设置Internet tunnel’s IP address ID Note: this field may return `null`, indicating that no valid values can be obtained. * @param InstanceId Internet tunnel’s IP address ID Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetInstanceId(const std::string& _instanceId); /** * 判断参数 InstanceId 是否已赋值 * @return InstanceId 是否已赋值 */ bool InstanceIdHasBeenSet() const; /** * 获取Internet tunnel’s network address Note: this field may return `null`, indicating that no valid values can be obtained. * @return Subnet Internet tunnel’s network address Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string GetSubnet() const; /** * 设置Internet tunnel’s network address Note: this field may return `null`, indicating that no valid values can be obtained. * @param Subnet Internet tunnel’s network address Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetSubnet(const std::string& _subnet); /** * 判断参数 Subnet 是否已赋值 * @return Subnet 是否已赋值 */ bool SubnetHasBeenSet() const; /** * 获取Mask length of a network address Note: this field may return `null`, indicating that no valid values can be obtained. * @return MaskLen Mask length of a network address Note: this field may return `null`, indicating that no valid values can be obtained. */ int64_t GetMaskLen() const; /** * 设置Mask length of a network address Note: this field may return `null`, indicating that no valid values can be obtained. * @param MaskLen Mask length of a network address Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetMaskLen(const int64_t& _maskLen); /** * 判断参数 MaskLen 是否已赋值 * @return MaskLen 是否已赋值 */ bool MaskLenHasBeenSet() const; /** * 获取Address type. Valid values: 0: BGP 1: China Telecom 2: China Mobile 3: China Unicom Note: this field may return `null`, indicating that no valid values can be obtained. * @return AddrType Address type. Valid values: 0: BGP 1: China Telecom 2: China Mobile 3: China Unicom Note: this field may return `null`, indicating that no valid values can be obtained. */ int64_t GetAddrType() const; /** * 设置Address type. Valid values: 0: BGP 1: China Telecom 2: China Mobile 3: China Unicom Note: this field may return `null`, indicating that no valid values can be obtained. * @param AddrType Address type. Valid values: 0: BGP 1: China Telecom 2: China Mobile 3: China Unicom Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetAddrType(const int64_t& _addrType); /** * 判断参数 AddrType 是否已赋值 * @return AddrType 是否已赋值 */ bool AddrTypeHasBeenSet() const; /** * 获取Address status. Valid values: 0: in use 1: disabled 2: returned * @return Status Address status. Valid values: 0: in use 1: disabled 2: returned */ int64_t GetStatus() const; /** * 设置Address status. Valid values: 0: in use 1: disabled 2: returned * @param Status Address status. Valid values: 0: in use 1: disabled 2: returned */ void SetStatus(const int64_t& _status); /** * 判断参数 Status 是否已赋值 * @return Status 是否已赋值 */ bool StatusHasBeenSet() const; /** * 获取Applied at Note: this field may return `null`, indicating that no valid values can be obtained. * @return ApplyTime Applied at Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string GetApplyTime() const; /** * 设置Applied at Note: this field may return `null`, indicating that no valid values can be obtained. * @param ApplyTime Applied at Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetApplyTime(const std::string& _applyTime); /** * 判断参数 ApplyTime 是否已赋值 * @return ApplyTime 是否已赋值 */ bool ApplyTimeHasBeenSet() const; /** * 获取Disabled at Note: this field may return `null`, indicating that no valid values can be obtained. * @return StopTime Disabled at Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string GetStopTime() const; /** * 设置Disabled at Note: this field may return `null`, indicating that no valid values can be obtained. * @param StopTime Disabled at Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetStopTime(const std::string& _stopTime); /** * 判断参数 StopTime 是否已赋值 * @return StopTime 是否已赋值 */ bool StopTimeHasBeenSet() const; /** * 获取Returned at Note: this field may return `null`, indicating that no valid values can be obtained. * @return ReleaseTime Returned at Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string GetReleaseTime() const; /** * 设置Returned at Note: this field may return `null`, indicating that no valid values can be obtained. * @param ReleaseTime Returned at Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetReleaseTime(const std::string& _releaseTime); /** * 判断参数 ReleaseTime 是否已赋值 * @return ReleaseTime 是否已赋值 */ bool ReleaseTimeHasBeenSet() const; /** * 获取Region Note: this field may return `null`, indicating that no valid values can be obtained. * @return Region Region Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string GetRegion() const; /** * 设置Region Note: this field may return `null`, indicating that no valid values can be obtained. * @param Region Region Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetRegion(const std::string& _region); /** * 判断参数 Region 是否已赋值 * @return Region 是否已赋值 */ bool RegionHasBeenSet() const; /** * 获取User ID Note: this field may return `null`, indicating that no valid values can be obtained. * @return AppId User ID Note: this field may return `null`, indicating that no valid values can be obtained. */ int64_t GetAppId() const; /** * 设置User ID Note: this field may return `null`, indicating that no valid values can be obtained. * @param AppId User ID Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetAppId(const int64_t& _appId); /** * 判断参数 AppId 是否已赋值 * @return AppId 是否已赋值 */ bool AppIdHasBeenSet() const; /** * 获取Address protocol. Valid values: 0: IPv4; 1: IPv6 Note: this field may return `null`, indicating that no valid values can be obtained. * @return AddrProto Address protocol. Valid values: 0: IPv4; 1: IPv6 Note: this field may return `null`, indicating that no valid values can be obtained. */ int64_t GetAddrProto() const; /** * 设置Address protocol. Valid values: 0: IPv4; 1: IPv6 Note: this field may return `null`, indicating that no valid values can be obtained. * @param AddrProto Address protocol. Valid values: 0: IPv4; 1: IPv6 Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetAddrProto(const int64_t& _addrProto); /** * 判断参数 AddrProto 是否已赋值 * @return AddrProto 是否已赋值 */ bool AddrProtoHasBeenSet() const; /** * 获取Retention period of a released IP address, in days Note: this field may return `null`, indicating that no valid values can be obtained. * @return ReserveTime Retention period of a released IP address, in days Note: this field may return `null`, indicating that no valid values can be obtained. */ int64_t GetReserveTime() const; /** * 设置Retention period of a released IP address, in days Note: this field may return `null`, indicating that no valid values can be obtained. * @param ReserveTime Retention period of a released IP address, in days Note: this field may return `null`, indicating that no valid values can be obtained. */ void SetReserveTime(const int64_t& _reserveTime); /** * 判断参数 ReserveTime 是否已赋值 * @return ReserveTime 是否已赋值 */ bool ReserveTimeHasBeenSet() const; private: /** * Internet tunnel’s IP address ID Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string m_instanceId; bool m_instanceIdHasBeenSet; /** * Internet tunnel’s network address Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string m_subnet; bool m_subnetHasBeenSet; /** * Mask length of a network address Note: this field may return `null`, indicating that no valid values can be obtained. */ int64_t m_maskLen; bool m_maskLenHasBeenSet; /** * Address type. Valid values: 0: BGP 1: China Telecom 2: China Mobile 3: China Unicom Note: this field may return `null`, indicating that no valid values can be obtained. */ int64_t m_addrType; bool m_addrTypeHasBeenSet; /** * Address status. Valid values: 0: in use 1: disabled 2: returned */ int64_t m_status; bool m_statusHasBeenSet; /** * Applied at Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string m_applyTime; bool m_applyTimeHasBeenSet; /** * Disabled at Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string m_stopTime; bool m_stopTimeHasBeenSet; /** * Returned at Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string m_releaseTime; bool m_releaseTimeHasBeenSet; /** * Region Note: this field may return `null`, indicating that no valid values can be obtained. */ std::string m_region; bool m_regionHasBeenSet; /** * User ID Note: this field may return `null`, indicating that no valid values can be obtained. */ int64_t m_appId; bool m_appIdHasBeenSet; /** * Address protocol. Valid values: 0: IPv4; 1: IPv6 Note: this field may return `null`, indicating that no valid values can be obtained. */ int64_t m_addrProto; bool m_addrProtoHasBeenSet; /** * Retention period of a released IP address, in days Note: this field may return `null`, indicating that no valid values can be obtained. */ int64_t m_reserveTime; bool m_reserveTimeHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_DC_V20180410_MODEL_INTERNETADDRESSDETAIL_H_
39.532864
116
0.520219
[ "vector", "model" ]
f379bb3d87b0da7d2ed8a2944408f2e983084987
4,895
c
C
nitan/kungfu/skill/bingpo-shenzhen/bing.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/kungfu/skill/bingpo-shenzhen/bing.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/kungfu/skill/bingpo-shenzhen/bing.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
#include <ansi.h> #include <combat.h> inherit F_SSERVER; string name() { return HIG "寒冰針" NOR; } #include "/kungfu/skill/eff_msg.h"; int perform(object me, object target) { int skill, n; int ap, dp, p, damage; string msg, pmsg; object weapon; int level; if (! target) target = offensive_target(me); if (! target || ! me->is_fighting(target)) return notify_fail(name() + "只能在戰鬥中對對手使用。\n"); if( !objectp(weapon=query_temp("handing", me)) || query("skill_type", weapon) != "throwing" ) return notify_fail("你現在手中沒有拿着暗器,難以施展" + name() + "。\n"); if (weapon->query_amount() < 1) return notify_fail("你手中沒有針,無法施展" + name() + "。\n"); if ((skill = me->query_skill("bingpo-shenzhen", 1)) < 120) return notify_fail("你的冰魄神針不夠嫻熟,難以施展" + name() + "。\n"); if ((int)me->query_skill("force") < 150) return notify_fail("你的內功修為不足,難以施展" + name() + "。\n"); if( query("max_neili", me)<1500 ) return notify_fail("你的內力修為不足,難以施展" + name() + "。\n"); if( query("neili", me)<150 ) return notify_fail("你現在真氣不足,難以施展" + name() + "。\n"); if( query_temp("bingpo", target) ) return notify_fail("對方已經中了你的絕招,現在是廢人一" "個,趕快進攻吧!\n"); if (! living(target)) return notify_fail("對方都已經這樣了,用不着這麼費力吧?\n"); addn("neili", -120, me); weapon->add_amount(-1); msg = HIY "只見$N" HIY "長袖微拂,手腕一轉,一招「" HIW "寒冰針" HIY"」,將手中" + weapon->name() + HIY "猛地射出。剎那\n" "間,長空破響," + weapon->name() + HIY "如同一顆流星劃過," "襲向$n!\n" NOR; ap = attack_power(me, "throwing"); dp = defense_power(target, "dodge"); level = skill; if (ap + random(ap / 2) > dp) { damage = damage_power(me, "throwing"); if (target->query_skill("parry") < me->query_skill("throwing")) { msg += HIR "只聽$n" HIR "慘叫一聲," + weapon->name() + HIR "已經射中要害,只感傷口處透處陣陣寒意,頓覺全身軟" "弱無力。\n"NOR; target->receive_damage("qi", damage, me); target->receive_wound("qi", damage/ 3, me); set_temp("bingpo", 1, target); addn_temp("apply/attack", -level/5, target); addn_temp("apply/dodge", -level/5, target); addn_temp("apply/parry", -level/10, target); target->set_weak(3, 0); COMBAT_D->clear_ahinfo(); weapon->hit_ob(me,target,query("jiali", me)+180); p=query("qi", target)*100/query("max_qi", target); if (stringp(pmsg = COMBAT_D->query_ahinfo())) msg += pmsg; msg += "( $n" + eff_status_msg(p) + " )\n"; message_combatd(msg, me, target); tell_object(target, RED "你現在要穴受到重損,乃至全身乏力" ",提不上半點力道!\n" NOR); tell_object(me, HIC "你心知剛才這招已打中對方要害,不禁暗自冷笑。\n" NOR); call_out("back", 2 + random(skill / 15), target, level); } else { msg += HIR "$n" HIR "眼見暗器襲來,左躲右閃,但仍" "然受了一點輕傷。\n" NOR, me, target; target->receive_damage("qi", damage/2); target->receive_wound("qi", damage/4); COMBAT_D->clear_ahinfo(); weapon->hit_ob(me,target,query("jiali", me)/2); p=query("qi", target)*100/query("max_qi", target); msg += "( $n" + eff_status_msg(p) + " )\n"; message_combatd(msg, me, target); tell_object(target, RED "你只覺全身幾處一陣刺痛,知道自己" "雖被擊中,但卻是避開了要害。\n" NOR); me->start_busy(1 + random(2)); } } else { msg += CYN "可是$n" CYN "身法靈巧,小心閃避,好不容易避開了" CYN "$N" CYN "迅猛如電的攻擊。\n" NOR; message_combatd(msg, me, target); me->start_busy(3); } return 1; } void back(object target, int level) { if (objectp(target)) { addn_temp("apply/attack", level/5, target); addn_temp("apply/dodge", level/5, target); addn_temp("apply/parry", level/10, target); // tell_object(target, HIY "漸漸的你覺得力氣一絲絲的恢復了。\n" NOR); delete_temp("bingpo", target); } }
36.529851
80
0.4476
[ "object" ]
f37dcef99da733c2ad9c8a895db0cfd8a10a93b2
2,911
h
C
addons/ofxCvGui/src/ofxCvGui/Utils/Utils.h
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
addons/ofxCvGui/src/ofxCvGui/Utils/Utils.h
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
addons/ofxCvGui/src/ofxCvGui/Utils/Utils.h
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
#pragma once #include "ofxSingleton.h" #include "ofRectangle.h" #include "ofColor.h" #include "ofCamera.h" #include "ofGraphics.h" #include <glm/glm.hpp> #include <vector> #include <string> //#define OFXCVGUI_DISBALE_SCISSOR #define OFXCVGUI_TEXT_BACKGROUND 0x46 #define OFXCVGUI_TEXT_SIZE 15 namespace ofxCvGui { namespace Utils { #pragma mark Text ofRectangle OFXCVGUI_API_ENTRY drawText(const std::string& text, float x, float y, bool background = true, float minHeight = 15, float minWidth = 0, bool scissor = false, const ofColor & backgroundColor = ofColor(OFXCVGUI_TEXT_BACKGROUND)); ofRectangle OFXCVGUI_API_ENTRY drawText(const std::string& text, const ofRectangle & bounds, bool background = true, bool scissor = false); void OFXCVGUI_API_ENTRY drawProcessingNotice(std::string message); void OFXCVGUI_API_ENTRY drawToolTip(const std::string & text, const glm::vec2 & position); std::string OFXCVGUI_API_ENTRY makeString(char key); void OFXCVGUI_API_ENTRY drawTextAnnotation(const std::string& text, const glm::vec3& position, const ofColor & = ofColor(40)); /// <summary> /// A deferred system for rendering annotations to 3D views /// </summary> class OFXCVGUI_API_ENTRY AnnotationManager : public ofxSingleton::Singleton<AnnotationManager> { public: struct TextAnnotation { std::string text; glm::vec3 position; ofColor color; glm::mat4x4 worldViewTransform = ofGetCurrentMatrix(ofMatrixMode::OF_MATRIX_MODELVIEW); }; struct DrawAnnotation { std::function<void()> drawCall; ofRectangle bounds; glm::vec3 position; ofColor color; glm::mat4x4 worldViewTransform = ofGetCurrentMatrix(ofMatrixMode::OF_MATRIX_MODELVIEW); }; AnnotationManager(); void clear(); void annotate(const std::string & text, const glm::vec3 & position, const ofColor & = ofColor(40)); void annotate(const TextAnnotation&); void annotate(const DrawAnnotation&); void renderAndClearAnnotations(const ofCamera & camera , const ofRectangle & viewport); void setEnabled(bool); protected: std::vector<TextAnnotation> textAnnotations; std::vector<DrawAnnotation> drawAnnotations; bool enabled = true; }; #pragma mark Animation ofColor OFXCVGUI_API_ENTRY getBeatingSelectionColor(); #pragma mark Scissor class OFXCVGUI_API_ENTRY ScissorManager : public ofxSingleton::Singleton<ScissorManager> { public: ScissorManager(); bool getScissorEnabled() const; void setScissorEnabled(bool); void pushScissor(const ofRectangle &); void popScissor(); ofRectangle getScissor() const; protected: void setScissor(const ofRectangle &); bool scissorEnabled; std::vector<ofRectangle> scissorHistory; }; #pragma mark Math ofRectangle OFXCVGUI_API_ENTRY operator*(const ofRectangle &, const glm::mat4 &); #pragma mark Colors ofColor OFXCVGUI_API_ENTRY toColor(const std::string &); } }
31.641304
242
0.749914
[ "vector", "3d" ]
f38707051f21d7b3fd2f305b3e826edca585dfcc
510
h
C
negele/quad.h
cheshyre/negele-srg-solver-cpp
9510a40665480508c28de784f9af2eb4c7e6c0ae
[ "MIT" ]
null
null
null
negele/quad.h
cheshyre/negele-srg-solver-cpp
9510a40665480508c28de784f9af2eb4c7e6c0ae
[ "MIT" ]
null
null
null
negele/quad.h
cheshyre/negele-srg-solver-cpp
9510a40665480508c28de784f9af2eb4c7e6c0ae
[ "MIT" ]
null
null
null
// Copyright 2020 Matthias Heinz #ifndef NEGELE_QUAD_H_ #define NEGELE_QUAD_H_ #include <tuple> #include <vector> namespace negele { namespace quad { /** * @brief Get the gauss legendre quadrature object * * @param num_pts * @param x_min * @param x_max * @return std::tuple<std::vector, std::vector> */ std::tuple<std::vector<double>, std::vector<double>> get_gauss_legendre_quadrature(int num_pts, double x_min, double x_max); } // namespace quad } // namespace negele #endif // NEGELE_QUAD_H_
19.615385
71
0.723529
[ "object", "vector" ]
f3902120c2c80ef251eb6f0744bf7d341e93ee63
507
h
C
JAERO/fftwrapper.h
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
152
2015-12-02T01:38:42.000Z
2022-03-29T10:41:37.000Z
JAERO/fftwrapper.h
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
59
2015-12-02T02:11:24.000Z
2022-03-21T02:48:11.000Z
JAERO/fftwrapper.h
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
38
2015-12-07T16:24:03.000Z
2021-12-25T15:44:27.000Z
#ifndef FFTWRAPPER_H #define FFTWRAPPER_H #include <QVector> #include <complex> #include "jfft.h" //underlying fft still uses the type in the kiss_fft_type in the c stuff template<typename T> class FFTWrapper { public: FFTWrapper(int nfft, bool inverse, bool kissfft_scaling=true); ~FFTWrapper(); void transform(const QVector< std::complex<T> > &in, QVector< std::complex<T> > &out); private: JFFT fft; int nfft; bool inverse; bool kissfft_scaling; }; #endif // FFTWRAPPER_H
21.125
90
0.710059
[ "transform" ]
f3937e9192e12619714e0cfcc4e59a3886ff2fc4
1,029
h
C
deploy/android_demo/app/src/main/cpp/common.h
ninetailskim/PaddleOCR
5586dbf42511517d00dc541070e0c5e094587c72
[ "Apache-2.0" ]
21
2020-12-01T14:00:40.000Z
2022-03-29T03:26:10.000Z
deploy/android_demo/app/src/main/cpp/common.h
ninetailskim/PaddleOCR
5586dbf42511517d00dc541070e0c5e094587c72
[ "Apache-2.0" ]
3
2021-04-28T09:22:27.000Z
2022-01-05T11:16:40.000Z
deploy/android_demo/app/src/main/cpp/common.h
ninetailskim/PaddleOCR
5586dbf42511517d00dc541070e0c5e094587c72
[ "Apache-2.0" ]
9
2021-01-26T01:46:00.000Z
2021-04-27T00:42:05.000Z
// // Created by fu on 4/25/18. // #pragma once #import <vector> #import <numeric> #ifdef __ANDROID__ #include <android/log.h> #define LOG_TAG "OCR_NDK" #define LOGI(...) \ __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGW(...) \ __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #define LOGE(...) \ __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #else #include <stdio.h> #define LOGI(format, ...) \ fprintf(stdout, "[" LOG_TAG "]" format "\n", ##__VA_ARGS__) #define LOGW(format, ...) \ fprintf(stdout, "[" LOG_TAG "]" format "\n", ##__VA_ARGS__) #define LOGE(format, ...) \ fprintf(stderr, "[" LOG_TAG "]Error: " format "\n", ##__VA_ARGS__) #endif enum RETURN_CODE { RETURN_OK = 0 }; enum NET_TYPE{ NET_OCR = 900100, NET_OCR_INTERNAL = 991008 }; template <typename T> inline T product(const std::vector<T> &vec) { if (vec.empty()){ return 0; } return std::accumulate(vec.begin(), vec.end(), 1, std::multiplies<T>()); }
21
76
0.653061
[ "vector" ]
f3a32980108d0644c2898a33e7607284fff12ab0
1,671
h
C
sample-chat-obj-c/sample-chat/Components/ChatScreen/Views/ChatCollectionView/ChatCollectionViewFlowLayout/ChatCollectionViewFlowLayout.h
SafetyCulture/quickblox-ios-sdk
3ead25767a33cde72ca669ed050ca87fcee262a9
[ "BSD-3-Clause" ]
397
2015-01-05T16:56:41.000Z
2021-12-30T09:30:21.000Z
sample-chat-obj-c/sample-chat/Components/ChatScreen/Views/ChatCollectionView/ChatCollectionViewFlowLayout/ChatCollectionViewFlowLayout.h
usama2razzaq/quickblox-ios-sdk
05a2b08e0c212a6fcf1328e1faf91e2922b07755
[ "BSD-3-Clause" ]
1,022
2015-01-02T08:32:03.000Z
2022-03-03T09:05:13.000Z
sample-chat-obj-c/sample-chat/Components/ChatScreen/Views/ChatCollectionView/ChatCollectionViewFlowLayout/ChatCollectionViewFlowLayout.h
usama2razzaq/quickblox-ios-sdk
05a2b08e0c212a6fcf1328e1faf91e2922b07755
[ "BSD-3-Clause" ]
334
2015-01-06T17:06:59.000Z
2022-03-24T08:10:14.000Z
// // ChatCollectionViewFlowLayout.h // samplechat // // Created by Injoit on 2/25/19. // Copyright © 2019 Quickblox. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class ChatCollectionView; /** * The `ChatCollectionViewFlowLayout` is a concrete layout object that inherits * from `UICollectionViewFlowLayout` and organizes message items in a vertical list. * Each `ChatCollectionViewCell` in the layout can display messages of arbitrary sizes and avatar images, * as well as metadata such as a timestamp and sender. * You can easily customize the layout via its properties or its delegate methods * defined in `ChatCollectionViewDelegateFlowLayout`. * * @see ChatCollectionViewDelegateFlowLayout. * @see ChatCollectionViewCell. */ @interface ChatCollectionViewFlowLayout : UICollectionViewFlowLayout /** * The collection view object currently using this layout object. */ @property (weak, nonatomic) ChatCollectionView *chatCollectionView; /** * Returns the width of items in the layout. */ @property (readonly, nonatomic) CGFloat itemWidth; - (CGSize)containerViewSizeForItemAtIndexPath:(NSIndexPath *)indexPath; /** * Size for item and index path. * * @discussion Returns cached size of item. If size is not in cache, then counts it first. * * @return Size of item at index path */ - (CGSize)sizeForItemAtIndexPath:(NSIndexPath *)indexPath; /** * Removing size for itemID from cache. * * @discussion Use this method before any of collection view reload methods, that will update missed cached sizes. */ - (void)removeSizeFromCacheForItemID:(NSString *)itemID; @end NS_ASSUME_NONNULL_END
27.85
115
0.75763
[ "object" ]
f3a91785f4f7098d28a4ad21e20f4e63aca75401
17,119
h
C
multimedia/directx/dplay/dplay4/protocol/arpstruc.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/directx/dplay/dplay4/protocol/arpstruc.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/directx/dplay/dplay4/protocol/arpstruc.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1997 Microsoft Corporation Module Name: ARPSTRUC.H Abstract: Structure definitions for the ARP protocol implementation Author: Aaron Ogus (aarono) Environment: Win32/COM Revision History: Date Author Description ======= ====== ============================================================ 1/27/97 aarono Original 2/18/98 aarono Added more fields to SEND for SendEx support 6/6/98 aarono Turn on throttling and windowing 2/12/00 aarono Concurrency issues, fix VOL usage and Refcount --*/ #ifndef _ARPSTRUC_H_ #define _ARPSTRUC_H_ #include <windows.h> #include <mmsystem.h> #include <dplay.h> #include "arpd.h" #include "bufpool.h" #include "bilink.h" #include "mydebug.h" //#include "threads.h" //#pragma warning( disable : 4090) #define VOL volatile // // Information about sent packets, tracked for operational statistics. // #define SENDSTAT_SIGN SIGNATURE('S','T','A','T') typedef struct PROTOCOL *PPROTOCOL; typedef struct _SENDSTAT { #ifdef SIGN UINT Signature; // Signature for SIGN #endif union { BILINK StatList; // linked on Send and later SESSION. struct _SENDSTAT *pNext; }; UINT messageid; UINT sequence; // sequence number UINT serial; // serial number UINT tSent; // tick time when this packet instance sent. UINT LocalBytesSent; // number of bytes sent on session at send time. UINT RemoteBytesReceived;// last remote byte report at send time. UINT tRemoteBytesReceived; // remote timestamp when received. UINT bResetBias; } SENDSTAT, *PSENDSTAT; #define SEND_SIGN SIGNATURE('S','E','N','D') typedef enum _TRANSMITSTATE { Start=0, // Never sent a packet. Sending=1, // Thread to send is running and xmitting. Throttled=2, // Waiting for send bandwidth. WaitingForAck=3, // Timer running, listening for ACKs. WaitingForId=4, // Waiting for a Send Id. ReadyToSend=5, // Have stuff to xmit, waiting for thread. TimedOut=6, // Retry timed out. Cancelled=7, // User cancelled send. UserTimeOut=8, // Didn't try to send until too late. Done=9 // Finished sending, singalled sender. } TRANSMITSTATE; struct _SESSION; // this Send is an ACK or NACK (OR'ed into SEND.dwFlags) #define ASEND_PROTOCOL 0x80000000 #pragma pack(push,1) typedef struct _SEND{ #ifdef SIGN UINT Signature; // Signature for SIGN #endif CRITICAL_SECTION SendLock; // Lock for Send Structure UINT RefCount; // @#$%! - not marked volatile since accessed only with Interlocked fns. VOL TRANSMITSTATE SendState; // State of this message's transmission. // Lists and Links... union { struct _SEND *pNext; // linking on free pool BILINK SendQ; // linking on session send queue }; BILINK m_GSendQ; // Global Priority Queue BILINK TimeoutList; // List of sends waiting for timeout (workaround MMTIMER cancel bug). struct _SESSION *pSession; // pointer to SESSIONion(gets a ref) PPROTOCOL pProtocol; // pointer to Protocol instance that created us. // Send Information DPID idFrom; DPID idTo; WORD wIdTo; // index in table WORD wIdFrom; // index in table UINT dwFlags; // Send Flags (include reliable) PBUFFER pMessage; // Buffer chain describing message. UINT MessageSize; // Total size of the message. UINT FrameDataLen; // Data area of each frame. UINT nFrames; // Number of frames for this message. UINT Priority; // Send Priority. // User cancel and complete info DWORD dwMsgID; // message id given to user, for use in cancel. LPVOID lpvUserMsgID; // user's own identifier for this send. BOOL bSendEx; // called through SendEx. // Vars for reliability BOOL fSendSmall; VOL BOOL fUpdate; // update to NS,NR NACKMask made by receive. UINT messageid; // Message ID number. UINT serial; // serial number. VOL UINT OpenWindow; // Number of sends we are trying to get outstanding VOL UINT NS; // Sequence Sent. VOL UINT NR; // Sequence ACKED. UINT SendSEQMSK; // Mask to use. VOL UINT NACKMask; // Bit pattern of NACKed frames. // These are the values at NR - updated by ACKs VOL UINT SendOffset; // Current offset we are sending. VOL PBUFFER pCurrentBuffer; // Current buffer being sent. VOL UINT CurrentBufferOffset; // Offset in the current buffer of next packet. // info to update link characteristics when ACKs come in. BILINK StatList; // Info for packets already sent. DWORD BytesThisSend; // number of bytes being sent in the current packet. // Operational Characteristics VOL UINT_PTR uRetryTimer; UINT TimerUnique; UINT RetryCount; // Number of times we retransmitted. UINT WindowSize; // Maximum Window Size. UINT SAKInterval; // interval (frames) at which a SAK is required. UINT SAKCountDown; // countdown to 0 from interval. UINT tLastACK; // Time we last got an ACK. UINT dwSendTime; // time we were called in send. UINT dwTimeOut; // timeout time. UINT PacketSize; // Size of packets to send. UINT FrameSize; // Size of Frames for this send. // Completion Vars HANDLE hEvent; // Event to wait on for internal send. UINT Status; // Send Completion Status. PASYNCSENDINFO pAsyncInfo; // ptr to Info for completing Async send(NULL=>internal send) ASYNCSENDINFO AsyncInfo; // actual info (copied at send call). DWORD tScheduled; // the time we scheduled the retry; DWORD tRetryScheduled; // expected retry timer run time. VOL BOOL bCleaningUp; // we are on the queue but don't take a ref pls. } SEND, *PSEND; #pragma pack(pop) #define RECEIVE_SIGN SIGNATURE('R','C','V','_') // Receive buffers are in reverse receive order. When they have all // been received, they are then put in proper order. typedef struct _RECEIVE { #ifdef SIGN UINT Signature; // Signature for SIGN #endif union { BILINK pReceiveQ; struct _RECEIVE * pNext; }; BILINK RcvBuffList; // List of receive buffers that make up the message. CRITICAL_SECTION ReceiveLock; struct _SESSION *pSession; VOL BOOL fBusy; // Someone is moving this receive. BOOL fReliable; // Whether this is a reliable receive. VOL BOOL fEOM; // Whether we received the EOM bit. UINT command; UINT messageid; VOL UINT MessageSize; VOL UINT iNR; // Absolute index of first receiving packet (reliable only). VOL UINT NR; // Last in sequence packet received. VOL UINT NS; // Highest packet number received. VOL UINT RCVMask; // bitmask of received packets (NR relative) PUCHAR pSPHeader; UCHAR SPHeader[0]; } RECEIVE, *PRECEIVE; #pragma pack(push,1) typedef struct _CMDINFO { WORD wIdTo; // index WORD wIdFrom; // index DPID idTo; // actual DPID DPID idFrom; // actual DPID UINT bytes; // read from ACK. DWORD tRemoteACK; // remote time remote ACKed/NACKed UINT tReceived; // timeGetTime() when received. UINT command; UINT IDMSK; USHORT SEQMSK; USHORT messageid; USHORT sequence; UCHAR serial; UCHAR flags; PVOID pSPHeader; // used to issue a reply. } CMDINFO, *PCMDINFO; #pragma pack(pop) #define SESSION_SIGN SIGNATURE('S','E','S','S') // since we now have a full byte for messagid and sequenne in the small headers, // we no longer have an advantage for full headers until we apply the new // bitmask package, then we must transit to large frame for windows > 127 messages. #define MAX_SMALL_CSENDS 29UL // Maximum Concurrent Sends when using small frame headers #define MAX_LARGE_CSENDS 29UL // Maxinum Concurrent Sends when using large frame headers (could make larger except for mask bits) #define MAX_SMALL_DG_CSENDS 16UL // Maximum concurrent datagrams when using small frame #define MAX_LARGE_DG_CSENDS 16UL // Maximum Concurrent datagrams when using large frames. #define MAX_SMALL_WINDOW 24UL #define MAX_LARGE_WINDOW 24UL typedef enum _SESSION_STATE { Open, // When created and Inited. Closing, // Don't accept new receives/sends. Closed // gone. } SESSION_STATE; #define SERVERPLAYER_INDEX 0xFFFE #define SESSION_THROTTLED 0x00000001 // session throttle is on. #define SESSION_UNTHROTTLED 0x00000002 // unthrottle is deffered to avoid confusing GetMessageQueue. ///////////////////////////////////////////////////////////////// // // Transition Matrix for Throttle Adjust // // Initial State Event: // No Drops 1 Drop >1 Drop // // Start + Start - Meta -- Start // // Meta + Meta - Stable -- Meta // // Stable + Stable - Stable -- Meta // // // Engagement of Backlog Throttle goes to MetaStable State. /////////////////////////////////////////////////////////////////// #define METASTABLE_GROWTH_RATE 4 #define METASTABLE_ADJUST_SMALL_ERR 12 #define METASTABLE_ADJUST_LARGE_ERR 25 #define START_GROWTH_RATE 50 #define START_ADJUST_SMALL_ERR 25 #define START_ADJUST_LARGE_ERR 50 #define STABLE_GROWTH_RATE 2 #define STABLE_ADJUST_SMALL_ERR 12 #define STABLE_ADJUST_LARGE_ERR 25 typedef enum _ThrottleAdjustState { Begin=0, // At start, double until drop or backlog MetaStable=1, // Meta stable, large deltas for drops Stable=2 // Stable, small deltas for drops } eThrottleAdjust; typedef struct _SESSION { PPROTOCOL pProtocol; // back ptr to object. #ifdef SIGN UINT Signature; // Signature for SIGN #endif // Identification CRITICAL_SECTION SessionLock; // Lock for the SESSIONion. UINT RefCount; // RefCount for the SESSION. - not vol, only accessed with Interlocked VOL SESSION_STATE eState; HANDLE hClosingEvent; // Delete waits on this during close. DPID dpid; // The remote direct play id for this session. UINT iSession; // index in the session table UINT iSysPlayer; // index in session table of sys player. // NOTE: if iSysPlayer != iSession, then rest of struct not req'd. BILINK SendQ; // Priority order sendQ; BOOL fFastLink; // set True when link > 50K/sec, set False when less than 10K/sec. BOOL fSendSmall; // Whether we are sending small reliable frames. BOOL fSendSmallDG; // Whether we are sending small datagram frames. BOOL fReceiveSmall; BOOL fReceiveSmallDG; UINT MaxPacketSize; // Largest packet allowed on the media. // Operating parameters -- Send // Common UINT MaxCSends; // maximum number of concurrent sends UINT MaxCDGSends; // maximum number of concurrent datagram sends // Reliable VOL UINT FirstMsg; // First message number being transmitted VOL UINT LastMsg; // Last message number being transmitted VOL UINT OutMsgMask; // relative to FirstMsg, unacked messages UINT nWaitingForMessageid; // number of sends on queue that can't start sending because they don't have an id. // DataGram VOL UINT DGFirstMsg; // First message number being transmitted VOL UINT DGLastMsg; // Last message number being transmitted VOL UINT DGOutMsgMask; // relative to FirstMsg, not-fully sent messages. UINT nWaitingForDGMessageid; // number of sends on queue that can't start sending because they don't have an id. // Send stats are tracked seperately since sends may // no longer be around when completions come in. //BILINK OldStatList; // Operating parameters -- Receive // DataGram Receive. BILINK pDGReceiveQ; // queue of ongoing datagram receives // Reliable Receive. BILINK pRlyReceiveQ; // queue of ongoing reliable receives BILINK pRlyWaitingQ; // Queue of out of order reliable receives waiting. // only used when PROTOCOL_NO_ORDER not set. VOL UINT FirstRlyReceive; VOL UINT LastRlyReceive; VOL UINT InMsgMask; // mask of fully received receives, relative to FirstRlyReceive // Operational characteristics - MUST BE DWORD ALIGNED!!! - this is because we read and write them // without a lock and assume the reads and writes are atomic (not in combination) UINT WindowSize; // Max outstanding packets on a send - reliable UINT DGWindowSize; // Max outstanding packets on a send - datagram UINT MaxRetry; // Usual max retries before dropping. UINT MinDropTime; // Min time to retry before dropping. UINT MaxDropTime; // After this time always drop. VOL UINT LocalBytesReceived; // Total Data Bytes received (including retries). VOL UINT RemoteBytesReceived; // Last value from remote. VOL DWORD tRemoteBytesReceived; // Remote time last value received. UINT LongestLatency; // longest observed latency (msec) UINT ShortestLatency; // shortest observed latency(msec) UINT LastLatency; // last observed latency (msec) UINT FpAverageLatency; // average latency (msec 24.8) (128 samples) UINT FpLocalAverageLatency; // Local average latency (msec 24.8) (16 samples) UINT FpAvgDeviation; // average deviation of latency. (msec 24.8) (128 samples) UINT FpLocalAvgDeviation; // average deviation of latency. (msec 24.8) (16 samples) UINT Bandwidth; // latest observed bandwidth (bps) UINT HighestBandwidth; // highest observed bandwidth (bps) // we will use changes in the remote ACK delta to isolate latency in the send direction. UINT RemAvgACKDelta; // average clock delta between our send time (local time) and remote ACK time (remote time). UINT RemAvgACKDeltaResidue; UINT RemAvgACKBias; // This value is used to pull the clock delta into a safe range (not near 0 or -1) // that won't risk hitting the wraparound when doing calculations // Throttle statistics DWORD dwFlags; // Session Flags - currently just "throttle on/off"(MUST STAY THIS WAY) UINT SendRateThrottle; // current rate (bps) at which we are throttling. DWORD bhitThrottle; // we hit a throttle DWORD tNextSend; // when we are allowed to send again. DWORD tNextSendResidue; // residual from calculating next send time DWORD_PTR uUnThrottle; DWORD UnThrottleUnique; DWORD FpAvgUnThrottleTime; // (24.8) how late Unthrottle usually called. (throttle when send is this far ahead) // last 16 samples, start at 5 ms. DWORD tLastSAK; // last time we asked for an ACK CRITICAL_SECTION SessionStatLock; // [locks this section ------------------------------------------- ] BILINK DGStatList; // [Send Statistics for Datagrams (for reliable they are on Sends) ] DWORD BytesSent; // [Total Bytes Sent to this target ] DWORD BytesLost; // [Total Bytes Lost on the link. ] DWORD bResetBias; // [Counts down to reset latency bias ] // [---------------------------------------------------------------] eThrottleAdjust ThrottleState; // ZEROINIT puts in Start DWORD GrowCount; // number of times we grew in this state DWORD ShrinkCount; // number of times we shrank in this state DWORD tLastThrottleAdjust; // remember when we last throttled to avoid overthrottling. } SESSION, *PSESSION; #endif
38.383408
133
0.609615
[ "object" ]
f3e2d667a60854d463e714065c6ba8b7ca46e329
8,300
h
C
lib/EMBOSS-6.6.0/ajax/core/ajcod.h
alegione/CodonShuffle
bd6674b2eb21ee144a39d6d1e9b7264aba887240
[ "MIT" ]
5
2016-11-11T21:57:49.000Z
2021-07-27T14:13:31.000Z
lib/EMBOSS-6.6.0/ajax/core/ajcod.h
frantallukas10/CodonShuffle
4c408e1a8617f2a52dcb0329bba9617e1be17313
[ "MIT" ]
4
2016-05-15T07:56:25.000Z
2020-05-20T05:21:48.000Z
lib/EMBOSS-6.6.0/ajax/core/ajcod.h
frantallukas10/CodonShuffle
4c408e1a8617f2a52dcb0329bba9617e1be17313
[ "MIT" ]
10
2015-08-19T20:37:46.000Z
2020-04-07T06:49:23.000Z
/* @include ajcod ************************************************************* ** ** AJAX codon functions ** ** @author Copyright (C) 1999 Alan Bleasby ** @version $Revision: 1.27 $ ** @modified Aug 07 ajb First version ** @modified $Date: 2011/10/18 14:23:40 $ by $Author: rice $ ** @@ ** ** 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.1 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., 51 Franklin Street, Fifth Floor, Boston, ** MA 02110-1301, USA. ** ******************************************************************************/ #ifndef AJCOD_H #define AJCOD_H /* ========================================================================= */ /* ============================= include files ============================= */ /* ========================================================================= */ #include "ajdefine.h" #include "ajfile.h" AJ_BEGIN_DECLS /* ========================================================================= */ /* =============================== constants =============================== */ /* ========================================================================= */ /* ========================================================================= */ /* ============================== public data ============================== */ /* ========================================================================= */ /* @data AjPCod *************************************************************** ** ** Ajax codon object. ** ** Holds arrays describing codon usage ** The length is known and held internally. ** ** AjPCod is implemented as a pointer to a C data structure. ** ** @alias AjSCod ** @alias AjOCod ** ** @attr Name [AjPStr] Name of codon file ** @attr Species [AjPStr] Species ** @attr Division [AjPStr] Division (gbbct etc.) ** @attr Release [AjPStr] Database name and release ** @attr Desc [AjPStr] Description ** @attr CdsCount [ajint] Number of coding sequences used ** @attr CodonCount [ajint] Number of individual codons used ** @attr aa [ajint*] Amino acid represented by codon ** @attr num [ajint*] Number of codons ** @attr tcount [double*] Codons per thousand ** @attr fraction [double*] Fraction of amino acids of this type ** @attr back [ajint*] Index of favoured amino acid for back translation ** @attr GeneticCode [ajint] Genetic code NCBI number to match ** amino acids to codons. ** @attr Padding [char[4]] Padding to alignment boundary ** @@ ******************************************************************************/ typedef struct AjSCod { AjPStr Name; AjPStr Species; AjPStr Division; AjPStr Release; AjPStr Desc; ajint CdsCount; ajint CodonCount; ajint *aa; ajint *num; double *tcount; double *fraction; ajint *back; ajint GeneticCode; char Padding[4]; } AjOCod; #define AjPCod AjOCod* /* ========================================================================= */ /* =========================== public functions ============================ */ /* ========================================================================= */ /* ** Prototype definitions */ void ajCodSetCodenum(AjPCod thys, ajint geneticcode); void ajCodSetDescC(AjPCod thys, const char* desc); void ajCodSetDescS(AjPCod thys, const AjPStr desc); void ajCodSetDivisionC(AjPCod thys, const char* division); void ajCodSetDivisionS(AjPCod thys, const AjPStr division); void ajCodSetNameC(AjPCod thys, const char* name); void ajCodSetNameS(AjPCod thys, const AjPStr name); void ajCodSetNumcds(AjPCod thys, ajint numcds); void ajCodSetNumcodons(AjPCod thys, ajint numcodon); void ajCodSetReleaseC(AjPCod thys, const char* release); void ajCodSetReleaseS(AjPCod thys, const AjPStr release); void ajCodSetSpeciesC(AjPCod thys, const char* species); void ajCodSetSpeciesS(AjPCod thys, const AjPStr species); void ajCodBacktranslate(AjPStr *b, const AjPStr a, const AjPCod thys); void ajCodBacktranslateAmbig(AjPStr *b, const AjPStr a, const AjPCod thys); ajint ajCodBase(ajint c); double ajCodCalcCaiCod(const AjPCod thys); double ajCodCalcCaiSeq(const AjPCod cod, const AjPStr str); void ajCodCalcGribskov(AjPCod thys, const AjPStr s); double ajCodCalcNc(const AjPCod thys); void ajCodCalcUsage(AjPCod thys, ajint c); void ajCodClear(AjPCod thys); void ajCodClearData(AjPCod thys); void ajCodComp(ajint *NA, ajint *NC, ajint *NG, ajint *NT, const char *str); void ajCodSetTripletsS(AjPCod thys, const AjPStr s, ajint *c); void ajCodDel(AjPCod *thys); ajint ajCodGetCode(const AjPCod thys); const AjPStr ajCodGetDesc(const AjPCod thys); const char* ajCodGetDescC(const AjPCod thys); const AjPStr ajCodGetDivision(const AjPCod thys); const char* ajCodGetDivisionC(const AjPCod thys); void ajCodExit(void); void ajCodGetCodonlist(const AjPCod cod, AjPList list); const AjPStr ajCodGetName(const AjPCod thys); const char* ajCodGetNameC(const AjPCod thys); ajint ajCodGetNumcds(const AjPCod thys); ajint ajCodGetNumcodon(const AjPCod thys); const AjPStr ajCodGetRelease(const AjPCod thys); const char* ajCodGetReleaseC(const AjPCod thys); const AjPStr ajCodGetSpecies(const AjPCod thys); const char* ajCodGetSpeciesC(const AjPCod thys); ajint ajCodIndex(const AjPStr s); ajint ajCodIndexC(const char *codon); AjPCod ajCodNew(void); AjPCod ajCodNewCodenum(ajint code); AjPCod ajCodNewCod(const AjPCod thys); AjBool ajCodRead(AjPCod thys, const AjPStr fn, const AjPStr format); void ajCodSetBacktranslate(AjPCod thys); char* ajCodTriplet(ajint idx); void ajCodWrite(AjPCod thys, AjPFile outf); void ajCodWriteOut(const AjPCod thys, AjPOutfile outf); AjBool ajCodoutformatFind(const AjPStr name, ajint *iformat); void ajCodPrintFormat(AjPFile outf, AjBool full); /* ** End of prototype definitions */ #ifdef AJ_COMPILE_DEPRECATED_BOOK #endif /* AJ_COMPILE_DEPRECATED_BOOK */ #ifdef AJ_COMPILE_DEPRECATED __deprecated ajint ajCodOutFormat(const AjPStr name); __deprecated AjPCod ajCodDup(const AjPCod thys); __deprecated AjPCod ajCodNewCode(ajint code); __deprecated void ajCodAssCode(AjPCod thys, ajint geneticcode); __deprecated void ajCodAssDesc(AjPCod thys, const AjPStr desc); __deprecated void ajCodAssDescC(AjPCod thys, const char* desc); __deprecated void ajCodAssDivision(AjPCod thys, const AjPStr division); __deprecated void ajCodAssDivisionC(AjPCod thys, const char* division); __deprecated void ajCodAssNumcds(AjPCod thys, ajint numcds); __deprecated void ajCodAssNumcodon(AjPCod thys, ajint numcodon); __deprecated void ajCodAssRelease(AjPCod thys, const AjPStr release); __deprecated void ajCodAssReleaseC(AjPCod thys, const char* release); __deprecated void ajCodAssSpecies(AjPCod thys, const AjPStr species); __deprecated void ajCodAssSpeciesC(AjPCod thys, const char* species); __deprecated void ajCodAssName(AjPCod thys, const AjPStr name); __deprecated void ajCodAssNameC(AjPCod thys, const char* name); __deprecated void ajCodCountTriplets(AjPCod thys, const AjPStr s, ajint *c); __deprecated double ajCodCalcCai(const AjPCod cod, const AjPStr str); __deprecated void ajCodCalculateUsage(AjPCod thys, ajint c); #endif /* AJ_COMPILE_DEPRECATED */ AJ_END_DECLS #endif /* !AJCOD_H */
38.073394
79
0.603976
[ "object" ]
f3e3607bdc9fc245c97c4ade1b3788e65460643d
14,488
h
C
src/GUI-qt/plugins/AdvancedColorMaps/ColorMapExtended.h
OpenCMISS-Dependencies/cube
bb425e6f75ee5dbdf665fa94b241b48deee11505
[ "Cube" ]
null
null
null
src/GUI-qt/plugins/AdvancedColorMaps/ColorMapExtended.h
OpenCMISS-Dependencies/cube
bb425e6f75ee5dbdf665fa94b241b48deee11505
[ "Cube" ]
null
null
null
src/GUI-qt/plugins/AdvancedColorMaps/ColorMapExtended.h
OpenCMISS-Dependencies/cube
bb425e6f75ee5dbdf665fa94b241b48deee11505
[ "Cube" ]
2
2016-09-19T00:16:05.000Z
2021-03-29T22:06:45.000Z
/**************************************************************************** ** CUBE http://www.scalasca.org/ ** ***************************************************************************** ** Copyright (c) 1998-2016 ** ** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre ** ** ** ** This software may be modified and distributed under the terms of ** ** a BSD-style license. See the COPYING file in the package base ** ** directory for details. ** ****************************************************************************/ #ifndef SRC_GUI_QT_PLUGINS_ADVANCEDCOLORMAPS_COLORMAPEXTENDED_H_ #define SRC_GUI_QT_PLUGINS_ADVANCEDCOLORMAPS_COLORMAPEXTENDED_H_ #include <string> #include <utility> #include <QWidget> #include <QColor> #include <QPainter> #include <QStyle> #include <QStyleOption> #include <QGroupBox> #include <QCheckBox> #include <QFormLayout> #include <QStackedLayout> #include <QComboBox> #include <QSettings> #include "ColorMap.h" #include "ColorMapPlot.h" using std::pair; using std::string; class ColorMapWidget; /** * @class ColorMapExtended * @author Marcin Copik (m.copik@fz-juelich.de) * @date January 2015 * @brief Extended parent class for color maps. * Implements basic processing, common for all color maps (special cases, filtering etc). */ class ColorMapExtended : public ColorMap { Q_OBJECT public: ColorMapExtended(); virtual ~ColorMapExtended(); /** * Invert color map - draw from 1 to 0, instead of 0 to 1. */ void invertColorMap(); /** * @return true iff the map is inverted */ bool invertedColorMap(); /** * Default color for values out of range. */ static const QColor DEFAULT_COLOR_VALUES_OUT_OF_RANGE; /** * @return color used currently by all maps for values out of range */ static QColor getColorForValuesOutOfRange(); /** * @param new color for values out of range */ static void setColorForValuesOutOfRange( const QColor& ); /** * Enable/disable filtering at limit pos, providing boolean value. * @param pos * @param val */ static void enableFiltering( ColorMapPlot::MarkersPositions::FilterPosition pos, bool val ); /** * @param pos * @return true when filtering is enabled for selected position */ static bool isFilteringEnabled( ColorMapPlot::MarkersPositions::FilterPosition pos ); /** * @return description of color map, displayed to user in GUI */ virtual const QString& getColorMapDescription() const = 0; /** * @return instance of widget used to configure this color map */ virtual ColorMapWidget* getConfigurationPanel() = 0; void setMarkersPositions( ColorMapPlot::MarkersPositions* pos ); /** * Apply filtering borders to current data min/max. * @param min * @param max * @return pair <min, max> */ pair<double, double> adjustFilteringBorders( double min, double max ) const; /** * Save user-modified maps. * @param settings */ virtual void saveGlobalSettings( QSettings& settings ); /** * Load user-modified maps. * @param settings */ virtual void loadGlobalSettings( QSettings& settings ); /** * @class CIELABColor * Implementation of CIELAB color space. */ class CIELABColor { /** * L* value in color space. */ double lightness; /** * a* value in color space. */ double a; /** * b* value in color space. */ double b; /** * Used in the process of RGB -> CIELAB (and vice versa) conversion. * * Use whitepoint from Illuminant D65. * http://en.wikipedia.org/wiki/Illuminant_D65 */ static const double WHITEPOINT_X; static const double WHITEPOINT_Y; static const double WHITEPOINT_Z; static const double RGBXYZ_CONVERSION_MATRIX[ 3 ][ 3 ]; /** * CIELAB conversion function used in conversion RGB->CIELAB */ static double cielabConversionFunction( const double& x ); /** * CIELAB inverse conversion function used in conversion CIELAB->RGB */ static double cielabConversionFunctionInverse( const double& x ); public: /** * Create color in CIELAB space using explicit values. * @param _lightness * @param _a * @param _b */ CIELABColor( double _lightness, double _a, double _b ); /** * Copy constructor. * @param c */ CIELABColor( const CIELABColor& c ); /** * @param RGB color to convert * @return representation of RGB color in CIELAB space */ static CIELABColor fromRGB( const QColor& ); /** * @return representation of current color in RGB */ QColor toRGB() const; /** * @return textual representation of current color */ string toString() const; /** * @param l new value for lightness */ void setLightness( const double& l ); /** * @return L* value of color */ double getLightness() const; /** * @return a* value of color */ double getAStar() const; /** * @return b* value of color */ double getBStar() const; }; /** * @class MSHColor * Implementation of MSH color space - polar version of CIELAB. */ class MSHColor { /** * M value - vector length */ double m; /** * S value - trigonometric function of angle */ double s; /** * S value - trigonometric function of angle */ double h; /** * Function used in MSH color space * @param colorSat * @param Munsat * @return */ static double adjustHue( const MSHColor& colorSat, double Munsat ); static pair<double, double> adjustHues( const MSHColor& start, const MSHColor& end ); public: /** * Create color in MSH space using explicit values. * @param _m * @param _s * @param _h */ MSHColor( double _m, double _s, double _h ); /** * Copy constructor. * @param c */ MSHColor( const MSHColor& c ); /** * Default constructor - create white. */ MSHColor(); /** * @param RGB color to convert * @return representation of RGB color in CIELAB space */ static MSHColor fromRGB( const QColor& ); /** * @return representation of current color in CIELAB space */ CIELABColor toCIELAB() const; /** * @return representation of current color in RGB */ QColor toRGB() const; /** * @return textual representation of current color */ string toString() const; /** * Interpolate linearly between two colors. * @param start begin color * @param end end color * @param interpolation_place value between 0.0 and 1.0 * @return interpolation of color at given position */ static MSHColor interpolate( const MSHColor& start, const MSHColor& end, double interpolation_place ); /** * Interpolate exponentially between two colors. * @param start begin color * @param end end color * @param interpolation_place value between 0.0 and 1.0 * @return interpolation of color at given position */ static MSHColor interpolateExp( const MSHColor& start, const MSHColor& end, double interpolation_place ); /** * Interpolate linearly between two colors with additional "speed" parameter. * @param start begin color * @param end end color * @param interpolation_place value between 0.0 and 1.0 * @param marker_position position of middle marker, specifying interpolation "speed" * @return interpolation of color at given position */ static MSHColor interpolate( const MSHColor& start, const MSHColor& end, double interpolation_place, double marker_position ); /** * Interpolate exponentially between two colors. * @param start begin color * @param end end color * @param interpolation_place value between 0.0 and 1.0 * @param marker_position position of middle marker, specifying interpolation "speed" * @return interpolated color */ static MSHColor interpolateExp( const MSHColor& start, const MSHColor& end, double interpolation_place, double marker_position ); /** * @return M value of color */ double getM() const; /** * @return s value of color */ double getS() const; /** * @return h value of color */ double getH() const; /** * @param * @return true iff both colors are the same (or at least very similar - float comparison) */ bool compare( const MSHColor& ) const; /** * White color in MSH color space. */ static const MSHColor WHITE; }; protected: /** * Common preprocessing for getColor method. Arguments are the same as in getColor. * @param value * @param minValue * @param maxValue * @param whiteForZero * @return pair of unsigned integer and color: * integer: 0 -> generate color as usual * 1 -> red field of second element contains position * 2 -> second element is generated color */ pair<unsigned short, QColor> getColorBasicProcessing( double value, double minValue, double maxValue, bool whiteForZero ) const; /** * Color used when the value is out of range. */ static QColor colorValuesOutOfRange; /** * Enabled/disabled filtering for min/max. */ // static bool enableFilters[2]; /** * Currently used plot position method; */ ColorMapPlot::MarkersPositions* markersPositions; /** * If true, then invert color map values. */ bool invertedCM; /** * GUI widget. */ ColorMapWidget* widget; }; /** * @class ColorMapWidget * @author Marcin Copik (m.copik@fz-juelich.de) * @date January 2015 * @brief Abstract parent class for configuration widgets used by color maps. */ class ColorMapWidget : public QWidget { Q_OBJECT public: /** * Constructor; initialize plot to NULL. */ ColorMapWidget( ColorMapExtended& ); /** * Delete plot. */ virtual ~ColorMapWidget() = 0; /** * @return reference to parent color map, automatically casted to proper subclass */ virtual ColorMapExtended& getParent() const = 0; /** * Repaint plot and other updates of GUI. */ virtual void colorMapUpdated(); /** * Notifies widget about parent update - used only when settings are loaded. */ virtual void parentUpdated() { }; /** * Overriden from QWidget */ virtual bool hasHeightForWidth() const; /** * Informs internal structure of subclasses that the buttons 'Apply' or 'Ok' have been pressed, * which means that temporal changes introduced in color map are now considered as stable. */ virtual void applyChanges(); /** * Informs internal structure of subclasses that the button 'Cancel' or 'Ok' has been pressed, * which means that temporal changes introduced in color map should be replaced by previous values. */ virtual void revertChanges(); protected: ColorMapExtended& parent; ColorMapPlot plotPercentage; ColorMapPlot* currentPlot; /** * Status of CM inversion between any changes. */ bool cacheInvertedParent; /** * Status of color for values out of range between any changes. */ static QColor cachedColorOutOfRangesParent; /** * Add plot to GUI. * @param parent layout for plot */ void addPlotToGUI( QLayout& ); /** * Enable/disable color change at plots. * @param col * @param val */ void enablePlotColorChange( bool val ); /** * Enable/disable drawing and using of middle mark in plot. * @param val */ void enablePlotMiddleMark( bool val ); protected slots: virtual void processColorChanged( ColorMapPlot::Color, const QColor& ); /** * Currently not used void filteringValueStateChanged(int); void plotTypeChanged(int type); */ private: /** * Currently not used ColorMapPlot plot; QCheckBox filterCheck[2]; QFormLayout filterBorders; QComboBox plotChoose; QWidget filterWidget; static const QString FILTER_CHECKBOX_NAMES[2]; */ QStackedLayout plotLayout; QWidget plotWidget; }; #endif /* SRC_GUI_QT_PLUGINS_ADVANCEDCOLORMAPS_COLORMAPEXTENDED_H_ */
25.065744
103
0.54307
[ "vector" ]
1391dbc884eb3adcb4c1088a0a775a0e18c82f21
649
h
C
MapView.h
archibate/Rocketist
28f70e3714fff31b3dbe8d559cbdfd3457fd2c40
[ "MIT" ]
null
null
null
MapView.h
archibate/Rocketist
28f70e3714fff31b3dbe8d559cbdfd3457fd2c40
[ "MIT" ]
null
null
null
MapView.h
archibate/Rocketist
28f70e3714fff31b3dbe8d559cbdfd3457fd2c40
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "GLView.h" #include "FutureTrackRender.h" #include "BasicVessel.h" class OrbiterM; class Orbit_APZ; class MapView : public GLView { private: const Orbit_APZ &orbitAPZ; const BasicVessel &orbiter; const std::vector<OrbiterM> &orbitees; public: FutureTrackRender futureTrack; MapView(const Orbit_APZ *orbitAPZ, const BasicVessel *orbiter, const std::vector<OrbiterM> *orbitees) : orbitAPZ(*orbitAPZ) , orbiter(*orbiter) , orbitees(*orbitees) , futureTrack(static_cast<const Orbiter *>(orbiter), orbitees) {} public: virtual void onSetup() override; virtual void onRender() override; };
20.28125
64
0.745763
[ "vector" ]
1395580a68a04d7c6f2be244b639b13041498d31
539
h
C
include/IRPrinter.h
BrandonKi/ARCVM
f60f95f31f54791c093f35c5f395ad49524951d7
[ "MIT" ]
2
2021-10-03T20:50:57.000Z
2022-01-29T03:23:18.000Z
include/IRPrinter.h
BrandonKi/ARCVM
f60f95f31f54791c093f35c5f395ad49524951d7
[ "MIT" ]
null
null
null
include/IRPrinter.h
BrandonKi/ARCVM
f60f95f31f54791c093f35c5f395ad49524951d7
[ "MIT" ]
null
null
null
#ifndef ARCVM_IRPRINTER_H #define ARCVM_IRPRINTER_H #include "Common.h" #include <iostream> namespace arcvm { namespace IRPrinter { void print(Module*, i32 indent = 0); void print(Function*, i32 = 0, i32 indent = 0); void print(std::vector<Type>&, i32&, i32 indent = 0); void print(std::vector<Attribute>&, i32 indent = 0); void print(Block*, i32&, i32 indent = 0); void print(BasicBlock*, i32&, i32 indent = 0); void print(Entry*, i32&, i32 indent = 0); void print(Value* value, i32 indent = 0); } // namespace IRPrinter }; #endif
21.56
53
0.692022
[ "vector" ]
139d806adc16cd7f8d5b71d84acbf85e46d09435
3,141
h
C
device/fido/u2f_register.h
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
device/fido/u2f_register.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
device/fido/u2f_register.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef DEVICE_FIDO_U2F_REGISTER_H_ #define DEVICE_FIDO_U2F_REGISTER_H_ #include <memory> #include <set> #include <string> #include <vector> #include "base/component_export.h" #include "base/containers/flat_set.h" #include "base/macros.h" #include "base/optional.h" #include "device/fido/authenticator_make_credential_response.h" #include "device/fido/fido_constants.h" #include "device/fido/fido_transport_protocol.h" #include "device/fido/u2f_request.h" namespace service_manager { class Connector; }; namespace device { class COMPONENT_EXPORT(DEVICE_FIDO) U2fRegister : public U2fRequest { public: using RegisterResponseCallback = base::OnceCallback<void( FidoReturnCode status_code, base::Optional<AuthenticatorMakeCredentialResponse> response_data)>; static std::unique_ptr<U2fRequest> TryRegistration( service_manager::Connector* connector, const base::flat_set<FidoTransportProtocol>& transports, std::vector<std::vector<uint8_t>> registered_keys, std::vector<uint8_t> challenge_digest, std::vector<uint8_t> application_parameter, bool individual_attestation_ok, RegisterResponseCallback completion_callback); U2fRegister(service_manager::Connector* connector, const base::flat_set<FidoTransportProtocol>& transports, std::vector<std::vector<uint8_t>> registered_keys, std::vector<uint8_t> challenge_digest, std::vector<uint8_t> application_parameter, bool individual_attestation_ok, RegisterResponseCallback completion_callback); ~U2fRegister() override; private: void TryDevice() override; void OnTryDevice(bool is_duplicate_registration, base::Optional<std::vector<uint8_t>> response); // Callback function called when non-empty exclude list was provided. This // function iterates through all key handles in |registered_keys_| for all // devices and checks for already registered keys. void OnTryCheckRegistration( std::vector<std::vector<uint8_t>>::const_iterator it, base::Optional<std::vector<uint8_t>> response); // Function handling registration flow after all devices were checked for // already registered keys. void CompleteNewDeviceRegistration(); // Returns whether |current_device_| has been checked for duplicate // registration for all key handles provided in |registered_keys_|. bool CheckedForDuplicateRegistration(); // Indicates whether the token should be signaled that using an individual // attestation certificate is acceptable. const bool individual_attestation_ok_; RegisterResponseCallback completion_callback_; // List of authenticators that did not create any of the key handles in the // exclude list. std::set<std::string> checked_device_id_list_; base::WeakPtrFactory<U2fRegister> weak_factory_; DISALLOW_COPY_AND_ASSIGN(U2fRegister); }; } // namespace device #endif // DEVICE_FIDO_U2F_REGISTER_H_
36.523256
77
0.75772
[ "vector" ]
13b90b01b413821b30c7cd7becb71bb05599bd5f
6,243
h
C
Utilities/VisItBridge/avt/Database/Ghost/avtDomainBoundaries.h
aashish24/paraview-climate-3.11.1
c8ea429f56c10059dfa4450238b8f5bac3208d3a
[ "BSD-3-Clause" ]
1
2016-09-08T14:47:11.000Z
2016-09-08T14:47:11.000Z
Utilities/VisItBridge/avt/Database/Ghost/avtDomainBoundaries.h
aashish24/paraview-climate-3.11.1
c8ea429f56c10059dfa4450238b8f5bac3208d3a
[ "BSD-3-Clause" ]
null
null
null
Utilities/VisItBridge/avt/Database/Ghost/avtDomainBoundaries.h
aashish24/paraview-climate-3.11.1
c8ea429f56c10059dfa4450238b8f5bac3208d3a
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************** * * Copyright (c) 2000 - 2010, Lawrence Livermore National Security, LLC * Produced at the Lawrence Livermore National Laboratory * LLNL-CODE-400124 * All rights reserved. * * This file is part of VisIt. For details, see https://visit.llnl.gov/. The * full copyright notice is contained in the file COPYRIGHT located at the root * of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html. * * 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 disclaimer below. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the disclaimer (as noted below) in the * documentation and/or other materials provided with the distribution. * - Neither the name of the LLNS/LLNL nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, * LLC, THE U.S. DEPARTMENT OF ENERGY 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. * *****************************************************************************/ // ************************************************************************* // // avtDomainBoundaries.h // // ************************************************************************* // #ifndef AVT_DOMAIN_BOUNDARIES_H #define AVT_DOMAIN_BOUNDARIES_H #include <database_exports.h> #include <avtGhostData.h> #include <vector> using std::vector; class vtkDataSet; class vtkDataArray; class avtMixedVariable; class avtMaterial; // **************************************************************************** // Class: avtDomainBoundaries // // Purpose: // Encapsulate domain boundary information. // // Programmer: Jeremy Meredith // Creation: October 25, 2001 // // Modifications: // Jeremy Meredith, Thu Dec 13 11:47:06 PST 2001 // Added mats to the exchange mixvars call. // // Kathleen Bonnell, Fri Feb 8 11:03:49 PST 2002 // vtkScalars and vtkVectors have been deprecated in VTK 4.0, // use vtkDataArray instead. // // Kathleen Bonnell, Mon May 20 13:40:17 PDT 2002 // Made ExhangeVector into two methods to handle different underlying // data types (int, float). // // Hank Childs, Sat Aug 14 06:41:00 PDT 2004 // Added ghost nodes. // // Hank Childs, Sun Feb 27 12:00:12 PST 2005 // Added pure virtual methods RequiresCommunication. Added "allDomains" // argument to CreateGhostNodes. // // Hank Childs, Mon Jun 27 16:28:22 PDT 2005 // Added virtual method ResetCachedMembers. // // Hank Childs, Thu Jan 26 10:04:34 PST 2006 // Add virtual method "CreatesRobustGhostNodes". // // Hank Childs, Thu Feb 14 17:12:38 PST 2008 // Add virtual method "CanOnlyCreateGhostNodes". // // **************************************************************************** class DATABASE_API avtDomainBoundaries { public: avtDomainBoundaries(); virtual ~avtDomainBoundaries(); virtual vector<vtkDataSet*> ExchangeMesh(vector<int> domainNum, vector<vtkDataSet*> meshes) =0; virtual vector<vtkDataArray*> ExchangeScalar(vector<int> domainNum, bool isPointData, vector<vtkDataArray*> scalars) =0; virtual vector<vtkDataArray*> ExchangeFloatVector(vector<int> domainNum, bool isPointData, vector<vtkDataArray*> vectors) =0; virtual vector<vtkDataArray*> ExchangeIntVector(vector<int> domainNum, bool isPointData, vector<vtkDataArray*> vectors) =0; virtual vector<avtMaterial*> ExchangeMaterial(vector<int> domainNum, vector<avtMaterial*> mats) =0; virtual vector<avtMixedVariable*> ExchangeMixVar(vector<int> domainNum, const vector<avtMaterial*> mats, vector<avtMixedVariable*> mixvars) =0; virtual void CreateGhostNodes(vector<int> domainNum, vector<vtkDataSet*> meshes, vector<int> &) =0; virtual bool CreatesRobustGhostNodes(void) { return true; }; virtual bool CanOnlyCreateGhostNodes(void) { return false; }; virtual bool RequiresCommunication(avtGhostDataType) = 0; virtual bool ConfirmMesh(vector<int> domainNum, vector<vtkDataSet*> meshes) =0; virtual void ResetCachedMembers(void) {;}; }; #endif
45.23913
82
0.559186
[ "vector" ]
13c4f8e6d5d060ee4124995c70ef495d042e21ca
1,544
h
C
include/graphics/format/oisb.h
Nielsbishere/oish_gen
16ad8b8b35120793ad7550de0b094e4972c0a494
[ "MIT" ]
null
null
null
include/graphics/format/oisb.h
Nielsbishere/oish_gen
16ad8b8b35120793ad7550de0b094e4972c0a494
[ "MIT" ]
1
2018-05-27T10:04:22.000Z
2018-05-27T10:04:22.000Z
include/graphics/format/oisb.h
Nielsbishere/oish_gen
16ad8b8b35120793ad7550de0b094e4972c0a494
[ "MIT" ]
null
null
null
#pragma once #include <template/enum.h> namespace oi { struct SLFile; namespace gc { class Graphics; struct ShaderBufferInfo; DEnum(SBHeaderVersion, u8, Undefined = 0, v0_1 = 1 ); enum class SBHeaderFlag : u8 { IS_WRITE = 0x1U, IS_STORAGE = 0x2U, IS_ALLOCATED = 0x4U }; struct SBHeader { char header[4]; u8 version; //SBHeaderVersion_s u8 flags; //SBHeaderFlag; & 0x3 = Buffer type u16 padding = 0; u16 structs; u16 vars; u32 bufferSize; }; struct SBStruct { u16 nameIndex; u16 parent; u32 offset; u32 arraySize; u32 length; SBStruct(u16 nameIndex, u16 parent, u32 offset, u32 arraySize, u32 length); SBStruct(); }; struct SBVar { u16 nameIndex; u16 parent; u32 offset; u32 arraySize; u8 type; //TextureFormat u8 padding[3]; SBVar(u16 nameIndex, u16 parent, u32 offset, u32 arraySize, u8 type); SBVar(); }; struct SBFile { SBHeader header; std::vector<SBStruct> structs; std::vector<SBVar> vars; u32 size; SBFile(std::vector<SBStruct> structs, std::vector<SBVar> vars); SBFile(); }; struct oiSB { static bool read(String path, SBFile &file); static bool read(Buffer data, SBFile &file); static SBFile convert(ShaderBufferInfo info, SLFile *names = nullptr); static ShaderBufferInfo convert(Graphics *g, SBFile file, SLFile *names = nullptr); static Buffer write(SBFile file); //Creates new buffer static bool write(String path, SBFile file); }; } }
15.755102
86
0.650907
[ "vector" ]
13cd8a7f66400a6f3071835b6628757d70db9202
19,196
h
C
minisat/core/SolverTypes.h
jia-kai/minisatcs
21b5a73db7adac660040f999481a8f8b018d77e5
[ "MIT" ]
3
2020-12-24T08:14:09.000Z
2021-12-21T11:39:04.000Z
minisat/core/SolverTypes.h
jia-kai/minisatcs
21b5a73db7adac660040f999481a8f8b018d77e5
[ "MIT" ]
null
null
null
minisat/core/SolverTypes.h
jia-kai/minisatcs
21b5a73db7adac660040f999481a8f8b018d77e5
[ "MIT" ]
null
null
null
/***********************************************************************************[SolverTypes.h] Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson 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 Minisat_SolverTypes_h #define Minisat_SolverTypes_h #include <cassert> #include <utility> #include <vector> #include "minisat/mtl/Alg.h" #include "minisat/mtl/Alloc.h" #include "minisat/mtl/IntTypes.h" #include "minisat/mtl/Vec.h" namespace MinisatCS { //================================================================================================= // Variables, literals, lifted booleans, clauses: // NOTE! Variables are just integers. No abstraction here. They should be chosen // from 0..N, so that they can be used as array indices. typedef int Var; #define var_Undef (-1) struct Lit { int x; bool operator==(Lit p) const { return x == p.x; } bool operator!=(Lit p) const { return x != p.x; } bool operator<(Lit p) const { return x < p.x; } // '<' makes p, ~p adjacent in the ordering. }; static inline Lit mkLit(Var var, bool sign = false) { Lit p; p.x = var + var + (int)sign; return p; } static inline Lit operator~(Lit p) { Lit q; q.x = p.x ^ 1; return q; } static inline Lit operator^(Lit p, bool b) { Lit q; q.x = p.x ^ (unsigned int)b; return q; } static inline bool sign(Lit p) { return p.x & 1; } static inline int var(Lit p) { return p.x >> 1; } // Mapping Literals to and from compact integers suitable for array indexing: static inline int toInt(Var v) { return v; } static inline int toInt(Lit p) { return p.x; } static inline Lit toLit(int i) { Lit p; p.x = i; return p; } // const Lit lit_Undef = mkLit(var_Undef, false); // }- Useful special // constants. const Lit lit_Error = mkLit(var_Undef, true ); // } static constexpr Lit lit_Undef = {-2}; // }- Useful special constants. static constexpr Lit lit_Error = {-1}; // } //================================================================================================= // Lifted booleans: // // NOTE: this implementation is optimized for the case when comparisons between // values are mostly between one variable and one constant. Some care had to be // taken to make sure that gcc does enough constant propagation to produce // sensible code, and this appears to be somewhat fragile unfortunately. struct lbool_true_type {}; struct lbool_false_type {}; struct lbool_undef_type {}; struct lbool_invalid_type {}; static constexpr lbool_true_type l_True; static constexpr lbool_false_type l_False; static constexpr lbool_undef_type l_Undef; static constexpr lbool_invalid_type l_Invalid; class lbool { uint8_t value; explicit constexpr lbool(uint8_t v) : value{v} {} public: constexpr lbool() : value(0) {} constexpr explicit lbool(bool v) : value{!v} {} constexpr lbool(lbool_true_type) : lbool(true) {} constexpr lbool(lbool_false_type) : lbool(false) {} constexpr lbool(lbool_undef_type) : lbool(static_cast<uint8_t>(2)) {} constexpr lbool(lbool_invalid_type) : lbool(static_cast<uint8_t>(4)) {} template <typename T> lbool(T) = delete; static constexpr lbool make_raw(uint8_t v) { return lbool{v}; } constexpr bool operator==(lbool_true_type) const { return value == 0; } constexpr bool operator==(lbool_false_type) const { return value == 1; } constexpr bool operator==(lbool_undef_type) const { return value & 2; } constexpr bool operator==(lbool_invalid_type) const { return value & 4; } template <typename T> constexpr bool operator!=(T t) const { return !operator==(t); } constexpr lbool operator^(bool b) const { return make_raw(value ^ (uint8_t)b); } constexpr bool is_boolv(bool b) const { return value == (static_cast<uint8_t>(b) ^ 1); } template<bool b> constexpr bool is_bool() const { return value == (static_cast<uint8_t>(b) ^ 1); } bool as_bool() const { assert(!(value & 6)); return value == 0; } constexpr bool is_not_undef() const { return !(value & 2); } }; /* ========================== LeqStatus =========================== */ //! Clause reference type using CRef = RegionAllocator<uint32_t>::Ref; //! status for an LEQ clause union LeqStatus { static constexpr uint32_t OFFSET_IN_CLAUSE = 3; enum ImplyType { //! no var has been implied from this clause IMPLY_NONE = 0, //! value of dst is implied (preconditions are placed at the beginning) IMPLY_DST = 1, //! some lits are implied (preconditions are placed at the beginning) IMPLY_LITS = 2, //! dst var and know lits cause a conflict IMPLY_CONFL = 3, }; struct { //! number of known true lits uint16_t nr_true : 15; //! whether preconditions for the imply is true uint16_t precond_is_true : 1; //! number of decided lits (sum of nr_true and nr_false) uint16_t nr_decided : 14; //! one value in ImplyType uint16_t imply_type : 2; }; uint32_t val_u32; void decr(uint32_t delta_nr_true, uint32_t delta_nr_decided) { val_u32 -= (delta_nr_decided << 16) | delta_nr_true; }; void incr(uint32_t delta_nr_true, uint32_t delta_nr_decided) { val_u32 += (delta_nr_decided << 16) | delta_nr_true; }; //! if bit = 1, set imply_type to 0; otherwise it is unchanged. //! bit should be either 0 or 1 void clear_imply_type_with(uint32_t bit) { val_u32 &= ((1u << 30) - 1) | (bit - 1); } //! get CRef of rellocated clause from this var. Note that the cref is a //! clause, not for a var CRef get_cref_after_reloc() { return *(reinterpret_cast<CRef*>(this) - 3); } bool operator==(const LeqStatus& rhs) const { return val_u32 == rhs.val_u32; } }; /* ========================== end LeqStatus =========================== */ //================================================================================================= // Clause -- a simple class for representing a clause: class Clause { /*! * Note: * 1. learnt and is_leq can not both be true * 2. use_extra and is_leq can not both be true * 3. If is_leq is true, there would be two extra data items: one is * leq_dst, the other is leq_bound * 4. Layout for LEQ clauses: header, lits[], dst, bound, status */ struct { unsigned mark : 2; unsigned learnt : 1; unsigned is_leq : 1; unsigned has_extra : 1; unsigned reloced : 1; unsigned size : 26; } header; union Data { Lit lit; float act; uint32_t abs; int32_t leq_bound; LeqStatus leq_status; CRef rel; }; Data data[0]; friend class ClauseAllocator; // NOTE: This constructor cannot be used directly (doesn't allocate enough // memory). template <class V> Clause(const V& ps, bool use_extra, bool learnt, bool is_leq) { assert(!learnt || !is_leq); assert(!use_extra || !is_leq); assert(ps.size() < (1 << 26)); // leq size determined by LeqStatus and LeqWatcher assert(!is_leq || ps.size() < (1 << 14)); header.mark = 0; header.learnt = learnt; header.is_leq = is_leq; header.has_extra = use_extra; header.reloced = 0; header.size = ps.size(); for (int i = 0; i < ps.size(); i++) { data[i].lit = ps[i]; } if (header.has_extra) { if (header.learnt) data[header.size].act = 0; else calcAbstraction(); } } public: void calcAbstraction() { assert(header.has_extra); uint32_t abstraction = 0; for (int i = 0; i < size(); i++) abstraction |= 1u << (var(data[i].lit) & 31); data[header.size].abs = abstraction; } int size() const { return header.size; } void shrink(int i) { assert(i <= size() && !header.is_leq); if (header.has_extra) data[header.size - i] = data[header.size]; header.size -= i; } void pop() { shrink(1); } void shrink_leq_to(int new_size, int new_bound) { assert(header.is_leq && !header.has_extra); data[new_size] = data[header.size]; data[new_size + 1].leq_bound = new_bound; data[new_size + 2] = data[header.size + 2]; header.size = new_size; } bool learnt() const { return header.learnt; } bool is_leq() const { return header.is_leq; } Lit leq_dst() const { return data[header.size].lit; } int leq_bound() const { return data[header.size + 1].leq_bound; } LeqStatus& leq_status() { return data[header.size + 2].leq_status; } LeqStatus leq_status() const { return data[header.size + 2].leq_status; } bool has_extra() const { return header.has_extra; } uint32_t mark() const { return header.mark; } void mark(uint32_t m) { header.mark = m; } Lit last() const { return data[header.size - 1].lit; } const Lit* lit_data() const { static_assert(sizeof(Data) == sizeof(Lit)); return &data[0].lit; } bool reloced() const { return header.reloced; } CRef relocation() const { return data[0].rel; } //! relocate to another clause; this can only be called once and is //! destructive void record_relocate(CRef c) { assert(!header.reloced); header.reloced = 1; data[0].rel = c; // for LEQ clauses data[size() - 1].rel = c; } // NOTE: somewhat unsafe to change the clause in-place! Must manually call // 'calcAbstraction' afterwards for // subsumption operations to behave correctly. Lit& operator[](int i) { return data[i].lit; } Lit operator[](int i) const { return data[i].lit; } operator const Lit*(void)const { return (Lit*)data; } float& activity() { assert(header.has_extra); return data[header.size].act; } uint32_t abstraction() const { assert(header.has_extra); return data[header.size].abs; } Lit subsumes(const Clause& other) const; void strengthen(Lit p); }; //================================================================================================= // ClauseAllocator -- a simple class for allocating memory for clauses: static constexpr CRef CRef_Undef = RegionAllocator<uint32_t>::Ref_Undef; class ClauseAllocator : public RegionAllocator<uint32_t> { using Super = RegionAllocator<uint32_t>; static int clauseWord32Size(int size, bool has_extra, bool is_leq) { assert(!has_extra || !is_leq); size += static_cast<int>(has_extra) + static_cast<int>(is_leq) * 3; return (sizeof(Clause) + (sizeof(Lit) * size)) / sizeof(uint32_t); } public: bool extra_clause_field = false; ClauseAllocator(uint32_t start_cap) : Super(start_cap) {} ClauseAllocator() = default; void moveTo(ClauseAllocator& to) { to.extra_clause_field = extra_clause_field; Super::moveTo(to); } template <class Lits> CRef alloc(const Lits& ps, bool learnt = false, Lit leq_dst = lit_Undef, int leq_bound = 0) { static_assert(sizeof(Clause::Data) == sizeof(uint32_t)); bool use_extra = learnt | extra_clause_field; bool is_leq = leq_dst != lit_Undef; CRef cid = Super::alloc(clauseWord32Size(ps.size(), use_extra, is_leq)); Clause* cl = new (lea(cid)) Clause{ps, use_extra, learnt, is_leq}; if (is_leq) { cl->data[ps.size()].lit = leq_dst; cl->data[ps.size() + 1].leq_bound = leq_bound; cl->data[ps.size() + 2].leq_status.val_u32 = 0; } return cid; } // Deref, Load Effective Address (LEA), Inverse of LEA (AEL): Clause& operator[](Ref r) { return reinterpret_cast<Clause&>(Super::operator[](r)); } const Clause& operator[](Ref r) const { return const_cast<ClauseAllocator*>(this)->operator[](r); } Clause* lea(Ref r) { return reinterpret_cast<Clause*>(Super::lea(r)); } const Clause* lea(Ref r) const { return const_cast<ClauseAllocator*>(this)->lea(r); } template <typename T> T* lea_as(Ref r) { static_assert(sizeof(T) % sizeof(uint32_t) == 0 && alignof(T) % alignof(uint32_t) == 0); return reinterpret_cast<T*>(Super::lea(r)); } template <typename T> const T* lea_as(Ref r) const { return const_cast<ClauseAllocator*>(this)->lea_as<T>(r); } template <typename T> Ref ael(const T* t) { static_assert(sizeof(T) % sizeof(uint32_t) == 0 && alignof(T) % alignof(uint32_t) == 0); return Super::ael(reinterpret_cast<const uint32_t*>(t)); } void free(CRef cid) { Clause& c = operator[](cid); Super::free(clauseWord32Size(c.size(), c.has_extra(), c.is_leq())); } void reloc(CRef& cr, ClauseAllocator& to) { Clause& c = operator[](cr); if (c.reloced()) { cr = c.relocation(); return; } if (c.is_leq()) { cr = to.alloc(c, c.learnt(), c.leq_dst(), c.leq_bound()); to[cr].leq_status() = c.leq_status(); } else { cr = to.alloc(c, c.learnt()); } c.record_relocate(cr); // Copy extra data-fields: // (This could be cleaned-up. Generalize Clause-constructor to be // applicable here instead?) to[cr].mark(c.mark()); if (to[cr].learnt()) to[cr].activity() = c.activity(); else if (to[cr].has_extra()) to[cr].calcAbstraction(); } }; //================================================================================================= /*! * a class for maintaining occurence lists with lazy deletion * * \tparam Refresh: a functor class to refresh the watchers; it can modify * watchers in place. Return true if a watcher should be removed. */ template <class Idx, class Vec, class Refresh> class OccLists { std::vector<Vec> m_occs; vec<bool> m_dirty; vec<Idx> m_dirties; Refresh m_refresh; //! refresh dirty watches and remove deleted items in the list of idx void clean(const Idx& idx); public: template <typename... Args> explicit OccLists(Args&&... args) : m_refresh{std::forward<Args>(args)...} {} void init(const Idx& idx) { size_t size = toInt(idx) + 1; if (size > m_occs.size()) { while (m_occs.size() < size) { m_occs.emplace_back(); } m_dirty.growTo(size); } } // Vec& operator[](const Idx& idx){ return occs[toInt(idx)]; } Vec& operator[](const Idx& idx) { return m_occs[toInt(idx)]; } Vec& lookup(const Idx& idx) { if (m_dirty[toInt(idx)]) clean(idx); return m_occs[toInt(idx)]; } void cleanAll(); //! mark that watchers in a given index should be refreshed void smudge(const Idx& idx) { if (m_dirty[toInt(idx)] == 0) { m_dirty[toInt(idx)] = 1; m_dirties.push(idx); } } void clear(bool free = true) { if (free) { std::vector<Vec> t; m_occs.swap(t); } else { m_occs.clear(); } m_dirty.clear(free); m_dirties.clear(free); } }; template <class Idx, class Vec, class Refresh> void OccLists<Idx, Vec, Refresh>::cleanAll() { for (Idx i : m_dirties) { // Dirties may contain duplicates so check here if a variable is already // cleaned: if (m_dirty[toInt(i)]) { clean(i); } } m_dirties.clear(); } template <class Idx, class Vec, class Refresh> void OccLists<Idx, Vec, Refresh>::clean(const Idx& idx) { Vec& vec = m_occs[toInt(idx)]; int i, j; for (i = j = 0; i < vec.size(); i++) { if (!m_refresh(vec[i])) { vec[j++] = vec[i]; } } vec.shrink(i - j); m_dirty[toInt(idx)] = 0; } /*_________________________________________________________________________________________________ | | subsumes : (other : const Clause&) -> Lit | | Description: | Checks if clause subsumes 'other', and at the same time, if it can be used to simplify 'other' | by subsumption resolution. | | Result: | lit_Error - No subsumption or simplification | lit_Undef - Clause subsumes 'other' | p - The literal p can be deleted from 'other' |________________________________________________________________________________________________@*/ inline Lit Clause::subsumes(const Clause& other) const { // if (other.size() < size() || (extra.abst & ~other.extra.abst) != 0) // if (other.size() < size() || (!learnt() && !other.learnt() && (extra.abst // & ~other.extra.abst) != 0)) assert(!header.learnt); assert(!other.header.learnt); assert(header.has_extra); assert(other.header.has_extra); if (other.header.size < header.size || (data[header.size].abs & ~other.data[other.header.size].abs) != 0) return lit_Error; Lit ret = lit_Undef; const Lit* c = (const Lit*)(*this); const Lit* d = (const Lit*)other; for (unsigned i = 0; i < header.size; i++) { // search for c[i] or ~c[i] for (unsigned j = 0; j < other.header.size; j++) if (c[i] == d[j]) goto ok; else if (ret == lit_Undef && c[i] == ~d[j]) { ret = c[i]; goto ok; } // did not find it return lit_Error; ok:; } return ret; } inline void Clause::strengthen(Lit p) { remove(*this, p); calcAbstraction(); } //================================================================================================= } // namespace MinisatCS #endif
31.993333
100
0.583715
[ "vector" ]
13cebd8fffc599b86c5dcbdce5704207564c7518
505
h
C
src/include/list.h
allangagnon/SimpleList
95e5721d30b8caa93268eee02a90a16f6cc0fbcd
[ "MIT" ]
1
2020-05-23T00:12:53.000Z
2020-05-23T00:12:53.000Z
src/include/list.h
allangagnon/SimpleList
95e5721d30b8caa93268eee02a90a16f6cc0fbcd
[ "MIT" ]
null
null
null
src/include/list.h
allangagnon/SimpleList
95e5721d30b8caa93268eee02a90a16f6cc0fbcd
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class List { private: protected: public: List(){ //constructor } ~List(){ //destructor } vector<string> list; vector<vector<string>> mainList; string name; int currentUserIndex; void print_menu(); void print_list(); void add_item(); void delete_item(); bool find_userList(); void save_list(); };
18.703704
40
0.516832
[ "vector" ]
13d481eaf5860c9a61bac425921b24cca095ffaf
20,007
c
C
src/session-native.c
odilitime/session-native
435e8dadad67689440344df54523f9632478a514
[ "MIT" ]
1
2021-02-16T13:15:06.000Z
2021-02-16T13:15:06.000Z
src/session-native.c
odilitime/session-native
435e8dadad67689440344df54523f9632478a514
[ "MIT" ]
1
2021-02-16T13:15:42.000Z
2021-02-23T18:17:35.000Z
src/session-native.c
odilitime/session-native
435e8dadad67689440344df54523f9632478a514
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> // for strdup ssize_t getline(char **linep, size_t *np, FILE *stream); #include <sodium.h> #include "include/opengem/network/http/http.h" // for makeUrlRequest #include "include/opengem/network/protocols.h" #include "include/opengem/ui/components/component_button.h" #include "include/opengem/ui/components/component_input.h" #include "include/opengem/ui/components/component_tab.h" #include "include/opengem/ui/app.h" #include "include/opengem/session/snode.h" //#include "include/opengem/session/session.h" #include "include/opengem/session/send.h" #include "include/opengem/session/recv.h" #include "include/opengem/timer/scheduler.h" //#include "include/opengem/ui/textblock.h" #define MIN(a,b) (((a)<(b))?(a):(b)) // Access MacOS APIs from c/c++ // https://codereview.stackexchange.com/a/95909 /* - initial UI - open group support - profile support - avatar / attachment support - mutlithreading - encrypted database - onion routing support / lokinet support - closed group support */ /* LEAKS - openssl, reuse more... - openssl, clean up more... */ extern struct dynList snodeURLs; struct app session; struct tabbed_component *convoTab; struct tabbed_component *messagesTab; struct text_component *identityText; struct input_component *input; struct button_component *sendButton; struct text_component *statusBar; struct llLayerInstance *newConvoLayer; struct input_component *idInput; struct dynList conversations; struct session_keypair current_skp; struct conversation { char *pubkeyStr; struct tab *tab; uint16_t badgeCount; struct dynList messages; }; struct message { char *fromStr; char *body; }; #define HEAP_ALLOCATE(TYPE,VAR) TYPE *VAR = malloc(sizeof(TYPE)); void *loadMessage_iterator(const struct dynListItem *item, void *user) { // render message struct messagesTab struct message *msg = item->value; if (!msg) return user; tab_add(messagesTab, msg->body, session.activeAppWindow->win); return user; } void selectConversation(struct tab *tab) { printf("selectConversation [%p=>%p]\n", convoTab->selectedTab, tab); // we can't abort here because we need drive the first select // and since tab_add selects it, we are already selected. //if (convoTab->selectedTab == tab) return; // unselect old one //convoTab->selectedTabId = convoId; tabbed_component_selectTab((struct tabbed_component *)messagesTab, tab); //convoTab->selectedTab = tab; // find messages tabs struct llLayerInstance *ll = messagesTab->super.layers.head->value; // FIXME: iterator on destroy on them // erase them dynList_reset(&ll->rootComponent->children); // load messages struct conversation *tabConvo = tab->user; int c[] = {1}; dynList_iterator_const(&tabConvo->messages, loadMessage_iterator, c); ll->rootComponent->renderDirty = true; if (tab) { printf("selectConversation - Enabling input\n"); input->super.super.disabled = false; // don't enable send button until they type } else { input->super.super.disabled = true; sendButton->super.disabled = true; } convoTab->super.super.renderDirty = true; } void *find_conversationFrom_iterator(const struct dynListItem *item, void *user) { struct conversation *convo = item->value; if (strcmp(user, convo->pubkeyStr) == 0) { return convo; } return user; } void *recv_callback_iter(const struct dynListItem *item, void *user) { // event system? struct handleUnidentifiedMessageType_result *result = item->value; //struct session_recv_io *io = user; char from[67]; pkToString(result->source, from); // convert to hexstring if (result->content->datamessage) { printf("%s: %s\n", from, result->content->datamessage->body); char *useFrom = from; if (strcmp(from, current_skp.pkStr) == 0) { useFrom = "Note to self"; } if (strcmp(from, "05c87493c457b29a4137c091b59998cb5ffd7fd727d19ba0046deff47abb7adf35") == 0) { useFrom = "Bot directory"; } // we do have a conversation for this from? void *searchRes = dynList_iterator_const(&conversations, find_conversationFrom_iterator, useFrom); if (searchRes == from) { // if not create it HEAP_ALLOCATE(struct conversation, conf) dynList_init(&conf->messages, sizeof(char *), "Convo messages"); conf->pubkeyStr = strdup(from); conf->badgeCount = 0; conf->tab = tab_add(convoTab, conf->pubkeyStr, session.activeAppWindow->win); conf->tab->user = conf; selectConversation(conf->tab); dynList_push(&conversations, conf); searchRes = conf; } struct conversation *convo = searchRes; //strcmp(convo->source, from) == 0 // is the selected conversation == from if (convoTab->selectedTab == convo->tab) { // if so add it to the existing list tab_add(messagesTab, result->content->datamessage->body, session.activeAppWindow->win); } else { // update badge char *label = malloc(strlen(convo->tab->titleBox.text) + 8); // how does this just not continue to append shit // also this breaks sending to that person sprintf(label, "%s (%d)", convo->tab->titleBox.text, convo->badgeCount); //char *oldLabel = convo->tab->titleBox.text; if (convo->tab->titleBox.text != convo->pubkeyStr) { // can't free it because that string is also used in convo->pubkeyStr free((char *)convo->tab->titleBox.text); } convo->tab->titleBox.text = label; convo->badgeCount++; convoTab->super.super.renderDirty = true; } HEAP_ALLOCATE(struct message, msg) msg->body = result->content->datamessage->body; msg->fromStr = from; dynList_push(&convo->messages, msg); } else { // non-data message printf("Non-data message typing[%p] receipt[%p]\n", result->content->typingmessage, result->content->receiptmessage); } return user; } struct recv_callback_data { struct session_keypair *skp; char lastHash[129]; // hexstring version }; void updateStatusBar(char *status) { text_component_setText(statusBar, status); app_window_render(session.activeAppWindow); // draw it to the screen // we can't make setText auto draw because it doesn't know we're done making change } void session_recv_cb(struct session_recv_io *io) { //printf("session_native::session_recv_cb - start\n"); updateStatusBar("Updating UI..."); if (io->contents) { printf("Found [%zu] messages\n", (size_t)io->contents->count); dynList_iterator_const(io->contents, recv_callback_iter, io); free(io->contents); } struct recv_callback_data *recv_data = io->user; // if changed... if (io->lastHash != recv_data->lastHash) { // pass lastHash to next call strncpy(recv_data->lastHash, io->lastHash, MIN(strlen(io->lastHash), 129)); } text_component_setText(statusBar, "Ready"); } bool recv_callback(struct md_timer *timer, double now) { updateStatusBar("Checking for new messages"); struct recv_callback_data *recv_data = timer->user; struct session_keypair *skp = recv_data->skp; // can't have this go out of scope // because of the net io (threading) split struct session_recv_io *io = malloc(sizeof(struct session_recv_io)); io->kp = skp; io->contents = 0; io->lastHash = recv_data->lastHash; io->cb = session_recv_cb; io->user = recv_data; session_recv(io); return true; } void *getComponentById(char *id) { void *res = app_window_group_instance_getElementById(session.activeAppWindowGroup, id); if (!res) { printf("Cannot find %s\n", id); return 0; }; return res; } void eventHandler(struct app_window *appwin, struct component *comp, const char *event) { printf("eventHandler - event[%s]\n", event); bool found = false; switch(event[0]) { case 'c': { // copy if (strcmp(event, "copy") == 0) { struct text_component *text = (struct text_component *)comp; appwin->win->setClipboard(appwin->win, (char *)text->text); text_component_setText(statusBar, "Identity copied to clipboard"); found = true; } else if (strcmp(event, "cancelConvo") == 0) { newConvoLayer->hidden = true; newConvoLayer->rootComponent->renderDirty = true; found = true; } else if (strcmp(event, "createConvo") == 0) { char *newId = textblock_getValue(&idInput->text);; if (strlen(newId) < 64 || strlen(newId) > 66) { printf("Invalid SessionID size\n"); text_component_setText(statusBar, "Invalid SessionID size"); return; } HEAP_ALLOCATE(struct conversation, conf) dynList_init(&conf->messages, sizeof(char *), "Convo messages"); conf->pubkeyStr = newId; if (strcmp(conf->pubkeyStr, identityText->text) == 0) { conf->pubkeyStr = strdup("Note to self"); } conf->badgeCount = 0; conf->tab = tab_add(convoTab, conf->pubkeyStr, session.activeAppWindow->win); conf->tab->user = conf; selectConversation(conf->tab); dynList_push(&conversations, conf); text_component_setText(statusBar, "conversation created!"); input_component_setValue(idInput, ""); newConvoLayer->hidden = true; newConvoLayer->rootComponent->renderDirty = true; component_setBlur(&idInput->super.super, appwin); found = true; } break; } case 'n': { // newConvo // check clipboard for one sessionid const char *clipboard = appwin->win->getClipboard(appwin->win); if (strlen(clipboard) == 66) { printf("May have sessionID in clipboard\n"); // set the value... input_component_setValue(idInput, clipboard); } newConvoLayer->hidden = false; newConvoLayer->rootComponent->renderDirty = true; component_setFocus(&idInput->super.super, appwin); found = true; break; } case 's': { // send char *msg = textblock_getValue(&input->text); if (!strlen(msg)) { text_component_setText(statusBar, "No message!"); return; } // to who? if (!convoTab->selectedTab) { text_component_setText(statusBar, "No conversation selected!"); return; } // blocking action incoming input_component_setValue(input, ""); sendButton->super.disabled = true; updateStatusBar("Sending..."); const char *dest = convoTab->selectedTab->titleBox.text; if (strcmp(dest, "Note to self") == 0) { dest = identityText->text; } if (strcmp(dest, "Bot directory") == 0) { dest = "05c87493c457b29a4137c091b59998cb5ffd7fd727d19ba0046deff47abb7adf35"; } // copy first 66 bytesnce char *finalDest = malloc(67); memcpy(finalDest, dest, 66); finalDest[66] = 0; HEAP_ALLOCATE(struct message, msg2) msg2->body = strdup(msg); msg2->fromStr = finalDest; struct conversation *convo = convoTab->selectedTab->user; dynList_push(&convo->messages, msg2); // FIXME: no local echo until we reload the convo... // and it's not a dirty render thing... //printf("Sending [%s] to [%s]\n", msg, finalDest); session_send(finalDest, &current_skp, msg, 0); free(msg); text_component_setText(statusBar, "Ready"); found = true; break; } default: printf("eventHandler - unknown event[%s]\n", event); found = true; break; } if (!found) { printf("eventHandler - unknown event[%s]\n", event); } } struct component *lastTab = 0; // defeat dragging to sort tho.. bool tabMouse = false; void tab_onMouseUp(struct window *win, int button, int mods, void *user) { // user has to be a type of event //component_onMouseUp(win, button, mods, user); //struct app_window *const appwin = user; //printf("tab_onMouseUp [%s] hover[%s]\n", appwin->rootComponent.super.name, appwin->hoverComponent->name); tabMouse = false; if (!lastTab || !lastTab->parent) { // click on tabbed control but not a tab... // maybe try reseting X and trying again.. return; } struct tab *tab = lastTab->parent->pickUser; selectConversation(tab); // actually make it active... //tabbed_component_selectTab((struct tabbed_component *)appwin->hoverComponent, tab); } void tab_onMouseDown(struct window *win, int x, int y, void *user) { //component_onMouseDown(win, x, y, user); struct app_window *const appwin = user; // pick // translate tab pos into pick // and then which //printf("tab_onMouseDown\n"); tabMouse = true; if (!lastTab || !lastTab->parent) { // click on tabbed control but not a tab... // maybe try reseting X and trying again.. return; } struct tab *tab = lastTab->parent->pickUser; // we don't use selectConvo here because we don't want to change messages yet struct tabbed_component *tComp = (struct tabbed_component *)appwin->hoverComponent; tabbed_component_selectTab(tComp, tab); } void tab_onMouseMove(struct window *win, int16_t x, int16_t y, void *user) { //component_onMouseMove(win, x, y, user); //printf("tab_onMouseMove [%d,%d]\n", x, y); struct app_window *const appwin = user; // feels a tad sluggish // we could do component_pick but it just calls this anyways struct component *pick = multiComponent_pick(appwin->hoverComponent, appwin->win->cursorX, appwin->win->cursorY); lastTab = pick; if (!pick) { appwin->win->changeCursor(appwin->win, 0); return; } appwin->win->changeCursor(appwin->win, pick->hoverCursorType); // is mouse down? if (tabMouse) { if (!lastTab->parent) { // click on tabbed control but not a tab... // maybe try reseting X and trying again.. printf("no parent[%s]\n", lastTab->name); return; } struct tab *tab = lastTab->parent->pickUser; tabbed_component_selectTab((struct tabbed_component *)appwin->hoverComponent, tab); } else { //printf("Mouse is up\n"); } } void idInput_onKeyUp(struct window *win, int key, int scancode, int mod, void *user) { //printf("toInput_onKeyUp\n"); if (key == 13) { //printf("toInput_onKeyUp enter\n"); eventHandler(user, 0, "createConvo"); return; } input_component_keyUp(win, key, scancode, mod, idInput); } void input_onKeyUp(struct window *win, int key, int scancode, int mod, void *user) { //printf("input_onKeyUp\n"); if (key == 13) { //printf("input_onKeyUp enter\n"); eventHandler(user, 0, "send"); return; } input_component_keyUp(win, key, scancode, mod, input); char *msg = textblock_getValue(&input->text); if (strlen(msg)) { sendButton->super.disabled = false; } else { sendButton->super.disabled = true; } } // block until ready and return? void waitForURLRequest(struct loadWebsite_t *task, struct app *app) { //printf("Waiting [%s]\n", task->request.uri); while(!task->response.complete && !app->requestShutdown) { // if 0 is there, we wait for uesr input when we're just waiting for net io og_app_tickForSloppy(app, 100); } //printf("Waited\n"); } int main(int argc, char *argv[]) { time_t t; srand((unsigned) time(&t)); if (sodium_init() == -1) { printf("sodium couldn't init\n"); return 1; } thread_spawn_worker(); if (app_init(&session)) { printf("compiled with no renders\n"); return 1; } // create app struct app_window_group_template wgSession; app_window_group_template_init(&wgSession, &session); // load ntr into app struct app_window_template wtSession; app_window_template_init(&wtSession, "Resources/session-native.ntrml"); // we would set winPos wtSession.title = "session-native"; //wtBrowser.winPos.w = 640; //wtBrowser.winPos.h = 480; //wtBrowser.desiredFPS = 60; app_window_group_template_addWindowTemplate(&wgSession, &wtSession); wgSession.leadWindow = &wtSession; wgSession.eventHandler = eventHandler; // start app //struct app_window_group_instance *wingrp_inst = app_window_group_template_spawn(&wgSession, session.renderer); // wire up interface identityText = getComponentById("identity"); // (struct tabbed_component *) convoTab = getComponentById("conversations"); messagesTab = getComponentById("messages"); input = getComponentById("sendbar"); sendButton = getComponentById("sendBut"); statusBar = getComponentById("statusBar"); idInput = getComponentById("toIdentity"); struct component *ncLater = getComponentById("newConvo"); newConvoLayer = multiComponent_layer_findByComponent(&session.activeAppWindow->rootComponent, ncLater); if (!newConvoLayer) { printf("Can't find layer newConvo\n"); } if (!(identityText && convoTab && messagesTab && input && sendButton && statusBar && newConvoLayer && idInput)) { return 1; } updateStatusBar("Starting..."); dynList_init(&conversations, sizeof(struct conversation), "conversations"); struct loadWebsite_t *task = goSnodes(); //printf("task user[%p] req->user[%p]\n", task->user, task->request.user); waitForURLRequest(task, &session); while(!snodeURLs.count) { printf("Bootstrapping\n"); task = goSnodes(); waitForURLRequest(task, &session); } printf("Bootstrapped[%zu]\n", (size_t)snodeURLs.count); //crypto_box_keypair(skp.pk, skp.sk); crypto_sign_ed25519_keypair(current_skp.epk, current_skp.esk); crypto_sign_ed25519_sk_to_curve25519(current_skp.sk, current_skp.esk); int res = crypto_sign_ed25519_pk_to_curve25519(current_skp.pk, current_skp.epk); // res is usually zero if (res) { printf("Signing ED result[%d]\n", res); return 1; } current_skp.pkStr = malloc(67); pkToString(current_skp.pk, current_skp.pkStr); // convert to hexstring printf("Session started for [%s]\n", current_skp.pkStr); text_component_setText(identityText, current_skp.pkStr); input->super.super.event_handlers->onKeyUp = input_onKeyUp; //input->super.super.event_handlers->onKeyUpUser = input; if (!convoTab->super.super.event_handlers) { convoTab->super.super.event_handlers = malloc(sizeof(struct event_tree)); event_tree_init(convoTab->super.super.event_handlers); } convoTab->super.super.event_handlers->onMouseDown = tab_onMouseDown; convoTab->super.super.event_handlers->onMouseMove = tab_onMouseMove; convoTab->super.super.event_handlers->onMouseUp = tab_onMouseUp; input->super.super.disabled = true; sendButton->super.disabled = true; //messagesTab->selectColor = 0x000000FF; //tabbed_component_updateColors(messagesTab, session.activeAppWindow->win); idInput->super.super.event_handlers->onKeyUp = idInput_onKeyUp; HEAP_ALLOCATE(struct conversation, conf) dynList_init(&conf->messages, sizeof(char *), "Convo messages"); conf->pubkeyStr = strdup("Bot directory"); conf->badgeCount = 0; conf->tab = tab_add(convoTab, conf->pubkeyStr, session.activeAppWindow->win); conf->tab->user = conf; selectConversation(conf->tab); dynList_push(&conversations, conf); //send("05e308f32ab4bcb9dae4cdd8ebdc912396cd3570832e6a8215e13720c6b0088a3e", &skp, "Hi", 0); struct recv_callback_data recv_data; strcpy(recv_data.lastHash, "undefined"); recv_data.skp = &current_skp; if (1) { struct md_timer *reciever = setInterval(recv_callback, 10000); reciever->name = "session-native-reciever"; reciever->user = &recv_data; } else { // good for UI debugging. // just poll once to avoid stacking issues // we need to be dynamically allocated because we'll respond after recv is called struct session_recv_io *io = malloc(sizeof(struct session_recv_io)); io->kp = recv_data.skp; io->contents = 0; io->lastHash = recv_data.lastHash; io->cb = session_recv_cb; io->user = &recv_data; session_recv(io); } text_component_setText(statusBar, "Ready"); printf("Start loop\n"); session.loop(&session); free(current_skp.pkStr); return 0; } #include "getline.c"
34.083475
121
0.682061
[ "render" ]