content
stringlengths
12
2.72M
<filename>Medium/vowel_string.c #include<stdio.h> #include<string.h> int main() { char str[300], * ptr, c1, c2; c1=c2=0; printf("Enter String: "); gets(str); ptr = str; while (*ptr != '\0') { if (*ptr == 'a' || *ptr == 'e' || *ptr == 'i' || *ptr == 'o' || *ptr == 'u' || *ptr == 'A' || *ptr == 'E' || *ptr == 'I' || *ptr == 'O' || *ptr == 'U') ++c2; else if ((*ptr >= 'a' && *ptr <= 'z') || (*ptr >= 'A' && *ptr <= 'Z')) ++c1; ++ptr; } printf("Number of Vowels: %d", c2); }
<filename>Flopio/src/core/resourse/files/DirectoryResourceFile.h #pragma once #include "../ResourceFile.h" #include <string> #include <map> #include <utility> namespace engine { class DirectoryResourceFile : public ResourceFile { private: std::map<std::string, unsigned int> filesMap; public: DirectoryResourceFile(std::string path) : ResourceFile(path) {} virtual void VReload() override; virtual bool VOpen() override; virtual int VGetRawResourceSize(const Resource &r) override; virtual int VGetRawResource(const Resource &r, char *buffer) override; virtual int VGetNumResources() const override; virtual std::string VGetResourceName(int num) const override; }; }
<reponame>Tonyx97/TombMP<gh_stars>1-10 #pragma once void ControlFireHead(int16_t item_number); void InitialiseFireHead(int16_t item_number); void ControlRotateyThing(int16_t item_number);
<reponame>Quorafind/GuiLiteSamples #ifndef _TEMP_VALUE_VIEW_H_ #define _TEMP_VALUE_VIEW_H_ class c_temp_value_view : public c_value_view { public: virtual void on_init_children(void); virtual c_wnd* clone(){return new c_temp_value_view();} }; #endif
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/UIKit.framework/UIKit */ @interface UIImpactFeedbackGenerator : UIFeedbackGenerator @property (getter=_impactConfiguration, nonatomic, readonly) _UIImpactFeedbackGeneratorConfiguration *impactConfiguration; + (Class)_configurationClass; + (id)impactBehaviorWithCoordinateSpace:(id)arg1 configuration:(id)arg2; - (id)_impactConfiguration; - (void)_impactOccurredWithIntensity:(double)arg1; - (id)_stats_key; - (void)impactOccurred; - (id)initWithStyle:(long long)arg1; @end
<reponame>amvb/GUCEF /* Public domain */ #ifndef _AGAR_CORE_THREADS_H_ #define _AGAR_CORE_THREADS_H_ #ifdef AG_THREADS #include <agar/config/have_pthreads.h> #ifdef HAVE_PTHREADS #include <pthread.h> #include <signal.h> #include <stdio.h> #include <string.h> #else # error "AG_THREADS option requires POSIX threads" #endif typedef pthread_mutex_t AG_Mutex; typedef pthread_mutexattr_t AG_MutexAttr; typedef pthread_t AG_Thread; typedef pthread_cond_t AG_Cond; typedef pthread_key_t AG_ThreadKey; #ifdef _SGI_SOURCE #define AG_MUTEX_INITIALIZER {{0}} #else #define AG_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER #endif #include <agar/core/begin.h> __BEGIN_DECLS extern pthread_mutexattr_t agRecursiveMutexAttr; extern AG_Thread agEventThread; __END_DECLS #include <agar/core/close.h> #define AG_ThreadSelf() pthread_self() #define AG_ThreadEqual(t1,t2) pthread_equal((t1),(t2)) #define AG_ThreadExit(p) pthread_exit(p) #define AG_ThreadKeyGet(k) pthread_getspecific(k) #define AG_ThreadSigMask(how,n,o) pthread_sigmask((how),(n),(o)) #define AG_ThreadKill(thread,signo) (void)pthread_kill((thread),(signo)) #define AG_MutexTryLock(m) pthread_mutex_trylock(m) #define AG_CondWait(cd,m) pthread_cond_wait(cd,m) #define AG_CondTimedWait(cd,m,t) pthread_cond_timedwait(cd,m,t) /* * Thread interface */ static __inline__ void AG_ThreadCreate(AG_Thread *th, void *(*fn)(void *), void *arg) { int rv; if ((rv = pthread_create(th, NULL, fn, arg)) != 0) AG_FatalError("pthread_create (%d)", rv); } static __inline__ int AG_ThreadTryCreate(AG_Thread *th, void *(*fn)(void *), void *arg) { int rv; if ((rv = pthread_create(th, NULL, fn, arg)) != 0) { AG_SetError("%s", AG_Strerror(rv)); return (-1); } return (0); } static __inline__ void AG_ThreadCancel(AG_Thread th) { if (pthread_cancel(th) != 0) AG_FatalError("pthread_cancel"); } static __inline__ int AG_ThreadTryCancel(AG_Thread th) { int rv; if ((rv = pthread_cancel(th)) != 0) { AG_SetError("%s", AG_Strerror(rv)); return (-1); } return (0); } static __inline__ void AG_ThreadJoin(AG_Thread th, void **p) { if (pthread_join(th, p) != 0) AG_FatalError("pthread_join"); } static __inline__ int AG_ThreadTryJoin(AG_Thread th, void **p) { int rv; if ((rv = pthread_join(th, p)) != 0) { AG_SetError("%s", AG_Strerror(rv)); return (-1); } return (0); } /* * Mutex interface */ static __inline__ void AG_MutexInit(AG_Mutex *m) { if (pthread_mutex_init(m, NULL) != 0) AG_FatalError("pthread_mutex_init"); } static __inline__ void AG_MutexInitRecursive(AG_Mutex *m) { if (pthread_mutex_init(m, &agRecursiveMutexAttr) != 0) AG_FatalError("pthread_mutex_init(recursive)"); } static __inline__ int AG_MutexTryInit(AG_Mutex *m) { int rv; if ((rv = pthread_mutex_init(m, NULL)) != 0) { AG_SetError("%s", AG_Strerror(rv)); return (-1); } return (0); } static __inline__ int AG_MutexTryInitRecursive(AG_Mutex *m) { int rv; if ((rv = pthread_mutex_init(m, &agRecursiveMutexAttr)) != 0) { AG_SetError("%s", AG_Strerror(rv)); return (-1); } return (0); } static __inline__ void AG_MutexLock(AG_Mutex *m) { if (pthread_mutex_lock(m) != 0) AG_FatalError("pthread_mutex_lock"); } static __inline__ void AG_MutexUnlock(AG_Mutex *m) { if (pthread_mutex_unlock(m) != 0) AG_FatalError("pthread_mutex_unlock"); } static __inline__ void AG_MutexDestroy(AG_Mutex *m) { if (pthread_mutex_destroy(m) != 0) AG_FatalError("pthread_mutex_destroy"); } /* * Condition variable interface */ static __inline__ void AG_CondInit(AG_Cond *cd) { if (pthread_cond_init(cd, NULL) != 0) AG_FatalError("pthread_cond_init"); } static __inline__ int AG_CondTryInit(AG_Cond *cd) { int rv; if ((rv = pthread_cond_init(cd, NULL)) != 0) { AG_SetError("%s", AG_Strerror(rv)); return (-1); } return (0); } static __inline__ void AG_CondDestroy(AG_Cond *cd) { if (pthread_cond_destroy(cd) != 0) AG_FatalError("pthread_cond_destroy"); } static __inline__ void AG_CondBroadcast(AG_Cond *cd) { if (pthread_cond_broadcast(cd) != 0) AG_FatalError("pthread_cond_broadcast"); } static __inline__ void AG_CondSignal(AG_Cond *cd) { if (pthread_cond_signal(cd) != 0) AG_FatalError("pthread_cond_signal"); } /* * Thread-local storage interface */ static __inline__ void AG_ThreadKeyCreate(AG_ThreadKey *k, void (*destructorFn)(void *)) { if (pthread_key_create(k,destructorFn) != 0) AG_FatalError("pthread_key_create"); } static __inline__ int AG_ThreadKeyTryCreate(AG_ThreadKey *k, void (*destructorFn)(void *)) { int rv; if ((rv = pthread_key_create(k,destructorFn)) != 0) { AG_SetError("%s", AG_Strerror(rv)); return (-1); } return (0); } static __inline__ void AG_ThreadKeyDelete(AG_ThreadKey k) { if (pthread_key_delete(k) != 0) AG_FatalError("pthread_key_delete"); } static __inline__ int AG_ThreadKeyTryDelete(AG_ThreadKey k) { int rv; if ((rv = pthread_key_delete(k)) != 0) { AG_SetError("%s", AG_Strerror(rv)); return (-1); } return (0); } static __inline__ void AG_ThreadKeySet(AG_ThreadKey k, const void *p) { if (pthread_setspecific(k, p) != 0) AG_FatalError("pthread_setspecific"); } static __inline__ int AG_ThreadKeyTrySet(AG_ThreadKey k, const void *p) { int rv; if ((rv = pthread_setspecific(k, p)) != 0) { AG_SetError("%s", AG_Strerror(rv)); return (-1); } return (0); } #else /* !AG_THREADS */ typedef void *AG_Mutex; typedef void *AG_Thread; typedef void *AG_Cond; typedef void *AG_MutexAttr; typedef int AG_ThreadKey; #define AG_MUTEX_INITIALIZER 0 #define AG_COND_INITIALIZER 0 #define AG_MutexInit(m) #define AG_MutexInitRecursive(m) #define AG_MutexDestroy(m) #define AG_MutexLock(m) #define AG_MutexUnlock(m) #define AG_CondInit(cd) #define AG_CondDestroy(cd) #define AG_CondBroadcast(cd) #define AG_CondSignal(cd) #define AG_CondWait(cd,m) #define AG_CondTimedWait(cd,m,t) static __inline__ int AG_MutexTryInit(AG_Mutex *mu) { return (0); } static __inline__ int AG_MutexTryInitRecursive(AG_Mutex *mu) { return (0); } static __inline__ int AG_MutexTryLock(AG_Mutex *mu) { return (0); } #undef HAVE_PTHREADS #endif /* AG_THREADS */ #endif /* _AGAR_CORE_THREADS_H_ */
#ifndef GTMPI_H #define GTMPI_H void gtmpi_init(int num_processes); void gtmpi_barrier(); void gtmpi_finalize(); #endif
#ifndef INCLUDE_SPRITE_H #define INCLUDE_SPRITE_H #include <glm/vec2.hpp> #include <string> class Sprite { public: virtual ~Sprite() = default; virtual void render(const std::string &name, glm::vec2 position, glm::vec2 size) const = 0; }; #endif //INCLUDE_SPRITE_H
/* * Copyright 2020 McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education. */ #ifndef DEVICE_REGS_H #define DEVICE_REGS_H #include <cstdint> static constexpr uint16_t SYSTEM_START = 0x0000; static constexpr uint16_t SYSTEM_END = 0x2FFF; static constexpr uint16_t USER_START = 0x3000; static constexpr uint16_t USER_END = 0xFDFF; static constexpr uint16_t MMIO_START = 0xFE00; static constexpr uint16_t MMIO_END = 0xFFFF; static constexpr uint16_t RESET_PC = 0x0200; static constexpr uint16_t SYSTEM_STACK_POINTER = 0x3000; static constexpr uint16_t TRAP_TABLE_START = 0x0000; static constexpr uint16_t INTEX_TABLE_START = 0x0100; static constexpr uint16_t KBSR = 0xFE00; static constexpr uint16_t KBDR = 0xFE02; static constexpr uint16_t DSR = 0xFE04; static constexpr uint16_t DDR = 0xFE06; static constexpr uint16_t BSP = 0xFFFA; static constexpr uint16_t PSR = 0xFFFC; static constexpr uint16_t MCR = 0xFFFE; #endif
#include "substitute.h" #include "substitute-internal.h" #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <time.h> int main(int argc, char **argv) { if (argc <= 2) { printf("usage: test-inject <pid> <dylib>\n"); return 1; } int pid = atoi(argv[1]); char *error; mach_port_t port = 0; assert(!mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port)); struct shuttle shuttles[] = { {.type = SUBSTITUTE_SHUTTLE_MACH_PORT, .u.mach.port = port, .u.mach.right_type = MACH_MSG_TYPE_MAKE_SEND} }; clock_t a = clock(); int ret = substitute_dlopen_in_pid(pid, argv[2], 0, shuttles, 1, &error); clock_t b = clock(); printf("ret=%d err=%s time=%ld\n", ret, error, (long) (b - a)); assert(!ret); free(error); static struct { mach_msg_header_t hdr; char body[5]; mach_msg_trailer_t huh; } msg; kern_return_t kr = mach_msg_overwrite(NULL, MACH_RCV_MSG, 0, sizeof(msg), port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL, &msg.hdr, 0); printf("kr=%x\n", kr); assert(!kr); printf("received '%.5s'\n", msg.body); }
<reponame>DavHau/Riner<gh_stars>1-10 #pragma once #include "Pool.h" #include <future> #include <list> #include <src/config/Config.h> #include <src/application/Registry.h> #include <atomic> namespace riner { /** * maintains connections to multiple Pools as written down in the Config in descending priority order. * `tryGetWork` always fetches work from the highest priority Pool that does not * have a dead connection. * A connection is considered dead if the Pool (which extends StillAliveTrackable) * did not call its `onStillAlive()` for `PoolSwitcher::durUntilDeclaredDead` seconds * This condition is being checked regularly on a separate thread every 'checkInterval' seconds by this class */ class PoolSwitcher : public Pool { public: using clock = StillAliveTrackable::clock; /** * creates a PoolSwitcher for a given PowType * @param powType the PowType of all pools that will ever be added to this pool switcher * @param checkInterval the interval in which the alive status (see `StillAliveTrackable`) of pools is checked * @param durUntilDeclaredDead if the checking thread notices that the last life sign of a pool was longer ago than this duration, the pool will be declared dead, and the next alive pool will be chosen as active pool. */ explicit PoolSwitcher(std::string powType, clock::duration checkInterval = std::chrono::seconds(20), clock::duration durUntilDeclaredDead = std::chrono::seconds(60)); ~PoolSwitcher() override; /** * Tries to construct a pool (may fail if the poolImplName doesn't exist in `Registry`) * the new pool's `PoolRecords` will get connected to the total records of this PoolSwitcher */ std::shared_ptr<Pool> tryAddPool(const PoolConstructionArgs &args, const char *poolImplName, const Registry &registry = Registry{}) { std::shared_ptr<Pool> pool = registry.makePool(poolImplName, args); RNR_EXPECTS(pool != nullptr); pool->addRecordsListener(records); pool->setOnStateChangeCv(onStateChange); _pools.lock()->emplace_back(pool); notifyOnPoolsChange(); return pool; } /** * redirects the tryGetWork call to the active pool. * @return nullptr if either the active pool does not have work, or there is no active pool. Valid work otherwise, which can be downcast to the specific work type (e.g. WorkEthash for powType "ethash") */ unique_ptr <Work> tryGetWorkImpl() override; /** * redirects the submitSolution call to the active pool. See implementation for more details */ void submitSolutionImpl(unique_ptr<WorkSolution>) override; /** * obsolete * poolswitcher should be no longer subclass of Pool */ void onDeclaredDead() override {} bool isExpiredJob(const PoolJob &job) override {return true; } void expireJobs() override {} void clearJobs() override {} /***/ /** * amount of pools added to this pool switcher */ size_t poolCount() const; /** * @return const references to the pools with shared ownership. useful for introspection of * pool data (e.g. by ApiServer) */ std::vector<std::shared_ptr<const Pool>> getPoolsData() const { auto pools_lock_guard = _pools.readLock(); const auto &pools = *pools_lock_guard; std::vector<std::shared_ptr<const Pool>> constPools(pools.size()); for (size_t i = 0; i < pools.size(); i++) { constPools[i] = pools[i]; } return constPools; } private: //shutdown related variables std::atomic_bool shutdown {false}; mutable std::mutex mut; //periodic checking void periodicAliveCheck(); std::future<void> periodicAliveCheckTask; clock::duration checkInterval; clock::duration durUntilDeclaredDead; SharedLockGuarded<std::vector<shared_ptr<Pool>>> _pools; std::atomic<bool> pools_changed{false}; /** * after changes of _pools this method shall be called, so that the PoolSwitcher can check pools immediately */ inline void notifyOnPoolsChange() { pools_changed = true; onStateChange->notify_all(); } struct { private: std::shared_ptr<Pool> pool; public: inline std::shared_ptr<Pool> get() const { return std::atomic_load(&pool); } inline void set(std::shared_ptr<Pool> new_pool) { std::atomic_store(&pool, new_pool); } } active_pool; /** * check which pools are still alive and if the active pool is no longer alive, switch active pool. * called by the periodicAliveCheckTask thread */ size_t aliveCheckAndMaybeSwitch(size_t activePoolIndex); }; }
<gh_stars>0 /****************************************************************************//* * Copyright (C) 2022 <NAME> * * 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 MCUTILS_GEO_ECEF_H_ #define MCUTILS_GEO_ECEF_H_ //////////////////////////////////////////////////////////////////////////////// #include <mcutils/defs.h> #include <mcutils/geo/Geo.h> #include <mcutils/math/Angles.h> #include <mcutils/math/Matrix3x3.h> #include <mcutils/math/Quaternion.h> #include <mcutils/math/Vector3.h> //////////////////////////////////////////////////////////////////////////////// namespace mc { /** * @brief Earth-centered, Earth-fixed (ECEF) coordinate system class. * * This class is used to store and calculate location expressed in * Earth-centered, Earth-fixed coordinate system. It also provides functions * to calculate rotation matricies between ECEF and local North-East-Down (NED) * as well as between ECEF and local East-North-Up (ENU) axis systems.<br/> * * The z-axis coincident with the spin axis and positive North, x-axis laying * an equatorial plane and positive through 0 longitude and 0 latitude, * and y-axis completing right-handed system.<br/> * * <h3>Refernces:</h3> * <ul> * <li><NAME>.: A Comparison of Methods Used in Rectangular to Geodetic Coordinate Transformations, 2006</li> * <li><NAME>.: Transformation from spatial to geocentric coordinates, 1976</li> * <li>Zhu J.: Conversion of Earth-centered Earth-fixed coordinates to geodetic coordinates, 1994</li> * </ul> */ class MCUTILSAPI ECEF { public: static const Matrix3x3 _enu2ned; ///< matrix of rotation from ENU to NED static const Matrix3x3 _ned2enu; ///< matrix of rotation from NED to ENU /** @brief Constructor. */ ECEF(); /** * @brief Copy constructor. * * @param ecef object to copy */ ECEF( const ECEF &ecef ); /** * @brief Moving constructor. * * @param ecef object to move */ ECEF( ECEF &&ecef ); /** * @brief Constructor. * * @param a [m] equatorial radius * @param f [-] ellipsoid flattening */ ECEF( double a, double f ); /** @brief Destructor. */ virtual ~ECEF(); /** * @brief Converts geodetic coordinates into ECEF coordinates. * * @param lat [rad] geodetic latitude * @param lon [rad] geodetic longitude * @param alt [m] altitude above mean sea level * @param x [m] resulting ECEF x-coordinate pointer * @param y [m] resulting ECEF y-coordinate pointer * @param z [m] resulting ECEF z-coordinate pointer */ void geo2ecef( double lat, double lon, double alt, double *x, double *y, double *z ) const; /** * @brief Converts geodetic coordinates into ECEF coordinates. * * @param lat [rad] geodetic latitude * @param lon [rad] geodetic longitude * @param alt [m] altitude above mean sea level * @return [m] resulting ECEF coordinates vector */ Vector3 geo2ecef( double lat, double lon, double alt ) const; /** * @brief Converts geodetic coordinates into ECEF coordinates. * * @param pos_geo [m] geodetic coordinates * @return [m] resulting ECEF coordinates vector */ Vector3 geo2ecef( const Geo &pos_geo ) const; /** * @brief Converts geodetic coordinates into ECEF coordinates. * * @param pos_geo [m] geodetic coordinates * @param pos_ecef [m] resulting ECEF coordinates vector pointer */ void geo2ecef( const Geo &pos_geo, Vector3 *pos_ecef ) const; /** * @brief Converts ECEF coordinates into geodetic coordinates. * * @param x [m] ECEF x-coordinate * @param y [m] ECEF y-coordinate * @param z [m] ECEF z-coordinate * @param lat [rad] resulting geodetic latitude pointer * @param lon [rad] resulting geodetic longitude pointer * @param alt [m] resulting altitude above mean sea level pointer */ void ecef2geo( double x, double y, double z, double *lat, double *lon, double *alt ) const; /** * @brief Converts ECEF coordinates into geodetic coordinates. * * @param x [m] ECEF x-coordinate * @param y [m] ECEF y-coordinate * @param z [m] ECEF z-coordinate * @return resulting geodetic coordinates */ Geo ecef2geo( double x, double y, double z ) const; /** * @brief Converts ECEF coordinates into geodetic coordinates. * * @param pos_ecef [m] ECEF coordinates vector * @return resulting geodetic coordinates */ Geo ecef2geo( const Vector3 &pos_ecef ) const; /** * @brief Converts ECEF coordinates into geodetic coordinates. * * @param pos_ecef [m] ECEF coordinates vector * @param pos_geo resulting geodetic coordinates pointer */ void ecef2geo( const Vector3 &pos_ecef, Geo *pos_geo ) const; /** * @brief Calculates coordinates moved by the given offset. * * @param heading [rad] heading * @param offset_x [m] longitudinal offset * @param offset_y [m] lateral offset * @return resulting geodetic coordinates */ Geo getGeoOffset( double heading, double offset_x, double offset_y ) const; inline double getA () const { return _a; } inline double getF () const { return _f; } inline double getB () const { return _b; } inline double getR1 () const { return _r1; } inline double getA2 () const { return _a2; } inline double getB2 () const { return _b2; } inline double getE2 () const { return _e2; } inline double getE () const { return _e; } inline double getEp2 () const { return _ep2; } inline double getEp () const { return _ep; } Angles getAngles_NED ( const Angles &angles_ecef ) const; Angles getAngles_ECEF ( const Angles &angles_ned ) const; Quaternion getNED2BAS ( const Quaternion &att_ecef ) const; Quaternion getECEF2BAS ( const Quaternion &att_ned ) const; inline Geo getPos_Geo () const { return _pos_geo; } inline Vector3 getPos_ECEF () const { return _pos_ecef; } inline Matrix3x3 getENU2NED() const { return _enu2ned; } inline Matrix3x3 getNED2ENU() const { return _ned2enu; } inline Matrix3x3 getENU2ECEF() const { return _enu2ecef; } inline Matrix3x3 getNED2ECEF() const { return _ned2ecef; } inline Matrix3x3 getECEF2ENU() const { return _ecef2enu; } inline Matrix3x3 getECEF2NED() const { return _ecef2ned; } /** */ void setPos_Geo( const Geo &pos_geo ); /** */ void setPos_ECEF( const Vector3 &pos_ecef ); /** @brief Assignment operator. */ ECEF& operator= ( const ECEF &ecef ); /** @brief Moving assignment operator. */ ECEF& operator= ( ECEF &&ecef ); protected: double _a; ///< [m] equatorial radius double _f; ///< [-] ellipsoid flattening double _b; ///< [m] polar radius double _r1; ///< [m] mean radius double _a2; ///< [m^2] equatorial radius squared double _b2; ///< [m^2] polar radius squared double _e2; ///< [-] ellipsoid first eccentricity squared double _e; ///< [-] ellipsoid first eccentricity double _ep2; ///< [-] ellipsoid second eccentricity squared double _ep; ///< [-] ellipsoid second eccentricity Geo _pos_geo; ///< geodetic coordinates Vector3 _pos_ecef; ///< [m] coordinates vector expressed in ECEF Matrix3x3 _enu2ecef; ///< rotation matrix from ENU to ECEF Matrix3x3 _ned2ecef; ///< rotation matrix from NED to ECEF Matrix3x3 _ecef2enu; ///< rotation matrix from ECEF to ENU Matrix3x3 _ecef2ned; ///< rotation matrix from ECEF to NED virtual void update(); private: void copyData( const ECEF &ecef ); void copyParams( const ECEF &ecef ); /** * @brief Updates rotation matrices due to position. * * This function updates rotation matrices due to current ECEF coordinates. */ void updateMatrices(); }; } // namespace mc //////////////////////////////////////////////////////////////////////////////// #endif // MCUTILS_GEO_ECEF_H_
<gh_stars>1-10 class CPythonDocTemplate; // // Document Template Object. // class PYW_EXPORT PyCDocTemplate : public PyCCmdTarget { protected: virtual void cleanup(); PyCDocTemplate(); ~PyCDocTemplate(); public: static CPythonDocTemplate *GetTemplate(PyObject *self); static BOOL RemoveDocTemplateFromApp(CDocTemplate *pTemplate); static PyObject *create(PyObject *self, PyObject *args); static PyObject *DoCreateDocHelper(PyObject *self, PyObject *args, CRuntimeClass *pClass, ui_type_CObject &new_type); static PyObject *DoCreateDoc(PyObject *self, PyObject *args); static PyObject *AddDocTemplate(PyObject *self, PyObject *args); static PyObject *SetDocStrings(PyObject *self, PyObject *args); static PyObject *SetContainerInfo(PyObject *self, PyObject *args); static PyObject *CreateNewFrame(PyObject *self, PyObject *args); static PyObject *OpenDocumentFile(PyObject *self, PyObject *args); static PyObject *GetResourceID(PyObject *self, PyObject *args); static PyObject *GetSharedMenu(PyObject *self, PyObject *args); static PyObject *GetDocumentList(PyObject *self, PyObject *args); static PyObject *FindOpenDocument(PyObject *self, PyObject *args); static PyObject *GetDocString(PyObject *self, PyObject *args); static PyObject *InitialUpdateFrame(PyObject *self, PyObject *args); static ui_type_CObject type; MAKE_PY_CTOR(PyCDocTemplate) }; // The MFC derived class. class PYW_EXPORT CPythonDocTemplate : public CMultiDocTemplate { friend class PyCDocTemplate; public: CPythonDocTemplate(UINT idResource); virtual ~CPythonDocTemplate(); virtual CDocument *CreateNewDocument(); virtual CDocument *OpenDocumentFile(LPCTSTR lpszPathName, BOOL bMakeVisible = TRUE); virtual CFrameWnd *CreateNewFrame(CDocument *pDoc, CFrameWnd *pOther); virtual void InitialUpdateFrame(CFrameWnd *pFrame, CDocument *pDoc, BOOL bMakeVisible = TRUE); #ifndef _MAC virtual CDocTemplate::Confidence MatchDocType(LPCTSTR lpszPathName, CDocument *&rpDocMatch); #else virtual CDocTemplate::Confidence MatchDocType(LPCTSTR lpszPathName, DWORD dwFileType, CDocument *&rpDocMatch); #endif UINT GetResourceID() { return m_nIDResource; } };
#ifndef _TEXT_BITS_H_ #define _TEXT_BITS_H_ #include "momusys.h" #include "text_defs.h" /* struct for counting bits */ typedef struct { Int Y; Int C; Int vec; Int CBPY; Int CBPC; Int MCBPC; Int MODB; Int CBPB; Int MBTYPE; Int COD; Int MB_Mode; Int header; Int DQUANT; Int total; Int no_inter; Int no_inter4v; Int no_intra; Int no_GMC; /* NTT for GMC coding */ Int ACpred_flag; Int G; /* HYUNDAI : (Grayscale) */ Int CODA; /* HYUNDAI : (Grayscale) */ Int CBPA; /* HYUNDAI : (Grayscale) */ Int g_ACpred_flag; /* HYUNDAI : (Grayscale) */ Int no_field; Int no_skipped; Int no_Pskip; Int no_noDCT; Int fieldDCT; Int interlaced; Int Btype[7]; Int Nmvs[3]; } Bits; #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ Void MB_CodeCoeff _P_(( Bits *bits, Int *qcoeff, Int Mode, Int CBP, Int ncoeffs, Int intra_dcpred_disable, Image *DCbitstream, Image *bitstream, Int transp_pattern[], Int direction[], Int error_res_disable, Int reverse_vlc, Int switched, Int alternate_scan )); void Bits_Reset _P_(( Bits *bits )); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _TEXT_BITS_H_ */
#ifndef CLIENT_H #define CLIENT_H #include <string> #ifdef __linux__ #include <netinet/in.h> #elif _WIN32 #include <windows.h> #endif using namespace std; class Client { public: Client(const string &address = "127.0.0.1", unsigned short port = 6666); ~Client(); void sendMessage(const string &message); void sendFile(const string &fileName); private: struct sockaddr_in client; int socketDescriptor = -1; }; #endif // CLIENT_H
/** Onion HTTP server library Copyright (C) 2010-2018 <NAME> and others This library is free software; you can redistribute it and/or modify it under the terms of, at your choice: a. the Apache License Version 2.0. b. the GNU General Public License as published by the Free Software Foundation; either version 2.0 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 both licenses, if not see <http://www.gnu.org/licenses/> and <http://www.apache.org/licenses/LICENSE-2.0>. */ #include <signal.h> #include <onion/log.h> #include <onion/onion.h> #include <onion/shortcuts.h> /** * @short This handler just answers the content of the POST parameter "text" * * It checks if its a HEAD in which case it writes the headers, and if not just printfs the * user data. */ onion_connection_status post_data(void *_, onion_request * req, onion_response * res) { if (onion_request_get_flags(req) & OR_HEAD) { onion_response_write_headers(res); return OCS_PROCESSED; } const char *user_data = onion_request_get_post(req, "text"); onion_response_printf(res, "The user wrote: %s", user_data); return OCS_PROCESSED; } onion *o = NULL; void onexit(int _) { ONION_INFO("Exit"); if (o) onion_listen_stop(o); } /** * This example creates a onion server and adds two urls: the base one is a static content with a form, and the * "data" URL is the post_data handler. */ int main(int argc, char **argv) { o = onion_new(O_ONE_LOOP); onion_url *urls = onion_root_url(o); onion_url_add_static(urls, "", "<html>\n" "<head>\n" " <title>Simple post example</title>\n" "</head>\n" "\n" "Write something: \n" "<form method=\"POST\" action=\"data\">\n" "<input type=\"text\" name=\"text\">\n" "<input type=\"submit\">\n" "</form>\n" "\n" "</html>\n", HTTP_OK); onion_url_add(urls, "data", post_data); signal(SIGTERM, onexit); signal(SIGINT, onexit); onion_listen(o); onion_free(o); return 0; }
<reponame>Rishav-12/stats-with-c // This program calculates the roots of a quadratic equation ax^2 + bx + c = 0 #include <stdio.h> #include <math.h> int main(void) { float a, b, c; printf("Enter the coefficients a, b, c\n"); scanf("%f %f %f", &a, &b, &c); float d = pow(b*b - 4*a*c, 0.5); float root1 = (-b + d) / (2*a); float root2 = (-b - d) / (2*a); printf("The roots of the equation are %f, %f\n", root1, root2); return 0; }
<reponame>NonupleThoughts/Algorithm #ifndef _mergersort_h #define _mergersort_h void Divide(float *dataset, int first, int last, float *sortset); void Merge(float *dataset,int first, int mid, int last, float *sortset); void MergeSort(float *dataset, int size); #endif
<reponame>christopherco/rpi-iotcore // // Copyright (c) Microsoft Corporation. All rights reserved. // // Module Name: // // Mailbox.c // // Abstract: // // Mailbox Interface. // #include "precomp.h" #include "trace.h" #include "Mailbox.tmh" #include "register.h" #include "device.h" #include "mailbox.h" RPIQ_PAGED_SEGMENT_BEGIN /*++ Routine Description: Initialize Mailbox. Arguments: Device - A handle to a framework device object. Return Value: NTSTATUS --*/ _Use_decl_annotations_ NTSTATUS RpiqMailboxInit ( WDFDEVICE Device ) { NTSTATUS status; WDF_OBJECT_ATTRIBUTES attributes; DEVICE_CONTEXT *deviceContextPtr = RpiqGetContext(Device); PAGED_CODE(); WDF_OBJECT_ATTRIBUTES_INIT(&attributes); attributes.ParentObject = Device; // Serialize write to mailbox status = WdfWaitLockCreate( &attributes, &deviceContextPtr->WriteLock); if (!NT_SUCCESS(status)) { RPIQ_LOG_ERROR( "Failed to allocate lock resources for mailbox status = %!STATUS!", status); return status; } return status; } /*++ Routine Description: Write to mail box in a serialize manner Arguments: DeviceContextPtr - Pointer to device context Channel - Mailbox Channel Value - Value to be written Request - Optional WDF request object associated with this mailbox transaction Return Value: NTSTATUS --*/ _Use_decl_annotations_ NTSTATUS RpiqMailboxWrite ( DEVICE_CONTEXT* DeviceContextPtr, ULONG Channel, ULONG Value, WDFREQUEST Request ) { NTSTATUS status; ULONG count = 0, reg; LARGE_INTEGER timeOut = { 0 }; PAGED_CODE(); WdfWaitLockAcquire(DeviceContextPtr->WriteLock, NULL); timeOut.QuadPart = WDF_REL_TIMEOUT_IN_MS(1); reg = READ_REGISTER_NOFENCE_ULONG(&DeviceContextPtr->Mailbox->Status); // Poll until mailbox is available. It doesn't seem like // the mailbox is full often so polling is sufficient for now // rather than enable mailbox empty interrupt while (reg & MAILBOX_STATUS_FULL) { if (count > MAX_POLL) { RPIQ_LOG_ERROR( "Exit Fail Status 0x%08x", DeviceContextPtr->Mailbox->Status); status = STATUS_IO_TIMEOUT; goto End; } KeDelayExecutionThread(KernelMode, FALSE, &timeOut); reg = READ_REGISTER_NOFENCE_ULONG(&DeviceContextPtr->Mailbox->Status); ++count; } if (Request) { status = WdfRequestForwardToIoQueue( Request, DeviceContextPtr->ChannelQueue[Channel]); if (!NT_SUCCESS(status)) { RPIQ_LOG_ERROR( "WdfRequestForwardToIoQueue failed ( %!STATUS!)", status); goto End; } } WRITE_REGISTER_NOFENCE_ULONG( &DeviceContextPtr->Mailbox->Write, (Value & ~MAILBOX_CHANNEL_MASK) | Channel); status = STATUS_SUCCESS; End: WdfWaitLockRelease(DeviceContextPtr->WriteLock); return status; } /*++ Routine Description: Process mailbox property request. Arguments: DeviceContextPtr - Pointer to device context DataInPtr - Pointer to property data DataSize - Data size for input and output is the expected to be the same Request - WDF request object associated with this mailbox transaction Return Value: NTSTATUS --*/ _Use_decl_annotations_ NTSTATUS RpiqMailboxProperty ( DEVICE_CONTEXT* DeviceContextPtr, const VOID* DataInPtr, ULONG DataSize, ULONG Channel, WDFREQUEST Request ) { NTSTATUS status; PHYSICAL_ADDRESS highAddress; PHYSICAL_ADDRESS lowAddress = { 0 }; PHYSICAL_ADDRESS boundaryAddress = { 0 }; PHYSICAL_ADDRESS addrProperty; RPIQ_REQUEST_CONTEXT* requestContextPtr; PAGED_CODE(); highAddress.QuadPart = HEX_1_G; if (DataInPtr == NULL || DataSize < sizeof(MAILBOX_HEADER)) { status = STATUS_INVALID_PARAMETER; goto End; } { WDF_OBJECT_ATTRIBUTES wdfObjectAttributes; WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE( &wdfObjectAttributes, RPIQ_REQUEST_CONTEXT); wdfObjectAttributes.EvtCleanupCallback = RpiqRequestContextCleanup; status = WdfObjectAllocateContext( Request, &wdfObjectAttributes, &requestContextPtr); if (!NT_SUCCESS(status)) { RPIQ_LOG_WARNING( "WdfObjectAllocateContext() failed %!STATUS!)", status); goto End; } } // Firmware expects mailbox request to be in contiguous memory requestContextPtr->PropertyMemory = MmAllocateContiguousNodeMemory( DataSize, lowAddress, highAddress, boundaryAddress, PAGE_NOCACHE | PAGE_READWRITE, MM_ANY_NODE_OK); if (requestContextPtr->PropertyMemory == NULL) { RPIQ_LOG_ERROR("RpiqMailboxProperty fail to allocate memory"); status = STATUS_INSUFFICIENT_RESOURCES; goto End; } requestContextPtr->PropertyMemorySize = DataSize; addrProperty = MmGetPhysicalAddress(requestContextPtr->PropertyMemory); RtlCopyMemory(requestContextPtr->PropertyMemory, DataInPtr, DataSize); status = RpiqMailboxWrite( DeviceContextPtr, Channel, addrProperty.LowPart + OFFSET_DIRECT_SDRAM, Request); if (!NT_SUCCESS(status)) { RPIQ_LOG_ERROR("RpiqMailboxWrite failed %!STATUS!", status); goto End; } End: return status; } RPIQ_PAGED_SEGMENT_END RPIQ_NONPAGED_SEGMENT_BEGIN /*++ Routine Description: RpiqRequestContextCleanup would perform cleanup when request object is delete. Arguments: WdfObject - A handle to a framework object in this case a WDFRequest Return Value: VOID --*/ _Use_decl_annotations_ VOID RpiqRequestContextCleanup ( WDFOBJECT WdfObject ) { RPIQ_REQUEST_CONTEXT* requestContextPtr = RpiqGetRequestContext(WdfObject); if (requestContextPtr->PropertyMemory) { MmFreeContiguousMemory(requestContextPtr->PropertyMemory); } } RPIQ_NONPAGED_SEGMENT_END
<reponame>liaman/SLIM-release-apps-public<gh_stars>1-10 /* * CARP/Kaczmarz sweep on diagonally banded matrix. The essential loop is: * * for each row i * x = x + w*(b(i) - A(i,:)*x)*A(i,:)' * end * * The matrix is given in band storage format, where each row (stored * contiguously in memory) of the array R stores a diagonal of the matrix with * offset idx(j), such that * * A(i,i+idx(j)) = R(i,j) * * use (from MATLAB): * y = sweepR_mex(R,idx,x,b,w,dir) * * R - matrix of diagonals of matrix A * idx - offsets of diagonals * x - initial guess * b - right hand side (source) * w - relaxation parameter (0 <= w <= 2) * dir - if dir > 0, go through matrix rows in ascending order. * if dir < 0, go through matrix rows in descending order. * n_threads - OPTIONAL argument to control the number of execution * threads solving CARP blocks in parallel. The number of threads can also * be defined via an environment variable (OMP_NUM_THREADS), but this * optional argument takes precedence. The default number of threads is * one. Take care if using more than one MATLAB worker per node: each * MATLAB worker will use OMP_NUM_THREADS, so if there are four workers on * a node, there will be 4 x OMP_NUM_THREADS parallel CARP sweeps. * * Author: <NAME>, <NAME> * Seismic Laboratory for Imaging and Modeling * Department of Earth, Ocean, and Atmosperic Sciences * The University of British Columbia * * Date: July, 2014 * You may use this code only under the conditions and terms of the * license contained in the file LICENSE provided with this source * code. If you do not agree to these terms you may not use this * software. */ #include <stdlib.h> /* for getenv */ #include <stddef.h> /* for size_t type */ #include <string.h> /* for memcpy */ #include <pthread.h> /* for threading */ /* The following section allows this file to compile on Mac OS X 10.8.5. Pass * the flag -DARCH_MACI64 to the compiler to activate it. */ #ifdef ARCH_MACI64 #include "pthread_barrier.h" #include <mach/error.h> typedef wchar_t char16_t; #else /* not ARCH_MACI64 */ #include <error.h> #endif /* ARCH_MACI64 */ #include <math.h> #include <mex.h> #include <matrix.h> #include <blas.h> struct copy_init_guess_data_t { double *copy_src_real, *copy_dst_real; double *copy_src_imag, *copy_dst_imag; long n_to_copy; }; struct sweep_data_t { long start_row, end_row, ncol, ny, nx, haloWidth, main_diagonal_offset; double *Rr, *Ri, *yr, *yi, *br, *bi; long *idx; double w; int dir; }; struct average_data_t { double *copy_src_real, *copy_dst_real; double *copy_src_imag, *copy_dst_imag; double *halo_1_real, *halo_2_real; double *halo_1_imag, *halo_2_imag; double *halo_dst_real, *halo_dst_imag; long n_to_copy, n_in_halo; }; struct thread_data_t { struct copy_init_guess_data_t copy_init_guess_data; struct sweep_data_t sweep_data; struct average_data_t average_data; pthread_barrier_t *barrier; }; void *do_sweep(void *thread_args_void) { struct sweep_data_t *thread_args; /* Variables contained in thread_args_void struct */ long start_row, end_row, haloWidth, ncol, ny, nx; /* Rr and Ri are pointers to short fat ncol-by-N matrices */ double *Rr, *Ri, *yr, *yi, *br, *bi; long *idx; double w; int dir; /* Temporary storage variables */ double cr = 0, ci = 0; long offset, main_diagonal_offset; /* Assign local pointers to data locations in shared memory */ thread_args = (struct sweep_data_t *) thread_args_void; start_row = thread_args->start_row; end_row = thread_args->end_row; ncol = thread_args->ncol; ny = thread_args->ny; nx = thread_args->nx; haloWidth = thread_args->haloWidth; main_diagonal_offset = thread_args->main_diagonal_offset; Rr = thread_args->Rr; Ri = thread_args->Ri; idx = thread_args->idx; yr = thread_args->yr; yi = thread_args->yi; br = thread_args->br; bi = thread_args->bi; w = thread_args->w; dir = thread_args->dir; offset = (start_row == 0 ? 0 : haloWidth - main_diagonal_offset); /* Kaczmarz sweep on one row block */ for(long i = (dir > 0 ? start_row : end_row-1); dir > 0 ? i<end_row : i>=start_row; dir > 0 ? i++ : i--) { if (0 <= i + main_diagonal_offset && i + main_diagonal_offset < nx){ cr = br[i + main_diagonal_offset]; ci = bi[i + main_diagonal_offset]; } else{ //error(1,0,"Discovery of whether the iterate vector is haloed failed."); } /* First loop over non-zero row elements calculates inner product * of matrix row and CARP iterate */ for(long j=0, k; j<ncol;j++){ /* i + idx[j] is the column index for the full Helmholtz matrix. * k is the index into the vector representing the CARP iterate * of the given block. */ k = i + idx[j] - start_row + offset; if(0<=k && k<ny){ cr -= Rr[i*ncol + j]*yr[k] - Ri[i*ncol + j]*yi[k]; ci -= Rr[i*ncol + j]*yi[k] + Ri[i*ncol + j]*yr[k]; } } /* Second loop over non-zero row elements updates CARP iterate */ cr *= w; ci *= w; for(long j=0, k; j<ncol;j++){ k = i + idx[j] - start_row + offset; if(0<=k && k<ny){ yr[k] += cr*Rr[i*ncol + j] + ci*Ri[i*ncol + j]; yi[k] += -cr*Ri[i*ncol + j] + ci*Rr[i*ncol + j]; } } } return NULL; } void *average_halos(void *thread_args_void) { struct average_data_t *thread_args; double *copy_src_real, *copy_dst_real; double *copy_src_imag, *copy_dst_imag; double *halo_1_real, *halo_2_real; double *halo_1_imag, *halo_2_imag; double *halo_dst_real, *halo_dst_imag; size_t n_to_copy, n_in_halo; /* Assign local pointer to data locations in shared memory */ thread_args = (struct average_data_t *) thread_args_void; copy_src_real = thread_args->copy_src_real; copy_dst_real = thread_args->copy_dst_real; copy_src_imag = thread_args->copy_src_imag; copy_dst_imag = thread_args->copy_dst_imag; n_to_copy = thread_args->n_to_copy; halo_1_real = thread_args->halo_1_real; halo_2_real = thread_args->halo_2_real; halo_dst_real = thread_args->halo_dst_real; halo_1_imag = thread_args->halo_1_imag; halo_2_imag = thread_args->halo_2_imag; halo_dst_imag = thread_args->halo_dst_imag; n_in_halo = thread_args->n_in_halo; /* Copy the non-halo parts of the domain block directly to output array */ memcpy((void *)copy_dst_real, (void *)copy_src_real, sizeof(double)*n_to_copy); memcpy((void *)copy_dst_imag, (void *)copy_src_imag, sizeof(double)*n_to_copy); /* Average the halo parts of the domain block and copy to output array. * NOTE: this assumes domain blocks overlap only with their nearest * neighbour segments. */ for (long i = 0; i < n_in_halo; i++){ halo_dst_real[i] = (halo_1_real[i] + halo_2_real[i]) / 2; halo_dst_imag[i] = (halo_1_imag[i] + halo_2_imag[i]) / 2; } return NULL; } void *sweep_and_average(void *thread_data_void) { struct thread_data_t *thread_data = (struct thread_data_t *) thread_data_void; /* Copy the initial guess into the working arrays */ memcpy((void *)thread_data->copy_init_guess_data.copy_dst_real, (void *)thread_data->copy_init_guess_data.copy_src_real, sizeof(double)*thread_data->copy_init_guess_data.n_to_copy); memcpy((void *)thread_data->copy_init_guess_data.copy_dst_imag, (void *)thread_data->copy_init_guess_data.copy_src_imag, sizeof(double)*thread_data->copy_init_guess_data.n_to_copy); do_sweep((void *) &(thread_data->sweep_data)); pthread_barrier_wait(thread_data->barrier); average_halos((void *) &(thread_data->average_data)); return NULL; } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* structs to hold all arguments to each thread in one variable */ struct sweep_data_t **thread_args_sweep = NULL; struct average_data_t **thread_args_average = NULL; struct thread_data_t **thread_data = NULL; struct copy_init_guess_data_t **copy_init_guess_data = NULL; pthread_barrier_t barrier_after_sweep_before_halo_average; mwSize ncol, nx; ptrdiff_t ncolBlas, idxIncBlas = 1, maxIdxLoc = 0; mwSize haloWidth; mwSize n_threads = 1; char *n_threads_str = NULL; double *Rr,*Ri,*idxd = NULL,*xr,*xi,*br,*bi,*yr,*yi; long *idx = NULL; double w = 0; int dir = 1; mwSize N=1, numGridPointsPerBlock, main_diagonal_offset; /* Flags that are set if memory is allocated within the MEX file */ int Ri_alloc=0, xi_alloc=0, bi_alloc=0; /* a return code flag and segment demarcation arrays */ mwSize i_thread; mwSize *seg_bounds_hi, *seg_bounds_mid, *seg_bounds_row, *seg_bounds_lo; /* Threading variables */ pthread_t *threadIDs = NULL; pthread_attr_t attr; /* Arrays to hold (overlapping) segments of yr and yi, a pair for each * thread */ double **yr_seg = NULL, **yi_seg = NULL; /* Allow worker threads to join back to main thread once they are done */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); /* Read input arguments; initialize complex part to zero if input is real. */ N = mxGetN(prhs[0]); ncol = mxGetM(prhs[0]); ncolBlas = (ptrdiff_t)ncol; Rr = mxGetPr(prhs[0]); if(mxIsComplex(prhs[0])){ Ri = mxGetPi(prhs[0]); } else{ Ri = mxCalloc(N*ncol,sizeof(double)); Ri_alloc = 1; } idxd = mxGetPr(prhs[1]); nx = mxGetM(prhs[2]); xr = mxGetPr(prhs[2]); if(mxIsComplex(prhs[2])){ xi = mxGetPi(prhs[2]); } else{ xi = mxCalloc(nx,sizeof(double)); xi_alloc = 1; } br = mxGetPr(prhs[3]); if(mxIsComplex(prhs[3])){ bi = mxGetPi(prhs[3]); } else{ bi = mxCalloc(nx,sizeof(double)); bi_alloc = 1; } if (mxGetM(prhs[3]) != nx){ mexPrintf('%d %d \n',mxGetM(prhs[3]),nx); mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:NumElements", "The number of elements in the iterate and right hand side vectors must be equal."); } w = mxGetScalar(prhs[4]); dir = lrint(mxGetScalar(prhs[5])); /* The default value for the number of threads can be overridden by an * environment variable. */ n_threads_str = getenv("OMP_NUM_THREADS"); if (n_threads_str == NULL){ n_threads = 1; } else{ n_threads = strtol(n_threads_str, NULL, 10); if(n_threads < 1){ n_threads = 1; } } /* The environment variable can in turn be overridden by an optional * argument to the mexFunction. */ if (nrhs >= 7){ if(1 <= lrint(mxGetScalar(prhs[6]))){ n_threads = lrint(mxGetScalar(prhs[6])); } } /* Allocate the final output vector */ plhs[0] = mxCreateDoubleMatrix(nx, 1, mxCOMPLEX); yr = mxGetPr(plhs[0]); yi = mxGetPi(plhs[0]); /* Check to make sure memory was allocated correctly */ if (Rr==NULL || Ri==NULL || idxd==NULL || xr==NULL || xi==NULL || br==NULL || bi==NULL || yr==NULL || yi==NULL){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:OutOfMemory", "Could not allocate memory for main computational variables."); } if ((idx = (long *) mxCalloc(ncol, sizeof(long))) == NULL){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:OutOfMemory", "Could not allocate memory for main computational variables."); } for (mwSize i=0; i < ncol; i++){ idx[i] = lrint(idxd[i]); } /* Compute (half) halo width. Remember that BLAS routines like idamax * return FORTRAN-style indices. */ maxIdxLoc = idamax_(&ncolBlas, idxd, &idxIncBlas) - 1; haloWidth = (mwSize)labs(idx[maxIdxLoc]); /* Partition the iterate vector into blocks. Note that the below * partitioning scheme is slighlty different from that in pCARPCG.m in this * directory. The partitioning scheme of pCARPCG corresponds to * distributing a three dimensional array with dimensions given by n * according to Matlab's codistributor1d.defaultPartition(n(3)), and then * vectorizing it. The partition scheme of the present file instead uses * Matlab's codistributor1d.defaultPartion(prod(n)). In other words, * pCARPCG divides the iterate into blocks along the slow dimension, * whereas sweepR_mex.c does not take dimensionality into account, only the * total number of gridpoints. This is done to avoid needing an extra input * parameter with the the system dimensions. The seg_bounds_hi, _lo and * _mid arrays contain indices into non-haloed vectors, while the * seg_bounds_row array contains indices to the rows of the system matrix. * * yr_seg[i_thread-1] overlap yr_seg[i_thread] * ------------------------|-----|-----|------------------------------- * .----------------^ | ^-------------------. * seg_bounds_lo[i_thread], seg_bounds_mid[i_thread], seg_bounds_hi[i_thread] */ numGridPointsPerBlock = N / n_threads; seg_bounds_hi = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize)); seg_bounds_mid = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize)); seg_bounds_lo = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize)); seg_bounds_row = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize)); if (N == nx){ main_diagonal_offset = 0; } else{ /* The vector is haloed. We are only able to correctly process matrices * with a non-zero main diagonal and symmetric off-main diagonal offsets. */ if (ncol % 2 != 1){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:EvenNumberOfDiags", "Input iterate vector appears to be haloed but there is an even number of non-zero diagonals in the system matrix."); } main_diagonal_offset = idx[ncol/2]; for (mwSize i = 1; i <= ncol/2; i++){ if (idx[ncol/2 + i] - main_diagonal_offset != -(idx[ncol/2 - i] - main_diagonal_offset)){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:DiagsNotSymmetric", "Input iterate vector appears to be haloed but the pattern of non-zero diagonals in the system matrix is not symmetric."); } } } for (i_thread=0; i_thread<n_threads; i_thread++){ /* First domain block */ if (i_thread==0){ seg_bounds_hi[i_thread] = 0; seg_bounds_mid[i_thread] = 0; seg_bounds_row[i_thread] = 0; seg_bounds_lo[i_thread] = 0; } /* Other domain blocks */ else { if (i_thread <= N % n_threads) { seg_bounds_mid[i_thread] = (numGridPointsPerBlock+1)*i_thread + main_diagonal_offset; seg_bounds_row[i_thread] = (numGridPointsPerBlock+1)*i_thread; seg_bounds_hi[i_thread] = (numGridPointsPerBlock+1)*i_thread + haloWidth + main_diagonal_offset; seg_bounds_lo[i_thread] = (numGridPointsPerBlock+1)*i_thread - haloWidth + main_diagonal_offset; } else{ seg_bounds_mid[i_thread] = (N % n_threads) + numGridPointsPerBlock*i_thread + main_diagonal_offset; seg_bounds_row[i_thread] = (N % n_threads) + numGridPointsPerBlock*i_thread; seg_bounds_hi[i_thread] = (N % n_threads) + numGridPointsPerBlock*i_thread + haloWidth + main_diagonal_offset; seg_bounds_lo[i_thread] = (N % n_threads) + numGridPointsPerBlock*i_thread - haloWidth + main_diagonal_offset; } /* Check that halos do not overlap each other */ if (seg_bounds_lo[i_thread] < seg_bounds_hi[i_thread-1]){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:TooManyThreads", "Too many threads; non-adjacent domain blocks share nearest-neighbour grid points."); } } } seg_bounds_lo[n_threads] = nx; seg_bounds_hi[n_threads] = nx; seg_bounds_mid[n_threads] = nx; seg_bounds_row[n_threads] = N; /* Allocate pointers to segments, to thread arguments and thread IDs */ thread_args_sweep = (struct sweep_data_t **)mxCalloc(n_threads, sizeof(struct sweep_data_t *)); if (n_threads > 1) { /* Set up a barrier for synchronization of all threads save the master that * executes mexFunction. Note that strictly speaking, only threads working * on domain blocks that share halos need to synchronize with each other. * */ if (pthread_barrier_init(&barrier_after_sweep_before_halo_average, NULL, n_threads)){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreads", "Could not initialize pthread barrier."); } thread_data = (struct thread_data_t **)mxCalloc(n_threads, sizeof(struct thread_data_t *)); thread_args_average = (struct average_data_t **)mxCalloc(n_threads, sizeof(struct average_data_t *)); copy_init_guess_data = (struct copy_init_guess_data_t **)mxCalloc(n_threads, sizeof(struct copy_init_guess_data_t *)); yr_seg = (double **)mxCalloc(n_threads,sizeof(double *)); yi_seg = (double **)mxCalloc(n_threads,sizeof(double *)); threadIDs = (pthread_t *)mxCalloc(n_threads,sizeof(pthread_t)); } for (i_thread=0; i_thread<n_threads; i_thread++){ /* Allocate the segments for each thread */ if (n_threads > 1) { yr_seg[i_thread] = (double *)mxCalloc((seg_bounds_hi[i_thread+1]-seg_bounds_lo[i_thread]),sizeof(double)); yi_seg[i_thread] = (double *)mxCalloc((seg_bounds_hi[i_thread+1]-seg_bounds_lo[i_thread]),sizeof(double)); /* Check that segments were allocated correctly */ if (yr_seg[i_thread]==NULL || yi_seg[i_thread]==NULL){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreadsOutOfMemory", "Could not allocate memory for thread computational variables."); } copy_init_guess_data[i_thread] = (struct copy_init_guess_data_t *)mxCalloc(1,sizeof(struct copy_init_guess_data_t)); copy_init_guess_data[i_thread]->copy_src_real = &xr[seg_bounds_lo[i_thread]]; copy_init_guess_data[i_thread]->copy_src_imag = &xi[seg_bounds_lo[i_thread]]; copy_init_guess_data[i_thread]->copy_dst_real = yr_seg[i_thread]; copy_init_guess_data[i_thread]->copy_dst_imag = yi_seg[i_thread]; copy_init_guess_data[i_thread]->n_to_copy = (size_t) (seg_bounds_hi[i_thread+1] - seg_bounds_lo[i_thread]); } /* Set thread arguments */ thread_args_sweep[i_thread] = (struct sweep_data_t *)mxCalloc(1,sizeof(struct sweep_data_t)); thread_args_sweep[i_thread]->start_row = seg_bounds_row[i_thread]; thread_args_sweep[i_thread]->end_row = seg_bounds_row[i_thread+1]; thread_args_sweep[i_thread]->ncol = ncol; thread_args_sweep[i_thread]->ny = seg_bounds_hi[i_thread+1]-seg_bounds_lo[i_thread]; thread_args_sweep[i_thread]->nx = nx; thread_args_sweep[i_thread]->haloWidth = haloWidth*(i_thread ? 1 : 0); thread_args_sweep[i_thread]->main_diagonal_offset = main_diagonal_offset; thread_args_sweep[i_thread]->Rr = Rr; thread_args_sweep[i_thread]->Ri = Ri; thread_args_sweep[i_thread]->idx = idx; if (n_threads > 1){ thread_args_sweep[i_thread]->yr = yr_seg[i_thread]; thread_args_sweep[i_thread]->yi = yi_seg[i_thread]; } else{ thread_args_sweep[i_thread]->yr = yr; thread_args_sweep[i_thread]->yi = yi; } thread_args_sweep[i_thread]->br = br; thread_args_sweep[i_thread]->bi = bi; thread_args_sweep[i_thread]->w = w; thread_args_sweep[i_thread]->dir = dir; if (n_threads > 1){ /* Set the arguments for the averaging threads. Note that each * thread is responsible for averaging the low end of its address * range. The middle of its address range is copied, while the high * end of its address range is left for the next thread. */ thread_args_average[i_thread] = (struct average_data_t *)mxCalloc(1,sizeof(struct average_data_t)); thread_args_average[i_thread]->copy_src_real = &(yr_seg[i_thread][seg_bounds_hi[i_thread] - seg_bounds_lo[i_thread]]); thread_args_average[i_thread]->copy_dst_real = &(yr[seg_bounds_hi[i_thread]]); thread_args_average[i_thread]->copy_src_imag = &(yi_seg[i_thread][seg_bounds_hi[i_thread] - seg_bounds_lo[i_thread]]); thread_args_average[i_thread]->copy_dst_imag = &(yi[seg_bounds_hi[i_thread]]); thread_args_average[i_thread]->n_to_copy = (size_t) (seg_bounds_lo[i_thread+1] - seg_bounds_hi[i_thread]); thread_args_average[i_thread]->halo_1_real = &(yr_seg[i_thread-1 >= 0 ? i_thread-1 : 0][seg_bounds_lo[i_thread] - seg_bounds_lo[i_thread-1 >= 0 ? i_thread-1 : 0]]); thread_args_average[i_thread]->halo_2_real = yr_seg[i_thread]; thread_args_average[i_thread]->halo_dst_real = &(yr[seg_bounds_lo[i_thread]]); thread_args_average[i_thread]->halo_1_imag = &(yi_seg[i_thread-1 >= 0 ? i_thread-1 : 0][seg_bounds_lo[i_thread] - seg_bounds_lo[i_thread-1 >= 0 ? i_thread-1 : 0]]); thread_args_average[i_thread]->halo_2_imag = yi_seg[i_thread]; thread_args_average[i_thread]->halo_dst_imag = &(yi[seg_bounds_lo[i_thread]]); thread_args_average[i_thread]->n_in_halo = (size_t) (seg_bounds_hi[i_thread] - seg_bounds_lo[i_thread]); thread_data[i_thread] = (struct thread_data_t *)mxCalloc(1,sizeof(struct thread_data_t)); thread_data[i_thread]->copy_init_guess_data = *copy_init_guess_data[i_thread]; thread_data[i_thread]->sweep_data = *thread_args_sweep[i_thread]; thread_data[i_thread]->average_data = *thread_args_average[i_thread]; thread_data[i_thread]->barrier = &barrier_after_sweep_before_halo_average; } } if (n_threads == 1) { /* Set the initial guess directly in the output array too */ memcpy((void *)yr, (void *)xr, sizeof(double)*nx); memcpy((void *)yi, (void *)xi, sizeof(double)*nx); do_sweep((void *)thread_args_sweep[0]); } else{ /* Sweep and average, in separate worker threads */ for (i_thread=0; i_thread<n_threads; i_thread++){ if (pthread_create(&threadIDs[i_thread], &attr, sweep_and_average, (void *)thread_data[i_thread])){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreadCreate", "pthread_create returned non-zero."); } } /* Wait for threads to finish */ for (i_thread=0; i_thread<n_threads; i_thread++){ if (pthread_join(threadIDs[i_thread], NULL)){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreadCreate", "pthread_join returned non-zero."); } } } /* Free memory if it was allocated within the MEX file. */ if (Ri_alloc){ mxFree(Ri); } if (xi_alloc){ mxFree(xi); } if (bi_alloc){ mxFree(bi); } mxFree(seg_bounds_hi); mxFree(seg_bounds_mid); mxFree(seg_bounds_row); mxFree(seg_bounds_lo); if (n_threads > 1) { mxFree(threadIDs); } for (i_thread=0; i_thread<n_threads; i_thread++){ mxFree(thread_args_sweep[i_thread]); if (n_threads > 1){ mxFree(thread_args_average[i_thread]); mxFree(thread_data[i_thread]); mxFree(copy_init_guess_data[i_thread]); mxFree(yr_seg[i_thread]); mxFree(yi_seg[i_thread]); } } if (n_threads > 1){ pthread_barrier_destroy(&barrier_after_sweep_before_halo_average); mxFree(thread_args_average); mxFree(thread_data); mxFree(copy_init_guess_data); mxFree(yr_seg); mxFree(yi_seg); } mxFree(idx); mxFree(thread_args_sweep); pthread_attr_destroy(&attr); /* Don't think I need pthread_exit() here, because pthread_join is called above */ return; }
// // OLDGLView.h // OpenGLDemo // // Created by 罗海雄 on 2020/7/2. // Copyright © 2020 luohaixiong. All rights reserved. // #import <UIKit/UIKit.h> #import <OpenGLES/ES3/gl.h> NS_ASSUME_NONNULL_BEGIN typedef struct{ GLfloat x, y, z; GLfloat r, g, b, a; } OLDGLData; ///用于显示 OpenGL内容 @interface OLDGLView : UIView ///用于绘制OpenGL内容的图层 @property(nonatomic, readonly) CAEAGLLayer *glLayer; ///绘制模式 默认 GL_TRIANGLE_STRIP @property(nonatomic, assign) GLenum drawMode; - (void)drawWithData:(const OLDGLData*) data size:(GLsizeiptr) size backgroundColor:(UIColor*) backgroudColor; @end NS_ASSUME_NONNULL_END
<filename>pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_downstreamvisitor.h<gh_stars>0 #ifndef INCLUDED_CALC_DOWNSTREAMVISITOR #define INCLUDED_CALC_DOWNSTREAMVISITOR #ifndef INCLUDED_STDDEFX #include "stddefx.h" #define INCLUDED_STDDEFX #endif // Library headers. #ifndef INCLUDED_BOOST_NONCOPYABLE #include <boost/noncopyable.hpp> #define INCLUDED_BOOST_NONCOPYABLE #endif // PCRaster library headers. #ifndef INCLUDED_CALC_LDDGRAPH #include "calc_lddgraph.h" #define INCLUDED_CALC_LDDGRAPH #endif // Module headers. namespace calc { // DownstreamVisitor declarations. } namespace calc { //! visitor of a directed graph such as Ldd and Mldd /*! * modelled after the Boost graph dfs en bfs visitors */ class DownstreamVisitor: private boost::noncopyable { const LddGraph& d_graph; public: //---------------------------------------------------------------------------- // CREATORS //---------------------------------------------------------------------------- DownstreamVisitor (const LddGraph& graph); virtual ~DownstreamVisitor (); //---------------------------------------------------------------------------- // MANIPULATORS //---------------------------------------------------------------------------- void visitEntireLdd (); void visitCatchmentOfPit (LddGraph::Catchments::const_iterator c); void visitCatchment (LddGraph::Catchment const& i); //---------------------------------------------------------------------------- // ACCESSORS //---------------------------------------------------------------------------- const LddGraph& graph () const; protected: virtual void visitEdge (size_t /* up */,size_t /* down */); virtual void finishVertex (size_t /* v */); virtual void finishVertex2 (size_t /* v */); virtual void startCatchment (size_t pitId); }; //------------------------------------------------------------------------------ // INLINE FUNCTIONS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // FREE OPERATORS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // FREE FUNCTIONS //------------------------------------------------------------------------------ } // namespace calc #endif
<filename>Engine/inc/CentralRepositoryKeys.h<gh_stars>0 /* ==================================================================== * File: CentralRepositoryKeys.h * Created: 06/07/10 * Modifed: 06/07/10 * Author: <NAME> * Copyright (c): Tieto, All rights reserved * ==================================================================== */ #ifndef CENTRALREPOSITORYKEYS_H #define CENTRALREPOSITORYKEYS_H /** * The Uid for the repository itself * This repository holds the settings for Te2Engine */ const TUid KCRUidTe2Engine = { 0xe01ff1ca }; const TUint32 KTetris2Top1Score = 0x00000001; const TUint32 KTetris2Top1DateTime = 0x00000002; const TUint32 KTetris2Top2Score = 0x00000003; const TUint32 KTetris2Top2DateTime = 0x00000004; const TUint32 KTetris2Top3Score = 0x00000005; const TUint32 KTetris2Top3DateTime = 0x00000006; const TUint32 KTetris2Top4Score = 0x00000007; const TUint32 KTetris2Top4DateTime = 0x00000008; const TUint32 KTetris2Top5Score = 0x00000009; const TUint32 KTetris2Top5DateTime = 0x0000000a; #endif // CENTRALREPOSITORYKEYS_H // End Of File
<reponame>LetsPlentendo-CH/nsmbw-inspector #pragma once #include "Dolphin-memory-engine/Source/DolphinProcess/DolphinAccessor.h" #include "Dolphin-memory-engine/Source/Common/CommonUtils.h" #define MEMBUF_SIZE 0x100000 class DolphinReader { public: static DolphinComm::DolphinAccessor::DolphinStatus hook(); static u32 readU32(u32 address); static u16 readU16(u16 address); static u8 readU16(u8 address); static float readFloat(u32 address); static void *readValues(u32 address, u16 size); static void writeU32(u32 address, u32 value); static void writeU16(u32 address, u16 value); static void writeU8(u32 address, u8 value); static void writeFloat(u32 address, float value); static void writeValues(u32 address, void *data, u16 size); };
#ifndef YUN_MENU_H #define YUN_MENU_H #define PICK_CLASS 0 #define CONFIRM 1 void print_picked(void); void print_options(int what, short mask); void pick_class(void); void confirm_character(void); void do_char_creation(void); #endif
/* * Level.h * PSCAcoustic * * Objects needed at each level of the FMM tree * * * Copyright 2014 <NAME> * * 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 LEVEL_FMM_H #define LEVEL_FMM_H #include "General.h" #include "Transfer_Function.h" #include "Transfer_Vector.h" #include "Translation_Function.h" #include "NFunction.h" #include "TransferUtils.h" #include "Quadrature.h" #include "../L_choice.h" namespace FMM { typedef list<Trans_Vector> TVList; typedef TVList::iterator TVIter; typedef list<Close_Vector> CVList; typedef CVList::iterator CVIter; typedef std::vector<Transfer_Function*> TFList; typedef TFList::iterator TFIter; typedef std::vector<Translation_Function*> TLList; typedef TLList::iterator TLIter; typedef list<Box*> BoxSet; typedef BoxSet::iterator BoxIter; //template <int DIM> class Level { public: const static int BRANCH = 1 << DIM; // The branching factor = 2^DIM bool HF; // Level belongs to HF regime or not bool INTF; // whether level lies at interface between HF and LF regime bool LEAF; // whether level is leaf level int L; // Max order for spherical wave functions Indexing* index; //Indexing for spherical wave functions up to order L static Indexing global_index; double boxSize; // Size of a box this levels contains complex k_out; // Background wave number complex k; // Scatterer wave number BoxSet boxList; // The list of nonempty boxes this level contains Quadrature* quad; // Quadrature for numerical functions of this level NFunction scratchSpace; // Scratch space of size quadrature for computation TVList transList; // The list of transfer std::vectors CVList closeList; // The list of close std::vectors (necessary?) TFList transferFunc; // The list of transfer functions (necessary?) TLList translationFunc; // The list of translation functions std::vector< std::vector<int> > closeIdx; // The index of the particles associated w/ a close transfer std::vector<Vec3> closeVec; // The transfer std::vectors TFList closeFunc; // The list of close transfers (only at leaf level) Interpolator* upReterp; Anterpolator* downReterp; SH_Transform* SH_T; public: // Constructors Level( double boxSize_ = 0, complex k_out_ = K_OUT, complex k_ = K, double cutoff = 2*PI*OMEGA ); // Destructor ~Level(); //-- Auxilliary functions --// inline std::vector< std::vector<int> > getCloseIdx() { return closeIdx; } inline double getBoxSize(){ return boxSize; } inline void addBox( Box* b ){ boxList.push_back(b); } inline Indexing* getIndex(){ return index; } inline Quadrature* getQuad(){ return quad; } inline int getIdxSize(){ return index->size(); } void setL(double eps, double r, complex k, complex k_out); int getL(){ return L; }; void initializeFields( Type type = FORWARD ); void zeroFields(); //--- Quadrature ---// void defineQuadrature( HelmKernel KERNEL, double eps); //--- Spherical Harmonics Transform ---// // Getter inline SH_Transform* getSH_T(){ return SH_T; } // Create instance of Spherical Harmonics Transform inline void defineSH_T(Quadrature* quad_lower, Indexing* index_lower){ SH_T = new SH_Transform(quad_lower, index_lower); } // Compute actual transforms void computeSH_T_Forward( Type type ); void computeSH_T_Backward( Type type ); //--- Translation and Transfer ---// void defineTransfers( double eps, complex k_out ); void addTransfer( Box* b1, Box* b2 ); void addClose( Box* b1, Box* b2 ); // Define close transfers (only at leaf level) void addCloseTransfer( int& idxTo, int& idxFrom, Vec3& r0, complex k_out ); // Define the translation functions from a lower level void defineTranslations(Indexing* pIndex, Indexing* cIndex, complex k_out); // Get the translation function from a child box b // to its parent box in this level inline Translation_Function& getTranslationUp( Box* b ) { return *translationFunc[b->n & (BRANCH-1)]; } // Get the translation function from a parent box to a child box b // in this level inline Translation_Function& getTranslationDown( Box* b ) { return *translationFunc[(b->n & (BRANCH-1)) ^ (BRANCH-1)]; } //--- Interpolation ---// // TODO :Should follow same convention as translation functions // Interpolator: interpolation from current level to upper/parent level // Anterpolator: interpolation from current level to lower/child level inline void defineInterp( Quadrature* quad_Upper) { upReterp = new Interpolator( quad, quad_Upper); } inline Interpolator* getInterp() { return upReterp; } // Define an anterpolator from the quadrature of this level // to the quadrature of level qb inline void defineAnterp( Quadrature* quad_Lower ) { downReterp = new Anterpolator( quad, quad_Lower); } inline Anterpolator* getAnterp() { return downReterp; } //--- Execution ---// void applyTransferFunctions( Type type ); void applyClose(const std::vector< std::vector<complex> >& PWE, std::vector< std::vector<complex> >& T_PWE, complex k_out, Type type ); // Get box indices inline BoxIter boxbegin(){ return boxList.begin(); } inline BoxIter boxend(){ return boxList.end(); } }; } #endif
#ifndef _ODBC_CONNECTION_H_ #define _ODBC_CONNECTION_H_ #ifdef WIN32 #include <windows.h> #endif #include <sql.h> #include <sqlext.h> #include "tcharx.h" namespace Framework { namespace Odbc { class CConnection { public: CConnection(const TCHAR*); ~CConnection(); SQLHANDLE GetConnectionHandle(); private: void ThrowErrorException(); SQLHANDLE m_EnvHandle; SQLHANDLE m_ConHandle; }; } } #endif
<gh_stars>0 #pragma once #include "../PilhaInt.h" /** * Questão 26 * Função decimal_conversao * Converte um número decimal * para binário, octal ou hexadecimal */ typedef enum Base Base; void decimal_conversao(int, Base);
<reponame>petersieg/oscilloscope-vector-display /* * dlo.c - Disk-Like Objects: vector game sprites that behave as hard disks * (geometrical disks, not the data-storage type) */ #include <stdlib.h> #include <math.h> #include "vec2f.h" #include "display.h" #include "dlo.h" const float PI = 3.141592653f; void DLO_init(DLO *d, dlo_outline_t ot, int n_pts, float r_min, float r_max) { d->n_pts = n_pts; d->pts = (vec2f *) malloc(n_pts * sizeof(vec2f)); if (NULL == d->pts){ ERROR("malloc() failed"); } d->r = r_min; vec2f zero = {0.f, 0.f}; d->pos = zero; d->pvel = zero; d->ang = 0; d->avel = 0; d->m = 0; float dtheta = 2.f*PI/n_pts; for (int i=0; i<n_pts; ++i){ float theta = 2.f*PI*i/n_pts; switch(ot){ case DLO_OUTLINE_REGULAR: d->pts[i].x = r_min * cosf(theta); d->pts[i].y = r_min * sinf(theta); d->m += 2 * r_min*cosf(dtheta/2) * r_min*sinf(dtheta/2); break; case DLO_OUTLINE_RANDOM: { float r = r_min + (r_max - r_min) * drand48(); if (r > d->r){ d->r = r; } d->pts[i].x = r * cosf(theta); d->pts[i].y = r * sinf(theta); d->m += 2 * r*cosf(dtheta/2) * r*sinf(dtheta/2); /* approx */ break; } default: ERROR("unknown DLO outline type"); } } } void DLO_free(DLO *d) { if (d->pts){ free(d->pts); } } void DLO_update(DLO *d) { vec2f_addto(&d->pos, d->pvel); d->ang += d->avel; } /* detect if a collision happened in the last time step */ DLO_collision DLO_intersect_DLO(const DLO* d, const DLO* e) { DLO_collision collision; if (vec2f_dist(d->pos, e->pos) > (d->r + e->r)){ collision.detected = 0; return collision; } /* find time (in past) when collision should have happened */ vec2f dp = vec2f_sub(d->pos, e->pos); vec2f v = vec2f_sub(d->pvel, e->pvel); float a = v.x*v.x + v.y*v.y; float b = 2.f*(v.x*dp.x + v.y*dp.y); float c = dp.x*dp.x + dp.y*dp.y - (d->r + e->r)*(d->r + e->r); float t0, t1; // use numerically stable quadratic solution // https://people.csail.mit.edu/bkph/articles/Quadratics.pdf float det = b*b-4.f*a*c; if (det < 0.f){ // never intersected: corner case collision.detected = 0; return collision; } det = sqrtf(det); if (b >= 0){ t0 = (-b - det)/(2.f*a); t1 = 2.f*c/(-b - det); } else { t0 = 2.f*c/(-b + det); t1 = (-b + det)/(2.f*a); } float t; if (t0 < 0.f){ t = t0; } if (t1 < t){ t = t1; } collision.detected = 1; collision.t = t; return collision; } DLO_collision DLO_intersect_WALL(const DLO* d, const Wall* w) { } /* bounce two DLOs off each other */ void DLO_interact_DLO(DLO *a, DLO *b, DLO_collision *coll) { if (!coll->detected){ return; } /* reverse positions to interaction time */ vec2f_addto(&a->pos, vec2f_mul_f(a->pvel, coll->t)); vec2f_addto(&b->pos, vec2f_mul_f(b->pvel, coll->t)); /* find unit vector between centers */ vec2f l = vec2f_sub(a->pos, b->pos); vec2f_normalize(&l); /* velocity components along axis before collision */ float va = vec2f_dot(a->pvel, l); float vb = vec2f_dot(b->pvel, l); /* axial velocity post collison */ float va_p = ((a->m - b->m)*va + 2*b->m*vb)/(a->m + b->m); float vb_p = ((b->m - a->m)*vb + 2*a->m*va)/(a->m + b->m); /* update velocities */ vec2f_addto(&a->pvel, vec2f_mul_f(l, -va)); vec2f_addto(&a->pvel, vec2f_mul_f(l, va_p)); vec2f_addto(&b->pvel, vec2f_mul_f(l, -vb)); vec2f_addto(&b->pvel, vec2f_mul_f(l, vb_p)); /* update to post-interaction positions */ vec2f_addto(&a->pos, vec2f_mul_f(a->pvel, -coll->t)); vec2f_addto(&b->pos, vec2f_mul_f(b->pvel, -coll->t)); } void DLO_interact_WALL() { } void DLO_render(DisplayList *dl, DLO *d, float slew) { Line *l = NewLine(); l->slew = slew; for (int i = 0; i <= d->n_pts; ++i){ float x = d->pts[i % d->n_pts].x; float y = d->pts[i % d->n_pts].y; float xp = x * cosf(d->ang) - y * sinf(d->ang); float yp = x * sinf(d->ang) + y * cosf(d->ang); Point *p = NewPoint(d->pos.x + xp, d->pos.y + yp); AddPoint(l, p); } AddLine(dl, l); }
<reponame>CptnGreen/fillit /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_memchr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: slisandr <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/05 19:38:56 by slisandr #+# #+# */ /* Updated: 2019/05/05 19:38:59 by slisandr ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /* ** The memchr() function scans the initial n bytes of the ** memory area pointed to by s for the first instance of c. ** Both c and the bytes of the memory area pointed to by s ** are interpreted as unsigned char. The memchr() function ** return a pointer to the matching byte or NULL if the ** character does not occur in the given memory area. */ void *ft_memchr(void const *s, int c, size_t n) { char *str; size_t i; i = 0; str = (char *)s; while (i < n) { if (str[i] == c) return (str + i); i++; } return (NULL); }
#include <stdlib.h> #include <stdio.h> #include "SiconosLapack.h" #include <assert.h> #include "test_utils.h" /* Parameters */ #define N 5 #define LDA N /* Main program */ int main() { /* Locals */ int n = N, lda = LDA, info; /* Local arrays */ int ipiv[N]; double a[LDA*N] = { 6.80, -2.11, 5.66, 5.97, 8.23, -6.05, -3.30, 5.36, -4.44, 1.08, -0.45, 2.58, -2.70, 0.27, 9.04, 8.32, 2.71, 4.35, -7.17, 2.14, -9.67, -5.14, -7.26, 6.08, -6.87 }; double b[LDA*N]; cblas_dcopy (LDA*N, a, 1, b, 1); /* Executable statements */ printf( "LAPACKE_dgetr (column-major, high-level) Example Program Results\n" ); /* Solve the equations A*X = B */ DGETRF(n, n, a, lda, ipiv, &info ); if( info > 0 ) { printf( "DGETRF failed.\n" ); exit( 1 ); } DGETRI(n, a, lda, ipiv, &info ); if( info > 0 ) { printf( "DGETRI failed.\n" ); exit( 1 ); } double tol = 1e-9; double c[LDA*N]; cblas_dgemm(CblasColMajor, CblasNoTrans,CblasNoTrans, N, N, N, 1.0, a, N, b, N, 0.0, c, N); for(int i=0;i<N;++i) for(int j = 0; j<N; ++j) if(i==j) {if (fabs(c[i+N*j]-1.0)>tol) exit(1);} else {if (fabs(c[i+N*j]) > tol) exit(1);} print_matrix("Id?", N,N,b,N); exit( 0 ); }
#ifndef QREMOTEFILE_H #define QREMOTEFILE_H #include "qrmf_base.h" #include "qrmf_file.h" #include "qrmf_filemap2.h" #include "qrmf_filemanager.h" #include "qrmf_proto.h" #include "qrmf_socketadapter.h" #endif // QREMOTEFILE_H
#include "osapi.h" #include "stdint.h" #include "c_types.h" #include "hv_ic.h" #include "defines.h" #include "gpio.h" #include "eagle_soc.h" int HV_BRIGHTNESS_LEVEL = 100; enum hv_status_enum HV_STATUS = HV_NORMAL; void hv_blank_pwm(void *arg){ static int counter = 0; if (HV_STATUS == HV_NORMAL){ if (counter <= HV_BRIGHTNESS_LEVEL){ // HV_BLANK // Turn tubes ON (blank is active LOW) gpio_output_set(0, (1 << HV_BLANK), 0, 0); } else{ // Turn tubes OFF (blank is active LOW) gpio_output_set((1 << HV_BLANK), 0, 0, 0); } } else{ gpio_output_set((1 << HV_BLANK), 0, 0, 0); } counter++; if (counter > 100){ counter = 0; } } void ICACHE_FLASH_ATTR hv_push_byte(uint8_t data){ // uint8_t mask = 0x01; // // Push out LSB first // // HV_DATA is on GPIO16 // while (mask){ // if (data & mask){ // gpio16_output_set(1); // } // else{ // gpio16_output_set(0); // } // // Make a clock edge. Data is read on CLK H->L // gpio_output_set(0, (1 << HV_CLK), 0, 0); // // Shift reg operates @max 8 MHz, add some delay // os_delay_us(1); // gpio_output_set((1 << HV_CLK), 0, 0, 0); // mask = mask << 1; // } uint8_t mask = 0x80; // TODO: Remove this GPIO_OUTPUT_SET(GPIO_ID_PIN(HV_BLANK), 0); // Push out MSB first // HV_DATA is on GPIO16 while (mask){ if (data & mask){ gpio16_output_set(1); } else{ gpio16_output_set(0); } // Make a clock edge. Data is read on CLK H->L GPIO_OUTPUT_SET(GPIO_ID_PIN(HV_CLK), 1); // Shift reg operates @max 8 MHz, add some delay os_delay_us(1); GPIO_OUTPUT_SET(GPIO_ID_PIN(HV_CLK), 0); os_delay_us(1); mask = mask >> 1; } // TODO: Remove this GPIO_OUTPUT_SET(GPIO_ID_PIN(HV_BLANK), 1); }
<reponame>Snehakri022/Competitive-Programming-Solutions // Write a program to find the remainder when two given numbers are divided. // Input // The first line contains an integer T, total number of test cases. Then follow T lines, each line contains two Integers A and B. // Output // Find remainder when A is divided by B. // Constraints // 1 ≤ T ≤ 1000 // 1 ≤ A,B ≤ 10000 // Example // Input // 3 // 1 2 // 100 200 // 10 40 // Output // 1 // 100 // 10 #include <stdio.h> int main() { // Read the number of test cases. int T; scanf("%d", &T); while (T--) { // Read the input a, b int a, b; scanf("%d %d", &a, &b); // Compute the ans. // Complete this line. int ans = a %b; printf("%d\n", ans); } return 0; }
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #pragma once #include "RobotContainerBase.h" #include "subsystems/Rocky/DriveTrainRocky.h" #include "subsystems/Rocky/LoaderRocky.h" #include "subsystems/Rocky/ShooterRocky.h" #include "commands/DriveCMD.h" #include "commands/LoadCMD.h" #include "commands/ShooterCMD.h" class RobotContainerRocky : public RobotContainerBase { public: RobotContainerRocky(); void Init() override; frc2::Command *GetAutonomousCommand() override; // Turret void SetAButton(); void SetBButton(); // Loader void SetXButton(); void SetYButton(); // Shooter void SetRightTrigger(); void SetLeftTrigger(); private: void ConfigureButtonBindings(); DriveCMD *m_pDriveCMD = nullptr; LoadCMD *m_pLoadCMD = nullptr; LoadCMD *m_pEjectCMD = nullptr; LoadCMD *m_pLoadStopCMD = nullptr; ShooterCMD *m_pShooterCMD = nullptr; ShooterCMD *m_pReverseShootCMD = nullptr; ShooterCMD *m_pStopShootCMD = nullptr; };
<filename>src/driver/vision_flow/mateksys/pmw3901_l0x.c /****************************************************************************** * Copyright 2020 The Firmament Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <firmament.h> #include "hal/serial.h" #include "module/sensor/sensor_hub.h" #include "protocol/msp/msp.h" // TBD #define OPFLOW_SQUAL_THRESHOLD_HIGH 90 #define OPFLOW_SQUAL_THRESHOLD_LOW 50 typedef struct __attribute__((packed)) { uint8_t quality; // [0;255] int32_t distanceMm; // Negative value for out of range } mspRangefinderSensor_t; typedef struct __attribute__((packed)) { uint8_t quality; // [0;255] int32_t motionX; int32_t motionY; } mspOpflowSensor_t; // MCN_DEFINE(sensor_optflow, sizeof(optflow_data_t)); // MCN_DEFINE(sensor_rangefinder, sizeof(rf_data_t)); MCN_DECLARE(sensor_optflow); MCN_DECLARE(sensor_rangefinder); static rf_data_t rangefinder_report = { .timestamp_ms = 0, .distance_m = -1.0f }; static optflow_data_t optflow_report = { 0 }; static int sensor_opt_flow_echo(void* param) { fmt_err_t err; optflow_data_t optflow_report; err = mcn_copy_from_hub((McnHub*)param, &optflow_report); if (err != FMT_EOK) { return -1; } console_printf("timestamp:%-8d vx:%.2f vy:%.2f valid:%d\n", optflow_report.timestamp_ms, optflow_report.vx_mPs, optflow_report.vy_mPs, optflow_report.valid); return 0; } static int sensor_rangefinder_echo(void* param) { fmt_err_t err; rf_data_t rangefinder_report; err = mcn_copy_from_hub((McnHub*)param, &rangefinder_report); if (err != FMT_EOK) { return -1; } console_printf("timestamp:%-8d distance:%.3f\n", rangefinder_report.timestamp_ms, rangefinder_report.distance_m); return 0; } static mspResult_e mspFcProcessCommand(mspPacket_t* cmd, mspPacket_t* reply) { const uint16_t cmdMSP = cmd->cmd; if (MSP2_IS_SENSOR_MESSAGE(cmdMSP)) { switch (cmdMSP) { case MSP2_SENSOR_RANGEFINDER: { const mspRangefinderSensor_t* pkt = (const mspRangefinderSensor_t*)cmd->buf; rangefinder_report.timestamp_ms = systime_now_ms(); rangefinder_report.distance_m = pkt->distanceMm > 0 ? (float)pkt->distanceMm * 0.001f : -1.0f; mcn_publish(MCN_HUB(sensor_rangefinder), &rangefinder_report); } break; case MSP2_SENSOR_OPTIC_FLOW: { const mspOpflowSensor_t* pkt = (const mspOpflowSensor_t*)cmd->buf; optflow_report.timestamp_ms = systime_now_ms(); /* rotate to Body frame */ optflow_report.vx_mPs = (float)(pkt->motionY * -0.01f); optflow_report.vy_mPs = (float)(pkt->motionX * 0.01f); /* opt flow valid only if rangefinder valid and opt flow's quality is okay */ if (rangefinder_report.distance_m > 0.0f) { if (pkt->quality >= OPFLOW_SQUAL_THRESHOLD_HIGH) { optflow_report.valid = 1; } if (pkt->quality <= OPFLOW_SQUAL_THRESHOLD_LOW) { optflow_report.valid = 0; } } else { optflow_report.valid = 0; } mcn_publish(MCN_HUB(sensor_optflow), &optflow_report); } break; default: break; } } return MSP_RESULT_NO_REPLY; } rt_err_t pmw3901_l0x_drv_init(const char* serial_dev_name) { rt_device_t dev = rt_device_find(serial_dev_name); if (dev == NULL) { return RT_ERROR; } if (msp_register(dev, mspFcProcessCommand) == NULL) { return RT_ERROR; } // mcn_advertise(MCN_HUB(sensor_optflow), sensor_opt_flow_echo); // mcn_advertise(MCN_HUB(sensor_rangefinder), sensor_rangefinder_echo); return RT_EOK; }
// Copyright 2018 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 ASH_SYSTEM_ROTATION_ROTATION_LOCK_FEATURE_POD_CONTROLLER_H_ #define ASH_SYSTEM_ROTATION_ROTATION_LOCK_FEATURE_POD_CONTROLLER_H_ #include "ash/ash_export.h" #include "ash/display/screen_orientation_controller.h" #include "ash/public/cpp/tablet_mode_observer.h" #include "ash/system/unified/feature_pod_controller_base.h" #include "base/macros.h" namespace ash { // Controller of a feature pod button that toggles rotation lock mode. class ASH_EXPORT RotationLockFeaturePodController : public FeaturePodControllerBase, public TabletModeObserver, public ScreenOrientationController::Observer { public: RotationLockFeaturePodController(); RotationLockFeaturePodController(const RotationLockFeaturePodController&) = delete; RotationLockFeaturePodController& operator=( const RotationLockFeaturePodController&) = delete; ~RotationLockFeaturePodController() override; // FeaturePodControllerBase: FeaturePodButton* CreateButton() override; void OnIconPressed() override; SystemTrayItemUmaType GetUmaType() const override; // TabletModeObserver: void OnTabletPhysicalStateChanged() override; // ScreenOrientationController::Observer: void OnUserRotationLockChanged() override; private: void UpdateButton(); FeaturePodButton* button_ = nullptr; }; } // namespace ash #endif // ASH_SYSTEM_ROTATION_ROTATION_LOCK_FEATURE_POD_CONTROLLER_H_
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef GPU_COMMAND_BUFFER_SERVICE_GL_STREAM_TEXTURE_IMAGE_H_ #define GPU_COMMAND_BUFFER_SERVICE_GL_STREAM_TEXTURE_IMAGE_H_ #include "gpu/gpu_gles2_export.h" #include "ui/gl/gl_image.h" namespace gpu { namespace gles2 { // Specialization of GLImage that allows us to support (stream) textures // that supply a texture matrix. class GPU_GLES2_EXPORT GLStreamTextureImage : public gl::GLImage { public: // Get the matrix. // Copy the texture matrix for this image into |matrix|. // Subclasses must return a matrix appropriate for a coordinate system where // UV=(0,0) corresponds to the top left corner of the image. virtual void GetTextureMatrix(float matrix[16]) = 0; virtual void NotifyPromotionHint(bool promotion_hint, int display_x, int display_y, int display_width, int display_height) = 0; protected: ~GLStreamTextureImage() override = default; // Convenience function for subclasses that deal with SurfaceTextures, whose // coordinate system has (0,0) at the bottom left of the image. // [ a e i m ] [ 1 0 0 0 ] [ a -e i m+e ] // [ b f j n ] [ 0 -1 0 1 ] = [ b -f j n+f ] // [ c g k o ] [ 0 0 1 0 ] [ c -g k o+g ] // [ d h l p ] [ 0 0 0 1 ] [ d -h l p+h ] static void YInvertMatrix(float matrix[16]) { for (int i = 0; i < 4; ++i) { matrix[i + 12] += matrix[i + 4]; matrix[i + 4] = -matrix[i + 4]; } } }; } // namespace gles2 } // namespace gpu #endif // GPU_COMMAND_BUFFER_SERVICE_GL_STREAM_TEXTURE_IMAGE_H_
<gh_stars>0 #include "com.h" #define WIFI_STA (0) class WiFi { public: int status(); char* localIP(); // void begin(); void begin(String, String); void mode(int); private: }; int WiFi::status() { return 0; } char* WiFi::localIP() { return NULL; } //void WiFi::begin() //{ //} void WiFi::mode(int mode) { } void WiFi::begin(String ssid, String pw) { } WiFi WiFi;
<reponame>Jelinek-J/INSPiRE<gh_stars>1-10 #pragma once #include "../common/filesystem.h" #include "../common/exception.h" #include <vector> #include <map> #include <iostream> #include <sstream> namespace inspire { namespace backend { class MutuallyOptimizer { private: static const size_t HEADER = 5; size_t DIMENSION = -1; std::vector<std::ifstream*> INPUTS; std::ofstream OUTPUT; protected: virtual double combine_row(std::vector<double> &values) = 0; public: MutuallyOptimizer(std::string output) : OUTPUT(output) { } ~MutuallyOptimizer() { OUTPUT.flush(); OUTPUT.close(); for (size_t i = 0; i < INPUTS.size(); i++) { INPUTS[i]->close(); delete INPUTS[i]; } } void add_input(std::string header, std::string input) { size_t index = INPUTS.size(); INPUTS.push_back(new std::ifstream(input)); std::string line; if (!std::getline(*INPUTS[index], line)) { throw common::exception::TitledException("File '" + input + "' is empty or it is not possible to read from it."); } std::stringstream parts(line); std::string part; size_t columns = 0; while (std::getline(parts, part, '\t')) { ++columns; } if (DIMENSION == -1) { if (columns < HEADER) { throw common::exception::TitledException("Unexpected format of optimization file '" + input + "': header has less than 5 elements."); } DIMENSION = columns - HEADER; OUTPUT << "threshold"; for (size_t i = 1; i < DIMENSION; i++) { OUTPUT << '\t'; } } else { if (DIMENSION + HEADER != columns) { throw common::exception::TitledException("File '" + input + "' has a different dimension then previous file(s)."); } } OUTPUT << '\t' << header; } void combine() { double max = -2; if (INPUTS.size() == 0) { throw common::exception::TitledException("No file was added"); } OUTPUT << '\n'; std::string line; while (std::getline(*INPUTS[0], line)) { std::vector<double> values; // Well, tests causes slow down, but this is not time nor memory critical point, so it is not a problem std::vector<std::string> thresholds; { std::stringstream parts(line); std::string part; for (size_t i = 0; i < DIMENSION; i++) { if (!std::getline(parts, part, '\t')) { throw common::exception::TitledException("The first file contains a line with an insufficient count of columns"); } thresholds.push_back(part); OUTPUT << part << '\t'; } for (size_t i = 0; i < HEADER; i++) { if (!std::getline(parts, part, '\t')) { throw common::exception::TitledException("The first file contains a line with an insufficient count of columns"); } } OUTPUT << part << '\t'; values.push_back(std::stod(part)); } for (size_t input = 1; input < INPUTS.size(); input++) { if (!std::getline(*INPUTS[input], line)) { throw common::exception::TitledException("The " + std::to_string(input) + "th file contains a line with an insufficient count of colomns"); } std::stringstream parts(line); std::string part; for (size_t i = 0; i < DIMENSION; i++) { if (!std::getline(parts, part, '\t')) { throw common::exception::TitledException("The " + std::to_string(input) + "th file contains a line with an insufficient count of colomns"); } if (part != thresholds[i]) { throw common::exception::TitledException("The " + std::to_string(input) + "th file and " + std::to_string(input) + "th file don't have the same thresholds"); } } for (size_t i = 0; i < HEADER; i++) { if (!std::getline(parts, part, '\t')) { throw common::exception::TitledException("The first file contains a line with an insufficient count of colomns"); } } OUTPUT << part << '\t'; values.push_back(std::stod(part)); } double value = combine_row(values); OUTPUT << value << '\n'; if (value > max) { max = value; } } OUTPUT.flush(); std::cout << max << std::endl; } }; class AverageMutuallyOptimize : public MutuallyOptimizer { protected: double combine_row(std::vector<double> &values) override { double sum = 0; for (size_t i = 0; i < values.size(); i++) { sum += values[i]; } return sum / values.size(); } public: AverageMutuallyOptimize(std::string output) : MutuallyOptimizer(output) { } }; class MedianMutuallyOptimize : public MutuallyOptimizer { protected: double combine_row(std::vector<double> &values) override { std::sort(values.begin(), values.end()); return values.size() %2 == 0 ? (values[values.size()/2-1] + values[values.size()/2])/2 : values[values.size()/2]; } public: MedianMutuallyOptimize(std::string output) : MutuallyOptimizer(output) { } }; } }
<filename>WordWar/WordWar/ScoreRatioView.h // // ScoreRatio.h // WordWar // // Created by <NAME> on 7/20/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @class Player; @interface ScoreRatioView : UIView @property (nonatomic, copy) NSArray *ratios; - (instancetype)initWithMyPlayer:(Player *)myPlayer players:(NSArray *)players NS_DESIGNATED_INITIALIZER; @end
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <sanitizer/asan_interface.h> // TODO(45047): BUILD.gn machinery passes the suppress-lsan.ld input linker // script to define this symbol as some nonzero address (never to be // dereferenced, just observed as nonzero). __attribute__((weak)) extern struct { } _FUCHSIA_SUPPRESS_LSAN; // ASan applies the options here before looking at the ASAN_OPTIONS // environment variable. const char* __asan_default_options(void) { // TODO(45047): Remove this later. If the magic cookie was linked in, // add LSan suppression to the compiled-in options list. if (&_FUCHSIA_SUPPRESS_LSAN) { return ASAN_DEFAULT_OPTIONS ":detect_leaks=0"; } // This macro is defined by BUILD.gn from the `asan_default_options` GN // build argument. return ASAN_DEFAULT_OPTIONS; }
/* Copyright (c) 2017, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sysload/kparam.h> #include <sysload/flags.h> #include <kern/machine/bioscall.h> #include <kern/console.h> #include <kern/clock.h> #include <kern/start.h> #include <kern/errno.h> #include <kern/lib.h> #include <dev/console.h> #include <stdint.h> #define WIDTH 640 #define HEIGHT 480 #define MODE 0xc101 #define PORT 0x3c0 #define FG 255 #define BG 0 #define FONTH 8 #define FONTW 8 #define LINESPC 2 static void gc_disable(struct console *con); static void gc_reset(struct console *con); static void gc_clear(struct console *con); static int gc_getxy(struct console *con, int x, int y); static void gc_putxy(struct console *con, int x, int y, int c); static void gc_putc(struct console *con, int c); static void gc_status(struct console *con, int flags); static void gc_gotoxy(struct console *con, int x, int y); static void gc_puta(struct console *con, int x, int y, int c, int a); struct console eccon = { .width = 80, .height = 48, .flags = CF_COLOR | CF_ADDR, .disable = gc_disable, .reset = gc_reset, .clear = gc_clear, .putc = gc_putc, .status = gc_status, .gotoxy = gc_gotoxy, .puta = gc_puta, }; extern char monofnt[]; static uint8_t * gc_font = (void *)monofnt; static uint8_t * gc_buf; static volatile int gc_busy; static volatile int gc_cvis; static int gc_enabled; static int gc_x, gc_y; static int gc_anim = 0; static uint8_t gc_sbuf[WIDTH * FONTH]; static void gc_setdac(int i, int r, int g, int b) { outb(PORT + 0x8, i); outb(PORT + 0x9, r); outb(PORT + 0x9, g); outb(PORT + 0x9, b); } static int gc_posval(struct console *con, int x, int y) { if (x >= 0 && x < con->width && y >= 0 && y < con->height) return 1; return 0; } static void gc_disable(struct console *con) { gc_enabled = 0; gc_anim = 0; } static void gc_reset(struct console *con) { struct real_regs *r = get_bios_regs(); int i; gc_busy++; r->intr = 0x10; r->ax = 0x4f02; r->bx = 0xc101; v86_call(); for (i = 0; i < 256; i++) gc_setdac(i, i >> 2, i >> 2, i >> 2); gc_enabled = 1; gc_clear(con); gc_busy--; } static void gc_icurs(struct console *con) { uint8_t *p = gc_buf + gc_x * FONTW + gc_y * (FONTH + LINESPC) * WIDTH; int x, y; gc_busy++; if (gc_posval(con, gc_x, gc_y)) for (y = FONTH; y < FONTH + LINESPC; y++) for (x = 0; x < FONTW; x++) p[x + y * WIDTH] ^= 255; gc_cvis = !gc_cvis; gc_busy--; } static void gc_hcurs(struct console *con) { if (gc_cvis) gc_icurs(con); } static void gc_scurs(struct console *con) { if (!gc_cvis) gc_icurs(con); } static void gc_clear(struct console *con) { gc_busy++; memset(gc_buf, 0, WIDTH * HEIGHT); gc_x = gc_y = 0; gc_cvis = 0; gc_busy--; } static void gc_rchar(uint8_t *dp, int c) { uint8_t *sp; uint8_t row; int px, py; sp = gc_font + (c & 127) * 8; for (py = 0; py < 8; py++) { row = *sp++; for (px = 0; px < 8; px++) { *dp++ = (row & 128) ? FG : BG; row <<= 1; } dp += WIDTH; dp -= 8; } } static void gc_putxy(struct console *con, int x, int y, int c) { uint8_t *dp; int s; if (!gc_posval(con, x, y)) return; if (gc_anim) dp = gc_sbuf + x * FONTW; else dp = gc_buf + x * FONTW + y * (FONTH + LINESPC) * WIDTH; s = intr_dis(); if (x == gc_x && y == gc_y) gc_hcurs(con); gc_rchar(dp, c); intr_res(s); } static void gc_bll(int y, int r) { uint8_t *dp = gc_buf + (y + gc_y * FONTH) * WIDTH; uint8_t *sp = gc_sbuf + y * WIDTH; int x, i, x0, x1; int acc; for (x = 0; x < WIDTH; x++) { x0 = x - r; x1 = x + r; if (x0 < 0) x0 = 0; if (x1 >= WIDTH) x1 = WIDTH - 1; for (acc = 0, i = x0; i <= x1; i++) acc += sp[i]; acc /= 2 * r + 1; *dp++ = acc; } } static void gc_blur(int r) { int y; for (y = 0; y < FONTH; y++) gc_bll(y, r); } static void gc_anewlin(struct console *con) { int hz = clock_hz(); int t0 = clock_ticks(); int du = hz / 4; int t, r; if (!gc_anim) return; do { t = clock_ticks() - t0; if (t < 0) t += hz; r = (du - t) * 80 / hz; if (r < 0) r = 0; gc_blur(r); } while (du > t); memset(gc_sbuf, BG, sizeof gc_sbuf); } static void gc_scroll(struct console *con) { int len = WIDTH * (HEIGHT - FONTH - LINESPC); memmove(gc_buf, gc_buf + WIDTH * FONTH, len); memset(gc_buf + len, BG, WIDTH * FONTH); if (gc_y > 0) gc_y--; } static void gc_clock(void) { static int div; uint16_t v; if (++div >= clock_hz() / 2) { if (gc_enabled) gc_icurs(&eccon); div = 0; } } static void gc_putc(struct console *con, int c) { gc_busy++; switch (c) { case '\n': gc_anewlin(con); gc_gotoxy(con, 0, gc_y + 1); if (gc_y >= con->height) gc_scroll(con); break; case '\b': if (gc_x > 0) gc_gotoxy(con, gc_x - 1, gc_y); break; default: if (gc_x >= con->width) gc_gotoxy(con, 0, gc_y + 1); if (gc_y >= con->height) gc_scroll(con); gc_putxy(con, gc_x, gc_y, c); gc_gotoxy(con, gc_x + 1, gc_y); } gc_busy--; } static void gc_status(struct console *con, int flags) { } static void gc_gotoxy(struct console *con, int x, int y) { gc_hcurs(con); gc_x = x; gc_y = y; gc_scurs(con); } static int gc_conva(int a) { int va = 0; va = (a & 1) << 10; va |= (a & 2) << 8; va |= (a & 4) << 6; va |= (a & 16) << 10; va |= (a & 32) << 8; va |= (a & 64) << 6; return va; } static void gc_puta(struct console *con, int x, int y, int c, int a) { gc_putxy(con, x, y, (c & 255) | gc_conva(a)); } int gc_init(void) { struct real_regs *r = get_bios_regs(); uint8_t *buf = get_bios_buf(); int err; r->intr = 0x10; r->ax = 0x4f01; r->cx = 0xc101; r->es = (uint32_t)buf >> 4; r->di = (uint32_t)buf & 15; v86_call(); if (r->ax != 0x004f) { printk("console: vesa call failed\n"); return ENODEV; } printk("console: lfb at 0x%x\n", *(uint32_t *)(buf + 0x28)); err = phys_map((void **)&gc_buf, *(uint32_t *)(buf + 0x28), WIDTH * HEIGHT, 0); if (err) return err; con_install(&eccon); clock_ihand(gc_clock); if (kparam.boot_flags & BOOT_VERBOSE) printk("console: vesa\n"); return 0; }
#ifndef __PHI_WIDGET_Multi_Button_H #define __PHI_WIDGET_Multi_Button_H #include "phi_widget_base.h" #include "../epdgui_button.h" #include "ArduinoJson.h" #include <list> class PHI_Widget_Multi_Button : public PHI_Widget_Base { public: static const int16_t SEPARATOR_HEIGHT = 2; static const int16_t SEPARATOR_HORIZONTAL_MARGIN = 10; static const int16_t SEPARATOR_COLOR = 6; public: PHI_Widget_Multi_Button(int16_t x, int16_t y, int16_t w, int16_t h, int16_t items); ~PHI_Widget_Multi_Button(); void Draw(m5epd_update_mode_t mode = UPDATE_MODE_GC16); //UPDATE_MODE_DU4 void Draw(M5EPD_Canvas *canvas); void BindEvent(int16_t event, void (*func_cb)(epdgui_args_vector_t &)); void UpdateTouchState(int16_t x, int16_t y); void Render(JsonVariant data); private: std::list<EPDGUI_Button *> _buttons; void RenderButtonContent(M5EPD_Canvas *canvas, bool pressed, String description, String icon, bool first, bool last); }; #endif //__PHI_WIDGET_Multi_Button_H
#ifndef _CROSSHAIRMODEL_H_ #define _CROSSHAIRMODEL_H_ #include "IModel.h" class CrossHairModel : public IModel { public: virtual bool IsChanged() {return true;} virtual glm::mat4 GetModel() {return model;} virtual glm::mat4 GetView() {return view;} virtual glm::mat4 GetProjection() {return projection;} private: glm::mat4 model = glm::mat4(1.0f); glm::mat4 view = glm::mat4(1.0f); glm::mat4 projection = glm::mat4(1.0f); }; #endif
// Copyright 2004-present Facebook. All Rights Reserved. #import <ComponentKit/CKComponent.h> @interface CKMButtonComponent : CKComponent + (instancetype)newWithTitle:(NSString *)title type:(NSButtonType)type viewAttributes:(CKViewComponentAttributeValueMap)viewAttributes; @end
/* * Copyright (C) 2003-2016 Free Software Foundation, Inc. * Copyright (C) 2012-2016 <NAME> * Copyright (C) 2016-2017 Red Hat, Inc. * * Author: <NAME> * * This file is part of GnuTLS. * * The GnuTLS 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 program. If not, see <https://www.gnu.org/licenses/> * */ /* This file contains functions to handle PKCS #10 certificate requests, see RFC 2986. */ #include "gnutls_int.h" #include <datum.h> #include <global.h> #include "errors.h" #include <common.h> #include <x509.h> #include <x509_b64.h> #include <gnutls/x509-ext.h> #include "x509_int.h" #include <libtasn1.h> #include <pk.h> #include "attributes.h" /** * gnutls_x509_crq_init: * @crq: A pointer to the type to be initialized * * This function will initialize a PKCS#10 certificate request * structure. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_init(gnutls_x509_crq_t * crq) { int result; FAIL_IF_LIB_ERROR; *crq = gnutls_calloc(1, sizeof(gnutls_x509_crq_int)); if (!*crq) return GNUTLS_E_MEMORY_ERROR; result = asn1_create_element(_gnutls_get_pkix(), "PKIX1.pkcs-10-CertificationRequest", &((*crq)->crq)); if (result != ASN1_SUCCESS) { gnutls_assert(); gnutls_free(*crq); return _gnutls_asn2err(result); } return 0; } /** * gnutls_x509_crq_deinit: * @crq: the type to be deinitialized * * This function will deinitialize a PKCS#10 certificate request * structure. **/ void gnutls_x509_crq_deinit(gnutls_x509_crq_t crq) { if (!crq) return; if (crq->crq) asn1_delete_structure(&crq->crq); gnutls_free(crq); } #define PEM_CRQ "NEW CERTIFICATE REQUEST" #define PEM_CRQ2 "CERTIFICATE REQUEST" /** * gnutls_x509_crq_import: * @crq: The data to store the parsed certificate request. * @data: The DER or PEM encoded certificate. * @format: One of DER or PEM * * This function will convert the given DER or PEM encoded certificate * request to a #gnutls_x509_crq_t type. The output will be * stored in @crq. * * If the Certificate is PEM encoded it should have a header of "NEW * CERTIFICATE REQUEST". * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_import(gnutls_x509_crq_t crq, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format) { int result = 0, need_free = 0; gnutls_datum_t _data; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } _data.data = data->data; _data.size = data->size; /* If the Certificate is in PEM format then decode it */ if (format == GNUTLS_X509_FMT_PEM) { /* Try the first header */ result = _gnutls_fbase64_decode(PEM_CRQ, data->data, data->size, &_data); if (result < 0) /* Go for the second header */ result = _gnutls_fbase64_decode(PEM_CRQ2, data->data, data->size, &_data); if (result < 0) { gnutls_assert(); return result; } need_free = 1; } result = _asn1_strict_der_decode(&crq->crq, _data.data, _data.size, NULL); if (result != ASN1_SUCCESS) { result = _gnutls_asn2err(result); gnutls_assert(); goto cleanup; } result = 0; cleanup: if (need_free) _gnutls_free_datum(&_data); return result; } /** * gnutls_x509_crq_get_signature_algorithm: * @crq: should contain a #gnutls_x509_cr_t type * * This function will return a value of the #gnutls_sign_algorithm_t * enumeration that is the signature algorithm that has been used to * sign this certificate request. * * Since 3.6.0 this function never returns a negative error code. * Error cases and unknown/unsupported signature algorithms are * mapped to %GNUTLS_SIGN_UNKNOWN. * * Returns: a #gnutls_sign_algorithm_t value * * Since: 3.4.0 **/ int gnutls_x509_crq_get_signature_algorithm(gnutls_x509_crq_t crq) { return map_errs_to_zero(_gnutls_x509_get_signature_algorithm(crq->crq, "signatureAlgorithm")); } /** * gnutls_x509_crq_get_private_key_usage_period: * @crq: should contain a #gnutls_x509_crq_t type * @activation: The activation time * @expiration: The expiration time * @critical: the extension status * * This function will return the expiration and activation * times of the private key of the certificate. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE * if the extension is not present, otherwise a negative error value. **/ int gnutls_x509_crq_get_private_key_usage_period(gnutls_x509_crq_t crq, time_t * activation, time_t * expiration, unsigned int *critical) { int result, ret; ASN1_TYPE c2 = ASN1_TYPE_EMPTY; uint8_t buf[128]; size_t buf_size = sizeof(buf); if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } ret = gnutls_x509_crq_get_extension_by_oid(crq, "172.16.17.32", 0, buf, &buf_size, critical); if (ret < 0) return gnutls_assert_val(ret); result = asn1_create_element (_gnutls_get_pkix(), "PKIX1.PrivateKeyUsagePeriod", &c2); if (result != ASN1_SUCCESS) { gnutls_assert(); ret = _gnutls_asn2err(result); goto cleanup; } result = _asn1_strict_der_decode(&c2, buf, buf_size, NULL); if (result != ASN1_SUCCESS) { gnutls_assert(); ret = _gnutls_asn2err(result); goto cleanup; } if (activation) *activation = _gnutls_x509_get_time(c2, "notBefore", 1); if (expiration) *expiration = _gnutls_x509_get_time(c2, "notAfter", 1); ret = 0; cleanup: asn1_delete_structure(&c2); return ret; } /** * gnutls_x509_crq_get_dn: * @crq: should contain a #gnutls_x509_crq_t type * @buf: a pointer to a structure to hold the name (may be %NULL) * @buf_size: initially holds the size of @buf * * This function will copy the name of the Certificate request subject * to the provided buffer. The name will be in the form * "C=xxxx,O=yyyy,CN=zzzz" as described in RFC 2253. The output string * @buf will be ASCII or UTF-8 encoded, depending on the certificate * data. * * This function does not output a fully RFC4514 compliant string, if * that is required see gnutls_x509_crq_get_dn3(). * * Returns: %GNUTLS_E_SHORT_MEMORY_BUFFER if the provided buffer is not * long enough, and in that case the *@buf_size will be updated with * the required size. On success 0 is returned. **/ int gnutls_x509_crq_get_dn(gnutls_x509_crq_t crq, char *buf, size_t * buf_size) { if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } return _gnutls_x509_parse_dn(crq->crq, "certificationRequestInfo.subject.rdnSequence", buf, buf_size, GNUTLS_X509_DN_FLAG_COMPAT); } /** * gnutls_x509_crq_get_dn2: * @crq: should contain a #gnutls_x509_crq_t type * @dn: a pointer to a structure to hold the name * * This function will allocate buffer and copy the name of the Certificate * request. The name will be in the form "C=xxxx,O=yyyy,CN=zzzz" as * described in RFC4514. The output string will be ASCII or UTF-8 * encoded, depending on the certificate data. * * This function does not output a fully RFC4514 compliant string, if * that is required see gnutls_x509_crq_get_dn3(). * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. and a negative error code on error. * * Since: 3.1.10 **/ int gnutls_x509_crq_get_dn2(gnutls_x509_crq_t crq, gnutls_datum_t * dn) { if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } return _gnutls_x509_get_dn(crq->crq, "certificationRequestInfo.subject.rdnSequence", dn, GNUTLS_X509_DN_FLAG_COMPAT); } /** * gnutls_x509_crq_get_dn3: * @crq: should contain a #gnutls_x509_crq_t type * @dn: a pointer to a structure to hold the name * @flags: zero or %GNUTLS_X509_DN_FLAG_COMPAT * * This function will allocate buffer and copy the name of the Certificate * request. The name will be in the form "C=xxxx,O=yyyy,CN=zzzz" as * described in RFC4514. The output string will be ASCII or UTF-8 * encoded, depending on the certificate data. * * When the flag %GNUTLS_X509_DN_FLAG_COMPAT is specified, the output * format will match the format output by previous to 3.5.6 versions of GnuTLS * which was not not fully RFC4514-compliant. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. and a negative error code on error. * * Since: 3.5.7 **/ int gnutls_x509_crq_get_dn3(gnutls_x509_crq_t crq, gnutls_datum_t * dn, unsigned flags) { if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } return _gnutls_x509_get_dn(crq->crq, "certificationRequestInfo.subject.rdnSequence", dn, flags); } /** * gnutls_x509_crq_get_dn_by_oid: * @crq: should contain a gnutls_x509_crq_t type * @oid: holds an Object Identifier in a null terminated string * @indx: In case multiple same OIDs exist in the RDN, this specifies * which to get. Use (0) to get the first one. * @raw_flag: If non-zero returns the raw DER data of the DN part. * @buf: a pointer to a structure to hold the name (may be %NULL) * @buf_size: initially holds the size of @buf * * This function will extract the part of the name of the Certificate * request subject, specified by the given OID. The output will be * encoded as described in RFC2253. The output string will be ASCII * or UTF-8 encoded, depending on the certificate data. * * Some helper macros with popular OIDs can be found in gnutls/x509.h * If raw flag is (0), this function will only return known OIDs as * text. Other OIDs will be DER encoded, as described in RFC2253 -- * in hex format with a '\#' prefix. You can check about known OIDs * using gnutls_x509_dn_oid_known(). * * Returns: %GNUTLS_E_SHORT_MEMORY_BUFFER if the provided buffer is * not long enough, and in that case the *@buf_size will be * updated with the required size. On success 0 is returned. **/ int gnutls_x509_crq_get_dn_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * buf_size) { gnutls_datum_t td; int ret; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } ret = _gnutls_x509_parse_dn_oid (crq->crq, "certificationRequestInfo.subject.rdnSequence", oid, indx, raw_flag, &td); if (ret < 0) return gnutls_assert_val(ret); return _gnutls_strdatum_to_buf(&td, buf, buf_size); } /** * gnutls_x509_crq_get_dn_oid: * @crq: should contain a gnutls_x509_crq_t type * @indx: Specifies which DN OID to get. Use (0) to get the first one. * @oid: a pointer to a structure to hold the name (may be %NULL) * @sizeof_oid: initially holds the size of @oid * * This function will extract the requested OID of the name of the * certificate request subject, specified by the given index. * * Returns: %GNUTLS_E_SHORT_MEMORY_BUFFER if the provided buffer is * not long enough, and in that case the *@sizeof_oid will be * updated with the required size. On success 0 is returned. **/ int gnutls_x509_crq_get_dn_oid(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid) { if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } return _gnutls_x509_get_dn_oid(crq->crq, "certificationRequestInfo.subject.rdnSequence", indx, oid, sizeof_oid); } /** * gnutls_x509_crq_get_challenge_password: * @crq: should contain a #gnutls_x509_crq_t type * @pass: will hold a (0)-terminated password string * @pass_size: Initially holds the size of @pass. * * This function will return the challenge password in the request. * The challenge password is intended to be used for requesting a * revocation of the certificate. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_get_challenge_password(gnutls_x509_crq_t crq, char *pass, size_t * pass_size) { gnutls_datum_t td; int ret; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } ret = _x509_parse_attribute(crq->crq, "certificationRequestInfo.attributes", "1.2.840.113549.1.9.7", 0, 0, &td); if (ret < 0) return gnutls_assert_val(ret); return _gnutls_strdatum_to_buf(&td, pass, pass_size); } /** * gnutls_x509_crq_set_attribute_by_oid: * @crq: should contain a #gnutls_x509_crq_t type * @oid: holds an Object Identifier in a null-terminated string * @buf: a pointer to a structure that holds the attribute data * @buf_size: holds the size of @buf * * This function will set the attribute in the certificate request * specified by the given Object ID. The provided attribute must be be DER * encoded. * * Attributes in a certificate request is an optional set of data * appended to the request. Their interpretation depends on the CA policy. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_set_attribute_by_oid(gnutls_x509_crq_t crq, const char *oid, void *buf, size_t buf_size) { gnutls_datum_t data; data.data = buf; data.size = buf_size; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } return _x509_set_attribute(crq->crq, "certificationRequestInfo.attributes", oid, &data); } /** * gnutls_x509_crq_get_attribute_by_oid: * @crq: should contain a #gnutls_x509_crq_t type * @oid: holds an Object Identifier in null-terminated string * @indx: In case multiple same OIDs exist in the attribute list, this * specifies which to get, use (0) to get the first one * @buf: a pointer to a structure to hold the attribute data (may be %NULL) * @buf_size: initially holds the size of @buf * * This function will return the attribute in the certificate request * specified by the given Object ID. The attribute will be DER * encoded. * * Attributes in a certificate request is an optional set of data * appended to the request. Their interpretation depends on the CA policy. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_get_attribute_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned indx, void *buf, size_t * buf_size) { int ret; gnutls_datum_t td; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } ret = _x509_parse_attribute(crq->crq, "certificationRequestInfo.attributes", oid, indx, 1, &td); if (ret < 0) return gnutls_assert_val(ret); return _gnutls_strdatum_to_buf(&td, buf, buf_size); } /** * gnutls_x509_crq_set_dn_by_oid: * @crq: should contain a #gnutls_x509_crq_t type * @oid: holds an Object Identifier in a (0)-terminated string * @raw_flag: must be 0, or 1 if the data are DER encoded * @data: a pointer to the input data * @sizeof_data: holds the size of @data * * This function will set the part of the name of the Certificate * request subject, specified by the given OID. The input string * should be ASCII or UTF-8 encoded. * * Some helper macros with popular OIDs can be found in gnutls/x509.h * With this function you can only set the known OIDs. You can test * for known OIDs using gnutls_x509_dn_oid_known(). For OIDs that are * not known (by gnutls) you should properly DER encode your data, and * call this function with raw_flag set. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_set_dn_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned int raw_flag, const void *data, unsigned int sizeof_data) { if (sizeof_data == 0 || data == NULL || crq == NULL) { return GNUTLS_E_INVALID_REQUEST; } return _gnutls_x509_set_dn_oid(crq->crq, "certificationRequestInfo.subject", oid, raw_flag, data, sizeof_data); } /** * gnutls_x509_crq_set_version: * @crq: should contain a #gnutls_x509_crq_t type * @version: holds the version number, for v1 Requests must be 1 * * This function will set the version of the certificate request. For * version 1 requests this must be one. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_set_version(gnutls_x509_crq_t crq, unsigned int version) { int result; unsigned char null = version; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } if (null > 0) null--; result = asn1_write_value(crq->crq, "certificationRequestInfo.version", &null, 1); if (result != ASN1_SUCCESS) { gnutls_assert(); return _gnutls_asn2err(result); } return 0; } /** * gnutls_x509_crq_get_version: * @crq: should contain a #gnutls_x509_crq_t type * * This function will return the version of the specified Certificate * request. * * Returns: version of certificate request, or a negative error code on * error. **/ int gnutls_x509_crq_get_version(gnutls_x509_crq_t crq) { uint8_t version[8]; int len, result; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } len = sizeof(version); if ((result = asn1_read_value(crq->crq, "certificationRequestInfo.version", version, &len)) != ASN1_SUCCESS) { if (result == ASN1_ELEMENT_NOT_FOUND) return 1; /* the DEFAULT version */ gnutls_assert(); return _gnutls_asn2err(result); } return (int) version[0] + 1; } /** * gnutls_x509_crq_set_key: * @crq: should contain a #gnutls_x509_crq_t type * @key: holds a private key * * This function will set the public parameters from the given private * key to the request. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_set_key(gnutls_x509_crq_t crq, gnutls_x509_privkey_t key) { int result; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } result = _gnutls_x509_encode_and_copy_PKI_params (crq->crq, "certificationRequestInfo.subjectPKInfo", &key->params); if (result < 0) { gnutls_assert(); return result; } return 0; } /** * gnutls_x509_crq_get_key_rsa_raw: * @crq: Holds the certificate * @m: will hold the modulus * @e: will hold the public exponent * * This function will export the RSA public key's parameters found in * the given structure. The new parameters will be allocated using * gnutls_malloc() and will be stored in the appropriate datum. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_key_rsa_raw(gnutls_x509_crq_t crq, gnutls_datum_t * m, gnutls_datum_t * e) { int ret; gnutls_pk_params_st params; gnutls_pk_params_init(&params); if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } ret = gnutls_x509_crq_get_pk_algorithm(crq, NULL); if (ret != GNUTLS_PK_RSA) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } ret = _gnutls_x509_crq_get_mpis(crq, &params); if (ret < 0) { gnutls_assert(); return ret; } ret = _gnutls_mpi_dprint(params.params[0], m); if (ret < 0) { gnutls_assert(); goto cleanup; } ret = _gnutls_mpi_dprint(params.params[1], e); if (ret < 0) { gnutls_assert(); _gnutls_free_datum(m); goto cleanup; } ret = 0; cleanup: gnutls_pk_params_release(&params); return ret; } /** * gnutls_x509_crq_set_key_rsa_raw: * @crq: should contain a #gnutls_x509_crq_t type * @m: holds the modulus * @e: holds the public exponent * * This function will set the public parameters from the given private * key to the request. Only RSA keys are currently supported. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. * * Since: 2.6.0 **/ int gnutls_x509_crq_set_key_rsa_raw(gnutls_x509_crq_t crq, const gnutls_datum_t * m, const gnutls_datum_t * e) { int result, ret; size_t siz = 0; gnutls_pk_params_st temp_params; gnutls_pk_params_init(&temp_params); if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } memset(&temp_params, 0, sizeof(temp_params)); siz = m->size; if (_gnutls_mpi_init_scan_nz(&temp_params.params[0], m->data, siz)) { gnutls_assert(); ret = GNUTLS_E_MPI_SCAN_FAILED; goto error; } siz = e->size; if (_gnutls_mpi_init_scan_nz(&temp_params.params[1], e->data, siz)) { gnutls_assert(); ret = GNUTLS_E_MPI_SCAN_FAILED; goto error; } temp_params.params_nr = RSA_PUBLIC_PARAMS; temp_params.algo = GNUTLS_PK_RSA; result = _gnutls_x509_encode_and_copy_PKI_params (crq->crq, "certificationRequestInfo.subjectPKInfo", &temp_params); if (result < 0) { gnutls_assert(); ret = result; goto error; } ret = 0; error: gnutls_pk_params_release(&temp_params); return ret; } /** * gnutls_x509_crq_set_challenge_password: * @crq: should contain a #gnutls_x509_crq_t type * @pass: holds a (0)-terminated password * * This function will set a challenge password to be used when * revoking the request. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_set_challenge_password(gnutls_x509_crq_t crq, const char *pass) { int result; char *password = NULL; if (crq == NULL || pass == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } /* Add the attribute. */ result = asn1_write_value(crq->crq, "certificationRequestInfo.attributes", "NEW", 1); if (result != ASN1_SUCCESS) { gnutls_assert(); return _gnutls_asn2err(result); } if (pass) { gnutls_datum_t out; result = _gnutls_utf8_password_normalize(pass, strlen(pass), &out, 0); if (result < 0) return gnutls_assert_val(result); password = (char*)out.data; } assert(password != NULL); result = _gnutls_x509_encode_and_write_attribute ("1.2.840.113549.1.9.7", crq->crq, "certificationRequestInfo.attributes.?LAST", password, strlen(password), 1); if (result < 0) { gnutls_assert(); goto cleanup; } result = 0; cleanup: gnutls_free(password); return result; } /** * gnutls_x509_crq_sign2: * @crq: should contain a #gnutls_x509_crq_t type * @key: holds a private key * @dig: The message digest to use, i.e., %GNUTLS_DIG_SHA256 * @flags: must be 0 * * This function will sign the certificate request with a private key. * This must be the same key as the one used in * gnutls_x509_crt_set_key() since a certificate request is self * signed. * * This must be the last step in a certificate request generation * since all the previously set parameters are now signed. * * A known limitation of this function is, that a newly-signed request will not * be fully functional (e.g., for signature verification), until it * is exported an re-imported. * * After GnuTLS 3.6.1 the value of @dig may be %GNUTLS_DIG_UNKNOWN, * and in that case, a suitable but reasonable for the key algorithm will be selected. * * Returns: %GNUTLS_E_SUCCESS on success, otherwise a negative error code. * %GNUTLS_E_ASN1_VALUE_NOT_FOUND is returned if you didn't set all * information in the certificate request (e.g., the version using * gnutls_x509_crq_set_version()). * **/ int gnutls_x509_crq_sign2(gnutls_x509_crq_t crq, gnutls_x509_privkey_t key, gnutls_digest_algorithm_t dig, unsigned int flags) { int result; gnutls_privkey_t privkey; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } result = gnutls_privkey_init(&privkey); if (result < 0) { gnutls_assert(); return result; } result = gnutls_privkey_import_x509(privkey, key, 0); if (result < 0) { gnutls_assert(); goto fail; } result = gnutls_x509_crq_privkey_sign(crq, privkey, dig, flags); if (result < 0) { gnutls_assert(); goto fail; } result = 0; fail: gnutls_privkey_deinit(privkey); return result; } /** * gnutls_x509_crq_sign: * @crq: should contain a #gnutls_x509_crq_t type * @key: holds a private key * * This function is the same a gnutls_x509_crq_sign2() with no flags, * and an appropriate hash algorithm. The hash algorithm used may * vary between versions of GnuTLS, and it is tied to the security * level of the issuer's public key. * * A known limitation of this function is, that a newly-signed request will not * be fully functional (e.g., for signature verification), until it * is exported an re-imported. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. */ int gnutls_x509_crq_sign(gnutls_x509_crq_t crq, gnutls_x509_privkey_t key) { return gnutls_x509_crq_sign2(crq, key, 0, 0); } /** * gnutls_x509_crq_export: * @crq: should contain a #gnutls_x509_crq_t type * @format: the format of output params. One of PEM or DER. * @output_data: will contain a certificate request PEM or DER encoded * @output_data_size: holds the size of output_data (and will be * replaced by the actual size of parameters) * * This function will export the certificate request to a PEM or DER * encoded PKCS10 structure. * * If the buffer provided is not long enough to hold the output, then * %GNUTLS_E_SHORT_MEMORY_BUFFER will be returned and * *@output_data_size will be updated. * * If the structure is PEM encoded, it will have a header of "BEGIN * NEW CERTIFICATE REQUEST". * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_export(gnutls_x509_crq_t crq, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size) { if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } return _gnutls_x509_export_int(crq->crq, format, PEM_CRQ, output_data, output_data_size); } /** * gnutls_x509_crq_export2: * @crq: should contain a #gnutls_x509_crq_t type * @format: the format of output params. One of PEM or DER. * @out: will contain a certificate request PEM or DER encoded * * This function will export the certificate request to a PEM or DER * encoded PKCS10 structure. * * The output buffer is allocated using gnutls_malloc(). * * If the structure is PEM encoded, it will have a header of "BEGIN * NEW CERTIFICATE REQUEST". * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. * * Since 3.1.3 **/ int gnutls_x509_crq_export2(gnutls_x509_crq_t crq, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out) { if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } return _gnutls_x509_export_int2(crq->crq, format, PEM_CRQ, out); } /** * gnutls_x509_crq_get_pk_algorithm: * @crq: should contain a #gnutls_x509_crq_t type * @bits: if bits is non-%NULL it will hold the size of the parameters' in bits * * This function will return the public key algorithm of a PKCS#10 * certificate request. * * If bits is non-%NULL, it should have enough size to hold the * parameters size in bits. For RSA the bits returned is the modulus. * For DSA the bits returned are of the public exponent. * * Returns: a member of the #gnutls_pk_algorithm_t enumeration on * success, or a negative error code on error. **/ int gnutls_x509_crq_get_pk_algorithm(gnutls_x509_crq_t crq, unsigned int *bits) { int result; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } result = _gnutls_x509_get_pk_algorithm (crq->crq, "certificationRequestInfo.subjectPKInfo", NULL, bits); if (result < 0) { gnutls_assert(); return result; } return result; } /** * gnutls_x509_crq_get_spki; * @crq: should contain a #gnutls_x509_crq_t type * @spki: a SubjectPublicKeyInfo structure of type #gnutls_x509_spki_t * @flags: must be zero * * This function will return the public key information of a PKCS#10 * certificate request. The provided @spki must be initialized. * * Returns: Zero on success, or a negative error code on error. **/ int gnutls_x509_crq_get_spki(gnutls_x509_crq_t crq, gnutls_x509_spki_t spki, unsigned int flags) { int result; gnutls_x509_spki_st params; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } memset(&params, 0, sizeof(params)); spki->pk = gnutls_x509_crq_get_pk_algorithm(crq, NULL); result = _gnutls_x509_crq_read_spki_params(crq, &params); if (result < 0) { gnutls_assert(); return result; } if (params.pk == GNUTLS_PK_UNKNOWN) return gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE); spki->rsa_pss_dig = params.rsa_pss_dig; spki->salt_size = params.salt_size; return 0; } /** * gnutls_x509_crq_get_signature_oid: * @crq: should contain a #gnutls_x509_crq_t type * @oid: a pointer to a buffer to hold the OID (may be null) * @oid_size: initially holds the size of @oid * * This function will return the OID of the signature algorithm * that has been used to sign this certificate request. This function * is useful in the case gnutls_x509_crq_get_signature_algorithm() * returned %GNUTLS_SIGN_UNKNOWN. * * Returns: zero or a negative error code on error. * * Since: 3.5.0 **/ int gnutls_x509_crq_get_signature_oid(gnutls_x509_crq_t crq, char *oid, size_t *oid_size) { char str[MAX_OID_SIZE]; int len, result, ret; gnutls_datum_t out; len = sizeof(str); result = asn1_read_value(crq->crq, "signatureAlgorithm.algorithm", str, &len); if (result != ASN1_SUCCESS) { gnutls_assert(); return _gnutls_asn2err(result); } out.data = (void*)str; out.size = len; ret = _gnutls_copy_string(&out, (void*)oid, oid_size); if (ret < 0) { gnutls_assert(); return ret; } return 0; } /** * gnutls_x509_crq_get_pk_oid: * @crq: should contain a #gnutls_x509_crq_t type * @oid: a pointer to a buffer to hold the OID (may be null) * @oid_size: initially holds the size of @oid * * This function will return the OID of the public key algorithm * on that certificate request. This function * is useful in the case gnutls_x509_crq_get_pk_algorithm() * returned %GNUTLS_PK_UNKNOWN. * * Returns: zero or a negative error code on error. * * Since: 3.5.0 **/ int gnutls_x509_crq_get_pk_oid(gnutls_x509_crq_t crq, char *oid, size_t *oid_size) { char str[MAX_OID_SIZE]; int len, result, ret; gnutls_datum_t out; len = sizeof(str); result = asn1_read_value(crq->crq, "certificationRequestInfo.subjectPKInfo.algorithm.algorithm", str, &len); if (result != ASN1_SUCCESS) { gnutls_assert(); return _gnutls_asn2err(result); } out.data = (void*)str; out.size = len; ret = _gnutls_copy_string(&out, (void*)oid, oid_size); if (ret < 0) { gnutls_assert(); return ret; } return 0; } /** * gnutls_x509_crq_get_attribute_info: * @crq: should contain a #gnutls_x509_crq_t type * @indx: Specifies which attribute number to get. Use (0) to get the first one. * @oid: a pointer to a structure to hold the OID * @sizeof_oid: initially holds the maximum size of @oid, on return * holds actual size of @oid. * * This function will return the requested attribute OID in the * certificate, and the critical flag for it. The attribute OID will * be stored as a string in the provided buffer. Use * gnutls_x509_crq_get_attribute_data() to extract the data. * * If the buffer provided is not long enough to hold the output, then * *@sizeof_oid is updated and %GNUTLS_E_SHORT_MEMORY_BUFFER will be * returned. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error code in case of an error. If your have reached the * last extension available %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE * will be returned. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_attribute_info(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid) { int result; char name[MAX_NAME_SIZE]; int len; if (!crq) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } snprintf(name, sizeof(name), "certificationRequestInfo.attributes.?%u.type", indx + 1); len = *sizeof_oid; result = asn1_read_value(crq->crq, name, oid, &len); *sizeof_oid = len; if (result == ASN1_ELEMENT_NOT_FOUND) return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; else if (result < 0) { gnutls_assert(); return _gnutls_asn2err(result); } return 0; } /** * gnutls_x509_crq_get_attribute_data: * @crq: should contain a #gnutls_x509_crq_t type * @indx: Specifies which attribute number to get. Use (0) to get the first one. * @data: a pointer to a structure to hold the data (may be null) * @sizeof_data: initially holds the size of @oid * * This function will return the requested attribute data in the * certificate request. The attribute data will be stored as a string in the * provided buffer. * * Use gnutls_x509_crq_get_attribute_info() to extract the OID. * Use gnutls_x509_crq_get_attribute_by_oid() instead, * if you want to get data indexed by the attribute OID rather than * sequence. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error code in case of an error. If your have reached the * last extension available %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE * will be returned. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_attribute_data(gnutls_x509_crq_t crq, unsigned indx, void *data, size_t * sizeof_data) { int result, len; char name[MAX_NAME_SIZE]; if (!crq) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } snprintf(name, sizeof(name), "certificationRequestInfo.attributes.?%u.values.?1", indx + 1); len = *sizeof_data; result = asn1_read_value(crq->crq, name, data, &len); *sizeof_data = len; if (result == ASN1_ELEMENT_NOT_FOUND) return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; else if (result < 0) { gnutls_assert(); return _gnutls_asn2err(result); } return 0; } /** * gnutls_x509_crq_get_extension_info: * @crq: should contain a #gnutls_x509_crq_t type * @indx: Specifies which extension number to get. Use (0) to get the first one. * @oid: a pointer to store the OID * @sizeof_oid: initially holds the maximum size of @oid, on return * holds actual size of @oid. * @critical: output variable with critical flag, may be NULL. * * This function will return the requested extension OID in the * certificate, and the critical flag for it. The extension OID will * be stored as a string in the provided buffer. Use * gnutls_x509_crq_get_extension_data() to extract the data. * * If the buffer provided is not long enough to hold the output, then * *@sizeof_oid is updated and %GNUTLS_E_SHORT_MEMORY_BUFFER will be * returned. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error code in case of an error. If your have reached the * last extension available %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE * will be returned. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_extension_info(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid, unsigned int *critical) { int result; char str_critical[10]; char name[MAX_NAME_SIZE]; char *extensions = NULL; size_t extensions_size = 0; ASN1_TYPE c2; int len; if (!crq) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } /* read extensionRequest */ result = gnutls_x509_crq_get_attribute_by_oid(crq, "1.2.840.113549.1.9.14", 0, NULL, &extensions_size); if (result == GNUTLS_E_SHORT_MEMORY_BUFFER) { extensions = gnutls_malloc(extensions_size); if (extensions == NULL) { gnutls_assert(); return GNUTLS_E_MEMORY_ERROR; } result = gnutls_x509_crq_get_attribute_by_oid(crq, "1.2.840.113549.1.9.14", 0, extensions, &extensions_size); } if (result < 0) { gnutls_assert(); goto out; } result = asn1_create_element(_gnutls_get_pkix(), "PKIX1.Extensions", &c2); if (result != ASN1_SUCCESS) { gnutls_assert(); result = _gnutls_asn2err(result); goto out; } result = _asn1_strict_der_decode(&c2, extensions, extensions_size, NULL); if (result != ASN1_SUCCESS) { gnutls_assert(); asn1_delete_structure(&c2); result = _gnutls_asn2err(result); goto out; } snprintf(name, sizeof(name), "?%u.extnID", indx + 1); len = *sizeof_oid; result = asn1_read_value(c2, name, oid, &len); *sizeof_oid = len; if (result == ASN1_ELEMENT_NOT_FOUND) { asn1_delete_structure(&c2); result = GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; goto out; } else if (result < 0) { gnutls_assert(); asn1_delete_structure(&c2); result = _gnutls_asn2err(result); goto out; } snprintf(name, sizeof(name), "?%u.critical", indx + 1); len = sizeof(str_critical); result = asn1_read_value(c2, name, str_critical, &len); asn1_delete_structure(&c2); if (result < 0) { gnutls_assert(); result = _gnutls_asn2err(result); goto out; } if (critical) { if (str_critical[0] == 'T') *critical = 1; else *critical = 0; } result = 0; out: gnutls_free(extensions); return result; } /** * gnutls_x509_crq_get_extension_data: * @crq: should contain a #gnutls_x509_crq_t type * @indx: Specifies which extension number to get. Use (0) to get the first one. * @data: a pointer to a structure to hold the data (may be null) * @sizeof_data: initially holds the size of @oid * * This function will return the requested extension data in the * certificate. The extension data will be stored as a string in the * provided buffer. * * Use gnutls_x509_crq_get_extension_info() to extract the OID and * critical flag. Use gnutls_x509_crq_get_extension_by_oid() instead, * if you want to get data indexed by the extension OID rather than * sequence. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error code in case of an error. If your have reached the * last extension available %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE * will be returned. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_extension_data(gnutls_x509_crq_t crq, unsigned indx, void *data, size_t * sizeof_data) { int ret; gnutls_datum_t raw; ret = gnutls_x509_crq_get_extension_data2(crq, indx, &raw); if (ret < 0) return gnutls_assert_val(ret); ret = _gnutls_copy_data(&raw, data, sizeof_data); if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER && data == NULL) ret = 0; gnutls_free(raw.data); return ret; } /** * gnutls_x509_crq_get_extension_data2: * @crq: should contain a #gnutls_x509_crq_t type * @extension_id: An X.509 extension OID. * @indx: Specifies which extension OID to read. Use (0) to get the first one. * @data: will contain the extension DER-encoded data * * This function will return the requested extension data in the * certificate request. The extension data will be allocated using * gnutls_malloc(). * * Use gnutls_x509_crq_get_extension_info() to extract the OID. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, * otherwise a negative error code is returned. If you have reached the * last extension available %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE * will be returned. * * Since: 3.3.0 **/ int gnutls_x509_crq_get_extension_data2(gnutls_x509_crq_t crq, unsigned indx, gnutls_datum_t * data) { int ret, result; char name[MAX_NAME_SIZE]; unsigned char *extensions = NULL; size_t extensions_size = 0; ASN1_TYPE c2 = ASN1_TYPE_EMPTY; if (!crq) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } /* read extensionRequest */ ret = gnutls_x509_crq_get_attribute_by_oid(crq, "1.2.840.113549.1.9.14", 0, NULL, &extensions_size); if (ret != GNUTLS_E_SHORT_MEMORY_BUFFER) { gnutls_assert(); if (ret == 0) return GNUTLS_E_INTERNAL_ERROR; return ret; } extensions = gnutls_malloc(extensions_size); if (extensions == NULL) { gnutls_assert(); return GNUTLS_E_MEMORY_ERROR; } ret = gnutls_x509_crq_get_attribute_by_oid(crq, "1.2.840.113549.1.9.14", 0, extensions, &extensions_size); if (ret < 0) { gnutls_assert(); goto cleanup; } result = asn1_create_element(_gnutls_get_pkix(), "PKIX1.Extensions", &c2); if (result != ASN1_SUCCESS) { gnutls_assert(); ret = _gnutls_asn2err(result); goto cleanup; } result = _asn1_strict_der_decode(&c2, extensions, extensions_size, NULL); if (result != ASN1_SUCCESS) { gnutls_assert(); ret = _gnutls_asn2err(result); goto cleanup; } snprintf(name, sizeof(name), "?%u.extnValue", indx + 1); ret = _gnutls_x509_read_value(c2, name, data); if (ret == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND) { ret = GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; goto cleanup; } else if (ret < 0) { gnutls_assert(); goto cleanup; } ret = 0; cleanup: asn1_delete_structure(&c2); gnutls_free(extensions); return ret; } /** * gnutls_x509_crq_get_key_usage: * @crq: should contain a #gnutls_x509_crq_t type * @key_usage: where the key usage bits will be stored * @critical: will be non-zero if the extension is marked as critical * * This function will return certificate's key usage, by reading the * keyUsage X.509 extension (172.16.17.32). The key usage value will * ORed values of the: %GNUTLS_KEY_DIGITAL_SIGNATURE, * %GNUTLS_KEY_NON_REPUDIATION, %GNUTLS_KEY_KEY_ENCIPHERMENT, * %GNUTLS_KEY_DATA_ENCIPHERMENT, %GNUTLS_KEY_KEY_AGREEMENT, * %GNUTLS_KEY_KEY_CERT_SIGN, %GNUTLS_KEY_CRL_SIGN, * %GNUTLS_KEY_ENCIPHER_ONLY, %GNUTLS_KEY_DECIPHER_ONLY. * * Returns: the certificate key usage, or a negative error code in case of * parsing error. If the certificate does not contain the keyUsage * extension %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE will be * returned. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_key_usage(gnutls_x509_crq_t crq, unsigned int *key_usage, unsigned int *critical) { int result; uint8_t buf[128]; size_t buf_size = sizeof(buf); gnutls_datum_t bd; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } result = gnutls_x509_crq_get_extension_by_oid(crq, "172.16.17.32", 0, buf, &buf_size, critical); if (result < 0) { gnutls_assert(); return result; } bd.data = buf; bd.size = buf_size; result = gnutls_x509_ext_import_key_usage(&bd, key_usage); if (result < 0) { gnutls_assert(); return result; } return 0; } /** * gnutls_x509_crq_get_basic_constraints: * @crq: should contain a #gnutls_x509_crq_t type * @critical: will be non-zero if the extension is marked as critical * @ca: pointer to output integer indicating CA status, may be NULL, * value is 1 if the certificate CA flag is set, 0 otherwise. * @pathlen: pointer to output integer indicating path length (may be * NULL), non-negative error codes indicate a present pathLenConstraint * field and the actual value, -1 indicate that the field is absent. * * This function will read the certificate's basic constraints, and * return the certificates CA status. It reads the basicConstraints * X.509 extension (172.16.31.109). * * Returns: If the certificate is a CA a positive value will be * returned, or (0) if the certificate does not have CA flag set. * A negative error code may be returned in case of errors. If the * certificate does not contain the basicConstraints extension * %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE will be returned. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_basic_constraints(gnutls_x509_crq_t crq, unsigned int *critical, unsigned int *ca, int *pathlen) { int result; unsigned int tmp_ca; uint8_t buf[256]; size_t buf_size = sizeof(buf); gnutls_datum_t bd; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } result = gnutls_x509_crq_get_extension_by_oid(crq, "2.5.29.19", 0, buf, &buf_size, critical); if (result < 0) { gnutls_assert(); return result; } bd.data = buf; bd.size = buf_size; result = gnutls_x509_ext_import_basic_constraints(&bd, &tmp_ca, pathlen); if (ca) *ca = tmp_ca; if (result < 0) { gnutls_assert(); return result; } return tmp_ca; } static int get_subject_alt_name(gnutls_x509_crq_t crq, unsigned int seq, void *ret, size_t * ret_size, unsigned int *ret_type, unsigned int *critical, int othername_oid) { int result; ASN1_TYPE c2 = ASN1_TYPE_EMPTY; gnutls_x509_subject_alt_name_t type; gnutls_datum_t dnsname = { NULL, 0 }; size_t dns_size = 0; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } if (ret) memset(ret, 0, *ret_size); else *ret_size = 0; /* Extract extension. */ result = gnutls_x509_crq_get_extension_by_oid(crq, "172.16.31.10", 0, NULL, &dns_size, critical); if (result < 0) { gnutls_assert(); return result; } dnsname.size = dns_size; dnsname.data = gnutls_malloc(dnsname.size); if (dnsname.data == NULL) { gnutls_assert(); return GNUTLS_E_MEMORY_ERROR; } result = gnutls_x509_crq_get_extension_by_oid(crq, "172.16.31.10", 0, dnsname.data, &dns_size, critical); if (result < 0) { gnutls_assert(); gnutls_free(dnsname.data); return result; } result = asn1_create_element (_gnutls_get_pkix(), "PKIX1.SubjectAltName", &c2); if (result != ASN1_SUCCESS) { gnutls_assert(); gnutls_free(dnsname.data); return _gnutls_asn2err(result); } result = _asn1_strict_der_decode(&c2, dnsname.data, dnsname.size, NULL); gnutls_free(dnsname.data); if (result != ASN1_SUCCESS) { gnutls_assert(); asn1_delete_structure(&c2); return _gnutls_asn2err(result); } result = _gnutls_parse_general_name(c2, "", seq, ret, ret_size, ret_type, othername_oid); asn1_delete_structure(&c2); if (result < 0) { return result; } type = result; return type; } /** * gnutls_x509_crq_get_subject_alt_name: * @crq: should contain a #gnutls_x509_crq_t type * @seq: specifies the sequence number of the alt name, 0 for the * first one, 1 for the second etc. * @ret: is the place where the alternative name will be copied to * @ret_size: holds the size of ret. * @ret_type: holds the #gnutls_x509_subject_alt_name_t name type * @critical: will be non-zero if the extension is marked as critical * (may be null) * * This function will return the alternative names, contained in the * given certificate. It is the same as * gnutls_x509_crq_get_subject_alt_name() except for the fact that it * will return the type of the alternative name in @ret_type even if * the function fails for some reason (i.e. the buffer provided is * not enough). * * Returns: the alternative subject name type on success, one of the * enumerated #gnutls_x509_subject_alt_name_t. It will return * %GNUTLS_E_SHORT_MEMORY_BUFFER if @ret_size is not large enough to * hold the value. In that case @ret_size will be updated with the * required size. If the certificate request does not have an * Alternative name with the specified sequence number then * %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE is returned. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_subject_alt_name(gnutls_x509_crq_t crq, unsigned int seq, void *ret, size_t * ret_size, unsigned int *ret_type, unsigned int *critical) { return get_subject_alt_name(crq, seq, ret, ret_size, ret_type, critical, 0); } /** * gnutls_x509_crq_get_subject_alt_othername_oid: * @crq: should contain a #gnutls_x509_crq_t type * @seq: specifies the sequence number of the alt name (0 for the first one, 1 for the second etc.) * @ret: is the place where the otherName OID will be copied to * @ret_size: holds the size of ret. * * This function will extract the type OID of an otherName Subject * Alternative Name, contained in the given certificate, and return * the type as an enumerated element. * * This function is only useful if * gnutls_x509_crq_get_subject_alt_name() returned * %GNUTLS_SAN_OTHERNAME. * * Returns: the alternative subject name type on success, one of the * enumerated gnutls_x509_subject_alt_name_t. For supported OIDs, * it will return one of the virtual (GNUTLS_SAN_OTHERNAME_*) types, * e.g. %GNUTLS_SAN_OTHERNAME_XMPP, and %GNUTLS_SAN_OTHERNAME for * unknown OIDs. It will return %GNUTLS_E_SHORT_MEMORY_BUFFER if * @ret_size is not large enough to hold the value. In that case * @ret_size will be updated with the required size. If the * certificate does not have an Alternative name with the specified * sequence number and with the otherName type then * %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE is returned. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_subject_alt_othername_oid(gnutls_x509_crq_t crq, unsigned int seq, void *ret, size_t * ret_size) { return get_subject_alt_name(crq, seq, ret, ret_size, NULL, NULL, 1); } /** * gnutls_x509_crq_get_extension_by_oid: * @crq: should contain a #gnutls_x509_crq_t type * @oid: holds an Object Identifier in a null terminated string * @indx: In case multiple same OIDs exist in the extensions, this * specifies which to get. Use (0) to get the first one. * @buf: a pointer to a structure to hold the name (may be null) * @buf_size: initially holds the size of @buf * @critical: will be non-zero if the extension is marked as critical * * This function will return the extension specified by the OID in * the certificate. The extensions will be returned as binary data * DER encoded, in the provided buffer. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error code in case of an error. If the certificate does not * contain the specified extension * %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE will be returned. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_extension_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned indx, void *buf, size_t * buf_size, unsigned int *critical) { int result; unsigned int i; char _oid[MAX_OID_SIZE]; size_t oid_size; for (i = 0;; i++) { oid_size = sizeof(_oid); result = gnutls_x509_crq_get_extension_info(crq, i, _oid, &oid_size, critical); if (result < 0) { gnutls_assert(); return result; } if (strcmp(oid, _oid) == 0) { /* found */ if (indx == 0) return gnutls_x509_crq_get_extension_data(crq, i, buf, buf_size); else indx--; } } return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; } /** * gnutls_x509_crq_get_extension_by_oid2: * @crq: should contain a #gnutls_x509_crq_t type * @oid: holds an Object Identifier in a null terminated string * @indx: In case multiple same OIDs exist in the extensions, this * specifies which to get. Use (0) to get the first one. * @output: will hold the allocated extension data * @critical: will be non-zero if the extension is marked as critical * * This function will return the extension specified by the OID in * the certificate. The extensions will be returned as binary data * DER encoded, in the provided buffer. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error code in case of an error. If the certificate does not * contain the specified extension * %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE will be returned. * * Since: 3.3.8 **/ int gnutls_x509_crq_get_extension_by_oid2(gnutls_x509_crq_t crq, const char *oid, unsigned indx, gnutls_datum_t *output, unsigned int *critical) { int result; unsigned int i; char _oid[MAX_OID_SIZE]; size_t oid_size; for (i = 0;; i++) { oid_size = sizeof(_oid); result = gnutls_x509_crq_get_extension_info(crq, i, _oid, &oid_size, critical); if (result < 0) { gnutls_assert(); return result; } if (strcmp(oid, _oid) == 0) { /* found */ if (indx == 0) return gnutls_x509_crq_get_extension_data2(crq, i, output); else indx--; } } return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; } /** * gnutls_x509_crq_set_subject_alt_name: * @crq: a certificate request of type #gnutls_x509_crq_t * @nt: is one of the #gnutls_x509_subject_alt_name_t enumerations * @data: The data to be set * @data_size: The size of data to be set * @flags: %GNUTLS_FSAN_SET to clear previous data or * %GNUTLS_FSAN_APPEND to append. * * This function will set the subject alternative name certificate * extension. It can set the following types: * * %GNUTLS_SAN_DNSNAME: as a text string * * %GNUTLS_SAN_RFC822NAME: as a text string * * %GNUTLS_SAN_URI: as a text string * * %GNUTLS_SAN_IPADDRESS: as a binary IP address (4 or 16 bytes) * * %GNUTLS_SAN_OTHERNAME_XMPP: as a UTF8 string * * Since version 3.5.7 the %GNUTLS_SAN_RFC822NAME, %GNUTLS_SAN_DNSNAME, and * %GNUTLS_SAN_OTHERNAME_XMPP are converted to ACE format when necessary. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. * * Since: 2.8.0 **/ int gnutls_x509_crq_set_subject_alt_name(gnutls_x509_crq_t crq, gnutls_x509_subject_alt_name_t nt, const void *data, unsigned int data_size, unsigned int flags) { int result = 0; gnutls_datum_t der_data = { NULL, 0 }; gnutls_datum_t prev_der_data = { NULL, 0 }; unsigned int critical = 0; size_t prev_data_size = 0; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } /* Check if the extension already exists. */ if (flags & GNUTLS_FSAN_APPEND) { result = gnutls_x509_crq_get_extension_by_oid(crq, "2.5.29.17", 0, NULL, &prev_data_size, &critical); prev_der_data.size = prev_data_size; switch (result) { case GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE: /* Replacing non-existing data means the same as set data. */ break; case GNUTLS_E_SUCCESS: prev_der_data.data = gnutls_malloc(prev_der_data.size); if (prev_der_data.data == NULL) { gnutls_assert(); return GNUTLS_E_MEMORY_ERROR; } result = gnutls_x509_crq_get_extension_by_oid(crq, "2.5.29.17", 0, prev_der_data. data, &prev_data_size, &critical); if (result < 0) { gnutls_assert(); gnutls_free(prev_der_data.data); return result; } break; default: gnutls_assert(); return result; } } /* generate the extension. */ result = _gnutls_x509_ext_gen_subject_alt_name(nt, NULL, data, data_size, &prev_der_data, &der_data); gnutls_free(prev_der_data.data); if (result < 0) { gnutls_assert(); goto finish; } result = _gnutls_x509_crq_set_extension(crq, "2.5.29.17", &der_data, critical); _gnutls_free_datum(&der_data); if (result < 0) { gnutls_assert(); return result; } return 0; finish: return result; } /** * gnutls_x509_crq_set_subject_alt_othername: * @crq: a certificate request of type #gnutls_x509_crq_t * @oid: is the othername OID * @data: The data to be set * @data_size: The size of data to be set * @flags: %GNUTLS_FSAN_SET to clear previous data or * %GNUTLS_FSAN_APPEND to append. * * This function will set the subject alternative name certificate * extension. It can set the following types: * * The values set must be binary values and must be properly DER encoded. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. * * Since: 3.5.0 **/ int gnutls_x509_crq_set_subject_alt_othername(gnutls_x509_crq_t crq, const char *oid, const void *data, unsigned int data_size, unsigned int flags) { int result = 0; gnutls_datum_t der_data = { NULL, 0 }; gnutls_datum_t encoded_data = { NULL, 0 }; gnutls_datum_t prev_der_data = { NULL, 0 }; unsigned int critical = 0; size_t prev_data_size = 0; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } /* Check if the extension already exists. */ if (flags & GNUTLS_FSAN_APPEND) { result = gnutls_x509_crq_get_extension_by_oid(crq, "172.16.31.10", 0, NULL, &prev_data_size, &critical); prev_der_data.size = prev_data_size; switch (result) { case GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE: /* Replacing non-existing data means the same as set data. */ break; case GNUTLS_E_SUCCESS: prev_der_data.data = gnutls_malloc(prev_der_data.size); if (prev_der_data.data == NULL) { gnutls_assert(); return GNUTLS_E_MEMORY_ERROR; } result = gnutls_x509_crq_get_extension_by_oid(crq, "172.16.31.10", 0, prev_der_data. data, &prev_data_size, &critical); if (result < 0) { gnutls_assert(); goto finish; } break; default: gnutls_assert(); return result; } } result = _gnutls_encode_othername_data(flags, data, data_size, &encoded_data); if (result < 0) { gnutls_assert(); goto finish; } /* generate the extension. */ result = _gnutls_x509_ext_gen_subject_alt_name(GNUTLS_SAN_OTHERNAME, oid, encoded_data.data, encoded_data.size, &prev_der_data, &der_data); if (result < 0) { gnutls_assert(); goto finish; } result = _gnutls_x509_crq_set_extension(crq, "2.5.29.17", &der_data, critical); if (result < 0) { gnutls_assert(); goto finish; } result = 0; finish: _gnutls_free_datum(&prev_der_data); _gnutls_free_datum(&der_data); _gnutls_free_datum(&encoded_data); return result; } /** * gnutls_x509_crq_set_basic_constraints: * @crq: a certificate request of type #gnutls_x509_crq_t * @ca: true(1) or false(0) depending on the Certificate authority status. * @pathLenConstraint: non-negative error codes indicate maximum length of path, * and negative error codes indicate that the pathLenConstraints field should * not be present. * * This function will set the basicConstraints certificate extension. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. * * Since: 2.8.0 **/ int gnutls_x509_crq_set_basic_constraints(gnutls_x509_crq_t crq, unsigned int ca, int pathLenConstraint) { int result; gnutls_datum_t der_data; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } /* generate the extension. */ result = gnutls_x509_ext_export_basic_constraints(ca, pathLenConstraint, &der_data); if (result < 0) { gnutls_assert(); return result; } result = _gnutls_x509_crq_set_extension(crq, "192.168.3.11", &der_data, 1); _gnutls_free_datum(&der_data); if (result < 0) { gnutls_assert(); return result; } return 0; } /** * gnutls_x509_crq_set_key_usage: * @crq: a certificate request of type #gnutls_x509_crq_t * @usage: an ORed sequence of the GNUTLS_KEY_* elements. * * This function will set the keyUsage certificate extension. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. * * Since: 2.8.0 **/ int gnutls_x509_crq_set_key_usage(gnutls_x509_crq_t crq, unsigned int usage) { int result; gnutls_datum_t der_data; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } /* generate the extension. */ result = gnutls_x509_ext_export_key_usage(usage, &der_data); if (result < 0) { gnutls_assert(); return result; } result = _gnutls_x509_crq_set_extension(crq, "172.16.17.32", &der_data, 1); _gnutls_free_datum(&der_data); if (result < 0) { gnutls_assert(); return result; } return 0; } /** * gnutls_x509_crq_get_key_purpose_oid: * @crq: should contain a #gnutls_x509_crq_t type * @indx: This specifies which OID to return, use (0) to get the first one * @oid: a pointer to store the OID (may be %NULL) * @sizeof_oid: initially holds the size of @oid * @critical: output variable with critical flag, may be %NULL. * * This function will extract the key purpose OIDs of the Certificate * specified by the given index. These are stored in the Extended Key * Usage extension (172.16.58.3). See the GNUTLS_KP_* definitions for * human readable names. * * Returns: %GNUTLS_E_SHORT_MEMORY_BUFFER if the provided buffer is * not long enough, and in that case the *@sizeof_oid will be * updated with the required size. On success 0 is returned. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_key_purpose_oid(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid, unsigned int *critical) { char tmpstr[MAX_NAME_SIZE]; int result, len; gnutls_datum_t prev = { NULL, 0 }; ASN1_TYPE c2 = ASN1_TYPE_EMPTY; size_t prev_size = 0; if (oid) memset(oid, 0, *sizeof_oid); else *sizeof_oid = 0; /* Extract extension. */ result = gnutls_x509_crq_get_extension_by_oid(crq, "2.5.29.37", 0, NULL, &prev_size, critical); prev.size = prev_size; if (result < 0) { gnutls_assert(); return result; } prev.data = gnutls_malloc(prev.size); if (prev.data == NULL) { gnutls_assert(); return GNUTLS_E_MEMORY_ERROR; } result = gnutls_x509_crq_get_extension_by_oid(crq, "2.5.29.37", 0, prev.data, &prev_size, critical); if (result < 0) { gnutls_assert(); gnutls_free(prev.data); return result; } result = asn1_create_element (_gnutls_get_pkix(), "PKIX1.ExtKeyUsageSyntax", &c2); if (result != ASN1_SUCCESS) { gnutls_assert(); gnutls_free(prev.data); return _gnutls_asn2err(result); } result = _asn1_strict_der_decode(&c2, prev.data, prev.size, NULL); gnutls_free(prev.data); if (result != ASN1_SUCCESS) { gnutls_assert(); asn1_delete_structure(&c2); return _gnutls_asn2err(result); } indx++; /* create a string like "?1" */ snprintf(tmpstr, sizeof(tmpstr), "?%u", indx); len = *sizeof_oid; result = asn1_read_value(c2, tmpstr, oid, &len); *sizeof_oid = len; asn1_delete_structure(&c2); if (result == ASN1_VALUE_NOT_FOUND || result == ASN1_ELEMENT_NOT_FOUND) { return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; } if (result != ASN1_SUCCESS) { if (result != ASN1_MEM_ERROR) gnutls_assert(); return _gnutls_asn2err(result); } return 0; } /** * gnutls_x509_crq_set_key_purpose_oid: * @crq: a certificate of type #gnutls_x509_crq_t * @oid: a pointer to a null-terminated string that holds the OID * @critical: Whether this extension will be critical or not * * This function will set the key purpose OIDs of the Certificate. * These are stored in the Extended Key Usage extension (172.16.58.3) * See the GNUTLS_KP_* definitions for human readable names. * * Subsequent calls to this function will append OIDs to the OID list. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. * * Since: 2.8.0 **/ int gnutls_x509_crq_set_key_purpose_oid(gnutls_x509_crq_t crq, const void *oid, unsigned int critical) { int result; gnutls_datum_t prev = { NULL, 0 }, der_data; ASN1_TYPE c2 = ASN1_TYPE_EMPTY; size_t prev_size = 0; /* Read existing extension, if there is one. */ result = gnutls_x509_crq_get_extension_by_oid(crq, "172.16.58.3", 0, NULL, &prev_size, &critical); prev.size = prev_size; switch (result) { case GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE: /* No existing extension, that's fine. */ break; case GNUTLS_E_SUCCESS: prev.data = gnutls_malloc(prev.size); if (prev.data == NULL) { gnutls_assert(); return GNUTLS_E_MEMORY_ERROR; } result = gnutls_x509_crq_get_extension_by_oid(crq, "2.5.29.37", 0, prev.data, &prev_size, &critical); if (result < 0) { gnutls_assert(); gnutls_free(prev.data); return result; } break; default: gnutls_assert(); return result; } result = asn1_create_element(_gnutls_get_pkix(), "PKIX1.ExtKeyUsageSyntax", &c2); if (result != ASN1_SUCCESS) { gnutls_assert(); gnutls_free(prev.data); return _gnutls_asn2err(result); } if (prev.data) { /* decode it. */ result = _asn1_strict_der_decode(&c2, prev.data, prev.size, NULL); gnutls_free(prev.data); if (result != ASN1_SUCCESS) { gnutls_assert(); asn1_delete_structure(&c2); return _gnutls_asn2err(result); } } /* generate the extension. */ /* 1. create a new element. */ result = asn1_write_value(c2, "", "NEW", 1); if (result != ASN1_SUCCESS) { gnutls_assert(); asn1_delete_structure(&c2); return _gnutls_asn2err(result); } /* 2. Add the OID. */ result = asn1_write_value(c2, "?LAST", oid, 1); if (result != ASN1_SUCCESS) { gnutls_assert(); asn1_delete_structure(&c2); return _gnutls_asn2err(result); } result = _gnutls_x509_der_encode(c2, "", &der_data, 0); asn1_delete_structure(&c2); if (result != ASN1_SUCCESS) { gnutls_assert(); return _gnutls_asn2err(result); } result = _gnutls_x509_crq_set_extension(crq, "172.16.58.3", &der_data, critical); _gnutls_free_datum(&der_data); if (result < 0) { gnutls_assert(); return result; } return 0; } /** * gnutls_x509_crq_get_key_id: * @crq: a certificate of type #gnutls_x509_crq_t * @flags: should be one of the flags from %gnutls_keyid_flags_t * @output_data: will contain the key ID * @output_data_size: holds the size of output_data (and will be * replaced by the actual size of parameters) * * This function will return a unique ID that depends on the public key * parameters. This ID can be used in checking whether a certificate * corresponds to the given private key. * * If the buffer provided is not long enough to hold the output, then * *@output_data_size is updated and GNUTLS_E_SHORT_MEMORY_BUFFER will * be returned. The output will normally be a SHA-1 hash output, * which is 20 bytes. * * Returns: In case of failure a negative error code will be * returned, and 0 on success. * * Since: 2.8.0 **/ int gnutls_x509_crq_get_key_id(gnutls_x509_crq_t crq, unsigned int flags, unsigned char *output_data, size_t * output_data_size) { int ret = 0; gnutls_pk_params_st params; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } ret = _gnutls_x509_crq_get_mpis(crq, &params); if (ret < 0) { gnutls_assert(); return ret; } ret = _gnutls_get_key_id(&params, output_data, output_data_size, flags); gnutls_pk_params_release(&params); return ret; } /** * gnutls_x509_crq_privkey_sign: * @crq: should contain a #gnutls_x509_crq_t type * @key: holds a private key * @dig: The message digest to use, i.e., %GNUTLS_DIG_SHA1 * @flags: must be 0 * * This function will sign the certificate request with a private key. * This must be the same key as the one used in * gnutls_x509_crt_set_key() since a certificate request is self * signed. * * This must be the last step in a certificate request generation * since all the previously set parameters are now signed. * * A known limitation of this function is, that a newly-signed request will not * be fully functional (e.g., for signature verification), until it * is exported an re-imported. * * After GnuTLS 3.6.1 the value of @dig may be %GNUTLS_DIG_UNKNOWN, * and in that case, a suitable but reasonable for the key algorithm will be selected. * * Returns: %GNUTLS_E_SUCCESS on success, otherwise a negative error code. * %GNUTLS_E_ASN1_VALUE_NOT_FOUND is returned if you didn't set all * information in the certificate request (e.g., the version using * gnutls_x509_crq_set_version()). * * Since: 2.12.0 **/ int gnutls_x509_crq_privkey_sign(gnutls_x509_crq_t crq, gnutls_privkey_t key, gnutls_digest_algorithm_t dig, unsigned int flags) { int result; gnutls_datum_t signature; gnutls_datum_t tbs; gnutls_pk_algorithm_t pk; gnutls_x509_spki_st params; const gnutls_sign_entry_st *se; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } /* Make sure version field is set. */ if (gnutls_x509_crq_get_version(crq) == GNUTLS_E_ASN1_VALUE_NOT_FOUND) { result = gnutls_x509_crq_set_version(crq, 1); if (result < 0) { gnutls_assert(); return result; } } if (dig == 0) { /* attempt to find a reasonable choice */ gnutls_pubkey_t pubkey; int ret; ret = gnutls_pubkey_init(&pubkey); if (ret < 0) return gnutls_assert_val(ret); ret = gnutls_pubkey_import_privkey(pubkey, key, 0, 0); if (ret < 0) { gnutls_pubkey_deinit(pubkey); return gnutls_assert_val(ret); } ret = gnutls_pubkey_get_preferred_hash_algorithm(pubkey, &dig, NULL); gnutls_pubkey_deinit(pubkey); if (ret < 0) return gnutls_assert_val(ret); } result = _gnutls_privkey_get_spki_params(key, &params); if (result < 0) { gnutls_assert(); return result; } pk = gnutls_privkey_get_pk_algorithm(key, NULL); result = _gnutls_privkey_update_spki_params(key, pk, dig, 0, &params); if (result < 0) { gnutls_assert(); return result; } /* Step 1. Self sign the request. */ result = _gnutls_x509_get_tbs(crq->crq, "certificationRequestInfo", &tbs); if (result < 0) { gnutls_assert(); return result; } se = _gnutls_pk_to_sign_entry(params.pk, dig); if (se == NULL) return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST); FIX_SIGN_PARAMS(params, flags, dig); result = privkey_sign_and_hash_data(key, se, &tbs, &signature, &params); gnutls_free(tbs.data); if (result < 0) { gnutls_assert(); return result; } /* Step 2. write the signature (bits) */ result = asn1_write_value(crq->crq, "signature", signature.data, signature.size * 8); _gnutls_free_datum(&signature); if (result != ASN1_SUCCESS) { gnutls_assert(); return _gnutls_asn2err(result); } /* Step 3. Write the signatureAlgorithm field. */ result = _gnutls_x509_write_sign_params(crq->crq, "signatureAlgorithm", se, &params); if (result < 0) { gnutls_assert(); return result; } return 0; } /** * gnutls_x509_crq_verify: * @crq: is the crq to be verified * @flags: Flags that may be used to change the verification algorithm. Use OR of the gnutls_certificate_verify_flags enumerations. * * This function will verify self signature in the certificate * request and return its status. * * Returns: In case of a verification failure %GNUTLS_E_PK_SIG_VERIFY_FAILED * is returned, and zero or positive code on success. * * Since 2.12.0 **/ int gnutls_x509_crq_verify(gnutls_x509_crq_t crq, unsigned int flags) { gnutls_datum_t data = { NULL, 0 }; gnutls_datum_t signature = { NULL, 0 }; gnutls_pk_params_st params; gnutls_x509_spki_st sign_params; const gnutls_sign_entry_st *se; int ret; gnutls_pk_params_init(&params); ret = _gnutls_x509_get_signed_data(crq->crq, NULL, "certificationRequestInfo", &data); if (ret < 0) { gnutls_assert(); return ret; } ret = _gnutls_x509_get_signature_algorithm(crq->crq, "signatureAlgorithm"); if (ret < 0) { gnutls_assert(); goto cleanup; } se = _gnutls_sign_to_entry(ret); if (se == NULL) { gnutls_assert(); ret = GNUTLS_E_UNSUPPORTED_SIGNATURE_ALGORITHM; goto cleanup; } ret = _gnutls_x509_get_signature(crq->crq, "signature", &signature); if (ret < 0) { gnutls_assert(); goto cleanup; } ret = _gnutls_x509_crq_get_mpis(crq, &params); if (ret < 0) { gnutls_assert(); goto cleanup; } ret = _gnutls_x509_read_sign_params(crq->crq, "signatureAlgorithm", &sign_params); if (ret < 0) { gnutls_assert(); goto cleanup; } ret = pubkey_verify_data(se, hash_to_entry(se->hash), &data, &signature, &params, &sign_params, flags); if (ret < 0) { gnutls_assert(); goto cleanup; } ret = 0; cleanup: _gnutls_free_datum(&data); _gnutls_free_datum(&signature); gnutls_pk_params_release(&params); return ret; } /** * gnutls_x509_crq_set_private_key_usage_period: * @crq: a certificate of type #gnutls_x509_crq_t * @activation: The activation time * @expiration: The expiration time * * This function will set the private key usage period extension (172.16.17.32). * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_set_private_key_usage_period(gnutls_x509_crq_t crq, time_t activation, time_t expiration) { int result; gnutls_datum_t der_data; ASN1_TYPE c2 = ASN1_TYPE_EMPTY; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } result = asn1_create_element(_gnutls_get_pkix(), "PKIX1.PrivateKeyUsagePeriod", &c2); if (result != ASN1_SUCCESS) { gnutls_assert(); return _gnutls_asn2err(result); } result = _gnutls_x509_set_time(c2, "notBefore", activation, 1); if (result < 0) { gnutls_assert(); goto cleanup; } result = _gnutls_x509_set_time(c2, "notAfter", expiration, 1); if (result < 0) { gnutls_assert(); goto cleanup; } result = _gnutls_x509_der_encode(c2, "", &der_data, 0); if (result < 0) { gnutls_assert(); goto cleanup; } result = _gnutls_x509_crq_set_extension(crq, "2.5.29.16", &der_data, 0); _gnutls_free_datum(&der_data); cleanup: asn1_delete_structure(&c2); return result; } /** * gnutls_x509_crq_get_tlsfeatures: * @crq: An X.509 certificate request * @features: If the function succeeds, the * features will be stored in this variable. * @flags: zero or %GNUTLS_EXT_FLAG_APPEND * @critical: the extension status * * This function will get the X.509 TLS features * extension structure from the certificate request. * The returned structure needs to be freed using * gnutls_x509_tlsfeatures_deinit(). * * When the @flags is set to %GNUTLS_EXT_FLAG_APPEND, * then if the @features structure is empty this function will behave * identically as if the flag was not set. Otherwise if there are elements * in the @features structure then they will be merged with. * * Note that @features must be initialized prior to calling this function. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, * otherwise a negative error value. * * Since: 3.5.1 **/ int gnutls_x509_crq_get_tlsfeatures(gnutls_x509_crq_t crq, gnutls_x509_tlsfeatures_t features, unsigned int flags, unsigned int *critical) { int ret; gnutls_datum_t der = {NULL, 0}; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } if ((ret = gnutls_x509_crq_get_extension_by_oid2(crq, GNUTLS_X509EXT_OID_TLSFEATURES, 0, &der, critical)) < 0) { return ret; } if (der.size == 0 || der.data == NULL) { gnutls_assert(); return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; } ret = gnutls_x509_ext_import_tlsfeatures(&der, features, flags); if (ret < 0) { gnutls_assert(); goto cleanup; } ret = 0; cleanup: gnutls_free(der.data); return ret; } /** * gnutls_x509_crq_set_tlsfeatures: * @crq: An X.509 certificate request * @features: If the function succeeds, the * features will be added to the certificate * request. * * This function will set the certificate request's * X.509 TLS extension from the given structure. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, * otherwise a negative error value. * * Since: 3.5.1 **/ int gnutls_x509_crq_set_tlsfeatures(gnutls_x509_crq_t crq, gnutls_x509_tlsfeatures_t features) { int ret; gnutls_datum_t der; if (crq == NULL || features == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } ret = gnutls_x509_ext_export_tlsfeatures(features, &der); if (ret < 0) { gnutls_assert(); return ret; } ret = _gnutls_x509_crq_set_extension(crq, GNUTLS_X509EXT_OID_TLSFEATURES, &der, 0); _gnutls_free_datum(&der); if (ret < 0) { gnutls_assert(); } return ret; } /** * gnutls_x509_crq_set_extension_by_oid: * @crq: a certificate of type #gnutls_x509_crq_t * @oid: holds an Object Identifier in null terminated string * @buf: a pointer to a DER encoded data * @sizeof_buf: holds the size of @buf * @critical: should be non-zero if the extension is to be marked as critical * * This function will set an the extension, by the specified OID, in * the certificate request. The extension data should be binary data DER * encoded. * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. **/ int gnutls_x509_crq_set_extension_by_oid(gnutls_x509_crq_t crq, const char *oid, const void *buf, size_t sizeof_buf, unsigned int critical) { int result; gnutls_datum_t der_data; der_data.data = (void *) buf; der_data.size = sizeof_buf; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } result = _gnutls_x509_crq_set_extension(crq, oid, &der_data, critical); if (result < 0) { gnutls_assert(); return result; } return 0; } /** * gnutls_x509_crq_set_spki: * @crq: a certificate request of type #gnutls_x509_crq_t * @spki: a SubjectPublicKeyInfo structure of type #gnutls_x509_spki_t * @flags: must be zero * * This function will set the certificate request's subject public key * information explicitly. This is intended to be used in the cases * where a single public key (e.g., RSA) can be used for multiple * signature algorithms (RSA PKCS1-1.5, and RSA-PSS). * * To export the public key (i.e., the SubjectPublicKeyInfo part), check * gnutls_pubkey_import_x509(). * * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a * negative error value. * * Since: 3.6.0 **/ int gnutls_x509_crq_set_spki(gnutls_x509_crq_t crq, const gnutls_x509_spki_t spki, unsigned int flags) { int ret; gnutls_pk_algorithm_t crq_pk; gnutls_x509_spki_st tpki; gnutls_pk_params_st params; unsigned bits; if (crq == NULL) { gnutls_assert(); return GNUTLS_E_INVALID_REQUEST; } ret = _gnutls_x509_crq_get_mpis(crq, &params); if (ret < 0) { gnutls_assert(); return ret; } bits = pubkey_to_bits(&params); crq_pk = params.algo; if (!_gnutls_pk_are_compat(crq_pk, spki->pk)) { ret = gnutls_assert_val(GNUTLS_E_INVALID_REQUEST); goto cleanup; } if (spki->pk != GNUTLS_PK_RSA_PSS) { if (crq_pk == spki->pk) { ret = 0; goto cleanup; } gnutls_assert(); ret = GNUTLS_E_INVALID_REQUEST; goto cleanup; } memset(&tpki, 0, sizeof(gnutls_x509_spki_st)); if (crq_pk == GNUTLS_PK_RSA) { const mac_entry_st *me; me = hash_to_entry(spki->rsa_pss_dig); if (unlikely(me == NULL)) { gnutls_assert(); ret = GNUTLS_E_INVALID_REQUEST; goto cleanup; } tpki.pk = spki->pk; tpki.rsa_pss_dig = spki->rsa_pss_dig; /* If salt size is zero, find the optimal salt size. */ if (spki->salt_size == 0) { ret = _gnutls_find_rsa_pss_salt_size(bits, me, spki->salt_size); if (ret < 0) { gnutls_assert(); goto cleanup; } tpki.salt_size = ret; } else tpki.salt_size = spki->salt_size; } else if (crq_pk == GNUTLS_PK_RSA_PSS) { ret = _gnutls_x509_crq_read_spki_params(crq, &tpki); if (ret < 0) { gnutls_assert(); goto cleanup; } tpki.salt_size = spki->salt_size; tpki.rsa_pss_dig = spki->rsa_pss_dig; } memcpy(&params.spki, &tpki, sizeof(tpki)); ret = _gnutls_x509_check_pubkey_params(&params); if (ret < 0) { gnutls_assert(); goto cleanup; } ret = _gnutls_x509_write_spki_params(crq->crq, "certificationRequestInfo." "subjectPKInfo." "algorithm", &tpki); if (ret < 0) { gnutls_assert(); goto cleanup; } ret = 0; cleanup: gnutls_pk_params_release(&params); return ret; }
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object3080106164.h" // UnityEngine.Vector3[] struct Vector3U5BU5D_t1718750761; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.UI.RectangularVertexClipper struct RectangularVertexClipper_t626611136 : public Il2CppObject { public: // UnityEngine.Vector3[] UnityEngine.UI.RectangularVertexClipper::m_WorldCorners Vector3U5BU5D_t1718750761* ___m_WorldCorners_0; // UnityEngine.Vector3[] UnityEngine.UI.RectangularVertexClipper::m_CanvasCorners Vector3U5BU5D_t1718750761* ___m_CanvasCorners_1; public: inline static int32_t get_offset_of_m_WorldCorners_0() { return static_cast<int32_t>(offsetof(RectangularVertexClipper_t626611136, ___m_WorldCorners_0)); } inline Vector3U5BU5D_t1718750761* get_m_WorldCorners_0() const { return ___m_WorldCorners_0; } inline Vector3U5BU5D_t1718750761** get_address_of_m_WorldCorners_0() { return &___m_WorldCorners_0; } inline void set_m_WorldCorners_0(Vector3U5BU5D_t1718750761* value) { ___m_WorldCorners_0 = value; Il2CppCodeGenWriteBarrier(&___m_WorldCorners_0, value); } inline static int32_t get_offset_of_m_CanvasCorners_1() { return static_cast<int32_t>(offsetof(RectangularVertexClipper_t626611136, ___m_CanvasCorners_1)); } inline Vector3U5BU5D_t1718750761* get_m_CanvasCorners_1() const { return ___m_CanvasCorners_1; } inline Vector3U5BU5D_t1718750761** get_address_of_m_CanvasCorners_1() { return &___m_CanvasCorners_1; } inline void set_m_CanvasCorners_1(Vector3U5BU5D_t1718750761* value) { ___m_CanvasCorners_1 = value; Il2CppCodeGenWriteBarrier(&___m_CanvasCorners_1, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:52:12 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/CameraUI.framework/CameraUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <CameraUI/CameraUI-Structs.h> #import <UIKitCore/UIView.h> #import <libobjc.A.dylib/CAMExpandableMenuButtonDelegate.h> #import <libobjc.A.dylib/CEKApertureButtonDelegate.h> @protocol CAMControlVisibilityUpdateDelegate; @class UIView, CUShutterButton, CAMModeDial, CAMImageWell, UIButton, CAMCreativeCameraButton, PUReviewScreenDoneButton, CAMFlipButton, CAMFlashButton, CAMHDRButton, CAMTimerButton, CAMLivePhotoButton, CEKApertureButton, CAMUtilityBar, CAMExpandableMenuButton; @interface CAMBottomBar : UIView <CAMExpandableMenuButtonDelegate, CEKApertureButtonDelegate> { long long _layoutStyle; long long _backgroundStyle; UIView* _backgroundView; id<CAMControlVisibilityUpdateDelegate> _visibilityUpdateDelegate; CUShutterButton* _shutterButton; CUShutterButton* _stillDuringVideoButton; CAMModeDial* _modeDial; CAMImageWell* _imageWell; UIButton* _reviewButton; CAMCreativeCameraButton* _creativeCameraButton; PUReviewScreenDoneButton* _doneButton; CAMFlipButton* _flipButton; CAMFlashButton* _flashButton; CAMHDRButton* _HDRButton; CAMTimerButton* _timerButton; CAMLivePhotoButton* _livePhotoButton; CEKApertureButton* _apertureButton; CAMUtilityBar* _utilityBar; double _utilityBarExtensionDistance; CAMExpandableMenuButton* __expandedMenuButton; } @property (setter=_setExpandedMenuButton:,nonatomic,retain) CAMExpandableMenuButton * _expandedMenuButton; //@synthesize _expandedMenuButton=__expandedMenuButton - In the implementation block @property (assign,nonatomic) long long layoutStyle; //@synthesize layoutStyle=_layoutStyle - In the implementation block @property (assign,nonatomic) long long backgroundStyle; //@synthesize backgroundStyle=_backgroundStyle - In the implementation block @property (nonatomic,readonly) UIView * backgroundView; //@synthesize backgroundView=_backgroundView - In the implementation block @property (assign,nonatomic,__weak) id<CAMControlVisibilityUpdateDelegate> visibilityUpdateDelegate; //@synthesize visibilityUpdateDelegate=_visibilityUpdateDelegate - In the implementation block @property (nonatomic,retain) CUShutterButton * shutterButton; //@synthesize shutterButton=_shutterButton - In the implementation block @property (nonatomic,retain) CUShutterButton * stillDuringVideoButton; //@synthesize stillDuringVideoButton=_stillDuringVideoButton - In the implementation block @property (nonatomic,retain) CAMModeDial * modeDial; //@synthesize modeDial=_modeDial - In the implementation block @property (nonatomic,retain) CAMImageWell * imageWell; //@synthesize imageWell=_imageWell - In the implementation block @property (nonatomic,retain) UIButton * reviewButton; //@synthesize reviewButton=_reviewButton - In the implementation block @property (nonatomic,retain) CAMCreativeCameraButton * creativeCameraButton; //@synthesize creativeCameraButton=_creativeCameraButton - In the implementation block @property (nonatomic,retain) PUReviewScreenDoneButton * doneButton; //@synthesize doneButton=_doneButton - In the implementation block @property (nonatomic,retain) CAMFlipButton * flipButton; //@synthesize flipButton=_flipButton - In the implementation block @property (nonatomic,retain) CAMFlashButton * flashButton; //@synthesize flashButton=_flashButton - In the implementation block @property (nonatomic,retain) CAMHDRButton * HDRButton; //@synthesize HDRButton=_HDRButton - In the implementation block @property (nonatomic,retain) CAMTimerButton * timerButton; //@synthesize timerButton=_timerButton - In the implementation block @property (nonatomic,retain) CAMLivePhotoButton * livePhotoButton; //@synthesize livePhotoButton=_livePhotoButton - In the implementation block @property (nonatomic,retain) CEKApertureButton * apertureButton; //@synthesize apertureButton=_apertureButton - In the implementation block @property (nonatomic,retain) CAMUtilityBar * utilityBar; //@synthesize utilityBar=_utilityBar - In the implementation block @property (assign,nonatomic) double utilityBarExtensionDistance; //@synthesize utilityBarExtensionDistance=_utilityBarExtensionDistance - In the implementation block +(CGRect)shutterButtonAlignmentRectInBounds:(CGRect)arg1 forLayoutStyle:(long long)arg2 ; +(BOOL)wantsVerticalBarForLayoutStyle:(long long)arg1 ; -(void)setDoneButton:(PUReviewScreenDoneButton *)arg1 ; -(void)setApertureButton:(CEKApertureButton *)arg1 ; -(long long)layoutStyle; -(void)_ensureSubviewOrdering; -(PUReviewScreenDoneButton *)doneButton; -(CAMExpandableMenuButton *)_expandedMenuButton; -(id)hudItemForAccessibilityHUDManager:(id)arg1 ; -(CEKApertureButton *)apertureButton; -(CAMFlipButton *)flipButton; -(id)initWithLayoutStyle:(long long)arg1 ; -(BOOL)pointInside:(CGPoint)arg1 withEvent:(id)arg2 ; -(id)touchingRecognizersToCancel; -(void)_layoutFlipButtonForLayoutStyle:(long long)arg1 ; -(void)setBackgroundStyle:(long long)arg1 animated:(BOOL)arg2 ; -(void)setShutterButton:(CUShutterButton *)arg1 ; -(void)setLayoutStyle:(long long)arg1 ; -(void)setBackgroundStyle:(long long)arg1 ; -(void)setImageWell:(CAMImageWell *)arg1 ; -(void)collapseMenuButton:(id)arg1 animated:(BOOL)arg2 ; -(void)_layoutMenuButtons:(id)arg1 apply:(BOOL)arg2 withExpandedMenuButton:(id)arg3 collapsingMenuButton:(id)arg4 collapsingFrame:(CGRect*)arg5 ; -(void)_updateFlipButtonTappableEdgeInsets; -(void)_layoutReviewButtonForLayoutStyle:(long long)arg1 ; -(void)setUtilityBarExtensionDistance:(double)arg1 ; -(CAMFlashButton *)flashButton; -(void)_updateImageWellTappableEdgeInsets; -(void)_layoutUtilityBarForLayoutStyle:(long long)arg1 ; -(void)_updateCreativeCameraButtonTappableEdgeInsets; -(void)_iterateViewsInHUDManager:(id)arg1 forHUDItem:(/*^block*/id)arg2 ; -(id)initWithFrame:(CGRect)arg1 ; -(void)setCreativeCameraButton:(CAMCreativeCameraButton *)arg1 ; -(void)_setExpandedMenuButton:(id)arg1 ; -(void)setStillDuringVideoButton:(CUShutterButton *)arg1 ; -(CUShutterButton *)stillDuringVideoButton; -(void)apertureButtonNeedsLayout:(id)arg1 animated:(BOOL)arg2 ; -(void)_layoutImageWellForLayoutStyle:(long long)arg1 ; -(UIButton *)reviewButton; -(double)_opacityForBackgroundStyle:(long long)arg1 ; -(void)layoutSubviews; -(CAMLivePhotoButton *)livePhotoButton; -(void)setTimerButton:(CAMTimerButton *)arg1 ; -(void)_layoutCreativeCameraButtonForLayoutStyle:(long long)arg1 ; -(CAMHDRButton *)HDRButton; -(void)_layoutModeDialForLayoutStyle:(long long)arg1 ; -(long long)backgroundStyle; -(UIView *)backgroundView; -(CUShutterButton *)shutterButton; -(void)setFlipButton:(CAMFlipButton *)arg1 ; -(CGRect)expandedFrameForMenuButton:(id)arg1 ; -(CGRect)collapsedFrameForMenuButton:(id)arg1 ; -(void)_updateControlVisibilityAnimated:(BOOL)arg1 ; -(void)setHDRButton:(CAMHDRButton *)arg1 ; -(CAMImageWell *)imageWell; -(void)_commonCAMBottomBarInitializationInitWithLayoutStyle:(long long)arg1 ; -(id)initWithCoder:(id)arg1 ; -(void)_layoutDoneButtonForLayoutStyle:(long long)arg1 ; -(void)selectedByAccessibilityHUDManager:(id)arg1 ; -(id<CAMControlVisibilityUpdateDelegate>)visibilityUpdateDelegate; -(void)setUtilityBar:(CAMUtilityBar *)arg1 ; -(CAMTimerButton *)timerButton; -(void)_layoutShutterButtonForLayoutStyle:(long long)arg1 ; -(void)setReviewButton:(UIButton *)arg1 ; -(id)_currentMenuButtons; -(CAMUtilityBar *)utilityBar; -(void)setLivePhotoButton:(CAMLivePhotoButton *)arg1 ; -(void)setModeDial:(CAMModeDial *)arg1 ; -(void)setVisibilityUpdateDelegate:(id<CAMControlVisibilityUpdateDelegate>)arg1 ; -(void)expandMenuButton:(id)arg1 animated:(BOOL)arg2 ; -(CAMModeDial *)modeDial; -(id)hitTest:(CGPoint)arg1 withEvent:(id)arg2 ; -(double)utilityBarExtensionDistance; -(void)setFlashButton:(CAMFlashButton *)arg1 ; -(CAMCreativeCameraButton *)creativeCameraButton; -(void)_layoutStillDuringVideoButtonForLayoutStyle:(long long)arg1 ; @end
<reponame>atelier-saulx/selva-client #include <math.h> #include <stdarg.h> #include <stddef.h> #include "cdefs.h" #include "selva.h" #include "errors.h" #include "redismodule.h" #include "alias.h" #include "selva_set.h" int SelvaSet_CompareRms(struct SelvaSetElement *a, struct SelvaSetElement *b) { RedisModuleString *ra = a->value_rms; RedisModuleString *rb = b->value_rms; TO_STR(ra, rb); if (ra_len < rb_len) { return -1; } if (ra_len > rb_len) { return 1; } return memcmp(ra_str, rb_str, ra_len); } int SelvaSet_CompareDouble(struct SelvaSetElement *a, struct SelvaSetElement *b) { double da = a->value_d; double db = b->value_d; return da < db ? -1 : da > db ? 1 : 0; } int SelvaSet_CompareLongLong(struct SelvaSetElement *a, struct SelvaSetElement *b) { long long lla = a->value_ll; long long llb = b->value_ll; return lla < llb ? -1 : lla > llb ? 1 : 0; } int SelvaSet_CompareNodeId(struct SelvaSetElement *a, struct SelvaSetElement *b) { return memcmp(a->value_nodeId, b->value_nodeId, SELVA_NODE_ID_SIZE); } RB_GENERATE(SelvaSetRms, SelvaSetElement, _entry, SelvaSet_CompareRms) RB_GENERATE(SelvaSetDouble, SelvaSetElement, _entry, SelvaSet_CompareDouble) RB_GENERATE(SelvaSetLongLong, SelvaSetElement, _entry, SelvaSet_CompareLongLong) RB_GENERATE(SelvaSetNodeId, SelvaSetElement, _entry, SelvaSet_CompareNodeId) int SelvaSet_AddRms(struct SelvaSet *set, struct RedisModuleString *s) { struct SelvaSetElement *el; if (set->type != SELVA_SET_TYPE_RMSTRING) { return SELVA_EINTYPE; } if (SelvaSet_HasRms(set, s)) { return SELVA_EEXIST; } el = RedisModule_Calloc(1, sizeof(struct SelvaSetElement)); if (!el) { return SELVA_ENOMEM; } el->value_rms = s; (void)RB_INSERT(SelvaSetRms, &set->head_rms, el); set->size++; return 0; } int SelvaSet_AddDouble(struct SelvaSet *set, double d) { struct SelvaSetElement *el; if (set->type != SELVA_SET_TYPE_DOUBLE) { return SELVA_EINTYPE; } if (isnan(d)) { return SELVA_EINVAL; } if (SelvaSet_HasDouble(set, d)) { return SELVA_EEXIST; } el = RedisModule_Calloc(1, sizeof(struct SelvaSetElement)); if (!el) { return SELVA_ENOMEM; } el->value_d = d; (void)RB_INSERT(SelvaSetDouble, &set->head_d, el); set->size++; return 0; } int SelvaSet_AddLongLong(struct SelvaSet *set, long long ll) { struct SelvaSetElement *el; if (set->type != SELVA_SET_TYPE_LONGLONG) { return SELVA_EINTYPE; } if (SelvaSet_HasLongLong(set, ll)) { return SELVA_EEXIST; } el = RedisModule_Calloc(1, sizeof(struct SelvaSetElement)); if (!el) { return SELVA_ENOMEM; } el->value_ll = ll; (void)RB_INSERT(SelvaSetLongLong, &set->head_ll, el); set->size++; return 0; } int SelvaSet_AddNodeId(struct SelvaSet *set, const Selva_NodeId node_id) { struct SelvaSetElement *el; if (set->type != SELVA_SET_TYPE_NODEID) { return SELVA_EINTYPE; } if (SelvaSet_HasNodeId(set, node_id)) { return SELVA_EEXIST; } el = RedisModule_Calloc(1, sizeof(struct SelvaSetElement)); if (!el) { return SELVA_ENOMEM; } memcpy(el->value_nodeId, node_id, SELVA_NODE_ID_SIZE); (void)RB_INSERT(SelvaSetNodeId, &set->head_nodeId, el); set->size++; return 0; } void SelvaSet_DestroyElement(struct SelvaSetElement *el) { if (!el) { return; } RedisModule_Free(el); } static void SelvaSet_DestroyRms(struct SelvaSet *set) { struct SelvaSetRms *head = &set->head_rms; struct SelvaSetElement *el; struct SelvaSetElement *next; for (el = RB_MIN(SelvaSetRms, head); el != NULL; el = next) { next = RB_NEXT(SelvaSetRms, head, el); RB_REMOVE(SelvaSetRms, head, el); RedisModule_FreeString(NULL, el->value_rms); SelvaSet_DestroyElement(el); } set->size = 0; } static void SelvaSet_DestroyDouble(struct SelvaSet *set) { struct SelvaSetDouble *head = &set->head_d; struct SelvaSetElement *el; struct SelvaSetElement *next; for (el = RB_MIN(SelvaSetDouble, head); el != NULL; el = next) { next = RB_NEXT(SelvaSetDouble, head, el); RB_REMOVE(SelvaSetDouble, head, el); SelvaSet_DestroyElement(el); } set->size = 0; } static void SelvaSet_DestroyLongLong(struct SelvaSet *set) { struct SelvaSetLongLong *head = &set->head_ll; struct SelvaSetElement *el; struct SelvaSetElement *next; for (el = RB_MIN(SelvaSetLongLong, head); el != NULL; el = next) { next = RB_NEXT(SelvaSetLongLong, head, el); RB_REMOVE(SelvaSetLongLong, head, el); SelvaSet_DestroyElement(el); } set->size = 0; } static void SelvaSet_DestroyNodeId(struct SelvaSet *set) { struct SelvaSetNodeId *head = &set->head_nodeId; struct SelvaSetElement *el; struct SelvaSetElement *next; for (el = RB_MIN(SelvaSetNodeId, head); el != NULL; el = next) { next = RB_NEXT(SelvaSetNodeId, head, el); RB_REMOVE(SelvaSetNodeId, head, el); SelvaSet_DestroyElement(el); } set->size = 0; } static void (*const SelvaSet_Destructors[])(struct SelvaSet *set) = { [SELVA_SET_TYPE_RMSTRING] = SelvaSet_DestroyRms, [SELVA_SET_TYPE_DOUBLE] = SelvaSet_DestroyDouble, [SELVA_SET_TYPE_LONGLONG] = SelvaSet_DestroyLongLong, [SELVA_SET_TYPE_NODEID] = SelvaSet_DestroyNodeId, }; void SelvaSet_Destroy(struct SelvaSet *set) { enum SelvaSetType type = set->type; if (type >= 0 && type < num_elem(SelvaSet_Destructors)) { SelvaSet_Destructors[type](set); } } RedisModuleString *SelvaSet_FindRms(struct SelvaSet *set, RedisModuleString *s) { struct SelvaSetElement find = { .value_rms = s, }; RedisModuleString *res = NULL; if (likely(set->type == SELVA_SET_TYPE_RMSTRING)) { struct SelvaSetElement *el; el = RB_FIND(SelvaSetRms, &set->head_rms, &find); if (el) { res = el->value_rms; } } return res; } int SelvaSet_HasRms(struct SelvaSet *set, RedisModuleString *s) { struct SelvaSetElement find = { .value_rms = s, }; if (unlikely(set->type != SELVA_SET_TYPE_RMSTRING)) { return 0; } return !!RB_FIND(SelvaSetRms, &set->head_rms, &find); } int SelvaSet_HasDouble(struct SelvaSet *set, double d) { struct SelvaSetElement find = { .value_d = d, }; if (unlikely(set->type != SELVA_SET_TYPE_DOUBLE)) { return 0; } if (isnan(d)) { return 0; } return !!RB_FIND(SelvaSetDouble, &set->head_d, &find); } int SelvaSet_HasLongLong(struct SelvaSet *set, long long ll) { struct SelvaSetElement find = { .value_ll = ll, }; if (unlikely(set->type != SELVA_SET_TYPE_LONGLONG)) { return 0; } return !!RB_FIND(SelvaSetLongLong, &set->head_ll, &find); } int SelvaSet_HasNodeId(struct SelvaSet *set, const Selva_NodeId node_id) { struct SelvaSetElement find = { 0 }; memcpy(find.value_nodeId, node_id, SELVA_NODE_ID_SIZE); if (unlikely(set->type != SELVA_SET_TYPE_NODEID)) { return 0; } return !!RB_FIND(SelvaSetNodeId, &set->head_nodeId, &find); } struct SelvaSetElement *SelvaSet_RemoveRms(struct SelvaSet *set, RedisModuleString *s) { struct SelvaSetElement find = { .value_rms = s, }; struct SelvaSetElement *el = NULL; if (likely(set->type == SELVA_SET_TYPE_RMSTRING)) { el = RB_FIND(SelvaSetRms, &set->head_rms, &find); if (el && RB_REMOVE(SelvaSetRms, &set->head_rms, el)) { set->size--; } } return el; } struct SelvaSetElement *SelvaSet_RemoveDouble(struct SelvaSet *set, double d) { struct SelvaSetElement find = { .value_d = d, }; struct SelvaSetElement *el = NULL; if (likely(set->type == SELVA_SET_TYPE_DOUBLE)) { el = RB_FIND(SelvaSetDouble, &set->head_d, &find); if (el && RB_REMOVE(SelvaSetDouble, &set->head_d, el)) { set->size--; } } return el; } struct SelvaSetElement *SelvaSet_RemoveLongLong(struct SelvaSet *set, long long ll) { struct SelvaSetElement find = { .value_ll = ll, }; struct SelvaSetElement *el = NULL; if (likely(set->type == SELVA_SET_TYPE_LONGLONG)) { el = RB_FIND(SelvaSetLongLong, &set->head_ll, &find); if (el && RB_REMOVE(SelvaSetLongLong, &set->head_ll, el)) { set->size--; } } return el; } struct SelvaSetElement *SelvaSet_RemoveNodeId(struct SelvaSet *set, const Selva_NodeId node_id) { struct SelvaSetElement find = { 0 }; struct SelvaSetElement *el = NULL; memcpy(find.value_nodeId, node_id, SELVA_NODE_ID_SIZE); if (likely(set->type == SELVA_SET_TYPE_NODEID)) { el = RB_FIND(SelvaSetNodeId, &set->head_nodeId, &find); if (el && RB_REMOVE(SelvaSetNodeId, &set->head_nodeId, el)) { set->size--; } } return el; } int SelvaSet_Merge(struct SelvaSet *dst, struct SelvaSet *src) { enum SelvaSetType type = src->type; struct SelvaSetElement *tmp; struct SelvaSetElement *el; if (type != dst->type) { return SELVA_EINTYPE; } if (type == SELVA_SET_TYPE_RMSTRING) { SELVA_SET_RMS_FOREACH_SAFE(el, src, tmp) { if (!SelvaSet_Has(dst, el->value_rms)) { RB_REMOVE(SelvaSetRms, &src->head_rms, el); src->size--; RB_INSERT(SelvaSetRms, &dst->head_rms, el); dst->size++; } } } else if (type == SELVA_SET_TYPE_DOUBLE) { SELVA_SET_DOUBLE_FOREACH_SAFE(el, src, tmp) { if (!SelvaSet_Has(dst, el->value_d)) { RB_REMOVE(SelvaSetDouble, &src->head_d, el); src->size--; RB_INSERT(SelvaSetDouble, &dst->head_d, el); dst->size++; } } } else if (type == SELVA_SET_TYPE_LONGLONG) { SELVA_SET_LONGLONG_FOREACH_SAFE(el, src, tmp) { if (!SelvaSet_Has(dst, el->value_ll)) { RB_REMOVE(SelvaSetLongLong, &src->head_ll, el); src->size--; RB_INSERT(SelvaSetLongLong, &dst->head_ll, el); dst->size++; } } } else if (type == SELVA_SET_TYPE_NODEID) { SELVA_SET_NODEID_FOREACH_SAFE(el, src, tmp) { if (!SelvaSet_Has(dst, el->value_nodeId)) { RB_REMOVE(SelvaSetNodeId, &src->head_nodeId, el); src->size--; RB_INSERT(SelvaSetNodeId, &dst->head_nodeId, el); dst->size++; } } } return 0; } int SelvaSet_Union(struct SelvaSet *res, ...) { const enum SelvaSetType type = res->type; va_list argp; int err = 0; va_start(argp, res); /* * We only accept empty set for the result set. */ if (!res || res->size > 0) { err = SELVA_EINVAL; goto out; } if (type == SELVA_SET_TYPE_RMSTRING) { struct SelvaSet *set; while ((set = va_arg(argp, struct SelvaSet *))) { struct SelvaSetElement *el; if (set->type != type) { continue; } SELVA_SET_RMS_FOREACH(el, set) { RedisModuleString *rms; rms = RedisModule_HoldString(NULL, el->value_rms); if (!rms) { err = SELVA_ENOMEM; goto out; } err = SelvaSet_Add(res, rms); if (err) { RedisModule_FreeString(NULL, rms); goto out; } } } } else if (type == SELVA_SET_TYPE_DOUBLE) { struct SelvaSet *set; while ((set = va_arg(argp, struct SelvaSet *))) { struct SelvaSetElement *el; if (set->type != type) { continue; } SELVA_SET_DOUBLE_FOREACH(el, set) { err = SelvaSet_Add(res, el->value_d); if (err) { goto out; } } } } else if (type == SELVA_SET_TYPE_LONGLONG) { struct SelvaSet *set; while ((set = va_arg(argp, struct SelvaSet *))) { struct SelvaSetElement *el; if (set->type != type) { continue; } SELVA_SET_LONGLONG_FOREACH(el, set) { err = SelvaSet_Add(res, el->value_ll); if (err) { goto out; } } } } else if (type == SELVA_SET_TYPE_NODEID) { struct SelvaSet *set; while ((set = va_arg(argp, struct SelvaSet *))) { struct SelvaSetElement *el; if (set->type != type) { continue; } SELVA_SET_NODEID_FOREACH(el, set) { err = SelvaSet_Add(res, el->value_nodeId); if (err) { goto out; } } } } out: va_end(argp); return err; }
<filename>stack.c #include <stdio.h> #include <malloc.h> #include "stack.h" #include "debug.h" /** * @brief スタックのpush * @param stack スタック * @param value pushする値 */ void push(Stack *stack, int value) { DPRINTF("Push : %d\n", value); Elem *elem = (Elem *)calloc(1, sizeof(Elem)); elem->value = value; elem->next = stack->head; stack->head = elem; }; /** * @brief スタックのpop * @param stack スタック * @return popした値 */ int pop(Stack *stack) { Elem *elem = stack->head; int value = elem->value; stack->head = elem->next; free(elem); DPRINTF("Pop : %d\n", value); return value; }; /** * @brief スタックトップの値を取得する(popはしない) * @param stack スタック * @return スタックトップの値 */ int peek(Stack *stack) { return stack->head->value; }; /** * @brief スタックの中身を表示する(デバッグ用) * @param stack スタック */ void printStack(Stack *stack) { printf("=== Stack : %p ===\n", stack); int count = 0; for (Elem *elem = stack->head; elem != NULL; elem = elem->next) { printf("%04d : %d\n", count++, elem->value); } };
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "ZDBaseKit.h" #import "NSArray+ZDAdd.h" #import "NSData+ZDAdd.h" #import "NSDate+ZDAdd.h" #import "NSDictionary+ZDAdd.h" #import "NSNotificationCenter+ZDAdd.h" #import "NSString+ZDAdd.h" #import "NSTimer+ZDAdd.h" #import "ZDFoundation.h" #import "UIAlertController+ZDAdd.h" #import "UIBarButtonItem+ZDAdd.h" #import "UIButton+ZDAdd.h" #import "UIColor+ZDAdd.h" #import "UIImage+ZDAdd.h" #import "UILabel+ZDAdd.h" #import "UINavigationController+ZDAdd.h" #import "UITabBar+ZDAdd.h" #import "UITextField+ZDAdd.h" #import "UITextView+ZDAdd.h" #import "UIView+ZDAdd.h" #import "UIViewController+ZDAdd.h" #import "ZDUIKit.h" FOUNDATION_EXPORT double ZDBaseKitVersionNumber; FOUNDATION_EXPORT const unsigned char ZDBaseKitVersionString[];
<filename>FireInTheWater/afacfrota.h<gh_stars>0 #ifndef AFACFROTA_H #define AFACFROTA_H #include <faccontratorpedeiro.h> #include <facnaviostanque.h> #include <facportaavioes.h> #include <facsubmarino.h> class AfacFrota { private: static AfacFrota* instance; void setFrota (int sxa, int sya, int sxb, int syb, int cxa, int cya, int cxb, int cyb, int cxc, int cyc, int nxa, int nya, int nxb, int nyb, int nxc, int nyc, int nxd, int nyd, int pxa, int pya, int pxb, int pyb, int pxc, int pyc, int pxd, int pyd, int pxe, int pye) { submarinoInst.setSubmarino(sxa, sya, sxb, syb); contratorPedeiroInst.setContratorPedeiro(cxa, cya, cxb, cyb, cxc, cyc); naviosTanqueInst.setNaviosTanque(nxa, nya, nxb, nyb, nxc, nyc, nxd, nyd); portaAvioesInst.setPortaAvioes(pxa, pya, pxb, pyb, pxc, pyc, pxd, pyd, pxe, pye); } public: static AfacFrota* getInstance(int sxa, int sya, int sxb, int syb, int cxa, int cya, int cxb, int cyb, int cxc, int cyc, int nxa, int nya, int nxb, int nyb, int nxc, int nyc, int nxd, int nyd, int pxa, int pya, int pxb, int pyb, int pxc, int pyc, int pxd, int pyd, int pxe, int pye); facSubmarino submarinoInst; facContratorPedeiro contratorPedeiroInst; facNaviosTanque naviosTanqueInst; facPortaAvioes portaAvioesInst; }; #endif // AFACFROTA_H
/* * Copyright (C) 2014 by ARM Ltd. All rights reserved. * * Permission to use, copy, modify, and distribute this software * is freely granted, provided that this notice is preserved. */ #include <stdio.h> #include "check.h" const char m[8] = {'M','M','M','M','M','M','M','M'}; int main() { printf ("%.*s\n", 8, m); exit (0); }
<reponame>hakandilek/keysmith<gh_stars>1-10 // // KeysmithCommon.h // Mora // // Created by <NAME> on 06/05/2013. // Copyright (c) 2013 Lion User. All rights reserved. // #ifndef Mora_KeysmithCommon_h #define Mora_KeysmithCommon_h #import <CommonCrypto/CommonDigest.h> #import <CommonCrypto/CommonCryptor.h> // The chosen symmetric key and digest algorithm chosen for this sample is AES and SHA1. // The reasoning behind this was due to the fact that the iPhone and iPod touch have // hardware accelerators for those particular algorithms and therefore are energy efficient. #define kChosenCipherBlockSize kCCBlockSize3DES #define kChosenCipherKeySize kCCKeySize3DES #define kChosenDigestLength CC_SHA1_DIGEST_LENGTH // Global constants for padding schemes. #define kTypeOfWrapPadding kSecPaddingPKCS1 #define kSecretKeyPadding kCCOptionPKCS7Padding #define kSecretKeyAlgorithm kCCAlgorithm3DES // constants used to find public, private, and symmetric keys. #define kPublicKeyTag "keysmith.publickey" #define kPrivateKeyTag "keysmith.privatekey" #define kSecretKeyTag "keysmith.secretkey" #if DEBUG #define LOGGING_FACILITY(X, Y) \ NSAssert(X, Y); #define LOGGING_FACILITY1(X, Y, Z) \ NSAssert1(X, Y, Z); #else #define LOGGING_FACILITY(X, Y) \ if (!(X)) { \ NSLog(Y); \ } #define LOGGING_FACILITY1(X, Y, Z) \ if (!(X)) { \ NSLog(Y, Z); \ } #endif #endif
/* * Copyright (C) 2016 The Android Open Source Project * * 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 LIBMEMUNREACHABLE_LEAK_PIPE_H_ #define LIBMEMUNREACHABLE_LEAK_PIPE_H_ #include <sys/socket.h> #include <vector> #include "android-base/macros.h" #include "ScopedPipe.h" #include "log.h" // LeakPipe implements a pipe that can transfer vectors of simple objects // between processes. The pipe is created in the sending process and // transferred over a socketpair that was created before forking. This ensures // that only the sending process can have the send side of the pipe open, so if // the sending process dies the pipe will close. class LeakPipe { public: LeakPipe() { int ret = socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, sv_); if (ret < 0) { LOG_ALWAYS_FATAL("failed to create socketpair: %s", strerror(errno)); } } ~LeakPipe() { Close(); } void Close() { close(sv_[0]); close(sv_[1]); sv_[0] = -1; sv_[1] = -1; } bool OpenReceiver() { int fd = ReceiveFd(sv_[0]); if (fd < 0) { return false; } receiver_.SetFd(fd); return true; } bool OpenSender() { ScopedPipe pipe; if (!SendFd(sv_[1], pipe.Receiver())) { return false; } pipe.ReleaseReceiver(); sender_.SetFd(pipe.ReleaseSender()); return true; } class LeakPipeBase { public: LeakPipeBase() : fd_(-1) {} ~LeakPipeBase() { Close(); } void SetFd(int fd) { fd_ = fd; } void Close() { close(fd_); fd_ = -1; } protected: int fd_; private: DISALLOW_COPY_AND_ASSIGN(LeakPipeBase); }; class LeakPipeSender : public LeakPipeBase { public: using LeakPipeBase::LeakPipeBase; template<typename T> bool Send(const T& value) { ssize_t ret = TEMP_FAILURE_RETRY(write(fd_, &value, sizeof(T))); if (ret < 0) { ALOGE("failed to send value: %s", strerror(errno)); return false; } else if (static_cast<size_t>(ret) != sizeof(T)) { ALOGE("eof while writing value"); return false; } return true; } template<class T, class Alloc = std::allocator<T>> bool SendVector(const std::vector<T, Alloc>& vector) { size_t size = vector.size() * sizeof(T); if (!Send(size)) { return false; } ssize_t ret = TEMP_FAILURE_RETRY(write(fd_, vector.data(), size)); if (ret < 0) { ALOGE("failed to send vector: %s", strerror(errno)); return false; } else if (static_cast<size_t>(ret) != size) { ALOGE("eof while writing vector"); return false; } return true; } }; class LeakPipeReceiver : public LeakPipeBase { public: using LeakPipeBase::LeakPipeBase; template<typename T> bool Receive(T* value) { ssize_t ret = TEMP_FAILURE_RETRY(read(fd_, reinterpret_cast<void*>(value), sizeof(T))); if (ret < 0) { ALOGE("failed to receive value: %s", strerror(errno)); return false; } else if (static_cast<size_t>(ret) != sizeof(T)) { ALOGE("eof while receiving value"); return false; } return true; } template<class T, class Alloc = std::allocator<T>> bool ReceiveVector(std::vector<T, Alloc>& vector) { size_t size = 0; if (!Receive(&size)) { return false; } vector.resize(size / sizeof(T)); char* ptr = reinterpret_cast<char*>(vector.data()); while (size > 0) { ssize_t ret = TEMP_FAILURE_RETRY(read(fd_, ptr, size)); if (ret < 0) { ALOGE("failed to send vector: %s", strerror(errno)); return false; } else if (ret == 0) { ALOGE("eof while reading vector"); return false; } size -= ret; ptr += ret; } return true; } }; LeakPipeReceiver& Receiver() { return receiver_; } LeakPipeSender& Sender() { return sender_; } private: LeakPipeReceiver receiver_; LeakPipeSender sender_; bool SendFd(int sock, int fd); int ReceiveFd(int sock); DISALLOW_COPY_AND_ASSIGN(LeakPipe); int sv_[2]; }; #endif // LIBMEMUNREACHABLE_LEAK_PIPE_H_
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef NSRES_H #define NSRES_H #include "cdefs.h" #include "mcom_db.h" __BEGIN_DECLS /* C version */ #define NSRESHANDLE void * typedef void (*NSRESTHREADFUNC)(void *); typedef struct NSRESTHREADINFO { void *lock; NSRESTHREADFUNC fn_lock; NSRESTHREADFUNC fn_unlock; } NSRESTHREADINFO; #define MAXBUFNUM 10 #define MAXSTRINGLEN 300 #define MAX_MODULE_NAME 40 /************************************************************** Database Record: Each record has its unique key Each record contains charset, translatable and data fields. Record key is generated from library and id Record data is from dataBuffer and dataBufferSize Note: when passing binary data, make sure set dataBufferSize ***************************************************************/ typedef struct _NSRESRecordData { char library[MAX_MODULE_NAME]; int id; PRInt32 dataType; char *dataBuffer; PRInt32 dataBufferSize; PRInt32 trans; } NSRESRecordData; /**************************************************************************** Table Access: Creation and Reading *****************************************************************************/ DBMDLLEXPORT NSRESHANDLE NSResCreateTable(const char *filename, NSRESTHREADINFO *threadinfo); DBMDLLEXPORT NSRESHANDLE NSResOpenTable(const char *filename, NSRESTHREADINFO *threadinfo); DBMDLLEXPORT void NSResCloseTable(NSRESHANDLE handle); /*************************************************************************** Load Record data (String or Binary) to DBM table ***************************************************************************/ DBMDLLEXPORT PRInt32 NSResGetSize(NSRESHANDLE handle, const char *library, PRInt32 id); DBMDLLEXPORT int NSResQueryString(NSRESHANDLE handle, const char * library, PRInt32 id, unsigned int charsetid, char *retbuf); DBMDLLEXPORT char *NSResLoadString(NSRESHANDLE handle, const char * library, PRInt32 id, unsigned int charsetid, char *retbuf); DBMDLLEXPORT PRInt32 NSResLoadResource(NSRESHANDLE handle, const char *library, PRInt32 id, char *retbuf); /*************************************************************************** Append Record data (String or Binary) to DBM table ****************************************************************************/ DBMDLLEXPORT int NSResAddString(NSRESHANDLE handle, const char *library, PRInt32 id, const char *string, unsigned int charset); DBMDLLEXPORT int NSResAddResource(NSRESHANDLE handle, const char *library, PRInt32 id, char *buffer, PRInt32 bufsize); /****************************************************************** Enumeration all table records ******************************************************************/ DBMDLLEXPORT int NSResFirstData(NSRESHANDLE handle, char *keybuf, char *buffer, PRInt32 *size, PRInt32 *charset); DBMDLLEXPORT int NSResNextData(NSRESHANDLE handle, char *keybuf, char *buffer, PRInt32 *size, PRInt32 *charset); /****************************************************************** Load Data in round memory, so caller doesn't need to free it. ******************************************************************/ DBMDLLEXPORT char *NSResLoadStringWithRoundMemory(NSRESHANDLE handle, const char * library, PRInt32 id, unsigned int charsetid, char *retbuf); /****************************************************************** Client generates the record key value and pass to DBM *****************************************************************/ DBMDLLEXPORT PRInt32 NSResGetInfo_key(NSRESHANDLE handle, char *keyvalue, int *size, int *charset); DBMDLLEXPORT PRInt32 NSResLoadResourceWithCharset_key(NSRESHANDLE handle, char *key, unsigned char *retbuf, int *charset); DBMDLLEXPORT PRInt32 NSResAddResourceWithCharset_key(NSRESHANDLE handle, char *key, unsigned char *buffer, PRInt32 bufsize, int charset); /*************************************************************************** Record Interface. Client fills in Record data structure and pass to DBM ****************************************************************************/ DBMDLLEXPORT int NSResAppendString(NSRESHANDLE hNSRes, NSRESRecordData *record); DBMDLLEXPORT int NSResAppendResource(NSRESHANDLE hNSRes, NSRESRecordData *record); DBMDLLEXPORT int NSResLoadFirstData(NSRESHANDLE hNSRes, NSRESRecordData *record); DBMDLLEXPORT int NSResLoadNextData(NSRESHANDLE hNSRes, NSRESRecordData *record); DBMDLLEXPORT int NSResAppendRecord(NSRESHANDLE handle, NSRESRecordData *record); __END_DECLS #endif
<filename>Classes/MPWInteger.h // // MPWInteger.h // MPWFoundation // // Created by <NAME> on 20/3/07. // Copyright 2007 by <NAME>. All rights reserved. // #import <MPWFoundation/MPWNumber.h> @interface MPWInteger : MPWNumber { @public int intValue; } +integer:(int)newInt; -initWithInteger:(NSInteger)newInt; +numberWithInt:(int)anInt; -(void)setIntValue:(int)newInt; -(void)setFloatValue:(float)newFloat; @end
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2016 <NAME> <<EMAIL>> // Copyright (C) 2018 <NAME> <<EMAIL>> // // 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 IGL_GRID_H #define IGL_GRID_H #include "igl_inline.h" #include <Eigen/Core> namespace igl { // Construct vertices of a regular grid, suitable for input to // `igl::marching_cubes` // // Inputs: // res #res list of number of vertices along each dimension filling a unit // #res-cube // Outputs: // GV res.array().prod() by #res list of mesh vertex positions. // // See also: triangulated_grid, quad_grid template < typename Derivedres, typename DerivedGV> IGL_INLINE void grid( const Eigen::MatrixBase<Derivedres> & res, Eigen::PlainObjectBase<DerivedGV> & GV); } #ifndef IGL_STATIC_LIBRARY # include "grid.cpp" #endif #endif
<filename>Docs/References/Ref_codes/Lidar/lidar_slam/hectorslam/HectorDebugInfoProvider.h #ifndef HECTOR_DEBUG_INFO_PROVIDER_H__ #define HECTOR_DEBUG_INFO_PROVIDER_H__ #include "util/HectorDebugInfoInterface.h" #include "util/UtilFunctions.h" //#include "hector_mapping/HectorDebugInfo.h" class HectorDebugInfoProvider : public HectorDebugInfoInterface { public: HectorDebugInfoProvider() { //ros::NodeHandle nh_; //debugInfoPublisher_ = nh_.advertise<hector_mapping::HectorDebugInfo>("hector_debug_info", 50, true); }; virtual void sendAndResetData() { //debugInfoPublisher_.publish(debugInfo); //debugInfo.iterData.clear(); } virtual void addHessianMatrix(const Eigen::Matrix3f& hessian) { /*hector_mapping::HectorIterData iterData; for (int i=0; i < 9; ++i){ iterData.hessian[i] = static_cast<double>(hessian.data()[i]); iterData.determinant = hessian.determinant(); Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eig(hessian); const Eigen::Vector3f& eigValues (eig.eigenvalues()); iterData.conditionNum = eigValues[2] / eigValues[0]; iterData.determinant2d = hessian.block<2,2>(0,0).determinant(); Eigen::SelfAdjointEigenSolver<Eigen::Matrix2f> eig2d(hessian.block<2,2>(0,0)); const Eigen::Vector2f& eigValues2d (eig2d.eigenvalues()); iterData.conditionNum2d = eigValues2d[1] / eigValues2d[0]; } debugInfo.iterData.push_back(iterData);*/ } virtual void addPoseLikelihood(float lh) { } //hector_mapping::HectorDebugInfo debugInfo; //ros::Publisher debugInfoPublisher_; }; #endif
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #pragma once #include <string> #include <vector> #include "mongo/bson/bsonobjbuilder.h" #include "mongo/client/connection_string.h" #include "mongo/db/operation_context.h" #include "mongo/db/server_options.h" #include "mongo/executor/task_executor.h" #include "mongo/platform/mutex.h" #include "mongo/s/client/shard.h" #include "mongo/s/client/shard_factory.h" #include "mongo/stdx/unordered_map.h" #include "mongo/util/concurrency/thread_pool.h" #include "mongo/util/net/hostandport.h" #include "mongo/util/read_through_cache.h" namespace mongo { class ShardRegistryData { public: using ShardMap = stdx::unordered_map<ShardId, std::shared_ptr<Shard>, ShardId::Hasher>; /** * Creates a basic ShardRegistryData, that only contains the config shard. Needed during * initialization, when the config servers are contacted for the first time (ie. the first time * createFromCatalogClient() is called). */ static ShardRegistryData createWithConfigShardOnly(std::shared_ptr<Shard> configShard); /** * Reads shards docs from the catalog client and fills in maps. */ static std::pair<ShardRegistryData, Timestamp> createFromCatalogClient( OperationContext* opCtx, ShardFactory* shardFactory); /** * Merges alreadyCachedData and configServerData into a new ShardRegistryData. * * The merged data is the same as configServerData, except that for the host and connection * string based lookups, any values from alreadyCachedData will take precedence over those from * configServerData. * * Returns the merged data, as well as the shards that have been removed (ie. that are present * in alreadyCachedData but not configServerData) as a mapping from ShardId to * std::shared_ptr<Shard>. * * Called when reloading the shard registry. It is important to merge _hostLookup because * reloading the shard registry can interleave with updates to the shard registry passed by the * RSM. */ static std::pair<ShardRegistryData, ShardMap> mergeExisting( const ShardRegistryData& alreadyCachedData, const ShardRegistryData& configServerData); /** * Create a duplicate of existingData, but additionally updates the shard for newConnString. * Used when notified by the RSM of a new connection string from a shard. */ static ShardRegistryData createFromExisting(const ShardRegistryData& existingData, const ConnectionString& newConnString, ShardFactory* shardFactory); /** * Returns the shard with the given shard id, connection string, or host and port. * * Callers might pass in the connection string or HostAndPort rather than ShardId, so this * method will first look for the shard by ShardId, then connection string, then HostAndPort * stopping once it finds the shard. */ std::shared_ptr<Shard> findShard(const ShardId& shardId) const; /** * Returns the shard with the given replica set name, or nullptr if no such shard. */ std::shared_ptr<Shard> findByRSName(const std::string& name) const; /** * Returns the shard which contains a mongod with the given host and port, or nullptr if no such * shard. */ std::shared_ptr<Shard> findByHostAndPort(const HostAndPort&) const; /** * Returns a vector of all known shard ids. * The order of the elements is not guaranteed. */ std::vector<ShardId> getAllShardIds() const; /** * Returns a vector of all known shard objects. * The order of the elements is not guaranteed. */ std::vector<std::shared_ptr<Shard>> getAllShards() const; void toBSON(BSONObjBuilder* result) const; void toBSON(BSONObjBuilder* map, BSONObjBuilder* hosts, BSONObjBuilder* connStrings) const; BSONObj toBSON() const; private: /** * Returns the shard with the given shard id, or nullptr if no such shard. */ std::shared_ptr<Shard> _findByShardId(const ShardId&) const; /** * Returns the shard with the given connection string, or nullptr if no such shard. */ std::shared_ptr<Shard> _findByConnectionString(const std::string& connectionString) const; /** * Puts the given shard object into the lookup maps. */ void _addShard(std::shared_ptr<Shard>); // Map of shardName -> Shard ShardMap _shardIdLookup; // Map from replica set name to shard corresponding to this replica set ShardMap _rsLookup; // Map of HostAndPort to Shard stdx::unordered_map<HostAndPort, std::shared_ptr<Shard>> _hostLookup; // Map of connection string to Shard std::map<std::string, std::shared_ptr<Shard>> _connStringLookup; }; /** * Maintains the set of all shards known to the instance and their connections and exposes * functionality to run commands against shards. All commands which this registry executes are * retried on NotPrimary class of errors and in addition all read commands are retried on network * errors automatically as well. */ class ShardRegistry { ShardRegistry(const ShardRegistry&) = delete; ShardRegistry& operator=(const ShardRegistry&) = delete; public: /** * A callback type for functions that can be called on shard removal. */ using ShardRemovalHook = std::function<void(const ShardId&)>; /** * Used when informing updateReplSetHosts() of a new connection string for a shard. */ enum class ConnectionStringUpdateType { kConfirmed, kPossible }; /** * Instantiates a new shard registry. * * @param shardFactory Makes shards * @param configServerCS ConnectionString used for communicating with the config servers * @param shardRemovalHooks A list of hooks that will be called when a shard is removed. The * hook is expected not to throw. If it does throw, the process will be * terminated. */ ShardRegistry(std::unique_ptr<ShardFactory> shardFactory, const ConnectionString& configServerCS, std::vector<ShardRemovalHook> shardRemovalHooks = {}); ~ShardRegistry(); /** * Initializes ShardRegistry with config shard. Must be called outside c-tor to avoid calls on * this while its still not fully constructed. */ void init(ServiceContext* service); /** * Startup the periodic reloader of the ShardRegistry. * Can be called only after ShardRegistry::init() */ void startupPeriodicReloader(OperationContext* opCtx); /** * Shutdown the periodic reloader of the ShardRegistry. */ void shutdownPeriodicReloader(); /** * Shuts down the threadPool. Needs to be called explicitly because ShardRegistry is never * destroyed as it's owned by the static grid object. */ void shutdown(); /** * This is invalid to use on the config server and will hit an invariant if it is done. * If the config server has need of a connection string for itself, it should get it from the * replication state. * * Returns the connection string for the config server. */ ConnectionString getConfigServerConnectionString() const; /** * Returns shared pointer to the shard object representing the config servers. * * The config shard is always known, so this function never blocks. */ std::shared_ptr<Shard> getConfigShard() const; /** * Returns a shared pointer to the shard object with the given shard id, or ShardNotFound error * otherwise. * * May refresh the shard registry if there's no cached information about the shard. The shardId * parameter can actually be the shard name or the HostAndPort for any server in the shard. */ StatusWith<std::shared_ptr<Shard>> getShard(OperationContext* opCtx, const ShardId& shardId); /** * Returns a vector containing all known shard IDs. * The order of the elements is not guaranteed. */ std::vector<ShardId> getAllShardIds(OperationContext* opCtx); /** * Returns the number of shards. */ int getNumShards(OperationContext* opCtx); /** * Takes a connection string describing either a shard or config server replica set, looks * up the corresponding Shard object based on the replica set name, then updates the * ShardRegistry's notion of what hosts make up that shard. */ void updateReplSetHosts(const ConnectionString& givenConnString, ConnectionStringUpdateType updateType); /** * Instantiates a new detached shard connection, which does not appear in the list of shards * tracked by the registry and as a result will not be returned by getAllShardIds. * * The caller owns the returned shard object and is responsible for disposing of it when done. * * @param connStr Connection string to the shard. */ std::unique_ptr<Shard> createConnection(const ConnectionString& connStr) const; /** * The ShardRegistry is "up" once a successful lookup from the config servers has been * completed. */ bool isUp() const; void toBSON(BSONObjBuilder* result) const; /** * Force a reload of the ShardRegistry based on the contents of the config server's * config.shards collection. */ void reload(OperationContext* opCtx); /** * Clears all entries from the shard registry entries, which will force the registry to do a * reload on next access. */ void clearEntries(); /** * For use in mongos which needs notifications about changes to shard replset membership to * update the config.shards collection. */ static void updateReplicaSetOnConfigServer(ServiceContext* serviceContex, const ConnectionString& connStr) noexcept; // TODO SERVER-50206: Remove usage of these non-causally consistent accessors. // // Their most important current users are dispatching requests to hosts, and processing // responses from hosts. These contexts need to know the shard that the host is associated // with, but usually have no access to any associated opCtx (if there even is one), and also // cannot tolerate waiting for further network activity (if the cache is stale and needs to be // refreshed via _lookup()). /** * Returns a shared pointer to the shard object with the given shard id. The shardId parameter * can actually be the shard name or the HostAndPort for any server in the shard. Will not * refresh the shard registry or otherwise perform any network traffic. This means that if the * shard was recently added it may not be found. USE WITH CAUTION. */ std::shared_ptr<Shard> getShardNoReload(const ShardId& shardId) const; /** * Finds the Shard that the mongod listening at this HostAndPort is a member of. Will not * refresh the shard registry or otherwise perform any network traffic. */ std::shared_ptr<Shard> getShardForHostNoReload(const HostAndPort& shardHost) const; std::vector<ShardId> getAllShardIdsNoReload() const; int getNumShardsNoReload() const; private: /** * The ShardRegistry uses the ReadThroughCache to handle refreshing itself. The cache stores * a single entry, with key of Singleton, value of ShardRegistryData, and causal-consistency * time which is primarily Timestamp (based on the TopologyTime), but with additional * "increment"s that are used to flag additional refresh criteria. */ using Increment = int64_t; struct Time { explicit Time() {} explicit Time(Timestamp topologyTime, Increment rsmIncrement, Increment forceReloadIncrement) : topologyTime(topologyTime), rsmIncrement(rsmIncrement), forceReloadIncrement(forceReloadIncrement) {} bool operator==(const Time& other) const { return (topologyTime.isNull() || other.topologyTime.isNull() || topologyTime == other.topologyTime) && rsmIncrement == other.rsmIncrement && forceReloadIncrement == other.forceReloadIncrement; } bool operator!=(const Time& other) const { return !(*this == other); } bool operator>(const Time& other) const { // SERVER-56950: When setFCV(v4.4) overlaps with a ShardRegistry reload, // the ShardRegistry can fall into an infinite loop of lookups return (!topologyTime.isNull() && !other.topologyTime.isNull() && topologyTime > other.topologyTime) || rsmIncrement > other.rsmIncrement || forceReloadIncrement > other.forceReloadIncrement; } bool operator>=(const Time& other) const { return (*this > other) || (*this == other); } bool operator<(const Time& other) const { return !(*this >= other); } bool operator<=(const Time& other) const { return !(*this > other); } std::string toString() const { BSONObjBuilder bob; bob.append("topologyTime", topologyTime); bob.append("rsmIncrement", rsmIncrement); bob.append("forceReloadIncrement", forceReloadIncrement); return bob.obj().toString(); } Timestamp topologyTime; // The increments are used locally to trigger the lookup function. // // The rsmIncrement is used to indicate that that there are stashed RSM updates that need to // be incorporated. // // The forceReloadIncrement is used to indicate that the latest data should be fetched from // the configsvrs (ie. when the topologyTime can't be used for this, eg. in the first // lookup, and in contexts like unittests where topologyTime isn't gossipped but the // ShardRegistry still needs to be reloaded). This is how reload() is able to force a // refresh from the config servers - incrementing the forceReloadIncrement causes the cache // to call _lookup() (rather than having reload() attempt to do a synchronous refresh). Increment rsmIncrement{0}; Increment forceReloadIncrement{0}; }; enum class Singleton { Only }; static constexpr auto _kSingleton = Singleton::Only; using Cache = ReadThroughCache<Singleton, ShardRegistryData, Time>; Cache::LookupResult _lookup(OperationContext* opCtx, const Singleton& key, const Cache::ValueHandle& cachedData, const Time& timeInStore); /** * Gets a causally-consistent (ie. latest-known) copy of the ShardRegistryData, refreshing from * the config servers if necessary. */ Cache::ValueHandle _getData(OperationContext* opCtx); /** * Gets a causally-consistent (ie. latest-known) copy of the ShardRegistryData asynchronously, * refreshing from the config servers if necessary. */ SharedSemiFuture<Cache::ValueHandle> _getDataAsync(); /** * Gets the latest-cached copy of the ShardRegistryData. Never fetches from the config servers. * Only used by the "NoReload" accessors. * TODO SERVER-50206: Remove usage of this non-causally consistent accessor. */ Cache::ValueHandle _getCachedData() const; /** * Lookup shard by replica set name. Returns nullptr if the name can't be found. * Note: this doesn't refresh the table if the name isn't found, so it's possible that a * newly added shard/Replica Set may not be found. * TODO SERVER-50206: Remove usage of this non-causally consistent accessor. */ std::shared_ptr<Shard> _getShardForRSNameNoReload(const std::string& name) const; using LatestConnStrings = stdx::unordered_map<ShardId, ConnectionString, ShardId::Hasher>; std::pair<std::vector<LatestConnStrings::value_type>, Increment> _getLatestConnStrings() const; void _removeReplicaSet(const std::string& setName); void _initializeCacheIfNecessary() const; SharedSemiFuture<Cache::ValueHandle> _reloadInternal(); /** * Factory to create shards. Never changed after startup so safe to access outside of _mutex. */ const std::unique_ptr<ShardFactory> _shardFactory; /** * Specified in the ShardRegistry c-tor. It's used only in init() to initialize the config * shard. */ const ConnectionString _initConfigServerCS; /** * A list of callbacks to be called asynchronously when it has been discovered that a shard was * removed. */ const std::vector<ShardRemovalHook> _shardRemovalHooks; // Thread pool used when looking up new values for the cache (ie. in which _lookup() runs). ThreadPool _threadPool; // Executor for periodically reloading the registry (ie. in which _periodicReload() runs). std::shared_ptr<executor::TaskExecutor> _executor{}; mutable Mutex _cacheMutex = MONGO_MAKE_LATCH("ShardRegistry::_cacheMutex"); std::unique_ptr<Cache> _cache; // Counters for incrementing the rsmIncrement and forceReloadIncrement fields of the Time used // by the _cache. See the comments for these fields in the Time class above for an explanation // of their purpose. AtomicWord<Increment> _rsmIncrement{0}; AtomicWord<Increment> _forceReloadIncrement{0}; // Protects _configShardData, and _latestNewConnStrings. mutable Mutex _mutex = MONGO_MAKE_LATCH("ShardRegistry::_mutex"); // Store a reference to the configShard. ShardRegistryData _configShardData; // The key is replset name (the type is ShardId just to take advantage of its hasher). LatestConnStrings _latestConnStrings; AtomicWord<bool> _isInitialized{false}; // The ShardRegistry is "up" once there has been a successful refresh. AtomicWord<bool> _isUp{false}; // Set to true in shutdown call to prevent calling it twice. AtomicWord<bool> _isShutdown{false}; ServiceContext* _service{nullptr}; }; } // namespace mongo
/* * Copyright (c) 2005, <NAME> and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #ifndef _TestRunnerApplication_h_ #define _TestRunnerApplication_h_ #include "Application.h" //---- TestRunnerApplication ----------------------------------------------------------- //! comment class TestRunnerApplication : public Application { public: TestRunnerApplication(); TestRunnerApplication(const char *AppName); ~TestRunnerApplication(); protected: //! does the work //! Runs the application //! \return return code to pass up to calling process //! \pre application is ready to be runned virtual int DoRun(); // GlobalInit: keeps argc and argv for later use virtual int DoGlobalInit(int argc, const char *argv[], const ROAnything config); int fgArgc; const char **fgArgv; }; #endif
<reponame>SlimKatLegacy/android_external_chromium<filename>chrome/browser/tab_contents/tab_util.h // Copyright (c) 2010 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 CHROME_BROWSER_TAB_CONTENTS_TAB_UTIL_H_ #define CHROME_BROWSER_TAB_CONTENTS_TAB_UTIL_H_ #pragma once class TabContents; namespace tab_util { // Helper to find the TabContents that originated the given request. Can be // NULL if the tab has been closed or some other error occurs. // Should only be called from the UI thread, since it accesses TabContent. TabContents* GetTabContentsByID(int render_process_host_id, int routing_id); } // namespace tab_util #endif // CHROME_BROWSER_TAB_CONTENTS_TAB_UTIL_H_
<filename>src/GUI/MimeTypes.h /* * MimeTypes.h * * Created on: Aug 8, 2015 * Author: richard * * Copyright 2017 <NAME> * Licensed under the MIT License */ #ifndef GUI_MIMETYPES_H_ #define GUI_MIMETYPES_H_ #include <string> namespace http { namespace mime_types { /// Convert a file extension into a MIME type. std::string extension_to_type(const std::string& extension); } // namespace mime_types } // namespace http #endif // GUI_MIMETYPES_H_
<gh_stars>1-10 /////////////////////////////////////////////////////////////////////////////// // LSystem LNodeContainer.h // ======== // For creating start nodes and end nodes vectors! // // AUTHOR: <NAME> (<EMAIL>) // CREATED: 2013-06-01 // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "LNode.h" #include <vector> using std::vector; class LNodesContainer { public: LNodesContainer(); ~LNodesContainer(); inline void addStartNode(LNode _sNode) { startNodes.push_back(_sNode); } inline void removeStartNode() { startNodes.pop_back(); } inline void addEndNode(LNode _eNode) { endNodes.push_back(_eNode); } inline vector <LNode> getStartNodes() const { return startNodes; } inline vector <LNode> getEndNodes() const { return endNodes; } private: vector <LNode> startNodes; vector <LNode> endNodes; };
<reponame>zhyzhyzhy/tinyhttp // // Created by 朱逸尘 on 2017/7/31. // #include <stdlib.h> #include <pthread.h> #include <stdio.h> #include <unistd.h> #include "threadpool.h" #include "log.h" #include "mempool.h" #include "handle.h" /** * the work method that threads do * @param arg the threadpool_t point * @return NULL */ void* work(void *arg) { threadpool_t *pool = (threadpool_t*)arg; for(;;) { //lock pthread_mutex_lock(pool->lock); //if job_count == 0, then wait while(pool->job_count == 0) { pthread_cond_wait(pool->cond, pool->lock); //if the server is shutting down then exit if (pool->shutdown == 1) { pthread_mutex_unlock(pool->lock); pthread_exit(arg); } } thread_job *job = pool->job_head; pool->job_head = pool->job_head->next; pool->job_count--; //unlock pthread_mutex_unlock(pool->lock); //process the action job->func(job->arg); mfree(job); if (pool->shutdown == 1) { break; } } return NULL; } /** * * @param thread_num the num of threads in the thread pool * @return one thread pool */ threadpool_t* threadpool_init(int thread_num) { log_info("init thread pool with thread num %d", thread_num); threadpool_t *pool = (threadpool_t*)malloc(sizeof(threadpool_t)); if (pool == NULL) { log_err("can not malloc for thread pool\nexiting..."); exit(1); } pool->pthreads = (pthread_t *)malloc(sizeof(pthread_t) * thread_num); if (pool->pthreads == NULL) { log_err("can not malloc for threads\nexiting..."); exit(1); } pool->job_head = (thread_job*)mmalloc(sizeof(thread_job)); pool->job_count = 0; pool->thread_count = thread_num; pool->shutdown = 0; pool->cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t)); pool->lock = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)); if (pool->cond == NULL || pool->lock == NULL) { log_err("can not malloc for lock!\nexiting..."); exit(1); } pthread_mutex_init(pool->lock, NULL); pthread_cond_init(pool->cond, NULL); for (int i = 0; i < thread_num; i++) { pthread_create(&(pool->pthreads)[i], NULL, work, pool); } return pool; } /** * add job into the thread pool * @param pool the target thread pool * @param job the thread_job need to add to pool */ void add_job(threadpool_t *pool, thread_job* job) { pthread_mutex_lock(pool->lock); job->next = pool->job_head; pool->job_head = job; pool->job_count++; pthread_mutex_unlock(pool->lock); pthread_cond_signal(pool->cond); } /** * stop the threads in target thread pool and clear the resource * @param pool the thread pool that need to destroy */ void threadpool_destroy(threadpool_t *pool) { //set thread pool state to shutdown pool->shutdown = 1; pthread_cond_broadcast(pool->cond); for (int i = 0; i < pool->thread_count; i++) { debug("thread %d join", i); pthread_join((pool->pthreads)[i], NULL); } free(pool->lock); free(pool->cond); free(pool->pthreads); //free all waiting job thread_job* head = pool->job_head; while (head != NULL) { thread_job* p = head->next; struct http_request *request = (struct http_request*)head->arg; if (request != NULL) { close(request->connfd); mfree(request); } mfree(head); head= p; } free(pool); }
<gh_stars>10-100 /********************************************************************** This component implements the runtime's `State`, which is the central component of the VM; implementing memory management, error management, and responsible for managing the lifetime of the other components. A pointer to the runtime's `State*` is directly cast to `ten_State*` before being given to the host application. **********************************************************************/ // The State instance is the center of a Ten VM, it represents the // global VM state and is responsible for managing resources and // handling errors. This is where all the other components come // together to form a useable VM instance. #ifndef ten_state_h #define ten_state_h #include "ten.h" #include "ten_types.h" #include <setjmp.h> #include <stddef.h> #include <stdarg.h> // This represents the header for a garbage collected heap // object. The object is transparant to the rest of the // other components of the system as its prepended to any // object allocations. typedef struct { // This tagged pointer holds a pointer to the next // GC object in the pool, as well as the following // bits in its tag portion: // // [rrrrrrrrr][d][m][ttttt] // 9 1 1 4 // // Where the [r] bits are reserved for future use, the // [m] bit is used by the GC to 'mark' the object as // being reachable, the [d] bit indicates if the object // has already been destructed, and the [t] bits give the // object's type tag. #define OBJ_DEAD_SHIFT (6) #define OBJ_MARK_SHIFT (5) #define OBJ_TAG_SHIFT (0) #define OBJ_DEAD_BIT (0x1 << OBJ_DEAD_SHIFT) #define OBJ_MARK_BIT (0x1 << OBJ_MARK_SHIFT) #define OBJ_TAG_BITS (0x1F << OBJ_TAG_SHIFT) TPtr next; // The object's type specific data follows. char data[]; } Object; // Convert an object pointer to and from a pointer to its data. #define OBJ_DAT_OFFSET ((size_t)&((Object*)0)->data) #define objGetDat( OBJ ) ((void*)(OBJ) + OBJ_DAT_OFFSET) #define objGetTag( OBJ ) ((tpGetTag( (OBJ)->next ) & OBJ_TAG_BITS) >> OBJ_TAG_SHIFT) #define objIsDead( OBJ ) ((tpGetTag( (OBJ)->next ) & OBJ_DEAD_BIT) >> OBJ_DEAD_SHIFT) #define datGetObj( DAT ) ((Object*)((void*)(DAT) - OBJ_DAT_OFFSET)) #define datGetTag( DAT ) (objGetTag( datGetObj( DAT ) )) #define datIsDead( DAT ) (objIsDead( datGetObj( DAT ) )) // The way Ten's VM is setup, we're gonna be long jumping up the // stack whenever an error occurs; this is efficient for error // handling, but can lead to some loose ends as far as memory // allocations and other resource managment goes if we long jump // at the wrong times. So to allow these jumps in a safe way without // chance of a memory or resource leak we define two types: Part // and Defer. // // The Part type is for allocating memory, it represents // an incomplete object or raw memory allocation; providing access // to the allocated memory with the condition that, should an error // jump occur before the memory is committed (with another function // call) it will be released automatically. Object allocations also // are not added to the GC list until committed, this gives us time // to ensure the object is initialized to a valid GC state without // worrying about the possibility of a cycle. // // The Defer type basically just allows us to register an arbitrary // callback to be invoked in case of an error. The callback // is passed a pointer to the Defer itself; so the defer is expected // to be extended with any other data it needs to perform its task. // // Both of these types are typically allocated on the native stack // and linked into the state. So if we forget to commit or otherwise // unlink them before the call frame they're allocated in is popped // the pointers can become corrupted; causing issues with the entire // list. So in debug builds we prefix and postfix these with magic // numbers, which we validate regularly to check for corruption, and // add some fields for keeping track of where the struct was installed // from. typedef struct Part { #define RAW_PART_BEGIN_NUM \ ((ulong)'R' << 24 | (ulong)'B' << 16 | (ulong)'M' << 8 | (ulong)'N') #define OBJ_PART_BEGIN_NUM \ ((ulong)'O' << 24 | (ulong)'B' << 16 | (ulong)'M' << 8 | (ulong)'N') #ifdef ten_DEBUG uint beginNum; char const* file; uint line; #endif // Pointer to the next Part, and a pointer to the previous // Part's pointer to this one. We use the second pointer // for making the adjustments necessary after removing this // Part form the list. struct Part* next; struct Part** link; // A pointer to the allocation, this will either be a pointer // to a raw memory allocation or a pointer to the data portion // of an object allocation. void* ptr; // The size of the allocation, autmatically filled by the // allocator and should not be changed. size_t sz; #define RAW_PART_END_NUM \ ((ulong)'R' << 24 | (ulong)'E' << 16 | (ulong)'M' << 8 | (ulong)'N') #define OBJ_PART_END_NUM \ ((ulong)'O' << 24 | (ulong)'E' << 16 | (ulong)'M' << 8 | (ulong)'N') #ifdef ten_DEBUG uint endNum; #endif } Part; typedef struct Defer { #define DEFER_BEGIN_NUM \ ((ulong)'D' << 24 | (ulong)'B' << 16 | (ulong)'M' << 8 | (ulong)'N') #ifdef ten_DEBUG uint beginNum; char const* file; uint line; #endif // Pointer to the next Defer, and a pointer to the previous // Defer's pointer to this one. struct Defer* next; struct Defer** link; // The actual callback to be called when an error occurs, // the user can choose whether or not to invoke it before // removing the Defer even if an error hasn't occured. // The error type and value itself will be set in the State // before calling, so can be retrieved from there. void (*cb)( State* state, struct Defer* self ); #define DEFER_END_NUM \ ((ulong)'D' << 24 | (ulong)'E' << 16 | (ulong)'M' << 8 | (ulong)'N') #ifdef ten_DEBUG uint endNum; #endif } Defer; // We try to keep the components of Ten's VM as isolated from each other // as possible. Whith each components knowning as little as possible // about the inner workings of the others. The State component // implements GC for the VM as a whole, but shouldn't have to know // about the internals of the other components; so it allows them // to register Scanners and Finalizers. The callbacks specified in // Scanners will be called during each GC cycle, allowing each component // to traverse and mark its GC values. The Finalizers will be called // before destruction of the VM, they can be registered to do any // cleanup required by a component. The callbacks from both types // are passed a self pointer, so the structs are expected to be // extended with any extra data needed for their task. typedef struct Scanner { struct Scanner* next; struct Scanner** link; void (*cb)( State* state, struct Scanner* self ); } Scanner; typedef struct Finalizer { struct Finalizer* next; struct Finalizer** link; void (*cb)( State* state, struct Finalizer* self ); } Finalizer; // This is the State definition itself. The only things it's directly // responsible for is memory management (including GC) and error // handling; otherwise it's just a place to put pointers to all the // other components' state. We also keep a few fields for statistics // tracking here if ten_VERBOSE is defined. struct State { // A copy of the VM configuration, its structure is specified // in the user API file `ten.h`. ten_Config config; // Pointers to the states of all other components. FmtState* fmtState; SymState* symState; PtrState* ptrState; GenState* genState; ComState* comState; EnvState* envState; StrState* strState; IdxState* idxState; RecState* recState; FunState* funState; ClsState* clsState; FibState* fibState; UpvState* upvState; DatState* datState; LibState* libState; ApiState* apiState; // Error related stuff. The `errJmp` points to the // current error handler, which will be jumped to // in case of an error. The others contain the // type and value associated with the error, and // `trace` is where we put the generated stack // trace. jmp_buf* errJmp; ten_ErrNum errNum; TVal errVal; ten_Trace* trace; // Pre-allocated error messages. TVal errOutOfMem; // Current number of bytes allocated on the heap, and // the number that needs to be reached to trigger the // next GC. size_t memUsed; size_t memLimit; #define MEM_LIMIT_INIT (2048) #define DEFAULT_MEM_GROWTH (1.5) // For most garbage collection cycles Ten will only collect // heap objects linked into the `objects` list. This lends // to its efficiency since Symbols and Pointers will generally // have a longer lifetime than most normal objects. But // occasionally we perform a full GC cycle and scan for Symbols // and Pointers as well as objects. These are used to keep // track of which cycle we're performing now and when to do // the next full collection. bool gcFull; bool gcProg; uint gcCount; // List of GC objects. Object* objects; // The current fiber, this is the GC root pointer and // is where we start GC reference traversal after // invoking all the Scanners. Fiber* fiber; // The Part and Defer lists. We have two lists for Parts, // one for raw memory allocations and another for object // allocations. Part* rawParts; Part* objParts; Defer* defers; // The Scanner and Finalizer lists. Scanner* scanners; Finalizer* finalizers; // Temporary variables. #define NUM_TMP_VARS (32) uint tmpNext; TVal* tmpBase; Tup tmpTup; TVal tmpVals[NUM_TMP_VARS]; ten_Var tmpVars[NUM_TMP_VARS]; // GC Stack. #define GC_STACK_SIZE (128) Object** gcCap; Object** gcTop; Object* gcBuf[GC_STACK_SIZE]; }; // Initialization, and finalization. void stateInit( State* state, ten_Config const* config, jmp_buf* errJmp ); void stateFinl( State* state ); // These are convenient routines for accessing the 'current' // stack. If there's a current running fiber (i.e `fib != NULL`) // then these calls will be forwarded to that fiber; otherwise // they'll be forwarded to the environment component. Tup statePush( State* state, uint n ); Tup stateTop( State* state ); void statePop( State* state ); // Returns the next temporary variable. ten_Var* stateTmp( State* state, TVal val ); // Throw an error. The `stateErrStr()` should only be used for // critical errors where a String allocation would otherwise // fail; it expects `str` to be a static string, and will not // release or copy it. In most cases `stateErrFmt*()` is what // we use, this uses the formatting component to generate a // String object as the error value based on the given pattern // and arguments. The `stateErrVal()` specifies an error value // directly. void stateErrFmtA( State* state, ten_ErrNum err, char const* fmt, ... ); void stateErrFmtV( State* state, ten_ErrNum err, char const* fmt, va_list ap ); void stateErrVal( State* state, ten_ErrNum err, TVal val ); void stateErrProp( State* state ); // At some places we need to intercept the errors produced to // prevent them from propegating to the rest of the program; // in such cases the unit in question calls this to replace the // current error handling jump with its own; once the routine // finishes it's expected to swap back to the original, so it // must save the returned pointer. jmp_buf* stateSwapErrJmp( State* state, jmp_buf* jmp ); // Memory management. The allocators return the same value as // put in the `ptr` field of the given Part struct. After // allocation the respective `stateCommit*()` function must // be called to finalize the allocation; this should be called // only once the allocated 'thing' is initialized and there's // no chance of a leak if an error occurs. #ifdef ten_DEBUG #define stateAllocObj( STATE, P, SZ, TAG ) \ _stateAllocObj( STATE, P, SZ, TAG, __FILE__, __LINE__ ) void* _stateAllocObj( State* state, Part* p, size_t sz, ObjTag tag, char const* file, uint line ); #else void* stateAllocObj( State* state, Part* p, size_t sz, ObjTag tag ); #endif void stateCommitObj( State* state, Part* p ); void stateCancelObj( State* state, Part* p ); #ifdef ten_DEBUG #define stateAllocRaw( STATE, P, SZ ) \ _stateAllocRaw( STATE, P, SZ, __FILE__, __LINE__ ) void* _stateAllocRaw( State* state, Part* p, size_t sz, char const* file, unsigned line ); #else void* stateAllocRaw( State* state, Part* p, size_t sz ); #endif #ifdef ten_DEBUG #define stateResizeRaw( STATE, P, SZ ) \ _stateResizeRaw( STATE, P, SZ, __FILE__, __LINE__ ) void* _stateResizeRaw( State* state, Part* p, size_t sz, char const* file, uint line ); #else void* stateResizeRaw( State* state, Part* p, size_t sz ); #endif void stateCommitRaw( State* state, Part* p ); void stateCancelRaw( State* state, Part* p ); void stateFreeRaw( State* state, void* old, size_t osz ); // Defers. Once registered a defer will be invoked if // an error occurs; but they can also be invoked manually // with `stateCommitDefer()` or removed from the list // with `stateCancelDefer()`. #ifdef ten_DEBUG #define stateInstallDefer( STATE, DEFER ) \ _stateInstallDefer( STATE, DEFER, __FILE__, __LINE__ ) void _stateInstallDefer( State* state, Defer* defer, char const* file, uint line ); #else void stateInstallDefer( State* state, Defer* defer ); #endif void stateCommitDefer( State* state, Defer* defer ); void stateCancelDefer( State* state, Defer* defer ); // Install and remove Scanners and Finalizers. void stateInstallScanner( State* state, Scanner* scanner ); void stateRemoveScanner( State* state, Scanner* scanner ); void stateInstallFinalizer( State* state, Finalizer* finalizer ); void stateRemoveFinalizer( State* state, Finalizer* finalizer ); // Push a trace entry to the front of the `trace`, this // allows arbitrary components to add more specificity // to stack traces. void statePushTrace( State* state, char const* unit, char const* file, uint line ); // This clears the trace list but does not free it, instead // returning the list of trace nodes to the caller. It's // used by fibers to internalize the error trace. ten_Trace* stateClaimTrace( State* state ); // Clear the current `trace`, this frees all entries. void stateClearTrace( State* state ); // Free an external trace claimed by a fiber. void stateFreeTrace( State* state, ten_Trace* trace ); // Clear the current error value and trace. void stateClearError( State* state ); // Mark an object reachable and scan it for further references. void stateMark( State* state, void* ptr ); // Force a GC cycle. void stateCollect( State* state ); #ifdef ten_DEBUG void stateCheckState( State* state, char const* file, uint line ); #define CHECK_STATE stateCheckState( state, __FILE__, __LINE__ ); #else #define CHECK_STATE #endif #endif
#ifndef MYTRANLATORPARSER_H #define MYTRANLATORPARSER_H #include <QObject> #include <QFile> #include <QFileInfo> #include <QtDebug> #include <QRegularExpression> #include <QTextStream> //model #include "third-party/ts_tool/ts_model.h" // Local #include "MyLanguageModel.h" /************************************************ * @brief Tranlator Parser. * \class MyTranlatorParser ***********************************************/ class MyTranlatorParser : public QObject { Q_OBJECT public: explicit MyTranlatorParser(MyLanguageModel *thisLanguageModel = nullptr, QObject *parent = nullptr); // base_node::base_node_ptr parse_ts_file(const QString &inputFile); //!< parse_ts_file bool parse_txt_file(const QString &inputFile, visitors::map_QStringQString &strings); //!< parse_txt_file void toTXT(const QString &inputFile, const QString &outputDir, bool with_unfinished, bool with_vanished, bool unfinished_only); //!< toTXT void toTS(const QString &inputDir, const QString &outputFile, const QString &langid); //!< toTS // Is Debug Message void setDebugMessage(bool thisState); //!< set Debug Message bool getDebugMessage(); //!< get Debug Message void setMessage(const QString &thisMessage); //!< set Message private: MyLanguageModel *myLanguageModel; //!< \c myLanguageModel @brief Localization Model. bool isDebugMessage = true; //!< \c isDebugMessage @brief is Debug Message }; #endif // MYTRANLATORPARSER_H /******************************* End of File *********************************/
// // SHDPerson.h // SHDCircularView // // Created by <NAME> on 09.09.14. // Copyright (c) 2014 ShadeApps. All rights reserved. // #import <Foundation/Foundation.h> @interface SHDPerson : NSObject @property (nonatomic, retain) NSString *personName; @property (nonatomic, retain) NSString *personAvatarImageName; @end
/* FAR Manager ASCII Table Plugin (c) SysTools 2016,2018 http://systools.losthost.org/?misc#asciitab ASCII Table plugin like one from DOS Navigator. Tested under FAR Manager 3.00 build 5100 x64 */ #include <windows.h> // FAR Manager Plugins SDK #include "far300hd/plugin.hpp" #include "far300hd/farcolor.hpp" #define EXPORT __declspec(dllexport) // const structs const static TCHAR InfoFmtStr[] = TEXT("#Char: # Decimal: ### Hex: ## \x25A0 "); const static TCHAR PluginInfo[] = TEXT("http://systools.losthost.org"); const static TCHAR PluginName[] = TEXT("ASCII Table"); const static TCHAR *PluginMenuStrings[1]; static const GUID MainGuid = { 0xaaf2988a, 0x1718, 0x4567, { 0xb0, 0xb7, 0xf6, 0x78, 0xfe, 0xd1, 0x94, 0x0e } }; static const GUID MenuGuid = { 0x6b9ebfa7, 0xb357, 0x403c, { 0xbf, 0x2a, 0x6e, 0xbc, 0xed, 0x0a, 0x86, 0xe3 } }; static const GUID DlgsGuid = { 0x39533487, 0x429b, 0x4181, { 0x96, 0x0b, 0x41, 0xe8, 0x0c, 0x3a, 0x97, 0x97 } }; #define MAX_ELEM 4 static struct PluginStartupInfo FARAPI; static struct FarDialogItem DialogItems[MAX_ELEM]; static struct FAR_CHAR_INFO vb[256 + 32]; // table + info static DWORD dwCodePage; TCHAR GetCharCP(DWORD c) { WCHAR w; w = TEXT(' '); c &= 0xFFFF; MultiByteToWideChar(dwCodePage, 0, (CCHAR *)&c, 1, &w, 1); return(w); } BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { return(TRUE); } // The GetGlobalInfoW function is called to get general plugin information EXPORT void WINAPI GetGlobalInfoW(struct GlobalInfo *Info) { Info->StructSize = sizeof(Info[0]); Info->MinFarVersion = FARMANAGERVERSION; Info->Version = MAKEFARVERSION(FARMANAGERVERSION_MAJOR,FARMANAGERVERSION_MINOR,FARMANAGERVERSION_REVISION,1,VS_RELEASE); Info->Guid = MainGuid; Info->Title = PluginName; Info->Description = PluginName; Info->Author = PluginInfo; } // The SetStartupInfo function is called once, after the DLL module is loaded to memory. // This function gives the plugin information necessary for further operation. EXPORT void WINAPI SetStartupInfoW(const struct PluginStartupInfo *Info) { DWORD i; // switch codepage dwCodePage = (dwCodePage == CP_OEMCP) ? CP_ACP : CP_OEMCP; FARAPI = *Info; // initialization code ZeroMemory(DialogItems, sizeof(DialogItems[0]) * MAX_ELEM); // dialog box DialogItems[0].Type = DI_DOUBLEBOX; DialogItems[0].X1 = 0; DialogItems[0].Y1 = 0; DialogItems[0].X2 = 33; DialogItems[0].Y2 = 11; // separator DialogItems[1].Type = DI_SINGLEBOX; DialogItems[1].X1 = 1; DialogItems[1].Y1 = 9; DialogItems[1].X2 = 32; DialogItems[1].Y2 = 9; DialogItems[1].Flags = DIF_SEPARATOR; // information text DialogItems[2].Type = DI_USERCONTROL; DialogItems[2].X1 = 1; DialogItems[2].Y1 = 10; DialogItems[2].X2 = 32; DialogItems[2].Y2 = 10; DialogItems[2].Param.VBuf = &vb[256]; // characters table DialogItems[3].Type = DI_USERCONTROL; DialogItems[3].X1 = 1; DialogItems[3].Y1 = 1; DialogItems[3].X2 = 32; DialogItems[3].Y2 = 8; DialogItems[3].Param.VBuf = vb; // init table ZeroMemory(vb, sizeof(vb[0]) * (256 + 32)); // characters table FARAPI.AdvControl(&MainGuid, ACTL_GETCOLOR, COL_DIALOGTEXT, &vb[0].Attributes); for (i = 0; i < 256; i++) { vb[i].Char = GetCharCP(i); vb[i].Attributes = vb[0].Attributes; } // information text FARAPI.AdvControl(&MainGuid, ACTL_GETCOLOR, COL_DIALOGHIGHLIGHTTEXT, &vb[256].Attributes); for (i = 0; i < 32; i++) { if (InfoFmtStr[i] == TEXT('#')) { vb[256 + i].Char = TEXT(' '); vb[256 + i].Attributes = vb[256].Attributes; } else { vb[256 + i].Char = InfoFmtStr[i]; vb[256 + i].Attributes = vb[0].Attributes; } } } EXPORT void WINAPI GetPluginInfoW(struct PluginInfo *Info) { Info->StructSize = sizeof(Info[0]); Info->Flags = PF_EDITOR | PF_VIEWER; PluginMenuStrings[0] = PluginName; Info->PluginMenu.Guids = &MenuGuid; Info->PluginMenu.Strings = PluginMenuStrings; Info->PluginMenu.Count = 1; } void UpdateInfoLine(HANDLE hDlg, COORD *c) { struct FAR_CHAR_INFO *v; DWORD r; FARAPI.SendDlgMessage(hDlg, DM_SETCURSORPOS, 3, (void *) c); r = ((c->Y * 32) + c->X) & 0xFF; v = &vb[256]; // char v[7].Char = GetCharCP(r); // digit if (r >= 100) { v[18].Char = TEXT('0') + (r/100); } else { v[18].Char = TEXT(' '); } if (r >= 10) { v[19].Char = TEXT('0') + ((r/10)%10); } else { v[19].Char = TEXT(' '); } v[20].Char = TEXT('0') + (r%10); // hex v[27].Char = TEXT('0') + (r >> 4); v[28].Char = TEXT('0') + (r & 0x0F); v[27].Char += (v[27].Char > TEXT('9')) ? 7 : 0; v[28].Char += (v[28].Char > TEXT('9')) ? 7 : 0; // update color character if (r) { v[30].Attributes.Flags = FCF_4BITMASK; v[30].Attributes.Foreground.ForegroundColor = (r & 0x0F); v[30].Attributes.Background.BackgroundColor = ((r >> 4) & 0x0F); } else { v[30].Attributes = vb[0].Attributes; } // force information text to redraw FARAPI.SendDlgMessage(hDlg, DM_SETDLGITEM, 2, (void *) &DialogItems[2]); } intptr_t WINAPI DlgPrc(HANDLE hDlg, intptr_t Msg, intptr_t Param1, void *Param2) { COORD c; INPUT_RECORD *ir; switch (Msg) { case DN_INITDIALOG: // set dialog title and also restore it after F1 FARAPI.SendDlgMessage(hDlg, DM_SETTEXTPTR, 0, (void*) &PluginName); // center of the table c.X = 16; c.Y = 4; // set focus to characters table FARAPI.SendDlgMessage(hDlg, DM_SETFOCUS, 3, NULL); // make cursor big FARAPI.SendDlgMessage(hDlg, DM_SETCURSORSIZE, 3, (void *) MAKELONG(1, 99)); // show information text UpdateInfoLine(hDlg, &c); // save character address pointer FARAPI.SendDlgMessage(hDlg, DM_SETDLGDATA, 0, Param2); // tell FAR that information text was updated return(TRUE); break; // do not allow to change focus // to any other element except // the characters table case DN_KILLFOCUS: return(3); break; // walk through characters case DN_CONTROLINPUT: ir = (INPUT_RECORD *) Param2; // if keyboard if (ir->EventType == KEY_EVENT) { if (Param1 == 3) { FARAPI.SendDlgMessage(hDlg, DM_GETCURSORPOS, 3, (void *) &c); ir = (INPUT_RECORD *) Param2; switch (ir->Event.KeyEvent.wVirtualKeyCode) { case VK_UP: c.Y -= (c.Y ? 1 : 0); break; case VK_DOWN: c.Y += ((c.Y < 7) ? 1 : 0); break; case VK_LEFT: c.X -= (c.X ? 1 : 0); break; case VK_RIGHT: c.X += ((c.X < 31) ? 1 : 0); break; case VK_HOME: c.X = 0; break; case VK_END: c.X = 31; break; case VK_PRIOR: c.Y = 0; break; case VK_NEXT: c.Y = 7; break; case VK_F8: SetStartupInfoW(&FARAPI); break; } UpdateInfoLine(hDlg, &c); } // about if (ir->Event.KeyEvent.wVirtualKeyCode == VK_F1) { // set text to dialog title FARAPI.SendDlgMessage(hDlg, DM_SETTEXTPTR, 0, (void *) &PluginInfo); } } // mouse clicked if ((ir->EventType == MOUSE_EVENT) && (Param1 == 3)) { UpdateInfoLine(hDlg, &ir->Event.MouseEvent.dwMousePosition); } break; // on close - return selected character case DN_CLOSE: if (Param1 == 3) { FARAPI.SendDlgMessage(hDlg, DM_GETCURSORPOS, 3, (void *) &c); // return selected character *((DWORD *) FARAPI.SendDlgMessage(hDlg, DM_GETDLGDATA, 0, NULL)) = GetCharCP(((c.Y * 32) + c.X) & 0xFF); } break; } // default dialogue procedure return(FARAPI.DefDlgProc(hDlg, Msg, Param1, Param2)); } intptr_t FARAPI_DialogEx( const GUID* PluginId, intptr_t X1, intptr_t Y1, intptr_t X2, intptr_t Y2, const wchar_t *HelpTopic, const struct FarDialogItem *Item, size_t ItemsNumber, intptr_t Reserved, FARDIALOGFLAGS Flags, FARWINDOWPROC DlgProc, void *Param ) { intptr_t r; HANDLE hDlg; // FARAPI.Message(&MainGuid, NULL, FMSG_ALLINONE, NULL, TEXT("Test\nOK"), 2, 1); hDlg = FARAPI.DialogInit( PluginId, &DlgsGuid, X1, Y1, X2, Y2, HelpTopic, Item, ItemsNumber, Reserved, Flags, DlgProc, Param ); if (hDlg != INVALID_HANDLE_VALUE) { r = FARAPI.DialogRun(hDlg); FARAPI.DialogFree(hDlg); } else { r = -1; } return(r); } // The OpenPlugin is called to create a new plugin instance. EXPORT HANDLE WINAPI OpenW(const struct OpenInfo *Info) { DWORD pchr; if (FARAPI_DialogEx(&MainGuid, -1, -1, 32+2, 8+2+2, NULL, DialogItems, MAX_ELEM, 0, FDLG_NONE, DlgPrc, (void *) &pchr) != -1) { // insert character only in editor or file panel if (Info->OpenFrom != OPEN_VIEWER) { if (Info->OpenFrom == OPEN_EDITOR) { FARAPI.EditorControl(-1, ECTL_INSERTTEXT, 0, (void *) &pchr); } else { FARAPI.PanelControl(PANEL_ACTIVE, FCTL_INSERTCMDLINE, 0, (void *) &pchr); } } } return(0); }
<gh_stars>10-100 // // Header.h // SuspensionAssistiveTouch // // Created by Rainy on 2017/10/30. // Copyright © 2017年 Rainy. All rights reserved. // #ifndef Header_h #define Header_h #import "UIView+Extension.h" #define kSuspensionViewDisNotificationName @"SUSPENSIONVIEWDISAPPER_NOTIFICATIONNAME" #define kSuspensionViewShowNotificationName @"SUSPENSIONVIEWSHOW_NOTIFICATIONNAME" #define kNotificationCenter [NSNotificationCenter defaultCenter] #define kWindow [[UIApplication sharedApplication].windows firstObject] #define kScreenBounds [[UIScreen mainScreen] bounds] #define kScreenWidth kScreenBounds.size.width #define kScreenHeight kScreenBounds.size.height #define kAssistiveTouchIMG [UIImage imageNamed:@"icon.png"] #define kHeaderViewIMG [UIImage imageNamed:@"header"] #define kHeaderIMG [UIImage imageNamed:@"touxiang"] #define kAlpha 0.5 #define kPrompt_DismisTime 0.2 #define kProportion 0.82 #endif /* Header_h */
<filename>user/openlumi-21.02.0-rc/files/package/kernel/rtl8723bs/src/hal/btc/halbtc8821cwifionly.c /* SPDX-License-Identifier: GPL-2.0 */ /****************************************************************************** * * Copyright(c) 2016 - 2017 Realtek Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * *****************************************************************************/ #include "mp_precomp.h" static struct rfe_type_8821c_wifi_only gl_rfe_type_8821c_1ant; static struct rfe_type_8821c_wifi_only *rfe_type = &gl_rfe_type_8821c_1ant; VOID hal8821c_wifi_only_switch_antenna( IN struct wifi_only_cfg *pwifionlycfg, IN u1Byte is_5g ) { boolean switch_polatiry_inverse = false; u8 regval_0xcb7 = 0; u8 pos_type, ctrl_type; if (!rfe_type->ext_ant_switch_exist) return; /* swap control polarity if use different switch control polarity*/ /* Normal switch polarity for DPDT, 0xcb4[29:28] = 2b'01 => BTG to Main, WLG to Aux, 0xcb4[29:28] = 2b'10 => BTG to Aux, WLG to Main */ /* Normal switch polarity for SPDT, 0xcb4[29:28] = 2b'01 => Ant to BTG, 0xcb4[29:28] = 2b'10 => Ant to WLG */ if (rfe_type->ext_ant_switch_ctrl_polarity) switch_polatiry_inverse = !switch_polatiry_inverse; /* swap control polarity if 1-Ant at Aux */ if (rfe_type->ant_at_main_port == false) switch_polatiry_inverse = !switch_polatiry_inverse; if (is_5g) pos_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_TO_WLA; else pos_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_TO_WLG; switch (pos_type) { default: case BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_TO_WLA: break; case BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_TO_WLG: if (!rfe_type->wlg_Locate_at_btg) switch_polatiry_inverse = !switch_polatiry_inverse; break; } if (pwifionlycfg->haldata_info.ant_div_cfg) ctrl_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_CTRL_BY_ANTDIV; else ctrl_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_CTRL_BY_BBSW; switch (ctrl_type) { default: case BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_CTRL_BY_BBSW: halwifionly_phy_set_bb_reg(pwifionlycfg, 0x4c, 0x01800000, 0x2); /* BB SW, DPDT use RFE_ctrl8 and RFE_ctrl9 as control pin */ halwifionly_phy_set_bb_reg(pwifionlycfg, 0xcb4, 0x000000ff, 0x77); regval_0xcb7 = (switch_polatiry_inverse == false ? 0x1 : 0x2); /* 0xcb4[29:28] = 2b'01 for no switch_polatiry_inverse, DPDT_SEL_N =1, DPDT_SEL_P =0 */ halwifionly_phy_set_bb_reg(pwifionlycfg, 0xcb4, 0x30000000, regval_0xcb7); break; case BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_CTRL_BY_ANTDIV: halwifionly_phy_set_bb_reg(pwifionlycfg, 0x4c, 0x01800000, 0x2); /* BB SW, DPDT use RFE_ctrl8 and RFE_ctrl9 as control pin */ halwifionly_phy_set_bb_reg(pwifionlycfg, 0xcb4, 0x000000ff, 0x88); /* no regval_0xcb7 setup required, because antenna switch control value by antenna diversity */ break; } } VOID halbtc8821c_wifi_only_set_rfe_type( IN struct wifi_only_cfg *pwifionlycfg ) { /* the following setup should be got from Efuse in the future */ rfe_type->rfe_module_type = (pwifionlycfg->haldata_info.rfe_type) & 0x1f; rfe_type->ext_ant_switch_ctrl_polarity = 0; switch (rfe_type->rfe_module_type) { case 0: default: rfe_type->ext_ant_switch_exist = true; rfe_type->ext_ant_switch_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_USE_DPDT; /*2-Ant, DPDT, WLG*/ rfe_type->wlg_Locate_at_btg = false; rfe_type->ant_at_main_port = true; break; case 1: rfe_type->ext_ant_switch_exist = true; rfe_type->ext_ant_switch_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_USE_SPDT; /*1-Ant, Main, DPDT or SPDT, WLG */ rfe_type->wlg_Locate_at_btg = false; rfe_type->ant_at_main_port = true; break; case 2: rfe_type->ext_ant_switch_exist = true; rfe_type->ext_ant_switch_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_USE_SPDT; /*1-Ant, Main, DPDT or SPDT, BTG */ rfe_type->wlg_Locate_at_btg = true; rfe_type->ant_at_main_port = true; break; case 3: rfe_type->ext_ant_switch_exist = true; rfe_type->ext_ant_switch_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_USE_DPDT; /*1-Ant, Aux, DPDT, WLG */ rfe_type->wlg_Locate_at_btg = false; rfe_type->ant_at_main_port = false; break; case 4: rfe_type->ext_ant_switch_exist = true; rfe_type->ext_ant_switch_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_USE_DPDT; /*1-Ant, Aux, DPDT, BTG */ rfe_type->wlg_Locate_at_btg = true; rfe_type->ant_at_main_port = false; break; case 5: rfe_type->ext_ant_switch_exist = false; /*2-Ant, no antenna switch, WLG*/ rfe_type->ext_ant_switch_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_NONE; rfe_type->wlg_Locate_at_btg = false; rfe_type->ant_at_main_port = true; break; case 6: rfe_type->ext_ant_switch_exist = false; /*2-Ant, no antenna switch, WLG*/ rfe_type->ext_ant_switch_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_NONE; rfe_type->wlg_Locate_at_btg = false; rfe_type->ant_at_main_port = true; break; case 7: rfe_type->ext_ant_switch_exist = true; /*2-Ant, DPDT, BTG*/ rfe_type->ext_ant_switch_type = BT_8821C_WIFI_ONLY_EXT_ANT_SWITCH_USE_DPDT; rfe_type->wlg_Locate_at_btg = true; rfe_type->ant_at_main_port = true; break; } } VOID ex_hal8821c_wifi_only_hw_config( IN struct wifi_only_cfg *pwifionlycfg ) { halbtc8821c_wifi_only_set_rfe_type(pwifionlycfg); /* set gnt_wl, gnt_bt control owner to WL*/ halwifionly_phy_set_bb_reg(pwifionlycfg, 0x70, 0x400000, 0x1); /*gnt_wl=1 , gnt_bt=0*/ halwifionly_phy_set_bb_reg(pwifionlycfg, 0x1704, 0xffffffff, 0x7700); halwifionly_phy_set_bb_reg(pwifionlycfg, 0x1700, 0xffffffff, 0xc00f0038); } VOID ex_hal8821c_wifi_only_scannotify( IN struct wifi_only_cfg *pwifionlycfg, IN u1Byte is_5g ) { hal8821c_wifi_only_switch_antenna(pwifionlycfg, is_5g); } VOID ex_hal8821c_wifi_only_switchbandnotify( IN struct wifi_only_cfg *pwifionlycfg, IN u1Byte is_5g ) { hal8821c_wifi_only_switch_antenna(pwifionlycfg, is_5g); }
#ifndef ENGINE_TYPES_H #define ENGINE_TYPES_H typedef unsigned char u8; typedef unsigned short u16; typedef unsigned long u32; typedef u8 bool; typedef signed char s8; typedef signed short s16; typedef signed long s32; #define true 1 #define false 0 #define NULL 0 #endif /* ENGINE_TYPES_H */
/*************************************** * Framework Handler Task * https://github.com/goganoga/FHT * Created: 14.10.19 * Copyright (C) goganoga 2019 ***************************************/ #ifndef FHTICLIENT_H #define FHTICLIENT_H #include <memory> #include <cstdint> #include <functional> #include <map> #include <boost/beast/core/multi_buffer.hpp> #include <boost/beast/core/buffers_to_string.hpp> #include <boost/beast/http/fields.hpp> #include <boost/beast/http/verb.hpp> #include <boost/asio/buffer.hpp> #include <boost/exception/to_string.hpp> namespace FHT { struct iClient { struct httpClient { struct httpResponse { int status = 0; std::string err; boost::beast::multi_buffer body; std::map<std::string, std::string> headers; inline std::string getStringFromBody() { return boost::beast::buffers_to_string(body.data()); } }; std::string url; boost::beast::multi_buffer body; std::map<std::string, std::string> headers; boost::beast::http::verb type = boost::beast::http::verb::get; inline void setStringToBody(std::string body_str) { headers.emplace(boost::beast::http::to_string(boost::beast::http::field::content_type), "text/plain"); body.commit(boost::asio::buffer_copy(body.prepare(body_str.size()), boost::asio::buffer(body_str))); type = boost::beast::http::verb::post; } //async fetch void fetch(std::function<void(httpResponse)>); //sync fetch const httpResponse fetch(); }; virtual ~iClient() = default; }; } #endif //FHTICLIENT_H
// The MIT License // // Copyright (c) 2014 <NAME> // // 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. #import <Foundation/Foundation.h> #import "GRMustacheAvailabilityMacros.h" @protocol GRMustacheRendering; @class GRMustacheTag; @class GRMustacheContext; /** * A C struct that hold GRMustache version information * * @since v1.0 */ typedef struct { int major; /**< The major component of the version. */ int minor; /**< The minor component of the version. */ int patch; /**< The patch-level component of the version. */ } GRMustacheVersion; /** * The GRMustache class provides with global-level information and configuration * of the GRMustache library. * * @since v1.0 */ @interface GRMustache: NSObject //////////////////////////////////////////////////////////////////////////////// /// @name Getting the GRMustache version //////////////////////////////////////////////////////////////////////////////// /** * @return The version of GRMustache as a GRMustacheVersion struct. * * @since v7.0 */ + (GRMustacheVersion)libraryVersion AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER; //////////////////////////////////////////////////////////////////////////////// /// @name Preventing NSUndefinedKeyException in Development configuration //////////////////////////////////////////////////////////////////////////////// /** * Have GRMustache avoid most `NSUndefinedKeyExceptions` when rendering * templates. * * The rendering of a GRMustache template can lead to `NSUndefinedKeyExceptions` * to be raised, because of the usage of the `valueForKey:` method. Those * exceptions are nicely handled by GRMustache, and are part of the regular * rendering of a template. * * Unfortunately, Objective-C exceptions have several drawbacks, particularly: * * 1. they play badly with autorelease pools, and are reputed to leak memory. * 2. they usually stop your debugger when you are developping your application. * * The first point is indeed a matter of worry: Apple does not guarantee that * exceptions raised by `valueForKey:` do not leak memory. However, I never had * any evidence of such a leak from NSObject's implementation. * * Should you still worry, we recommend that you avoid the `valueForKey:` method * altogether. Instead, implement the [keyed subscripting](http://clang.llvm.org/docs/ObjectiveCLiterals.html#dictionary-style-subscripting) * `objectForKeyedSubscript:` method on objects that you provide to GRMustache. * * The second point is valid also: NSUndefinedKeyException raised by template * rendering may become a real annoyance when you are debugging your project, * because it's likely you've told your debugger to stop on every Objective-C * exceptions. * * You can avoid them as well: make sure you invoke once, early in your * application, the `preventNSUndefinedKeyExceptionAttack` method. * * Depending on the number of NSUndefinedKeyException that get prevented, you * will experience a slight performance hit, or a performance improvement. * * Since the main use case for this method is to avoid Xcode breaks on rendering * exceptions, the best practice is to conditionally invoke this method, using * the [NS_BLOCK_ASSERTIONS](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html) * that helps identifying the Debug configuration of your targets: * * ``` * #if !defined(NS_BLOCK_ASSERTIONS) * // Debug configuration: keep GRMustache quiet * [GRMustache preventNSUndefinedKeyExceptionAttack]; * #endif * ``` * * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/runtime.md * * @since v1.7 */ + (void)preventNSUndefinedKeyExceptionAttack AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER; //////////////////////////////////////////////////////////////////////////////// /// @name Standard Library //////////////////////////////////////////////////////////////////////////////// /** * @return The GRMustache standard library. * * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/standard_library.md * * @since v6.4 */ + (NSObject *)standardLibrary AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER; //////////////////////////////////////////////////////////////////////////////// /// @name Building rendering objects //////////////////////////////////////////////////////////////////////////////// /** * This method is deprecated. Use * `+[GRMustacheRendering renderingObjectForObject:]` instead. * * @see GRMustacheRendering class * * @since v6.0 * @deprecated v7.0 */ + (id<GRMustacheRendering>)renderingObjectForObject:(id)object AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER_BUT_DEPRECATED; /** * This method is deprecated. Use * `+[GRMustacheRendering renderingObjectWithBlock:]` instead. * * @see GRMustacheRendering class * * @since v6.0 * @deprecated v7.0 */ + (id<GRMustacheRendering>)renderingObjectWithBlock:(NSString *(^)(GRMustacheTag *tag, GRMustacheContext *context, BOOL *HTMLSafe, NSError **error))block AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER_BUT_DEPRECATED; @end #import "GRMustacheTemplate.h" #import "GRMustacheTagDelegate.h" #import "GRMustacheTemplateRepository.h" #import "GRMustacheFilter.h" #import "GRMustacheError.h" #import "GRMustacheVersion.h" #import "GRMustacheContentType.h" #import "GRMustacheContext.h" #import "GRMustacheRendering.h" #import "GRMustacheTag.h" #import "GRMustacheConfiguration.h" #import "GRMustacheLocalizer.h" #import "GRMustacheSafeKeyAccess.h"
/** * Simple test to compile a song and, then, count how many samples are needed * for that song * * @file tst/tst_countSamples.c */ #include <c_synth/synth.h> #include <c_synth/synth_assert.h> #include <c_synth/synth_errors.h> #include <stdio.h> #include <string.h> /* Simple test song */ static char __song[] = "MML t90 l16 o5 e e8 e r c e r g4 > g4 <"; /** * Entry point * * @param [ in]argc Number of arguments * @param [ in]argv List of arguments * @return The exit code */ int main(int argc, char *argv[]) { char *pSrc; int freq, handle, i, isFile, len, num; synthCtx *pCtx; synth_err rv; /* Clean the context, so it's not freed on error */ pCtx = 0; /* Store the default frequency */ freq = 44100; isFile = 0; pSrc = 0; len = 0; /* Check argc/argv */ if (argc > 1) { int i; i = 1; while (i < argc) { #define IS_PARAM(l_cmd, s_cmd) \ if (strcmp(argv[i], l_cmd) == 0 || strcmp(argv[i], s_cmd) == 0) IS_PARAM("--string", "-s") { if (argc <= i + 1) { printf("Expected parameter but got nothing! Run " "'tst_countSampler --help' for usage!\n"); return 1; } /* Store the string and retrieve its length */ pSrc = argv[i + 1]; isFile = 0; len = strlen(argv[i + 1]); } IS_PARAM("--file", "-f") { if (argc <= i + 1) { printf("Expected parameter but got nothing! Run " "'tst_countSampler --help' for usage!\n"); return 1; } /* Store the filename */ pSrc = argv[i + 1]; isFile = 1; } IS_PARAM("--frequency", "-F") { if (argc <= i + 1) { printf("Expected parameter but got nothing! Run " "'tst_countSampler --help' for usage!\n"); return 1; } char *pNum; int tmp; pNum = argv[i + 1]; tmp = 0; while (*pNum != '\0') { tmp = tmp * 10 + (*pNum) - '0'; pNum++; } freq = tmp; } IS_PARAM("--help", "-h") { printf("A simple test for the c_synth library\n" "\n" "Usage: tst_countSamples [--string | -s \"the song\"] " "[--file | -f <file>]\n" " [--frequency | -F <freq>] " "[--help | -h]\n" "\n" "Only one song can be compiled at a time, and this " "program simply checks if it \n" "compiles successfully or not (no output is " "generated).\n" "On error, however, this program does display the " "cause and position of the \n" "error.\n" "\n" "If no argument is passed, it will compile a simple " "test song.\n" "\n" "After compiling the song, the number of samples " "required by it will be counted\n"); return 0; } i += 2; #undef IS_PARAM } } /* Initialize it */ printf("Initialize the synthesizer...\n"); rv = synth_init(&pCtx, freq); SYNTH_ASSERT(rv == SYNTH_OK); /* Compile a song */ if (pSrc != 0) { if (isFile) { printf("Compiling song from file '%s'...\n", pSrc); rv = synth_compileSongFromFile(&handle, pCtx, pSrc); } else { printf("Compiling song '%s'...\n", pSrc); rv = synth_compileSongFromString(&handle, pCtx, pSrc, len); } } else { printf("Compiling static song '%s'...\n", __song); rv = synth_compileSongFromStringStatic(&handle, pCtx, __song); } if (rv != SYNTH_OK) { char *pError; synth_err irv; /* Retrieve and print the error */ irv = synth_getCompilerErrorString(&pError, pCtx); SYNTH_ASSERT_ERR(irv == SYNTH_OK, irv); printf("%s", pError); } else { printf("Song compiled successfully!\n"); } SYNTH_ASSERT(rv == SYNTH_OK); /* Get the number of tracks in the song */ printf("Retrieving the number of tracks in the song...\n"); rv = synth_getAudioTrackCount(&num, pCtx, handle); SYNTH_ASSERT(rv == SYNTH_OK); printf("Found %i tracks\n", num); /* Get the number of samples in each track */ printf("Counting the number of samples required by the song...\n"); i = 0; while (i < num) { int intro, len; rv = synth_getTrackIntroLength(&intro, pCtx, handle, i); SYNTH_ASSERT(rv == SYNTH_OK); rv = synth_getTrackLength(&len, pCtx, handle, i); SYNTH_ASSERT(rv == SYNTH_OK); printf("Track %i requires %i samples and loops at %i\n", i + 1, len, intro); i++; } rv = SYNTH_OK; __err: if (rv != SYNTH_OK) { printf("An error happened!\n"); } if (pCtx) { printf("Releasing resources used by the lib...\n"); synth_free(&pCtx); } printf("Exiting...\n"); return rv; }
<reponame>hpgem/hpgem /* This file forms part of hpGEM. This package has been developed over a number of years by various people at the University of Twente and a full list of contributors can be found at http://hpgem.org/about-the-code/team This code is distributed using BSD 3-Clause License. A copy of which can found below. Copyright (c) 2014, University of Twente All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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 HPGEM_KERNEL_VTKSPECIFICTIMEWRITER_H #define HPGEM_KERNEL_VTKSPECIFICTIMEWRITER_H #include <functional> #include <fstream> #include <map> #include <memory> #include "Base/MeshManipulator.h" #include "Geometry/ReferenceGeometry.h" #include "VTKElement.h" namespace hpgem { namespace Output { ///\class VTKSpecificTimeWriter ///\brief writes steady state data or a single time level /// /// this produces multiple files, you do not have to append anything, just load /// the .pvtu into paraview VTK makes the assumption that all data is 3D data, /// this class will provide conversions where necessary, but not from 4D to 3D /// /// Implementation note: The output can in general be discontinuous at the /// element boundaries. To handle such a function requires a bit of special /// care. The VTK fileformat associates data values with cells (elements) or /// points. If we would store a single function value f(x) for a node at x, then /// the result is necessarily continuous. After all, independently from which /// element one approaches x, the value will be f(x). /// To represent discontinuous data we will therefore need to duplicate the node /// x to x_E1, x_E2, ... x_EN for the N attached elements. This way we can store /// multiple values f(x_E1), f(x_E2), ..., f(x_EN) and represent data that is /// discontinuous at the element boundaries. /// /// \tparam DIM The dimension of the mesh // class is final because the destructor would be the only virtual function template <std::size_t DIM> class VTKSpecificTimeWriter final { public: ///\brief write front matter and open file stream ///\param baseName name of the file WITHOUT extentions ///\param mesh the mesh containing the data you want to output /// if you want to write from multiple meshes, simply have paraview load /// both output files /// \param timelevel /// \param order The polynomial order of the solution VTKSpecificTimeWriter(const std::string& baseName, const Base::MeshManipulator<DIM>* mesh, std::size_t timelevel = 0, std::size_t order = 1); ///\brief write end matter and close the file stream ~VTKSpecificTimeWriter(); ///\brief write a scalar field void write( std::function<double( Base::Element*, const Geometry::PointReference<DIM>&, std::size_t)>, const std::string& name); ///\brief write a vector field void write( std::function<LinearAlgebra::SmallVector<DIM>( Base::Element*, const Geometry::PointReference<DIM>&, std::size_t)>, const std::string& name); ///\brief write an order 2 tensor field void write( std::function<LinearAlgebra::SmallMatrix<DIM, DIM>( Base::Element*, const Geometry::PointReference<DIM>&, std::size_t)>, const std::string& name); template <typename T> void writeMultiple( std::function<T(Base::Element*, const Geometry::PointReference<DIM>&, std::size_t)> extractor, std::map<std::string, std::function<double(T&)>> scalars, std::map<std::string, std::function<LinearAlgebra::SmallVector<DIM>(T&)>> vectors = {}, std::map<std::string, std::function<LinearAlgebra::SmallMatrix<DIM, DIM>(T&)>> tensors = {}); ///\brief do not copy the writer to prevent havoc when destructing all the /// copies VTKSpecificTimeWriter(const VTKSpecificTimeWriter& orig) = delete; VTKSpecificTimeWriter operator=(const VTKSpecificTimeWriter& orig) = delete; private: /** * Write the start of the master pvtu file, this will contain the * indirection to the data in the local vtu files. * @param baseName The base name for the file (actual file will have .pvtu * extension) */ void writeMasterFileHeader(const std::string& baseName); /** * Write the start of the processor local vtu file. * @param baseName The base name for the file (actual files will have .[proc * num].vtu extension) */ void writeLocalFileHeader(const std::string& baseName); /** * Write the data for a <DataArray> with binary data to the local file. * * This only writes the data content (including the length header) but does * not write the enclosing XML tags. The user should make sure that the type * of the data matches that of the one described in the <DataArray> tag. * * @tparam T The type of the data. */ template <class T> void writeBinaryDataArrayData(std::vector<T> data); /** * Write a vector to the output storage, adding zero padding as needed. * * @param in The input vector * @param offset The offset of the vector (i.e. the number of previous * vectors). * @param out The place to write to, should be of at least size 3*(offset+1) */ void writePaddedVector(LinearAlgebra::SmallVector<DIM> in, std::size_t offset, std::vector<double>& out); /** * Write a second order tensor to the output storage, adding padding as * needed. The padding will be in the form of the idenity tensor. * * @param in The input tensor * @param offset The offset of the tensor (i.e. the number of previously * written tensors) * @param out The place to write to, should be of at least size 9*(offset+1) */ void writePaddedTensor(LinearAlgebra::SmallMatrix<DIM, DIM> in, std::size_t offset, std::vector<double>& out); std::ofstream localFile_; std::ofstream masterFile_; /// Number of points in the local file std::uint32_t totalPoints_; /// Number of elements in the local file std::uint32_t totalElements_; const Base::MeshManipulator<DIM>* mesh_; std::size_t timelevel_; void setupMapping(std::size_t order); /** * The mapping from hpgem-reference geometry to the VTK elements */ std::unordered_map<Geometry::ReferenceGeometryType, std::shared_ptr<VTKElement<DIM>>> elementMapping_; }; } // namespace Output } // namespace hpgem #include "VTKSpecificTimeWriter_Impl.h" #endif // HPGEM_KERNEL_VTKSPECIFICTIMEWRITER_H
/* * QFaustPreferences.h * * Created by <NAME> on 12/05/09. * Copyright 2009 Grame. All rights reserved. * * GNU Lesser General Public License Usage * Alternatively, this file may be used under the terms of the GNU Lesser * General Public License version 2.1 as published by the Free Software * Foundation and appearing in the file LICENSE.LGPL included in the * packaging of this file. Please review the following information to * ensure the GNU Lesser General Public License version 2.1 requirements * will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. * * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef FaustPreferences_H #define FaustPreferences_H #include <QDialog> #include <QHash> #include <QVariant> namespace Ui { class FaustPreferences; } class FaustMainWindow; //------------------------------------------------------------------------------------------------------------------------ class QFaustPreferences : public QDialog { Q_OBJECT public: QFaustPreferences(FaustMainWindow * parent = 0); protected slots: void apply(); void cancel(); void reset(); void findFaustPath(); void addTarget(); void removeTarget(); void addOption(); protected: void updateWidgets(); void updateConfigurationWidgets( const QString& settingKey , const QString& widgetName , const QString& nameEditName , const QString& commandEditName , QWidget * parent ); void addConfigurationLine( const QString& targetName , const QString& targetCommand , const QString& widgetName , const QString& nameEditName , const QString& commandEditName , QWidget * parent ); void updateTabOrder(); void addTarget( const QString& targetName , const QString& targetCommand ); void addOption( const QString& optionName , const QString& optionCommand ); void applyConfiguration( const QString& settingKey , const QString& widgetName , const QString& nameEditName , const QString& commandEditName , QWidget * box ); FaustMainWindow* mMainWindow; static void saveSettings(); static void restoreSettings(); static QHash<QString,QVariant> mSavedSettings; private: Ui::FaustPreferences * mUI; }; #endif
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2018. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifndef UCT_IB_MLX5_DV_H_ #define UCT_IB_MLX5_DV_H_ #ifndef UCT_IB_MLX5_H_ # error "Never include <uct/ib/mlx5/ib_mlx5_dv.h> directly; use <uct/ib/mlx5/ib_mlx5.h> instead." #endif #include <ucs/type/status.h> #include <infiniband/verbs.h> typedef struct { struct mlx5dv_obj dv; #ifdef HAVE_IBV_EXP_DM struct { struct ibv_exp_dm *in; struct mlx5dv_dm *out; } dv_dm; #endif } uct_ib_mlx5dv_t; typedef struct { struct mlx5dv_qp dv; } uct_ib_mlx5dv_qp_t; typedef struct { struct mlx5dv_srq dv; } uct_ib_mlx5dv_srq_t; /* Completion queue */ typedef struct { struct mlx5dv_cq dv; } uct_ib_mlx5dv_cq_t; /** * Get internal verbs information. */ ucs_status_t uct_ib_mlx5dv_init_obj(uct_ib_mlx5dv_t *obj, uint64_t type); /** * Update CI to support req_notify_cq */ void uct_ib_mlx5_update_cq_ci(struct ibv_cq *cq, unsigned cq_ci); /** * Retrieve CI from the driver */ unsigned uct_ib_mlx5_get_cq_ci(struct ibv_cq *cq); /** * Get internal AV information. */ void uct_ib_mlx5_get_av(struct ibv_ah *ah, struct mlx5_wqe_av *av); /** * Backports for legacy bare-metal support */ struct ibv_qp *uct_dv_get_cmd_qp(struct ibv_srq *srq); void *uct_dv_get_info_uar0(void *uar); /* * DM backports */ #ifdef HAVE_IBV_EXP_DM # define ibv_dm ibv_exp_dm # define ibv_alloc_dm_attr ibv_exp_alloc_dm_attr # define ibv_alloc_dm ibv_exp_alloc_dm # define ibv_free_dm ibv_exp_free_dm struct mlx5dv_dm { void *buf; uint64_t length; uint64_t comp_mask; }; enum { MLX5DV_OBJ_DM = 1 << 4, }; static struct ibv_mr * UCS_F_MAYBE_UNUSED ibv_reg_dm_mr(struct ibv_pd *pd, struct ibv_dm *dm, uint64_t dm_offset, size_t length, unsigned int access_flags) { struct ibv_exp_reg_mr_in mr_in = {}; mr_in.pd = pd; mr_in.comp_mask = IBV_EXP_REG_MR_DM; mr_in.dm = dm; mr_in.length = length; return ibv_exp_reg_mr(&mr_in); } typedef struct uct_mlx5_dm_va { struct ibv_dm ibv_dm; size_t length; uint64_t *start_va; } uct_mlx5_dm_va_t; static ucs_status_t UCS_F_MAYBE_UNUSED uct_ib_mlx5_get_dm_info(struct ibv_exp_dm *dm, struct mlx5dv_dm *dm_info) { dm_info->buf = ((uct_mlx5_dm_va_t*)dm)->start_va; return UCS_OK; } # define UCT_IB_MLX5_DV_DM(_obj) _obj.dv_dm #else # define UCT_IB_MLX5_DV_DM(_obj) _obj.dv.dm #endif #endif
// generated from rosidl_generator_c/resource/idl.h.em // with input from rmf_charger_msgs:msg/ChargerRequest.idl // generated code does not contain a copyright notice #ifndef RMF_CHARGER_MSGS__MSG__CHARGER_REQUEST_H_ #define RMF_CHARGER_MSGS__MSG__CHARGER_REQUEST_H_ #include "rmf_charger_msgs/msg/detail/charger_request__struct.h" #include "rmf_charger_msgs/msg/detail/charger_request__functions.h" #include "rmf_charger_msgs/msg/detail/charger_request__type_support.h" #endif // RMF_CHARGER_MSGS__MSG__CHARGER_REQUEST_H_
<filename>include/Model.h // // Created by Link on 2022/1/30. // #ifndef NERENDERER_MODEL_H #define NERENDERER_MODEL_H #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <vector> //#include <Mesh.h> #include <Shader.h> #include <Object.h> //unsigned int TextureFromFile(const char* path, const std::string &directory, bool gamma = false); class Model { friend class Object; public: /* 函数 */ explicit Model(const std::string& path); void draw(Shader& shader); ~Model() { for (auto& iter : meshes) delete iter; // for (auto& iter : loadedTexture) delete iter; } private: /* 模型数据 */ void processNode(aiNode *node, const aiScene *scene); void loadMaterialTextures(aiMaterial *mat, aiTextureType type, std::vector<Texture*> &textures); Mesh* processMesh(aiMesh *mesh, const aiScene *scene); std::vector<Mesh*> meshes; std::string directory; std::vector<Texture*> loadedTexture; }; #endif //NERENDERER_MODEL_H
<filename>System/Library/Frameworks/UIKit.framework/_UIDatePickerMode_TimeInterval.h<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Wednesday, March 22, 2017 at 9:02:41 AM Mountain Standard Time * Operating System: Version 10.1 (Build 14U593) * Image Source: /System/Library/Frameworks/UIKit.framework/UIKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <UIKit/UIKit-Structs.h> #import <UIKit/_UIDatePickerMode.h> @interface _UIDatePickerMode_TimeInterval : _UIDatePickerMode { double _componentWidth; } +(long long)datePickerMode; +(unsigned long long)extractableCalendarUnits; -(double)rowHeight; -(id)font; -(BOOL)isTimeIntervalMode; -(void)takeExtremesFromMinimumDate:(id)arg1 maximumDate:(id)arg2 ; -(long long)hourForRow:(long long)arg1 ; -(BOOL)areValidDateComponents:(id)arg1 comparingUnits:(long long)arg2 ; -(id)dateComponentsByRestrictingSelectedComponents:(id)arg1 withLastManipulatedColumn:(long long)arg2 ; -(void)resetComponentWidths; -(double)widthForCalendarUnit:(unsigned long long)arg1 font:(id)arg2 maxWidth:(double)arg3 ; -(id)localizedFormatString; -(long long)numberOfRowsForCalendarUnit:(unsigned long long)arg1 ; -(unsigned long long)nextUnitSmallerThanUnit:(unsigned long long)arg1 ; -(unsigned long long)nextUnitLargerThanUnit:(unsigned long long)arg1 ; -(NSRange)rangeForCalendarUnit:(unsigned long long)arg1 ; -(long long)valueForDate:(id)arg1 dateComponents:(id)arg2 calendarUnit:(unsigned long long)arg3 ; -(long long)titleAlignmentForCalendarUnit:(unsigned long long)arg1 ; -(id)titleForRow:(long long)arg1 inComponent:(long long)arg2 ; -(BOOL)_shouldEnableValueForRow:(long long)arg1 inComponent:(long long)arg2 calendarUnit:(unsigned long long)arg3 ; @end
<gh_stars>100-1000 typedef struct { int typenode; char *str; int keycode; int lloc; char *sep; char *modificator; char *classname; } orafce_lexnode;
/* * common_component.h * * Created on: 11.05.2017 * Author: michaelboeckling */ #ifndef _INCLUDE_COMMON_COMPONENT_H_ #define _INCLUDE_COMMON_COMPONENT_H_ typedef enum { UNINITIALIZED, INITIALIZED, RUNNING, STOPPED } component_status_t; #endif /* _INCLUDE_COMMON_COMPONENT_H_ */
<filename>extsrc/mesa/src/gallium/auxiliary/postprocess/pp_mlaa.h<gh_stars>1000+ /** * Copyright (C) 2010 <NAME> (<EMAIL>) * Copyright (C) 2010 <NAME> (<EMAIL>) * Copyright (C) 2010 <NAME> (<EMAIL>) * Copyright (C) 2010 <NAME> (<EMAIL>) * Copyright (C) 2010 <NAME> (<EMAIL>) * Copyright (C) 2011 <NAME> (<EMAIL>) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the following statement: * * "Uses Jimenez's MLAA. Copyright (C) 2010 by <NAME>, <NAME>, * <NAME>, <NAME> and <NAME>." * * Only for use in the Mesa project, this point 2 is filled by naming the * technique Jimenez's MLAA in the Mesa config options. * * 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 COPYRIGHT HOLDERS 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the copyright holders. */ #ifndef PP_MLAA_H #define PP_MLAA_H #include "postprocess/pp_mlaa_areamap.h" static const char depth1fs[] = "FRAG\n" "PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1\n" "DCL IN[0], GENERIC[0], PERSPECTIVE\n" "DCL IN[1], GENERIC[10], PERSPECTIVE\n" "DCL IN[2], GENERIC[11], PERSPECTIVE\n" "DCL OUT[0], COLOR\n" "DCL SAMP[0]\n" "DCL TEMP[0..2]\n" "IMM FLT32 { 0.0030, 0.0000, 1.0000, 0.0000}\n" " 0: TEX TEMP[0].x, IN[1].xyyy, SAMP[0], 2D\n" " 1: MOV TEMP[1].x, TEMP[0].xxxx\n" " 2: TEX TEMP[0].x, IN[1].zwww, SAMP[0], 2D\n" " 3: MOV TEMP[1].y, TEMP[0].xxxx\n" " 4: TEX TEMP[0].x, IN[2].xyyy, SAMP[0], 2D\n" " 5: MOV TEMP[1].z, TEMP[0].xxxx\n" " 6: TEX TEMP[0].x, IN[2].zwww, SAMP[0], 2D\n" " 7: MOV TEMP[1].w, TEMP[0].xxxx\n" " 8: TEX TEMP[0].x, IN[0].xyyy, SAMP[0], 2D\n" " 9: ADD TEMP[2], TEMP[0].xxxx, -TEMP[1]\n" " 10: ABS TEMP[0], TEMP[2]\n" " 11: SGE TEMP[2], TEMP[0], IMM[0].xxxx\n" " 12: DP4 TEMP[0].x, TEMP[2], IMM[0].zzzz\n" " 13: SEQ TEMP[1].x, TEMP[0].xxxx, IMM[0].yyyy\n" " 14: IF TEMP[1].xxxx :16\n" " 15: KILP\n" " 16: ENDIF\n" " 17: MOV OUT[0], TEMP[2]\n" " 18: END\n"; static const char color1fs[] = "FRAG\n" "PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1\n" "DCL IN[0], GENERIC[0], PERSPECTIVE\n" "DCL IN[1], GENERIC[10], PERSPECTIVE\n" "DCL IN[2], GENERIC[11], PERSPECTIVE\n" "DCL OUT[0], COLOR\n" "DCL SAMP[0]\n" "DCL TEMP[0..2]\n" "IMM FLT32 { 0.2126, 0.7152, 0.0722, 0.1000}\n" "IMM FLT32 { 1.0000, 0.0000, 0.0000, 0.0000}\n" " 0: TEX TEMP[1].xyz, IN[1].xyyy, SAMP[0], 2D\n" " 1: DP3 TEMP[0].x, TEMP[1].xyzz, IMM[0]\n" " 2: TEX TEMP[1].xyz, IN[1].zwww, SAMP[0], 2D\n" " 3: DP3 TEMP[0].y, TEMP[1].xyzz, IMM[0].xyzz\n" " 4: TEX TEMP[1].xyz, IN[2].xyyy, SAMP[0], 2D\n" " 5: DP3 TEMP[0].z, TEMP[1].xyzz, IMM[0].xyzz\n" " 6: TEX TEMP[1].xyz, IN[2].zwww, SAMP[0], 2D\n" " 7: DP3 TEMP[0].w, TEMP[1].xyzz, IMM[0].xyzz\n" " 8: TEX TEMP[1].xyz, IN[0].xyyy, SAMP[0], 2D\n" " 9: DP3 TEMP[2].x, TEMP[1].xyzz, IMM[0].xyzz\n" " 10: ADD TEMP[1], TEMP[2].xxxx, -TEMP[0]\n" " 11: ABS TEMP[0], TEMP[1]\n" " 12: SGE TEMP[2], TEMP[0], IMM[0].wwww\n" " 13: DP4 TEMP[0].x, TEMP[2], IMM[1].xxxx\n" " 14: SEQ TEMP[1].x, TEMP[0].xxxx, IMM[1].yyyy\n" " 15: IF TEMP[1].xxxx :17\n" " 16: KILP\n" " 17: ENDIF\n" " 18: MOV OUT[0], TEMP[2]\n" " 19: END\n"; static const char neigh3fs[] = "FRAG\n" "PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1\n" "DCL IN[0], GENERIC[0], PERSPECTIVE\n" "DCL IN[1], GENERIC[10], PERSPECTIVE\n" "DCL IN[2], GENERIC[11], PERSPECTIVE\n" "DCL OUT[0], COLOR\n" "DCL SAMP[0]\n" "DCL SAMP[1]\n" "DCL TEMP[0..8]\n" "IMM FLT32 { 1.0000, 0.00001, 0.0000, 0.0000}\n" " 0: TEX TEMP[0], IN[0].xyyy, SAMP[1], 2D\n" " 1: MOV TEMP[1].x, TEMP[0].xxxx\n" " 2: TEX TEMP[2].y, IN[2].zwww, SAMP[1], 2D\n" " 3: MOV TEMP[1].y, TEMP[2].yyyy\n" " 4: MOV TEMP[1].z, TEMP[0].zzzz\n" " 5: TEX TEMP[1].w, IN[2].xyyy, SAMP[1], 2D\n" " 6: MUL TEMP[4], TEMP[1], TEMP[1]\n" " 7: MUL TEMP[5], TEMP[4], TEMP[1]\n" " 8: DP4 TEMP[1].x, TEMP[5], IMM[0].xxxx\n" " 9: SLT TEMP[4].x, TEMP[1].xxxx, IMM[0].yyyy\n" " 10: IF TEMP[4].xxxx :12\n" " 11: KILP\n" " 12: ENDIF\n" " 13: TEX TEMP[4], IN[0].xyyy, SAMP[0], 2D\n" " 14: TEX TEMP[6], IN[1].zwww, SAMP[0], 2D\n" " 15: ADD TEMP[7].x, IMM[0].xxxx, -TEMP[0].xxxx\n" " 16: MUL TEMP[8], TEMP[4], TEMP[7].xxxx\n" " 17: MAD TEMP[7], TEMP[6], TEMP[0].xxxx, TEMP[8]\n" " 18: MUL TEMP[6], TEMP[7], TEMP[5].xxxx\n" " 19: TEX TEMP[7], IN[2].zwww, SAMP[0], 2D\n" " 20: ADD TEMP[8].x, IMM[0].xxxx, -TEMP[2].yyyy\n" " 21: MUL TEMP[3], TEMP[4], TEMP[8].xxxx\n" " 22: MAD TEMP[8], TEMP[7], TEMP[2].yyyy, TEMP[3]\n" " 23: MAD TEMP[2], TEMP[8], TEMP[5].yyyy, TEMP[6]\n" " 24: TEX TEMP[6], IN[1].xyyy, SAMP[0], 2D\n" " 25: ADD TEMP[7].x, IMM[0].xxxx, -TEMP[0].zzzz\n" " 26: MUL TEMP[8], TEMP[4], TEMP[7].xxxx\n" " 27: MAD TEMP[7], TEMP[6], TEMP[0].zzzz, TEMP[8]\n" " 28: MAD TEMP[0], TEMP[7], TEMP[5].zzzz, TEMP[2]\n" " 29: TEX TEMP[2], IN[2].xyyy, SAMP[0], 2D\n" " 30: ADD TEMP[6].x, IMM[0].xxxx, -TEMP[1].wwww\n" " 31: MUL TEMP[7], TEMP[4], TEMP[6].xxxx\n" " 32: MAD TEMP[4], TEMP[2], TEMP[1].wwww, TEMP[7]\n" " 33: MAD TEMP[2], TEMP[4], TEMP[5].wwww, TEMP[0]\n" " 34: RCP TEMP[0].x, TEMP[1].xxxx\n" " 35: MUL OUT[0], TEMP[2], TEMP[0].xxxx\n" " 36: END\n"; static const char offsetvs[] = "VERT\n" "DCL IN[0]\n" "DCL IN[1]\n" "DCL OUT[0], POSITION\n" "DCL OUT[1], GENERIC[0]\n" "DCL OUT[2], GENERIC[10]\n" "DCL OUT[3], GENERIC[11]\n" "DCL CONST[0]\n" "IMM FLT32 { 1.0000, 0.0000, -1.0000, 0.0000}\n" " 0: MOV OUT[0], IN[0]\n" " 1: MOV OUT[1], IN[1]\n" " 2: MAD OUT[2], CONST[0].xyxy, IMM[0].zyyz, IN[1].xyxy\n" " 3: MAD OUT[3], CONST[0].xyxy, IMM[0].xyyx, IN[1].xyxy\n" " 4: END\n"; static const char blend2fs_1[] = "FRAG\n" "PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1\n" "DCL IN[0], GENERIC[0], PERSPECTIVE\n" "DCL OUT[0], COLOR\n" "DCL SAMP[0]\n" "DCL SAMP[1]\n" "DCL SAMP[2]\n" "DCL CONST[0]\n" "DCL TEMP[0..6]\n" "IMM FLT32 { 0.0000, -0.2500, 0.00609756, 0.5000}\n" "IMM FLT32 { -1.5000, -2.0000, 0.9000, 1.5000}\n" "IMM FLT32 { 2.0000, 1.0000, 4.0000, 33.0000}\n"; static const char blend2fs_2[] = " 0: MOV TEMP[0], IMM[0].xxxx\n" " 1: TEX TEMP[1], IN[0].xyyy, SAMP[1], 2D\n" " 2: MOV TEMP[2].x, TEMP[1]\n" " 3: SNE TEMP[3].x, TEMP[1].yyyy, IMM[0].xxxx\n" " 4: IF TEMP[3].xxxx :76\n" " 5: MOV TEMP[1].xy, IN[0].xyxx\n" " 6: MOV TEMP[4].x, IMM[1].xxxx\n" " 7: BGNLOOP :24\n" " 8: MUL TEMP[5].x, IMM[1].yyyy, IMM[3].xxxx\n" " 9: SLE TEMP[6].x, TEMP[4].xxxx, TEMP[5].xxxx\n" " 10: IF TEMP[6].xxxx :12\n" " 11: BRK\n" " 12: ENDIF\n" " 13: MOV TEMP[4].y, IMM[0].xxxx\n" " 14: MAD TEMP[3].xyz, CONST[0].xyyy, TEMP[4].xyyy, TEMP[1].xyyy\n" " 15: MOV TEMP[3].w, IMM[0].xxxx\n" " 16: TXL TEMP[5], TEMP[3], SAMP[2], 2D\n" " 17: MOV TEMP[3].x, TEMP[5].yyyy\n" " 18: SLT TEMP[6].x, TEMP[5].yyyy, IMM[1].zzzz\n" " 19: IF TEMP[6].xxxx :21\n" " 20: BRK\n" " 21: ENDIF\n" " 22: ADD TEMP[6].x, TEMP[4].xxxx, IMM[1].yyyy\n" " 23: MOV TEMP[4].x, TEMP[6].xxxx\n" " 24: ENDLOOP :7\n" " 25: ADD TEMP[1].x, TEMP[4].xxxx, IMM[1].wwww\n" " 26: MAD TEMP[6].x, -IMM[2].xxxx, TEMP[3].xxxx, TEMP[1].xxxx\n" " 27: MUL TEMP[1].x, IMM[1].yyyy, IMM[3].xxxx\n" " 28: MAX TEMP[4].x, TEMP[6].xxxx, TEMP[1].xxxx\n" " 29: MOV TEMP[1].x, TEMP[4].xxxx\n" " 30: MOV TEMP[3].xy, IN[0].xyxx\n" " 31: MOV TEMP[5].x, IMM[1].wwww\n" " 32: BGNLOOP :49\n" " 33: MUL TEMP[6].x, IMM[2].xxxx, IMM[3].xxxx\n" " 34: SGE TEMP[4].x, TEMP[5].xxxx, TEMP[6].xxxx\n" " 35: IF TEMP[4].xxxx :37\n" " 36: BRK\n" " 37: ENDIF\n" " 38: MOV TEMP[5].y, IMM[0].xxxx\n" " 39: MAD TEMP[4].xyz, CONST[0].xyyy, TEMP[5].xyyy, TEMP[3].xyyy\n" " 40: MOV TEMP[4].w, IMM[0].xxxx\n" " 41: TXL TEMP[6].xy, TEMP[4], SAMP[2], 2D\n" " 42: MOV TEMP[4].x, TEMP[6].yyyy\n" " 43: SLT TEMP[0].x, TEMP[6].yyyy, IMM[1].zzzz\n" " 44: IF TEMP[0].xxxx :46\n" " 45: BRK\n" " 46: ENDIF\n" " 47: ADD TEMP[6].x, TEMP[5].xxxx, IMM[2].xxxx\n" " 48: MOV TEMP[5].x, TEMP[6].xxxx\n" " 49: ENDLOOP :32\n" " 50: ADD TEMP[3].x, TEMP[5].xxxx, IMM[1].xxxx\n" " 51: MAD TEMP[5].x, IMM[2].xxxx, TEMP[4].xxxx, TEMP[3].xxxx\n" " 52: MUL TEMP[3].x, IMM[2].xxxx, IMM[3].xxxx\n" " 53: MIN TEMP[4].x, TEMP[5].xxxx, TEMP[3].xxxx\n" " 54: MOV TEMP[3].x, TEMP[1].xxxx\n" " 55: MOV TEMP[3].y, TEMP[4].xxxx\n" " 56: MOV TEMP[5].yw, IMM[0].yyyy\n" " 57: MOV TEMP[5].x, TEMP[1].xxxx\n" " 58: ADD TEMP[1].x, TEMP[4].xxxx, IMM[2].yyyy\n" " 59: MOV TEMP[5].z, TEMP[1].xxxx\n" " 60: MAD TEMP[1], TEMP[5], CONST[0].xyxy, IN[0].xyxy\n" " 61: MOV TEMP[4], TEMP[1].xyyy\n" " 62: MOV TEMP[4].w, IMM[0].xxxx\n" " 63: TXL TEMP[5].x, TEMP[4], SAMP[2], 2D\n" " 64: MOV TEMP[4].x, TEMP[5].xxxx\n" " 65: MOV TEMP[5], TEMP[1].zwww\n" " 66: MOV TEMP[5].w, IMM[0].xxxx\n" " 67: TXL TEMP[1].x, TEMP[5], SAMP[2], 2D\n" " 68: MOV TEMP[4].y, TEMP[1].xxxx\n" " 69: MUL TEMP[5].xy, IMM[2].zzzz, TEMP[4].xyyy\n" " 70: ROUND TEMP[1].xy, TEMP[5].xyyy\n" " 71: ABS TEMP[4].xy, TEMP[3].xyyy\n" " 72: MAD TEMP[3].xy, IMM[2].wwww, TEMP[1].xyyy, TEMP[4].xyyy\n" " 73: MUL TEMP[5].xyz, TEMP[3].xyyy, IMM[0].zzzz\n" " 74: MOV TEMP[5].w, IMM[0].xxxx\n" " 75: TXL TEMP[0].xy, TEMP[5], SAMP[0], 2D\n" " 76: ENDIF\n" " 77: SNE TEMP[1].x, TEMP[2].xxxx, IMM[0].xxxx\n" " 78: IF TEMP[1].xxxx :151\n" " 79: MOV TEMP[1].xy, IN[0].xyxx\n" " 80: MOV TEMP[3].x, IMM[1].xxxx\n" " 81: BGNLOOP :98\n" " 82: MUL TEMP[4].x, IMM[1].yyyy, IMM[3].xxxx\n" " 83: SLE TEMP[5].x, TEMP[3].xxxx, TEMP[4].xxxx\n" " 84: IF TEMP[5].xxxx :86\n" " 85: BRK\n" " 86: ENDIF\n" " 87: MOV TEMP[3].y, IMM[0].xxxx\n" " 88: MAD TEMP[5].xyz, CONST[0].xyyy, TEMP[3].yxxx, TEMP[1].xyyy\n" " 89: MOV TEMP[5].w, IMM[0].xxxx\n" " 90: TXL TEMP[4], TEMP[5], SAMP[2], 2D\n" " 91: MOV TEMP[2].x, TEMP[4].xxxx\n" " 92: SLT TEMP[5].x, TEMP[4].xxxx, IMM[1].zzzz\n" " 93: IF TEMP[5].xxxx :95\n" " 94: BRK\n" " 95: ENDIF\n" " 96: ADD TEMP[4].x, TEMP[3].xxxx, IMM[1].yyyy\n" " 97: MOV TEMP[3].x, TEMP[4].xxxx\n" " 98: ENDLOOP :81\n" " 99: ADD TEMP[1].x, TEMP[3].xxxx, IMM[1].wwww\n" "100: MAD TEMP[6].x, -IMM[2].xxxx, TEMP[2].xxxx, TEMP[1].xxxx\n" "101: MUL TEMP[1].x, IMM[1].yyyy, IMM[3].xxxx\n" "102: MAX TEMP[3].x, TEMP[6].xxxx, TEMP[1].xxxx\n" "103: MOV TEMP[1].x, TEMP[3].xxxx\n" "104: MOV TEMP[2].xy, IN[0].xyxx\n" "105: MOV TEMP[4].x, IMM[1].wwww\n" "106: BGNLOOP :123\n" "107: MUL TEMP[5].x, IMM[2].xxxx, IMM[3].xxxx\n" "108: SGE TEMP[6].x, TEMP[4].xxxx, TEMP[5].xxxx\n" "109: IF TEMP[6].xxxx :111\n" "110: BRK\n" "111: ENDIF\n" "112: MOV TEMP[4].y, IMM[0].xxxx\n" "113: MAD TEMP[5].xyz, CONST[0].xyyy, TEMP[4].yxxx, TEMP[2].xyyy\n" "114: MOV TEMP[5].w, IMM[0].xxxx\n" "115: TXL TEMP[6], TEMP[5], SAMP[2], 2D\n" "116: MOV TEMP[3].x, TEMP[6].xxxx\n" "117: SLT TEMP[5].x, TEMP[6].xxxx, IMM[1].zzzz\n" "118: IF TEMP[5].xxxx :120\n" "119: BRK\n" "120: ENDIF\n" "121: ADD TEMP[6].x, TEMP[4].xxxx, IMM[2].xxxx\n" "122: MOV TEMP[4].x, TEMP[6].xxxx\n" "123: ENDLOOP :106\n" "124: ADD TEMP[2].x, TEMP[4].xxxx, IMM[1].xxxx\n" "125: MAD TEMP[4].x, IMM[2].xxxx, TEMP[3].xxxx, TEMP[2].xxxx\n" "126: MUL TEMP[2].x, IMM[2].xxxx, IMM[3].xxxx\n" "127: MIN TEMP[3].x, TEMP[4].xxxx, TEMP[2].xxxx\n" "128: MOV TEMP[2].x, TEMP[1].xxxx\n" "129: MOV TEMP[2].y, TEMP[3].xxxx\n" "130: MOV TEMP[4].xz, IMM[0].yyyy\n" "131: MOV TEMP[4].y, TEMP[1].xxxx\n" "132: ADD TEMP[1].x, TEMP[3].xxxx, IMM[2].yyyy\n" "133: MOV TEMP[4].w, TEMP[1].xxxx\n" "134: MAD TEMP[1], TEMP[4], CONST[0].xyxy, IN[0].xyxy\n" "135: MOV TEMP[3], TEMP[1].xyyy\n" "136: MOV TEMP[3].w, IMM[0].xxxx\n" "137: TXL TEMP[4].y, TEMP[3], SAMP[2], 2D\n" "138: MOV TEMP[3].x, TEMP[4].yyyy\n" "139: MOV TEMP[4], TEMP[1].zwww\n" "140: MOV TEMP[4].w, IMM[0].xxxx\n" "141: TXL TEMP[1].y, TEMP[4], SAMP[2], 2D\n" "142: MOV TEMP[3].y, TEMP[1].yyyy\n" "143: MUL TEMP[4].xy, IMM[2].zzzz, TEMP[3].xyyy\n" "144: ROUND TEMP[1].xy, TEMP[4].xyyy\n" "145: ABS TEMP[3].xy, TEMP[2].xyyy\n" "146: MAD TEMP[2].xy, IMM[2].wwww, TEMP[1].xyyy, TEMP[3].xyyy\n" "147: MUL TEMP[3].xyz, TEMP[2].xyyy, IMM[0].zzzz\n" "148: MOV TEMP[3].w, IMM[0].xxxx\n" "149: TXL TEMP[1].xy, TEMP[3], SAMP[0], 2D\n" "150: MOV TEMP[0].zw, TEMP[1].yyxy\n" "151: ENDIF\n" "152: MOV OUT[0], TEMP[0]\n" "153: END\n"; #endif
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // XSDK // Copyright (c) 2015 <NAME> // // Use, modification, and distribution is subject to the Boost Software License, // Version 1.0 (See accompanying file LICENSE). // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #ifndef _Webby_ServerSideResponse_h #define _Webby_ServerSideResponse_h #include "XSDK/XStreamIO.h" #include "XSDK/XBaseObject.h" #include "XSDK/XHash.h" #include "XSDK/XString.h" #include "XSDK/XMemory.h" #include <list> namespace WEBBY { class ServerSideResponse : public XSDK::XBaseObject { public: enum StatusCode { SC_100_Continue = 100, SC_101_Switching_Protocols = 101, SC_200_OK = 200, SC_201_Created = 201, SC_202_Accepted = 202, SC_204_No_Content = 204, SC_400_Bad_Request = 400, SC_401_Unauthorized = 401, SC_403_Forbidden = 403, SC_404_Not_Found = 404, SC_406_Not_Acceptable = 406, SC_412_Precondition_Failed = 412, SC_415_Unsupported_Media_Type = 415, SC_418_Im_A_Teapot = 418, SC_453_Not_Enough_Bandwidth = 453, SC_454_Session_Not_Found = 454, SC_500_Internal_Server_Error = 500, SC_501_Not_Implemented = 501 }; X_API ServerSideResponse(StatusCode status = SC_200_OK, const XSDK::XString& contentType = "text/plain"); X_API ServerSideResponse(const ServerSideResponse& obj); X_API virtual ~ServerSideResponse() throw(); X_API ServerSideResponse& operator=(const ServerSideResponse& obj); X_API void SetStatusCode(StatusCode status); X_API StatusCode GetStatusCode(); // // Possible Content-Type: values... // "text/plain" // "image/jpeg" // "application/xhtml+xml" // "application/x-rtsp-tunnelled" // "multipart/mixed; boundary="foo" X_API void SetContentType(const XSDK::XString& contentType); X_API XSDK::XString GetContentType(); X_API void SetBody(const XSDK::XString& body); X_API void SetBody(XIRef<XSDK::XMemory> body); X_API XSDK::XString GetBodyAsString(); X_API XIRef<XSDK::XMemory> GetBody(); X_API void ClearAdditionalHeaders(); X_API void AddAdditionalHeader(const XSDK::XString& headerName, const XSDK::XString& headerValue); X_API XSDK::XString GetAdditionalHeader(const XSDK::XString& headerName); X_API bool WriteResponse(XRef<XSDK::XStreamIO> socket); // Chunked transfer encoding support... X_API bool WriteChunk(XRef<XSDK::XStreamIO> socket, XIRef<XSDK::XMemory> chunk); X_API bool WriteChunkFinalizer(XRef<XSDK::XStreamIO> socket); // Multipart mimetype support // WritePart() will automaticaly add a Content-Length header per // part. X_API bool WritePart( XRef<XSDK::XStreamIO> socket, const XSDK::XString& boundary, const XSDK::XHash<XSDK::XString>& partHeaders, XIRef<XSDK::XMemory> chunk ); X_API bool WritePart( XRef<XSDK::XStreamIO> socket, const XSDK::XString& boundary, const XSDK::XHash<XSDK::XString>& partHeaders, void* chunk, uint32_t size ); X_API bool WritePartFinalizer(const XSDK::XString& boundary, XRef<XSDK::XStreamIO> socket); private: XSDK::XString _GetStatusMessage(StatusCode sc); bool _WriteHeader(XRef<XSDK::XStreamIO> socket); bool _SendString(XRef<XSDK::XStreamIO> socket, const XSDK::XString& line); bool _SendData(XRef<XSDK::XStreamIO> socket, const void* data, size_t dataLen); StatusCode _status; XSDK::XString _contentType; XIRef<XSDK::XMemory> _body; bool _headerWritten; XSDK::XHash<XSDK::XString> _additionalHeaders; }; } #endif
#ifndef PIPELINE_H #define PIPELINE_H #include "Camera.h" #include <opencv2/opencv.hpp> #include <QTimer> #include <QList> class FrameHandler; /** * A pipeline contains multiple FramHanders * A frame will be processed by the FrameHandlers in the order they are added to the pipeline */ class PipeLine: public QObject { Q_OBJECT public: void openCamera(const Camera& camera); void addHandler(FrameHandler* handler); void start(int fps = 10); void stop(); cv::Size getFrameSize(); Camera getCamera() const; private slots: void onTimer(); private: cv::VideoCapture _input; QList<FrameHandler*> _handlers; QTimer _timer; cv::Mat _frame; cv::Mat _prevFrame; Camera _camera; }; #endif
#pragma once #include <catboost/private/libs/text_features/bow.h> #include <catboost/private/libs/text_features/bm25.h> #include <catboost/private/libs/text_features/feature_calcer.h> #include <catboost/private/libs/text_features/naive_bayesian.h> #include <catboost/private/libs/text_features/text_processing_collection.h> #include <catboost/private/libs/text_processing/tokenizer.h> #include <catboost/private/libs/text_processing/dictionary.h> #include <catboost/private/libs/text_processing/ut/lib/text_processing_data.h> #include <util/generic/fwd.h> #include <util/generic/ptr.h> #include <util/system/types.h> namespace NCBTest { TIntrusivePtr<NCB::TMultinomialNaiveBayes> CreateBayes( const TTokenizedTextFeature& features, TConstArrayRef<ui32> target, ui32 numClasses ); TIntrusivePtr<NCB::TBM25> CreateBm25( const TTokenizedTextFeature& features, TConstArrayRef<ui32> target, ui32 numClasses ); TIntrusivePtr<NCB::TBagOfWordsCalcer> CreateBoW(const NCB::TDictionaryPtr& dictionaryPtr); void CreateTextDataForTest( TVector<TTextFeature>* features, TVector<TTokenizedTextFeature>* tokenizedFeatures, TVector<NCB::TDigitizer>* digitizers, TVector<NCB::TTextFeatureCalcerPtr>* calcers, TVector<TVector<ui32>>* perFeatureDigitizers, TVector<TVector<ui32>>* perTokenizedFeatureCalcers ); TIntrusivePtr<NCB::TTextProcessingCollection> CreateTextProcessingCollectionForTest(); }
<reponame>LwRuan/RainEngine #pragma once #include <vulkan/vulkan.h> #include <vector> #include "buffer/buffer.h" #include "camera/camera.h" #include "device/device.h" #include "mathtype.h" #include "scene/scene.h" #include "surface/swapchain.h" #include "tetmesh.h" namespace Rain { struct GlobalUniformData { alignas(16) Mat4f proj_view; // camera alignas(16) Vec3f ambient; alignas(16) Vec3f directional; alignas(16) Vec3f light_direction; }; struct ModelUniformData { // ambient + non-transparency alignas(16) Vec4f Ka_d_ = Vec4f(0.2f, 0.2f, 0.2f, 1.0f); // diffuse alignas(16) Vec4f Kd_ = Vec4f(0.8f, 0.8f, 0.8f, 0.0f); // specular rgb + shininess alignas(16) Vec4f Ks_Ns_ = Vec4f(1.0f, 1.0f, 1.0f, 0.0f); // model transformation alignas(16) Mat4f model_ = Mat4f::Identity(); }; class RenderModel { // TODO: not optimal, use vma to alloc a big buffer, then divide to models public: Object* obj_; ModelUniformData uniform_data_; std::vector<Buffer> vertex_buffers_; Buffer index_buffer_; std::vector<VkBuffer> vertex_vkbuffers_; std::vector<VkDeviceSize> vertex_vkbuffer_offsets_; uint32_t ubo_offset_; uint32_t ubo_size_; void Init(Object* obj); VkResult CreateBuffers(Device* device); void Destroy(VkDevice device); static std::vector<VkVertexInputBindingDescription> GetBindDescription(); static std::vector<VkVertexInputAttributeDescription> GetAttributeDescriptions(); }; class RenderScene { public: Camera* camera_ = nullptr; Vec3f ambient_light_= Vec3f(0.5f, 0.5f, 0.5f); Vec3f directional_light_ = Vec3f(1.0f, 1.0f, 1.0f); Vec3f light_direction_; float light_x_angle_ = 45.0; float light_y_angle_ = 45.0; std::vector<Buffer> global_ubs_; // per swap image std::vector<Buffer> model_ubs_; // per swap image std::vector<RenderModel> models_; uint32_t n_swap_image_; uint8_t* model_ubo_data_ = nullptr; uint32_t model_ubo_size_; uint32_t n_uniform_buffer_ = 2; // TODO: now only global uint32_t n_uniform_texture_ = 0; VkDescriptorSetLayout layout_ = VK_NULL_HANDLE; VkDescriptorPool pool_ = VK_NULL_HANDLE; std::vector<VkDescriptorSet> sets_; VkResult Init(Device* device, SwapChain* swap_chain, Scene* scene); VkResult InitUniform(Device* device, SwapChain* swap_chain); VkResult InitDescriptor(Device* device); void UpdateUniform(VkDevice device, uint32_t image_index); void BindAndDraw(VkCommandBuffer command_buffer, VkPipelineLayout layout, uint32_t image_index, uint32_t model_index); void DestroyUniform(VkDevice device); void Destroy(VkDevice device); }; }; // namespace Rain
#include <common/linkedlist.h> #include <memory/memory.h> int iterator_linked_list_next(iterator(linked_list)* this) { if(this->current==this->list->tail) { return 0; } this->current = this->current->next; return 1; } int iterator_linked_list_prev(iterator(linked_list)* this) { if(this->current==this->list->head.next) { return 0; } this->current = this->current->prev; return 1; } void iterator_linked_list_remove(iterator(linked_list)* this) { //首先,判断我们是不是在头结点。 if(this->current!=&(this->list->head)) { //如果当前不是尾部的话,修改一下下一个结点的信息。 if(this->current!=(this->list->tail)) { this->current->next->prev = this->current->prev; } //如果是尾部的话,修改tail的记录信息。 else { this->list->tail = this->current->prev; } this->current->prev->next = this->current->next; //向前一位。 this->current = this->current->prev; } else { return; } } void insert_existing_node(linked_list* list,linked_list_node* node,int pos) { //如果位置<0,那么直接在尾部插入。 if(pos<0) { node->next = nullptr; node->prev = list->tail; list->tail->next = node; list->tail = node; return; } //如果位置>0,则找到位置后插入。 int i=0; linked_list_node* p = &(list->head); while(i<pos&&p!=list->tail) { i++; p = p->next; } //在其后方插入。 node->next = p->next; node->prev = p; p->next = node; //如果本身p就是tail的话,将tail后移。 if(list->tail==p) { list->tail = list->tail->next; } return; } void insert_existing_node_before_existing(linked_list* list,linked_list_node* node,linked_list_node* existing) { //插入。 node->prev = existing->prev; node->next = existing; if(existing != &(list->head)) { existing->prev->next = node; existing->prev = node; } } void remove_node_pos(linked_list* list,int pos) { int i=0; linked_list_node* p = list->head.next; while(i<pos&&p!=list->tail) { i++; p = p->next; } remove_node(list,p); } void remove_node(linked_list* list,linked_list_node* node) { if(list->tail == node) { node->prev->next = nullptr; list->tail = node->prev; } else { node->next->prev = node->prev; node->prev->next = node->next; } } void insert_existing_inline_node(inline_linked_list* list,inline_linked_list_node* node,int pos) { //如果位置<0,那么直接在尾部插入。 if(pos<0) { node->next = nullptr; node->prev = list->tail; list->tail->next = node; list->tail = node; return; } //如果位置>0,则找到位置后插入。 int i=0; inline_linked_list_node* p = &(list->head); while(i<pos&&p!=list->tail) { i++; p = p->next; } //在其后方插入。 node->next = p->next; node->prev = p; p->next = node; //如果本身p就是tail的话,将tail后移。 if(list->tail==p) { list->tail = list->tail->next; } return; } void insert_existing_inline_node_before_existing(inline_linked_list* list,inline_linked_list_node* node,inline_linked_list_node* existing) { //插入。 node->prev = existing->prev; node->next = existing; if(existing != &(list->head)) { existing->prev->next = node; existing->prev = node; } } void remove_inline_node_pos(inline_linked_list* list,int pos) { int i=0; inline_linked_list_node* p = list->head.next; while(i<pos&&p!=list->tail) { i++; p = p->next; } remove_inline_node(list,p); } void remove_inline_node(inline_linked_list* list,inline_linked_list_node* node) { if(list->tail == node) { node->prev->next = nullptr; list->tail = node->prev; } else { node->next->prev = node->prev; node->prev->next = node->next; } } int iterator_inline_linked_list_next(iterator(inline_linked_list)* this) { if(this->current==this->list->tail) { return 0; } this->current = this->current->next; return 1; } int iterator_inline_linked_list_prev(iterator(inline_linked_list)* this) { if(this->current==this->list->head.next) { return 0; } this->current = this->current->prev; return 1; } void iterator_inline_linked_list_remove(iterator(inline_linked_list)* this) { //首先,判断我们是不是在头结点。 if(this->current!=&(this->list->head)) { //如果当前不是尾部的话,修改一下下一个结点的信息。 if(this->current!=(this->list->tail)) { this->current->next->prev = this->current->prev; } //如果是尾部的话,修改tail的记录信息。 else { this->list->tail = this->current->prev; } this->current->prev->next = this->current->next; //向前一位。 this->current = this->current->prev; } else { return; } } void init_iterator_inline_linked_list(iterator(inline_linked_list)* iterator, inline_linked_list* source) { iterator->list = source; iterator->current = &(source->head); iterator->next = iterator_inline_linked_list_next; iterator->prev = iterator_inline_linked_list_prev; iterator->remove = iterator_inline_linked_list_remove; } void init_iterator_linked_list(iterator(linked_list)* iterator, linked_list* source) { iterator->list = source; iterator->current = &(source->head); iterator->next = iterator_linked_list_next; iterator->prev = iterator_linked_list_prev; iterator->remove = iterator_linked_list_remove; }
/* * Copyright (c) 2018-2021 <NAME> <<EMAIL>> * * tll is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #ifndef _PROCESSOR_CONTEXT_H #define _PROCESSOR_CONTEXT_H #include "tll/channel/base.h" #include "tll/channel/impl.h" #include "tll/channel/logic.h" #include "tll/processor.h" #include "tll/processor/loop.h" #include "tll/logger.h" #include "processor/deps.h" #include "processor/worker.h" #include <list> #include <map> #include <set> namespace tll::processor::_ { struct Processor : public tll::channel::Base<Processor> { static constexpr auto open_policy() { return OpenPolicy::Manual; } static constexpr auto close_policy() { return ClosePolicy::Long; } static constexpr auto process_policy() { return ProcessPolicy::Never; } static constexpr auto child_policy() { return ChildPolicy::Single; } // Set Proxy cap to access IPC child channel static constexpr std::string_view channel_protocol() { return "processor"; } struct PreObject { tll::Channel::Url url; tll::Config config; std::string name; bool disabled = false; struct depends_t { std::set<std::string> list; int depth = -1; } depends_open, depends_init; depends_t & depends(bool init) { if (init) return depends_init; else return depends_open; } }; tll::processor::Loop loop; tll::Config _cfg; std::list<Object> _objects; std::multimap<tll::time_point, Object *> _pending; tll_channel_t context_channel = {}; tll_channel_internal_t context_internal = { TLL_STATE_CLOSED }; std::list<std::unique_ptr<tll::Channel>> _workers_ptr; std::map<std::string, tll::processor::_::Worker *, std::less<>> _workers; std::unique_ptr<tll::Channel> _ipc; std::unique_ptr<tll::Channel> _timer; ~Processor() { _free(); } std::optional<tll::Channel::Url> parse_common(std::string_view type, std::string_view path, const Config &cfg); int parse_deps(Object &obj, const Config &cfg); int init_one(const PreObject &obj); int init_depends(); std::optional<PreObject> init_pre(std::string_view name, Config &cfg); int object_depth(std::map<std::string, PreObject, std::less<>> &map, PreObject &o, std::list<std::string_view> & path, bool init); Worker * init_worker(std::string_view name); void decay(Object * obj, bool root = false); void activate(Object & obj); int build_rdepends(); int _init(const tll::Channel::Url &, tll::Channel *); int _open(const tll::PropsView &); int _close(bool force); void _close_workers(); void _free(); void activate(); void update(const Channel *, tll_state_t state); Object * find(const Channel *c) { for (auto & i : _objects) { if (i.get() == c) return &i; } return nullptr; } Object * find(std::string_view name) { for (auto & i : _objects) { if (i->name() == name) return &i; } return nullptr; } friend struct tll::CallbackT<Processor>; int cb(const Channel * c, const tll_msg_t * msg); using tll::channel::Base<Processor>::post; template <typename T> int post(tll_addr_t addr, T body); template <typename T> int post(const Object *o, T body) { return post<T>(o->worker->proc.addr, body); } bool pending_has(const tll::time_point &ts, const Object * o) { auto it = _pending.find(ts); if (it == _pending.end()) return false; for (; it->first == ts; it++) { if (it->second == o) return true; } return false; } void pending_add(tll::time_point ts, Object * o); void pending_del(const tll::time_point &ts, const Object * o); int pending_rearm(const tll::time_point &ts); static int pending_process(const tll_channel_t * c, const tll_msg_t * msg, void * user) { if (msg->type != TLL_MESSAGE_DATA) return 0; return static_cast<Processor *>(user)->pending_process(msg); } int pending_process(const tll_msg_t * msg); }; } // namespace tll::processor #endif//_PROCESSOR_CONTEXT_H
#ifndef __JSON_H_ #define __JSON_H_ #include <map> #include "NacosString.h" #include "src/naming/beat/BeatInfo.h" #include "naming/ServiceInfo.h" #include "src/rapidjson/document.h" #include "src/rapidjson/writer.h" #include "src/rapidjson/stringbuffer.h" #include "naming/Instance.h" #include "src/server/NacosServerInfo.h" #include "naming/ListView.h" #include "naming/ServiceInfo2.h" #include "src/security/SecurityManager.h" /** * JSON * * @author <NAME> * Adapter from nacos-sdk-cpp to a json parser */ namespace nacos{ class JSON { public: static NacosString toJSONString(BeatInfo &beatInfo); static NacosString toJSONString(const std::map <NacosString, NacosString> &mapinfo); static void Map2JSONObject(rapidjson::Document &d, rapidjson::Value &jsonOb, std::map <NacosString, NacosString> &mapinfo); static void JSONObject2Map(std::map <NacosString, NacosString> &mapinfo, const rapidjson::Value &jsonOb); static long getLong(const NacosString &jsonString, const NacosString &fieldname); static ServiceInfo JsonStr2ServiceInfo(const NacosString &jsonString) throw(NacosException); static Instance Json2Instance(const rapidjson::Value &jsonString) throw(NacosException); static Instance Json2Instance(const NacosString &jsonString) throw(NacosException); static void markRequired(const rapidjson::Document &d, const NacosString &requiredField) throw(NacosException); static void markRequired(const rapidjson::Value &d, const NacosString &requiredField) throw(NacosException); static std::list<NacosServerInfo> Json2NacosServerInfo(const NacosString &nacosString) throw(NacosException); static ServiceInfo2 Json2ServiceInfo2(const NacosString &nacosString) throw(NacosException); static ListView<NacosString> Json2ServiceList(const NacosString &nacosString) throw(NacosException); static AccessToken Json2AccessToken(const NacosString &nacosString) throw(NacosException); }; }//namespace nacos #endif
#ifndef _FS_FONT_TTF_DATA_MGR_H_ #define _FS_FONT_TTF_DATA_MGR_H_ #include "mgr/FsResourceMgr.h" NS_FS_BEGIN class FontTTF; class FontTTFMgr:public ResourceMgr { public: static FontTTFMgr* create(); public: FontTTF* loadFontTTF(const char* name); public: virtual const char* className(); protected: FontTTFMgr(); virtual ~FontTTFMgr(); }; NS_FS_END #endif /*_FS_FONT_TTF_DATA_MGR_H_*/
<reponame>X-EcutiOnner/Notepad3<gh_stars>10-100 // Scintilla source code edit control /** @file CharacterType.h ** Tests for character type and case-insensitive comparisons. **/ // Copyright 2007 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef CHARACTERTYPE_H #define CHARACTERTYPE_H namespace Scintilla::Internal { // Functions for classifying characters /** * Check if a character is a space. * This is ASCII specific but is safe with chars >= 0x80. */ constexpr bool IsASpace(int ch) noexcept { return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d)); } constexpr bool IsSpaceOrTab(int ch) noexcept { return (ch == ' ') || (ch == '\t'); } constexpr bool IsControl(int ch) noexcept { return ((ch >= 0) && (ch <= 0x1F)) || (ch == 0x7F); } constexpr bool IsEOLCharacter(int ch) noexcept { return ch == '\r' || ch == '\n'; } constexpr bool IsBreakSpace(int ch) noexcept { // used for text breaking, treat C0 control character as space. // by default C0 control character is handled as special representation, // so not appears in normal text. 0x7F DEL is omitted to simplify the code. return ch >= 0 && ch <= ' '; } constexpr bool IsADigit(int ch) noexcept { return (ch >= '0') && (ch <= '9'); } constexpr bool IsADigit(int ch, int base) noexcept { if (base <= 10) { return (ch >= '0') && (ch < '0' + base); } else { return ((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch < 'A' + base - 10)) || ((ch >= 'a') && (ch < 'a' + base - 10)); } } constexpr bool IsASCII(int ch) noexcept { return (ch >= 0) && (ch < 0x80); } constexpr bool IsLowerCase(int ch) noexcept { return (ch >= 'a') && (ch <= 'z'); } constexpr bool IsUpperCase(int ch) noexcept { return (ch >= 'A') && (ch <= 'Z'); } constexpr bool IsUpperOrLowerCase(int ch) noexcept { return IsUpperCase(ch) || IsLowerCase(ch); } constexpr bool IsAlphaNumeric(int ch) noexcept { return ((ch >= '0') && (ch <= '9')) || ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')); } constexpr bool IsPunctuation(int ch) noexcept { switch (ch) { case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case '[': case '\\': case ']': case '^': case '_': case '`': case '{': case '|': case '}': case '~': return true; default: return false; } } // Simple case functions for ASCII supersets. template <typename T> constexpr T MakeUpperCase(T ch) noexcept { if (ch < 'a' || ch > 'z') return ch; else return ch - 'a' + 'A'; } template <typename T> constexpr T MakeLowerCase(T ch) noexcept { if (ch < 'A' || ch > 'Z') return ch; else return ch - 'A' + 'a'; } int CompareCaseInsensitive(const char *a, const char *b) noexcept; int CompareNCaseInsensitive(const char *a, const char *b, size_t len) noexcept; } #endif
/* ================================================================================ * Copyright: (C) 2021, SIRRL Social and Intelligent Robotics Research Laboratory, * University of Waterloo, All rights reserved. * * Authors: * <NAME> <<EMAIL>> * * CopyPolicy: Released under the terms of the BSD 3-Clause License. * See the accompanying LICENSE file for details. * ================================================================================ */ #ifndef HRI_PHYSIO_PROCESSING_BIQUADRATIC_H #define HRI_PHYSIO_PROCESSING_BIQUADRATIC_H #include <cmath> #include <memory> #include <HriPhysio/helpers.h> namespace hriPhysio { namespace Processing { class Biquadratic; } } class hriPhysio::Processing::Biquadratic { protected: /* ============================================================================ ** Variables received from the constructor. ** ============================================================================ */ unsigned int sampling_rate; double band_width; double center_frequency; /* ============================================================================ ** Filter Coefficients. ** ============================================================================ */ double a0, a1, a2, b1, b2; public: /* ============================================================================ ** Main Constructor. ** ** @param rate Sampling-rate of the provided signal. ** @param width Width for the band pass/notch. [Optional arg] ** ============================================================================ */ Biquadratic(const unsigned int rate, const double width=0.0); /* ============================================================================ ** Filter the provided data by bilinear transformation. ** Note: if provided a different freq, coefficients are recalculated. ** ** @param source Array of data to be filtered. ** @param target Array of where the filtered data should go. ** @param numSamples The number of samples in the input array. ** @param freq The center frequency to filter at. ** ============================================================================ */ void filter(const double* source, double* target, const std::size_t numSamples, const double freq); /* ============================================================================ ** Pure virtual function to be implemented by inheriter to set the following ** variables which get used in the bilinear transformation: a0, a1, a2, b1, b2. ** ** @param freq The center frequency used to calculate filter coefficients. ** ============================================================================ */ virtual void updateCoefficients(const double freq) = 0; /* ============================================================================ ** Sets the internal variable sampling_rate used for computing the coefficients. ** Note: Also clears the cached center_frequency variable, to force recompute. ** ** @param rate The sampling rate of the signal to be filtered. ** ============================================================================ */ void setSamplingRate(const unsigned int rate); /* ============================================================================ ** Sets the internal variable band_width used for computing the coefficients. ** Note: Also clears the cached center_frequency variable, to force recompute. ** Band Width is also only really used in band-pass/notch filters!! ** ** @param rate The sampling rate of the signal to be filtered. ** ============================================================================ */ void setBandWidth(const double width); protected: /* ============================================================================ ** Performs a bilinear transformation on the source signal and places it in ** the target array, according to the set internal coefficients. ** Note: target needs to be PRE-ALLOCATED with the same size as source!! ** ** @param source Array of data to be filtered. ** @param target Array of where the filtered data should go. ** @param numSamples The number of samples in the input array. ** ============================================================================ */ void bilinearTransformation(const double* source, double* target, const std::size_t numSamples); }; #endif /* HRI_PHYSIO_PROCESSING_BIQUADRATIC_H */
<gh_stars>1-10 /* $Id: ~|^` @(#) This is dedicated_sort_decl.h version 1.14 dated 2018-06-10T01:25:16Z. \ $ */ /* maintenance note: master file /data/projects/automation/940/lib/libmedian/include/s.dedicated_sort_decl.h */ /* can qualify (e.g. extern or static) at inclusion */ DEDICATED_SORT_RETURN_TYPE DEDICATED_SORT(/*This is a declaration, not a macro*/ char *base, size_t first, size_t beyond, /*const*/ size_t size, COMPAR_DECL, void (*swapf)(char *, char *, size_t), size_t alignsize, size_t size_ratio, size_t cache_sz, size_t pbeyond, unsigned int options)
<reponame>emotionbug/incubator-age-pg /* This is the prototype for the strdup() function which is distributed with Postgres. That strdup() is only needed on those systems that don't already have strdup() in their system libraries. The Postgres strdup() is in src/utils/strdup.c. */ extern char* strdup(char const*);
// Enable debug prints to serial monitor #define MY_DEBUG // Enable and select radio type attached //#define MY_RADIO_RF24 //#define MY_RADIO_NRF5_ESB //#define MY_RADIO_RFM69 #define MY_RADIO_RFM95 #include <MySensors.h> #define CHILD_ID_MQ 0 /************************Hardware Related Macros************************************/ #define MQ_SENSOR_ANALOG_PIN (0) //define which analog input channel you are going to use #define RL_VALUE (5) //define the load resistance on the board, in kilo ohms #define RO_CLEAN_AIR_FACTOR (9.83) //RO_CLEAR_AIR_FACTOR=(Sensor resistance in clean air)/RO, //which is derived from the chart in datasheet /***********************Software Related Macros************************************/ #define CALIBARAION_SAMPLE_TIMES (50) //define how many samples you are going to take in the calibration phase #define CALIBRATION_SAMPLE_INTERVAL (500) //define the time interval(in milliseconds) between each samples in the //calibration phase #define READ_SAMPLE_INTERVAL (50) //define how many samples you are going to take in normal operation #define READ_SAMPLE_TIMES (5) //define the time interval(in milliseconds) between each samples in //normal operation /**********************Application Related Macros**********************************/ #define GAS_LPG (0) #define GAS_CO (1) #define GAS_SMOKE (2) /*****************************Globals***********************************************/ uint32_t SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) //VARIABLES float Ro = 10000.0; // this has to be tuned 10K Ohm int val = 0; // variable to store the value coming from the sensor uint16_t lastMQ = 0; float LPGCurve[3] = {2.3,0.21,-0.47}; //two points are taken from the curve. //with these two points, a line is formed which is "approximately equivalent" //to the original curve. //data format:{ x, y, slope}; point1: (lg200, 0.21), point2: (lg10000, -0.59) float COCurve[3] = {2.3,0.72,-0.34}; //two points are taken from the curve. //with these two points, a line is formed which is "approximately equivalent" //to the original curve. //data format:{ x, y, slope}; point1: (lg200, 0.72), point2: (lg10000, 0.15) float SmokeCurve[3] = {2.3,0.53,-0.44}; //two points are taken from the curve. //with these two points, a line is formed which is "approximately equivalent" //to the original curve. //data format:{ x, y, slope}; point1: (lg200, 0.53), point2:(lg10000,-0.22) int MQGetGasPercentage(float rs_ro_ratio, int gas_id); float MQResistanceCalculation(int raw_adc); float MQCalibration(int mq_pin); float MQRead(int mq_pin); int MQGetPercentage(float rs_ro_ratio, float *pcurve); /****************** MQResistanceCalculation **************************************** Input: raw_adc - raw value read from adc, which represents the voltage Output: the calculated sensor resistance Remarks: The sensor and the load resistor forms a voltage divider. Given the voltage across the load resistor and its resistance, the resistance of the sensor could be derived. ************************************************************************************/ float MQResistanceCalculation(int raw_adc) { return ( ((float)RL_VALUE*(1023-raw_adc)/raw_adc)); } /***************************** MQCalibration **************************************** Input: mq_pin - analog channel Output: Ro of the sensor Remarks: This function assumes that the sensor is in clean air. It use MQResistanceCalculation to calculates the sensor resistance in clean air and then divides it with RO_CLEAN_AIR_FACTOR. RO_CLEAN_AIR_FACTOR is about 10, which differs slightly between different sensors. ************************************************************************************/ float MQCalibration(int mq_pin) { int i; float inVal=0; for (i=0; i<CALIBARAION_SAMPLE_TIMES; i++) { //take multiple samples inVal += MQResistanceCalculation(analogRead(mq_pin)); delay(CALIBRATION_SAMPLE_INTERVAL); } inVal = inVal/CALIBARAION_SAMPLE_TIMES; //calculate the average value inVal = inVal/RO_CLEAN_AIR_FACTOR; //divided by RO_CLEAN_AIR_FACTOR yields the Ro //according to the chart in the datasheet return inVal; } /***************************** MQRead ********************************************* Input: mq_pin - analog channel Output: Rs of the sensor Remarks: This function use MQResistanceCalculation to calculate the sensor resistance (Rs). The Rs changes as the sensor is in the different concentration of the target gas. The sample times and the time interval between samples could be configured by changing the definition of the macros. ************************************************************************************/ float MQRead(int mq_pin) { int i; float rs=0; for (i=0; i<READ_SAMPLE_TIMES; i++) { rs += MQResistanceCalculation(analogRead(mq_pin)); delay(READ_SAMPLE_INTERVAL); } rs = rs/READ_SAMPLE_TIMES; return rs; } /***************************** MQGetGasPercentage ********************************** Input: rs_ro_ratio - Rs divided by Ro gas_id - target gas type Output: ppm of the target gas Remarks: This function passes different curves to the MQGetPercentage function which calculates the ppm (parts per million) of the target gas. ************************************************************************************/ int MQGetGasPercentage(float rs_ro_ratio, int gas_id) { if ( gas_id == GAS_LPG ) { return MQGetPercentage(rs_ro_ratio,LPGCurve); } else if ( gas_id == GAS_CO ) { return MQGetPercentage(rs_ro_ratio,COCurve); } else if ( gas_id == GAS_SMOKE ) { return MQGetPercentage(rs_ro_ratio,SmokeCurve); } return 0; } /***************************** MQGetPercentage ********************************** Input: rs_ro_ratio - Rs divided by Ro pcurve - pointer to the curve of the target gas Output: ppm of the target gas Remarks: By using the slope and a point of the line. The x(logarithmic value of ppm) of the line could be derived if y(rs_ro_ratio) is provided. As it is a logarithmic coordinate, power of 10 is used to convert the result to non-logarithmic value. ************************************************************************************/ int MQGetPercentage(float rs_ro_ratio, float *pcurve) { return (pow(10,( ((log(rs_ro_ratio)-pcurve[1])/pcurve[2]) + pcurve[0]))); }
/*****************************************************************************/ /** * @file InteractorBase.h * @author <NAME> */ /*****************************************************************************/ #pragma once #include <kvs/EventListener> namespace kvs { /*===========================================================================*/ /** * @brief Interactor base class. */ /*===========================================================================*/ class InteractorBase : public kvs::EventListener { public: using BaseClass = kvs::EventListener; public: InteractorBase(); virtual ~InteractorBase() {} protected: virtual void initializeEvent(); virtual void paintEvent(); virtual void resizeEvent( int w, int h ); virtual void keyPressEvent( kvs::KeyEvent* e ); }; } // end of namespace kvs
/* Psychtoolbox3/Source/Common/SCREENGetMovieTimeIndex.c AUTHORS: mario.kleiner at tuebingen.mpg.de mk PLATFORMS: This file should build on any platform. HISTORY: 10/23/05 mk Created. DESCRIPTION: TO DO: */ #include "Screen.h" static char useString[] = "timeindex = Screen('GetMovieTimeIndex', moviePtr);"; static char synopsisString[] = "Return current time index for movie object 'moviePtr'."; static char seeAlsoString[] = "CloseMovie PlayMovie GetMovieImage GetMovieTimeIndex SetMovieTimeIndex"; PsychError SCREENGetMovieTimeIndex(void) { int moviehandle = -1; // All sub functions should have these two lines PsychPushHelp(useString, synopsisString, seeAlsoString); if(PsychIsGiveHelp()) {PsychGiveHelp(); return(PsychError_none);}; PsychErrorExit(PsychCapNumInputArgs(1)); // Max. 1 input args. PsychErrorExit(PsychRequireNumInputArgs(1)); // Min. 1 input args required. PsychErrorExit(PsychCapNumOutputArgs(1)); // One output arg. // Get the movie handle: PsychCopyInIntegerArg(1, TRUE, &moviehandle); if (moviehandle==-1) { PsychErrorExitMsg(PsychError_user, "GetMovieTimeIndex called without valid handle to a movie object."); } // Retrieve and return current movie time index: PsychCopyOutDoubleArg(1, TRUE, PsychGetMovieTimeIndex(moviehandle)); return(PsychError_none); }