blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80 values | src_encoding stringclasses 28 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 8 9.86M | extension stringclasses 52 values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
037e432edeff8e2b13f193f4fcf66a62bd266680 | b0eee769ed1fde3b965b66cb4eaabc56b3f4efad | /test/echoclient.cpp | cbe321546d4a57c6a548809f37d89670e36bf5a5 | [
"BSD-2-Clause"
] | permissive | DamonXu/libevlite | df2d4bf0276cc6be6b720631e403079dfdc7cc68 | 36de7af8256b71f9a02c5fb26887f20c65fde5f8 | refs/heads/master | 2020-11-29T21:21:06.359573 | 2019-10-14T08:56:36 | 2019-10-14T08:56:36 | 150,943,062 | 1 | 0 | BSD-2-Clause | 2018-09-30T07:31:42 | 2018-09-30T07:31:42 | null | UTF-8 | C++ | false | false | 2,616 | cpp |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include "io.h"
//
// 回显服务实例
//
class CEchoSession : public Utils::IIOSession
{
public :
CEchoSession()
{}
virtual ~CEchoSession()
{}
public :
virtual ssize_t onProcess( const char * buf, size_t nbytes )
{
std::string line( buf, buf+nbytes );
printf("%s", line.c_str() );
fflush(stdout);
return nbytes;
}
virtual int32_t onError( int32_t result )
{
printf("the Session (SID=%ld) : error, code=0x%08x \n", id(), result );
return 0;
}
virtual int32_t onShutdown()
{
return 0;
}
};
class CEchoService : public Utils::IIOService
{
public :
CEchoService( uint8_t nthreads, uint32_t nclients )
: Utils::IIOService( nthreads, nclients )
{
}
virtual ~CEchoService()
{
}
public :
Utils::IIOSession * onConnect( sid_t id, const char * host, uint16_t port )
{
m_ClientSid = id;
return new CEchoSession();
}
public :
int32_t send2( const std::string & buffer )
{
return send( m_ClientSid, buffer );
}
private :
sid_t m_ClientSid;
};
// -------------------------------------------------------------------------------
// -------------------------------------------------------------------------------
// -------------------------------------------------------------------------------
bool g_Running;
void signal_handle( int32_t signo )
{
g_Running = false;
}
int main( int argc, char ** argv )
{
std::string line;
CEchoService * service = NULL;
if ( argc != 3 )
{
printf("Usage: echoclient [host] [port] \n");
return -1;
}
signal( SIGPIPE, SIG_IGN );
signal( SIGINT, signal_handle );
service = new CEchoService( 1, 200 );
if ( service == NULL )
{
return -1;
}
service->start();
if ( !service->connect( argv[1], atoi(argv[2]), 10 ) )
{
printf("service start failed \n");
delete service;
return -2;
}
g_Running = true;
while ( g_Running )
{
int ch = getc(stdin);
line.push_back( (char)ch );
if ( ch == '\n' )
{
if ( strcmp( line.c_str(), "quit\n" ) == 0 )
{
g_Running = false;
continue;
}
service->send2( line );
line.clear();
}
fflush(stdin);
}
printf("EchoClient stoping ...\n");
service->stop();
delete service;
return 0;
}
| [
"spriteray@gmail.com"
] | spriteray@gmail.com |
1bf4af8ceb03d7bed5b676ade296dbdc71e13f23 | 8c7b03f24517e86f6159e4d74c8528bfbcbf31af | /source/Plugins/SymbolFile/Symtab/SymbolFileSymtab.h | 0ea06560d0f1bc014380d8a0c77207c60060e5bf | [
"NCSA"
] | permissive | markpeek/lldb | f849567fbd7791be10aacd41be44ee15f1a4fdc4 | 58c8d5af715a3da6cbb7e0efc6905e9d07410038 | refs/heads/master | 2021-01-15T17:01:57.014568 | 2011-12-24T01:08:58 | 2011-12-24T01:08:58 | 3,042,888 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,056 | h | //===-- SymbolFileSymtab.h --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef liblldb_SymbolFileSymtab_h_
#define liblldb_SymbolFileSymtab_h_
#include "lldb/Symbol/SymbolFile.h"
#include "lldb/Symbol/Symtab.h"
#include <vector>
class SymbolFileSymtab : public lldb_private::SymbolFile
{
public:
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
static void
Initialize();
static void
Terminate();
static const char *
GetPluginNameStatic();
static const char *
GetPluginDescriptionStatic();
static lldb_private::SymbolFile*
CreateInstance (lldb_private::ObjectFile* obj_file);
//------------------------------------------------------------------
// Constructors and Destructors
//------------------------------------------------------------------
SymbolFileSymtab(lldb_private::ObjectFile* obj_file);
virtual
~SymbolFileSymtab();
virtual uint32_t CalculateAbilities ();
//------------------------------------------------------------------
// Compile Unit function calls
//------------------------------------------------------------------
virtual uint32_t
GetNumCompileUnits();
virtual lldb::CompUnitSP
ParseCompileUnitAtIndex(uint32_t index);
virtual size_t
ParseCompileUnitFunctions (const lldb_private::SymbolContext& sc);
virtual bool
ParseCompileUnitLineTable (const lldb_private::SymbolContext& sc);
virtual bool
ParseCompileUnitSupportFiles (const lldb_private::SymbolContext& sc, lldb_private::FileSpecList &support_files);
virtual size_t
ParseFunctionBlocks (const lldb_private::SymbolContext& sc);
virtual size_t
ParseTypes (const lldb_private::SymbolContext& sc);
virtual size_t
ParseVariablesForContext (const lldb_private::SymbolContext& sc);
virtual lldb_private::Type*
ResolveTypeUID(lldb::user_id_t type_uid);
virtual lldb::clang_type_t
ResolveClangOpaqueTypeDefinition (lldb::clang_type_t clang_Type);
virtual uint32_t
ResolveSymbolContext (const lldb_private::Address& so_addr, uint32_t resolve_scope, lldb_private::SymbolContext& sc);
virtual uint32_t
ResolveSymbolContext (const lldb_private::FileSpec& file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, lldb_private::SymbolContextList& sc_list);
virtual uint32_t
FindGlobalVariables(const lldb_private::ConstString &name, const lldb_private::ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, lldb_private::VariableList& variables);
virtual uint32_t
FindGlobalVariables(const lldb_private::RegularExpression& regex, bool append, uint32_t max_matches, lldb_private::VariableList& variables);
virtual uint32_t
FindFunctions(const lldb_private::ConstString &name, const lldb_private::ClangNamespaceDecl *namespace_decl, uint32_t name_type_mask, bool append, lldb_private::SymbolContextList& sc_list);
virtual uint32_t
FindFunctions(const lldb_private::RegularExpression& regex, bool append, lldb_private::SymbolContextList& sc_list);
virtual uint32_t
FindTypes (const lldb_private::SymbolContext& sc,const lldb_private::ConstString &name, const lldb_private::ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, lldb_private::TypeList& types);
// virtual uint32_t
// FindTypes(const lldb_private::SymbolContext& sc, const lldb_private::RegularExpression& regex, bool append, uint32_t max_matches, lldb_private::TypeList& types);
virtual lldb_private::ClangNamespaceDecl
FindNamespace (const lldb_private::SymbolContext& sc,
const lldb_private::ConstString &name,
const lldb_private::ClangNamespaceDecl *parent_namespace_decl);
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
virtual const char *
GetPluginName();
virtual const char *
GetShortPluginName();
virtual uint32_t
GetPluginVersion();
protected:
typedef std::map<lldb_private::ConstString, lldb::TypeSP> TypeMap;
lldb_private::Symtab::IndexCollection m_source_indexes;
lldb_private::Symtab::IndexCollection m_func_indexes;
lldb_private::Symtab::IndexCollection m_code_indexes;
lldb_private::Symtab::IndexCollection m_data_indexes;
lldb_private::Symtab::NameToIndexMap m_objc_class_name_to_index;
TypeMap m_objc_class_types;
lldb_private::ClangASTContext &
GetClangASTContext ();
private:
DISALLOW_COPY_AND_ASSIGN (SymbolFileSymtab);
};
#endif // liblldb_SymbolFileSymtab_h_
| [
"mark@peek.org"
] | mark@peek.org |
ccef118a23d111084290623336b58e733cbcce52 | aabfbd4f6c940aa7c75195bd60d19a551fce3822 | /summer_school_private/anymal_research/any_measurements/include/any_measurements/NavSat.hpp | 76c44473ab32564a6df3d7e82178e01256cb8dd2 | [] | no_license | daoran/eth_supermegabot | 9c5753507be243fc15133c9dfb1d0a5d4ff1d496 | 52b82300718c91344f41b4e11bbcf892d961af4b | refs/heads/master | 2020-07-28T13:42:08.906212 | 2019-12-04T16:51:42 | 2019-12-04T16:51:42 | 209,428,875 | 1 | 1 | null | 2019-09-19T00:36:33 | 2019-09-19T00:36:33 | null | UTF-8 | C++ | false | false | 3,021 | hpp | /*!
* @file NavSat.hpp
* @author Philipp Leemann
* @date Mar 03, 2017
* @version 0.0
*
*/
#pragma once
#include <Eigen/Core>
#include "any_measurements/Time.hpp"
#include <string>
namespace any_measurements {
struct NavSat
{
public:
using CovarianceMatrix = Eigen::Matrix<double, 3, 3>;
// Whether to output an augmented fix is determined by both the fix
// type and the last time differential corrections were received. A
// fix is valid when status >= STATUS_FIX.
enum Status : int8_t {
// same as in sensor_msgs/NavSatStatus.msg
STATUS_NO_FIX=-1,
STATUS_FIX=0,
STATUS_SBAS_FIX=1,
STATUS_GBAS_FIX=2
};
// Bits defining which Global Navigation Satellite System signals were
// used by the receiver.
enum Service : uint16_t {
// same as in sensor_msgs/NavSatStatus.msg
SERVICE_NONE = 0,
SERVICE_GPS = 1,
SERVICE_GLONASS = 2,
SERVICE_COMPASS = 4, // includes BeiDou.
SERVICE_GALILEO = 8
};
enum CovarianceType : uint8_t {
// same as in sensor_msgs/NavSatFix.msg
COVARIANCE_TYPE_UNKNOWN=0,
COVARIANCE_TYPE_APPROXIMATED,
COVARIANCE_TYPE_DIAGONAL_KNOWN,
COVARIANCE_TYPE_KNOWN
};
NavSat():
time_(),
status_(STATUS_NO_FIX),
service_(SERVICE_GPS),
latitude_(0.0),
longitude_(0.0),
altitude_(0.0),
positionCovarianceType_(COVARIANCE_TYPE_UNKNOWN),
positionCovariance_(CovarianceMatrix::Zero())
{
}
NavSat(const Time& time,
const Status status,
const Service service,
const double latitude,
const double longitude,
const double altitude,
const CovarianceType positionCovarianceType,
const CovarianceMatrix& positionCovariance
):
time_(time),
status_(status),
service_(service),
latitude_(latitude),
longitude_(longitude),
altitude_(altitude),
positionCovarianceType_(positionCovarianceType),
positionCovariance_(positionCovariance)
{
}
virtual ~NavSat() = default;
public:
Time time_;
Status status_;
Service service_;
double latitude_;
double longitude_;
double altitude_;
CovarianceType positionCovarianceType_;
CovarianceMatrix positionCovariance_;
};
inline std::ostream& operator<<(std::ostream& os, const NavSat& navSat)
{
return os << "NavSat (Time: " << navSat.time_ << ")"
<< "\n Status: " << navSat.status_
<< "\n Service: " << static_cast<uint16_t>(navSat.service_)
<< "\n Latitude: " << navSat.latitude_
<< "\n Longitude: " << navSat.longitude_
<< "\n Altitude: " << navSat.altitude_
<< "\n PositionCovarianceType: " << navSat.positionCovarianceType_
<< "\n PositionCovariance: " << navSat.positionCovariance_;
}
} /* namespace any_measurements */
| [
"hlin@ethz.ch"
] | hlin@ethz.ch |
f1b4330e6b340e3965bb54057832f8318d8eb552 | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/vc7addon/vs/src/vc/ide/pkgs/projbld/vcpb/linktoolbase.h | 6dbc46b100f8d39d1613cce905a54f38cee8a957 | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,281 | h | // VCLinkerBaseTool.h: Definition of the CVCLinkerBaseTool class
//
//////////////////////////////////////////////////////////////////////
#pragma once
#include "vctool.h"
#include "settingspage.h"
template<class T, class IFace>
class ATL_NO_VTABLE CVCLinkerBasePage :
public IDispatchImpl<IFace, &(__uuidof(IFace)), &LIBID_VCProjectEnginePrivateLibrary, PrivateProjBuildTypeLibNumber, 0, CVsTypeInfoHolder>,
public CPageObjectImpl<T, VCLINKERTOOL_MIN_DISPID, VCLINKERTOOL_MAX_DISPID>,
public CComObjectRoot
{
public:
BEGIN_COM_MAP(T)
COM_INTERFACE_ENTRY(IPerPropertyBrowsing)
COM_INTERFACE_ENTRY(IVsPerPropertyBrowsing)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(IFace)
COM_INTERFACE_ENTRY(IVCPropertyContainer)
COM_INTERFACE_ENTRY(IProvidePropertyBuilder)
END_COM_MAP()
// IDispatch override
STDMETHOD(Invoke)( DISPID dispid, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pdispParams, VARIANT *pvarResult, EXCEPINFO *pexcepInfo, UINT *puArgErr )
{
IDispatchImpl<IFace, &(__uuidof(IFace)), &LIBID_VCProjectEnginePrivateLibrary, PrivateProjBuildTypeLibNumber,0, CVsTypeInfoHolder>::Invoke( dispid, riid, lcid, wFlags, pdispParams, pvarResult, pexcepInfo, puArgErr );
return S_OK;
}
// IVCPropertyContainer override
public:
STDMETHOD(Commit)()
{
if (m_pContainer)
{
// need to set/unset 'generate map file' if name changes and user didn't explictly change the 'generate'
CComVariant varName;
if (m_pContainer->GetLocalProp(VCLINKID_MapFileName, &varName) == S_OK) // name changed
{
CComVariant var;
// if both changed locally, don't do anything about keeping them in sync
if (m_pContainer->GetLocalProp(VCLINKID_GenerateMapFile, &var) != S_OK)
{
CStringW strName = varName.bstrVal;
strName.TrimLeft();
if (m_pContainer->GetProp(VCLINKID_GenerateMapFile, &var) != S_OK)
{
var.vt = VT_BOOL;
var.boolVal = VARIANT_FALSE;
}
if (var.boolVal && strName.IsEmpty())
{
var.boolVal = VARIANT_FALSE;
m_pContainer->SetProp(VCLINKID_GenerateMapFile, var);
}
else if (!var.boolVal && !strName.IsEmpty())
{
var.boolVal = VARIANT_TRUE;
m_pContainer->SetProp(VCLINKID_GenerateMapFile, var);
}
}
}
}
return CPageObjectImpl<T, VCLINKERTOOL_MIN_DISPID, VCLINKERTOOL_MAX_DISPID>::Commit();
}
};
class ATL_NO_VTABLE CVCLinkerGeneralPage :
public CVCLinkerBasePage<CVCLinkerGeneralPage, IVCLinkerGeneralPage>
{
// IVCLinkerGeneralPage
public:
STDMETHOD(get_AdditionalOptions)(BSTR* pbstrAdditionalOptions);
STDMETHOD(put_AdditionalOptions)(BSTR bstrAdditionalOptions);
STDMETHOD(get_OutputFile)(BSTR* pbstrOut); // (/OUT:[file]) change the output file name (default is based on 1st lib or obj name on cmd line)
STDMETHOD(put_OutputFile)(BSTR bstrOut);
STDMETHOD(get_ShowProgress)(linkProgressOption* poptSetting); // see enum above (/VERBOSE)
STDMETHOD(put_ShowProgress)(linkProgressOption optSetting);
STDMETHOD(get_Version)(BSTR* pbstrVersion); // (/VERSION:version) put this version number into header of created image
STDMETHOD(put_Version)(BSTR bstrVersion);
STDMETHOD(get_LinkIncremental)(linkIncrementalType* poptSetting); // (/INCREMENTAL:YES, /INCREMENTAL:NO, not set)
STDMETHOD(put_LinkIncremental)(linkIncrementalType optSetting);
STDMETHOD(get_SuppressStartupBanner)(enumSuppressStartupBannerUpBOOL* pbNoLogo); // (/NOLOGO) enable suppression of copyright message (no explicit off)
STDMETHOD(put_SuppressStartupBanner)(enumSuppressStartupBannerUpBOOL bNoLogo);
STDMETHOD(get_IgnoreImportLibrary)(enumBOOL* pbIgnore); // ignore export .lib
STDMETHOD(put_IgnoreImportLibrary)(enumBOOL bIgnore);
STDMETHOD(get_RegisterOutput)(enumBOOL* pbRegister); // register the primary output of the build
STDMETHOD(put_RegisterOutput)(enumBOOL bRegister);
STDMETHOD(get_AdditionalLibraryDirectories)(BSTR* pbstrLibPath); // (/LIBPATH:[dir]) specify path to search for libraries on, can have multiple
STDMETHOD(put_AdditionalLibraryDirectories)(BSTR bstrLibPath);
// helpers
public:
virtual void GetBaseDefault(long id, CComVariant& varValue);
virtual BOOL UseDirectoryPickerDialog(long id) { return (id == VCLINKID_AdditionalLibraryDirectories); }
};
class ATL_NO_VTABLE CVCLinkerInputPage :
public CVCLinkerBasePage<CVCLinkerInputPage, IVCLinkerInputPage>
{
// IVCLinkerInputPage
public:
STDMETHOD(get_AdditionalDependencies)(BSTR* pbstrInputs); // additional inputs for the link path (comdlg32.lib, etc.)
STDMETHOD(put_AdditionalDependencies)(BSTR bstrInputs);
STDMETHOD(get_IgnoreAllDefaultLibraries)(enumIgnoreAllDefaultLibrariesBOOL* pbNoDefaults); // (/NODEFAULTLIB) ignore all default libraries
STDMETHOD(put_IgnoreAllDefaultLibraries)(enumIgnoreAllDefaultLibrariesBOOL bNoDefaults);
STDMETHOD(get_IgnoreDefaultLibraryNames)(BSTR* pbstrLib); // (/NODEFAULTLIB:[name]) ignore particular default library, can have multiple
STDMETHOD(put_IgnoreDefaultLibraryNames)(BSTR bstrLib);
STDMETHOD(get_ModuleDefinitionFile)(BSTR* pbstrDefFile); // (/DEF:file) use/specify module definition file
STDMETHOD(put_ModuleDefinitionFile)(BSTR bstrDefFile);
STDMETHOD(get_AddModuleNamesToAssembly)(BSTR* pbstrNonAssy); // (/ASSEMBLYMODULE:file) imports a non-assembly file
STDMETHOD(put_AddModuleNamesToAssembly)(BSTR bstrNonAssy);
STDMETHOD(get_EmbedManagedResourceFile)(BSTR* pbstrRes); // (/ASSEMBLYRESOURCE:file) embed an assembly resource file
STDMETHOD(put_EmbedManagedResourceFile)(BSTR bstrRes);
STDMETHOD(get_ForceSymbolReferences)(BSTR* pbstrSymbol); // (/INCLUDE:[symbol]) force symbol reference, can have multiple
STDMETHOD(put_ForceSymbolReferences)(BSTR bstrSymbol);
STDMETHOD(get_DelayLoadDLLs)(BSTR* pbstrDLLName); // (/DELAYLOAD:[dll_name]) delay load specified DLL, can have multiple
STDMETHOD(put_DelayLoadDLLs)(BSTR bstrDLLName);
};
class ATL_NO_VTABLE CVCLinkerDebugPage :
public CVCLinkerBasePage<CVCLinkerDebugPage, IVCLinkerDebugPage>
{
// IVCLinkerDebugPage
public:
STDMETHOD(get_GenerateDebugInformation)(enumGenerateDebugInformationBOOL* pbDebug); // (/DEBUG) generate debug info
STDMETHOD(put_GenerateDebugInformation)(enumGenerateDebugInformationBOOL bDebug);
STDMETHOD(get_ProgramDatabaseFile)(BSTR* pbstrFile); // (/PDB:file) use program database
STDMETHOD(put_ProgramDatabaseFile)(BSTR bstrFile);
STDMETHOD(get_StripPrivateSymbols)(BSTR* pbstrStrippedPDB); // (/PDBSTRIPPED:file) create PDB with no private symbols
STDMETHOD(put_StripPrivateSymbols)(BSTR bstrStrippedPDB);
STDMETHOD(get_GenerateMapFile)(enumGenerateMapFileBOOL* pbMap); // (/MAP[:file]) generate map file during linking
STDMETHOD(put_GenerateMapFile)(enumGenerateMapFileBOOL bMap);
STDMETHOD(get_MapFileName)(BSTR* pbstrMapFile); // optional argument to GenerateMapFile property
STDMETHOD(put_MapFileName)(BSTR bstrMapFile);
STDMETHOD(get_MapExports)(enumMapExportsBOOL* pbExports); // (/MAPINFO:EXPORTS) include exported functions in map info
STDMETHOD(put_MapExports)(enumMapExportsBOOL bExports);
STDMETHOD(get_MapLines)(enumMapLinesBOOL* pbLines); // (/MAPINFO:LINES) include line number info in map info
STDMETHOD(put_MapLines)(enumMapLinesBOOL bLines);
// helpers
public:
virtual void GetBaseDefault(long id, CComVariant& varValue);
};
class ATL_NO_VTABLE CVCLinkerSystemPage :
public CVCLinkerBasePage<CVCLinkerSystemPage, IVCLinkerSystemPage>
{
// IVsPerPropertyBrowsing
public:
STDMETHOD(HideProperty)(DISPID dispid, BOOL *pfHide);
// IVCLinkerSystemPage
public:
STDMETHOD(get_SubSystem)(subSystemOption* poptSetting); // see subSystem enum (/SUBSYSTEM)
STDMETHOD(put_SubSystem)(subSystemOption optSetting);
STDMETHOD(get_HeapReserveSize)(long* pnReserveSize); // (/HEAP:reserve[,commit]) total heap allocation size in virtual memory
STDMETHOD(put_HeapReserveSize)(long nReserveSize);
STDMETHOD(get_HeapCommitSize)(long* pnCommitSize); // (/HEAP:reserve[,commit]) total heap allocation size in physical memory
STDMETHOD(put_HeapCommitSize)(long nCommitSize);
STDMETHOD(get_StackReserveSize)(long* pnReserveSize); // (/STACK:reserve[,commit]) total stack allocation size in virtual memory
STDMETHOD(put_StackReserveSize)(long nReserveSize);
STDMETHOD(get_StackCommitSize)(long* pnCommitSize); // (/STACK:reserve[,commit]) total stack allocation size in physical memory
STDMETHOD(put_StackCommitSize)(long nCommitSize);
STDMETHOD(get_LargeAddressAware)(addressAwarenessType* poptSetting); // (/LARGEADDRESSAWARE[:NO]) tells the linker the app can handle addresses greater than 2GB
STDMETHOD(put_LargeAddressAware)(addressAwarenessType optSetting);
STDMETHOD(get_TerminalServerAware)(termSvrAwarenessType* poptSetting); // (/TSAWARE, /TSAWARE:NO, not set) not in docs
STDMETHOD(put_TerminalServerAware)(termSvrAwarenessType optSetting);
STDMETHOD(get_SwapRunFromCD)(enumSwapRunFromCDBOOL* pbRun); // swap run from the CD (/SWAPRUN:CD)
STDMETHOD(put_SwapRunFromCD)(enumSwapRunFromCDBOOL bRun);
STDMETHOD(get_SwapRunFromNet)(enumSwapRunFromNetBOOL* pbRun); // swap run from the net (/SWAPRUN:NET)
STDMETHOD(put_SwapRunFromNet)(enumSwapRunFromNetBOOL bRun);
};
class ATL_NO_VTABLE CVCLinkerOptimizationPage :
public CVCLinkerBasePage<CVCLinkerOptimizationPage, IVCLinkerOptimizationPage>
{
// IVCLinkerOptimizationPage
public:
STDMETHOD(get_OptimizeReferences)(optRefType* poptSetting); // (/OPT:REF, /OPT:NOREF, not set) eliminate/keep functions & data never referenced
STDMETHOD(put_OptimizeReferences)(optRefType optSetting);
STDMETHOD(get_EnableCOMDATFolding)(optFoldingType* poptSetting); // (/OPT:ICF, /OPT:NOICF, not set) eliminate/keep redundant COMDAT data (data folding)
STDMETHOD(put_EnableCOMDATFolding)(optFoldingType optSetting);
STDMETHOD(get_OptimizeForWindows98)(optWin98Type* poptSetting); // (/OPT:WIN98, /OPT:NOWIN98, not set)
STDMETHOD(put_OptimizeForWindows98)(optWin98Type optSetting);
STDMETHOD(get_FunctionOrder)(BSTR* pbstrOrder); // (/ORDER:@[file]) place functions in order specified in file
STDMETHOD(put_FunctionOrder)(BSTR bstrOrder);
};
class ATL_NO_VTABLE CVCLinkerAdvancedPage :
public CVCLinkerBasePage<CVCLinkerAdvancedPage, IVCLinkerAdvancedPage>
{
// IVCLinkerAdvancedPage
public:
STDMETHOD(get_EntryPointSymbol)(BSTR* pbstrEntry); // (/ENTRY:[symbol]) set entry point address for EXE or DLL; incompatible with /NOENTRY
STDMETHOD(put_EntryPointSymbol)(BSTR bstrEntry);
STDMETHOD(get_ResourceOnlyDLL)(enumResourceOnlyDLLBOOL* pbNoEntry); // (/NOENTRY) no entry point. required for resource-only DLLs; incompatible with /ENTRY
STDMETHOD(put_ResourceOnlyDLL)(enumResourceOnlyDLLBOOL bNoEntry);
STDMETHOD(get_SetChecksum)(enumSetChecksumBOOL* pbRelease); // (/RELEASE) set the checksum in the header of a .exe
STDMETHOD(put_SetChecksum)(enumSetChecksumBOOL bRelease);
STDMETHOD(get_BaseAddress)(BSTR* pbstrAddress); // (/BASE:{address| filename,key}) base address to place program at; can be numeric or string
STDMETHOD(put_BaseAddress)(BSTR bstrAddress);
STDMETHOD(get_TurnOffAssemblyGeneration)(enumTurnOffAssemblyGenerationBOOL* pbNoAssy); // (/NOASSEMBLY) cause the output file to be built without an assembly
STDMETHOD(put_TurnOffAssemblyGeneration)(enumTurnOffAssemblyGenerationBOOL bNoAssy);
STDMETHOD(get_SupportUnloadOfDelayLoadedDLL)(enumSupportUnloadOfDelayLoadedDLLBOOL* pbDelay); // (/DELAY:UNLOAD) use to allow explicit unloading of the DLL
STDMETHOD(put_SupportUnloadOfDelayLoadedDLL)(enumSupportUnloadOfDelayLoadedDLLBOOL bDelay);
STDMETHOD(get_ImportLibrary)(BSTR* pbstrImportLib); // (/IMPLIB:[library]) generate specified import library
STDMETHOD(put_ImportLibrary)(BSTR bstrImportLib);
STDMETHOD(get_MergeSections)(BSTR* pbstrMerge); // (/MERGE:from=to) merge section 'from' into section 'to'
STDMETHOD(put_MergeSections)(BSTR bstrMerge);
STDMETHOD(get_TargetMachine)(machineTypeOption* poptSetting); // (/MACHINE:type) specify target platform
STDMETHOD(put_TargetMachine)(machineTypeOption optSetting);
};
class ATL_NO_VTABLE CVCLinkerMIDLPage :
public CVCLinkerBasePage<CVCLinkerMIDLPage, IVCLinkerMIDLPage>
{
// IVCLinkerMIDLPage
public:
STDMETHOD(get_MidlCommandFile)(BSTR* pbstrMidlCmdFile); // (/midl:<@midl cmd file>) specify response file for MIDL commands to use
STDMETHOD(put_MidlCommandFile)(BSTR bstrMidlCmdFile);
STDMETHOD(get_IgnoreEmbeddedIDL)(enumIgnoreEmbeddedIDLBOOL* pbIgnoreIDL); // (/ignoreidl) ignore .idlsym sections of .obj files
STDMETHOD(put_IgnoreEmbeddedIDL)(enumIgnoreEmbeddedIDLBOOL bIgnoreIDL);
STDMETHOD(get_MergedIDLBaseFileName)(BSTR* pbstrIDLFile); // (/idlout:<filename>) name intermediate IDL output file
STDMETHOD(put_MergedIDLBaseFileName)(BSTR bstrIDLFile);
STDMETHOD(get_TypeLibraryFile)(BSTR* pbstrTLBFile); // (/tlbout:<filename>) name intermediate typelib output file
STDMETHOD(put_TypeLibraryFile)(BSTR bstrTLBFile);
STDMETHOD(get_TypeLibraryResourceID)(long* pnResID); // (/tlbid:<id>) specify resource ID for generated .tlb file
STDMETHOD(put_TypeLibraryResourceID)(long nResID);
protected:
virtual BOOL UseCommandsDialog(long id) { return (id == VCLINKID_MidlCommandFile); }
};
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
5b5961313b5527742e6ea14425353175d0aa3c72 | 6090f669e19701747f639cffe7fea50979155661 | /IMU_Code_Abbreviated/IMU_Code_Abbreviated.ino | 0a6ffcc68f13420cff883294a9e3a5d5ed6b1ce6 | [] | no_license | capuanomat/Mini-Quanser-Project | c0a1b52dc4b488442fd6acf67380ed79d0227762 | 8b5d863b4f86e809ef088fbdb2a29e58b19e8e78 | refs/heads/master | 2020-05-30T08:04:33.755443 | 2018-04-26T16:43:30 | 2018-04-26T16:43:30 | 95,507,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,216 | ino | // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
// MATTHIEU
#include <stdio.h>
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high
/* =========================================================================
NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
depends on the MPU-6050's INT pin being connected to the Arduino's
external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
digital I/O pin 2.
* ========================================================================= */
// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL
#define INTERRUPT_PIN 2 // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;
// MPU control/status vars
bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer
// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
int x = 50;
// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}
// ================================================================
// === INITIAL SETUP ===
// ================================================================
void setup() {
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
// initialize serial communication
// (115200 chosen because it is required for Teapot Demo output, but it's
// really up to you depending on your project)
Serial.begin(9600);
while (!Serial); // wait for Leonardo enumeration, others continue immediately
// NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
// Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
// the baud timing being too misaligned with processor ticks. You must use
// 38400 or slower in these cases, or use some kind of external separate
// crystal solution for the UART timer.
// initialize device
Serial.println(F("Initializing I2C devices..."));
mpu.initialize();
pinMode(INTERRUPT_PIN, INPUT);
// verify connection
Serial.println(F("Testing device connections..."));
Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
// wait for ready
Serial.println(F("\nSend any character to begin DMP programming and demo: "));
while (Serial.available() && Serial.read()); // empty buffer
while (!Serial.available()); // wait for data
while (Serial.available() && Serial.read()); // empty buffer again
// load and configure the DMP
Serial.println(F("Initializing DMP..."));
devStatus = mpu.dmpInitialize();
// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXAccelOffset(-1639);
mpu.setYAccelOffset(-443);
mpu.setZAccelOffset(976);
mpu.setXGyroOffset(110);
mpu.setYGyroOffset(-69);
mpu.setZGyroOffset(5);
//mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// turn on the DMP, now that it's ready
Serial.println(F("Enabling DMP..."));
mpu.setDMPEnabled(true);
// enable Arduino interrupt detection
Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
Serial.println(F("DMP ready! Waiting for first interrupt..."));
dmpReady = true;
// get expected DMP packet size for later comparison
packetSize = mpu.dmpGetFIFOPacketSize();
} else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
Serial.print(F("DMP Initialization failed (code "));
Serial.print(devStatus);
Serial.println(F(")"));
}
// configure LED for output
pinMode(LED_PIN, OUTPUT);
}
// ================================================================
// === MAIN PROGRAM LOOP ===
// ================================================================
void loop() {
// if programming failed, don't try to do anything
if (!dmpReady) return;
// wait for MPU interrupt or extra packet(s) available
while (!mpuInterrupt && fifoCount < packetSize) {
// other program behavior stuff here
// .
// .
// .
// if you are really paranoid you can frequently test in between other
// stuff to see if mpuInterrupt is true, and if so, "break;" from the
// while() loop to immediately process the MPU data
// .
// .
// .
}
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
Serial.println(F("FIFO overflow!"));
// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
#ifdef OUTPUT_READABLE_YAWPITCHROLL
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
//Serial.print("Error\t");
//Serial.print(ypr[0] * 180/M_PI);
Serial.print("PITCH \t");
Serial.println(ypr[1] * 180/M_PI);
//desired = Serial.read();
//error = desired - (ypr[1] * 180/M_PI);
//Serial.println(error);
//Serial.print("\t");
//Serial.println(ypr[2] * 180/M_PI);
#endif
// blink LED to indicate activity
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
}
float getpitch() {
return ypr[1];
}
}
| [
"capuanomat@gmail.com"
] | capuanomat@gmail.com |
05a3da6ece61f766d7e778a43a3093906b0641d8 | d392c6c567ecb9a9ea76ae279759879dc36868ef | /ADS1115_Sensor_Check.ino | fb1b171f211ed27ea857d4e71eb993e3668881c7 | [
"Unlicense"
] | permissive | hansvana/ADS1115_Sensor_Check | ef2748cb1c88641d673117189017ffda0cc09ec1 | bcbead401fb147a8cc8cf57868aee2869b4a1c9c | refs/heads/main | 2023-03-16T10:39:45.105769 | 2021-03-06T16:13:22 | 2021-03-06T16:13:22 | 345,136,732 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,230 | ino | /**************************************************************************/
/*
Distributed with a free-will license.
Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
ADS1115
This code is designed to work with the ADS1115_I2CADC I2C Mini Module available from ControlEverything.com.
https://www.controleverything.com/content/Analog-Digital-Converters?sku=ADS1115_I2CADC#tabs-0-product_tabset-2
*/
/**************************************************************************/
#include <Wire.h>
#include <ADS1115.h>
ADS1115 ads;
void setup(void)
{
Serial.begin(9600);
// The address can be changed making the option of connecting multiple devices
ads.getAddr_ADS1115(ADS1115_DEFAULT_ADDRESS); // 0x48, 1001 000 (ADDR = GND)
// ads.getAddr_ADS1115(ADS1115_VDD_ADDRESS); // 0x49, 1001 001 (ADDR = VDD)
// ads.getAddr_ADS1115(ADS1115_SDA_ADDRESS); // 0x4A, 1001 010 (ADDR = SDA)
// ads.getAddr_ADS1115(ADS1115_SCL_ADDRESS); // 0x4B, 1001 011 (ADDR = SCL)
// The ADC gain (PGA), Device operating mode, Data rate
// can be changed via the following functions
ads.setGain(GAIN_TWO); // 2x gain +/- 2.048V 1 bit = 0.0625mV (default)
//ads.setGain(GAIN_TWOTHIRDS); // 2/3x gain +/- 6.144V 1 bit = 0.1875mV
// ads.setGain(GAIN_ONE); // 1x gain +/- 4.096V 1 bit = 0.125mV
// ads.setGain(GAIN_FOUR); // 4x gain +/- 1.024V 1 bit = 0.03125mV
// ads.setGain(GAIN_EIGHT); // 8x gain +/- 0.512V 1 bit = 0.015625mV
// ads.setGain(GAIN_SIXTEEN); // 16x gain +/- 0.256V 1 bit = 0.0078125mV
ads.setMode(MODE_CONTIN); // Continuous conversion mode
// ads.setMode(MODE_SINGLE); // Power-down single-shot mode (default)
ads.setRate(RATE_128); // 128SPS (default)
// ads.setRate(RATE_8); // 8SPS
// ads.setRate(RATE_16); // 16SPS
// ads.setRate(RATE_32); // 32SPS
// ads.setRate(RATE_64); // 64SPS
// ads.setRate(RATE_250); // 250SPS
// ads.setRate(RATE_475); // 475SPS
// ads.setRate(RATE_860); // 860SPS
ads.setOSMode(OSMODE_SINGLE); // Set to start a single-conversion
ads.begin();
}
void loop(void)
{
byte error;
int8_t address;
address = ads.ads_i2cAddress;
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
int16_t adc0, adc1, adc2, adc3;
adc0 = ads.Measure_SingleEnded(0);
float mACurrent = adc0 * 0.000628;
Serial.print("Current Loop Input at Channel 1: ");
Serial.println(mACurrent,3);
adc1 = ads.Measure_SingleEnded(1);
float mACurrent1 = adc1 * 0.000628;
Serial.print("Current Loop Input at Channel 2: ");
Serial.println(mACurrent1,3);
}
else
{
Serial.println("ADS1115 Disconnected!");
Serial.println(" ");
Serial.println(" ************ ");
Serial.println(" ");
}
delay(1000);
}
| [
"hansvanarken@gmail.com"
] | hansvanarken@gmail.com |
81a7c0b028977e0e2bc2818a0af9fc9358c2f152 | 5e557741c8867bca4c4bcf2d5e67409211d059a3 | /torch/csrc/jit/tensorexpr/tensor.cpp | c78f27f19b6707545ac1c5f3414e9b6033207dcc | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0"
] | permissive | Pandinosaurus/pytorch | a2bb724cfc548f0f2278b5af2fd8b1d2758adb76 | bb8978f605e203fbb780f03010fefbece35ac51c | refs/heads/master | 2023-05-02T20:07:23.577610 | 2021-11-05T14:01:30 | 2021-11-05T14:04:40 | 119,666,381 | 2 | 0 | NOASSERTION | 2021-11-05T19:55:56 | 2018-01-31T09:37:34 | C++ | UTF-8 | C++ | false | false | 5,045 | cpp | #include <torch/csrc/jit/tensorexpr/tensor.h>
#include <c10/util/Logging.h>
#include <c10/util/irange.h>
#include <torch/csrc/jit/tensorexpr/dim_arg.h>
#include <torch/csrc/jit/tensorexpr/reduction.h>
namespace torch {
namespace jit {
namespace tensorexpr {
StmtPtr Tensor::constructStmt(
const std::vector<VarPtr>& args,
ExprPtr body,
const std::vector<ExprPtr>& reduce_dims,
const std::vector<VarPtr>& reduce_args) const {
std::vector<ExprPtr> indices(args.begin(), args.end());
StmtPtr s = alloc<Store>(buf_, indices, body);
size_t ndim = buf()->ndim();
size_t reduce_ndim = reduce_dims.size();
if (ndim == 0 && reduce_ndim == 0) {
return s;
}
ExprPtr init_expr = buf()->initializer();
if (reduce_ndim > 0) {
for (const auto i : c10::irange(reduce_ndim)) {
// Going in reverse order: from innermost loop to the outermost
size_t dim_index = reduce_ndim - i - 1;
auto const& dim = reduce_dims[dim_index];
s = alloc<For>(reduce_args[dim_index], immLike(dim, 0), dim, s);
}
if (init_expr) {
StorePtr init_stmt = alloc<Store>(buf(), indices, init_expr);
s = alloc<Block>(std::vector<StmtPtr>({init_stmt, s}));
}
}
for (const auto i : c10::irange(ndim)) {
// Going in reverse order: from innermost loop to the outermost
size_t dim_index = ndim - i - 1;
auto const& dim = buf()->dim(dim_index);
s = alloc<For>(args[dim_index], immLike(dim, 0), dim, s);
}
return s;
}
Tensor Compute(
const std::string& name,
const std::vector<DimArg>& dim_args,
const std::function<ExprHandle(const std::vector<VarHandle>&)>& body_func) {
std::vector<ExprPtr> dims;
std::vector<VarPtr> args;
unpack_dim_args(dim_args, &dims, &args);
ExprPtr body = body_func(VarVectorToVarHandleVector(args)).node();
BufPtr buf = alloc<Buf>(name, dims, body->dtype());
return Tensor(buf, args, body);
}
Tensor Compute(
const std::string& name,
const std::vector<DimArg>& dim_args,
const std::function<ExprHandle(const VarHandle&)>& body_func) {
if (dim_args.size() != 1) {
throw malformed_input("mismatch between body and arg size (1)");
}
std::vector<ExprPtr> dims;
std::vector<VarPtr> args;
unpack_dim_args(dim_args, &dims, &args);
ExprPtr body = body_func(VarHandle(args[0])).node();
BufPtr buf = alloc<Buf>(name, dims, body->dtype());
return Tensor(buf, args, body);
}
Tensor Compute(
const std::string& name,
const std::vector<DimArg>& dim_args,
const std::function<ExprHandle(const VarHandle&, const VarHandle&)>&
body_func) {
if (dim_args.size() != 2) {
throw malformed_input("mismatch between body and arg size (2)");
}
std::vector<ExprPtr> dims;
std::vector<VarPtr> args;
unpack_dim_args(dim_args, &dims, &args);
ExprPtr body = body_func(VarHandle(args[0]), VarHandle(args[1])).node();
BufPtr buf = alloc<Buf>(name, dims, body->dtype());
return Tensor(buf, args, body);
}
Tensor Compute(
const std::string& name,
const std::vector<DimArg>& dim_args,
const std::function<
ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>&
body_func) {
if (dim_args.size() != 3) {
throw malformed_input("mismatch between body and arg size (3)");
}
std::vector<ExprPtr> dims;
std::vector<VarPtr> args;
unpack_dim_args(dim_args, &dims, &args);
ExprPtr body =
body_func(VarHandle(args[0]), VarHandle(args[1]), VarHandle(args[2]))
.node();
BufPtr buf = alloc<Buf>(name, dims, body->dtype());
return Tensor(buf, args, body);
}
Tensor Compute(
const std::string& name,
const std::vector<DimArg>& dim_args,
const std::function<ExprHandle(
const VarHandle&,
const VarHandle&,
const VarHandle&,
const VarHandle&)>& body_func) {
if (dim_args.size() != 4) {
throw malformed_input("mismatch between body and arg size (4)");
}
std::vector<ExprPtr> dims;
std::vector<VarPtr> args;
unpack_dim_args(dim_args, &dims, &args);
ExprPtr body = body_func(
VarHandle(args[0]),
VarHandle(args[1]),
VarHandle(args[2]),
VarHandle(args[3]))
.node();
BufPtr buf = alloc<Buf>(name, dims, body->dtype());
return Tensor(buf, args, body);
}
Tensor Reduce(
const std::string& name,
const std::vector<DimArg>& dim_args,
const Reducer& reducer,
const BufHandle& buffer,
const std::vector<DimArg>& reduce_args) {
return Reduce(
name,
dim_args,
reducer,
[&](ParameterList& p) { return buffer.load(p); },
reduce_args);
}
Tensor Reduce(
const std::string& name,
const std::vector<DimArg>& dim_args,
const Reducer& reducer,
Tensor tensor,
const std::vector<DimArg>& reduce_args) {
return Reduce(
name,
dim_args,
reducer,
[&](ParameterList& p) { return tensor.load(p); },
reduce_args);
}
} // namespace tensorexpr
} // namespace jit
} // namespace torch
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
d6d54274af57bf2277fe6a8be8a037555d39d78a | f82577a89c347c477db1c3247aa7a88774cf9275 | /include/fast-fair/btree.h | 5c0f24914e4f70d95bb378c37d9cf777611ff5a0 | [] | no_license | xiaoliou008/bysj | 7c4a4c0672dfd00054bbe3964fbbb27c18a0c4ac | 17cc879eca64767d7fe4dbbf2a88fa29bd47e3fe | refs/heads/main | 2023-05-05T15:24:19.571979 | 2021-03-31T05:08:59 | 2021-03-31T05:08:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,368 | h | /*
Copyright (c) 2018, UNIST. All rights reserved. The license is a free
non-exclusive, non-transferable license to reproduce, use, modify and display
the source code version of the Software, with or without modifications solely
for non-commercial research, educational or evaluation purposes. The license
does not entitle Licensee to technical support, telephone assistance,
enhancements or updates to the Software. All rights, title to and ownership
interest in the Software, including all intellectual property rights therein
shall remain in UNIST.
*/
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string.h>
#include <cassert>
#include <climits>
#include <future>
#include <mutex>
#include "nvm_alloc.h"
#define PAGESIZE 256
#define CACHE_LINE_SIZE 64
#define IS_FORWARD(c) (c % 2 == 0)
using entry_key_t = uint64_t;
using namespace std;
inline void clflush(char *data, int len)
{
#ifndef USE_MEM
NVM::Mem_persist(data, len);
#endif
}
namespace FastFair
{
// const size_t NVM_ValueSize = 256;
static void alloc_memalign(void **ret, size_t alignment, size_t size) {
#ifdef USE_MEM
posix_memalign(ret, alignment, size);
#else
*ret = NVM::data_alloc->alloc(size);
#endif
}
class page;
class btree {
private:
int height;
char* root;
public:
btree();
btree(page *root);
void setNewRoot(char *);
void btree_insert(entry_key_t, char*);
void btree_insert_internal(char *, entry_key_t, char *, uint32_t);
void btree_delete(entry_key_t);
void btree_delete_internal(entry_key_t, char *, uint32_t, entry_key_t *, bool *, page **);
char *btree_search(entry_key_t);
page *btree_search_leaf(entry_key_t);
void btree_search_range(entry_key_t, entry_key_t, unsigned long *);
void btree_search_range(entry_key_t, entry_key_t, std::vector<pair<entry_key_t, uint64_t>> &result, int &size);
void btree_search_range(entry_key_t, entry_key_t, void **values, int &size);
void printAll();
void PrintInfo();
void CalculateSapce(uint64_t &space);
friend class page;
};
class header{
private:
page* leftmost_ptr; // 8 bytes
page* sibling_ptr; // 8 bytes
uint32_t level; // 4 bytes
uint8_t switch_counter; // 1 bytes
uint8_t is_deleted; // 1 bytes
int16_t last_index; // 2 bytes
char dummy[8]; // 8 bytes
friend class page;
friend class btree;
public:
header() {
leftmost_ptr = NULL;
sibling_ptr = NULL;
switch_counter = 0;
last_index = -1;
is_deleted = false;
}
~header() {
}
};
class entry{
private:
entry_key_t key; // 8 bytes
char* ptr; // 8 bytes
public :
entry(){
key = LONG_MAX;
ptr = NULL;
}
friend class page;
friend class btree;
};
const int cardinality = (PAGESIZE-sizeof(header))/sizeof(entry);
const int count_in_line = CACHE_LINE_SIZE / sizeof(entry);
class page{
private:
header hdr; // header in persistent memory, 16 bytes
entry records[cardinality]; // slots in persistent memory, 16 bytes * n
public:
friend class btree;
page(uint32_t level = 0) {
hdr.level = level;
records[0].ptr = NULL;
}
// this is called when tree grows
page(page* left, entry_key_t key, page* right, uint32_t level = 0) {
hdr.leftmost_ptr = left;
hdr.level = level;
records[0].key = key;
records[0].ptr = (char*) right;
records[1].ptr = NULL;
hdr.last_index = 0;
clflush((char*)this, sizeof(page));
}
void *operator new(size_t size) {
void *ret;
// posix_memalign(&ret,64,size);
alloc_memalign(&ret, 64, size);
return ret;
}
uint32_t GetLevel() {
return hdr.level;
}
void linear_search_range(entry_key_t min, entry_key_t max,
std::vector<pair<entry_key_t, uint64_t>> &result, int &size);
void linear_search_range(entry_key_t min, entry_key_t max, void **values, int &size);
inline int count() {
uint8_t previous_switch_counter;
int count = 0;
do {
previous_switch_counter = hdr.switch_counter;
count = hdr.last_index + 1;
while(count >= 0 && records[count].ptr != NULL) {
if(IS_FORWARD(previous_switch_counter))
++count;
else
--count;
}
if(count < 0) {
count = 0;
while(records[count].ptr != NULL) {
++count;
}
}
} while(previous_switch_counter != hdr.switch_counter);
return count;
}
inline bool remove_key(entry_key_t key) {
// Set the switch_counter
if(IS_FORWARD(hdr.switch_counter))
++hdr.switch_counter;
bool shift = false;
int i;
for(i = 0; records[i].ptr != NULL; ++i) {
if(!shift && records[i].key == key) {
records[i].ptr = (i == 0) ?
(char *)hdr.leftmost_ptr : records[i - 1].ptr;
shift = true;
}
if(shift) {
records[i].key = records[i + 1].key;
records[i].ptr = records[i + 1].ptr;
// sbh modify
// clflush((char *)(&records[i]), sizeof(entry));
// flush
uint64_t records_ptr = (uint64_t)(&records[i]);
int remainder = records_ptr % CACHE_LINE_SIZE;
bool do_flush = (remainder == 0) ||
((((int)(remainder + sizeof(entry)) / CACHE_LINE_SIZE) == 1) &&
((remainder + sizeof(entry)) % CACHE_LINE_SIZE) != 0);
if(do_flush) {
clflush((char *)records_ptr, CACHE_LINE_SIZE);
}
}
}
if(shift) {
--hdr.last_index;
clflush((char *)&(hdr.last_index), sizeof(int16_t));
}
return shift;
}
bool remove(btree* bt, entry_key_t key, bool only_rebalance = false, bool with_lock = true) {
if(!only_rebalance) {
register int num_entries_before = count();
// This node is root
if(this == (page *)bt->root) {
if(hdr.level > 0) {
if(num_entries_before == 1 && !hdr.sibling_ptr) {
bt->root = (char *)hdr.leftmost_ptr;
clflush((char *)&(bt->root), sizeof(char *));
hdr.is_deleted = 1;
clflush((char *)&(hdr.is_deleted), sizeof(uint8_t));
}
}
// Remove the key from this node
bool ret = remove_key(key);
return true;
}
bool should_rebalance = true;
// check the node utilization
if(num_entries_before - 1 >= (int)((cardinality - 1) * 0.5)) {
should_rebalance = false;
}
// Remove the key from this node
bool ret = remove_key(key);
if(!should_rebalance) {
return (hdr.leftmost_ptr == NULL) ? ret : true;
}
}
//Remove a key from the parent node
entry_key_t deleted_key_from_parent = 0;
bool is_leftmost_node = false;
page *left_sibling;
bt->btree_delete_internal(key, (char *)this, hdr.level + 1,
&deleted_key_from_parent, &is_leftmost_node, &left_sibling);
if(is_leftmost_node) {
hdr.sibling_ptr->remove(bt, hdr.sibling_ptr->records[0].key, true,
with_lock);
return true;
}
register int num_entries = count();
register int left_num_entries = left_sibling->count();
// Merge or Redistribution
int total_num_entries = num_entries + left_num_entries;
if(hdr.leftmost_ptr)
++total_num_entries;
entry_key_t parent_key;
if(total_num_entries > cardinality - 1) { // Redistribution
register int m = (int) ceil(total_num_entries / 2);
if(num_entries < left_num_entries) { // left -> right
if(hdr.leftmost_ptr == nullptr){
for(int i=left_num_entries - 1; i>=m; i--){
insert_key
(left_sibling->records[i].key, left_sibling->records[i].ptr, &num_entries);
}
left_sibling->records[m].ptr = nullptr;
clflush((char *)&(left_sibling->records[m].ptr), sizeof(char *));
left_sibling->hdr.last_index = m - 1;
clflush((char *)&(left_sibling->hdr.last_index), sizeof(int16_t));
parent_key = records[0].key;
}
else{
insert_key(deleted_key_from_parent, (char*)hdr.leftmost_ptr,
&num_entries);
for(int i=left_num_entries - 1; i>m; i--){
insert_key
(left_sibling->records[i].key, left_sibling->records[i].ptr, &num_entries);
}
parent_key = left_sibling->records[m].key;
hdr.leftmost_ptr = (page*)left_sibling->records[m].ptr;
clflush((char *)&(hdr.leftmost_ptr), sizeof(page *));
left_sibling->records[m].ptr = nullptr;
clflush((char *)&(left_sibling->records[m].ptr), sizeof(char *));
left_sibling->hdr.last_index = m - 1;
clflush((char *)&(left_sibling->hdr.last_index), sizeof(int16_t));
}
if(left_sibling == ((page *)bt->root)) {
page* new_root = new page(left_sibling, parent_key, this, hdr.level + 1);
bt->setNewRoot((char *)new_root);
}
else {
bt->btree_insert_internal
((char *)left_sibling, parent_key, (char *)this, hdr.level + 1);
}
}
else{ // from leftmost case
hdr.is_deleted = 1;
clflush((char *)&(hdr.is_deleted), sizeof(uint8_t));
page* new_sibling = new page(hdr.level);
new_sibling->hdr.sibling_ptr = hdr.sibling_ptr;
int num_dist_entries = num_entries - m;
int new_sibling_cnt = 0;
if(hdr.leftmost_ptr == nullptr){
for(int i=0; i<num_dist_entries; i++){
left_sibling->insert_key(records[i].key, records[i].ptr,
&left_num_entries);
}
for(int i=num_dist_entries; records[i].ptr != NULL; i++){
new_sibling->insert_key(records[i].key, records[i].ptr,
&new_sibling_cnt, false);
}
clflush((char *)(new_sibling), sizeof(page));
left_sibling->hdr.sibling_ptr = new_sibling;
clflush((char *)&(left_sibling->hdr.sibling_ptr), sizeof(page *));
parent_key = new_sibling->records[0].key;
}
else{
left_sibling->insert_key(deleted_key_from_parent,
(char*)hdr.leftmost_ptr, &left_num_entries);
for(int i=0; i<num_dist_entries - 1; i++){
left_sibling->insert_key(records[i].key, records[i].ptr,
&left_num_entries);
}
parent_key = records[num_dist_entries - 1].key;
new_sibling->hdr.leftmost_ptr = (page*)records[num_dist_entries - 1].ptr;
for(int i=num_dist_entries; records[i].ptr != NULL; i++){
new_sibling->insert_key(records[i].key, records[i].ptr,
&new_sibling_cnt, false);
}
clflush((char *)(new_sibling), sizeof(page));
left_sibling->hdr.sibling_ptr = new_sibling;
clflush((char *)&(left_sibling->hdr.sibling_ptr), sizeof(page *));
}
if(left_sibling == ((page *)bt->root)) {
page* new_root = new page(left_sibling, parent_key, new_sibling, hdr.level + 1);
bt->setNewRoot((char *)new_root);
}
else {
bt->btree_insert_internal
((char *)left_sibling, parent_key, (char *)new_sibling, hdr.level + 1);
}
}
}
else {
hdr.is_deleted = 1;
clflush((char *)&(hdr.is_deleted), sizeof(uint8_t));
if(hdr.leftmost_ptr)
left_sibling->insert_key(deleted_key_from_parent,
(char *)hdr.leftmost_ptr, &left_num_entries);
for(int i = 0; records[i].ptr != NULL; ++i) {
left_sibling->insert_key(records[i].key, records[i].ptr, &left_num_entries);
}
left_sibling->hdr.sibling_ptr = hdr.sibling_ptr;
clflush((char *)&(left_sibling->hdr.sibling_ptr), sizeof(page *));
}
return true;
}
inline void
insert_key(entry_key_t key, char* ptr, int *num_entries, bool flush = true,
bool update_last_index = true) {
// update switch_counter
if(!IS_FORWARD(hdr.switch_counter))
++hdr.switch_counter;
// FAST
if(*num_entries == 0) { // this page is empty
entry* new_entry = (entry*) &records[0];
entry* array_end = (entry*) &records[1];
new_entry->key = (entry_key_t) key;
new_entry->ptr = (char*) ptr;
array_end->ptr = (char*)NULL;
if(flush) {
clflush((char*) this, CACHE_LINE_SIZE);
}
}
else {
int i = *num_entries - 1, inserted = 0, to_flush_cnt = 0;
records[*num_entries+1].ptr = records[*num_entries].ptr;
// clflush((char*)&(records[*num_entries+1].ptr), sizeof(char*));
if(flush) {
if((uint64_t)&(records[*num_entries+1].ptr) % CACHE_LINE_SIZE == 0)
clflush((char*)&(records[*num_entries+1].ptr), sizeof(char*));
}
// FAST
for(i = *num_entries - 1; i >= 0; i--) {
if(key < records[i].key ) {
records[i+1].ptr = records[i].ptr;
records[i+1].key = records[i].key;
// clflush((char *)(&records[i+1]), sizeof(entry));
if(flush) {
uint64_t records_ptr = (uint64_t)(&records[i+1]);
int remainder = records_ptr % CACHE_LINE_SIZE;
bool do_flush = (remainder == 0) ||
((((int)(remainder + sizeof(entry)) / CACHE_LINE_SIZE) == 1)
&& ((remainder+sizeof(entry))%CACHE_LINE_SIZE)!=0);
if(do_flush) {
clflush((char*)records_ptr,CACHE_LINE_SIZE);
to_flush_cnt = 0;
}
else
++to_flush_cnt;
}
}
else{
records[i+1].ptr = records[i].ptr;
records[i+1].key = key;
records[i+1].ptr = ptr;
// clflush((char *)(&records[i+1]), sizeof(entry));
if(flush)
clflush((char*)&records[i+1],sizeof(entry));
inserted = 1;
break;
}
}
if(inserted==0){
records[0].ptr =(char*) hdr.leftmost_ptr;
records[0].key = key;
records[0].ptr = ptr;
if(flush)
clflush((char*) &records[0], sizeof(entry));
}
}
if(update_last_index) {
hdr.last_index = *num_entries;
clflush((char *)&(hdr.last_index), sizeof(int16_t));
}
++(*num_entries);
}
// Insert a new key - FAST and FAIR
page *store
(btree* bt, char* left, entry_key_t key, char* right,
bool flush, page *invalid_sibling = NULL) {
// If this node has a sibling node,
if(hdr.sibling_ptr && (hdr.sibling_ptr != invalid_sibling)) {
// Compare this key with the first key of the sibling
if(key > hdr.sibling_ptr->records[0].key) {
return hdr.sibling_ptr->store(bt, NULL, key, right,
true, invalid_sibling);
}
}
register int num_entries = count();
// FAST
if(num_entries < cardinality - 1) {
insert_key(key, right, &num_entries, flush);
return this;
}
else {// FAIR
// overflow
// create a new node
page* sibling = new page(hdr.level);
register int m = (int) ceil(num_entries/2);
entry_key_t split_key = records[m].key;
// migrate half of keys into the sibling
int sibling_cnt = 0;
if(hdr.leftmost_ptr == NULL){ // leaf node
for(int i=m; i<num_entries; ++i){
sibling->insert_key(records[i].key, records[i].ptr, &sibling_cnt, false);
}
}
else{ // internal node
for(int i=m+1;i<num_entries;++i){
sibling->insert_key(records[i].key, records[i].ptr, &sibling_cnt, false);
}
sibling->hdr.leftmost_ptr = (page*) records[m].ptr;
}
sibling->hdr.sibling_ptr = hdr.sibling_ptr;
clflush((char *)sibling, sizeof(page));
hdr.sibling_ptr = sibling;
clflush((char*) &hdr, sizeof(hdr));
// set to NULL
if(IS_FORWARD(hdr.switch_counter))
hdr.switch_counter += 2;
else
++hdr.switch_counter;
records[m].ptr = NULL;
clflush((char*) &records[m], sizeof(entry));
hdr.last_index = m - 1;
clflush((char *)&(hdr.last_index), sizeof(int16_t));
num_entries = hdr.last_index + 1;
page *ret;
// insert the key
if(key < split_key) {
insert_key(key, right, &num_entries);
ret = this;
}
else {
sibling->insert_key(key, right, &sibling_cnt);
ret = sibling;
}
// Set a new root or insert the split key to the parent
if(bt->root == (char *)this) { // only one node can update the root ptr
page* new_root = new page((page*)this, split_key, sibling,
hdr.level + 1);
bt->setNewRoot((char *)new_root);
}
else {
bt->btree_insert_internal(NULL, split_key, (char *)sibling,
hdr.level + 1);
}
return ret;
}
}
// Search keys with linear search
void linear_search_range
(entry_key_t min, entry_key_t max, unsigned long *buf) {
int i, off = 0;
uint8_t previous_switch_counter;
page *current = this;
while(current) {
int old_off = off;
do {
previous_switch_counter = current->hdr.switch_counter;
off = old_off;
entry_key_t tmp_key;
char *tmp_ptr;
if(IS_FORWARD(previous_switch_counter)) {
if((tmp_key = current->records[0].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[0].ptr) != NULL) {
if(tmp_key == current->records[0].key) {
if(tmp_ptr) {
buf[off++] = (unsigned long)tmp_ptr;
}
}
}
}
else
return;
}
for(i=1; current->records[i].ptr != NULL; ++i) {
if((tmp_key = current->records[i].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[i].ptr) != current->records[i - 1].ptr) {
if(tmp_key == current->records[i].key) {
if(tmp_ptr)
buf[off++] = (unsigned long)tmp_ptr;
}
}
}
else
return;
}
}
}
else {
for(i=count() - 1; i > 0; --i) {
if((tmp_key = current->records[i].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[i].ptr) != current->records[i - 1].ptr) {
if(tmp_key == current->records[i].key) {
if(tmp_ptr)
buf[off++] = (unsigned long)tmp_ptr;
}
}
}
else
return;
}
}
if((tmp_key = current->records[0].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[0].ptr) != NULL) {
if(tmp_key == current->records[0].key) {
if(tmp_ptr) {
buf[off++] = (unsigned long)tmp_ptr;
}
}
}
}
else
return;
}
}
} while(previous_switch_counter != current->hdr.switch_counter);
current = current->hdr.sibling_ptr;
}
}
char *linear_search(entry_key_t key) {
int i = 1;
uint8_t previous_switch_counter;
char *ret = NULL;
char *t;
entry_key_t k;
if(hdr.leftmost_ptr == NULL) { // Search a leaf node
do {
previous_switch_counter = hdr.switch_counter;
ret = NULL;
// search from left ro right
if(IS_FORWARD(previous_switch_counter)) {
if((k = records[0].key) == key) {
if((t = records[0].ptr) != NULL) {
if(k == records[0].key) {
ret = t;
continue;
}
}
}
for(i=1; records[i].ptr != NULL; ++i) {
if((k = records[i].key) == key) {
if(records[i-1].ptr != (t = records[i].ptr)) {
if(k == records[i].key) {
ret = t;
break;
}
}
}
}
}
else { // search from right to left
for(i = count() - 1; i > 0; --i) {
if((k = records[i].key) == key) {
if(records[i - 1].ptr != (t = records[i].ptr) && t) {
if(k == records[i].key) {
ret = t;
break;
}
}
}
}
if(!ret) {
if((k = records[0].key) == key) {
if(NULL != (t = records[0].ptr) && t) {
if(k == records[0].key) {
ret = t;
continue;
}
}
}
}
}
} while(hdr.switch_counter != previous_switch_counter);
if(ret) {
return ret;
}
if((t = (char *)hdr.sibling_ptr) && key >= ((page *)t)->records[0].key)
return t;
return NULL;
}
else { // internal node
do {
previous_switch_counter = hdr.switch_counter;
ret = NULL;
if(IS_FORWARD(previous_switch_counter)) {
if(key < (k = records[0].key)) {
if((t = (char *)hdr.leftmost_ptr) != records[0].ptr) {
ret = t;
continue;
}
}
for(i = 1; records[i].ptr != NULL; ++i) {
if(key < (k = records[i].key)) {
if((t = records[i-1].ptr) != records[i].ptr) {
ret = t;
break;
}
}
}
if(!ret) {
ret = records[i - 1].ptr;
continue;
}
}
else { // search from right to left
for(i = count() - 1; i >= 0; --i) {
if(key >= (k = records[i].key)) {
if(i == 0) {
if((char *)hdr.leftmost_ptr != (t = records[i].ptr)) {
ret = t;
break;
}
}
else {
if(records[i - 1].ptr != (t = records[i].ptr)) {
ret = t;
break;
}
}
}
}
}
} while(hdr.switch_counter != previous_switch_counter);
if((t = (char *)hdr.sibling_ptr) != NULL) {
if(key >= ((page *)t)->records[0].key)
return t;
}
if(ret) {
return ret;
}
else
return (char *)hdr.leftmost_ptr;
}
return NULL;
}
// print a node
void print() {
if(hdr.leftmost_ptr == NULL)
printf("[%d] leaf %p \n", this->hdr.level, this);
else
printf("[%d] internal %p \n", this->hdr.level, this);
printf("last_index: %d\n", hdr.last_index);
printf("switch_counter: %d\n", hdr.switch_counter);
printf("search direction: ");
if(IS_FORWARD(hdr.switch_counter))
printf("->\n");
else
printf("<-\n");
if(hdr.leftmost_ptr!=NULL)
printf("%p ",hdr.leftmost_ptr);
for(int i=0;records[i].ptr != NULL;++i)
printf("%ld,%p ",records[i].key,records[i].ptr);
printf("%p ", hdr.sibling_ptr);
printf("\n");
}
void printAll() {
if(hdr.leftmost_ptr==NULL) {
printf("printing leaf node: ");
print();
}
else {
printf("printing internal node: ");
print();
((page*) hdr.leftmost_ptr)->printAll();
for(int i=0;records[i].ptr != NULL;++i){
((page*) records[i].ptr)->printAll();
}
}
}
void CalculateSapce(uint64_t &space) {
if(hdr.leftmost_ptr==NULL) {
space += PAGESIZE;
}
else {
space += PAGESIZE;
((page*) hdr.leftmost_ptr)->CalculateSapce(space);
for(int i=0;records[i].ptr != NULL;++i){
((page*) records[i].ptr)->CalculateSapce(space);
}
}
}
};
static inline page* NewBpNode() {
return new page();
}
void page::linear_search_range(entry_key_t min, entry_key_t max,
std::vector<pair<uint64_t, uint64_t>> &result, int &size) {
int i, off = 0;
uint8_t previous_switch_counter;
page *current = this;
while(current) {
int old_off = off;
do {
previous_switch_counter = current->hdr.switch_counter;
off = old_off;
entry_key_t tmp_key;
char *tmp_ptr;
if(IS_FORWARD(previous_switch_counter)) {
if((tmp_key = current->records[0].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[0].ptr) != NULL) {
if(tmp_key == current->records[0].key) {
if(tmp_ptr) {
// buf[off++] = (unsigned long)tmp_ptr;
result.push_back({tmp_key, (uint64_t)tmp_ptr});
off++;
if(off >= size) {
return ;
}
}
}
}
}
else {
size = off;
return;
}
}
for(i=1; current->records[i].ptr != NULL; ++i) {
if((tmp_key = current->records[i].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[i].ptr) != current->records[i - 1].ptr) {
if(tmp_key == current->records[i].key) {
if(tmp_ptr) {
// buf[off++] = (unsigned long)tmp_ptr;
result.push_back({tmp_key, (uint64_t)tmp_ptr});
off++;
if(off >= size) {
return ;
}
}
}
}
}
else {
size = off;
return;
}
}
}
}
else {
for(i=count() - 1; i > 0; --i) {
if((tmp_key = current->records[i].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[i].ptr) != current->records[i - 1].ptr) {
if(tmp_key == current->records[i].key) {
if(tmp_ptr) {
// buf[off++] = (unsigned long)tmp_ptr;
result.push_back({tmp_key, (uint64_t)tmp_ptr});
off++;
if(off >= size) {
return ;
}
}
}
}
}
else {
size = off;
return;
}
}
}
if((tmp_key = current->records[0].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[0].ptr) != NULL) {
if(tmp_key == current->records[0].key) {
if(tmp_ptr) {
// buf[off++] = (unsigned long)tmp_ptr;
result.push_back({tmp_key, (uint64_t)tmp_ptr});
off++;
if(off >= size) {
return ;
}
}
}
}
}
else {
size = off;
return;
}
}
}
} while(previous_switch_counter != current->hdr.switch_counter);
current = current->hdr.sibling_ptr;
}
size = off;
}
void page::linear_search_range(entry_key_t min, entry_key_t max, void **values, int &size) {
int i, off = 0;
uint8_t previous_switch_counter;
page *current = this;
while(current) {
int old_off = off;
do {
previous_switch_counter = current->hdr.switch_counter;
off = old_off;
entry_key_t tmp_key;
char *tmp_ptr;
if(IS_FORWARD(previous_switch_counter)) {
if((tmp_key = current->records[0].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[0].ptr) != NULL) {
if(tmp_key == current->records[0].key) {
if(tmp_ptr) {
// buf[off++] = (unsigned long)tmp_ptr;
values[off] = tmp_ptr;
off++;
if(off >= size) {
return ;
}
}
}
}
}
else {
size = off;
return;
}
}
for(i=1; current->records[i].ptr != NULL; ++i) {
if((tmp_key = current->records[i].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[i].ptr) != current->records[i - 1].ptr) {
if(tmp_key == current->records[i].key) {
if(tmp_ptr) {
// buf[off++] = (unsigned long)tmp_ptr;
values[off] = tmp_ptr;
off++;
if(off >= size) {
return ;
}
}
}
}
}
else {
size = off;
return;
}
}
}
}
else {
for(i=count() - 1; i > 0; --i) {
if((tmp_key = current->records[i].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[i].ptr) != current->records[i - 1].ptr) {
if(tmp_key == current->records[i].key) {
if(tmp_ptr) {
// buf[off++] = (unsigned long)tmp_ptr;
values[off] = tmp_ptr;
off++;
if(off >= size) {
return ;
}
}
}
}
}
else {
size = off;
return;
}
}
}
if((tmp_key = current->records[0].key) > min) {
if(tmp_key < max) {
if((tmp_ptr = current->records[0].ptr) != NULL) {
if(tmp_key == current->records[0].key) {
if(tmp_ptr) {
// buf[off++] = (unsigned long)tmp_ptr;
values[off] = tmp_ptr;
off++;
if(off >= size) {
return ;
}
}
}
}
}
else {
size = off;
return;
}
}
}
} while(previous_switch_counter != current->hdr.switch_counter);
current = current->hdr.sibling_ptr;
}
size = off;
}
btree::btree(){
root = (char*)new page();
printf("[Fast-Fair]: root is %p, btree is %p.\n", root, this);
height = 1;
}
btree::btree(page *root_) {
if(root_ == nullptr) {
root = (char*)new page();
height = 1;
} else {
root = (char *)root_;
height = root_->GetLevel() + 1;
}
printf("[Fast-Fair]: root is %p, btree is %p, height is %d.\n", root, this, height);
}
void btree::setNewRoot(char *new_root) {
this->root = (char*)new_root;
clflush((char*)&(this->root),sizeof(char*));
++height;
}
char *btree::btree_search(entry_key_t key){
page* p = (page*)root;
while(p->hdr.leftmost_ptr != NULL) {
p = (page *)p->linear_search(key);
}
page *t;
while((t = (page *)p->linear_search(key)) == p->hdr.sibling_ptr) {
p = t;
if(!p) {
break;
}
}
if(!t) {
// printf("NOT FOUND %llx, t = %x\n", key, t);
return NULL;
}
return (char *)t;
}
page *btree::btree_search_leaf(entry_key_t key){
page* p = (page*)root;
while(p->hdr.leftmost_ptr != NULL) {
p = (page *)p->linear_search(key);
}
return p;
}
// insert the key in the leaf node
void btree::btree_insert(entry_key_t key, char* right){ //need to be string
page* p = (page*)root;
while(p->hdr.leftmost_ptr != NULL) {
p = (page*)p->linear_search(key);
}
if(!p->store(this, NULL, key, right, true)) { // store
btree_insert(key, right);
}
}
// store the key into the node at the given level
void btree::btree_insert_internal
(char *left, entry_key_t key, char *right, uint32_t level) {
if(level > ((page *)root)->hdr.level)
return;
page *p = (page *)this->root;
while(p->hdr.level > level)
p = (page *)p->linear_search(key);
if(!p->store(this, NULL, key, right, true)) {
btree_insert_internal(left, key, right, level);
}
}
void btree::btree_delete(entry_key_t key) {
page* p = (page*)root;
while(p->hdr.leftmost_ptr != NULL){
p = (page*) p->linear_search(key);
}
page *t;
while((t = (page *)p->linear_search(key)) == p->hdr.sibling_ptr) {
p = t;
if(!p)
break;
}
if(p && t) {
if(!p->remove(this, key)) {
btree_delete(key);
}
}
else {
;
// printf("not found the key to delete %llx\n", key);
}
}
void btree::btree_delete_internal
(entry_key_t key, char *ptr, uint32_t level, entry_key_t *deleted_key,
bool *is_leftmost_node, page **left_sibling) {
if(level > ((page *)this->root)->hdr.level)
return;
page *p = (page *)this->root;
while(p->hdr.level > level) {
p = (page *)p->linear_search(key);
}
if((char *)p->hdr.leftmost_ptr == ptr) {
*is_leftmost_node = true;
return;
}
*is_leftmost_node = false;
for(int i=0; p->records[i].ptr != NULL; ++i) {
if(p->records[i].ptr == ptr) {
if(i == 0) {
if((char *)p->hdr.leftmost_ptr != p->records[i].ptr) {
*deleted_key = p->records[i].key;
*left_sibling = p->hdr.leftmost_ptr;
p->remove(this, *deleted_key, false, false);
break;
}
}
else {
if(p->records[i - 1].ptr != p->records[i].ptr) {
*deleted_key = p->records[i].key;
*left_sibling = (page *)p->records[i - 1].ptr;
p->remove(this, *deleted_key, false, false);
break;
}
}
}
}
}
// Function to search keys from "min" to "max"
void btree::btree_search_range
(entry_key_t min, entry_key_t max, unsigned long *buf) {
page *p = (page *)root;
while(p) {
if(p->hdr.leftmost_ptr != NULL) {
// The current page is internal
p = (page *)p->linear_search(min);
}
else {
// Found a leaf
p->linear_search_range(min, max, buf);
break;
}
}
}
void btree::btree_search_range(entry_key_t min, entry_key_t max,
std::vector<pair<entry_key_t, uint64_t>> &result, int &size) {
page *p = (page *)root;
while(p) {
if(p->hdr.leftmost_ptr != NULL) {
// The current page is internal
p = (page *)p->linear_search(min);
}
else {
// Found a leaf
p->linear_search_range(min, max, result, size);
break;
}
}
}
void btree::btree_search_range(entry_key_t min, entry_key_t max, void **values, int &size) {
page *p = (page *)root;
while(p) {
if(p->hdr.leftmost_ptr != NULL) {
// The current page is internal
p = (page *)p->linear_search(min);
}
else {
// Found a leaf
p->linear_search_range(min, max, values, size);
break;
}
}
}
void btree::printAll(){
int total_keys = 0;
page *leftmost = (page *)root;
printf("root: %p\n", root);
if(root) {
do {
page *sibling = leftmost;
while(sibling) {
if(sibling->hdr.level == 0) {
total_keys += sibling->hdr.last_index + 1;
}
sibling->print();
sibling = sibling->hdr.sibling_ptr;
}
printf("-----------------------------------------\n");
leftmost = leftmost->hdr.leftmost_ptr;
} while(leftmost);
}
printf("total number of keys: %d\n", total_keys);
}
void btree::CalculateSapce(uint64_t &space) {
if(root != nullptr) {
((page*)root)->CalculateSapce(space);
}
}
void btree::PrintInfo() {
printf("This is a b+ tree.\n");
printf("Node size is %lu, M path is %d.\n", sizeof(page), cardinality);
printf("Tree height is %d.\n", height);
}
} // namespace FastFair | [
"1103597933@qq.com"
] | 1103597933@qq.com |
6e1b5d52fc16ae436fc94c54a3af1906ace1e9a8 | acbd102afb1b78b74de43db93088e602ca1b4337 | /employecontractuel.h | 5e9939b60d6712acfc89c9f07fbc58f2da97cc4f | [] | no_license | AndrewOuellet/TPAndrewSaifLP | 5dd0bfebd01266c91183de6691894d768e537bfb | 97a6c92402e5116ac3416b3c1730ae167248bf76 | refs/heads/master | 2022-12-01T16:52:35.545745 | 2020-08-09T23:00:23 | 2020-08-09T23:00:23 | 286,325,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | h | #ifndef __EMPLOYECONTRACTUEL_H__
#define __EMPLOYECONTRACTUEL_H__
#include <iostream>
#include "employe.h"
class EmployeContractuel : public Employe {
protected:
double montant_contrat;
double semaines;
public:
//Constructeur
EmployeContractuel(std::string nom, int matricule, double le_montant_contrat, double les_semaines);
//Destructeur
~EmployeContractuel() {
std::cout <<"Employe Contractuel detruit"<<std::endl;
}
//Afficher Employe Contractuel
void afficherEmploye();
//Afficher paie
void afficherPaie();
};
#endif // __EMPLOYECONTRACTUEL_H__ | [
"andrewouellet@crosement.qc.ca"
] | andrewouellet@crosement.qc.ca |
85104016608debfeb92baf4e58356136841eb74b | 30a4246c51a851b76708cc96a7139156a275f79b | /DBMS/DBMS/FieldDAO.cpp | c2a88aecb1d09196a6682563b189e0ffb30c142a | [] | no_license | 15301111/DBSM | f6ded15a88de6137c8b6a2f705e10027be417c37 | d1185bde4325fefed685baa36b9eced4eebb9057 | refs/heads/master | 2021-01-20T07:23:39.018620 | 2017-05-29T10:50:08 | 2017-05-29T10:50:08 | 89,998,378 | 0 | 1 | null | 2017-05-08T12:13:04 | 2017-05-02T06:19:05 | null | GB18030 | C++ | false | false | 3,920 | cpp | #include "stdafx.h"
#include "FieldDAO.h"
#include "BinaryFile.h"
CFieldDAO::CFieldDAO(void)
{
}
CFieldDAO::~CFieldDAO(void)
{
}
//从文件读取字段列表
vector<CFieldEntity> CFieldDAO::ReadFieldList(CString &tbFileName)
{
vector<CFieldEntity> res;
vector<CString> strList=CBinaryFile::ReadAll(tbFileName);
if(!strList.empty())
{
for (vector<CString>::iterator ite = strList.begin()+1; ite != strList.end(); ++ite)
{
vector<CString> tmpList=CUtil::StrSplit(*ite,L"#");
int id=CUtil::StringToInteger(tmpList[0]);
CString name=tmpList[1];
int type=CUtil::StringToInteger(tmpList[3]);
int length=CUtil::StringToInteger(tmpList[4]);
int isPK=CUtil::StringToInteger(tmpList[8]);
int isNull=CUtil::StringToInteger(tmpList[9]);
int isUnique=CUtil::StringToInteger(tmpList[10]);
CString comment=tmpList[11];
CFieldEntity tmpFieldEntity=CFieldEntity(id,name,type,length,isPK,isNull,isUnique,comment);
tmpFieldEntity.SetMax(CUtil::StringToInteger(tmpList[5]));
tmpFieldEntity.SetMin(CUtil::StringToInteger(tmpList[6]));
tmpFieldEntity.SetDefault(tmpList[7]);
res.push_back(tmpFieldEntity);
}
}
return res;
}
//文件增加一个字段记录
bool CFieldDAO::WriteAnField(CFieldEntity &newField,CString &tdfFileName)
{
CString str=CUtil::IntegerToString(newField.GetId())+CString("#")+newField.GetName()+CString("#")
+CUtil::IntegerToString(newField.GetOrder())+CString("#")+CUtil::IntegerToString(newField.GetType())
+CString("#")+CUtil::IntegerToString(newField.GetLength())+CString("#")+CUtil::IntegerToString(newField.GetMax())
+CString("#")+CUtil::IntegerToString(newField.GetMin())+CString("#")+newField.GetDefault()+CString("#")
+CUtil::IntegerToString(newField.GetIsPK())+CString("#")+CUtil::IntegerToString(newField.GetIsNull())
+CString("#")+CUtil::IntegerToString(newField.GetIsUnique())+CString("#")+newField.GetComment();
return CBinaryFile::AddAnLine(tdfFileName,str);
}
//从文件删除一条字段信息
bool CFieldDAO::DeleteField(CString &fieldName,CString &tdfFileName)
{
vector<CString> list = CBinaryFile::ReadAll(tdfFileName);
if (!list.empty())
{
for (vector<CString>::iterator ite=list.begin()+1;ite!=list.end();++ite)
{
CFieldEntity temp(*ite);
if(temp.GetName()==fieldName)
{
list.erase(ite);
break;
}
}
return CBinaryFile::Write(tdfFileName,list);
}
else
return false;
}
//把修改后的字段写入文件
bool CFieldDAO::ModifyField(CFieldEntity &newField,CString &tdfFileName)
{
vector<CString> list = CBinaryFile::ReadAll(tdfFileName);
if(list.empty())
return false;
else
{
for (vector<CString>::iterator ite=list.begin()+1;ite!=list.end();++ite)
{
vector<CString> vfield = CUtil::StrSplit(*ite,CString("#"));
if(vfield[0] == CUtil::IntegerToString(newField.GetId()))
{
CString str=CUtil::IntegerToString(newField.GetId())+CString("#")+newField.GetName()+CString("#")
+CUtil::IntegerToString(newField.GetOrder())+CString("#")+CUtil::IntegerToString(newField.GetType())
+CString("#")+CUtil::IntegerToString(newField.GetLength())+CString("#")+CUtil::IntegerToString(newField.GetMax())
+CString("#")+CUtil::IntegerToString(newField.GetMin())+CString("#")+newField.GetDefault()+CString("#")
+CUtil::IntegerToString(newField.GetIsPK())+CString("#")+CUtil::IntegerToString(newField.GetIsNull())
+CString("#")+CUtil::IntegerToString(newField.GetIsUnique())+CString("#")+newField.GetComment();
*ite = str;
break;
}
}
return CBinaryFile::Write(tdfFileName,list);
}
}
int CFieldDAO::GetFieldCounter(CString &fieldFileName)
{
CString firstLine=CBinaryFile::ReadFirstLine(fieldFileName);
CString res = CUtil::StrSplit(firstLine,CString("#"))[0];
return CUtil::StringToInteger(res);
}
bool CFieldDAO::SaveFieldCounter(CString &fieldFileName,int counter)
{
return CBinaryFile::SaveCounter(fieldFileName,counter);
}
| [
"15301111@bjtu.edu.cn"
] | 15301111@bjtu.edu.cn |
9113b832a6eb66a5988f1ff656e37c26adc3b8fa | 840484c6553cde4722e91904166eb8e0855555e0 | /LAB nou/Lab 1/C++ Qt/QT date/18.09/TooTip/testtooltip.h | 659025b5b48c4477b10dd29fbc3e30fb9eb10fa7 | [] | no_license | raul7alex/TAP | db869b8074591026f54f3b5f0fe70e0f14b9e54d | d16bf6b23a8b0d875b074325ef4b32f4c1f8df53 | refs/heads/master | 2020-05-02T22:00:39.413700 | 2019-03-28T16:08:32 | 2019-03-28T16:08:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | h | #ifndef TESTTOOLTIP_H
#define TESTTOOLTIP_H
#include <QMainWindow>
class QHBoxLayout;
class QPushButton;
class TestToolTip : public QMainWindow
{
Q_OBJECT
public:
explicit TestToolTip(QWidget *parent = 0);
signals:
public slots:
private:
QWidget* centralWidget;
QHBoxLayout *layout;
QPushButton *sendPushButton, *namePushButton;
};
#endif // TESTTOOLTIP_H
| [
"raul7_alex@yahoo.com"
] | raul7_alex@yahoo.com |
24885e02c601fe40f51ec3390732a87cc3abd63b | 09d2cbd9ae667167a845a485bb3e0bc8afbbe323 | /GameEngineTK/State/InAirState.cpp | 54e14b76e04ba99c65a80dd91f58668b41b55450 | [] | no_license | kaiyamamoto/GameEngineTK | 1e7f8c98fd6a8cf4736d760a27ad95a8641f28a9 | 738c9b694f103ea93b6e1936959e7cdf60960894 | refs/heads/master | 2021-01-19T19:50:46.931972 | 2017-07-24T03:08:17 | 2017-07-24T03:08:17 | 88,451,283 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,405 | cpp | #include "InAirState.h"
#include "JumpingState.h"
#include "MoveState.h"
#include <simplemath.h>
#include "OnGroundState.h"
#include "..\Input.h"
using namespace DirectX::SimpleMath;
using namespace DirectX;
using namespace YamagenLib;
InAirState* InAirState::m_instance = nullptr;
/// <summary>
/// 入口処理
/// </summary>
/// <param name="player"></param>
void InAirState::Enter(Robot & player)
{
}
/// <summary>
/// 入力処理
/// </summary>
/// <param name="player">プレイヤー</param>
/// <param name="keyTracker">入力されたキー</param>
/// <returns>次の状態があるときは状態を返す</returns>
RobotState * InAirState::HandleInput(Robot & robot)
{
MoveState::GetInstance()->HandleInput(robot);
// ジャンプ(仮)
if (Input::GetKeyDown(Key::Space)) return JumpingState::GetInstance();
return nullptr;
}
/// <summary>
/// 更新処理
/// </summary>
/// <param name="player"></param>
void InAirState::Update(Robot & robot)
{
// 重力を反映
float speedY = robot.GetSpeed().y;
speedY += Object3D::GRAVITY;
robot.SetSpeedY(speedY);
}
/// <summary>
/// 出口処理
/// </summary>
/// <param name="robot"></param>
void InAirState::Exit(Robot & robot)
{
robot.SetSpeedY(0.0f);
robot.GetRobotParts(Robot::Parts::LEFTLEG)->SetPosition(Vector3(1.0f, 0.0f, 0.0f));
robot.GetRobotParts(Robot::Parts::RIGHTLEG)->SetPosition(Vector3(-1.0f, 0.0f, 0.0f));
}
| [
"dqx_2527@yahoo.co.jp"
] | dqx_2527@yahoo.co.jp |
d8c83eb4950231eb11a4fcfc3222625ef978064a | bf817b914f2c423da15c330b2a60bdf9f32c798a | /8_30_class_practice/8_30_class_practice/main2.cpp | 0b4a4cf5fc303522fe9083b69c40fe433b207be4 | [] | no_license | z397318716/C-Plus-Plus | 2d074ea53f7f45534f72b3109c86c0612eb32bfe | 6a7405386e60e1c2668fd8e92d7e4b4ab7903339 | refs/heads/master | 2021-12-10T22:16:34.871394 | 2021-09-27T01:55:23 | 2021-09-27T01:55:23 | 204,134,098 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 471 | cpp | #include <iostream>
using namespace std;
class Testtop{
public:
int m_a;
int m_b;
Testtop() :m_a(0), m_b(0)
{
}
Testtop(int a, int b) :m_a(a), m_b(b)
{
}
Testtop operator+(const Testtop &s) const//在函数后加 const 表示 this 不能变
{
Testtop res;
res.m_a = m_a + s.m_a;
res.m_b = m_b + s.m_b;
return res;
}
};
int main2()
{
Testtop a(3, 5);
Testtop b(2, 7);
Testtop c = a + b;
cout << c.m_a << ' ' << c.m_b << endl;
return 0;
} | [
"397318716@qq.com"
] | 397318716@qq.com |
a009e4b4d5243784caa737bece8f2b51b1491e38 | 16c2aa1096e8d0efed3f3219b22f1b0a86a78c52 | / cf-C - Strange Birthday Party - code.cpp | 21df3001628411ed0dba36aa9b48c677bf5b4b27 | [] | no_license | ash1526/CodeLibrary | e1c36045c979031f98f99fbfbd446d3e29c050b7 | 7ee6fa852e1cc4b38c9160c927fdb0cf580eb5ab | refs/heads/master | 2023-08-17T12:50:16.964705 | 2021-10-19T16:51:43 | 2021-10-19T16:51:43 | 361,191,580 | 0 | 2 | null | 2021-10-04T17:43:18 | 2021-04-24T15:02:46 | C++ | UTF-8 | C++ | false | false | 2,051 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define inf LLONG_MAX
#define ninf LLONG_MIN
#define io ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define all(s) s.begin(),s.end()
#define rep(i, a, b) for(ll i = a; i < b; i++)
#define rr(v) for(auto &val:v)
#define _max(v) *max_element(v.begin(), v.end())
#define _min(v) *min_element(v.begin(), v.end())
#define ms(s, n) memset(s, n, sizeof(s))
ll power(ll x, ll y){ll res = 1;while (y > 0){ if (y & 1){res = res*x;} y = y>>1;x = x*x;}return res;}
ll powermod(ll x, ll y, ll p){int res = 1;x = x % p;while (y > 0){if (y & 1){res = (res*x) % p;}y = y>>1; x = (x*x) % p;}return res;}
ll gcd(ll a, ll b) { if (b == 0)return a; return gcd(b, a % b);}
ll fact(ll n){ll res = 1; for (ll i = 2; i <= n; i++) res = res * i; return res; }
ll ceel(ll x,ll y) {return (x+y-1)/y;}
ll nCr(ll n, ll r){ return fact(n) / (fact(r) * fact(n - r));}
#define print(v) rep(i, 0, v.size()) cout<< v[i]<< " "; cout<< endl;
#define mod 1e9+7
int main()
{
io;
ll t; cin >> t;
//t=1;
while(t--)
{
vector<ll> v1, v2;
ll x, m, n;
cin >> n >> m;
rep(i, 0, n)
{
cin >> x;
x--;
v1.pb(x);
}
rep(i, 0, m)
{
cin >> x; v2.pb(x);
}
sort(all(v1), greater<ll>());
ll ptr=0;
vector<ll> ans;
rep(i, 0, v1.size())
{
if(v1[i]==ptr)
{
ans.pb(ptr);
}
else if(v1[i]>ptr)
{
ans.pb(ptr);
ptr++;
}
else if(v1[i]<ptr)
{
ans.pb(v1[i]);
// ptr++;
}
}
// print(ans);
ll sum=0;
rep(i, 0, ans.size()) sum+=v2[ans[i]];
cout<< sum << endl;
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
386827133fc109f08be5e078c931d5feb0b57ee0 | 2f5ae7f519aaae6681fa0ca57efc6627f5d97478 | /dp/sg/gl/TextureGL.h | e920280040901bddccdc8cb5f846ccf91035171d | [
"BSD-3-Clause"
] | permissive | mtavenrath/pipeline | c8048f51ac7ccfaeeb589090e28c847000f8af78 | 5085ba5e854fa1485acf14f4b1c4c4d341b3c6ef | refs/heads/master | 2020-12-31T02:32:55.843062 | 2014-09-11T15:46:02 | 2014-09-11T15:46:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,823 | h | // Copyright NVIDIA Corporation 2010
// 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 <dp/sg/gl/Config.h>
#include <dp/sg/gl/BufferGL.h>
#include <dp/sg/core/Texture.h>
#include <dp/sg/core/TextureHost.h>
#include <dp/gl/Texture.h>
namespace dp
{
namespace sg
{
namespace gl
{
#define NVSG_TIF_INVALID 0 //!< Invalid texture format
//! GLTexImageFmt specifies the format and data type of a texture image.
struct GLTexImageFmt
{
GLint intFmt; //!< The OpenGL internal format of a texture.
GLint usrFmt; //!< The OpenGL user format of a texture
GLint type; //!< The OpenGL type of a texture
GLint uploadHint; //!< An upload hint for the texture: 0=glTexImage, 1=PBO
};
//! Internal data structure used to describe formats
struct NVSGTexImageFmt
{
GLint fixedPtFmt; //!< The OpenGL internal format for fixed point
GLint floatFmt; //!< The OpenGL internal format for floating point
GLint integerFmt; //!< The OpenGL internal format integer textures
GLint compressedFmt; //!< The OpenGL internal format for compressed textures
GLint nonLinearFmt; //!< The OpenGL internal format SRGB textures
GLint usrFmt; //!< The 'typical' OpenGL user format of a texture (integer textures excluded)
GLint type; //!< The OpenGL type of a texture
GLint uploadHint; //!< An upload hint for the texture: 0=glTexImage, 1=PBO
};
class TextureGL : public dp::sg::core::Texture
{
public:
DP_SG_GL_API static TextureGLSharedPtr create( const dp::gl::SmartTexture& textureGL );
DP_SG_GL_API virtual dp::sg::core::HandledObjectSharedPtr clone() const;
DP_SG_GL_API const dp::gl::SmartTexture& getTexture() const;
DP_SG_GL_API static bool getTexImageFmt( GLTexImageFmt & tfmt, dp::sg::core::Image::PixelFormat fmt, dp::sg::core::Image::PixelDataType type, dp::sg::core::TextureHost::TextureGPUFormat gpufmt );
protected:
DP_SG_GL_API TextureGL( const dp::gl::SmartTexture& texture );
private:
dp::gl::SmartTexture m_texture;
};
} // namespace gl
} // namespace sg
} // namespace dp
| [
"matavenrath@nvidia.com"
] | matavenrath@nvidia.com |
2751b7d4d0f097f9f2872e0526ae3d347b39765c | a7764174fb0351ea666faa9f3b5dfe304390a011 | /inc/Handle_StepElement_SurfaceSectionField.hxx | c81ec27f75dc70ab8a71a8fd739f8a65bcc8de7b | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _Handle_StepElement_SurfaceSectionField_HeaderFile
#define _Handle_StepElement_SurfaceSectionField_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineHandle_HeaderFile
#include <Standard_DefineHandle.hxx>
#endif
#ifndef _Handle_MMgt_TShared_HeaderFile
#include <Handle_MMgt_TShared.hxx>
#endif
class Standard_Transient;
class Handle(Standard_Type);
class Handle(MMgt_TShared);
class StepElement_SurfaceSectionField;
DEFINE_STANDARD_HANDLE(StepElement_SurfaceSectionField,MMgt_TShared)
#endif
| [
"shoka.sho2@excel.co.jp"
] | shoka.sho2@excel.co.jp |
041bc18e5b00c034b493909e4f66bccad25b1705 | a69792817ed5c8af39fe16898b6272b4620a6199 | /PDI2015B/PDI2015B.cpp | 5478b13a9c753d9cbe13d5a85dfe86e97bd6061b | [] | no_license | saulchavezr/PDI2015B | 459b7d3f1e0354026b96b0ae8120ebd90ba6f0f7 | 477e55403a9bfce720dfa6bd57289a542179f263 | refs/heads/master | 2022-11-03T19:05:08.422309 | 2015-12-04T16:57:49 | 2015-12-04T16:57:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,380 | cpp | // PDI2015B.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "PDI2015B.h"
#include "DXGIManager.h"
#include "math.h"
#include "CSDefault.h"
#include "CSConvolve.h"
#include "CSALU.h"
#include "..\\Video\\AtWareVideoCapture.h"
#include "VideoProcessor.h"
#include "Frame.h"
#include "CSMetaCanvas.h"
#include "CSFusion.h"
#include "GIFManager.h"
#include "TextureQueue.h"
//#include "gif.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
CDXGIManager g_Manager;
ID3D11Texture2D* g_pSource;
ID3D11Texture2D* g_pStaticVideoImage;
ID3D11Texture2D* g_pMetaCanvas;
CCSDefault *g_pCSDefault;
CCSConvolve* g_pCSConvolve; //Shader de convolucion
CCSALU* g_pCSALU;
IAtWareVideoCapture* g_pIVC; //Interface Video Capture
CVideoProcessor g_VP; //The video processor
CCSMetaCanvas* g_pCSMC;
CCSFusion* g_pCSFusion;
CGIFManager* g_pCGIF;
CTextureQueue* g_pTQ;
bool g_ExistsStaticVideoImage;
bool g_ExistsMetaCanvas;
//GifWriter* g_gifWriter;
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK VideoHost(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
CDXGIManager::PIXEL alpha(CDXGIManager::PIXEL);
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_PDI2015B, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PDI2015B));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int)msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PDI2015B));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
//wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.hbrBackground = 0;
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_PDI2015B);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
ATOM a = RegisterClassEx(&wcex);
wcex.lpfnWndProc = VideoHost;
wcex.lpszClassName = L"VideoHost";
wcex.lpszMenuName = NULL;
RegisterClassEx(&wcex);
return a;
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
IDXGIAdapter *pAdapter = g_Manager.EnumAdapters(hWnd);
bool bResult = g_Manager.Initialize(hWnd, pAdapter, false);
SAFE_RELEASE(pAdapter);
if (!bResult)
return FALSE;
g_pCSDefault = new CCSDefault(&g_Manager);
if (!g_pCSDefault->Initialize())
return FALSE;
g_pCSConvolve = new CCSConvolve(&g_Manager);
if (!g_pCSConvolve->Initialize())
return FALSE;
g_pCSALU = new CCSALU(&g_Manager);
if (!g_pCSALU->Initialize())
return FALSE;
g_pCSMC = new CCSMetaCanvas(&g_Manager);
if (!g_pCSMC->Initialize())
return FALSE;
g_pCSFusion = new CCSFusion(&g_Manager);
if (!g_pCSFusion->Initialize())
return FALSE;
g_pCGIF = new CGIFManager();
g_pTQ = new CTextureQueue();
//g_gifWriter = new GifWriter;
g_pSource = g_Manager.LoadTexture("..\\Resources\\iss.bmp", -1, alpha);
g_pStaticVideoImage = g_pSource;
g_ExistsStaticVideoImage = false;
g_ExistsMetaCanvas = false;
printf("hola mundo");
wprintf(L"hola mundo");
HWND hWndVH = CreateWindowEx(WS_EX_TOOLWINDOW, L"VideoHost", L"Vista Previa",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInst, NULL);
g_pIVC = CreateAtWareVideoCapture();
g_pIVC->Initialize(hWndVH);
g_pIVC->EnumAndChooseCaptureDevice();
g_pIVC->BuildStreamGraph();
g_pIVC->SetCallBack(&g_VP, 1);
AM_MEDIA_TYPE mt;
g_pIVC->GetMediaType(&mt);
g_VP.m_mt = mt;
g_pIVC->Start();
g_pIVC->ShowPreviewWindow(true);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
ShowWindow(hWndVH, nCmdShow);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
static float s_fTime = 0;
static float s_fScale = 1.0f;
static float s_fTheta = 0;
static int ALU_op = 0;
static int s_fInterpolation = 0;
static int s_mnx, s_mny = -1;
static int s_prev_mnx, s_prev_mny = -1;
static int brush_size = 10;
static int style = 0;
static bool canvasresised = false;
//static int gifFrameNumber = 0;
static bool toGif = false;
static bool record = false;
static int click = 0;
switch (message)
{
case WM_KEYDOWN:
{
switch (wParam)
{
case 'Z':
s_fScale += 0.1;
break;
case 'X':
s_fScale -= 0.1;
break;
case 'Q':
s_fTheta += 0.1;
break;
case 'E':
s_fTheta -= 0.1;
break;
case 'I':
s_fInterpolation = ~s_fInterpolation;
break;
case 'U':
if(ALU_op<12)
ALU_op++;
break;
case 'D':
if (ALU_op>0)
ALU_op--;
break;
case 'M':
g_ExistsStaticVideoImage = false;
break;
case 'P':
if(brush_size<100)
brush_size++;
break;
case 'L':
if(brush_size>1)
brush_size--;
break;
case '1':
style = 1;
break;
case '0':
style = 0;
break;
case '2':
style = 2;
case 'N':
g_ExistsMetaCanvas = false;
break;
case 'G':
toGif = toGif == true? false:true;
if (!toGif)
{
g_pCGIF->CreateGIF();
}
break;
case 'R':
record = record == true ? false : true;
break;
}
}
break;
case WM_LBUTTONDOWN:
click = 1;
break;
case WM_RBUTTONDOWN:
click = 2;
break;
case WM_RBUTTONUP:
case WM_LBUTTONUP:
click = 0;
break;
case WM_MOUSEMOVE:
{
s_mnx = LOWORD(lParam);
s_mny = HIWORD(lParam);
break;
}
break;
case WM_CREATE:
SetTimer(hWnd, 1, 20, NULL);
return 0;
case WM_TIMER:
switch (wParam)
{
case 1:
s_fTime += 0.2;
InvalidateRect(hWnd, NULL, false);
}
break;
case WM_SIZE:
if (g_Manager.GetDevice())
g_Manager.Resize(LOWORD(lParam), HIWORD(lParam));
break;
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
{
/*if (CFrame* pullFrame = g_VP.Pull())
{
g_pSource = g_Manager.LoadTexture(pullFrame);
CFrame* frame = g_Manager.LoadTextureBack(g_pSource);
//for (int j = 0; j < frame->m_sy; j++)
//{
// int pixelnum = 0;
// for (int i = 0; i < frame->m_sx; i++)
// {
// CFrame::PIXEL Color;
// Color.r = uint8_tFrame[(frame->m_sx*j * 4) + (i * 4)];
// Color.g = uint8_tFrame[(frame->m_sx*j * 4) + (i * 4) + 1];
// Color.b = uint8_tFrame[(frame->m_sx*j * 4) + (i * 4) + 2];
// Color.a = uint8_tFrame[(frame->m_sx*j * 4) + (i * 4)+3];
// frame->GetPixel(i, j) = Color;
// }
//}
//g_pSource = g_Manager.LoadTexture(frame);
D3D11_TEXTURE2D_DESC dtd;
//Initializes textures
g_Manager.GetBackBuffer()->GetDesc(&dtd);
dtd.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
g_pCSALU->m_pInput_1 = g_pSource;
g_pCSALU->m_pOutput = g_Manager.GetBackBuffer();
g_pCSALU->Configure((ALU_OPERATION)ALU_COPY);
g_pCSALU->Execute();
UINT frameSize = frame->m_sx*frame->m_sy;
uint8_t* uint8_tFrame;
uint8_tFrame = new uint8_t[frameSize * 4];
for (int j = 0; j < frame->m_sy; j++)
{
for (int i = 0; i < frame->m_sx; i++)
{
CFrame::PIXEL Color = frame->GetPixel(i, j);
uint8_tFrame[(frame->m_sx*j * 4) + (i * 4)] = (uint8_t)Color.r;
uint8_tFrame[(frame->m_sx*j * 4) + (i * 4) + 1] = (uint8_t)Color.g;
uint8_tFrame[(frame->m_sx*j * 4) + (i * 4) + 2] = (uint8_t)Color.b;
uint8_tFrame[(frame->m_sx*j * 4) + (i * 4) + 3] = (uint8_t)Color.a;
}
}
if (gifFrameNumber == 0)
{
GifBegin(g_gifWriter, "..\\Resources\\myGif.gif", frame->m_sx, frame->m_sy, 2);
}
if (gifFrameNumber < 100)
{
GifWriteFrame(g_gifWriter, uint8_tFrame, frame->m_sx, frame->m_sy, 2);
gifFrameNumber++;
}
if (gifFrameNumber == 100)
{
GifEnd(g_gifWriter);
gifFrameNumber++;
}
}*/
static int width = 0;
static int height = 0;
if (CFrame* pullFrame = g_VP.Pull())
{
if (!g_ExistsMetaCanvas)
{
//This function creates a white texture2d of the same size as the pulled video frame.
//It does not delete the frame
g_pMetaCanvas = g_Manager.LoadWhiteTextureOfSize(pullFrame);
g_ExistsMetaCanvas = true;
}
//Creates a texture2d from the pulled video frame and then deletes the frame
width = pullFrame->m_sx;
height = pullFrame->m_sy;
g_pSource = g_Manager.LoadTexture(pullFrame);
//Creates an static image for the style 0
if (!g_ExistsStaticVideoImage)
{
g_pStaticVideoImage = g_pSource;
g_ExistsStaticVideoImage = true;
}
}
if (s_prev_mnx == -1)
{
s_prev_mnx = s_mnx;
s_prev_mny = s_mny;
}
//If it doesn't exist a metacanvas yet, do not do anything
if (!g_pMetaCanvas)
return 0;
//Pipeline textures
ID3D11Texture2D* pFusionOut;
ID3D11Texture2D* pMetaCanvasOut;
ID3D11Texture2D* pImageModifiedOut;
ID3D11Texture2D* pImageModified = NULL;
D3D11_TEXTURE2D_DESC dtd;
//Initializes textures
g_Manager.GetBackBuffer()->GetDesc(&dtd);
if (width && height) {
dtd.Height = height;
dtd.Width = width;
}
dtd.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
g_Manager.GetDevice()->CreateTexture2D(&dtd, NULL, &pMetaCanvasOut);
g_Manager.GetDevice()->CreateTexture2D(&dtd, NULL, &pFusionOut);
//Style 0: Static Video Image
if (style == 0)
{
pImageModified = g_pStaticVideoImage;
}
//Style 2: Negative Image
else if (style == 1)
{
g_Manager.GetDevice()->CreateTexture2D(&dtd, NULL, &pImageModifiedOut);
g_pCSALU->m_pInput_1 = g_pSource;
g_pCSALU->m_pOutput = pImageModifiedOut;
g_pCSALU->Configure((ALU_OPERATION)ALU_NEG);
g_pCSALU->Execute();
pImageModified = pImageModifiedOut;
}
//Style 3
else if (style == 2)
{
/*g_Manager.GetDevice()->CreateTexture2D(&dtd, NULL, &pImageModifiedOut);
g_pCSALU->m_pInput_1 = g_pTQ->Pull();
g_pCSALU->m_pOutput = pImageModifiedOut;
g_pCSALU->Configure((ALU_OPERATION)ALU_NEG);
g_pCSALU->Execute();*/
pImageModified = g_pTQ->Pull();
if (!pImageModified)
pImageModified = g_pSource;
}
g_pCSFusion->m_pInput_1 = g_pSource;
g_pCSFusion->m_pInput_2 = pImageModified;
g_pCSFusion->m_pInput_3 = g_pMetaCanvas;
g_pCSFusion->m_pOutput = pFusionOut;
g_pCSFusion->Configure();
g_pCSFusion->Execute();
if (record)
{
ID3D11Texture2D* pTextureToRecord;
g_Manager.GetDevice()->CreateTexture2D(&dtd, NULL, &pTextureToRecord);
g_pCSALU->m_pInput_1 = pFusionOut;
g_pCSALU->m_pOutput = pTextureToRecord;
g_pCSALU->Configure((ALU_OPERATION)ALU_COPY);
g_pCSALU->Execute();
g_pTQ->Push(pTextureToRecord);
}
static int framesSkipped = 0;
static int skipFrames = 2;
if (toGif && framesSkipped++ == skipFrames)
{
CUFrame* frame;
frame = g_Manager.LoadTextureBack(pFusionOut);
g_pCGIF->Push(frame);
framesSkipped = 0;
}
g_pCSMC->m_pInput_1 = pFusionOut;
g_pCSMC->m_pInput_2 = g_pMetaCanvas;
g_pCSMC->m_pOutput_1 = g_Manager.GetBackBuffer();
g_pCSMC->m_pOutput_2 = pMetaCanvasOut;
g_pCSMC->m_Params.cursor_posX = s_mnx;
g_pCSMC->m_Params.cursor_posY = s_mny;
g_pCSMC->m_Params.cursor_prev_posX = s_prev_mnx;
g_pCSMC->m_Params.cursor_prev_posY = s_prev_mny;
g_pCSMC->m_Params.brush_size = brush_size;
int dx = s_prev_mnx - s_mnx;
int dy = s_prev_mny - s_mny;
if (dx != 0)
{
g_pCSMC->m_Params.m = (float)dy / (float)dx;
}
else
{
g_pCSMC->m_Params.m = 0;
}
g_pCSMC->m_Params.click = click;
g_pCSMC->Configure();
g_pCSMC->Execute();
g_pCSALU->m_pInput_1 = pMetaCanvasOut;
g_pCSALU->m_pOutput = g_pMetaCanvas;
g_pCSALU->Configure((ALU_OPERATION)ALU_COPY);
g_pCSALU->Execute();
//Procesar
/*g_pCSConvolve->m_pInput = g_pSource;
g_pCSConvolve->m_pOutput = pDefaultOut;
MATRIX4D S = Scale(s_fScale, s_fScale, 1);
MATRIX4D R = RotationZ(s_fTheta);
MATRIX4D T = Translate(s_mnx, s_mny, 0);
g_pCSConvolve->m_Params.Kernel = g_pCSConvolve->getKernelLaplace();
g_pCSConvolve->m_Params.C = 0.5;
g_pCSConvolve->Configure();
g_pCSConvolve->Execute();*/
/*g_pCSDefault->m_pInput = g_pSource;
g_pCSDefault->m_pOutput = pDefaultOut;
MATRIX4D S = Scale(s_fScale, s_fScale, 1);
MATRIX4D R = RotationZ(s_fTheta);
MATRIX4D T = Translate(s_mnx, s_mny, 0);
g_pCSDefault->m_Params.M = Inverse(S*R*T);
g_pCSDefault->Configure();
g_pCSDefault->Execute(); */
/*g_pIC->m_pInput_1 = g_pSource;
g_pIC->m_pInput_2 = g_pStaticVideoImage;
g_pIC->m_pOutput = pDefaultOut;
g_pIC->Configure();
g_pIC->Execute();*/
/*#pragma region Convolve
g_pCSConvolve->m_pInput = g_pSource;
g_pCSConvolve->m_pOutput = pConvolveOut;
g_pCSConvolve->m_Params.Kernel = g_pCSConvolve->getKernelSharp(s_fTime);
g_pCSConvolve->m_Params.C = 0;
g_pCSConvolve->Configure();
g_pCSConvolve->Execute();
#pragma endregion
//ALU_Thresholds
g_pCSALU->m_pInput_1 = pDefaultOut;
g_pCSALU->m_pInput_2 = pConvolveOut;
//g_pCSALU->m_Params.m_Threshold = { 0,0,0,0 };
g_pCSALU->m_Params.Threshold = 0.4;
g_pCSALU->m_pOutput = g_Manager.GetBackBuffer();
g_pCSALU->Configure((ALU_OPERATION)ALU_op);
g_pCSALU->Execute();*/
s_prev_mnx = s_mnx;
s_prev_mny = s_mny;
//Liberar toda memoria intermedia al terminar de procesar
SAFE_RELEASE(pFusionOut);
SAFE_RELEASE(pMetaCanvasOut);
g_Manager.GetSwapChain()->Present(1, 0);//T-1 sync
}
ValidateRect(hWnd, NULL);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
CDXGIManager::PIXEL alpha(CDXGIManager::PIXEL p)
{
CDXGIManager::PIXEL pAlpha = p;
pAlpha.a = p.b;
return pAlpha;
}
LRESULT WINAPI VideoHost(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
return 0;
case WM_SIZE:
{
RECT rc;
GetClientRect(hWnd, &rc);
g_pIVC->SetPreviewWindowPosition(&rc);
}
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
} | [
"romsc93@live.com.mx"
] | romsc93@live.com.mx |
805ef53005a68ae04dea8c037c30938f4718a3fa | bbbc505ddebcc710c0cbf7143d360b492a7af452 | /zerojudge/AC/c044.cpp | cec63f99ad4fe2895abd5a642442aa61c7477bd9 | [] | no_license | mandy840907/cpp | 25efb95b181775042a3aee9acaac04a1a9746233 | 793414c2af24b78cbfafff8c738eb5d83c610570 | refs/heads/master | 2020-05-29T17:07:54.273693 | 2020-04-08T04:45:29 | 2020-04-08T04:45:29 | 54,814,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 984 | cpp | #include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int times, array[26] = {}, array2[26];
string sen;
for(int i = 0; i < 26; i++)
array2[i] = i;
cin >> times;
getchar();
for(int a = 0; a < times; a++)
{
getline(cin, sen);
for(int n = 0; n < sen.length(); n++)
{
if(sen[n] >= 'A' && sen[n] <= 'Z')
array[sen[n] - 'A'] += 1;
else if(sen[n] >= 'a' && sen[n] <= 'z')
array[sen[n] - 'a']++;
}
}
// for(int n = 0; n < 26; n++)
// {
// cout << static_cast<char>(n + 'A') << array[n] << " ";
// }
for(int i = 25; i >= 0; i--)
{
for(int j = 0; j < i; j++)
{
if(array[j] < array[j + 1] || (array[j] == array[j + 1] && array2[j] > array2[j + 1]))
{
swap(array[j], array[j + 1]);
swap(array2[j], array2[j + 1]);
}
}
}
for(int n = 0; n < 26 && array[n] > 0; n++)
{
if(array[n])
cout << static_cast<char>(array2[n] + 'A') << " " << array[n] << endl;
}
return 0;
} | [
"mandy840907@gmail.com"
] | mandy840907@gmail.com |
358eaa9c79a8b795ac6f5f0bf78e40ba6c75d1c0 | c840e9ff34327aabf65b8df1e60beafb2872beac | /MyOpt.cpp | 411113badfc3caa51d1e9eecfb64621cbf2bd9ed | [] | no_license | Alaya-in-Matrix/MyOpt | df69a68d788073fac6fe4890b341c0ded1924959 | 728837817068bfe39bc8a548f3e6e80c2770920c | refs/heads/master | 2021-01-12T04:36:44.040197 | 2017-01-25T10:45:12 | 2017-01-25T10:45:12 | 77,688,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,262 | cpp | #include "MyOpt.h"
#include <cassert>
#include <iostream>
#include <fstream>
#include <cstdio>
#include "def.h"
using namespace std;
using namespace Eigen;
MyOpt::MyOpt(MyOpt::Algorithm a, size_t dim)
: _algo(a), _dim(dim), _cond(_default_stop_cond()), _data(nullptr), _solver(nullptr)
{
}
StopCond MyOpt::_default_stop_cond()
{
StopCond sc;
sc.stop_val = -1 * INF;
sc.xtol_rel = 1e-15;
sc.ftol_rel = 1e-15;
sc.gtol = 1e-15;
sc.history = 2;
sc.max_iter = 100;
sc.max_eval = 300;
return sc;
}
void MyOpt::set_min_objective(ObjFunc f, void* d)
{
_func = f;
_data = d;
}
MyOpt::Result MyOpt::optimize(VectorXd& x0, double& y)
{
switch (_algo)
{
case CG:
_solver = new class CG(_func, _dim, _cond, _data);
break;
case BFGS:
_solver = new class BFGS(_func, _dim, _cond, _data);
break;
case RProp:
_solver = new class RProp(_func, _dim, _cond, _data);
break;
default:
cerr << "Unsupported algorithm, tag: " << _algo << endl;
return INVALID_ARGS;
}
_solver->set_param(_params);
return _solver->minimize(x0, y);
}
MyOpt::~MyOpt()
{
if (_solver != nullptr) delete _solver;
}
void MyOpt::set_stop_val(double v) { _cond.stop_val = v; }
void MyOpt::set_xtol_rel(double v) { _cond.xtol_rel = v; }
void MyOpt::set_ftol_rel(double v) { _cond.ftol_rel = v; }
void MyOpt::set_gtol(double v) { _cond.gtol = v; }
void MyOpt::set_history(size_t h) { _cond.history = h + 1; }
void MyOpt::set_max_eval(size_t v) { _cond.max_eval = v; }
void MyOpt::set_max_iter(size_t v) { _cond.max_iter = v; }
void MyOpt::set_algo_param(const std::map<std::string, double>& p) { _params = p; }
std::string MyOpt::get_algorithm_name() const noexcept
{
#define C(A) case A: return #A
switch (_algo)
{
C(CG);
C(BFGS);
C(RProp);
default:
return "Unsupported algorithm";
}
#undef C
}
std::string MyOpt::explain_result(Result r)
{
#define C(A) case A: return #A
switch(r)
{
C(FAILURE );
C(INVALID_ARGS );
C(INVALID_INITIAL );
C(NANINF );
C(SUCCESS );
C(STOPVAL_REACHED);
C(FTOL_REACHED);
C(XTOL_REACHED);
C(GTOL_REACHED);
C(MAXEVAL_REACHED);
C(MAXITER_REACHED);
default:
return "Unknown reason" + to_string(r);
}
#undef C
}
size_t MyOpt::get_dimension() const noexcept { return _dim; }
Solver::Solver(ObjFunc f, size_t dim, StopCond sc, void* d)
: _func(f),
_line_search_trial(1.0),
_eval_counter(0),
_iter_counter(0),
_dim(dim),
_cond(sc),
_data(d),
_result(MyOpt::SUCCESS),
_history_x(queue<VectorXd>()),
_history_y(queue<double>()),
_c_decrease(0.01),
_c_curvature(0.9)
{}
double Solver::_run_func(const VectorXd& x, VectorXd& g, bool need_g)
{
const double val = _func(x, g, need_g, _data);
// automatically record best evaluation and update _eval_counter
++_eval_counter;
if (val < _besty)
{
_bestx = x;
_besty = val;
}
return val;
}
Solver::~Solver() {}
void Solver::_init()
{
_eval_counter = 0;
_iter_counter = 0;
while (!_history_x.empty())
{
_history_x.pop();
_history_y.pop();
}
_bestx = VectorXd::Constant(_dim, 1, INF);
_besty = INF;
_current_x = VectorXd::Constant(_dim, 1, INF);
_current_g = VectorXd::Constant(_dim, 1, INF);
_current_y = INF;
}
MyOpt::Result Solver::minimize(VectorXd& x0, double& y)
{
_init();
_current_x = x0;
_current_g = VectorXd::Constant(_dim, 1, INF);
_current_y = _run_func(_current_x, _current_g, true);
while (!_limit_reached())
{
_one_iter();
++_iter_counter;
_update_hist();
}
x0 = _bestx;
y = _besty;
return _result;
}
void Solver::_update_hist()
{
assert(_history_x.size() == _history_y.size());
_history_x.push(_current_x);
_history_y.push(_besty);
while (_history_x.size() > _cond.history)
{
_history_x.pop();
_history_y.pop();
}
}
void Solver::set_param(const map<string, double>& p) { _params = p; }
bool Solver::_limit_reached()
{
if (_result == MyOpt::SUCCESS)
{
if (_besty < _cond.stop_val)
_result = MyOpt::STOPVAL_REACHED;
else if (_history_x.size() >= _cond.history &&
(_history_x.front() - _history_x.back()).norm() < _cond.xtol_rel * (1 + _history_x.front().norm()))
_result = MyOpt::XTOL_REACHED;
else if (_history_y.size() >= _cond.history &&
fabs(_history_y.front() - _history_y.back()) < _cond.ftol_rel * (1 + fabs(_history_y.front())))
_result = MyOpt::FTOL_REACHED;
else if (_current_g.norm() < _cond.gtol)
_result = MyOpt::GTOL_REACHED;
else if (_eval_counter > _cond.max_eval)
_result = MyOpt::MAXEVAL_REACHED;
else if (_iter_counter > _cond.max_iter)
_result = MyOpt::MAXITER_REACHED;
}
return _result != MyOpt::SUCCESS;
}
void Solver::_set_linesearch_factor(double c1, double c2)
{
assert(0 <= c1 && c1 <= c2 && c2 <= 1.0);
_c_decrease = c1;
_c_curvature = c2;
}
void Solver::_set_trial(double t) { _line_search_trial = t; }
double Solver::_get_trial() const noexcept { return _line_search_trial; }
bool Solver::_line_search_inexact(const Eigen::VectorXd& direction, double& alpha, Eigen::VectorXd& x,
Eigen::VectorXd& g, double& y, size_t max_search)
{
// Basically translated from minimize.m of gpml toolbox
const double trial = _get_trial();
const size_t init_eval = _eval_counter;
const double interpo = 0.618;
const double extrapo = 1 / 0.618;
const double rho = _c_decrease; // sufficient decrease
const double sig = _c_curvature; // curvature
const double d0 = _current_g.dot(direction);
const double f0 = _current_y;
double x2, f2, d2; VectorXd df2(_dim);
double x3, f3, d3; VectorXd df3(_dim);
if(d0 > 0 || std::isinf(d0) || std::isnan(d0))
{
alpha = 0;
x = _current_x;
g = _current_g;
y = _current_y;
return false;
}
assert(d0 <= 0);
// extrapolation
x3 = trial; f3 = INF; d3 = INF;
while(true)
{
x2 = 0; f2 = f0; d2 = d0;
while(_eval_counter - init_eval < max_search)
{
f3 = _run_func(_current_x + x3 * direction, df3, true);
d3 = df3.dot(direction);
if(std::isnan(f3) || std::isnan(d3) || std::isinf(f3) || std::isinf(d3))
x3 /= 2;
else
break;
}
if(d3 > sig * d0 || f3 > f0 + x3 * rho * d0)
break;
double x1, f1, d1;
x1 = x2; f1 = f2; d1 = d2;
x2 = x3; f2 = f3; d2 = d3;
const double A = 6*(f1-f2)+3*(d2+d1)*(x2-x1); // make cubic extrapolation
const double B = 3*(f2-f1)-(2*d1+d2)*(x2-x1);
x3 = x1 - d1 * pow(x2 - x1, 2) / (B + sqrt(B * B - A * d1 * (x2 - x1))); // num. error possible, ok!
if (std::isnan(x3) || std::isinf(x3) || x3 < 0) // num prob | wrong sign?
x3 = x2 * extrapo; // extrapolate maximum amount
else if (x3 > x2 * extrapo) // new point beyond extrapolation limit?
x3 = x2 * extrapo; // extrapolate maximum amount
else if (x3 < x2 + interpo * (x2 - x1)) // new point too close to previous point?
x3 = x2 + interpo * (x2 - x1);
}
// Interpolation
double x4 = INF, f4 = -1*INF, d4 = INF;
while ((abs(d3) > -1*sig*d0 || f3 > f0 + x3 * rho * d0) && _eval_counter - init_eval < max_search)
{
if (d3 > 0 || f3 > f0+x3*rho*d0) // choose subinterval
{
x4 = x3; f4 = f3; d4 = d3; // move point 3 to point 4
}
else
{
x2 = x3; f2 = f3; d2 = d3; // move point 3 to point 2
}
if (f4 > f0)
x3 = x2 - (0.5 * d2 * pow(x4 - x2, 2)) / (f4 - f2 - d2 * (x4 - x2)); // quadratic interpolation
else
{
const double A = 6 * (f2 - f4) / (x4 - x2) + 3 * (d4 + d2); // cubic interpolation
const double B = 3 * (f4 - f2) - (2 * d2 + d4) * (x4 - x2);
x3 = x2 + (sqrt(B * B - A * d2 * pow(x4 - x2, 2)) - B) / A; // num. error possible, ok!
}
if (isnan(x3) || isinf(x3))
x3 = (x2+x4)/2; // if we had a numerical problem then bisect
x3 = max(min(x3, x4-interpo*(x4-x2)),x2+interpo*(x4-x2)); // don't accept too close
f3 = _run_func(_current_x + x3 * direction, df3, true);
d3 = df3.dot(direction);
}
alpha = x3;
x = _current_x + alpha * direction;
g = df3;
y = f3;
if(! (abs(d3) < -sig*d0 && f3 < f0+x3*rho*d0))
{
#ifdef MYDEBUG
cerr << "Linesearch Wolfe condition violated" << endl;
#endif
return false;
}
return true;
}
void CG::_init()
{
Solver::_init();
_former_g = VectorXd(_dim);
_former_direction = VectorXd(_dim);
_set_linesearch_factor(0.05, 0.1);
}
double CG::_beta_FR() const noexcept
{
return _current_g.squaredNorm() / _former_g.squaredNorm();
};
double CG::_beta_PR() const noexcept
{
return std::max(0.0, _current_g.dot(_current_g - _former_g) / _former_g.squaredNorm());
};
MyOpt::Result CG::_one_iter()
{
const size_t inner_iter = _iter_counter % _dim;
double trial = 1.0 / (1 + _current_g.squaredNorm());
if(_iter_counter == 0)
_set_trial(trial);
VectorXd direction(_dim);
if(inner_iter == 0)
direction = -1 * _current_g;
else
{
// double beta = _beta_FR();
double beta = _beta_PR();
direction = -1 * _current_g + beta * _former_direction;
}
double alpha = 0;
double y = 0;
VectorXd x(_dim);
VectorXd g(_dim);
_line_search_inexact(direction, alpha, x, g, y, 20);
const double ratio = 10;
if(inner_iter != 0)
trial = alpha * min(ratio, direction.dot(_current_g) / _former_direction.dot(_former_g));
else
trial = alpha;
_set_trial(trial);
_former_g = _current_g;
_former_direction = direction;
_current_x = x;
_current_g = g;
_current_y = y;
return MyOpt::SUCCESS;
}
void BFGS::_init()
{
Solver::_init();
_set_linesearch_factor(1e-4, 0.9); // suggested by <Numerical Optimization>
_invB = MatrixXd::Identity(_dim, _dim);
}
MyOpt::Result BFGS::_one_iter()
{
double trial = 1.0 / (1 + _current_g.norm());
if(_iter_counter == 0)
_set_trial(trial);
VectorXd direction = -1 * _invB * _current_g;
double alpha, y;
VectorXd x(_dim);
VectorXd g(_dim);
bool ls_success = _line_search_inexact(direction, alpha, x, g, y, 20); // always use 1.0 as trial
trial = alpha * 1.1;
_set_trial(trial);
if(ls_success)
{
VectorXd sk = alpha * direction;
VectorXd yk = g - _current_g;
_invB = _invB + ((sk.dot(yk) + yk.transpose() * _invB * yk) * (sk * sk.transpose())) / pow(sk.dot(yk), 2)
- (_invB * yk * sk.transpose() + sk * yk.transpose() * _invB) / sk.dot(yk);
_current_x = x;
_current_g = g;
_current_y = y;
}
else
{
_invB = MatrixXd::Identity(_dim, _dim);
}
return MyOpt::SUCCESS;
}
void RProp::_init()
{
Solver::_init();
_delta = VectorXd::Constant(_dim, 1, _delta0);
_grad_old = VectorXd::Ones(_dim, 1);
}
MyOpt::Result RProp::_one_iter()
{
VectorXd sign(_dim);
for(size_t i = 0; i < _dim; ++i)
{
sign(i) = _current_g(i) == 0 ? 0 : (_current_g(i) > 0 ? 1 : -1);
const double changed = _current_g(i) * _grad_old(i);
if(changed > 0)
_delta(i) = min(_delta(i) * _eta_plus, _delta_max);
else if(changed < 0)
{
_delta(i) = max(_delta(i) * _eta_minus, _delta_min);
_current_g(i) = 0;
sign(i) = 0;
}
}
VectorXd this_delta = -1*sign.cwiseProduct(_delta);
_grad_old = _current_g;
VectorXd x_old = _current_x;
_current_x += this_delta;
_current_y = _run_func(_current_x, _current_g, true);
// Recover from inf or NaN
const size_t max_retry = 20;
size_t retry = 0;
while (std::isinf(_current_y) || std::isnan(_current_y) || std::isinf(_current_g.squaredNorm()) ||
std::isnan(_current_g.squaredNorm()))
{
this_delta = 0.618 * this_delta;
_current_x = x_old + this_delta;
_current_y = _run_func(_current_x, _current_g, true);
++retry;
if(retry >= max_retry)
{
break;
}
#ifdef MYDEBUG
cerr << "Rprop recover, y = " << _current_y << endl;
#endif
}
return MyOpt::SUCCESS;
}
| [
"lvwenlong_lambda@qq.com"
] | lvwenlong_lambda@qq.com |
05ed14ddf26ecdbe01bb3f1e4b0aad2a7988f1c6 | 7247ede3c0eb4f01f4f6d3b845ab32ed80e0c855 | /include/itkPSMEntropyMixedEffectsModelFilter.h | bc44320e5f728fcae164ce035d3314bbbae00d36 | [
"Apache-2.0"
] | permissive | prasanna86/ITKParticleShapeModeling | bbbc7136292329b29e466247f0535750aa547740 | ed3cb4f1a2eb5effe1166ce62fc8680117577102 | refs/heads/master | 2020-12-31T03:15:57.526952 | 2014-02-05T19:10:37 | 2014-02-05T19:10:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,508 | h | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 __itkPSMEntropyMixedEffectsModelFilter_h
#define __itkPSMEntropyMixedEffectsModelFilter_h
#include "itkPSMEntropyModelFilter.h"
#include "itkPSMMixedEffectsShapeMatrixAttribute.h"
namespace itk
{
/** \class PSMEntropyMixedEffectsModelFilter
*
* \brief
*
* This class decorates the base PSMEntropyModelFilter class with some
* additional methods for setting explanatory variables for the
* regression computation and retrieving regression model paramters.
*
* \ingroup PSM
* \ingroup PSMModelingFilters
* \author Josh Cates
*/
template <class TImage, class TShapeMatrix = PSMMixedEffectsShapeMatrixAttribute<double, TImage::ImageDimension> >
class ITK_EXPORT PSMEntropyMixedEffectsModelFilter
: public PSMEntropyModelFilter<TImage,TShapeMatrix>
{
public:
/** Standard class typedefs. */
typedef PSMEntropyMixedEffectsModelFilter Self;
typedef PSMEntropyModelFilter<TImage, TShapeMatrix> Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Dimensionality of the domain of the particle system. */
itkStaticConstMacro(Dimension, unsigned int, TImage::ImageDimension);
/** Type of the particle system */
typedef typename Superclass::ParticleSystemType ParticleSystemType;
/** The type of the Shape Matrix, which defines optimization behavior. */
typedef TShapeMatrix ShapeMatrixType;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(PSMEntropyMixedEffectsModelFilter, PSMEntropyModelFilter);
/** Type of the input/output image. */
typedef typename Superclass::ImageType ImageType;
/** Expose the point type */
typedef typename Superclass::PointType PointType;
/** Type of the optimizer */
typedef typename Superclass::OptimizerType OptimizerType;
/** Set/Get the explanatory variables */
void SetVariables(const std::vector<double> &v)
{
this->GetShapeMatrix()->SetVariables(v);
}
const std::vector<double> &GetVariables() const
{
return this->GetShapeMatrix()->GetVariables();
}
/** */
unsigned int GetTimePointsPerIndividual() const
{
return this->GetShapeMatrix()->GetTimePointsPerIndividual();
}
void SetTimePointsPerIndividual(unsigned int n)
{
this->GetShapeMatrix()->SetTimePointsPerIndividual(n);
}
protected:
PSMEntropyMixedEffectsModelFilter() {}
virtual ~PSMEntropyMixedEffectsModelFilter() {}
void PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
private:
PSMEntropyMixedEffectsModelFilter(const Self&); //purposely not implemented
void operator=(const Self&); //purposely not implemented
};
} // end namespace itk
#endif
| [
"josh.cates@gmail.com"
] | josh.cates@gmail.com |
8c49462e127d8c71701313c4e592efdbb96e4eb2 | 5b24be9bfdca2a81558486483e425e9ece774dac | /SkeletalAng_Kinect/10/Source/10.0.15063.0/ucrt/string/wcsncmp.cpp | 1418875c57ecf31e376f39d407ee806fa5cc7eeb | [] | no_license | jingpingnie/Android-App | cf3fd3eef1c54dbd4252c57ced714b8af05d5bcb | 91980433fcac8c15b0d9d2474c7d05bf4d069362 | refs/heads/master | 2021-10-08T15:20:39.401655 | 2018-12-13T22:40:03 | 2018-12-13T22:40:03 | 161,702,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 928 | cpp | //
// wcsncmp.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Defines wcsncmp(), which compares two wide character strings, determining
// their lexical order. The function tests at most 'count' characters.
//
// Note that the comparison is performed with unsigned elements (wchar_t is
// unsigned in this implementation), so the null character (0) is less than
// all other characters.
//
// Returns:
// * a negative value if a < b
// * zero if a == b
// * a positive value if a > b
//
#include <string.h>
#ifdef _M_ARM
#pragma function(wcsncmp)
#endif
extern "C" int __cdecl wcsncmp(
wchar_t const* a,
wchar_t const* b,
size_t count
)
{
if (count == 0)
return 0;
while (--count != 0 && *a && *a == *b)
{
++a;
++b;
}
return static_cast<int>(*a - *b);
}
| [
"niejingping@dyn-160-39-148-180.dyn.columbia.edu"
] | niejingping@dyn-160-39-148-180.dyn.columbia.edu |
f301290f063e7c00e1288e444271af44fcc21fa0 | e74de656faf680988ca5a2a5dc2948e0649266e6 | /Solving for Carrots/main.cpp | c3c568c5fa0c2b93280b36cfeadfcac1a903bc76 | [] | no_license | kolbjornkelly/kattis | f8445d9bb7211a7de596582b76b1dc242f031574 | 9916365500b3d654ffb36b0be6c7b389778b93b8 | refs/heads/master | 2022-12-22T07:08:12.715068 | 2020-10-01T06:44:53 | 2020-10-01T06:44:53 | 299,951,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | cpp | //
// main.cpp
// Solving for Carrots
//
// Created by Kolbjørn Kelly on 22.09.2017.
// Copyright © 2017 Kolbjørn Kelly. All rights reserved.
//
#include <iostream>
using namespace std;
int main()
{
int contestors;
int problems;
string description;
cin >> contestors >> problems;
cout << endl;
cin >> description;
cout << problems;
return 0;
}
| [
"kolbjorn.kelly@gmail.com"
] | kolbjorn.kelly@gmail.com |
b70082b1700162012797cf0df1595e2be2e427d3 | 5a6e95ea550c1ab70933db273782c79c520ac2ec | /DDK/src/print/oemdll/bitmap/enable.cpp | bc570991b6a30e0333c228e31c079bee19dfee0c | [] | no_license | 15831944/Longhorn_SDK_And_DDK_4074 | ffa9ce6c99345a6c43a414dab9458e4c29f9eb2a | c07d26bb49ecfa056d00b1dffd8981f50e11c553 | refs/heads/master | 2023-03-21T09:27:53.770894 | 2020-10-10T03:34:29 | 2020-10-10T03:34:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,008 | cpp | // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright 1998 - 2003 Microsoft Corporation. All Rights Reserved.
//
// FILE: Enable.cpp
//
//
// PURPOSE: Enable routines for User Mode COM Customization DLL.
//
//
// Functions:
// OEMEnableDriver
// OEMDisableDriver
// OEMEnablePDEV
// OEMResetPDEV
// OEMDisablePDEV
//
//
//
//
// PLATFORMS: Windows XP, Windows Server 2003, Windows codenamed Longhorn
//
//
// History:
// 06/24/03 xxx created.
//
//
#include "precomp.h"
#include <PRCOMOEM.H>
#include "debug.h"
#include "bitmap.h"
#include "ddihook.h"
// ==================================================================
// The purpose of this array is to inform UNIDRV of the callbacks
// that are implemented in this driver.
//
// Note that there is *NO* order dependency in this array. New
// index values and their corresponding callbacks can be placed
// anywhere within the list as needed.
//
static const DRVFN s_aOemHookFuncs[] =
#if defined(DDIS_HAVE_BEEN_IMPL)
{
// The following are defined in ddihook.cpp.
//
#if defined(IMPL_ALPHABLEND)
{INDEX_DrvAlphaBlend, (PFN)OEMAlphaBlend},
#endif
#if defined(IMPL_BITBLT)
{INDEX_DrvBitBlt, (PFN)OEMBitBlt},
#endif
#if defined(IMPL_COPYBITS)
{INDEX_DrvCopyBits, (PFN)OEMCopyBits},
#endif
#if defined(IMPL_DITHERCOLOR)
{INDEX_DrvDitherColor, (PFN)OEMDitherColor},
#endif
#if defined(IMPL_FILLPATH)
{INDEX_DrvFillPath, (PFN)OEMFillPath},
#endif
#if defined(IMPL_FONTMANAGEMENT)
{INDEX_DrvFontManagement, (PFN)OEMFontManagement},
#endif
#if defined(IMPL_GETGLYPHMODE)
{INDEX_DrvGetGlyphMode, (PFN)OEMGetGlyphMode},
#endif
#if defined(IMPL_GRADIENTFILL)
{INDEX_DrvGradientFill, (PFN)OEMGradientFill},
#endif
#if defined(IMPL_LINETO)
{INDEX_DrvLineTo, (PFN)OEMLineTo},
#endif
#if defined(IMPL_PAINT)
{INDEX_DrvPaint, (PFN)OEMPaint},
#endif
#if defined(IMPL_PLGBLT)
{INDEX_DrvPlgBlt, (PFN)OEMPlgBlt},
#endif
#if defined(IMPL_QUERYADVANCEWIDTHS)
{INDEX_DrvQueryAdvanceWidths, (PFN)OEMQueryAdvanceWidths},
#endif
#if defined(IMPL_QUERYFONT)
{INDEX_DrvQueryFont, (PFN)OEMQueryFont},
#endif
#if defined(IMPL_QUERYFONTDATA)
{INDEX_DrvQueryFontData, (PFN)OEMQueryFontData},
#endif
#if defined(IMPL_QUERYFONTTREE)
{INDEX_DrvQueryFontTree, (PFN)OEMQueryFontTree},
#endif
#if defined(IMPL_REALIZEBRUSH)
{INDEX_DrvRealizeBrush, (PFN)OEMRealizeBrush},
#endif
#if defined(IMPL_STRETCHBLT)
{INDEX_DrvStretchBlt, (PFN)OEMStretchBlt},
#endif
#if defined(IMPL_STRETCHBLTROP)
{INDEX_DrvStretchBltROP, (PFN)OEMStretchBltROP},
#endif
#if defined(IMPL_STROKEANDFILLPATH)
{INDEX_DrvStrokeAndFillPath, (PFN)OEMStrokeAndFillPath},
#endif
#if defined(IMPL_STROKEPATH)
{INDEX_DrvStrokePath, (PFN)OEMStrokePath},
#endif
#if defined(IMPL_TEXTOUT)
{INDEX_DrvTextOut, (PFN)OEMTextOut},
#endif
#if defined(IMPL_TRANSPARENTBLT)
{INDEX_DrvTransparentBlt, (PFN)OEMTransparentBlt},
#endif
#if defined(IMPL_STARTDOC)
{INDEX_DrvStartDoc, (PFN)OEMStartDoc},
#endif
#if defined(IMPL_ENDDOC)
{INDEX_DrvEndDoc, (PFN)OEMEndDoc},
#endif
#if defined(IMPL_STARTPAGE)
{INDEX_DrvStartPage, (PFN)OEMStartPage},
#endif
#if defined(IMPL_SENDPAGE)
{INDEX_DrvSendPage, (PFN)OEMSendPage},
#endif
#if defined(IMPL_STARTBANDING)
{INDEX_DrvStartBanding, (PFN)OEMStartBanding},
#endif
#if defined(IMPL_NEXTBAND)
{INDEX_DrvNextBand, (PFN)OEMNextBand},
#endif
#if defined(IMPL_ESCAPE)
{INDEX_DrvEscape, (PFN)OEMEscape},
#endif
};
#else
// No DDI hooks have been enabled. This is provided to eliminate
// a compiler error.
{
{0,NULL}
};
#endif
BOOL APIENTRY
OEMEnableDriver(
DWORD dwOEMintfVersion,
DWORD dwSize,
PDRVENABLEDATA pded
)
/*++
Routine Description:
Implementation of IPrintOemUni::EnableDriver.
OEMEnableDriver is called by IPrintOemUni::EnableDriver
which is defined in intrface.cpp.
The IPrintOemUni::EnableDriver method allows a rendering
plug-in to perform the same types of operations as the
DrvEnableDriver function. Like the DrvEnableDriver function,
the IPrintOemUni::EnableDriver method is responsible for
providing addresses of internally supported graphics DDI functions,
or DDI hook functions.
The method should fill the supplied DRVENABLEDATA structure
and allocate an array of DRVFN structures. It should fill the
array with pointers to hooking functions, along with winddi.h-defined
index values that identify the hooked out graphics DDI functions.
Please refer to DDK documentation for more details.
Arguments:
IN DriverVersion - interface version number. This value is defined
by PRINTER_OEMINTF_VERSION, in printoem.h.
IN cbSize - size, in bytes, of the structure pointed to by pded.
OUT pded - pointer to a DRVENABLEDATA structure. Fill this structure
with pointers to the DDI hook functions.
Return Value:
TRUE if successful, FALSE if there is an error
--*/
{
OEMDBG(DBG_VERBOSE, L"OEMEnableDriver entry.");
// We need to return the DDI functions that have been hooked
// in pded. Here we fill out the fields in pded.
//
pded->iDriverVersion = PRINTER_OEMINTF_VERSION;
pded->c = sizeof(s_aOemHookFuncs) / sizeof(DRVFN);
pded->pdrvfn = (DRVFN *) s_aOemHookFuncs;
return TRUE;
}
VOID APIENTRY
OEMDisableDriver(
VOID
)
/*++
Routine Description:
Implementation of IPrintOemUni::DisableDriver.
OEMDisableDriver is called by IPrintOemUni::DisableDriver
which is defined in intrface.cpp.
The IPrintOemUni::DisableDriver method allows a rendering
plug-in for Unidrv to free resources that were allocated by the
plug-in's IPrintOemUni::EnableDriver method. This is the last
IPrintOemUni interface method that is called before the rendering
plug-in is unloaded.
Please refer to DDK documentation for more details.
Arguments:
NONE
Return Value:
NONE
--*/
{
OEMDBG(DBG_VERBOSE, L"OEMDisableDriver entry.");
// Do any cleanup stuff here
//
}
PDEVOEM APIENTRY
OEMEnablePDEV(
PDEVOBJ pdevobj,
PWSTR pPrinterName,
ULONG cPatterns,
HSURF *phsurfPatterns,
ULONG cjGdiInfo,
GDIINFO *pGdiInfo,
ULONG cjDevInfo,
DEVINFO *pDevInfo,
DRVENABLEDATA *pded // Unidrv's hook table
)
/*++
Routine Description:
Implementation of IPrintOemUni::EnablePDEV.
OEMEnablePDEV is called by IPrintOemUni::EnablePDEV
which is defined in intrface.cpp.
The IPrintOemUni::EnablePDEV method performs the same types
of operations as the DrvEnablePDEV function that is exported
by a printer graphics DLL. Its purpose is to allow a rendering
plug-in to create its own PDEV structure. For more information
about PDEV structures, see "Customized PDEV Structures" in the DDK docs.
Please refer to DDK documentation for more details.
Arguments:
IN pdevobj - pointer to a DEVOBJ structure.
IN pPrinterName - pointer to a text string representing the logical
address of the printer.
IN cPatterns - value representing the number of HSURF-typed
surface handles contained in the buffer pointed to
by phsurfPatterns.
IN phsurfPatterns - pointer to a buffer that is large enough to
contain cPatterns number of HSURF-typed
surface handles.
IN cjGdiInfo - value representing the size of the structure pointed
to by pGdiInfo.
IN pGdiInfo - pointer to a GDIINFO structure.
IN cjDevInfo - value representing the size of the structure pointed
to by pDevInfo.
IN pDevInfo - pointer to a DEVINFO structure.
IN pded - pointer to a DRVENABLEDATA structure containing the
addresses of the printer driver's graphics DDI hooking functions.
Return Value:
OUT pDevOem - pointer to a private PDEV structure.
Return NULL if error occurs.
--*/
{
OEMDBG(DBG_VERBOSE, L"OEMEnablePDEV entry.");
// Allocate an instance of our private PDEV.
//
POEMPDEV pOemPDEV = new COemPDEV();
if (NULL == pOemPDEV)
{
return NULL;
}
pOemPDEV->InitializeDDITable(pded);
DBG_GDIINFO(DBG_VERBOSE, L"pGdiInfo", pGdiInfo);
DBG_DEVINFO(DBG_VERBOSE, L"pDevInfo", pDevInfo);
// Initializing private oempdev stuff
//
pOemPDEV->bHeadersFilled = FALSE;
pOemPDEV->bColorTable = FALSE;
pOemPDEV->cbHeaderOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
pOemPDEV->bmInfoHeader.biHeight = 0;
pOemPDEV->bmInfoHeader.biSizeImage = 0;
pOemPDEV->pBufStart = NULL;
pOemPDEV->dwBufSize = 0;
// We create a BGR palette for 24bpp so that we can avoid color byte order manipulation
//
if (pGdiInfo->cBitsPixel == 24)
pDevInfo->hpalDefault = EngCreatePalette(PAL_BGR, 0, 0, 0, 0, 0);
// Store the handle to the default palette so that we can fill the color table later
//
pOemPDEV->hpalDefault = pDevInfo->hpalDefault;
return pOemPDEV;
}
BOOL APIENTRY
OEMResetPDEV(
PDEVOBJ pdevobjOld,
PDEVOBJ pdevobjNew
)
/*++
Routine Description:
Implementation of IPrintOemUni::ResetPDEV.
OEMResetPDEV is called by IPrintOemUni::ResetPDEV
which is defined in intrface.cpp.
A rendering plug-in's IPrintOemUni::ResetPDEV method performs
the same types of operations as the DrvResetPDEV function. During
the processing of an application's call to the Platform SDK ResetDC
function, the IPrintOemUni::ResetPDEV method is called by Unidrv's
DrvResetPDEV function. For more information about when DrvResetPDEV
is called, see its description in the DDK docs.
The rendering plug-in's private PDEV structure's address is contained
in the pdevOEM member of the DEVOBJ structure pointed to by pdevobjOld.
The IPrintOemUni::ResetPDEV method should use relevant members of this
old structure to fill in the new structure, which is referenced through pdevobjNew.
Please refer to DDK documentation for more details.
Arguments:
IN pdevobjOld - pointer to a DEVOBJ structure containing
current PDEV information.
OUT pdevobjNew - pointer to a DEVOBJ structure into which
the method should place new PDEV information.
Return Value:
TRUE if successful, FALSE if there is an error
--*/
{
OEMDBG(DBG_VERBOSE, L"OEMResetPDEV entry.");
return TRUE;
}
VOID APIENTRY
OEMDisablePDEV(
PDEVOBJ pdevobj
)
/*++
Routine Description:
Implementation of IPrintOemUni::DisablePDEV.
OEMDisablePDEV is called by IPrintOemUni::DisablePDEV
which is defined in intrface.cpp.
The IPrintOemUni::DisablePDEV method performs the same types of
operations as the DrvDisablePDEV function. Its purpose is to allow a
rendering plug-in to delete the private PDEV structure that is pointed
to by the DEVOBJ structure's pdevOEM member. This PDEV structure
is one that was allocated by the plug-in's IPrintOemUni::EnablePDEV method.
Please refer to DDK documentation for more details.
Arguments:
IN pdevobj - pointer to a DEVOBJ structure.
Return Value:
NONE
--*/
{
OEMDBG(DBG_VERBOSE, L"OEMDisablePDEV entry.");
// Release our COemPDEV instance created by the call to
// EnablePDEV.
//
POEMPDEV pOemPDEV = (POEMPDEV)pdevobj->pdevOEM;
delete pOemPDEV;
pOemPDEV = NULL;
}
| [
"masonleeback@gmail.com"
] | masonleeback@gmail.com |
493ee23e6327597dd3980df3418c304a5b297994 | a2c803dcec27a058644a633f6bc0f0ad42482144 | /src/qt/optionsmodel.h | bb374937984999bf78b9740a852f1279f7a54d9d | [
"MIT"
] | permissive | AUHtoken/Gold_Hawgs | 1631bf209c332090d53b8248da4708fb6e32fbf0 | b65c073bf5b743a197428159c0b5a1af018f5a3a | refs/heads/master | 2020-06-13T08:57:23.899683 | 2019-10-04T12:23:50 | 2019-10-04T12:23:50 | 194,607,138 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,951 | h | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef OPTIONSMODEL_H
#define OPTIONSMODEL_H
#include <QAbstractListModel>
extern bool fUseBlackTheme;
QT_BEGIN_NAMESPACE
class QNetworkProxy;
QT_END_NAMESPACE
/** Interface from Qt to configuration data structure for Bitcoin client.
To Qt, the options are presented as a list with the different options
laid out vertically.
This can be changed to a tree once the settings become sufficiently
complex.
*/
class OptionsModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit OptionsModel(QObject *parent = 0);
enum OptionID {
StartAtStartup, // bool
MinimizeToTray, // bool
MapPortUPnP, // bool
MinimizeOnClose, // bool
ProxyUse, // bool
ProxyIP, // QString
ProxyPort, // int
ProxySocksVersion, // int
Fee, // qint64
ReserveBalance, // qint64
DisplayUnit, // BitcoinUnits::Unit
Language, // QString
CoinControlFeatures, // bool
UseBlackTheme, // bool
DarksendRounds, // int
AnonymizeGold_HawgsAmount, //int
OptionIDRowCount,
};
void Init();
void Reset();
int rowCount(const QModelIndex & parent = QModelIndex()) const;
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole);
/* Explicit getters */
qint64 getReserveBalance();
bool getMinimizeToTray() { return fMinimizeToTray; }
bool getMinimizeOnClose() { return fMinimizeOnClose; }
int getDisplayUnit() { return nDisplayUnit; }
bool getProxySettings(QNetworkProxy& proxy) const;
bool getCoinControlFeatures() { return fCoinControlFeatures; }
const QString& getOverriddenByCommandLine() { return strOverriddenByCommandLine; }
/* Restart flag helper */
void setRestartRequired(bool fRequired);
bool isRestartRequired();
private:
/* Qt-only settings */
bool fMinimizeToTray;
bool fMinimizeOnClose;
QString language;
int nDisplayUnit;
bool fCoinControlFeatures;
/* settings that were overriden by command-line */
QString strOverriddenByCommandLine;
/// Add option to list of GUI options overridden through command line/config file
void addOverriddenOption(const std::string &option);
signals:
void displayUnitChanged(int unit);
void transactionFeeChanged(qint64);
void reserveBalanceChanged(qint64);
void coinControlFeaturesChanged(bool);
void darksendRoundsChanged(int);
void AnonymizeGold_HawgsAmountChanged(int);
};
#endif // OPTIONSMODEL_H
| [
"52383318+AUHtoken@users.noreply.github.com"
] | 52383318+AUHtoken@users.noreply.github.com |
f37e2ff5505e3007e41e5bd77db06808d9dcade1 | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/RcppAlgos/inst/include/CombPermResultPtr.h | 20929704ec5f755f57459958b84de37166e84d8e | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,284 | h | #ifndef COMB_PERM_RESULT_PTR_H
#define COMB_PERM_RESULT_PTR_H
#include "CombinationResults.h"
#include "PermutationResults.h"
template <typename T, typename U>
using combPermResPtr = void (*const)(T &matRcpp, const std::vector<U> &v,
std::vector<int> z, int n, int m, int strt, int nRows,
const std::vector<int> &freqs, funcPtr<U> myFun);
template <typename T, typename U>
Rcpp::XPtr<combPermResPtr<T, U>> putCombResPtrInXPtr(bool IsComb, bool IsMult, bool IsRep) {
if (IsComb) {
if (IsMult)
return(Rcpp::XPtr<combPermResPtr<T, U>>(new combPermResPtr<T, U>(&MultisetComboResult)));
else if (IsRep)
return(Rcpp::XPtr<combPermResPtr<T, U>>(new combPermResPtr<T, U>(&ComboGenResRep)));
else
return(Rcpp::XPtr<combPermResPtr<T, U>>(new combPermResPtr<T, U>(&ComboGenResNoRep)));
} else {
if (IsMult)
return(Rcpp::XPtr<combPermResPtr<T, U>>(new combPermResPtr<T, U>(&MultisetPermRes)));
else if (IsRep)
return(Rcpp::XPtr<combPermResPtr<T, U>>(new combPermResPtr<T, U>(&PermuteGenResRep)));
else
return(Rcpp::XPtr<combPermResPtr<T, U>>(new combPermResPtr<T, U>(&PermuteGenResNoRep)));
}
}
#endif
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
317a06a99c0305c644cb8492ee8a559f427a2934 | c94dc44f5040cabdad07cbb2e4daa45ea00cfcb6 | /src/ABP.cpp | ee17c3e7b132649c37e3d695e54e89de255a5f20 | [
"MIT"
] | permissive | presunto7/test | cec5cb0aa8e11c4f7690cf7d9b0b3ef4a8011932 | 23b4d2efa877ae88f023e7231a92b62752e49340 | refs/heads/master | 2023-04-02T01:27:19.659246 | 2021-04-09T11:34:23 | 2021-04-09T11:34:23 | 346,517,160 | 0 | 1 | MIT | 2021-04-09T11:34:24 | 2021-03-10T23:10:14 | Python | UTF-8 | C++ | false | false | 1,510 | cpp | #include "ABP.h"
#include <Wire.h>
ABP::ABP(int i2c_adress)
{
this->m_i2c_adress = i2c_adress;
this->m_pressure_psi = 0;
this->m_pressure_cmh2o = 0;
Wire.begin();
}
ABP::~ABP()
{
}
void ABP::read_sensor()
{
uint16_t data = 0;
data = request_data();
this->m_pressure_psi = calculate_pressure(data);
this->m_pressure_cmh2o = convert_psi_to_cho(this->m_pressure_psi);
return;
}
uint16_t ABP::request_data()
{
uint16_t data = 0;
uint8_t index = 0;
Wire.requestFrom(m_i2c_adress,ABP_NUM_BYTES);
while(Wire.available())
{
uint8_t c = Wire.read();
data = (data << (index * 8)) | c ;
index = index + 1;
}
return data;
}
double ABP::calculate_pressure(uint16_t rev_data)
{
double pressure = 0;
uint16_t data = rev_data;
double out = 0;
#ifdef PERCENTAGE //if percentage is defined, calculate correspondent output percentage to convert into pressure
double perc = convert_out_hex_to_perc(data);
Serial.println(perc, DEC);
Serial.print("\r\n");
out=perc;
#else //if PERCENTAGE is not defined use data as output
out = data;
#endif //end ifdef PERCENTAGE
pressure = (((out - ABP_OUT_MIN) * (ABP_P_RANGE)) / ABP_OUT_MAX ) + ABP_P_MIN;
return pressure;
}
#ifdef PERCENTAGE
double ABP::convert_out_hex_to_perc(uint16_t data){
return double((100.0/ABP_OUT_MAX_HEX)*data);
}
#endif
double ABP::convert_psi_to_cho(double pressure)
{
return pressure * PSI_TO_CMCH2O;
}
| [
"bruno.vilaca.sa@gmail.com"
] | bruno.vilaca.sa@gmail.com |
78b762d2959fca6380ef60db100bb9d41f599c98 | d05f7e6ecf895dc553cdf596f00609d68b957d3f | /Source/Flanger.h | bd22a69da02fa48ed2271af422a5892aecea39ed | [] | no_license | kartikaygolcha/Clove-Synthesizer | e4e7509b8541826c332c9564426cf32198affd1c | ebb10e9b0b88ecacbbed2c53979e3c1ae19b5930 | refs/heads/master | 2022-05-25T01:01:09.637780 | 2020-05-04T01:13:37 | 2020-05-04T01:13:37 | 261,052,026 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,638 | h | /*
==============================================================================
Flanger.h
Class file for a Flanger/Chorus and a Delay Line
==============================================================================
*/
//Inclde Oscillators Class
#include "Oscillators.h"
/**
Class Flanger for adding flanging
*/
class Flanger
{
public:
//Set initial flanger parameters
Flanger() : osc1()
{
osc1.setSampleRate(sampleRate);
osc1.setFrequency(freq1);
osc2.setSampleRate(sampleRate);
osc2.setFrequency(freq2);
clear();
};
/// Clearing the Buffer
void clear()
{
buffer1 = new float[bufferSize];
for (int i = 0; i < bufferSize; i++)
buffer1[i] = 0;
}
/// Process a sample and add flanger to it
float process(float input)
{
float delay2 = 20 * (1 + (osc2.process()));
float delay = 10 * (1 + (osc1.process()));
float fb = interpolate(delay);
float fb2 = interpolate(delay2);
float out = input + (gain * fb) + (gain2 * fb2);
return (out/3.0f);
}
/// Adding sample to a parallel buffer
void addSampleToBuffer(float data) {
buffer1[writePos] = data;
writePos++;
writePos %= bufferSize;
}
/// Read Sample from Delay Line @params delay-> Delay from writePos in Samples
float getSample(int delay) {
if (writePos - delay < 0)
return buffer1[bufferSize + writePos - delay];
else
return buffer1[writePos - delay];
}
/// Interpolate Samples @params-> idx
float interpolate(float idx)
{
float b = getSample((int)idx);
float a = getSample((int)idx + 1);
return (((1-idx + (int)idx)) * (b - a) + a);
}
/// Set Gain for two oscillators @params g-> Gain 1 or g1-> Gain2
void setGain(float g, float g1)
{
gain = g;
gain2 = g1;
}
/// Set Sample Rate
void setSampleRate(float sr)
{
sampleRate=sr;
}
/// Set BufferSize
void setBufferSize(int buff_size)
{
delete buffer1;
bufferSize=buff_size ;
clear();
}
/// Set Gain for two oscillators
void setFreuency(float fr1, float fr2)
{
freq1 = fr1;
freq2 = fr2;
osc1.setSampleRate(sampleRate);
osc1.setFrequency(freq1);
osc2.setSampleRate(sampleRate);
osc2.setFrequency(freq2);
}
private:
SinOsc osc1, osc2; // Sin Oscillator Instances
float sampleRate=44100.0f; // Sample Rate
float freq1=0.5f,freq2=2.0f; // Frequency for two Oscillators
float gain = 0.6f, gain2 = 0.7f; //Gains for each osc
int writePos = 0; //index for write pointer
int bufferSize = 44100; //bufferSize in samples
float* buffer1; //Uninitialized Buffer pointer
};
/// Delay Line Class
class DelayLine
{
public:
/// store a value in the delay and retrieve the sample at the current read position
float process(float inSamp)
{
float outVal = readVal();
writeVal(inSamp + feedback * outVal); // note the feedback here, scaling the output back in to the delay
return outVal;
}
/// read a value from the buffer at the read head position, then increment and wrap the readPos
float readVal()
{
float outVal = buffer[readPos];
readPos++;
readPos %= size;
return outVal;
}
/// write a value to the buffer at the write head position, then increment and wrap the writePos
void writeVal(float inSamp)
{
buffer[writePos] = inSamp;
writePos++;
writePos %= size;
}
/// set the actual delay time in samples
void setDelayTimeInSamples(int delTime)
{
delayTimeInSamples = delTime;
readPos = writePos - delayTimeInSamples;
while (readPos < 0)
readPos += size;
}
/// initialise the float array to a given maximum size (your specified delay time must always be less than this)
void setSize(int newSize)
{
size = newSize;
buffer = new float[size];
for (int i = 0; i < size; i++)
{
buffer[i] = 0.0f;
}
}
void setFeedback(float fb)
{
feedback = fb;
// check we're not going to get crazy positive feedback:
if (feedback > 1)
feedback = 1.0f;
if (feedback < 0)
feedback = 0.0f;
}
private:
float* buffer; // the actual buffer - not yet initialised to a size
int size; // buffer size in samples
int writePos = 0; // write head location - should always be 0 ≤ writePos < size
int readPos = 0.0f; // read head location - should always be 0 ≤ readPos < size
int delayTimeInSamples;
float feedback = 0.0f; // how much of the delay line to mix with the input?
};
#pragma once
| [
"noreply@github.com"
] | noreply@github.com |
4e8180f50c8e32a7a25438cac39042c42d43efaf | c3b3dffa5c84a4de04934b699e645788d0fb370e | /GFG 11 Week/array/practice/rough.cpp | 3702dd74a7a41b15e310d4d34cd85e91232b5ff5 | [] | no_license | guptasajal411/problem-solving | ceb94cd4d5e010032af58193511ab07fcea6c3d6 | 24ab9f94c8da6a6d12302648fa1f1df507982518 | refs/heads/main | 2023-06-19T12:47:41.743573 | 2021-07-16T12:17:42 | 2021-07-16T12:17:42 | 343,034,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 935 | cpp | // { Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
int remove_duplicate(int array[],int n){
for (int i = 0; i < n + 1; i++){
for (int i = 1; i < n; i++){
if (array[i] == array[i - 1]){
for (int j = i; j < n; j++){
array[j] = array[j + 1];
}
n = n - 1;
}
}
}
return array[];
}
};
// { Driver Code Starts.
int main()
{
int T;
cin>>T;
while(T--)
{
int N;
cin>>N;
int a[N];
for(int i=0;i<N;i++)
{
cin>>a[i];
}
Solution ob;
int n = ob.remove_duplicate(a,N);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
} // } Driver Code Ends | [
"guptasajal411@gmail.com"
] | guptasajal411@gmail.com |
66230e2eaced3ec7222c3835b76b08999d41f770 | 00340ef958689a9be50c6a6c726cbfa344eb15f0 | /Unit/cscene.cpp | 34dc56889adf6a72aae0f50028159eb953942863 | [] | no_license | ikutoo/yggdrasil | b7d79d96922db5a9c94fc782f471f410444769c5 | 4d5e1ef0caec1e13425c097d98e11d87774e985b | refs/heads/master | 2021-01-17T23:02:00.955443 | 2017-03-07T14:45:43 | 2017-03-07T14:45:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,663 | cpp | /**************************************************************************
File: cscene.cpp
Author: Song Xiaofeng
Date: 2016-05-17
Description:
**************************************************************************/
#include "cscene.h"
#include <QBrush>
#include "Unit/basic_data_structure.h"
///////////////////////////////////////////////////////////////////
//all public functions are here
///////////////////////////////////////////////////////////////////
CScene::CScene(QWidget* parent) {
this->setParent(parent);
this->setBackgroundBrush(QBrush(QColor("#A0A0A0"), Qt::CrossPattern));
mBuildConnects();
//this->setForegroundBrush();
}
///////////////////////////////////////////////////////////////////
//all private functions are here
///////////////////////////////////////////////////////////////////
void CScene::mousePressEvent(QMouseEvent * event) {
}
void CScene::slot_selected_item_changed() {
QList<QGraphicsItem*> itemList = this->selectedItems();
emit signal_update_component(itemList);
QList<int> list;
for (QList<QGraphicsItem*>::iterator it = itemList.begin(); it != itemList.end(); it++) {
int id = (*it)->data(EnumDataType::DataId).toInt();
list.push_back(id);
}
emit signal_update_selected_item(list);
}
void CScene::mBuildConnects() {
connect(this, &CScene::changed, this, &CScene::slot_selected_item_changed);
m_unitController = CUnitController::getInstance();
connect(this, &CScene::signal_update_selected_item, m_unitController, &CUnitController::slot_update_selected_item);
connect(this, &CScene::signal_update_component, m_unitController, &CUnitController::slot_update_component);
} | [
"1007833641@qq.com"
] | 1007833641@qq.com |
efe1f182ad2b02bfb95a1d4c6f205b1c405bb660 | ebc5e13e1a88de8479649734c7244d3fa62c5bd0 | /cursuri/users_code/amiel-21-7.cpp | f5059e6cfbcd28543777c8e9d013d08286fdd985 | [] | no_license | msorins/IronCoders | 9a1c84e20bca78a5f00ca02785f3617100749964 | 910713d6cfebeab2d88c19120a21238f17f3ff7f | refs/heads/master | 2021-01-23T08:29:12.189949 | 2019-02-24T09:35:37 | 2019-02-24T09:35:37 | 102,522,229 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | #include <iostream>
using namespace std;
int main()
{
int x,y;
cin>>x>>y;
if (x>5){
}
else
{
x<5;
cout << "Scrie un numar valid";
}
} | [
"root@server.mirceasorin.ro"
] | root@server.mirceasorin.ro |
9322d7527bb3e5be257a25fa1a168fb3d80dfb81 | fcdea24e6466d4ec8d7798555358a9af8acf9b35 | /Engine/mrayMath/Polygon2D.h | fd65a46f2443e65b54f9ae34f6f28d1772dd58e6 | [] | no_license | yingzhang536/mrayy-Game-Engine | 6634afecefcb79c2117cecf3e4e635d3089c9590 | 6b6fcbab8674a6169e26f0f20356d0708620b828 | refs/heads/master | 2021-01-17T07:59:30.135446 | 2014-11-30T16:10:54 | 2014-11-30T16:10:54 | 27,630,181 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,083 | h |
/********************************************************************
created: 2009/02/01
created: 1:2:2009 19:32
filename: i:\Programing\GameEngine\mrayEngine\mrayEngine\include\Polygon2D.h
file path: i:\Programing\GameEngine\mrayEngine\mrayEngine\include
file base: Polygon2D
file ext: h
author: Mohamad Yamen Saraiji
purpose:
*********************************************************************/
#ifndef ___Polygon2D___
#define ___Polygon2D___
#include "Point2d.h"
#include "rect.h"
//#include "mArray.h"
#include <vector>
namespace mray{
namespace math{
class MRAY_MATH_DLL Polygon2D
{
protected:
std::vector<math::vector2d> m_points;
math::rectf m_boundingRect;
public:
Polygon2D();
virtual~Polygon2D();
void addPoint(const math::vector2d &p);
void removePoint(size_t i);
void clear();
const math::vector2d& getPoint(size_t i)const;
size_t getPointsCount()const;
const math::rectf& getBoundingRect()const;
bool isPointInside(const math::vector2d&p)const;
};
}
}
#endif //___Polygon2D___
| [
"mrayyamen@gmail.com"
] | mrayyamen@gmail.com |
e9668051a77652285482481ec2d62a9df2e924a2 | b8f91f0f394874af500f1b9757fc37274bad28cc | /huffman_testing.cpp | 2d409fc156d614b671298f77dbfa3cfb28d8ab0e | [] | no_license | HelenYO/Huffman | ca95b24135e364eb8ccb8480ae0dd8d56ec81d97 | b71c8d227429d5bb9747a099d2f57f5228406758 | refs/heads/master | 2020-03-31T02:25:24.798901 | 2018-10-06T13:31:10 | 2018-10-06T13:31:10 | 151,822,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,368 | cpp | #include <sstream>
#include <random>
#include "gtest/gtest.h"
#include "lib/huffman.h"
namespace {
std::string compress_decompress(std::string const& str) {
std::istringstream in(str);
std::ostringstream compressed_out;
compress(in, compressed_out);
std::istringstream compressed_in(compressed_out.str());
std::ostringstream decompressed_out;
decompress(compressed_in, decompressed_out);
return decompressed_out.str();
}
}
TEST(correctness, blank) // NOLINT
{
std::string str;
EXPECT_EQ(str, compress_decompress(str));
}
namespace {
std::mt19937 gen(0); // NOLINT
std::uniform_int_distribution<> char_dist(std::numeric_limits<char>::min(), std::numeric_limits<char>::max()); // NOLINT
char random_char()
{
return static_cast<char>(char_dist(gen));
}
std::string random_string(size_t n)
{
std::string str;
str.reserve(n);
for (size_t i = 0; i < n; ++i) {
str.push_back(random_char());
}
return str;
}
std::uniform_int_distribution<> short_str_dist(0, 500); // NOLINT
size_t random_short_str_length()
{
return static_cast<size_t>(short_str_dist(gen));
}
}
TEST(correctness, random_short_strings) // NOLINT
{
constexpr size_t LOOP_COUNT = 100;
for (size_t i = 0; i < LOOP_COUNT; ++i) {
std::string str = random_string(random_short_str_length());
EXPECT_EQ(str, compress_decompress(str));
}
}
namespace {
std::uniform_int_distribution<> long_str_dist(10000, 100000); // NOLINT
size_t random_long_str_length()
{
return static_cast<size_t>(long_str_dist(gen));
}
}
TEST(correctness, random_long_strings) // NOLINT
{
constexpr size_t LOOP_COUNT = 50;
for (size_t i = 0; i < LOOP_COUNT; ++i) {
std::string str = random_string(random_long_str_length());
EXPECT_EQ(str, compress_decompress(str));
}
}
namespace {
std::uniform_int_distribution<> long_long_str_dist(100000, 1000000); // NOLINT
size_t random_long_long_str_length()
{
return static_cast<size_t>(long_long_str_dist(gen));
}
}
TEST(correctness, random_long_long_strings) // NOLINT
{
constexpr size_t LOOP_COUNT = 25;
for (size_t i = 0; i < LOOP_COUNT; ++i) {
std::string str = random_string(random_long_long_str_length());
EXPECT_EQ(str, compress_decompress(str));
}
} | [
"noreply@github.com"
] | noreply@github.com |
854b3d90b35f38e0e4452fec9c4e534029efc898 | c1e31e0ec70f3cc1caa2e17f07fe1e1a01301bbe | /widgets/ui_aboutdialog.h | b795fd116e91b3dd924c329c32ebdab226c8d87a | [] | no_license | pm19960106/painttyWidget | ca1c20c0570853d0fdb1456ab6c71cc9e3979418 | 01dea25dc559fd64026a78ca0bbc1fab3746fa0e | refs/heads/master | 2021-01-18T15:57:17.630904 | 2013-02-20T08:25:29 | 2013-02-20T08:25:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,930 | h | /********************************************************************************
** Form generated from reading UI file 'aboutdialog.ui'
**
** Created by: Qt User Interface Compiler version 5.0.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_ABOUTDIALOG_H
#define UI_ABOUTDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QVBoxLayout>
QT_BEGIN_NAMESPACE
class Ui_AboutDialog
{
public:
QVBoxLayout *verticalLayout;
QLabel *label_2;
QDialogButtonBox *buttonBox;
void setupUi(QDialog *AboutDialog)
{
if (AboutDialog->objectName().isEmpty())
AboutDialog->setObjectName(QStringLiteral("AboutDialog"));
verticalLayout = new QVBoxLayout(AboutDialog);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
label_2 = new QLabel(AboutDialog);
label_2->setObjectName(QStringLiteral("label_2"));
QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(label_2->sizePolicy().hasHeightForWidth());
label_2->setSizePolicy(sizePolicy);
label_2->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop);
label_2->setWordWrap(true);
label_2->setOpenExternalLinks(true);
label_2->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse);
verticalLayout->addWidget(label_2);
buttonBox = new QDialogButtonBox(AboutDialog);
buttonBox->setObjectName(QStringLiteral("buttonBox"));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Ok);
verticalLayout->addWidget(buttonBox);
retranslateUi(AboutDialog);
QObject::connect(buttonBox, SIGNAL(accepted()), AboutDialog, SLOT(accept()));
QMetaObject::connectSlotsByName(AboutDialog);
} // setupUi
void retranslateUi(QDialog *AboutDialog)
{
AboutDialog->setWindowTitle(QApplication::translate("AboutDialog", "About", 0));
label_2->setText(QApplication::translate("AboutDialog", "<p>Mr.Paint is a free software for paint-chat. However, it's in alpha state.</p><p>If you have any questions about Mr.Paint, please visit <a href=\"http://mrspaint.com\">our site</a>.</p>", 0));
} // retranslateUi
};
namespace Ui {
class AboutDialog: public Ui_AboutDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_ABOUTDIALOG_H
| [
"liuyanghejerry@126.com"
] | liuyanghejerry@126.com |
31c0627f763c6d6e27ecc89058f53e793c0d31f4 | 21553f6afd6b81ae8403549467230cdc378f32c9 | /arm/cortex/Freescale/MK70F12/include/arch/reg/mcg.hpp | 6358d0eaca313ae824e48448f279596a3e76409a | [] | no_license | digint/openmptl-reg-arm-cortex | 3246b68dcb60d4f7c95a46423563cab68cb02b5e | 88e105766edc9299348ccc8d2ff7a9c34cddacd3 | refs/heads/master | 2021-07-18T19:56:42.569685 | 2017-10-26T11:11:35 | 2017-10-26T11:11:35 | 108,407,162 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,702 | hpp | /*
* OpenMPTL - C++ Microprocessor Template Library
*
* This program is a derivative representation of a CMSIS System View
* Description (SVD) file, and is subject to the corresponding license
* (see "Freescale CMSIS-SVD License Agreement.pdf" in the parent directory).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
////////////////////////////////////////////////////////////////////////
//
// Import from CMSIS-SVD: "Freescale/MK70F12.svd"
//
// vendor: Freescale Semiconductor, Inc.
// vendorID: Freescale
// name: MK70F12
// series: Kinetis_K
// version: 1.6
// description: MK70F12 Freescale Microcontroller
// --------------------------------------------------------------------
//
// C++ Header file, containing architecture specific register
// declarations for use in OpenMPTL. It has been converted directly
// from a CMSIS-SVD file.
//
// https://digint.ch/openmptl
// https://github.com/posborne/cmsis-svd
//
#ifndef ARCH_REG_MCG_HPP_INCLUDED
#define ARCH_REG_MCG_HPP_INCLUDED
#warning "using untested register declarations"
#include <register.hpp>
namespace mptl {
/**
* Multipurpose Clock Generator module
*/
struct MCG
{
static constexpr reg_addr_t base_addr = 0x40064000;
/**
* MCG Control 1 Register
*/
struct C1
: public reg< uint8_t, base_addr + 0, rw, 0x4 >
{
using type = reg< uint8_t, base_addr + 0, rw, 0x4 >;
using IREFSTEN = regbits< type, 0, 1 >; /**< Internal Reference Stop Enable */
using IRCLKEN = regbits< type, 1, 1 >; /**< Internal Reference Clock Enable */
using IREFS = regbits< type, 2, 1 >; /**< Internal Reference Select */
using FRDIV = regbits< type, 3, 3 >; /**< FLL External Reference Divider */
using CLKS = regbits< type, 6, 2 >; /**< Clock Source Select */
};
/**
* MCG Control 2 Register
*/
struct C2
: public reg< uint8_t, base_addr + 0x1, rw, 0x80 >
{
using type = reg< uint8_t, base_addr + 0x1, rw, 0x80 >;
using IRCS = regbits< type, 0, 1 >; /**< Internal Reference Clock Select */
using LP = regbits< type, 1, 1 >; /**< Low Power Select */
using EREFS0 = regbits< type, 2, 1 >; /**< External Reference Select */
using HGO0 = regbits< type, 3, 1 >; /**< High Gain Oscillator Select */
using RANGE0 = regbits< type, 4, 2 >; /**< Frequency Range Select */
using LOCRE0 = regbits< type, 7, 1 >; /**< Loss of Clock Reset Enable */
};
/**
* MCG Control 3 Register
*/
struct C3
: public reg< uint8_t, base_addr + 0x2, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x2, rw, 0 >;
using SCTRIM = regbits< type, 0, 8 >; /**< Slow Internal Reference Clock Trim Setting */
};
/**
* MCG Control 4 Register
*/
struct C4
: public reg< uint8_t, base_addr + 0x3, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x3, rw, 0 >;
using SCFTRIM = regbits< type, 0, 1 >; /**< Slow Internal Reference Clock Fine Trim */
using FCTRIM = regbits< type, 1, 4 >; /**< Fast Internal Reference Clock Trim Setting */
using DRST_DRS = regbits< type, 5, 2 >; /**< DCO Range Select */
using DMX32 = regbits< type, 7, 1 >; /**< DCO Maximum Frequency with 32.768 kHz Reference */
};
/**
* MCG Control 5 Register
*/
struct C5
: public reg< uint8_t, base_addr + 0x4, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x4, rw, 0 >;
using PRDIV0 = regbits< type, 0, 3 >; /**< PLL0 External Reference Divider */
using PLLSTEN0 = regbits< type, 5, 1 >; /**< PLL0 Stop Enable */
using PLLCLKEN0 = regbits< type, 6, 1 >; /**< PLL Clock Enable */
using PLLREFSEL0 = regbits< type, 7, 1 >; /**< PLL0 External Reference Select */
};
/**
* MCG Control 6 Register
*/
struct C6
: public reg< uint8_t, base_addr + 0x5, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x5, rw, 0 >;
using VDIV0 = regbits< type, 0, 5 >; /**< VCO0 Divider */
using CME0 = regbits< type, 5, 1 >; /**< Clock Monitor Enable */
using PLLS = regbits< type, 6, 1 >; /**< PLL Select */
using LOLIE0 = regbits< type, 7, 1 >; /**< Loss of Lock Interrrupt Enable */
};
/**
* MCG Status Register
*/
struct S
: public reg< uint8_t, base_addr + 0x6, rw, 0x10 >
{
using type = reg< uint8_t, base_addr + 0x6, rw, 0x10 >;
using IRCST = regbits< type, 0, 1 >; /**< Internal Reference Clock Status */
using OSCINIT0 = regbits< type, 1, 1 >; /**< OSC Initialization */
using CLKST = regbits< type, 2, 2 >; /**< Clock Mode Status */
using IREFST = regbits< type, 4, 1 >; /**< Internal Reference Status */
using PLLST = regbits< type, 5, 1 >; /**< PLL Select Status */
using LOCK0 = regbits< type, 6, 1 >; /**< Lock Status */
using LOLS0 = regbits< type, 7, 1 >; /**< Loss of Lock Status */
};
/**
* MCG Status and Control Register
*/
struct SC
: public reg< uint8_t, base_addr + 0x8, rw, 0x2 >
{
using type = reg< uint8_t, base_addr + 0x8, rw, 0x2 >;
using LOCS0 = regbits< type, 0, 1 >; /**< OSC0 Loss of Clock Status */
using FCRDIV = regbits< type, 1, 3 >; /**< Fast Clock Internal Reference Divider */
using FLTPRSRV = regbits< type, 4, 1 >; /**< FLL Filter Preserve Enable */
using ATMF = regbits< type, 5, 1 >; /**< Automatic Trim machine Fail Flag */
using ATMS = regbits< type, 6, 1 >; /**< Automatic Trim Machine Select */
using ATME = regbits< type, 7, 1 >; /**< Automatic Trim Machine Enable */
};
/**
* MCG Auto Trim Compare Value High Register
*/
struct ATCVH
: public reg< uint8_t, base_addr + 0xa, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0xa, rw, 0 >;
// fixme: Field name equals parent register name: ATCVH
using ATCVH_ = regbits< type, 0, 8 >; /**< ATM Compare Value High */
};
/**
* MCG Auto Trim Compare Value Low Register
*/
struct ATCVL
: public reg< uint8_t, base_addr + 0xb, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0xb, rw, 0 >;
// fixme: Field name equals parent register name: ATCVL
using ATCVL_ = regbits< type, 0, 8 >; /**< ATM Compare Value Low */
};
/**
* MCG Control 7 Register
*/
struct C7
: public reg< uint8_t, base_addr + 0xc, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0xc, rw, 0 >;
using OSCSEL = regbits< type, 0, 1 >; /**< MCG OSC Clock Select */
};
/**
* MCG Control 8 Register
*/
struct C8
: public reg< uint8_t, base_addr + 0xd, rw, 0x80 >
{
using type = reg< uint8_t, base_addr + 0xd, rw, 0x80 >;
using LOCS1 = regbits< type, 0, 1 >; /**< RTC Loss of Clock Status */
using CME1 = regbits< type, 5, 1 >; /**< Clock Monitor Enable1 */
using LOCRE1 = regbits< type, 7, 1 >; /**< Loss of Clock Reset Enable */
};
/**
* MCG Control 10 Register
*/
struct C10
: public reg< uint8_t, base_addr + 0xf, rw, 0x80 >
{
using type = reg< uint8_t, base_addr + 0xf, rw, 0x80 >;
using EREFS1 = regbits< type, 2, 1 >; /**< External Reference Select */
using HGO1 = regbits< type, 3, 1 >; /**< High Gain Oscillator1 Select */
using RANGE1 = regbits< type, 4, 2 >; /**< Frequency Range1 Select */
using LOCRE2 = regbits< type, 7, 1 >; /**< OSC1 Loss of Clock Reset Enable */
};
/**
* MCG Control 11 Register
*/
struct C11
: public reg< uint8_t, base_addr + 0x10, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x10, rw, 0 >;
using PRDIV1 = regbits< type, 0, 3 >; /**< PLL1 External Reference Divider */
using PLLCS = regbits< type, 4, 1 >; /**< PLL Clock Select */
using PLLSTEN1 = regbits< type, 5, 1 >; /**< PLL1 Stop Enable */
using PLLCLKEN1 = regbits< type, 6, 1 >; /**< PLL1 Clock Enable */
using PLLREFSEL1 = regbits< type, 7, 1 >; /**< PLL1 External Reference Select */
};
/**
* MCG Control 12 Register
*/
struct C12
: public reg< uint8_t, base_addr + 0x11, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x11, rw, 0 >;
using VDIV1 = regbits< type, 0, 5 >; /**< VCO1 Divider */
using CME2 = regbits< type, 5, 1 >; /**< Clock Monitor Enable2 */
using LOLIE1 = regbits< type, 7, 1 >; /**< PLL1 Loss of Lock Interrupt Enable */
};
/**
* MCG Status 2 Register
*/
struct S2
: public reg< uint8_t, base_addr + 0x12, rw, 0 >
{
using type = reg< uint8_t, base_addr + 0x12, rw, 0 >;
using LOCS2 = regbits< type, 0, 1 >; /**< OSC1 Loss of Clock Status */
using OSCINIT1 = regbits< type, 1, 1 >; /**< OSC1 Initialization */
using PLLCST = regbits< type, 4, 1 >; /**< PLL Clock Select Status */
using LOCK1 = regbits< type, 6, 1 >; /**< Lock1 Status */
using LOLS1 = regbits< type, 7, 1 >; /**< Loss of Lock2 Status */
};
};
} // namespace mptl
#endif // ARCH_REG_MCG_HPP_INCLUDED
| [
"axel@tty0.ch"
] | axel@tty0.ch |
87103a9d2d162d21c05ad2bf383fde71ff1f958d | 5396e20b5eee35bf19de2fd54fd2d1817963defb | /IllusionEngine/src/ResourceManagement/ResourceManager.cpp | 9a73ea86ffa288a16774e0683a94eb359436cf28 | [] | no_license | Mesiow/Illusion-Engine | de302ff1d611a1551caf4773c4602617af4a980e | 0d48de78ef65e162cdd146936628d726b2856b29 | refs/heads/master | 2020-04-23T23:38:55.518978 | 2019-04-05T19:41:30 | 2019-04-05T19:41:30 | 171,542,901 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 383 | cpp | #include "../pcHeaders.h"
#include "ResourceManager.h"
namespace Illusion
{
////
std::unordered_map<std::string, sf::Texture> ResourceManager::textures;
std::unordered_map<std::string, sf::Font> ResourceManager::fonts;
std::unordered_map<std::string, sf::SoundBuffer> ResourceManager::sounds;
////
std::unordered_map<std::string, std::string> ResourceManager::texturePaths;
} | [
"34993144+Mesiow@users.noreply.github.com"
] | 34993144+Mesiow@users.noreply.github.com |
545831aef0a36dbe18bb828d10c21cca9cd44449 | f26ac91ea049d25c4b716455899aa79fff89a991 | /CODES/UPSOLVING/2/Pruebas Individuales UCLV - Graphs/d.cpp | c9c7a63f480c87c667bff9716decdc246e0bf57b | [] | no_license | Saborit/CODING | 3490f8eae1b2ed9b39932eaad5422ce649e26b4d | 07c1e345f846f8f2d70d977f73838ee82187b329 | refs/heads/master | 2020-12-27T20:31:50.622995 | 2020-02-19T21:10:27 | 2020-02-19T21:10:27 | 238,040,809 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,624 | cpp | /* Code by Saborit */
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define MX 405
#define INF (1<<30)
#define EPS 1e-9
#define MOD 1000000007
#define mid (x+xend)/2
#define izq nod*2
#define der nod*2+1
#define fr first
#define sc second
#define pb push_back
#define all(X) (X).begin(), (X).end()
#define unique(X) (X).resize(unique(all(X)) - (X).begin())
using namespace std;
using namespace __gnu_pbds;
typedef long long int64;
typedef unsigned long long unt64;
struct par{
int nwn, cost;
bool operator < (const par &p)const{
return cost > p.cost;
}
};
int cn, ca;
int dist[MX][MX], T[MX][MX];
bool mk[MX];
vector<par> G[MX];
priority_queue<par> Q;
void dijkstra(int ni){
for(Q.push({ni, 0}); !Q.empty(); Q.pop()){
int nod = Q.top().nwn;
for(auto i: G[nod]){
if( dist[ni][i.nwn] > dist[ni][nod] + i.cost ){
dist[ni][i.nwn] = dist[ni][nod] + i.cost;
Q.push({i.nwn, dist[ni][i.nwn]});
}
}
}
}
int main(void){
//~ freopen("a.in", "r", stdin);
//~ freopen("a.out", "w", stdout);
scanf("%d%d", &cn, &ca);
for(int i=1, a, b, c; i<=ca; i++){
scanf("%d%d%d", &a, &b, &c);
T[a][b] = c;
}
for(int i=1; i<=cn; i++){
for(int j=1; j<=cn; j++){
if( T[i][j] > 0 )
G[i].pb({j, T[i][j]});
dist[i][j] = INF;
}
dist[i][i] = 0;
}
for(int ni=1; ni<=cn; ni++)
dijkstra(ni);
int Q, a, b;
scanf("%d", &Q);
while( Q-- ){
scanf("%d%d", &a, &b);
printf(dist[a][b] < INF ? "%d\n" : "-1\n", dist[a][b]);
}
return 0;
}
| [
"lsaborit@uclv.cu"
] | lsaborit@uclv.cu |
7c030b4089cbd24d2fa83f411de5549f42f08865 | e1fbc8e53b950097f521278b53b5b00a4f5d62db | /logsetuplib/main.cpp | 6448be6fc69f690ea42bfa193674104e7e3807e6 | [
"MIT"
] | permissive | pgorsira/nheqminer | e9ac5ef4b6a06ddf465b29d06c25d2e3544bf87e | 45660cd104c1aab8593bba71072840cc38d0c76c | refs/heads/master | 2021-05-03T21:35:16.087426 | 2016-10-20T20:44:07 | 2016-10-20T20:44:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,025 | cpp | #include <iostream>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
namespace logging = boost::log;
namespace keywords = boost::log::keywords;
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace aux {
template< typename CharT, typename ArgsT >
shared_ptr<
sinks::synchronous_sink<
sinks::basic_text_ostream_backend< CharT >
>
> add_console_log2(boost::log::core_ptr cptr, std::basic_ostream< CharT >& strm, ArgsT const& args)
{
shared_ptr< std::basic_ostream< CharT > > pStream(&strm, boost::null_deleter());
typedef sinks::basic_text_ostream_backend< CharT > backend_t;
shared_ptr< backend_t > pBackend = boost::make_shared< backend_t >();
pBackend->add_stream(pStream);
pBackend->auto_flush(args[keywords::auto_flush | false]);
typedef sinks::synchronous_sink< backend_t > sink_t;
shared_ptr< sink_t > pSink = boost::make_shared< sink_t >(pBackend);
aux::setup_filter(*pSink, args,
typename is_void< typename parameter::binding< ArgsT, keywords::tag::filter, void >::type >::type());
aux::setup_formatter(*pSink, args,
typename is_void< typename parameter::binding< ArgsT, keywords::tag::format, void >::type >::type());
cptr->add_sink(pSink);
return pSink;
}
}
BOOST_LOG_CLOSE_NAMESPACE
}
#ifndef _DEBUG
__declspec(dllexport)
#endif
void init_logging(boost::log::core_ptr cptr, int level)
{
std::cout << "Setting log level to " << level << std::endl;
cptr->set_filter
(
logging::trivial::severity >= level
);
logging::aux::add_console_log2
(
cptr,
std::clog,
keywords::format = "[%TimeStamp%][%ThreadID%]: %Message%"
);
cptr->add_global_attribute("TimeStamp", boost::log::attributes::local_clock());
cptr->add_global_attribute("ThreadID", boost::log::attributes::current_thread_id());
} | [
"krsticch@gmail.com"
] | krsticch@gmail.com |
59bc1313586c06f080a3af4380d66f6c189ee588 | 17dbbbdc6bd3fe56a466d97f674b735720da60a5 | /android_webview/browser/gfx/aw_draw_fn_impl.cc | 0f950696e45c48be7cbfdc3171606732379e36b0 | [
"BSD-3-Clause"
] | permissive | aileolin1981/chromium | 3df50a9833967cf68e9809017deb9f0c79722687 | 876a076ba4c2fac9d01814e21e6b5bcb7ec78ad3 | refs/heads/master | 2022-12-21T09:32:02.120314 | 2019-03-21T02:41:19 | 2019-03-21T02:41:19 | 173,888,576 | 0 | 1 | null | 2019-03-05T06:31:00 | 2019-03-05T06:31:00 | null | UTF-8 | C++ | false | false | 26,999 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/browser/gfx/aw_draw_fn_impl.h"
#include <utility>
#include "android_webview/browser/gfx/aw_vulkan_context_provider.h"
#include "android_webview/common/aw_switches.h"
#include "android_webview/public/browser/draw_gl.h"
#include "base/android/android_hardware_buffer_compat.h"
#include "base/android/scoped_hardware_buffer_fence_sync.h"
#include "base/task/post_task.h"
#include "base/trace_event/trace_event.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "gpu/ipc/common/android/android_image_reader_utils.h"
#include "gpu/vulkan/vulkan_function_pointers.h"
#include "gpu/vulkan/vulkan_implementation.h"
#include "jni/AwDrawFnImpl_jni.h"
#include "third_party/skia/include/gpu/GrBackendSemaphore.h"
#include "third_party/skia/include/gpu/GrContext.h"
#include "third_party/skia/include/gpu/vk/GrVkBackendContext.h"
#include "third_party/skia/include/gpu/vk/GrVkExtensions.h"
#include "third_party/skia/src/gpu/vk/GrVkSecondaryCBDrawContext.h"
#include "ui/gfx/color_space.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context_egl.h"
#include "ui/gl/gl_image_ahardwarebuffer.h"
#include "ui/gl/gl_surface_egl.h"
#include "ui/gl/init/gl_factory.h"
using base::android::JavaParamRef;
using content::BrowserThread;
namespace android_webview {
namespace {
GLNonOwnedCompatibilityContext* g_gl_context = nullptr;
}
class GLNonOwnedCompatibilityContext : public gl::GLContextEGL {
public:
GLNonOwnedCompatibilityContext()
: gl::GLContextEGL(nullptr),
surface_(
base::MakeRefCounted<gl::PbufferGLSurfaceEGL>(gfx::Size(1, 1))) {
gl::GLContextAttribs attribs;
Initialize(surface_.get(), attribs);
DCHECK(!g_gl_context);
g_gl_context = this;
}
bool MakeCurrent(gl::GLSurface* surface) override {
// A GLNonOwnedCompatibilityContext may have set the GetRealCurrent()
// pointer to itself, while re-using our EGL context. In these cases just
// call SetCurrent to restore expected GetRealContext().
if (GetHandle() == eglGetCurrentContext()) {
if (surface) {
// No one should change the current EGL surface without also changing
// the context.
DCHECK(eglGetCurrentSurface(EGL_DRAW) == surface->GetHandle());
}
SetCurrent(surface);
return true;
}
return gl::GLContextEGL::MakeCurrent(surface);
}
bool MakeCurrent() { return MakeCurrent(surface_.get()); }
static scoped_refptr<GLNonOwnedCompatibilityContext> GetOrCreateInstance() {
if (g_gl_context)
return base::WrapRefCounted(g_gl_context);
return base::WrapRefCounted(new GLNonOwnedCompatibilityContext);
}
private:
~GLNonOwnedCompatibilityContext() override {
DCHECK_EQ(g_gl_context, this);
g_gl_context = nullptr;
}
scoped_refptr<gl::GLSurface> surface_;
DISALLOW_COPY_AND_ASSIGN(GLNonOwnedCompatibilityContext);
};
namespace {
AwDrawFnFunctionTable* g_draw_fn_function_table = nullptr;
void OnSyncWrapper(int functor, void* data, AwDrawFn_OnSyncParams* params) {
TRACE_EVENT1("android_webview,toplevel", "DrawFn_OnSync", "functor", functor);
CHECK_EQ(static_cast<AwDrawFnImpl*>(data)->functor_handle(), functor);
static_cast<AwDrawFnImpl*>(data)->OnSync(params);
}
void OnContextDestroyedWrapper(int functor, void* data) {
TRACE_EVENT1("android_webview,toplevel", "DrawFn_OnContextDestroyed",
"functor", functor);
CHECK_EQ(static_cast<AwDrawFnImpl*>(data)->functor_handle(), functor);
static_cast<AwDrawFnImpl*>(data)->OnContextDestroyed();
}
void OnDestroyedWrapper(int functor, void* data) {
TRACE_EVENT1("android_webview,toplevel", "DrawFn_OnDestroyed", "functor",
functor);
CHECK_EQ(static_cast<AwDrawFnImpl*>(data)->functor_handle(), functor);
delete static_cast<AwDrawFnImpl*>(data);
}
void DrawGLWrapper(int functor, void* data, AwDrawFn_DrawGLParams* params) {
TRACE_EVENT1("android_webview,toplevel", "DrawFn_DrawGL", "functor", functor);
CHECK_EQ(static_cast<AwDrawFnImpl*>(data)->functor_handle(), functor);
static_cast<AwDrawFnImpl*>(data)->DrawGL(params);
}
void InitVkWrapper(int functor, void* data, AwDrawFn_InitVkParams* params) {
TRACE_EVENT1("android_webview,toplevel", "DrawFn_InitVk", "functor", functor);
CHECK_EQ(static_cast<AwDrawFnImpl*>(data)->functor_handle(), functor);
static_cast<AwDrawFnImpl*>(data)->InitVk(params);
}
void DrawVkWrapper(int functor, void* data, AwDrawFn_DrawVkParams* params) {
TRACE_EVENT1("android_webview,toplevel", "DrawFn_DrawVk", "functor", functor);
CHECK_EQ(static_cast<AwDrawFnImpl*>(data)->functor_handle(), functor);
static_cast<AwDrawFnImpl*>(data)->DrawVk(params);
}
void PostDrawVkWrapper(int functor,
void* data,
AwDrawFn_PostDrawVkParams* params) {
TRACE_EVENT1("android_webview,toplevel", "DrawFn_PostDrawVk", "functor",
functor);
CHECK_EQ(static_cast<AwDrawFnImpl*>(data)->functor_handle(), functor);
static_cast<AwDrawFnImpl*>(data)->PostDrawVk(params);
}
sk_sp<GrVkSecondaryCBDrawContext> CreateDrawContext(
GrContext* gr_context,
AwDrawFn_DrawVkParams* params,
sk_sp<SkColorSpace> color_space) {
// Create a GrVkSecondaryCBDrawContext to render our AHB w/ Vulkan.
// TODO(ericrk): Handle non-RGBA.
SkImageInfo info =
SkImageInfo::MakeN32Premul(params->width, params->height, color_space);
VkRect2D draw_bounds;
GrVkDrawableInfo drawable_info{
.fSecondaryCommandBuffer = params->secondary_command_buffer,
.fColorAttachmentIndex = params->color_attachment_index,
.fCompatibleRenderPass = params->compatible_render_pass,
.fFormat = params->format,
.fDrawBounds = &draw_bounds,
};
SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
return GrVkSecondaryCBDrawContext::Make(gr_context, info, drawable_info,
&props);
}
template <typename T>
sk_sp<SkColorSpace> CreateColorSpace(T* params) {
skcms_TransferFunction transfer_fn{
params->transfer_function_g, params->transfer_function_a,
params->transfer_function_b, params->transfer_function_c,
params->transfer_function_d, params->transfer_function_e,
params->transfer_function_f};
skcms_Matrix3x3 to_xyz;
static_assert(sizeof(to_xyz.vals) == sizeof(params->color_space_toXYZD50),
"Color space matrix sizes do not match");
memcpy(&to_xyz.vals[0][0], ¶ms->color_space_toXYZD50[0],
sizeof(to_xyz.vals));
return SkColorSpace::MakeRGB(transfer_fn, to_xyz);
}
// Create a VkFence and submit it to the queue.
VkFence CreateAndSubmitFence(VkDevice device, VkQueue queue) {
VkFence fence = VK_NULL_HANDLE;
VkFenceCreateInfo create_info{
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
};
auto result =
vkCreateFence(device, &create_info, nullptr /* pAllocator */, &fence);
if (result != VK_SUCCESS) {
LOG(ERROR) << "Could not create VkFence.";
return VK_NULL_HANDLE;
}
result =
vkQueueSubmit(queue, 0 /* submitCount */, nullptr /* pSubmits */, fence);
if (result != VK_SUCCESS) {
LOG(ERROR) << "Could not create VkFence.";
vkDestroyFence(device, fence, nullptr /* pAllocator */);
return VK_NULL_HANDLE;
}
return fence;
}
} // namespace
static void JNI_AwDrawFnImpl_SetDrawFnFunctionTable(JNIEnv* env,
jlong function_table) {
g_draw_fn_function_table =
reinterpret_cast<AwDrawFnFunctionTable*>(function_table);
}
AwDrawFnImpl::AwDrawFnImpl()
: is_interop_mode_(!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kWebViewEnableVulkan)),
render_thread_manager_(
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI})) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(g_draw_fn_function_table);
static AwDrawFnFunctorCallbacks g_functor_callbacks{
&OnSyncWrapper, &OnContextDestroyedWrapper,
&OnDestroyedWrapper, &DrawGLWrapper,
&InitVkWrapper, &DrawVkWrapper,
&PostDrawVkWrapper,
};
functor_handle_ =
g_draw_fn_function_table->create_functor(this, &g_functor_callbacks);
}
AwDrawFnImpl::~AwDrawFnImpl() {}
void AwDrawFnImpl::ReleaseHandle(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj) {
render_thread_manager_.RemoveFromCompositorFrameProducerOnUI();
g_draw_fn_function_table->release_functor(functor_handle_);
}
jint AwDrawFnImpl::GetFunctorHandle(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return functor_handle_;
}
jlong AwDrawFnImpl::GetCompositorFrameConsumer(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return reinterpret_cast<intptr_t>(GetCompositorFrameConsumer());
}
static jlong JNI_AwDrawFnImpl_Create(JNIEnv* env) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return reinterpret_cast<intptr_t>(new AwDrawFnImpl());
}
void AwDrawFnImpl::OnSync(AwDrawFn_OnSyncParams* params) {
render_thread_manager_.UpdateViewTreeForceDarkStateOnRT(
params->apply_force_dark);
render_thread_manager_.CommitFrameOnRT();
}
void AwDrawFnImpl::OnContextDestroyed() {
// Try to make GL current to safely clean up. Ignore failures.
if (gl_context_)
gl_context_->MakeCurrent();
{
RenderThreadManager::InsideHardwareReleaseReset release_reset(
&render_thread_manager_);
render_thread_manager_.DestroyHardwareRendererOnRT(
false /* save_restore */);
}
if (!in_flight_draws_.empty()) {
DCHECK(!is_interop_mode_);
// Make sure the last pending draw is finished, and then we can destroy all
// pending draws safely.
VkFence last_fence = in_flight_draws_.back().fence;
VkDevice device =
vulkan_context_provider_->GetDeviceQueue()->GetVulkanDevice();
VkResult result =
vkWaitForFences(device, 1, &last_fence, VK_TRUE,
base::TimeDelta::FromSeconds(60).InNanoseconds());
DCHECK_EQ(result, VK_SUCCESS);
while (!in_flight_draws_.empty()) {
auto& draw = in_flight_draws_.front();
vkDestroyFence(device, draw.fence, nullptr /* pAllocator */);
draw.draw_context->releaseResources();
draw.draw_context = nullptr;
in_flight_draws_.pop();
}
}
while (!in_flight_interop_draws_.empty()) {
DCHECK(is_interop_mode_);
// Let returned InFlightInteropDraw go out of scope.
TakeInFlightInteropDrawForReUse();
}
vulkan_context_provider_.reset();
gl_context_.reset();
}
void AwDrawFnImpl::DrawGL(AwDrawFn_DrawGLParams* params) {
auto color_space = params->version >= 2 ? CreateColorSpace(params) : nullptr;
DrawInternal(params, color_space.get());
}
void AwDrawFnImpl::InitVk(AwDrawFn_InitVkParams* params) {
// We should never have a |vulkan_context_provider_| if we are calling VkInit.
// This means context destroyed was not correctly called.
DCHECK(!vulkan_context_provider_);
vulkan_context_provider_ =
AwVulkanContextProvider::GetOrCreateInstance(params);
// Make sure we have a GL context.
DCHECK(!gl_context_);
gl_context_ = GLNonOwnedCompatibilityContext::GetOrCreateInstance();
}
void AwDrawFnImpl::DrawVk(AwDrawFn_DrawVkParams* params) {
if (is_interop_mode_) {
DrawVkInterop(params);
} else {
DrawVkDirect(params);
}
}
void AwDrawFnImpl::PostDrawVk(AwDrawFn_PostDrawVkParams* params) {
if (is_interop_mode_) {
PostDrawVkInterop(params);
} else {
PostDrawVkDirect(params);
}
}
void AwDrawFnImpl::DrawVkDirect(AwDrawFn_DrawVkParams* params) {
if (!vulkan_context_provider_)
return;
DCHECK(!draw_context_);
auto color_space = CreateColorSpace(params);
if (!color_space) {
// If we weren't passed a valid colorspace, default to sRGB.
LOG(ERROR) << "Received invalid colorspace.";
color_space = SkColorSpace::MakeSRGB();
}
draw_context_ = CreateDrawContext(vulkan_context_provider_->gr_context(),
params, color_space);
// Set the draw contexct in |vulkan_context_provider_|, so the SkiaRenderer
// and SkiaOutputSurface* will use it as frame render target.
AwVulkanContextProvider::ScopedDrawContext scoped_draw_context(
vulkan_context_provider_.get(), draw_context_.get());
DrawInternal(params, color_space.get());
}
void AwDrawFnImpl::PostDrawVkDirect(AwDrawFn_PostDrawVkParams* params) {
if (!vulkan_context_provider_)
return;
DCHECK(draw_context_);
VkDevice device =
vulkan_context_provider_->GetDeviceQueue()->GetVulkanDevice();
VkQueue queue = vulkan_context_provider_->GetDeviceQueue()->GetVulkanQueue();
VkFence fence = CreateAndSubmitFence(device, queue);
DCHECK(fence != VK_NULL_HANDLE);
in_flight_draws_.emplace(fence, std::move(draw_context_));
// Cleanup completed draws.
while (!in_flight_draws_.empty()) {
auto& draw = in_flight_draws_.front();
VkResult result = vkGetFenceStatus(device, draw.fence);
if (result == VK_NOT_READY)
break;
if (result == VK_SUCCESS) {
vkDestroyFence(device, draw.fence, nullptr /* pAllocator */);
draw.draw_context->releaseResources();
draw.draw_context = nullptr;
in_flight_draws_.pop();
continue;
}
// Handle context lost.
NOTREACHED();
}
DCHECK_LE(in_flight_draws_.size(), 2u);
}
void AwDrawFnImpl::DrawVkInterop(AwDrawFn_DrawVkParams* params) {
if (!vulkan_context_provider_ || !gl_context_)
return;
if (!gl_context_->MakeCurrent()) {
LOG(ERROR) << "Failed to make GL context current for drawing.";
return;
}
// If |pending_draw_| is non-null, we called DrawVk twice without PostDrawVk.
DCHECK(!pending_draw_);
// If we've exhausted our buffers, re-use an existing one.
// TODO(ericrk): Benchmark using more than 1 buffer.
if (in_flight_interop_draws_.size() >= 1 /* single buffering */) {
pending_draw_ = TakeInFlightInteropDrawForReUse();
}
// If prev buffer is wrong size, just re-allocate.
if (pending_draw_ && pending_draw_->ahb_image->GetSize() !=
gfx::Size(params->width, params->height)) {
pending_draw_ = nullptr;
}
// If we weren't able to re-use a previous draw, create one.
if (!pending_draw_) {
pending_draw_ =
std::make_unique<InFlightInteropDraw>(vulkan_context_provider_.get());
AHardwareBuffer_Desc desc = {};
desc.width = params->width;
desc.height = params->height;
desc.layers = 1; // number of images
// TODO(ericrk): Handle other formats.
desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
desc.usage = AHARDWAREBUFFER_USAGE_CPU_READ_NEVER |
AHARDWAREBUFFER_USAGE_CPU_WRITE_NEVER |
AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT;
AHardwareBuffer* buffer = nullptr;
base::AndroidHardwareBufferCompat::GetInstance().Allocate(&desc, &buffer);
if (!buffer) {
LOG(ERROR) << "Failed to allocate AHardwareBuffer for WebView rendering.";
return;
}
auto scoped_buffer =
base::android::ScopedHardwareBufferHandle::Adopt(buffer);
pending_draw_->ahb_image = base::MakeRefCounted<gl::GLImageAHardwareBuffer>(
gfx::Size(params->width, params->height));
if (!pending_draw_->ahb_image->Initialize(scoped_buffer.get(),
false /* preserved */)) {
LOG(ERROR) << "Failed to initialize GLImage for AHardwareBuffer.";
return;
}
glGenTextures(1, static_cast<GLuint*>(&pending_draw_->texture_id));
GLenum target = GL_TEXTURE_2D;
glBindTexture(target, pending_draw_->texture_id);
if (!pending_draw_->ahb_image->BindTexImage(target)) {
LOG(ERROR) << "Failed to bind GLImage for AHardwareBuffer.";
return;
}
glBindTexture(target, 0);
glGenFramebuffersEXT(1, &pending_draw_->framebuffer_id);
glBindFramebufferEXT(GL_FRAMEBUFFER, pending_draw_->framebuffer_id);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, pending_draw_->texture_id, 0);
if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER) !=
GL_FRAMEBUFFER_COMPLETE) {
LOG(ERROR) << "Failed to set up framebuffer for WebView GL drawing.";
return;
}
}
// Ask GL to wait on any Vk sync_fd before writing.
gpu::InsertEglFenceAndWait(std::move(pending_draw_->sync_fd));
auto color_space = CreateColorSpace(params);
if (!color_space) {
// If we weren't passed a valid colorspace, default to sRGB.
LOG(ERROR) << "Received invalid colorspace.";
color_space = SkColorSpace::MakeSRGB();
}
// Bind buffer and render with GL.
base::ScopedFD gl_done_fd;
{
glBindFramebufferEXT(GL_FRAMEBUFFER, pending_draw_->framebuffer_id);
glViewport(0, 0, params->width, params->height);
glDisable(GL_STENCIL_TEST);
glDisable(GL_SCISSOR_TEST);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
DrawInternal(params, color_space.get());
gl_done_fd = gpu::CreateEglFenceAndExportFd();
}
pending_draw_->draw_context = CreateDrawContext(
vulkan_context_provider_->gr_context(), params, color_space);
// If we have a |gl_done_fd|, create a Skia GrBackendSemaphore from
// |gl_done_fd| and wait.
if (gl_done_fd.is_valid()) {
VkSemaphore gl_done_semaphore;
if (!vulkan_context_provider_->implementation()->ImportSemaphoreFdKHR(
vulkan_context_provider_->device(), std::move(gl_done_fd),
&gl_done_semaphore)) {
LOG(ERROR) << "Could not create Vulkan semaphore for GL completion.";
return;
}
GrBackendSemaphore gr_semaphore;
gr_semaphore.initVulkan(gl_done_semaphore);
if (!pending_draw_->draw_context->wait(1, &gr_semaphore)) {
// If wait returns false, we must clean up the |gl_done_semaphore|.
vkDestroySemaphore(vulkan_context_provider_->device(), gl_done_semaphore,
nullptr);
LOG(ERROR) << "Could not wait on GL completion semaphore.";
return;
}
}
// Create a VkImage and import AHB.
if (!pending_draw_->image_info.fImage) {
VkImage vk_image;
VkImageCreateInfo vk_image_info;
VkDeviceMemory vk_device_memory;
VkDeviceSize mem_allocation_size;
if (!vulkan_context_provider_->implementation()->CreateVkImageAndImportAHB(
vulkan_context_provider_->device(),
vulkan_context_provider_->physical_device(),
gfx::Size(params->width, params->height),
base::android::ScopedHardwareBufferHandle::Create(
pending_draw_->ahb_image->GetAHardwareBuffer()->buffer()),
&vk_image, &vk_image_info, &vk_device_memory,
&mem_allocation_size)) {
LOG(ERROR) << "Could not create VkImage from AHB.";
return;
}
// Create backend texture from the VkImage.
GrVkAlloc alloc = {vk_device_memory, 0, mem_allocation_size, 0};
pending_draw_->image_info = {vk_image,
alloc,
vk_image_info.tiling,
vk_image_info.initialLayout,
vk_image_info.format,
vk_image_info.mipLevels};
}
// Create an SkImage from AHB.
GrBackendTexture backend_texture(params->width, params->height,
pending_draw_->image_info);
pending_draw_->ahb_skimage = SkImage::MakeFromTexture(
vulkan_context_provider_->gr_context(), backend_texture,
kBottomLeft_GrSurfaceOrigin, kRGBA_8888_SkColorType, kPremul_SkAlphaType,
color_space);
if (!pending_draw_->ahb_skimage) {
LOG(ERROR) << "Could not create SkImage from VkImage.";
return;
}
// Draw the SkImage.
SkPaint paint;
paint.setBlendMode(SkBlendMode::kSrcOver);
pending_draw_->draw_context->getCanvas()->drawImage(
pending_draw_->ahb_skimage, 0, 0, &paint);
pending_draw_->draw_context->flush();
}
void AwDrawFnImpl::PostDrawVkInterop(AwDrawFn_PostDrawVkParams* params) {
if (!vulkan_context_provider_ || !gl_context_)
return;
// Release the SkImage so that Skia transitions it back to EXTERNAL.
pending_draw_->ahb_skimage.reset();
// Create a semaphore to track the image's transition back to external.
VkExportSemaphoreCreateInfo export_info;
export_info.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO;
export_info.pNext = nullptr;
export_info.handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
VkSemaphoreCreateInfo sem_info;
sem_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
sem_info.pNext = &export_info;
sem_info.flags = 0;
VkResult result =
vkCreateSemaphore(vulkan_context_provider_->device(), &sem_info, nullptr,
&pending_draw_->post_draw_semaphore);
if (result != VK_SUCCESS) {
LOG(ERROR) << "Could not create VkSemaphore.";
return;
}
GrBackendSemaphore gr_post_draw_semaphore;
gr_post_draw_semaphore.initVulkan(pending_draw_->post_draw_semaphore);
// Flush so that we know the image's transition has been submitted and that
// the |post_draw_semaphore| is pending.
GrSemaphoresSubmitted submitted =
vulkan_context_provider_->gr_context()->flushAndSignalSemaphores(
1, &gr_post_draw_semaphore);
if (submitted != GrSemaphoresSubmitted::kYes) {
LOG(ERROR) << "Skia could not submit GrSemaphore.";
return;
}
if (!vulkan_context_provider_->implementation()->GetSemaphoreFdKHR(
vulkan_context_provider_->device(),
pending_draw_->post_draw_semaphore, &pending_draw_->sync_fd)) {
LOG(ERROR) << "Could not retrieve SyncFD from |post_draw_semaphore|.";
return;
}
DCHECK(VK_NULL_HANDLE == pending_draw_->post_draw_fence);
VkDevice device =
vulkan_context_provider_->GetDeviceQueue()->GetVulkanDevice();
VkQueue queue = vulkan_context_provider_->GetDeviceQueue()->GetVulkanQueue();
VkFence fence = CreateAndSubmitFence(device, queue);
if (fence != VK_NULL_HANDLE) {
pending_draw_->post_draw_fence = fence;
// Add the |pending_draw_| to |in_flight_interop_draws_|.
in_flight_interop_draws_.push(std::move(pending_draw_));
} else {
pending_draw_ = nullptr;
}
}
template <typename T>
void AwDrawFnImpl::DrawInternal(T* params, SkColorSpace* color_space) {
struct HardwareRendererDrawParams hr_params {};
hr_params.clip_left = params->clip_left;
hr_params.clip_top = params->clip_top;
hr_params.clip_right = params->clip_right;
hr_params.clip_bottom = params->clip_bottom;
hr_params.width = params->width;
hr_params.height = params->height;
hr_params.is_layer = params->is_layer;
if (color_space)
hr_params.color_space = gfx::ColorSpace(*color_space);
static_assert(base::size(decltype(params->transform){}) ==
base::size(hr_params.transform),
"transform size mismatch");
for (size_t i = 0; i < base::size(hr_params.transform); ++i) {
hr_params.transform[i] = params->transform[i];
}
render_thread_manager_.DrawOnRT(false /* save_restore */, &hr_params);
}
std::unique_ptr<AwDrawFnImpl::InFlightInteropDraw>
AwDrawFnImpl::TakeInFlightInteropDrawForReUse() {
DCHECK(vulkan_context_provider_);
DCHECK(!in_flight_interop_draws_.empty());
std::unique_ptr<InFlightInteropDraw>& draw = in_flight_interop_draws_.front();
// Wait for our draw's |post_draw_fence| to pass.
DCHECK(draw->post_draw_fence != VK_NULL_HANDLE);
VkResult wait_result = vkWaitForFences(
vulkan_context_provider_->device(), 1, &draw->post_draw_fence, VK_TRUE,
base::TimeDelta::FromSeconds(60).InNanoseconds());
if (wait_result != VK_SUCCESS) {
LOG(ERROR) << "Fence did not pass in the expected timeframe.";
return nullptr;
}
draw->draw_context->releaseResources();
draw->draw_context.reset();
vkDestroyFence(vulkan_context_provider_->device(), draw->post_draw_fence,
nullptr);
draw->post_draw_fence = VK_NULL_HANDLE;
vkDestroySemaphore(vulkan_context_provider_->device(),
draw->post_draw_semaphore, nullptr);
draw->post_draw_semaphore = VK_NULL_HANDLE;
std::unique_ptr<InFlightInteropDraw> draw_to_return = std::move(draw);
in_flight_interop_draws_.pop();
return draw_to_return;
}
AwDrawFnImpl::InFlightDraw::InFlightDraw(
VkFence fence,
sk_sp<GrVkSecondaryCBDrawContext> draw_context)
: fence(fence), draw_context(std::move(draw_context)) {}
AwDrawFnImpl::InFlightDraw::InFlightDraw(InFlightDraw&& other) = default;
AwDrawFnImpl::InFlightDraw::~InFlightDraw() = default;
AwDrawFnImpl::InFlightInteropDraw::InFlightInteropDraw(
AwVulkanContextProvider* vk_context_provider)
: vk_context_provider(vk_context_provider) {}
AwDrawFnImpl::InFlightInteropDraw::~InFlightInteropDraw() {
// If |draw_context| is valid, we encountered an error during Vk drawing and
// should call vkQueueWaitIdle to ensure safe shutdown.
bool encountered_error = !!draw_context;
if (encountered_error) {
// Clean up one-off objects which may have been left alive due to an error.
// Clean up |ahb_skimage| first, as doing so generates Vk commands we need
// to flush before the vkQueueWaitIdle below.
if (ahb_skimage) {
ahb_skimage.reset();
vk_context_provider->gr_context()->flush();
}
// We encountered an error and are not sure when our Vk objects are safe to
// delete. VkQueueWaitIdle to ensure safety.
vkQueueWaitIdle(vk_context_provider->queue());
if (draw_context) {
draw_context->releaseResources();
draw_context.reset();
}
if (post_draw_fence != VK_NULL_HANDLE) {
vkDestroyFence(vk_context_provider->device(), post_draw_fence, nullptr);
post_draw_fence = VK_NULL_HANDLE;
}
if (post_draw_semaphore != VK_NULL_HANDLE) {
vkDestroySemaphore(vk_context_provider->device(), post_draw_semaphore,
nullptr);
post_draw_semaphore = VK_NULL_HANDLE;
}
}
DCHECK(!draw_context);
DCHECK(!ahb_skimage);
DCHECK(post_draw_fence == VK_NULL_HANDLE);
DCHECK(post_draw_semaphore == VK_NULL_HANDLE);
// Clean up re-usable components that are expected to still be alive.
if (texture_id)
glDeleteTextures(1, &texture_id);
if (framebuffer_id)
glDeleteFramebuffersEXT(1, &framebuffer_id);
if (image_info.fImage != VK_NULL_HANDLE) {
vkDestroyImage(vk_context_provider->device(), image_info.fImage, nullptr);
vkFreeMemory(vk_context_provider->device(), image_info.fAlloc.fMemory,
nullptr);
}
}
} // namespace android_webview
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
35c6aeec148154f028830344ae820f92195dbf30 | 9b9d58d50fe12c2eaa697a1ecee581a5bd74654c | /src/graphDraw.cpp | f5eeea55035cb3ac835fe9821666e9a714c82b4f | [] | no_license | janosimas/graph_drawing | 1226539df059686596a8cb4aa6d6334dc49395e9 | 357b7f4f33c6cee98f8693cfdb0eff93c974b647 | refs/heads/master | 2021-08-30T23:46:10.692582 | 2017-11-28T17:25:57 | 2017-11-28T17:25:57 | 112,585,655 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,256 | cpp | #include "graphDraw.hpp"
#include <Magnum/DefaultFramebuffer.h>
#include <Magnum/Math/Vector3.h>
#include <Magnum/Platform/Sdl2Application.h>
GraphDraw::GraphDraw(const BaseGraph& graph) : _graph(graph){}
std::pair<float, float> GraphDraw::coordinates(const Node& node) {
auto diff = (2.*3.14)/_graph.nodes.size();
auto it = _nodeXY.find(node);
if(it == _nodeXY.end()) {
auto angle = (node.id()-1)*diff;
//nova coordenada
float newX = static_cast<float>(std::cos(angle)*0.9);
float newY = static_cast<float>(std::sin(angle)*0.9);
auto p = std::make_pair(newX,newY);
_nodeXY[node] = p;
return p;
} else {
return it->second;
}
}
void GraphDraw::draw() {
using namespace Magnum;
using namespace Math::Literals;
std::vector<Vertex> vNodes; vNodes.reserve(_graph.nodes.size());
std::vector<Vertex> vEdges; vEdges.reserve(_graph.edges.size()*2);
for(auto node = _graph.nodes.begin(); node != _graph.nodes.end(); ++node) {
auto xy = coordinates(*node);
vNodes.emplace_back(Vertex{{xy.first, xy.second}, 0xff0000_srgbf});
vEdges.emplace_back(Vertex{{xy.first, xy.second}, 0x000000_srgbf});
vEdges.emplace_back(Vertex{{0,0}, 0x000000_srgbf});
for(auto edge = node.begin(); edge != node.end(); ++edge) {
auto n1 = edge.left();
auto n2 = edge.right();
auto v1 = coordinates(*n1);
auto v2 = coordinates(*n2);
vEdges.emplace_back(Vertex{{v1.first, v1.second}, 0x000000_srgbf});
vEdges.emplace_back(Vertex{{v2.first, v2.second}, 0x000000_srgbf});
}
}
_buffer2.setData(vEdges, BufferUsage::StaticDraw);
_mesh2.setPrimitive(MeshPrimitive::Lines)
.setCount(static_cast<int>(vEdges.size()*2))
.addVertexBuffer(_buffer2, 0,
Shaders::VertexColor2D::Position{},
Shaders::VertexColor2D::Color{Shaders::VertexColor2D::Color::Components::Three});
_mesh2.draw(_shader2);
_buffer.setData(vNodes, BufferUsage::StaticDraw);
_mesh.setPrimitive(MeshPrimitive::Points)
.setCount(static_cast<int>(vNodes.size()))
.addVertexBuffer(_buffer, 0,
Shaders::VertexColor2D::Position{},
Shaders::VertexColor2D::Color{Shaders::VertexColor2D::Color::Components::Three});
_mesh.draw(_shader);
}
| [
"janosimas@gmail.com"
] | janosimas@gmail.com |
fb295cf031e56c435d9add7b6951adfec0da756d | 0132e5a2f893aab73bdb3197bfcd063ad807463e | /include/elikos_roomba/ArenaManager.h | 04e379dc9b50c1be0bf2a2bc3bc9ec19cdd0392c | [] | no_license | ganwy2017/elikos_roomba | 4d1a591bcdb61ff745b1e03475330223995d95f1 | bcdcd3bb02c02160f2b8314eb03356dcf1cacfa2 | refs/heads/master | 2020-03-21T19:46:38.609086 | 2018-03-11T02:38:38 | 2018-03-11T02:38:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,142 | h | #ifndef ARENA_MANAGER_H
#define ARENA_MANAGER_H
/**
* \file ArenaManager.h
* \brief NOT WORKING
* \author christophebedard
*/
#include "elikos_roomba/ServiceRedirect.h" // use topic names, service names, and other values
#include "elikos_roomba/robot_viz.h"
#include <tf/transform_listener.h>
class ArenaManager
{
public:
/*
* Constructor
* groundrobotQty: number of (ground) robots
*/
ArenaManager(ros::NodeHandle& n, int groundrobotQty, double arenaDimension);
~ArenaManager();
/*
* Wrapper for ROS_INFO_STREAM, includes node name
*/
void ROS_INFO_STREAM_ARENAMANAGER(std::string message);
/*
* Concatenate string and int (because other methods weren't working)
*/
std::string catStringInt(std::string strng, int eent);
/*
* Check if (x,y) coordinate is inside arena, assuming middle is (0,0)
*/
bool isInsideArena(double x, double y);
/*
* ROS spin. Called only once (by node); contains ROS while loop
*/
void spin();
protected:
ros::NodeHandle& n_;
double loop_hz_;
bool is_running_slowly_;
/* Ground robot quantity */
int groundrobotQty_;
/* Dimension of arena, assuming square and origin (0,0) being in the middle */
double arenaDimension_;
/*===========================
* Update
*===========================*/
/*
* Update; called every spinOnce()
*/
void update();
/*
* ROS spin once, called on every loop
*/
void spinOnce();
private:
tf::TransformListener tf_listener_;
bool new_isInsideArena_[];
bool old_isInsideArena_[];
/*===========================
* Services
*===========================*/
/* Ground robot bumper trigger service clients */
std::vector<ros::ServiceClient> grndbot_brumpertrigger_srv_clients_;
std_srvs::Empty srv_;
};
#endif // ELIKOS_ROOMBA_ARENA_MANAGER_H | [
"chrisvolkoff@gmail.com"
] | chrisvolkoff@gmail.com |
76bd5a81854d97aea891bc3c39b0c3ac69252fe4 | 80842a8223f9e97826916e98bdb75dddc8bed82b | /action/RemoveFloorBlockAction.h | 16d424578d213d03089186c54365f841772de41b | [] | no_license | TWVerstraaten/Blocks | 4cbd3f892f2b5202d2df30afe42c43b73e69a150 | 13268ab0c2e146a5d35d93c005b8b74c23872f3c | refs/heads/master | 2023-03-01T20:36:38.823087 | 2021-02-09T00:37:10 | 2021-02-09T00:37:10 | 321,815,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 599 | h | //
// Created by teunv on 1/19/2021.
//
#ifndef BLOCKS_REMOVEFLOORBLOCKACTION_H
#define BLOCKS_REMOVEFLOORBLOCKACTION_H
#include "AddFloorBlockAction.h"
namespace action {
class RemoveFloorBlockAction : public AddFloorBlockAction {
public:
RemoveFloorBlockAction(model::Level* level, model::FLOOR_BLOCK_TYPE type, const model::GridXy& gridXy);
void undo() override;
void redo() override;
[[nodiscard]] ACTION_TYPE type() const override;
};
} // namespace action
#endif // BLOCKS_REMOVEFLOORBLOCKACTION_H
| [
"t.w.verstraaten@rug.nl"
] | t.w.verstraaten@rug.nl |
48c1631903c085c807d97c85f11f3c8cac3eb10f | 887f3a72757ff8f691c1481618944b727d4d9ff5 | /third_party/gecko_1.9.1/linux/gecko_sdk/include/nsIDOMHTMLLegendElement.h | 73c4c95a8936abc6888d6e23e96e9d7a26584abd | [] | no_license | zied-ellouze/gears | 329f754f7f9e9baa3afbbd652e7893a82b5013d1 | d3da1ed772ed5ae9b82f46f9ecafeb67070d6899 | refs/heads/master | 2020-04-05T08:27:05.806590 | 2015-09-03T13:07:39 | 2015-09-03T13:07:39 | 41,813,794 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,027 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/moz2_slave/mozilla-1.9.1-linux-xulrunner/build/dom/public/idl/html/nsIDOMHTMLLegendElement.idl
*/
#ifndef __gen_nsIDOMHTMLLegendElement_h__
#define __gen_nsIDOMHTMLLegendElement_h__
#ifndef __gen_nsIDOMHTMLElement_h__
#include "nsIDOMHTMLElement.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIDOMHTMLLegendElement */
#define NS_IDOMHTMLLEGENDELEMENT_IID_STR "a6cf9098-15b3-11d2-932e-00805f8add32"
#define NS_IDOMHTMLLEGENDELEMENT_IID \
{0xa6cf9098, 0x15b3, 0x11d2, \
{ 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 }}
/**
* The nsIDOMHTMLLegendElement interface is the interface to a [X]HTML
* legend element.
*
* For more information on this interface please see
* http://www.w3.org/TR/DOM-Level-2-HTML/
*
* @status FROZEN
*/
class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMHTMLLegendElement : public nsIDOMHTMLElement {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMHTMLLEGENDELEMENT_IID)
/* readonly attribute nsIDOMHTMLFormElement form; */
NS_SCRIPTABLE NS_IMETHOD GetForm(nsIDOMHTMLFormElement * *aForm) = 0;
/* attribute DOMString accessKey; */
NS_SCRIPTABLE NS_IMETHOD GetAccessKey(nsAString & aAccessKey) = 0;
NS_SCRIPTABLE NS_IMETHOD SetAccessKey(const nsAString & aAccessKey) = 0;
/* attribute DOMString align; */
NS_SCRIPTABLE NS_IMETHOD GetAlign(nsAString & aAlign) = 0;
NS_SCRIPTABLE NS_IMETHOD SetAlign(const nsAString & aAlign) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMHTMLLegendElement, NS_IDOMHTMLLEGENDELEMENT_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMHTMLLEGENDELEMENT \
NS_SCRIPTABLE NS_IMETHOD GetForm(nsIDOMHTMLFormElement * *aForm); \
NS_SCRIPTABLE NS_IMETHOD GetAccessKey(nsAString & aAccessKey); \
NS_SCRIPTABLE NS_IMETHOD SetAccessKey(const nsAString & aAccessKey); \
NS_SCRIPTABLE NS_IMETHOD GetAlign(nsAString & aAlign); \
NS_SCRIPTABLE NS_IMETHOD SetAlign(const nsAString & aAlign);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMHTMLLEGENDELEMENT(_to) \
NS_SCRIPTABLE NS_IMETHOD GetForm(nsIDOMHTMLFormElement * *aForm) { return _to GetForm(aForm); } \
NS_SCRIPTABLE NS_IMETHOD GetAccessKey(nsAString & aAccessKey) { return _to GetAccessKey(aAccessKey); } \
NS_SCRIPTABLE NS_IMETHOD SetAccessKey(const nsAString & aAccessKey) { return _to SetAccessKey(aAccessKey); } \
NS_SCRIPTABLE NS_IMETHOD GetAlign(nsAString & aAlign) { return _to GetAlign(aAlign); } \
NS_SCRIPTABLE NS_IMETHOD SetAlign(const nsAString & aAlign) { return _to SetAlign(aAlign); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMHTMLLEGENDELEMENT(_to) \
NS_SCRIPTABLE NS_IMETHOD GetForm(nsIDOMHTMLFormElement * *aForm) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetForm(aForm); } \
NS_SCRIPTABLE NS_IMETHOD GetAccessKey(nsAString & aAccessKey) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAccessKey(aAccessKey); } \
NS_SCRIPTABLE NS_IMETHOD SetAccessKey(const nsAString & aAccessKey) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetAccessKey(aAccessKey); } \
NS_SCRIPTABLE NS_IMETHOD GetAlign(nsAString & aAlign) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAlign(aAlign); } \
NS_SCRIPTABLE NS_IMETHOD SetAlign(const nsAString & aAlign) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetAlign(aAlign); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMHTMLLegendElement : public nsIDOMHTMLLegendElement
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMHTMLLEGENDELEMENT
nsDOMHTMLLegendElement();
private:
~nsDOMHTMLLegendElement();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMHTMLLegendElement, nsIDOMHTMLLegendElement)
nsDOMHTMLLegendElement::nsDOMHTMLLegendElement()
{
/* member initializers and constructor code */
}
nsDOMHTMLLegendElement::~nsDOMHTMLLegendElement()
{
/* destructor code */
}
/* readonly attribute nsIDOMHTMLFormElement form; */
NS_IMETHODIMP nsDOMHTMLLegendElement::GetForm(nsIDOMHTMLFormElement * *aForm)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute DOMString accessKey; */
NS_IMETHODIMP nsDOMHTMLLegendElement::GetAccessKey(nsAString & aAccessKey)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsDOMHTMLLegendElement::SetAccessKey(const nsAString & aAccessKey)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute DOMString align; */
NS_IMETHODIMP nsDOMHTMLLegendElement::GetAlign(nsAString & aAlign)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsDOMHTMLLegendElement::SetAlign(const nsAString & aAlign)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMHTMLLegendElement_h__ */
| [
"gears.daemon@fe895e04-df30-0410-9975-d76d301b4276"
] | gears.daemon@fe895e04-df30-0410-9975-d76d301b4276 |
522ef7bd1876212f202a9bbe7a89c00bb6fbfca7 | 721b2e5596c314aacde4238dea00b1281a1042d5 | /bitmapfontgenerator-gui/textureatlaseditor.h | f3bffae55f5ff752b268d43ecc3ef14d7324d0e1 | [
"MIT"
] | permissive | Phault/BitmapFontGenerator | 7ee68b551360b995813d75a2e341ec874a32475d | 32007bb65742637f66e948d2b1ebea9d26dd4006 | refs/heads/master | 2020-03-26T17:10:07.510696 | 2018-08-17T16:46:09 | 2018-08-17T16:49:09 | 145,145,349 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 617 | h | #ifndef BITMAPOPTIONS_H
#define BITMAPOPTIONS_H
#include "fonteditorwidget.h"
#include <QWidget>
namespace Ui {
class TextureAtlasEditor;
}
class TextureAtlasEditor : public FontEditorWidget
{
Q_OBJECT
public:
explicit TextureAtlasEditor(FontGenerator &generator, QWidget *parent = nullptr);
~TextureAtlasEditor() override;
private slots:
void on_textureSize_valueChanged(int);
void on_pageMargin_valueChanged(int);
void on_glyphSpacing_valueChanged(int);
void on_packingMethod_currentIndexChanged(int index);
private:
Ui::TextureAtlasEditor *ui;
};
#endif // BITMAPOPTIONS_H
| [
"casper.developer@gmail.com"
] | casper.developer@gmail.com |
666443216ed626aeb2c273799fb5ef2468005cce | d65407dec2786f84be13596a78530ff4633ad9a7 | /ui/UI_Button.cpp | af1bd6f2a996cca088808a3103e97bc709e6f5d6 | [] | no_license | vincentdar/LUCY | 78a7d669bc722301c019e2119f16b6ab349ca3d9 | 694fa3507b33fb48f894c96ecc184bd7205e19d3 | refs/heads/master | 2022-11-05T04:57:42.525718 | 2020-06-26T01:46:36 | 2020-06-26T01:46:36 | 263,029,292 | 0 | 0 | null | 2020-06-23T13:36:44 | 2020-05-11T11:58:37 | C++ | UTF-8 | C++ | false | false | 3,486 | cpp | #include "UI_Button.h"
#include "../Utils.h"
namespace UI {
void Button::init() {
}
void Button::handleInput(sf::Event & event, sf::RenderWindow & window)
{
if (!enabled) return;
if (isHovered(event, window)) {
hovered = true;
}
else {
hovered = false;
}
if (isClicked(event, window)) {
clicked = true;
}
else {
clicked = false;
}
}
void Button::setText(std::string text)
{
this->text.setCharacterSize(30);
this->text.setString(text);
}
void Button::setFont(sf::Font * font)
{
this->font = font;
this->text.setFont(*this->font);
}
void Button::setOutline(float thickness, sf::Color color)
{
base_shape.setOutlineThickness(thickness);
base_shape.setOutlineColor(color);
}
void Button::update(sf::RenderWindow& window)
{
this->text.setPosition(
base_shape.getGlobalBounds().left + base_shape.getGlobalBounds().width / 2.0 - UTILS::getTextWidth(text) / 2.0,
base_shape.getGlobalBounds().top + base_shape.getGlobalBounds().height / 2.0 - 15
);
// Check apakah button disabled
if (!enabled) {
if (usingColor) {
this->base_shape.setFillColor(disabled);
}
else {
this->base_shape.setTexture(disabled_texture);
}
return;
}
if (usingColor) {
if (!usingSecondary)
this->base_shape.setFillColor(main_color);
else
this->base_shape.setFillColor(secondary);
}
else {
if (!usingSecondary)
this->base_shape.setTexture(main_texture);
else
this->base_shape.setTexture(secondary_texture);
}
// Check apakah button hovered
if (hovered) {
if (usingColor) {
this->base_shape.setFillColor(hovered_color);
}
else {
this->base_shape.setTexture(hovered_texture);
}
}
if (clicked)
{
if (usingColor) {
this->base_shape.setFillColor(pressed);
}
else {
this->base_shape.setTexture(pressed_texture);
}
return;
}
}
bool Button::isClicked(sf::Event& event, sf::RenderWindow& window)
{
return (UTILS::isMouseOver(
sf::Vector2f(base_shape.getGlobalBounds().left, base_shape.getGlobalBounds().top),
base_shape.getSize().x, base_shape.getSize().y, window) && event.type == sf::Event::MouseButtonPressed);
}
bool Button::isHovered(sf::Event& event, sf::RenderWindow& window)
{
return UTILS::isMouseOver(
sf::Vector2f(base_shape.getGlobalBounds().left, base_shape.getGlobalBounds().top),
base_shape.getSize().x, base_shape.getSize().y, window);
}
void Button::draw(sf::RenderTarget& target)
{
target.draw(base_shape);
target.draw(text);
}
void Button::setColor(sf::Color main, sf::Color pressed, sf::Color hovered, sf::Color disabled, sf::Color secondary)
{
usingColor = true;
this->main_color = main;
this->pressed = pressed;
this->hovered_color = hovered;
this->disabled = disabled;
this->secondary = secondary;
}
void Button::setTexture(sf::Texture* main_texture, sf::Texture* pressed_texture, sf::Texture* hovered_texture, sf::Texture* disabled_texture, sf::Texture* secondary_texture)
{
usingColor = false;
this->main_texture = main_texture;
// Kalau nullptr, maka dapatnya main_texture;
this->hovered_texture = hovered_texture == nullptr ? main_texture : hovered_texture;
this->secondary_texture = secondary_texture == nullptr ? main_texture : secondary_texture;
this->pressed_texture = pressed_texture == nullptr ? main_texture : pressed_texture;
this->disabled_texture = disabled_texture == nullptr ? main_texture : disabled_texture;
}
}
| [
"matthew.sutanto0612@yahoo.com"
] | matthew.sutanto0612@yahoo.com |
8a0efb431996c317dfece21df3b627592ab81fa4 | c6eb77cfdd6131e72aca7d276112c415ccf74b73 | /CourseEra_specialization/ALGORITHMIC_TOOLBOX/week 2/fibo.cpp | 87cf1305f8e2a0474ec859f850e20c767c461618 | [] | no_license | kailasmanivannan/DATA_STRUCTURES_AND_ALGOS | 09b1277d5ccc3ad7b80029030495951689b2f6c8 | 96508afe718d8a2828fbd1e633f1878a2779177e | refs/heads/master | 2021-06-26T02:40:43.932862 | 2021-05-30T16:19:25 | 2021-05-30T16:19:25 | 225,181,056 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 261 | cpp | #include<iostream>
#include<vector>
using namespace std;
int main(){
int n;
cin>>n;
vector <int> ar(n+1);
ar[0]=0;
ar[1]=1;
for(int j = 2 ;j <= n ; j++){
ar[j]=ar[j-1]+ar[j-2];
}
cout<<ar[n];
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
d588b0fae9d295f5cedcaa4106de71fd0befe9b9 | ae2ab980d7b678c2f21733916b3e8295d99571ef | /1º AÑO/1ºCuatrimestre/FP/Practicas/Practica 2/Relacion ejercicio 1/ejercicio 5, nueva if else.cpp | 4329855eac8f453ce8be652b2d52b5cfd602db61 | [] | no_license | thejosess/Informatica-UGR | 2f1a45804e2a6c3a91876ff049a0a375f213a3b0 | 7ac9bf5aa75f29988b798e508c8d3332a4e92d21 | refs/heads/master | 2021-06-18T21:40:09.496409 | 2021-06-11T14:22:56 | 2021-06-11T14:22:56 | 216,213,168 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,366 | cpp | //Ejercicio 5
#include <iostream>
using namespace std;
int main()
{
//Entrada
int numero_1 , numero_2 , numero_3 ;
cout << "Introducir numero entero distinto a 0 : " ;
cin >> numero_1 ;
cout << "Introducir numero entero distinto a 0 : " ;
cin >> numero_2 ;
cout << "Introducir numero entero distinto a 0 : " ;
cin >> numero_3 ;
//Proceso
if ( numero_1 > 0 && numero_2 > 0 && numero_3 > 0 )
cout << "El signo predominante es positivo" << endl;
if ( numero_3 > 0 && numero_2 > 0 && numero_1 < 0 )
cout << "El signo predominante es positivo" << endl ;
if ( numero_2 > 0 && numero_1 > 0 && numero_3 < 0 )
cout << "El signo predominante es positivo" << endl ;
if ( numero_1 > 0 && numero_3 > 0 && numero_2 < 0 )
cout << "El signo predominante es positivo" << endl ;
if ( numero_1 < 0 && numero_2 < 0 && numero_3 < 0 )
cout << "El signo predominante es negativo" << endl;
if ( numero_3 < 0 && numero_2 < 0 && numero_1 > 0 )
cout << "El signo predominante es negativo" << endl ;
if ( numero_2 < 0 && numero_1 < 0 && numero_3 > 0 )
cout << "El signo predominante es negativo" << endl ;
if ( numero_1 < 0 && numero_3 < 0 && numero_2 > 0 )
cout << "El signo predominante es negativo" << endl ;
}
| [
"santossalvador@correo.ugr.es"
] | santossalvador@correo.ugr.es |
adb5a024112739377396d98108ca5ab2ed046f67 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/FilterListInSystem/UNIX_FilterListInSystem_TRU64.hxx | 033091e2f18dd8c868e3f71e929bca151a1a67dc | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,821 | hxx | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_TRU64
#ifndef __UNIX_FILTERLISTINSYSTEM_PRIVATE_H
#define __UNIX_FILTERLISTINSYSTEM_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
ca95b0dba24bc175d94e7dda057d937a08b7b1b4 | 0e029609eca453668ee52c5e95364abea91e80cf | /src/ThresholdParameter.h | 2522c873b5fa757b8ca502ee03abd97a7ad2d826 | [] | no_license | asw221/thresh | d56d77f95301ffa7e4483c814e70bb8dba6566f4 | 861fa218739fc36f90a67b4a964b97f90cce3ac5 | refs/heads/master | 2020-12-02T06:15:31.122161 | 2017-08-10T23:02:34 | 2017-08-10T23:02:34 | 96,805,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,766 | h |
#ifndef _THRESHOLD_PARAMETER_
#define _THRESHOLD_PARAMETER_
#include <Eigen/Core>
#include <Eigen/SparseCore>
#include <cmath>
#include <random>
#include <algorithm>
#include "RandWalkParam.h"
#include "ThreshCoef.h"
class ThresholdParameter
{
private:
double _data;
double Min;
double Max;
RandWalkParam<> walk;
double logPosterior(
const double &theta,
const Eigen::Map< Eigen::VectorXd > &y,
const Eigen::Map< Eigen::MatrixXd > &X,
const ThreshCoef &alpha,
const double &tauSq
) const
{
Eigen::VectorXd res = y - X * alpha.getSparseCoefs(theta);
double rss = res.transpose() * res;
return (-0.5 * tauSq * rss);
};
double logPosterior(
const double &tauSq,
const double &residSS
) const
{
return (-0.5 * tauSq * residSS);
};
public:
ThresholdParameter(
const double maxVal = 1.0,
const double minVal = 0.0
) : Min(minVal), Max(maxVal)
{
_data = (Max - Min) / 2; // uniform expectation
walk.setKernel((Max - Min) / std::sqrt(12)); // uniform sigma
// walk.setScale(2.4);
walk.setScale(1.0);
};
double operator = (const double &rhs) {
if (rhs < Min || rhs > Max)
throw (std::logic_error("ThresholdParameter value out of bounds"));
_data = rhs;
return (rhs);
};
operator double () const {
return (_data);
};
void update(
std::mt19937 &engine,
const Eigen::Map< Eigen::VectorXd > &y,
const Eigen::Map< Eigen::MatrixXd > &X,
const ThreshCoef &alpha,
const double &tauSq,
const double &residSS
) {
static std::normal_distribution< double > z(0.0, 1.0);
static std::uniform_real_distribution< double > unif(0.0, 1.0);
double proposal = _data + walk.getKernel() * z(engine);
double p = 0.0, r;
if (proposal < Max && proposal > Min) {
r = std::exp(logPosterior(proposal, y, X, alpha, tauSq) -
logPosterior(tauSq, residSS)
);
p = std::min(r, 1.0);
if (unif(engine) < r)
_data = proposal;
}
walk.updateParams(_data, p);
};
void updateKernel() {
const double p = walk.getProb();
const double newScale = scaleKernel(walk.getScale(), p);
// if (newScale != walk.getScale() && p > 0.05 && p < 0.7)
// walk.updateKernel();
if (p > 0.05 && p < 0.7)
walk.updateKernel();
else
walk.clear();
walk.setScale(newScale);
};
double getKernel() const {
return (walk.getKernel());
};
double getJumpProb() const {
return (walk.getProb());
};
void setKernel(const double &Kern) {
if (Kern <= 0)
throw (std::logic_error("ThresholdParameter jumping kernel <= 0"));
walk.setKernel(Kern);
};
};
#endif // _THRESHOLD_PARAMETER_
| [
"AprilVKwong@April-Kwongs-MacBook-Pro.local"
] | AprilVKwong@April-Kwongs-MacBook-Pro.local |
e65dee5e12afa7cc259ab9c00bf92c087dcbba5c | f8327fe3a6c6c743a42dc5a2574c14be8e1ea8b2 | /star.h | a9cf2ac98bc900778c24899433c5584fe076b9d6 | [] | no_license | AdamGinna/StarSystem | fa16ac8d9ba2bc90230ed21670ccdfa5f6710b82 | f94cb5f494035c6d36d1e300ffa02072758daadb | refs/heads/master | 2020-07-27T08:07:21.613405 | 2019-09-05T15:36:22 | 2019-09-05T15:36:22 | 209,024,545 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 359 | h | #ifndef STAR_H
#define STAR_H
#include "sphere.h"
class Star : public Sphere
{
public:
Star(int x, int y, int z, double radius, double lightIntesity)
:Sphere(x, y, z, radius)
{this->lightIntensity = lightIntesity;}
double getIntensity();
private:
double lightIntensity;
double mass;
QVector3D velocity;
};
#endif // STAR_H
| [
"adam.ginna.work@gmail.com"
] | adam.ginna.work@gmail.com |
f1c24c3b07ae41976c8c2cb07b684da1e922fc5f | b77349e25b6154dae08820d92ac01601d4e761ee | /Image Processing/GradualChange/GradualChange.h | a0fd26692e522099c22d3e46afc148a24e7d968d | [] | no_license | ShiverZm/MFC | e084c3460fe78f820ff1fec46fe1fc575c3e3538 | 3d05380d2e02b67269d2f0eb136a3ac3de0dbbab | refs/heads/master | 2023-02-21T08:57:39.316634 | 2021-01-26T10:18:38 | 2021-01-26T10:18:38 | 332,725,087 | 0 | 0 | null | 2021-01-25T11:35:20 | 2021-01-25T11:29:59 | null | UTF-8 | C++ | false | false | 1,384 | h | // GradualChange.h : main header file for the GRADUALCHANGE application
//
#if !defined(AFX_GRADUALCHANGE_H__E1BE1F3C_3404_41DF_8FC3_1E926B20D61A__INCLUDED_)
#define AFX_GRADUALCHANGE_H__E1BE1F3C_3404_41DF_8FC3_1E926B20D61A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CGradualChangeApp:
// See GradualChange.cpp for the implementation of this class
//
class CGradualChangeApp : public CWinApp
{
public:
CGradualChangeApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CGradualChangeApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CGradualChangeApp)
afx_msg void OnAppAbout();
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_GRADUALCHANGE_H__E1BE1F3C_3404_41DF_8FC3_1E926B20D61A__INCLUDED_)
| [
"w.z.y2006@163.com"
] | w.z.y2006@163.com |
36d9ebdfe715437bdecbf1b7f75c07692f00c684 | 166729f27064d7565dac923450bd41c2fe6eb7a4 | /logdevice/common/configuration/nodes/NodesConfigurationStore.h | 176a8b02067a49016956fa778368f95df2ad4037 | [
"BSD-3-Clause"
] | permissive | abhishekg785/LogDevice | 742e7bd6bf3177056774346c8095b43a7fe82c79 | 060da71ef84b61f3371115ed352a7ee7b07ba9e2 | refs/heads/master | 2020-04-17T05:26:15.201210 | 2019-01-17T14:18:09 | 2019-01-17T14:23:57 | 166,278,849 | 1 | 0 | NOASSERTION | 2019-01-17T18:53:23 | 2019-01-17T18:53:22 | null | UTF-8 | C++ | false | false | 3,940 | h | /**
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <type_traits>
#include <unordered_map>
#include <folly/Function.h>
#include <folly/Optional.h>
#include <folly/Synchronized.h>
#include "logdevice/common/VersionedConfigStore.h"
#include "logdevice/include/Err.h"
#include "logdevice/include/types.h"
namespace facebook { namespace logdevice { namespace configuration {
namespace nodes {
// Backing data source of NodesConfig, used both by the LogDevice server and by
// tooling. This is mostly owned and accessed by the NodesConfigurationManager
// singleton. This is just an API, implementations include
// VersionedNodesConfigurationStore and ServerBasedNodesConfigurationStore.
class NodesConfigurationStore {
public:
using version_t = VersionedConfigStore::version_t;
using value_callback_t = VersionedConfigStore::value_callback_t;
using write_callback_t = VersionedConfigStore::write_callback_t;
using extract_version_fn = VersionedConfigStore::extract_version_fn;
virtual ~NodesConfigurationStore() = default;
// Read the documentation of VersionedConfigStore::getConfig.
virtual void getConfig(value_callback_t cb) const = 0;
// Read the documentation of VersionedConfigStore::getConfigSync.
virtual Status getConfigSync(std::string* value_out) const = 0;
// Read the documentation of VersionedConfigStore::updateConfig.
virtual void updateConfig(std::string value,
folly::Optional<version_t> base_version,
write_callback_t cb = {}) = 0;
// Read the documentation of VersionedConfigStore::updateConfigSync.
virtual Status updateConfigSync(std::string value,
folly::Optional<version_t> base_version,
version_t* version_out = nullptr,
std::string* value_out = nullptr) = 0;
};
// A NodesConfigurationStore implementation that's backed by a
// VersionedConfigStore.
template <class T>
class VersionedNodesConfigurationStore : public NodesConfigurationStore {
static_assert(std::is_base_of<VersionedConfigStore, T>::value,
"The generic type should be a VersionedConfigStore");
public:
static constexpr const auto kConfigKey = "/ncm/config";
template <typename... Args>
VersionedNodesConfigurationStore(Args&&... args)
: store_(std::make_unique<T>(std::forward<Args>(args)...)) {}
virtual ~VersionedNodesConfigurationStore() = default;
virtual void getConfig(value_callback_t cb) const override {
store_->getConfig(kConfigKey, std::move(cb));
}
virtual Status getConfigSync(std::string* value_out) const override {
return store_->getConfigSync(kConfigKey, value_out);
}
virtual void updateConfig(std::string value,
folly::Optional<version_t> base_version,
write_callback_t cb = {}) override {
store_->updateConfig(
kConfigKey, std::move(value), std::move(base_version), std::move(cb));
}
virtual Status updateConfigSync(std::string value,
folly::Optional<version_t> base_version,
version_t* version_out = nullptr,
std::string* value_out = nullptr) override {
return store_->updateConfigSync(kConfigKey,
std::move(value),
std::move(base_version),
version_out,
value_out);
}
private:
std::unique_ptr<T> store_;
};
template <class T>
constexpr const char* const VersionedNodesConfigurationStore<T>::kConfigKey;
}}}} // namespace facebook::logdevice::configuration::nodes
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
0168d203d70c65194d765cfa6ddebcea58780022 | 037d518773420f21d74079ee492827212ba6e434 | /blaze/util/constraints/Builtin.h | 5e56b1c7060732f5199f015e06cd048f6e450997 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | chkob/forked-blaze | 8d228f3e8d1f305a9cf43ceaba9d5fcd603ecca8 | b0ce91c821608e498b3c861e956951afc55c31eb | refs/heads/master | 2021-09-05T11:52:03.715469 | 2018-01-27T02:31:51 | 2018-01-27T02:31:51 | 112,014,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,914 | h | //=================================================================================================
/*!
// \file blaze/util/constraints/Builtin.h
// \brief Constraint on the data type
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZE_UTIL_CONSTRAINTS_BUILTIN_H_
#define _BLAZE_UTIL_CONSTRAINTS_BUILTIN_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <blaze/util/typetraits/IsBuiltin.h>
namespace blaze {
//=================================================================================================
//
// MUST_BE_BUILTIN_TYPE CONSTRAINT
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Constraint on the data type.
// \ingroup constraints
//
// In case the given data type \a T is not a built-in data type, a compilation error is created.
*/
#define BLAZE_CONSTRAINT_MUST_BE_BUILTIN_TYPE(T) \
static_assert( ::blaze::IsBuiltin<T>::value, "Non-built-in type detected" )
//*************************************************************************************************
//=================================================================================================
//
// MUST_NOT_BE_BUILTIN_TYPE CONSTRAINT
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Constraint on the data type.
// \ingroup constraints
//
// In case the given data type \a T is a built-in data type, a compilation error is created.
*/
#define BLAZE_CONSTRAINT_MUST_NOT_BE_BUILTIN_TYPE(T) \
static_assert( !::blaze::IsBuiltin<T>::value, "Built-in type detected" )
//*************************************************************************************************
} // namespace blaze
#endif
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
27e7ccf586310511b72468454117a11cfededff5 | 52180c66d580f87fd69d154e2077d0016f70504f | /PetriNet/PetriNet/LbfToPrimitiveSeparator.cpp | 323d8f3c2863947458955c0e20400dfeea49b25a | [] | no_license | BrotherhoodOfGrant/petri_logistics | 2c8fc9c47961a0c3cddc24b7616a0d646d24035c | a11fb76e1ee9c7976c8cbca987c0a67d243ccf51 | refs/heads/master | 2016-09-01T05:14:26.423368 | 2015-11-06T19:59:28 | 2015-11-06T19:59:28 | 44,558,129 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 282 | cpp | #include "stdafx.h"
#include "LbfToPrimitiveSeparator.h"
Petri_Net* LbfToPrimitiveSeparator::Separate(_In_ Petri_Net& lbfNet, _Out_ Matrix* tensor)
{
return NULL;
}
LbfToPrimitiveSeparator::LbfToPrimitiveSeparator()
{
}
LbfToPrimitiveSeparator::~LbfToPrimitiveSeparator()
{
}
| [
"c016s006b017@mail.ru"
] | c016s006b017@mail.ru |
68dffd230a06a8d8829cf5b9c34011c8493c8adc | 827405b8f9a56632db9f78ea6709efb137738b9d | /CodingWebsites/WHU_OJ/test.cpp | e9d500476dec470638de0fe4f43e06a878be75c0 | [] | no_license | MingzhenY/code-warehouse | 2ae037a671f952201cf9ca13992e58718d11a704 | d87f0baa6529f76e41a448b8056e1f7ca0ab3fe7 | refs/heads/master | 2020-03-17T14:59:30.425939 | 2019-02-10T17:12:36 | 2019-02-10T17:12:36 | 133,694,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 178 | cpp | #include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
int main(){
string a = "";
printf("%d\n",a == "");
return 0;
}
| [
"mingzhenyan@yahoo.com"
] | mingzhenyan@yahoo.com |
aa4097e7ebf87ab61184d4bb7517a3154dc23b64 | 3ae80dbc18ed3e89bedf846d098b2a98d8e4b776 | /header/DB/SQLGenerator.h | 707175b256c1793afe21505af10f0b8f346104dd | [] | no_license | sswroom/SClass | deee467349ca249a7401f5d3c177cdf763a253ca | 9a403ec67c6c4dfd2402f19d44c6573e25d4b347 | refs/heads/main | 2023-09-01T07:24:58.907606 | 2023-08-31T11:24:34 | 2023-08-31T11:24:34 | 329,970,172 | 10 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 1,891 | h | #ifndef _SM_DB_SQLGENERATOR
#define _SM_DB_SQLGENERATOR
#include "DB/PageRequest.h"
#include "DB/SQLBuilder.h"
#include "DB/TableDef.h"
namespace DB
{
class SQLGenerator
{
public:
enum class PageStatus
{
Succ,
NoOffset,
NoPage
};
public:
static void AppendColDef(DB::SQLType sqlType, DB::SQLBuilder *sql, DB::ColDef *col);
static void AppendColType(DB::SQLType sqlType, DB::SQLBuilder *sql, DB::DBUtil::ColType colType, UOSInt colSize, UOSInt colSize2, Bool autoInc, Text::String *nativeType);
static Bool GenCreateTableCmd(DB::SQLBuilder *sql, Text::CString schemaName, Text::CString tableName, DB::TableDef *tabDef, Bool multiline);
static Bool GenInsertCmd(DB::SQLBuilder *sql, Text::CString schemaName, Text::CString tableName, DB::DBReader *r);
static Bool GenInsertCmd(DB::SQLBuilder *sql, DB::TableDef *tabDef, DB::DBReader *r);
static Bool GenInsertCmd(DB::SQLBuilder *sql, Text::CString schemaName, Text::CString tableName, DB::TableDef *tabDef, DB::DBReader *r);
static Bool GenCreateDatabaseCmd(DB::SQLBuilder *sql, Text::CString databaseName, const Collation *collation);
static Bool GenDeleteDatabaseCmd(DB::SQLBuilder *sql, Text::CString databaseName);
static Bool GenCreateSchemaCmd(DB::SQLBuilder *sql, Text::CString schemaName);
static Bool GenDeleteSchemaCmd(DB::SQLBuilder *sql, Text::CString schemaName);
static Bool GenDropTableCmd(DB::SQLBuilder *sql, Text::CString tableName);
static Bool GenDeleteTableDataCmd(DB::SQLBuilder *sql, Text::CString schemaName, Text::CString tableName);
static Bool GenTruncateTableCmd(DB::SQLBuilder *sql, Text::CString schemaName, Text::CString tableName);
static PageStatus GenSelectCmdPage(DB::SQLBuilder *sql, DB::TableDef *tabDef, DB::PageRequest *page);
static UTF8Char *GenInsertCmd(UTF8Char *sqlstr, DB::SQLType sqlType, Text::CString tableName, DB::DBReader *r);
};
}
#endif
| [
"sswroom@yahoo.com"
] | sswroom@yahoo.com |
2d0f2a1e103ac7f113f05b068a657c068044a953 | 4fc5c01bbe09b045f52c7e5625797779c8db2b85 | /EngineeringDepartment.h | 59b4b9de6a06a12fc6877dfad174d38bd1604bd7 | [] | no_license | 214Project2020/214-Project-RC | 3ff15c2b7aad39ceb35509ab6cf1ff9aee6ad8ff | 463dd0716d538c5281b4ae9e8d1d76cd1fbcbd57 | refs/heads/main | 2023-01-09T00:52:14.950126 | 2020-11-09T19:04:06 | 2020-11-09T19:04:06 | 300,345,602 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | h | #ifndef ENGINEERINGDEPARTMENT_H
#define ENGINEERINGDEPARTMENT_H
#include "CurrentSeasonDepartment.h"
#include "NextSeasonDepartment.h"
#include "ElectronicsCurrentSeason.h"
#include "AerodynamicsCurrentSeason.h"
#include "EngineCurrentSeason.h"
#include "ChassisCurrentSeason.h"
#include "ElectronicsNextSeason.h"
#include "AerodynamicsNextSeason.h"
#include "EngineNextSeason.h"
#include "ChassisNextSeason.h"
class EngineeringDepartment{
public:
EngineeringDepartment();
~EngineeringDepartment();
virtual CurrentSeasonDepartment * createCurrentSeason() = 0;
virtual NextSeasonDepartment * createNextSeason() = 0;
};
#endif | [
"mattywoodx@gmail.com"
] | mattywoodx@gmail.com |
45fc7ad07b5747c3638bf365ff6d2595e2a656f8 | 5ac691580c49d8cf494d5b98c342bb11f3ff6514 | /AtCoder/abc178/abc178_d.cpp | 7332ba87a4b72b781f5d925b6d89e6f687a83a1a | [] | no_license | sweatpotato13/Algorithm-Solving | e68411a4f430d0517df4ae63fc70d1a014d8b3ba | b2f8cbb914866d2055727b9872f65d7d270ba31b | refs/heads/master | 2023-03-29T23:44:53.814519 | 2023-03-21T23:09:59 | 2023-03-21T23:09:59 | 253,355,531 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 818 | cpp | #pragma warning(disable : 4996)
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pld;
typedef tuple<ll,ll,ll> tl3;
#define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))
#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))
#define rep(i, n) FOR(i, 0, n)
#define repn(i, n) FORN(i, 1, n)
#define tc(t) while (t--)
// https://atcoder.jp/contests/abc177/tasks/abc178_d
const ll mod = 1e9+7;
ll dp[2001] = {0,};
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll s;
cin >> s;
dp[0] = 1;
dp[1] = 0;
dp[2] = 0;
for(ll i = 3;i<=s;i++){
dp[i] = (dp[i-1] + dp[i-3])%mod;
}
cout << dp[s];
return 0;
}
| [
"sweatpotato13@gmail.com"
] | sweatpotato13@gmail.com |
742408e4e8d723dc76370a7a41704c87fe35ccd1 | a7cfc8c4cf0f9514c4056dd599d5c97595d21444 | /ProyectoGraficas1/ProyectoGraficas1/APase.h | b88c3d8b1e738386efe5f24b58f9e2a2aa15d3a6 | [] | no_license | arlo999/Graficas1_Axel | 7bfe974f7b5e534e71a4a1c290f9b225cf091b9c | eee1b7295a7f3b64ab058d5d977a5972fce6b495 | refs/heads/main | 2023-06-16T13:04:55.647068 | 2021-07-13T01:42:14 | 2021-07-13T01:42:14 | 328,456,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | h | #pragma once
#include "AModel.h"
#include <iostream>
#include <vector>
#include "GraphicsModule.h"
#include "AShader.h"
#if defined(DX11)
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dcompiler.h>
#include <xnamath.h>
#endif
class APase
{
public:
APase();
APase(bool _PostProceso);
APase(int _typePase);
~APase();
HRESULT Init();
void Render();
HRESULT InitGBuffer();
HRESULT InitCopy();
HRESULT InitLight();
HRESULT InitSao();
HRESULT InitTooneMap();
HRESULT InitSkybox();
HRESULT InitSkeleto();
bool forward = false;
HRESULT CompileShaderFromFile(const char* szFileName, const D3D10_SHADER_MACRO* _Macros, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut);
private:
HWND g_hwnd;
ID3D11VertexShader* g_pVertexShader = NULL;
ID3D11PixelShader* g_pPixelShader = NULL;
ID3D11InputLayout* g_pVertexLayout = NULL;
ID3D11RasterizerState* m_Rasterizador = NULL;
std::vector<ID3D11RenderTargetView*>m_ListRenderTV;
std::vector<AModel*>m_ModelList;
int m_TypePase;
};
| [
"59717448+arlo999@users.noreply.github.com"
] | 59717448+arlo999@users.noreply.github.com |
8610e1e292c90dc1d54b84e14bf0a694011f0247 | 2dd50afaa6def54b13af4337383871b1fecfd422 | /Source/Input/TouchDispather.h | 9caeb4099dce5b4e4393fcfdd89082997387327d | [
"MIT"
] | permissive | redchew-fork/Dorothy-SSR | cee73f9bba569295f8f71b614cc59d3266cc77b3 | 1874254224a5e83617b799795be1bfa4c8b707ac | refs/heads/master | 2023-04-16T07:35:24.060383 | 2021-04-25T00:07:53 | 2021-04-25T00:07:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,997 | h | /* Copyright (c) 2021 Jin Li, http://www.luvfight.me
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#pragma once
#include "Support/Geometry.h"
NS_DOROTHY_BEGIN
class TouchHandler
{
public:
PROPERTY_BOOL(SwallowTouches);
PROPERTY_BOOL(SwallowMouseWheel);
TouchHandler();
virtual ~TouchHandler();
virtual bool handle(const SDL_Event& event) = 0;
private:
bool _swallowTouches;
bool _swallowMouseWheel;
};
class Node;
class Touch : public Object
{
public:
enum
{
FromMouse = 1,
FromTouch = 1 << 1,
FromMouseAndTouch = FromMouse | FromTouch,
};
PROPERTY_BOOL(Enabled);
PROPERTY_READONLY_BOOL(Mouse);
PROPERTY_READONLY_BOOL(First);
PROPERTY_READONLY(int, Id);
PROPERTY_READONLY(Vec2, Delta);
PROPERTY_READONLY_CREF(Vec2, Location);
PROPERTY_READONLY_CREF(Vec2, PreLocation);
PROPERTY_READONLY_CREF(Vec2, WorldLocation);
PROPERTY_READONLY_CREF(Vec2, WorldPreLocation);
PROPERTY_READONLY_CLASS(Uint32, Source);
CREATE_FUNC(Touch);
protected:
Touch(int id);
private:
Flag _flags;
int _id;
Vec2 _location;
Vec2 _preLocation;
Vec2 _worldLocation;
Vec2 _worldPreLocation;
enum
{
Enabled = 1,
Selected = 1 << 1,
IsMouse = 1 << 2,
IsFirst = 1 << 3,
};
static Uint32 _source;
friend class NodeTouchHandler;
DORA_TYPE_OVERRIDE(Touch);
};
class NodeTouchHandler : public TouchHandler
{
public:
NodeTouchHandler(Node* target);
virtual bool handle(const SDL_Event& event) override;
protected:
Touch* alloc(SDL_FingerID fingerId);
Touch* get(SDL_FingerID fingerId);
void collect(SDL_FingerID fingerId);
Vec2 getPos(const SDL_Event& event);
Vec2 getPos(const Vec3& winPos);
bool up(const SDL_Event& event);
bool down(const SDL_Event& event);
bool move(const SDL_Event& event);
bool wheel(const SDL_Event& event);
bool gesture(const SDL_Event& event);
private:
Node* _target;
std::stack<int> _availableTouchIds;
std::unordered_map<SDL_FingerID, Ref<Touch>> _touchMap;
};
class UITouchHandler : public TouchHandler
{
public:
PROPERTY_BOOL(TouchSwallowed);
PROPERTY_BOOL(WheelSwallowed);
PROPERTY_READONLY(float, MouseWheel);
PROPERTY_READONLY_CREF(Vec2, MousePos);
PROPERTY_READONLY_BOOL(LeftButtonPressed);
PROPERTY_READONLY_BOOL(RightButtonPressed);
PROPERTY_READONLY_BOOL(MiddleButtonPressed);
UITouchHandler();
virtual ~UITouchHandler();
void clear();
virtual bool handle(const SDL_Event& event) override;
void handleEvent(const SDL_Event& event);
private:
bool _touchSwallowed;
bool _wheelSwallowed;
bool _leftButtonPressed;
bool _middleButtonPressed;
bool _rightButtonPressed;
float _mouseWheel;
Vec2 _mousePos;
};
class TouchDispatcher
{
public:
void add(const SDL_Event& event);
void add(TouchHandler* handler);
void dispatch();
void clearHandlers();
void clearEvents();
protected:
TouchDispatcher() { }
private:
std::vector<TouchHandler*> _handlers;
std::list<SDL_Event> _events;
SINGLETON_REF(TouchDispatcher, Director);
};
#define SharedTouchDispatcher \
Dorothy::Singleton<Dorothy::TouchDispatcher>::shared()
NS_DOROTHY_END
| [
"dragon-fly@qq.com"
] | dragon-fly@qq.com |
b2c2189f2a8b8e6ebc983bce710791822091878d | a79fbaa0083667aa86d044c588874774ece57f28 | /api_arv/lib/homography/src/sources/NR/.svn/text-base/transpose.cc.svn-base | 0775c902cd0ebc04a55c9fe3751a67fae647e68c | [] | no_license | VB6Hobbyst7/RVProject | c04b88f27ac8a84f912ec86191574d111cd8fc6c | 0e2461da5ae347fb5707d7e8b1ba247a24bd4a9a | refs/heads/master | 2021-12-02T07:29:24.001171 | 2011-01-28T17:04:46 | 2011-01-28T17:04:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | #ifndef __tvNR_transpose__
#define __tvNR_transpose__
// res[1..c][1..r] returns the transposed matrix of a[1..r][1..c]
template <class T>
void tvNR_transpose (T** a, T** res, int r, int c)
{
int i, j;
for (i = 1; i <= r; i++)
for (j = 1; j <= c; j++)
res[j][i] = a[i][j];
}
#endif
| [
"meuh@Rosalie.(none)"
] | meuh@Rosalie.(none) | |
58263258bfe987ddf88ae57c9608f69bdb390bc7 | c514c249ccfde74560a1f1eb436bc273ec4fc69e | /college_assignments/Assignment6/impsel.cpp | 4eb99d9928e54421aa297a94cde203565c22a6f7 | [] | no_license | rishusingh022/Data-structures_prac | 9c3d4f651cabba62a0ba31c489daec0b4975dd44 | 6c3eedd7eb2fa47c391809f2eceab7492e62b4b4 | refs/heads/main | 2023-01-12T07:20:11.738030 | 2020-11-13T11:43:29 | 2020-11-13T11:43:29 | 310,329,912 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | cpp | #include<bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cout<<"Enter no. of elements in array: ";
cin>>n;
vector<int> x(n);
cout<<"Enter elements of array: ";
for(int i = 0;i<n;i++)
{
cin>>x[i];
}
int i,j;
for(i = 0,j = n-1;i<j;i++,j--)
{ int minimum = x[i],maximum = x[j],min_index=i,max_index=j;
for(int k= i;k<=j;k++)
{
if(x[k]<minimum)
{
minimum = x[k];
min_index = k;
}
if(x[k]>maximum)
{
maximum = x[k];
max_index = k;
}
}
swap(x[i], x[min_index]);
if (x[min_index] == maximum)
swap(x[j], x[min_index]);
else
swap(x[j], x[max_index]);
}
cout<<"Sorted Array is: ";
for(int elem:x)
cout<<elem<<" ";
}
int main()
{
solve();
return 0;
}
| [
"rishusingh022@gmail.com"
] | rishusingh022@gmail.com |
9ca3495cbccc10ad2d03bf700aeb003ba6ce7518 | cd8783d914d71e1b9437f195f6c1c98d1844a26b | /Practica5/glwidget.cpp | 961fe38ba60522d82a87bd3a56eb5623e41c67a0 | [
"MIT"
] | permissive | MarcosAlarconRivas/IGr | 916143ea77cc894eb446cd481305c05be59ccff3 | 5f347880fdf346d2b798c7c5106fadc36a3d3867 | refs/heads/master | 2021-01-22T14:25:04.811749 | 2014-05-27T09:26:24 | 2014-05-27T09:26:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,013 | cpp | #include "glwidget.h"
#include "trglpipe.h"
static const double k = 2;
static V3D rusa0(double t){
return V3D(3*cos(t), 2*cos(1.5*t), 3*sin(t))*k;
}
static V3D rusa1(double t){
return V3D(-3*sin(t), -3*sin(1.5*t), 3*cos(t))*k;
}
static V3D rusa2(double t){
return V3D(-3*cos(t), -4.5*cos(1.5*t), -3*sin(t))*k;
}
GLWidget::GLWidget(QWidget *parent)
: QGLWidget(QGLFormat(QGL::SampleBuffers), parent){
setAutoFillBackground(false);
setFocusPolicy(Qt::ClickFocus);
setFocus();
//create scene objects
//pipe= new Extrusion(1, 16, &rusa0, &rusa1, &rusa2, 100, 0, 4*M_PI);
//pipe= new Extrusion(1, 16, &rusa0, 100, 0, 4*M_PI);
pipe= unique_ptr<Extrusion>( new TrglPipe(1, 16, &rusa0, &rusa1, &rusa2, 50, 0, 4*M_PI) );
car= unique_ptr<Car>( new Car(1, .75, 1.5, .2, .1) );
car->setWay(&rusa0, &rusa1, &rusa2);
car->setChassisCol(0, 1, 0);
car->setWheelsCol(.5, .5, .5);
car->setT(0);
}
GLWidget::~GLWidget(){
//delete pipe;
//delete car;
}
void GLWidget::initializeGL(){
glClearColor(0,0,0,1);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glMaterialf(GL_FRONT, GL_SHININESS, 0.1);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_NORMALIZE);
glShadeModel(GL_SMOOTH);//a normal for each vertex
//glShadeModel(GL_FLAT);//a normal for each face
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//do not paint back faces
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
//Camera
eye[0]=eye[1]=eye[2] =100;
look[0]=look[1]=look[2]=0;
up[0]=0; up[1]=1; up[2]=0;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(eye[0], eye[1], eye[2], look[0], look[1], look[2], up[0], up[1], up[2]);
//View Volume
N=1; F=1000; zoom=25;
//Ligth0
glEnable(GL_LIGHT0);
GLfloat LuzDifusa[]={1.0,1.0,1.0,1.0};
glLightfv(GL_LIGHT0, GL_DIFFUSE, LuzDifusa);
GLfloat LuzAmbiente[]={0.3,0.3,0.3,1.0};
glLightfv(GL_LIGHT0, GL_AMBIENT, LuzAmbiente);
GLfloat PosicionLuz0[]={25.0, 25.0, 0.0, 1.0};
glLightfv(GL_LIGHT0, GL_POSITION, PosicionLuz0);
}
void GLWidget::paintGL(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(axis){
//Axis draw
glBegin(GL_LINES);
glColor4f(1, 0, 0, 1);
glVertex3f( 0, 0, 0);
glVertex3f(100, 0, 0);
glColor4f(0, 1, 0, 1);
glVertex3f( 0, 0, 0);
glVertex3f( 0, 100, 0);
glColor4f(0, 0, 1, 1);
glVertex3f( 0, 0, 0);
glVertex3f( 0, 0, 100);
glEnd();
}
glPushMatrix();
//Rotate scene
glMultTransposeMatrixf(Rot);
//Draw scene
glColor4f(0, 0, 1, 1);
pipe->paint(full);
glColor4f(0,1,1,.5);
if(showN)pipe->paintNormals();
car->paint(full);
if(showN)car->paintNormals();
glPopMatrix();
}
void GLWidget::aplyView(){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float z= 2*zoom;
GLdouble x= width()/z, y= height()/z;
glOrtho(-x, x,-y, y, N, F);
glMatrixMode(GL_MODELVIEW);
}
void GLWidget::sceneRot(int i, double alpha){
if(!i){
float cx=cos(alpha), sx=sin(alpha);
/*
Rx[16]=float{1, 0, 0, 0,
0, cx,-sx, 0,
0, sx, cx, 0,
0, 0, 0, 1};
*/
float R5 = cx, R6 = -sx;
float R9 = sx, R10= cx;
//M*=Rx
/*
* m0, m1, m2, m3
* m4r5+m8r6, m5r5+m9r6, m6r5+m10r6, m7r5+m11r6
* m4r9+m8r10,m5r9+m9r10,m6r9+m10r10,m7r9+m11r10
* m12, m13, m14, m15
*/
for(int i=0;i<4;i++){
int a=4+i, b=8+i;
float Ma=Rot[a];
Rot[a]=Ma*R5+Rot[b]*R6;
Rot[b]=Ma*R9+Rot[b]*R10;
}
}else if(i==1){
float cy=cos(alpha), sy=sin(alpha);
/*
Ry[16]=float{cy, 0, sy, 0,
0, 1, 0, 0,
-sy, 0, cy, 0,
0, 0, 0, 1};
*/
float R0 = cy, R2 = sy;
float R8 = -sy, R10= cy;
//M*=Ry
/*
* m0r0+m8r2, m1r0+m9r2, m2r0+m10r2, m3r0+m11r2
* m4, m5, m6, m7
* m0r8+m8r10,m1r8+m9r10,m2r8+m10r10,m3r8+m11r10
* m12, m13, m14, m15
*/
for(int i=0;i<4;i++){
int a=i, b=8+i;
float Ma=Rot[a];
Rot[a]=Ma*R0+Rot[b]*R2;
Rot[b]=Ma*R8+Rot[b]*R10;
}
}else if(i==2){
float cz=cos(alpha), sz=sin(alpha);
/*
Rz[16]={cz,-sz, 0, 0,
sz, cz, 0, 0,
0, 0, 0, 0,
0, 0, 0, 1};
*/
float R0 = cz, R1 = -sz;
float R4 = sz, R5 = cz;
//M*=Rz
/*
* m0r0+m4r1, m1r0+m5r1, m2r0+m6r1, m3r0+m7r1
* m0r4+m4r5, m1r4+m5r5, m2r4+m6r5, m3r4+m7r5
* m8, m9, m10, m11
* m12, m13, m14, m15
*/
for(int i=0;i<4;i++){
int a=i, b=4+i;
float Ma=Rot[a];
Rot[a]=Ma*R0+Rot[b]*R1;
Rot[b]=Ma*R4+Rot[b]*R5;
}
}
}
void GLWidget::resizeGL(int width, int height){
//View port update
glViewport(0,0,width,height);
aplyView();
}
void GLWidget::keyPressEvent(QKeyEvent *e){
int key= e->key();
switch(key){
case Qt::Key_Plus :
zoom*=1.1;
aplyView();
break;
case Qt::Key_Minus :
zoom/=1.1;
aplyView();
break;
case Qt::Key_Up :
sceneRot(0, .1);
break;
case Qt::Key_Down :
sceneRot(0, -.1);
break;
case Qt::Key_Right :
sceneRot(1, .1);
break;
case Qt::Key_Left :
sceneRot(1, -.1);
break;
case Qt::Key_A :
sceneRot(2, .1);
break;
case Qt::Key_Z :
sceneRot(2, -.1);
break;
case Qt::Key_H :
full= !full;
break;
case Qt::Key_J :
showN= !showN;
break;
case Qt::Key_K :
axis= !axis;
break;
case Qt::Key_W :
car->advance( .05);
break;
case Qt::Key_Q :
car->advance(-.05);
break;
default: return;
}
repaint();
}
| [
"marcos.alarcon@ucm.es"
] | marcos.alarcon@ucm.es |
356c3f288fb3c6f4fd961b75a0f8dc78a115dd2c | 0b6d16678c8f802eb1c72992f832c137a4c6e05a | /include/wtf/font.hpp | a4f6165bf542365bfc2743103a34b9c16742bd10 | [
"BSL-1.0"
] | permissive | dmott-eyelock/wtf | 6dbdedaa973bea84caa9486c894e46464ebc9f1f | c232d89cdf9817c28c4c4937300caf117bcb6876 | refs/heads/master | 2023-03-21T14:35:31.645411 | 2018-12-22T09:42:09 | 2018-12-22T09:42:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,134 | hpp | /** @file
@copyright David Mott (c) 2016. Distributed under the Boost Software License Version 1.0. See LICENSE.md or http://boost.org/LICENSE_1_0.txt for details.
*/
#pragma once
namespace wtf {
struct font : private LOGFONT {
using map = std::map<tstring, font>;
font() = delete;
~font() = default;
font(font&&) = default;
font& operator=(font&&) = default;
font& operator=(const font& src) = default;
font(const font &src) noexcept { memcpy(this, &src, sizeof(LOGFONT)); }
font(const LOGFONT &src) noexcept { memcpy(this, &src, sizeof(LOGFONT)); }
enum class weights{
thin = FW_THIN,
extra_light = FW_EXTRALIGHT,
light = FW_LIGHT,
normal = FW_NORMAL,
semi_bold = FW_SEMIBOLD,
bold = FW_BOLD,
extra_bold = FW_EXTRABOLD,
heavy = FW_HEAVY,
black = FW_BLACK,
};
weights weight() const noexcept { return static_cast<weights>(lfWeight); }
void weight(weights newval) noexcept { lfWeight = static_cast<LONG>(newval); }
bool italic() const noexcept { return (lfItalic ? true : false); }
void italic(bool newval) noexcept { lfItalic = (newval ? 1 : 0); }
bool strikeout() const noexcept { return (lfStrikeOut ? true : false); }
void strikeout(bool newval) noexcept { lfStrikeOut = (newval ? 1 : 0); }
bool underline() const noexcept { return (lfUnderline ? true : false); }
void underline(bool newval) noexcept { lfUnderline = (newval ? 1 : 0); }
LONG height() const noexcept { return lfHeight; }
void height(LONG newval) noexcept { lfHeight = newval; }
LONG width() const noexcept { return lfWidth; }
void width(LONG newval) noexcept { lfWidth = newval; }
struct handle : std::unique_ptr<HFONT__, void (*)(HFONT)> {
operator HFONT() const noexcept { return get(); }
~handle() = default;
handle() = delete;
handle(handle &&src) = default;
handle &operator=(handle &&) = default;
handle(const handle&) = delete;
handle &operator=(const handle &) = delete;
static handle ansi_fixed() {
return handle(wtf::exception::throw_lasterr_if((HFONT)
::GetStockObject(ANSI_FIXED_FONT), [](HFONT f) noexcept { return !f; }), [](HFONT) noexcept {});
}
static handle ansi_variable() {
return handle(wtf::exception::throw_lasterr_if((HFONT)
::GetStockObject(ANSI_VAR_FONT), [](HFONT f) noexcept { return !f; }), [](HFONT) noexcept {});
}
static handle device_default() {
return handle(wtf::exception::throw_lasterr_if((HFONT)
::GetStockObject(DEVICE_DEFAULT_FONT), [](HFONT f) noexcept { return !f; }), [](HFONT) noexcept {});
}
static handle gui_default() {
return handle(wtf::exception::throw_lasterr_if((HFONT)
::GetStockObject(DEFAULT_GUI_FONT), [](HFONT f) noexcept { return !f; }), [](HFONT) noexcept {});
}
static handle oem_fixed() {
return handle(wtf::exception::throw_lasterr_if((HFONT)
::GetStockObject(OEM_FIXED_FONT), [](HFONT f) noexcept { return !f; }), [](HFONT) noexcept {});
}
static handle system() {
return handle(wtf::exception::throw_lasterr_if((HFONT)
::GetStockObject(SYSTEM_FONT), [](HFONT f) noexcept { return !f; }), [](HFONT) noexcept {});
}
static handle system_fixed() {
return handle(wtf::exception::throw_lasterr_if((HFONT)
::GetStockObject(SYSTEM_FIXED_FONT), [](HFONT f) noexcept { return !f; }), [](HFONT) noexcept {});
}
protected:
friend struct font;
template<typename ... _ArgTs>
handle(_ArgTs &&...oArgs) noexcept : unique_ptr(std::forward<_ArgTs>(oArgs)...) {}
};
handle open() const {
return handle(wtf::exception::throw_lasterr_if(::CreateFontIndirect(this), [](HFONT f) noexcept { return !f; }),
[](HFONT f) noexcept { ::DeleteObject(f); });
}
protected:
};
}
| [
"mott.david.j@gmail.com"
] | mott.david.j@gmail.com |
bc6ae272cab1eed6b88d2da4114493ed8ad09235 | 4fed64b845eac6df62e6ac8813d2aeff05262f46 | /p2/GrTown/BHLights.h | ec45b8f754d4d5463e6dabe04348fcaf642c3d70 | [] | no_license | xiangzhi/cs559-Fall2014 | a397c2f0e0a318b1e58803354ceb5c1a1bf9caf9 | 9fa59ace18407f22f92024d6e8ee28ece2392ccc | refs/heads/master | 2020-12-07T00:43:31.796307 | 2014-12-13T04:43:15 | 2014-12-13T04:43:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | h | //CS559 - Project 2 - Xiang Zhi Tan
//BHLight.h
//A class that creates a cone of light using surface of revolution
#pragma once
#include "GrObjectVBO.h"
class BHLights :
public GrObjectVBO
{
public:
BHLights();
//it takes in the object it is tracking
BHLights(GrObjectVBO* BH, GrObjectVBO* track);
~BHLights();
GrObjectVBO* BH;
GrObjectVBO* track;
void initializeAfter();
void preDraw(DrawingState* drst);
void draw(DrawingState*, glm::mat4 proj, glm::mat4 view, glm::mat4 model);
void redoSOR();
float rotation = 10;
};
| [
"tan.xiang.zhi@gmail.com"
] | tan.xiang.zhi@gmail.com |
35a00d677a2b6786b20257cd71a138c741490daa | d9c1f9fd6353be7cd2eca1edcd5d15f7ef993d98 | /Qt5/include/QtQml/5.12.2/QtQml/private/qv4instr_moth_p.h | 2ca8f692b86ae28ab4ae4da0485b35e5ba2ca30c | [] | no_license | LuxCoreRender/WindowsCompileDeps | f0e3cdba92880f5340ae9df18c6aa81779cbc2ea | f96d4b5a701679f3222385c1ac099aaf3f0e0be9 | refs/heads/master | 2021-12-28T20:20:19.752792 | 2021-11-25T16:21:17 | 2021-11-25T16:21:17 | 113,448,564 | 3 | 8 | null | 2019-11-06T09:41:07 | 2017-12-07T12:31:38 | C++ | UTF-8 | C++ | false | false | 24,488 | h | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QV4INSTR_MOTH_P_H
#define QV4INSTR_MOTH_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include <private/qv4global_p.h>
#include <private/qv4value_p.h>
#include <private/qv4runtime_p.h>
#include <private/qv4compileddata_p.h> // for CompiledData::CodeOffsetToLine used by the dumper
#include <qendian.h>
QT_BEGIN_NAMESPACE
#define INSTRUCTION(op, name, nargs, ...) \
op##_INSTRUCTION(name, nargs, __VA_ARGS__)
/* for all jump instructions, the offset has to come last, to simplify the job of the bytecode generator */
#define INSTR_Nop(op) INSTRUCTION(op, Nop, 0)
#define INSTR_Ret(op) INSTRUCTION(op, Ret, 0)
#define INSTR_Debug(op) INSTRUCTION(op, Debug, 0)
#define INSTR_LoadConst(op) INSTRUCTION(op, LoadConst, 1, index)
#define INSTR_LoadZero(op) INSTRUCTION(op, LoadZero, 0)
#define INSTR_LoadTrue(op) INSTRUCTION(op, LoadTrue, 0)
#define INSTR_LoadFalse(op) INSTRUCTION(op, LoadFalse, 0)
#define INSTR_LoadNull(op) INSTRUCTION(op, LoadNull, 0)
#define INSTR_LoadUndefined(op) INSTRUCTION(op, LoadUndefined, 0)
#define INSTR_LoadInt(op) INSTRUCTION(op, LoadInt, 1, value)
#define INSTR_MoveConst(op) INSTRUCTION(op, MoveConst, 2, constIndex, destTemp)
#define INSTR_LoadReg(op) INSTRUCTION(op, LoadReg, 1, reg)
#define INSTR_StoreReg(op) INSTRUCTION(op, StoreReg, 1, reg)
#define INSTR_MoveReg(op) INSTRUCTION(op, MoveReg, 2, srcReg, destReg)
#define INSTR_LoadImport(op) INSTRUCTION(op, LoadImport, 1, index)
#define INSTR_LoadLocal(op) INSTRUCTION(op, LoadLocal, 1, index)
#define INSTR_StoreLocal(op) INSTRUCTION(op, StoreLocal, 1, index)
#define INSTR_LoadScopedLocal(op) INSTRUCTION(op, LoadScopedLocal, 2, scope, index)
#define INSTR_StoreScopedLocal(op) INSTRUCTION(op, StoreScopedLocal, 2, scope, index)
#define INSTR_LoadRuntimeString(op) INSTRUCTION(op, LoadRuntimeString, 1, stringId)
#define INSTR_MoveRegExp(op) INSTRUCTION(op, MoveRegExp, 2, regExpId, destReg)
#define INSTR_LoadClosure(op) INSTRUCTION(op, LoadClosure, 1, value)
#define INSTR_LoadName(op) INSTRUCTION(op, LoadName, 1, name)
#define INSTR_LoadGlobalLookup(op) INSTRUCTION(op, LoadGlobalLookup, 1, index)
#define INSTR_StoreNameSloppy(op) INSTRUCTION(op, StoreNameSloppy, 1, name)
#define INSTR_StoreNameStrict(op) INSTRUCTION(op, StoreNameStrict, 1, name)
#define INSTR_LoadProperty(op) INSTRUCTION(op, LoadProperty, 1, name)
#define INSTR_GetLookup(op) INSTRUCTION(op, GetLookup, 1, index)
#define INSTR_LoadScopeObjectProperty(op) INSTRUCTION(op, LoadScopeObjectProperty, 3, propertyIndex, base, captureRequired)
#define INSTR_LoadContextObjectProperty(op) INSTRUCTION(op, LoadContextObjectProperty, 3, propertyIndex, base, captureRequired)
#define INSTR_LoadIdObject(op) INSTRUCTION(op, LoadIdObject, 2, index, base)
#define INSTR_Yield(op) INSTRUCTION(op, Yield, 0)
#define INSTR_YieldStar(op) INSTRUCTION(op, YieldStar, 0)
#define INSTR_Resume(op) INSTRUCTION(op, Resume, 1, offset)
#define INSTR_IteratorNextForYieldStar(op) INSTRUCTION(op, IteratorNextForYieldStar, 2, iterator, object)
#define INSTR_StoreProperty(op) INSTRUCTION(op, StoreProperty, 2, name, base)
#define INSTR_SetLookup(op) INSTRUCTION(op, SetLookup, 2, index, base)
#define INSTR_LoadSuperProperty(op) INSTRUCTION(op, LoadSuperProperty, 1, property)
#define INSTR_StoreSuperProperty(op) INSTRUCTION(op, StoreSuperProperty, 1, property)
#define INSTR_StoreScopeObjectProperty(op) INSTRUCTION(op, StoreScopeObjectProperty, 2, base, propertyIndex)
#define INSTR_StoreContextObjectProperty(op) INSTRUCTION(op, StoreContextObjectProperty, 2, base, propertyIndex)
#define INSTR_LoadElement(op) INSTRUCTION(op, LoadElement, 1, base)
#define INSTR_StoreElement(op) INSTRUCTION(op, StoreElement, 2, base, index)
#define INSTR_CallValue(op) INSTRUCTION(op, CallValue, 3, name, argc, argv)
#define INSTR_CallWithReceiver(op) INSTRUCTION(op, CallWithReceiver, 4, name, thisObject, argc, argv)
#define INSTR_CallProperty(op) INSTRUCTION(op, CallProperty, 4, name, base, argc, argv)
#define INSTR_CallPropertyLookup(op) INSTRUCTION(op, CallPropertyLookup, 4, lookupIndex, base, argc, argv)
#define INSTR_CallElement(op) INSTRUCTION(op, CallElement, 4, base, index, argc, argv)
#define INSTR_CallName(op) INSTRUCTION(op, CallName, 3, name, argc, argv)
#define INSTR_CallPossiblyDirectEval(op) INSTRUCTION(op, CallPossiblyDirectEval, 2, argc, argv)
#define INSTR_CallGlobalLookup(op) INSTRUCTION(op, CallGlobalLookup, 3, index, argc, argv)
#define INSTR_CallScopeObjectProperty(op) INSTRUCTION(op, CallScopeObjectProperty, 4, name, base, argc, argv)
#define INSTR_CallContextObjectProperty(op) INSTRUCTION(op, CallContextObjectProperty, 4, name, base, argc, argv)
#define INSTR_CallWithSpread(op) INSTRUCTION(op, CallWithSpread, 4, func, thisObject, argc, argv)
#define INSTR_Construct(op) INSTRUCTION(op, Construct, 3, func, argc, argv)
#define INSTR_ConstructWithSpread(op) INSTRUCTION(op, ConstructWithSpread, 3, func, argc, argv)
#define INSTR_SetUnwindHandler(op) INSTRUCTION(op, SetUnwindHandler, 1, offset)
#define INSTR_UnwindDispatch(op) INSTRUCTION(op, UnwindDispatch, 0)
#define INSTR_UnwindToLabel(op) INSTRUCTION(op, UnwindToLabel, 2, level, offset)
#define INSTR_DeadTemporalZoneCheck(op) INSTRUCTION(op, DeadTemporalZoneCheck, 1, name)
#define INSTR_ThrowException(op) INSTRUCTION(op, ThrowException, 0)
#define INSTR_GetException(op) INSTRUCTION(op, GetException, 0)
#define INSTR_SetException(op) INSTRUCTION(op, SetException, 0)
#define INSTR_CreateCallContext(op) INSTRUCTION(op, CreateCallContext, 0)
#define INSTR_PushCatchContext(op) INSTRUCTION(op, PushCatchContext, 2, index, name)
#define INSTR_PushWithContext(op) INSTRUCTION(op, PushWithContext, 0)
#define INSTR_PushBlockContext(op) INSTRUCTION(op, PushBlockContext, 1, index)
#define INSTR_CloneBlockContext(op) INSTRUCTION(op, CloneBlockContext, 0)
#define INSTR_PushScriptContext(op) INSTRUCTION(op, PushScriptContext, 1, index)
#define INSTR_PopScriptContext(op) INSTRUCTION(op, PopScriptContext, 0)
#define INSTR_PopContext(op) INSTRUCTION(op, PopContext, 0)
#define INSTR_GetIterator(op) INSTRUCTION(op, GetIterator, 1, iterator)
#define INSTR_IteratorNext(op) INSTRUCTION(op, IteratorNext, 2, value, done)
#define INSTR_IteratorClose(op) INSTRUCTION(op, IteratorClose, 1, done)
#define INSTR_DestructureRestElement(op) INSTRUCTION(op, DestructureRestElement, 0)
#define INSTR_DeleteProperty(op) INSTRUCTION(op, DeleteProperty, 2, base, index)
#define INSTR_DeleteName(op) INSTRUCTION(op, DeleteName, 1, name)
#define INSTR_TypeofName(op) INSTRUCTION(op, TypeofName, 1, name)
#define INSTR_TypeofValue(op) INSTRUCTION(op, TypeofValue, 0)
#define INSTR_DeclareVar(op) INSTRUCTION(op, DeclareVar, 2, varName, isDeletable)
#define INSTR_DefineArray(op) INSTRUCTION(op, DefineArray, 2, argc, args)
#define INSTR_DefineObjectLiteral(op) INSTRUCTION(op, DefineObjectLiteral, 3, internalClassId, argc, args)
#define INSTR_CreateClass(op) INSTRUCTION(op, CreateClass, 3, classIndex, heritage, computedNames)
#define INSTR_CreateMappedArgumentsObject(op) INSTRUCTION(op, CreateMappedArgumentsObject, 0)
#define INSTR_CreateUnmappedArgumentsObject(op) INSTRUCTION(op, CreateUnmappedArgumentsObject, 0)
#define INSTR_CreateRestParameter(op) INSTRUCTION(op, CreateRestParameter, 1, argIndex)
#define INSTR_ConvertThisToObject(op) INSTRUCTION(op, ConvertThisToObject, 0)
#define INSTR_LoadSuperConstructor(op) INSTRUCTION(op, LoadSuperConstructor, 0)
#define INSTR_ToObject(op) INSTRUCTION(op, ToObject, 0)
#define INSTR_Jump(op) INSTRUCTION(op, Jump, 1, offset)
#define INSTR_JumpTrue(op) INSTRUCTION(op, JumpTrue, 1, offset)
#define INSTR_JumpFalse(op) INSTRUCTION(op, JumpFalse, 1, offset)
#define INSTR_JumpNotUndefined(op) INSTRUCTION(op, JumpNotUndefined, 1, offset)
#define INSTR_JumpNoException(op) INSTRUCTION(op, JumpNoException, 1, offset)
#define INSTR_CmpEqNull(op) INSTRUCTION(op, CmpEqNull, 0)
#define INSTR_CmpNeNull(op) INSTRUCTION(op, CmpNeNull, 0)
#define INSTR_CmpEqInt(op) INSTRUCTION(op, CmpEqInt, 1, lhs)
#define INSTR_CmpNeInt(op) INSTRUCTION(op, CmpNeInt, 1, lhs)
#define INSTR_CmpEq(op) INSTRUCTION(op, CmpEq, 1, lhs)
#define INSTR_CmpNe(op) INSTRUCTION(op, CmpNe, 1, lhs)
#define INSTR_CmpGt(op) INSTRUCTION(op, CmpGt, 1, lhs)
#define INSTR_CmpGe(op) INSTRUCTION(op, CmpGe, 1, lhs)
#define INSTR_CmpLt(op) INSTRUCTION(op, CmpLt, 1, lhs)
#define INSTR_CmpLe(op) INSTRUCTION(op, CmpLe, 1, lhs)
#define INSTR_CmpStrictEqual(op) INSTRUCTION(op, CmpStrictEqual, 1, lhs)
#define INSTR_CmpStrictNotEqual(op) INSTRUCTION(op, CmpStrictNotEqual, 1, lhs)
#define INSTR_CmpIn(op) INSTRUCTION(op, CmpIn, 1, lhs)
#define INSTR_CmpInstanceOf(op) INSTRUCTION(op, CmpInstanceOf, 1, lhs)
#define INSTR_UNot(op) INSTRUCTION(op, UNot, 0)
#define INSTR_UPlus(op) INSTRUCTION(op, UPlus, 0)
#define INSTR_UMinus(op) INSTRUCTION(op, UMinus, 0)
#define INSTR_UCompl(op) INSTRUCTION(op, UCompl, 0)
#define INSTR_Increment(op) INSTRUCTION(op, Increment, 0)
#define INSTR_Decrement(op) INSTRUCTION(op, Decrement, 0)
#define INSTR_Add(op) INSTRUCTION(op, Add, 1, lhs)
#define INSTR_BitAnd(op) INSTRUCTION(op, BitAnd, 1, lhs)
#define INSTR_BitOr(op) INSTRUCTION(op, BitOr, 1, lhs)
#define INSTR_BitXor(op) INSTRUCTION(op, BitXor, 1, lhs)
#define INSTR_UShr(op) INSTRUCTION(op, UShr, 1, lhs)
#define INSTR_Shr(op) INSTRUCTION(op, Shr, 1, lhs)
#define INSTR_Shl(op) INSTRUCTION(op, Shl, 1, lhs)
#define INSTR_BitAndConst(op) INSTRUCTION(op, BitAndConst, 1, rhs)
#define INSTR_BitOrConst(op) INSTRUCTION(op, BitOrConst, 1, rhs)
#define INSTR_BitXorConst(op) INSTRUCTION(op, BitXorConst, 1, rhs)
#define INSTR_UShrConst(op) INSTRUCTION(op, UShrConst, 1, rhs)
#define INSTR_ShrConst(op) INSTRUCTION(op, ShrConst, 1, rhs)
#define INSTR_ShlConst(op) INSTRUCTION(op, ShlConst, 1, rhs)
#define INSTR_Exp(op) INSTRUCTION(op, Exp, 1, lhs)
#define INSTR_Mul(op) INSTRUCTION(op, Mul, 1, lhs)
#define INSTR_Div(op) INSTRUCTION(op, Div, 1, lhs)
#define INSTR_Mod(op) INSTRUCTION(op, Mod, 1, lhs)
#define INSTR_Sub(op) INSTRUCTION(op, Sub, 1, lhs)
#define INSTR_LoadQmlContext(op) INSTRUCTION(op, LoadQmlContext, 1, result)
#define INSTR_LoadQmlImportedScripts(op) INSTRUCTION(op, LoadQmlImportedScripts, 1, result)
#define INSTR_InitializeBlockDeadTemporalZone(op) INSTRUCTION(op, InitializeBlockDeadTemporalZone, 2, firstReg, count)
#define INSTR_ThrowOnNullOrUndefined(op) INSTRUCTION(op, ThrowOnNullOrUndefined, 0)
#define INSTR_GetTemplateObject(op) INSTRUCTION(op, GetTemplateObject, 1, index)
#define INSTR_TailCall(op) INSTRUCTION(op, TailCall, 4, func, thisObject, argc, argv)
#define FOR_EACH_MOTH_INSTR_ALL(F) \
F(Nop) \
FOR_EACH_MOTH_INSTR(F)
#define FOR_EACH_MOTH_INSTR(F) \
F(Ret) \
F(LoadConst) \
F(LoadZero) \
F(LoadTrue) \
F(LoadFalse) \
F(LoadNull) \
F(LoadUndefined) \
F(LoadInt) \
F(LoadRuntimeString) \
F(MoveConst) \
F(LoadReg) \
F(StoreReg) \
F(MoveReg) \
F(LoadImport) \
F(LoadLocal) \
F(StoreLocal) \
F(LoadScopedLocal) \
F(StoreScopedLocal) \
F(MoveRegExp) \
F(LoadClosure) \
F(LoadName) \
F(LoadGlobalLookup) \
F(StoreNameSloppy) \
F(StoreNameStrict) \
F(LoadElement) \
F(StoreElement) \
F(LoadProperty) \
F(GetLookup) \
F(StoreProperty) \
F(SetLookup) \
F(LoadSuperProperty) \
F(StoreSuperProperty) \
F(StoreScopeObjectProperty) \
F(StoreContextObjectProperty) \
F(LoadScopeObjectProperty) \
F(LoadContextObjectProperty) \
F(LoadIdObject) \
F(ConvertThisToObject) \
F(ToObject) \
F(Jump) \
F(JumpTrue) \
F(JumpFalse) \
F(JumpNoException) \
F(JumpNotUndefined) \
F(CmpEqNull) \
F(CmpNeNull) \
F(CmpEqInt) \
F(CmpNeInt) \
F(CmpEq) \
F(CmpNe) \
F(CmpGt) \
F(CmpGe) \
F(CmpLt) \
F(CmpLe) \
F(CmpStrictEqual) \
F(CmpStrictNotEqual) \
F(CmpIn) \
F(CmpInstanceOf) \
F(UNot) \
F(UPlus) \
F(UMinus) \
F(UCompl) \
F(Increment) \
F(Decrement) \
F(Add) \
F(BitAnd) \
F(BitOr) \
F(BitXor) \
F(UShr) \
F(Shr) \
F(Shl) \
F(BitAndConst) \
F(BitOrConst) \
F(BitXorConst) \
F(UShrConst) \
F(ShrConst) \
F(ShlConst) \
F(Exp) \
F(Mul) \
F(Div) \
F(Mod) \
F(Sub) \
F(CallValue) \
F(CallWithReceiver) \
F(CallProperty) \
F(CallPropertyLookup) \
F(CallElement) \
F(CallName) \
F(CallPossiblyDirectEval) \
F(CallGlobalLookup) \
F(CallScopeObjectProperty) \
F(CallContextObjectProperty) \
F(CallWithSpread) \
F(Construct) \
F(ConstructWithSpread) \
F(SetUnwindHandler) \
F(UnwindDispatch) \
F(UnwindToLabel) \
F(DeadTemporalZoneCheck) \
F(ThrowException) \
F(GetException) \
F(SetException) \
F(CreateCallContext) \
F(PushCatchContext) \
F(PushWithContext) \
F(PushBlockContext) \
F(CloneBlockContext) \
F(PopContext) \
F(GetIterator) \
F(IteratorNext) \
F(IteratorClose) \
F(DestructureRestElement) \
F(DeleteProperty) \
F(DeleteName) \
F(TypeofName) \
F(TypeofValue) \
F(DeclareVar) \
F(DefineArray) \
F(DefineObjectLiteral) \
F(CreateMappedArgumentsObject) \
F(CreateUnmappedArgumentsObject) \
F(CreateRestParameter) \
F(LoadQmlContext) \
F(LoadQmlImportedScripts) \
F(Yield) \
F(YieldStar) \
F(Resume) \
F(IteratorNextForYieldStar) \
F(CreateClass) \
F(LoadSuperConstructor) \
F(PushScriptContext) \
F(PopScriptContext) \
F(InitializeBlockDeadTemporalZone) \
F(ThrowOnNullOrUndefined) \
F(GetTemplateObject) \
F(TailCall) \
F(Debug) \
#define MOTH_NUM_INSTRUCTIONS() (static_cast<int>(Moth::Instr::Type::Debug_Wide) + 1)
#if defined(Q_CC_GNU) && !defined(Q_CC_INTEL)
// icc before version 1200 doesn't support computed goto, and at least up to version 18.0.0 the
// current use results in an internal compiler error. We could enable this if/when it gets fixed
// in a later version.
# define MOTH_COMPUTED_GOTO
#endif
#define MOTH_INSTR_ALIGN_MASK (Q_ALIGNOF(QV4::Moth::Instr) - 1)
#define MOTH_INSTR_ENUM(I) I, I##_Wide,
#define MOTH_INSTR_SIZE(I) (sizeof(QV4::Moth::Instr::instr_##I))
#define MOTH_EXPAND_FOR_MSVC(x) x
#define MOTH_DEFINE_ARGS(nargs, ...) \
MOTH_EXPAND_FOR_MSVC(MOTH_DEFINE_ARGS##nargs(__VA_ARGS__))
#define MOTH_DEFINE_ARGS0()
#define MOTH_DEFINE_ARGS1(arg) \
int arg;
#define MOTH_DEFINE_ARGS2(arg1, arg2) \
int arg1; \
int arg2;
#define MOTH_DEFINE_ARGS3(arg1, arg2, arg3) \
int arg1; \
int arg2; \
int arg3;
#define MOTH_DEFINE_ARGS4(arg1, arg2, arg3, arg4) \
int arg1; \
int arg2; \
int arg3; \
int arg4;
#define MOTH_COLLECT_ENUMS(instr) \
INSTR_##instr(MOTH_GET_ENUM)
#define MOTH_GET_ENUM_INSTRUCTION(name, ...) \
name,
#define MOTH_EMIT_STRUCTS(instr) \
INSTR_##instr(MOTH_EMIT_STRUCT)
#define MOTH_EMIT_STRUCT_INSTRUCTION(name, nargs, ...) \
struct instr_##name { \
MOTH_DEFINE_ARGS(nargs, __VA_ARGS__) \
};
#define MOTH_EMIT_INSTR_MEMBERS(instr) \
INSTR_##instr(MOTH_EMIT_INSTR_MEMBER)
#define MOTH_EMIT_INSTR_MEMBER_INSTRUCTION(name, nargs, ...) \
instr_##name name;
#define MOTH_COLLECT_NARGS(instr) \
INSTR_##instr(MOTH_COLLECT_ARG_COUNT)
#define MOTH_COLLECT_ARG_COUNT_INSTRUCTION(name, nargs, ...) \
nargs, nargs,
#define MOTH_DECODE_ARG(arg, type, nargs, offset) \
arg = qFromLittleEndian<type>(qFromUnaligned<type>(reinterpret_cast<const type *>(code) - nargs + offset));
#define MOTH_ADJUST_CODE(type, nargs) \
code += static_cast<quintptr>(nargs*sizeof(type) + 1)
#define MOTH_DECODE_INSTRUCTION(name, nargs, ...) \
MOTH_DEFINE_ARGS(nargs, __VA_ARGS__) \
op_int_##name: \
MOTH_ADJUST_CODE(int, nargs); \
MOTH_DECODE_ARGS(name, int, nargs, __VA_ARGS__) \
goto op_main_##name; \
op_byte_##name: \
MOTH_ADJUST_CODE(qint8, nargs); \
MOTH_DECODE_ARGS(name, qint8, nargs, __VA_ARGS__) \
op_main_##name: \
; \
#define MOTH_DECODE_WITH_BASE_INSTRUCTION(name, nargs, ...) \
MOTH_DEFINE_ARGS(nargs, __VA_ARGS__) \
const char *base_ptr; \
op_int_##name: \
base_ptr = code; \
MOTH_ADJUST_CODE(int, nargs); \
MOTH_DECODE_ARGS(name, int, nargs, __VA_ARGS__) \
goto op_main_##name; \
op_byte_##name: \
base_ptr = code; \
MOTH_ADJUST_CODE(qint8, nargs); \
MOTH_DECODE_ARGS(name, qint8, nargs, __VA_ARGS__) \
op_main_##name: \
; \
#define MOTH_DECODE_ARGS(name, type, nargs, ...) \
MOTH_EXPAND_FOR_MSVC(MOTH_DECODE_ARGS##nargs(name, type, nargs, __VA_ARGS__))
#define MOTH_DECODE_ARGS0(name, type, nargs, dummy)
#define MOTH_DECODE_ARGS1(name, type, nargs, arg) \
MOTH_DECODE_ARG(arg, type, nargs, 0);
#define MOTH_DECODE_ARGS2(name, type, nargs, arg1, arg2) \
MOTH_DECODE_ARGS1(name, type, nargs, arg1); \
MOTH_DECODE_ARG(arg2, type, nargs, 1);
#define MOTH_DECODE_ARGS3(name, type, nargs, arg1, arg2, arg3) \
MOTH_DECODE_ARGS2(name, type, nargs, arg1, arg2); \
MOTH_DECODE_ARG(arg3, type, nargs, 2);
#define MOTH_DECODE_ARGS4(name, type, nargs, arg1, arg2, arg3, arg4) \
MOTH_DECODE_ARGS3(name, type, nargs, arg1, arg2, arg3); \
MOTH_DECODE_ARG(arg4, type, nargs, 3);
#ifdef MOTH_COMPUTED_GOTO
/* collect jump labels */
#define COLLECT_LABELS(instr) \
INSTR_##instr(GET_LABEL) \
INSTR_##instr(GET_LABEL_WIDE)
#define GET_LABEL_INSTRUCTION(name, ...) \
&&op_byte_##name,
#define GET_LABEL_WIDE_INSTRUCTION(name, ...) \
&&op_int_##name,
#define MOTH_JUMP_TABLE \
static const void *jumpTable[] = { \
FOR_EACH_MOTH_INSTR_ALL(COLLECT_LABELS) \
};
#define MOTH_DISPATCH_SINGLE() \
goto *jumpTable[*reinterpret_cast<const uchar *>(code)];
#define MOTH_DISPATCH() \
MOTH_DISPATCH_SINGLE() \
op_byte_Nop: \
++code; \
MOTH_DISPATCH_SINGLE() \
op_int_Nop: /* wide prefix */ \
++code; \
goto *jumpTable[0x100 | *reinterpret_cast<const uchar *>(code)];
#else
#define MOTH_JUMP_TABLE
#define MOTH_INSTR_CASE_AND_JUMP(instr) \
INSTR_##instr(GET_CASE_AND_JUMP) \
INSTR_##instr(GET_CASE_AND_JUMP_WIDE)
#define GET_CASE_AND_JUMP_INSTRUCTION(name, ...) \
case Instr::Type::name: goto op_byte_##name;
#define GET_CASE_AND_JUMP_WIDE_INSTRUCTION(name, ...) \
case Instr::Type::name##_Wide: goto op_int_##name;
#define MOTH_DISPATCH() \
Instr::Type type = Instr::Type(static_cast<uchar>(*code)); \
dispatch: \
switch (type) { \
case Instr::Type::Nop: \
++code; \
type = Instr::Type(static_cast<uchar>(*code)); \
goto dispatch; \
case Instr::Type::Nop_Wide: /* wide prefix */ \
++code; \
type = Instr::Type(0x100 | static_cast<uchar>(*code)); \
goto dispatch; \
FOR_EACH_MOTH_INSTR(MOTH_INSTR_CASE_AND_JUMP) \
}
#endif
namespace QV4 {
namespace CompiledData {
struct CodeOffsetToLine;
}
namespace Moth {
class StackSlot {
int index;
public:
static StackSlot createRegister(int index) {
Q_ASSERT(index >= 0);
StackSlot t;
t.index = index;
return t;
}
int stackSlot() const { return index; }
operator int() const { return index; }
};
inline bool operator==(const StackSlot &l, const StackSlot &r) { return l.stackSlot() == r.stackSlot(); }
inline bool operator!=(const StackSlot &l, const StackSlot &r) { return l.stackSlot() != r.stackSlot(); }
// When making changes to the instructions, make sure to bump QV4_DATA_STRUCTURE_VERSION in qv4compileddata_p.h
void dumpConstantTable(const Value *constants, uint count);
void dumpBytecode(const char *bytecode, int len, int nLocals, int nFormals, int startLine = 1,
const QVector<CompiledData::CodeOffsetToLine> &lineNumberMapping = QVector<CompiledData::CodeOffsetToLine>());
inline void dumpBytecode(const QByteArray &bytecode, int nLocals, int nFormals, int startLine = 1,
const QVector<CompiledData::CodeOffsetToLine> &lineNumberMapping = QVector<CompiledData::CodeOffsetToLine>()) {
dumpBytecode(bytecode.constData(), bytecode.length(), nLocals, nFormals, startLine, lineNumberMapping);
}
union Instr
{
enum class Type {
FOR_EACH_MOTH_INSTR_ALL(MOTH_INSTR_ENUM)
};
static Type wideInstructionType(Type t) { return Type(int(t) | 1); }
static Type narrowInstructionType(Type t) { return Type(int(t) & ~1); }
static bool isWide(Type t) { return int(t) & 1; }
static bool isNarrow(Type t) { return !(int(t) & 1); }
static int encodedLength(Type t) { return int(t) >= 256 ? 2 : 1; }
static Type unpack(const uchar *c) { if (c[0] == 0x1) return Type(0x100 + c[1]); return Type(c[0]); }
static uchar *pack(uchar *c, Type t) {
if (uint(t) >= 256) {
c[0] = 0x1;
c[1] = uint(t) &0xff;
return c + 2;
}
c[0] = uchar(uint(t));
return c + 1;
}
FOR_EACH_MOTH_INSTR_ALL(MOTH_EMIT_STRUCTS)
FOR_EACH_MOTH_INSTR_ALL(MOTH_EMIT_INSTR_MEMBERS)
int argumentsAsInts[4];
};
struct InstrInfo
{
static const int argumentCount[];
static int size(Instr::Type type);
};
template<int N>
struct InstrMeta {
};
QT_WARNING_PUSH
QT_WARNING_DISABLE_GCC("-Wuninitialized")
QT_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
#define MOTH_INSTR_META_TEMPLATE(I) \
template<> struct InstrMeta<int(Instr::Type::I)> { \
enum { Size = MOTH_INSTR_SIZE(I) }; \
typedef Instr::instr_##I DataType; \
static const DataType &data(const Instr &instr) { return instr.I; } \
static void setData(Instr &instr, const DataType &v) \
{ memcpy(reinterpret_cast<char *>(&instr.I), \
reinterpret_cast<const char *>(&v), \
Size); } \
};
FOR_EACH_MOTH_INSTR_ALL(MOTH_INSTR_META_TEMPLATE);
#undef MOTH_INSTR_META_TEMPLATE
QT_WARNING_POP
template<int InstrType>
class InstrData : public InstrMeta<InstrType>::DataType
{
};
struct Instruction {
#define MOTH_INSTR_DATA_TYPEDEF(I) typedef InstrData<int(Instr::Type::I)> I;
FOR_EACH_MOTH_INSTR_ALL(MOTH_INSTR_DATA_TYPEDEF)
#undef MOTH_INSTR_DATA_TYPEDEF
private:
Instruction();
};
} // namespace Moth
} // namespace QV4
QT_END_NAMESPACE
#endif // QV4INSTR_MOTH_P_H
| [
"35339386+acasta69@users.noreply.github.com"
] | 35339386+acasta69@users.noreply.github.com |
8b9df7bee20272be3e6da1b729166e5a38a3aab2 | e2dd3667a2d702d0f1c94ffa181003cde7ea80e6 | /Level_4/Homework/Section_2_5/Exercise_3/Array.cpp | 58e5a3078277e17ce823299e3cba2913c55e108c | [] | no_license | jeffsnguyen/Quantnet_Cplusplus | b413cd56d6a1e4b102bcc9428db6c637d0605321 | 4304019fb64f4ae2c00dd5bbc8e3792c31e544e2 | refs/heads/master | 2023-07-20T15:20:47.188271 | 2021-09-06T03:15:23 | 2021-09-06T03:15:23 | 368,723,670 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,738 | cpp | // Type: Homework
// Level: 4
// Section: 2.4 Basic Operators Overloading
// Exercise: 3
// Description: Source file contains functionalities for class Array()
// It is easy to forget to delete memory created with new.
// A good practice is to let a class manage memory.
// Then the client of that class does not have to manage memory and can’t forget to delete memory.
// So instead of creating a C array with new, you can use an array class that handle memory for you.
// In this exercise we are going to create an array class for Point objects (see Figure 5):
// • Add a source- and header file for the Array class to your current project.
// • Add a data member for a dynamic C array of Point objects (Point* m_data).
// • Add a data member for the size of the array.
// • Add a default constructor that allocates for example 10 elements.
// • Add a constructor with a size argument. The implementation should allocate
// the number of elements specified by thesize input argument.
// • Add a copy constructor. Keep in mind that just copying the C array pointer
// will create an Array object that shares the data with the original Array object.
// Thus you need to allocate a new C array with the same size and copy each element separately.
// • Add a destructor. It should delete the internal C array. Don’t forget the square brackets.
// • Add an assignment operator.
// Keep in mind you can’t copy only the C array pointers just as in the case of the copy constructor.
// • Also don’t forget to delete the old C array and
// allocate new memory before copying the elements. This is because C arrays can’t grow.
//
// Further check if the source object is not the same as the this object.
// If you don’t check it, then a statement like arr1=arr1 will go wrong.
// The internal C array will then be deleted before it is copied.
// • Add a Size() function that returns the size of the array.
// • Add a SetElement() function that sets an element.
// When the index is out of bounds, ignore the “set”. We will add better error handling later.
// • Add a GetElement() function.
// You can return the element by reference since the returned element
// has a longer lifetime than the GetElement() function.
// When the index is out of bounds, return the first element.
// We will add better error handling later.
// • You can also add a square bracket operator.
// Return a reference so the [] operator can be used for both reading and writing elements.
// When the index is out of bounds, return the first element. We will add better error handling later.
// Point& operator [] (int index);
// • In the main program, test the Array class.
/*---------------------------------*/
#include "Point.hpp"
#include "Array.hpp"
#include <iostream>
#include <sstream>
#include <cmath>
using namespace std;
/*---------------------------------*/
// Initializing a dynamic array of 10 elements
Array::Array(): m_data(new Point[10]), m_size(10)
{
cout << "Default array created" << endl;
}
// Initialize array with newSize number of elements
Array::Array(int newSize): m_data(new Point[newSize]), m_size(newSize)
{
cout << "Array created." << endl;
}
// Copy Constructor
Array::Array(const Array& array): m_data(new Point[array.m_size]), m_size(array.m_size)
{
cout << "Copy constructor called." << endl;
for (int idx=0; idx<m_size; idx++)
{
m_data[idx] = array.m_data[idx];
cout << "arr[" << idx << "] = " << m_data[idx] << endl;
}
}
// Destructor
Array::~Array()
{
delete[] m_data;
cout << "Array destroyed.\n";
}
// Returns the size of the array
const int& Array::Size() const
{
return m_size;
}
// Set an element of the array based on the index
// Check if idx is out-of-bound, if so, display on-screen notification
void Array::SetElement(int idx, const Point& point)
{
if (idx < m_size && !(idx < 0))
{
m_data[idx] = point;
}
else
{
cout << "Index out-of-bound. Nothing done." << endl;
}
}
// Get an element based on its array index
const Point& Array::GetElement(int idx) const
{
if (idx < m_size && !(idx < 0))
{
return m_data[idx];
}
else
{
cout << "Index out-of-bound. Returning the first element." << endl;
return m_data[0];
}
}
// Assignment operator.
Array& Array::operator = (const Array& source)
{
// Self-assignment preclusion
if (this == &source)
{
return *this;
}
else
{
delete[] m_data; // Clean up old array before assignment
m_data = new Point[source.m_size];
m_size = source.m_size;
for (int idx=0; idx<m_size; idx++)
{
m_data[idx] = source.m_data[idx];
}
return *this; // Assign the result to itself
}
}
// Return a reference so the [] operator can be used for both reading and writing elements.
// When the index is out of bounds, return the first element.
Point& Array::operator [] (int idx)
{
if (idx < m_size && !(idx <0))
{
return m_data[idx];
}
else
{
cout << "Index out-of-bound. Returning the first element." << endl;
return m_data[0];
}
}
// Return a reference so the [] operator can be used for both reading and writing elements.
// When the index is out of bounds, return the first element.
// Necessary when you want to read-only
const Point& Array::operator [] (int idx) const
{
if (idx < m_size && !(idx <0))
{
return m_data[idx];
}
else
{
cout << "Index out-of-bound. Returning the first element." << endl;
return m_data[0];
}
} | [
"son.jeff.nguyen@gmail.com"
] | son.jeff.nguyen@gmail.com |
5df0f31570b707b9a55248b4d08e1811ca478748 | 2f9a425e8f5d034da4d35c9f941ff609cb232883 | /poj/2945/POJ_2945_2386755_AC_1421MS_1640K.cpp | f66abd77f9e3ab0d73e983d3775d7e6a1333b326 | [] | no_license | wangyongliang/nova | baac90cd8e7bdb03c6c5916fbab9675dabf49af5 | 86b00b1a12f1cc6291635f31a33e791f6fb19d1a | refs/heads/master | 2022-02-18T05:35:02.447764 | 2019-09-08T02:22:06 | 2019-09-08T02:22:06 | 10,247,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 523 | cpp | #include<iostream>
#include<map>
#include<string>
#include<memory>
using namespace std;
string name[20000];
int out[20001];
int main()
{
int n,m,c;
string str;
map<string,int> mp;
while(cin >> n >> m && m+n){
mp.clear();
c = 0;
for(int i = 0; i < n; i++){
cin >> str;
if(mp[str] == 0)
name[c++] = str;
mp[str]++;
}
memset(out,0,sizeof(out));
for(i = 0; i < c; i++){
out[mp[name[i]]]++;
}
for(i = 1; i <= n; i++)
cout << out[i] << endl;
}
return 0;
}
| [
"wangyongliang.wyl@gmail.com"
] | wangyongliang.wyl@gmail.com |
ca3846eaacb39b0c54c53eac286eb8653cafcf69 | f66f564631e5971978572306023a7641956e3052 | /ps/ps/geometric_calibration.cpp | 89569d86c9d83405e8acb87ed0f4e3af5ac9992b | [] | no_license | sophie-greene/c-CompVis | d777a347f27beaa940eed44ec5f82f6bf6a4bb7b | 48d2a78f5c2471dc9c7442f22bd3d84e739678aa | refs/heads/master | 2020-07-01T17:05:40.798036 | 2016-11-20T12:13:43 | 2016-11-20T12:13:43 | 74,271,732 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,608 | cpp |
#include "geometric_calibration.h"
#define CAM_NUM 8
using namespace std;
//using namespace cv;
/****************************************************************
Read camera matrix and distorsion coefficients from file
Input:
file_name: file.yml
cameraMatrix: cv::Mat where to store the camera matrix
distCoeffs: cv::Mat where to store the distorsion coefficients
*****************************************************************/
void read_intrinsic_parameters(string file_name, cv::Mat &cameraMatrix, cv::Mat &distCoeffs) {
cv::FileStorage fs(file_name.c_str(), cv::FileStorage::READ);
fs["cameraMatrix"] >> cameraMatrix;
fs["DistCoeffs"] >> distCoeffs;
//cout << "camera matrix: " << cameraMatrix << endl
// << "distortion coeffs: " << distCoeffs << endl;
fs.release();
}
/****************************************************************
Read rotation matrix and translation vector from file
Input:
file_name: file.yml
trans: cv::Mat where to store the translation vector
rot: cv::Mat where to store the rotation matrix
*****************************************************************/
void read_extrinsic_parameters(string file_name,cv::Mat &trans, cv::Mat &rot) {
cv::FileStorage fs(file_name.c_str(), cv::FileStorage::READ);
fs["translationVector"] >> trans;
fs["rotationMatrix"] >> rot;
//cout << "rotation matrix: " << rot << endl
// << "translation vector: " << trans << endl;
fs.release();
}
/*******************************************************************
Fucntion that call the above functions to real all information
related the the camera calibration.
Input:
path: path to the .yml files where to find the calibration information
Output:
cam_paramas_t structure vector containing the intrinsics and extrinsics
and the position for each camera
****************************************************************/
vector<cam_params_t> read_cameras_calibration(string path) {
string heading = "cam";
string intrinsic = "Intrinsics.yml";
string extrinsic = "Extrinsic.yml";
string filename;
vector<cam_params_t> params_list;
for (int i = 0; i < CAM_NUM; i++) {
cam_params_t params;
stringstream ss;
ss << i;
string counter = ss.str();
filename = heading + counter + intrinsic;
read_intrinsic_parameters(path+filename, params.cam, params.dist);
filename = heading + counter + extrinsic;
read_extrinsic_parameters(path+filename, params.trans, params.rot);
params.pos = -params.rot.t() * params.trans;
params_list.push_back(params);
//cout << "position: " << params.pos << endl;
}
return params_list;
}
| [
"eng.s.green@gmail.com"
] | eng.s.green@gmail.com |
84607e8f3c55b01754047e1cce37bf87a402fea7 | 37ef8e3de7defdc1ec2658c26f5711b16f0dd66d | /GoogleTests/GoogleTests/Sector_containerTest.cpp | 6e19b9cfd51b3f1348d43abc9262fe35346d7635 | [] | no_license | hohlov06/CPP_for_Kuchin | 57d950fd1bddadacf9d22c44a2be924e1977e87b | fb1d598d94bb7f42c72474dc19af1f407eca7878 | refs/heads/master | 2020-04-24T10:14:26.243155 | 2019-06-11T16:42:48 | 2019-06-11T16:42:48 | 171,887,001 | 1 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 5,023 | cpp | #include "pch.h"
// Для запуска этого файла раскомментировать , если закомментировано
// Закомментировать во всех остальных cpp всё, что ниже #include "pch.h"
// либо исключить из проекта все остальные cpp
//
//#include "../../Sector_container/Sector_container/SectorContainer.h"
//
//
//#include <iostream>
//#include <utility>
//#include <vector>
//
//using namespace std;
//
//template <bool flag>
//class TestCase
//{
//public:
// SectorContainer<flag>& cont;
// TestCase(SectorContainer<flag>& cont_) : cont(cont_)
// {
// cont.clear();
// cont.add({ 0,5 });
// cont.add({ 12,12 });
// cont.add({ 6,9 });
// cont.add({ 20,30 });
// cont.add({40,100000});
// cont.print();
// }
//
// void step_one()
// {
// cont.add({ -99,-90 });
// cont.add({ -80,-70 });
// cont.add({ -60,-50 });
// cont.add({ -40,-30 });
// cont.add({ -20,-10 });
// cont.add({ -100, -20 });
// cont.add({ -99, -21 });
// cont.print();
// }
//
// void step_two()
// {
// cont.add({ -5,-1 });
// cont.add({ -1,0 });
// cont.add({ 5,6 });
// cont.add({ 5,5 });
// cont.add({12 , 12});
// cont.print();
// }
//
// ~TestCase()
// {
// cont.clear();
// }
//};
//
//
//TEST(WithExceptionTests, Exceptions)
//{
// SectorContainer<true> cont;
// TestCase<true> qwe(cont);
//
// ASSERT_THROW(cont.add({0,2}), std::domain_error);
// ASSERT_THROW(cont.add({2,2}), std::domain_error);
// ASSERT_THROW(cont.add({12,12}), std::domain_error);
// ASSERT_THROW(cont.add({ -1,10 }), std::domain_error);
// ASSERT_THROW(cont.add({ 5,6 }), std::domain_error);
// ASSERT_THROW(cont.add({ 1,2 }), std::domain_error);
// ASSERT_THROW(cont.add({-1, 100000000}), std::domain_error);
//}
//
//TEST(WithExceptionTests, findFunction)
//{
// SectorContainer<true> cont;
// TestCase<true> qwe(cont);
//
// EXPECT_EQ(sector(*cont.find(0) ), sector(0,5));
// EXPECT_EQ(sector(*cont.find(2) ), sector(0,5));
// EXPECT_EQ(sector(*cont.find(5) ), sector(0,5));
// EXPECT_EQ(sector(*cont.find(6) ), sector(6,9));
// EXPECT_EQ(sector(*cont.find(9) ), sector(6,9));
// EXPECT_EQ(sector(*cont.find(50)), sector(40, 100000));
// EXPECT_EQ(cont.find(-1), cont.end());
// EXPECT_EQ(cont.find(10), cont.end());
// EXPECT_EQ(cont.find(11), cont.end());
// EXPECT_EQ(cont.find(15), cont.end());
// EXPECT_EQ(cont.find(100001), cont.end());
// EXPECT_EQ(cont.find(35), cont.end());
//}
//
//
//TEST(NoExceptionTests, mergeTest)
//{
// SectorContainer<false> cont;
// TestCase<false> qwe(cont);
// qwe.step_one();
// EXPECT_EQ(sector(*cont.begin()), sector(-100,-10));
//
// cont.erase(cont.begin());
// SectorContainer<false> cont2;
// TestCase<false> qwe2(cont2);
// EXPECT_EQ(cont, cont2);
//}
//
//
//TEST(NoExceptionTests, findFunction)
//{
// SectorContainer<false> cont;
// TestCase<false> qwe(cont);
// qwe.step_one();
// qwe.step_two();
//
// EXPECT_EQ(sector(*cont.find(-10)), sector(-100,-10));
// EXPECT_EQ(sector(*cont.find(-3)), sector(-5,9));
// EXPECT_EQ(cont.find(-7), cont.end() );
// EXPECT_EQ(cont.find(10), cont.end() );
//
// auto it = cont.begin();
// EXPECT_EQ(sector(*it), sector(-100, -10) );
// it++;
// EXPECT_EQ(sector(*it), sector(-5,9 ));
// it++;
// EXPECT_EQ(sector(*it), sector(12, 12));
// it++;
// EXPECT_EQ(sector(*it), sector(20, 30));
// it++;
// EXPECT_EQ(sector(*it), sector(40,100000 ));
// it++;
// EXPECT_EQ(it, cont.end());
//}
//
//
//
//
//int main(int argc, char** argv)
//{
// //по умолчанию считаем пару уже упорядоченной, т.е. first <= second
// try
// {
// //SimpleVector vec;
//
// //vec.add({ 1,2 });
// //vec.add({ 0,2 });
// //vec.add({ 6,7 });
// //auto val = vec.find(3);
//
// SectorContainer<false> sect; // шаблонный параметр true - кидаются исключения при пересечении отрезков,
// // false(по умолчанию) - слияние пересекающихся в один
// sector a(1, 4);
// sector b(3, 7);
// sect.add(a);
// sect.add(b);
// sect.add(sector(8, 9));
// sect.add({ 13,15 });
// sect.add({ { 0,1 }, { 9,13 }, {16,19} });
// std::vector<sector> vecsec({ {-9,-8}, {-6,1} });
// sect.add(vecsec);
//
// auto it = sect.find(16);
//
// sect.print();
// }
// catch (std::exception& e)
// {
// cout << e.what() << endl;
// //std::abort();
// }
//
//
// ::testing::InitGoogleTest(&argc, argv);
// return RUN_ALL_TESTS();
//} | [
"43324895+hohlov06@users.noreply.github.com"
] | 43324895+hohlov06@users.noreply.github.com |
8dc1f984f4b83ef6dedddad631c147db3f3c8f54 | 4c25432a6d82aaebd82fd48e927317b15a6bf6ab | /src/LibToolingAST/transformers/IOTransformers/sync_with_stdio_transformer.cpp | 2dcccdeb134b232c396c6d538580373e1a41911c | [] | no_license | wzj1988tv/code-imitator | dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933 | 07a461d43e5c440931b6519c8a3f62e771da2fc2 | refs/heads/master | 2020-12-09T05:33:21.473300 | 2020-01-09T15:29:24 | 2020-01-09T15:29:24 | 231,937,335 | 1 | 0 | null | 2020-01-05T15:28:38 | 2020-01-05T15:28:37 | null | UTF-8 | C++ | false | false | 3,796 | cpp | #ifndef CLANG_LIBS
#define CLANG_LIBS
#include "llvm/Support/CommandLine.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Rewrite/Core/Rewriter.h"
#endif
#include "../utils_transform.h"
#include "../../Utilities/Utils.h"
#include "../IOTransformers/utils_io_transformers.h"
#include "../ASTFrontendActionWithPrepTemplate.inl"
#include "output_transformer.cpp"
#include "../include/SourceTextHelper.h"
#include <algorithm>
using namespace clang;
using namespace llvm::cl;
enum Strategy {change_syncwithstdio=1};
// ** These are the command line options **
static llvm::cl::OptionCategory MyOptionCategory("Sync With Stdio Transformer");
static llvm::cl::opt<Strategy> StrategyOpt("strategy", desc("Transformation strategy"), Required,
values(clEnumVal(change_syncwithstdio,
"Add or remove syncwithstdio")),
cat(MyOptionCategory));
/**
* Adds or remove sync_with_stdio command, based on the fact if
* standard C++ streams are synchronized to the standard C streams.
*/
class SyncWithStdioTransformer : public IOTransformer {
public:
// Here, we set what streams are considered to be checked if streams are mixed due to sync_with_stdio.
sync_with_stdio_channels sync_mode = sync_both_output_input;
explicit SyncWithStdioTransformer(ASTContext &Context, Rewriter &OurRewriter, PreprocessingInfos *prepinfos) :
IOTransformer(Context, OurRewriter, prepinfos) {}
void replacecommand(Strategy cmdoption) {
// A. Check TODO check if following two checks are necessary for this transformer
if((!this->cxxstream_outputexpressions.empty()) &&
(!this->coutexpressions.empty() || !this->printfexpressions.empty())){
// we also have a problem now. The author mixed cout's and ofstream, so we do not have a unique stdout.
// freopen is not necessary to consider...
llvm::errs() << "Code 900: no unique stdout. mixed cout's/printfs and ofstream \n";
return;
}
if((!this->cxxstream_inputexpressions.empty()) &&
(!this->cplusplusInputExpressions.empty() || !this->cstyleInputExpressions.empty())){
// we also have a problem now. The author mixed cin's and ifstream, so we do not have a unique stdin.
// freopen is not necessary to consider...
llvm::errs() << "Code 900: no unique stdout. mixed cout's/printfs and ofstream \n";
return;
}
// B. Rewrite
if(cmdoption==change_syncwithstdio){
rewrite_syncwithstdio(sync_mode);
return;
}
}
};
/* ****************** ************** **************** */
class MyASTConsumer : public ASTConsumer {
public:
explicit MyASTConsumer(ASTContext &Context, Rewriter &OurRewriter, PreprocessingInfos *prepinfos)
: Visitor(Context, OurRewriter, prepinfos) {
}
void HandleTranslationUnit(ASTContext &Context) override {
Visitor.TraverseDecl(Context.getTranslationUnitDecl());
Visitor.replacecommand(StrategyOpt.getValue());
}
private:
SyncWithStdioTransformer Visitor;
};
int main(int argc, const char **argv) {
clang::tooling::CommonOptionsParser OptionsParser(argc, argv, MyOptionCategory);
clang::tooling::ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList());
return Tool.run(&*clang::tooling::newFrontendActionFactory
<MyFrontendActionWithPrep<MyASTConsumer, PreprocessingInfos>>());
}
| [
"e.quiring@tu-bs.de"
] | e.quiring@tu-bs.de |
2d38621bcae19bc5c8d8f1bf9ce66fff48b6e022 | 8b7e6de2a3b6fdaef98fd700bbb3ef33b922e15d | /test/load_survey.cpp | 859bd5815c578753fe86428192e88b333bacd73b | [
"Apache-2.0"
] | permissive | cedricpradalier/SymphonyLakeDataset | ae95b948e058e5f1e0ee39f432a7629e3ee16d3d | 5366560263b660b0151844a297effa517480991a | refs/heads/master | 2020-03-26T08:04:58.618557 | 2018-08-14T08:34:13 | 2018-08-14T08:34:13 | 144,685,137 | 2 | 0 | Apache-2.0 | 2018-08-14T07:33:58 | 2018-08-14T07:33:58 | null | UTF-8 | C++ | false | false | 2,247 | cpp | #ifdef NDEBUG
#undef NDEBUG
#endif
#include <stdlib.h>
#include <stdio.h>
#include <random>
#include <memory>
#include <sys/stat.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
// #define INSPECT
bool loadFromString(const std::string & line, std::string & data) {
data = line.substr(0,6);
return true;
}
#include <symphony_lake_dataset/SurveyVector.h>
using namespace symphony_lake_dataset;
#define R2D(X) ((X)*180./M_PI)
int main(int argc, char *argv[]) {
srand(time(NULL));
if (argc < 4) {
printf("Usage: %s <map root dir> <image root dir> <surveys...>",argv[0]);
printf("Example:\n\t %s data/Maps data/VBags 140106\n",argv[0]);
return -1;
}
std::string map_folders(argv[1]);
std::string image_folders(argv[2]);
std::vector<std::string> survey_list;
for (int i=3;i<argc;i++) {
survey_list.push_back(argv[i]);
}
SurveyVector surveys;
surveys.load(map_folders,image_folders,survey_list);
const Survey & S = surveys.get(0);
printf("Loaded one survey: %d poses, %d images\n",int(S.getNumPoses()),int(S.getNumImages()));
SurveyVector::PoseRef pref(0 /* survey index */ ,0 /* image index */);
// Make sure that there is an image and a pose available at this time
bool ok = surveys.checkPoseRef(pref);
cv::Mat I = surveys.loadImage(pref);
const ImagePoint & ip = surveys.getImagePoint(pref);
const Pose & P = surveys.getPose(pref);
double theta_cam = surveys.getCameraDir(pref);
printf("Loaded image 0. Pose %s: (%.2f m, %.2f m) boat heading %.2f deg camera heading %.2f deg\n"
"GPS %.2f %.2f Compass %.2f deg Camera Pan %.2f deg\n",
(ok?"ok":"not ok"),P.xg, P.yg, R2D(P.thetag), R2D(theta_cam),
ip.x, ip.y, R2D(ip.theta), R2D(ip.pan));
cv::imshow("I",I);
printf("Press 'q' in the graphic window to quit\n");
while (1) {
int k = cv::waitKey(0) & 0xFF;
switch (k) {
case 'q':
case 'Q':
case 0x27:
return 0;
break;
default:
break;
}
}
return 0;
}
| [
"cedric.pradalier@gmail.com"
] | cedric.pradalier@gmail.com |
14ce41f35d44fd167e2c0febabcac90fd5c70e30 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.h | b1c8dc8bd90e1bddba9c36479721d48ed5f0bba9 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 3,543 | h | /*
* Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
* Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef SVGFilterBuilder_h
#define SVGFilterBuilder_h
#include "core/style/SVGComputedStyleDefs.h"
#include "platform/graphics/filters/FilterEffect.h"
#include "platform/heap/Handle.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/AtomicStringHash.h"
class SkPaint;
namespace blink {
class FloatRect;
class LayoutObject;
class SVGFilterElement;
// A map from LayoutObject -> FilterEffect and FilterEffect -> dependent
// (downstream) FilterEffects ("reverse DAG"). Used during invalidations from
// changes to the primitives (graph nodes).
class SVGFilterGraphNodeMap final
: public GarbageCollected<SVGFilterGraphNodeMap> {
public:
static SVGFilterGraphNodeMap* create() { return new SVGFilterGraphNodeMap; }
typedef HeapHashSet<Member<FilterEffect>> FilterEffectSet;
void addBuiltinEffect(FilterEffect*);
void addPrimitive(LayoutObject*, FilterEffect*);
inline FilterEffectSet& effectReferences(FilterEffect* effect) {
// Only allowed for effects belongs to this builder.
ASSERT(m_effectReferences.contains(effect));
return m_effectReferences.find(effect)->value;
}
// Required to change the attributes of a filter during an
// svgAttributeChanged.
inline FilterEffect* effectByRenderer(LayoutObject* object) {
return m_effectRenderer.get(object);
}
void invalidateDependentEffects(FilterEffect*);
DECLARE_TRACE();
private:
SVGFilterGraphNodeMap();
// The value is a list, which contains those filter effects,
// which depends on the key filter effect.
HeapHashMap<Member<FilterEffect>, FilterEffectSet> m_effectReferences;
HeapHashMap<LayoutObject*, Member<FilterEffect>> m_effectRenderer;
};
class SVGFilterBuilder {
STACK_ALLOCATED();
public:
SVGFilterBuilder(FilterEffect* sourceGraphic,
SVGFilterGraphNodeMap* = nullptr,
const SkPaint* fillPaint = nullptr,
const SkPaint* strokePaint = nullptr);
void buildGraph(Filter*, SVGFilterElement&, const FloatRect&);
FilterEffect* getEffectById(const AtomicString& id) const;
FilterEffect* lastEffect() const { return m_lastEffect.get(); }
static ColorSpace resolveColorSpace(EColorInterpolation);
private:
void add(const AtomicString& id, FilterEffect*);
void addBuiltinEffects();
typedef HeapHashMap<AtomicString, Member<FilterEffect>> NamedFilterEffectMap;
NamedFilterEffectMap m_builtinEffects;
NamedFilterEffectMap m_namedEffects;
Member<FilterEffect> m_lastEffect;
Member<SVGFilterGraphNodeMap> m_nodeMap;
};
} // namespace blink
#endif // SVGFilterBuilder_h
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
48b2bbd114df0c9b3be495fe57860b6ea3b02b53 | 518c307c4ed3c147c182e886b934f255e629af5e | /sources/FEM/rf_st_new.h | 577258f5d4f897f952897bcec76059d99ce234c6 | [
"BSD-2-Clause"
] | permissive | wolf-pf/ogs_kb1 | 4e3fecd67eeb6084e94d5ec4aecd1aa586630f23 | 97ace8bc8fb80b033b8a32f6ed4a20983caa241f | refs/heads/master | 2021-01-17T06:53:24.022886 | 2018-11-24T15:33:31 | 2018-11-24T15:33:31 | 109,251,762 | 1 | 0 | NOASSERTION | 2018-11-24T15:33:32 | 2017-11-02T10:43:46 | C++ | UTF-8 | C++ | false | false | 20,404 | h | /**************************************************************************
FEMLib - Object: Source Terms ST
Task: class implementation
Programing:
01/2003 OK Implementation
last modified
**************************************************************************/
#ifndef rf_st_new_INC
#define rf_st_new_INC
// FEM
#include "DistributionInfo.h" // TF
#include "GeoInfo.h" // TF
#include "LinearFunctionData.h" // TF
#include "ProcessInfo.h" // TF
#include "fem_ele.h"
#include "Constrained.h"
class CNodeValue;
class CGLPolyline;
class CGLLine;
class Surface;
namespace process //WW
{
class CRFProcessDeformation;
};
namespace MathLib
{
template<class T1, class T2> class InverseDistanceInterpolation;
}
namespace MeshLib
{
class CFEMesh;
class MeshNodesAlongPolyline;
}
class SourceTerm;
typedef struct
{
std::vector<double> value_reference;
std::vector<double> last_source_value;
//double value_store[10][5000];
double** value_store; //[PCS_NUMBER_MAX*2]First ref no processes(two fields per process..time, value), second ref no values
} NODE_HISTORY;
class CSourceTerm : public ProcessInfo, public GeoInfo, public DistributionInfo
{
public:
CSourceTerm();
CSourceTerm(const SourceTerm* st);
~CSourceTerm();
std::ios::pos_type Read(std::ifstream* in,
const GEOLIB::GEOObjects & geo_obj,
const std::string & unique_name);
void Write(std::fstream*);
void EdgeIntegration(MeshLib::CFEMesh* m_msh,
const std::vector<long> & nodes_on_ply,
std::vector<double> & node_value_vector) const;
void FaceIntegration(MeshLib::CFEMesh* m_msh,
std::vector<long> const & nodes_on_sfc,
std::vector<double> & node_value_vector);
void DomainIntegration(MeshLib::CFEMesh* m_msh,
const std::vector<long> & nodes_in_dom,
std::vector<double> & node_value_vector) const;
void SetNOD2MSHNOD(std::vector<long> & nodes, std::vector<long> & conditional_nodes);
/**
* @param nodes
* @param conditional_nodes
*/
// 09/2010 TF
void SetNOD2MSHNOD(const std::vector<size_t>& nodes,
std::vector<size_t>& conditional_nodes) const;
double GetNodeLastValue(long n, int idx); // used only once in a global in rf_st_new
// used only once in a global in rf_st_new
void SetNodePastValue(long n, int idx, int pos, double value);
// used only once in a global in rf_st_new
void SetNodeLastValue(long n, int idx, double value);
double GetNodePastValue(long, int, int); // used only once in a global in rf_st_new
// used only once in a global in rf_st_new
double GetNodePastValueReference(long n, int idx);
// used only in sourcetermgroup
void SetSurfaceNodeVectorConditional(std::vector<long> & sfc_nod_vector,
std::vector<long> & sfc_nod_vector_cond);
void SetSurfaceNodeVectorConnected(std::vector<long> & sfc_nod_vector,
std::vector<long> & sfc_nod_vector_cond); // JOD 2/2015
// used only once in sourcetermgroup
void InterpolatePolylineNodeValueVector(CGLPolyline* m_ply,
std::vector<double> & Distribed,
std::vector<double> & ply_nod_vector);
void InterpolatePolylineNodeValueVector(
std::vector<double> const & nodes_as_interpol_points,
std::vector<double>& node_values) const;
void SetNodeValues(const std::vector<long> & nodes, const std::vector<long> & nodes_cond,
const std::vector<double> & node_values, int ShiftInNodeVector); // used only in sourcetermgroup
void SetNOD();
//23.02.2009. WW
void DirectAssign(const long ShiftInNodeVector);
// KR / NB
// including climate data into source terms
const MathLib::InverseDistanceInterpolation<GEOLIB::PointWithID*, GEOLIB::Station*> *getClimateStationDistanceInterpolation() const { return this->_distances; };
const std::vector<GEOLIB::Station*>& getClimateStations() const { return this->_weather_stations; }; //NB
//03.2010. WW
std::string DirectAssign_Precipitation(double current_time);
double getCoupLeakance () const;
const std::vector<double>& getDistribution () const { return DistribedBC; }
/**
* REMOVE CANDIDATE only for compatibility with old GEOLIB version
* @return
*/
const std::string & getGeoName() const;
double getGeoNodeValue() const { return geo_node_value; } //KR
int CurveIndex;
std::vector<int> element_st_vector;
double st_rill_height, coup_given_value, coup_residualPerm; // JOD
double sorptivity, constant, rainfall, rainfall_duration, moistureDeficit /*1x*/;
bool node_averaging, distribute_volume_flux; // JOD
bool no_surface_water_pressure, explicit_surface_water_pressure; // JOD
bool isCoupled () const { return _coupled; }
bool isConnected() const { return connected_geometry; } // JOD 2/2015
double getNormalDepthSlope () const { return normaldepth_slope; }
bool everyoneWithEveryone; // take all nodes from surface and connect with all nodes of other surface JOD 2015-11-18
// constrain a ST by other process
bool isConstrainedST() const { return _isConstrainedST; }
Constrained const & getConstrainedST(std::size_t constrainedID) const { return _constrainedST[constrainedID]; }
std::size_t getNumberOfConstrainedSTs() const { return _constrainedST.size(); }
bool isCompleteConstrainST(std::size_t constrainedID) const { return _constrainedST[constrainedID]._isCompleteConstrained; }
bool getCompleteConstrainedSTStateOff(std::size_t constrainedID) const { return _constrainedST[constrainedID]._completeConstrainedStateOff; }
void setCompleteConstrainedSTStateOff(bool status, std::size_t i) { _constrainedST[i]._completeConstrainedStateOff = status; }
void pushBackConstrainedSTNode(std::size_t constrainedID, bool constrainedStatus) { _constrainedST[constrainedID]._constrainedNodes.push_back(constrainedStatus); }
bool getConstrainedSTNode(std::size_t constrainedID, int position) const { return _constrainedST[constrainedID]._constrainedNodes[position]; }
void setConstrainedSTNode(std::size_t constrainedID, bool node_status, int position) { _constrainedST[constrainedID]._constrainedNodes[position] = node_status; }
std::size_t getNumberOfConstrainedSTNodes(std::size_t constrainedID) const { return _constrainedST[constrainedID]._constrainedNodes.size(); }
int getConstrainedSTNodesIndex(int position) const { return _constrainedSTNodesIndices[position]; }
void setConstrainedSTNodesIndex(int st_node_index, int position) { _constrainedSTNodesIndices[position]=st_node_index; }
std::size_t getSTVectorGroup() const { return _st_vector_group; }
void setSTVectorGroup(int group) { _st_vector_group = group; }
const std::string& getFunctionName () const { return fct_name; }
int getFunctionMethod () const { return fct_method; }
const std::vector<int>& getPointsWithDistribedST () const { return PointsHaveDistribedBC; }
const std::vector<double>& getDistribedST() const { return DistribedBC; }
bool isAnalytical () const { return analytical; }
bool isPressureBoundaryCondition () const { return pressureBoundaryCondition; }
void SetPressureBoundaryConditionFlag (bool pBC) { pressureBoundaryCondition = pBC;}
double GetAnalyticalSolution(long location);
size_t getNumberOfTerms () const { return number_of_terms; }
void setMaxNumberOfTerms (size_t max_no_terms) { _max_no_terms = max_no_terms; }
void setNumberOfAnalyticalSolutions (size_t no_an_sol) { _no_an_sol = no_an_sol; }
double GetRelativeInterfacePermeability(CRFProcess* m_pcs, // JOD
double head,
long msh_node);
bool channel, channel_width, air_breaking;
double air_breaking_factor, air_breaking_capillaryPressure, air_closing_capillaryPressure;
int geo_node_number;
double* nodes;
std::vector<int> node_number_vector;
std::vector<double> node_value_vector;
std::vector<int> node_renumber_vector;
std::string tim_type_name;
std::string interpolation_method; //BG
int TimeInterpolation; //BG
std::string pcs_type_name_cond;
std::string pcs_pv_name_cond;
int getTimeContrCurve() {return time_contr_curve; } //SB:02.2014 get bc ativity controlled curve
std::string getTimeContrFunction() {return time_contr_function; } //SB:02.2014 get bc ativity controlled curve
std::string getFunction() { return fct_name; } //SB:02.2014 get bc ativity controlled curve
int getSubDomainIndex () const { return _sub_dom_idx; }
std::string fname;
double getTransferCoefficient() { return transfer_coefficient; } //TN
double getValueSurrounding() { return value_surrounding;} //TN
std::vector<double> get_node_value_vectorArea(){ return node_value_vectorArea;} //TN
std::vector<long> st_node_ids;
// NNNC
bool connected_geometry; // SB 02/2015
bool diagonalOnly; // JOD 2016-4-18 - true for flow coupling, normal depth, critical depth
std::string connected_geometry_type;
std::string connected_geometry_name;
std::vector<long> connected_nodes_idx;
int connected_geometry_verbose_level;
double connected_geometry_exchange_term; // leakance
int connected_geometry_mode;
long connected_geometry_ref_element_number; // JOD 2015-11-18 - mode 2
double connected_geometry_minimum_velocity_abs; //
double connected_geometry_reference_direction[3]; //
private: // TF, KR
void ReadDistributionType(std::ifstream* st_file);
void ReadGeoType(std::ifstream* st_file,
const GEOLIB::GEOObjects& geo_obj,
const std::string& unique_name);
void CreateHistoryNodeMemory(NODE_HISTORY* nh);
void DeleteHistoryNodeMemory();
double geo_node_value;
// active state is controlled by time curve SB
int time_contr_curve;
std::string time_contr_function;
/**
* is the source term coupled with another source term
*/
bool _coupled;
double normaldepth_slope; // used only once in a global in rf_st_new
/// Subdomain index for excvation simulation
// 14.12.2010. WW
int _sub_dom_idx;
int fct_method;
std::string fct_name;
LinearFunctionData* dis_linear_f; //24.8.2011. WW
bool analytical; //2x?
bool pressureBoundaryCondition; // pressure load boundary condition
size_t number_of_terms;
size_t _max_no_terms; // used only once in a global in rf_st_new
size_t _no_an_sol;
int analytical_material_group; // used only once in a global in rf_st_new
int resolution; // used only once in a global in rf_st_new
double analytical_diffusion; // used only once in a global in rf_st_new
double analytical_porosity; // used only once in a global in rf_st_new
double analytical_tortousity; // used only once in a global in rf_st_new
double analytical_linear_sorption_Kd; // used only once in a global in rf_st_new
double analytical_matrix_density; // used only once in a global in rf_st_new
double factor;
double transfer_coefficient; //TN - for DIS_TYPE TRANSFER_SURROUNDING
double value_surrounding; //TN - for DIS_TYPE TRANSFER_SURROUNDING
std::string nodes_file;
int msh_node_number;
std::string msh_type_name;
std::vector<int> PointsHaveDistribedBC;
std::vector<double> DistribedBC;
std::vector<double> node_value_vectorArea;
std::vector<double*> normal2surface;
std::vector<double*> pnt_parameter_vector;
// 03.2010. WW
long start_pos_in_st;
double* GIS_shape_head; // 07.06.2010. WW
std::vector<double> precip_times;
std::vector<std::string> precip_files;
friend class CSourceTermGroup;
friend class process::CRFProcessDeformation; //WW
friend class ::CRFProcess; //WW
std::string geo_name;
double _coup_leakance;
// including climate data into source terms
MathLib::InverseDistanceInterpolation<GEOLIB::PointWithID*, GEOLIB::Station*> *_distances; // NB
std::vector<GEOLIB::Station*> _weather_stations; //NB
bool _isConstrainedST;
std::vector<Constrained> _constrainedST;
//std::vector<bool> _constrainedSTNodes;
std::vector<int> _constrainedSTNodesIndices;
std::size_t _st_vector_group;
};
class CSourceTermGroup
{
public:
CSourceTermGroup() //WW
{
}
void Set(CRFProcess* m_pcs, const int ShiftInNodeVector, std::string this_pv_name = "");
//WW std::vector<CNodeValue*>group_vector;
/**
* \brief process type for the physical process
* possible values are
* <table>
* <tr><td>LIQUID_FLOW</td> <td>H process (incompressible flow)</td></tr>
* <tr><td>GROUNDWATER_FLOW</td> <td>H process (incompressible flow)</td></tr>
* <tr><td>RIVER_FLOW</td> <td>H process (incompressible flow)</td></tr>
* <tr><td>RICHARDS_FLOW</td> <td>H process (incompressible flow)</td></tr>
* <tr><td>OVERLAND_FLOW</td> <td>process (incompressible flow)</td></tr>
* <tr><td>GAS_FLOW</td> <td>H process (compressible flow)</td></tr>
* <tr><td>TWO_PHASE_FLOW</td> <td>H2 process (incompressible/compressible flow)</td></tr>
* <tr><td>COMPONENTAL_FLOW</td> <td>H2 process (incompressible/compressible flow)</td></tr>
* <tr><td>HEAT_TRANSPORT</td> <td>T process (single/multi-phase flow)</td></tr>
* <tr><td>DEFORMATION</td> <td>M process (single/multi-phase flow)</td></tr>
* <tr><td>MASS_TRANSPORT</td> <td>C process (single/multi-phase flow)</td></tr>
* </table>
*/
std::string pcs_name;
std::string pcs_type_name; //OK
std::string pcs_pv_name; //OK
MeshLib::CFEMesh* m_msh;
MeshLib::CFEMesh* m_msh_cond;
//WW std::vector<CSourceTerm*>st_group_vector; //OK
//WW double GetConditionalNODValue(int,CSourceTerm*); //OK
//WW double GetRiverNODValue(int,CSourceTerm*, long msh_node); //MB
//WW double GetCriticalDepthNODValue(int,CSourceTerm*, long msh_node); //MB
//WW double GetNormalDepthNODValue(int,CSourceTerm*, long msh_node); //MB JOD
//WW Changed from the above
// double GetAnalyticalSolution(CSourceTerm *m_st,long node_number, std::string process);//CMCD
// TRANSFER OF DUAL RICHARDS
std::string fct_name; //YD
private:
// JOD
void SetPNT(CRFProcess* m_pcs, CSourceTerm* m_st, const int ShiftInNodeVector);
// JOD
void SetLIN(CRFProcess* m_pcs, CSourceTerm* m_st, const int ShiftInNodeVector);
//OK
void SetPLY(CSourceTerm* st, int ShiftInNodeVector);
// JOD
void SetDMN(CSourceTerm* m_st, const int ShiftInNodeVector);
// JOD
void SetSFC(CSourceTerm* m_st, const int ShiftInNodeVector);
// JOD
void SetCOL(CSourceTerm* m_st, const int ShiftInNodeVector);
// JOD
// void SetPolylineNodeVector(CGLPolyline* m_ply, std::vector<long>&ply_nod_vector);
void SetPolylineNodeVectorConditional(CSourceTerm* st,
std::vector<long>&ply_nod_vector,
std::vector<long>&ply_nod_vector_cond);
/**
* 09/2010 TF
* @param st
* @param ply_nod_vector
* @param ply_nod_vector_cond
*/
void SetPolylineNodeVectorConditional(CSourceTerm* st,
std::vector<size_t>& ply_nod_vector,
std::vector<size_t>& ply_nod_vector_cond);
void SetPolylineNodeValueVector(CSourceTerm* st, CGLPolyline * old_ply,
const std::vector<long>& ply_nod_vector,
std::vector<long>& ply_nod_vector_cond, std::vector<double>& ply_nod_val_vector);
/**
* 09/2010 / 03/2011 TF
* @param st
* @param ply_nod_vector
* @param ply_nod_vector_cond
* @param ply_nod_val_vector
*/
void SetPolylineNodeValueVector(CSourceTerm* st,
std::vector<long> const & ply_nod_vector,
std::vector<long> const & ply_nod_vector_cond,
std::vector<double>& ply_nod_val_vector) const;
// JOD
void SetSurfaceNodeVector(Surface* m_sfc, std::vector<long>&sfc_nod_vector);
void SetSurfaceNodeVector(GEOLIB::Surface const* sfc,
std::vector<std::size_t> & sfc_nod_vector);
void SetSurfaceNodeValueVector( CSourceTerm* m_st,
Surface* m_sfc,
std::vector<long> const &sfc_nod_vector,
std::vector<double>&sfc_nod_val_vector);
void AreaAssembly(const CSourceTerm* const st, const std::vector<long>& ply_nod_vector_cond,
std::vector<double>& ply_nod_val_vector) const;
void DistributeVolumeFlux(CSourceTerm* st, std::vector<long> const & ply_nod_vector, // 5.3.07
std::vector<double>& ply_nod_val_vector);
// CB JOD MERGE //
//void CSourceTermGroup::WriteNodeConnections();
void WriteNodeConnections(); // WTP
};
extern CSourceTermGroup* STGetGroup(std::string pcs_type_name,std::string pcs_pv_name);
extern std::list<CSourceTermGroup*> st_group_list;
/**
* read source term file
* @param file_base_name base file name (without extension) containing the source terms
* @param geo_obj object of class GEOObjects managing the geometric entities
* @param unique_name unique name to access the geometric entities in geo_obj
* @return true if source terms found in file, else false
*/
bool STRead(const std::string& file_base_name,
const GEOLIB::GEOObjects& geo_obj,
const std::string& unique_name);
extern void STWrite(std::string);
#define ST_FILE_EXTENSION ".st"
//extern void STCreateFromPNT();
extern std::vector<CSourceTerm*> st_vector;
extern void STDelete();
void STCreateFromLIN(std::vector<CGLLine*>);
CSourceTerm* STGet(std::string);
extern void STGroupDelete(std::string pcs_type_name,std::string pcs_pv_name);
extern void STGroupsDelete(void); //Haibing;
extern size_t aktueller_zeitschritt;
extern double aktuelle_zeit;
extern std::vector<std::string>analytical_processes;
//OK
extern CSourceTerm* STGet(const std::string&, const std::string&, const std::string&);
// WW moved here
//CMCD, WW
extern double GetAnalyticalSolution(long node_number, CSourceTerm* m_st);
//extern void GetRiverNODValue(double& value, CNodeValue* cnodev, const CSourceTerm* m_st);
extern double GetConditionalNODValue(CSourceTerm* m_st, CNodeValue* cnodev);
//MB
extern void GetCriticalDepthNODValue(double& value, CSourceTerm*, long msh_node);
// JOD
extern void GetCouplingNODValue(double& value, CSourceTerm* m_st, CNodeValue* cnodev);
// JOD
extern void GetCouplingNODValueNewton(double& value, CSourceTerm* m_st, CNodeValue* cnodev);
//MB JOD
extern void GetNormalDepthNODValue(double& value, CSourceTerm*, long msh_node);
// JOD
extern void GetCouplingNODValuePicard(double& value, CSourceTerm* m_st, CNodeValue* cnodev);
//#endif
// JOD
extern double CalcCouplingValue(double factor,
double h_this,
double h_cond,
double z_cond,
CSourceTerm* m_st);
// JOD
// JOD
extern void GetCouplingFieldVariables(CRFProcess* m_pcs_this,
CRFProcess* m_pcs_cond,
double* h_this,
double* h_cond,
double* h_shifted,
double* h_averaged,
double* z_this,
double* z_cond,
CSourceTerm* m_st,
CNodeValue* cnodev,
long msh_node_number,
long msh_node_number_cond,
double gamma);
// JOD
extern void GetPhilipNODValue(double& value, const CSourceTerm* m_st);
// JOD
extern void GetGreenAmptNODValue(double& value, CSourceTerm* m_st, long msh_node);
// JOD
extern void GetNODValue(double& value, CNodeValue* cnodev,CSourceTerm* m_st);
void IncorporateConnectedGeometries(double& value, CNodeValue* cnodev, CSourceTerm* m_st);// JOD 2/2015
extern void GetNODHeatTransfer(double& value, CSourceTerm* st, long geo_node); //TN
#endif
| [
"jod@gpi.uni-kiel.de"
] | jod@gpi.uni-kiel.de |
1611a93626f2afc64802aa1251c772e42718199d | cdbda05d68cb62e1ea9b71543dbb1692c09d5600 | /src/_IO.cpp | e4ae7e74a8bbb76749231706ed2ed9a805e184da | [] | no_license | cams7/arduino_sisbarc-emulator | d0dc9ca9f98e9c79bbb08f3728b19f719a8031a3 | 7d50eb7b0684683acccd802df1275b61c5ecb531 | refs/heads/master | 2021-01-20T05:55:01.558790 | 2015-02-15T12:52:51 | 2015-02-15T12:52:51 | 30,697,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | cpp | /*
* _IO.cpp
*
* Created on: 10/02/2015
* Author: cams7
*/
#include "_IO.h"
#include <stdlib.h>
#include <math.h>
namespace SISBARC {
const char IO::NEW_LINE = 0x0A; //Nova linha '\n' - 10
const char IO::STRING_END = 0x00; //Final de String '\0' - 0
const char IO::SPACE = 0x20; //Espaço em branco - 32
const uint8_t IO::CODE_ASCII_SIZE = 10;
const uint8_t IO::CODE_ASCII[CODE_ASCII_SIZE] = { 48, 49, 50, 51, 52, 53, 54,
55, 56, 57 };
int8_t IO::getIndexASCII(const uint8_t code) {
for (uint8_t i = 0x00; i < CODE_ASCII_SIZE; i++)
if (CODE_ASCII[i] == code)
return i;
return -1;
}
int8_t IO::getCodeASCII(const uint8_t index) {
return CODE_ASCII[index];
}
uint16_t IO::getValueLine(const char* stringValue, uint8_t totalChars) {
uint16_t value = 0x0000;
for (uint8_t i = 0x00; i < totalChars; i++)
value += getIndexASCII(stringValue[i]) * pow(10, totalChars - i - 1);
return value;
}
char* IO::getStringLine(uint8_t value, uint8_t totalChars) {
if (value < 0x000A) //10
totalChars -= 2;
else if (value < 0x0064) //100
totalChars -= 1;
char *string;
string = (char*) malloc(totalChars + 1);
if (string == NULL)
return NULL;
uint8_t index = totalChars - 1;
if (value >= 0) {
do {
*(string + index) = getCodeASCII(value % 10);
value /= 10;
index--;
} while (value != 0);
}
*(string + totalChars) = STRING_END;
return string;
}
} /* namespace SISBARC */
| [
"ceanma@gmail.com"
] | ceanma@gmail.com |
f7c00a5b145b056b559f4345682065588de6ab8c | 901a70a9629ca9559d7a495cfcea750047f26070 | /undoredo.cpp | 7d1111a0797b97a04994a3ed93b9d763685c31cf | [] | no_license | delafrog/MolRed | a449817484fbcec8c102cb4762cd30e984195e97 | 0869427b01028bca7bc7931308cba6d36622d1fd | refs/heads/master | 2022-12-02T12:15:35.737262 | 2020-08-23T12:58:41 | 2020-08-23T12:58:41 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 52,809 | cpp | #ifndef UNDOREDO_CPP
#define UNDOREDO_CPP
#include <QAction>
#include <QLabel>
#include <QString>
#include <QVBoxLayout>
#include <QSplitter>
#include "undoredo.h"
#include "linalg.h"
//#include "linalg.cpp"
#include "datatypes.h"
#include "rdwrfls.h"
#include "GLframe.h"
//---------------------
CommandItem::CommandItem(const QList<QVariant> &data, CommandItem *parent)
{
itemData = data;
parentItem = parent;
}
//---------------------
CommandItem::~CommandItem()
{
qDeleteAll(childItems);
}
//---------------------
void CommandItem::appendChild(CommandItem *child)
{
childItems.append(child); // добавление производиться с помощью метода класса QList
}
//---------------------
//---------------------
CommandItem *CommandItem::child(int row) // возвращает указатель на дочерний элемент с номером 'row' в списке текущего элемента
{
return childItems.value(row);
}
//---------------------
int CommandItem::childCount() const // возвращает количество дочерних элементов
{
return childItems.count();
}
//---------------------
int CommandItem::columnCount() const // возвращает количество столбцов
{
return itemData.count();
}
//---------------------
QVariant CommandItem::data(int column) const // возвращает данные для столбца с номером 'column'
{
return itemData.value(column);
}
//---------------------
CommandItem *CommandItem::parent() // возвращает указатель на родительский элемент
{
return parentItem;
}
//---------------------
int CommandItem::row() const // возвращает номер текущего элемента в списке родительского
{
if (parentItem)
return parentItem->childItems.indexOf(const_cast<CommandItem*>(this));
return 0;
}
//-------------------------------------------------
//---------------------
CmdTrModel::CmdTrModel(const QString &data, QObject * parent) : QAbstractItemModel(parent)
{
QList<QVariant> rootData;
rootData<<tr("Command")<<tr("Data")<<tr("|");
rootItem = new CommandItem(rootData);
setupModelData(data.split(QString("\n")), rootItem);
}
CmdTrModel::CmdTrModel(QObject * parent) : QAbstractItemModel(parent)
{
QList<QVariant> rootData;
rootData<<tr("Command")<<tr("Data")<<tr("|");
rootItem = new CommandItem(rootData);
//setupModelData();//data.split(QString("\n")), rootItem);
}
CmdTrModel::~CmdTrModel()
{
delete rootItem;
}
QVariant CmdTrModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
CommandItem *item = static_cast<CommandItem*>(index.internalPointer());
return item->data(index.column());
}
Qt::ItemFlags CmdTrModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable ;
}
//---------------------
void CmdTrModel::setupModelData(const QStringList &lines, CommandItem *parent)
{
QList<CommandItem*> parents;
QList<int> indentations;
parents << parent;
indentations << 0;
int number = 0;
beginResetModel();
while (number < lines.count()) {
int position = 0;
while (position < lines[number].length()) {
if (lines[number].mid(position, 1) != " ")
break;
position++;
}
QString lineData = lines[number].mid(position).trimmed();
if (!lineData.isEmpty()) {
// Read the column data from the rest of the line.
QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
QList<QVariant> columnData;
for (int column = 0; column < columnStrings.count(); ++column)
columnData << columnStrings[column];
if (position > indentations.last()) {
// The last child of the current parent is now the new parent
// unless the current parent has no children.
if (parents.last()->childCount() > 0) {
parents << parents.last()->child(parents.last()->childCount()-1);
indentations << position;
}
} else {
while (position < indentations.last() && parents.count() > 0) {
parents.pop_back();
indentations.pop_back();
}
}
// Append a new item to the current parent's list of children.
parents.last()->appendChild(new CommandItem(columnData, parents.last()));
}
number++;
}
endResetModel();
}
QVariant CmdTrModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return rootItem->data(section);
return QVariant();
}
QModelIndex CmdTrModel::index(int row, int column, const QModelIndex &parent)
const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
CommandItem *parentItem;
if (!parent.isValid())
parentItem = rootItem;
else
parentItem = static_cast<CommandItem*>(parent.internalPointer());
CommandItem *childItem = parentItem->child(row);
if (childItem)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex CmdTrModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
CommandItem *childItem = static_cast<CommandItem*>(index.internalPointer());
CommandItem *parentItem = childItem->parent();
if (parentItem == rootItem)
return QModelIndex();
return createIndex(parentItem->row(), 0, parentItem);
}
int CmdTrModel::rowCount(const QModelIndex &parent) const
{
CommandItem *parentItem;
if (parent.column() > 0)
return 0;
if (!parent.isValid())
parentItem = rootItem;
else
parentItem = static_cast<CommandItem*>(parent.internalPointer());
return parentItem->childCount();
}
int CmdTrModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid())
return static_cast<CommandItem*>(parent.internalPointer())->columnCount();
else
return rootItem->columnCount();
}
//---------------------
void CmdTrModel::updateModel()//const Molecule &mol,SmplTpzlTable &tbl) // обновить данные
{
delete rootItem;
QList<QVariant> rootData;
rootData<<tr("Command")<<tr("Data")<<tr("|");
rootItem = new CommandItem(rootData);
setUpModelData();//mol,tbl);
}
void CmdTrModel::clearAllModelData()
{
//parents
}/**/
void CmdTrModel::setUpModelData()
{
QList<CommandItem*> parents;
parents << rootItem;
QString nstr,nstr1;
QList<QVariant> sdt;
QList<QString> comnms;
QList<QString> datas;
int i_beg,i_end,di;
beginResetModel();
if(!unrd)
{
i_beg = UR->id_cr_op-1;
i_end = 0;
di = -1;
}else
{
i_beg = UR->id_cr_op;
i_end = UR->operations.N;
di = 1;
}
for(int ii=i_beg;(unrd ? ii<i_end : ii>=i_end);ii+=di)
{
sdt.clear();
comnms.clear();
datas.clear();
switch (UR->operations.x[ii].x[0])
{
case ADD_MOL :
{
nstr = QString(tr("Add Molecule"));
// comnms.append(tr("Type of molecule :"));
// comnms.append(tr("Molecule`s nubmer :"));
// datas.append(QString("%1").arg(UR->WF->Mls.N));
//comnms.append(tr("Amoount of atoms : "));
break;
}
case DEL_MOL :
{
nstr = QString(tr("Delete Molecule"));
// comnms.append(tr("Type of molecule :"));
comnms.append(tr("Molecule`s nubmer :"));
datas.append(QString("%1").arg(UR->id_ml_dl_op.x[UR->operations.x[ii].x[1]]+1));
//comnms.append(tr("Amoount of atoms : "));
break;
}
case ADD_ATM :
{
nstr = QString(tr("Add Atom"));
comnms.append(tr("Molecule`s nubmer :"));
//comnms.append(tr("Atoms`s nubmer : "));
datas.append(QString("%1").arg(UR->id_at_br_op.x[UR->operations.x[ii].x[1]]+1));
//datas.append(QString("%1").arg(UR->WF->Mls.x[UR->id_at_br_op.x[UR->operations.x[ii].x[1]]]->Atoms.N));
break;
}
case DEL_ATM :
{
nstr = QString(tr("Delete Atom"));
comnms.append(tr("Molecule`s nubmer :"));
comnms.append(tr("Atoms`s nubmer : "));
datas.append(QString("%1").arg(UR->id_at_dl_op.x[UR->operations.x[ii].x[1]].x[0]+1));
datas.append(QString("%1").arg(UR->id_at_dl_op.x[UR->operations.x[ii].x[1]].x[1]+1));
break;
}
case ADD_BND :
{
nstr = QString(tr("Add Bond"));
comnms.append(tr("Molecule`s nubmer :"));
comnms.append(tr("Nubmers of atoms :"));
datas.append(QString("%1").arg(UR->id_bn_br_op.x[UR->operations.x[ii].x[1]].x[0]+1));
datas.append(QString("%1").arg(UR->id_bn_br_op.x[UR->operations.x[ii].x[1]].x[1]+1));
datas.last().append(QString(", %1").arg(UR->id_bn_br_op.x[UR->operations.x[ii].x[1]].x[2]+1));
//comnms.append(tr("Nubmer of bond :"));
break;
}
case DEL_BND :
{
nstr = QString(tr("Delete Bond"));
comnms.append(tr("Molecule`s nubmer :"));
comnms.append(tr("Nubmers of atoms :"));
datas.append(QString("%1").arg(UR->id_bn_dl_op.x[UR->operations.x[ii].x[1]].x[0]+1));
datas.append(QString("%1").arg(UR->id_bn_dl_op.x[UR->operations.x[ii].x[1]].x[1]+1));
datas.last().append(QString(", %1").arg(UR->id_bn_dl_op.x[UR->operations.x[ii].x[1]].x[2]+1));
break;
}
case UNI_MOL :
{
nstr = QString(tr("Unite Molecules"));
comnms.append(tr("Nubmers of molecules :"));
datas.append(QString("%1").arg(UR->id_ml_un_op.x[UR->operations.x[ii].x[1]].x[0]+1));
datas.last().append(QString(", %1").arg(UR->id_ml_un_op.x[UR->operations.x[ii].x[1]].x[1]+1));
break;
}
case SEP_MOL :
{
nstr = QString(tr("Split Molecule"));
comnms.append(tr("Nubmer of molecule :"));
comnms.append(tr("Separation atom :"));
datas.append(QString("%1").arg(UR->id_ml_un_op.x[UR->operations.x[ii].x[1]].x[0]+1));
datas.append(QString("%1").arg(UR->id_ml_sp_op.x[UR->operations.x[ii].x[1]]+1));
break;
}
case CHG_TYP :
{
nstr = QString(tr("Change Atom Type"));
comnms.append(tr("Nubmer of molecule :"));
comnms.append(tr("Nubmer of atom :"));
comnms.append(tr("Type of atom :"));
//comnms.append(tr("Additional data"));
datas.append(QString("%1").arg(UR->id_at_tp_op.x[UR->operations.x[ii].x[1]].x[0]+1));
datas.append(QString("%1").arg(UR->id_at_tp_op.x[UR->operations.x[ii].x[1]].x[1]+1));
vecT<char> ch(UR->WF->TableZR.Lines.x[ UR->id_at_tp_op.x[UR->operations.x[ii].x[1]].x[2] ].Ch.x,2);
ch.add('\0');
datas.append(QString(ch.x));
break;
}
case CHG_BND :
{
nstr = QString(tr("Change Bond Order"));
comnms.append(tr("Nubmer of molecule :"));
comnms.append(tr("Nubmers of atoms :"));
comnms.append(tr("Bond order:"));
datas.append(QString("%1").arg(UR->id_bn_tp_op.x[UR->operations.x[ii].x[1]].x[0]+1));
datas.append(QString("%1").arg(UR->id_bn_tp_op.x[UR->operations.x[ii].x[1]].x[1]+1));
datas.last().append(QString(", %1").arg(UR->id_bn_tp_op.x[UR->operations.x[ii].x[1]].x[2]+1));
datas.append(QString("%1").arg(UR->id_bn_tp_op.x[UR->operations.x[ii].x[1]].x[3]+1));
break;
}
case MOV_ATM :
{
nstr = QString(tr("Move Atom"));
comnms.append(tr("Nubmer of molecule :"));
comnms.append(tr("Nubmer of atom :"));
comnms.append(tr("Displacement vector :"));
datas.append(QString("%1").arg(UR->at_mv_op.x[UR->operations.x[ii].x[1]].id_at_mv_op.x[0]+1));
datas.append(QString("%1").arg(UR->at_mv_op.x[UR->operations.x[ii].x[1]].id_at_mv_op.x[1]+1));
datas.append(QString("x: %1, ").arg(UR->at_mv_op.x[UR->operations.x[ii].x[1]].dr_at_mv_op.x[0],0,'g',8));
datas.last().append(QString("y: %1, ").arg(UR->at_mv_op.x[UR->operations.x[ii].x[1]].dr_at_mv_op.x[1],0,'g',8));
datas.last().append(QString("z: %1.").arg(UR->at_mv_op.x[UR->operations.x[ii].x[1]].dr_at_mv_op.x[2],0,'g',8));
break;
}
case MOV_MOL :
{
nstr = QString(tr("Move Molecule"));
comnms.append(tr("Nubmer of molecule :"));
comnms.append(tr("Displacement vector :"));
comnms.append(tr("Center vector :"));
comnms.append(tr("Rotation quaternion :"));
datas.append(QString("%1").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].id_ml_mv_op+1));
datas.append(QString("x: %1, ").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].dr_ml_mv_op.x[0],0,'g',8));
datas.last().append(QString("y: %1, ").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].dr_ml_mv_op.x[1],0,'g',8));
datas.last().append(QString("z: %1. ").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].dr_ml_mv_op.x[2],0,'g',8));
datas.append(QString("x: %1, ").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].cq_ml_mv_op.x[0],0,'g',8));
datas.last().append(QString("y: %1, ").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].cq_ml_mv_op.x[1],0,'g',8));
datas.last().append(QString("z: %1. ").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].cq_ml_mv_op.x[2],0,'g',8));
datas.append(QString("cos(a/2): %1, ").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].qa_ml_mv_op.x[0],0,'g',8));
datas.last().append(QString("x: %1, ").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].qa_ml_mv_op.x[1],0,'g',8));
datas.last().append(QString("y: %1, ").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].qa_ml_mv_op.x[2],0,'g',8));
datas.last().append(QString("z: %1. ").arg(UR->ml_mv_op.x[UR->operations.x[ii].x[1]].qa_ml_mv_op.x[3],0,'g',8));
break;
}
case MOV_FRG :
{
nstr = QString(tr("Move Fragment"));
comnms.append(tr("Nubmer of molecule :"));
comnms.append(tr("Nubmers of atoms :"));
comnms.append(tr("Displacement vector :"));
comnms.append(tr("Center vector :"));
comnms.append(tr("Rotation quaternion :"));
datas.append(QString("%1").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].id_ml+1));
datas.append(QString("%1").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].id_fr_mv_op.x[0]+1));
for(int ij=1;ij<UR->fr_mv_op.x[UR->operations.x[ii].x[1]].id_fr_mv_op.N;ij++)
{
datas.last().append(QString(", %1").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].id_fr_mv_op.x[ij]+1));
}
datas.append(QString("x: %1, ").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].dr_fr_mv_op.x[0],0,'g',8));
datas.last().append(QString("y: %1, ").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].dr_fr_mv_op.x[1],0,'g',8));
datas.last().append(QString("z: %1. ").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].dr_fr_mv_op.x[2],0,'g',8));
datas.append(QString("x: %1, ").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].cq_fr_mv_op.x[0],0,'g',8));
datas.last().append(QString("y: %1, ").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].cq_fr_mv_op.x[1],0,'g',8));
datas.last().append(QString("z: %1. ").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].cq_fr_mv_op.x[2],0,'g',8));
datas.append(QString("cos(a/2): %1, ").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].qa_fr_mv_op.x[0],0,'g',8));
datas.last().append(QString("x: %1, ").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].qa_fr_mv_op.x[1],0,'g',8));
datas.last().append(QString("y: %1, ").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].qa_fr_mv_op.x[2],0,'g',8));
datas.last().append(QString("z: %1. ").arg(UR->fr_mv_op.x[UR->operations.x[ii].x[1]].qa_fr_mv_op.x[3],0,'g',8));
break;
}
case SWP_ATM :
{
nstr = QString(tr("Swap Atoms"));
comnms.append(tr("Nubmer of molecule :"));
comnms.append(tr("Nubmers of atoms :"));
datas.append(QString("%1").arg(UR->id_at_sw_op.x[UR->operations.x[ii].x[1]].x[0]+1));
datas.append(QString("%1, ").arg(UR->id_at_sw_op.x[UR->operations.x[ii].x[1]].x[1]+1));
datas.last().append(QString("%1").arg(UR->id_at_sw_op.x[UR->operations.x[ii].x[1]].x[2]+1));
break;
}
case SWP_MOL :
{
nstr = QString(tr("Swap Molecules"));
comnms.append(tr("Nubmers of molecules :"));
datas.append(QString("%1").arg(UR->id_ml_sw_op.x[UR->operations.x[ii].x[1]].x[0]+1));
datas.last().append(QString(", %1").arg(UR->id_ml_sw_op.x[UR->operations.x[ii].x[1]].x[1]+1));
break;
}
case ADD_PAA :
{
nstr = QString(tr("Add Atom Node"));
comnms.append(tr("Number of molecule :"));
comnms.append(tr("Number of chain :"));
comnms.append(tr("Number of aminoacid :"));
comnms.append(tr("Number of atom (in amin) :"));
comnms.append(tr("AminoName of atom : "));
datas.append(QString("%1").arg(UR->id_pr_at_op.x[UR->operations.x[ii].x[1]].id_s.x[0]+1));
datas.append(QString("%1").arg(UR->id_pr_at_op.x[UR->operations.x[ii].x[1]].id_s.x[1]+1));
datas.append(QString("%1").arg(UR->id_pr_at_op.x[UR->operations.x[ii].x[1]].id_s.x[2]+1));
datas.append(QString("%1").arg(UR->id_pr_at_op.x[UR->operations.x[ii].x[1]].id_s.x[3]+1));
datas.append(QString(UR->id_pr_at_op.x[UR->operations.x[ii].x[1]].name.x));
break;
}
case DEL_PAA :
{
nstr = QString(tr("Delete Atom Node"));
comnms.append(tr("Number of molecule :"));
comnms.append(tr("Number of chain :"));
comnms.append(tr("Number of aminoacid :"));
comnms.append(tr("Number of atom (in amin) :"));
//comnms.append(tr("Name of atom in amin :"));
datas.append(QString("%1").arg(UR->id_pr_at_op.x[UR->operations.x[ii].x[1]].id_s.x[0]+1));
datas.append(QString("%1").arg(UR->id_pr_at_op.x[UR->operations.x[ii].x[1]].id_s.x[1]+1));
datas.append(QString("%1").arg(UR->id_pr_at_op.x[UR->operations.x[ii].x[1]].id_s.x[2]+1));
datas.append(QString("%1").arg(UR->id_pr_at_op.x[UR->operations.x[ii].x[1]].id_s.x[3]+1));
//datas.append(QString("%1").arg(UR->id_pr_dl_op.x[UR->operations.x[ii].x[1]].x[3]+1));
break;
}
case DEL_AMN :
{
nstr = QString(tr("Delete AminoAcid Node"));
comnms.append(tr("Number of molecule :"));
comnms.append(tr("Number of chain :"));
comnms.append(tr("Aminoacid :"));
datas.append(QString("%1").arg(UR->id_pr_am_op.x[UR->operations.x[ii].x[1]].id_s.x[0]+1));
datas.append(QString("%1").arg(UR->id_pr_am_op.x[UR->operations.x[ii].x[1]].id_s.x[1]+1));
datas.append(QString("%1 ( ").arg(UR->id_pr_am_op.x[UR->operations.x[ii].x[1]].id_s.x[2]+1));
datas.last().append(QString(UR->id_pr_am_op.x[UR->operations.x[ii].x[1]].name.x));
datas.last().append(QString(" %1 )").arg(UR->id_pr_am_op.x[UR->operations.x[ii].x[1]].id_ch));
break;
}
case ADD_AMN :
{
nstr = QString(tr("Add AminoAcid Node"));
comnms.append(tr("Number of molecule :"));
comnms.append(tr("Number of chain :"));
comnms.append(tr("Number of aminoacid :"));
datas.append(QString("%1").arg(UR->id_pr_am_op.x[UR->operations.x[ii].x[1]].id_s.x[0]+1));
datas.append(QString("%1").arg(UR->id_pr_am_op.x[UR->operations.x[ii].x[1]].id_s.x[1]+1));
datas.append(QString("%1 ( ").arg(UR->id_pr_am_op.x[UR->operations.x[ii].x[1]].id_s.x[2]+1));
datas.last().append(QString(UR->id_pr_am_op.x[UR->operations.x[ii].x[1]].name.x));
datas.last().append(QString(" %1 )").arg(UR->id_pr_am_op.x[UR->operations.x[ii].x[1]].id_ch));
break;
}
case DEL_CHN :
{
nstr = QString(tr("Delete Chain Node"));
comnms.append(tr("Number of molecule :"));
comnms.append(tr("Number of chain :"));
datas.append(QString("%1").arg(UR->id_pr_ch_op.x[UR->operations.x[ii].x[1]].id_s.x[0]+1));
datas.append(QString("%1 (").arg(UR->id_pr_ch_op.x[UR->operations.x[ii].x[1]].id_s.x[1]+1));
datas.last().append(QChar(UR->id_pr_ch_op.x[UR->operations.x[ii].x[1]].ch));
datas.last().append(QString(")"));
break;
}
case ADD_CHN :
{
nstr = QString(tr("Add Chain Node"));
comnms.append(tr("Number of molecule :"));
comnms.append(tr("Number of chain :"));
datas.append(QString("%1").arg(UR->id_pr_ch_op.x[UR->operations.x[ii].x[1]].id_s.x[0]+1));
datas.append(QString("%1 (").arg(UR->id_pr_ch_op.x[UR->operations.x[ii].x[1]].id_s.x[1]+1));
datas.last().append(QChar(UR->id_pr_ch_op.x[UR->operations.x[ii].x[1]].ch));
datas.last().append(QString(")"));
break;
}
case DEL_PRT :
{
nstr = QString(tr("Delete Protein Node"));
comnms.append(tr("Number of molecule :"));
datas.append(QString("%1").arg(UR->id_pr_pr_op.x[UR->operations.x[ii].x[1]].id_s+1));
break;
}
case ADD_PRT :
{
nstr = QString(tr("Add Protein Node"));
comnms.append(tr("Number of molecule :"));
datas.append(QString("%1").arg(UR->id_pr_pr_op.x[UR->operations.x[ii].x[1]].id_s+1));
break;
}
case STOP_OP :
{
nstr = QString(tr("Stop"));
break;
}
}
sdt<<nstr;
nstr = QString("%1").arg(ii);
nstr.append(QString(" %1").arg(UR->operations.x[ii].x[1]));
sdt<<nstr;
parents.last()->appendChild(new CommandItem(sdt,parents.last()));
parents<<parents.last()->child(parents.last()->childCount()-1);
for(int jj=0;jj<comnms.length();jj++)
{
sdt.clear();
sdt<<comnms.value(jj);
sdt<<datas.value(jj);
parents.last()->appendChild(new CommandItem(sdt,parents.last()));
}
parents<<parents.last()->parent();
}
endResetModel();
}
HstrView::HstrView(QWidget *parent) : QTreeView(parent)
{
// setSelectionMode(QAbstractItemView::ExtendedSelection);
// setSelectionBehavior(QAbstractItemView::SelectRows);
setHorizontalScrollMode ( QAbstractItemView::ScrollPerPixel );
}
//---------------------
undoredo::undoredo(QWidget *parent ) : QWidget(parent)
{
setWindowIcon(QIcon(":/images/undoredo.png"));
setWindowTitle(tr("Undo/Redo Viewer"));
unmodel = new CmdTrModel;
unhistory = new HstrView;
unhistory->setModel(unmodel);
unmodel->setUR(this);
unmodel->setundo();
rdmodel = new CmdTrModel;
rdhistory = new HstrView;
rdhistory->setModel(rdmodel);
rdmodel->setUR(this);
rdmodel->setredo();
//QTextBrowser *textBrowser = new QTextBrowser;
//textBrowser->setText(tr("Some text."));
//QVBoxLayout *mainLayout = new QVBoxLayout;
QLabel *lb = new QLabel(tr("Undo Operations"));
QVBoxLayout *leftLayout = new QVBoxLayout;
leftLayout->addWidget(lb);
leftLayout->addWidget(unhistory);
QLabel *rb = new QLabel(tr("Redo Operations"));
QVBoxLayout *rigthLayout = new QVBoxLayout;
rigthLayout->addWidget(rb);
rigthLayout->addWidget(rdhistory);
QHBoxLayout *mainLayout = new QHBoxLayout;
QWidget * hWidget1, *hWidget2;
hWidget1 = new QWidget;
hWidget2 = new QWidget;
hWidget1->setLayout(leftLayout);
hWidget2->setLayout(rigthLayout);
QSplitter * splitterWidget;
splitterWidget = new QSplitter;
splitterWidget->addWidget(hWidget1);
splitterWidget->addWidget(hWidget2);
mainLayout->addWidget(splitterWidget);
setLayout(mainLayout);
//setWindowFlags(Qt::WindowStaysOnTopHint);
id_cr_op = 0;
op_count = 0;
WF = 0x0;
GW = 0x0;
undoAction = 0x0;
redoAction = 0x0;
}
// методы инициализации
void undoredo::AddMol_init(Molecule *r)
{
vec2int opr;
id_ml_dl_op.add(WF->Mls.N); // запись об инверсной оперции
ml_br_dl_op.add(r);
opr.x[0] = ADD_MOL;
opr.x[1] = id_ml_dl_op.N-1;
operations.add(opr); // запись о прямой операции
}
void undoredo::DelMol_init(int id_ml)
{
vec2int opr;
id_ml_dl_op.add(id_ml);
ml_br_dl_op.pad(WF->Mls.x[id_ml]);
opr.x[0] = DEL_MOL;
opr.x[1] = id_ml_dl_op.N-1;
operations.add(opr); // запись о прямой оперции
// инверсная операция не имеет параметром - для неё нет записи
}
/*void undoredo::AddProt_init(Protein *r)
{
vec2int opr;
id_ml_dl_op.add(WF->Prot.N); // запись об инверсной оперции
ml_br_dl_op.add(r);
opr.x[0] = ADD_MOL;
opr.x[1] = id_ml_dl_op.N-1;
operations.add(opr); // запись о прямой операции
}*/
void undoredo::AddAtm_init(int id_ml)
{
vec2int opr;
//AtomData * ptr = 0x0;
opr.x[0] = id_ml;
opr.x[1] = WF->Mls.x[id_ml]->Atoms.N;
id_at_br_op.add(id_ml);
id_at_dl_op.add(opr); // инверсия оперции
//ptr_dat_op.add(ptr);
opr.x[0] = ADD_ATM;
opr.x[1] = id_at_br_op.N-1;
operations.add(opr);
}
void undoredo::SwpAtm_init(int id_ml,int &id_at1,int &id_at2) // swap атомов id_at1 и id_at2
{
vec2int opr;
vec3int data(id_ml,id_at1,id_at2);
id_at_sw_op.add(data);
opr.x[0] = SWP_ATM;
opr.x[1] = id_at_sw_op.N-1;
operations.add(opr);
}
void undoredo::SwpMol_init(int id_ml1,int &id_ml2) // swap атомов id_at1 и id_at2
{
vec2int opr(id_ml1,id_ml2);
id_ml_sw_op.add(opr);
opr.x[0] = SWP_MOL;
opr.x[1] = id_ml_sw_op.N-1;
operations.add(opr);
}
void undoredo::DelAtm_init(int id_ml,int &id_at)
{
vec2int opr;
opr.x[0] = id_ml;
opr.x[1] = id_at;
//ptr_dat_op.add(WF->Mls.x[id_ml]->Atoms.x[id_at].dat.dat);
id_at_dl_op.add(opr);
id_at_br_op.add(id_ml);// инверсия операции
opr.x[0] = DEL_ATM;
opr.x[1] = id_at_dl_op.N-1;
operations.add(opr);
}
void undoredo::AddPaa_init(int id_ml, int id_ch, int id_am, int id_at, vecT<char> &name)
{
vec2int opr;
data_op12 dat;
dat.id_s.x[0] = id_ml;
dat.id_s.x[1] = id_ch;
dat.id_s.x[2] = id_am;
dat.id_s.x[3] = id_at;
dat.name.pst(name);
id_pr_at_op.pad(dat);
//id_pr_aa_op.add(dat);
//id_pr_dl_op.add(dat); // для инверсной операции
opr.x[0] = ADD_PAA;
opr.x[1] = id_pr_at_op.N-1;
operations.add(opr);
}
void undoredo::DelPaa_init(int id_ml, int id_ch, int id_am, int id_at )
{
vec2int opr;
data_op12 dat;
dat.id_s.x[0] = id_ml;
dat.id_s.x[1] = id_ch;
dat.id_s.x[2] = id_am;
dat.id_s.x[3] = id_at;
dat.name.pst(WF->Mls.x[id_ml]->p_prt->getChild(id_ch)->getChild(id_am)->getChild(id_at)->name);
//vec4int dat(id_ml,id_ch,id_am,id_at);
opr.x[0] = DEL_PAA;
opr.x[1] = id_pr_at_op.N;
id_pr_at_op.pad(dat);
//id_pr_dl_op.add(dat);
//id_pr_aa_op.add(dat); // инверсная операция
operations.add(opr);
}
void undoredo::DelAmn_init(int id_ml, int id_ch, int id_am )
{
vec2int opr;
data_op13 dat;
dat.id_s = vec3int(id_ml,id_ch,id_am);
dat.name.pst(WF->Mls.x[id_ml]->p_prt->getChild(id_ch)->getChild(id_am)->name);
dat.id_ch = WF->Mls.x[id_ml]->p_prt->getChild(id_ch)->getChild(id_am)->id_ch;
opr.x[0] = DEL_AMN;
opr.x[1] = id_pr_am_op.N;
id_pr_am_op.pad(dat);
operations.add(opr);
}
void undoredo::AddAmn_init(int id_ml, int id_ch, int id_am, vecT<char> &name, int id_a)
{
vec2int opr;
data_op13 dat;
dat.id_s = vec3int(id_ml,id_ch,id_am);
dat.name.pst(name);
dat.id_ch = id_a;
opr.x[0] = ADD_AMN;
opr.x[1] = id_pr_am_op.N;
id_pr_am_op.pad(dat);
operations.add(opr);
}
void undoredo::DelChn_init(int id_ml, int id_ch )
{
vec2int opr;
data_op14 dat;
dat.id_s = vec2int(id_ml,id_ch);
dat.ch = WF->Mls.x[id_ml]->p_prt->getChild(id_ch)->ch;
opr.x[0] = DEL_CHN;
opr.x[1] = id_pr_ch_op.N;
id_pr_ch_op.pad(dat);
operations.add(opr);
}
void undoredo::AddChn_init(int id_ml, int id_ch , char ch)
{
vec2int opr;
data_op14 dat;
dat.id_s = vec2int(id_ml,id_ch);
dat.ch = ch;
opr.x[0] = ADD_CHN;
opr.x[1] = id_pr_ch_op.N;
id_pr_ch_op.pad(dat);
operations.add(opr);
}
void undoredo::DelPrt_init(int id_ml )
{
vec2int opr;
opr.x[0] = DEL_PRT;
opr.x[1] = id_pr_pr_op.N;
data_op15 dat;
dat.id_s = id_ml;
dat.protname.pst(WF->Mls.x[id_ml]->p_prt->protname);
id_pr_pr_op.pad(dat);
operations.add(opr);
}
void undoredo::AddPrt_init(int id_ml , vecT<char> &name)
{
vec2int opr;
opr.x[0] = ADD_PRT;
opr.x[1] = id_pr_pr_op.N;
data_op15 dat;
dat.id_s = id_ml;
dat.protname.pst(name);
id_pr_pr_op.pad(dat);
operations.add(opr);
}
//-------
void undoredo::AddBnd_init(int id_ml,int &id_at1,int &id_at2) // добавить связь
{
vec2int opr;
vec3int data(id_ml,id_at1,id_at2);
id_bn_br_op.add(data);
//opr.x[0] = id_ml;
//opr.x[1] = WF->Mls.x[id_ml]->Bonds.N;
id_bn_dl_op.add(data); // инверсия
opr.x[0] = ADD_BND;
opr.x[1] = id_bn_br_op.N-1;
operations.add(opr);
}
void undoredo::DelBnd_init(int id_ml,int &id_at1,int &id_at2) // удалить связь
{
//int id_bn;
vec3int data(id_ml,id_at1,id_at2);
id_bn_dl_op.add(data);
//id_at1 = WF->Mls.x[id_ml]->Bonds.x[id_bn].id_Atoms.x[0];
//id_at2 = WF->Mls.x[id_ml]->Bonds.x[id_bn].id_Atoms.x[1];
id_bn_br_op.add(data); // инверсия
vec2int opr;
opr.x[0] = DEL_BND;
opr.x[1] = id_bn_dl_op.N-1;
operations.add(opr);
}
void undoredo::UniMol_init(int &id_ml1,int &id_ml2) // объединть две молекулы
{
vec2int opr(id_ml1,id_ml2);
id_ml_un_op.add(opr);
opr.x[0] = UNI_MOL;
opr.x[1] = id_ml_un_op.N-1;
operations.add(opr);
id_ml_sp_op.add(WF->Mls.x[id_ml1]->Atoms.N);
// инверсия операци
/*vecT<int> data;
data.var1D(0,1,WF->Mls.x[id_ml2]->Atoms.N);
data += WF->Mls.x[id_ml1]->Atoms.N;*/
//int id = id_ml1>id_ml2 ? id_ml2 : id_ml1;
//id_ml_sp_op.add(id_ml1);
}
void undoredo::SepMol_init(int &id_ml1,int &id_ml2)//,vecT<int> &id_bn)
{
id_ml_sp_op.add(id_ml2);
vec2int opr(id_ml1,WF->Mls.N-1);
id_ml_un_op.add(opr);
opr.x[0] = SEP_MOL;
opr.x[1] = id_ml_un_op.N-1;
operations.add(opr);
// запись для инверсной операции
//opr.x[0] = id_ml;
//opr.x[1] = WF->Mls.N;
//id_ml_un_op.add(opr);
}
void undoredo::ChgTyp_init(int id_ml,int id_at,int id_tp, AtomData *ptr) // изменить тип атома
{
vec2int opr;
vec3int data(id_ml,id_at,id_tp);
id_at_tp_op.add(data);
/*if(ptr==0x0) // 0х0 означает что атом будет удаляться
{
ptr = WF->Mls.x[id_ml]->Atoms.x[id_at].dat.dat;//WF->Mls.x[id_ml].Atoms.x[id_at]
}*/
ptr_dat_op.add(ptr);
opr.x[0] = CHG_TYP;
opr.x[1] = id_at_tp_op.N-1;
operations.add(opr);
}
void undoredo::ChgBnd_init(int id_ml,int &id_at1,int &id_at2,int &id_tp) // изменить тип связи
{
vec2int opr;
vec4int data(id_ml,id_at1,id_at2,id_tp);
id_bn_tp_op.add(data);
opr.x[0] = CHG_BND;
opr.x[1] = id_bn_tp_op.N-1;
operations.add(opr);
}
void undoredo::MovAtm_init(int id_ml,int &id_at,vec3db &dr) // поступательное смещение атома
{
data_op5 op_data;
vec2int opr;
opr.x[0] = MOV_ATM;
opr.x[1] = at_mv_op.N;
operations.add(opr);
op_data.id_at_mv_op.x[0] = id_ml;
op_data.id_at_mv_op.x[1] = id_at;
op_data.dr_at_mv_op = dr;
at_mv_op.add(op_data);
}
void undoredo::MovMol_init(int id_ml,vec3db &dr,vec3db &cq,Quaternion<double> &qa) // смещение и поворот молекулы
{
data_op6 op_data;
vec2int opr;
opr.x[0] = MOV_MOL;
opr.x[1] = ml_mv_op.N;
operations.add(opr);
op_data.id_ml_mv_op = id_ml;
op_data.dr_ml_mv_op = dr;
op_data.cq_ml_mv_op = cq;
op_data.qa_ml_mv_op = qa;
ml_mv_op.add(op_data);
//id_ml_mv_op.add(id_ml);
//dr_ml_mv_op.add(dr);
//cq_ml_mv_op.add(cq);
//qa_ml_mv_op.add(qa);
}
void undoredo::MovFrg_init(int id_ml,vecT<int> &id_at,vec3db &dr,vec3db &cq,Quaternion<double> &qa) // смещение и поворот фрагмента
{
data_op7 op_data;
vec2int opr;
opr.x[0] = MOV_FRG;
opr.x[1] = fr_mv_op.N;
operations.add(opr);
op_data.id_ml = id_ml;
op_data.id_fr_mv_op.pst(id_at);
op_data.dr_fr_mv_op = dr;
op_data.cq_fr_mv_op = cq;
op_data.qa_fr_mv_op = qa;
fr_mv_op.add(op_data);
;
}
void undoredo::Stop_init()
{
vec2int opr;
opr.x[0] = STOP_OP;
opr.x[1] = 0;
operations.add(opr);
id_cr_op = operations.N;
unmodel->updateModel();
rdmodel->updateModel();
}
// ------------------------
// методы операци
void undoredo::SwpAtm_op()
{
int ii,id_ml,id_at1,id_at2;
ii = operations.x[id_cr_op].x[1];
id_ml = id_at_sw_op.x[ii].x[0];
id_at1 = id_at_sw_op.x[ii].x[1];
id_at2 = id_at_sw_op.x[ii].x[2];
GW->swp_Selected_ids(id_ml,id_at1,id_at2);
WF->Mls.x[id_ml]->AtomSwap(id_at1,id_at2);
}
void undoredo::SwpMol_op()
{
int ii,id_ml1,id_ml2;
ii = operations.x[id_cr_op].x[1];
id_ml1 = id_ml_sw_op.x[ii].x[0];
id_ml2 = id_ml_sw_op.x[ii].x[1];
WF->MolSwap(id_ml1,id_ml2);
}
void undoredo::AddMol_op() // добавить пустую молекулу
{
int ii;
ii = operations.x[id_cr_op].x[1];
WF->Mls.add(ml_br_dl_op.x[ii]);
// инверсия текущей оперции:
operations.x[id_cr_op].x[0] = DEL_MOL;
}
void undoredo::DelMol_op() // удалить молекулу
{
int ii,id_ml;//,m;
ii = operations.x[id_cr_op].x[1]; // номер элемента из массива с входными данными
id_ml = id_ml_dl_op.x[ii]; // номер удаляемой молекулы;
--WF->Mls.N;
// инверсия текущей оперции:
operations.x[id_cr_op].x[0] = ADD_MOL;
}
/*void undoredo::AddPrt_op() // добавить пустую молекулу
{
int ii;
ii = operations.x[id_cr_op].x[1];
WF->Prot.add(pr_br_dl_op.x[ii]);
// инверсия текущей оперции:
operations.x[id_cr_op].x[0] = DEL_PRT;
}*/
void undoredo::AddAtm_op()
{
int id_ml,ii;
ii = operations.x[id_cr_op].x[1]; // номер элемента из массива структур входных данных
id_ml = id_at_br_op.x[ii]; // номер молекулы для которой происходит рождене атома
WF->Mls.x[id_ml]->AtomIns(0);
// инверсия текущей оперции:
operations.x[id_cr_op].x[0] = DEL_ATM;
}
void undoredo::DelAtm_op()
{
int id_ml,id_at,ii;
ii = operations.x[id_cr_op].x[1];
id_ml = id_at_dl_op.x[ii].x[0];
id_at = id_at_dl_op.x[ii].x[1];
WF->Mls.x[id_ml]->AtomDel(id_at);
// инверсия текущей оперции:
operations.x[id_cr_op].x[0] = ADD_ATM;
}
void undoredo::AddBnd_op() // добавить связь
{
int ii,id_ml,id_at1,id_at2;
ii = operations.x[id_cr_op].x[1];
id_ml = id_bn_br_op.x[ii].x[0];
id_at1 = id_bn_br_op.x[ii].x[1];
id_at2 = id_bn_br_op.x[ii].x[2];
WF->Mls.x[id_ml]->AddBond(1,id_at1,id_at2);
// инверсия текущей оперции:
operations.x[id_cr_op].x[0] = DEL_BND;
}
void undoredo::DelBnd_op() // удалить связь
{
int ii,id_ml,id_at1,id_at2,id_bn;
ii = operations.x[id_cr_op].x[1];
id_ml = id_bn_dl_op.x[ii].x[0];
id_at1 = id_bn_dl_op.x[ii].x[1];
id_at2 = id_bn_dl_op.x[ii].x[2];
id_bn = WF->Mls.x[id_ml]->Connect.get(id_at1,id_at2)-1;
WF->Mls.x[id_ml]->BondDel(id_bn);
// инверсия текущей оперции:
operations.x[id_cr_op].x[0] = ADD_BND;
}
void undoredo::UniMol_op()
{
int ii,id_ml1,id_ml2;
vecT<int> id1;
ii = operations.x[id_cr_op].x[1];
id_ml1 = id_ml_un_op.x[ii].x[0];
id_ml2 = id_ml_un_op.x[ii].x[1];
WF->Mls.x[id_ml1]->UniMol(WF->Mls.x[id_ml2]);
//WF->Mls.N--;
//delete WF->Mls.x[WF->Mls.N];
// инверсия текущей оперции:
operations.x[id_cr_op].x[0] = SEP_MOL;
}
void undoredo::SepMol_op() // разъединить молекулу на две
{
int ii,jj,id_ml1,id_ml2;
vecT<int> id1,id2;
ii = operations.x[id_cr_op].x[1];
id_ml1 = id_ml_un_op.x[ii].x[0];
id_ml2 = id_ml_un_op.x[ii].x[1];
jj = id_ml_sp_op.x[ii];
WF->Mls.x[id_ml1]->SepMol(WF->Mls.x[id_ml2],jj);
//WF->Mls.x[id_ml1];
//Molecule *m;
//WF->Mls.x[id_ml]->SepMol(*m,id1,id2);
//WF->Mls.add(m);
//m = 0x0;
// коррекция данных о номерах атомов в новообразованных молекулах
/* idmcns(id1);
//n_k = id_ml;
if(idn.N>0)
{
swp3_(id_at_tp_op,0,id_ml,1);
swp2_(id_at_dl_op,0,id_ml,1);
swp3_(id_bn_br_op,0,id_ml,1);
swp3_(id_bn_br_op,0,id_ml,2);
swp3_(id_bn_dl_op,0,id_ml,1);
swp3_(id_bn_dl_op,0,id_ml,2);
swp2_(id_at_mv_op,0,id_ml,1);
swp4_(id_bn_tp_op,0,id_ml,1);
swp4_(id_bn_tp_op,0,id_ml,2);
}
idmcns(id2);
//n_k = jj;
if(idn.N>0)
{
swp_3(id_at_tp_op,0,id_ml,jj,1);
swp_2(id_at_dl_op,0,id_ml,jj,1);
swp3_(id_bn_br_op,0,id_ml,1);
swp_3(id_bn_br_op,0,id_ml,jj,2);
swp3_(id_bn_dl_op,0,id_ml,1);
swp_3(id_bn_dl_op,0,id_ml,jj,2);
swp_2(id_at_mv_op,0,id_ml,jj,1);
swp4_(id_bn_tp_op,0,id_ml,1);
swp_4(id_bn_tp_op,0,id_ml,jj,2);
}*/
// swp2(id_at_dl_op,0,id_ml2,WF->Mls.N);
// инверсия текущей оперции:
operations.x[id_cr_op].x[0] = UNI_MOL;
}
void undoredo::ChgTyp_op() // изменить тип атома
{
int ii,id_ml,id_at,id_tp;
AtomData * ptr;
ii = operations.x[id_cr_op].x[1];
id_ml = id_at_tp_op.x[ii].x[0];
id_at = id_at_tp_op.x[ii].x[1];
id_tp = WF->Mls.x[id_ml]->Atoms.x[id_at].id_Tpz;
ptr = WF->Mls.x[id_ml]->Atoms.x[id_at].dat.dat;
WF->Mls.x[id_ml]->Atoms.x[id_at].id_Tpz = id_at_tp_op.x[ii].x[2];
WF->Mls.x[id_ml]->Atoms.x[id_at].dat.dat = ptr_dat_op.x[ii];
// инверсия оперции
id_at_tp_op.x[ii].x[2] = id_tp;
ptr_dat_op.x[ii] = ptr;
}
void undoredo::ChgBnd_op() // изменить тип связи
{
int ii,id_ml,id_bn,id_tp,id_at1,id_at2;
ii = operations.x[id_cr_op].x[1];
id_ml = id_bn_tp_op.x[ii].x[0];
id_at1 = id_bn_tp_op.x[ii].x[1];
id_at2 = id_bn_tp_op.x[ii].x[2];
id_bn = WF->Mls.x[id_ml]->Connect.get(id_at1,id_at2)-1;
id_tp = WF->Mls.x[id_ml]->Bonds.x[id_bn].oder;
WF->Mls.x[id_ml]->Bonds.x[id_bn].oder = id_bn_tp_op.x[ii].x[3];
// инверсия оперции
id_bn_tp_op.x[ii].x[3] = id_tp;
}
void undoredo::MovAtm_op() // поступательное смещение атома
{
int ii,id_ml,id_at;
vec3db dr;
ii = operations.x[id_cr_op].x[1];
id_ml = at_mv_op.x[ii].id_at_mv_op.x[0];
id_at = at_mv_op.x[ii].id_at_mv_op.x[1];
dr = at_mv_op.x[ii].dr_at_mv_op;
WF->Mls.x[id_ml]->Atoms.x[id_at].r += dr;
// инверсия оперции
at_mv_op.x[ii].dr_at_mv_op *= -1.0;
}
void undoredo::MovMol_op() // смещение и поворот молекулы
{
int jj,ii,id_ml;
vec3db dr,cq,rr;
FullMatrix<double> A;
ii = operations.x[id_cr_op].x[1];
id_ml = ml_mv_op.x[ii].id_ml_mv_op;
dr = ml_mv_op.x[ii].dr_ml_mv_op;
cq = ml_mv_op.x[ii].cq_ml_mv_op;
A = ml_mv_op.x[ii].qa_ml_mv_op.qua2matrR();
for(jj=0;jj<WF->Mls.x[id_ml]->Atoms.N;jj++)
{
rr = WF->Mls.x[id_ml]->Atoms.x[jj].r - cq;
rr = A*rr;
WF->Mls.x[id_ml]->Atoms.x[jj].r = rr + cq + dr;
}
// инверсия
ml_mv_op.x[ii].qa_ml_mv_op.conjugate();
ml_mv_op.x[ii].dr_ml_mv_op *= -1.0;
}
void undoredo::MovFrg_op() // смещение и поворот молекулы
{
int jj,ii,id_ml;
vec3db dr,cq,rr;
vecT<int> ids_at;
FullMatrix<double> A;
ii = operations.x[id_cr_op].x[1];
id_ml = fr_mv_op.x[ii].id_ml;
dr = fr_mv_op.x[ii].dr_fr_mv_op;
cq = fr_mv_op.x[ii].cq_fr_mv_op;
ids_at.N = 0;
ids_at.add(fr_mv_op.x[ii].id_fr_mv_op.x,fr_mv_op.x[ii].id_fr_mv_op.N);
A = fr_mv_op.x[ii].qa_fr_mv_op.qua2matrR();
for(jj=0;jj<ids_at.N;jj++)
{
rr = WF->Mls.x[id_ml]->Atoms.x[ids_at.x[jj]].r - cq;
rr = A*rr;
rr += dr;
WF->Mls.x[id_ml]->Atoms.x[ids_at.x[jj]].r = rr + cq;
}
// инверсия
fr_mv_op.x[ii].qa_fr_mv_op.conjugate();
fr_mv_op.x[ii].dr_fr_mv_op *= -1.0;
}
void undoredo::AddPaa_op()
{
int ii;
ii = operations.x[id_cr_op].x[1];
data_op12 dat;
dat = id_pr_at_op.x[ii];
atom_node * p_atm = WF->Mls.x[dat.id_s.x[0]]->p_prt->addAtomNode(dat.id_s.x[1],dat.id_s.x[2],dat.id_s.x[3]);//)->atom=&WF->Mls.x[data.x[0]]->Atoms.x[data.x[3]];
p_atm->atom = &WF->Mls.x[dat.id_s.x[0]]->Atoms.x[WF->Mls.x[dat.id_s.x[0]]->Atoms.N-1];// связь атом-узла с !!!ПОСЛЕДНИМ!!! атомом
p_atm->atom->dat.dat->amin = p_atm; // связь атома с атом-узлом
p_atm->name.pst(dat.name);
operations.x[id_cr_op].x[0] = DEL_PAA; // инверсия операции
}
void undoredo::DelPaa_op()
{
int ii,id_at;
data_op12 dat;
ii = operations.x[id_cr_op].x[1];
//protein_node * p_prt;
dat = id_pr_at_op.x[ii];
//p_prt = WF->Mls.x[dat.x[0]]->p_prt;
id_at = dat.id_s.x[3]; //WF->Mls.x[dat.x[0]]->Atoms.x[dat.x[3]].dat.dat->amin->id;
//p_prt->getChild(dat.x[1])->getChild(dat.x[2])->delChild(id_at);//->getChild(data.x[2])
WF->Mls.x[dat.id_s.x[0]]->p_prt->childs.x[dat.id_s.x[1]]->childs.x[dat.id_s.x[2]]->delChild(id_at);//->getChild(data.x[2])
operations.x[id_cr_op].x[0] = ADD_PAA; // инверсия операции
}
void undoredo::AddAmn_op()
{
int ii;
ii = operations.x[id_cr_op].x[1];
data_op13 dat;
dat = id_pr_am_op.x[ii];
amino_node * p_atm = new amino_node;//WF->Mls.x[dat.x[0]]->p_prt->addAtomNode(dat.x[1],dat.x[2]);//)->atom=&WF->Mls.x[data.x[0]]->Atoms.x[data.x[3]];
p_atm->id_ch = dat.id_ch;
p_atm->name.pst(dat.name);
WF->Mls.x[dat.id_s.x[0]]->p_prt->childs.x[dat.id_s.x[1]]->addChild(p_atm,dat.id_s.x[2]);
operations.x[id_cr_op].x[0] = DEL_AMN; // инверсия операции
}
void undoredo::DelAmn_op()
{
int ii;
ii = operations.x[id_cr_op].x[1];
data_op13 dat;
dat = id_pr_am_op.x[ii];
WF->Mls.x[dat.id_s.x[0]]->p_prt->childs.x[dat.id_s.x[1]]->delChild(dat.id_s.x[2]);
operations.x[id_cr_op].x[0] = ADD_AMN; // инверсия операции
}
void undoredo::AddChn_op()
{
int ii;
ii = operations.x[id_cr_op].x[1];
data_op14 dat;
dat = id_pr_ch_op.x[ii];
chain_node * p_chs = new chain_node;//WF->Mls.x[dat.x[0]]->p_prt->addAtomNode(dat.x[1],dat.x[2]);//)->atom=&WF->Mls.x[data.x[0]]->Atoms.x[data.x[3]];
p_chs->ch = dat.ch;
WF->Mls.x[dat.id_s.x[0]]->p_prt->addChild(p_chs,dat.id_s.x[1]);
operations.x[id_cr_op].x[0] = DEL_CHN; // инверсия операции
}
void undoredo::DelChn_op()
{
int ii;
ii = operations.x[id_cr_op].x[1];
data_op14 dat;
dat = id_pr_ch_op.x[ii];
WF->Mls.x[dat.id_s.x[0]]->p_prt->delChild(dat.id_s.x[1]);
operations.x[id_cr_op].x[0] = ADD_CHN; // инверсия операции
}
void undoredo::AddPrt_op()
{
int ii;
ii = operations.x[id_cr_op].x[1];
data_op15 dat;
dat = id_pr_pr_op.x[ii];
protein_node * p_prt = new protein_node;//WF->Mls.x[dat.x[0]]->p_prt->addAtomNode(dat.x[1],dat.x[2]);//)->atom=&WF->Mls.x[data.x[0]]->Atoms.x[data.x[3]];
p_prt->protname.pst(dat.protname);
WF->Mls.x[dat.id_s]->p_prt = p_prt;
operations.x[id_cr_op].x[0] = DEL_PRT; // инверсия операции
}
void undoredo::DelPrt_op()
{
int ii;
ii = operations.x[id_cr_op].x[1];
data_op15 dat;
dat = id_pr_pr_op.x[ii];
delete WF->Mls.x[dat.id_s]->p_prt;
WF->Mls.x[dat.id_s]->p_prt = 0x0;
operations.x[id_cr_op].x[0] = ADD_PRT; // инверсия операции
}
void undoredo::Frwd_op()// реализация операции вперёд по списку операций
{
if(id_cr_op<(operations.N-1))
{
//id_cr_op++;
if(!undoAction->isEnabled()) undoAction->setEnabled(true);
for(;(operations.x[id_cr_op].x[0]!=STOP_OP);id_cr_op++)
{
switch (operations.x[id_cr_op].x[0])
{
case ADD_MOL :
{
AddMol_op();
break;
}
case DEL_MOL :
{
DelMol_op(); // удалить молекулу
break;
}
/*case ADD_PRT :
{
AddPrt_op();
break;
}*/
case ADD_ATM :
{
AddAtm_op(); // добавить нетипизированный атом
break;
}
case DEL_ATM :
{
DelAtm_op(); // удалить атом
break;
}
case ADD_BND :
{
AddBnd_op(); // добавить связь
break;
}
case DEL_BND :
{
DelBnd_op(); // удалить связь
break;
}
case UNI_MOL :
{
UniMol_op(); // объединть две молекулы
break;
}
case SEP_MOL :
{
SepMol_op(); // разъединить молекулу на две
break;
}
case CHG_TYP :
{
ChgTyp_op(); // изменить тип атома
break;
}
case CHG_BND :
{
ChgBnd_op(); // изменить тип связи
break;
}
case MOV_ATM :
{
MovAtm_op(); // поступательное смещение атома
break;
}
case MOV_MOL :
{
MovMol_op(); // вращение молекулы
break;
}
case MOV_FRG :
{
MovFrg_op();
break;
}
case SWP_ATM :
{
SwpAtm_op();
break;
}
case SWP_MOL :
{
SwpMol_op();
break;
}
case ADD_PAA :
{
AddPaa_op();
break;
}
case DEL_PAA :
{
DelPaa_op();
break;
}
case DEL_AMN :
{
DelAmn_op();
break;
}
case ADD_AMN :
{
AddAmn_op();
break;
}
case DEL_CHN :
{
DelChn_op();
break;
}
case ADD_CHN :
{
AddChn_op();
break;
}
case DEL_PRT :
{
DelPrt_op();
break;
}
case ADD_PRT :
{
AddPrt_op();
break;
}
case STOP_OP :
{
break;
}
}
}
id_cr_op++;
}
if(id_cr_op>=(operations.N-1))
{
redoAction->setEnabled(false);
}
unmodel->updateModel();
rdmodel->updateModel();
}
void undoredo::Back_op()// реализация операции назад по списку опеаций
{
if(id_cr_op>1)
{
if(!redoAction->isEnabled()) redoAction->setEnabled(true);
id_cr_op--;
id_cr_op--;
for(;(operations.x[id_cr_op].x[0]!=STOP_OP);id_cr_op--)
{
switch (operations.x[id_cr_op].x[0])
{
case ADD_MOL :
{
AddMol_op();
break;
}
case DEL_MOL :
{
DelMol_op(); // удалить молекулу
break;
}
/*case ADD_PRT :
{
AddPrt_op();
break;
}*/
case ADD_ATM :
{
AddAtm_op(); // добавить нетипизированный атом
break;
}
case DEL_ATM :
{
DelAtm_op(); // удалить атом
break;
}
case ADD_BND :
{
AddBnd_op(); // добавить связь
break;
}
case DEL_BND :
{
DelBnd_op(); // удалить связь
break;
}
case UNI_MOL :
{
UniMol_op(); // объединть две молекулы
break;
}
case SEP_MOL :
{
SepMol_op(); // разъединить молекулу на две
break;
}
case CHG_TYP :
{
ChgTyp_op(); // изменить тип атома
break;
}
case CHG_BND :
{
ChgBnd_op(); // изменить тип связи
break;
}
case MOV_ATM :
{
MovAtm_op(); // поступательное смещение атома
break;
}
case MOV_MOL :
{
MovMol_op();
break;
}
case MOV_FRG :
{
MovFrg_op();
break;
}
case SWP_ATM :
{
SwpAtm_op();
break;
}
case SWP_MOL :
{
SwpMol_op();
break;
}
case ADD_PAA :
{
AddPaa_op();
break;
}
case DEL_PAA :
{
DelPaa_op();
break;
}
case DEL_AMN :
{
DelAmn_op();
break;
}
case ADD_AMN :
{
AddAmn_op();
break;
}
case DEL_CHN :
{
DelChn_op();
break;
}
case ADD_CHN :
{
AddChn_op();
break;
}
case DEL_PRT :
{
DelPrt_op();
break;
}
case ADD_PRT :
{
AddPrt_op();
break;
}
case STOP_OP :
{
break;
}
}
}
id_cr_op++;
}
if(id_cr_op<=1)
{
undoAction->setEnabled(false);
}
unmodel->updateModel();
rdmodel->updateModel();
}
void undoredo::reset_op() // сброс операций описанных впереди от текущего положения индикатора операций
{
int ii;
ii = operations.N;
ii--;
for(;ii>=id_cr_op;ii--)
{
switch (operations.x[ii].x[0])
{
case ADD_MOL :
{
id_ml_dl_op.N--;
ml_br_dl_op.N--;
Molecule *mol = ml_br_dl_op.x[ml_br_dl_op.N];
if (ml_br_dl_op.fnd(mol)==-1)// найти ниаменьший номер ячейки с указателем совпадаюсщим с текущим указателем
{ // если дугих таких таких указателей нет, то данные по текущему указателю можно удалять
delete ml_br_dl_op.x[ml_br_dl_op.N];
}
ml_br_dl_op.x[ml_br_dl_op.N] = 0x0;
break;
}
case DEL_MOL :
{
id_ml_dl_op.N--; // удалить молекулу
ml_br_dl_op.N--;
Molecule *mol = ml_br_dl_op.x[ml_br_dl_op.N];
if (ml_br_dl_op.fnd(mol)==-1)// найти ниаменьший номер ячейки с указателем совпадаюсщим с текущим указателем
{ // если дугих таких таких указателей нет, то данные по текущему указателю можно удалять
delete ml_br_dl_op.x[ml_br_dl_op.N];
}
ml_br_dl_op.x[ml_br_dl_op.N] = 0x0;
break;
}
case ADD_ATM :
{
id_at_br_op.N--; // добавить нетипизированный атом
id_at_dl_op.N--;
break;
}
case DEL_ATM :
{
id_at_br_op.N--; // удалить нетипизированный атом
id_at_dl_op.N--;
break;
}
case ADD_BND :
{
id_bn_br_op.N--;
id_bn_dl_op.N--;
break;
}
case DEL_BND :
{
id_bn_br_op.N--;
id_bn_dl_op.N--;
break;
}
case UNI_MOL :
{
id_ml_un_op.N--;
id_ml_sp_op.N--;
break;
}
case SEP_MOL :
{
id_ml_un_op.N--;
id_ml_sp_op.N--;
break;
}
case CHG_TYP :
{
id_at_tp_op.N--;
if(ptr_dat_op.x[id_at_tp_op.N]!=0x0)
{
delete ptr_dat_op.x[id_at_tp_op.N];
ptr_dat_op.x[id_at_tp_op.N] = 0x0;
}
ptr_dat_op.N--;
break;
}
case CHG_BND :
{
id_bn_tp_op.N--;
break;
}
case MOV_ATM :
{
at_mv_op.N--;
break;
}
case MOV_MOL :
{
ml_mv_op.N--;
break;
}
case MOV_FRG :
{
fr_mv_op.N--;
break;
}
case SWP_ATM :
{
id_at_sw_op.N--;
break;
}
case SWP_MOL :
{
id_ml_sw_op.N--;
break;
}
case ADD_PAA :
{
id_pr_at_op.N--;
//id_pr_dl_op.N--;
break;
}
case DEL_PAA :
{
id_pr_at_op.N--;
//id_pr_dl_op.N--;
break;
}
case DEL_AMN :
{
id_pr_am_op.N--;
break;
}
case ADD_AMN :
{
id_pr_am_op.N--;
break;
}
case DEL_CHN :
{
id_pr_ch_op.N--;
break;
}
case ADD_CHN :
{
id_pr_ch_op.N--;
break;
}
case DEL_PRT :
{
id_pr_pr_op.N--;
break;
}
case ADD_PRT :
{
id_pr_pr_op.N--;
break;
}
case STOP_OP :
{
break;
}
}
}
operations.N = id_cr_op;
redoAction->setEnabled(false);
}
void undoredo::reset_all() // сброс всех операций
{
id_cr_op = 1;
reset_op();
}
void undoredo::chesk_reset()
{
if(operations.N!=id_cr_op) reset_op();
}
// ----------------------------
#endif | [
"noreply@github.com"
] | noreply@github.com |
790c37361eaced9a6ddc7d3ba44c140a5080c639 | 83cf4a77f4ceca344a2ec4bc6cb25614120ea032 | /toolkit/Source/src/gs2d/src/Video/Direct3D9/D3D9Texture.cpp | 37d4f067333fee169503759b887e5f18152d868c | [
"MIT"
] | permissive | kylemsguy/snake-shooter-mobile | e8b6a84a400562fd53294f056330d928179f4785 | 322c72d1844565fa8f9859ec450f3161821d1013 | refs/heads/master | 2020-12-25T05:25:24.122305 | 2015-08-19T09:35:07 | 2015-08-19T09:35:07 | 41,019,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,619 | cpp | /*--------------------------------------------------------------------------------------
Ethanon Engine (C) Copyright 2008-2013 Andre Santee
http://ethanonengine.com/
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------------*/
#include "D3D9Texture.h"
#include "../../Video.h"
namespace gs2d {
using namespace math;
D3D9Texture::D3D9Texture()
{
m_pTexture = NULL;
m_pDevice = NULL;
m_texType = Texture::TT_NONE;
}
D3D9Texture::~D3D9Texture()
{
if (m_pTexture)
{
m_pTexture->Release();
m_pTexture = NULL;
}
}
bool D3D9Texture::CreateRenderTarget(VideoWeakPtr video, const unsigned int width, const unsigned int height,
const TARGET_FORMAT fmt)
{
m_video = video;
GetInternalData();
IDirect3DTexture9 *pTexture = NULL;
m_profile.mask = 0x0;
m_profile.nMipMaps = 1;
m_texType = TT_RENDER_TARGET;
const DWORD dwUsage = D3DUSAGE_RENDERTARGET;
if (width <= 0 || height <= 0)
{
str_type::stringstream ss;
ss << GS_L("Couldn't create the render surface - D3D9Texture::LoadTexture") << std::endl;
ShowMessage(ss, GSMT_ERROR);
return false;
}
IDirect3DSurface9 *pBackBuffer = NULL;
D3DSURFACE_DESC surfDesc;
m_pDevice->GetRenderTarget(0, &pBackBuffer);
pBackBuffer->GetDesc(&surfDesc);
pBackBuffer->Release();
m_pDevice->CreateTexture(width, height, 1,
dwUsage, (fmt == TF_ARGB) ? D3DFMT_A8R8G8B8 : surfDesc.Format,
D3DPOOL_DEFAULT, &pTexture, NULL);
m_profile.width = width;
m_profile.height = height;
m_profile.originalWidth = m_profile.width;
m_profile.originalHeight = m_profile.height;
m_pTexture = pTexture;
return true;
}
bool D3D9Texture::LoadTexture(VideoWeakPtr video, const str_type::string& fileName, Color mask,
const unsigned int width, const unsigned int height, const unsigned int nMipMaps)
{
Platform::FileManagerPtr fileManager = video.lock()->GetFileIOHub()->GetFileManager();
Platform::FileBuffer out;
fileManager->GetFileBuffer(fileName, out);
bool r = false;
if (out)
{
r = LoadTexture(video, out->GetAddress(), mask, width, height, nMipMaps, out->GetBufferSize());
}
if (!r)
{
str_type::stringstream ss;
ss << GS_L("D3D9Texture::LoadTextureFromFile:\nCannot find and/or create the texture from a bitmap: ");
ss << fileName << std::endl;
ShowMessage(ss, GSMT_ERROR);
}
return r;
}
bool D3D9Texture::LoadTexture(VideoWeakPtr video, const void *pBuffer, Color mask,
const unsigned int width, const unsigned int height,
const unsigned int nMipMaps, const unsigned int bufferLength)
{
m_video = video;
GetInternalData();
IDirect3DTexture9 *pTexture = NULL;
m_profile.mask = mask;
m_profile.nMipMaps = nMipMaps;
m_texType = TT_STATIC;
if (m_texType == TT_STATIC)
{
D3DXIMAGE_INFO imageInfo;
HRESULT hr;
hr = D3DXCreateTextureFromFileInMemoryEx(
m_pDevice,
pBuffer,
bufferLength,
(width) ? width : D3DX_DEFAULT_NONPOW2,
(height) ? height : D3DX_DEFAULT_NONPOW2,
(nMipMaps == FULL_MIPMAP_CHAIN) ? D3DX_DEFAULT : Max(nMipMaps, static_cast<unsigned int>(1)),
0,
D3DFMT_UNKNOWN,
D3DPOOL_MANAGED,
D3DX_DEFAULT,
D3DX_DEFAULT,
mask.color,
&imageInfo,
NULL,
&pTexture
);
if (FAILED(hr))
{
return false;
}
if (width == 0 && height == 0)
{
m_profile.width = imageInfo.Width;
m_profile.height = imageInfo.Height;
}
else
{
m_profile.width = width;
m_profile.height = height;
}
m_profile.originalWidth = imageInfo.Width;
m_profile.originalHeight = imageInfo.Height;
}
m_pTexture = pTexture;
return true;
}
bool D3D9Texture::GetInternalData()
{
try
{
Video *pVideo = m_video.lock().get();
m_pDevice = boost::any_cast<IDirect3DDevice9*>(pVideo->GetGraphicContext());
}
catch (const boost::bad_any_cast &)
{
str_type::stringstream ss;
ss << GS_L("D3D9Texture::GetInternalData: Invalid device");
ShowMessage(ss, GSMT_ERROR);
return false;
}
return true;
}
bool D3D9Texture::IsAllBlack() const
{
ShowMessage(GS_L("D3D9Texture::IsAllBlack: Method not implemented on D3D9"), GSMT_WARNING);
return false;
}
Vector2 D3D9Texture::GetBitmapSize() const
{
return Vector2(static_cast<float>(m_profile.width), static_cast<float>(m_profile.height));
}
bool D3D9Texture::SetTexture(const unsigned int passIdx)
{
m_pDevice->SetTexture(passIdx, m_pTexture);
return true;
}
Texture::PROFILE D3D9Texture::GetProfile() const
{
return m_profile;
}
Texture::TYPE D3D9Texture::GetTextureType() const
{
return m_texType;
}
boost::any D3D9Texture::GetTextureObject()
{
return m_pTexture;
}
} // namespace gs2d
| [
"andre.santee@gmail.com"
] | andre.santee@gmail.com |
494b50d6f2efed1de9341b87e5102c02c5c34691 | 055ebf98f1029a0134866fcaf49dccad26f80258 | /MemoryPool/pool.h | 9551f58c87945cb92d4fbdf589024a89b6170788 | [] | no_license | xiaopeifeng/CodeTricks | 24249e675296e94b93012216eb49bc880a1724d2 | 105096b9ebaf6f1c176c371a185a38d05764dbce | refs/heads/master | 2021-06-02T02:03:02.231720 | 2019-10-07T07:44:31 | 2019-10-07T07:44:31 | 26,275,437 | 21 | 13 | null | null | null | null | UTF-8 | C++ | false | false | 328 | h | #pragma once
#include <vector>
class memory_pool
{
public:
explicit memory_pool(unsigned int num, unsigned int size);
~memory_pool();
public:
void* Allocate();
void Release(void* ptr);
private:
unsigned int _total_blocks;
unsigned int _block_size;
std::vector<void*> _free_blocks;
std::vector<void*> _busy_blocks;
}; | [
"xiaopeifenng@gmail.com"
] | xiaopeifenng@gmail.com |
a74f5f56b841464dd80a3fa4ecdc72852e751fd6 | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/ui/views/controls/combobox/combobox.h | e71604e4238bf4f8a41c5a35b4b79bf8a4256744 | [
"BSD-3-Clause"
] | permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,707 | h | // 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 UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_H_
#define UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_H_
#include <string>
#include "ui/gfx/native_widget_types.h"
#include "ui/views/controls/combobox/native_combobox_wrapper.h"
#include "ui/views/controls/prefix_delegate.h"
#include "ui/views/view.h"
namespace gfx {
class Font;
}
namespace ui {
class ComboboxModel;
}
namespace views {
class ComboboxListener;
class PrefixSelector;
// A non-editable combobox (aka a drop-down list).
class VIEWS_EXPORT Combobox : public PrefixDelegate {
public:
// The combobox's class name.
static const char kViewClassName[];
// |model| is not owned by the combobox.
explicit Combobox(ui::ComboboxModel* model);
virtual ~Combobox();
static const gfx::Font& GetFont();
// Sets the listener which will be called when a selection has been made.
void set_listener(ComboboxListener* listener) {
listener_ = listener;
}
// Informs the combobox that its model changed.
void ModelChanged();
// Gets/Sets the selected index.
int selected_index() const { return selected_index_; }
void SetSelectedIndex(int index);
// Called when the combobox's selection is changed by the user.
void SelectionChanged();
ui::ComboboxModel* model() const { return model_; }
// Set the accessible name of the combobox.
void SetAccessibleName(const string16& name);
// Provided only for testing:
gfx::NativeView GetTestingHandle() const {
return native_wrapper_ ? native_wrapper_->GetTestingHandle() : NULL;
}
NativeComboboxWrapper* GetNativeWrapperForTesting() const {
return native_wrapper_;
}
// Visually marks the combobox as having an invalid value selected. The caller
// is responsible for flipping it back to valid if the selection changes.
void SetInvalid(bool invalid);
bool invalid() const {
return invalid_;
}
// Overridden from View:
virtual gfx::Size GetPreferredSize() OVERRIDE;
virtual void Layout() OVERRIDE;
virtual void OnEnabledChanged() OVERRIDE;
virtual bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) OVERRIDE;
virtual void OnPaintFocusBorder(gfx::Canvas* canvas) OVERRIDE;
virtual bool OnKeyPressed(const ui::KeyEvent& e) OVERRIDE;
virtual bool OnKeyReleased(const ui::KeyEvent& e) OVERRIDE;
virtual void OnFocus() OVERRIDE;
virtual void OnBlur() OVERRIDE;
virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE;
virtual ui::TextInputClient* GetTextInputClient() OVERRIDE;
// Overridden from PrefixDelegate:
virtual int GetRowCount() OVERRIDE;
virtual int GetSelectedRow() OVERRIDE;
virtual void SetSelectedRow(int row) OVERRIDE;
virtual string16 GetTextForRow(int row) OVERRIDE;
protected:
// Overridden from View:
virtual void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) OVERRIDE;
virtual const char* GetClassName() const OVERRIDE;
// The object that actually implements the native combobox.
NativeComboboxWrapper* native_wrapper_;
private:
// Our model. Not owned.
ui::ComboboxModel* model_;
// Our listener. Not owned. Notified when the selected index change.
ComboboxListener* listener_;
// The current selected index.
int selected_index_;
// True when the selection is visually denoted as invalid.
bool invalid_;
// The accessible name of this combobox.
string16 accessible_name_;
scoped_ptr<PrefixSelector> selector_;
DISALLOW_COPY_AND_ASSIGN(Combobox);
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_H_
| [
"ProjectRetroScope@gmail.com"
] | ProjectRetroScope@gmail.com |
dc82a706ec7985b176c7fcbf51a7423f80149b4a | fafce52a38479e8391173f58d76896afcba07847 | /uppdev/GridCtrlMC/GridDisplay.h | 756258e93a90ab4a90ef640fad23626451e043c0 | [] | no_license | Sly14/upp-mirror | 253acac2ec86ad3a3f825679a871391810631e61 | ed9bc6028a6eed422b7daa21139a5e7cbb5f1fb7 | refs/heads/master | 2020-05-17T08:25:56.142366 | 2015-08-24T18:08:09 | 2015-08-24T18:08:09 | 41,750,819 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,631 | h | #ifndef _GridCtrl_GridDisplay_h_
#define _GridCtrl_GridDisplay_h_
#define IMAGEFILE <GridCtrl/GridDisplay.iml>
#define IMAGECLASS GridDispImg
#include <Draw/iml_header.h>
#define BIT(x) (1 << x)
class GridCtrl;
namespace GD
{
enum
{
CURSOR = BIT(0),
SELECT = BIT(1),
LIVE = BIT(2),
FOCUS = BIT(3),
READONLY = BIT(4),
FOUND = BIT(5),
HIGHLIGHT = BIT(6),
EVEN = BIT(7),
ODD = BIT(8),
LEFT = BIT(9),
RIGHT = BIT(10),
TOP = BIT(11),
BOTTOM = BIT(12),
HCENTER = BIT(13),
VCENTER = BIT(14),
HPOS = BIT(15),
VPOS = BIT(16),
WRAP = BIT(17),
CHAMELEON = BIT(18),
NOTEXT = BIT(19),
ALIGN = LEFT | RIGHT | TOP | BOTTOM | VCENTER | HCENTER
};
}
class GridDisplay
{
public:
Image leftImg;
Image rightImg;
Image centerImg;
Image bgImg;
Font font;
int align;
int lm, rm, tm, bm;
int theme;
bool hgrid;
bool vgrid;
int col, row;
GridCtrl *parent;
GridDisplay() : font(StdFont())
{
align = GD::TOP | GD::LEFT;
lm = rm = 4;
tm = bm = 0;
theme = 5;
}
~GridDisplay() {};
void SetLeftImage(const Image &img) { leftImg = img; }
void SetRightImage(const Image &img) { rightImg = img; }
void SetCenterImage(const Image &img) { centerImg = img; }
void SetBgImage(Image &img) { bgImg = img; }
void SetFont(Font &fnt) { font = fnt; }
void SetTextAlign(int al) { align = al; }
void SetHMargin(int left, int right) { lm = left; rm = right; }
void SetVMargin(int top, int bottom) { tm = top; bm = bottom; }
void SetTheme(int th) { theme = th; }
int GetThemeCount() { return 6; }
void DrawText(Draw &w, int mx, int x, int y, int cx, int cy, int align,
const wchar *s, const Font &font, const Color &fg, const Color &bg,
bool found, int fs, int fe, bool wrap);
virtual void Paint(Draw &w, int x, int y, int cx, int cy, const Value &val, dword style,
Color &fg, Color &bg, Font &fnt, bool found = false, int fs = 0, int fe = 0);
virtual void PaintFixed(Draw &w, bool firstx, bool firsty, int x, int y, int cx, int cy, const Value &val, dword style,
bool indicator = false, bool moved = false,
int sortmode = 0, int sortcol = -1, int sortcnt = 0, bool horizontal = true);
};
extern GridDisplay StdGridDisplay;
#endif
| [
"cxl@ntllib.org"
] | cxl@ntllib.org |
e4eb7a8a91041a77ae483d31d0c6868b24388131 | 8d334310b4f744ba689ea5d40c97479579c459f1 | /src/lib/Module.cpp | 1168e0c8cde569a086c83c1cbfdded1528d50969 | [
"BSD-2-Clause"
] | permissive | mwasplund/botan | af01e6152277dfa3d0c5ef3ecdb69d531ef66d64 | 4a81a54d741aeef70f482cdf89015b7fa4229229 | refs/heads/master | 2021-03-10T12:57:29.069423 | 2020-04-15T19:18:37 | 2020-04-15T19:18:37 | 246,454,923 | 0 | 0 | null | 2020-03-11T02:22:29 | 2020-03-11T02:22:28 | null | UTF-8 | C++ | false | false | 10,716 | cpp | module;
#include <cstddef>
#include <algorithm>
#include <array>
#include <chrono>
#include <cctype>
#include <cstdint>
#include <deque>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <type_traits>
export module Botan;
#include <botan/assert.h>
#include <botan/build.h>
#include <botan/types.h>
#include <botan/aead.h>
#include <botan/base64.h>
#include <botan/bcrypt_pbkdf.h>
#include <botan/ber_dec.h>
#include <botan/bigint.h>
#include <botan/block_cipher.h>
#include <botan/calendar.h>
#include <botan/cbc.h>
#include <botan/certstor_system.h>
#include <botan/certstor_windows.h>
#include <botan/charset.h>
#include <botan/cpuid.h>
#include <botan/credentials_manager.h>
#include <botan/ctr.h>
#include <botan/curve_nistp.h>
#include <botan/der_enc.h>
#include <botan/dh.h>
#include <botan/divide.h>
#include <botan/blinding.h>
#include <botan/blowfish.h>
#include <botan/ecdh.h>
#include <botan/elgamal.h>
#include <botan/emsa_pkcs1.h>
#include <botan/emsa.h>
#include <botan/entropy_src.h>
#include <botan/ghash.h>
#include <botan/hash_id.h>
#include <botan/hash.h>
#include <botan/hex.h>
#include <botan/keypair.h>
#include <botan/loadstor.h>
#include <botan/mac.h>
#include <botan/oids.h>
#include <botan/parsing.h>
#include <botan/pem.h>
#include <botan/pk_algs.h>
#include <botan/pk_ops.h>
#include <botan/pubkey.h>
#include <botan/rng.h>
#include <botan/rotate.h>
#include <botan/rsa.h>
#include <botan/scan_name.h>
#include <botan/stream_cipher.h>
#include <botan/system_rng.h>
#include <botan/tls_callbacks.h>
#include <botan/tls_client.h>
#include <botan/tls_exceptn.h>
#include <botan/tls_messages.h>
#include <botan/tls_policy.h>
#include <botan/tls_session_manager.h>
#include <botan/x509path.h>
#include <botan/internal/bit_ops.h>
#include <botan/internal/codec_base.h>
#include <botan/internal/ct_utils.h>
#include <botan/internal/filesystem.h>
#include <botan/internal/mp_core.h>
#include <botan/internal/mp_monty.h>
#include <botan/internal/os_utils.h>
#include <botan/internal/padding.h>
#include <botan/internal/pk_ops_impl.h>
#include <botan/internal/primality.h>
#include <botan/internal/rounding.h>
#include <botan/internal/safeint.h>
#include <botan/internal/socket.h>
#include <botan/internal/stl_util.h>
#include <botan/internal/timer.h>
#include <botan/internal/tls_cbc.h>
#include <botan/internal/tls_handshake_io.h>
#include <botan/internal/tls_handshake_hash.h>
#include <botan/internal/tls_handshake_state.h>
#include <botan/internal/tls_reader.h>
#include <botan/internal/tls_record.h>
#include <botan/internal/tls_seq_numbers.h>
#include <botan/internal/tls_session_key.h>
#if defined(BOTAN_HAS_CERTSTOR_MACOS)
#include <botan/certstor_macos.h>
#elif defined(BOTAN_HAS_CERTSTOR_WINDOWS)
#include <botan/certstor_windows.h>
#elif defined(BOTAN_HAS_CERTSTOR_FLATFILE) && defined(BOTAN_SYSTEM_CERT_BUNDLE)
#include <botan/certstor_flatfile.h>
#endif
#if defined(BOTAN_HAS_TLS_CBC)
#include <botan/internal/tls_cbc.h>
#endif
#if defined(BOTAN_HAS_EMSA1)
#include <botan/emsa1.h>
#endif
#if defined(BOTAN_HAS_EMSA_X931)
#include <botan/emsa_x931.h>
#endif
#if defined(BOTAN_HAS_EMSA_PKCS1)
#include <botan/emsa_pkcs1.h>
#endif
#if defined(BOTAN_HAS_EMSA_PSSR)
#include <botan/pssr.h>
#endif
#if defined(BOTAN_HAS_EMSA_RAW)
#include <botan/emsa_raw.h>
#endif
#if defined(BOTAN_HAS_ISO_9796)
#include <botan/iso9796.h>
#endif
#if defined(BOTAN_HAS_SCRYPT)
#include <botan/scrypt.h>
#endif
#if defined(BOTAN_HAS_PBKDF1)
#include <botan/pbkdf1.h>
#endif
#if defined(BOTAN_HAS_PBKDF2)
#include <botan/pbkdf2.h>
#endif
#if defined(BOTAN_HAS_PGP_S2K)
#include <botan/pgp_s2k.h>
#endif
#if defined(BOTAN_HAS_MODE_XTS)
#include <botan/xts.h>
#endif
#if defined(BOTAN_HAS_GCM_CLMUL_CPU)
#include <botan/internal/clmul_cpu.h>
#endif
#if defined(BOTAN_HAS_GCM_CLMUL_SSSE3)
#include <botan/internal/clmul_ssse3.h>
#endif
#if defined(BOTAN_HAS_BLOCK_CIPHER)
#include <botan/block_cipher.h>
#endif
#if defined(BOTAN_HAS_AEAD_CCM)
#include <botan/ccm.h>
#endif
#if defined(BOTAN_HAS_AEAD_CHACHA20_POLY1305)
#include <botan/chacha20poly1305.h>
#endif
#if defined(BOTAN_HAS_AEAD_EAX)
#include <botan/eax.h>
#endif
#if defined(BOTAN_HAS_AEAD_GCM)
#include <botan/gcm.h>
#endif
#if defined(BOTAN_HAS_AEAD_OCB)
#include <botan/ocb.h>
#endif
#if defined(BOTAN_HAS_AEAD_SIV)
#include <botan/siv.h>
#endif
#if defined(BOTAN_HAS_CBC_MAC)
#include <botan/cbc_mac.h>
#endif
#if defined(BOTAN_HAS_CMAC)
#include <botan/cmac.h>
#endif
#if defined(BOTAN_HAS_GMAC)
#include <botan/gmac.h>
#include <botan/block_cipher.h>
#endif
#if defined(BOTAN_HAS_HMAC)
#include <botan/hmac.h>
#include <botan/hash.h>
#endif
#if defined(BOTAN_HAS_POLY1305)
#include <botan/poly1305.h>
#endif
#if defined(BOTAN_HAS_SIPHASH)
#include <botan/siphash.h>
#endif
#if defined(BOTAN_HAS_ANSI_X919_MAC)
#include <botan/x919_mac.h>
#endif
#if defined(BOTAN_HAS_HKDF)
#include <botan/hkdf.h>
#endif
#if defined(BOTAN_HAS_KDF1)
#include <botan/kdf1.h>
#endif
#if defined(BOTAN_HAS_KDF2)
#include <botan/kdf2.h>
#endif
#if defined(BOTAN_HAS_KDF1_18033)
#include <botan/kdf1_iso18033.h>
#endif
#if defined(BOTAN_HAS_TLS_V10_PRF) || defined(BOTAN_HAS_TLS_V12_PRF)
#include <botan/prf_tls.h>
#endif
#if defined(BOTAN_HAS_X942_PRF)
#include <botan/prf_x942.h>
#endif
#if defined(BOTAN_HAS_SP800_108)
#include <botan/sp800_108.h>
#endif
#if defined(BOTAN_HAS_SP800_56A)
#include <botan/sp800_56a.h>
#endif
#if defined(BOTAN_HAS_SP800_56C)
#include <botan/sp800_56c.h>
#endif
#if defined(BOTAN_HAS_ADLER32)
#include <botan/adler32.h>
#endif
#if defined(BOTAN_HAS_CRC24)
#include <botan/crc24.h>
#endif
#if defined(BOTAN_HAS_CRC32)
#include <botan/crc32.h>
#endif
#if defined(BOTAN_HAS_GOST_34_11)
#include <botan/gost_3411.h>
#endif
#if defined(BOTAN_HAS_KECCAK)
#include <botan/keccak.h>
#endif
#if defined(BOTAN_HAS_MD4)
#include <botan/md4.h>
#endif
#if defined(BOTAN_HAS_MD5)
#include <botan/md5.h>
#endif
#if defined(BOTAN_HAS_RIPEMD_160)
#include <botan/rmd160.h>
#endif
#if defined(BOTAN_HAS_SHA1)
#include <botan/sha160.h>
#endif
#if defined(BOTAN_HAS_SHA2_32)
#include <botan/sha2_32.h>
#endif
#if defined(BOTAN_HAS_SHA2_64)
#include <botan/sha2_64.h>
#endif
#if defined(BOTAN_HAS_SHA3)
#include <botan/sha3.h>
#endif
#if defined(BOTAN_HAS_SKEIN_512)
#include <botan/skein_512.h>
#endif
#if defined(BOTAN_HAS_SHAKE)
#include <botan/shake.h>
#endif
#if defined(BOTAN_HAS_STREEBOG)
#include <botan/streebog.h>
#endif
#if defined(BOTAN_HAS_SM3)
#include <botan/sm3.h>
#endif
#if defined(BOTAN_HAS_TIGER)
#include <botan/tiger.h>
#endif
#if defined(BOTAN_HAS_WHIRLPOOL)
#include <botan/whrlpool.h>
#endif
#if defined(BOTAN_HAS_PARALLEL_HASH)
#include <botan/par_hash.h>
#endif
#if defined(BOTAN_HAS_COMB4P)
#include <botan/comb4p.h>
#endif
#if defined(BOTAN_HAS_BLAKE2B)
#include <botan/blake2b.h>
#endif
#if defined(BOTAN_HAS_EME_OAEP)
#include <botan/oaep.h>
#endif
#if defined(BOTAN_HAS_EME_PKCS1)
#include <botan/eme_pkcs.h>
#endif
#if defined(BOTAN_HAS_EME_RAW)
#include <botan/eme_raw.h>
#endif
#if defined(BOTAN_HAS_CHACHA)
#include <botan/chacha.h>
#endif
#if defined(BOTAN_HAS_SALSA20)
#include <botan/salsa20.h>
#endif
#if defined(BOTAN_HAS_SHAKE_CIPHER)
#include <botan/shake_cipher.h>
#endif
#if defined(BOTAN_HAS_CTR_BE)
#include <botan/ctr.h>
#endif
#if defined(BOTAN_HAS_OFB)
#include <botan/ofb.h>
#endif
#if defined(BOTAN_HAS_RC4)
#include <botan/rc4.h>
#endif
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
#include <botan/locking_allocator.h>
#endif
#if defined(BOTAN_HAS_SYSTEM_RNG)
#include <botan/system_rng.h>
#endif
#if defined(BOTAN_HAS_ENTROPY_SRC_RDRAND)
#include <botan/internal/rdrand.h>
#endif
#if defined(BOTAN_HAS_ENTROPY_SRC_RDSEED)
#include <botan/internal/rdseed.h>
#endif
#if defined(BOTAN_HAS_ENTROPY_SRC_DARN)
#include <botan/internal/p9_darn.h>
#endif
#if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM)
#include <botan/internal/dev_random.h>
#endif
#if defined(BOTAN_HAS_ENTROPY_SRC_WIN32)
#include <botan/internal/es_win32.h>
#endif
#if defined(BOTAN_HAS_ENTROPY_SRC_PROC_WALKER)
#include <botan/internal/proc_walk.h>
#include <botan/internal/os_utils.h>
#endif
#if defined(BOTAN_HAS_ENTROPY_SRC_GETENTROPY)
#include <botan/internal/getentropy.h>
#endif
#if defined(BOTAN_HAS_HTTP_UTIL)
#include <botan/http_util.h>
#endif
#if defined(BOTAN_TARGET_OS_HAS_RTLGENRANDOM)
#include <botan/dyn_load.h>
#endif
#if defined(BOTAN_HAS_AES)
#include <botan/aes.h>
#endif
#if defined(BOTAN_HAS_ARIA)
#include <botan/aria.h>
#endif
#if defined(BOTAN_HAS_BLOWFISH)
#include <botan/blowfish.h>
#endif
#if defined(BOTAN_HAS_CAMELLIA)
#include <botan/camellia.h>
#endif
#if defined(BOTAN_HAS_CAST_128)
#include <botan/cast128.h>
#endif
#if defined(BOTAN_HAS_CAST_256)
#include <botan/cast256.h>
#endif
#if defined(BOTAN_HAS_CASCADE)
#include <botan/cascade.h>
#endif
#if defined(BOTAN_HAS_DES)
#include <botan/des.h>
#include <botan/desx.h>
#endif
#if defined(BOTAN_HAS_GOST_28147_89)
#include <botan/gost_28147.h>
#endif
#if defined(BOTAN_HAS_IDEA)
#include <botan/idea.h>
#endif
#if defined(BOTAN_HAS_KASUMI)
#include <botan/kasumi.h>
#endif
#if defined(BOTAN_HAS_LION)
#include <botan/lion.h>
#endif
#if defined(BOTAN_HAS_MISTY1)
#include <botan/misty1.h>
#endif
#if defined(BOTAN_HAS_NOEKEON)
#include <botan/noekeon.h>
#endif
#if defined(BOTAN_HAS_SEED)
#include <botan/seed.h>
#endif
#if defined(BOTAN_HAS_SERPENT)
#include <botan/serpent.h>
#endif
#if defined(BOTAN_HAS_SHACAL2)
#include <botan/shacal2.h>
#endif
#if defined(BOTAN_HAS_SM4)
#include <botan/sm4.h>
#endif
#if defined(BOTAN_HAS_TWOFISH)
#include <botan/twofish.h>
#endif
#if defined(BOTAN_HAS_THREEFISH_512)
#include <botan/threefish_512.h>
#endif
#if defined(BOTAN_HAS_XTEA)
#include <botan/xtea.h>
#endif
#if defined(BOTAN_HAS_OPENSSL)
#include <botan/internal/openssl.h>
#endif
#if defined(BOTAN_HAS_COMMONCRYPTO)
#include <botan/internal/commoncrypto.h>
#endif | [
"mwasplund@outlook.com"
] | mwasplund@outlook.com |
b78b6b7dbdb0396f970c68e65ab486f1cf7ecae0 | 8c096e28b755defa6c60da44d43e060756796d18 | /src/zmq/zmqpublishnotifier.cpp | d747c4f692a5a074f759b839a4d2b24143b57019 | [
"MIT"
] | permissive | twairgroup/wondercoin | b9599deae3e1acb40dcaa5f5db3fd89985ba9736 | c075c2d0c1a4927d9f04d5100106e369a85128e5 | refs/heads/master | 2022-07-30T05:46:30.125814 | 2021-06-13T21:08:03 | 2021-06-13T21:08:03 | 361,614,184 | 1 | 1 | MIT | 2021-06-13T08:45:10 | 2021-04-26T04:13:04 | C++ | UTF-8 | C++ | false | false | 5,729 | cpp | // Copyright (c) 2015-2016 The Bitcoin Core developers
// Copyright (c) 2021 The Wondercoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "chainparams.h"
#include "streams.h"
#include "zmqpublishnotifier.h"
#include "validation.h"
#include "util.h"
#include "rpc/server.h"
static std::multimap<std::string, CZMQAbstractPublishNotifier*> mapPublishNotifiers;
static const char *MSG_HASHBLOCK = "hashblock";
static const char *MSG_HASHTX = "hashtx";
static const char *MSG_RAWBLOCK = "rawblock";
static const char *MSG_RAWTX = "rawtx";
// Internal function to send multipart message
static int zmq_send_multipart(void *sock, const void* data, size_t size, ...)
{
va_list args;
va_start(args, size);
while (1)
{
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, size);
if (rc != 0)
{
zmqError("Unable to initialize ZMQ msg");
va_end(args);
return -1;
}
void *buf = zmq_msg_data(&msg);
memcpy(buf, data, size);
data = va_arg(args, const void*);
rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
if (rc == -1)
{
zmqError("Unable to send ZMQ msg");
zmq_msg_close(&msg);
va_end(args);
return -1;
}
zmq_msg_close(&msg);
if (!data)
break;
size = va_arg(args, size_t);
}
va_end(args);
return 0;
}
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
// check if address is being used by other publish notifier
std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator i = mapPublishNotifiers.find(address);
if (i==mapPublishNotifiers.end())
{
psocket = zmq_socket(pcontext, ZMQ_PUB);
if (!psocket)
{
zmqError("Failed to create socket");
return false;
}
int rc = zmq_bind(psocket, address.c_str());
if (rc!=0)
{
zmqError("Failed to bind address");
zmq_close(psocket);
return false;
}
// register this notifier for the address, so it can be reused for other publish notifier
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
else
{
LogPrint(BCLog::ZMQ, "zmq: Reusing socket for address %s\n", address);
psocket = i->second->psocket;
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
}
void CZMQAbstractPublishNotifier::Shutdown()
{
assert(psocket);
int count = mapPublishNotifiers.count(address);
// remove this notifier from the list of publishers using this address
typedef std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator iterator;
std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
for (iterator it = iterpair.first; it != iterpair.second; ++it)
{
if (it->second==this)
{
mapPublishNotifiers.erase(it);
break;
}
}
if (count == 1)
{
LogPrint(BCLog::ZMQ, "Close socket at address %s\n", address);
int linger = 0;
zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(psocket);
}
psocket = 0;
}
bool CZMQAbstractPublishNotifier::SendMessage(const char *command, const void* data, size_t size)
{
assert(psocket);
/* send three parts, command & data & a LE 4byte sequence number */
unsigned char msgseq[sizeof(uint32_t)];
WriteLE32(&msgseq[0], nSequence);
int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), (void*)0);
if (rc == -1)
return false;
/* increment memory only sequence number after sending */
nSequence++;
return true;
}
bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashblock %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHBLOCK, data, 32);
}
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHTX, data, 32);
}
bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
LogPrint(BCLog::ZMQ, "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex());
const Consensus::Params& consensusParams = Params().GetConsensus();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
{
LOCK(cs_main);
CBlock block;
if(!ReadBlockFromDisk(block, pindex, consensusParams))
{
zmqError("Can't read block from disk");
return false;
}
ss << block;
}
return SendMessage(MSG_RAWBLOCK, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawtx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendMessage(MSG_RAWTX, &(*ss.begin()), ss.size());
}
| [
"twairgroup888@gmail.com"
] | twairgroup888@gmail.com |
dc66a6f11985dfb96678d1626296d30d8ec9d92d | 3507039561c827050b9eafc1fbdd6be525710fa0 | /Lista02/Questao 4/Retangulo.h | c6fc0e787167788968e716d19735d2cb2474f983 | [] | no_license | diegolrs/Codigos-LPI-Cpp- | a5c924035156c1e0251296cf5fabc8570f1a7372 | 6dadea3bcc30ae6a52f6292b1208d1a505b86bd1 | refs/heads/master | 2020-09-28T04:24:45.203144 | 2020-03-19T01:50:50 | 2020-03-19T01:50:50 | 226,687,287 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 230 | h | #ifndef RETANGULO_H
#define RETANGULO_H
#include "Figura.h"
#define PI 3.1415
#include <iostream>
class Retangulo : public Figura
{
public:
Retangulo(double bs, double alt, double r);
};
#endif // RETANGULO_H
| [
"noreply@github.com"
] | noreply@github.com |
fe7a099d16294fd84c103c9fd8b9382be5de4c6d | 67d1eba373b9afe9cd1f6bc8a52fde774207e6c7 | /UVA/10107 - What is the Median.cpp | 11d91e16a9eaff6e1f0412c1d5b5fac2c6e743e1 | [] | no_license | evan-hossain/competitive-programming | 879b8952df587baf906298a609b471971bdfd421 | 561ce1a6b4a4a6958260206a5d0252cc9ea80c75 | refs/heads/master | 2021-06-01T13:54:04.351848 | 2018-01-19T14:18:35 | 2018-01-19T14:18:35 | 93,148,046 | 2 | 3 | null | 2020-10-01T13:29:54 | 2017-06-02T09:04:50 | C++ | UTF-8 | C++ | false | false | 470 | cpp | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#define pub push_back
using namespace std;
int main()
{
vector <int> v;
int n;
while(scanf("%d", &n) == 1)
{
v.pub(n);
sort(v.begin(), v.end());
int l = v.size(), i;
if(!(l & 1))
printf("%d\n", (v[l >> 1] + v[(l >> 1) - 1]) >> 1);
else
printf("%d\n", v[l >> 1]);
}
return 0;
}
| [
"evan.hossain@ipay.com.bd"
] | evan.hossain@ipay.com.bd |
c527529ebe4297e6d8744ade8bef27b9c5c6592d | 441b12109006a9e674c9e814ac768915f9023cea | /ARGO/KickCommand.h | d8e04c5a9ac188caa3d5dd5036f1e027ecf18f51 | [] | no_license | itcgames/ARGO_2018_19_C | 34abc634239d8a513a8f4b62b2f95d22716b7f1c | a67c61a4bb013b478eb708c2595ad06eb4a730aa | refs/heads/master | 2020-04-20T19:54:17.196029 | 2019-03-01T13:58:15 | 2019-03-01T13:58:15 | 169,061,885 | 3 | 1 | null | 2019-03-01T13:58:16 | 2019-02-04T10:29:23 | C | UTF-8 | C++ | false | false | 323 | h | #pragma once
#include "Command.h"
class KickCommand : public Command
{
public:
KickCommand() {};
~KickCommand() {}
void execute(Entity * e, Client & client)
{
ControlComponent * controlComp = (ControlComponent*)e->getCompByType("Control");
controlComp->kick();
};
void stop(Entity * e)
{
};
protected:
};
| [
"C00206167@itcarlow.ie"
] | C00206167@itcarlow.ie |
1bd749230397f88b01bddf0fade18d4a96c28d21 | 76763c51ed3049882c1a30cc64d3a1a9f37d0cb1 | /Creational Pattern/Factories/Inner Factory/Inner Factory.cpp | d2b47133ee1ed08e96a2befbb82a5ad8ac934aab | [] | no_license | tolerance93/Design-Patterns-in-cpp | e23636a0dc0d83ed0981c886df629d8b52be2b68 | ac05ea2ac981c6f8727a3517c1453ec07da68399 | refs/heads/master | 2023-04-06T01:07:53.681244 | 2021-05-08T09:23:21 | 2021-05-08T09:23:21 | 331,330,814 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,466 | cpp | #include <cmath>
/**
* C#, Java등 프렌드 키워드가 없는 언어들은 내부 팩토리를 흔하게 사용한다.
*/
// do not need this for factory
enum class PointType
{
cartesian,
polar
};
class Point
{
/*Point(float a, float b, PointType type = PointType::cartesian)
{
if (type == PointType::cartesian)
{
x = a; b = y;
}
else
{
x = a*cos(b);
y = a*sin(b);
}
}*/
// use a factory method
/**
* 사용자 입장에서는 생성자가 private이라면 Point::를 통해 사용가능한 수단이 무엇이 있는지 확인할 것이고,
* 팩토리는 그러한 사용자의 기대에 부흥한다!
*/
Point(float x, float y) : x(x), y(y) {}
/**
* Point와 PointFactory는 서로의 private member에 자유로운 접근권한을 가진다.
* 팩토리가 생성해야할 클래스가 단 한 종류일 때 유용하다.
*/
class PointFactory
{
PointFactory() {}
public:
static Point NewCartesian(float x, float y)
{
return { x,y };
}
static Point NewPolar(float r, float theta)
{
return{ r*cos(theta), r*sin(theta) };
}
};
public:
float x, y;
static PointFactory Factory;
};
int main()
{
// will not work
// Point p{ 1,2 };
// nope!
// Point::PointFactory pf;
// if factory is public, then
//auto p = Point::PointFactory::NewCartesian(3, 4);
// at any rate, use this
auto pp = Point::Factory.NewCartesian(2, 3);
return 0;
}
| [
"zpgy77@gmail.com"
] | zpgy77@gmail.com |
a828a19b8cf5f38216385a8e26b4a25dc51ac11a | 0464ef72e5f9cd84a0563bc250e9f1a42b78ee45 | /cocos2d/external/bullet/BulletMultiThreaded/SpuNarrowPhaseCollisionTask/SpuContactResult.cpp | adc38618b66586babebfb65539e77a9b2406b903 | [
"MIT"
] | permissive | lcyzgdy/KeepDistance | 5389bfa35b8bd8b48e3374c17afc1ead56fe2a7f | 1f93a7f553846c0176a7fae10acadf962b0b4c1b | refs/heads/master | 2021-01-01T06:44:17.494408 | 2017-07-17T17:20:54 | 2017-07-17T17:20:54 | 97,500,785 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,084 | cpp | /*
BulletSprite Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/BulletSprite/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SpuContactResult.h"
//#define DEBUG_SPU_COLLISION_DETECTION 1
#ifdef DEBUG_SPU_COLLISION_DETECTION
#ifndef __SPU__
#include <stdio.h>
#define spu_printf printf
#endif
#endif //DEBUG_SPU_COLLISION_DETECTION
SpuContactResult::SpuContactResult()
{
m_manifoldAddress = 0;
m_spuManifold = NULL;
m_RequiresWriteBack = false;
}
SpuContactResult::~SpuContactResult()
{
g_manifoldDmaExport.swapBuffers();
}
///User can override this material combiner by implementing gContactAddedCallback and setting body0->m_collisionFlags |= btCollisionObject::customMaterialCallback;
inline btScalar calculateCombinedFriction(btScalar friction0,btScalar friction1)
{
btScalar friction = friction0*friction1;
const btScalar MAX_FRICTION = btScalar(10.);
if (friction < -MAX_FRICTION)
friction = -MAX_FRICTION;
if (friction > MAX_FRICTION)
friction = MAX_FRICTION;
return friction;
}
inline btScalar calculateCombinedRestitution(btScalar restitution0,btScalar restitution1)
{
return restitution0*restitution1;
}
void SpuContactResult::setContactInfo(btPersistentManifold* spuManifold, ppu_address_t manifoldAddress,const btTransform& worldTrans0,const btTransform& worldTrans1, btScalar restitution0,btScalar restitution1, btScalar friction0,btScalar friction1, bool isSwapped)
{
//spu_printf("SpuContactResult::setContactInfo ManifoldAddress: %lu\n", manifoldAddress);
m_rootWorldTransform0 = worldTrans0;
m_rootWorldTransform1 = worldTrans1;
m_manifoldAddress = manifoldAddress;
m_spuManifold = spuManifold;
m_combinedFriction = calculateCombinedFriction(friction0,friction1);
m_combinedRestitution = calculateCombinedRestitution(restitution0,restitution1);
m_isSwapped = isSwapped;
}
void SpuContactResult::setShapeIdentifiersA(int partId0,int index0)
{
}
void SpuContactResult::setShapeIdentifiersB(int partId1,int index1)
{
}
///return true if it requires a dma transfer back
bool ManifoldResultAddContactPoint(const btVector3& normalOnBInWorld,
const btVector3& pointInWorld,
float depth,
btPersistentManifold* manifoldPtr,
btTransform& transA,
btTransform& transB,
btScalar combinedFriction,
btScalar combinedRestitution,
bool isSwapped)
{
// float contactTreshold = manifoldPtr->getContactBreakingThreshold();
//spu_printf("SPU: add contactpoint, depth:%f, contactTreshold %f, manifoldPtr %llx\n",depth,contactTreshold,manifoldPtr);
#ifdef DEBUG_SPU_COLLISION_DETECTION
spu_printf("SPU: contactTreshold %f\n",contactTreshold);
#endif //DEBUG_SPU_COLLISION_DETECTION
if (depth > manifoldPtr->getContactBreakingThreshold())
return false;
//if (depth > manifoldPtr->getContactProcessingThreshold())
// return false;
btVector3 pointA;
btVector3 localA;
btVector3 localB;
btVector3 normal;
if (isSwapped)
{
normal = normalOnBInWorld * -1;
pointA = pointInWorld + normal * depth;
localA = transA.invXform(pointA );
localB = transB.invXform(pointInWorld);
}
else
{
normal = normalOnBInWorld;
pointA = pointInWorld + normal * depth;
localA = transA.invXform(pointA );
localB = transB.invXform(pointInWorld);
}
btManifoldPoint newPt(localA,localB,normal,depth);
newPt.m_positionWorldOnA = pointA;
newPt.m_positionWorldOnB = pointInWorld;
newPt.m_combinedFriction = combinedFriction;
newPt.m_combinedRestitution = combinedRestitution;
int insertIndex = manifoldPtr->getCacheEntry(newPt);
if (insertIndex >= 0)
{
// we need to replace the current contact point, otherwise small errors will accumulate (spheres start rolling etc)
manifoldPtr->replaceContactPoint(newPt,insertIndex);
return true;
} else
{
/*
///@todo: SPU callbacks, either immediate (local on the SPU), or deferred
//User can override friction and/or restitution
if (gContactAddedCallback &&
//and if either of the two bodies requires custom material
((m_body0->m_collisionFlags & btCollisionObject::customMaterialCallback) ||
(m_body1->m_collisionFlags & btCollisionObject::customMaterialCallback)))
{
//experimental feature info, for per-triangle material etc.
(*gContactAddedCallback)(newPt,m_body0,m_partId0,m_index0,m_body1,m_partId1,m_index1);
}
*/
manifoldPtr->addManifoldPoint(newPt);
return true;
}
return false;
}
void SpuContactResult::writeDoubleBufferedManifold(btPersistentManifold* lsManifold, btPersistentManifold* mmManifold)
{
///only write back the contact information on SPU. Other platforms avoid copying, and use the data in-place
///see SpuFakeDma.cpp 'cellDmaLargeGetReadOnly'
#if defined (__SPU__) || defined (USE_LIBSPE2)
memcpy(g_manifoldDmaExport.getFront(),lsManifold,sizeof(btPersistentManifold));
g_manifoldDmaExport.swapBuffers();
ppu_address_t mmAddr = (ppu_address_t)mmManifold;
g_manifoldDmaExport.backBufferDmaPut(mmAddr, sizeof(btPersistentManifold), DMA_TAG(9));
// Should there be any kind of wait here? What if somebody tries to use this tag again? What if we call this function again really soon?
//no, the swapBuffers does the wait
#endif
}
void SpuContactResult::addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth)
{
#ifdef DEBUG_SPU_COLLISION_DETECTION
spu_printf("*** SpuContactResult::addContactPoint: depth = %f\n",depth);
spu_printf("*** normal = %f,%f,%f\n",normalOnBInWorld.getX(),normalOnBInWorld.getY(),normalOnBInWorld.getZ());
spu_printf("*** position = %f,%f,%f\n",pointInWorld.getX(),pointInWorld.getY(),pointInWorld.getZ());
#endif //DEBUG_SPU_COLLISION_DETECTION
#ifdef DEBUG_SPU_COLLISION_DETECTION
// int sman = sizeof(rage::phManifold);
// spu_printf("sizeof_manifold = %i\n",sman);
#endif //DEBUG_SPU_COLLISION_DETECTION
btPersistentManifold* localManifold = m_spuManifold;
btVector3 normalB(normalOnBInWorld.getX(),normalOnBInWorld.getY(),normalOnBInWorld.getZ());
btVector3 pointWrld(pointInWorld.getX(),pointInWorld.getY(),pointInWorld.getZ());
//process the contact point
const bool retVal = ManifoldResultAddContactPoint(normalB,
pointWrld,
depth,
localManifold,
m_rootWorldTransform0,
m_rootWorldTransform1,
m_combinedFriction,
m_combinedRestitution,
m_isSwapped);
m_RequiresWriteBack = m_RequiresWriteBack || retVal;
}
void SpuContactResult::flush()
{
if (m_spuManifold && m_spuManifold->getNumContacts())
{
m_spuManifold->refreshContactPoints(m_rootWorldTransform0,m_rootWorldTransform1);
m_RequiresWriteBack = true;
}
if (m_RequiresWriteBack)
{
#ifdef DEBUG_SPU_COLLISION_DETECTION
spu_printf("SPU: Start SpuContactResult::flush (Put) DMA\n");
spu_printf("Num contacts:%d\n", m_spuManifold->getNumContacts());
spu_printf("Manifold address: %llu\n", m_manifoldAddress);
#endif //DEBUG_SPU_COLLISION_DETECTION
// spu_printf("writeDoubleBufferedManifold\n");
writeDoubleBufferedManifold(m_spuManifold, (btPersistentManifold*)m_manifoldAddress);
#ifdef DEBUG_SPU_COLLISION_DETECTION
spu_printf("SPU: Finished (Put) DMA\n");
#endif //DEBUG_SPU_COLLISION_DETECTION
}
m_spuManifold = NULL;
m_RequiresWriteBack = false;
}
| [
"Guan@DESKTOP-JK3JBCQ.localdomain"
] | Guan@DESKTOP-JK3JBCQ.localdomain |
da63c7c0d2260eb95eecf5aac64ad568ea9f3918 | fdabe402222103f11cae8091d2a887310e313a0c | /searchandsort/sortemployees.c++ | e6d316d6a239383c2d9f34346f767b3ebccc55cc | [] | no_license | DEBMALYASEN/program | a15b5d9264773e67207e7301b186a9e59fb27f76 | 1967297e05a0a32a54c3f0ba87fba753cf69fe1d | refs/heads/master | 2023-06-23T20:09:19.828678 | 2021-07-26T06:14:01 | 2021-07-26T06:14:01 | 389,529,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | #include<bits/stdc++.h>
using namespace std;
void sortemployees(vector<pair<string,int>>&a)
{
sort(a.begin(), a.end(), [](const pair<string,int>& p1, const pair<string,int>& p2)
{
if (p1.second == p2.second)
return p1.first < p2.first;
return p1.second < p2.second;
});
}
int main()
{
vector<pair<string,int>>a={{"xbnnskd", 100}, {"geek", 50}};
sortemployees(a);
for(auto i:a)
cout<<i.first<<" "<<i.second<<" ";
}
| [
"boonysen@gmail.com"
] | boonysen@gmail.com | |
31d0329fe81a68ffcf457b42f0496725d6957f30 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /drv/Dico/Dico_IteratorOfDictionaryOfInteger_0.cxx | 9c22fc266318d894b0b3315fa6acf693b20b82e6 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,447 | cxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#include <Dico_IteratorOfDictionaryOfInteger.hxx>
#ifndef _Dico_DictionaryOfInteger_HeaderFile
#include <Dico_DictionaryOfInteger.hxx>
#endif
#ifndef _Dico_StackItemOfDictionaryOfInteger_HeaderFile
#include <Dico_StackItemOfDictionaryOfInteger.hxx>
#endif
#ifndef _Standard_NoSuchObject_HeaderFile
#include <Standard_NoSuchObject.hxx>
#endif
#ifndef _TCollection_AsciiString_HeaderFile
#include <TCollection_AsciiString.hxx>
#endif
#define TheItem Standard_Integer
#define TheItem_hxx <Standard_Integer.hxx>
#define Dico_Iterator Dico_IteratorOfDictionaryOfInteger
#define Dico_Iterator_hxx <Dico_IteratorOfDictionaryOfInteger.hxx>
#define Dico_StackItem Dico_StackItemOfDictionaryOfInteger
#define Dico_StackItem_hxx <Dico_StackItemOfDictionaryOfInteger.hxx>
#define Handle_Dico_StackItem Handle_Dico_StackItemOfDictionaryOfInteger
#define Dico_StackItem_Type_() Dico_StackItemOfDictionaryOfInteger_Type_()
#define Dico_Dictionary Dico_DictionaryOfInteger
#define Dico_Dictionary_hxx <Dico_DictionaryOfInteger.hxx>
#define Handle_Dico_Dictionary Handle_Dico_DictionaryOfInteger
#define Dico_Dictionary_Type_() Dico_DictionaryOfInteger_Type_()
#include <Dico_Iterator.gxx>
| [
"shoka.sho2@excel.co.jp"
] | shoka.sho2@excel.co.jp |
0c77dd8c637f55cc2da9b5529fc97af744ca602a | 879681c994f1ca9c8d2c905a4e5064997ad25a27 | /root-2.3.0/run/tutorials/multiphase/twoPhaseEulerFoam/RAS/fluidisedBed/0.24/T.particles | a5c2ec3851bdd5bb034dffb83a59873a36f5183c | [] | no_license | MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu | 3828272d989d45fb020e83f8426b849e75560c62 | daeb870be81275e8a81f5cbac4ca1906a9bc69c0 | refs/heads/master | 2020-05-17T16:36:41.848261 | 2015-04-18T09:29:48 | 2015-04-18T09:29:48 | 34,159,882 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,633 | particles | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.24";
object T.particles;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 1 0 0 0];
internalField nonuniform List<scalar>
6000
(
597.715
598.401
598.393
598.132
597.943
597.852
597.792
597.761
597.737
597.703
597.67
597.638
597.615
597.6
597.592
597.593
597.6
597.615
597.639
597.669
597.703
597.737
597.761
597.792
597.853
597.944
598.138
598.398
598.404
597.712
599.027
599.865
599.902
599.872
599.609
599.298
599.178
599.188
599.248
599.283
599.29
599.278
599.265
599.254
599.246
599.246
599.255
599.266
599.281
599.292
599.286
599.249
599.19
599.181
599.303
599.617
599.873
599.902
599.864
599.036
599.818
599.96
599.967
599.965
599.934
599.83
599.747
599.764
599.811
599.833
599.838
599.832
599.824
599.817
599.813
599.813
599.817
599.824
599.832
599.838
599.834
599.811
599.765
599.749
599.832
599.935
599.965
599.967
599.959
599.823
599.954
599.968
599.97
599.97
599.965
599.937
599.895
599.904
599.924
599.932
599.933
599.93
599.926
599.923
599.922
599.922
599.923
599.926
599.93
599.933
599.933
599.924
599.904
599.896
599.937
599.965
599.97
599.97
599.968
599.955
599.97
599.971
599.971
599.97
599.969
599.961
599.942
599.945
599.953
599.956
599.957
599.955
599.954
599.952
599.952
599.952
599.952
599.954
599.955
599.957
599.956
599.953
599.945
599.943
599.962
599.969
599.97
599.971
599.971
599.97
599.971
599.971
599.971
599.971
599.97
599.967
599.959
599.959
599.963
599.964
599.964
599.964
599.963
599.963
599.962
599.962
599.963
599.963
599.964
599.964
599.964
599.963
599.959
599.959
599.967
599.97
599.97
599.971
599.971
599.971
599.972
599.971
599.971
599.97
599.97
599.969
599.965
599.965
599.966
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.966
599.965
599.966
599.969
599.97
599.97
599.971
599.971
599.972
599.972
599.972
599.971
599.97
599.97
599.969
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.968
599.969
599.97
599.97
599.971
599.972
599.972
599.972
599.972
599.971
599.97
599.97
599.969
599.969
599.969
599.968
599.968
599.968
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.968
599.968
599.968
599.969
599.969
599.969
599.97
599.97
599.971
599.972
599.972
599.972
599.972
599.97
599.97
599.97
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.97
599.97
599.971
599.972
599.972
599.972
599.972
599.97
599.97
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.97
599.97
599.971
599.972
599.972
599.972
599.972
599.97
599.97
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.97
599.97
599.971
599.972
599.972
599.972
599.972
599.97
599.97
599.97
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.97
599.97
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.97
599.97
599.971
599.972
599.973
599.972
599.972
599.971
599.97
599.97
599.969
599.969
599.969
599.969
599.969
599.969
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.969
599.969
599.969
599.969
599.969
599.969
599.97
599.97
599.971
599.972
599.973
599.973
599.972
599.971
599.97
599.97
599.969
599.969
599.969
599.969
599.969
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.969
599.969
599.969
599.969
599.969
599.97
599.97
599.971
599.972
599.973
599.973
599.972
599.971
599.97
599.97
599.97
599.969
599.969
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.969
599.969
599.97
599.97
599.97
599.971
599.972
599.973
599.973
599.972
599.971
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.971
599.972
599.973
599.973
599.973
599.972
599.971
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.971
599.973
599.973
599.973
599.973
599.972
599.971
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.971
599.972
599.973
599.973
599.973
599.973
599.973
599.971
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.971
599.972
599.973
599.973
599.973
599.973
599.973
599.972
599.971
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.971
599.971
599.973
599.973
599.973
599.973
599.973
599.973
599.972
599.971
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.971
599.972
599.973
599.973
599.973
599.973
599.973
599.973
599.972
599.971
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.971
599.971
599.972
599.973
599.974
599.974
599.973
599.973
599.973
599.972
599.971
599.971
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.971
599.971
599.971
599.972
599.973
599.974
599.974
599.973
599.973
599.973
599.973
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.973
599.973
599.974
599.974
599.974
599.973
599.973
599.973
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.973
599.973
599.974
599.974
599.974
599.973
599.973
599.973
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.972
599.973
599.973
599.974
599.974
599.974
599.974
599.973
599.972
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.972
599.973
599.974
599.974
599.974
599.975
599.974
599.973
599.972
599.972
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.972
599.972
599.973
599.974
599.974
599.974
599.975
599.974
599.973
599.972
599.972
599.972
599.972
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.972
599.972
599.972
599.973
599.974
599.974
599.974
599.975
599.974
599.973
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.973
599.974
599.974
599.975
599.975
599.974
599.973
599.973
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.973
599.974
599.975
599.975
599.975
599.974
599.973
599.973
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.973
599.973
599.974
599.975
599.975
599.975
599.974
599.973
599.973
599.973
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.973
599.973
599.974
599.975
599.975
599.975
599.974
599.974
599.973
599.973
599.973
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.973
599.973
599.973
599.974
599.975
599.975
599.975
599.974
599.974
599.974
599.973
599.973
599.973
599.973
599.973
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.973
599.973
599.973
599.973
599.973
599.974
599.975
599.975
599.975
599.975
599.975
599.974
599.974
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.974
599.975
599.975
599.975
599.975
599.975
599.974
599.974
599.974
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.974
599.975
599.975
599.976
599.975
599.975
599.975
599.974
599.974
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.974
599.975
599.976
599.976
599.975
599.975
599.975
599.975
599.974
599.974
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.974
599.974
599.975
599.976
599.976
599.975
599.975
599.975
599.975
599.974
599.974
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.974
599.975
599.975
599.976
599.976
599.975
599.975
599.975
599.975
599.974
599.974
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.974
599.975
599.975
599.976
599.976
599.976
599.975
599.975
599.975
599.974
599.974
599.974
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.974
599.974
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.975
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.973
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.973
599.973
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.973
599.973
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.973
599.973
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.973
599.972
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.972
599.972
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.972
599.972
599.974
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.974
599.972
599.972
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.972
599.973
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.975
599.974
599.973
599.973
599.974
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.973
599.973
599.973
599.973
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.974
599.974
599.973
599.973
599.973
599.973
599.973
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.973
599.973
599.973
599.972
599.973
599.973
599.974
599.975
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.976
599.975
599.974
599.973
599.973
599.972
599.972
599.972
599.973
599.974
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.974
599.973
599.972
599.972
599.971
599.972
599.973
599.974
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.974
599.973
599.972
599.971
599.969
599.971
599.973
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.973
599.971
599.969
599.966
599.97
599.974
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.974
599.97
599.966
599.959
599.969
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.969
599.959
599.951
599.967
599.974
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.974
599.967
599.952
599.951
599.966
599.974
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.974
599.966
599.951
599.951
599.967
599.974
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.974
599.967
599.951
599.951
599.968
599.974
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.974
599.968
599.951
599.951
599.97
599.974
599.974
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.975
599.974
599.974
599.97
599.951
599.951
599.972
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.972
599.951
599.951
599.972
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.972
599.951
599.951
599.972
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.972
599.951
599.951
599.972
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.972
599.951
599.951
599.971
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.971
599.951
599.951
599.969
599.973
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.974
599.973
599.969
599.952
599.953
599.966
599.973
599.974
599.974
599.974
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.974
599.974
599.974
599.973
599.966
599.953
599.955
599.964
599.972
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.972
599.964
599.955
599.957
599.963
599.971
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.971
599.963
599.957
599.958
599.963
599.97
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.973
599.969
599.962
599.958
599.958
599.962
599.969
599.973
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.969
599.962
599.958
599.958
599.962
599.969
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.972
599.972
599.972
599.972
599.972
599.972
599.972
599.969
599.962
599.958
599.956
599.962
599.97
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.97
599.962
599.956
599.954
599.963
599.97
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.971
599.97
599.962
599.954
599.95
599.966
599.969
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.969
599.97
599.97
599.97
599.97
599.97
599.97
599.97
599.969
599.966
599.95
599.948
599.966
599.966
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.967
599.966
599.966
599.948
599.944
599.962
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.964
599.963
599.945
599.943
599.953
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.962
599.963
599.963
599.962
599.954
599.943
599.941
599.943
599.953
599.961
599.961
599.961
599.961
599.961
599.961
599.961
599.96
599.96
599.96
599.96
599.96
599.96
599.96
599.96
599.96
599.961
599.961
599.961
599.961
599.961
599.961
599.961
599.961
599.956
599.944
599.94
599.931
599.933
599.94
599.956
599.959
599.959
599.959
599.959
599.959
599.959
599.959
599.959
599.959
599.958
599.958
599.958
599.958
599.959
599.959
599.959
599.959
599.959
599.959
599.959
599.959
599.959
599.957
599.942
599.934
599.932
599.922
599.926
599.932
599.941
599.955
599.955
599.954
599.954
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.955
599.944
599.933
599.927
599.923
599.916
599.92
599.925
599.93
599.94
599.941
599.941
599.942
599.944
599.945
599.945
599.946
599.946
599.946
599.945
599.945
599.945
599.945
599.946
599.946
599.945
599.945
599.944
599.943
599.942
599.941
599.931
599.926
599.922
599.917
599.908
599.914
599.919
599.921
599.921
599.92
599.918
599.919
599.92
599.921
599.923
599.924
599.924
599.923
599.921
599.921
599.921
599.922
599.924
599.924
599.922
599.922
599.921
599.921
599.92
599.921
599.921
599.92
599.916
599.911
599.893
599.905
599.91
599.908
599.901
599.892
599.89
599.894
599.896
599.897
599.899
599.901
599.901
599.899
599.898
599.897
599.898
599.9
599.902
599.901
599.899
599.898
599.897
599.896
599.895
599.9
599.908
599.911
599.907
599.9
599.85
599.873
599.883
599.881
599.869
599.857
599.855
599.861
599.862
599.863
599.866
599.87
599.871
599.87
599.867
599.866
599.866
599.871
599.875
599.873
599.87
599.866
599.865
599.866
599.866
599.874
599.883
599.884
599.877
599.874
599.408
599.764
599.811
599.818
599.821
599.816
599.816
599.821
599.821
599.822
599.827
599.832
599.834
599.826
599.822
599.826
599.822
599.831
599.837
599.832
599.826
599.823
599.825
599.826
599.817
599.82
599.817
599.813
599.754
599.656
597.061
599.216
599.591
599.647
599.687
599.717
599.729
599.752
599.769
599.776
599.783
599.792
599.798
599.789
599.782
599.787
599.783
599.79
599.793
599.78
599.764
599.749
599.738
599.719
599.679
599.673
599.655
599.63
599.268
597.646
593.122
598.004
598.983
599.086
599.237
599.481
599.567
599.619
599.694
599.715
599.721
599.737
599.755
599.754
599.746
599.749
599.742
599.741
599.731
599.702
599.679
599.642
599.563
599.474
599.35
599.252
599.292
599.344
599.144
593.369
588.975
596.385
598.2
598.45
598.654
599.127
599.371
599.476
599.624
599.682
599.699
599.717
599.742
599.741
599.734
599.737
599.725
599.719
599.706
599.672
599.64
599.576
599.459
599.26
598.996
598.888
598.971
599.084
599.007
591.491
584.485
593.251
596.562
597.169
597.418
598.256
598.945
599.187
599.463
599.62
599.662
599.695
599.722
599.725
599.719
599.716
599.697
599.688
599.664
599.626
599.583
599.5
599.302
598.903
598.339
598.202
598.293
598.4
598.153
588.574
579.649
587.813
593.609
594.879
595.345
596.636
598.078
598.666
599.131
599.503
599.617
599.667
599.696
599.706
599.7
599.692
599.668
599.655
599.624
599.583
599.511
599.38
599.064
598.325
597.309
597.003
596.949
596.921
595.623
582.359
578.074
585.068
589.987
591.835
592.956
594.843
596.902
597.983
598.667
599.318
599.562
599.64
599.666
599.678
599.678
599.668
599.638
599.62
599.584
599.515
599.365
599.123
598.551
597.434
596.104
595.437
595.087
594.676
592.536
578.922
577.461
581.971
584.841
588.613
591.149
593.569
595.915
597.4
598.334
599.098
599.475
599.602
599.63
599.633
599.644
599.635
599.597
599.564
599.519
599.408
599.163
598.797
597.897
596.392
595.099
593.927
593.045
591.622
589.195
577.905
576.733
570.311
573.838
584.42
589.34
592.198
595.229
597.093
598.157
598.96
599.388
599.571
599.602
599.579
599.59
599.613
599.556
599.507
599.361
599.189
598.793
598.305
597.084
595.096
593.38
591.801
589.732
586.189
584.051
577.481
571.296
555.48
568.487
582.539
588.018
590.619
593.415
595.879
597.301
598.317
599.055
599.441
599.558
599.553
599.55
599.581
599.501
599.443
599.154
598.83
598.298
597.615
596.077
593.533
590.864
587.606
582.545
573.062
568.009
573.82
557.711
550.398
568.179
582.404
587.859
590.313
592.078
594.096
596.104
597.694
598.749
599.31
599.491
599.498
599.492
599.52
599.451
599.338
598.9
598.349
597.807
596.957
595.323
592.732
589.837
586.076
579.826
567.205
557.599
563.174
540.413
549.402
571.849
583.196
587.971
590.287
591.856
593.474
594.966
596.607
598.173
599.093
599.383
599.411
599.41
599.427
599.346
599.158
598.612
598.012
597.476
596.685
595.153
592.675
589.71
585.908
579.545
565.857
547.479
549.635
537.541
555.36
577.7
585.204
588.605
590.598
592.043
593.469
594.795
596.173
597.693
598.761
599.174
599.274
599.295
599.298
599.188
598.912
598.335
597.693
597.166
596.438
595.105
592.926
589.947
586.274
580.355
567.156
542.548
535.999
537.729
564.176
580.648
587.053
589.976
591.639
592.834
593.942
594.964
596.113
597.331
598.378
598.933
599.111
599.167
599.148
599.019
598.653
598.038
597.46
597.02
596.287
594.905
592.999
590.331
586.85
581.318
568.699
541.272
522.884
540.3
566.22
581.557
587.741
590.903
592.586
593.544
594.257
595.084
596.104
597.155
598.131
598.72
598.952
598.993
598.969
598.807
598.388
597.778
597.32
596.921
596.088
594.637
592.839
590.312
586.823
581.19
568.257
540.994
514.23
543.917
567.098
581.996
588.23
591.314
592.955
593.957
594.649
595.265
596.131
597.106
598.04
598.602
598.806
598.855
598.805
598.561
598.102
597.547
597.215
596.819
595.935
594.418
592.416
589.393
585.069
578.044
561.747
536.666
510.565
552.026
569.698
582.665
588.679
591.71
593.28
594.378
595.04
595.603
596.231
596.933
597.778
598.341
598.596
598.653
598.591
598.336
597.927
597.463
597.157
596.727
595.745
594.056
591.615
587.878
582.664
572.119
551.813
522.381
508.504
554.928
571.782
583.037
588.816
591.875
593.531
594.599
595.214
595.738
596.344
596.944
597.713
598.219
598.477
598.524
598.452
598.078
597.65
597.283
597.045
596.528
595.261
593.182
590.346
586.286
580.222
569.303
550.2
517.841
503.368
555.3
569.979
582.77
588.705
591.974
593.644
594.688
595.389
596.037
596.509
596.978
597.666
598.16
598.413
598.433
598.339
597.929
597.385
597.025
596.757
596.077
594.49
592.398
589.618
585.499
579.079
568.905
551.884
519.744
497.607
551.342
564.279
580.312
588.244
591.96
593.623
594.765
595.457
596.088
596.539
597.006
597.637
598.111
598.368
598.378
598.24
597.795
597.293
596.916
596.526
595.544
593.791
591.732
589.362
585.31
578.927
569.948
556.198
529.112
495.299
545.084
560.488
579.122
587.646
591.618
593.511
594.697
595.414
596.057
596.559
597.064
597.651
598.083
598.321
598.318
598.151
597.716
597.262
596.897
596.465
595.381
593.535
591.702
589.303
585.504
579.814
572.528
560.981
534.012
491.784
542.281
565.015
579.322
587.056
591.297
593.495
594.635
595.294
595.987
596.636
597.217
597.713
598.057
598.264
598.26
598.087
597.659
597.242
596.899
596.463
595.348
593.543
591.786
589.482
585.555
580.151
574.316
563.093
534.756
485.994
537.963
565.771
579.7
586.889
591.385
593.553
594.535
595.217
595.995
596.751
597.358
597.751
598.038
598.203
598.167
597.965
597.555
597.202
596.917
596.464
595.283
593.624
592.001
589.505
585.315
580.307
575.341
564.864
540.066
484.876
534.387
559.674
578.36
586.772
591.409
593.288
594.459
595.222
596.072
596.797
597.374
597.74
598.007
598.157
598.137
597.968
597.579
597.141
596.902
596.478
595.283
593.745
592.329
589.82
585.651
581.019
576.371
566.548
540.498
484.111
530.877
559.068
577.012
585.319
590.55
592.992
594.468
595.297
596.068
596.784
597.361
597.713
597.958
598.089
598.082
597.955
597.622
597.17
596.859
596.455
595.299
593.857
592.537
590.148
586.237
582.047
577.114
565.7
532.544
477.111
525.294
557.082
575.126
583.696
590.17
593.098
594.58
595.275
595.988
596.713
597.282
597.68
597.925
598.04
598.038
597.934
597.62
597.21
596.89
596.375
595.336
594.025
592.644
590.22
586.608
582.74
577.119
563.395
523.535
471.346
518.979
553.08
574.983
583.548
589.86
593.135
594.511
595.12
595.757
596.502
597.217
597.661
597.896
598.003
597.999
597.896
597.601
597.209
596.927
596.404
595.311
594.219
592.781
590.26
586.671
582.977
577.413
563.469
525.281
469.717
515.423
552.201
574.771
583.498
589.235
592.761
594.212
594.943
595.571
596.412
597.192
597.635
597.859
597.964
597.96
597.85
597.538
597.188
596.922
596.403
595.4
594.256
592.831
590.425
586.813
583.033
577.439
563.606
528.311
468.277
502.949
550.971
574.485
583.379
588.693
592.137
593.753
594.776
595.536
596.346
597.103
597.559
597.794
597.922
597.924
597.82
597.497
597.128
596.872
596.327
595.454
594.419
592.843
590.42
586.998
583.24
577.032
561.65
521.977
460.786
473.176
542.216
572.711
582.769
587.919
591.651
593.666
594.881
595.589
596.341
597.039
597.49
597.679
597.852
597.847
597.748
597.427
597.075
596.734
596.264
595.483
594.519
593.034
590.365
586.872
583.149
575.875
557.965
514.542
457.27
460.88
533.388
569.564
581.422
586.933
591.483
593.869
595.01
595.663
596.369
597.024
597.367
597.59
597.735
597.767
597.675
597.337
596.967
596.616
596.133
595.475
594.57
593.157
590.452
586.558
582.576
574.206
554.635
512.82
457.411
463.581
531.26
566.916
579.597
585.672
591.402
594.096
595.181
595.806
596.461
597.004
597.263
597.494
597.619
597.682
597.591
597.254
596.881
596.472
596.012
595.38
594.561
593.23
590.577
586.897
581.648
571.2
552.471
513.531
457.663
463.235
528.689
565.875
578.966
585.444
591.442
594.362
595.488
596.141
596.725
596.927
597.143
597.352
597.51
597.673
597.484
597.145
596.801
596.365
595.853
595.273
594.441
593.206
590.73
587.098
581.803
569.525
549.204
511.382
457.857
456.078
526.244
565.715
579.35
585.811
591.607
594.49
595.691
596.329
596.699
596.846
596.994
597.237
597.463
597.652
597.453
597.137
596.806
596.288
595.744
595.062
594.194
593.005
590.698
587.112
581.664
570.19
548.82
508.836
455.617
452.481
528.324
567.129
579.682
585.65
591.183
594.355
595.659
596.248
596.542
596.667
596.912
597.163
597.418
597.604
597.448
597.151
596.832
596.291
595.671
594.901
593.939
592.734
590.449
586.941
580.708
569.491
551.318
510.156
453.631
454.314
534.988
567.606
578.595
584.61
589.987
593.971
595.455
595.977
596.187
596.535
596.827
597.096
597.364
597.557
597.428
597.222
596.867
596.307
595.65
594.871
593.944
592.599
590.107
585.953
578.079
567.092
550.155
510.324
454.337
454.666
536.926
566.604
577.302
582.33
587.976
593.211
594.93
595.289
595.87
596.373
596.742
597.05
597.272
597.436
597.382
597.239
596.944
596.34
595.645
594.827
593.928
592.587
589.633
584.758
576.314
565.878
549.625
514.52
461.914
443.702
531.938
564.548
574.602
579.801
586.167
591.755
593.827
594.735
595.66
596.329
596.696
596.998
597.223
597.403
597.319
597.218
596.938
596.321
595.582
594.699
593.798
592.504
589.54
584.701
576.395
565.814
550.413
517.728
465.886
425.103
496.135
555.435
571.694
577.951
584.56
590.49
593.237
594.684
595.692
596.36
596.674
596.979
597.239
597.372
597.28
597.144
596.844
596.132
595.272
594.339
593.46
592.22
589.335
585.091
577.208
567.242
552.787
519.725
465.392
412.25
469.652
540.374
567.824
576.631
584.188
590.416
593.334
594.879
595.877
596.43
596.67
597.007
597.256
597.335
597.217
597.016
596.649
595.809
594.773
593.863
592.935
591.602
588.74
584.944
578.74
570.227
554.79
516.951
465.172
410.602
471.37
539.683
566.914
576.569
584.238
590.615
593.607
595.051
595.995
596.515
596.702
597.043
597.248
597.298
597.162
596.919
596.494
595.602
594.455
593.493
592.275
590.528
587.318
583.277
576.271
566.831
548.736
509.585
464.709
408.924
471.928
538.269
565.805
576.295
584.041
590.551
593.531
595.18
596.1
596.533
596.734
597.038
597.216
597.237
597.104
596.858
596.423
595.498
594.354
593.343
591.861
589.324
584.514
577.65
566.829
552.211
530.409
493.131
458.647
408.145
467.911
534.238
563.05
574.99
583.197
590.074
593.503
595.218
596.112
596.496
596.757
597.055
597.216
597.236
597.103
596.857
596.408
595.486
594.35
593.221
591.54
588.506
582.916
576.236
565.193
550.679
526.34
480.389
441.906
408.844
468.231
532.16
562.094
574.223
581.265
588.926
593.301
595.171
596.056
596.485
596.851
597.123
597.228
597.225
597.094
596.849
596.376
595.383
594.204
593.065
591.339
588.198
582.045
574.041
563.012
548.577
521.577
473.284
428.914
411.123
469.411
526.536
555.786
568.558
576.318
585.743
592.168
594.783
595.834
596.472
596.902
597.197
597.233
597.19
597.066
596.826
596.332
595.299
594.058
592.778
590.764
587.368
581.145
573.673
561.237
544.89
516.69
468.83
426.941
411.136
463.626
519.511
548.928
563.937
573.25
582.752
590.517
594.183
595.663
596.459
596.907
597.215
597.224
597.076
596.982
596.764
596.25
595.131
593.946
592.63
590.32
586.808
580.952
573.148
561.5
542.805
511.686
465.604
426.479
408.846
447.562
510.794
544.745
562.695
572.586
582.412
590.295
594.02
595.602
596.431
596.888
597.204
597.185
596.896
596.749
596.579
596.018
594.864
593.687
592.424
590.29
586.726
580.983
573.209
561.397
543.587
515.473
470.94
427.818
407.255
441.716
506.811
544.342
562.33
572.841
582.63
590.334
593.904
595.488
596.303
596.787
597.155
597.135
596.845
596.552
596.285
595.705
594.634
593.39
592.011
590.131
586.704
581.146
573.339
561.274
543.55
520.648
481.445
440.14
405.737
447.976
508.63
544.305
562.563
573.029
582.432
590.113
593.612
595.187
595.914
596.489
597.002
597.127
596.87
596.509
596.093
595.51
594.55
593.255
591.762
589.64
586.317
581.029
572.888
560.28
543.906
521.924
487.217
452.96
409.776
454.511
509.949
545.127
562.484
572.406
580.94
589.052
592.712
594.387
595.381
596.254
596.799
597.105
596.975
596.546
596.032
595.449
594.553
593.205
591.558
589.373
585.665
580.36
571.42
558.444
543.811
523.916
488.966
456.698
412.017
456.757
511.696
545.337
561.135
570
578.615
586.368
591.026
593.543
595.046
596.134
596.637
597.053
597
596.644
596.027
595.452
594.597
593.215
591.312
588.848
585.159
579.583
570.871
558.027
543.06
523.936
491.632
454.93
416.778
461.717
513.371
543.997
559.047
568.683
576.419
584.216
589.934
593.082
594.832
595.978
596.434
596.93
596.957
596.654
596.015
595.452
594.685
593.346
591.34
588.543
584.209
578.698
570.423
557.824
542.6
521.451
490.939
455.594
427.656
468.79
512.827
543.294
559.076
567.54
574.976
582.975
589.285
592.699
594.535
595.642
596.003
596.587
596.788
596.557
595.938
595.391
594.635
593.304
591.294
588.34
583.471
577.507
569.555
557.239
541.759
520.924
488.522
452.568
433.818
470.295
511.22
543.537
558.691
566.924
574.118
581.767
588.063
591.929
593.882
594.795
594.941
595.743
596.324
596.149
595.6
595.113
594.408
593.029
590.895
587.783
583.244
577.012
568.412
555.965
540.616
521.141
488.215
445.872
430.867
469.367
513.002
542.241
557.737
566.333
573.176
579.978
586.036
590.252
592.543
593.507
593.844
594.643
595.432
595.385
595.06
594.481
593.791
592.315
590.097
586.873
582.473
576.72
567.827
555.31
540.974
522.339
489.237
443.002
421.942
470.716
512.425
538.27
555.179
564.984
571.673
578.227
584.185
588.551
591.081
592.284
593.093
593.761
594.471
594.548
594.32
593.704
592.635
590.918
588.695
585.429
580.891
575.434
567.052
554.936
542.09
525.06
488.199
443.136
419.866
467.637
510.559
535.848
551.596
561.886
569.302
576.26
582.379
586.86
589.669
591.343
592.323
592.78
593.199
593.581
593.57
592.822
591.194
589.121
586.688
583.384
579.159
573.467
565.024
555.037
545.792
529.034
491.373
448.297
411.166
457.469
506.843
534.563
548.925
558.677
566.601
573.955
580.575
585.841
589.034
590.861
591.813
592.069
592.416
592.583
592.47
591.542
589.634
587.412
584.744
581.306
577.186
571.751
563.333
554.426
545.829
530.721
495.63
457.745
405.436
449.621
500.373
532.332
547.712
557.185
564.823
572.113
579.03
584.534
587.927
590.184
591.177
591.412
591.236
591.004
590.827
589.88
588.122
585.843
583.014
579.252
574.919
569.81
562.442
553.092
544.337
527.75
491.716
456.439
405.711
449.041
497.605
530.214
546.793
556.717
563.795
570.612
577.47
582.918
586.918
589.357
590.279
590.379
590.244
589.829
589.312
588.291
586.484
583.898
580.591
576.819
572.448
567.404
560.905
551.767
541.725
523.45
484.458
450.609
411.229
453.568
498.481
527.933
544.757
555.793
562.631
569.162
575.616
581.205
585.538
588.306
589.393
589.552
589.334
588.828
587.933
586.72
584.478
581.327
577.468
573.17
569.192
564.243
557.287
548.279
537.301
516.903
475.9
440.818
422.379
463.794
501.848
525.128
540.701
553.671
562.688
568.011
574.368
579.919
584.222
587.158
588.255
588.387
588.092
587.539
586.323
584.703
582.072
578.262
573.652
568.462
563.408
558.418
549.435
537.692
523.26
497.508
451.371
419.772
432.577
470.661
504.674
522.037
536.588
553.052
562.343
567.564
573.73
579.007
582.994
585.671
586.745
586.847
586.497
585.811
584.454
582.541
579.672
575.539
570.304
564.086
556.87
549.973
539.144
522.366
499.937
467.652
428.277
400.726
433.07
468.975
503.58
520.618
535.501
551.054
561.313
567.318
572.835
577.357
581.161
583.357
584.678
584.82
584.344
583.548
582.276
580.214
577.229
572.996
567.242
560.218
552.022
543.083
530.672
513.847
488.676
454.997
421.72
389.546
425.935
460.018
502.775
521.451
533.159
545.885
558.686
566.656
571.542
575.567
578.992
580.747
581.93
581.946
581.527
580.856
579.306
577.155
573.937
569.428
563.293
555.982
547.952
538.54
527.68
511.769
486.716
454.549
419.665
382.286
414.945
449.673
501.266
519.873
528.804
539.517
553.128
564.205
569.604
573.776
576.99
578.22
578.899
578.942
578.544
577.806
575.856
572.975
569.458
564.956
559.181
552.525
544.862
534.245
523.366
509.468
485.937
456.972
421.751
380.738
410.926
447.176
495.357
515.731
524.937
533.61
545.152
556.64
565.306
570.103
573.096
574.633
574.961
574.928
574.672
573.901
571.64
568.381
564.909
560.941
555.959
550.55
543.91
533.956
524.148
511.969
490.39
461.482
419.649
376.89
408.51
441.993
484.053
509.581
521.057
529.131
538.442
548.172
557.06
564.208
568.329
569.829
570.282
570.37
570.405
570.068
568.177
565.2
561.844
558.065
553.429
548.65
542.656
533.831
526.275
515.798
497.841
462.237
409.123
368.061
402.323
433.955
471.525
500.188
515.053
524.015
531.849
540.586
548.002
555.308
562.307
565.021
565.929
566.067
565.876
565.314
563.942
561.762
558.708
554.528
549.473
545.367
539.342
530.439
522.611
512.596
494.694
457.509
402.464
363.455
389.805
417.37
452.177
482.95
502.914
514.705
524.747
534.763
542.633
550.048
556.488
560.403
561.354
560.909
559.862
558.993
558.369
556.68
553.054
547.389
542.458
538.279
527.58
516.494
507.458
497.267
481.118
446.629
396.45
359.735
369.961
390.844
416.978
446.053
474.273
494.304
510.319
525.456
533.567
540.591
547.89
552.461
552.422
549.998
547.094
545.833
546.744
545.549
540.644
531.377
526.65
517.706
503.517
492.391
476.544
459.13
443.432
418.699
377.934
352.564
352.869
365.113
378.523
395.513
415.95
444.385
474.657
498.805
506.566
514.924
528.167
534.254
530.324
520.089
514.003
512.69
516.724
515.549
509.764
492.242
472.954
455.903
452.155
444.862
431.403
412.219
396.881
381.639
357.677
343.86
343.387
349.935
354.044
359.485
367.261
386.337
409.264
422.002
427.067
449.321
472.211
485.039
471.156
449.077
444.033
444.969
449.458
448.641
446.402
431.726
408.621
396.12
399.679
397.443
391.099
379.387
366.77
356.254
345.213
337.805
339.821
344.006
343.408
343.576
344.934
353.314
362.282
362.484
367.384
383.195
402.664
416.768
407.967
394.088
391.775
391.819
394.784
397.581
398.602
391.534
376.609
368.061
370.12
367.594
362.902
357.108
349.468
343.359
339.804
335.603
336.406
343.135
340.841
338.285
337.272
340.397
344.203
346.119
349.025
356.133
367.373
377.24
376.107
370.865
369.105
368.113
370.619
375.496
377.95
373.598
361.054
354.194
353.365
351.509
346.483
341.634
338.264
336.168
336.472
332.099
)
;
boundaryField
{
inlet
{
type zeroGradient;
}
outlet
{
type zeroGradient;
}
walls
{
type zeroGradient;
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
| [
"mizuha.watanabe@gmail.com"
] | mizuha.watanabe@gmail.com |
e28f0b342c224bbb4897d70eb9a51b3901e59cdd | bac7d74c7e0123e54f216bf7e16ea4569b4daced | /include/trans.h | bf9d20f711abac565a3ef174f328c22085b4884d | [
"MIT"
] | permissive | jjsisjjz/kepub | fab1e0dea83229f810f70f500daf744c1e268684 | 982166cc80466ee2007b1cb65bc5e98b2a10dfd2 | refs/heads/main | 2023-08-01T06:42:35.766718 | 2021-09-16T13:14:27 | 2021-09-16T13:14:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 122 | h | #pragma once
#include <string>
namespace kepub {
std::string trans_str(const std::string &str);
} // namespace kepub
| [
"1244713586@qq.com"
] | 1244713586@qq.com |
a4161afb89fb997e2d7a62cec5986206cb85b79b | 8b1cedbca5f5a967e5c37c280f53dfdbff00ff19 | /cocos/170810/Classes/CEnemy.h | 12df48a6d49a9a0265878704612f2b265b807458 | [] | no_license | kcwzzz/KCW | ef552641c77d1971ad4536d37a70eb9a59f4d4e6 | 34973e5fae0a4095418ac0bd99637ffa24f525be | refs/heads/master | 2020-12-03T05:11:38.828978 | 2017-09-29T08:10:59 | 2017-09-29T08:10:59 | 95,736,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 539 | h | #pragma once
#include "cocos2d.h"
#include "CCharacter.h"
#include <vector>
USING_NS_CC;
using namespace std;
class CEnemyBullet;
typedef vector <CEnemyBullet *> CEnemyBulletVec;
class CEnemy :public CCharacter
{
private:
protected:
CEnemyBulletVec mEnemyBulletVec;
float mEnemyRegenTime;
public:
virtual void Create();
virtual void Build();
virtual void Destroy();
virtual void Update(float dt);
virtual void SetScene(GameScene *tpScene);
virtual void ReadyToFire(float f);
public:
CEnemy();
virtual ~CEnemy();
}; | [
"kcwzzz@naver.com"
] | kcwzzz@naver.com |
d3ec2015fc412bce9c778762ea8c535ada496cee | 9825e0d367fcfc52e7a2f511f57d52a21d08d5bd | /utils.cpp | 59e619d8081b04adb87d67bc8e14a013ad0d483a | [] | no_license | ahosler/FPGACNN | dae35e15f7ddb18d4523f83cea770438ae791b03 | b5eaf1579063c597ea38e5b16467d837f05e2544 | refs/heads/master | 2020-03-27T20:09:29.989051 | 2018-09-02T01:06:59 | 2018-09-02T01:06:59 | 147,043,845 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,145 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#include <sys/time.h>
#include "defines.h"
#include "CL/opencl.h"
#include "AOCLUtils/aocl_utils.h"
using namespace aocl_utils;
unsigned int convert_endian_4bytes(unsigned int input){
unsigned char* bytes = (unsigned char*) &input;
return (unsigned int) bytes[3] | (((unsigned int) bytes[2]) << 8) | (((unsigned int) bytes[1]) << 16) | (((unsigned int) bytes[0]) << 24);
}
void write_weights_file(char *filename, float *weights, int num_weights) {
FILE *f = fopen(filename, "wb");
if (f == NULL){
printf("ERROR: could not open %s\n",filename);
return;
}
fwrite(weights, sizeof(float), num_weights, f);
fclose(f);
}
// TODO: You may need to modify this file to read in files with differently sized weights.
bool read_weights_file(char *filename, float *weights, int width) {
FILE *f = fopen(filename, "rb");
if (f == NULL){
printf("ERROR: could not open %s\n",filename);
return false;
}
//printf("%d\n", FEATURE_COUNT);
int read_elements = -1;
if (width == 16) {
read_elements = fread(weights, sizeof(short), FEATURE_COUNT, f);
}else if(width == 8) {
read_elements = fread(weights, sizeof(char), FEATURE_COUNT, f);
}else if(width == 4) {
read_elements = fread(weights, sizeof(char), FEATURE_COUNT/2, f);
}else {
read_elements = fread(weights, sizeof(float), FEATURE_COUNT, f);
//for (int i = 0; i<FEATURE_COUNT; i++) {
//printf("%f\n",weights[i]);
//}
}
fclose(f);
//TODO: Uncomment with fix
if (read_elements != FEATURE_COUNT){
if(width == 4 && read_elements != FEATURE_COUNT/2) {
printf("ERROR: read incorrect number of weights from %s\n", filename);
return false;
} else {
return true;
}
printf("ERROR: read incorrect number of weights from %s\n", filename);
return false;
}
return true;
}
int parse_MNIST_images(const char* file, unsigned char** X){
int n_items = 0, magic_num = 0, n_rows = 0, n_cols = 0, elements_read = 0;
FILE* f = fopen(file, "rb");
if (f == NULL){
printf("ERROR: Could not open %s\n",file);
return 0;
}
elements_read = fread(&magic_num, sizeof(int), 1, f );
if (convert_endian_4bytes(magic_num) != MNIST_IMAGE_FILE_MAGIC_NUMBER){
printf("WARNING: Magic number mismatch in %s.\n", file);
}
elements_read = fread(&n_items, sizeof(int), 1, f );
elements_read = fread(&n_rows, sizeof(int), 1, f );
elements_read = fread(&n_cols, sizeof(int), 1, f );
n_items = convert_endian_4bytes(n_items);
n_rows = convert_endian_4bytes(n_rows);
n_cols = convert_endian_4bytes(n_cols);
// n_rows * n_cols should equal FEATURE_COUNT (28*28 = 784)
if (n_rows*n_cols != FEATURE_COUNT){
printf("ERROR: Unexpected image size in %s.\n", file);
return 0;
}
*X = (cl_uchar*)alignedMalloc(n_items*FEATURE_COUNT*sizeof(unsigned char));
unsigned char* X_ptr = *X;
// Read in the pixels. Each pixel is 1 byte. There should be n_items*n_rows*n_cols pixels).
elements_read = fread(X_ptr, sizeof(unsigned char), n_rows*n_cols*n_items, f);
if (elements_read != n_rows*n_cols*n_items){
printf("ERROR: Unexpected file length for %s.\n", file);
free(*X);
return 0;
}
return n_items;
}
int parse_MNIST_labels(const char* file, unsigned char** y){
int n_items = 0;
int magic_num = 0;
int elements_read = 0;
FILE* f = fopen(file, "rb");
if (f == NULL){
printf("ERROR: Could not open %s\n",file);
return 0;
}
elements_read = fread(&magic_num, sizeof(int), 1, f );
if (convert_endian_4bytes(magic_num) != MNIST_LABEL_FILE_MAGIC_NUMBER){
printf("WARNING: Magic number mismatch in %s.\n", file);
}
elements_read = fread(&n_items, sizeof(int), 1, f );
n_items = convert_endian_4bytes(n_items);
*y = (cl_uchar*) alignedMalloc(n_items*sizeof(unsigned char));
// Read in the pixels. Each pixel is 1 byte. There should be n_items*n_rows*n_cols pixels).
elements_read = fread(*y, sizeof(unsigned char), n_items, f);
if (elements_read != n_items){
printf("ERROR: Unexpected file length for %s.\n", file);
free(*y);
return 0;
}
return n_items;
}
void parse_arguments(int argc, char *argv[], int *task, float *alpha, int *iterations, int *n_items_limit) {
// Setting task based on FIRST argument
*task = UNKNOWN;
if(argc >= 2) {
if(strcmp(argv[1], "train") == 0)
*task = TRAIN;
else if(strcmp(argv[1], "test") == 0)
*task = TEST;
}
if(*task != UNKNOWN) {
// Set default values.
*alpha = DEFAULT_ALPHA;
*iterations = DEFAULT_ITERATIONS;
*n_items_limit = DEFAULT_N_ITEMS_LIMIT;
// Read command line arguments.
for(int i = 2; i < argc - 1; i++) {
if (strcmp(argv[i], "--alpha") == 0)
*alpha = atof(argv[i + 1]);
else if (strcmp(argv[i], "--alpha_int") == 0)
*alpha = atoi(argv[i + 1]);
else if (strcmp(argv[i], "--iter") == 0)
*iterations = atoi(argv[i + 1]);
else if (strcmp(argv[i], "--nitems") == 0)
*n_items_limit = atoi(argv[i + 1]);
}
}
}
double get_wall_time(){
struct timeval time;
if (gettimeofday(&time,NULL)){
// Handle error
return 0;
}
return (double)time.tv_sec*1000 + (double)time.tv_usec /1000;
}
| [
"noreply@github.com"
] | noreply@github.com |
de078c5092150d91f531ad8be490ed299d0b8e2c | 42ecd4ac9c64cbcdec4f9876667a23b363454d63 | /flash_readwritelol/flash_readwritelol.ino | 0d9076e16eec12b909b9843e0111781ec94cac80 | [] | no_license | YenniferMontes/MSP430G2553 | 65dd3019b3c99b48c995e565b36a750a832c7444 | 78d884354e5850aef5d7686aa1fa0a22bc2ae805 | refs/heads/master | 2021-01-01T18:03:51.488303 | 2017-07-02T21:19:27 | 2017-07-02T21:19:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,613 | ino | /*
flas_readwrite.h - Read/Write flash memory library example for MSP430 Energia
Copyright (c) 2012 Peter Brier. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Provide access to the MSP430 flash memory controller.
All flash memory can be read, erased and written (except SEGMENT_A, the LOCK bits are not in the code, for a good reason).
Flash can only be erased per 512 byte segments (except the 4 special information segments, they are 64 bytes in size)
The same flash locations can be written multiple times with new values, but flash bits can only be reset (from 1 to 0) and cannot
change to a 1 (you need to flash erase the whole segment)
functions:
~~~~~~~~~~
erase(): Erase a flash segment, all bytes in the segment will read 0xFF after an erase
read(): Read flash locations (actually just a proxy for memcpy)
write(): Write flash locations (actually just a proxy for memcpy), the same location can be written multiple times,
but once a bit is reset, you cannot set it with a subsequent write, you need to flash the complete segment to do so.
constants:
~~~~~~~~~~
SEGMENT_A // pointer to 64 byte flash segments
SEGMENT_B
SEGMENT_C
SEGMENT_D
Macros:
~~~~~~~
SEGPTR(x) // Return pointer to first complete segment inside variable
SEGMENT(n) // Return pointer to start of segment n (n=0..63)
NOTE: you are flashing the program memory, you can modify EVERYTHING (program, data) this is usually not what you want.
Be carefull when flashing data. You may use SEG_B to SEG_D for normal use, they should not be filled by the compiler
If you wish to use main memory, you need to inform the linker NOT to use the segments you wish to use in the linker script
(this is not for the faint of heart).
An alternative approach is to allocate a static variable with a size of AT LEAST 2 SEGMENTS in your program.
This makes sure there is at least ONE COMPLETE SEGMENT in this static variable, so there is no colleteral damage when you flash this
area. You need to find the pointer to the start of the next segment. There is a macro define to do this: SEGPTR(x)
A example that makes 2 segments available for flashing by allocating 3 segments of constant data:
Using the example:
~~~~~~~~~~~~~~~~~~
On the launchpad; put the two UART jumpers in HARDWARE SERIAL position (horizontal position) and use the terminal window to connect
to the board (9600baud).
'e' Erase the flash segment
'w' Write "Hello World" to the flash
'r' Read the contents of the flash, and print as byte values and characters. stop at the first NULL byte
- When you program the launchpad and read the flash, a single "0" character should be read (mem contains zero values)
Writing the flash before you have erased it is not possible (you cannot program OFF bits to ON bits)
- When you erase the flash, 0xFF values will be read back
- When you write the flash, "Hello World" will be read back
*/
#include "MspFlash.h"
// Two options to use for flash: One of the info flash segments, or a part of the program memory
// either define a bit of constant program memory, and pass a pointer to the start of a segment to the flash functions,
//*** Option 1: use program memory, uncomment these lines and you have 512 bytes of flash available (1024 bytes allocated) ****
const unsigned char data[2*SEGMENT_SIZE] = {0};
#define flash SEGPTR(data)
//
//*** Option 2: use one of the 64 byte info segments, uncomment this line. Use SEGMENT_B, SEGMENT_C or SEGMENT_D (each 64 bytes, 192 bytes in total)
//#define flash SEGMENT_D
//
const int xpin = A0;
const int ypin = A3;
const int zpin = A4;
int bufer = 0;
int guardo = 0;
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
delay(10000);
}
void loop() {
doErase();
delay(10000);
doRead();
delay(10000);
doWrite();
delay(10000);
doRead();
delay(10000);
}
void doRead()
{
unsigned char p = 0;
int i=0;
Serial.println("Read:");
do
{
Flash.read(flash+i, &p, 1);
guardo = (int) &p;
Serial.write(p);
Serial.print(":");
Serial.println(guardo);
} while ( p && (i++ < 10) );
Serial.println(".");
}
void doErase()
{
Serial.println("Erase");
Flash.erase(flash);
Serial.println("Done.");
}
void doWrite()
{
Serial.println("Write");
for (int x = 0; x<50; x++){
bufer = analogRead(xpin);
Flash.write(flash+(9*x), (unsigned char*) String(bufer).c_str() ,3);
bufer = analogRead(ypin);
Flash.write(flash+(9*x)+3, (unsigned char*) String(bufer).c_str() ,3);
bufer = analogRead(zpin);
Flash.write(flash+(9*x)+6, (unsigned char*) String(bufer).c_str() ,3);
delay(10);
}
Serial.println("Done.");
}
void doHelp()
{
int div = (F_CPU/400000L) & 63;
Serial.println("flash test: e, r, w");
Serial.println(F_CPU);
Serial.println(div);
}
| [
"tiannymonti@gmail.com"
] | tiannymonti@gmail.com |
51dba95002ffa584fcb240152cff268420f85e0d | 3b04925b4271fe921020cff037b86e4a5a2ae649 | /windows_embedded_ce_6_r3_170331/WINCE600/PRIVATE/SERVERS/TIMESVC2/SNTP/sntp.cxx | f0a809c06f45d031ace2aaa9f1fa52739bdcf349 | [] | no_license | fanzcsoft/windows_embedded_ce_6_r3_170331 | e3a4d11bf2356630a937cbc2b7b4e25d2717000e | eccf906d61a36431d3a37fb146a5d04c5f4057a2 | refs/heads/master | 2022-12-27T17:14:39.430205 | 2020-09-28T20:09:22 | 2020-09-28T20:09:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,498 | cxx | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft shared
// source or premium shared source license agreement under which you licensed
// this source code. If you did not accept the terms of the license agreement,
// you are not authorized to use this source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the SOURCE.RTF on your install media or the root of your tools installation.
// THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES.
//
/*--
Module Name: sntp.cxx
Abstract: service sntp module
--*/
#include <windows.h>
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <svsutil.hxx>
#include <service.h>
#include <notify.h>
#include "../inc/timesvc.h"
#define NOTIFICATION_WAIT_SEC 30
#if ! defined(DNS_MAX_NAME_BUFFER_LENGTH)
#define DNS_MAX_NAME_BUFFER_LENGTH (256)
#endif
#define NTP_PORT 123
#define NTP_PORT_A "123"
#define BASE_KEY L"services\\timesvc"
#define MIN_REFRESH (5*60*1000)
#define MIN_MULTICAST (5*60*1000)
#define MIN_TIMEUPDATE (5*1000)
#define MAX_STACKS 5
#define MAX_SERVERS 10
#define MAX_MCASTS 10
#define MAX_MSZ 1024
static HANDLE hNotifyThread = NULL;
static HANDLE hExitEvent = NULL;
typedef BOOL (*tCeRunAppAtEvent)(WCHAR *pwszAppName, LONG lWhichEvent);
typedef DWORD (*tNotifyAddrChange)(PHANDLE Handle, LPOVERLAPPED overlapped);
#define NTPTIMEOFFSET (0x014F373BFDE04000)
#define FIVETOTHESEVETH (0x001312D)
/*
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|LI | VN |Mode | Stratum | Poll | Precision |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Root Delay |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Root Dispersion |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reference Identifier |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| Reference Timestamp (64) |
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| Originate Timestamp (64) |
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| Receive Timestamp (64) |
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| Transmit Timestamp (64) |
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Key Identifier (optional) (32) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| |
| Message Digest (optional) (128) |
| |
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
///////////////////////////////////////////////////////////////////////
//
// Base Classes
//
//
class NTP_REQUEST {
private:
union {
struct {
unsigned char i_lvm, i_stratum, i_poll, i_prec;
unsigned char i_root_delay[4];
unsigned char i_root_dispersion[4];
unsigned char i_ref_identifier[4];
unsigned char i_ref_stamp[8];
unsigned char i_orig_stamp[8];
unsigned char i_recv_stamp[8];
unsigned char i_trans_stamp[8];
};
unsigned __int64 ll;
};
public:
unsigned int li (void) {
return (i_lvm >> 6) & 0x03;
}
void set_li (unsigned int l) {
i_lvm = (i_lvm & 0x3f) | ((l & 0x3) << 6);
}
unsigned int vn (void) {
return (i_lvm >> 3) & 0x07;
}
void set_vn (unsigned int v) {
i_lvm = (i_lvm & 0xc7) | ((v & 0x7) << 3);
}
unsigned int mode (void) {
return i_lvm & 0x07;
}
void set_mode (unsigned int m) {
i_lvm = (i_lvm & 0xf8) | (m & 0x7);
}
unsigned int stratum (void) {
return i_stratum;
}
void set_stratum (unsigned int s) {
i_stratum = s;
}
unsigned int poll (void) {
return i_poll;
}
void set_poll (unsigned int p) {
i_poll = p;
}
unsigned int precision (void) {
return i_prec;
}
void set_precision (unsigned int p) {
i_prec = p;
}
unsigned int root_delay (void) {
return (i_root_delay[0] << 24) | (i_root_delay[1] << 16) | (i_root_delay[2] << 8) | i_root_delay[3];
}
void set_root_delay (unsigned int rd) {
i_root_delay[0] = (unsigned char)(rd >> 24);
i_root_delay[1] = (unsigned char)(rd >> 16);
i_root_delay[2] = (unsigned char)(rd >> 8);
i_root_delay[3] = (unsigned char) rd;
}
unsigned int root_dispersion (void) {
return (i_root_dispersion[0] << 24) | (i_root_dispersion[1] << 16) | (i_root_dispersion[2] << 8) | i_root_dispersion[3];
}
void set_root_dispersion (unsigned int rd) {
i_root_dispersion[0] = (unsigned char)(rd >> 24);
i_root_dispersion[1] = (unsigned char)(rd >> 16);
i_root_dispersion[2] = (unsigned char)(rd >> 8);
i_root_dispersion[3] = (unsigned char) rd;
}
unsigned int ref_id (void) {
return (i_ref_identifier[0] << 24) | (i_ref_identifier[1] << 16) | (i_ref_identifier[2] << 8) | i_ref_identifier[3];
}
void set_ref_id (unsigned int rid) {
i_ref_identifier[0] = (unsigned char)(rid >> 24);
i_ref_identifier[1] = (unsigned char)(rid >> 16);
i_ref_identifier[2] = (unsigned char)(rid >> 8);
i_ref_identifier[3] = (unsigned char) rid;
}
unsigned __int64 ref_stamp (void) {
return *(unsigned __int64 *)i_ref_stamp;
}
void set_ref_stamp (unsigned __int64 ll) {
*(unsigned __int64 *)i_ref_stamp = ll;
}
unsigned __int64 orig_stamp (void) {
return *(unsigned __int64 *)i_orig_stamp;
}
void set_orig_stamp (unsigned __int64 ll) {
*(unsigned __int64 *)i_orig_stamp = ll;
}
unsigned __int64 recv_stamp (void) {
return *(unsigned __int64 *)i_recv_stamp;
}
void set_recv_stamp (unsigned __int64 ll) {
*(unsigned __int64 *)i_recv_stamp = ll;
}
unsigned __int64 trans_stamp (void) {
return *(unsigned __int64 *)i_trans_stamp;
}
void set_trans_stamp (unsigned __int64 ll) {
*(unsigned __int64 *)i_trans_stamp = ll;
}
};
enum When {
Now,
Shortly,
Later
};
class TimeState : public SVSSynch {
SVSThreadPool *pEvents;
SOCKET saServer[MAX_STACKS];
int iSock;
DWORD dwRefreshMS;
DWORD dwRecoveryRefreshMS;
DWORD dwAdjustThreshMS;
DWORD dwMulticastPeriodMS;
SVSCookie ckNextRefresh;
SVSCookie ckNextMulticast;
char sntp_servers[MAX_SERVERS][DNS_MAX_NAME_BUFFER_LENGTH];
char sntp_mcasts[MAX_MCASTS][DNS_MAX_NAME_BUFFER_LENGTH];
int cServers;
int cMcasts;
union {
struct {
unsigned int fStarted : 1;
unsigned int fHaveClient : 1;
unsigned int fHaveServer : 1;
unsigned int fSystemTimeCorrect : 1;
unsigned int fRefreshRequired : 1;
unsigned int fForceTimeToServer : 1;
};
unsigned int uiFlags;
};
void ReInit (void) {
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] State reinitialized\r\n"));
pEvents = 0;
for (int i = 0 ; i < SVSUTIL_ARRLEN(saServer) ; ++i)
saServer[i] = INVALID_SOCKET;
iSock = 0;
llLastSyncTimeXX = 0;
ckNextRefresh = ckNextMulticast = 0;
memset (sntp_servers, 0, sizeof(sntp_servers));
memset (sntp_mcasts, 0, sizeof(sntp_mcasts));
cServers = 0;
cMcasts = 0;
dwRefreshMS = dwRecoveryRefreshMS = dwAdjustThreshMS = dwMulticastPeriodMS = 0;
uiFlags = 0;
}
public:
unsigned __int64 llLastSyncTimeXX;
int IsStarted (void) { return fStarted; }
int LastUpdateFailed (void) { return fRefreshRequired; }
int RefreshConfig (void);
int ForcedUpdate (void);
int UpdateNowOrLater (enum When, int fForceTime = FALSE);
int TimeChanged (void);
int Start (void);
SVSThreadPool *Stop (void);
TimeState (void) {
ReInit ();
}
int IsTimeAccurate(void) {
// Trust the time if we have a local clock, or if
// we have a client and there is no refresh required (its up-to-date).
return fSystemTimeCorrect || (! fRefreshRequired && fHaveClient);
};
friend DWORD WINAPI RxThread (LPVOID lpUnused);
friend DWORD WINAPI TimeRefreshThread (LPVOID lpUnused);
friend DWORD WINAPI MulticastThread (LPVOID lpUnused);
friend DWORD WINAPI GetTimeOffsetOnServer (LPVOID lpArg);
};
struct GetTimeOffset {
__int64 llOffset;
unsigned char cchServer[DNS_MAX_NAME_BUFFER_LENGTH];
};
static int GetAddressList (HKEY hk, WCHAR *szValue, char *pItems, int cItems, int cItemSize, int *piCount) {
*piCount = 0;
union {
DWORD dw;
in_addr ia;
WCHAR szM[MAX_MSZ];
} u;
DWORD dwType;
DWORD dwSize = sizeof(u);
if (ERROR_SUCCESS != RegQueryValueEx (hk, szValue, NULL, &dwType, (LPBYTE)&u, &dwSize))
return ERROR_SUCCESS;
u.szM[MAX_MSZ-1] = '\0';
u.szM[MAX_MSZ-2] = '\0';
if (dwType == REG_DWORD) { // Legacy: ip address
if (dwSize == sizeof(DWORD)) {
*piCount = 1;
strcpy (pItems, inet_ntoa (u.ia));
return ERROR_SUCCESS;
}
}
if (dwType == REG_SZ) { // Legacy: single name
int cc = WideCharToMultiByte (CP_ACP, 0, u.szM, -1, pItems, cItemSize, NULL, NULL);
if (cc > 0) {
*piCount = 1;
return ERROR_SUCCESS;
}
}
if (dwType == REG_MULTI_SZ) { // List of names/addresses
WCHAR *p = u.szM;
while (*p) {
int cc = cItems ? WideCharToMultiByte (CP_ACP, 0, p, -1, pItems, cItemSize, NULL, NULL) : 0;
if (cc == 0) {
*piCount = 0;
break;
}
++*piCount;
pItems += cItemSize;
cItems--;
p += wcslen (p) + 1;
}
return ERROR_SUCCESS;
}
return ERROR_BAD_CONFIGURATION;
}
///////////////////////////////////////////////////////////////////////
//
// Base Classes - implementation
//
//
int TimeState::RefreshConfig (void) {
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Refreshing configuration\r\n"));
HKEY hk;
int iErr = ERROR_BAD_CONFIGURATION;
ReInit ();
if (ERROR_SUCCESS == RegOpenKeyEx (HKEY_LOCAL_MACHINE, BASE_KEY, 0, KEY_READ, &hk)) {
iErr = GetAddressList (hk, L"server", (char *)sntp_servers, SVSUTIL_ARRLEN(sntp_servers), SVSUTIL_ARRLEN(sntp_servers[0]), &cServers);
if (cServers) {
iErr = ERROR_SUCCESS;
DWORD dw;
DWORD dwType = 0;
DWORD dwSize = sizeof(dw);
if ((ERROR_SUCCESS == RegQueryValueEx (hk, L"AutoUpdate", NULL, &dwType, (LPBYTE)&dw, &dwSize)) &&
(dwType == REG_DWORD) && (dwSize == sizeof(dw)) && dw)
fHaveClient = TRUE;
if (fHaveClient) {
dwType = 0;
dwSize = sizeof(dwRefreshMS);
if ((ERROR_SUCCESS == RegQueryValueEx (hk, L"refresh", NULL, &dwType, (LPBYTE)&dwRefreshMS, &dwSize)) &&
(dwType == REG_DWORD) && (dwSize == sizeof(DWORD)) && (dwRefreshMS >= MIN_REFRESH)) {
;
} else {
iErr = ERROR_BAD_CONFIGURATION; // Require refresh key if we have a client
RETAILMSG(1, (L"[TIMESVC] Configuration error: refresh rate incorrect. Aborting.\r\n"));
}
}
if ((iErr == ERROR_SUCCESS) && fHaveClient) {
iErr = ERROR_BAD_CONFIGURATION; // Require accelerated refresh key if we have a client
dwType = 0;
dwSize = sizeof(dwRecoveryRefreshMS);
if ((ERROR_SUCCESS == RegQueryValueEx (hk, L"recoveryrefresh", NULL, &dwType, (LPBYTE)&dwRecoveryRefreshMS, &dwSize)) &&
(dwType == REG_DWORD) && (dwSize == sizeof(DWORD)) && (dwRecoveryRefreshMS >= MIN_REFRESH) && (dwRecoveryRefreshMS <= dwRefreshMS)) {
iErr = ERROR_SUCCESS;
} else {
RETAILMSG(1, (L"[TIMESVC] Configuration error: accelerated refresh rate incorrect. Aborting.\r\n"));
}
}
if ((iErr == ERROR_SUCCESS) && fHaveClient) {
iErr = ERROR_BAD_CONFIGURATION; // Require threshold if we have a client
dwType = 0;
dwSize = sizeof(dw);
if ((ERROR_SUCCESS == RegQueryValueEx (hk, L"threshold", NULL, &dwType, (LPBYTE)&dw, &dwSize)) &&
(dwType == REG_DWORD) && (dwSize == sizeof(dw))) {
dwAdjustThreshMS = dw;
iErr = ERROR_SUCCESS;
} else {
RETAILMSG(1, (L"[TIMESVC] Configuration error: time adjustment threshold incorrect. Aborting.\r\n"));
}
}
} else {
iErr = ERROR_SUCCESS;
fSystemTimeCorrect = TRUE;
}
DWORD dw;
DWORD dwType = 0;
DWORD dwSize = sizeof(dw);
if ((iErr == ERROR_SUCCESS) && (ERROR_SUCCESS == RegQueryValueEx (hk, L"ServerRole", NULL, &dwType, (LPBYTE)&dw, &dwSize)) &&
(dwType == REG_DWORD) && (dwSize == sizeof(dw)) && dw)
fHaveServer = TRUE;
dwType = 0;
dwSize = sizeof(dw);
if ((ERROR_SUCCESS == RegQueryValueEx (hk, L"trustlocalclock", NULL, &dwType, (LPBYTE)&dw, &dwSize)) &&
(dwType == REG_DWORD) && (dwSize == sizeof(dw)) && dw)
fSystemTimeCorrect = TRUE;
if (fHaveServer) {
iErr = GetAddressList (hk, L"multicast", (char *)sntp_mcasts, SVSUTIL_ARRLEN(sntp_mcasts), SVSUTIL_ARRLEN(sntp_mcasts[0]), &cMcasts);
if ((iErr == ERROR_SUCCESS) && cMcasts) {
if ((ERROR_SUCCESS == RegQueryValueEx (hk, L"multicastperiod", NULL, &dwType, (LPBYTE)&dw, &dwSize)) &&
(dwType == REG_DWORD) && (dwSize == sizeof(dw)) && (dw > MIN_MULTICAST))
dwMulticastPeriodMS = dw;
else {
iErr = ERROR_BAD_CONFIGURATION;
RETAILMSG(1, (L"[TIMESVC] Configuration error: Multicast period required. Aborting.\r\n"));
}
}
}
RegCloseKey (hk);
} else {
fHaveClient = TRUE;
fHaveServer = TRUE;
iErr = ERROR_SUCCESS;
strcpy ((char *)sntp_servers[0], "time.windows.com");
cServers = 1;
sntp_mcasts[0][0] = '\0';
cMcasts = 0; // No multicasts
dwRefreshMS = 14*24*60*60*1000; // Synchronize clock every two weeks
dwRecoveryRefreshMS = 30*60*1000; // Try every half hour if it fails
dwAdjustThreshMS = 24*60*60*1000; // Allow one day
fSystemTimeCorrect = TRUE; // Server provides time even if time synch failed
}
if (fHaveServer) {
}
for (int i = 0 ; i < cServers ; ++i) {
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Configuration: sntp server : %a\r\n", sntp_servers[i]));
}
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Configuration: client : %s\r\n", fHaveClient ? L"enabled" : L"disabled"));
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Configuration: server : %s\r\n", fHaveServer ? L"enabled" : L"disabled"));
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Configuration: regular refresh : %d ms (%d day(s))\r\n", dwRefreshMS, dwRefreshMS/(24*60*60*1000)));
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Configuration: accelerated refresh : %d ms (%d day(s))\r\n", dwRecoveryRefreshMS, dwRecoveryRefreshMS/(24*60*60*1000)));
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Configuration: adjustment threshold : %d ms\r\n", dwAdjustThreshMS));
if (fHaveServer) {
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Configuration: system clock : %s\r\n", fSystemTimeCorrect ? L"presumed correct" : L"presumed wrong if not updates"));
for (int i = 0 ; i < cMcasts ; ++i) {
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Configuration: multicast address : %a\r\n", sntp_mcasts[i]));
}
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Configuration: multicast period : %d ms\r\n", dwMulticastPeriodMS));
}
return iErr;
}
int TimeState::ForcedUpdate (void) {
fRefreshRequired = TRUE;
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Client: updating time NOW\r\n"));
if (ckNextRefresh)
pEvents->UnScheduleEvent (ckNextRefresh);
if (! fSystemTimeCorrect)
fForceTimeToServer = TRUE;
if (! (ckNextRefresh = pEvents->ScheduleEvent (TimeRefreshThread, NULL, 0)))
return ERROR_OUTOFMEMORY;
return ERROR_SUCCESS;
}
int TimeState::UpdateNowOrLater (enum When when, int fForceTime) {
if (! fHaveClient) {
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Client: not enabled; update request ignored\r\n"));
return ERROR_SUCCESS;
}
DWORD dwTimeout;
if (when == Now) {
fRefreshRequired = TRUE;
dwTimeout = NULL;
} else if (when == Shortly) {
SVSUTIL_ASSERT (fRefreshRequired);
dwTimeout = dwRecoveryRefreshMS;
} else
dwTimeout = dwRefreshMS;
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Client: schedule time update in %d ms %s\r\n", dwTimeout, fForceTime ? L"(require refresh)" : L""));
if (ckNextRefresh)
pEvents->UnScheduleEvent (ckNextRefresh);
if (fForceTime || (! fSystemTimeCorrect))
fForceTimeToServer = TRUE;
if (! (ckNextRefresh = pEvents->ScheduleEvent (TimeRefreshThread, NULL, dwTimeout)))
return ERROR_OUTOFMEMORY;
return ERROR_SUCCESS;
}
int TimeState::TimeChanged (void) {
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Server: Time changed - multicast now?\r\n"));
if (cMcasts == 0)
return 0;
if (ckNextMulticast)
pEvents->UnScheduleEvent (ckNextMulticast);
if (! (ckNextMulticast = pEvents->ScheduleEvent (MulticastThread, NULL, 0)))
return ERROR_OUTOFMEMORY;
return ERROR_SUCCESS;
}
int TimeState::Start (void) {
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Service starting\r\n"));
pEvents = new SVSThreadPool (5);
if (! pEvents) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Start error: Out of memory allocating threads\r\n"));
return ERROR_OUTOFMEMORY;
}
if (fHaveServer) {
ADDRINFO aiHints;
ADDRINFO *paiLocal = NULL;
memset(&aiHints, 0, sizeof(aiHints));
aiHints.ai_family = PF_UNSPEC;
aiHints.ai_socktype = SOCK_DGRAM;
aiHints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
iSock = 0;
int iErr = ERROR_SUCCESS;
if (0 != getaddrinfo(NULL, NTP_PORT_A, &aiHints, &paiLocal)) {
iErr = GetLastError ();
DEBUGMSG(ZONE_ERROR,(L"[TIMESVC] Start error: getaddrinfo() fails, GLE=0x%08x\r\n",iErr));
} else {
for (ADDRINFO *paiTrav = paiLocal; paiTrav && (iSock < SVSUTIL_ARRLEN(saServer)) ; paiTrav = paiTrav->ai_next) {
if (INVALID_SOCKET == (saServer[iSock] = socket(paiTrav->ai_family, paiTrav->ai_socktype, paiTrav->ai_protocol)))
continue;
if (SOCKET_ERROR == bind(saServer[iSock], paiTrav->ai_addr, paiTrav->ai_addrlen)) {
iErr = GetLastError ();
DEBUGMSG(ZONE_ERROR,(L"[TIMESVC] Start error: failed to bind socket, GLE=0x%08x\r\n",iErr));
closesocket (saServer[iSock]);
continue;
}
++iSock;
}
}
if (paiLocal)
freeaddrinfo(paiLocal);
if (iSock == 0) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Start error: failure to register time server (error %d)\r\n", iErr));
delete pEvents;
ReInit ();
return iErr;
}
if ( ! pEvents->ScheduleEvent (RxThread, NULL)) {
for (int i = 0 ; i < iSock ; ++i)
closesocket (saServer[i]);
SVSThreadPool *pp = pEvents;
ReInit ();
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Start error: Out of memory scheduling server thread\r\n"));
Unlock ();
delete pp;
Lock ();
return ERROR_OUTOFMEMORY;
}
}
if (ERROR_SUCCESS != UpdateNowOrLater (Now)) {
for (int i = 0 ; i < iSock ; ++i)
closesocket (saServer[i]);
SVSThreadPool *pp = pEvents;
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Start error: Out of memory scheduling time update\r\n"));
ReInit ();
Unlock ();
delete pp;
Lock ();
return ERROR_OUTOFMEMORY;
}
fStarted = TRUE;
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Service started successfully\r\n"));
return ERROR_SUCCESS;
}
SVSThreadPool *TimeState::Stop (void) {
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Stopping service\r\n"));
fStarted = FALSE;
for (int i = 0 ; i < iSock ; ++i) {
closesocket (saServer[i]);
saServer[i] = INVALID_SOCKET;
}
iSock = 0;
SVSThreadPool *pp = pEvents;
pEvents = NULL;
return pp;
}
///////////////////////////////////////////////////////////////////////
//
// Globals
//
//
static TimeState *gpTS = NULL;
///////////////////////////////////////////////////////////////////////
//
// Service functions
//
// Note: NTP time conversion functions derived from XP's NTP sources (ntpbase.*)
//
static inline unsigned char EndianSwap (unsigned char x) {
return x;
}
static inline unsigned short EndianSwap (unsigned short x) {
return (EndianSwap ((unsigned char)x) << 8) | EndianSwap ((unsigned char)(x >> 8));
}
static inline unsigned int EndianSwap (unsigned int x) {
return (EndianSwap ((unsigned short)x) << 16) | EndianSwap ((unsigned short)(x >> 16));
}
static inline unsigned __int64 EndianSwap (unsigned __int64 x) {
return (((unsigned __int64)EndianSwap ((unsigned int)x)) << 32) | EndianSwap ((unsigned int)(x >> 32));
}
static unsigned __int64 NtTimeEpochFromNtpTimeEpoch(unsigned __int64 te) {
//return (qwNtpTime*(10**7)/(2**32))+NTPTIMEOFFSET
// ==>
//return (qwNtpTime*( 5**7)/(2**25))+NTPTIMEOFFSET
// ==>
//return ((qwNTPtime*FIVETOTHESEVETH)>>25)+NTPTIMEOFFSET;
// ==>
// Note: 'After' division, we round (instead of truncate) the result for better precision
unsigned __int64 qwNtpTime=EndianSwap(te);
unsigned __int64 qwTemp=((qwNtpTime&0x00000000FFFFFFFF)*FIVETOTHESEVETH)+0x0000000001000000; //rounding step: if 25th bit is set, round up;
return (qwTemp>>25) + ((qwNtpTime&0xFFFFFFFF00000000)>>25)*FIVETOTHESEVETH + NTPTIMEOFFSET;
}
static unsigned __int64 NtpTimeEpochFromNtTimeEpoch(unsigned __int64 te) {
//return (qwNtTime-NTPTIMEOFFSET)*(2**32)/(10**7);
// ==>
//return (qwNtTime-NTPTIMEOFFSET)*(2**25)/(5**7);
// ==>
//return ((qwNtTime-NTPTIMEOFFSET)<<25)/FIVETOTHESEVETH);
// ==>
// Note: The high bit is lost (and assumed to be zero) but
// it will not be set for another 29,000 years (around year 31587). No big loss.
// Note: 'After' division, we truncate the result because the precision of NTP already excessive
unsigned __int64 qwTemp=(te-NTPTIMEOFFSET)<<1;
unsigned __int64 qwHigh=qwTemp>>8;
unsigned __int64 qwLow=(qwHigh%FIVETOTHESEVETH)<<32 | (qwTemp&0x00000000000000FF)<<24;
return EndianSwap(((qwHigh/FIVETOTHESEVETH)<<32) | (qwLow/FIVETOTHESEVETH));
}
static void GetCurrTimeNtp (unsigned __int64 *ptimeXX) {
SYSTEMTIME st;
GetSystemTime (&st);
union {
FILETIME ft;
unsigned __int64 ui64ft;
};
SystemTimeToFileTime (&st, &ft);
*ptimeXX = NtpTimeEpochFromNtTimeEpoch (ui64ft);
}
static int Exec (LPTHREAD_START_ROUTINE pfunc, void *pvControlBlock = NULL) {
HANDLE h = CreateThread (NULL, 0, pfunc, pvControlBlock, 0, NULL);
if (! h)
return GetLastError ();
WaitForSingleObject (h, INFINITE);
DWORD dw = ERROR_INTERNAL_ERROR;
GetExitCodeThread (h, &dw);
CloseHandle (h);
return (int)dw;
}
#if defined (DEBUG) || defined (_DEBUG)
static void DumpPacket (NTP_REQUEST *pPacket) {
unsigned int li = pPacket->li ();
unsigned int vn = pPacket->vn ();
unsigned int mode = pPacket->mode ();
unsigned int poll = pPacket->poll ();
unsigned int stratum = pPacket->stratum ();
unsigned int precision = pPacket->precision ();
unsigned int root_delay = pPacket->root_delay ();
unsigned int root_dispersion = pPacket->root_dispersion ();
unsigned int ref_id = pPacket->ref_id ();
unsigned __int64 ref_stamp = pPacket->ref_stamp ();
unsigned __int64 orig_stamp = pPacket->orig_stamp ();
unsigned __int64 recv_stamp = pPacket->recv_stamp ();
unsigned __int64 trans_stamp = pPacket->trans_stamp ();
DEBUGMSG(ZONE_PACKETS, (L"\r\nSNTP Packet:\r\n"));
WCHAR *pText = L"";
switch (li) {
case 0:
pText = L"No warning";
break;
case 1:
pText = L"Last minute has 61 seconds";
break;
case 2:
pText = L"Last minute has 59 seconds";
break;
case 3:
pText = L"Alarm condition (clock not synchronized)";
break;
default:
pText = L"Illegal or reserved code";
break;
}
DEBUGMSG(ZONE_PACKETS, (L"Leap : %d (%s)\r\n", li, pText));
DEBUGMSG(ZONE_PACKETS, (L"Version : %d\r\n", vn));
pText = L"";
switch (mode) {
case 1:
pText = L"symmetric active";
break;
case 2:
pText = L"symmetric passive";
break;
case 3:
pText = L"client";
break;
case 4:
pText = L"server";
break;
case 5:
pText = L"broadcast";
break;
case 6:
pText = L"NTP control";
break;
case 7:
pText = L"private use";
break;
default:
pText = L"illegal or reserved code";
break;
}
DEBUGMSG(ZONE_PACKETS, (L"Mode : %d (%s)\r\n", mode, pText));
DEBUGMSG(ZONE_PACKETS, (L"Stratum : %d\r\n", stratum));
DEBUGMSG(ZONE_PACKETS, (L"Poll : %d\r\n", poll));
DEBUGMSG(ZONE_PACKETS, (L"Precision : %d\r\n", poll));
DEBUGMSG(ZONE_PACKETS, (L"Root delay: 0x%08x (%d sec)\r\n", root_delay, ((int)root_delay)/4));
DEBUGMSG(ZONE_PACKETS, (L"Root disp : 0x%08x (%d sec)\r\n", root_dispersion, ((int)root_dispersion)/4));
in_addr ia;
ia.S_un.S_addr = ref_id;
DEBUGMSG(ZONE_PACKETS, (L"Refid : %08x (or %a)\r\n", ref_id, inet_ntoa (ia)));
union {
unsigned __int64 ui64;
FILETIME ft;
};
SYSTEMTIME xst;
ui64 = NtTimeEpochFromNtpTimeEpoch (ref_stamp);
FileTimeToSystemTime ((FILETIME *)&ui64, &xst);
DEBUGMSG(ZONE_PACKETS, (L"Reference time: %02d/%02d/%d %02d:%02d:%02d.%03d\n", xst.wMonth, xst.wDay, xst.wYear, xst.wHour, xst.wMinute, xst.wSecond, xst.wMilliseconds));
ui64 = NtTimeEpochFromNtpTimeEpoch (orig_stamp);
FileTimeToSystemTime ((FILETIME *)&ui64, &xst);
DEBUGMSG(ZONE_PACKETS, (L"Origination time: %02d/%02d/%d %02d:%02d:%02d.%03d\n", xst.wMonth, xst.wDay, xst.wYear, xst.wHour, xst.wMinute, xst.wSecond, xst.wMilliseconds));
ui64 = NtTimeEpochFromNtpTimeEpoch (recv_stamp);
FileTimeToSystemTime ((FILETIME *)&ui64, &xst);
DEBUGMSG(ZONE_PACKETS, (L"Received time: %02d/%02d/%d %02d:%02d:%02d.%03d\n", xst.wMonth, xst.wDay, xst.wYear, xst.wHour, xst.wMinute, xst.wSecond, xst.wMilliseconds));
ui64 = NtTimeEpochFromNtpTimeEpoch (trans_stamp);
FileTimeToSystemTime ((FILETIME *)&ui64, &xst);
DEBUGMSG(ZONE_PACKETS, (L"Transmitted time: %02d/%02d/%d %02d:%02d:%02d.%03d\n", xst.wMonth, xst.wDay, xst.wYear, xst.wHour, xst.wMinute, xst.wSecond, xst.wMilliseconds));
DEBUGMSG(ZONE_PACKETS, (L"\r\n\r\n"));
}
#endif
///////////////////////////////////////////////////////////////////////
//
// Threads
//
//
static DWORD WINAPI MulticastThread (LPVOID lpUnused) {
DEBUGMSG(ZONE_SERVER, (L"[TIMESVC] Multicast Event\r\n"));
int fSuccess = FALSE;
if (! gpTS) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Multicast: service not initialized!\r\n"));
return 0;
}
gpTS->Lock ();
if (! gpTS->IsStarted ()) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Time Refresh: service not active!\r\n"));
gpTS->Unlock ();
return 0;
}
int fTimeAccurate = gpTS->IsTimeAccurate();
unsigned int uiPollInterval = gpTS->dwMulticastPeriodMS / 1000;
unsigned int poll = 1;
while (poll < uiPollInterval)
poll <<= 1;
poll >>= 1;
unsigned int ref = (unsigned int)gpTS->llLastSyncTimeXX & 0xffffffff;
unsigned __int64 ref_ts = gpTS->llLastSyncTimeXX;
gpTS->Unlock ();
if (! fTimeAccurate) {
DEBUGMSG(ZONE_SERVER, (L"[TIMESVC] Multicast server does not have accurate time\r\n"));
return 0;
}
NTP_REQUEST dg;
memset (&dg, 0, sizeof(dg));
dg.set_vn (4);
dg.set_mode (5);
dg.set_stratum (2);
dg.set_poll (poll);
dg.set_precision((unsigned int)-7);
dg.set_ref_id (ref);
dg.set_ref_stamp (ref_ts);
int icast = 0;
for ( ; ; ) {
if (! gpTS) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Multicast: service not initialized!\r\n"));
return 0;
}
gpTS->Lock ();
if (! gpTS->IsStarted ()) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Multicast: service not active!\r\n"));
gpTS->Unlock ();
return 0;
}
if (icast >= gpTS->cMcasts)
break;
char hostname[DNS_MAX_NAME_BUFFER_LENGTH];
strcpy (hostname, gpTS->sntp_mcasts[icast++]);
gpTS->Unlock ();
DEBUGMSG(ZONE_SERVER, (L"[TIMESVC] Multicast: multicasting to %a\r\n", hostname));
ADDRINFO aiHints;
ADDRINFO *paiLocal = NULL;
memset(&aiHints, 0, sizeof(aiHints));
aiHints.ai_family = PF_UNSPEC;
aiHints.ai_socktype = SOCK_DGRAM;
aiHints.ai_flags = 0; // Or AI_NUMERICHOST; ?
if (0 != getaddrinfo(hostname, NTP_PORT_A, &aiHints, &paiLocal)) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Multicast: host %a is not reachable\r\n", hostname));
continue;
}
for (ADDRINFO *paiTrav = paiLocal; paiTrav ; paiTrav = paiTrav->ai_next) {
SOCKET s;
if (INVALID_SOCKET == (s = socket(paiTrav->ai_family, paiTrav->ai_socktype, paiTrav->ai_protocol)))
continue;
int on = 1;
if (0 != setsockopt (s, SOL_SOCKET, SO_BROADCAST, (char *)&on, sizeof(on))) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Multicast: could not set broadcast option, error %d\n", GetLastError ()));
}
unsigned __int64 llTXX;
GetCurrTimeNtp (&llTXX);
dg.set_trans_stamp (llTXX);
int iRet = sendto (s, (char *)&dg, sizeof(dg), 0, paiTrav->ai_addr, paiTrav->ai_addrlen);
closesocket (s);
if (sizeof(dg) == iRet)
break;
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Multicast failed: error %d; retrying different address family\n", GetLastError ()));
}
if (paiLocal)
freeaddrinfo(paiLocal);
}
if (gpTS->dwMulticastPeriodMS > 1000)
gpTS->ckNextMulticast = gpTS->pEvents->ScheduleEvent (MulticastThread, NULL, gpTS->dwMulticastPeriodMS);
gpTS->Unlock ();
DEBUGMSG(ZONE_SERVER, (L"[TIMESVC] Multicast event processing completed\r\n"));
return 0;
}
static int GetOffsetFromServer (char *hostname, __int64 *pllOffset) {
ADDRINFO aiHints;
ADDRINFO *paiLocal = NULL;
memset(&aiHints, 0, sizeof(aiHints));
aiHints.ai_family = PF_UNSPEC;
aiHints.ai_socktype = SOCK_DGRAM;
aiHints.ai_flags = 0; // Or AI_NUMERICHOST; ?
if (0 != getaddrinfo(hostname, NTP_PORT_A, &aiHints, &paiLocal)) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Time Refresh: host %a is not reachable\r\n", hostname));
return FALSE;
}
for (ADDRINFO *paiTrav = paiLocal; paiTrav ; paiTrav = paiTrav->ai_next) {
SOCKET s;
if (INVALID_SOCKET == (s = socket(paiTrav->ai_family, paiTrav->ai_socktype, paiTrav->ai_protocol)))
continue;
for (int i = 0 ; i < 3 ; ++i) {
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Time Refresh: querying server %a\r\n", hostname));
NTP_REQUEST dg;
memset (&dg, 0, sizeof(dg));
dg.set_vn (4);
dg.set_mode (3);
unsigned __int64 llT1XX;
GetCurrTimeNtp (&llT1XX);
dg.set_trans_stamp (llT1XX);
#if defined (DEBUG) || defined (_DEBUG)
DEBUGMSG (ZONE_PACKETS, (L"[TIMESVC] Sending SNTP request\r\n"));
DumpPacket (&dg);
#endif
if (sizeof (dg) == sendto (s, (char *)&dg, sizeof(dg), 0, paiTrav->ai_addr, paiTrav->ai_addrlen)) {
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Time Refresh: sent request, awaiting response\r\n"));
fd_set f;
FD_ZERO (&f);
FD_SET (s, &f);
timeval tv;
tv.tv_sec = 3;
tv.tv_usec = 0;
if (select (0, &f, NULL, NULL, &tv) > 0) {
SOCKADDR_STORAGE sa;
int salen = sizeof(sa);
if (sizeof(dg) == recvfrom (s, (char *)&dg, sizeof(dg), 0, (sockaddr *)&sa, &salen)) {
unsigned __int64 llT4XX;
GetCurrTimeNtp (&llT4XX);
#if defined (DEBUG) || defined (_DEBUG)
DEBUGMSG (ZONE_PACKETS, (L"[TIMESVC] Received SNTP response\r\n"));
DumpPacket (&dg);
#endif
int fSuccess = FALSE;
if ((dg.li () != 3) && (llT1XX == dg.orig_stamp ())) {
unsigned __int64 llT2XX = dg.recv_stamp ();
unsigned __int64 llT3XX = dg.trans_stamp ();
unsigned __int64 llT1 = NtTimeEpochFromNtpTimeEpoch (llT1XX);
unsigned __int64 llT2 = NtTimeEpochFromNtpTimeEpoch (llT2XX);
unsigned __int64 llT3 = NtTimeEpochFromNtpTimeEpoch (llT3XX);
unsigned __int64 llT4 = NtTimeEpochFromNtpTimeEpoch (llT4XX);
*pllOffset = ((__int64)((llT2 - llT1) + (llT3 - llT4))) / 2;
fSuccess = TRUE;
} else {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Time Refresh: sntp server not synchronized\r\n"));
}
closesocket (s);
if (paiLocal)
freeaddrinfo(paiLocal);
return fSuccess;
} else {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Time Refresh: sntp server datagram size incorrect (or authentication requested)\r\n"));
}
} else {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Time Refresh: sntp server response timeout (no SNTP on server?)\r\n"));
}
} else {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Time Refresh: host %a unreachable\r\n", hostname));
}
closesocket (s);
}
}
if (paiLocal)
freeaddrinfo(paiLocal);
return FALSE;
}
static int RefreshTimeFromServer (char *hostname, int fForceTime, DWORD dwMaxAdjustS, int *pfTimeChanged) {
*pfTimeChanged = FALSE;
__int64 llOffset;
if (GetOffsetFromServer (hostname, &llOffset)) {
int iOffsetSec = (int)(llOffset / 10000000);
if (fForceTime || ((DWORD)abs (iOffsetSec) < dwMaxAdjustS)) {
SYSTEMTIME st, st2;
unsigned __int64 llTime;
GetSystemTime (&st);
SystemTimeToFileTime (&st, (FILETIME *)&llTime);
llTime += llOffset;
FileTimeToSystemTime ((FILETIME *)&llTime, &st2);
// The system must be updated with whether we're DST or STD
// before we update the system clock. We're updating in UTC
// but system clock will convert and save this as local time,
// which means it will apply the DST/STD bias first.
SetDaylightOrStandardTimeDST(&st2);
SetSystemTime (&st2);
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Time Refresh: time accepted. offset = %d s.\r\n", iOffsetSec));
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Time Refresh: old time: %02d/%02d/%d %02d:%02d:%02d.%03d\r\n", st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds));
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Time Refresh: new time: %02d/%02d/%d %02d:%02d:%02d.%03d\r\n", st2.wMonth, st2.wDay, st2.wYear, st2.wHour, st2.wMinute, st2.wSecond, st2.wMilliseconds));
if ((DWORD)abs (iOffsetSec) > MIN_TIMEUPDATE)
*pfTimeChanged = TRUE;
return TRUE;
} else {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Time Refresh: time indicated by server is not within allowed adjustment boundaries (offset = %d s)\r\n", iOffsetSec));
}
}
return FALSE;
}
static DWORD WINAPI TimeRefreshThread (LPVOID lpUnused) {
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Refresh Event\r\n"));
int fSuccess = FALSE;
int fTimeChanged = FALSE;
int iSrv = 0;
while (! fSuccess) {
if (! gpTS) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Time Refresh: service not initialized!\r\n"));
return 0;
}
gpTS->Lock ();
if (! gpTS->IsStarted ()) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Time Refresh: service not active!\r\n"));
gpTS->Unlock ();
return 0;
}
if (iSrv >= gpTS->cServers) {
DEBUGMSG(ZONE_WARNING, (L"[TIMESVC] Time Refresh: all servers queried, but time not updated.\r\n"));
gpTS->Unlock ();
break;
}
int fForceTime = gpTS->fForceTimeToServer;
DWORD dwMaxAdjustS = gpTS->dwAdjustThreshMS / 1000;
char hostname[DNS_MAX_NAME_BUFFER_LENGTH];
memcpy (hostname, gpTS->sntp_servers[iSrv++], sizeof(hostname));
gpTS->Unlock ();
fSuccess = RefreshTimeFromServer (hostname, fForceTime, dwMaxAdjustS, &fTimeChanged);
}
if (gpTS) {
gpTS->Lock ();
if (gpTS->IsStarted ()) {
if (fSuccess) {
GetCurrTimeNtp (&gpTS->llLastSyncTimeXX);
gpTS->fRefreshRequired = FALSE;
gpTS->UpdateNowOrLater (Later);
gpTS->fForceTimeToServer = FALSE;
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Time successfully refreshed\r\n"));
if (fTimeChanged || (gpTS->ckNextMulticast == 0))
gpTS->TimeChanged ();
} else {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Time Refresh failed, rescheduling\r\n"));
gpTS->fRefreshRequired = TRUE;
gpTS->UpdateNowOrLater (Shortly);
if(gpTS->ckNextMulticast == 0)
gpTS->TimeChanged();
}
}
gpTS->Unlock ();
}
DEBUGMSG(ZONE_CLIENT, (L"[TIMESVC] Time Refresh event processing completed\r\n"));
return 0;
}
static DWORD WINAPI RxThread (LPVOID lpUnused) {
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Server thread started\r\n"));
for ( ; ; ) {
if (! gpTS) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Server: Not initialized, quitting\r\n"));
return 0;
}
gpTS->Lock ();
if (! gpTS->IsStarted ()) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Server: Not active, quitting\r\n"));
gpTS->Unlock ();
return 0;
}
fd_set sockSet;
FD_ZERO(&sockSet);
for (int i = 0; i < gpTS->iSock; ++i)
FD_SET(gpTS->saServer[i], &sockSet);
gpTS->Unlock ();
int iSockReady = select (0,&sockSet,NULL,NULL,NULL);
if (iSockReady == 0 || iSockReady == SOCKET_ERROR) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Server: select failed, error=%d\r\n", GetLastError ()));
break;
}
for (i = 0; i < iSockReady; ++i) {
NTP_REQUEST dg;
SOCKADDR_STORAGE sa;
int salen = sizeof(sa);
int iRecv = recvfrom (sockSet.fd_array[i], (char *)&dg, sizeof(dg), 0, (sockaddr *)&sa, &salen);
if (iRecv <= 0) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] Server: receive failed, error=%d\r\n", GetLastError ()));
break;
}
if (iRecv != sizeof(dg)) {
DEBUGMSG(ZONE_SERVER, (L"[TIMESVC] Server: size mismatch, packet ignored\r\n"));
continue;
}
#if defined (DEBUG) || defined (_DEBUG)
DEBUGMSG(ZONE_PACKETS, (L"[TIMESVC] Received SNTP request\r\n"));
DumpPacket (&dg);
#endif
if (dg.mode () == 3) { //client
dg.set_mode (4); //server
} else if (dg.mode () == 1) { // symmetric, active
dg.set_mode(1); // symmetric, passive
} else {
DEBUGMSG(ZONE_SERVER, (L"[TIMESVC] Server: Not a request, aborting\r\n"));
continue;
}
dg.set_root_delay (0);
dg.set_root_dispersion (0);
dg.set_precision((unsigned int)-7);
unsigned __int64 llOrigTimeXX = dg.trans_stamp ();
dg.set_orig_stamp (llOrigTimeXX);
unsigned __int64 llRecvTimeXX;
GetCurrTimeNtp (&llRecvTimeXX);
dg.set_recv_stamp (llRecvTimeXX);
dg.set_trans_stamp (llRecvTimeXX);
if (! gpTS)
break;
gpTS->Lock ();
dg.set_ref_stamp (gpTS->llLastSyncTimeXX);
dg.set_ref_id ((unsigned int)gpTS->llLastSyncTimeXX);
if (gpTS->IsTimeAccurate()) {
dg.set_li (0);
dg.set_stratum (2);
} else {
dg.set_li (3);
dg.set_stratum (15);
}
gpTS->Unlock ();
sendto (sockSet.fd_array[i], (char *)&dg, sizeof(dg), 0, (sockaddr *)&sa, salen);
#if defined (DEBUG) || defined (_DEBUG)
DEBUGMSG(ZONE_PACKETS, (L"[TIMESVC] Sent SNTP response\r\n"));
DumpPacket (&dg);
#endif
}
}
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Server Thread exited\r\n"));
return 0;
}
///////////////////////////////////////////////////////////////////////
//
// Interface, initialization, management
//
//
static DWORD WINAPI SyncTime (LPVOID dwUnused) {
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Time update request from OS\r\n"));
int iErr = ERROR_SERVICE_DOES_NOT_EXIST;
if (gpTS) {
gpTS->Lock ();
iErr = ERROR_SUCCESS;
if (! gpTS->IsStarted())
iErr = ERROR_SERVICE_NOT_ACTIVE;
if (iErr == ERROR_SUCCESS)
iErr = gpTS->UpdateNowOrLater (Now);
gpTS->Unlock ();
}
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Time update request : %d\r\n", iErr));
return iErr;
}
static DWORD WINAPI ForceSyncTime (LPVOID dwUnused) {
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Forced time update request from OS\r\n"));
int iErr = ERROR_SERVICE_DOES_NOT_EXIST;
if (gpTS) {
gpTS->Lock ();
iErr = ERROR_SUCCESS;
if (! gpTS->IsStarted())
iErr = ERROR_SERVICE_NOT_ACTIVE;
if (iErr == ERROR_SUCCESS) {
iErr = gpTS->ForcedUpdate ();
}
gpTS->Unlock ();
}
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Forced time update request : %d\r\n", iErr));
return iErr;
}
static DWORD WINAPI GetTimeOffsetOnServer (LPVOID lpArg) {
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Time offset request from OS\r\n"));
GetTimeOffset *pArg = (GetTimeOffset *)lpArg;
int fTimeChanged = FALSE;
int iSrv = 0;
for ( ; ; ) {
if (! gpTS) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] GetServerOffset: service not initialized!\r\n"));
return ERROR_SERVICE_DOES_NOT_EXIST;
}
char hostname[DNS_MAX_NAME_BUFFER_LENGTH];
if (pArg->cchServer[0] == '\0') {
int iErr = ERROR_SUCCESS;
gpTS->Lock ();
if (gpTS->IsStarted ()) {
if (iSrv < gpTS->cServers) {
memcpy (hostname, gpTS->sntp_servers[iSrv++], sizeof(hostname));
} else {
DEBUGMSG(ZONE_WARNING, (L"[TIMESVC] GetServerOffset: all servers queried, but no connection.\r\n"));
iErr = ERROR_HOST_UNREACHABLE;
}
} else {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] GetServerOffset: service not active!\r\n"));
iErr = ERROR_SERVICE_NOT_ACTIVE;
}
gpTS->Unlock ();
if (iErr != ERROR_SUCCESS)
return iErr;
} else
memcpy (hostname, pArg->cchServer, sizeof(hostname));
if (GetOffsetFromServer (hostname, &pArg->llOffset))
return ERROR_SUCCESS;
if (pArg->cchServer[0] != '\0')
break;
}
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] GetServerOffset : could not connect (ERROR_HOST_UNREACHABLE)\r\n"));
return ERROR_HOST_UNREACHABLE;
}
static DWORD WINAPI SetTime (LPVOID dwUnused) {
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Force time update request from OS\r\n"));
int iErr = ERROR_SERVICE_DOES_NOT_EXIST;
if (gpTS) {
gpTS->Lock ();
iErr = ERROR_SUCCESS;
if (! gpTS->IsStarted())
iErr = ERROR_SERVICE_NOT_ACTIVE;
if (iErr == ERROR_SUCCESS)
iErr = gpTS->UpdateNowOrLater (Now, TRUE);
gpTS->Unlock ();
}
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Force time update request : %d\r\n", iErr));
return iErr;
}
static DWORD WINAPI NetworkChange (LPVOID dwUnused) {
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Network up/down event from OS\r\n"));
int iErr = ERROR_SERVICE_DOES_NOT_EXIST;
if (gpTS) {
gpTS->Lock ();
iErr = ERROR_SUCCESS;
if (! gpTS->IsStarted())
iErr = ERROR_SERVICE_NOT_ACTIVE;
if ((iErr == ERROR_SUCCESS) && (gpTS->LastUpdateFailed ()))
iErr = gpTS->UpdateNowOrLater (Now);
gpTS->Unlock ();
}
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Time update request : %d\r\n", iErr));
return iErr;
}
static DWORD WINAPI StartServer (LPVOID lpUnused) {
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Start Server request from OS\r\n"));
int iErr = ERROR_SERVICE_DOES_NOT_EXIST;
if (gpTS) {
gpTS->Lock ();
iErr = ERROR_SUCCESS;
if (gpTS->IsStarted())
iErr = ERROR_ALREADY_INITIALIZED;
WSADATA wsd;
WSAStartup (MAKEWORD(1,1), &wsd);
if (iErr == ERROR_SUCCESS)
iErr = gpTS->RefreshConfig ();
if (iErr == ERROR_SUCCESS)
iErr = gpTS->Start ();
gpTS->Unlock ();
}
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Start Server request : %d\r\n", iErr));
return iErr;
}
static DWORD WINAPI StopServer (LPVOID lpUnused) {
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Stop Server request from OS\r\n"));
int iErr = ERROR_SERVICE_DOES_NOT_EXIST;
if (gpTS) {
gpTS->Lock ();
iErr = ERROR_SUCCESS;
if (! gpTS->IsStarted())
iErr = ERROR_SERVICE_NOT_ACTIVE;
SVSThreadPool *pp = (iErr == ERROR_SUCCESS) ? gpTS->Stop () : NULL;
gpTS->Unlock ();
if (pp) {
delete pp;
WSACleanup ();
}
}
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] Stop Server request : %d\r\n", iErr));
return iErr;
}
static DWORD WINAPI ExternalTimeUpdate (LPVOID lpUnused) {
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] External time update indicator from OS\r\n"));
int iErr = ERROR_SERVICE_DOES_NOT_EXIST;
if (gpTS) {
gpTS->Lock ();
iErr = ERROR_SUCCESS;
if (! gpTS->IsStarted()) {
iErr = ERROR_SERVICE_NOT_ACTIVE;
} else {
iErr = gpTS->TimeChanged ();
}
gpTS->Unlock ();
}
DEBUGMSG(ZONE_TRACE, (L"[TIMESVC] External time update indicator : %d\r\n", iErr));
return iErr;
}
///////////////////////////////////////////////////////////////////////
//
// OS interface
//
//
static DWORD WINAPI NotifyThread (LPVOID lpUnused) {
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] NotifyThread started\r\n"));
HMODULE hCoreDll = LoadLibrary (L"coredll.dll");
tCeRunAppAtEvent pCeRunAppAtEvent = (tCeRunAppAtEvent)GetProcAddress (hCoreDll, L"CeRunAppAtEvent");
HANDLE hWakeup = CreateEvent (NULL, FALSE, FALSE, L"timesvc\\wakeup");
HANDLE hTimeSet = CreateEvent (NULL, FALSE, FALSE, L"timesvc\\timeset");
HANDLE hNotifyInitialized = OpenEvent (EVENT_ALL_ACCESS, FALSE, NOTIFICATION_EVENTNAME_API_SET_READY);
if (! (pCeRunAppAtEvent && hWakeup && hTimeSet && hNotifyInitialized)) {
DEBUGMSG(ZONE_ERROR, (L"[TIMESVC] NotifyThread: could not initialize, aborting\r\n"));
FreeLibrary (hCoreDll);
if (hWakeup)
CloseHandle (hWakeup);
if (hTimeSet)
CloseHandle (hTimeSet);
if (hNotifyInitialized)
CloseHandle (hNotifyInitialized);
return 0;
}
// Clean up...
int fNotificationsPresent = (WAIT_OBJECT_0 == WaitForSingleObject (hNotifyInitialized, NOTIFICATION_WAIT_SEC*1000));
CloseHandle (hNotifyInitialized);
if (! fNotificationsPresent) {
CloseHandle (hWakeup);
CloseHandle (hTimeSet);
return 0;
}
pCeRunAppAtEvent (NAMED_EVENT_PREFIX_TEXT L"timesvc\\wakeup", 0);
pCeRunAppAtEvent (NAMED_EVENT_PREFIX_TEXT L"timesvc\\timeset", 0);
pCeRunAppAtEvent (NAMED_EVENT_PREFIX_TEXT L"timesvc\\wakeup", NOTIFICATION_EVENT_WAKEUP);
pCeRunAppAtEvent (NAMED_EVENT_PREFIX_TEXT L"timesvc\\timeset", NOTIFICATION_EVENT_TIME_CHANGE);
HMODULE hiphlp = LoadLibrary (L"iphlpapi.dll");
tNotifyAddrChange pNotifyAddrChange = hiphlp ? (tNotifyAddrChange)GetProcAddress (hiphlp, L"NotifyAddrChange") : NULL;
HANDLE hNetwork = NULL;
if (pNotifyAddrChange)
pNotifyAddrChange(&hNetwork, NULL);
for ( ; ; ) {
HANDLE ah[4];
ah[0] = hExitEvent;
ah[1] = hWakeup;
ah[2] = hTimeSet;
ah[3] = hNetwork;
DWORD cEvents = hNetwork ? 4 : 3;
DWORD dwRes = WaitForMultipleObjects (cEvents, ah, FALSE, INFINITE);
if (dwRes == (WAIT_OBJECT_0+1)) // Wakeup
Exec (SyncTime);
else if (dwRes == (WAIT_OBJECT_0+2)) // Time reset
Exec (ExternalTimeUpdate);
else if (dwRes == (WAIT_OBJECT_0+3)) // Network address changed
Exec (NetworkChange);
else
break;
}
pCeRunAppAtEvent (NAMED_EVENT_PREFIX_TEXT L"timesvc\\wakeup", 0);
pCeRunAppAtEvent (NAMED_EVENT_PREFIX_TEXT L"timesvc\\timeset", 0);
CloseHandle (hWakeup);
CloseHandle (hTimeSet);
if (hiphlp)
FreeLibrary (hiphlp);
FreeLibrary (hCoreDll);
DEBUGMSG(ZONE_INIT, (L"Notify Thread exited\r\n"));
return 0;
}
static int StartOsNotifications (void) {
if (hExitEvent)
return FALSE;
hExitEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
hNotifyThread = NULL;
if (hExitEvent) {
hNotifyThread = CreateThread (NULL, 0, NotifyThread, NULL, 0, NULL);
if (! hNotifyThread) {
CloseHandle (hExitEvent);
hExitEvent = NULL;
}
}
return hNotifyThread != NULL;
}
static int StopOsNotifications (void) {
if (hNotifyThread) {
SetEvent (hExitEvent);
CloseHandle (hExitEvent);
hExitEvent = NULL;
WaitForSingleObject (hNotifyThread, INFINITE);
CloseHandle (hNotifyThread);
hNotifyThread = NULL;
}
return TRUE;
}
//
// Public interface
//
int InitializeSNTP (HINSTANCE hMod) {
svsutil_Initialize ();
DEBUGREGISTER(hMod);
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Module loaded\r\n"));
gpTS = new TimeState;
return (gpTS != NULL) ? ERROR_SUCCESS : ERROR_OUTOFMEMORY;
}
void DestroySNTP (void) {
delete gpTS;
gpTS = NULL;
DEBUGMSG(ZONE_INIT, (L"[TIMESVC] Module unloaded\r\n"));
svsutil_DeInitialize ();
}
int StartSNTP (void) {
int iErr = Exec (StartServer);
if (iErr == ERROR_SUCCESS)
StartOsNotifications ();
return iErr;
}
int StopSNTP (void) {
int iErr = Exec (StopServer);
if (iErr == ERROR_SUCCESS)
StopOsNotifications ();
return iErr;
}
int RefreshSNTP (void) {
int iErr = Exec (StopServer);
if (iErr == ERROR_SUCCESS)
iErr = Exec (StartServer);
return iErr;
}
DWORD GetStateSNTP (void) {
DWORD dwState = SERVICE_STATE_UNINITIALIZED;
if (gpTS) {
gpTS->Lock ();
dwState = gpTS->IsStarted () ? SERVICE_STATE_ON : SERVICE_STATE_OFF;
gpTS->Unlock ();
}
return dwState;
}
int ServiceControlSNTP (PBYTE pBufIn, DWORD dwLenIn, PBYTE pBufOut, DWORD dwLenOut, PDWORD pdwActualOut, int *pfProcessed) {
int iErr = ERROR_INVALID_PARAMETER;
*pfProcessed = FALSE;
if ((dwLenIn == sizeof(L"sync")) && (wcsicmp ((WCHAR *)pBufIn, L"sync") == 0)) {
*pfProcessed = TRUE;
return Exec (ForceSyncTime);
} else if ((dwLenIn == sizeof(L"set")) && (wcsicmp ((WCHAR *)pBufIn, L"set") == 0)) {
*pfProcessed = TRUE;
return Exec (SetTime);
} else if ((dwLenIn == sizeof(L"update")) && (wcsicmp ((WCHAR *)pBufIn, L"update") == 0)) {
*pfProcessed = TRUE;
return Exec (ExternalTimeUpdate);
} else if ((dwLenIn >= sizeof(L"gettimeoffset")) && (wcsnicmp ((WCHAR *)pBufIn, L"gettimeoffset", (sizeof(L"gettimeoffset") - sizeof(L""))/ sizeof(WCHAR)) == 0)) {
*pfProcessed = TRUE;
// Check for '\0' sentinel
if (((WCHAR *)pBufIn)[(dwLenIn-1)/sizeof(WCHAR)] != '\0')
return ERROR_INVALID_PARAMETER;
if ((dwLenOut != sizeof (__int64)) || (! pdwActualOut))
return ERROR_INVALID_PARAMETER;
GetTimeOffset *pArg = (GetTimeOffset *)LocalAlloc (LMEM_FIXED, sizeof(GetTimeOffset));
if (! pArg)
return GetLastError ();
pArg->llOffset = 0;
pArg->cchServer[0] = '\0';
dwLenIn -= (sizeof(L"gettimeoffset") - sizeof(L""));
pBufIn += (sizeof(L"gettimeoffset") - sizeof(L""));
if (dwLenIn > sizeof(WCHAR)) {
if (*(WCHAR *)pBufIn != ' ') {
LocalFree (pArg);
return ERROR_INVALID_PARAMETER;
}
dwLenIn += sizeof(WCHAR);
pBufIn += sizeof(WCHAR);
if ((dwLenIn < 2*sizeof(WCHAR)) || (*(WCHAR *)pBufIn == '\0')) {
LocalFree (pArg);
return ERROR_INVALID_PARAMETER;
}
if (0 == WideCharToMultiByte (CP_ACP, 0, (WCHAR *)pBufIn, -1, (LPSTR)pArg->cchServer, sizeof(pArg->cchServer), NULL, NULL)) {
LocalFree (pArg);
return GetLastError ();
}
} else {
SVSUTIL_ASSERT (*(WCHAR *)pBufIn == '\0');
}
iErr = Exec (GetTimeOffsetOnServer, pArg);
if (iErr == ERROR_SUCCESS) {
memcpy (pBufOut, &pArg->llOffset, sizeof(pArg->llOffset));
*pdwActualOut = sizeof(pArg->llOffset);
}
LocalFree (pArg);
}
return iErr;
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
3db971ebdabb79e36bcbfaa6df141c311a86fa9d | 387ad3775fad21d2d8ffa3c84683d9205b6e697d | /openhpi/branches/release_2_1_0/plugins/ipmidirect/thread.cpp | 580b1fd35f5b63286336883e56f0fee0559d67b6 | [] | no_license | kodiyalashetty/test_iot | 916088ceecffc17d2b6a78d49f7ea0bbd0a6d0b7 | 0ae3c2ea6081778e1005c40a9a3f6d4404a08797 | refs/heads/master | 2020-03-22T11:53:21.204497 | 2018-03-09T01:43:41 | 2018-03-09T01:43:41 | 140,002,491 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,153 | cpp | /*
* thread.cpp
*
* thread classes
*
* Copyright (c) 2004 by FORCE Computers.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. This
* file and program are licensed under a BSD style license. See
* the Copying file included with the OpenHPI distribution for
* full licensing terms.
*
* Authors:
* Thomas Kanngieser <thomas.kanngieser@fci.com>
*/
#include "thread.h"
#include <stdio.h>
#include <assert.h>
#include <sys/time.h>
#include <errno.h>
static void
GetTimeout( struct timespec &t, unsigned int timeout )
{
timeval tv;
int rv = gettimeofday( &tv, 0 );
assert( rv == 0 );
tv.tv_usec += timeout * 1000;
while( tv.tv_usec > 1000000 )
{
tv.tv_sec++;
tv.tv_usec -= 1000000;
}
t.tv_sec = tv.tv_sec;
t.tv_nsec = tv.tv_usec * 1000;
}
//////////////////////////////////////////////////
// cThread
//////////////////////////////////////////////////
static pthread_key_t thread_key;
class cThreadMain : public cThread
{
public:
cThreadMain( const pthread_t &thread, bool main_thread, tTheadState state )
: cThread( thread, main_thread, state ) {}
protected:
virtual void *Run() { return 0; }
};
class cInit
{
public:
cInit();
~cInit();
};
cInit::cInit()
{
pthread_key_create( &thread_key, 0 );
cThreadMain *thread = new cThreadMain( pthread_self(), true, eTsRun );
pthread_setspecific( thread_key, thread );
}
cInit::~cInit()
{
cThreadMain *thread = (cThreadMain *)pthread_getspecific( thread_key );
assert( thread );
delete thread;
pthread_key_delete( thread_key );
}
static cInit init;
cThread::cThread()
: m_main( false ), m_state( eTsSuspend )
{
}
cThread::cThread( const pthread_t &thread, bool main_thread, tTheadState state )
: m_thread( thread ), m_main( main_thread ), m_state( state )
{
}
cThread::~cThread()
{
}
cThread *
cThread::GetThread()
{
cThread *thread = (cThread *)pthread_getspecific( thread_key );
assert( thread );
return thread;
}
void *
cThread::Thread( void *param )
{
cThread *thread = (cThread *)param;
pthread_setspecific( thread_key, thread );
thread->m_state = eTsRun;
void *rv = thread->Run();
thread->m_state = eTsExit;
return rv;
}
bool
cThread::Start()
{
if ( m_state == eTsRun )
{
assert( 0 );
return false;
}
m_state = eTsSuspend;
int rv = pthread_create( &m_thread, 0, Thread, this );
if ( rv )
return false;
// wait till the thread is runnung
while( m_state == eTsSuspend )
// wait 100 ms
usleep( 10000 );
return true;
}
bool
cThread::Wait( void *&rv )
{
if ( m_state != eTsRun )
return false;
void *rr;
int r = pthread_join( m_thread, &rr );
if ( r )
return false;
rv = rr;
return true;
}
void
cThread::Exit( void *rv )
{
m_state = eTsExit;
pthread_exit( rv );
}
//////////////////////////////////////////////////
// cThreadLock
//////////////////////////////////////////////////
static pthread_mutex_t lock_tmpl = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
cThreadLock::cThreadLock()
: m_lock( lock_tmpl )
{
}
cThreadLock::~cThreadLock()
{
int rv = pthread_mutex_destroy( &m_lock );
assert( rv == 0 );
}
void
cThreadLock::Lock()
{
pthread_mutex_lock( &m_lock );
}
void
cThreadLock::Unlock()
{
pthread_mutex_unlock( &m_lock );
}
bool
cThreadLock::TryLock()
{
return pthread_mutex_trylock( &m_lock ) == 0;
}
bool
cThreadLock::TimedLock( unsigned int timeout )
{
struct timespec t;
GetTimeout( t, timeout );
int rv = pthread_mutex_timedlock( &m_lock, &t );
if ( rv )
{
assert( rv == ETIMEDOUT );
return false;
}
return true;
}
//////////////////////////////////////////////////
// cThreadLockRw
//////////////////////////////////////////////////
static pthread_rwlock_t rwlock_tmpl = PTHREAD_RWLOCK_INITIALIZER;
cThreadLockRw::cThreadLockRw()
{
m_rwlock = rwlock_tmpl;
}
cThreadLockRw::~cThreadLockRw()
{
int rv = pthread_rwlock_destroy( &m_rwlock );
assert( rv == 0 );
}
void
cThreadLockRw::ReadLock()
{
pthread_rwlock_rdlock( &m_rwlock );
}
void
cThreadLockRw::ReadUnlock()
{
pthread_rwlock_unlock( &m_rwlock );
}
bool
cThreadLockRw::TryReadLock()
{
int rv = pthread_rwlock_trywrlock( &m_rwlock );
return rv == 0;
}
bool
cThreadLockRw::TimedReadLock( unsigned int timeout )
{
struct timespec t;
GetTimeout( t, timeout );
int rv = pthread_rwlock_timedrdlock( &m_rwlock, &t );
if ( rv )
{
assert( rv == ETIMEDOUT );
return false;
}
return true;
}
void
cThreadLockRw::WriteLock()
{
pthread_rwlock_wrlock( &m_rwlock );
}
void
cThreadLockRw::WriteUnlock()
{
pthread_rwlock_unlock( &m_rwlock );
}
bool
cThreadLockRw::TryWriteLock()
{
int rv = pthread_rwlock_trywrlock( &m_rwlock );
return rv == 0;
}
bool
cThreadLockRw::TimedWriteLock( unsigned int timeout )
{
struct timespec t;
GetTimeout( t, timeout );
int rv = pthread_rwlock_timedwrlock( &m_rwlock, &t );
if ( rv )
{
assert( rv == ETIMEDOUT );
return false;
}
return true;
}
bool
cThreadLockRw::CheckLock()
{
bool rv = TryWriteLock();
if ( rv )
WriteUnlock();
return rv;
}
//////////////////////////////////////////////////
// cThreadCond
//////////////////////////////////////////////////
static pthread_cond_t cond_tmpl = PTHREAD_COND_INITIALIZER;
cThreadCond::cThreadCond()
{
m_cond = cond_tmpl;
}
cThreadCond::~cThreadCond()
{
int rv = pthread_cond_destroy( &m_cond );
assert( rv == 0 );
}
void
cThreadCond::Signal()
{
pthread_cond_signal( &m_cond );
}
void
cThreadCond::Wait()
{
pthread_cond_wait( &m_cond, &m_lock );
}
bool
cThreadCond::TimedWait( unsigned int timeout )
{
struct timespec t;
GetTimeout( t, timeout );
int rv = pthread_cond_timedwait( &m_cond, &m_lock, &t );
if ( rv )
{
assert( rv == ETIMEDOUT );
return false;
}
return true;
}
| [
"nobody@a44bbd40-eb13-0410-a9b2-f80f2f72fa26"
] | nobody@a44bbd40-eb13-0410-a9b2-f80f2f72fa26 |
2ec7bbbb961a174f06b371b2f76896bb1d9220e2 | ce224da6da1c2ab23dccf54788d7fa4e8d1e7f4c | /apps/hmtMapViewer/hmtMapViewerMain.h | 19f4202c3822a8b4a93bd0db74efb97a4c8dbef9 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | astoeckel/mrpt | 40d158fc9c857fcf1c7da952990b76cd332791e2 | a587d5bcec68bdc8ce84d1030cd255667a5fbfa8 | refs/heads/master | 2021-01-18T05:59:35.665087 | 2016-01-21T13:33:50 | 2016-01-21T13:33:50 | 50,109,461 | 1 | 0 | null | 2016-01-21T13:30:50 | 2016-01-21T13:30:50 | null | UTF-8 | C++ | false | false | 5,322 | h | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2015, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#ifndef HMTMAPVIEWERMAIN_H
#define HMTMAPVIEWERMAIN_H
//(*Headers(hmtMapViewerFrame)
#include <wx/toolbar.h>
#include <wx/sizer.h>
#include <wx/menu.h>
#include <wx/panel.h>
#include <wx/splitter.h>
#include <wx/statusbr.h>
#include <wx/frame.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/choice.h>
#include <wx/treectrl.h>
//*)
#include <wx/timer.h>
/* Jerome Monceaux : 2011/03/08
* Include <string> needed under snow leopard
*/
#include <string>
class CMyGLCanvas;
class hmtMapViewerFrame: public wxFrame
{
public:
hmtMapViewerFrame(wxWindow* parent,wxWindowID id = -1);
virtual ~hmtMapViewerFrame();
bool AskForOpenHMTMap( std::string &fil );
// Returns true if OK.
bool loadHTMSLAMFromFile( const std::string &filePath );
// Rebuilds the tree view on the left panel.
void rebuildTreeView();
void updateGlobalMapView();
void updateLocalMapView();
std::string m_curFileOpen; //!< File loaded now.
private:
//(*Handlers(hmtMapViewerFrame)
void OnQuit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
void OnMenuLoad(wxCommandEvent& event);
void OnMenuOverlapBtw2(wxCommandEvent& event);
void OnMenuTranslationBtw2(wxCommandEvent& event);
void OntreeViewSelectionChanged(wxTreeEvent& event);
void OnmenuExportLocalMapsSelected(wxCommandEvent& event);
void OnTopologicalModel_Gridmap(wxCommandEvent& event);
void OnTopologicalModel_Fabmap(wxCommandEvent& event);
//*)
//(*Identifiers(hmtMapViewerFrame)
static const long ID_STATICTEXT1;
static const long ID_STATICTEXT2;
static const long ID_CHOICE1;
static const long ID_PANEL5;
static const long ID_TREECTRL1;
static const long ID_PANEL9;
static const long ID_TEXTCTRL1;
static const long ID_PANEL8;
static const long ID_SPLITTERWINDOW3;
static const long ID_PANEL1;
static const long ID_STATICTEXT3;
static const long ID_PANEL6;
static const long ID_PANEL3;
static const long ID_STATICTEXT4;
static const long ID_PANEL7;
static const long ID_PANEL4;
static const long ID_SPLITTERWINDOW2;
static const long ID_PANEL2;
static const long ID_SPLITTERWINDOW1;
static const long ID_MENUITEM1;
static const long ID_MENUITEM4;
static const long idMenuQuit;
static const long ID_MENUITEM2;
static const long ID_MENUITEM3;
static const long ID_MENUITEM6;
static const long ID_MENUITEM7;
static const long ID_MENUITEM5;
static const long idMenuAbout;
static const long ID_STATUSBAR1;
static const long ID_TOOLBARITEM1;
static const long ID_TOOLBARITEM2;
static const long ID_TOOLBAR1;
//*)
static const long ID_TIMER1;
//(*Declarations(hmtMapViewerFrame)
wxPanel* Panel6;
wxPanel* Panel1;
wxPanel* Panel7;
wxStatusBar* StatusBar1;
wxMenuItem* menuExportLocalMaps;
wxChoice* cbHypos;
wxMenu* Menu3;
wxPanel* Panel8;
wxPanel* Panel9;
wxStaticText* StaticText1;
wxPanel* Panel2;
wxToolBarToolBase* ToolBarItem2;
wxSplitterWindow* SplitterWindow1;
wxStaticText* StaticText3;
wxMenu* MenuItem6;
wxPanel* Panel4;
wxSplitterWindow* SplitterWindow2;
wxMenuItem* MenuItem3;
wxPanel* Panel5;
wxSplitterWindow* SplitterWindow3;
wxToolBar* ToolBar1;
wxPanel* Panel3;
wxTextCtrl* edLog;
wxMenuItem* MenuItem5;
wxStaticText* StaticText4;
wxToolBarToolBase* ToolBarItem1;
wxStaticText* StaticText2;
wxMenuItem* MenuItem7;
wxMenuItem* MenuItem4;
wxTreeCtrl* treeView;
wxMenuItem* MenuItem8;
//*)
DECLARE_EVENT_TABLE()
CMyGLCanvas *m_canvas_HMAP;
CMyGLCanvas *m_canvas_LMH;
wxTimer timAutoLoad;
void OntimAutoLoadTrigger(wxTimerEvent& event);
};
#ifdef wxUSE_UNICODE
#define _U(x) wxString((x),wxConvUTF8)
#define _UU(x,y) wxString((x),y)
#else
#define _U(x) (x)
#define _UU(x,y) (x)
#endif
#define WX_START_TRY \
try \
{
#define WX_END_TRY \
} \
catch(std::exception &e) \
{ \
wxMessageBox( wxString(e.what(),wxConvUTF8), wxT("Exception"), wxOK, this); \
} \
catch(...) \
{ \
wxMessageBox( _("Untyped exception!"), _("Exception"), wxOK, this); \
}
#endif // HMTMAPVIEWERMAIN_H
| [
"joseluisblancoc@gmail.com"
] | joseluisblancoc@gmail.com |
68a90a88a54effd597e2e3dfc3e66098c12accf3 | 5f3dfdbfe87cf66fec26bcaa80ff7f869175a157 | /chapter11/program/IntVector-2017-02-15_09-12-43-048.cpp | dbf07e9971f3c6b7c9d10b9eb6fb5baada30585c | [] | no_license | jluo117/cs012 | dd3132f8e5b846b08fefa42502d60d155f25ed77 | 06e4b29757cbbe1f8e6ca7548bfa00af1510d8e0 | refs/heads/master | 2021-08-07T09:26:14.778903 | 2017-11-07T23:45:02 | 2017-11-07T23:45:02 | 87,961,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,628 | cpp | #include <iostream>
#include <stdlib.h>
#include <stdexcept>
#include "IntVector.h"
using namespace std;
IntVector :: IntVector(){
sz = 0;
cap = 0;
data = 0;
}
IntVector :: IntVector(unsigned size, int value){
sz = size;
cap = sz;
data = new int [cap];
for (unsigned i = 0;i < size; i++){
data[i] = value;
}
return;
}
IntVector ::~ IntVector(){
delete data;
return;
}
unsigned IntVector :: size() const {
return sz;
}
unsigned IntVector :: capacity() const {
return cap;
}
bool IntVector:: empty() const {
return (sz == 0);
}
void IntVector::expand(unsigned amount){
dataTemp = new int[cap];
for (unsigned i = 0; i < cap; i++){
dataTemp[i] = data[i];
}
delete data;
data = new int[amount];
for (unsigned i = 0; i< cap; i++){
data[i] = dataTemp[i];
}
delete dataTemp;
}
void IntVector :: insert(unsigned index, int value){
if (index >= sz){
throw out_of_range("IntVector::at_range_check");
}
if (sz == cap){
expand(cap *2);
}
sz++;
for (unsigned i = sz; i > index; i++){
data[i] = data[i -1];
}
data[index] = value;
}
const int & IntVector:: at(unsigned index) const{
/*if ((index >= sz)||(empty())){
throw out_of_range("IntVector::at_range_check");
}
return data[index];
*/
if (index < sz ) {
return data[index];
}
else {
throw out_of_range("IntVector::at_range_check");
}
}
const int & IntVector:: back() const{
return data[sz -1];
}
const int & IntVector::front() const{
return data[0];
}
| [
"luojames52@gmail.com"
] | luojames52@gmail.com |
60b0fc259558a7fd8c696e0653358cad0386bf8e | ce034e3865b06680338d8980e0b9d141ae8d7fdc | /CBlackList.h | 550898108418a5107a138f3e6091e3d2fcd02f8a | [] | no_license | heavyair/testjni | 422b6de78c6f4c3de469d78ec3e0c3d0bf107d9c | 646668ed709e58fa90711f7659fd072cfde79b34 | refs/heads/master | 2021-01-21T05:02:20.575257 | 2016-06-10T05:09:51 | 2016-06-10T05:09:51 | 38,285,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | h | /*
* CBlackList.h
*
* Created on: Jan 13, 2015
* Author: root
*/
#ifndef CBLACKLIST_H_
#define CBLACKLIST_H_
#include "netheader.h"
#include <list>
#include <map>
#include "CComputer.h"
class CBlackList {
public:
CBlackList();
virtual ~CBlackList();
CBlackList& operator=( const CBlackList& other );
CBlackList( const CBlackList& other);
CBlackList(CComputer & p_Computer);
void Save2File(ofstream &p_IOStream);
void LoadFromFile(char * & buff);
public:
//u_char mac[6];
MACADDR mac;
map<DWORD,bool> IPs;
string hostname;
int nSpeedLimit;
};
#endif /* CBLACKLIST_H_ */
| [
"heavyair@users.noreply.github.com"
] | heavyair@users.noreply.github.com |
01ede787e0be69f8b533afa1ec796d53d124b916 | 6eb235e59b138dcde613cde3b3f2042d08029b38 | /src/virtual_driver.cpp | ace14f38f5b6d842d7315371b1d4b20afd828225 | [] | no_license | hssavage/CarND-T3-Path-Planning | 3776a1b5fed3ea53790894a3fedfc91ebc9c1680 | ae30ca30e93f562d6f0d4422b1cbe639c08a7e68 | refs/heads/master | 2021-05-16T16:24:52.544326 | 2018-02-20T05:39:58 | 2018-02-20T05:39:58 | 119,940,704 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 41,313 | cpp | #include "virtual_driver.h"
#include <iostream>
#include <sstream>
using namespace std;
// TO-DO: Define some debug header maybe so it can be cross file?
#define DEBUG
// #define CLI_OUTPUT
/******************************************************************************
* Utility Functions and Helpers *
******************************************************************************/
// TO-DO: Define a Util header? Put constants and helper functions in there.
// TO-DO: Define a WayPoint class for dealing with all the frenet stuff? Or,
// put it in the map class. Might be nicer that way since only the
// map really cares about the way points. Erryone else just wants points
// to be translated between Frenet and Cartesian
// time between steps
static const double TIME_DELTA = 0.02;
// conversion ratio to/from MPH and M/S
static double MPH_TO_MPS(double mph) {return mph / 2.23694;}
static double MPS_TO_MPH(double ms) {return ms * 2.23694;}
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
static double deg2rad(double x) { return x * pi() / 180; }
static double rad2deg(double x) { return x * 180 / pi(); }
static double distance(double x1, double y1, double x2, double y2)
{
return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
static int ClosestWaypoint(double x, double y, const std::vector<double> &maps_x, const std::vector<double> &maps_y)
{
double closestLen = 100000; //large number
int closestWaypoint = 0;
for(int i = 0; i < maps_x.size(); i++)
{
double map_x = maps_x[i];
double map_y = maps_y[i];
double dist = distance(x,y,map_x,map_y);
if(dist < closestLen)
{
closestLen = dist;
closestWaypoint = i;
}
}
return closestWaypoint;
}
static int NextWaypoint(double x, double y, double theta, const std::vector<double> &maps_x, const std::vector<double> &maps_y)
{
int closestWaypoint = ClosestWaypoint(x,y,maps_x,maps_y);
double map_x = maps_x[closestWaypoint];
double map_y = maps_y[closestWaypoint];
double heading = atan2((map_y-y),(map_x-x));
double angle = fabs(theta-heading);
angle = fmin(2.0*pi() - angle, angle);
if(angle > pi()/4)
{
closestWaypoint++;
if (closestWaypoint == maps_x.size()) closestWaypoint = 0;
}
return closestWaypoint;
}
// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
static std::vector<double> getFrenet(double x, double y, double theta, const std::vector<double> &maps_x, const std::vector<double> &maps_y)
{
int next_wp = NextWaypoint(x,y, theta, maps_x, maps_y);
int prev_wp;
prev_wp = next_wp - 1;
if(next_wp == 0) prev_wp = maps_x.size() - 1;
double n_x = maps_x[next_wp] - maps_x[prev_wp];
double n_y = maps_y[next_wp] - maps_y[prev_wp];
double x_x = x - maps_x[prev_wp];
double x_y = y - maps_y[prev_wp];
// find the projection of x onto n
double proj_norm = (x_x * n_x + x_y * n_y) / (n_x * n_x + n_y * n_y);
double proj_x = proj_norm * n_x;
double proj_y = proj_norm * n_y;
double frenet_d = distance(x_x, x_y, proj_x, proj_y);
//see if d value is positive or negative by comparing it to a center point
double center_x = 1000 - maps_x[prev_wp];
double center_y = 2000 - maps_y[prev_wp];
double centerToPos = distance(center_x, center_y, x_x, x_y);
double centerToRef = distance(center_x, center_y, proj_x, proj_y);
if(centerToPos <= centerToRef) frenet_d *= -1;
// calculate s value
double frenet_s = 0;
for(int i = 0; i < prev_wp; i++)
frenet_s += distance(maps_x[i], maps_y[i], maps_x[i+1], maps_y[i+1]);
frenet_s += distance(0, 0, proj_x, proj_y);
return {frenet_s, frenet_d};
}
// Transform from Frenet s,d coordinates to Cartesian x,y
static std::vector<double> getXY(double s, double d, const std::vector<double> &maps_s, const std::vector<double> &maps_x, const std::vector<double> &maps_y)
{
int prev_wp = -1;
while(s > maps_s[prev_wp + 1] && (prev_wp < (int)(maps_s.size() - 1) ))
{
prev_wp++;
}
int wp2 = (prev_wp + 1) % maps_x.size();
double heading = atan2((maps_y[wp2] - maps_y[prev_wp]), (maps_x[wp2] - maps_x[prev_wp]));
// the x,y,s along the segment
double seg_s = (s - maps_s[prev_wp]);
double seg_x = maps_x[prev_wp] + seg_s * cos(heading);
double seg_y = maps_y[prev_wp] + seg_s * sin(heading);
double perp_heading = heading - (pi() / 2.0);
double x = seg_x + d * cos(perp_heading);
double y = seg_y + d * sin(perp_heading);
return {x,y};
}
// Credit to Effendi for suggesting this method and providing a snippet of
// code to make it work. See his full source at:
// https://github.com/edufford/CarND-Path-Planning-Project-P11
std::vector<double> GetHiResXY(double s, double d,
const std::vector<double> &map_s,
const std::vector<double> &map_x,
const std::vector<double> &map_y)
{
// Wrap around s
s = std::fmod(s, 6945.554);
// Find 2 waypoints before s and 2 waypoints after s for angular interpolation
auto it_wp1_search = std::lower_bound(map_s.begin(), map_s.end(), s);
int wp1 = (it_wp1_search - map_s.begin() - 1); // wp before s
int wp2 = (wp1 + 1) % map_s.size(); // wp after s
int wp3 = (wp2 + 1) % map_s.size(); // wp 2nd after s
int wp0 = wp1 - 1; // wp 2nd before s
if (wp0 < 0) { wp0 = map_s.size() - 1; } // wrap around backwards
// Use angle between wp1-wp2 to derive segment vector at distance s from wp1
double theta_wp = atan2((map_y[wp2] - map_y[wp1]),
(map_x[wp2] - map_x[wp1]));
// The (x,y,s) along the segment vector between wp1 and wp2
double seg_s = s - map_s[wp1];
double seg_x = map_x[wp1] + seg_s * cos(theta_wp);
double seg_y = map_y[wp1] + seg_s * sin(theta_wp);
// Interpolate theta at s based on the distance between wp1 (with ave angle
// from wp0 before and wp2 after) and wp2 (with ave angle from wp1 before
// and wp3 after)
double theta_wp1ave = atan2((map_y[wp2] - map_y[wp0]),
(map_x[wp2] - map_x[wp0]));
double theta_wp2ave = atan2((map_y[wp3] - map_y[wp1]),
(map_x[wp3] - map_x[wp1]));
double s_interp = (s - map_s[wp1]) / (map_s[wp2] - map_s[wp1]);
double cos_interp = ((1-s_interp) * cos(theta_wp1ave)
+ s_interp * cos(theta_wp2ave));
double sin_interp = ((1-s_interp) * sin(theta_wp1ave)
+ s_interp * sin(theta_wp2ave));
double theta_interp = atan2(sin_interp, cos_interp);
// Use interpolated theta to calculate final (x,y) at d offset from the
// segment vector
double theta_perp = theta_interp - pi()/2;
double x = seg_x + d * cos(theta_perp);
double y = seg_y + d * sin(theta_perp);
return {x, y};
}
/******************************************************************************
* Class Functions *
******************************************************************************/
// Default Constructor
VirtualDriver::VirtualDriver(){}
// Destructor
VirtualDriver::~VirtualDriver()
{
for(int i = m_vehicle_behaviors.size() - 1; i >= 0 ; --i)
delete m_vehicle_behaviors[i];
}
// Non-Default Constructor
VirtualDriver::VirtualDriver(const Vehicle initial_status, const Road &r,
const Map &m, const double planning_horizon)
{
// Map data
mMap = m;
// Immediate Road data - set speed limit plus that no one is in the lanes
mRoad = r;
mRoad.speed_limit = MPH_TO_MPS(mRoad.speed_limit);
// Planning timing parameters - convert times in seconds to steps
m_planning_horizon = planning_horizon / TIME_DELTA;
// Intial pathing status
m_prev_points_left = 0;
m_cur_s_coeffs = JMT();
m_cur_d_coeffs = JMT();
m_last_followed_window_size = 11;
// Tracking object
m_tracker = ObstacleTracker(55, 5);
// Behaviors this Driver can plan for
m_vehicle_behaviors = std::vector<Behavior *>(3, NULL);
m_vehicle_behaviors[0] = new LaneKeep();
m_vehicle_behaviors[1] = new LaneFollow();
m_vehicle_behaviors[2] = new LaneChange();
// Set up our FSM for our behaviors
//
// +--+ * implementation has
// | | logic to sometimes
// v | limit this to {2}
// (LANE CHANGE)--+
// ^ ^
// | |
// v v
// (KEEP)<------>(FOLLOW)
//
m_vehicle_behaviors[0]->id = 0;
m_vehicle_behaviors[1]->id = 1;
m_vehicle_behaviors[2]->id = 2;
m_vehicle_behaviors[0]->next_behaviors = {0, 1, 2};
m_vehicle_behaviors[1]->next_behaviors = {0, 1, 2};
m_vehicle_behaviors[2]->next_behaviors = {0, 1, 2};
// Keeping is current
m_current_behavior = 0;
m_vehicle_behaviors[0]->current = true;
// Initial Ego car state
mVeh = initial_status;
// Initial reference lane is whatever we're in
m_reference_lane = mRoad.get_vehicle_lane(mVeh);
}
/******************************************************************************
* Sensor Fusion Updates *
******************************************************************************/
// Ingest the sensor fusion updates and cascade values to other internal states
// Update First car in front and behind for each lane
void VirtualDriver::sensor_fusion_updates(const long &ts, std::vector<Obstacle> &obs)
{
m_tracker.update(ts, obs, mVeh, mRoad);
}
/******************************************************************************
* Localization Updates *
******************************************************************************/
// Localization tells us about where we are. It gives us our vehicle's exact
// location (x/y/s/d) and tells us about our vehicle's state (vx,vy). In a real
// vehicle, the CAN network would be able to report accurate acceleration vals
// for all 6 degrees of freedom as well, but the simulator doesn't report that.
// Localization would also probably be responsible for telling us map updates,
// including landmarks AND road updates (lanes, speed limit, etc). Since these
// things update at different frequencies, I split them up, but they're all
// parts of localization updates
// Update vehicle location and state
// NOTE: Simulator has speeds in MPH, so I convert it here early on
void VirtualDriver::vehicle_update(Vehicle v)
{
v.speed = MPH_TO_MPS(v.speed);
v.vx = v.speed*std::cos(v.yaw);
v.vy = v.speed*std::sin(v.yaw);
mVeh = v;
}
// Update Road Characteristics
void VirtualDriver::road_update(const Road &r)
{
mRoad = r;
mRoad.speed_limit = MPH_TO_MPS(mRoad.speed_limit);
}
// Update the map we're using
void VirtualDriver::map_update(const Map &m){mMap = m;}
// Update the route we we're juuuust following
void VirtualDriver::path_history_update(const Path &prev)
{
// Grab how many points we have left from our old window
m_prev_points_left = prev.size();
#ifdef DEBUG
cout << " [$] Received path update - We have " << m_prev_points_left
<< " points of the old path left"
<< endl;
#endif
// Update our window of followed points given our last path
int last_ind_followed = m_planning_horizon - m_prev_points_left - 1;
#ifdef DEBUG
cout << " [$] From last path we can add on (0," << last_ind_followed << ")"
<< endl;
#endif
for(int i = 0; i <= last_ind_followed && i < m_last_path.size(); ++i)
{
m_last_followed_points.push_back(Point(m_last_path.x[i], m_last_path.y[i]));
if(m_last_followed_points.size() > m_last_followed_window_size)
{
m_last_followed_points.pop_front();
}
}
#ifdef DEBUG
cout << " [$] Last " << m_last_followed_window_size << " points followed window:\n";
for(auto it = m_last_followed_points.begin(); it != m_last_followed_points.end(); ++it)
{
cout << " - (" << (*it).x << ", " << (*it).y << ")\n";
}
cout << flush;
#endif
}
/******************************************************************************
* Trajectory Pool Generation *
******************************************************************************/
// Given were we are and whats around us (AND where we think those things will
// go), we can choose what we think we should do. This is effectively our
// driving brain thats telling the system what manuevers to make and how to go
// through traffic.
// The Behavior Planner is tightly coupled with the Trajectory planner. Here,
// the trajectory planner does a lot of heavy lifting to generate a bunch of
// candidate trajectories that can be evaluated for optimality later by the
// behavior planner. Its a bit backwards compared to some of the lessons, but
// the lines are super blurred here because of how closely these layers work
// together
// Get the next behavior from our set of behaviors, given our current one
BehaviorSet VirtualDriver::get_next_behaviors()
{
// If we haven't initialized a behavior, anything goes! <-- shouldnt happen
if(m_current_behavior == -1) return {0, 1, 2};
// Otherwise, the behaviors store their own next states
else return m_vehicle_behaviors[m_current_behavior]->get_next_behaviors(mVeh.s, mVeh.d, mRoad, m_reference_lane);
}
// Calculate trajectories for an action, given where we are now and whats
// around us
TrajectorySet VirtualDriver::generate_trajectories()
{
// Trajectory set to return
TrajectorySet n_possible_trajectories;
// Path State Parameters for JMT generation
double si, si_dot, si_dot_dot;
double di, di_dot, di_dot_dot;
// Calculate an index based on how many dots have been eaten
// and how many we've decided to consistently plan out to.
// We can pull our initial status off this
int start_ind = (m_planning_horizon - m_prev_points_left - 1);
// Set the start time based on our start index
double start_time = start_ind * TIME_DELTA;
// Initial take off state based on current trajectory
// NOTE: These will be overwritten below if there's no existing path
si = m_cur_s_coeffs.get_position_at(start_time);
si_dot = m_cur_s_coeffs.get_velocity_at(start_time);
si_dot_dot = m_cur_s_coeffs.get_acceleration_at(start_time);
di = m_cur_d_coeffs.get_position_at(start_time);
di_dot = m_cur_d_coeffs.get_velocity_at(start_time);
di_dot_dot = m_cur_d_coeffs.get_acceleration_at(start_time);
// If we don't have a previous state, override the normal default values
// to something more sensible based on what we know the state of the car
// to be. Most likely cases of this are 1) start up, or 2) long latency
// between updates. This may be more accurate than the previous trajectory
// we know of
if(m_prev_points_left == 0)
{
// Special initial take off state
si = mVeh.s;
si_dot = 0;
si_dot_dot = 0;
di = mVeh.d;
di_dot = 0;
di_dot_dot = 0;
}
// Watch out for start states that wrap around the map tile we've got
// Velocity and acceleration shouldn't matter but position certainly does
if(si >= mMap.max_s) si -= mMap.max_s;
// I've seen weird cases where I might collide with a car and get a negative
// velocity. The simulator doesn't seem to handle this very well at all. I'm
// gonna cap the speed to positive for now, cant be worse than whats already
// going on.
if(si_dot < 0) si_dot = 0;
#ifdef DEBUG
std::cout << " [*] Starting Parameters:" << std::endl
<< " - si: " << si << std::endl
<< " - si_d: " << si_dot << std::endl
<< " - si_dd: " << si_dot_dot << std::endl
<< " - di: " << di << std::endl
<< " - di_d: " << di_dot << std::endl
<< " - di_dd: " << di_dot_dot << std::endl
<< " - reference_lane: " << m_reference_lane << std::endl
<< " - speed_limit: " << mRoad.speed_limit << " m/s" << std::endl;
#endif
// Get our next possible behaviors from our current one
BehaviorSet next_behaviors = get_next_behaviors();
// With our current set of starting conditions and some final conditions set
// we can now vary parameters to generate a set of possible trajectories we
// can follow.
int count = -1;
for(int i = 0; i < next_behaviors.size(); ++i)
{
int j = next_behaviors[i];
#ifdef DEBUG
cout << " [*] Behavior (ID " << j << "): "
<< m_vehicle_behaviors[j]->name()
<< endl;
#endif
count = m_vehicle_behaviors[j]->add_trajectories(n_possible_trajectories,
si, si_dot, si_dot_dot,
di, di_dot, di_dot_dot,
m_reference_lane, mRoad,
m_tracker);
#ifdef DEBUG
std::cout << " [+] Added " << count << " for '"
<< m_vehicle_behaviors[j]->name() << "'" << std::endl;
#endif
}
#ifdef DEBUG
std::cout << " [+] Determined " << n_possible_trajectories.size() << " Possible Trajectories" << std::endl;
#endif
return n_possible_trajectories;
}
/******************************************************************************
* Prediction Planning and Behavior Selection *
******************************************************************************/
// The object tracker will maintain the status of the surrounding vehicles and
// lanes. Given our sorted list of possible trajectories, we can probe the
// tracker to tell us the first one that _doesnt_ collide with an obstacle.
// Since behaviors are sorted by lowest cost, we'll take the first one that
// comes back as safe!
// Attempt to hard limit the speeds of the path we choose
bool VirtualDriver::comfortable(Trajectory &traj)
{
// Get the path from the trajectory that we would be following
Path p = generate_path(traj);
// For averaging velocity over a window/gating the acceleration
double last_x2 = 0.0, last_y2 = 0.0, last_x = 0.0, last_y = 0.0, last_v_avg = 0.0, v_avg = 0.0;
int window_size = 10;
vector<double> vels = vector<double>(window_size, 0.0);
int v_count = 0;
double MAX_ACC_MAG = 9.9;
// Use our last followed points to get acceleration guesses for
// early points since we're using a rolling, windowed average
auto it = m_last_followed_points.begin();
// If we have no points then we can't do this, and if we have only
// one point then thats not enough to get a velocity to help the
// start point have an acceleration
if(it != m_last_followed_points.end() && m_last_followed_points.size() > 1)
{
#ifdef DEBUG
cout << " [&] We have enough points to use to calculate velocities"
<< endl;
#endif
// our "last" position is the front of the list/oldest point
last_x = (*it).x;
last_y = (*it).y;
++it;
#ifdef DEBUG
cout << " [&] Visiting old, past points:" << endl;
cout << " - (" << last_x << ", " << last_y << ") -- v = ? -- a = ?"
<< endl;
#endif
// NOTE: I'm using 'i' below to see how many velocities we've seen
// but the loop termination condition is based on the above
// iterator
for(int i = 1; it != m_last_followed_points.end(); ++it, ++i)
{
double dist = distance((*it).x, (*it).y, last_x, last_y);
double v = dist / TIME_DELTA;
#ifdef DEBUG
cout << " - (" << (*it).x << ", " << (*it).y << ") -- v = " << v;
#endif
// Add to our set of velocities for calculating the average
// velocity and acceleration
vels[v_count % window_size] = v;
++v_count;
// If we have enough velocities seen, get the average velocity
// over the window we're watching
if(v_count >= window_size)
{
last_v_avg = v_avg;
v_avg = 0.0;
for(int j = 0; j < window_size; ++j) v_avg += vels[j];
v_avg = v_avg / window_size;
#ifdef DEBUG
cout << " -- v_avg = " << v_avg;
#endif
}
#ifdef DEBUG
else cout << " -- v_avg = ?";
#endif
#ifdef DEBUG
// If we haven't seen 2 average velocities then we cant have a real value
// for acceleration, so only calc acceleration when i >= 2
if(v_count > window_size)
{
// Get the acceleration in the direction of the vehicle
double accT = (v_avg - last_v_avg) / TIME_DELTA;
// Get an estimate of the radius of curvature for the acceleration
// created due to turning
// roc = ((1 + (y'(x))^2)^1.5) / | y''(x) |
// y'(x) --> velocity at x
// y'(x) --> acceleration at x
// double r_o_c = pow((1 + (v_avg * v_Avg)), 1.5) / abs(accT);
Circle c = Circle({last_x2, last_y2}, {last_x, last_y}, {p.x[i], p.y[i]});
double r_o_c = c.radius();
double accN = (v_avg * v_avg) / r_o_c;
double a = sqrt(accN*accN + accT*accT);
cout << " -- accT = " << accT << "-- accN = " << accN << " -- a = " << a << endl;
}
else cout << " accT = ? -- accN = ? -- a = ?" << endl;
#endif
// Update our last know values
last_x2 = last_x;
last_y2 = last_y;
last_x = (*it).x;
last_y = (*it).y;
}
}
else
{
// Once we've potentially looked at the previous points and filled in
// the acceleration window, we're now at the beginning of the path/our
// current status
last_x2 = last_x;
last_y2 = last_y;
last_x = mVeh.x;
last_y = mVeh.y;
}
#ifdef DEBUG
cout << " [&] Velocities Seen: " << v_count << endl;
cout << " [&] Last Avg V: " << last_v_avg << endl;
cout << " [&] Avg V: " << v_avg << endl;
#endif
#ifdef DEBUG
cout << " [&] Starting at (" << last_x << ", " << last_y << ")" << endl;
#endif
// Because we have a reliable last_v, we can start at 0 (our current
// position) to get another acceleation value to add to the window.
// However, We don't really want to throw something out using the
// 0th point because we're already here and that would be silly.
for(int i = 1; i < p.size(); ++i)
{
// Get the instantanious velocity and accelerations
double dist = distance(p.x[i], p.y[i], last_x, last_y);
double v = dist / TIME_DELTA;
#ifdef DEBUG
cout << " [&] Evaluated " << i -1 << " to " << i << "(" << p.x[i] << ", " << p.y[i] << ") -- v = " << v << endl;
#endif
// Always check velocity each step
if(v >= mRoad.speed_limit)
{
#ifdef DEBUG
std::cout << " [*] Rejected for speed:" << std::endl
<< " - i = " << i << std::endl
<< " - last_x = " << last_x << std::endl
<< " - last_y = " << last_y << std::endl
<< " - x = " << p.x[i] << std::endl
<< " - y = " << p.y[i] << std::endl
<< " - dist = " << dist << std::endl
<< " - v = " << v << std::endl
<< " - type: " << traj.behavior << std::endl
<< " - s: " << traj.s << std::endl
<< " - d: " << traj.d << std::endl
<< " - cost: " << traj.cost << std::endl
<< " - T: " << traj.T << std::endl;
#endif
return false;
}
// Add to our set of velocities for calculating the average
// velocity and acceleration
vels[v_count % window_size] = v;
++v_count;
// If we have enough velocities seen, get the average velocity
// over the window we're watching
if(v_count >= window_size)
{
last_v_avg = v_avg;
v_avg = 0.0;
for(int j = 0; j < window_size; ++j) v_avg += vels[j];
v_avg = v_avg / window_size;
}
// If we've seen more than one averaged velocity then we can
// get a acceleration
if(v_count > window_size)
{
// Get the acceleration in the direction of the vehicle
double accT = (v_avg - last_v_avg) / (TIME_DELTA * window_size);
// Get the acceleration due to turning
double accN = 0.0;
// Get an estimate of the radius of curvature for the acceleration
// created due to turning
// OLD METHOD:
// roc = ((1 + (y'(x))^2)^1.5) / | y''(x) |
// y'(x) --> velocity at x
// y'(x) --> acceleration at x
// double r_o_c = pow((1 + (v_avg * v_avg)), 1.5) / abs(accT);
// NEW METHOD: Fit a circle and take the radius
Circle c = Circle({last_x2, last_y2}, {last_x, last_y}, {p.x[i], p.y[i]});
double r_o_c = c.radius();
if(r_o_c < 0) r_o_c = 1000000000000.0; // really big number
#ifdef DEBUG
cout << " [&] ROC: " << r_o_c << endl;
#endif
accN = (v_avg * v_avg) / r_o_c;
// Total acceleration
double a = sqrt(accN*accN + accT*accT);
#ifdef DEBUG
cout << " [&] Avg V: " << v_avg << endl;
cout << " [&] Last Avg V: " << last_v_avg << endl;
cout << " [&] AccT: " << accT << endl;
cout << " [&] AccN: " << accN << endl;
cout << " [&] AccTotal: " << a << endl;
#endif
// See if we violate the max acceleration
if(abs(a) >= MAX_ACC_MAG)
{
#ifdef DEBUG
std::cout << " [*] Rejected for acceleration:" << std::endl
<< " - i = " << i << std::endl
<< " - last_x = " << last_x << std::endl
<< " - last_y = " << last_y << std::endl
<< " - x = " << p.x[i] << std::endl
<< " - y = " << p.y[i] << std::endl
<< " - dist = " << dist << std::endl
<< " - v = " << v << std::endl
<< " - v_avg = " << v_avg << std::endl
<< " - last_v_avg = " << last_v_avg << std::endl
<< " - accT = " << accT << std::endl
<< " - accN = " << accN << std::endl
<< " - acc_total = " << a << std::endl
<< " - type: " << traj.behavior << std::endl
<< " - s: " << traj.s << std::endl
<< " - d: " << traj.d << std::endl
<< " - cost: " << traj.cost << std::endl
<< " - T: " << traj.T << std::endl;
#endif
return false;
}
}
// Update our last used points
last_x = p.x[i]; last_y = p.y[i];
}
return true;
}
// Given a list of sorted (by cost) trajectories, pick the optimal one for us
// to follow
Trajectory VirtualDriver::optimal_trajectory(TrajectorySet &possible_trajectories)
{
#ifdef DEBUG
std::cout << " [*] Determining optimal from " << possible_trajectories.size() << " Possible Trajectories" << std::endl;
#endif
// find the minimum cost
Trajectory *opt = NULL;
for(TrajectorySet::iterator it = possible_trajectories.begin(); it != possible_trajectories.end(); ++it)
{
#ifdef DEBUG
std::cout << " [+] Checking a '" << (*it).behavior << "' of cost " << (*it).cost
<< " and T = " << (*it).T
<< std::endl;
#endif
// Make sure the trajectory is safe (no collisions) and
// comfy (speed, accel and jerk are under requirements)
//if(comfortable(*it)) return *it;
if(m_tracker.trajectory_is_safe(*it) && comfortable(*it)) return *it;
#ifdef DEBUG
std::cout << " [*] Removed Trajectory:" << std::endl
<< " - type: " << m_vehicle_behaviors[(*it).behavior]->name() << std::endl
<< " - s: " << (*it).s << std::endl
<< " - d: " << (*it).d << std::endl
<< " - cost: " << (*it).cost << std::endl
<< " - T: " << (*it).T << std::endl;
#endif
}
#ifdef DEBUG
cout << "SHIT FUCK AHHHH DEFAULT TO THE LAST ONE?" << endl;
#endif
// Default to the last path we had I guess?
// TO-DO: What the heck do people do in real life here? Emergency stop?
Trajectory def = Trajectory(m_current_behavior, m_cur_s_coeffs, m_cur_d_coeffs, 0);
return def;
}
/******************************************************************************
* Path Output *
******************************************************************************/
// Turn a valid, vetted trajectory into a followable path
// Convert a Trajectory into an actual followable set of way points
Path VirtualDriver::generate_path(const Trajectory &traj)
{
// To contain points for the final path object
std::vector<double> xpts;
std::vector<double> ypts;
double s, d;
for(int i = 0; i < m_planning_horizon; ++i)
{
s = traj.s.at(((double) i) * TIME_DELTA);
d = traj.d.at(((double) i) * TIME_DELTA);
// Check if the (s, _) point falls outside the map, which
// can happen because the JMT doesn't care!
if(s > mMap.max_s) s -= mMap.max_s;
else if(s < 0) s += mMap.max_s;
std::vector<double> xy = GetHiResXY(s, d, mMap.waypoints_s, mMap.waypoints_x, mMap.waypoints_y);
xpts.push_back(xy[0]);
ypts.push_back(xy[1]);
}
return Path(xpts, ypts);
}
// Convert a Trajectory into a smoothed, actual followable path for the simulator
// NOTE: Currently Unused
Path VirtualDriver::generate_smoothed_path(const Trajectory &traj)
{
// Get the normal path
Path p = generate_path(traj);
// How long to plan for and how to step
double td = TIME_DELTA;
int n = m_planning_horizon;
// Calculate an index based on how many dots have been eaten
// and how many we've decided to consistently plan out to
int points_available = m_planning_horizon - m_prev_points_left - 1;
if(points_available == m_planning_horizon - 1) points_available = 0;
double t_cur_old_path = points_available * td;
// Define the window and initial bounds of the smoothing function
// Note: Smooth window size must be odd
// Note: By the nature of what we're doing, the first point of our
// new path should match a point of the old one, so we lose one from
// the set of possible smoothing points
// Note: A negative value will dip into the last used points IF they
// exist. If they don't, oh well. It would look likeeeee:
// (O = old, N = new, X = point to smooth) --> window = 5
// |---X---|
// O O O O O O O N N N N N N N
int smooth_size = 15;
int first = -1 * (smooth_size / 2);
int nth = first + smooth_size;
// For perspective shift
double yaw_rad = deg2rad(mVeh.yaw);
// Smooth out the beginning of the path
for(int i = 0; i < m_planning_horizon / 4; ++i)
{
// Adjust first/Nth based on existing path points. We have P points
// and a negative j means dip into the old points. If we dip too far
// then we just miss a point we can smooth ): Up the ranges
if(first < 0 && points_available + first < 0)
{
++first;
++nth;
continue;
}
// I've gotten weird instances where the path created isn't increasing
// and this wont work with the spline library. Its fine, we'll just
// skip over it and smooth out the next point.
bool inc = true;
// keep track of the points we want to use to smooth and make the
// smoothing spline object
std::vector<double> s_xpts;
std::vector<double> s_ypts;
tk::spline smoother;
// Go over the entire window and all the points except the middle one
for(int j = first; j < nth; ++j)
{
// The point's we'll grab to use
double __x = 0.0, __y = 0.0;
// If our first is negative, use the old set of points
if(j < 0)
{
double s = m_cur_s_coeffs.get_position_at((j + points_available) * td);
double d = m_cur_d_coeffs.get_position_at((j + points_available) * td);
if(s > mMap.max_s) s -= mMap.max_s;
else if(s < 0) s += mMap.max_s;
vector<double> xy = GetHiResXY(s, d, mMap.waypoints_s, mMap.waypoints_x, mMap.waypoints_y);
__x = xy[0];
__y = xy[1];
}
else if(j != i)
{
__x = p.x[j];
__y = p.y[j];
}
// Again, skip the middle point that we're smoothing
else continue;
// Covert the points to our perspective, relative to the vehicle
double _x = __x - mVeh.x;
double _y = __y - mVeh.y;
double x = _x * cos(0-yaw_rad) - _y * sin(0-yaw_rad);
double y = _x * sin(0-yaw_rad) + _y * cos(0-yaw_rad);
// Here's that weird non-increasing issue...
if(s_xpts.size() > 0 && x < s_xpts[s_xpts.size() - 1])
{
inc = false;
break;
}
// Push them on to our set of points to use with the smoother
s_xpts.push_back(x);
s_ypts.push_back(y);
}
// If its not increasing, on to the next one.
if(!inc) continue;
// Set up the spline
smoother.set_points(s_xpts, s_ypts);
// Smooth the middle point out -- convert the x point to be relative
// to the vehicle again
double _x = p.x[i] - mVeh.x;
double _y = p.y[i] - mVeh.y;
double x = _x * cos(0-yaw_rad) - _y * sin(0-yaw_rad);
double y = smoother(x);
// Change y back to proper frame -- relative to the world
y = x * sin(yaw_rad) + y * cos(yaw_rad) + mVeh.y;
// Add the "smoothed" point
p.y[i] = y;
first++;
nth++;
}
// return our final sets of points as a path
return p;
}
// Convert a Trajectory into a smoothed, actual followable path for the simulator
// NOTE: Currently Unused
Path VirtualDriver::generate_smoothed_path_2(const Trajectory &traj)
{
// Get the normal path - sets of x and y points
Path p = generate_path(traj);
// Set of coresponding time values -- We're going to parameterize the X and Y
// equations and smooth with splines
std::vector<double> time_set;
// For perspective shift of points
double yaw_rad = deg2rad(mVeh.yaw);
// Define our smoother splines and smoothing parameters
std::vector<double> xpts, ypts;
int smooth_interval = 5; // Rate to add points to the spline
int smooth_window = 0; // Window (+/-) the point to add
int smooth_window_step = smooth_window; // Increment size to step through
// the window
// Add points to our spline smoothers
for(int i = 0; i < p.size(); ++i)
{
if(i % smooth_interval == 0)
{
for(int j = i - smooth_window; j <= i + smooth_window; j += smooth_interval)
{
// Handle points that wouldn't be in the path already generated
if(j < 0 || j >= p.size()) continue;
// Add points in window to splines
xpts.push_back(p.x[i]);
ypts.push_back(p.y[i]);
time_set.push_back((double) j * TIME_DELTA);
}
}
}
// Create spline smoothers from data sets made above
tk::spline x_t, y_t;
x_t.set_points(time_set, xpts);
y_t.set_points(time_set, ypts);
// Extract smoothed points for our path
for(int i = 0; i < p.size(); ++i)
{
double t = ((double) i * TIME_DELTA);
p.x[i] = x_t(t);
p.y[i] = y_t(t);
}
// Return final path object
return p;
}
/******************************************************************************
* Path Planner Pipeline *
******************************************************************************/
// Path planning is the name used to describe to interaction of the above steps
// and the overall generation of a path given the status of your vehicle, the
// other vehicles, where you are, and what you think the other vehicles will do
// Given the internal state, plan the trajectory
// This will walk through the whole pipeline:
// - Given sensor fusion data of objects around us, predict where they will
// be in the future
// - Use predictions, road status and map waypoints to determine optimal
// behavior
// - Given the decided behavior, plan a trajectory to hand to a motion
// controller
Path VirtualDriver::plan_route()
{
// Debug state printing
#ifdef DEBUG
cout << " [+] Our speed: " << mVeh.speed << " m/s" << endl;
cout << m_tracker.get_debug_lanes();
#endif
#ifdef CLI_OUTPUT
static int step = 0;
std::stringstream ss;
ss << " [+] step: " << step++ << "\n"
<< " [+] planning_horizon: " << m_planning_horizon << "\n"
<< " [+] road speed limit: " << MPS_TO_MPH(mRoad.speed_limit) << " mph | "
<< mRoad.speed_limit << " m/s\n"
<< " [+] road width: " << mRoad.width << "\n"
<< " [+] vehicle (x, y) / (s, d): (" << mVeh.x << ", "
<< mVeh.y << ") / (" << mVeh.s << ", " << mVeh.d << ")\n"
<< " [+] vehicle lane: " << mRoad.get_vehicle_lane(mVeh) << "\n"
<< " [+] vehicle yaw: " << mVeh.yaw << " degrees | "
<< deg2rad(mVeh.yaw) << " rad/s\n"
<< " [+] vehicle speed: " << mVeh.speed << " m/s | "
<< MPS_TO_MPH(mVeh.speed) << " mph" << "\n"
<< " [+] reference lane: " << m_reference_lane << "\n"
<< " [+] m_current_behavior: (" << m_current_behavior << ") "
<< m_vehicle_behaviors[m_current_behavior]->name() << "\n"
<< " [+] Possible Next behaviors:\n";
BehaviorSet next_behaviors = get_next_behaviors();
for(int i = 0; i < next_behaviors.size(); ++i)
{
if(m_vehicle_behaviors[next_behaviors[i]]->current) ss << "\033[0;32m";
ss << " - " << m_vehicle_behaviors[next_behaviors[i]]->name() << "\t";
if(m_vehicle_behaviors[next_behaviors[i]]->current) ss << "\033[0m";
}
ss << endl;
#endif
// TRAJECTORY POOLING:
// -------------------
// Now that we know our lane, and know where the other cars/obstacles are,
// we can generate a set of possible trajectories to hand over to a
// behavior/feasiblity checker to weigh and pick from
std::vector<Trajectory> possible_trajectories = generate_trajectories();
// BEHAVIOR PLANNING:
// ------------------
// Given our set of possible trajectories, go through it to find the
// ultimate, optimal trajectory. Then turn that trajectory into a path
// Note: Since we're working with a simulator, the vehicle updates every .02
// seconds, and the ultimate distance to be applied needs to be in m/s, so
// (<dist> / 0.02) * 2.23694 = TARGET_SPEED --> <dist> = (TARGET_SPEED / 2.23694) * 0.02
// Extract the best one
Trajectory opt = optimal_trajectory(possible_trajectories);
#ifdef CLI_OUTPUT
bool found = false;
ss << " [*] Looking at top 96 (of " << possible_trajectories.size() << "):\n";
ss << "\033[0;31m";
for(int i = 0; i < 96 && i < possible_trajectories.size(); ++i)
{
if(trajs_are_same(possible_trajectories[i], opt))
{
ss << "\033[0;32m";
found = true;
}
ss << " - " << m_vehicle_behaviors[possible_trajectories[i].behavior]->name() << " - "
<< possible_trajectories[i].cost;
if(found) ss << "\033[0m";
if((i + 1) % 3 == 0) ss << "\n";
}
if(!found) ss << "\033[0m";
ss << "\n";
#endif
#ifdef CLI_OUTPUT
ss << m_tracker.get_debug_lanes();
ss << " [*] Behavior: " << m_vehicle_behaviors[opt.behavior]->name() << " (" << opt.cost << ")" << "\n"
<< " [*] Target time: " << opt.T << "\n"
<< " [*] Target Lane: " << mRoad.get_lane(opt.d.at(opt.T)) << "\n"
<< " [*] Target sf_dot: " << opt.s.get_velocity_at(opt.T) << " m/s | "
<< MPS_TO_MPH(opt.s.get_velocity_at(opt.T)) << " mph\n";
std::cerr << "\033[?25l" << std::flush; // hide cursor for update
std::cerr << "\033[1J" << std::flush; // clear entire screen above
std::cerr << "\033[1;1H" << std::flush; // Move to (1, 1) <-- 1 indexed
std::cerr << ss.str() << std::flush;
std::cerr << "\033[?25h" << std::flush; // show cursor again
#endif
#ifdef DEBUG
std::cout << " [*] Optimal Traj Found!" << std::endl
<< " - type: " << m_vehicle_behaviors[opt.behavior]->name() << std::endl
<< " - s: " << opt.s << std::endl
<< " - d: " << opt.d << std::endl
<< " - cost: " << opt.cost << std::endl
<< " - T: " << opt.T << std::endl;
if(mRoad.get_lane(opt.d.at(opt.T)) != m_reference_lane)
{
std::cout << "[*] Beginning a lane change from lane "
<< m_reference_lane << " to "
<< mRoad.get_lane(opt.d.at(opt.T)) << endl;
}
#endif
// Clear/Set current behavior
if(opt.behavior != m_current_behavior)
{
for(int i = 0; i < m_vehicle_behaviors.size(); ++i)
{
if(i == opt.behavior) m_vehicle_behaviors[i]->current = true;
else m_vehicle_behaviors[i]->current = false;
}
m_current_behavior = opt.behavior;
m_reference_lane = mRoad.get_lane(opt.d.at(opt.T));
}
// Generate the final, follow-able path
Path p = generate_path(opt);
#ifdef DEBUG_PATH
cout << " [^] Final output of path:" << endl;
for(int i = 0; i < p.size(); ++i)
{
cout << " " << i << " | " << "(" << p.x[i] << ", " << p.y[i] << ")";
if(i != 0) cout << " -- v = " << (distance(p.x[i-1], p.y[i-1], p.x[i], p.y[i]) / TIME_DELTA) << "m/s";
else cout << " -- v = ??.???? m/s";
cout << endl;
}
#endif
// Update our current trajectory, path, and reference lane
m_last_path = p;
m_cur_s_coeffs = opt.s;
m_cur_d_coeffs = opt.d;
// Return the path we have planned to the motion controller
return p;
}
| [
"hsavage5@ford.com"
] | hsavage5@ford.com |
e12583a7312a9a846e7902b0f19ed9e10ecb1660 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_old_log_5411.cpp | 48fea459f086ebcd2b195d60a8ab3c6649fad687 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cpp | fputs(
" include subdirectories and symbolic links.\n"
"\n"
" --local-port <num>[-num]\n"
" Set a preferred number or range of local port numbers to use for\n"
" the connection(s). Note that port numbers by nature are a\n"
" scarce resource that will be busy at times so setting this range\n"
" to something too narrow might cause unnecessary connection setup\n"
" failures. (Added in 7.15.2)\n"
"\n"
" -L/--location\n"
, stdout); | [
"993273596@qq.com"
] | 993273596@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.