content
stringlengths
12
2.72M
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBKIT_GLUE_FLING_ANIMATOR_IMPL_ANDROID_H_ #define WEBKIT_GLUE_FLING_ANIMATOR_IMPL_ANDROID_H_ #include "base/android/scoped_java_ref.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebFloatPoint.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebGestureCurve.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebSize.h" #include "ui/gfx/point.h" #include "ui/gfx/point_f.h" namespace WebKit { class WebGestureCurveTarget; } namespace webkit_glue { class FlingAnimatorImpl : public WebKit::WebGestureCurve { public: FlingAnimatorImpl(); virtual ~FlingAnimatorImpl(); static FlingAnimatorImpl* CreateAndroidGestureCurve( const WebKit::WebFloatPoint& velocity, const WebKit::WebSize&); virtual bool apply(double time, WebKit::WebGestureCurveTarget* target); private: void StartFling(const gfx::PointF& velocity); // Returns true if the animation is not yet finished. bool UpdatePosition(); gfx::Point GetCurrentPosition(); virtual void CancelFling(); bool is_active_; // Java OverScroller instance and methods. base::android::ScopedJavaGlobalRef<jobject> java_scroller_; jmethodID fling_method_id_; jmethodID abort_method_id_; jmethodID compute_method_id_; jmethodID getX_method_id_; jmethodID getY_method_id_; gfx::Point last_position_; DISALLOW_COPY_AND_ASSIGN(FlingAnimatorImpl); }; } // namespace webkit_glue #endif // WEBKIT_GLUE_FLING_ANIMATOR_IMPL_ANDROID_H_
<gh_stars>1-10 #include <pack.h> int set_bindtype_idx(T_PkgType *tp,int bindtype,const char *choose,int cols,char *idx) { char *p,buf[100],*p1; int i=0; if(!tp) return -1; if(!choose) { T_PkgType *typ; for(typ=tp;typ->type>-1;typ++) { typ->bindtype = bindtype; i++; } } else { p=(char *)choose; while(*p) { int n; p=stptok(p,buf,sizeof(buf),",|"); if(*p) p++; p1=skipblk(buf); TRIM(p1); n=index_col(idx,cols,p1,tp); if(n>-1) { tp[n].bindtype = bindtype; i++; } } } return i; }
#pragma once #include <memory> #include "decoders/Decoder.h" class ChipSim; class DecodeVGM : public Decoder { #pragma pack(push, 1) struct Header { uint32_t ident; // "Vgm " uint32_t eofOffset; uint32_t version; uint32_t sn76489Clock; uint32_t ym2413Clock; uint32_t gd3Offset; uint32_t totalSamples; uint32_t loopOffset; uint32_t loopSamples; uint32_t rate; uint16_t sn76489Feedback; uint16_t sn76489ShiftReg; uint32_t ym2612Clock; uint32_t ym2151Clock; uint32_t vgmDataOffset; uint32_t segaPcmClock; uint32_t spcmInterface; uint32_t rf5c68Clock; uint32_t ym2203Clock; uint32_t ym2608Clock; uint32_t ym2610bClock; uint32_t ym3812Clock; uint32_t ym3526Clock; uint32_t y8950Clock; uint32_t ymf262Clock; uint32_t ymf278bClock; uint32_t ymf271Clock; uint32_t ymz280bClock; uint32_t rf5c164Clock; uint32_t pwmClock; uint32_t ay8910Clock; uint8_t ay8910Type; uint8_t ay8910Flags; uint8_t ym2203ay8910Flags; uint8_t ym2608ay8910Flags; uint8_t volumeModifier; uint8_t reserved1; uint8_t loopBase; uint8_t loopModifier; uint32_t gbDmgClock; uint32_t nesApuClock; uint32_t multiPcmClock; uint32_t upd7759Clock; uint32_t okim6258Clock; uint8_t okim6258Flags; uint8_t k054539Flags; uint8_t c140Flags; uint8_t reserved2; uint32_t oki6295Clock; uint32_t k051649Clock; uint32_t k054539Clock; uint32_t huc6280Clock; uint32_t c140Clock; uint32_t k053260Clock; uint32_t pokeyClock; uint32_t qsoundClock; uint32_t scspClock; uint32_t extraHeaderOffset; uint32_t wswanClock; uint32_t vsuClock; uint32_t saa1090Clock; uint32_t es5503Clock; uint32_t es5506Clock; uint8_t es5503Channels; uint8_t es5506Channels; uint8_t c352ClockDivider; uint8_t reserved3; uint32_t x1010Clock; uint32_t c352Clock; uint32_t ga20Clock; uint8_t reserved4[7 * 4]; }; #pragma pack(pop) public: bool Open(Stream& stream) override; bool Decode(Frame& frame) override; void Close(Stream& stream) override; private: int DecodeBlock(); private: uint8_t* m_data; uint8_t* m_dataPtr; int m_loop; int m_samplesPerFrame; int m_processedSamples; std::shared_ptr<ChipSim> m_chip; bool m_isTS; };
<filename>Source/RenderPasses/PhotonMapperHash/PhotonMapperHash.h /*************************************************************************** # Copyright (c) 2015-21, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of NVIDIA CORPORATION nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "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. **************************************************************************/ #pragma once #include "Falcor.h" #include "Utils/Sampling/SampleGenerator.h" #include <chrono> using namespace Falcor; class PhotonMapperHash : public RenderPass { public: using SharedPtr = std::shared_ptr<PhotonMapperHash>; static const Info kInfo; /** Create a new render pass object. \param[in] pRenderContext The render context. \param[in] dict Dictionary of serialized parameters. \return A new object, or an exception is thrown if creation failed. */ static SharedPtr create(RenderContext* pRenderContext = nullptr, const Dictionary& dict = {}); virtual Dictionary getScriptingDictionary() override; virtual RenderPassReflection reflect(const CompileData& compileData) override; virtual void compile(RenderContext* pContext, const CompileData& compileData) override; virtual void execute(RenderContext* pRenderContext, const RenderData& renderData) override; virtual void renderUI(Gui::Widgets& widget) override; virtual void setScene(RenderContext* pRenderContext, const Scene::SharedPtr& pScene) override; virtual bool onMouseEvent(const MouseEvent& mouseEvent) override { return false; } virtual bool onKeyEvent(const KeyboardEvent& keyEvent) override { return false; } enum class TextureFormat { _8Bit = 0u, _16Bit = 1u, _32Bit = 2u }; enum LightTexMode : uint32_t { power = 0u, area = 1u }; private: PhotonMapperHash(); /** Prepares Program Variables and binds the sample generator */ void prepareVars(); /** Prepares the hash buffers */ void prepareHashBuffer(); /** Prepares all buffers neede for the generate photon pass */ bool preparePhotonBuffers(); /** Prepares the info textures. Is called inside of preparePhotonBuffers. Can be called seperate for format changes */ void preparePhotonInfoTexture(); /** Creates the photon counter for caustic and global photon buffers */ void preparePhotonCounters(); /** Resets buffer and runtime vars. Used for scene change or number of photons change */ void resetPhotonMapper(); /** Applies the changes to the number of photons */ void changeNumPhotons(); /** Copies the photon counter to a cpu buffer */ void copyPhotonCounter(RenderContext* pRenderContext); /** Creates the Generate Photon pass, where the photons are shot through the scene and saved in an AABB and information buffer */ void generatePhotons(RenderContext* pRenderContext, const RenderData& renderData); /** Pass that collect the photons. It will shoot a infinit small ray at the current camera position and collect all photons. * The needed position etc. has to be provided by a gBuffer */ void collectPhotons(RenderContext* pRenderContext, const RenderData& renderData); /** Prepares the buffer that holds the seeds for the SampleGenerator */ void prepareRandomSeedBuffer(const uint2 screenDimensions); /** Prepares a light sample texture for the photon generate pass */ void createLightSampleTexture(RenderContext* pRenderContext); /** Gets the active emissive triangles from the light collection. * This is analogous to the function from LightCollection. It is here to prevent changes to the core of Falcor. * As this is done once it has no impact on performance and only a minimal impact on CPU-Memory */ void getActiveEmissiveTriangles(RenderContext* pRenderContext); /** Checks the timer. This is to stop the renderer for performance tests */ void checkTimer(); // Internal state Scene::SharedPtr mpScene; ///< Current scene. SampleGenerator::SharedPtr mpSampleGenerator; ///< GPU sample generator. //Constants const float kMinPhotonRadius = 0.0001f; ///< At radius 0.0001 Photons are still visible const float kCollectTMin = 0.000001f; ///<non configurable constant for collection for now const float kCollectTMax = 0.000002f; ///< non configurable constant for collection for now const uint kInfoTexHeight = 512; ///< Height of the info tex as it is too big for 1D tex //*************************************************************************** // Configuration //*************************************************************************** bool mUseStatisticProgressivePM = true; ///< Activate Statistically Progressive Photon Mapping(SPPM) float mSPPMAlphaGlobal = 0.7f; ///< Global Alpha for SPPM float mSPPMAlphaCaustic = 0.7f; ///< Caustic Alpha for SPPM float mCausticRadiusStart = 0.01f; ///< Start value for the caustic Radius float mGlobalRadiusStart = 0.05f; ///< Start value for the caustic Radius float mCausticRadius = 1.f; ///< Current Radius for caustic Photons float mGlobalRadius = 1.f; ///< Current Radius for global Photons float mSpecRoughCutoff = 0.5f; ///< If rougness is over this value interpret the material as diffuse bool mResetIterations = false; ///<Resets the iterations counter once bool mAlwaysResetIterations = false; ///<Resets the iteration counter every frame bool mNumPhotonsChanged = false; ///<If true buffers needs to be restarted and Number of photons needs to be changed bool mFitBuffersToPhotonShot = false; ///<Changes the buffer size to be around the number of photons shot bool mUseAlphaTest = true; ///<Uses alpha test (Generate) bool mAdjustShadingNormals = true; ///<Adjusts the shading normals (Generate) uint mNumBucketBits = 20; ///< 2^NumBucketBits is the total amount of possible buckets uint mNumPhotonsPerBucket = 12; ///< Max Photons per hash grid. uint mQuadraticProbeIterations = 10; ///< Number of quadartic probe iteratons per hash. // Generate only uint mMaxBounces = 10; ///< Depth of recursion (0 = none). float mRussianRoulette = 0.3f; ///< Probabilty that a Global photon is saved uint mNumPhotons = 2000000; ///< Number of Photons shot uint mNumPhotonsUI = mNumPhotons; ///< For UI. It is decopled from the runtime var because changes have to be confirmed uint mGlobalBufferSizeUI = mNumPhotons / 2; ///< Size of the Global Photon Buffer uint mCausticBufferSizeUI = mNumPhotons / 4; ///< Size of the Caustic Photon Buffer float mIntensityScalar = 1.0f; ///<Scales the intensity of emissive light sources // Collect only bool mDisableGlobalCollection = false; ///<Disabled the collection of global photons bool mDisableCausticCollection = false; ///<Disabled the collection of caustic photons bool mEnableStochasticCollection = true; ///<Enables/Disables Stochasic collection float mStochasticCollectProbability = 0.33f; ///< Probability for collection //******************************************************* // Runtime data //******************************************************* uint mFrameCount = 0; ///< Frame count since last Reset std::vector<uint> mPhotonCount = { 0,0 }; bool mOptionsChanged = false; bool mResetCS = true; bool mSetConstantBuffers = true; bool mResizePhotonBuffers = true; ///< If true resize the Photon Buffers bool mPhotonInfoFormatChanged = false; bool mRebuildAS = false; uint mInfoTexFormat = 1; uint mNumBuckets = 0; //Light std::vector<uint> mActiveEmissiveTriangles; bool mRebuildLightTex = false; LightTexMode mLightTexMode = LightTexMode::power; Texture::SharedPtr mLightSampleTex; Buffer::SharedPtr mPhotonsPerTriangle; const uint mMaxDispatchY = 512; uint mPGDispatchX = 0; uint mAnalyticEndIndex = 0; uint mNumLights = 0; float mAnalyticInvPdf = 0.0f; //Clock/Timer bool mUseTimer = false; //<Activates the timer bool mResetTimer = false; //<Resets the timer bool mTimerStopRenderer = false; //<Stops rendering (via return) double mTimerDurationSec = 60.0; //<How long the timer is running uint mTimerMaxIterations = 0; //< Stop at certain iterations double mCurrentElapsedTime = 0.0; //<Elapsed time for UI std::chrono::time_point<std::chrono::steady_clock> mTimerStartTime; //<Start time for the timer // Ray tracing program. struct RayTraceProgramHelper { RtProgram::SharedPtr pProgram; RtBindingTable::SharedPtr pBindingTable; RtProgramVars::SharedPtr pVars; static const RayTraceProgramHelper create() { RayTraceProgramHelper r; r.pProgram = nullptr; r.pBindingTable = nullptr; r.pVars = nullptr; return r; } }; ComputePass::SharedPtr mpCSCollect; ///<Collect pass collects the photons that where shot RayTraceProgramHelper mTracerGenerate; ///<Description for the Generate Photon pass // //Photon Buffers // //Struct for the buffers that are needed for global and caustic photons bool mPhotonBuffersReady = false; bool mTestInit = false; struct { Buffer::SharedPtr counter; Buffer::SharedPtr reset; Buffer::SharedPtr cpuCopy; }mPhotonCounterBuffer; struct PhotonBuffers { uint maxSize = 0; Texture::SharedPtr position; Texture::SharedPtr infoFlux; Texture::SharedPtr infoDir; }; Buffer::SharedPtr mpGlobalBuckets; Buffer::SharedPtr mpCausticBuckets; PhotonBuffers mCausticBuffers; ///< Buffers for the caustic photons PhotonBuffers mGlobalBuffers; ///< Buffers for the global photons Texture::SharedPtr mRandNumSeedBuffer; ///< Buffer for the random seeds };
#ifndef CIRCLE_H #define CIRCLE_H #include "./Shape.h" //定义派生类Circle - 圆形 - 公有方式继承自Shape class Circle: public Shape { private: double radius;//半径 public: Circle(double radius);//构造函数 virtual ~Circle();//析构函数 virtual double area() const;//定义虚函数,,相当于接口,求圆面积 }; #endif
#pragma once // RichODBC.h: interface for the RichODBC class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_RichODBC_H__9820EFEA_1038_4AB4_AB7E_997758F992C7__INCLUDED_) #define AFX_RichODBC_H__9820EFEA_1038_4AB4_AB7E_997758F992C7__INCLUDED_ #include <windows.h> #include <Sqltypes.h> #include <sql.h> #include <sqlext.h> #include <stdio.h> #include <time.h> #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #define MAX_QUERY_SIZE 3072 typedef VOID ( *pExternErrorHandler )( CHAR *pszQuery, LONG siParam1 ); class RichODBC { public: RichODBC(); ~RichODBC(); void InitODBC(); void ReleaseODBC(); VOID SetParam(int siParamNo, int siType, void *pData, int siDatasize, SQLSMALLINT siParamType = SQL_PARAM_INPUT, bool bNull = false); int GetData(int iColNo, int iType, void *pvData, long siDataSize); int GetData(int iColNo, void *pvData, long siDataSize); public: VOID GetResult(VOID *pvResult, long siDatasize); const INT64 GetRowcount(); const RETCODE GetRetcode() { return m_retcode; } VOID SetPooling(BOOL data) { IsPooling = data; } private: BOOL bReconnectStat; BOOL bCanFetchRow; BOOL bIsConnected; public: void inline SetReconnect(BOOL bStat) { bReconnectStat = bStat; } BOOL inline GetReconnectStat() { return bReconnectStat; } BOOL Connect(char *cDriver, char *cServer, char *cDatabase, char *cUserID, char *cPasswd); BOOL ConnectProcess(); BOOL Reconnect(); int Disconnect(); VOID Prepare(); int ExecSQL(); bool FetchData(); bool NextRecordSet(); int SetQuery(char *pszQuery); ////////////////////////////////////////////////////////// void BeginSP(char *pszQuery); void EndSP(); void SetParam(int siType, void *pData, int siDatasize, SQLSMALLINT siParamType = SQL_PARAM_INPUT, bool bNull = false); int GetData(void *pvData, long siDataSize = 0); /////////////////////////////////////////////////////////*/ BOOL CheckMDAC(wchar_t *cRequire); BOOL CheckError(SQLSMALLINT hType, SQLHANDLE handle,char* hint=NULL, HWND hwnd = NULL); BOOL IsSuccess(void); int m_siParamNo; int m_sicount; INT64 m_siParamSize; //protected: SQLHDBC m_hdbc; SQLHSTMT m_hstmt; SQLHENV m_henv; INT64 m_siRowcount; INT64 m_siNTS, m_siZero; INT64 m_siNULL; char m_cConnectionString[1024]; char *m_pszQuery; time_t m_tBEGINSP; time_t m_tEXECSP; time_t m_tFETCH; time_t m_tNEXTRECORDSET; pExternErrorHandler m_pExternErrorHandler; VOID SetExternErrorHandler( pExternErrorHandler pexternerrorhandler ); private: RETCODE m_retcode; long m_lbytes; BOOL IsPooling; private: FILE *m_Queryfp; char m_cErrQuery[8192]; void PrintErrMsg(char *msg); void PrintQuery(char *msg); void PrintParam(char *msg); void WriteQuery(); void WriteMSG(char* msg, size_t length); public: void MakeTime( TIMESTAMP_STRUCT& src, time_t& dest ); void MakeTIMESTAMP_STRUCT( time_t& src, TIMESTAMP_STRUCT& dest ); }; class XDBException { public: int code; char msg[4096]; XDBException():code(0) { msg[0]='\0'; }; XDBException(int c,const char * m):code(0) { UNREFERENCED_PARAMETER(c); strncpy_s( msg, m, sizeof(msg) ); //#ifndef TEST // Log & log=*Log::Instance(); // log("XDBException:(%d:%s)\n",code,msg); //#endif }; }; #endif // !defined(AFX_RichODBC_H__9820EFEA_1038_4AB4_AB7E_997758F992C7__INCLUDED_)
////////////////////////////////////////////////////////////////////// // This file was auto-generated by codelite's wxCrafter Plugin // wxCrafter project file: GDCppDialogs.wxcp // Do not modify this file by hand! ////////////////////////////////////////////////////////////////////// #ifndef IDE_DIALOGS_GDCPPDIALOGS_BASE_CLASSES_H #define IDE_DIALOGS_GDCPPDIALOGS_BASE_CLASSES_H #include <wx/settings.h> #include <wx/xrc/xmlres.h> #include <wx/xrc/xh_bmp.h> #include <wx/panel.h> #include <wx/artprov.h> #include <wx/aui/framemanager.h> #include <wx/aui/dockart.h> #include <wx/pen.h> #include <wx/aui/auibar.h> #include <map> #include <wx/menu.h> #include <wx/toolbar.h> #include <wx/notebook.h> #include <wx/imaglist.h> #include <wx/sizer.h> #include <wx/listctrl.h> #include <wx/treectrl.h> #include <wx/stattext.h> #include <wx/bmpbuttn.h> #include <wx/dialog.h> #include <wx/iconbndl.h> #include <wx/statbox.h> #include <wx/hyperlink.h> #include <wx/statline.h> #include <wx/textctrl.h> #include <wx/button.h> #if wxVERSION_NUMBER >= 2900 #include <wx/persist.h> #include <wx/persist/toplevel.h> #include <wx/persist/bookctrl.h> #include <wx/persist/treebook.h> #endif class DebuggerGUIBase : public wxPanel { public: enum { ID_ADD_OBJECT_TOOL = 1001, ID_ADD_VARG_TOOL = 1002, ID_ADD_VAR_TOOL = 1003, ID_DELETE_BT = 1004, ID_GENERAL_LIST_CTRL = 1005, ID_OBJECTS_TREE_CTRL = 1006, ID_OBJECT_LIST = 1007, ID_PAUSE_TOOL = 1008, ID_PLAY_TOOL = 1009, ID_STEP_TOOL = 1010, }; protected: wxAuiManager* m_auimgr; wxAuiToolBar* m_toolbar; wxNotebook* m_notebook; wxPanel* m_panel31; wxListCtrl* m_generalList; wxPanel* m_panel33; wxTreeCtrl* m_objectsTree; wxStaticText* m_staticText45; wxStaticText* m_objectName; wxBitmapButton* m_deleteBt; wxListCtrl* m_objectList; protected: public: wxAuiToolBar* GetToolbar() { return m_toolbar; } wxListCtrl* GetGeneralList() { return m_generalList; } wxPanel* GetPanel31() { return m_panel31; } wxTreeCtrl* GetObjectsTree() { return m_objectsTree; } wxStaticText* GetStaticText45() { return m_staticText45; } wxStaticText* GetObjectName() { return m_objectName; } wxBitmapButton* GetDeleteBt() { return m_deleteBt; } wxListCtrl* GetObjectList() { return m_objectList; } wxPanel* GetPanel33() { return m_panel33; } wxNotebook* GetNotebook() { return m_notebook; } wxAuiManager* GetAuimgr() { return m_auimgr; } DebuggerGUIBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(500,300), long style = wxTAB_TRAVERSAL); virtual ~DebuggerGUIBase(); }; class AndroidExportDialogBase : public wxDialog { protected: wxStaticText* m_staticText55; wxStaticText* m_staticText85; wxHyperlinkCtrl* m_hyperLink57; wxStaticLine* m_staticLine59; wxStaticText* m_staticText61; wxTextCtrl* m_exportFolderTextCtrl; wxButton* m_browserButton; wxStdDialogButtonSizer* m_stdBtnSizer71; wxButton* m_okButton; wxButton* m_cancelButton; protected: virtual void OnHelpButtonClicked(wxHyperlinkEvent& event) { event.Skip(); } virtual void OnBrowseButtonClicked(wxCommandEvent& event) { event.Skip(); } public: wxStaticText* GetStaticText55() { return m_staticText55; } wxStaticText* GetStaticText85() { return m_staticText85; } wxHyperlinkCtrl* GetHyperLink57() { return m_hyperLink57; } wxStaticLine* GetStaticLine59() { return m_staticLine59; } wxStaticText* GetStaticText61() { return m_staticText61; } wxTextCtrl* GetExportFolderTextCtrl() { return m_exportFolderTextCtrl; } wxButton* GetBrowserButton() { return m_browserButton; } AndroidExportDialogBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Export to native Android"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(-1,-1), long style = wxDEFAULT_DIALOG_STYLE); virtual ~AndroidExportDialogBase(); }; #endif
#ifndef FUNCTIONS_H_ #define FUNCTIONS_H_ #include <ext/algorithm> #include <iterator> #include <set> #include <utility> #include <vector> namespace mt { namespace functions { /** * @brief A distance function object which calculates the <b>euclidean * distance</b> between two data objects representing coordinates. * @details Assumes that the data objects are same-sized sequences of numbers. * @see http://en.wikipedia.org/wiki/Euclidean_distance */ struct euclidean_distance { /** * @brief The operator that performs the calculation. */ template <typename Sequence> double operator()(const Sequence& data1, const Sequence& data2) const { double distance = 0; for(auto i1 = data1.begin(), i2 = data2.begin(); i1 != data1.end() && i2 != data2.end(); ++i1, ++i2) { double diff = *i1 - *i2; distance += diff * diff; } distance = sqrt(distance); return distance; } }; /** * @brief A promotion function object which randomly chooses two data objects * as promoted. */ struct random_promotion { /** * @brief The operator that performs the promotion. * @tparam Data The type of the data objects. * @tparam DistanceFunction The type of the function or function object used * to calculate the distance between two Data objects. * @return A pair with the promoted data objects. */ template <typename Data, typename DistanceFunction> std::pair<Data, Data> operator()(const std::set<Data>& data_objects, DistanceFunction& distance_function) const { std::vector<Data> promoted; random_sample_n(data_objects.begin(), data_objects.end(), inserter(promoted, promoted.begin()), 2); assert(promoted.size() == 2); return {promoted[0], promoted[1]}; } }; /** * @brief A partition function object which equally distributes the data objects * according to their distances to the promoted data objects. * @details The algorithm is roughly equivalent to this: * @code * data_objects := first_partition * first_partition := Empty * second_partition := Empty * Repeat until data_object is empty: * X := The object in data_objects which is the nearest to promoted.first * Remove X from data_object * Add X to first_partition * * Y := The object in data_objects which is the nearest to promoted.second * Remove Y from data_object * Add Y to second_partition * @endcode */ struct balanced_partition { /** * @brief The operator that performs the partition. * @tparam Data The type of the data objects. * @tparam DistanceFunction The type of the function or function object used * to calculate the distance between two @c Data * objects. * @param [in] promoted The promoted data objects. * @param [in,out] first_partition Initially, is the set containing all the * objects that must be partitioned. After * the partitioning, contains the objects * related to the first promoted data object, * which is @c promoted.first. * @param [out] second_partition Initially, is an empty set. After the * partitioning, contains the objects related * to the second promoted data object, which * is @c promoted.second. * @param [in] distance_function The distance function or function object. */ template <typename Data, typename DistanceFunction> void operator()(const std::pair<Data, Data>& promoted, std::set<Data>& first_partition, std::set<Data>& second_partition, DistanceFunction& distance_function ) const { std::vector<Data> queue1(first_partition.begin(), first_partition.end()); // Sort by distance to the first promoted data std::sort(queue1.begin(), queue1.end(), [&](const Data& data1, const Data& data2) { double distance1 = distance_function(data1, promoted.first); double distance2 = distance_function(data2, promoted.first); return distance1 < distance2; } ); std::vector<Data> queue2(first_partition.begin(), first_partition.end()); // Sort by distance to the second promoted data std::sort(queue2.begin(), queue2.end(), [&](const Data& data1, const Data& data2) { double distance1 = distance_function(data1, promoted.second); double distance2 = distance_function(data2, promoted.second); return distance1 < distance2; } ); first_partition.clear(); typename std::vector<Data>::iterator i1 = queue1.begin(); typename std::vector<Data>::iterator i2 = queue2.begin(); while(i1 != queue1.end() || i2 != queue2.end()) { while(i1 != queue1.end()) { Data& data = *i1; ++i1; if(second_partition.find(data) == second_partition.end()) { first_partition.insert(data); break; } } while(i2 != queue2.end()) { Data& data = *i2; ++i2; if(first_partition.find(data) == first_partition.end()) { second_partition.insert(data); break; } } } } }; /** * @brief A function object that defines a split function by composing a * promotion function and a partition function. * @tparam PromotionFunction The type of the function or function object which * implements a promotion function. * @tparam PartitionFunction The type of the function or function object which * implements a partition function. */ template <typename PromotionFunction, typename PartitionFunction> struct split_function { /** */ typedef PromotionFunction promotion_function_type; /** */ typedef PartitionFunction partition_function_type; PromotionFunction promotion_function; PartitionFunction partition_function; /** */ explicit split_function( PromotionFunction promotion_function = PromotionFunction(), PartitionFunction partition_function = PartitionFunction() ) : promotion_function(promotion_function), partition_function(partition_function) {} /** * @brief The operator that performs the split. * @tparam Data The type of the data objects. * @tparam DistanceFunction The type of the function or function object used * to calculate the distance between two @c Data * objects. * @param [in,out] first_partition Initially, is the set containing all the * objects that must be partitioned. After * the partitioning, contains the objects * related to the first promoted data object. * @param [out] second_partition Initially, is an empty set. After the * partitioning, contains the objects related * to the second promoted data object. * @param [in] distance_function The distance function or function object. * @return A pair with the promoted data objects. */ template <typename Data, typename DistanceFunction> std::pair<Data, Data> operator()( std::set<Data>& first_partition, std::set<Data>& second_partition, DistanceFunction& distance_function ) const { std::pair<Data, Data> promoted = promotion_function(first_partition, distance_function); partition_function(promoted, first_partition, second_partition, distance_function); return promoted; } }; template <typename Data, typename DistanceFunction> class cached_distance_function { public: explicit cached_distance_function(const DistanceFunction& distance_function) : distance_function(distance_function) {} double operator()(const Data& data1, const Data& data2) { typename CacheType::iterator i = cache.find(make_pair(data1, data2)); if(i != cache.end()) { return i->second; } i = cache.find(make_pair(data2, data1)); if(i != cache.end()) { return i->second; } // Not found in cache double distance = distance_function(data1, data2); // Store in cache cache.insert(make_pair(make_pair(data1, data2), distance)); cache.insert(make_pair(make_pair(data2, data1), distance)); return distance; } private: typedef std::map<std::pair<Data, Data>, double> CacheType; const DistanceFunction& distance_function; CacheType cache; }; } /* namespace functions */ } /* namespace mtree */ #endif /* FUNCTIONS_H_ */
<reponame>horance-liu/cub<filename>cub/algo/bound.h #ifndef H1BEBC79D_5BA8_1234_AD8C_94F820EC7D5B #define H1BEBC79D_5BA8_1234_AD8C_94F820EC7D5B #include <stddef.h> namespace cub { namespace details { template <typename T, bool IsLowBound> size_t bound(const T* array, size_t len, T key) { size_t low = 0; size_t high = len - 1; size_t mid = 0; if (key < array[low]) { return low; } if (key > array[high]) { return high; } while (low <= high) { mid = (low + high) >> 1; if (key == array[mid]) { return mid; } else if (key > array[mid]) { low = mid + 1; } else { high = mid - 1; } } return IsLowBound ? high : low; } } // namespace details template <typename T> size_t lower_bound(const T* array, size_t len, T key) { return details::bound<T, true>(array, len, key); } template <typename T> size_t upper_bound(const T* array, size_t len, T key) { return details::bound<T, false>(array, len, key); } } // namespace cub #endif
<reponame>mickaelcala/TNTbasic /******************** ***********************/ // // Player PRO 5.9 - DRIVER SOURCE CODE - // // Library Version 5.9 // // To use with MAD Library for Mac: Symantec, CodeWarrior and MPW // // <NAME> // 20 Micheli-Du-Crest // 1205 GENEVA // SWITZERLAND // // COPYRIGHT <NAME> 1996, 1997, 1998, 1999, 2000, 2001, 2002 // // Thank you for your interest in PlayerPRO ! // // FAX: (+41 22) 346 11 97 // PHONE: (+41 79) 203 74 62 // Internet: <EMAIL> // /******************** ***********************/ #include "FileUtils.h" #include <Script.h> extern void NSLog(CFStringRef format, ...); //TODO: migrate PlayerPRO away from FSSpec! //TODO: HSetVol isn't available in 64-bit code :( //TODO: Also, FSSpec is defined as UInt8 hidden[70] unsigned char* MYC2PStr( Ptr cStr) { long size = strlen( cStr); BlockMoveData( cStr, cStr + 1, strlen( cStr)); cStr[ 0] = size; return (unsigned char*) cStr; } void MYP2CStr( unsigned char *cStr) { long size = cStr[ 0]; BlockMoveData( cStr + 1, cStr, size); cStr[ size] = 0; } UNFILE iFileOpen(Ptr name) { UNFILE temp; OSErr iErr; FSRef Ref; FSSpec spec; HGetVol( NULL, &spec.vRefNum, &spec.parID); MYC2PStr( name); pStrcpy( spec.name, (unsigned char*) name); MYP2CStr((unsigned char*)name); iErr = FSpMakeFSRef(&spec, &Ref); if(iErr != noErr) return 0; Boolean UnusedBoolean, UnusedBoolean2; HFSUniStr255 whythis; FSGetDataForkName(&whythis); FSResolveAliasFile(&Ref, TRUE, &UnusedBoolean, &UnusedBoolean2); iErr = FSOpenFork(&Ref, whythis.length, whythis.unicode, fsCurPerm, &temp); if(iErr != noErr) return 0; else return temp; } long iGetEOF(UNFILE iFileRefI) { SInt64 curEOF; FSGetForkSize(iFileRefI, &curEOF); return curEOF; } OSErr iRead(long size, Ptr dest, UNFILE iFileRefI) { return FSReadFork(iFileRefI, fsAtMark, 0, size, dest, NULL); } OSErr iSeekCur(long size, UNFILE iFileRefI) { return FSSetForkPosition( iFileRefI, fsFromMark, size); } void iFileCreate(Ptr name, OSType type) { /* char *folderPath, *FileName; Boolean isFolder, unusedBool; OSStatus iErr; FSRef Ref; int slashCharPos = 0, nameLen, i, ii; FSCatalogInfo fileCat; FileInfo *fInfo = (FileInfo*)&fileCat.finderInfo; if(FSPathMakeRef((UInt8*)name, &Ref, NULL) == noErr) { FSDeleteObject(&Ref); } nameLen = strlen(name); for(i = 0; i > (nameLen); i++) { if(name[i] == '/') slashCharPos = i; } //TODO: use a better function folderPath = calloc((slashCharPos + 2), sizeof(char)); FileName = calloc((nameLen - slashCharPos + 2), sizeof(char)); for(i = 0; i == slashCharPos;i++) { folderPath[i] = name[i]; } for(i=slashCharPos+1, ii=0;i == nameLen;i++, ii++) { FileName[ii] = name[i]; FileName[ii+1] = '\0'; } // folderPath[slashCharPos+1] = '\0'; iErr = FSPathMakeRef((UInt8*)folderPath, &Ref, &isFolder); if(iErr != noErr) MyDebugStr(__LINE__, __FILE__, "Error creating FSRef"); if(isFolder == FALSE) NSLog(CFSTR("FSRef wasn't a folder. Ignoring, hoping it is an alias.")); iErr= FSResolveAliasFile(&Ref, TRUE, &isFolder, &unusedBool); if(iErr != noErr) MyDebugStr(__LINE__, __FILE__, "Error resolving Alias"); if(isFolder == FALSE) MyDebugStr(__LINE__, __FILE__, "FSRef wasn't a folder!"); //TODO: do NOT use CFString! CFStringRef UniCFSTR = CFStringCreateWithCString(kCFAllocatorDefault, FileName, CFStringGetSystemEncoding()); CFIndex UNIcharLen = CFStringGetLength(UniCFSTR); UniChar* UNICHARThing = calloc(UNIcharLen, sizeof(UniChar)); CFRange UNIRange; UNIRange.location = 0; UNIRange.length = UNIcharLen; CFStringGetCharacters(UniCFSTR, UNIRange, UNICHARThing); fInfo->fileType = type; fInfo->fileCreator = 'SNPL'; fInfo->finderFlags = 0; fInfo->location.h = 0; fInfo->location.v = 0; fInfo->reservedField = 0; FSCreateFileUnicode(&Ref, UNIcharLen, UNICHARThing, kFSCatInfoFinderInfo, &fileCat, NULL, NULL); CFRelease(UniCFSTR); free(folderPath); free(FileName); free(UNICHARThing); */ FSSpec spec; HGetVol( NULL, &spec.vRefNum, &spec.parID); MYC2PStr( name); pStrcpy( spec.name, (unsigned char*) name); FSpDelete( &spec); FSpCreate( &spec, 'SNPL', type, smSystemScript); MYP2CStr( (unsigned char*) name); } OSErr iWrite(long size, Ptr dest, UNFILE iFileRefI) { return FSWriteFork(iFileRefI, fsAtMark, 0, size, dest, NULL); } void iClose(UNFILE iFileRefI) { FSCloseFork(iFileRefI); } ///////////////////////////////// Ptr MADstrcpy( Ptr dst, const char* src) { // NSLog(CFSTR("MADstrcpy is depricated; just use strcpy")); long i = 0; do { dst[ i] = src[ i]; }while( src[ i++]); return dst; } //TODO: use system native strcmp? int MADstrcmp( const char *dst, const char* src) { long i = 0; do { if( dst[ i] != src[ i]) return -1; }while( src[ i++]); return 0; } EXP void OSType2Ptr( OSType type, Ptr str) { #ifdef __LITTLE_ENDIAN__ MOT32(&type); #endif BlockMoveData( &type, str, 4); str[ 4] = 0; } EXP OSType Ptr2OSType( char* str) { short i; OSType type; i = strlen( str); if( i > 4) i = 4; type = ' '; BlockMoveData( str, &type, i); #ifdef __LITTLE_ENDIAN__ MOT32(&type); #endif return type; }
// // IAPCell.h // ShopFolder // // Created by <NAME> on 2012/03/22. // Copyright (c) 2012年 CCTSAI. All rights reserved. // #import <UIKit/UIKit.h> @interface IAPCell : UITableViewCell { CGSize textLabelSize; } @property (nonatomic, assign) CGSize textLabelSize; @end
<reponame>ihowson/bulkem #ifndef BULKEM_H #define BULKEM_H // Do not include any R or CUDA headers in here; the R and CUDA stuff needs to be compiled separately. // To save time, we put a hard limit on the number of components that we can // fit. This limit can be removed if necessary. #define MAX_COMPONENTS 8 // TODO: Ditto for max observations. This limit really ought to be lifted; 10k obs isn't very large #define MAX_OBSERVATIONS 1000000 // This ought to work well for most modern machines (at least, as of 2015). // TODO: make it a parameter to the R interface #define NUM_THREADS 8 enum fit_result { FIT_NOT_ATTEMPTED = 0, // default; dataset has not been fit yet FIT_SUCCESS, FIT_FAILED // DID_NOT_CONVERGE, // OTHER }; typedef struct _invgauss_params_t { double mu; double lambda; double alpha; // mixing proportion } invgauss_params_t; typedef struct _dataset { // Before fitting, these fields are filled in double *data; int num_observations; // After fitting, these fields are filled in enum fit_result fr; double final_loglik; invgauss_params_t init_params[MAX_COMPONENTS]; // initial parameters used for the fit invgauss_params_t fit_params[MAX_COMPONENTS]; int num_iterations; // number of iterations used to produce the fit // TODO: return posterior probabilities } dataset; typedef struct _fit_params { dataset *datasets; int num_datasets; int num_components; double epsilon; int verbose; int random_inits; int max_iters; } fit_params; #ifdef __cplusplus extern "C" { #endif int bulkem_cuda(fit_params *fp); void stream_main(fit_params *fp); #ifdef __cplusplus } #endif #endif
<filename>wavebench-dag/include/core/math/vector-elemental-functions.h #ifndef __VECTOR_ELEMENTAL_FUNCTIONS_MATH_CORE_H__ #define __VECTOR_ELEMENTAL_FUNCTIONS_MATH_CORE_H__ #include "../macros/macros.h" #include "../meta/meta.h" #include "../types/types.h" #include "arithmetic.h" #include "elemental-functions.h" #include "vector-arithmetic.h" namespace __core__ { namespace __math__ { //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __floor__(const Vector<V,N,AV>& v) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__floor__(v(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__floor__(v(i));)) #endif return result; } template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __ceil__(const Vector<V,N,AV>& v) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__ceil__(v(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__ceil__(v(i));)) #endif return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __abs__(const Vector<V,N,AV>& v) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__abs__(v(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__abs__(v(i));)) #endif return result; } template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __sign__(const Vector<V,N,AV>& v) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__sign__(v(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__sign__(v(i));)) #endif return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=conditional_T<is_same_CE<void,RVT>(),V,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __max__(const Vector<V,N,AV>& v) { RT result=v(0); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result=__max__(v(i),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result=__max__(v(i),result);)) #endif return result; } template <typename RVT=void,typename V=void,typename U=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,U>,typename RET=basal_T<RT>,enable_IT<!is_vector_CE<U>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __max__(const Vector<V,N,AV>& v,const U x) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__max__(v(i),x);)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__max__(v(i),x);)) #endif return result; } template <typename RVT=void,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __max__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__max__(v(i),u(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__max__(v(i),u(i));)) #endif return result; } template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=conditional_T<is_same_CE<void,RVT>(),V,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __min__(const Vector<V,N,AV>& v) { RT result=v(0); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result=__min__(v(i),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result=__min__(v(i),result);)) #endif return result; } template <typename RVT=void,typename V=void,typename U=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,U>,typename RET=basal_T<RT>,enable_IT<!is_vector_CE<U>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __min__(const Vector<V,N,AV>& v,const U x) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__min__(v(i),x);)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__min__(v(i),x);)) #endif return result; } template <typename RVT=void,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __min__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__min__(v(i),u(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__min__(v(i),u(i));)) #endif return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,RVT>(),higher_PT<V,U>,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __max_diff__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result=__sub__<RM>(v(0),u(0)); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__max__(__sub__<RM>(v(i),u(i)),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__max__(__sub__<RM>(v(i),u(i)),result);)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,RVT>(),higher_PT<V,U>,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __min_diff__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result=__sub__<RM>(v(0),u(0)); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__min__(__sub__<RM>(v(i),u(i)),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__min__(__sub__<RM>(v(i),u(i)),result);)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,RVT>(),higher_PT<V,U>,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __max_abs_diff__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result=__sub__<RM>(v(0),u(0)); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__max__(__abs__(__sub__<RM>(v(i),u(i))),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__max__(__abs__(__sub__<RM>(v(i),u(i))),result);)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,RVT>(),higher_PT<V,U>,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __min_abs_diff__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result=__sub__<RM>(v(0),u(0)); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__min__(__abs__(__sub__<RM>(v(i),u(i))),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__min__(__abs__(__sub__<RM>(v(i),u(i))),result);)) #endif return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,U>,typename RET=basal_T<RT>,enable_IT<!is_vector_CE<U>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_add__(const Vector<V,N,AV>& v,const U x) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__abs__(__add__<RM,V,U>(v(i),x));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__abs__(__add__<RM,V,U>(v(i),x));)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_add__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__abs__(__add__<RM,V,U>(v(i),u(i)));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__abs__(__add__<RM,V,U>(v(i),u(i)));)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,typename X=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_add__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&,const X),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha),(result,v,u,alpha), (result[i]=__abs__(__ma__<RM>(v(i),alpha,u(i)));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&,const X),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha),(result,v,u,alpha), (result[i]=__abs__(__ma__<RM>(v(i),alpha,u(i)));)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,typename X=void,typename Y=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_add__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha,const Y beta) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&,const X,const Y),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha,const Y beta),(result,v,u,alpha,beta), (result[i]=__abs__(__ma__<RM>(v(i),alpha,__mul__<RM>(u(i),beta)));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&,const X,const Y),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha,const Y beta),(result,v,u,alpha,beta), (result[i]=__abs__(__ma__<RM>(v(i),alpha,__mul__<RM>(u(i),beta)));)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,U>,typename RET=basal_T<RT>,enable_IT<!is_vector_CE<U>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_sub__(const Vector<V,N,AV>& v,const U x) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__abs__(__sub__<RM,V,U>(v(i),x));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__abs__(__sub__<RM,V,U>(v(i),x));)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_sub__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__abs__(__sub__<RM,V,U>(v(i),u(i)));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__abs__(__sub__<RM,V,U>(v(i),u(i)));)) #endif return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,3,AV>,Vector<U,3,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __cross__(const Vector<V,3,AV>& v,const Vector<U,3,AU>& u) { RT result; result[0]=__sub__<RM>(__mul__<RM>(v(1),u(2)),__mul__<RM>(v(2),u(1))); result[1]=__sub__<RM>(__mul__<RM>(v(2),u(0)),__mul__<RM>(v(0),u(2))); result[2]=__sub__<RM>(__mul__<RM>(v(0),u(1)),__mul__<RM>(v(1),u(0))); return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename TRT=double,bool optimized=true,FastMathMode FM=__default_fast_math_mode__,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,TRT>(),higher_PT<V,U>,TRT>> __forceinline__ __optimize__ __host_device__ __forceflatten__ RT __angle__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { return __acos__(__dot__<TRT,RM>(v,u)/(__mul__<RM>(__norm2__<TRT,optimized,FM,RM>(v),__norm2__<TRT,optimized,FM,RM>(u)))); } template <typename TRT=double,bool optimized=true,FastMathMode FM=__default_fast_math_mode__,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,TRT>(),higher_PT<V,U>,TRT>> __forceinline__ __optimize__ __host_device__ __forceflatten__ RT __angle_cos__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { return __dot__<TRT,RM>(v,u)/(__mul__<RM>(__norm2__<TRT,optimized,FM,RM>(v),__norm2__<TRT,optimized,FM,RM>(u))); } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT,RoundingMode RM=__default_rounding_mode__,typename V=void,int N=0,uint AV=0,typename RET=basal_T<RVT>,enable_IT<same_dimensions<RVT,Vector<V,N,AV>>()&&(!is_same_CE<RVT,Vector<V,N,AV>>())> = 0> static inline __forceflatten__ __optimize__ __host_device__ RVT __cast__(const Vector<V,N,AV>& v) { RVT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RVT&,const Vector<V,N,AV>&),(RVT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__cast__<RET,RM>(v(i));)) #else __unroll_cpu__(int,i,0,N,(RVT&,const Vector<V,N,AV>&),(RVT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__cast__<RET,RM>(v(i));)) #endif return result; } template <typename RVT,RoundingMode RM=__default_rounding_mode__,typename V=void,int N=0,uint AV=0,typename RET=basal_T<RVT>,enable_IT<is_same_CE<RVT,Vector<V,N,AV>>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RVT __cast__(const Vector<V,N,AV>& v) { return v; } } } #endif
<reponame>alexcurylo/drawkit-touch<filename>DrawKitTouch/source/drawkit/Code/DKStyleRegistry.h // // DKStyleRegistry.h /// DrawKit ©2005-2008 Apptree.net // // Created by graham on 15/03/2008. /// /// This software is released subject to licensing conditions as detailed in DRAWKIT-LICENSING.TXT, which must accompany this source file. // // not in iPhone SDK, should be left to .pch ...alex //#import <Cocoa/Cocoa.h> #import "DKCategoryManager.h" @class DKStyle; // options flags - control behaviour when styles from a document are merged with the registry typedef enum { kDKIgnoreUnsharedStyles = ( 1 << 0 ), // compatibility with old registry - styles with sharing off are ignored kDKReplaceExistingStyles = ( 1 << 1 ), // styles passed in replace those with the same key (doc -> reg) kDKReturnExistingStyles = ( 1 << 2 ), // styles in reg with the same keys are returned (reg -> doc) kDKAddStylesAsNewVersions = ( 1 << 3 ) // styles with the same keys are copied and registered again (reg || doc) } DKStyleMergeOptions; // values you can test for in result of compareStylesInSet: enum { kDKStyleNotRegistered = 0, kDKStyleIsOlder = 1, kDKStyleUnchanged = 2, kDKStyleIsNewer = 3 }; // class: @interface DKStyleRegistry : DKCategoryManager // retrieving the registry and styles + (DKStyleRegistry*) sharedStyleRegistry; + (DKStyle*) styleForKey:(NSString*) styleID; + (DKStyle*) styleForKeyAddingToRecentlyUsed:(NSString*) styleID; // registering a style + (void) registerStyle:(DKStyle*) aStyle; + (void) registerStyle:(DKStyle*) aStyle inCategories:(NSArray*) styleCategories; + (void) registerStylesFromArray:(NSArray*) styles inCategories:(NSArray*) styleCategories; + (void) registerStylesFromArray:(NSArray*) styles inCategories:(NSArray*) styleCategories ignoringDuplicateNames:(BOOL) ignoreDupes; + (void) unregisterStyle:(DKStyle*) aStyle; + (void) setNeedsUIUpdate; + (void) setStyleNotificationsEnabled:(BOOL) enable; // merging sets of styles read in with a document + (NSSet*) mergeStyles:(NSSet*) styles inCategories:(NSArray*) styleCategories options:(DKStyleMergeOptions) options mergeDelegate:(id) aDel; + (NSDictionary*) compareStylesInSet:(NSSet*) styles; // high-level data access + (NSArray*) registeredStyleKeys; + (NSData*) registeredStylesData; + (void) saveDefaults; + (void) loadDefaults; + (void) resetRegistry; #ifndef TARGET_OS_IPHONE + (void) registerSolidColourFillsFromListNamed:(NSString*) name asCategory:(NSString*) catName; + (void) registerSolidColourStrokesFromListNamed:(NSString*) name asCategory:(NSString*) catName; #endif TARGET_OS_IPHONE + (void) setShouldNotAddDKDefaultCategory:(BOOL) noDKDefaults; // getting a fully-managed menu for all styles, organised by category: #ifndef TARGET_OS_IPHONE + (NSMenu*) managedStylesMenuWithItemTarget:(id) target itemAction:(SEL) selector; #endif TARGET_OS_IPHONE // low-level instance methods - (NSString*) styleNameForKey:(NSString*) styleID; - (DKStyle*) styleForKey:(NSString*) styleID; - (NSSet*) stylesInCategories:(NSArray*) cats; - (NSString*) uniqueNameForName:(NSString*) name; - (NSArray*) styleNames; - (NSArray*) styleNamesInCategory:(NSString*) catName; - (BOOL) writeToFile:(NSString*) path atomically:(BOOL) atom; - (BOOL) readFromFile:(NSString*) path mergeOptions:(DKStyleMergeOptions) options mergeDelegate:(id) aDel; - (DKStyle*) mergeFromStyle:(DKStyle*) aStyle mergeDelegate:(id) aDel; - (void) removeAllStyles; - (void) setNeedsUIUpdate; - (void) styleDidChange:(NSNotification*) note; #ifndef TARGET_OS_IPHONE - (NSMenu*) managedStylesMenuWithItemTarget:(id) target itemAction:(SEL) selector; #endif TARGET_OS_IPHONE @end // default registry category names: extern NSString* kDKStyleLibraryStylesCategory; extern NSString* kDKStyleTemporaryDocumentCategory; extern NSString* kDKStyleRegistryDKDefaultsCategory; extern NSString* kDKStyleRegistryTextStylesCategory; // notifications extern NSString* kDKStyleRegistryDidFlagPossibleUIChange; extern NSString* kDKStyleWasRegisteredNotification; extern NSString* kDKStyleWasRemovedFromRegistryNotification; extern NSString* kDKStyleWasEditedWhileRegisteredNotification; // delegate informal protocol allows the delegate to decide which of a pair of styles should be used @interface NSObject (DKStyleRegistryDelegate) - (DKStyle*) registry:(DKStyleRegistry*) reg shouldReplaceStyle:(DKStyle*) regStyle withStyle:(DKStyle*) docStyle; @end @interface NSObject (StyleRegistrySubstitution) - (DKStyleRegistry*) applicationWillReturnStyleRegistry; @end /* The style registry is a singleton category manager instance that consolidates styles from a variety of sources into a single app-wide "database" of styles, organised into categories. Styles can come from these sources: 1. The application defaults, if the app is launched with no library preferences available (i.e. first run). 2. The styles library, which is the complete registry saved to disk (user prefs) at quit time. 3. A document, when it is opened. 4. A separate file containing just styles. 5. A new style being created and registered by the user as the app is used. ------------------------------------------------------------------------------------------------------------------------------------------------- The point of the registry is twofold: A. It permits the construction of a UI for accessing pre-built styles and applying them to objects in a drawing. By organising styles into categories, potentially large number of styles may be managed effectively. B. It tracks styles across any number of documents as they are created. For example if a document uses a particular registered style, when that document is reopened at a later date, the style can be recognised and linked to the same style in the registry. If the style has changed in the meantime so that there is a difference between the saved style and the currently registered version, the user can be offered the option to update the style in the document to match the registry, update the registry to match the document, or to re-register the style as a new version. Note the registry is not mandatory - an app using DK can use styles without registering them if it wishes. The advantage of the registry is that it permits styles to persist and be tracked across multiple documents, saving the user from having to redefine styles for every new graphic. ------------------------------------------------------------------------------------------------------------------------------------------------- In order for the registry to uniquely and positively identify a style, its unique ID is used as its key. The unique ID is assigned when the style first comes into existence and cannot be changed. It is a string representation of a UUID so is guaranteed unique. UUID's are not very user friendly and should never be exposed by an application's user interface. Thus a style also has an ordinary descriptive name which can be displayed in the UI. Such names are not guaranteed to be unique however, as the user is free to enter whatever name they wish. When a style is first registered the name may be changed to avoid a collision with an already registered style having the same name - this is done by appending 1, 2, 3 etc until the name doesn't collide. However this is just done to disambiguate the style for the user - it is not intended to guarantee uniqueness so that the name can be used as a key to the object. A user interface will want to use the ordinary names, but internally must be set up to use the unique ID or the object itself to avoid any confusion as to which style is actually being referred to. For example a menu of available styles could use the UUID or the object as the represented object of the menu item. DO NOT USE THE ORDINARY NAME AS A KEY. ------------------------------------------------------------------------------------------------------------------------------------------------- Locking. Styles in the registry are usually locked. This is to prevent accidental alteration of a style that may be being used across many documents. When a style is added to the registry, it should be unlocked (because the name might need to be automatically changed) but the registry will lock the style upon a successful operation. Styles in a document. Styles used in a document may or may not be registered. A user may never register a style, but still have many styles defined in a document. Such styles work normally and can be copied and pasted and shared between objects if set to do so - use of styles is not dependent in any way upon the registry. When the document is saved, a flag as to whether the style was registered or not is saved with it. When the document is opened again later, such flagged styles will be optionally reconnected to the style registry so that the actual style used is always the registered style, so if the style is updated, existing documents are offered the opportunity to use the updated version. As well as any user-defined categories, documents may wish to create a temporary category using the document's name which gives the user a way to quickly discover the complete set of registered styles used in a document. The category should be removed when the document is closed. DKDrawDocument implements this behaviour by default, so if your document class is based on it, your app can get this feature for free. ------------------------------------------------------------------------------------------------------------------------------------------------- Registering a style. The style registry performs the following steps: 1. It checks that the style is not already registered. If it is, it does no more. 2. It checks that the style is unlocked. If not, an exception is thrown. 3. It resolves the style's name so that there are no collisions with any existing style's name, and changes the style's name if needed. 4. It creates any new categories as requested (depends on the particular method used to register the style). If no specific categories are requested, the style is added to the default category. 5. It adds the style to the registry using its unique ID as the key. 6. It locks the style. ------------------------------------------------------------------------------------------------------------------------------------------------- Cut/Paste: cut and paste of styles works independently of the registry, including dealing with shared styles. See DKStyle for more info. */
<reponame>martmists-gh/BDSP #pragma once #include "il2cpp.h" bool FieldMistWork__CheckMistWeather (const MethodInfo* method_info); bool FieldMistWork__AvailableKiribarai (const MethodInfo* method_info); EnvironmentSettings_o* FieldMistWork__GetCurrentSetting (FieldMistWork_o* __this, const MethodInfo* method_info); bool FieldMistWork__get_IsEnable (FieldMistWork_o* __this, const MethodInfo* method_info); void FieldMistWork__Setup (FieldMistWork_o* __this, const MethodInfo* method_info); EnvironmentSettings_o* FieldMistWork__GetBaseSetting (FieldMistWork_o* __this, int32_t zoneId, const MethodInfo* method_info); void FieldMistWork__Update (FieldMistWork_o* __this, float deltaTime, const MethodInfo* method_info); void FieldMistWork__ChangeMist (FieldMistWork_o* __this, float target, float time, const MethodInfo* method_info); void FieldMistWork__CalcCurrentSetting (FieldMistWork_o* __this, const MethodInfo* method_info); void FieldMistWork__BlendSetting (FieldMistWork_o* __this, EnvironmentSettings_Parameters_o* paramA, EnvironmentSettings_Parameters_o* paramB, float weight, EnvironmentSettings_Parameters_o* refOutParam, const MethodInfo* method_info); void FieldMistWork__CreateMistEffectSetting (FieldMistWork_o* __this, const MethodInfo* method_info); void FieldMistWork__OverrideParameter (FieldMistWork_o* __this, EnvironmentSettings_Parameters_o* param, int32_t paramHeadIndex, const MethodInfo* method_info); void FieldMistWork___ctor (FieldMistWork_o* __this, const MethodInfo* method_info); float FieldMistWork___OverrideParameter_g__Get_15_0 (FieldMistWork___c__DisplayClass15_0_o* , const MethodInfo* method_info);
<reponame>daidi-double/_new_YWB<filename>YuWa/YuWa/Foundation/Custom Category/UserSession.h<gh_stars>0 // // UserSession.h // NewVipxox // // Created by 黄佳峰 on 16/8/31. // Copyright © 2016年 黄蜂大魔王. All rights reserved. // #import <Foundation/Foundation.h> @interface UserSession : NSObject @property (nonatomic,assign)NSInteger uid;//uid @property (nonatomic,copy)NSString * token; //用户登录后标识 @property (nonatomic,copy)NSString * account; //账户 @property (nonatomic,copy)NSString * password; //密码 @property (nonatomic,copy)NSString * hxPassword; //环信密码 @property (nonatomic,copy)NSString * inviteID; //邀请ID @property (nonatomic,copy)NSString * invite_code;//邀请码 @property (nonatomic,copy)NSString * logo;//头像 @property (nonatomic,copy)NSString * nickName;//昵称 @property (nonatomic,copy)NSString * sex;//性别 @property (nonatomic,copy)NSString * birthDay;//生日 @property (nonatomic,copy)NSString * local; //常驻地 @property (nonatomic,copy)NSString * personality; //个人签名 @property (nonatomic,copy)NSString * businessAgreement;//商务会员协议 @property (nonatomic,copy)NSString * agreement;//用户协议 @property (nonatomic,copy)NSString * attentionCount;//关注数 @property (nonatomic,copy)NSString * fans;//粉丝 @property (nonatomic,copy)NSString * praised;//被赞数 @property (nonatomic,copy)NSString * collected;//被收藏 @property (nonatomic,copy)NSString * aldumCount; //专辑个数 @property (nonatomic,copy)NSString * money; //钱 @property (nonatomic,copy)NSString * last_login_time; @property (nonatomic,copy)NSString * reg_time; @property (nonatomic,copy)NSString * status; @property (nonatomic,copy)NSString * email; @property (nonatomic,copy)NSString * sale_id; //note_nums album_nums comment_nums @property(nonatomic,strong)NSString*note_nums; //多少条笔记 @property(nonatomic,strong)NSString*album_nums; //多少个专辑 @property(nonatomic,strong)NSString*comment_nums; //多少条评论 @property(nonatomic,strong)NSString*today_money; //今日收益 今天到登录为止时候的介绍分红和商务分红相加的钱(不算积分分红)7天后才会结算这部分钱 @property (nonatomic,strong)NSNumber*isVIP;//是否是会员 1普通用户2销售 没有3商家了移除 @property (nonatomic,strong)NSString * bankName;//记录上次提现的银行卡 @property (nonatomic,strong)NSString * bankCard;//记录上次提现的银行卡号 //@property(nonatomic,copy)NSString * currency; //货币 //已经登录 @property(nonatomic,assign)BOOL isLogin; //是否登录 (这个要自己给他) @property (nonatomic,assign)NSInteger baobaoLV; //雨娃宝宝等级 @property (nonatomic,assign)NSInteger baobaoEXP; //宝宝的经验 @property (nonatomic,assign)NSInteger baobaoNeedEXP; //宝宝升级需要的经验 //记录环信是否登录成功,成功是 yes 失败是NO; @property (nonatomic, assign) BOOL isLoginHX; +(UserSession*)instance; //创建单例 +(void)clearUser; //退出登录 删除数据 + (void)saveUserLoginWithAccount:(NSString *)account withPassword:(NSString *)password; //save login data + (void)saveUserInfoWithDic:(NSDictionary *)dataDic;//save user data + (void)autoLoginRequestWithPragram:(NSDictionary *)pragram; @end
<reponame>ssathy2/Hakken // // DDDRightNavigationView.h // Hakken // // Created by sathyam on 3/31/15. // Copyright (c) 2015 dotdotdot. All rights reserved. // #import <UIKit/UIKit.h> #import "UIView+Utility.h" @class DDDRightNavigationView; typedef void(^ViewAnimationBlock)(DDDRightNavigationView *navigationView); @interface DDDRightNavigationView : UIControl @property (weak, nonatomic) IBOutlet UILabel *numberLabel; // sets the number of the navigation view with any custom animations. If the 'animated' param is YES but 'animationBlock' is nil then a default spring animation will be used. - (void)setNumber:(NSInteger)number animated:(BOOL)animated withCustomAnimations:(ViewAnimationBlock)animationBlock; - (void)setNumberViewHidden:(BOOL)hidden animated:(BOOL)animated; @end
#include <config.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <netcdf.h> #define SYSCMD "ncgen -o %s %s" #define SYSCMD2 "ncgen -v 2 -o %s %s" #define LAT "lat" #define LON "lon" #define LAH "lah" #define LOH "loh" #ifndef DEBUG #define DEBUG 0 #endif #ifdef FORTRANCAPS #define read_cdf_static READ_CDF_STATIC #define write_cdf_static WRITE_CDF_STATIC #endif #ifdef FORTRANDOUBLEUNDERSCORE #define cdf_update_stat cdf_update_stat__ #define free_static_malloc free_static_malloc__ #define cdf_wrt_hdr_stat cdf_wrt_hdr_stat__ #define write_cdf_static write_cdf_static__ #define cdf_retr_grid_stat cdf_retr_grid_stat__ #define cdf_retr_hdr_stat cdf_retr_hdr_stat__ #define read_cdf_static read_cdf_static__ #define open_cdf open_cdf__ #define dim_size_v3 dim_size_v3__ #define nstrncpy nstrncpy__ #define fstrncpy fstrncpy__ #endif #ifdef FORTRANUNDERSCORE #define cdf_update_stat cdf_update_stat_ #define free_static_malloc free_static_malloc_ #define cdf_wrt_hdr_stat cdf_wrt_hdr_stat_ #define write_cdf_static write_cdf_static_ #define cdf_retr_grid_stat cdf_retr_grid_stat_ #define cdf_retr_hdr_stat cdf_retr_hdr_stat_ #define read_cdf_static read_cdf_static_ #define open_cdf open_cdf_ #define dim_size_v3 dim_size_v3_ #define nstrncpy nstrncpy_ #define fstrncpy fstrncpy_ #endif #if(SIZEOF_SHORT==4) #define fint4 short #elif(SIZEOF_INT==4) #define fint4 int #elif(SIZEOF_LONG==4) #define fint4 long #endif /***************************************************************************** * CDF_UPDATE_STAT * Category Product Management * Group General Purpose Database * Module Update the LAPS netCDF static file * Purpose To coordinate the writing of static info into * the appropriate netCDF file: find the * appropriate location to write the grid, * and call the routine that does the writing. * * Designer/Programmer : <NAME> * Modifications : original 9/5/90 * adapted for new WRITELAPSDATA 1/93 <NAME> * adapted from CDF_UPDATE_LAPS for new * WRT_LAPS_STATIC 4/93 <NAME> * * Input : * s_field A character string identifying the field: * lat latitude of grid point * lon longitude of grid point * avg average elev MSL of grid box * std std dev of elev's in box * env avg + std * zin avg converted to mb pressure, * then mapped 1100=0 to 100=20 * gptr A pointer to the grid (including product and data * headers). * Output : * None * Globals : * NC_WRITE A flag used to open the netCDF file for writing * Returns : * 0 if successful * -1 if an error occurs ***************************************************************************/ #ifdef __STDC__ int cdf_update_stat (int i_cdfid,int i_varid, char *s_field,void *gptr, char *commnt, char *comm_ptr) #else int cdf_update_stat (i_cdfid, i_varid, s_field, gptr, commnt, comm_ptr) int i_cdfid; int i_varid; char *s_field; void *gptr; char *commnt; char *comm_ptr; #endif { int i_status, i_comid; long start[4], count[4], start_c[3], count_c[3]; if(DEBUG==1) printf( "cdf_update_stat:grid name = %s\n", s_field); /* turn off the error handling done by the netCDF routines */ ncopts = NC_VERBOSE; /* get the x and y dimension sizes */ count[0] = 1; count[1] = 1; count[2] = dim_size_v3 (i_cdfid, "y"); count[3] = dim_size_v3 (i_cdfid, "x"); /* construct the arrays needed by the netcdf write routine */ start[0] = 0; start[1] = 0; start[2] = 0; start[3] = 0; start_c[0] = 0; start_c[1] = 0; start_c[2] = 0; count_c[0] = 1; count_c[1] = 1; count_c[2] = strlen(comm_ptr); /* get the variable ids */ if(DEBUG==1) printf( "Data variable name = %s\n", s_field); if ((i_comid = ncvarid (i_cdfid, commnt)) == (-1)) return -1; /* write the grid to the netcdf file */ i_status = ncvarput (i_cdfid, i_varid, (const long *)start, (const long *)count, (void *)gptr); if (i_status == (-1)) { if(DEBUG==1) printf( "1 cdf_update_stat: error during cdf write %d %d\n",i_cdfid,i_varid); return -1; } else { i_status = ncvarput (i_cdfid, i_comid, (const long *)start_c, (const long *)count_c, (void *)comm_ptr); if (i_status == (-1)){ if(DEBUG==1) printf( "2 cdf_update_stat: error during cdf write\n"); }else{ if(DEBUG==1) printf( "cdf_update_stat: cdf write ok\n"); } } return i_status; } /************************************************************************* * FREE_STATIC_MALLOC * Category Product Management * Group General Purpose Database * Module Write Static Grid data * Purpose Frees memory mallocd within write_cdf_static * * Designer/Programmer : <NAME> * Modifications : original 7/97 * * Input: * prefix String variable mallocd in write_cdf_static * comm_var String variable mallocd in write_cdf_static * model String variable mallocd in write_cdf_static * asctime String variable mallocd in write_cdf_static * var String variable mallocd in write_cdf_static * comment String variable mallocd in write_cdf_static * fname String variable mallocd in write_cdf_static * Output: * none * Globals: * none * Returns: * none *****************************************************************************/ #ifdef __STDC__ void free_static_malloc(char *prefix, char *comm_var, char *model, char *asctime, char *var, char *comment, char *units, char *fname) #else void free_static_malloc(prefix, comm_var, model, asctime, var, comment, units, fname) char *prefix; char *comm_var; char *model; char *asctime; char *var; char *comment; char *units; char *fname; #endif { if(prefix != NULL) free(prefix); if(comm_var != NULL) free(comm_var); if (model != NULL) free(model); if(asctime != NULL) free(asctime); if(var != NULL) free(var); if(comment != NULL) free(comment); if(units != NULL) free(units); if(fname != NULL) free(fname); return; } /************************************************************************* * CDF_WRT_HDR_STAT * Category Product Management * Group General Purpose Database * Module Write header data * Purpose Write header data into netCDF static file. * * Designer/Programmer : <NAME> * Modifications : original 7/97 * * Input: * cdf_id netCDF id of open file to write to * n_grids Number of grids available in file * grid_spacing size of grid box in METERS * asctime Ascii time file was generated * model Model generating static data * Nx X dimension of data in file * Ny Y dimension of data in file * Dx delta X in km of grid * Dy delta Y in km of grid * LoV standard longitude * Latin1 first standard latitude * Latin2 second standard latitude * Center_lat latitude of domain center * Center_lon longitude of domain center * lli lower left (SW) i coordinate of domain * llj lower left (SW) j coordinate of domain * uri upper right (NE) i coordinate of domain * urj upper right (NE) j coordinate of domain * parent_id Domain number of parent within which current domain resides * ratio_2_parent Integer number of grid points minus 1 in current domain between * two grid points of parent domain * origin site where LAPS being run * map_proj map projection * Output: * none * Globals: * none * Returns: * status Returns status to calling subroutine **************************************************************************/ #ifdef __STDC__ int cdf_wrt_hdr_stat(int cdf_id, fint4 *n_grids, float *grid_spacing, char *asctime, int asc_len, char *model, fint4 *nx, fint4 *ny, float *dx, float *dy, float *lov, float *latin1, float *latin2, float *la1, float *lo1, float *la2, float *lo2, float *center_lat, float *center_lon, int wrfsi, fint4 *lli, fint4 *llj, fint4 *uri, fint4 *urj, fint4 *parent_id, fint4 *ratio_2_parent, char *origin, char *map_proj, double unixtime, fint4 *status) #else int cdf_wrt_hdr_stat(cdf_id, n_grids, grid_spacing, asctime, asc_len,model, nx, ny, dx, dy, lov, latin1, latin2, la1,lo1, la2, lo2, center_lat, center_lon, wrfsi, lli, llj, uri, urj, parent_id, ratio_2_parent, origin, map_proj, unixtime, status) int cdf_id; fint4 *n_grids; float *grid_spacing; char *asctime; int asc_len; char *model; fint4 *nx; fint4 *ny; float *dx; float *dy; float *lov; float *latin1; float *latin2; float *la1; float *lo1; float *la2; float *lo2; fint4 *center_lat; fint4 *center_lon; int wrfsi; fint4 *lli; fint4 *llj; fint4 *uri; fint4 *urj; fint4 *parent_id; fint4 *ratio_2_parent; char *origin; char *map_proj; double unixtime; fint4 *status; #endif { int i_varid; long start[1], edges[1]; long start_map[2], edges_map[2]; short nx_in, ny_in; const long zero = 0L; /* store n_grids */ if ((i_varid = ncvarid (cdf_id, "n_grids")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)n_grids); /* store imax */ if ((i_varid = ncvarid (cdf_id, "imax")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)nx); /* store jmax */ if ((i_varid = ncvarid (cdf_id, "jmax")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)ny); /* store grid_spacing */ if ((i_varid = ncvarid (cdf_id, "grid_spacing")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)grid_spacing); start[0] = 0; /* store asctime */ if(DEBUG==1) printf("cdf_wrt_hdr_stat: C asc_len %d\n",asc_len); edges[0] = asc_len; if ((i_varid = ncvarid (cdf_id, "asctime")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, (const long *)start, (const long *)edges, (void *)asctime); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 1 %d\n",edges[0]); /* store model */ edges[0] = strlen(model); if ((i_varid = ncvarid (cdf_id, "process_name")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)model); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 1a %d %s\n",edges[0],model); edges[0] = 1; /* store Nx */ if ((i_varid = ncvarid (cdf_id, "Nx")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } nx_in = (short)(*nx); ncvarput(cdf_id, i_varid, start, edges, (void *)&nx_in); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 2 %d\n",edges[0]); /* store Ny */ if ((i_varid = ncvarid (cdf_id, "Ny")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ny_in = (short)*ny; ncvarput(cdf_id, i_varid, start, edges, (void *)&ny_in); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 3 %d\n",edges[0]); /* store Dx */ if ((i_varid = ncvarid (cdf_id, "Dx")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)dx); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 4 %d\n",edges[0]); /* store Dy */ if ((i_varid = ncvarid (cdf_id, "Dy")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)dy); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 5 %d\n",edges[0]); /* store LoV */ if ((i_varid = ncvarid (cdf_id, "LoV")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)lov); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 8 %d\n",edges[0]); /* store Latin1 */ if ((i_varid = ncvarid (cdf_id, "Latin1")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)latin1); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 9 %d\n",edges[0]); /* store Latin2 */ if ((i_varid = ncvarid (cdf_id, "Latin2")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)latin2); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 10 %d\n",edges[0]); /* store La1 */ if ((i_varid = ncvarid (cdf_id, "La1")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)la1); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 6 %d\n",edges[0]); /* store Lo1 */ if ((i_varid = ncvarid (cdf_id, "Lo1")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)lo1); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 7 %d\n",edges[0]); /* store La2 */ if ((i_varid = ncvarid (cdf_id, "La2")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)la2); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 6 %d\n",edges[0]); /* store Lo2 */ if ((i_varid = ncvarid (cdf_id, "Lo2")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)lo2); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 7 %d\n",edges[0]); /* store center_lat */ if ((i_varid = ncvarid (cdf_id, "center_lat")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)center_lat); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 10 %d\n",edges[0]); /* store center_lon */ if ((i_varid = ncvarid (cdf_id, "center_lon")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)center_lon); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 10 %d\n",edges[0]); /* write out 6 extra variables if domain is wrfsi */ if (wrfsi == 1) { /* store lower left i -> lli*/ if ((i_varid = ncvarid (cdf_id, "SW_i")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)lli); /* store lower left j -> llj*/ if ((i_varid = ncvarid (cdf_id, "SW_j")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)llj); /* store upper right i -> uri*/ if ((i_varid = ncvarid (cdf_id, "NE_i")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)uri); /* store upper right j -> urj*/ if ((i_varid = ncvarid (cdf_id, "NE_j")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)urj); /* store parent_id*/ if ((i_varid = ncvarid (cdf_id, "Parent_ID")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)parent_id); /* store ratio_2_parent*/ if ((i_varid = ncvarid (cdf_id, "Ratio_to_Parent")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)ratio_2_parent); } /* store valtime */ if ((i_varid = ncvarid (cdf_id, "valtime")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)&unixtime); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 11 %d\n",edges[0]); /* store reftime */ if ((i_varid = ncvarid (cdf_id, "reftime")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)&unixtime); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 12 %d\n",edges[0]); /* store origin */ edges[0] = strlen(origin); if ((i_varid = ncvarid (cdf_id, "origin_name")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)origin); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 13 %d\n",edges[0]); /* store map_proj */ start_map[0] = 0; start_map[1] = 0; edges_map[0] = 1; edges_map[1] = strlen(map_proj); if ((i_varid = ncvarid (cdf_id, "grid_type")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start_map, edges_map, (void *)map_proj); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 14 %d %d\n",edges_map[0],edges_map[1]); return 0; } /************************************************************************* * WRITE_CDF_STATIC * Category Product Management * Group General Purpose Database * Module Write Grid data * Purpose Write grid data into netCDF static file. * * Designer/Programmer : <NAME> * Modifications : original 4/93 * * Input: * filname NetCDF filename to open * asctime Ascii time of file * var Array of LAPS variables to write out * comment Comments for each level to write * imax X dimension of data in file * jmax Y dimension of data in file * n_grids Number of grids available in file & * dimension of the VAR and COMMENT * in the calling program * data 3D grid containing data to write * zin Grid for AVS applications * model Model generating static data * grid_spacing size of grid box in M * Output: * status Returns status to calling subroutine * Globals: * none * Returns: * none *****************************************************************************/ #ifdef __STDC__ void write_cdf_static(char *filname, fint4 *s_length, char *f_asctime, fint4 *f_asc_len, char *f_cdl_dir, fint4 *cdl_len, char *f_var, fint4 *var_len, char *f_comment, fint4 *com_len, char *f_ldf, fint4 *ldf_len, fint4 *imax, fint4 *jmax, fint4 *n_grids, fint4 *nx_lp, fint4 *ny_lp, float *data, char *f_model, float *grid_spacing, float *dx, float *dy, float *lov, float *latin1, float *latin2, float *la1, float *lo1, float *la2, float* lo2, float *center_lat, float *center_lon, fint4 *lli, fint4 *llj, fint4 *uri, fint4 *urj, fint4 *parent_id, fint4 *ratio_2_parent, char *f_origin, fint4 *origin_len, char *f_map_proj, fint4 *map_len, fint4 *unixtime, fint4 *status) #else void write_cdf_static(filname, s_length, f_asctime, f_asc_len, f_cdl_dir, cdl_len, f_var, var_len, f_comment, com_len, f_ldf, ldf_len, imax, jmax, n_grids, nx_lp, ny_lp, data, f_model, grid_spacing, dx, dy, lov, latin1, latin2, la1,lo1,la2,lo2, center_lat, center_lon, lli, llj, uri, urj, parent_id, ratio_2_parent, f_origin, origin_len, f_map_proj, map_len, unixtime, status) char *filname; fint4 *s_length; char *f_asctime; fint4 *f_asc_len; char *f_cdl_dir; fint4 *cdl_len; char *f_var; fint4 *var_len; char *f_comment; fint4 *com_len; char *f_ldf; fint4 *ldf_len; fint4 *imax; fint4 *jmax; fint4 *n_grids; fint4 *nx_lp; fint4 *ny_lp; float *data; char *f_model; float *grid_spacing; float *dx; float *dy; float *lov; float *latin1; float *latin2; float *la1; float *lo1; float *la2; float *lo2; fint4 *center_lat; fint4 *center_lon; fint4 *lli; fint4 *llj; fint4 *uri; fint4 *urj; fint4 *parent_id; fint4 *ratio_2_parent; char *f_origin; fint4 *origin_len; char *f_map_proj; fint4 *map_len; fint4 *unixtime; fint4 *status; #endif { char *prefix, *comm_var, *model, *asctime, *fname, *map_proj; char *var, *comment, *ldf, *p_var, *pf_var, *p_com, *pf_com; char *origin, *units; int mod_len, asc_len, c_var_len, c_com_len, wrfsi; int out_file, istat, i_varid, i, process_vr, count; int lat_index, lon_index, hdr_status; int xdimid, ydimid; static char *syscmd, *cdlfile; double d_unixtime; long nx_cdl, ny_cdl; /* turn off the error handling done by the netCDF routines */ ncopts = NC_VERBOSE; /* malloc space for c-strings */ c_var_len = *var_len + 1; prefix = malloc(c_var_len * sizeof(char)); comm_var = malloc((c_var_len+8) * sizeof(char)); mod_len = strlen(f_model); model = malloc(((mod_len)+1) * sizeof(char)); asc_len = *f_asc_len; asctime = malloc(((asc_len)+1) * sizeof(char)); map_proj = malloc(((*map_len)+1) * sizeof(char)); origin = malloc(((*origin_len)+1) * sizeof(char)); var = malloc(c_var_len * (*n_grids) * sizeof(char)); c_com_len = *com_len + 1; comment = malloc(c_com_len * (*n_grids) * sizeof(char)); fname = malloc(((*s_length)+1) * sizeof(char)); /* convert fortran string f_var to c string var */ for (i = 0; i < *n_grids; i++) { p_var = var + (i * c_var_len); pf_var = f_var + (i * (*var_len)); nstrncpy(p_var, pf_var, *var_len); downcase_c(p_var,p_var); p_com = comment + (i * c_com_len); pf_com = f_comment + (i * (*com_len)); fstrncpy(p_com,pf_com, *com_len); } fstrncpy(model,f_model,mod_len); fstrncpy(asctime,f_asctime,asc_len); fstrncpy(map_proj,f_map_proj,*map_len); fstrncpy(origin,f_origin,*origin_len); /* convert fortran file_name into C fname */ nstrncpy(fname,filname,s_length); /* allocate space for syscmd and cdlfile and fill up */ /* cdl file contains domain name + ".cdl\0" */ cdlfile = malloc(((*cdl_len)+(*ldf_len)+5) * sizeof(char)); nstrncpy(cdlfile,f_cdl_dir,*cdl_len); ldf = malloc(((*ldf_len) + 1) * sizeof(char)); nstrncpy(ldf,f_ldf,*ldf_len); strcat(cdlfile,ldf); /* determine if ldf is nest7grid or wrfsi */ if (strncmp(ldf,"wrfsi", 5) == 0) { wrfsi = 1; } else { wrfsi = 0; } free(ldf); strcat(cdlfile,".cdl"); *cdl_len = strlen(cdlfile); /* SYSCMD contains "ncgen -o %s %s\0" which is 16 char, cdlfile, and fname + 10 extra */ if (nx_cdl * ny_cdl > 4000000) { syscmd = malloc((strlen(SYSCMD2)+*cdl_len+*s_length+10) * sizeof(char)); sprintf(syscmd,SYSCMD2, fname, cdlfile); } else { syscmd = malloc((strlen(SYSCMD)+*cdl_len+*s_length+10) * sizeof(char)); sprintf(syscmd,SYSCMD, fname, cdlfile); } free(cdlfile); /* create output file */ #ifdef SMS *status = pcl_system(syscmd); #else system(syscmd); #endif free(syscmd); out_file = ncopen(fname,NC_WRITE); if (out_file == -1) { *status = -2; /* error in file creation */ free_static_malloc(prefix, comm_var, model, asctime, var, comment, NULL, fname); return; } /* get x and y dimensions from output file and make sure they are the same as nx_lp and ny_lp */ xdimid = ncdimid(out_file,"x"); ydimid = ncdimid(out_file,"y"); ncdiminq(out_file,xdimid, (char *) 0, &nx_cdl); ncdiminq(out_file,ydimid, (char *) 0, &ny_cdl); if ((nx_cdl == *nx_lp) && (ny_cdl == *ny_lp)) { } else { *status = -6; /* nest7grid.cdl & nest7grid.parms disagree */ free_static_malloc(prefix, comm_var, model, asctime, var, comment, NULL, fname); return; } /* check to see if we're working with LAPS...if we are, la1, lo1, la2, lo2 will all be -999.0 */ /* if they're filled, its wrfsi and they are passed in */ if ((*la1==-999.0)&&(*lo1==-999.0)&&(*la2==-999.0)&&(*lo2==-999.0)) { /* get La1 and Lo1 (SW corner lat and lon) and La2 and Lo2 (NE corner lat and lon) from data array */ lat_index = -1; lon_index = -1; for (i = 0; i < *n_grids; i++) { p_var = var + (i * c_var_len); if (strcmp(p_var, LAT) == 0) lat_index = i; if (strcmp(p_var, LON) == 0) lon_index = i; } if (lat_index == (-1)) { *la1 = -999.99; *la2 = -999.99; } else { *la1 = *(data + (lat_index*(*imax)*(*jmax))); *la2 = *(data + ((lat_index+1)*(*imax)*(*jmax)) - 1); } if (lon_index == (-1)) { *lo1 = -999.99; *lo2 = -999.99; } else { *lo1 = *(data + (lon_index*(*imax)*(*jmax))); *lo2 = *(data + ((lon_index+1)*(*imax)*(*jmax)) - 1); if (*lo1 < 0.0) *lo1 = 360.0 + *lo1; if (*lo2 < 0.0) *lo2 = 360.0 + *lo2; } } /* write header info to output file */ d_unixtime = (double)*unixtime; hdr_status = cdf_wrt_hdr_stat(out_file, n_grids, grid_spacing, asctime, asc_len,model, imax, jmax, dx, dy, lov, latin1, latin2,la1,lo1,la2,lo2, center_lat, center_lon, wrfsi, lli, llj, uri, urj, parent_id, ratio_2_parent, origin, map_proj,d_unixtime, status); if (hdr_status != 0) { *status = hdr_status; free_static_malloc(prefix, comm_var, model, asctime, var, comment, NULL, fname); return; } /* write data to grid and write out comment */ count = 0; for (i = 0; i < *n_grids; i++) { p_var = var + (i * c_var_len); p_com = comment + (i * c_com_len); strcpy(prefix,p_var); strcpy(comm_var,p_var); strcat(comm_var,"_comment"); if ((i_varid = ncvarid (out_file , prefix)) == (-1)) { printf("write_cdf_static: no variable %s in file.\n", prefix); } else { istat = cdf_update_stat(out_file,i_varid, prefix, (void *)(data + (i*(*imax)*(*jmax))), comm_var,p_com); if (istat == -1) { *status = -4; printf("1st case \n"); ncclose(out_file); return; } count++; } } *status = count; /* returns number of grids written */ ncclose(out_file); return; } /***************************************************************************** * CDF_RETR_GRID_STAT * Category Product Management * Group General Purpose Database * Module Retrieve Grid Data * Purpose To retrieve a specified grid from a netcdf file * * Designer/Programmer : <NAME> * Modifications : original 9/12/90 * modified for new READLAPSDATA 1/93 <NAME> * * Input : * i_cdfid NetCDF file id for file to be read * s_field A character string identifying the field * gptr Pointer to location in data array to write data. * cptr Pointer to location in data array to write comments * uptr Pointer to location in data array to write units. * Output : * none * Globals: * NC_NOWRITE A NetCDF global that opens the NetCDF file for reading * only. * Returns: * 0 if normal return * -1 if an error occurs *****************************************************************************/ #ifdef __STDC__ int cdf_retr_grid_stat(int i_cdfid, int i_varid, char *s_field, float *gptr, char *cptr, int c_com_len, char *uptr, int c_unit_len) #else int cdf_retr_grid_stat(i_cdfid, i_varid, s_field, gptr, cptr, c_com_len, uptr, c_unit_len) int i_cdfid; int i_varid; char *s_field; float *gptr; char *cptr; int c_com_len; char *uptr; int c_unit_len; #endif { int i_status, j; long start[4],count[4],start_c[3],count_c[3]; char var_name[13]; /* printf("cdf_ret_grd: level = %d fctime = %d field = %s\n", i_level, i_fctime, s_field); */ /* turn off the error handling done by the netCDF routines */ ncopts = NC_VERBOSE; /* get the x and y dimension sizes */ count[0] = 1; count[1] = 1; count[2] = dim_size_v3 (i_cdfid, "y"); count[3] = dim_size_v3 (i_cdfid, "x"); start[0] = 0; start[1] = 0; start[2] = 0; start[3] = 0; /* read the grid from the netcdf file */ i_status = ncvarget (i_cdfid, i_varid, (const long *)start, (const long *)count, (void *)gptr); if (i_status == (-1)) { printf("cdf_retrieve_laps: error retrieving data %s grid.\n", s_field); return -1; } /* retrieve units */ i_status = ncattget (i_cdfid, i_varid, "LAPS_units", uptr); if (i_status == (-1)) { printf("cdf_retrieve_laps: error retrieving LAPS_units.\n"); return -1; } if(DEBUG==1) printf("cdf_retrieve_laps: units >%s<\n",uptr); /* setup to read the comment from the netcdf file */ sprintf(var_name, "%s%s", s_field, "_comment"); if ((i_varid = ncvarid (i_cdfid, var_name)) == (-1)) { printf("cdf_retrieve_laps: no comment field available.\n"); return -1; } /* construct the arrays needed to read the grid */ start_c[0] = 0; start_c[1] = 0; start_c[2] = 0; count_c[0] = 1; count_c[1] = 1; count_c[2] = c_com_len; i_status = ncvarget (i_cdfid, i_varid, (const long *)start_c, (const long *)count_c, (void *)cptr); if (i_status == (-1)) { printf("cdf_retrieve_laps: error retrieving comment.\n"); return -1; } /* normal return */ return 0; } /***************************************************************************** * CDF_RETR_HDR_STAT * Category Product Management * Group General Purpose Database * Module Retrieve Static Grid * Purpose To retrieve header info from a netcdf file * * Designer/Programmer : <NAME> * Modifications : original 4/93 * * Input : * i_cdfid NetCDF file id for file to be read * Output : * imaxn number of x gridpoints * jmaxn number of y gridpoints * kmaxn number of grids in the file * laps_dom_file name of laps domain for this file * Globals: * NC_NOWRITE A NetCDF global that opens the NetCDF file for * reading only. * Returns: * -1 if an error occurs *****************************************************************************/ #ifdef __STDC__ int cdf_retr_hdr_stat(int i_cdfid,fint4 *imaxn, fint4 *jmaxn, fint4 *n_grids_n, float *grid_spacing_n) #else int cdf_retr_hdr_stat(i_cdfid,imaxn,jmaxn,n_grids_n,grid_spacing_n) int i_cdfid; fint4 *imaxn; fint4 *jmaxn; fint4 *n_grids_n; float *grid_spacing_n; #endif { int i_status, i_varid, i, temp, str_len; long mindex[1], start[1], count_asc[1], count_long[1]; static char c_ver[5]; char *t_ptr; /* turn off the error handling done by the netCDF routines */ ncopts = NC_VERBOSE; mindex[0] = 0; start[0] = 0; count_asc[0] = 18; count_long[0] = 132; /* get the data variable id */ if(DEBUG==1) printf( "cdf_read_grid: data variable name = %s\n", "imax"); if ((i_varid = ncvarid (i_cdfid, "imax")) == (-1)) return -1; /* read the var from the netcdf file */ i_status = ncvarget1 (i_cdfid, i_varid, (const long *)mindex, (void *)imaxn); if (i_status == (-1)) return -1; /* get the data variable id */ if(DEBUG==1) printf( "cdf_read_grid: data variable name = %s\n", "jmax"); if ((i_varid = ncvarid (i_cdfid, "jmax")) == (-1)) return -1; /* read the var from the netcdf file */ i_status = ncvarget1 (i_cdfid, i_varid, (const long *)mindex, (void *)jmaxn); if (i_status == (-1)) return -1; /* get the data variable id */ if(DEBUG==1) printf( "cdf_read_grid: data variable name = %s\n", "n_grids"); if ((i_varid = ncvarid (i_cdfid, "n_grids")) == (-1)) return -1; /* read the var from the netcdf file */ i_status = ncvarget1 (i_cdfid, i_varid, (const long *)mindex, (void *)n_grids_n); if (i_status == (-1)) return -1; /* get the data variable id */ if(DEBUG==1) printf( "cdf_read_grid: data variable name = %s\n", "grid_spacing"); if ((i_varid = ncvarid (i_cdfid, "grid_spacing")) == (-1)) return -1; /* read the var from the netcdf file */ i_status = ncvarget1 (i_cdfid, i_varid, (const long *)mindex, (void *)grid_spacing_n); if (i_status == (-1)) return -1; /* normal return */ return 0; } /************************************************************************* * READ_CDF_STATIC * Category Product Management * Group General Purpose Database * Module write_cdf-Read_cdf_file * Purpose Read LAPS data from netCDF format static file. * * Designer/Programmer : <NAME> * Modifications : original 4/93 * * Input: * filname NetCDF filename to open * s_length length of the filname string * f_var Array of static variables to retrieve * var_len length of one f_var string * f_comment Array to hold comment info retrieved * com_len length of one f_comment string * f_units Array to hold units info retrieved * unit_len length of one f_units string * imax Expected X dimension of data * jmax Expected Y dimension of data * n_grids Dimension of the f_var, comment, * data 3D grid containing data requested * otherwise contains 0 * and units arrays in the calling program * Output: * imax_n Actual X dimension of data in file * jmax_n Actual Y dimension of data in file * status Returns status to calling subroutine * Globals: * none * Returns: * count of requested variables that were not retrieved *************************************************************************/ #ifdef __STDC__ void read_cdf_static(char *filname, fint4 *s_length,char *f_var, fint4 *var_len, char *f_comment, fint4 *com_len, char *f_units,fint4 *unit_len, fint4 *imax,fint4 *jmax, fint4 *n_grids,float *data,float *grid_spacing, fint4 *no_laps_diag,fint4 *status) #else void read_cdf_static(filname,s_length,f_var,var_len,f_comment,com_len, f_units,unit_len,imax,jmax, n_grids,data, grid_spacing,no_laps_diag,status) char *filname; fint4 *s_length; char *f_var; int *var_len; char *f_comment; int *com_len; char *f_units; int *unit_len; fint4 *imax; fint4 *jmax; fint4 *n_grids; float *data; float *grid_spacing; fint4 *no_laps_diag; fint4 *status; #endif { /*char model[132], asctime[18], origin[132], version[5]; */ char *var, *comment, *units, *prefix, *fname; char *p_var, *pf_var, *p_com, *pf_com, *p_unit, *pf_unit; char *comm_var, *model, *asctime; float *p_data; int istat, i, j, unconv_var, process_vr, cdfid, varid; int c_var_len, c_com_len, c_unit_len, s_len; fint4 imaxn, jmaxn, n_grids_n; /* turn off the error handling done by the netCDF routines */ ncopts = NC_VERBOSE; /* malloc space for c-strings */ c_var_len = *var_len + 1; prefix = malloc(c_var_len * sizeof(char)); var = malloc(c_var_len * (*n_grids) * sizeof(char)); c_com_len = *com_len + 1; comment = calloc(c_com_len * (*n_grids), sizeof(char)); c_unit_len = *unit_len + 1; units = calloc(c_unit_len * (*n_grids), sizeof(char)); fname = malloc(((*s_length)+1) * sizeof(char)); /* null out arrays for units,comment before using */ /* convert fortran string f_var to c string var and downcase */ for (i = 0; i < *n_grids; i++) { p_unit = units + (i * c_unit_len); (*p_unit) = '\0'; p_com = comment + (i * c_com_len); (*p_com) = '\0'; p_var = var + (i * c_var_len); pf_var = f_var + (i * (*var_len)); nstrncpy(p_var, pf_var, *var_len); downcase_c(p_var,p_var); } /* convert fortran filname into C fname */ nstrncpy(fname,filname,s_length); /* open file for reading */ cdfid = open_cdf(NC_NOWRITE,fname,no_laps_diag); if (cdfid == -1) { *status = -1; /* error opening file */ free_static_malloc(prefix, NULL, NULL, NULL, var, comment, units, fname); return; } /* get header info */ istat = cdf_retr_hdr_stat(cdfid,&imaxn,&jmaxn,&n_grids_n, grid_spacing); if (istat == -1) { *status = -5; ncclose(cdfid); free_static_malloc(prefix, NULL, NULL, NULL, var, comment, units, fname); return; } if(DEBUG==1) printf("read_cdf_static: %d %d %d %d %d %d\n", imaxn,jmaxn,n_grids_n,*imax,*jmax,*n_grids); if (imaxn > *imax || jmaxn > *jmax ) { *status = -3; ncclose(cdfid); free_static_malloc(prefix, NULL, NULL, NULL, var, comment, units, fname); return; } unconv_var = 0; for (i = 0; i < *n_grids; i++) { p_var = var + (i * c_var_len); p_com = comment + (i * c_com_len); p_unit = units + (i * c_unit_len); p_data = data + (i*(*imax)*(*jmax)); strcpy(prefix,p_var); if ((varid = ncvarid (cdfid , prefix)) == (-1)) { printf("write_cdf_static: no variable %s in file.\n", prefix); unconv_var += 1; } else { /* if(DEBUG==1) printf("b write_cdf_static: >%s<>%s<\n",p_unit,units[i * c_unit_len]); */ istat = cdf_retr_grid_stat(cdfid,varid,prefix,p_data, p_com,c_com_len,p_unit, c_unit_len); if(DEBUG==1) printf("a write_cdf_static: %d %d >%s< >%s< %d >%s< %d \n", cdfid,varid,prefix, p_com,c_com_len,p_unit, c_unit_len); if (istat == -1) { *status = -4; printf("2nd case \n"); ncclose(cdfid); free_static_malloc(prefix, NULL, NULL, NULL, var, comment, units, fname); return; } } } ncclose(cdfid); for (i = 0; i < *n_grids; i++) { p_com = comment + (i * c_com_len); pf_com = f_comment + (i * (*com_len)); s_len = strlen(p_com); strncpy(pf_com, p_com, s_len); pf_com += s_len; if (s_len < (*com_len)) { for ( j = 0; j < (*com_len - s_len); j++) { *pf_com = ' '; pf_com++; } } p_unit = units + (i * c_unit_len); pf_unit = f_units + (i * (*unit_len)); s_len = strlen(p_unit); strncpy(pf_unit, p_unit, s_len); pf_unit += s_len; if (s_len < (*unit_len)) { for ( j = 0; j < (*unit_len - s_len); j++) { *pf_unit = ' '; pf_unit++; } } } free_static_malloc(prefix, NULL, NULL, NULL, var, comment, units, fname); *status = unconv_var; return; }
#include <pthread.h> // for pthread_create, pthread_join, pthread_exit #include <stdio.h> // for printf #include <stdlib.h> // for exit #define NITER 1000000 pthread_mutex_t mutex; int count = 0; void * Count(void * a) { int i, tmp; for(i = 0; i < NITER; i++) { pthread_mutex_lock( &mutex ); tmp = count; /* copy the global count locally */ tmp = tmp+1; /* increment the local copy */ count = tmp; /* store the local value into the global count */ pthread_mutex_unlock( &mutex ); } } int main(int argc, char * argv[]) { pthread_t tid1, tid2; pthread_mutex_init( & mutex, NULL ); if(pthread_create(&tid1, NULL, Count, NULL)) { printf("\n ERROR creating thread 1"); exit(1); } if(pthread_create(&tid2, NULL, Count, NULL)) { printf("\n ERROR creating thread 2"); exit(1); } if(pthread_join(tid1, NULL)) /* wait for the thread 1 to finish */ { printf("\n ERROR joining thread"); exit(1); } if(pthread_join(tid2, NULL)) /* wait for the thread 2 to finish */ { printf("\n ERROR joining thread"); exit(1); } if (count < 2 * NITER) printf("\n BAD! count is [%d], should be %d\n", count, 2*NITER); else printf("\n OK! count is [%d]\n", count); pthread_exit(NULL); }
<reponame>bianhaoyi/necache /* * twemcache - Twitter memcached. * Copyright (c) 2012, Twitter, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Twitter 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 <COPYRIGHT HOLDER> 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 _MC_THREAD_H_ #define _MC_THREAD_H_ #include <semaphore.h> #include <pthread.h> #include <mc_slabs.h> #include <mc_stats.h> #include <mc_connection.h> /* A mapping from a member to its key value in pthread */ struct thread_key { pthread_key_t stats_mutex; /* stats lock */ pthread_key_t stats_thread; /* thread stats */ pthread_key_t stats_slabs; /* slab stats */ pthread_key_t kbuf; /* klog buffer */ }; typedef void * (*thread_func_t)(void *); struct thread_worker { pthread_t tid; /* thread id */ struct event_base *base; /* libevent handle this thread uses */ struct event notify_event; /* listen event for notify pipe */ int notify_receive_fd; /* receiving end of notify pipe */ int notify_send_fd; /* sending end of notify pipe */ struct conn_q new_cq; /* new connection q */ cache_t *suffix_cache; /* suffix cache */ pthread_mutex_t *stats_mutex; /* lock for stats update/aggregation */ struct stats_metric *stats_thread; /* per-thread thread-level stats */ struct stats_metric **stats_slabs; /* per-thread slab-level stats */ struct kbuf *kbuf; /* per-thread klog buffer */ }; /* * Aggregator model: * * The stats aggregator thread periodically wakes itself up and collects * collects stats from all worker threads. * * Clients can collect stats by sending 'stats' command to a twemcache * server and get replies in pretty much the same format as before. But * data are obtained from the aggregator rather than collected on-the-fly. * * Note that update granularity is the same as aggregation interval. This * may break some tests which rely on instant stats update, our in-house * python tests factor this in, and should pass on all future versions. * * Semaphore: * * Because now workers can process stats commands while aggregator is updating, * a semaphore is utilized to prevent workers from getting inconsistent data * (imagine the aggregator has flushed half of its metrics before aggregation * when a stats query command comes in). On the other hand, we don't want to * discourage concurrent queries if they are all reads, therefore a semaphore * instead of a mutex. * * Configuration: * * aggregation interval: settings.stats_interval * - default: 0.1s, not much overhead with this value * (twctop.rb pulls data every 1 or 2 seconds) */ struct thread_aggregator { pthread_t tid; /* thread id */ struct event_base *base; /* libevent handle for this thread */ struct event ev; /* event object */ sem_t stats_sem; /* rw sempahore */ struct timeval stats_ts; /* aggregation timestamp */ struct stats_metric *stats_thread; /* aggregated thread-level stats */ struct stats_metric **stats_slabs; /* aggregated slab-level stats */ struct stats_slab_const stats_slabs_const[SLABCLASS_MAX_IDS]; }; /* * The command logger (klogger) model: * * klogger periodically wakes itself up through libevent, * and collects/logs command logs from all worker threads. * * Configuration: * collect interval: settings.klog_intvl * - default: 1ms, the structure is lockless so we can afford to wake up often * local log file: settings.klog_name * - default: NULL */ struct thread_klogger { pthread_t tid; /* unique ID of this thread */ struct event_base *base; /* libevent handle for this thread */ struct event ev; /* event object */ }; void *thread_get(pthread_key_t key); rstatus_t thread_init(struct event_base *main_base); void thread_deinit(void); rstatus_t thread_dispatch(int sd, conn_state_t state, int ev_flags, int udp); #endif
#ifndef _EXT_PROTOCOL_H_ #define _EXT_PROTOCOL_H_ #if defined(__cplusplus) extern "C" { #endif #define PROTOCOL_API_VERSION 1 typedef enum { extStreamTypeMpegTS = 0, extStreamTypeMpegPS = 1, }extStreamType_e; #define EXT_STATUS_OK 0 /** * Error opening media */ #define EXT_STATUS_OPEN_ERROR -1 /** * Read error */ #define EXT_STATUS_READ_ERROR -2 /** * End of stream while reading */ #define EXT_STATUS_EOS -3 /** * Bad argument */ #define EXT_STATUS_BAD_ARGUMENT -4 typedef struct ext_protocol ext_protocol_t; /** * Handle to the opened instance of the protocol. */ typedef void* ProtocolHandle; struct ext_protocol { /** * null-terminated string with protocol name(identifier). */ char ident[64]; /** * Some private data to be filled and used by the protocol. */ void * private_data; /** * Implementation version. */ int version; /** * Open stream via protocol. * * @param e - pointer to protocol * @param pHandle - handler to opened instatnce of protocol. * Will be used with all operations applied to opened instance. * In case of error *pHandle should be filled with NULL. * otherwise - with opened handle. * @param url - content URL to be played * @param extra_data - some extra_data * * @return 0 if success * error code otherwise. */ int (*open) (ext_protocol_t *e, ProtocolHandle* pHandle, const char *url); /** * Read data from stream. * @param handle - protocol instance handle * * @return number of bytes read: * 0 - no data received try again * <0 - error code. @See EXT_STATUS_XXX */ int (*read) (ProtocolHandle handle, char *buf, int buflen); /** * Close stream. * @param handle - protocol instance handle */ void (*close) (ProtocolHandle handle); /** * Send command to ext. protocol * This function is always called from other thread relative to calls of open,read,setPosTime,... * @param e - pointer to protocol * @param cmd - command to be executed. * @param params - command params. * * @return result of command execution allocated by malloc. * free() it after use. */ char * (*command) (ext_protocol_t *e, const char *cmd, const char *params); /** * Send event to protocol * @param e - pointer to protocol * @param event_id - event code. */ void (*event) (ext_protocol_t *e, unsigned long event_id); /** * Seek to specified time (in ms) in stream. * @param handle - protocol instance handle * @param posInMs - position in media in ms since start of media * always from 0 to duration (posInMs is not related to startTime) * * @return if success - >= 0 - success, returns stream position in ms * otherwise - < 0 - error */ int (*setPosTime) (ProtocolHandle handle, unsigned int posInMs); /** * Get timestamp of media content start point in ms. * * @param handle - protocol instance handle * * @return start time of the stream in ms if known * otherwise - 0. */ unsigned int(*getStartTime) (ProtocolHandle handle); /** * Get the duration of whole media in ms. * * @param handle - protocol instance handle * * @return duration of the stream in ms if known * otherwise - 0. */ unsigned int(*getDuration) (ProtocolHandle handle); /** * Get the stream type of the data that is being read from this protocol. * * @param handle - protocol instance handle * * @return type of the stream container provided by this protocol. */ extStreamType_e (*getStreamType)(ProtocolHandle handle); /** * Get video frame rate if available. * @param handle - protocol instance handle * * @return frame_rate*1000, e.i. 24000, 25000, ... , * 0 if not available */ int (*getVideoFPS) (ProtocolHandle handle); /** * Get content specific meta data information * It can be list of chapters etc. It should be JSON string * It should contain field "infoType" with string value which explicitly specifies * format of returned metadata information. */ const char* (*getMetadataInfo) (ProtocolHandle handle); /** * Return whether protocol is realtime or not. * @param e - pointer to protocol * * Return: non zero - if it is realtime protocol (default) * zero - otherwise */ int (*isRealTimeProtocol) (ext_protocol_t *e); /** * Leave space for future extensions. It must be filled by NULLs. */ void * padding[8]; }; typedef void (*ext_event_fn_t) (ext_protocol_t *e, unsigned long event_id, const char* event_data); typedef int (*ext_abort_fn_t) (ext_protocol_t *e); typedef ext_protocol_t * (*ext_protocol_init_t) (ext_event_fn_t ext_event_fn); typedef void (*ext_protocol_register_abort_fn_t)(ext_protocol_t *e, ext_abort_fn_t ext_abort_fn); typedef void (*ext_protocol_free_t) (ext_protocol_t **pe); /* The dynamic library will implement these */ /** * Allocate and return ext_protocol_t * * @param ext_event_fn Event function that will be called from inside ext_protocol * * @return pointer to protocol instance. */ ext_protocol_t * ext_protocol_init (ext_event_fn_t ext_event_fn); /** * Register abort function that should be called from inside ext_protocol * During long-duration operations such as read, open and setPosTime ext_protocol should periodically * call this function to check whether protocol should return from long-duration call with error. * ext_abort_fn return 0 if protocol can continue operation, otherwise - abort operation. * * ONLY for ext-protocol V1. * For V2 use per playback abort. * * @param e - pointer to protocol * @param ext_abort_fn abort function. * can be NULL if abort function should not be called. */ void ext_protocol_register_abort_fn(ext_protocol_t *e, ext_abort_fn_t ext_abort_fn); /** * Free ext_protocol_t * * @param *e - pointer to protocol */ void ext_protocol_free (ext_protocol_t **pe); //==============V2 extension ===================== typedef struct ext_protocol_v2 ext_protocol_v2_t; typedef void (*ext_protocol_playback_event_fn_v2_t)(ext_protocol_v2_t *e ,void * context ,unsigned long event_id ,const char* event_data); typedef int (*ext_playback_abort_fn_v2_t) (ext_protocol_v2_t *e ,void * context); struct ext_protocol_v2 { /** * null-terminated string with protocol name(identifier). */ char ident[64]; /** * Some private data to be filled and used by the protocol. */ void * private_data; /** * Implementation version. */ int version; /** * Open stream via protocol. * * @param e - pointer to protocol * @param pHandle - handler to opened instatnce of protocol. * Will be used with all operations applied to opened instance. * In case of error *pHandle should be filled with NULL. * otherwise - with opened handle. * @param evt_fn callback to pass events for the corresponding playback * @param abort_fn callback to check if stop is required, it's return value: * 1 - stop is required; * 0 - continue; * @param context - passed to evt_fn and abort_fn * @param url - content URL to be played * * @return 0 if success * error code otherwise. */ int (*open) (ext_protocol_v2_t *e ,ProtocolHandle * pHandle ,ext_protocol_playback_event_fn_v2_t evt_fn ,ext_playback_abort_fn_v2_t abort_fn ,void * context ,const char *url); /** * Read data from stream. * @param handle - protocol instance handle * * @return number of bytes read: * 0 - no data received try again * <0 - error code. @See EXT_STATUS_XXX */ int (*read) (ProtocolHandle handle, char *buf, int buflen); /** * Close stream. * @param handle - protocol instance handle */ void (*close) (ProtocolHandle handle); /** * Send command to ext. protocol * This function is always called from other thread relative to calls of open,read,setPosTime,... * @param e - pointer to protocol * @param handle the command pertains to, if NULL, command applies to the entire protocol * @param cmd - command to be executed. * @param params - command params. * * @return result of command execution allocated by malloc. * free() it after use. */ char * (*command) (ext_protocol_v2_t *e, ProtocolHandle handle, const char *cmd, const char *params); /** * Send event to protocol * @param e - pointer to protocol * @param handle the command pertains to, if NULL, command applies to the entire protocol * @param event_id - event code. */ void (*event) (ext_protocol_v2_t *e, ProtocolHandle handle, unsigned long event_id); /** * Seek to specified time (in ms) in stream. * @param handle - protocol instance handle * @param posInMs - position in media in ms since start of media * always from 0 to duration (posInMs is not related to startTime) * * @return if success - >= 0 - success, returns stream position in ms * otherwise - < 0 - error */ int (*setPosTime) (ProtocolHandle handle, unsigned int posInMs); /** * Get timestamp of media content start point in ms. * * @param handle - protocol instance handle * * @return start time of the stream in ms if known * otherwise - 0. */ unsigned int(*getStartTime) (ProtocolHandle handle); /** * Get the duration of whole media in ms. * * @param handle - protocol instance handle * * @return duration of the stream in ms if known * otherwise - 0. */ unsigned int(*getDuration) (ProtocolHandle handle); /** * Get the stream type of the data that is being read from this protocol. * * @param handle - protocol instance handle * * @return type of the stream container provided by this protocol. */ extStreamType_e (*getStreamType)(ProtocolHandle handle); /** * Get video frame rate if available. * @param handle - protocol instance handle * * @return frame_rate*1000, e.i. 24000, 25000, ... , * 0 if not available */ int (*getVideoFPS) (ProtocolHandle handle); /** * Get content specific meta data information * It can be list of chapters etc. It should be JSON string * It should contain field "infoType" with string value which explicitly specifies * format of returned metadata information. */ const char* (*getMetadataInfo) (ProtocolHandle handle); /** * Return whether protocol is realtime or not. * @param e - pointer to protocol * * Return: non zero - if it is realtime protocol (default) * zero - otherwise */ int (*isRealTimeProtocol) (ext_protocol_v2_t *e); /** * Leave space for future extensions. It must be filled by NULLs. */ void * padding[8]; }; typedef void (*ext_protocol_global_event_fn_v2_t)(ext_protocol_v2_t *e ,unsigned long event_id ,const char* event_data); /** * Allocate and return ext_protocol_v2 * * @param ext_event_fn Event function that will be called from inside ext_protocol * * @return pointer to protocol instance. */ typedef ext_protocol_v2_t * (*ext_protocol_init_v2_t) (ext_protocol_global_event_fn_v2_t ext_glob_event_fn); typedef void (*ext_protocol_free_v2_t) (ext_protocol_v2_t **p); /* The dynamic library will implement these */ ext_protocol_v2_t * ext_protocol_init_v2 (ext_protocol_global_event_fn_v2_t ext_event_fn); /** * Free ext_protocol_v2 * * @param *e - pointer to protocol */ void ext_protocol_free_v2 (ext_protocol_v2_t **pe); #if defined(__cplusplus) } #endif #endif //_EXT_PROTOCOL_H_
/* * Licensed to Systerel under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Systerel licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "sopc_dict.h" #include "sopc_mem_alloc.h" #include <assert.h> #define HASH_I(hash, i) (hash + (i / 2) + (i * i / 2)) /* This is a dictionary implemented using quadratic probing (see * https://en.wikipedia.org/wiki/Linear_probing) for resolving key conflicts. * * We distinguish between empty and non-empty buckets using a special value for * the key. Removal of items can be implemented by stealing a second value from * the keyspace and using it as a tombstone. */ typedef struct _SOPC_DictBucket { void* key; void* value; } SOPC_DictBucket; struct _SOPC_Dict { SOPC_DictBucket* buckets; size_t size; // Total number of buckets, always a power of two size_t sizemask; // sizemask == (size - 1), used to replace (hash % size) by (hash & sizemask) size_t n_items; // Number of buckets holding a "real" value (not empty, not tombstone) size_t n_busy; // Number of buckets where the key is not the empty key void* empty_key; void* tombstone_key; SOPC_Dict_KeyHash_Fct hash_func; SOPC_Dict_KeyEqual_Fct equal_func; SOPC_Dict_Free_Fct key_free; SOPC_Dict_Free_Fct value_free; }; static const size_t DICT_INITIAL_SIZE = 16; // Shrink the table if the number of items is below SHRINK_FACTOR * (number of buckets) // We never shrink below DICT_INITIAL_SIZE. static const double SHRINK_FACTOR = 0.4; static void set_empty_keys(SOPC_DictBucket* buckets, size_t n_buckets, void* empty_key) { for (size_t i = 0; i < n_buckets; ++i) { buckets[i].key = empty_key; } } static void free_bucket(SOPC_DictBucket* b, SOPC_Dict_Free_Fct key_free, SOPC_Dict_Free_Fct value_free) { if (key_free != NULL) { key_free(b->key); } if (value_free != NULL) { value_free(b->value); } } static bool insert_item(SOPC_Dict* d, uint64_t hash, void* key, void* value, bool overwrite) { for (size_t i = 0; i < d->size; ++i) { size_t idx = (size_t) HASH_I(hash, i) & d->sizemask; SOPC_DictBucket* b = &d->buckets[idx]; // Normal insert if (b->key == d->empty_key || b->key == d->tombstone_key) { b->key = key; b->value = value; d->n_items++; d->n_busy++; return true; } // Overwriting of existing value if (overwrite && d->equal_func(key, b->key)) { free_bucket(b, d->key_free, d->value_free); b->key = key; b->value = value; return true; } } assert(false && "Cannot find a free bucket?!"); return false; } static bool dict_resize(SOPC_Dict* d, size_t size) { size_t sizemask = size - 1; assert((size & sizemask) == 0); // Ensure we have a power of two SOPC_DictBucket* buckets = SOPC_Calloc(size, sizeof(SOPC_DictBucket)); if (buckets == NULL) { return false; } if (d->empty_key != NULL) { set_empty_keys(buckets, size, d->empty_key); } SOPC_Dict dict_backup = *d; d->n_busy = 0; d->n_items = 0; d->buckets = buckets; d->size = size; d->sizemask = sizemask; bool ok = true; for (size_t i = 0; i < dict_backup.size; ++i) { SOPC_DictBucket* b = &dict_backup.buckets[i]; if ((b->key == d->empty_key) || (b->key == d->tombstone_key)) { continue; } uint64_t hash = d->hash_func(b->key); if (!insert_item(d, hash, b->key, b->value, false)) { ok = false; break; } } if (ok) { SOPC_Free(dict_backup.buckets); } else { *d = dict_backup; } return ok; } SOPC_Dict* SOPC_Dict_Create(void* empty_key, SOPC_Dict_KeyHash_Fct key_hash, SOPC_Dict_KeyEqual_Fct key_equal, SOPC_Dict_Free_Fct key_free, SOPC_Dict_Free_Fct value_free) { SOPC_Dict* d = SOPC_Calloc(1, sizeof(SOPC_Dict)); if (d == NULL) { return NULL; } d->size = DICT_INITIAL_SIZE; d->sizemask = d->size - 1; d->buckets = SOPC_Calloc(d->size, sizeof(SOPC_DictBucket)); bool ok = d->buckets != NULL; if (!ok) { SOPC_Dict_Delete(d); return NULL; } d->empty_key = empty_key; d->tombstone_key = empty_key; d->hash_func = key_hash; d->equal_func = key_equal; d->key_free = key_free; d->value_free = value_free; // We only go touch the memory if the empty key is not 0, since the memory // for our buckets is always alloced with calloc. if (d->empty_key != NULL) { set_empty_keys(d->buckets, d->size, d->empty_key); } return d; } void SOPC_Dict_Delete(SOPC_Dict* d) { if (d != NULL) { // buckets can be NULL if called from SOPC_Dict_Create if (d->buckets != NULL) { for (size_t i = 0; i < d->size; ++i) { SOPC_DictBucket* bucket = &d->buckets[i]; if ((bucket->key != d->empty_key) && (bucket->key != d->tombstone_key)) { free_bucket(bucket, d->key_free, d->value_free); } } SOPC_Free(d->buckets); } SOPC_Free(d); } } // Compute the minimum dictionary size (a power of two) given an initial size // and a number of items to store. // The computed value is such that dictionary occupation stays under 50%. static size_t minimum_dict_size(size_t start_size, size_t n_items) { assert((start_size & (start_size - 1)) == 0); size_t size = start_size; while (size < (2 * n_items)) { size *= 2; } return size; } bool SOPC_Dict_Reserve(SOPC_Dict* d, size_t n_items) { assert(d != NULL); return dict_resize(d, minimum_dict_size(d->size, n_items)); } void SOPC_Dict_SetTombstoneKey(SOPC_Dict* d, void* tombstone_key) { assert(d != NULL); assert(d->empty_key != tombstone_key); assert(d->n_busy == 0); d->tombstone_key = tombstone_key; } // Delta is 1 when adding, 0 when removing static bool maybe_resize(SOPC_Dict* d, uint8_t delta) { const size_t shrink_limit = (size_t)(SHRINK_FACTOR * ((double) d->size)); size_t target_size = d->size; if (((delta > 0) && ((d->n_busy + delta) > (d->size / 2))) || ((delta == 0) && (d->n_items < shrink_limit))) { // One of the two cases: // - Overpopulation when adding items // - Underpopulation while removing items // // Compute the required number of buckets after eliminating tombstones // and resize. // Ensure the occupation will be under 50% target_size = minimum_dict_size(DICT_INITIAL_SIZE, d->n_items + delta); } return (d->size == target_size) ? true : dict_resize(d, target_size); } bool SOPC_Dict_Insert(SOPC_Dict* d, void* key, void* value) { assert(d != NULL); assert(key != d->empty_key); assert(key != d->tombstone_key); if (!maybe_resize(d, 1)) { return false; } uint64_t hash = d->hash_func(key); return insert_item(d, hash, key, value, true); } static SOPC_DictBucket* get_internal(const SOPC_Dict* d, const void* key) { assert(key != d->empty_key); assert(key != d->tombstone_key); uint64_t hash = d->hash_func(key); for (size_t i = 0; i < d->size; ++i) { uint64_t idx = HASH_I(hash, i) & d->sizemask; const void* bucket_key = d->buckets[idx].key; if (bucket_key == d->empty_key) { break; } // If removals are not supported, we have empty_key == tombstone_key, so // this if never matches. if (bucket_key == d->tombstone_key) { continue; } if (d->equal_func(key, bucket_key)) { return &d->buckets[idx]; } } return NULL; } void* SOPC_Dict_Get(const SOPC_Dict* d, const void* key, bool* found) { assert(d != NULL); SOPC_DictBucket* bucket = get_internal(d, key); if (found != NULL) { *found = (bucket != NULL); } return (bucket != NULL) ? bucket->value : NULL; } void* SOPC_Dict_GetKey(const SOPC_Dict* d, const void* key, bool* found) { assert(d != NULL); SOPC_DictBucket* bucket = get_internal(d, key); if (found != NULL) { *found = (bucket != NULL); } return (bucket != NULL) ? bucket->key : NULL; } void SOPC_Dict_Remove(SOPC_Dict* d, const void* key) { assert(d != NULL); // Check that a tombstone key has been defined assert(d->empty_key != d->tombstone_key); SOPC_DictBucket* bucket = get_internal(d, key); if (bucket == NULL) { return; } free_bucket(bucket, d->key_free, d->value_free); bucket->key = d->tombstone_key; bucket->value = NULL; --d->n_items; // We can ignore failures here, worst case we fail to compact and will try // later. maybe_resize(d, 0); } SOPC_Dict_Free_Fct SOPC_Dict_GetKeyFreeFunc(const SOPC_Dict* d) { assert(d != NULL); return d->key_free; } void SOPC_Dict_SetKeyFreeFunc(SOPC_Dict* d, SOPC_Dict_Free_Fct func) { assert(d != NULL); d->key_free = func; } SOPC_Dict_Free_Fct SOPC_Dict_GetValueFreeFunc(const SOPC_Dict* d) { assert(d != NULL); return d->value_free; } void SOPC_Dict_SetValueFreeFunc(SOPC_Dict* d, SOPC_Dict_Free_Fct func) { assert(d != NULL); d->value_free = func; } size_t SOPC_Dict_Size(const SOPC_Dict* d) { return d->n_items; } size_t SOPC_Dict_Capacity(const SOPC_Dict* d) { return d->size / 2; } void SOPC_Dict_ForEach(SOPC_Dict* d, SOPC_Dict_ForEach_Fct func, void* user_data) { for (size_t i = 0; i < d->size; ++i) { if (d->buckets[i].key != d->empty_key) { func(d->buckets[i].key, d->buckets[i].value, user_data); } } }
/** * WinPR: Windows Portable Runtime * Process Thread Functions * * Copyright 2012 <NAME> <<EMAIL>> * * 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 WINPR_THREAD_H #define WINPR_THREAD_H #include <winpr/winpr.h> #include <winpr/wtypes.h> #include <winpr/handle.h> #ifndef _WIN32 typedef struct _STARTUPINFOA { DWORD cb; LPSTR lpReserved; LPSTR lpDesktop; LPSTR lpTitle; DWORD dwX; DWORD dwY; DWORD dwXSize; DWORD dwYSize; DWORD dwXCountChars; DWORD dwYCountChars; DWORD dwFillAttribute; DWORD dwFlags; WORD wShowWindow; WORD cbReserved2; LPBYTE lpReserved2; HANDLE hStdInput; HANDLE hStdOutput; HANDLE hStdError; } STARTUPINFOA, *LPSTARTUPINFOA; typedef struct _STARTUPINFOW { DWORD cb; LPWSTR lpReserved; LPWSTR lpDesktop; LPWSTR lpTitle; DWORD dwX; DWORD dwY; DWORD dwXSize; DWORD dwYSize; DWORD dwXCountChars; DWORD dwYCountChars; DWORD dwFillAttribute; DWORD dwFlags; WORD wShowWindow; WORD cbReserved2; LPBYTE lpReserved2; HANDLE hStdInput; HANDLE hStdOutput; HANDLE hStdError; } STARTUPINFOW, *LPSTARTUPINFOW; #ifdef UNICODE typedef STARTUPINFOW STARTUPINFO; typedef LPSTARTUPINFOW LPSTARTUPINFO; #else typedef STARTUPINFOA STARTUPINFO; typedef LPSTARTUPINFOA LPSTARTUPINFO; #endif /* Process */ WINPR_API BOOL CreateProcessA(LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); WINPR_API BOOL CreateProcessW(LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); WINPR_API BOOL CreateProcessAsUserA(HANDLE hToken, LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); WINPR_API BOOL CreateProcessAsUserW(HANDLE hToken, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); #ifdef UNICODE #define CreateProcess CreateProcessW #define CreateProcessAsUser CreateProcessAsUserW #else #define CreateProcess CreateProcessA #define CreateProcessAsUser CreateProcessAsUserA #endif WINPR_API VOID ExitProcess(UINT uExitCode); WINPR_API HANDLE _GetCurrentProcess(VOID); WINPR_API DWORD GetCurrentProcessId(VOID); WINPR_API BOOL TerminateProcess(HANDLE hProcess, UINT uExitCode); /* Thread */ #define CREATE_SUSPENDED 0x00000004 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000 WINPR_API HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); WINPR_API HANDLE CreateRemoteThread(HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); WINPR_API VOID ExitThread(DWORD dwExitCode); WINPR_API HANDLE _GetCurrentThread(VOID); WINPR_API DWORD GetCurrentThreadId(VOID); WINPR_API DWORD ResumeThread(HANDLE hThread); WINPR_API DWORD SuspendThread(HANDLE hThread); WINPR_API BOOL SwitchToThread(VOID); WINPR_API BOOL TerminateThread(HANDLE hThread, DWORD dwExitCode); /* Processor */ WINPR_API DWORD GetCurrentProcessorNumber(VOID); /* Thread-Local Storage */ #define TLS_OUT_OF_INDEXES ((DWORD) 0xFFFFFFFF) WINPR_API DWORD TlsAlloc(VOID); WINPR_API LPVOID TlsGetValue(DWORD dwTlsIndex); WINPR_API BOOL TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue); WINPR_API BOOL TlsFree(DWORD dwTlsIndex); #else /* * GetCurrentProcess / GetCurrentThread cause a conflict on Mac OS X */ #define _GetCurrentProcess GetCurrentProcess #define _GetCurrentThread GetCurrentThread #endif #endif /* WINPR_THREAD_H */
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card