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
af00950cc8890ff35a7a3e2d573efe6bde1a42f3
e2bc8d420b8fcc0d5f81e4b42b7a2916dd33778e
/steam_api/guiwrap/Marshaling.h
5056b3d60aa2d93565e168f66c441af5c18f71bf
[]
no_license
charlie123/MeGusta2
d8aea2c3c9df3bd2e14c0a266e5c2eadc0fa1c55
ca6c6a101b50e0c2268ce5c59042456f379ae81f
refs/heads/master
2020-05-18T11:21:44.652201
2012-03-31T11:59:50
2012-03-31T11:59:50
3,884,896
1
5
null
null
null
null
WINDOWS-1251
C++
false
false
2,973
h
/*! @file @author Albert Semenov @date 01/2009 @module */ #pragma once #include <MyGUI.h> #include "Utility.h" namespace MyGUI { namespace Managed { class ObjectHolder { public: ObjectHolder() : object() { } ObjectHolder(System::Object ^ _obj) : object(_obj) { } ~ObjectHolder() { } System::Object ^ toObject() { return object; } private: gcroot<System::Object^> object; }; // базовые шаблоны для конвертации переменных и типов template <typename T> struct Convert { typedef T Type; static inline Type To(T _value) { return _value; } static inline T From(Type _value) { return _value; } }; // перегрузка для базовых типов template <> struct Convert<size_t> { typedef System::UInt32 Type; inline static System::UInt32 To(size_t _value) { return System::UInt32(_value); } inline static size_t From(System::UInt32 _value) { return size_t(_value); } }; template <> struct Convert<bool&> { typedef bool% Type; inline static bool% To(bool& _value) { return reinterpret_cast<bool&>(_value); } }; // перегрузка для строк template <> struct Convert<const std::string&> { typedef System::String^ Type; inline static System::String^ To(const std::string& _value) { return string_utility::utf8_to_managed(_value); } inline static std::string From(System::String^ _value) { return string_utility::managed_to_utf8(_value); } }; template <> struct Convert<const MyGUI::UString&> { typedef System::String^ Type; inline static System::String^ To(const MyGUI::UString& _value) { return string_utility::utf16_to_managed(_value); } inline static MyGUI::UString From(System::String^ _value) { return string_utility::managed_to_utf16(_value); } }; template <> struct Convert<MyGUI::UString> { typedef System::String^ Type; inline static System::String^ To(const MyGUI::UString& _value) { return string_utility::utf16_to_managed(_value); } inline static MyGUI::UString From(System::String^ _value) { return string_utility::managed_to_utf16(_value); } }; // прегрузка для Any template <> struct Convert<MyGUI::Any> { typedef System::Object^ Type; inline static System::Object^ To(MyGUI::Any _value) { ObjectHolder * data = _value.castType< ObjectHolder >(false); return data ? data->toObject() : nullptr; } inline static MyGUI::Any From(System::Object^ _value) { ObjectHolder data = _value; return data; } }; template <> struct Convert<const MyGUI::Guid&> { typedef System::Guid Type; inline static const System::Guid& To(const MyGUI::Guid& _value) { return reinterpret_cast<const System::Guid&>(_value); } inline static const MyGUI::Guid& From(System::Guid& _value) { return reinterpret_cast<const MyGUI::Guid&>(_value); } }; } // namespace Managed } // namespace MyGUI
[ "cristi126@yahoo.com" ]
cristi126@yahoo.com
ebc98acb963ddabd3d7c449b65623581097cbe4e
da3bd272b6d5a61ddabc88967976591ec4fd6e50
/src/table.h
9e3113cb43ac5a9800db5fdc49648ecbbcbd54e5
[ "MIT" ]
permissive
jaredloomis/sighlo
9c76e50ba68e57bea177595a4a3b67ae90a81755
5be797d14149a3d00b9d3093a827c281fe9125ea
refs/heads/master
2020-03-28T20:21:11.115719
2018-09-21T20:14:36
2018-09-21T20:14:36
149,062,148
1
0
null
null
null
null
UTF-8
C++
false
false
2,615
h
#ifndef _TABLE_H #define _TABLE_H #include <iostream> #include <fstream> #include <map> #include <vector> #include <random> #include <string> #include <optional> #include <cstdlib> #include <memory> #include "entity.h" class Table { public: std::map<Identifier, Entity*> entries; std::vector<std::string> log; Table() {} ~Table() { for(std::map<Identifier, Entity*>::iterator it = entries.begin(); it != entries.end(); ++it) delete it->second; } bool insert(Entity* entity) { entries[entity->id] = entity; return true; } std::vector<std::pair<Identifier, Entity*>> search(bool (*pred)(Identifier, Entity*)) const { std::vector<std::pair<Identifier, Entity*>> ret; auto all = list(); for(size_t i = 0; i < all.size(); ++i) { auto entity = all[i]; if(pred(entity.first, entity.second)) ret.push_back(entity); } return ret; } std::optional<Entity*> get(Identifier id) const { auto cached = get_cache(id); if(cached.has_value()) return cached; else return get_disk(id); } std::optional<Entity*> get_cache(Identifier id) const { try { return std::optional(entries.at(id)); } catch(std::out_of_range ex) { return std::nullopt; } } std::optional<Entity*> get_disk(Identifier id) const { return std::nullopt; } std::vector<std::pair<Identifier, Entity*>> list() const { std::vector<std::pair<Identifier, Entity*>> ret; for(std::map<Identifier, Entity*>::const_iterator it = entries.cbegin(); it != entries.cend(); ++it) ret.push_back(std::make_pair(it->first, it->second)); return ret; } Identifier generateID() const { return std::to_string(rand()); } }; std::ostream& operator<<(std::ostream& os, const Table& table) { auto entities = table.list(); for(size_t i = 0; i < entities.size(); ++i) { entities[i].second->write(os); os << "\n"; } return os; } std::istream& operator>>(std::istream& is, Table& table) { Entity* entity = nullptr; do { auto e = read_entity(is); if(e.has_value()) { entity = e.value(); if(entity->type != EntityType::NIL) { table.insert(entity); } else { delete entity; } } } while(entity != nullptr && entity->type != EntityType::NIL && is.tellg() != -1); return is; } #endif // _TABLE_H
[ "jaredloomis@users.noreply.github.com" ]
jaredloomis@users.noreply.github.com
ff8b94b719a49409f47e2f0df6eb63bd8b33dc60
6a705ffc83cddec356d616ffb72879811040dfec
/tensor.h
66ea60a9e59ed5016ed7f96b27274875014ede59
[]
no_license
alademm/neural-network-experiment
c65e93e4c11699984b42fe7947220852dc6313ad
6478f2e05c277f799f2c6f0332d017afac5539dc
refs/heads/master
2020-03-25T18:34:21.466950
2019-09-21T23:43:30
2019-09-21T23:43:30
144,037,648
0
0
null
null
null
null
UTF-8
C++
false
false
3,671
h
#pragma once #include <assert.h> #include <utility> //#define USE_GPU //class Tensor; //class TElement //{ //public: // operator float()const { return m_t->m_data[m_idx]; } // void operator=(float val) // { // m_t->m_data[m_idx] = val; // m_t->m_valid[m_idx] = true; // } // //private: // friend class Tensor; // explicit TElement(Tensor *t): m_t(t) {} // Tensor *m_t; // int m_idx; //}; class Tensor { public: enum { BLOCK_SIZE = 32 }; Tensor(); Tensor(int n_items, int n_channels, int n_rows, int n_cols); ~Tensor(); Tensor(const Tensor &) = delete; Tensor &operator=(const Tensor &) = delete; Tensor(Tensor &&); Tensor &operator=(Tensor &&); Tensor Clone()const; bool ToGPU(); bool UpdateFromGPU(); bool UpdateFromHost(); Tensor operator*(const Tensor &t2)const; Tensor operator-(const Tensor& t2)const; void operator*=(const float m); void operator-=(const Tensor& t2); // The following index into the host array, so make sure to have it updated from GPU first. inline float &operator()(int item, int channel, int row, int col); inline float operator()(int item, int channel, int row, int col)const; inline float& operator()(int idx); inline float operator()(int idx) const; int GetNumItems()const { return m_nitems; } int GetNumChannels()const { return m_nchannels; } int GetNumCols()const { return m_ncols; } int GetNumPaddedCols()const { return m_npadded_cols; } int GetNumPaddedRows()const { return m_npadded_rows; } int GetNumRows()const { return m_nrows; } int GetNumTotalElements()const { return (m_nitems * m_nchannels * m_npadded_rows * m_npadded_cols); } int GetNumValidElements()const { return (m_nitems * m_nchannels * m_nrows * m_ncols); } void SetItemHost(int idx, const Tensor& val); Tensor GetItemHost(int idx)const; Tensor ItemsSummed()const; void SetZero(); void HadamardProduct(const Tensor &t2); Tensor T(); inline float* GetGPUPointer()const { return m_data_gpu; } private: void allocate_storage(size_t n_elements); void free_storage(); float *m_data, *m_data_gpu; int m_nitems, m_nchannels, m_nrows, m_ncols, m_npadded_rows, m_npadded_cols; }; #define T_ITER_BEGIN(T) \ for (int it = 0; it < T.GetNumItems(); it++) {\ for (int ch = 0; ch < T.GetNumChannels(); ch++) {\ for (int r = 0; r < T.GetNumRows(); r++) {\ for (int c = 0; c < T.GetNumCols(); c++) {\ #define T_ITER_END(T) }}}}\ //================================================================ float &Tensor::operator()(int item, int channel, int row, int col) { assert(item >= 0 && item < GetNumItems()); assert(channel >= 0 && channel < GetNumChannels()); assert(row >= 0 && row < GetNumRows()); assert(col >= 0 && col < GetNumCols()); return m_data[item*m_nchannels*m_npadded_rows*m_npadded_cols + channel*m_npadded_rows*m_npadded_cols + row*m_npadded_cols + col]; } float Tensor::operator()(int item, int channel, int row, int col)const { assert(item >= 0 && item < GetNumItems()); assert(channel >= 0 && channel < GetNumChannels()); assert(row >= 0 && row < GetNumRows()); assert(col >= 0 && col < GetNumCols()); return m_data[item*m_nchannels*m_npadded_rows*m_npadded_cols + channel*m_npadded_rows*m_npadded_cols + row*m_npadded_cols + col]; } float& Tensor::operator()(int idx) { assert(idx >= 0 && idx < GetNumTotalElements()); return m_data[idx]; } float Tensor::operator()(int idx) const { assert(idx >= 0 && idx < GetNumTotalElements()); return m_data[idx]; }
[ "alademm@gmail.com" ]
alademm@gmail.com
211d49bf87884285cf5fd9cae1afcb07e860316b
0de763286c3d2ce8c48d8d6a0a82122a4ac0394f
/OpenGL/ShapeIO/Quads/Cube.h
6be72ce8da4a8842c42095942c0c6cfc695a2032
[ "MIT" ]
permissive
thejoebaldwin/fvtc-fall2013-cplusplus
d8280ea493375fad0113b7b7f8e4330b6d0415a6
fedb588813025a32d9ebc3ecaecb44340e4cf765
refs/heads/master
2020-04-05T23:21:55.026722
2014-03-18T17:02:54
2014-03-18T17:02:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,322
h
#include "Quad.h" class Cube : public Quad { private: public: void Draw(); Cube(); Cube(GLfloat, GLfloat, GLfloat, Colors); }; Cube::Cube() { Cube(0,0,10,RED); } Cube::Cube(GLfloat x, GLfloat y, GLfloat height, Colors color) { x_pos_ = x; y_pos_ = y; height_ = height; x_speed_ = 0; y_speed_ = 0; angle_ = 0; rotation_ = 0; set_color(color); } void Cube::Draw() { static GLfloat red[] = {1.0, 0.0, 0.0, 1.0}; static GLfloat green[] = {0.0, 1.0, 0.0, 1.0}; static GLfloat blue[] = {0.0, 0.0, 1.0, 1.0}; static GLfloat yellow[] = {1.0, 1.0, 0.0, 1.0}; static GLfloat white[] = {1.0, 1.0, 1.0, 1.0}; GLfloat half_height = height_ / 2.0f; glPushMatrix(); glTranslatef(x_pos_, y_pos_, 0); glRotatef(angle_, 0.0f, 0.0f, 1.0f); glBegin(GL_TRIANGLES); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color_); //front face glVertex3f(-half_height, -half_height,half_height); glVertex3f(half_height, half_height,half_height); glVertex3f(half_height, -half_height,half_height); glVertex3f(-half_height, -half_height,half_height); glVertex3f(-half_height,half_height,half_height); glVertex3f(half_height, half_height,half_height); //back face glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color_); glVertex3f(-half_height, -half_height,-half_height); glVertex3f(half_height, half_height,-half_height); glVertex3f(half_height, -half_height,-half_height); glVertex3f(-half_height, -half_height,-half_height); glVertex3f(-half_height,half_height,-half_height); glVertex3f(half_height, half_height,-half_height); //top glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color_); glVertex3f(-half_height, half_height,-half_height); glVertex3f(half_height, half_height,half_height); glVertex3f(half_height, half_height,-half_height); glVertex3f(-half_height, half_height,-half_height); glVertex3f(-half_height,half_height,half_height); glVertex3f(half_height, half_height,half_height); //bottom glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color_); glVertex3f(-half_height, -half_height,-half_height); glVertex3f(half_height, -half_height,half_height); glVertex3f(half_height, -half_height,-half_height); glVertex3f(-half_height, -half_height,-half_height); glVertex3f(-half_height,-half_height,half_height); glVertex3f(half_height, -half_height,half_height); //left glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color_); glVertex3f(-half_height, -half_height,-half_height); glVertex3f(-half_height, half_height,half_height); glVertex3f(-half_height, -half_height,half_height); glVertex3f(-half_height, -half_height,-half_height); glVertex3f(-half_height,half_height,-half_height); glVertex3f(-half_height, half_height,half_height); //right glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color_); glVertex3f(half_height, -half_height,-half_height); glVertex3f(half_height, half_height,half_height); glVertex3f(half_height, -half_height,half_height); glVertex3f(half_height, -half_height,-half_height); glVertex3f(half_height,half_height,-half_height); glVertex3f(half_height, half_height,half_height); glEnd(); glPopMatrix(); }
[ "contact@humboldttechgroup.com" ]
contact@humboldttechgroup.com
3a7402050700d25b0c1022f4c222205e95801098
438180ac509e4f743e4d27236a686ee9eb545fdd
/RenderSystems/Direct3D9/src/OgreD3D9HLSLProgram.cpp
99ef8e18044a6c5f6644bf3dcd4529b441bdd45c
[ "MIT" ]
permissive
milram/ogre-1.7.4-osx
15e3d14e827e3c198f7cda68872a0be26ba95e55
adec12bc0694b9b56a8f31e91cc72f0f75dd83c7
refs/heads/master
2021-01-01T19:21:11.880357
2012-04-30T18:34:49
2012-04-30T18:34:49
7,885,095
1
0
null
null
null
null
UTF-8
C++
false
false
22,944
cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2011 Torus Knot Software Ltd 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 "OgreD3D9HLSLProgram.h" #include "OgreGpuProgramManager.h" #include "OgreStringConverter.h" #include "OgreD3D9GpuProgram.h" namespace Ogre { //----------------------------------------------------------------------- D3D9HLSLProgram::CmdEntryPoint D3D9HLSLProgram::msCmdEntryPoint; D3D9HLSLProgram::CmdTarget D3D9HLSLProgram::msCmdTarget; D3D9HLSLProgram::CmdPreprocessorDefines D3D9HLSLProgram::msCmdPreprocessorDefines; D3D9HLSLProgram::CmdColumnMajorMatrices D3D9HLSLProgram::msCmdColumnMajorMatrices; D3D9HLSLProgram::CmdOptimisation D3D9HLSLProgram::msCmdOptimisation; D3D9HLSLProgram::CmdMicrocode D3D9HLSLProgram::msCmdMicrocode; D3D9HLSLProgram::CmdAssemblerCode D3D9HLSLProgram::msCmdAssemblerCode; class _OgreD3D9Export HLSLIncludeHandler : public ID3DXInclude { public: HLSLIncludeHandler(Resource* sourceProgram) : mProgram(sourceProgram) {} ~HLSLIncludeHandler() {} STDMETHOD(Open)(D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pByteLen ) { // find & load source code DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource( String(pFileName), mProgram->getGroup(), true, mProgram); String source = stream->getAsString(); // copy into separate c-string // Note - must NOT copy the null terminator, otherwise this will terminate // the entire program string! *pByteLen = static_cast<UINT>(source.length()); char* pChar = new char[*pByteLen]; memcpy(pChar, source.c_str(), *pByteLen); *ppData = pChar; return S_OK; } STDMETHOD(Close)(LPCVOID pData) { char* pChar = (char*)pData; delete [] pChar; return S_OK; } protected: Resource* mProgram; }; //----------------------------------------------------------------------- //----------------------------------------------------------------------- void D3D9HLSLProgram::loadFromSource(void) { // Populate preprocessor defines String stringBuffer; vector<D3DXMACRO>::type defines; const D3DXMACRO* pDefines = 0; if (!mPreprocessorDefines.empty()) { stringBuffer = mPreprocessorDefines; // Split preprocessor defines and build up macro array D3DXMACRO macro; String::size_type pos = 0; while (pos != String::npos) { macro.Name = &stringBuffer[pos]; macro.Definition = 0; String::size_type start_pos=pos; // Find delims pos = stringBuffer.find_first_of(";,=", pos); if(start_pos==pos) { if(pos==stringBuffer.length()) { break; } pos++; continue; } if (pos != String::npos) { // Check definition part if (stringBuffer[pos] == '=') { // Setup null character for macro name stringBuffer[pos++] = '\0'; macro.Definition = &stringBuffer[pos]; pos = stringBuffer.find_first_of(";,", pos); } else { // No definition part, define as "1" macro.Definition = "1"; } if (pos != String::npos) { // Setup null character for macro name or definition stringBuffer[pos++] = '\0'; } } else { macro.Definition = "1"; } if(strlen(macro.Name)>0) { defines.push_back(macro); } else { break; } } // Add NULL terminator macro.Name = 0; macro.Definition = 0; defines.push_back(macro); pDefines = &defines[0]; } // Populate compile flags DWORD compileFlags = 0; if (mColumnMajorMatrices) compileFlags |= D3DXSHADER_PACKMATRIX_COLUMNMAJOR; else compileFlags |= D3DXSHADER_PACKMATRIX_ROWMAJOR; #if OGRE_DEBUG_MODE compileFlags |= D3DXSHADER_DEBUG; #endif switch (mOptimisationLevel) { case OPT_DEFAULT: compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1; break; case OPT_NONE: compileFlags |= D3DXSHADER_SKIPOPTIMIZATION; break; case OPT_0: compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL0; break; case OPT_1: compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1; break; case OPT_2: compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL2; break; case OPT_3: compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL3; break; } LPD3DXBUFFER errors = 0; // include handler HLSLIncludeHandler includeHandler(this); // Compile & assemble into microcode HRESULT hr = D3DXCompileShader( mSource.c_str(), static_cast<UINT>(mSource.length()), pDefines, &includeHandler, mEntryPoint.c_str(), mTarget.c_str(), compileFlags, &mpMicroCode, &errors, &mpConstTable); if (FAILED(hr)) { String message = "Cannot assemble D3D9 high-level shader " + mName; if( errors ) { message += String(" Errors:\n") + static_cast<const char*>(errors->GetBufferPointer()); errors->Release(); } OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, message, "D3D9HLSLProgram::loadFromSource"); } } //----------------------------------------------------------------------- void D3D9HLSLProgram::createLowLevelImpl(void) { if (!mCompileError) { // Create a low-level program, give it the same name as us mAssemblerProgram = GpuProgramManager::getSingleton().createProgramFromString( mName, mGroup, "",// dummy source, since we'll be using microcode mType, mTarget); static_cast<D3D9GpuProgram*>(mAssemblerProgram.get())->setExternalMicrocode(mpMicroCode); } } //----------------------------------------------------------------------- void D3D9HLSLProgram::unloadHighLevelImpl(void) { SAFE_RELEASE(mpMicroCode); SAFE_RELEASE(mpConstTable); } //----------------------------------------------------------------------- void D3D9HLSLProgram::buildConstantDefinitions() const { // Derive parameter names from const table assert(mpConstTable && "Program not loaded!"); // Get contents of the constant table D3DXCONSTANTTABLE_DESC desc; HRESULT hr = mpConstTable->GetDesc(&desc); createParameterMappingStructures(true); if (FAILED(hr)) { OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Cannot retrieve constant descriptions from HLSL program.", "D3D9HLSLProgram::buildParameterNameMap"); } // Iterate over the constants for (unsigned int i = 0; i < desc.Constants; ++i) { // Recursively descend through the structure levels processParamElement(NULL, "", i); } } //----------------------------------------------------------------------- void D3D9HLSLProgram::processParamElement(D3DXHANDLE parent, String prefix, unsigned int index) const { D3DXHANDLE hConstant = mpConstTable->GetConstant(parent, index); // Since D3D HLSL doesn't deal with naming of array and struct parameters // automatically, we have to do it by hand D3DXCONSTANT_DESC desc; unsigned int numParams = 1; HRESULT hr = mpConstTable->GetConstantDesc(hConstant, &desc, &numParams); if (FAILED(hr)) { OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Cannot retrieve constant description from HLSL program.", "D3D9HLSLProgram::processParamElement"); } String paramName = desc.Name; // trim the odd '$' which appears at the start of the names in HLSL if (paramName.at(0) == '$') paramName.erase(paramName.begin()); // Also trim the '[0]' suffix if it exists, we will add our own indexing later if (StringUtil::endsWith(paramName, "[0]", false)) { paramName.erase(paramName.size() - 3); } if (desc.Class == D3DXPC_STRUCT) { // work out a new prefix for nested members, if it's an array, we need an index prefix = prefix + paramName + "."; // Cascade into struct for (unsigned int i = 0; i < desc.StructMembers; ++i) { processParamElement(hConstant, prefix, i); } } else { // Process params if (desc.Type == D3DXPT_FLOAT || desc.Type == D3DXPT_INT || desc.Type == D3DXPT_BOOL) { size_t paramIndex = desc.RegisterIndex; String name = prefix + paramName; GpuConstantDefinition def; def.logicalIndex = paramIndex; // populate type, array size & element size populateDef(desc, def); if (def.isFloat()) { def.physicalIndex = mFloatLogicalToPhysical->bufferSize; OGRE_LOCK_MUTEX(mFloatLogicalToPhysical->mutex) mFloatLogicalToPhysical->map.insert( GpuLogicalIndexUseMap::value_type(paramIndex, GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL))); mFloatLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; mConstantDefs->floatBufferSize = mFloatLogicalToPhysical->bufferSize; } else { def.physicalIndex = mIntLogicalToPhysical->bufferSize; OGRE_LOCK_MUTEX(mIntLogicalToPhysical->mutex) mIntLogicalToPhysical->map.insert( GpuLogicalIndexUseMap::value_type(paramIndex, GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL))); mIntLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; mConstantDefs->intBufferSize = mIntLogicalToPhysical->bufferSize; } mConstantDefs->map.insert(GpuConstantDefinitionMap::value_type(name, def)); // Now deal with arrays mConstantDefs->generateConstantDefinitionArrayEntries(name, def); } } } //----------------------------------------------------------------------- void D3D9HLSLProgram::populateDef(D3DXCONSTANT_DESC& d3dDesc, GpuConstantDefinition& def) const { def.arraySize = d3dDesc.Elements; switch(d3dDesc.Type) { case D3DXPT_INT: switch(d3dDesc.Columns) { case 1: def.constType = GCT_INT1; break; case 2: def.constType = GCT_INT2; break; case 3: def.constType = GCT_INT3; break; case 4: def.constType = GCT_INT4; break; } // columns break; case D3DXPT_FLOAT: switch(d3dDesc.Class) { case D3DXPC_MATRIX_COLUMNS: case D3DXPC_MATRIX_ROWS: { int firstDim, secondDim; firstDim = d3dDesc.RegisterCount / d3dDesc.Elements; if (d3dDesc.Class == D3DXPC_MATRIX_ROWS) { secondDim = d3dDesc.Columns; } else { secondDim = d3dDesc.Rows; } switch(firstDim) { case 2: switch(secondDim) { case 2: def.constType = GCT_MATRIX_2X2; def.elementSize = 8; // HLSL always packs break; case 3: def.constType = GCT_MATRIX_2X3; def.elementSize = 8; // HLSL always packs break; case 4: def.constType = GCT_MATRIX_2X4; def.elementSize = 8; break; } // columns break; case 3: switch(secondDim) { case 2: def.constType = GCT_MATRIX_3X2; def.elementSize = 12; // HLSL always packs break; case 3: def.constType = GCT_MATRIX_3X3; def.elementSize = 12; // HLSL always packs break; case 4: def.constType = GCT_MATRIX_3X4; def.elementSize = 12; break; } // columns break; case 4: switch(secondDim) { case 2: def.constType = GCT_MATRIX_4X2; def.elementSize = 16; // HLSL always packs break; case 3: def.constType = GCT_MATRIX_4X3; def.elementSize = 16; // HLSL always packs break; case 4: def.constType = GCT_MATRIX_4X4; def.elementSize = 16; break; } // secondDim break; } // firstDim } break; case D3DXPC_SCALAR: case D3DXPC_VECTOR: switch(d3dDesc.Columns) { case 1: def.constType = GCT_FLOAT1; break; case 2: def.constType = GCT_FLOAT2; break; case 3: def.constType = GCT_FLOAT3; break; case 4: def.constType = GCT_FLOAT4; break; } // columns break; } default: // not mapping samplers, don't need to take the space break; }; // D3D9 pads to 4 elements def.elementSize = GpuConstantDefinition::getElementSize(def.constType, true); } LPD3DXBUFFER D3D9HLSLProgram::getMicroCode() { return mpMicroCode; } //----------------------------------------------------------------------- D3D9HLSLProgram::D3D9HLSLProgram(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader) : HighLevelGpuProgram(creator, name, handle, group, isManual, loader) , mTarget() , mEntryPoint() , mPreprocessorDefines() , mColumnMajorMatrices(true) , mpMicroCode(NULL), mpConstTable(NULL) , mOptimisationLevel(OPT_DEFAULT) { if (createParamDictionary("D3D9HLSLProgram")) { setupBaseParamDictionary(); ParamDictionary* dict = getParamDictionary(); dict->addParameter(ParameterDef("entry_point", "The entry point for the HLSL program.", PT_STRING),&msCmdEntryPoint); dict->addParameter(ParameterDef("target", "Name of the assembler target to compile down to.", PT_STRING),&msCmdTarget); dict->addParameter(ParameterDef("preprocessor_defines", "Preprocessor defines use to compile the program.", PT_STRING),&msCmdPreprocessorDefines); dict->addParameter(ParameterDef("column_major_matrices", "Whether matrix packing in column-major order.", PT_BOOL),&msCmdColumnMajorMatrices); dict->addParameter(ParameterDef("optimisation_level", "The optimisation level to use.", PT_STRING),&msCmdOptimisation); dict->addParameter(ParameterDef("micro_code", "the micro code.", PT_STRING),&msCmdMicrocode); dict->addParameter(ParameterDef("assemble_code", "the assemble code.", PT_STRING),&msCmdAssemblerCode); } } //----------------------------------------------------------------------- D3D9HLSLProgram::~D3D9HLSLProgram() { // have to call this here reather than in Resource destructor // since calling virtual methods in base destructors causes crash if (isLoaded()) { unload(); } else { unloadHighLevel(); } } //----------------------------------------------------------------------- bool D3D9HLSLProgram::isSupported(void) const { if (mCompileError || !isRequiredCapabilitiesSupported()) return false; return GpuProgramManager::getSingleton().isSyntaxSupported(mTarget); } //----------------------------------------------------------------------- GpuProgramParametersSharedPtr D3D9HLSLProgram::createParameters(void) { // Call superclass GpuProgramParametersSharedPtr params = HighLevelGpuProgram::createParameters(); // Need to transpose matrices if compiled with column-major matrices params->setTransposeMatrices(mColumnMajorMatrices); return params; } //----------------------------------------------------------------------- void D3D9HLSLProgram::setTarget(const String& target) { mTarget = target; } //----------------------------------------------------------------------- const String& D3D9HLSLProgram::getLanguage(void) const { static const String language = "hlsl"; return language; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- String D3D9HLSLProgram::CmdEntryPoint::doGet(const void *target) const { return static_cast<const D3D9HLSLProgram*>(target)->getEntryPoint(); } void D3D9HLSLProgram::CmdEntryPoint::doSet(void *target, const String& val) { static_cast<D3D9HLSLProgram*>(target)->setEntryPoint(val); } //----------------------------------------------------------------------- String D3D9HLSLProgram::CmdTarget::doGet(const void *target) const { return static_cast<const D3D9HLSLProgram*>(target)->getTarget(); } void D3D9HLSLProgram::CmdTarget::doSet(void *target, const String& val) { static_cast<D3D9HLSLProgram*>(target)->setTarget(val); } //----------------------------------------------------------------------- String D3D9HLSLProgram::CmdPreprocessorDefines::doGet(const void *target) const { return static_cast<const D3D9HLSLProgram*>(target)->getPreprocessorDefines(); } void D3D9HLSLProgram::CmdPreprocessorDefines::doSet(void *target, const String& val) { static_cast<D3D9HLSLProgram*>(target)->setPreprocessorDefines(val); } //----------------------------------------------------------------------- String D3D9HLSLProgram::CmdColumnMajorMatrices::doGet(const void *target) const { return StringConverter::toString(static_cast<const D3D9HLSLProgram*>(target)->getColumnMajorMatrices()); } void D3D9HLSLProgram::CmdColumnMajorMatrices::doSet(void *target, const String& val) { static_cast<D3D9HLSLProgram*>(target)->setColumnMajorMatrices(StringConverter::parseBool(val)); } //----------------------------------------------------------------------- String D3D9HLSLProgram::CmdOptimisation::doGet(const void *target) const { switch(static_cast<const D3D9HLSLProgram*>(target)->getOptimisationLevel()) { default: case OPT_DEFAULT: return "default"; case OPT_NONE: return "none"; case OPT_0: return "0"; case OPT_1: return "1"; case OPT_2: return "2"; case OPT_3: return "3"; } } void D3D9HLSLProgram::CmdOptimisation::doSet(void *target, const String& val) { if (StringUtil::startsWith(val, "default", true)) static_cast<D3D9HLSLProgram*>(target)->setOptimisationLevel(OPT_DEFAULT); else if (StringUtil::startsWith(val, "none", true)) static_cast<D3D9HLSLProgram*>(target)->setOptimisationLevel(OPT_NONE); else if (StringUtil::startsWith(val, "0", true)) static_cast<D3D9HLSLProgram*>(target)->setOptimisationLevel(OPT_0); else if (StringUtil::startsWith(val, "1", true)) static_cast<D3D9HLSLProgram*>(target)->setOptimisationLevel(OPT_1); else if (StringUtil::startsWith(val, "2", true)) static_cast<D3D9HLSLProgram*>(target)->setOptimisationLevel(OPT_2); else if (StringUtil::startsWith(val, "3", true)) static_cast<D3D9HLSLProgram*>(target)->setOptimisationLevel(OPT_3); } //----------------------------------------------------------------------- String D3D9HLSLProgram::CmdMicrocode::doGet(const void *target) const { D3D9HLSLProgram* program=const_cast<D3D9HLSLProgram*>(static_cast<const D3D9HLSLProgram*>(target)); LPD3DXBUFFER buffer=program->getMicroCode(); if(buffer) { char* str =static_cast<Ogre::String::value_type*>(buffer->GetBufferPointer()); size_t size=static_cast<size_t>(buffer->GetBufferSize()); Ogre::String code; code.assign(str,size); return code; } else { return String(); } } void D3D9HLSLProgram::CmdMicrocode::doSet(void *target, const String& val) { //nothing to do //static_cast<D3D9HLSLProgram*>(target)->setColumnMajorMatrices(StringConverter::parseBool(val)); } //----------------------------------------------------------------------- String D3D9HLSLProgram::CmdAssemblerCode::doGet(const void *target) const { D3D9HLSLProgram* program=const_cast<D3D9HLSLProgram*>(static_cast<const D3D9HLSLProgram*>(target)); LPD3DXBUFFER buffer=program->getMicroCode(); if(buffer) { CONST DWORD* code =static_cast<CONST DWORD*>(buffer->GetBufferPointer()); LPD3DXBUFFER pDisassembly=0; HRESULT hr=D3DXDisassembleShader(code,FALSE,"// assemble code from D3D9HLSLProgram\n",&pDisassembly); if(pDisassembly) { char* str =static_cast<Ogre::String::value_type*>(pDisassembly->GetBufferPointer()); size_t size=static_cast<size_t>(pDisassembly->GetBufferSize()); Ogre::String assemble_code; assemble_code.assign(str,size); pDisassembly->Release(); return assemble_code; } return String(); } else { return String(); } } void D3D9HLSLProgram::CmdAssemblerCode::doSet(void *target, const String& val) { //nothing to do //static_cast<D3D9HLSLProgram*>(target)->setColumnMajorMatrices(StringConverter::parseBool(val)); } }
[ "1991md@gmail.com" ]
1991md@gmail.com
fdbdd5a1f75a7d420c888017e5cb1017d6bf1d6e
432ec5e2056256cb0ce136bacad1022c3ba77fc6
/nvdsinfer_custom_impl_Yolo/layers/route_layer.cpp
a3925a0357eaa448ff27630cb211adea60fb2937
[ "MIT" ]
permissive
marcoslucianops/DeepStream-Yolo
842d5f3545922591357e197014f0d0b2ac4ce1de
f630b10a8088398251bca7f2f50064b57fab06bb
refs/heads/master
2023-06-21T01:16:38.367179
2023-06-16T17:56:18
2023-06-16T17:56:18
251,735,890
1,102
316
MIT
2023-07-02T14:41:15
2020-03-31T21:27:38
C++
UTF-8
C++
false
false
2,820
cpp
/* * Created by Marcos Luciano * https://www.github.com/marcoslucianops */ #include "route_layer.h" nvinfer1::ITensor* routeLayer(int layerIdx, std::string& layers, std::map<std::string, std::string>& block, std::vector<nvinfer1::ITensor*> tensorOutputs, nvinfer1::INetworkDefinition* network) { nvinfer1::ITensor* output; assert(block.at("type") == "route"); assert(block.find("layers") != block.end()); std::string strLayers = block.at("layers"); std::vector<int> idxLayers; size_t lastPos = 0, pos = 0; while ((pos = strLayers.find(',', lastPos)) != std::string::npos) { int vL = std::stoi(trim(strLayers.substr(lastPos, pos - lastPos))); idxLayers.push_back(vL); lastPos = pos + 1; } if (lastPos < strLayers.length()) { std::string lastV = trim(strLayers.substr(lastPos)); if (!lastV.empty()) { idxLayers.push_back(std::stoi(lastV)); } } assert(!idxLayers.empty()); std::vector<nvinfer1::ITensor*> concatInputs; for (uint i = 0; i < idxLayers.size(); ++i) { if (idxLayers[i] < 0) { idxLayers[i] = tensorOutputs.size() + idxLayers[i]; } assert(idxLayers[i] >= 0 && idxLayers[i] < (int)tensorOutputs.size()); concatInputs.push_back(tensorOutputs[idxLayers[i]]); if (i < idxLayers.size() - 1) { layers += std::to_string(idxLayers[i]) + ", "; } } layers += std::to_string(idxLayers[idxLayers.size() - 1]); if (concatInputs.size() == 1) { output = concatInputs[0]; } else { int axis = 1; if (block.find("axis") != block.end()) { axis += std::stoi(block.at("axis")); std::cout << axis << std::endl; } if (axis < 0) { axis += concatInputs[0]->getDimensions().nbDims; } nvinfer1::IConcatenationLayer* concat = network->addConcatenation(concatInputs.data(), concatInputs.size()); assert(concat != nullptr); std::string concatLayerName = "route_" + std::to_string(layerIdx); concat->setName(concatLayerName.c_str()); concat->setAxis(axis); output = concat->getOutput(0); } if (block.find("groups") != block.end()) { nvinfer1::Dims prevTensorDims = output->getDimensions(); int groups = stoi(block.at("groups")); int group_id = stoi(block.at("group_id")); int startSlice = (prevTensorDims.d[1] / groups) * group_id; int channelSlice = (prevTensorDims.d[1] / groups); nvinfer1::ISliceLayer* slice = network->addSlice(*output, nvinfer1::Dims{4, {0, startSlice, 0, 0}}, nvinfer1::Dims{4, {prevTensorDims.d[0], channelSlice, prevTensorDims.d[2], prevTensorDims.d[3]}}, nvinfer1::Dims{4, {1, 1, 1, 1}}); assert(slice != nullptr); std::string sliceLayerName = "slice_" + std::to_string(layerIdx); slice->setName(sliceLayerName.c_str()); output = slice->getOutput(0); } return output; }
[ "marcoslucianops@gmail.com" ]
marcoslucianops@gmail.com
ad2d920410e4ede31c91b6f7c25563c0fe2bc85b
5229c748a3dee5f160bf0f02484dc2979dd996c2
/vmvis codes/consoleclient.h
8f396dfe65a0b1f79f08591640ebdc31658ca463
[]
no_license
vishnumuthu/vmvis
82acecbcd8aeccd7954619202ee7fee0d6ca1f87
20f13dc691d4a539819760b5f5144a756a07fb3a
refs/heads/master
2021-01-10T21:56:53.328634
2015-05-12T09:39:09
2015-05-12T09:39:09
35,479,688
1
1
null
null
null
null
UTF-8
C++
false
false
589
h
#ifndef CONSOLECLIENT_H #define CONSOLECLIENT_H #include <QPlainTextEdit> #include <QScrollBar> #include <QtCore/QDebug> #include "qprinter.h" class consoleclient : public QPlainTextEdit { Q_OBJECT public: explicit consoleclient(QWidget *parent = 0); void putData(const QByteArray &data); public slots: void print(); protected: virtual void keyPressEvent(QKeyEvent *e); virtual void mousePressEvent(QMouseEvent *e); virtual void mouseDoubleClickEvent(QMouseEvent *e); virtual void contextMenuEvent(QContextMenuEvent *e); }; #endif // CONSOLECLIENT_H
[ "v.vishnumuthu@gmail.com" ]
v.vishnumuthu@gmail.com
b579baccd55611b8026f327db1233be26998d006
47933728cd916c6d9de1e2f8afa64c82b197afcb
/gemm_tune/src/templates/zgemm_nt.cpp
a5121c4526f3ec9a8af0603c72cc3c011f574527
[ "LicenseRef-scancode-blas-2017", "Apache-2.0" ]
permissive
TechnikEmpire/ampblas
6742bb054ff4bb213101e266aa2e5d0514882c95
ac461cf8474951034e9d92c82ff98ca245991c07
refs/heads/master
2023-09-03T04:34:46.614195
2012-10-01T21:13:55
2012-10-01T21:13:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
476
cpp
#include "tune.h" #include "template.h" TUNE_NAMESPACE_BEGIN template <> void do_test<dcomplex, transpose::no_trans, transpose::trans>(concurrency::accelerator_view& av, dcomplex alpha, const concurrency::array_view<const dcomplex,2>& a, const concurrency::array_view<const dcomplex,2>& b, dcomplex beta, const concurrency::array_view<dcomplex,2>&c, const std::vector<dcomplex>& c_ref, int offset) { #include "../../data/zgemm_nt.data" } TUNE_NAMESPACE_END
[ "SND\\kyle_spagnoli_cp@4a90e977-6436-4932-9605-20e10c2b6fb3" ]
SND\kyle_spagnoli_cp@4a90e977-6436-4932-9605-20e10c2b6fb3
7141bf55f062bcbd4cf763bc7996b3ff84ef7eaa
cfc4ae42e253687b999a337419b6ef1b29f5347b
/mohawk_dasm.cc
01abdfa2df30b74f56aa1015dced9be1c0ff0d70
[ "MIT" ]
permissive
DrItanium/resource_dasm
4a352ff052931d1c8af7dc855d96f12667dd7509
c4643bf4505a20a5f651a7b66b7a95ba7637e0e1
refs/heads/master
2022-11-29T11:02:37.384534
2020-08-12T02:22:34
2020-08-12T02:22:34
286,889,646
0
0
MIT
2020-08-12T01:49:41
2020-08-12T01:49:41
null
UTF-8
C++
false
false
7,727
cc
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <exception> #include <phosg/Encoding.hh> #include <phosg/Filesystem.hh> #include <phosg/Strings.hh> #include <stdexcept> #include <string> #include <vector> #include "resource_fork.hh" using namespace std; struct mohawk_file_header { uint32_t signature; // 'MHWK' uint32_t remaining_file_size; // == file_size - 8 uint32_t resource_signature; // 'RSRC' uint16_t version; uint16_t unused1; uint32_t file_size; uint32_t resource_dir_offset; uint16_t file_table_offset; // relative to resource dir base uint16_t file_table_size; void byteswap() { this->signature = bswap32(this->signature); this->remaining_file_size = bswap32(this->remaining_file_size); this->resource_signature = bswap32(this->resource_signature); this->version = bswap16(this->version); this->unused1 = bswap16(this->unused1); this->file_size = bswap32(this->file_size); this->resource_dir_offset = bswap32(this->resource_dir_offset); this->file_table_offset = bswap16(this->file_table_offset); this->file_table_size = bswap16(this->file_table_size); } } __attribute__((packed)); struct resource_type_table { uint16_t name_list_offset; uint16_t count; struct type_entry { uint32_t type; uint16_t resource_table_offset; uint16_t name_table_offset; } __attribute__((packed)); type_entry entries[0]; void byteswap() { this->name_list_offset = bswap16(this->name_list_offset); this->count = bswap16(this->count); for (size_t x = 0; x < this->count; x++) { auto& e = this->entries[x]; // note: we intentionally don't byteswap type e.resource_table_offset = bswap16(e.resource_table_offset); e.name_table_offset = bswap16(e.name_table_offset); } } static uint32_t size_for_count(uint16_t count) { return sizeof(resource_type_table) + count * sizeof(type_entry); } } __attribute__((packed)); struct resource_table { uint16_t count; struct resource_entry { uint16_t resource_id; uint16_t file_table_index; } __attribute__((packed)); resource_entry entries[0]; void byteswap() { this->count = bswap16(this->count); for (size_t x = 0; x < this->count; x++) { auto& e = this->entries[x]; e.resource_id = bswap16(e.resource_id); e.file_table_index = bswap16(e.file_table_index); } } static uint32_t size_for_count(uint16_t count) { return sizeof(resource_table) + count * sizeof(resource_entry); } } __attribute__((packed)); struct resource_name_table { uint16_t count; struct name_entry { uint16_t name_offset; uint16_t resource_index; } __attribute__((packed)); name_entry entries[0]; void byteswap() { this->count = bswap16(this->count); for (size_t x = 0; x < this->count; x++) { auto& e = this->entries[x]; e.name_offset = bswap16(e.name_offset); e.resource_index = bswap16(e.resource_index); } } } __attribute__((packed)); struct resource_file_table { uint32_t count; struct file_entry { uint32_t data_offset; uint16_t size_low; uint8_t size_high; uint8_t flags; uint16_t unknown; uint32_t size() const { return this->size_low | (static_cast<uint32_t>(this->size_high) << 16); } } __attribute__((packed)); file_entry entries[0]; void byteswap() { this->count = bswap32(this->count); for (size_t x = 0; x < this->count; x++) { auto& e = this->entries[x]; e.data_offset = bswap32(e.data_offset); e.size_low = bswap16(e.size_low); } } static uint32_t size_for_count(uint16_t count) { return sizeof(resource_file_table) + count * sizeof(file_entry); } } __attribute__((packed)); struct resource_entry { uint32_t type; uint16_t id; uint32_t offset; uint32_t size; resource_entry(uint32_t type, uint16_t id, uint32_t offset, uint32_t size) : type(type), id(id), offset(offset), size(size) { } }; vector<resource_entry> load_index(int fd) { mohawk_file_header h = preadx<mohawk_file_header>(fd, 0); h.byteswap(); if (h.signature != 0x4D48574B) { throw runtime_error("file does not appear to be a mohawk archive"); } if (h.resource_signature != 0x52535243) { throw runtime_error("file does not appear to be a mohawk resource archive"); } uint16_t type_table_count = preadx<uint16_t>(fd, h.resource_dir_offset + 2); type_table_count = bswap16(type_table_count); string type_table_data = preadx(fd, resource_type_table::size_for_count(type_table_count), h.resource_dir_offset); resource_type_table* type_table = reinterpret_cast<resource_type_table*>(const_cast<char*>(type_table_data.data())); type_table->byteswap(); uint32_t file_table_offset = h.resource_dir_offset + h.file_table_offset; uint32_t file_table_count = preadx<uint32_t>(fd, file_table_offset); file_table_count = bswap32(file_table_count); string file_table_data = preadx(fd, resource_file_table::size_for_count(file_table_count), file_table_offset); resource_file_table* file_table = reinterpret_cast<resource_file_table*>(const_cast<char*>(file_table_data.data())); file_table->byteswap(); vector<resource_entry> ret; for (size_t type_index = 0; type_index < type_table->count; type_index++) { const auto& type_table_entry = type_table->entries[type_index]; uint32_t res_table_offset = h.resource_dir_offset + type_table_entry.resource_table_offset; uint16_t res_table_count = preadx<uint16_t>(fd, res_table_offset); res_table_count = bswap16(res_table_count); string res_table_data = preadx(fd, resource_table::size_for_count(res_table_count), res_table_offset); resource_table* res_table = reinterpret_cast<resource_table*>(const_cast<char*>(res_table_data.data())); res_table->byteswap(); for (size_t res_index = 0; res_index < res_table->count; res_index++) { const auto& res_entry = res_table->entries[res_index]; const auto& file_entry = file_table->entries[res_entry.file_table_index - 1]; ret.emplace_back(type_table_entry.type, res_entry.resource_id, file_entry.data_offset, file_entry.size()); } } return ret; } struct resource_data_header { uint32_t signature; uint32_t size; uint32_t type; void byteswap() { this->signature = bswap32(this->signature); this->size = bswap32(this->size); // note: we intentionally don't byteswap the type } } __attribute__((packed)); string get_resource_data(int fd, const resource_entry& e) { resource_data_header h = preadx<resource_data_header>(fd, e.offset); h.byteswap(); return preadx(fd, h.size - 4, e.offset + sizeof(resource_data_header)); } int main(int argc, char* argv[]) { printf("fuzziqer software mohawk archive disassembler\n\n"); if (argc <= 1) { fprintf(stderr, "no filename given\n"); return 1; } scoped_fd fd(argv[1], O_RDONLY); vector<resource_entry> resources = load_index(fd); for (const auto& it : resources) { string filename_prefix = string_printf("%s_%.4s_%hd", argv[1], reinterpret_cast<const char*>(&it.type), it.id); try { string data = get_resource_data(fd, it); save_file(filename_prefix + ".bin", data); printf("... %s.bin\n", filename_prefix.c_str()); } catch (const runtime_error& e) { printf("... %s (FAILED: %s)\n", filename_prefix.c_str(), e.what()); } } return 0; }
[ "mjem@wildblue.net" ]
mjem@wildblue.net
a9531a2ed9773f47634ab3a9a64716fd3a4b1162
d62244cdf3f9edaac1efc0e6e39a3f749140bf68
/src/Widget/RecentWidget.h
f4768543eeb42458eb557a0394cb1d1800f37842
[]
no_license
wurui1994/BiliPlayer
640f6ad312e0be8a329c9aa47a124848636916cc
c4ddbf2550031d9da92e648a06f5a3293abec023
refs/heads/master
2020-03-29T08:39:50.003971
2019-04-03T13:38:33
2019-04-03T13:38:33
146,700,986
0
0
null
null
null
null
UTF-8
C++
false
false
1,210
h
#pragma once #include <QtWidgets/QWidget> #include <QtCore/QPointer> #include <QtWidgets/QMenu> #include "ui_RecentWidget.h" #include "Utils.h" #include "RecentWidgetItem.h" class RecentWidget : public QWidget { Q_OBJECT public: RecentWidget(QWidget *parent = Q_NULLPTR); ~RecentWidget(); RecentWidgetItem* addRecent(Recent const& recent); void removeRecent(Recent const& recent); QList<Recent> recents(); void saveRecents(); void loadRecents(); void resetSelect(); void clearList(); bool nextVideo(); void onNextVideo(); void setIsAutoPlay(bool isAutoPlay); Recent getRecent(QString path); bool isSameFilePath(QString path1, QString path2); bool isAutoPlay(); Q_SIGNALS: void tryOpenFile(QString filePath); void tryOpenRecent(Recent recent); void tryClearList(); protected: void dragEnterEvent(QDragEnterEvent *e) override; void dropEvent(QDropEvent *e) override; protected Q_SLOTS: void on_listWidget_itemClicked(QListWidgetItem *item); void on_clearCheckBox_clicked(bool isChecked); void on_filterCheckBox_clicked(bool isChecked); private: Ui::RecentWidget ui; RecentWidgetItem* m_lastSelect = nullptr; bool m_isAutoPlay = true; };
[ "1341531859@qq.com" ]
1341531859@qq.com
73afc5c5514e5da15703635145a66c6fc01c2593
c67fc9559bae611b8caabdb6f69ad36b8381e742
/task5.cpp
0bb6d78fdb56ca2684204983590524d26889a92f
[]
no_license
Iqra-Shahid/C-projects
8c83116914817d82196a59a586ae0550661a13f3
31c67299db80e223fe39b3b67ccdbd6e79d43184
refs/heads/master
2022-04-26T04:55:46.751927
2020-04-25T08:33:49
2020-04-25T08:33:49
258,717,457
1
0
null
null
null
null
UTF-8
C++
false
false
1,670
cpp
# include <iostream> #include <cmath> using namespace std; int main() { char op; int num1, num2; cout << "Enter two operands -----> "; cin >> num1 >> num2; cout << "Enter operator OR first Letter of Function + - * / % > < Sin Cos Tan -----> "; cin >> op; switch(op) { case '+': cout <<"\n Sum = " <<num1+num2; break; case '-': cout <<"\n Difference = " << num1-num2; break; case '*': cout <<"\n Product = " << num1*num2; break; case '/': cout<<"\n quotation (integer division) = " << num1/num2; break; case '%': cout<<"\n Mod (remainder) = " << num1%num2; break; case '>': if(num1>num2) cout << num1<<" is bigger than "<<num2; else cout << num1<<" is not bigger than "<<num2; break; case '<': if(num1<num2) cout << num1<<" is Less than "<<num2; else cout << num1<<" is not Less than "<<num2; break; case 'S': case 's': cout << "sin ("<<num1<<") = "<<sin(double(num1)); break; case 'C': case 'c': cout << "cos ("<<num1<<") = "<<cos(double(num1)); break; case 'T': case 't': cout << "Tan ("<<num1<<") = "<<tan(double(num1)); break; default: // If the operator is other than +, -, * or /, error message is shown cout << "Error! operator is not correct"; break; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
c1be4123e23d8da7f0332716e0f2d789fbbd6bd8
517b8f53ecc24928a787ab92cb729b7ebe6b3de4
/10905 - Children's Game.cpp
cdd05f5a5bbf8023bac12f13d9303993fdf3676f
[]
no_license
sajalkhan/UVA-ONLINE-JUDGE
4c738fe946d536a5b058da56d8a025be54514856
801ebd2a6366d11226e275210171c66cc4baecfe
refs/heads/master
2021-05-12T08:15:41.628850
2018-01-12T19:32:30
2018-01-12T19:32:30
117,277,417
1
0
null
null
null
null
UTF-8
C++
false
false
528
cpp
/**-----------------------------------------*/ /// Author : sajal Khan /// Daffodil International University /**-----------------------------------------*/ #include<bits/stdc++.h> using namespace std; bool cmp(string i,string j) { return (i+j)>(j+i); } int main() { int n; while(scanf("%d",&n) && n) { string s; string num[100]; for(int i=0; i<n; i++)cin>>num[i]; sort(num,num+n,cmp); for(int i=0; i<n; i++)cout<<num[i]; printf("\n"); } return 0; }
[ "sajalhossen@yahoo.com" ]
sajalhossen@yahoo.com
190f0add17f3ac67c5094a6bb5c8507b6939666b
1cee3bf790b314103da3492b5a88a2bba2185e51
/apunte/src/opt/random-gen.cpp
8168dada550d4446b012d4762414092bc8b655d3
[]
no_license
Taller-de-Programacion/threads
238130754810fa214055c7827b58745729d2dec4
6f6e5891a7e5fb05ff754183e146832db159a882
refs/heads/master
2021-07-14T02:47:50.633353
2020-05-05T22:57:42
2020-05-05T22:57:42
102,299,927
3
2
null
2018-04-12T13:43:45
2017-09-03T23:12:54
C++
UTF-8
C++
false
false
1,122
cpp
#include <fstream> #include <iostream> #include <random> #include <string> #define OUTPUT_FILE_BUFFER_SIZE 1024 static const std::string validChars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEF \n"; char getRandChar(); int main (int argc, char** argv) { if (argc < 2) { std::cout << "Uso: ./random-gen <output-size>" << std::endl; return 1; } int outputSize = std::stoi(argv[1]); std::ofstream output ("random.txt", std::ofstream::binary); char outputBuffer[OUTPUT_FILE_BUFFER_SIZE]; int i = 0; for (; i < outputSize; ++i) { int charPos = i % OUTPUT_FILE_BUFFER_SIZE; if (charPos == 0 && i != 0) { output.write(outputBuffer, OUTPUT_FILE_BUFFER_SIZE); } outputBuffer[charPos] = getRandChar(); } output.write(outputBuffer, i % OUTPUT_FILE_BUFFER_SIZE); output.close(); return 0; } char getRandChar() { static std::default_random_engine generator; static std::uniform_int_distribution<int> distribution(0, validChars.size() - 1); int randPos = distribution(generator); return validChars[randPos]; }
[ "matias@shishi" ]
matias@shishi
0f846308cc88233721f368002eed3a2107cef0ca
60bb67415a192d0c421719de7822c1819d5ba7ac
/blazetest/src/mathtest/smatdmatschur/DCbMDa.cpp
c3ec97d657960183b1c1a8816844e9dd2dc9b6fb
[ "BSD-3-Clause" ]
permissive
rtohid/blaze
48decd51395d912730add9bc0d19e617ecae8624
7852d9e22aeb89b907cb878c28d6ca75e5528431
refs/heads/master
2020-04-16T16:48:03.915504
2018-12-19T20:29:42
2018-12-19T20:29:42
165,750,036
0
0
null
null
null
null
UTF-8
C++
false
false
4,123
cpp
//================================================================================================= /*! // \file src/mathtest/smatdmatschur/DCbMDa.cpp // \brief Source file for the DCbMDa sparse matrix/dense matrix Schur product math test // // 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/DiagonalMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatdmatschur/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'DCbMDa'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions using DCb = blaze::DiagonalMatrix< blaze::CompressedMatrix<TypeB> >; using MDa = blaze::DynamicMatrix<TypeA>; // Creator type definitions using CDCb = blazetest::Creator<DCb>; using CMDa = blazetest::Creator<MDa>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=i; ++j ) { RUN_SMATDMATSCHUR_OPERATION_TEST( CDCb( i, j ), CMDa( i, i ) ); } } // Running tests with large matrices RUN_SMATDMATSCHUR_OPERATION_TEST( CDCb( 67UL, 7UL ), CMDa( 67UL, 67UL ) ); RUN_SMATDMATSCHUR_OPERATION_TEST( CDCb( 128UL, 16UL ), CMDa( 128UL, 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix Schur product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
3aadd5db1f6ac63af5f6ce25d37de54ca4127e01
0a7f0197c47527a6462e244114cf17e96eb0930d
/ESLConsole/darwin/module.hpp
59617e1b2bf11833989d1873d97f907cfebb5e48
[]
no_license
BenzzzX/NESL
b67ed6fa099d0418d99e2bc31404c841bcd076b3
fcb6c80b774852820d0768f3c5370f2da4f0e9c6
refs/heads/master
2021-04-27T19:48:44.607260
2018-08-13T10:46:24
2018-08-13T10:46:24
122,364,692
3
1
null
2018-03-12T11:58:12
2018-02-21T16:52:56
C++
UTF-8
C++
false
false
1,039
hpp
#pragma once /* * Covariant Darwin Universal Character Graphics Library * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2018 Michael Lee(李登淳) * Email: mikecovlee@163.com * Github: https://github.com/mikecovlee */ #include "./adapter.hpp" namespace darwin { platform_adapter *module_resource(); } extern "C" { darwin::platform_adapter *COV_DARWIN_MODULE_MAIN() { return darwin::module_resource(); } }
[ "BenzzZX@outlook.com" ]
BenzzZX@outlook.com
0196eb0e25a67e124d424bd2749e5fdc33844a03
4ac9a9659d0bed177fee3344f81c0c6fcd5423ff
/final-project/src/Data/Filters/ActorFilterName.cpp
4ee23313e096d9adef75c788ec2b0081c9a24c55
[]
no_license
kamaroyl/data-structures-2421
791d4acac54ae5f6ffda5f08f89aafac20a2c4ff
1181c2c193ad11e70a7e54a8d278ce59b803116d
refs/heads/master
2021-06-06T21:54:17.955445
2020-07-14T02:57:26
2020-07-14T02:57:26
146,110,888
0
1
null
null
null
null
UTF-8
C++
false
false
410
cpp
#include "ActorFilterName.hpp" #include "ActorFilter.hpp" #include <iostream> ActorFilterName::ActorFilterName() { this->value = ""; } bool ActorFilterName::filter(Actor* actor) { if(this->value == "") return false; std::size_t found = (actor->getName()).find(this->value); return (found != std::string::npos); } void ActorFilterName::setValue(std::string value) { this->value = value; }
[ "kamaroyl@gmail.com" ]
kamaroyl@gmail.com
87edd5dc1dbee72f41f676626bca5ae27cafa3d7
26bed7abface5f72686bee4269fc6dcb0046cbd4
/devel/MindSpace/MindLink.cpp
feea7680be574bbfef6e71550de000f111ddd7ed
[]
no_license
josiahbryan/mindcore
03747edb3fed6a624f6f574f4888d9671e8cdbea
9b1d1d96e8a2a7a046b4310a4672302777ec0619
refs/heads/master
2021-03-13T00:03:42.919529
2012-07-02T14:04:09
2012-07-02T14:04:09
32,113,540
0
0
null
null
null
null
UTF-8
C++
false
false
6,606
cpp
#include "MindLink.h" #include <QUuid> namespace MindSpace { /* Our static hash containers for UUID->Link types */ QHash<QString,MLinkType> MindSpace::MLinkType::s_linkTypes; QDebug operator<<(QDebug dbg, const MLinkType& type) { dbg.nospace() << "MLinkType(name:" << type.name() <<", uuid:" << type.uuid() << ")"; return dbg.space(); } QDebug operator<<(QDebug dbg, const MTruthValue& value) { dbg.nospace() << "MTruthValue(type:" << (value.type() == MTruthValue::SimpleTruth ? "SimpleTruth" : "RangeTruth") <<", value:" << value.value()<<", rangeA:"<<value.rangeA()<<", rangeB:"<<value.rangeB() << ")"; return dbg.space(); } QDebug operator<<(QDebug dbg, const MLink* link) { return dbg.space() << qPrintable(MLink::toString(link)); } QString MLink::toString(const MLink *link, const MNode *from) { if(!link) return "MLink(0x0)"; if(from) { //type:" << type() <<", node1:" << node1() <<", node2:" << node2() << ", uuid:" << uuid() << " QStringList out = QStringList() << " +-- " << link->type().name(); if(link->type().hasList()) { if(link->node1() == from) out << " --> [ "; else out << " <-- " << MNode::toSimpleString(link->node1(), false) << " = [ "; QStringList sublist; if(link->arguments().isEmpty()) { if(link->node1() == from && link->node2()) sublist << MNode ::toSimpleString(link->node2(), false); else if(link->node2() == from && link->node1()) sublist << MNode ::toSimpleString(link->node1(), false); } else { foreach(MNode *node, link->arguments()) sublist << MNode ::toSimpleString(node, false); } out << sublist.join(" , ") << " ]"; } else { if(link->node1() == from) out << " --> " << MNode::toSimpleString(link->node2(), false); else out << " <-- " << MNode::toSimpleString(link->node1(), false); } double value = link->truthValue().value(); if(value < 1.0) { out << " (Tv:" << QString::number(value) << ")"; } return out.join(""); } else { QStringList out = QStringList() << "type:\"" << link->type().name() <<"\", node1:" << MNode::toString(link->node1(), false) <<", node2:" << MNode::toString(link->node2(), false) << ", uuid:" << link->uuid(); return "MLink(" + out.join("") + ")"; } } /*******************/ /** Creates an empty (null) MLink with the predefined link type 'PartOfLink'. \sa isNull */ MLink::MLink() : QStorableObject() , m_node1(0) , m_node2(0) , m_linkType(MLinkType::PartOfLink()) , m_truthValue() { createUuid(); //if(MSpace *mind = MSpace::activeSpace()) // mind->addLink(this); } /** Creates a new MLink from \a node1 to \a node2 with the givne \a linkType and \a truth value */ MLink::MLink(MNode* node1, MNode* node2, MLinkType linkType, MTruthValue truth) : QStorableObject() , m_node1(0) , m_node2(0) , m_linkType(linkType) , m_truthValue(truth) { createUuid(); setNode1(node1); setNode2(node2); /* if(MSpace *mind = MSpace::activeSpace()) mind->addLink(this);*/ } /** Creates a new MLink from \a node1 to the \a argumentList with the givne \a linkType and \a truth value */ MLink::MLink(MNode* node1, QList<MNode*> argumentList, MLinkType linkType, MTruthValue truth) : QStorableObject() , m_node1(0) , m_node2(0) , m_args() , m_linkType(linkType) , m_truthValue(truth) { createUuid(); setNode1(node1); setArguments(argumentList); /* if(MSpace *mind = MSpace::activeSpace()) mind->addLink(this);*/ } MLink::~MLink() { setNode1(0); setNode2(0); setArguments(QList<MNode*>()); //if(MSpace *mind = MSpace::activeSpace()) // mind->removeLink(this); } /** \return true if BOTH node1() and node2() are NULL. \sa node1, node2 */ bool MLink::isNull() { if(!m_node1 && !m_node2) return true; return false; } /** Set the MLinkType of this link to \a type. \sa type */ void MLink::setType(MindSpace::MLinkType type) { m_linkType = type; } /** Set the first MNode of this link to \a node1. \sa node1 */ void MLink::setNode1(MindSpace::MNode* node1) { if(m_node1) m_node1->removeLink(this); m_node1 = node1; if(node1) node1->addLink(this); } /** Set the second MNode of this link to \a node2. \sa node2 */ void MLink::setNode2(MindSpace::MNode* node2) { if(m_node2) m_node2->removeLink(this); m_node2 = node2; if(node2) node2->addLink(this); } /** Set the MTruthValue of this link to \a value. \sa truthValue */ void MLink::setTruthValue(MindSpace::MTruthValue value) { m_truthValue = value; //qDebug() << "MLink::setTruthValue: "<<this<<": new tv:"<<value.value(); emit truthValueChanged(value); } /** Set the list of argument nodes to \a arguments. \sa arguments */ void MLink::setArguments(QList<MNode*> arguments) { foreach(MNode *node, m_args) node->removeLink(this); m_args = arguments; foreach(MNode *node, arguments) node->addLink(this); } /** Creates a new UUId for this link only if no UUId already assigned. \sa uuid */ void MLink::createUuid() { if(!m_uuid.isEmpty()) return; m_uuid = QUuid::createUuid().toString(); } // From QStorableObject, used to return storable versions of the relevant properties (all except 'uuid' need to be sanitized by these functions) QVariant MLink::storableProperty(QString name) { if(name == "node1") return node1()->uuid(); else if(name == "node2") return node2() ? node2()->uuid() : QString(); else if(name == "arguments") { QVariantList list; foreach(MNode *node, arguments()) list << node->uuid(); return list; } else if(name == "truthValue") return truthValue().toVariant(); else if(name == "type") return type().toVariant(); else return property(qPrintable(name)); } void MLink::setStoredProperty(QString name, QVariant value) { //qDebug() << "MLink::setStoredProperty: "<<name<<value; if(name == "node1") { //qDebug() << "MLink::setStoredProperty: node1: "<<value.toString(); setNode1(MSpace::activeSpace()->uuidToNode(value.toString())); } else if(name == "node2") setNode2(MSpace::activeSpace()->uuidToNode(value.toString())); else if(name == "arguments") { QVariantList list = value.toList(); QList<MNode*> nodeList; foreach(QVariant value, list) nodeList << MSpace::activeSpace()->uuidToNode(value.toString()); setArguments(nodeList); } else if(name == "truthValue") setTruthValue(MTruthValue::fromVariant(value)); else if(name == "type") setType(MLinkType::fromVariant(value)); else if(name == "uuid") // Our Q_PROPERTY defenition doesn't provide a setter for uuid (rightfully so) m_uuid = value.toString(); else setProperty(qPrintable(name), value); } }; // end namespace
[ "josiahbryan@4aa2e13c-404a-5557-5e89-89554693dec9" ]
josiahbryan@4aa2e13c-404a-5557-5e89-89554693dec9
3d5c60fc13640d57302bdea31bf49ca220e30a64
1cb2dd2285c60d28ffcb01ce496bd75ffaa54110
/Voxel/Configuration.h
cebd5e3b94702fe1a9709083ffd7abc603ac1748
[ "BSD-3-Clause" ]
permissive
nickluo/voxelsdk
84553abeda7e777c866a2142f5a2070f24ac19ae
ff9efc71bbaff0fef5726ee00d1f40edcb9d94fc
refs/heads/master
2021-01-21T16:15:10.540915
2015-12-23T09:54:34
2015-12-23T09:56:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,571
h
/* * TI Voxel Lib component. * * Copyright (c) 2014 Texas Instruments Inc. */ #ifndef VOXEL_CONFIGURATION_H #define VOXEL_CONFIGURATION_H #include "Common.h" #include "Serializable.h" #include "DataPacket.h" #define FILE_PREFIX "file:" #define CALIB_DISABLE "calib_disable" namespace Voxel { /** * \ingroup Util */ struct SDKVersion { uint8_t major, minor, patch, abi, conf; }; class VOXEL_EXPORT Configuration { protected: struct _Path { String installPath; String environmentVariable; }; String _sdkPath; String _sdkVersion; Vector<String> _pathKeys; Vector<String> _pathValues; static const Map<String, _Path> _pathTypes; bool _getPaths(const String &type, Vector<String> &paths); bool _get(const String &type, String &name); static bool _addPath(const String &type, const String &path); public: static SDKVersion getSDKVersion(); Configuration(); inline bool getFirmwarePaths(Vector<String> &paths) { return _getPaths("fw", paths); } inline bool getConfPaths(Vector<String> &paths) { return _getPaths("conf", paths); } inline bool getLibPaths(Vector<String> &paths) { return _getPaths("lib", paths); } inline static bool addFirmwarePath(const String &path) { return _addPath("fw", path); } inline static bool addConfPath(const String &path) { return _addPath("conf", path); } inline static bool addLibPath(const String &path) { return _addPath("lib", path); } static bool addPathToEnvironmentVariable(const String &environmentVariable, const String &path, bool prepend = true); inline static bool getEnvironmentVariable(const String &environmentVariable, String &value) { char *p = getenv(environmentVariable.c_str()); if(p) { value = p; return true; } return false; } static bool setEnvironmentVariable(const String &environmentVariable, const String &value); inline static bool setSDKPath(const String &path) { return setEnvironmentVariable("VOXEL_SDK_PATH", path); } inline static bool getSDKPath(String &path) { return getEnvironmentVariable("VOXEL_SDK_PATH", path); } bool getLocalPath(const String &type, String &path); inline bool getLocalFirmwarePath(String &path) { return getLocalPath("fw", path); } inline bool getLocalConfPath(String &path) { return getLocalPath("conf", path); } inline bool getLocalLibPath(String &path) { return getLocalPath("lib", path); } bool getLocalFile(const String &type, String &fileName); inline bool getLocalFirmwareFile(String &fileName) { return getLocalFile("fw", fileName); } inline bool getLocalConfFile(String &fileName) { return getLocalFile("conf", fileName); } inline bool getLocalLibFile(String &fileName) { return getLocalFile("lib", fileName); } /// Updates "name" to full path inline bool getConfFile(String &fileName) { return _get("conf", fileName); } inline bool getFirmwareFile(String &fileName) { return _get("fw", fileName); } inline bool geLibFile(String &fileName) { return _get("lib", fileName); } }; class ConfigurationFile; class VOXEL_EXPORT ConfigSet { protected: bool _get(const String &name, String &value) const; bool _set(const String &name, const String &value); public: Map<String, String> params; Vector<String> paramNames; bool remove(const String &name); bool isEmpty() { return params.size() == 0; } bool isPresent(const String &name) const; String get(const String &name) const; int getInteger(const String &name) const; float getFloat(const String &name) const; bool getBoolean(const String &name) const; bool set(const String &name, const String &value); bool setInteger(const String &name, int value); bool setFloat(const String &name, float value); bool setBoolean(const String &name, bool value); friend class ConfigurationFile; }; struct ConfigDataPacket: public DataPacket { enum PacketType { PACKET_CONFIG = 0, PACKET_2D_DATA_FILE = 1 }; ConfigDataPacket(): DataPacket() {} }; class MainConfigurationFile; class VOXEL_EXPORT ConfigurationFile { protected: bool _get(const String &section, const String &name, String &value) const; bool _set(const String &section, const String &name, const String &value); String _fileName; Map<String, Vector<ByteType>> _dataFiles; MainConfigurationFile *_mainConfigurationFile; int _id, _parentID; String _profileName; mutable Mutex _mutex; bool _serializeAllDataFiles(OutputStream &out); bool _saveAllDataFiles(const String &prefix); template <typename T> bool _getData(const String &fileName, Vector<T> &data); template <typename T> bool _setData(const String &fileName, const Vector<T> &data); bool _copyFromParentIfNotPresent(ConfigurationFile *other, bool recurse = true); public: typedef Map<String, ConfigSet> ConfigSetMap; enum Location { IN_HOST = 0, IN_CAMERA = 1 }; protected: Location _location; public: ConfigSetMap configs; inline Location getLocation() const { return _location; } inline int getID() { return _id; } inline int getParentID() { return _parentID; } inline const String &getProfileName() { return _profileName; } virtual bool isPresent(const String &section, const String &name, bool includeParent = true) const; virtual String get(const String &section, const String &name) const; inline void setID(const int id) { _id = id; setInteger("global", "id", id); } template <typename T> bool getFile(const String &section, const String &name, String &fileName, Vector<T> &data); int getInteger(const String &section, const String &name) const; float getFloat(const String &section, const String &name) const; bool getBoolean(const String &section, const String &name) const; virtual bool set(const String &section, const String &name, const String &value); template <typename T> bool setFile(const String &section, const String &name, const String &fileName, const Vector<T> &data); bool setInteger(const String &section, const String &name, int value); bool setFloat(const String &section, const String &name, float value); bool setBoolean(const String &section, const String &name, bool value); bool remove(const String &section, const String &name); virtual bool getConfigSet(const String &section, const ConfigSet *&configSet) const; virtual bool read(const String &configFile); virtual bool read(InputStream &in); virtual bool write(const String &configFile = ""); virtual bool write(OutputStream &out); bool isValidCameraProfile(); virtual bool removeFile(); inline void clear() { Lock<Mutex> _(_mutex); configs.clear(); } inline const String &getConfigFileName() { return _fileName; } ConfigurationFile(): ConfigurationFile(0) {} ConfigurationFile(MainConfigurationFile *mainConfigurationFile): _mainConfigurationFile(mainConfigurationFile), _id(-1), _parentID(-1), _location(IN_HOST) {} ConfigurationFile(const ConfigurationFile &other) { operator =(other); } inline ConfigurationFile &operator =(const ConfigurationFile &other) { configs = other.configs; _fileName = other._fileName; _mainConfigurationFile = other._mainConfigurationFile; _id = other._id; _profileName = other._profileName; _parentID = other._parentID; _location = other._location; _dataFiles = other._dataFiles; return *this; } inline bool mergeParentConfiguration() { return _copyFromParentIfNotPresent(this); } inline ConfigurationFile &copy(const ConfigurationFile &other) { return operator =(other); } virtual ~ConfigurationFile() {} friend class MainConfigurationFile; }; template <typename T> bool ConfigurationFile::getFile(const String &section, const String &name, String &fileName, Vector<T> &data) { String v = get(section, name); if(v.compare(0, sizeof(FILE_PREFIX) - 1, FILE_PREFIX) != 0 || v.size() <= sizeof(FILE_PREFIX) - 1) { logger(LOG_ERROR) << "ConfigurationFile: section = " << section << ", name = " << name << ", is not a file type." << std::endl; return false; } fileName = v.substr(sizeof(FILE_PREFIX) - 1); return _getData(fileName, data); } template <typename T> bool ConfigurationFile::setFile(const String &section, const String &name, const String &fileName, const Vector<T> &data) { return _setData(fileName, data) && set(section, name, "file:" + fileName); } template <typename T> bool ConfigurationFile::_setData(const String &fileName, const Vector<T> &data) { Configuration c; String f = fileName; if(!c.getLocalConfFile(f)) { logger(LOG_ERROR) << "ConfigurationFile: Failed to locate file '" << fileName << "'" << std::endl; return false; } OutputFileStream fs(f, std::ios::out | std::ios::binary); if(!fs.good()) { logger(LOG_ERROR) << "ConfigurationFile: Could not open file '" << fileName << "'" << std::endl; return false; } fs.write((const char *)data.data(), data.size()*sizeof(T)); fs.close(); _dataFiles[fileName].resize(data.size()*sizeof(T)); memcpy(_dataFiles[fileName].data(), data.data(), data.size()*sizeof(T)); return true; } struct CalibrationInformation { String name; int id; Vector<String> definingParameters; Vector<String> calibrationParameters; }; class VOXEL_EXPORT MainConfigurationFile: public ConfigurationFile { protected: Map<int, ConfigurationFile> _cameraProfiles; Map<int, String> _cameraProfileNames; int _defaultCameraProfileID, _defaultCameraProfileIDInHardware; int _currentCameraProfileID; ConfigurationFile *_currentCameraProfile; bool _updateCameraProfileList(); String _mainConfigName, _hardwareID; int _getNewCameraProfileID(bool inHost = true); public: struct ConfigSerialNumberType { uint8_t major, minor; }; typedef Function<bool(ConfigSerialNumberType &, TimeStampType &, SerializedObject &)> HardwareSerializer; protected: bool _saveHardwareImage(ConfigSerialNumberType &serialNumber, TimeStampType &timestamp, SerializedObject &so); HardwareSerializer _hardwareReader, _hardwareWriter; Map<String, CalibrationInformation> _calibrationInformation; public: MainConfigurationFile(const String &name, const String &hardwareID, HardwareSerializer hardwareReader = nullptr, HardwareSerializer hardwareWriter = nullptr): _currentCameraProfile(nullptr), _defaultCameraProfileID(-1), _defaultCameraProfileIDInHardware(-1), _mainConfigName(name), _hardwareReader(hardwareReader), _hardwareWriter(hardwareWriter) {} virtual bool read(const String &configFile); bool readFromHardware(); bool writeToHardware(); inline bool hasHardwareConfigurationSupport() { return _hardwareReader && _hardwareWriter; } inline void setHardwareReader(HardwareSerializer hardwareReader) { _hardwareReader = hardwareReader; } inline void setHardwareWriter(HardwareSerializer hardwareWriter) { _hardwareWriter = hardwareWriter; } virtual String get(const String &section, const String &name) const; virtual bool isPresent(const String &section, const String &name, bool includeParent = true) const; int addCameraProfile(const String &profileName, const int parentID = -1); bool setCurrentCameraProfile(const int id); bool removeCameraProfile(const int id); bool saveCameraProfileToHardware(int &id); ConfigurationFile *getDefaultCameraProfile(); ConfigurationFile *getCameraProfile(const int id); template <typename T> bool getFile(const String &section, const String &name, String &fileName, Vector<T> &data); inline int getDefaultCameraProfileID() { if(_defaultCameraProfileIDInHardware >= 0) return _defaultCameraProfileIDInHardware; else return _defaultCameraProfileID; } inline int getDefaultCameraProfileIDInHost() { return _defaultCameraProfileID; } inline int getDefaultCameraProfileIDInCamera() { return _defaultCameraProfileID; } bool setDefaultCameraProfile(const int id); inline void setHardwareID(const String &hwID) { _hardwareID = hwID; } inline int getCurrentProfileID() { return _currentCameraProfileID; } bool getCameraProfileName(const int id, String &cameraProfileName); inline const Map<int, String> &getCameraProfileNames() { return _cameraProfileNames; } inline const Map<String, CalibrationInformation> &getCalibrationInformation() const { return _calibrationInformation; } virtual ~MainConfigurationFile() {} friend class ConfigurationFile; friend class DepthCamera; }; template <typename T> bool ConfigurationFile::_getData(const String &fileName, Vector<T> &data) { bool loadFromFile = false; if(_dataFiles.find(fileName) == _dataFiles.end()) { if(_mainConfigurationFile && _parentID >= 0) { ConfigurationFile *parentConfig = _mainConfigurationFile->getCameraProfile(_parentID); // TODO This does not handle circular references between profiles if(parentConfig && parentConfig->_getData<T>(fileName, data)) return true; else loadFromFile = true; } else loadFromFile = true; } if(loadFromFile) { Configuration c; String f = fileName; if(!c.getConfFile(f)) { logger(LOG_ERROR) << "ConfigurationFile: Could not locate file '" << fileName << "'" << std::endl; return false; } InputFileStream fs(f, std::ios::in | std::ios::binary | std::ios::ate); if(!fs.good()) { logger(LOG_ERROR) << "ConfigurationFile: Could not open file '" << fileName << "'" << std::endl; return false; } int size = fs.tellg(); if(size == 0) { logger(LOG_ERROR) << "ConfigurationFile: Null config data '" << f << "'" << std::endl; return false; } Vector<ByteType> &d = _dataFiles[fileName]; d.resize(size); fs.seekg(std::ios::beg); fs.clear(); fs.read((char *)d.data(), size); } Vector<ByteType> &d = _dataFiles[fileName]; data.resize((d.size() + sizeof(T)/2)/sizeof(T)); memcpy(data.data(), d.data(), d.size()); return true; } template <typename T> bool MainConfigurationFile::getFile(const String &section, const String &name, String &fileName, Vector<T> &data) { if(!_currentCameraProfile || !_currentCameraProfile->getFile(section, name, fileName, data)) return ConfigurationFile::getFile(section, name, fileName, data); else return true; } } #endif // CONFIGURATION_H
[ "gadiyar@ti.com" ]
gadiyar@ti.com
ce32763c459aa3b29f00d0fef5d9f6a5d7726fe6
dd4a1d4ab74076c19e20a7620995b2b5baa00d48
/silbot3_src/silbot3_core/src/device/server/handler/LEDHandler.cpp
0f08f3eefd3452a0ac798f839d2c7720e5b29202
[]
no_license
AnastasiyaRybakova/simulation_sb3_navi
27289b0ee675de4223eb7d78b0d4f2e10eab94b5
19e1e6eaa97698b7103d68d2418663f03159a64b
refs/heads/master
2020-03-21T07:22:39.107573
2018-06-22T08:31:01
2018-06-22T08:31:01
138,276,737
0
0
null
null
null
null
UTF-8
C++
false
false
770
cpp
#include "LEDHandler.h" using namespace cir::devicenode; LEDHandler::LEDHandler() { initHandler(); _ledServerProxy = new CLightEmittingDiodeERobot(); } LEDHandler::~LEDHandler() { } void LEDHandler::initHandler() { this->_ledSubscriber = this->_nodeHandle.subscribe<silbot3_msgs::Device_LED_Msg>("/DeviceNode/LED/commands", 1000, &LEDHandler::ledSubscribeCallback, this); ROS_DEBUG("LED handler created - /DeviceNode/LED/commands"); } void LEDHandler::ledSubscribeCallback(const silbot3_msgs::Device_LED_Msg::ConstPtr& message) { string command = message->command; ROS_DEBUG("[LEDHandler] receive a message - %s", command.c_str()); _ledServerProxy->on(message->id, message->bright, message->red, message->green, message->blue); }
[ "minhhud@ust.ac.kr" ]
minhhud@ust.ac.kr
4ef02cfda6e915a7d9b8ce05248e5d0f1e0b18c8
bbb88a637a46b610e51afa2fb57525412c758b19
/Villkorssatser/ein.cpp
d9136f24e56ac5869d745491b0a8b21fa0889790
[]
no_license
Bovince/Programmering
e94d6273545ac0796acf30454fc8c41b256711c4
0049585ae94d0fbdc6da0df026530e77e31305d5
refs/heads/master
2020-03-27T15:44:33.902947
2019-04-11T13:07:43
2019-04-11T13:07:43
146,736,151
0
0
null
null
null
null
UTF-8
C++
false
false
867
cpp
#include <iostream> using namespace std; int main() { int tal1, tal2; cout << "Skriv två tal" << endl; cin >> tal1; cout << endl; cin >> tal2; cout << endl; if(tal1<tal2) { cout << "De störe talet är: " << tal2; } else if(tal1>tal2) { cout << "De störe talet är: " << tal1; } else if(tal1==tal2*2) { cout << "Tal 1 är dubbelt så stort " << tal1; } else if(tal2==tal1*2) { cout << "Tal 2 är dubbelt så stort " << tal1; } else if(tal1>tal2) { cout << "De störe talet är: " << tal1; } else if(tal1>tal2) { cout << "De störe talet är: " << tal1; }else if(tal1>tal2) { cout << "De störe talet är: " << tal1; } else if(tal1>tal2) { cout << "De störe talet är: " << tal1; } else if(tal1>tal2) { cout << "De störe talet är: " << tal1; } else { cout << "Talen är lika stora"; } return 0; }
[ "vibo1001@live.mark.se" ]
vibo1001@live.mark.se
db09a24d11bf9d633107614577029b5e634efa67
d4b17a1dde0309ea8a1b2f6d6ae640e44a811052
/include/algorithms/neural_networks/layers/relu/relu_layer_forward.h
f51422eddd548bd67ced17f451fe3fd128653f70
[ "Apache-2.0", "Intel" ]
permissive
h2oai/daal
c50f2b14dc4a9ffc0b7f7bcb40b599cadac6d333
d49815df3040f3872a1fdb9dc99ee86148e4494e
refs/heads/daal_2018_beta_update1
2023-05-25T17:48:44.312245
2017-09-29T13:30:10
2017-09-29T13:30:10
96,125,165
2
3
null
2017-09-29T13:30:11
2017-07-03T15:26:26
C++
UTF-8
C++
false
false
8,045
h
/* file: relu_layer_forward.h */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* //++ // Implementation of the interface for the forward rectified linear unit (ReLU) layer // in the batch processing mode //-- */ #ifndef __RELU_LAYER_FORWARD_H__ #define __RELU_LAYER_FORWARD_H__ #include "algorithms/algorithm.h" #include "data_management/data/tensor.h" #include "services/daal_defines.h" #include "algorithms/neural_networks/layers/layer.h" #include "algorithms/neural_networks/layers/relu/relu_layer_types.h" #include "algorithms/neural_networks/layers/relu/relu_layer_forward_types.h" namespace daal { namespace algorithms { namespace neural_networks { namespace layers { /** * \brief Contains classes for the relu layer */ namespace relu { /** * \brief Contains classes for the forward relu layer */ namespace forward { namespace interface1 { /** * @defgroup relu_layers_forward_batch Batch * @ingroup relu_layers_forward * @{ */ /** * <a name="DAAL-CLASS-ALGORITHMS__NEURAL_NETWORKS__LAYERS__RELU__FORWARD__BATCHCONTAINER"></a> * \brief Class containing methods for the forward relu layer using algorithmFPType precision arithmetic */ template<typename algorithmFPType, Method method, CpuType cpu> class DAAL_EXPORT BatchContainer : public AnalysisContainerIface<batch> { public: /** * Constructs a container for the forward ReLU layer with a specified environment * in the batch processing mode * \param[in] daalEnv Environment object */ BatchContainer(daal::services::Environment::env *daalEnv); /** Default destructor */ ~BatchContainer(); /** * Computes the result of the forward ReLU layer in the batch processing mode * * \return Status of computations */ services::Status compute() DAAL_C11_OVERRIDE; }; /** * <a name="DAAL-CLASS-ALGORITHMS__NEURAL_NETWORKS__LAYERS__RELU__FORWARD__BATCH"></a> * \brief Computes the results of the forward relu layer in the batch processing mode * <!-- \n<a href="DAAL-REF-RELUFORWARD-ALGORITHM">Forward relu layer description and usage models</a> --> * * \tparam algorithmFPType Data type to use in intermediate computations for the forward relu layer, double or float * \tparam method The forward relu layer computation method, \ref Method * * \par Enumerations * - \ref Method Computation methods for the forward relu layer * - \ref forward::InputId Identifiers of input objects for the forward relu layer * - \ref forward::ResultId Identifiers of result objects for the forward relu layer * - \ref forward::ResultLayerDataId Identifiers of extra results computed by the forward relu layer * - \ref LayerDataId Identifiers of collection in result objects for the forward relu layer * * \par References * - \ref backward::interface1::Batch "backward::Batch" class */ template<typename algorithmFPType = DAAL_ALGORITHM_FP_TYPE, Method method = defaultDense> class Batch : public layers::forward::LayerIfaceImpl { public: typedef layers::forward::LayerIfaceImpl super; Parameter &parameter; /*!< relu layer \ref interface1::Parameter "parameters" structure */ Input input; /*!< %Input objects of the layer */ /** Default constructor */ Batch() : parameter(_defaultParameter) { initialize(); }; /** * Constructs a forward relu layer in the batch processing mode * and initializes its parameter with the provided parameter * \param[in] parameter Parameter to initialize the parameter of the layer */ Batch(Parameter& parameter) : parameter(parameter), _defaultParameter(parameter) { initialize(); } /** * Constructs a forward relu layer by copying input objects * and parameters of another forward relu layer in the batch processing mode * \param[in] other Algorithm to use as the source to initialize the input objects * and parameters of the algorithm */ Batch(const Batch<algorithmFPType, method> &other) : super(other), _defaultParameter(other.parameter), parameter(_defaultParameter), input(other.input) { initialize(); } /** * Returns method of the forward relu layer * \return Method of the forward relu layer */ virtual int getMethod() const DAAL_C11_OVERRIDE { return(int) method; } /** * Returns the structure that contains input objects of the forward relu layer * \return Structure that contains input objects of the forward relu layer */ virtual Input *getLayerInput() DAAL_C11_OVERRIDE { return &input; } /** * Returns the structure that contains parameters of the forward relu layer * \return Structure that contains parameters of the forward relu layer */ virtual Parameter *getLayerParameter() DAAL_C11_OVERRIDE { return &parameter; }; /** * Returns the structure that contains results of the forward relu layer * \return Structure that contains results of the forward relu layer */ layers::forward::ResultPtr getLayerResult() DAAL_C11_OVERRIDE { return getResult(); } /** * Returns the structure that contains the result of the forward relu layer * \return Structure that contains the result of forward relu layer */ ResultPtr getResult() { return _result; } /** * Registers user-allocated memory to store results of the forward relu layer * \param[in] result Structure to store results of the forward relu layer * * \return Status of computations */ services::Status setResult(const ResultPtr& result) { DAAL_CHECK(result, services::ErrorNullResult) _result = result; _res = _result.get(); return services::Status(); } /** * Returns a pointer to the newly allocated forward relu layer * with a copy of input objects of this forward relu layer * \return Pointer to the newly allocated algorithm */ services::SharedPtr<Batch<algorithmFPType, method> > clone() const { return services::SharedPtr<Batch<algorithmFPType, method> >(cloneImpl()); } /** * Allocates memory to store the result of the forward relu layer * * \return Status of computations */ virtual services::Status allocateResult() DAAL_C11_OVERRIDE { services::Status s = this->_result->template allocate<algorithmFPType>(&(this->input), &parameter, (int) method); this->_res = this->_result.get(); return s; } protected: virtual Batch<algorithmFPType, method> *cloneImpl() const DAAL_C11_OVERRIDE { return new Batch<algorithmFPType, method>(*this); } void initialize() { Analysis<batch>::_ac = new __DAAL_ALGORITHM_CONTAINER(batch, BatchContainer, algorithmFPType, method)(&_env); _in = &input; _par = &parameter; _result = ResultPtr(new Result()); } private: ResultPtr _result; Parameter _defaultParameter; }; /** @} */ } // namespace interface1 using interface1::BatchContainer; using interface1::Batch; } // namespace forward } // namespace relu } // namespace layers } // namespace neural_networks } // namespace algorithms } // namespace daal #endif
[ "vasily.rubtsov@intel.com" ]
vasily.rubtsov@intel.com
9a2d9c6ed335b2fbb1efac80a5cd56dafffdd4f9
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/enduser/zone_internetgames/src/client/shell/include/zgdi.h
94a65f91599aab9eaff95c27c018e4dfd4eb6f27
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
11,014
h
#pragma once #include <atlgdi.h> #include <DataStore.h> #ifndef _INC_VFW //!! hmm. #pragma message ("NOTE: You can speed compilation by including <vfw.h> in stdafx.h") #include <vfw.h> #endif #pragma comment(lib, "vfw32.lib") ///////////////////////////////////////////////////////////////////////////// // CDrawDC - usefull when you are given a DC (such as ATLs Draw()) and // therefore don't want to call DeleteObject() class CDrawDC : public CDC { public: CDrawDC(HDC hDC = NULL, BOOL bAutoRestore = TRUE) : CDC(hDC, bAutoRestore) { } ~CDrawDC() { if ( m_hDC != NULL ) { if(m_bAutoRestore) RestoreAllObjects(); Detach(); } } }; class CZoneFont : public CFont { public: HFONT CreateFont(ZONEFONT& zf,BYTE bItalic = FALSE, BYTE bUnderline = FALSE ,BYTE bStrikeOut = FALSE) { return CreateFont( zf.lfHeight, zf.lfFaceName, zf.lfWeight, bItalic, bUnderline, bStrikeOut ); } HFONT CreateFont(LONG nPointSize, LPCTSTR lpszFaceName, LONG nWeight, BYTE bItalic = FALSE, BYTE bUnderline = FALSE ,BYTE bStrikeOut = FALSE) { //!! hmm. Should I ask for the DC too? LOGFONT logFont; memset(&logFont, 0, sizeof(LOGFONT)); logFont.lfCharSet = DEFAULT_CHARSET; // If font size > 0, it is a fixed pixel size, otherwise it is a // true logical font size which respects the user's "large font" setting. if ( nPointSize > 0 ) logFont.lfHeight = -MulDiv(nPointSize, 96, 72); else { CWindowDC dc(NULL); logFont.lfHeight = MulDiv(nPointSize, dc.GetDeviceCaps(LOGPIXELSY), 72); } logFont.lfWeight = nWeight; logFont.lfItalic = bItalic; logFont.lfUnderline = bUnderline; logFont.lfStrikeOut = bStrikeOut; lstrcpyn(logFont.lfFaceName, lpszFaceName, sizeof(logFont.lfFaceName)/sizeof(TCHAR)); return CreateFontIndirect(&logFont); } // Font degredation HFONT SelectFont(ZONEFONT& zfPreferred, ZONEFONT&zfBackup, CDC& dc, BYTE bItalic = FALSE, BYTE bUnderline = FALSE ,BYTE bStrikeOut = FALSE) { // select the Preferred font if it is available, otherwise blindly // select the Backup font CreateFont(zfPreferred, bItalic, bUnderline, bStrikeOut); HFONT hOldFont = dc.SelectFont(m_hFont); TCHAR lfFaceName[LF_FACESIZE]; dc.GetTextFace(lfFaceName, LF_FACESIZE); //Return the original font to the DC dc.SelectFont( hOldFont ); if ( !lstrcmpi(lfFaceName, zfPreferred.lfFaceName) ) { return m_hFont; } DeleteObject(); CreateFont(zfBackup, bItalic, bUnderline, bStrikeOut); #if _DEBUG hOldFont = dc.SelectFont(m_hFont); dc.GetTextFace(lfFaceName, LF_FACESIZE); ASSERT(!lstrcmpi(lfFaceName, zfBackup.lfFaceName)); dc.SelectFont( hOldFont ); #endif return m_hFont; } int GetHeight(); }; // global functions for ordinary CBitmap too // extern CSize GetBitmapSize(CBitmap& Bitmap); extern bool DrawBitmap(CDC& dc, CBitmap& Bitmap, const CRect* rcDst=NULL, const CRect* rcSrc=NULL); extern HRESULT DrawDynTextToBitmap(HBITMAP hbm, IDataStore *pIDS, CONST TCHAR *szKey); extern void GetScreenRectWithMonitorFromWindow( HWND hWnd, CRect* prcOut ); extern void GetScreenRectWithMonitorFromRect( CRect* prcIn, CRect* prcOut ); //////////////// // CDib implements Device Independent Bitmaps as a form of CBitmap. // class CDib : public CBitmap { protected: BITMAP m_bm; // stored for speed DIBSECTION m_ds; // cached CPalette m_pal; // palette HDRAWDIB m_hdd; // for DrawDib public: CDib(); ~CDib(); long Width() { return m_bm.bmWidth; } long Height() { return m_bm.bmHeight; } CSize GetSize() { return CSize(m_bm.bmWidth, m_bm.bmHeight); } CRect GetRect() { return CRect(CPoint(0,0), GetSize()); } bool Attach(HBITMAP hbm); bool LoadBitmap(LPCTSTR lpResourceName, IResourceManager *pResMgr = NULL); bool LoadBitmap(UINT uID, IResourceManager *pResMgr = NULL) { return LoadBitmap(MAKEINTRESOURCE(uID), pResMgr); } bool LoadBitmapWithText(LPCTSTR lpResourceName, IResourceManager *pResMgr, IDataStore *pIDS, CONST TCHAR *szKey = NULL); bool LoadBitmapWithText(UINT uID, IResourceManager *pResMgr, IDataStore *pIDS, CONST TCHAR *szKey = NULL) { return LoadBitmapWithText(MAKEINTRESOURCE(uID), pResMgr, pIDS, szKey); } // Universal Draw function can use DrawDib or not. bool Draw(CDC& dc, const CRect* rcDst=NULL, const CRect* rcSrc=NULL, bool bUseDrawDib=TRUE, HPALETTE hPal=NULL, bool bForeground=FALSE); void DeleteObject(); bool CreatePalette(CPalette& pal); HPALETTE GetPalette() { return m_pal; } UINT GetColorTable(RGBQUAD* colorTab, UINT nColors); bool CreateCompatibleDIB( CDC& dc, const CSize& size) { return CreateCompatibleDIB(dc, size.cx, size.cy); } bool CreateCompatibleDIB( CDC& dc, long width, long height) { struct { BITMAPINFOHEADER bmiHeader; WORD bmiColors[256]; // need some space for a color table WORD unused[256]; // extra space, just in case } bmi; int nSizePalette = 0; // Assume no palette initially if (dc.GetDeviceCaps(RASTERCAPS) & RC_PALETTE) { _ASSERTE(dc.GetDeviceCaps(SIZEPALETTE) == 256); nSizePalette = 256; } memset(&bmi.bmiHeader, 0, sizeof(BITMAPINFOHEADER)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = height; //!! bmi.bmiHeader.biPlanes = dc.GetDeviceCaps(PLANES); // bmi.bmiHeader.biBitCount = dc.GetDeviceCaps(BITSPIXEL); bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = dc.GetDeviceCaps(BITSPIXEL) * dc.GetDeviceCaps(PLANES); bmi.bmiHeader.biCompression = BI_RGB; //bmi.bmiHeader.biSizeImage = 0; header already zero'd //bmi.bmiHeader.biXPelsPerMeter = 0; //bmi.bmiHeader.biYPelsPerMeter = 0; //bmi.bmiHeader.biClrUsed = 0; // implies full palette specified, if palette required //bmi.bmiHeader.biClrImportant = 0; // fill out the color table. Not used if a true color device void* pBits; if(bmi.bmiHeader.biBitCount == 8) { WORD* pIndexes = bmi.bmiColors; for (int i = 0; i < 256; i++) *pIndexes++ = i; Attach(CreateDIBSection(dc, (BITMAPINFO*)&bmi, DIB_PAL_COLORS, &pBits, NULL, 0)); } else Attach(CreateDIBSection(dc, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, &pBits, NULL, 0)); _ASSERTE(m_hBitmap != NULL); return ( m_hBitmap != NULL ); #if 0 // Create device context m_hDC = CreateCompatibleDC( NULL ); if ( !m_hDC ) return E_FAIL; m_hOldPalette = SelectPalette( m_hDC, palette, FALSE ); // fill in bitmapinfoheader bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 8; bmi.bmiHeader.biCompression = 0; bmi.bmiHeader.biSizeImage = WidthBytes( width * 8 ) * height; bmi.bmiHeader.biClrUsed = 0; bmi.bmiHeader.biClrImportant = 0; bmi.bmiHeader.biXPelsPerMeter = 0; bmi.bmiHeader.biYPelsPerMeter = 0; // fill in palette pIdx = (WORD*) bmi.bmiColors; for ( int i = 0; i < 256; i++ ) { *pIdx++ = (WORD) i; } // create section m_hBmp = CreateDIBSection( m_hDC, (BITMAPINFO*) &bmi, DIB_PAL_COLORS, (void**) &m_pBits, NULL, 0 ); if ( !m_hBmp ) { DeleteBitmap(); return E_FAIL; } if ( !GetObject( m_hBmp, sizeof(DIBSECTION), &m_DS ) ) { DeleteBitmap(); return E_FAIL; } m_lPitch = WidthBytes( m_DS.dsBmih.biBitCount * m_DS.dsBmih.biWidth ); m_hOldBmp = SelectObject( m_hDC, m_hBmp ); return NOERROR; #endif } }; #if 0 //!! missing transparency functionality. // if we decide we need it, I plan on having a CImage class where an // image is a CDib plus transparency. // functions for offscreen blting? // creating a compatible DC, appropriate Dib, etc. HRESULT CDibSection::SetColorTable( CPalette& palette ) { PALETTEENTRY* palColors; RGBQUAD dibColors[256], *pDibColors; int i; // Convert palette entries to dib color table palColors = palette.GetLogPalette()->palPalEntry; pDibColors = dibColors; for ( i = 0; i < 256; i++ ) { pDibColors->rgbRed = palColors->peRed; pDibColors->rgbGreen = palColors->peGreen; pDibColors->rgbBlue = palColors->peBlue; pDibColors->rgbReserved = 0; pDibColors++; palColors++; } // Attach color table to dib section if ( m_hOldPalette ) SelectPalette( m_hDC, m_hOldPalette, FALSE ); m_hOldPalette = SelectPalette( m_hDC, palette, FALSE ); if (SetDIBColorTable( m_hDC, 0, 256, dibColors ) != 256) return E_FAIL; return NOERROR; } //!! hmm. Do we want remapping functionality? HRESULT CDib::RemapToPalette( CPalette& palette, BOOL bUseIndex ) { BYTE map[256]; PALETTEENTRY* pe; BYTE* bits; RGBQUAD* dibColors; DWORD i; // Create dib to palette translation table dibColors = m_pBMI->bmiColors; for ( i = 0; i < 256; i++ ) { map[i] = GetNearestPaletteIndex( palette, RGB( dibColors->rgbRed, dibColors->rgbGreen, dibColors->rgbBlue ) ); dibColors++; } if ( m_iTransIdx >= 0 ) { map[ m_iTransIdx ] = palette.GetTransparencyIndex(); m_iTransIdx = palette.GetTransparencyIndex(); } // run bits through translation table bits = m_pBits; for ( i = 0; i < m_pBMI->bmiHeader.biSizeImage; i++ ) *bits++ = map[ *bits ]; // reset dib's color table to palette if ( bUseIndex ) { m_iColorTableUsage = DIB_PAL_COLORS; dibColors = m_pBMI->bmiColors; for ( i = 0; i < 256; i++ ) { *((WORD*) dibColors) = (WORD) i; dibColors++; } } else { m_iColorTableUsage = DIB_RGB_COLORS; pe = palette.GetLogPalette()->palPalEntry; dibColors = m_pBMI->bmiColors; for ( i = 0; i < 256; i++ ) { dibColors->rgbRed = pe->peRed; dibColors->rgbGreen = pe->peGreen; dibColors->rgbBlue = pe->peBlue; dibColors->rgbReserved = 0; dibColors++; pe++; } } // we're done return NOERROR; } #endif ///////////////////////////////////////////////////////////////////////////// // COffscreenBitmapDC - an offscreen bitmap compatible // therefore don't want to call DeleteObject() class CMemDC : public CDC { CDib m_dib; public: ~CMemDC() { if(m_bAutoRestore) RestoreAllObjects(); } HDC CreateOffscreenBitmap(const CSize& size, HPALETTE hPalette = NULL, HDC hDC = NULL) { return CreateOffscreenBitmap( size.cx, size.cy, hPalette, hDC); } HDC CreateOffscreenBitmap(long width, long height, HPALETTE hPalette = NULL, HDC hDC = NULL) { ATLASSERT(m_hDC == NULL); m_hDC = ::CreateCompatibleDC(hDC); if ( hPalette ) { SelectPalette( hPalette, TRUE); RealizePalette(); } m_dib.CreateCompatibleDIB(*this, width, height); SelectBitmap(m_dib); return m_hDC; } };
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
1eee1a686f30ad26be148ab6920e0e8ee34ca4a5
b9fd9ed02312be96e05ef23243c4dfac1392be08
/tensorflow/core/grappler/optimizers/layout_optimizer.cc
e4af71c40ace855f3c58846b47903bedc81c35d0
[ "Apache-2.0" ]
permissive
RLeili/tensorflow
9e5650b5d02771da94a345ceb97b4f3293638e1e
42ee949d022d8665cf2e908e800f1ef1594c6abf
refs/heads/master
2021-04-09T11:51:32.393739
2019-10-16T16:44:23
2019-10-16T16:44:23
125,318,700
0
0
Apache-2.0
2018-03-15T05:50:05
2018-03-15T05:50:04
null
UTF-8
C++
false
false
76,518
cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <deque> #include <unordered_set> #include "tensorflow/core/framework/attr_value.pb.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/framework/tensor.pb.h" #include "tensorflow/core/framework/tensor_shape.pb.h" #include "tensorflow/core/grappler/clusters/cluster.h" #include "tensorflow/core/grappler/devices.h" #include "tensorflow/core/grappler/grappler_item.h" #include "tensorflow/core/grappler/op_types.h" #include "tensorflow/core/grappler/optimizers/layout_optimizer.h" #include "tensorflow/core/grappler/utils.h" #include "tensorflow/core/grappler/utils/frame.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { namespace grappler { namespace { const char kSuffix[] = "LayoutOptimizer"; const char kPermNHWCToNCHW[] = "PermConstNHWCToNCHW"; const char kPermNCHWToNHWC[] = "PermConstNCHWToNHWC"; const char kTransposeNHWCToNCHW[] = "TransposeNHWCToNCHW"; const char kTransposeNCHWToNHWC[] = "TransposeNCHWToNHWC"; const char kDimMapNHWCToNCHW[] = "DimMapNHWCToNCHW"; const char kDimMapNCHWToNHWC[] = "DimMapNCHWToNHWC"; const char kVecPermuteNHWCToNCHW[] = "VecPermuteNHWCToNCHW"; const char kVecPermuteNCHWToNHWC[] = "VecPermuteNCHWToNHWC"; const char kReshapeNHWCToNCHW[] = "ReshapeNHWCToNCHW"; const char kReshapeConst[] = "ReshapeConst"; std::set<string> GetOpsFormatSupported() { std::set<string> ops_format_supported = { "AvgPool", "AvgPoolGrad", "Conv2D", "Conv2DBackpropFilter", "Conv2DBackpropInput", "BiasAdd", "BiasAddGrad", "DepthwiseConv2dNative", "DepthwiseConv2dNativeBackpropInput", "DepthwiseConv2dNativeBackpropFilter", "FusedBatchNorm", "FusedBatchNormV2", "FusedBatchNormGrad", "FusedBatchNormGradV2", "FusedConv2DBiasActivation", "MaxPool", "MaxPoolV2", "MaxPoolGrad", "MaxPoolGradGrad", "MaxPoolGradV2", "MaxPoolGradGradV2", "SpaceToDepth", "DepthToSpace"}; return ops_format_supported; } std::set<string> GetOpsFormatAgnostic() { std::set<string> ops_format_agnostic = {"Abs", "Add", "AddN", "AddV2", "Acos", "Acosh", "All", "Angle", "Any", "ApproximateEqual", "Asin", "Asinh", "Atan", "Atan2", "Atanh", "Betainc", "Bitcast", "Cast", "Ceil", "CheckNumerics", "Complex", "ComplexAbs", "Concat", "ConcatV2", "Conj", "Cos", "Cosh", "Digamma", "Div", "Elu", "EluGrad", "Enter", "Equal", "Erf", "Erfc", "Exit", "Exp", "Expm1", "Fill", "Floor", "FloorDiv", "FloorMod", "Greater", "GreaterEqual", "GuaranteeConst", "HistogramSummary", "Identity", "IdentityN", "Igamma", "Igammac", "Imag", "Inv", "InvGrad", "IsFinite", "IsInf", "IsNan", "Less", "LessEqual", "Lgamma", "Log", "LogicalAnd", "LogicalNot", "LogicalOr", "Log1p", "Max", "Maximum", "Mean", "Merge", "Min", "Minimum", "Mod", "Mul", "Neg", "NextIteration", "NotEqual", "OnesLike", "Pad", "PreventGradient", "Prod", "Polygamma", "Pow", "Real", "RealDiv", "Reciprocal", "ReciprocalGrad", "Relu", "Relu6", "Relu6Grad", "ReluGrad", "Rint", "Select", "Selu", "SeluGrad", "Shape", "ShapeN", "Sigmoid", "SigmoidGrad", "Sign", "Sin", "Sinh", "Slice", "Snapshot", "Softplus", "SoftplusGrad", "Split", "SplitV", "StridedSlice", "StridedSliceGrad", "Switch", "Tile", "TruncateDiv", "TruncateMod", "ReverseV2", "Round", "Rsqrt", "RsqrtGrad", "Sqrt", "SqrtGrad", "Square", "SquaredDifference", "Squeeze", "StopGradient", "Sub", "Sum", "Tan", "Tanh", "TanhGrad", "ZerosLike", "Zeta"}; return ops_format_agnostic; } bool EndWith(const string& str, const string& ending) { if (str.size() < ending.size()) return false; if (str.substr(str.size() - ending.size(), ending.size()) == ending) return true; return false; } bool IsNodeByLayoutOptimizer(const string& node_name) { const string suffix = kSuffix; return EndWith(node_name, suffix); } bool IsNodeType(const string& node_name, const string& type) { const string suffix = strings::StrCat(type, "-", kSuffix); return EndWith(node_name, suffix); } bool IsTransposeNHWCToNCHW(const string& node_name) { return IsNodeType(node_name, kTransposeNHWCToNCHW); } bool IsTransposeNCHWToNHWC(const string& node_name) { return IsNodeType(node_name, kTransposeNCHWToNHWC); } bool IsDimMapNHWCToNCHW(const string& node_name) { return IsNodeType(node_name, kDimMapNHWCToNCHW); } bool IsDimMapNCHWToNHWC(const string& node_name) { return IsNodeType(node_name, kDimMapNCHWToNHWC); } bool IsVecPermuteNHWCToNCHW(const string& node_name) { return IsNodeType(node_name, kVecPermuteNHWCToNCHW); } bool IsVecPermuteNCHWToNHWC(const string& node_name) { return IsNodeType(node_name, kVecPermuteNCHWToNHWC); } bool IsConcat(const NodeDef& node) { const auto op = node.op(); return op == "Concat" || op == "ConcatV2"; } bool IsConcatV1(const NodeDef& node) { const auto op = node.op(); return op == "Concat"; } bool IsMaxPoolV2(const NodeDef& node) { const auto& op = node.op(); return op == "MaxPoolV2"; } bool IsMaxPoolGradV1(const NodeDef& node) { const auto& op = node.op(); return op == "MaxPoolGrad"; } bool IsMaxPoolGradV2(const NodeDef& node) { const auto& op = node.op(); return op == "MaxPoolGradV2"; } bool IsMaxPoolGradGradV1(const NodeDef& node) { const auto& op = node.op(); return op == "MaxPoolGradGrad"; } bool IsMaxPoolGradGradV2(const NodeDef& node) { const auto& op = node.op(); return op == "MaxPoolGradGradV2"; } bool IsUnaryGrad(const NodeDef& node) { bool is_unary_grad = IsEluGrad(node) || IsInvGrad(node) || IsReciprocalGrad(node) || IsRelu6Grad(node) || IsReluGrad(node) || IsRsqrtGrad(node) || IsSeluGrad(node) || IsSigmoidGrad(node) || IsSoftplusGrad(node) || IsSoftsignGrad(node) || IsSqrtGrad(node) || IsTanhGrad(node); return is_unary_grad; } bool IsComparisonOp(const NodeDef& node) { bool is_compare = IsApproximateEqual(node) || IsEqual(node) || IsGreater(node) || IsGreaterEqual(node) || IsLess(node) || IsLessEqual(node) || IsNotEqual(node); return is_compare; } bool IsLogicalOp(const NodeDef& node) { return IsLogicalAnd(node) || IsLogicalNot(node) || IsLogicalOr(node); } bool IsReduceOp(const NodeDef& node) { return IsSum(node) || IsMean(node) || IsProd(node) || IsMax(node) || IsMin(node) || IsAll(node) || IsAny(node); } bool IsBinaryOp(const NodeDef& node) { bool is_binary = IsAdd(node) || IsAtan2(node) || IsComparisonOp(node) || IsComplex(node) || IsDiv(node) || IsFloorDiv(node) || IsIgamma(node) || IsIgammac(node) || IsLogicalAnd(node) || IsLogicalOr(node) || IsMaximum(node) || IsMinimum(node) || IsMod(node) || IsMul(node) || IsPolygamma(node) || IsPow(node) || IsRealDiv(node) || IsSquaredDifference(node) || IsSub(node) || IsTruncateDiv(node) || IsTruncateMod(node) || IsZeta(node); return is_binary; } std::vector<int> NonControlInputs(const NodeDef& node) { std::vector<int> pos; for (int i = 0; i < node.input_size(); i++) { if (!IsControlInput(node.input(i))) { pos.push_back(i); } } return pos; } std::vector<int> DataInputPosConcat(const NodeDef& node) { int n = node.attr().at("N").i(); std::vector<int> input_pos; int start = (IsConcatV1(node)) ? 1 : 0; int end = start + n; for (int i = start; i < end; i++) { input_pos.push_back(i); } return input_pos; } std::vector<int> DataInputPos(const NodeDef& node) { if (IsSplit(node) || IsHistogramSummary(node)) { return {1}; } if (IsStridedSliceGrad(node)) { return {4}; } if (IsBinaryOp(node) || IsUnaryGrad(node)) { return {0, 1}; } if (IsBetainc(node) || IsSelect(node)) { return {0, 1, 2}; } if (IsShapeN(node) || IsIdentityN(node) || IsAddN(node) || IsMerge(node)) { return NonControlInputs(node); } if (IsConcat(node)) { return DataInputPosConcat(node); } if (node.input_size() > 0 && !IsControlInput(node.input(0))) { return {0}; } return {}; } class GraphProcessor { public: GraphProcessor(const GraphProperties& graph_properties, const VirtualPlacer& virtual_placer, const std::unordered_set<string>& nodes_to_preserve, GraphDef* graph, NodeMap* node_map) : graph_properties_(graph_properties), virtual_placer_(virtual_placer), nodes_to_preserve_(nodes_to_preserve), graph_(graph), node_map_(node_map) {} protected: NodeDef* AddNodePermConst(const string& name, const string& device, const std::vector<int>& permutation) { NodeDef* node = graph_->add_node(); node_map_->AddNode(name, node); node->set_name(name); node->set_op("Const"); AttrValue attr_data_type; attr_data_type.set_type(DT_INT32); node->mutable_attr()->insert({"dtype", attr_data_type}); AttrValue attr_tensor; Tensor tensor(DT_INT32, TensorShape({4})); for (int i = 0; static_cast<size_t>(i) < permutation.size(); i++) { tensor.flat<int>()(i) = permutation[i]; } tensor.AsProtoTensorContent(attr_tensor.mutable_tensor()); node->mutable_attr()->insert({"value", attr_tensor}); string device_name; if (device.empty()) { device_name = virtual_placer_.get_canonical_device_name(*node); } else { device_name = device; } node->set_device(device_name); return node; } NodeDef* AddNodeConstScalar(const string& name, const string& device, DataType dtype, int value) { NodeDef* node = graph_->add_node(); node_map_->AddNode(name, node); node->set_name(name); node->set_op("Const"); AttrValue attr_data_type; attr_data_type.set_type(dtype); node->mutable_attr()->insert({"dtype", attr_data_type}); AttrValue attr_tensor; Tensor tensor(dtype, TensorShape({})); tensor.scalar<int>()() = value; tensor.AsProtoTensorContent(attr_tensor.mutable_tensor()); node->mutable_attr()->insert({"value", attr_tensor}); string device_name; if (device.empty()) { device_name = virtual_placer_.get_canonical_device_name(*node); } else { device_name = device; } node->set_device(device_name); return node; } string LayoutOptimizerNode(const string& base_name) { return strings::StrCat(base_name, "-", kSuffix); } const GraphProperties& graph_properties_; const VirtualPlacer& virtual_placer_; const std::unordered_set<string>& nodes_to_preserve_; GraphDef* graph_; NodeMap* node_map_; }; struct OptimizeContext { OptimizeContext(GraphDef* graph, NodeDef* node, NodeMap* node_map, const GraphProperties& graph_properties, const VirtualPlacer& virtual_placer, const std::unordered_set<string>& nodes_to_preserve, bool is_in_frame) : graph(graph), node(node), node_map(node_map), graph_properties(graph_properties), virtual_placer(virtual_placer), nodes_to_preserve(nodes_to_preserve), is_in_frame(is_in_frame) {} GraphDef* graph; NodeDef* node; NodeMap* node_map; const GraphProperties& graph_properties; const VirtualPlacer& virtual_placer; const std::unordered_set<string>& nodes_to_preserve; bool is_in_frame; }; class NodeProcessor : public GraphProcessor { public: explicit NodeProcessor(const OptimizeContext& opt_cxt) : GraphProcessor(opt_cxt.graph_properties, opt_cxt.virtual_placer, opt_cxt.nodes_to_preserve, opt_cxt.graph, opt_cxt.node_map), node_(opt_cxt.node), is_in_frame_(opt_cxt.is_in_frame) {} virtual ~NodeProcessor() {} virtual Status ConvertNode() { if (ShouldProcess()) { UpdateAttrDataFormat(); UpdateAttrKSize(); UpdateAttrStrides(); UpdateAttrShape(); TF_RETURN_IF_ERROR(AddLayoutTransposeToInputs()); TF_RETURN_IF_ERROR(AddLayoutTransposeToOutputs()); TF_RETURN_IF_ERROR(CustomizedProcessing()); } return Status::OK(); } protected: bool IsPortDimsN(const NodeDef& node, int port, int n) const { if (node.attr().find("_output_shapes") != node.attr().end()) { if (node.attr().at("_output_shapes").list().shape_size() > port) { auto shape = node.attr().at("_output_shapes").list().shape(port); if (shape.unknown_rank()) { return false; } if (shape.dim_size() == n) { return true; } } } return false; } bool IsPortZeroDimsN(const NodeDef& node, int n) const { return IsPortDimsN(node, 0, n); } bool IsPortZeroDimsFour(const NodeDef& node) const { return NodeProcessor::IsPortZeroDimsN(node, 4) || IsTransposeNCHWToNHWC(node.name()); } bool IsPortDimsFour(const NodeDef& node, int port) const { return NodeProcessor::IsPortDimsN(node, port, 4) || IsTransposeNCHWToNHWC(node.name()); } bool IsNHWC() const { if (node_->attr().find("data_format") != node_->attr().end()) { if (node_->attr().at("data_format").s().compare("NHWC") == 0) { return true; } } return false; } bool HasOutputs() const { auto outputs = node_map_->GetOutputs(node_->name()); return !outputs.empty(); } Status HasAttribute(const NodeDef& node, const string& attr) const { if (node.attr().find(attr) == node.attr().end()) { return Status(error::INVALID_ARGUMENT, strings::StrCat("Missing attribute ", attr)); } return Status::OK(); } bool MustPreserve() const { return nodes_to_preserve_.find(node_->name()) != nodes_to_preserve_.end(); } bool IsOnGPU() const { string device_name; if (node_->device().empty()) { device_name = virtual_placer_.get_canonical_device_name(*node_); } else { device_name = node_->device(); } string device; string not_used; if (DeviceNameUtils::SplitDeviceName(device_name, &not_used, &device) && (StringPiece(str_util::Lowercase(device))) .contains(str_util::Lowercase(DEVICE_GPU))) { return true; } return false; } virtual bool ShouldProcess() const { return !MustPreserve() && IsNHWC() && IsPortZeroDimsFour(*node_) && HasOutputs() && IsOnGPU(); } virtual void UpdateAttrShape() { if (node_->attr().find("_output_shapes") != node_->attr().end()) { for (const auto& pos : GetOutputPos()) { auto shape = node_->mutable_attr() ->at("_output_shapes") .mutable_list() ->mutable_shape(pos); if (shape->dim_size() == 4) { int64 h = shape->dim(1).size(); int64 w = shape->dim(2).size(); int64 c = shape->dim(3).size(); shape->mutable_dim(1)->set_size(c); shape->mutable_dim(2)->set_size(h); shape->mutable_dim(3)->set_size(w); } } } } Status UpdateAttrValueOfInput(int input_index, bool permute) { auto input_node = node_map_->GetNode(node_->input(input_index)); // We created a copy of the node, so that we don't modify the original node, // which might be used elsewhere. Note that this copy also copies the // control dependency input in the case this node is inside a loop, // to ensure added_node is in the same frame with node_. NodeDef* added_node = graph_->add_node(); *added_node = *input_node; string base_name = strings::StrCat(node_->name(), "-", input_index); string node_name = LayoutOptimizerNode(base_name); added_node->set_name(node_name); *node_->mutable_input(input_index) = node_name; node_map_->AddNode(node_name, added_node); node_map_->AddOutput(node_name, node_->name()); return UpdateAttrValue(added_node, permute); } virtual std::vector<int> GetInputPos() const { return {0}; } virtual std::set<int> GetOutputPos() const { // For most nodes, no need to process control nodes or nodes that use an // output other than the first output: only the first output is of // 4D NCHW/NHWC format and thus relevant here. std::set<int> output_pos = {0}; return output_pos; } virtual Status AddLayoutTransposeToInputs() { std::vector<int> input_pos = GetInputPos(); for (const auto& pos : input_pos) { string node_name = LayoutOptimizerNode( strings::StrCat(node_->name(), "-", pos, "-", kTransposeNHWCToNCHW)); DataType dtype = graph_properties_.GetInputProperties(node_->name())[pos].dtype(); auto input_node = node_map_->GetNode(node_->input(pos)); TF_RETURN_IF_ERROR(HasAttribute(*input_node, "_output_shapes")); string const_name = GetOrAddNodePermNHWCToNCHW(pos); int output_pos; ParseNodeName(node_->input(pos), &output_pos); AddNodeTranspose( node_name, node_->input(pos), const_name, dtype, input_node->attr().at("_output_shapes").list().shape(output_pos), true); node_map_->UpdateOutput(NodeName(node_->input(pos)), node_->name(), node_name); node_map_->AddOutput(node_name, node_->name()); *node_->mutable_input(pos) = node_name; } return Status::OK(); } Status AddTransformToOutputs(const string& op) { auto outputs = node_map_->GetOutputs(node_->name()); string const_name = GetOrAddNodePermNCHWToNHWC(); int output_count = 0; for (const auto& output : outputs) { int connections = 0; int connections_removed = 0; for (int i = 0; i < output->input_size(); i++) { auto& input = *output->mutable_input(i); int input_port; string input_name = ParseNodeName(input, &input_port); auto output_pos = GetOutputPos(); if (input_name == node_->name()) { connections++; if (output_pos.find(input_port) != output_pos.end()) { connections_removed++; string added_node_base_name = strings::StrCat(node_->name(), "-", output_count, "-", i); string added_node_name; DataType dtype = graph_properties_.GetOutputProperties(node_->name())[input_port] .dtype(); if (op == "Transpose") { added_node_name = LayoutOptimizerNode(strings::StrCat( added_node_base_name, "-", kTransposeNCHWToNHWC)); TF_RETURN_IF_ERROR(HasAttribute(*node_, "_output_shapes")); AddNodeTranspose( added_node_name, input, const_name, dtype, node_->attr().at("_output_shapes").list().shape(input_port), false); } else if (op == "DataFormatVecPermute") { added_node_name = LayoutOptimizerNode(strings::StrCat( added_node_base_name, "-", kVecPermuteNCHWToNHWC)); AddNodeDataFormatOp(added_node_name, input, op, dtype, false); } else { return errors::InvalidArgument("Unsupported op type: ", op); } input = added_node_name; node_map_->AddOutput(node_->name(), added_node_name); node_map_->AddOutput(added_node_name, output->name()); } } } if (connections == connections_removed) { node_map_->RemoveOutput(node_->name(), output->name()); } output_count++; } return Status::OK(); } virtual Status AddLayoutTransposeToOutputs() { return AddTransformToOutputs("Transpose"); } virtual Status CustomizedProcessing() { return Status::OK(); } Status UpdateOrTransformParamInput(int param_index, const string& op, DataType dtype) { auto param_node = node_map_->GetNode(node_->input(param_index)); bool permute = (op == "DataFormatVecPermute") ? true : false; if (IsConstant(*param_node)) { TF_RETURN_IF_ERROR(UpdateAttrValueOfInput(param_index, permute)); } else { AddDataFormatTranformToParamInput(op, param_index, dtype); } return Status::OK(); } NodeDef* node_; bool is_in_frame_; private: void UpdateAttrKSize() { if (node_->attr().find("ksize") != node_->attr().end()) { auto list = node_->mutable_attr()->at("ksize").mutable_list(); UpdateTuple(list); } } void UpdateAttrStrides() { if (node_->attr().find("strides") != node_->attr().end()) { auto list = node_->mutable_attr()->at("strides").mutable_list(); UpdateTuple(list); } } void UpdateAttrDataFormat() { if (node_->attr().find("data_format") != node_->attr().end()) { if (node_->attr().at("data_format").s().compare("NHWC") == 0) { string* data_format = node_->mutable_attr()->at("data_format").mutable_s(); *data_format = "NCHW"; } } } Status UpdateAttrValue(NodeDef* node, bool permute) { TF_RETURN_IF_ERROR(HasAttribute(*node, "value")); Tensor tensor; auto success = tensor.FromProto(node->mutable_attr()->at({"value"}).tensor()); if (!success) { LOG(ERROR) << "Failed to parse TensorProto."; } if (permute) { if (tensor.dims() == 1) { if (tensor.flat<int>().size() == 4) { int c = tensor.flat<int>()(3); tensor.flat<int>()(3) = tensor.flat<int>()(2); tensor.flat<int>()(2) = tensor.flat<int>()(1); tensor.flat<int>()(1) = c; } else { return Status(error::INVALID_ARGUMENT, strings::StrCat("Unsupported tensor size: ", tensor.flat<int>().size())); } } else if (tensor.dims() == 2) { for (int i = 0; i < 2; i++) { int c = tensor.matrix<int>()(3, i); tensor.matrix<int>()(3, i) = tensor.matrix<int>()(2, i); tensor.matrix<int>()(2, i) = tensor.matrix<int>()(1, i); tensor.matrix<int>()(1, i) = c; } } else { return Status( error::INVALID_ARGUMENT, strings::StrCat("Unsupported dimension size: ", tensor.dims())); } } else { for (int i = 0; i < tensor.flat<int>().size(); i++) { int value = tensor.flat<int>()(i); value = (value >= 0) ? value : value + 4; if (value == 1 || value == 2) { value = value + 1; } else if (value == 3) { value = 1; } tensor.flat<int>()(i) = value; } } if (tensor.dims() == 0) { tensor.AsProtoField(node->mutable_attr()->at({"value"}).mutable_tensor()); } else { tensor.AsProtoTensorContent( node->mutable_attr()->at({"value"}).mutable_tensor()); } return Status::OK(); } NodeDef* AddNodeTranspose(const string& node_name, const string& input_name, const string& const_name, DataType data_type, const TensorShapeProto& input_shape, bool NHWCToNCHW) { NodeDef* node = graph_->add_node(); node_map_->AddNode(node_name, node); node->set_name(node_name); *node->add_input() = input_name; *node->add_input() = const_name; node->set_op("Transpose"); node->set_device(node_->device()); AttrValue attr_data_type; attr_data_type.set_type(data_type); node->mutable_attr()->insert({"T", attr_data_type}); AttrValue attr_data_type_perm; attr_data_type_perm.set_type(DT_INT32); node->mutable_attr()->insert({"Tperm", attr_data_type_perm}); if (!input_shape.unknown_rank()) { AttrValue attr_output_shape; auto output_shape = attr_output_shape.mutable_list()->add_shape(); if (NHWCToNCHW) { output_shape->add_dim()->set_size(input_shape.dim(0).size()); output_shape->add_dim()->set_size(input_shape.dim(3).size()); output_shape->add_dim()->set_size(input_shape.dim(1).size()); output_shape->add_dim()->set_size(input_shape.dim(2).size()); } else { output_shape->add_dim()->set_size(input_shape.dim(0).size()); output_shape->add_dim()->set_size(input_shape.dim(2).size()); output_shape->add_dim()->set_size(input_shape.dim(3).size()); output_shape->add_dim()->set_size(input_shape.dim(1).size()); } node->mutable_attr()->insert({"_output_shapes", attr_output_shape}); } return node; } NodeDef* AddNodePermNHWCToNCHW(const string& base_name, const string& depended_node, const string& device) { string name = LayoutOptimizerNode(strings::StrCat(base_name, "-", kPermNHWCToNCHW)); auto const_node = AddNodePermConst(name, device, {0, 3, 1, 2}); // This is to ensure the transpose node and the const node are in the // same frame. *const_node->add_input() = AsControlDependency(depended_node); return const_node; } NodeDef* AddNodePermNCHWToNHWC(const string& base_name, const string& depended_node, const string& device) { auto const_node = AddNodePermConst( LayoutOptimizerNode(strings::StrCat(base_name, "-", kPermNCHWToNHWC)), device, {0, 2, 3, 1}); // This is to ensure the transpose node and the const node are in the same // frame. *const_node->add_input() = AsControlDependency(depended_node); return const_node; } string GetOrAddNodePermNHWCToNCHW(int pos) { string const_name; if (is_in_frame_) { string base_name = strings::StrCat(node_->name(), "-", pos); string input = NodeName(node_->input(pos)); string depended_node; if (!IsTransposeNCHWToNHWC(input)) { depended_node = input; } else { auto input_node = node_map_->GetNode(input); depended_node = NodeName(input_node->input(0)); } auto const_node = AddNodePermNHWCToNCHW(base_name, depended_node, node_->device()); const_name = const_node->name(); } else { const_name = LayoutOptimizerNode(kPermNHWCToNCHW); } return const_name; } string GetOrAddNodePermNCHWToNHWC() { string const_name; if (is_in_frame_) { auto const_node = AddNodePermNCHWToNHWC(node_->name(), node_->name(), node_->device()); const_name = const_node->name(); } else { const_name = LayoutOptimizerNode(kPermNCHWToNHWC); } return const_name; } void UpdateTuple(AttrValue_ListValue* list) { int64 h = list->i(1); int64 w = list->i(2); int64 c = list->i(3); list->set_i(1, c); list->set_i(2, h); list->set_i(3, w); } NodeDef* AddNodeDataFormatOp(const string& name, const string& input_name, const string& op, DataType dtype, bool nhwc_to_nchw) { NodeDef* added_node = graph_->add_node(); added_node->set_name(name); added_node->set_op(op); node_map_->AddNode(added_node->name(), added_node); added_node->set_device(node_->device()); AttrValue attr_data_type; attr_data_type.set_type(dtype); added_node->mutable_attr()->insert({"T", attr_data_type}); string src_format = (nhwc_to_nchw) ? "NHWC" : "NCHW"; string dst_format = (nhwc_to_nchw) ? "NCHW" : "NHWC"; AttrValue attr_format; attr_format.set_s(src_format); added_node->mutable_attr()->insert({"src_format", attr_format}); attr_format.set_s(dst_format); added_node->mutable_attr()->insert({"dst_format", attr_format}); *added_node->add_input() = input_name; return added_node; } void AddDataFormatTranformToParamInput(const string& op, int input_pos, DataType dtype) { string suffix = (op == "DataFormatVecPermute") ? kVecPermuteNHWCToNCHW : kDimMapNHWCToNCHW; string name = LayoutOptimizerNode( strings::StrCat(node_->name(), "-", input_pos, "-", suffix)); auto added_node = AddNodeDataFormatOp(name, node_->input(input_pos), op, dtype, true); *node_->mutable_input(input_pos) = added_node->name(); node_map_->UpdateOutput(NodeName(added_node->input(0)), node_->name(), added_node->name()); node_map_->AddOutput(added_node->name(), node_->name()); } }; class AvgPoolGradProcessor : public NodeProcessor { public: explicit AvgPoolGradProcessor(const OptimizeContext& opt_cxt) : NodeProcessor(opt_cxt) {} protected: std::vector<int> GetInputPos() const override { return {1}; } Status CustomizedProcessing() override { return UpdateOrTransformParamInput(0, "DataFormatVecPermute", DT_INT32); } }; class BiasAddGradProcessor : public NodeProcessor { public: explicit BiasAddGradProcessor(const OptimizeContext& opt_cxt) : NodeProcessor(opt_cxt) {} protected: bool ShouldProcess() const override { if (MustPreserve()) { return false; } if (!IsOnGPU()) { return false; } auto input = node_map_->GetNode(node_->input(0)); if (input) { int port; ParseNodeName(node_->input(0), &port); if (IsNHWC() && IsPortDimsFour(*input, port)) { return true; } } return false; } Status AddLayoutTransposeToOutputs() override { return Status::OK(); } }; class Conv2DProcessor : public NodeProcessor { public: Conv2DProcessor(const OptimizeContext& opt_cxt, bool no_gemm) : NodeProcessor(opt_cxt), no_gemm_(no_gemm) {} protected: bool ShouldProcess() const override { return !MustPreserve() && IsNHWC() && IsPortZeroDimsFour(*node_) && HasOutputs() && (!IsGemmUsed() || no_gemm_) && IsOnGPU(); } TensorShapeProto GetShape(const string& input_name) const { string node_name; int output_pos; node_name = ParseNodeName(input_name, &output_pos); NodeDef* node = node_map_->GetNode(node_name); if (node->attr().find("_output_shapes") != node->attr().end()) { return node->attr().at("_output_shapes").list().shape(output_pos); } TensorShapeProto shape; return shape; } bool IsStrideOne() const { if (node_->attr().find("strides") != node_->attr().end()) { auto list = node_->attr().at("strides").list(); return list.i(1) == 1 && list.i(2) == 1; } return false; } bool IsValidPadding() const { if (node_->attr().find("padding") != node_->attr().end()) { auto padding = node_->attr().at("padding").s(); return padding == "VALID"; } return false; } // The logic inside this function is based on the internal implementation of // Conv2D, Conv2DBackpropInput, and Conv2DBackpropFilter ops, and thus // needs to be updated accordingly if the internal implementation changes. bool IsGemmUsed(const TensorShapeProto& filter_shape, const TensorShapeProto& input_shape) const { if (filter_shape.dim_size() == 4) { if (filter_shape.dim(0).size() == 1 && filter_shape.dim(1).size() == 1 && IsStrideOne()) { return true; } } if (input_shape.dim_size() == 4 && filter_shape.dim_size() == 4) { if (input_shape.dim(1).size() == filter_shape.dim(0).size() && input_shape.dim(2).size() == filter_shape.dim(1).size() && IsValidPadding()) { return true; } } return false; } virtual bool IsGemmUsed() const { auto filter_shape = GetShape(node_->input(1)); auto input_shape = GetShape(node_->input(0)); return IsGemmUsed(filter_shape, input_shape); } bool no_gemm_; }; class Conv2DBackpropFilterProcessor : public Conv2DProcessor { public: Conv2DBackpropFilterProcessor(const OptimizeContext& opt_cxt, bool no_gemm) : Conv2DProcessor(opt_cxt, no_gemm) {} protected: bool IsGemmUsed() const override { auto filter_shape = GetShape(node_->name()); auto input_shape = GetShape(node_->input(0)); return Conv2DProcessor::IsGemmUsed(filter_shape, input_shape); } std::vector<int> GetInputPos() const override { return {0, 2}; } Status AddLayoutTransposeToOutputs() override { return Status::OK(); } // No need to update output shape, as it is always of shape // [filter_height, filter_width, in_channels, out_channels], regardless of // whether NCHW or NHWC is used. void UpdateAttrShape() override {} }; class Conv2DBackpropInputProcessor : public Conv2DProcessor { public: Conv2DBackpropInputProcessor(const OptimizeContext& opt_cxt, bool no_gemm) : Conv2DProcessor(opt_cxt, no_gemm) {} protected: bool IsGemmUsed() const override { auto filter_shape = GetShape(node_->input(1)); auto input_shape = GetShape(node_->name()); return Conv2DProcessor::IsGemmUsed(filter_shape, input_shape); } std::vector<int> GetInputPos() const override { return {2}; } Status CustomizedProcessing() override { return UpdateOrTransformParamInput(0, "DataFormatVecPermute", DT_INT32); } }; class FusedBatchNormGradProcessor : public NodeProcessor { public: explicit FusedBatchNormGradProcessor(const OptimizeContext& opt_cxt) : NodeProcessor(opt_cxt) {} protected: bool ShouldProcess() const override { return NodeProcessor::ShouldProcess() && IsTraining(); } std::vector<int> GetInputPos() const override { return {0, 1}; } private: bool IsTraining() const { if (node_->attr().find("is_training") != node_->attr().end()) { if (node_->attr().at("is_training").b()) { return true; } } return false; } }; class MaxPoolGradProcessor : public NodeProcessor { public: explicit MaxPoolGradProcessor(const OptimizeContext& opt_cxt) : NodeProcessor(opt_cxt) {} protected: std::vector<int> GetInputPos() const override { return {0, 1, 2}; } }; class MaxPoolGradV2Processor : public MaxPoolGradProcessor { public: explicit MaxPoolGradV2Processor(const OptimizeContext& opt_cxt) : MaxPoolGradProcessor(opt_cxt) {} protected: Status CustomizedProcessing() override { for (int i = 3; i <= 4; i++) { TF_RETURN_IF_ERROR( UpdateOrTransformParamInput(i, "DataFormatVecPermute", DT_INT32)); } return Status::OK(); } }; class MaxPoolV2Processor : public NodeProcessor { public: explicit MaxPoolV2Processor(const OptimizeContext& opt_cxt) : NodeProcessor(opt_cxt) {} protected: bool ShouldProcess() const override { // We check data_input's shape instead, because the shape inference of // MaxPoolV2 is not able to infer the shape when ksize or strides is not // constant. auto data_input = node_map_->GetNode(node_->input(0)); int port; ParseNodeName(node_->input(0), &port); return !MustPreserve() && IsNHWC() && IsPortDimsFour(*data_input, port) && HasOutputs() && IsOnGPU(); } Status CustomizedProcessing() override { for (int i = 1; i <= 2; i++) { TF_RETURN_IF_ERROR( UpdateOrTransformParamInput(i, "DataFormatVecPermute", DT_INT32)); } return Status::OK(); } }; class AgnosticNodeProcessor : public NodeProcessor { public: explicit AgnosticNodeProcessor(const OptimizeContext& opt_cxt) : NodeProcessor(opt_cxt) {} protected: bool ShouldProcess() const override { return !MustPreserve() && IsPortZeroDimsFour(*node_) && HasOutputs() && IsNodeAfterNCHWToNHWC() && IsOnGPU(); } bool IsNodeAfterNCHWToNHWC(const NodeDef& node) const { std::set<string> ops_format_agnostic = GetOpsFormatAgnostic(); std::deque<NodeDef*> queue; auto data_node_pos = DataInputPos(node); std::unordered_set<string> visited; for (const auto& pos : data_node_pos) { auto input_node = node_map_->GetNode(node.input(pos)); queue.push_back(input_node); visited.insert(input_node->name()); } // The code will exit this while loop in one iteration in most cases, as the // graph is already topologically sorted. while (!queue.empty()) { NodeDef* current_node = queue.front(); queue.pop_front(); if (IsTransposeNCHWToNHWC(current_node->name()) || IsDimMapNCHWToNHWC(current_node->name()) || IsVecPermuteNCHWToNHWC(current_node->name())) { return true; } // We only continue searching if the path is connected through // format-agnostic nodes. if (ops_format_agnostic.find(current_node->op()) != ops_format_agnostic.end()) { auto current_node_pos = DataInputPos(*current_node); for (const auto& pos : current_node_pos) { auto input_node = node_map_->GetNode(current_node->input(pos)); if (visited.find(input_node->name()) == visited.end()) { queue.push_back(input_node); visited.insert(input_node->name()); } } } } return false; } bool IsNodeAfterNCHWToNHWC() const { return IsNodeAfterNCHWToNHWC(*node_); } }; class AddNProcessor : public AgnosticNodeProcessor { public: explicit AddNProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: std::vector<int> GetInputPos() const override { return NonControlInputs(*node_); } }; class BinaryOpProcessor : public AgnosticNodeProcessor { public: explicit BinaryOpProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: bool ShouldProcess() const override { return !MustPreserve() && IsPortZeroDimsFour(*node_) && HasOutputs() && IsNodeAfterNCHWToNHWC() && (IsNDOperateWithMD(4, 0) || IsNDOperateWithMD(4, 1) || IsNDOperateWithMD(4, 4) || IsNDOperateWithMD(0, 4) || IsNDOperateWithMD(1, 4)) && IsOnGPU(); } std::vector<int> GetInputPos() const override { std::vector<int> input_pos; auto input0 = node_map_->GetNode(node_->input(0)); auto input1 = node_map_->GetNode(node_->input(1)); int input0_port; ParseNodeName(node_->input(0), &input0_port); int input1_port; ParseNodeName(node_->input(1), &input1_port); if (IsPortDimsFour(*input0, input0_port)) { input_pos.push_back(0); } if (IsPortDimsFour(*input1, input1_port)) { input_pos.push_back(1); } return input_pos; } bool IsNDOperateWithMD(int n, int m) const { auto input0 = node_map_->GetNode(node_->input(0)); auto input1 = node_map_->GetNode(node_->input(1)); int input0_port; ParseNodeName(node_->input(0), &input0_port); int input1_port; ParseNodeName(node_->input(1), &input1_port); if (input0 && input1) { bool input0_is_n = (n == 4) ? IsPortDimsFour(*input0, input0_port) : IsPortDimsN(*input0, input0_port, n); bool input1_is_m = (m == 4) ? IsPortDimsFour(*input1, input1_port) : IsPortDimsN(*input1, input1_port, m); return input0_is_n && input1_is_m; } return false; } NodeDef* AddNodeShapeConst(const string& name, int num_channels, const string& depended_node) { NodeDef* node = graph_->add_node(); node_map_->AddNode(name, node); node->set_name(name); node->set_op("Const"); node->set_device(node_->device()); AttrValue attr_data_type; attr_data_type.set_type(DT_INT32); node->mutable_attr()->insert({"dtype", attr_data_type}); AttrValue attr_tensor; Tensor tensor(DT_INT32, TensorShape({4})); std::vector<int> shape = {1, num_channels, 1, 1}; for (int i = 0; i < static_cast<int>(shape.size()); i++) { tensor.flat<int>()(i) = shape[i]; } tensor.AsProtoTensorContent(attr_tensor.mutable_tensor()); node->mutable_attr()->insert({"value", attr_tensor}); if (is_in_frame_) { // This is to ensure the transpose node and the const node are in the // same frame. *node->add_input() = AsControlDependency(depended_node); } return node; } NodeDef* AddNodeReshape(const string& node_name, const string& input_name, const string& shape_const_node_name, DataType data_type) { NodeDef* node = graph_->add_node(); node_map_->AddNode(node_name, node); node->set_name(node_name); *node->add_input() = input_name; *node->add_input() = shape_const_node_name; node->set_op("Reshape"); node->set_device(node_->device()); AttrValue attr_type_indices; attr_type_indices.set_type(DT_INT32); node->mutable_attr()->insert({"Tshape", attr_type_indices}); AttrValue attr_type_params; attr_type_params.set_type(data_type); node->mutable_attr()->insert({"T", attr_type_params}); return node; } Status CustomizedProcessing() override { int vector_index = -1; if (IsNDOperateWithMD(4, 1)) { vector_index = 1; } else if (IsNDOperateWithMD(1, 4)) { vector_index = 0; } if (vector_index != -1) { string base_name = strings::StrCat(node_->name(), "-", vector_index); string reshape_node_name = LayoutOptimizerNode( strings::StrCat(base_name, "-", kReshapeNHWCToNCHW)); string shape_const_node_name = LayoutOptimizerNode(strings::StrCat(base_name, "-", kReshapeConst)); auto input_node = node_map_->GetNode(node_->input(vector_index)); TF_RETURN_IF_ERROR(HasAttribute(*input_node, "_output_shapes")); int port; ParseNodeName(node_->input(vector_index), &port); int vector_size = input_node->attr() .at("_output_shapes") .list() .shape(port) .dim(0) .size(); AddNodeShapeConst(shape_const_node_name, vector_size, NodeName(node_->input(vector_index))); TF_RETURN_IF_ERROR(HasAttribute(*node_, "T")); AddNodeReshape(reshape_node_name, node_->input(vector_index), shape_const_node_name, node_->attr().at("T").type()); node_map_->AddOutput(shape_const_node_name, reshape_node_name); node_map_->UpdateOutput(NodeName(node_->input(vector_index)), node_->name(), reshape_node_name); node_map_->AddOutput(reshape_node_name, node_->name()); *node_->mutable_input(vector_index) = reshape_node_name; } return Status::OK(); } }; class ConcatProcessor : public AgnosticNodeProcessor { public: explicit ConcatProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) { // For Concat, the concat axis is the first input; for ConcatV2, // the last input. Note that if with control inputs, the number of inputs // is larger than the integer attribute N. int n = node_->attr().at("N").i(); axis_node_pos_ = (IsConcatV1(*node_)) ? 0 : n; } protected: std::vector<int> GetInputPos() const override { return DataInputPosConcat(*node_); } Status CustomizedProcessing() override { DataType dtype = (IsConcatV1(*node_)) ? DT_INT32 : node_->attr().at("Tidx").type(); return UpdateOrTransformParamInput(axis_node_pos_, "DataFormatDimMap", dtype); } int axis_node_pos_; }; class FillProcessor : public AgnosticNodeProcessor { public: explicit FillProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: std::vector<int> GetInputPos() const override { return {}; } Status CustomizedProcessing() override { DataType dtype = node_->attr().at("index_type").type(); return UpdateOrTransformParamInput(0, "DataFormatVecPermute", dtype); } }; class HistogramSummaryProcessor : public AgnosticNodeProcessor { public: explicit HistogramSummaryProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: bool ShouldProcess() const override { auto input1 = node_map_->GetNode(node_->input(1)); int port; ParseNodeName(node_->input(1), &port); return !MustPreserve() && HasOutputs() && IsNodeAfterNCHWToNHWC() && IsPortDimsFour(*input1, port) && IsOnGPU(); } std::vector<int> GetInputPos() const override { return {1}; } Status AddLayoutTransposeToOutputs() override { return Status::OK(); } }; class IdentityNProcessor : public AgnosticNodeProcessor { public: explicit IdentityNProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) { std::set<string> ops_format_agnostic = GetOpsFormatAgnostic(); for (int i = 0; i < node_->input_size(); i++) { auto input = node_map_->GetNode(node_->input(i)); int port; ParseNodeName(node_->input(i), &port); // Skip control input. if (port != -1) { bool is_agnostic = ops_format_agnostic.find(input->op()) != ops_format_agnostic.end(); if (IsPortDimsFour(*input, port) && ((IsNodeAfterNCHWToNHWC(*input) && is_agnostic) || IsTransposeNCHWToNHWC(input->name()))) { input_pos_.push_back(i); } } } } protected: bool ShouldProcess() const override { return !MustPreserve() && HasOutputs() && IsNodeAfterNCHWToNHWC() && IsOnGPU(); } std::vector<int> GetInputPos() const override { return input_pos_; } std::set<int> GetOutputPos() const override { std::set<int> output_pos{}; for (const auto& input_pos : input_pos_) { output_pos.insert(input_pos); } return output_pos; } private: std::vector<int> input_pos_; }; class ShapeProcessor : public IdentityNProcessor { public: explicit ShapeProcessor(const OptimizeContext& opt_cxt) : IdentityNProcessor(opt_cxt) {} protected: Status AddLayoutTransposeToOutputs() override { return Status::OK(); } Status CustomizedProcessing() override { return AddTransformToOutputs("DataFormatVecPermute"); } }; class MergeProcessor : public AgnosticNodeProcessor { public: explicit MergeProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: bool ShouldProcess() const override { return !MustPreserve() && IsPortZeroDimsFour(*node_) && HasOutputs() && IsEveryInputAfterNCHWToNHWC() && IsOnGPU(); } std::vector<int> GetInputPos() const override { std::vector<int> input_pos; int n = node_->attr().at("N").i(); input_pos.reserve(n); for (int i = 0; i < n; i++) { input_pos.push_back(i); } return input_pos; } private: bool IsEveryInputAfterNCHWToNHWC() const { std::set<string> ops_format_agnostic = GetOpsFormatAgnostic(); for (const auto& input : node_->input()) { auto input_node = node_map_->GetNode(input); int port; ParseNodeName(input, &port); bool is_agnostic = ops_format_agnostic.find(input_node->op()) != ops_format_agnostic.end(); if (IsPortDimsFour(*input_node, port) && ((IsNodeAfterNCHWToNHWC(*input_node) && is_agnostic) || IsTransposeNCHWToNHWC(input_node->name()))) { continue; } return false; } return true; } }; class PadProcessor : public AgnosticNodeProcessor { public: explicit PadProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: Status CustomizedProcessing() override { DataType dtype = node_->attr().at("Tpaddings").type(); return UpdateOrTransformParamInput(1, "DataFormatVecPermute", dtype); } }; class ReverseProcessor : public AgnosticNodeProcessor { public: explicit ReverseProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: Status CustomizedProcessing() override { DataType dtype = node_->attr().at("Tidx").type(); return UpdateOrTransformParamInput(1, "DataFormatDimMap", dtype); } }; class SplitProcessor : public AgnosticNodeProcessor { public: explicit SplitProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) { axis_node_pos_ = 0; } protected: std::vector<int> GetInputPos() const override { return {1}; } std::set<int> GetOutputPos() const override { std::set<int> output_pos{0}; if (HasAttribute(*node_, "num_split").ok()) { for (int i = 1; i < node_->attr().at("num_split").i(); i++) { output_pos.insert(i); } } return output_pos; } Status CustomizedProcessing() override { return UpdateOrTransformParamInput(axis_node_pos_, "DataFormatDimMap", DT_INT32); } int axis_node_pos_; }; class SplitVProcessor : public SplitProcessor { public: explicit SplitVProcessor(const OptimizeContext& opt_cxt) : SplitProcessor(opt_cxt) { axis_node_pos_ = 2; } protected: std::vector<int> GetInputPos() const override { return {0}; } }; class TernaryOpProcessor : public AgnosticNodeProcessor { public: explicit TernaryOpProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: std::vector<int> GetInputPos() const override { return {0, 1, 2}; } }; class SelectProcessor : public AgnosticNodeProcessor { public: explicit SelectProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: bool ShouldProcess() const override { auto input0 = node_map_->GetNode(node_->input(0)); int input0_port; ParseNodeName(node_->input(0), &input0_port); bool is_input0_scalar_vector_4d = IsPortDimsN(*input0, input0_port, 0) || IsPortDimsN(*input0, input0_port, 1) || IsPortDimsN(*input0, input0_port, 4); return AgnosticNodeProcessor::ShouldProcess() && is_input0_scalar_vector_4d; } std::vector<int> GetInputPos() const override { auto input0 = node_map_->GetNode(node_->input(0)); int input0_port; ParseNodeName(node_->input(0), &input0_port); // Input 0 could be a scalar, a vector with size matching the first // dimension of input 1 and 2, or must have the same shape as input 1 and 2. if (IsPortDimsFour(*input0, input0_port)) { return {0, 1, 2}; } else { return {1, 2}; } } }; class UnaryGradProcessor : public AgnosticNodeProcessor { public: explicit UnaryGradProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: std::vector<int> GetInputPos() const override { return {0, 1}; } }; class SliceProcessor : public AgnosticNodeProcessor { public: explicit SliceProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) { // Skip the first input, which is the data to be sliced. start_ = 1; // Note that we can't use node_->input_size() here because there // could be control inputs. end_ = 2; } protected: Status ProcessInputs() { for (int i = start_; i <= end_; i++) { DataType dtype = node_->attr().at("Index").type(); TF_RETURN_IF_ERROR( UpdateOrTransformParamInput(i, "DataFormatVecPermute", dtype)); } return Status::OK(); } Status CustomizedProcessing() override { return ProcessInputs(); } int start_; int end_; }; class StridedSliceProcessor : public SliceProcessor { public: explicit StridedSliceProcessor(const OptimizeContext& opt_cxt) : SliceProcessor(opt_cxt) { start_ = 1; end_ = 3; } protected: bool ShouldProcess() const override { return AgnosticNodeProcessor::ShouldProcess() && IsOnlyBeginEndMask(); } Status CustomizedProcessing() override { TF_RETURN_IF_ERROR(UpdateMask("begin_mask")); TF_RETURN_IF_ERROR(UpdateMask("end_mask")); TF_RETURN_IF_ERROR(ProcessInputs()); return Status::OK(); } private: bool IsMaskZero(const string& mask) const { return node_->attr().at(mask).i() == 0; } bool IsOnlyBeginEndMask() const { return IsMaskZero("ellipsis_mask") && IsMaskZero("new_axis_mask") && IsMaskZero("shrink_axis_mask"); } Status UpdateMask(const string& mask) { int i = node_->attr().at(mask).i(); if (i < 0 || i > 15) { return errors::InvalidArgument("invalid mask value: ", i); } if (i == 0 || i == 1 || i == 14 || i == 15) return Status::OK(); switch (i) { case 2: case 3: i += 2; break; case 4: case 5: i += 4; break; case 6: case 7: i += 6; break; case 8: case 9: i -= 6; break; case 10: case 11: i -= 4; break; case 12: case 13: i -= 2; break; } node_->mutable_attr()->at(mask).set_i(i); return Status::OK(); } }; class StridedSliceGradProcessor : public StridedSliceProcessor { public: explicit StridedSliceGradProcessor(const OptimizeContext& opt_cxt) : StridedSliceProcessor(opt_cxt) { start_ = 0; end_ = 3; } protected: std::vector<int> GetInputPos() const override { return {4}; } }; class SqueezeProcessor : public AgnosticNodeProcessor { public: explicit SqueezeProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: bool ShouldProcess() const override { bool is_dims_supported = (IsPortZeroDimsN(*node_, 2) && IsAlongHW()) || (IsPortZeroDimsN(*node_, 1) && IsAlongNHW()); return !MustPreserve() && HasOutputs() && IsNodeAfterNCHWToNHWC() && IsInputConvertible() && is_dims_supported && IsOnGPU(); } Status AddLayoutTransposeToOutputs() override { return Status::OK(); } Status CustomizedProcessing() override { TF_RETURN_IF_ERROR(HasAttribute(*node_, "squeeze_dims")); auto list = node_->mutable_attr()->at("squeeze_dims").mutable_list(); if (list->i_size() == 2) { list->set_i(0, 2); list->set_i(1, 3); } else if (list->i_size() == 3) { list->set_i(1, 2); list->set_i(2, 3); } return Status::OK(); } private: bool IsInputConvertible() const { int input_port; auto input = node_map_->GetNode(node_->input(0)); ParseNodeName(node_->input(0), &input_port); if (input->attr().find("_output_shapes") != input->attr().end()) { auto shape = input->attr().at("_output_shapes").list().shape(input_port); if (shape.dim_size() != 4) { return false; } if (shape.dim(1).size() == 1 && shape.dim(2).size() == 1) { return true; } if (shape.dim(0).size() == 1 && shape.dim(1).size() == 1 && shape.dim(2).size() == 1) { return true; } } return false; } bool IsAlongAxis(const std::vector<int>& axis) const { if (node_->attr().find("squeeze_dims") != node_->attr().end()) { auto list = node_->attr().at("squeeze_dims").list(); // If list is empty, Squeeze op will squeeze all dimensions of size 1. if (list.i_size() == 0) return true; if (list.i_size() == axis.size()) { bool along_axis = true; for (int i = 0; i < axis.size(); i++) { along_axis = along_axis && (list.i(i) == axis[i]); } if (along_axis) return true; } } return false; } bool IsAlongHW() const { return IsAlongAxis({1, 2}); } bool IsAlongNHW() const { return IsAlongAxis({0, 1, 2}); } }; class ReduceProcessor : public AgnosticNodeProcessor { public: explicit ReduceProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: bool ShouldProcess() const override { auto input0 = node_map_->GetNode(node_->input(0)); int port; ParseNodeName(node_->input(0), &port); return !MustPreserve() && HasOutputs() && IsNodeAfterNCHWToNHWC() && IsPortDimsFour(*input0, port) && IsReduceAxisSupported() && IsOnGPU(); } Status CustomizedProcessing() override { if (IsReduceAxisSupported()) { DataType dtype = node_->attr().at("Tidx").type(); TF_RETURN_IF_ERROR( UpdateOrTransformParamInput(1, "DataFormatDimMap", dtype)); } return Status::OK(); } Status AddLayoutTransposeToOutputs() override { if (KeepDims()) { return AddTransformToOutputs("Transpose"); } return Status::OK(); } private: bool IsReduceAxisSupported() const { return KeepDims() || ((IsAlongAllFourDims() || IsAlongHWC() || IsAlongNHW() || IsAlongHW() || IsAlongC()) && !KeepDims()); } bool IsAlongAxis(const std::vector<int>& axis) const { auto axis_node = node_map_->GetNode(node_->input(1)); if (!IsConstant(*axis_node)) { return false; } if (HasAttribute(*axis_node, "value").ok()) { Tensor tensor; auto success = tensor.FromProto(axis_node->attr().at({"value"}).tensor()); if (!success) { LOG(ERROR) << "Failed to parse TensorProto."; } if (tensor.dims() == 1 && tensor.dim_size(0) == axis.size()) { bool along_axis = true; for (int i = 0; i < axis.size(); i++) { along_axis = along_axis && (tensor.flat<int>()(i) == axis[i]); } if (along_axis) return true; } } return false; } bool IsAlongAllFourDims() const { return IsAlongAxis({0, 1, 2, 3}); } bool IsAlongHWC() const { return IsAlongAxis({1, 2, 3}); } bool IsAlongNHW() const { return IsAlongAxis({0, 1, 2}); } bool IsAlongHW() const { return IsAlongAxis({1, 2}); } bool IsAlongC() const { return IsAlongAxis({3}); } bool KeepDims() const { return node_->attr().at("keep_dims").b(); } }; class SwitchProcessor : public AgnosticNodeProcessor { public: explicit SwitchProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: std::set<int> GetOutputPos() const override { return {0, 1}; } }; class TileProcessor : public AgnosticNodeProcessor { public: explicit TileProcessor(const OptimizeContext& opt_cxt) : AgnosticNodeProcessor(opt_cxt) {} protected: Status CustomizedProcessing() override { DataType dtype = node_->attr().at("Tmultiples").type(); return UpdateOrTransformParamInput(1, "DataFormatVecPermute", dtype); } }; class DataLayoutOptimizer : GraphProcessor { public: explicit DataLayoutOptimizer( const GraphProperties& graph_properties, const VirtualPlacer& virtual_placer, const LayoutOptimizer::TuningConfig& config, const std::unordered_set<string>& nodes_to_preserve, GraphDef* graph, NodeMap* node_map) : GraphProcessor(graph_properties, virtual_placer, nodes_to_preserve, graph, node_map), config_(config) {} Status Optimize() { VLOG(1) << "Number of nodes for original graph: " << graph_->node_size(); TF_RETURN_IF_ERROR(Expand()); VLOG(1) << "Number of nodes after Expand: " << graph_->node_size(); TF_RETURN_IF_ERROR(Collapse()); VLOG(1) << "Number of nodes after Collapse: " << graph_->node_size(); return Status::OK(); } private: NodeDef* AddNodePermNHWCToNCHW() { return AddNodePermConst(LayoutOptimizerNode(kPermNHWCToNCHW), "", {0, 3, 1, 2}); } NodeDef* AddNodePermNCHWToNHWC() { return AddNodePermConst(LayoutOptimizerNode(kPermNCHWToNHWC), "", {0, 2, 3, 1}); } // Expand all nodes which is in NHWC, but supports NCHW or is layout agnostic. Status Expand() { int node_size_original = graph_->node_size(); std::unordered_map<const NodeDef*, std::vector<int>> frames; int num_frames; TF_RETURN_IF_ERROR(IdentifyFrames(*graph_, &frames, &num_frames)); // This is the first pass where we expand the nodes which support NCHW. std::set<string> ops_format_supported = GetOpsFormatSupported(); for (int i = 0; i < node_size_original; i++) { if (IsNodeByLayoutOptimizer(graph_->node(i).name())) { return Status(error::INVALID_ARGUMENT, "The graph is already optimized by layout optimizer."); } if (ops_format_supported.find(graph_->node(i).op()) != ops_format_supported.end()) { auto node = graph_->mutable_node(i); bool is_in_frame = !frames[node].empty(); OptimizeContext opt_cxt(graph_, node, node_map_, graph_properties_, virtual_placer_, nodes_to_preserve_, is_in_frame); std::unique_ptr<NodeProcessor> node_processor; if (IsAvgPoolGrad(*node)) { node_processor.reset(new AvgPoolGradProcessor(opt_cxt)); } else if (IsBiasAddGrad(*node)) { node_processor.reset(new BiasAddGradProcessor(opt_cxt)); } else if (IsConv2D(*node)) { node_processor.reset(new Conv2DProcessor(opt_cxt, config_.no_gemm)); } else if (IsConv2DBackpropFilter(*node)) { node_processor.reset( new Conv2DBackpropFilterProcessor(opt_cxt, config_.no_gemm)); } else if (IsConv2DBackpropInput(*node)) { node_processor.reset( new Conv2DBackpropInputProcessor(opt_cxt, config_.no_gemm)); } else if (IsDepthwiseConv2dNative(*node)) { node_processor.reset(new Conv2DProcessor(opt_cxt, true)); } else if (IsDepthwiseConv2dNativeBackpropFilter(*node)) { node_processor.reset( new Conv2DBackpropFilterProcessor(opt_cxt, true)); } else if (IsDepthwiseConv2dNativeBackpropInput(*node)) { node_processor.reset(new Conv2DBackpropInputProcessor(opt_cxt, true)); } else if (IsFusedBatchNormGrad(*node)) { node_processor.reset(new FusedBatchNormGradProcessor(opt_cxt)); } else if (IsMaxPoolV2(*node)) { node_processor.reset(new MaxPoolV2Processor(opt_cxt)); } else if (IsMaxPoolGradV1(*node) || IsMaxPoolGradGradV1(*node)) { node_processor.reset(new MaxPoolGradProcessor(opt_cxt)); } else if (IsMaxPoolGradV2(*node) || IsMaxPoolGradGradV2(*node)) { node_processor.reset(new MaxPoolGradV2Processor(opt_cxt)); } else { node_processor.reset(new NodeProcessor(opt_cxt)); } TF_RETURN_IF_ERROR(node_processor->ConvertNode()); } } // This is the second pass where we expand layout-agnostic nodes. This pass // only needs to be performed if at least one node in the previous pass is // expanded. if (graph_->node_size() > node_size_original) { NodeDef* n = AddNodePermNHWCToNCHW(); n = AddNodePermNCHWToNHWC(); std::set<string> ops_format_agnostic = GetOpsFormatAgnostic(); for (int i = 0; i < graph_->node_size(); i++) { if (ops_format_agnostic.find(graph_->node(i).op()) != ops_format_agnostic.end()) { auto node = graph_->mutable_node(i); bool is_in_frame = !frames[node].empty(); OptimizeContext opt_cxt(graph_, node, node_map_, graph_properties_, virtual_placer_, nodes_to_preserve_, is_in_frame); std::unique_ptr<NodeProcessor> node_processor; if (IsAddN(*node)) { node_processor.reset(new AddNProcessor(opt_cxt)); } else if (IsBetainc(*node)) { node_processor.reset(new TernaryOpProcessor(opt_cxt)); } else if (IsBinaryOp(*node)) { node_processor.reset(new BinaryOpProcessor(opt_cxt)); } else if (IsConcat(*node)) { node_processor.reset(new ConcatProcessor(opt_cxt)); } else if (IsFill(*node)) { node_processor.reset(new FillProcessor(opt_cxt)); } else if (IsHistogramSummary(*node)) { node_processor.reset(new HistogramSummaryProcessor(opt_cxt)); } else if (IsIdentityN(*node)) { node_processor.reset(new IdentityNProcessor(opt_cxt)); } else if (IsMerge(*node)) { node_processor.reset(new MergeProcessor(opt_cxt)); } else if (IsPad(*node) || IsMirrorPad(*node) || IsMirrorPadGrad(*node)) { node_processor.reset(new PadProcessor(opt_cxt)); } else if (IsReduceOp(*node)) { node_processor.reset(new ReduceProcessor(opt_cxt)); } else if (IsReverseV2(*node)) { node_processor.reset(new ReverseProcessor(opt_cxt)); } else if (IsSelect(*node)) { node_processor.reset(new SelectProcessor(opt_cxt)); } else if (IsSlice(*node)) { node_processor.reset(new SliceProcessor(opt_cxt)); } else if (IsStridedSlice(*node)) { node_processor.reset(new StridedSliceProcessor(opt_cxt)); } else if (IsShape(*node) || IsShapeN(*node)) { node_processor.reset(new ShapeProcessor(opt_cxt)); } else if (IsSplit(*node)) { node_processor.reset(new SplitProcessor(opt_cxt)); } else if (IsSplitV(*node)) { node_processor.reset(new SplitVProcessor(opt_cxt)); } else if (IsSqueeze(*node)) { node_processor.reset(new SqueezeProcessor(opt_cxt)); } else if (IsStridedSliceGrad(*node)) { node_processor.reset(new StridedSliceGradProcessor(opt_cxt)); } else if (IsSwitch(*node)) { node_processor.reset(new SwitchProcessor(opt_cxt)); } else if (IsTile(*node)) { node_processor.reset(new TileProcessor(opt_cxt)); } else if (IsUnaryGrad(*node)) { node_processor.reset(new UnaryGradProcessor(opt_cxt)); } else { node_processor.reset(new AgnosticNodeProcessor(opt_cxt)); } TF_RETURN_IF_ERROR(node_processor->ConvertNode()); } } } return Status::OK(); } // Remove all node pairs, where a NCHW-to-NHWC node is followed by // a NHWC-to-NCHW node. Status Collapse() { std::unordered_set<string> nodes_removable; for (int i = 0; i < graph_->node_size(); i++) { auto node = graph_->mutable_node(i); node->mutable_attr()->erase("_output_shapes"); if (IsTransposeNHWCToNCHW(node->name()) || IsDimMapNHWCToNCHW(node->name()) || IsVecPermuteNHWCToNCHW(node->name())) { bool transpose_pair = IsTransposeNHWCToNCHW(node->name()) && IsTransposeNCHWToNHWC(node->input(0)); bool dim_map_pair = IsDimMapNHWCToNCHW(node->name()) && IsDimMapNCHWToNHWC(node->input(0)); bool vec_permute_pair = IsVecPermuteNHWCToNCHW(node->name()) && IsVecPermuteNCHWToNHWC(node->input(0)); if (transpose_pair || dim_map_pair || vec_permute_pair) { const string& trans_first = node->input(0); const string& trans_second = node->name(); auto outputs = node_map_->GetOutputs(trans_second); CHECK(outputs.size() == 1) << "There is always only a single output for a Transpose node, " << "due to the way it is added by NodeProcessor."; NodeDef* output = *outputs.begin(); string input = node_map_->GetNode(trans_first)->input(0); for (int i = 0; i < output->input_size(); i++) { if (output->input(i).compare(trans_second) == 0) { *output->mutable_input(i) = input; break; } } nodes_removable.insert(trans_first); nodes_removable.insert(trans_second); } } } graph_->mutable_node()->erase( std::remove_if( graph_->mutable_node()->begin(), graph_->mutable_node()->end(), [nodes_removable](const NodeDef& node) { return nodes_removable.find(node.name()) != nodes_removable.end(); }), graph_->mutable_node()->end()); return Status::OK(); } const LayoutOptimizer::TuningConfig& config_; }; int GetNumGPUs(const Cluster& cluster) { auto devices = cluster.GetDevices(); int num_gpus = 0; for (const auto& device : devices) { if (device.second.type() == "GPU") { if (device.second.environment().find("architecture") != device.second.environment().end()) { const string arch = device.second.environment().at("architecture"); // TODO(yaozhang): Enable for Volta GPUs (compute capability version 7). if (arch < "7") { num_gpus++; } } } } return num_gpus; } } // namespace Status LayoutOptimizer::Tune(const GrapplerItem& item, const GraphProperties& graph_properties, const TuningConfig& config, GraphDef* output) { auto status = graph_properties.AnnotateOutputShapes(output); if (!status.ok()) { VLOG(1) << "Annotate shape return status: " << status.ToString(); *output = item.graph; return status; } NodeMap node_map(output); DataLayoutOptimizer layout_optimizer(graph_properties, *virtual_placer_, config, nodes_to_preserve_, output, &node_map); status = layout_optimizer.Optimize(); return status; } Status LayoutOptimizer::Optimize(Cluster* cluster, const GrapplerItem& item, GraphDef* output) { if (GetNumGPUs(*cluster) < 1) { // LayoutOptimizer is currently only tuned for GPU. *output = item.graph; return Status::OK(); } virtual_placer_.reset(new VirtualPlacer(cluster)); nodes_to_preserve_ = item.NodesToPreserve(); GraphProperties graph_properties(item); auto status = graph_properties.InferStatically(false); if (!status.ok()) { VLOG(1) << "Infer shape return status: " << status.ToString(); *output = item.graph; return status; } TuningConfig config; config.no_gemm = true; // TODO(yaozhang): Enable tuning with various TuningConfig choices wtih // the measurement-based estimator. status = Tune(item, graph_properties, config, output); if (!status.ok()) { *output = item.graph; } return status; } void LayoutOptimizer::Feedback(Cluster* cluster, const GrapplerItem& item, const GraphDef& optimize_output, double result) { // Nothing to do for LayoutOptimizer. } } // end namespace grappler } // end namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
cefc48d96163810fc5630abf03814b4d99ae7c3e
3db023edb0af1dcf8a1da83434d219c3a96362ba
/windows_nt_3_5_source_code/NT-782/PRIVATE/CRT32PSX/IOSTREAM/OSTRUINT.CXX
adb05100d4e1fe6f9715a8ddd6d1fc956eb270f1
[]
no_license
xiaoqgao/windows_nt_3_5_source_code
de30e9b95856bc09469d4008d76191f94379c884
d2894c9125ff1c14028435ed1b21164f6b2b871a
refs/heads/master
2022-12-23T17:58:33.768209
2020-09-28T20:20:18
2020-09-28T20:20:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,209
cxx
/*** * ostruint.cxx - definitions for ostream class operator<<(unsigned int) funct * * Copyright (c) 1991-1992, Microsoft Corporation. All rights reserved. * *Purpose: * Contains the member function definitions for ostream * operator<<(unsigned int). * *Revision History: * 09-23-91 KRS Created. Split out from ostream.cxx for granularity. * *******************************************************************************/ #include <cruntime.h> #include <internal.h> #include <stdio.h> #include <iostream.h> #pragma hdrstop ostream& ostream::operator<<(unsigned int n) { _WINSTATIC char obuffer[12]; _WINSTATIC char fmt[4] = "%u"; _WINSTATIC char leader[4] = "\0\0"; if (opfx()) { if (n) { if (x_flags & (hex|oct)) { if (x_flags & hex) { if (x_flags & uppercase) fmt[1] = 'X'; else fmt[1] = 'x'; leader[1] = fmt[1]; // 0x or 0X (or \0X) } else fmt[1] = 'o'; if (x_flags & showbase) leader[0] = '0'; } else if (x_flags & showpos) { leader[0] = '+'; } } sprintf(obuffer,fmt,n); writepad(leader,obuffer); osfx(); } return *this; }
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
1c56a72a4dfd74d0732453a70a3e9add5ee752b7
7e8fcdde2a47b889cba2dd39b1bca46d0f6fbb1c
/SliderValuesTutorial Lambda/JuceLibraryCode/JuceHeader.h
a702e4beb4ee82cb415ef5c8958161e024215d7b
[]
no_license
dropcontrol/juce-tutorial
2f4b4ee7e63839c6d514140ebb6837d32ca9888b
d8f95f8213d9036ce2d221049668210304fc0397
refs/heads/main
2023-05-13T09:45:37.039810
2021-06-12T11:56:25
2021-06-12T11:56:25
357,336,797
1
0
null
null
null
null
UTF-8
C++
false
false
1,869
h
/* IMPORTANT! This file is auto-generated each time you save your project - if you alter its contents, your changes may be overwritten! This is the header file that your files should include in order to get all the JUCE library headers. You should avoid including the JUCE headers directly in your own source files, because that wouldn't pick up the correct configuration options for your app. */ #pragma once #include <juce_audio_basics/juce_audio_basics.h> #include <juce_audio_devices/juce_audio_devices.h> #include <juce_audio_formats/juce_audio_formats.h> #include <juce_audio_processors/juce_audio_processors.h> #include <juce_audio_utils/juce_audio_utils.h> #include <juce_core/juce_core.h> #include <juce_data_structures/juce_data_structures.h> #include <juce_events/juce_events.h> #include <juce_graphics/juce_graphics.h> #include <juce_gui_basics/juce_gui_basics.h> #include <juce_gui_extra/juce_gui_extra.h> #if defined (JUCE_PROJUCER_VERSION) && JUCE_PROJUCER_VERSION < JUCE_VERSION /** If you've hit this error then the version of the Projucer that was used to generate this project is older than the version of the JUCE modules being included. To fix this error, re-save your project using the latest version of the Projucer or, if you aren't using the Projucer to manage your project, remove the JUCE_PROJUCER_VERSION define. */ #error "This project was last saved using an outdated version of the Projucer! Re-save this project with the latest version to fix this error." #endif #if ! JUCE_DONT_DECLARE_PROJECTINFO namespace ProjectInfo { const char* const projectName = "SliderValuesTutorial"; const char* const companyName = ""; const char* const versionString = "1.0.0"; const int versionNumber = 0x10000; } #endif
[ "yamato@gmail.com" ]
yamato@gmail.com
b46c0c15a65a0123b56a2796b48492287f9f471a
f13f67fb1a7c2699bf8a7c74aa7a10057d8d13d5
/Classes/Coms/ProgressCom.cpp
4f248f9d62687dd503a10bc62be58b8156bf07cf
[]
no_license
JCGit/genius-x
7a1d31dc81c83f038df912efc8b78c1017b82bbd
9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0
refs/heads/develop
2021-01-15T23:36:14.668365
2014-12-26T10:44:23
2014-12-26T10:44:23
35,144,165
1
1
null
2015-05-06T06:59:21
2015-05-06T06:59:21
null
UTF-8
C++
false
false
337
cpp
// // ProgressCom.cpp // sg // // Created by Elvis on 3/25/14. // // #include "ProgressCom.h" std::string ProgressCom::_TYPE="ProgressCom"; ProgressCom::ProgressCom():GX::Com(_TYPE) { } void ProgressCom::initWithMap(rapidjson::Value& value) { } GX::Com* ProgressCom::cloneEmpty() const { return new ProgressCom(); }
[ "hielvis@live.com" ]
hielvis@live.com
d62c2de567b1a3441583815796cc50d2e512e6fa
70ad3badf3fa6e2edf1889d8640f25a7ec0d9db1
/catkin_ws/devel/include/ublox_msgs/RxmRAWX_Meas.h
9d13dc79b51edb3cfb6cbed609b8a475d8dcdb1c
[]
no_license
MathieuHwei/OldGaitMaven
758a937dfda2cf4f1aee266dbbf682ef34989199
873f7d9089c5d1c0772bd3447e2b0a31dac68b70
refs/heads/main
2023-06-17T18:40:06.230823
2021-07-19T23:08:20
2021-07-19T23:08:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,178
h
// Generated by gencpp from file ublox_msgs/RxmRAWX_Meas.msg // DO NOT EDIT! #ifndef UBLOX_MSGS_MESSAGE_RXMRAWX_MEAS_H #define UBLOX_MSGS_MESSAGE_RXMRAWX_MEAS_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace ublox_msgs { template <class ContainerAllocator> struct RxmRAWX_Meas_ { typedef RxmRAWX_Meas_<ContainerAllocator> Type; RxmRAWX_Meas_() : prMes(0.0) , cpMes(0.0) , doMes(0.0) , gnssId(0) , svId(0) , reserved0(0) , freqId(0) , locktime(0) , cno(0) , prStdev(0) , cpStdev(0) , doStdev(0) , trkStat(0) , reserved1(0) { } RxmRAWX_Meas_(const ContainerAllocator& _alloc) : prMes(0.0) , cpMes(0.0) , doMes(0.0) , gnssId(0) , svId(0) , reserved0(0) , freqId(0) , locktime(0) , cno(0) , prStdev(0) , cpStdev(0) , doStdev(0) , trkStat(0) , reserved1(0) { (void)_alloc; } typedef double _prMes_type; _prMes_type prMes; typedef double _cpMes_type; _cpMes_type cpMes; typedef float _doMes_type; _doMes_type doMes; typedef uint8_t _gnssId_type; _gnssId_type gnssId; typedef uint8_t _svId_type; _svId_type svId; typedef uint8_t _reserved0_type; _reserved0_type reserved0; typedef uint8_t _freqId_type; _freqId_type freqId; typedef uint16_t _locktime_type; _locktime_type locktime; typedef int8_t _cno_type; _cno_type cno; typedef uint8_t _prStdev_type; _prStdev_type prStdev; typedef uint8_t _cpStdev_type; _cpStdev_type cpStdev; typedef uint8_t _doStdev_type; _doStdev_type doStdev; typedef uint8_t _trkStat_type; _trkStat_type trkStat; typedef uint8_t _reserved1_type; _reserved1_type reserved1; enum { TRK_STAT_PR_VALID = 1u }; enum { TRK_STAT_CP_VALID = 2u }; enum { TRK_STAT_HALF_CYC = 4u }; enum { TRK_STAT_SUB_HALF_CYC = 8u }; typedef boost::shared_ptr< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> const> ConstPtr; }; // struct RxmRAWX_Meas_ typedef ::ublox_msgs::RxmRAWX_Meas_<std::allocator<void> > RxmRAWX_Meas; typedef boost::shared_ptr< ::ublox_msgs::RxmRAWX_Meas > RxmRAWX_MeasPtr; typedef boost::shared_ptr< ::ublox_msgs::RxmRAWX_Meas const> RxmRAWX_MeasConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> & v) { ros::message_operations::Printer< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace ublox_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'ublox_msgs': ['/home/pi/catkin_ws/src/ublox/ublox_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> > { static const char* value() { return "d6a580262875bf83a377ba14dcdd659f"; } static const char* value(const ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xd6a580262875bf83ULL; static const uint64_t static_value2 = 0xa377ba14dcdd659fULL; }; template<class ContainerAllocator> struct DataType< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> > { static const char* value() { return "ublox_msgs/RxmRAWX_Meas"; } static const char* value(const ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> > { static const char* value() { return "# see message RxmRAWX\n\ #\n\ \n\ float64 prMes # Pseudorange measurement [m]. GLONASS inter frequency\n\ # channel delays are compensated with an internal\n\ # calibration table.\n\ float64 cpMes # Carrier phase measurement [L1 cycles]. The carrier\n\ # phase initial ambiguity is initialized using an\n\ # approximate value to make the magnitude of\n\ # the phase close to the pseudorange\n\ # measurement. Clock resets are applied to both\n\ # phase and code measurements in accordance\n\ # with the RINEX specification.\n\ float32 doMes # Doppler measurement [Hz] (positive sign for\n\ # approaching satellites)\n\ uint8 gnssId # GNSS identifier (see CfgGNSS for constants)\n\ \n\ uint8 svId # Satellite identifier (see Satellite Numbering)\n\ \n\ uint8 reserved0 # Reserved\n\ \n\ uint8 freqId # Only used for GLONASS: This is the frequency\n\ # slot + 7 (range from 0 to 13)\n\ uint16 locktime # Carrier phase locktime counter [ms] \n\ # (maximum 64500 ms)\n\ int8 cno # Carrier-to-noise density ratio (signal strength) \n\ # [dB-Hz]\n\ uint8 prStdev # Estimated pseudorange measurement standard\n\ # deviation [m / 0.01*2^n]\n\ uint8 cpStdev # Estimated carrier phase measurement standard\n\ # deviation (note a raw value of 0x0F indicates the\n\ # value is invalid) [cycles / 0.004]\n\ uint8 doStdev # Estimated Doppler measurement standard deviation \n\ # [Hz / 0.002*2^n]\n\ \n\ uint8 trkStat # Tracking status bitfield\n\ uint8 TRK_STAT_PR_VALID = 1 # Pseudorange valid\n\ uint8 TRK_STAT_CP_VALID = 2 # Carrier phase valid\n\ uint8 TRK_STAT_HALF_CYC = 4 # Half cycle valid\n\ uint8 TRK_STAT_SUB_HALF_CYC = 8 # Half cycle subtracted from phase\n\ \n\ uint8 reserved1 # Reserved\n\ "; } static const char* value(const ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.prMes); stream.next(m.cpMes); stream.next(m.doMes); stream.next(m.gnssId); stream.next(m.svId); stream.next(m.reserved0); stream.next(m.freqId); stream.next(m.locktime); stream.next(m.cno); stream.next(m.prStdev); stream.next(m.cpStdev); stream.next(m.doStdev); stream.next(m.trkStat); stream.next(m.reserved1); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct RxmRAWX_Meas_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ublox_msgs::RxmRAWX_Meas_<ContainerAllocator>& v) { s << indent << "prMes: "; Printer<double>::stream(s, indent + " ", v.prMes); s << indent << "cpMes: "; Printer<double>::stream(s, indent + " ", v.cpMes); s << indent << "doMes: "; Printer<float>::stream(s, indent + " ", v.doMes); s << indent << "gnssId: "; Printer<uint8_t>::stream(s, indent + " ", v.gnssId); s << indent << "svId: "; Printer<uint8_t>::stream(s, indent + " ", v.svId); s << indent << "reserved0: "; Printer<uint8_t>::stream(s, indent + " ", v.reserved0); s << indent << "freqId: "; Printer<uint8_t>::stream(s, indent + " ", v.freqId); s << indent << "locktime: "; Printer<uint16_t>::stream(s, indent + " ", v.locktime); s << indent << "cno: "; Printer<int8_t>::stream(s, indent + " ", v.cno); s << indent << "prStdev: "; Printer<uint8_t>::stream(s, indent + " ", v.prStdev); s << indent << "cpStdev: "; Printer<uint8_t>::stream(s, indent + " ", v.cpStdev); s << indent << "doStdev: "; Printer<uint8_t>::stream(s, indent + " ", v.doStdev); s << indent << "trkStat: "; Printer<uint8_t>::stream(s, indent + " ", v.trkStat); s << indent << "reserved1: "; Printer<uint8_t>::stream(s, indent + " ", v.reserved1); } }; } // namespace message_operations } // namespace ros #endif // UBLOX_MSGS_MESSAGE_RXMRAWX_MEAS_H
[ "giahuy050201@gmail.com" ]
giahuy050201@gmail.com
7006fbba3e5e52c0c5d8c2d59e023230a1b2ac64
32c640ce93ece6c87d1ad842c1dcd4bc12cb4c26
/src/solvers/gecode/presolver/digraph.hpp
c16a7c3fae60a8771cb7a1ff8d68626c26460614
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
matsc-at-sics-se/unison
54b225539724040b7c8089178fb1ecab0d87dbba
8d23b73aaf8f3af5c4d86f26e0e4432d70bab564
refs/heads/master
2021-04-27T14:27:50.918235
2018-12-27T09:21:47
2018-12-27T09:21:47
122,455,374
6
0
null
null
null
null
UTF-8
C++
false
false
4,779
hpp
/* * Main authors: * Erik Ekstrom <eeks@sics.se> * Mats Carlsson <mats.carlsson@ri.se> * Roberto Castaneda Lozano <roberto.castaneda@ri.se> * * Contributing authors: * Noric Couderc <noric@sics.se> * * This file is part of Unison, see http://unison-code.github.io * * Copyright (c) 2015-2016, Erik Ekstrom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Simple Digraph implementation with functions for computing reachability and * SCC. */ #ifndef __DIGRAPH_H__ #define __DIGRAPH_H__ #include <iostream> #include <map> #include <set> #include <utility> #include <vector> #include <stack> #include "models/parameters.hpp" using namespace std; typedef int vertex; typedef pair<vertex, vertex> edge; class Digraph { private: // Since graphs in the presolver tend to be sparse, use a map // as data structure for the adjacency list, // mapping vertex to adjacent vertices map<vertex, vector<vertex> > adjacency_list; // Set of vertices in the graph vector<vertex> V; void bron_kerbosch2(vector<vertex>& R, const vector<vertex>& P, const vector<vertex>& X, vector<vector<vertex>>& cliques); public: // TODO: one of these should be enough... Digraph(const vector<vector<vertex> >& edges); Digraph(const vector<edge>& edges); // Returns all vertices vector<vertex> vertices() const; // Returns all edges vector<edge> edges() const; // Returns vertices adjacent to v vector<vertex> neighbors(vertex v); // Returns a transposed graph of this graph. // A transposed graph have the same vertices but all edges are // reversed. Digraph transpose(); // Transitive closure of a digraph Digraph closure(); // Product with digraph B Digraph product(Digraph& B); // Transitive reduction of a digraph Digraph reduction(); // Returns all verteices u reachable from v vector<vertex> reachables(const vertex v); // Return all maximal cliques // Warning: assumes not a digraph, but an undirected graph vector<vector<vertex>> max_cliques(); // Returns all strongly connected components. // Each component is represented by a set of its vertices. vector<vector<vertex> > scc(); // DFS in grpah, starting at v. Collecting new visited vertices in a stack. void dfs2(vertex v, map<vertex, bool>& visited, stack<vertex>& s); // DFS in grpah, starting at v. Collecting new visited vertices in a // sorted vector. void dfs2(vertex v, map<vertex, bool>& visited, vector<vertex>& s); friend ostream& operator<<(ostream& os, const Digraph& g); }; // Returns the intersection of the sorted vectors v1 and v2 template <typename T> vector<T> vector_intersection(const vector<T>& v1, const vector<T>& v2){ vector<T> i; set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(),back_inserter(i)); return i; } // Returns the difference of the sorted vectors v1 and v2 template <typename T> vector<T> vector_difference(const vector<T>& v1, const vector<T>& v2){ vector<T> i; set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(),back_inserter(i)); return i; } // Check whether ordered v contains e template<typename T> bool vector_contains(const vector<T>& v, const T& e){ return binary_search(v.begin(), v.end(), e); } #endif
[ "rcas@sics.se" ]
rcas@sics.se
3a1abc5a9c2a7c4d265fd37fd32715b4408f4955
5639e1458966a3414f96930ea7f0afe45236e8c9
/src/coursework/views/skybox.cpp
9f925bd474c44aa850ed9d957b0b7779cbc63a5a
[]
no_license
kosmaks/drill
bcf9b6ed22083a29930f9d6a30632f9388dd8b66
e3c5840b4a501a820fa949f47d288c0f911c5c4e
refs/heads/master
2020-05-19T23:45:37.148377
2014-09-02T14:16:01
2014-09-02T14:16:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,370
cpp
#include "skybox.h" skybox_view::skybox_view() : drill::view() { model_path = "dist/models/skybox.obj"; texture_path = "dist/textures/workshop.png"; position = { 0, 0, 0 }; rotation = { 0, 0, 0, 0 }; c_program = nullptr; } skybox_view::~skybox_view() { if (c_program != nullptr) delete c_program; } void skybox_view::init() { // Load dependencies compiler = require<drill::compiler>(); linker = require<drill::linker>(); transform = require<drill::transform>(); material = require<drill::material>(); // Load model wf_reader.load_from_file(model_path); object = wf_reader.to_object(); c_object = compiler().compile(object); // Load texture png_reader.load_from_file(texture_path); texture = png_reader.to_texture(); c_texture = material().compile_texture(texture); // Init shaders c_program = linker().begin() .include(transform()) .include(material()) .create(); } void skybox_view::update(const drill::timeinfo_t &time) { c_program->use(); transform().model_identity() .model_translate(position) .model_rotate(rotation) .model_scale({ 7, 7, 1 }) .flush(c_program); material().use_texture(c_texture) .color({ 1, 1, 1, 1 }) .flush(c_program); c_object->render(); }
[ "kstmaks@gmail.com" ]
kstmaks@gmail.com
620e207a173feb45627170efa01e7ee65f5e9333
714d497030100394383853d93ba27ab792aec451
/Planner/planner.cpp
09c9d47564caff69838b579217f2578c231d3aaa
[]
no_license
Arganon/Test
789d721cdfda7ee9e537974e2ad87be60b0eecd1
a0cad9a58785333aba8ff4f1e633f4e5d0f6c8ce
refs/heads/master
2021-01-21T10:29:07.032167
2017-05-19T09:33:25
2017-05-19T09:33:25
65,823,869
0
0
null
null
null
null
UTF-8
C++
false
false
1,797
cpp
#include "planner.h" Planner::Planner() { this->db->openDbFile(); } Planner::~Planner() { this->db->closeDbFile(); } void Planner::setDate(int day, int month, int year) { if (!this->calendar.isCorrectDate(day, month, year)) { std::cout << "Incorrect date!\n"; exit(1); } this->day = day; this->month = month; this->year = year; } void Planner::setRemind(char *text_remind) { if (strlen(text_remind) > MAX) { exit(1); } this->text_remind = text_remind; } void Planner::addRemind() { Remind remind(this->day, this->month, this->year); remind.setTextRemind(this->text_remind); this->db->add(remind); } void Planner::getRemind(int index) { Remind temp; this->db->get(temp, index); std::cout << temp.getYear() << "." << temp.getMonth() << "." << temp.getDay() << ": " << temp.getTextRemind() << std::endl; } void Planner::getRemindByDate(int day, int month, int year) { Remind temp; for (int i = 1; i <= this->db->size(temp); i++) { this->db->get(temp, i); if (year == temp.getYear() && month == temp.getMonth() && day == temp.getDay()) { getRemind(i); break; } } } void Planner::showAllReminds() { Remind temp; for (int i = 1; i <= this->db->size(temp); i++) { this->db->get(temp, i); std::cout << temp.getYear() << "." << temp.getMonth() << "." << temp.getDay() << ": " << temp.getTextRemind() << std::endl; } } void Planner::deleteRemindByIndex(int index) { Remind temp; this->db->del(temp, index); } void Planner::deleteRemindByDate(int day, int month, int year) { Remind temp; for (int i = 1; i <= this->db->size(temp); i++) { this->db->get(temp, i); if (year == temp.getYear() && month == temp.getMonth() && day == temp.getDay()) { deleteRemindByIndex(i); break; } } } void Planner::clear() { this->db->clearDb(); }
[ "arganon@yandex.ru" ]
arganon@yandex.ru
6bdadbad1f787670a5783117f57e577d8aa13752
208032477a14d8b8b43550196eb3ca148912c0fc
/Study/UITest/SObjectDX.h
090ed161c18e2702263dde04d4495a3e0cb8540f
[]
no_license
garammaru68/00_Project
8602d16fe58a7b334bbf51367f49325fc62987ba
4f0b35913d151641d23b4666ec982db4a1df94a0
refs/heads/master
2023-04-21T01:18:50.104623
2021-05-16T18:35:02
2021-05-16T18:35:02
307,921,052
0
0
null
null
null
null
UTF-8
C++
false
false
1,166
h
#pragma once #include "SCore.h" #include "TObjStd.h" class TObjectDX { public: ID3D11Buffer* m_pVertexBuffer; ID3D11Buffer* m_pConstantBuffer; ID3D11VertexShader* m_pVertexShader; ID3D11PixelShader* m_pPixelShader; ID3DBlob* m_pVSBlob; ID3DBlob* m_pPSBlob; ID3DBlob* m_pErrorBlob; ID3D11InputLayout* m_pInputlayout; ID3D11ShaderResourceView* m_pTextureSRV; public: UINT m_iNumVertex; UINT m_iVertexSize; public: HRESULT CreateVertexBuffer( ID3D11Device* pd3dDevice, PCT_VERTEX* pVertexList, int iNumCount); HRESULT CreateConstantBuffer( ID3D11Device* pd3dDevice, void* pData, int iSize); HRESULT CreateVertexShader( ID3D11Device* pd3dDevice, const TCHAR* pName); HRESULT CreatePixelShader( ID3D11Device* pd3dDevice, const TCHAR* pName); HRESULT CreateLayout( ID3D11Device* pd3dDevice, ID3DBlob* pVSBlob); HRESULT LoadTexture( ID3D11Device* pd3dDevice, const TCHAR* pLoadFile); public: bool PreRender(ID3D11DeviceContext* pContext); bool Render(ID3D11DeviceContext* pContext); bool PostRender(ID3D11DeviceContext* pContext); bool Release(); public: TObjectDX(); virtual ~TObjectDX(); };
[ "63288078+garammaru68@users.noreply.github.com" ]
63288078+garammaru68@users.noreply.github.com
78937af428c7b5afb6cc58cf91abbbde0180c922
7cadc74198e3c0edd5cf046fe5ed053e70d21c1d
/third_party/yaml/src/scantag.cpp
2815aec960b0ecb3a1c5e6b3e9ca4b022641f2d3
[ "MIT" ]
permissive
junhyeokahn/PnC
d982d75ab27faf0ee21f8d7cab42375cfb086ebd
679f12ef18bc971078ac353ea7461d69e470d29d
refs/heads/master
2023-02-05T04:02:34.142001
2023-01-12T20:36:41
2023-01-12T20:36:41
137,776,919
45
13
MIT
2022-11-28T23:05:05
2018-06-18T16:20:17
C++
UTF-8
C++
false
false
1,573
cpp
#include "exp.h" #include "regex_yaml.h" #include "regeximpl.h" #include "stream.h" #include "third_party/yaml/include/yaml/exceptions.h" // IWYU pragma: keep #include "third_party/yaml/include/yaml/mark.h" namespace YAML { const std::string ScanVerbatimTag(Stream& INPUT) { std::string tag; // eat the start character INPUT.get(); while (INPUT) { if (INPUT.peek() == Keys::VerbatimTagEnd) { // eat the end character INPUT.get(); return tag; } int n = Exp::URI().Match(INPUT); if (n <= 0) break; tag += INPUT.get(n); } throw ParserException(INPUT.mark(), ErrorMsg::END_OF_VERBATIM_TAG); } const std::string ScanTagHandle(Stream& INPUT, bool& canBeHandle) { std::string tag; canBeHandle = true; Mark firstNonWordChar; while (INPUT) { if (INPUT.peek() == Keys::Tag) { if (!canBeHandle) throw ParserException(firstNonWordChar, ErrorMsg::CHAR_IN_TAG_HANDLE); break; } int n = 0; if (canBeHandle) { n = Exp::Word().Match(INPUT); if (n <= 0) { canBeHandle = false; firstNonWordChar = INPUT.mark(); } } if (!canBeHandle) n = Exp::Tag().Match(INPUT); if (n <= 0) break; tag += INPUT.get(n); } return tag; } const std::string ScanTagSuffix(Stream& INPUT) { std::string tag; while (INPUT) { int n = Exp::Tag().Match(INPUT); if (n <= 0) break; tag += INPUT.get(n); } if (tag.empty()) throw ParserException(INPUT.mark(), ErrorMsg::TAG_WITH_NO_SUFFIX); return tag; } }
[ "junhyeokahn91@gmail.com" ]
junhyeokahn91@gmail.com
2f5c8358c3b3b1e9d0b401dd0f68538b236e4c76
42528682bf4727cb4e7380cfad40b0fe09033220
/system/dev/usb/usb-virtual-bus/usb-virtual-host.h
16ffec95c7b4cbb386c9d108af67b9bee1364c6d
[ "BSD-3-Clause", "MIT" ]
permissive
vsrinivas/zircon
ab791322f7139fd7a2b0e89352f39b39ad97e49c
f7ea3ac681cf719bd79dfd8344a33e1128a11f5b
refs/heads/master
2023-08-16T21:22:51.103045
2023-08-09T01:23:39
2023-08-09T01:23:39
167,029,710
3
3
null
null
null
null
UTF-8
C++
false
false
2,132
h
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #pragma once #include <ddk/device.h> #include <ddktl/device.h> #include <ddktl/protocol/usb/hci.h> namespace usb_virtual_bus { class UsbVirtualBus; class UsbVirtualHost; using UsbVirtualHostType = ddk::Device<UsbVirtualHost>; // This class implements the virtual USB host controller protocol. class UsbVirtualHost : public UsbVirtualHostType, public ddk::UsbHciProtocol<UsbVirtualHost, ddk::base_protocol> { public: explicit UsbVirtualHost(zx_device_t* parent, UsbVirtualBus* bus) : UsbVirtualHostType(parent), bus_(bus) {} // Device protocol implementation. void DdkRelease(); // USB host controller protocol implementation. void UsbHciRequestQueue(usb_request_t* usb_request, const usb_request_complete_t* complete_cb); void UsbHciSetBusInterface(const usb_bus_interface_t* bus_intf); size_t UsbHciGetMaxDeviceCount(); zx_status_t UsbHciEnableEndpoint(uint32_t device_id, const usb_endpoint_descriptor_t* ep_desc, const usb_ss_ep_comp_descriptor_t* ss_com_desc, bool enable); uint64_t UsbHciGetCurrentFrame(); zx_status_t UsbHciConfigureHub(uint32_t device_id, usb_speed_t speed, const usb_hub_descriptor_t* desc); zx_status_t UsbHciHubDeviceAdded(uint32_t device_id, uint32_t port, usb_speed_t speed); zx_status_t UsbHciHubDeviceRemoved(uint32_t device_id, uint32_t port); zx_status_t UsbHciHubDeviceReset(uint32_t device_id, uint32_t port); zx_status_t UsbHciResetEndpoint(uint32_t device_id, uint8_t ep_address); zx_status_t UsbHciResetDevice(uint32_t hub_address, uint32_t device_id); size_t UsbHciGetMaxTransferSize(uint32_t device_id, uint8_t ep_address); zx_status_t UsbHciCancelAll(uint32_t device_id, uint8_t ep_address); size_t UsbHciGetRequestSize(); private: DISALLOW_COPY_ASSIGN_AND_MOVE(UsbVirtualHost); UsbVirtualBus* bus_; }; } // namespace usb_virtual_bus
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
4cb6e42afbe6ce436f9bf6b1a42f78954919999f
b42c29a7fdc1d8957da449a21d505047c295e603
/CPP code/cppreview1.cpp
b2c8db5ef4c9d03f4846db3cf34486f80281e634
[]
no_license
rumikalita19/Magnitude_Interview
5d34be5a10cc74b08e88aeeabe035f1656599a37
64e78f0b25c17d4e2f2cb5a8cc76b468e45f429a
refs/heads/master
2023-05-03T19:20:53.780664
2021-05-24T09:12:54
2021-05-24T09:12:54
370,291,176
0
0
null
null
null
null
UTF-8
C++
false
false
1,742
cpp
#include <iostream> #include <cstring> using namespace std; /* class A { public: void printA() { cout << endl << "Printing A"; } void printX() { cout << endl << "Printing X" << x; } private: int x; }; class B { public: void printB() { cout << endl << "Printing B"; } virtual void printY() { cout << endl << "Printing Y" << y; } private: int y; }; int main (void) { A* aObj = NULL; B* bObj = NULL; aObj->printA(); aObj->printX(); bObj->printB(); bObj->printY(); return 0; } ////////////////////////////////////////////////// //Segmentation Fault: //1.Segmentation fault as trying to access a memory //which is not instantiated line number 51 //2.Segmentation fault as trying to access a memory //which is not instantiated line number 54 //One observation: // 1. Syntex is okay // but cout << endl << "Printing A"; // could be cout << "Printing A"<< endl; //////////////////////////////////////////////// */ class A { public: A(int input):x(input) { } A() { } virtual ~B() { } void printA() { cout << endl << "Printing A"; } void printX() { cout << endl << "Printing X" << x; } private: int x; }; class B { public: B(int input):y(input) { } B() { } virtual ~B() { } void printB() { cout << endl << "Printing B"; } virtual void printY() { cout << endl << "Printing Y" << y; } private: int y; }; int main (void) { A* aObj = new A; B* bObj = new B; aObj->printA(); aObj->printX(); bObj->printB(); bObj->printY(); delete bObj; delete aObj; return 0; }
[ "80746307+rumikalita19@users.noreply.github.com" ]
80746307+rumikalita19@users.noreply.github.com
1f93f012f9119aaa5ba0ed7364e65f8e8dc314a0
077bae5fedcb7b6f5a8c4f1284482c3ad215e088
/client/SienaWindow.cpp
7df67a3499f5d14b0cd414a6e19e7ab4e7b959f8
[]
no_license
runngezhang/archived-chime3
7d59aef8c7fda432342cfdb7e68fba2a45b028da
a3b8592117436144b092922130cb2248b6a515d6
refs/heads/master
2021-01-23T23:46:37.708039
2002-05-11T21:32:02
2002-05-11T21:32:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,806
cpp
#define SYSDEF_PATH #include "cssysdef.h" #include "cssys/sysdriv.h" #include "csws/csws.h" #include "version.h" #include "ifontsrv.h" #include "icfgnew.h" #include "ChimeWindow.h" SienaWindow::~SienaWindow() {} SienaWindow::SienaWindow(csComponent *iParent) : ChimeWindow(iParent, "Siena Settings", CSWS_TITLEBAR | CSWS_BUTCLOSE | CSWS_BUTMAXIMIZE) { this->SetSize (500, 250); this->Center (); int px = 15, py = 20; int labelw = 150; //////////create the dialog/////////////// csDialog *d = new csDialog(this); this->SetDragStyle (this->GetDragStyle () & ~CS_DRAG_SIZEABLE); //////////////////////Siena Location field////////////////////////////// csInputLine *siena_location = new csInputLine(d); siena_location->SetSize(300,30); siena_location->SetPos(px+labelw,py); //set the text to the previous value //not implemented yet //username->SetText(font->GetFontName()); csStatic *siena_lbl = new csStatic(d, siena_location, "Siena SENP:"); siena_lbl->SetRect(px, py, px+labelw,py+siena_location->bound.Height()); py += siena_location->bound.Height(); /////////////////////Setup the Chat Host////////////////////////////////// csInputLine *chat_host = new csInputLine(d); chat_host->SetSize(300,30); chat_host->SetPos(px+labelw,py); //set the text to the previous value //not implemented yet //username->SetText(font->GetFontName()); csStatic *chat_lbl = new csStatic(d, chat_host, "Chat host:"); chat_lbl->SetRect(px, py, px+labelw,py+siena_location->bound.Height()); py += chat_lbl->bound.Height(); /////////////////////Setup the port to use for Chat//////////////////////////////// csInputLine *chat_port = new csInputLine(d); chat_port->SetSize(50,30); chat_port->SetPos(px+labelw,py); //set the text to the previous value //not implemented yet //password->SetText(font->GetFontName()); csStatic *chat_port_lbl = new csStatic(d, chat_port, "Chat Port:"); chat_port_lbl->SetRect(px, py, px+labelw,py+chat_port->bound.Height()); py += chat_port->bound.Height(); //setup the accept and cancel buttons csButton *butOK = new csButton(d, 66800); butOK->SetText("Save Settings"); butOK->SetSuggestedSize(16,8); butOK->SetPos(70, 175); //cancel button csButton *butCAN = new csButton(d, 66801); butCAN->SetText("Cancel"); butCAN->SetSuggestedSize(16,8); butCAN->SetPos(300, 175); } bool SienaWindow::HandleEvent (iEvent &Event) { if (csWindow::HandleEvent (Event)) return true; switch (Event.Type) { case csevCommand: switch (Event.Command.Code) { //OK button was pressed case 66800: Close(); return true; //Cancel Button has been pressed case 66801: Close(); return true; } break; } return false; }
[ "daa82" ]
daa82
677aad956d86a63c4d9fc15e9843a8fdf103f8af
4b6e4ac158750bc070268e0f634e31cbdf76b2f4
/algorithm/sequence/pseq_panlindrome.hpp
d7a6827d3a7094d8b42299a07d2aa40263135ddb
[ "MIT" ]
permissive
yancz1989/phantom
848f660804a82a7323156517bc4b5167dec6db52
d0e1f251433ee32683125940700b74c884ab94ba
refs/heads/master
2021-01-19T02:34:16.575742
2016-08-04T01:41:28
2016-08-04T01:41:28
49,866,198
0
0
null
null
null
null
UTF-8
C++
false
false
1,107
hpp
/* * @Author: yancz1989 * @Date: 2016-07-18 23:47:41 * @Last Modified by: yancz1989 * @Last Modified time: 2016-07-21 08:01:40 */ #ifndef PHANTOM_SEQUENCE_PANLINDROME_H #define PHANTOM_SEQUENCE_PANLINDROME_H #include "../phantom_algorithm.h" namespace phantom{ namespace algorithm namespace sequence{ template <typename key_type> class Manacher{ public: int panlindrome(key_type* seq, int l, int& left){ int i, w, bl = l * 2 + 3, *rad = new int[bl], r = 0, p = 0, maxl = -1; memset(rad, 0, sizeof(int) * bl); key_type *buf = new key_type[bl]; for(i = 0, w = 2; i < l; ++i) buf[w++] = seq[i], buf[w++] = '#'; buf[0] = '$', buf[1] = '#', buf[w] = 0; for(i = 1; i < w; ++i){ rad[i] = r > i ? min(rad[p * 2 - i], r - i) : 1; while(buf[i + rad[i]] == buf[i - rad[i]]) ++rad[i]; if(i + rad[i] > r){ p = i; r = i + rad[i]; } if(maxl < rad[i]){ maxl = rad[i]; left = (buf[i] == '#') ? (i - rad[i]) / 2 : (i - 1 - rad[i]) / 2; } } delete rad; delete buf; return maxl - 1; } }; } } } #endif
[ "yancz1989@gmail.com" ]
yancz1989@gmail.com
2d7817aaeb4bb01946aea73e432082e576175d7b
fe7cdba8848ad5ca4a221275665e142367e3c3de
/SWORD/剑指offer/数学题/66.构建乘积数组.cpp
c6fc4ce452e78a364c89bedda9f3c55257ab8095
[]
no_license
ccpang96/SWORD
dda9497689c5f4ab883ea43d9e15755c41fb1af5
414e3343b1cc0aed79ef0e663b6b7ff7648ad8a1
refs/heads/master
2022-11-14T09:41:08.569283
2020-07-08T07:27:30
2020-07-08T07:27:30
266,532,932
2
0
null
null
null
null
GB18030
C++
false
false
936
cpp
/************************************************************************/ /*@File Name : 66.构建乘积数组.cpp /*@Created Date : 2020/6/11 19:32 /*@Author : ccpang(ccpang96@163.com) /*@blog : www.cnblogs.com/ccpang /*@Description : /************************************************************************/ #include<iostream> #include<vector> #include<algorithm> #include<unordered_map> #include<string> #include<sstream> #include<queue> #include<stack> using namespace std; class Solution { public: vector<int> multiply(const vector<int>& A) { vector<int>B(A.size(),1); if (A.empty()) return B; //计算坐下三角部分 for (int i = 1; i < A.size(); i++) { B[i] = B[i - 1] * A[i - 1]; } //计算右上三角部分 int temp = 1; //B[n-1]也是1 for (int i = A.size() - 2; i >= 0; i--) { temp *= A[i+1]; B[i] *= temp; } return B; } };
[ "ccpang96@163.com" ]
ccpang96@163.com
a6c7bef6df4d52b5c7177f6a6fb0f6bc57cb1b23
5d6b3b668358dd35db4936235e0b180fa23f121a
/Ejercicios/lectura_ir/lectura_ir.ino
1090068ce4a4e576da7b9d3afa5b8ac6843659c5
[]
no_license
WilliamCancino/Arduino-basico
b96ddc96831284b0b5a7b47a095a8a313ff1d5a1
056253ab20b0e831c6eceee4d36036cd9d5638d4
refs/heads/master
2020-05-30T12:24:08.084011
2019-06-01T15:40:38
2019-06-01T15:40:38
189,733,384
0
0
null
null
null
null
UTF-8
C++
false
false
838
ino
/* ----- LECTURA DEL CÓDIGO DE UNA TECLA ----- */ #include <IRremote.h> // Se utiliza esta librería para el control remoto // Pines utilizados en el proyecto int receptor = 11; IRrecv irrecv(receptor); // Se indica a la librería cual pin recibe los códigos decode_results codigo; // Objeto de clase de la librería IRremote void setup() { Serial.begin(9600); // Inicia comunicación serial irrecv.enableIRIn(); // Inicia la recepción de datos } void loop() { if(irrecv.decode(&codigo)){ // Si recibe algún código, lo almacena en "codigo" y realiza lo sigiente Serial.print("0x"); Serial.println(codigo.value, HEX); // Imprime el código leído en hexadecimal delay(500); irrecv.resume(); // Reinicia el receptor para recibir otro código } }
[ "noreply@github.com" ]
noreply@github.com
4398e057116b3c1c80d43ad5f470d0f069f16281
2580233c06f8e29de7133e8c32dab8b901a9ee2c
/src/univalue/include/univalue.h
567a4174eaec942f5a2ad1b9a3a7bc32d724b406
[ "MIT" ]
permissive
patrykwnosuch/machinecoin-core
f72c99b31b0c3ed4ceffe8143e42f216a441eb3f
b6783c857f43f7f077de594d1e03d156f5295b9c
refs/heads/master
2020-08-05T15:05:01.248034
2019-05-25T10:52:30
2019-05-25T10:52:30
212,590,089
0
0
NOASSERTION
2019-10-03T13:41:45
2019-10-03T13:41:45
null
UTF-8
C++
false
false
8,682
h
// Copyright 2014 BitPay Inc. // Copyright 2015 Machinecoin Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef __UNIVALUE_H__ #define __UNIVALUE_H__ #include <stdint.h> #include <string.h> #include <string> #include <vector> #include <map> #include <cassert> #include <sstream> // .get_int64() #include <utility> // std::pair class UniValue { public: enum VType { VNULL, VOBJ, VARR, VSTR, VNUM, VBOOL, }; UniValue() { typ = VNULL; } UniValue(UniValue::VType initialType, const std::string& initialStr = "") { typ = initialType; val = initialStr; } UniValue(uint64_t val_) { setInt(val_); } UniValue(int64_t val_) { setInt(val_); } UniValue(bool val_) { setBool(val_); } UniValue(int val_) { setInt(val_); } UniValue(double val_) { setFloat(val_); } UniValue(const std::string& val_) { setStr(val_); } UniValue(const char *val_) { std::string s(val_); setStr(s); } ~UniValue() {} void clear(); bool setNull(); bool setBool(bool val); bool setNumStr(const std::string& val); bool setInt(uint64_t val); bool setInt(int64_t val); bool setInt(int val_) { return setInt((int64_t)val_); } bool setFloat(double val); bool setStr(const std::string& val); bool setArray(); bool setObject(); enum VType getType() const { return typ; } const std::string& getValStr() const { return val; } bool empty() const { return (values.size() == 0); } size_t size() const { return values.size(); } bool getBool() const { return isTrue(); } void getObjMap(std::map<std::string,UniValue>& kv) const; bool checkObject(const std::map<std::string,UniValue::VType>& memberTypes) const; const UniValue& operator[](const std::string& key) const; const UniValue& operator[](size_t index) const; bool exists(const std::string& key) const { size_t i; return findKey(key, i); } bool isNull() const { return (typ == VNULL); } bool isTrue() const { return (typ == VBOOL) && (val == "1"); } bool isFalse() const { return (typ == VBOOL) && (val != "1"); } bool isBool() const { return (typ == VBOOL); } bool isStr() const { return (typ == VSTR); } bool isNum() const { return (typ == VNUM); } bool isArray() const { return (typ == VARR); } bool isObject() const { return (typ == VOBJ); } bool push_back(const UniValue& val); bool push_back(const std::string& val_) { UniValue tmpVal(VSTR, val_); return push_back(tmpVal); } bool push_back(const char *val_) { std::string s(val_); return push_back(s); } bool push_back(uint64_t val_) { UniValue tmpVal(val_); return push_back(tmpVal); } bool push_back(int64_t val_) { UniValue tmpVal(val_); return push_back(tmpVal); } bool push_back(int val_) { UniValue tmpVal(val_); return push_back(tmpVal); } bool push_back(double val_) { UniValue tmpVal(val_); return push_back(tmpVal); } bool push_backV(const std::vector<UniValue>& vec); void __pushKV(const std::string& key, const UniValue& val); bool pushKV(const std::string& key, const UniValue& val); bool pushKV(const std::string& key, const std::string& val_) { UniValue tmpVal(VSTR, val_); return pushKV(key, tmpVal); } bool pushKV(const std::string& key, const char *val_) { std::string _val(val_); return pushKV(key, _val); } bool pushKV(const std::string& key, int64_t val_) { UniValue tmpVal(val_); return pushKV(key, tmpVal); } bool pushKV(const std::string& key, uint64_t val_) { UniValue tmpVal(val_); return pushKV(key, tmpVal); } bool pushKV(const std::string& key, bool val_) { UniValue tmpVal((bool)val_); return pushKV(key, tmpVal); } bool pushKV(const std::string& key, int val_) { UniValue tmpVal((int64_t)val_); return pushKV(key, tmpVal); } bool pushKV(const std::string& key, double val_) { UniValue tmpVal(val_); return pushKV(key, tmpVal); } bool pushKVs(const UniValue& obj); std::string write(unsigned int prettyIndent = 0, unsigned int indentLevel = 0) const; bool read(const char *raw, size_t len); bool read(const char *raw) { return read(raw, strlen(raw)); } bool read(const std::string& rawStr) { return read(rawStr.data(), rawStr.size()); } private: UniValue::VType typ; std::string val; // numbers are stored as C++ strings std::vector<std::string> keys; std::vector<UniValue> values; bool findKey(const std::string& key, size_t& retIdx) const; void writeArray(unsigned int prettyIndent, unsigned int indentLevel, std::string& s) const; void writeObject(unsigned int prettyIndent, unsigned int indentLevel, std::string& s) const; public: // Strict type-specific getters, these throw std::runtime_error if the // value is of unexpected type const std::vector<std::string>& getKeys() const; const std::vector<UniValue>& getValues() const; bool get_bool() const; const std::string& get_str() const; int get_int() const; int64_t get_int64() const; double get_real() const; const UniValue& get_obj() const; const UniValue& get_array() const; enum VType type() const { return getType(); } bool push_back(std::pair<std::string,UniValue> pear) { return pushKV(pear.first, pear.second); } friend const UniValue& find_value( const UniValue& obj, const std::string& name); }; // // The following were added for compatibility with json_spirit. // Most duplicate other methods, and should be removed. // static inline std::pair<std::string,UniValue> Pair(const char *cKey, const char *cVal) { std::string key(cKey); UniValue uVal(cVal); return std::make_pair(key, uVal); } static inline std::pair<std::string,UniValue> Pair(const char *cKey, std::string strVal) { std::string key(cKey); UniValue uVal(strVal); return std::make_pair(key, uVal); } static inline std::pair<std::string,UniValue> Pair(const char *cKey, uint64_t u64Val) { std::string key(cKey); UniValue uVal(u64Val); return std::make_pair(key, uVal); } static inline std::pair<std::string,UniValue> Pair(const char *cKey, int64_t i64Val) { std::string key(cKey); UniValue uVal(i64Val); return std::make_pair(key, uVal); } static inline std::pair<std::string,UniValue> Pair(const char *cKey, bool iVal) { std::string key(cKey); UniValue uVal(iVal); return std::make_pair(key, uVal); } static inline std::pair<std::string,UniValue> Pair(const char *cKey, int iVal) { std::string key(cKey); UniValue uVal(iVal); return std::make_pair(key, uVal); } static inline std::pair<std::string,UniValue> Pair(const char *cKey, double dVal) { std::string key(cKey); UniValue uVal(dVal); return std::make_pair(key, uVal); } static inline std::pair<std::string,UniValue> Pair(const char *cKey, const UniValue& uVal) { std::string key(cKey); return std::make_pair(key, uVal); } static inline std::pair<std::string,UniValue> Pair(std::string key, const UniValue& uVal) { return std::make_pair(key, uVal); } enum jtokentype { JTOK_ERR = -1, JTOK_NONE = 0, // eof JTOK_OBJ_OPEN, JTOK_OBJ_CLOSE, JTOK_ARR_OPEN, JTOK_ARR_CLOSE, JTOK_COLON, JTOK_COMMA, JTOK_KW_NULL, JTOK_KW_TRUE, JTOK_KW_FALSE, JTOK_NUMBER, JTOK_STRING, }; extern enum jtokentype getJsonToken(std::string& tokenVal, unsigned int& consumed, const char *raw, const char *end); extern const char *uvTypeName(UniValue::VType t); static inline bool jsonTokenIsValue(enum jtokentype jtt) { switch (jtt) { case JTOK_KW_NULL: case JTOK_KW_TRUE: case JTOK_KW_FALSE: case JTOK_NUMBER: case JTOK_STRING: return true; default: return false; } // not reached } static inline bool json_isspace(int ch) { switch (ch) { case 0x20: case 0x09: case 0x0a: case 0x0d: return true; default: return false; } // not reached } extern const UniValue NullUniValue; const UniValue& find_value( const UniValue& obj, const std::string& name); #endif // __UNIVALUE_H__
[ "nico.lucciola@gmail.com" ]
nico.lucciola@gmail.com
b5ccccac4f6c862d8699f7d62bae47d32ec09a8d
ea8152e9e4532c2a84f46680764e23e67d5313a6
/a12/a12_p9/Circle.cpp
25b5bc805d7963191ee18dbf33e3fa90f70eb607
[ "MIT" ]
permissive
j-mathe/Programming-in-C-and-Cpp
6f227a2c6476775b5cabc80b930310de6d7034fa
ff09d8b698bf4ed8084a7d24808a642defc4b729
refs/heads/master
2023-03-15T14:00:38.801214
2020-07-04T14:17:31
2020-07-04T14:17:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
370
cpp
#include <iostream> #include <cmath> #include "Circle.h" Circle::Circle(const char *n, double a) : Area(n) { radius = a; } Circle::~Circle() { } double Circle::calcArea() const { std::cout << "calcArea of Circle..."; return radius * radius * M_PI; } double Circle::calcPerimeter() const { std::cout << "calcPerimeter of Circle..."; return (2 * M_PI * radius); }
[ "henrisota@users.noreply.github.com" ]
henrisota@users.noreply.github.com
a1e751d528f937ac65b47a86b9e0051974fb8790
d3b5aaa10450a0382e14dd0af04682f9d34f9b79
/lab02_a1.cpp
1c01a6f996fbe54c235f74fafbfb88d3d56c15d3
[]
no_license
OwaisAN/csci1060
416b16be1b43205bb9548ebd3675b92fea670d30
1bcf903e2a06b5f5d7788cf68936632c868bfbdd
refs/heads/main
2023-03-03T12:23:15.165573
2021-02-15T02:22:26
2021-02-15T02:22:26
300,767,103
0
0
null
null
null
null
UTF-8
C++
false
false
1,102
cpp
#include <iostream> #include <ctime> #include <cstdlib> using namespace std; //declare function int genRandom(int max); int main () { int rounds = 100; for (int i = 9; i < rounds; i += 10) { int max = i; int guess; int rand = genRandom(max); int x = 1; char play_again = 'Y'; while (x < 5){ cout << "Guess a location of the battleship [0," << max << "]: " << endl; cin >> guess; if (rand != guess) { x += 1; cout << "MISS!" << endl; } else { x = 5; cout << "HIT!" << endl; } } cout << "PLAY AGAIN! (Y/N) " << endl; cin >> play_again; switch (play_again){ case 'N': break; default: break; } } return 0; } //define function int genRandom(int max) { srand(time(NULL)); return (rand()%max + 1); }
[ "owais.a.n7@gmail.com" ]
owais.a.n7@gmail.com
a17a0c55ed476d8ad7c2694ff224bc556e099170
48e9625fcc35e6bf790aa5d881151906280a3554
/Sources/Elastos/LibCore/inc/org/apache/http/message/AbstractHttpMessage.h
521e4375f739d0a58dea05d9a2fe1274207a1fb3
[ "Apache-2.0" ]
permissive
suchto/ElastosRT
f3d7e163d61fe25517846add777690891aa5da2f
8a542a1d70aebee3dbc31341b7e36d8526258849
refs/heads/master
2021-01-22T20:07:56.627811
2017-03-17T02:37:51
2017-03-17T02:37:51
85,281,630
4
2
null
2017-03-17T07:08:49
2017-03-17T07:08:49
null
UTF-8
C++
false
false
7,223
h
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #ifndef __ORG_APACHE_HTTP_MESSAGE_ABSTRACTHTTPMESSAGE_H_ #define __ORG_APACHE_HTTP_MESSAGE_ABSTRACTHTTPMESSAGE_H_ #include "Elastos.CoreLibrary.Apache.h" #include "elastos/core/Object.h" using Elastos::Core::IArrayOf; using Org::Apache::Http::IHttpMessage; using Org::Apache::Http::IHeader; using Org::Apache::Http::IHeaderIterator; using Org::Apache::Http::Params::IHttpParams; namespace Org { namespace Apache { namespace Http { namespace Message { /** * Basic implementation of an HTTP message that can be modified. * * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a> * * @version $Revision: 620287 $ * * @since 4.0 */ class AbstractHttpMessage : public Object , public IHttpMessage { public: CAR_INTERFACE_DECL() virtual ~AbstractHttpMessage() {} /** * Checks if a certain header is present in this message. Header values are * ignored. * * @param name the header name to check for. * @return true if at least one header with this name is present. */ CARAPI ContainsHeader( /* [in] */ const String& name, /* [out] */ Boolean* isContain); /** * Returns all the headers with a specified name of this message. Header values * are ignored. Headers are orderd in the sequence they will be sent over a * connection. * * @param name the name of the headers to return. * @return the headers whose name property equals <code>name</code>. */ CARAPI GetHeaders( /* [in] */ const String& name, /* [out, callee] */ ArrayOf<IHeader*>** headers); /** * Returns the first header with a specified name of this message. Header * values are ignored. If there is more than one matching header in the * message the first element of {@link #getHeaders(String)} is returned. * If there is no matching header in the message <code>null</code> is * returned. * * @param name the name of the header to return. * @return the first header whose name property equals <code>name</code> * or <code>null</code> if no such header could be found. */ CARAPI GetFirstHeader( /* [in] */ const String& name, /* [out] */ IHeader** firstHeader); /** * Returns the last header with a specified name of this message. Header values * are ignored. If there is more than one matching header in the message the * last element of {@link #getHeaders(String)} is returned. If there is no * matching header in the message <code>null</code> is returned. * * @param name the name of the header to return. * @return the last header whose name property equals <code>name</code>. * or <code>null</code> if no such header could be found. */ CARAPI GetLastHeader( /* [in] */ const String& name, /* [out] */ IHeader** lastHeader); /** * Returns all the headers of this message. Headers are orderd in the sequence * they will be sent over a connection. * * @return all the headers of this message */ CARAPI GetAllHeaders( /* [out, callee] */ ArrayOf<IHeader*>** allHeaders); /** * Adds a header to this message. The header will be appended to the end of * the list. * * @param header the header to append. */ CARAPI AddHeader( /* [in] */ IHeader* header); /** * Adds a header to this message. The header will be appended to the end of * the list. * * @param name the name of the header. * @param value the value of the header. */ CARAPI AddHeader( /* [in] */ const String& name, /* [in] */ const String& value); /** * Overwrites the first header with the same name. The new header will be appended to * the end of the list, if no header with the given name can be found. * * @param header the header to set. */ CARAPI SetHeader( /* [in] */ IHeader* header); /** * Overwrites the first header with the same name. The new header will be appended to * the end of the list, if no header with the given name can be found. * * @param name the name of the header. * @param value the value of the header. */ CARAPI SetHeader( /* [in] */ const String& name, /* [in] */ const String& value); /** * Overwrites all the headers in the message. * * @param headers the array of headers to set. */ CARAPI SetHeaders( /* [in] */ ArrayOf<IHeader*>* headers); /** * Removes a header from this message. * * @param header the header to remove. */ CARAPI RemoveHeader( /* [in] */ IHeader* header); /** * Removes all headers with a certain name from this message. * * @param name The name of the headers to remove. */ CARAPI RemoveHeaders( /* [in] */ const String& name); /** * Returns an iterator of all the headers. * * @return Iterator that returns Header objects in the sequence they are * sent over a connection. */ CARAPI GetHeaderIterator( /* [out] */ IHeaderIterator** headerIterator); /** * Returns an iterator of the headers with a given name. * * @param name the name of the headers over which to iterate, or * <code>null</code> for all headers * * @return Iterator that returns Header objects with the argument name * in the sequence they are sent over a connection. */ CARAPI GetHeaderIterator( /* [in] */ const String& name, /* [out] */ IHeaderIterator** headerIterator); /** * Returns the parameters effective for this message as set by * {@link #setParams(HttpParams)}. */ CARAPI GetParams( /* [out] */ IHttpParams** httpParams); /** * Provides parameters to be used for the processing of this message. * @param params the parameters */ CARAPI SetParams( /* [in] */ IHttpParams* params); protected: AbstractHttpMessage(); CARAPI_(void) Init( /* [in] */ IHttpParams* params); CARAPI_(void) Init(); protected: AutoPtr<IHeaderGroup> mHeadergroup; AutoPtr<IHttpParams> mParams; }; } // namespace Message } // namespace Http } // namespace Apache } // namespace Org #endif // __ORG_APACHE_HTTP_MESSAGE_ABSTRACTHTTPMESSAGE_H_
[ "cao.jing@kortide.com" ]
cao.jing@kortide.com
9aa3ab5a9c481b2d359d22689ace390a17cd993f
b91dd5132c5cc2a6df2124bb678467a478d61a9f
/ast/Declaration.cpp
bae5313a58cec7d5331eabe56ec83d9d48925485
[]
no_license
GuillaumeGas/Nyx
f7ed0eb43450f325c3385065bffad2b80911efd2
2ff3b5db7969951b06919ac8cd8f4efc4e8a9f56
refs/heads/master
2023-08-18T09:32:10.434428
2023-08-17T11:53:17
2023-08-17T11:53:17
60,631,759
1
1
null
null
null
null
UTF-8
C++
false
false
195
cpp
#include "Declaration.hpp" using namespace nyx; using namespace ast; Declaration::Declaration(Position* pos) : Ast(pos) {} void Declaration::declare() {} void Declaration::staticAnalysis() {}
[ "guillaume@gas-ntic.fr" ]
guillaume@gas-ntic.fr
42c1602f8fdc85edf65a8ea509bb4282f77d48c1
5de8899a3ab6fcb4f8b0bfa14987e4783aa9cc23
/solutions/02/max.cpp
02a858968d987e7fc091c2e8bd036911d98ac3ab
[]
no_license
Knackie/codesignal
9e06ff8f4e8665cc3825fbc336a344e3ddc140b4
611fe628151647184919d584c42e96fc5a760f78
refs/heads/master
2022-07-23T21:18:20.974434
2022-06-28T08:01:17
2022-06-28T08:01:17
149,557,440
1
1
null
null
null
null
UTF-8
C++
false
false
274
cpp
int adjacentElementsProduct(std::vector<int> inputArray) { int max=-1000000000; for(int i=0;i<inputArray.size()-1;++i) { if (inputArray[i]*inputArray[i+1]>max && i<inputArray.size()-1) max = inputArray[i]*inputArray[i+1]; } return max; }
[ "noreply@github.com" ]
noreply@github.com
2473423a3dee6db03cc1e813214673c804cbecd2
178c7fa06ccc0c306dc2b63d6113406e55297648
/drishti/splineeditor.h
da94b9fb9a9f7d92a714f124e8d34bd3f184e82d
[ "MIT" ]
permissive
nci/drishti
3314726701c77e4f5f0b2dfdb1e7782489ebce34
da80a8e1f5e39c3010e9752d2053ed4aac5407aa
refs/heads/master
2023-08-03T08:58:29.843136
2023-08-01T03:53:58
2023-08-01T03:53:58
14,131,626
145
29
MIT
2021-02-04T09:33:22
2013-11-05T04:00:01
C++
UTF-8
C++
false
false
2,920
h
#ifndef SPLINE_EDITOR_H #define SPLINE_EDITOR_H #include <QWidget> #include <QAction> #include "splinetransferfunction.h" class SplineEditor : public QWidget { Q_OBJECT public : enum PointShape { CircleShape, RectangleShape }; enum LockType { LockToLeft = 0x01, LockToRight = 0x02, LockToTop = 0x04, LockToBottom = 0x08 }; enum SortType { NoSort, XSort, YSort }; enum ConnectionType { NoConnection, LineConnection, CurveConnection }; SplineEditor(QWidget*); QImage colorMapImage(); void paintEvent(QPaintEvent*); void resizeEvent(QResizeEvent*); void mouseMoveEvent(QMouseEvent*); void mouseReleaseEvent(QMouseEvent*); void mousePressEvent(QMouseEvent*); void keyPressEvent(QKeyEvent*); void enterEvent(QEvent*); void leaveEvent(QEvent*); int border() const; void setBorder(const int); QSizeF pointSize() const; void setPointSize(const QSizeF&); QRectF boundingRect() const; ConnectionType connectionType(); void setConnectionType(ConnectionType); void setConnectionPen(const QPen&); void setShapePen(const QPen&); void setShapeBrush(const QBrush&); void setHistogramImage(QImage, QImage); void setTransferFunction(SplineTransferFunction*); void setMapping(QPolygonF); void setGradLimits(int, int); void setOpmod(float, float); void show2D(bool); bool set16BitPoint(float, float); public slots : void setGradientStops(QGradientStops); private slots : void saveTransferFunctionImage_cb(); signals : void refreshDisplay(); void splineChanged(); void selectEvent(QGradientStops); void deselectEvent(); void applyUndo(bool); private : QWidget *m_parent; SplineTransferFunction *m_splineTF; bool m_showGrid; bool m_showOverlay; bool m_show2D; QImage m_histogramImage1D; QImage m_histogramImage2D; QPolygonF m_mapping; QRectF m_bounds; PointShape m_pointShape; ConnectionType m_connectionType; int m_border; bool m_dragging; bool m_moveSpine; QSizeF m_pointSize; int m_currentIndex; int m_prevCurrentIndex; int m_normalIndex; int m_hoverIndex; QPen m_pointPen; QPen m_connectionPen; QBrush m_pointBrush; QRectF pointBoundingRect(QPointF, int); QPointF convertLocalToWidget(QPointF); QPointF convertWidgetToLocal(QPointF); int checkNormalPressEvent(QMouseEvent*); void getPainterPath(QPainterPath*, QPolygonF); void paintPatchLines(QPainter*); void paintPatchEndPoints(QPainter*); void paintUnderlay(QPainter*); void paintOverlay(QPainter*); QAction *save_transferfunction_image_action; void showHelp(); void askSplineChoice(); void saveSpline(); }; #endif
[ "limaye.ajay@gmail.com" ]
limaye.ajay@gmail.com
792ef161abf749d5f642178549c573879146f272
14ed283201f4800c6dfe864ebab00bbc22e1977e
/patterns.h
fd20ccc994058abdb3279e8955437d8cd299534e
[]
no_license
Bawerlacher/Landlord-related-AI
8290fda0df53eb0f1ec32b658878e086339e104c
5623bd52ed0fc81c72cd7e30db24bd83e73ef403
refs/heads/master
2020-04-14T17:31:34.044668
2019-01-25T07:53:25
2019-01-25T07:53:25
163,983,350
0
0
null
null
null
null
UTF-8
C++
false
false
11,780
h
#ifndef PATTERNS #define PATTERNS #include<iostream> #include<cstdlib> #include<map> #include<string> #include<cstdio> #include<vector> #include<queue> #include<time.h> #include<cmath> #include<stack> #include<typeinfo> #define NUM_CARD 15 #define NUM_NUM 4 #define PAIR_LENGTH 2 #define TRI_LENGTH 3 #define QUA_LENGTH 4 #define TWO 12 #define joker 13 #define JOKER 14 using namespace std; static double alpha = 100.0; static double beta = 0.1; double Power(int p){ return alpha * exp(-beta * p); } /** the pattern class that has the basic characteristic of a pattern**/ /** variables: String name: the name of the pattern int len: the length of the pattern **/ class pattern{ private: string name; int len; public: pattern(string nam, int l){ this->name = nam; this->len = l; } string getName() const{ return name; } int getSize() const{ return len; } void setSize(int length){ len = length; } virtual vector<int> toVec() = 0; }; /** the class representing single pattern variable: int num: the number value of the single card constructor: (int number): the number value **/ class Single: public pattern{ int num; public: Single(int number):pattern("S", 1){ this->num = number; } int getNum() const{ return num; } bool operator >(const Single& s){ return num > s.getNum(); } static bool ifExist(int card[], int index){ return card[index] > 0; } double getPow(const int counter[]){ int p = 0; for (int i = num + 1; i != NUM_CARD; i++) if(counter[i] > 0) p++; return Power(p); } vector<int> toVec(){ vector<int> vec; vec.push_back(num); return vec; } }; /** the class representing pair pattern variable: int num: the number value of the pair constructor: (int number): the number value **/ class Pair: public pattern{ int num; public: Pair(int number):pattern("P", PAIR_LENGTH){ this->num = number; } int getNum() const{ return num; } bool operator >(const Pair& p){ return num > p.getNum(); } static bool ifExist(int card[], int index){ return card[index] > 1; } double getPow(const int counter[]){ int p = 0; for (int i = num + 1; i != NUM_CARD; i++) if(counter[i] >= PAIR_LENGTH) p++; return getSize() * Power(p); } vector<int> toVec(){ vector<int> vec; vec.push_back(num); vec.push_back(num); return vec; } }; /** the class representing triple pattern variable: int tri: the number value of the triple part int appd: the number value of the appendix part constructor: (int triple, int appendix, int length) **/ class Triple:public pattern{ int tri, appd; public: Triple(int triple, int appendix, int length):pattern("T", length){ this->tri = triple; this-> appd = appendix; } int getTriple() const{ return tri; } int getAppendix() const{ return appd; } bool operator >(Triple& t){ if(this->getSize() != t.getSize()) return false; else return this->tri > t.getTriple(); } static bool ifExist(int card[], int tri_index, int appd_index, int appd_length){ return (card[tri_index] >= TRI_LENGTH) && (card[appd_index] >= appd_length); } double getPow(const int counter[]){ int p = 0; for (int i = tri + 1; i != NUM_CARD; i++) if(counter[i] >= TRI_LENGTH) p++; return getSize() * Power(p); } vector<int> toVec(){ vector<int> vec; for (int i = 0; i != TRI_LENGTH; i++) vec.push_back(tri); for (int i = 0; i != getSize() - TRI_LENGTH; i++) vec.push_back(appd); return vec; } }; /** the class representing straight pattern variable: int st: the number value of the start number of a straight constructor: (int start, int length): the number value and the length **/ class Straight:public pattern{ int st; public: Straight(int start, int length):pattern("ST", length){ this->st = start; } int getStart() const{ return st; } bool operator >(const Straight& st){ if(this->getSize() != st.getSize()) return false; else return this->st > st.getStart(); } static bool ifExist(int card[], int start, int length){ for (int i = start; i != start + length; i++) if (card[i] == 0) return false; return true; } double getPow(const int counter[]){ int p = 0; for (int i = st + 1; i <= TWO - this->getSize(); i++){ bool sw = true; for (int j = 0; j != this->getSize(); j++){ if(counter[i+j] == 0){ sw = false; break; } } if (sw) p++; } return getSize() * Power(p); } vector<int> toVec(){ vector<int> vec; for (int i = st; i != st + getSize(); i++) vec.push_back(i); return vec; } }; /** the class representing straight pairs pattern variable: int start: the number value of the start card constructor: (int start, int length): the number value and the length **/ class StraightPair:public pattern{ int st; public: StraightPair(int start, int length):pattern("SP", length){ this->st = start; } int getStart() const{ return st; } bool operator >(const StraightPair& sp){ if(this->getSize() != sp.getSize()) return false; else return this->st > sp.getStart(); } static bool ifExist(int card[], int start, int length){ for (int i = start; i != start + length; i++) if (card[i] < PAIR_LENGTH) return false; return true; } double getPow(const int counter[]){ int p = 0; for (int i = st; i <= TWO - this->getSize(); i++){ bool sw = true; for (int j = 0; j != this->getSize(); j++){ if(counter[i+j] < PAIR_LENGTH){ sw = false; break; } } if (sw) p++; } return getSize() * 2 * Power(p); } vector<int> toVec(){ vector<int> vec; for (int i = st; i != st + getSize(); i++){ vec.push_back(i); vec.push_back(i); } return vec; } }; /** the class representing plane pattern. **/ class Plane:public pattern{ int st, tri_num; vector<Triple> tri_set; public: Plane(int startTriple, int triples_num, vector<Triple> TripleSet, int length): pattern("PL", length){ this->st = startTriple; this->tri_num = triples_num; this->tri_set = TripleSet; } int getStartTriple() const{ return st; } vector<Triple> getTripleSet() const{ return tri_set; } bool operator >(const Plane& plane){ if (this->getSize() != plane.getSize()) return false; else{ return this->st > plane.getStartTriple(); } } static bool ifExist(int card[], int st, int length){ for (int i = st; i != st + length; i++) if (card[i] < TRI_LENGTH) return false; return true; } double getPow(const int counter[]){ int p = 0; for (int i = st + 1; i < TWO - tri_num; i++){ if(counter[i] >= TRI_LENGTH){ for (int j = 1; j != tri_num; j++){ if (counter[i + j] < TRI_LENGTH) break; if (j == tri_num - 1) p++; } } } return getSize() * Power(p); } vector<int> toVec(){ vector<int> vec; for (int i = 0; i != tri_set.size(); i++){ vector<int> temp = tri_set[i].toVec(); for (int j = 0; j != temp.size(); j++) vec.push_back(temp[j]); } return vec; } }; /** the class representing bomb pattern variable: int num: the number value of the bomb constructor: (int number, int length): the number value and length **/ class Bomb:public pattern{ int num; public: Bomb(int number, int length):pattern("B", length){ num = number; } int getNum() const{ return num; } bool operator >(const Bomb& b){ return num > b.getNum(); } static bool ifExist(int card[], int index){ if(index == JOKER || index == joker) return card[joker] && card[JOKER]; else return card[index] == QUA_LENGTH; } double getPow(const int counter[]){ int p = 0; for (int i = num + 1 ; i != NUM_CARD - 1; i++){ if(i == joker && counter[joker] && counter[JOKER]) p++; else if (counter[i] == QUA_LENGTH) p++; } return getSize() * 2 * Power(p); } vector<int> toVec(){ vector<int> vec; if (num == joker){ vec.push_back(joker); vec.push_back(JOKER); } else{ for (int i = 0; i != QUA_LENGTH; i++) vec.push_back(num); } return vec; } }; /** the class representing quadruple pattern variable: int quad: the number value of the quadruple part int appd1: the number value of the appendix part 1 int appd2: the number value of the appendix part 2 **/ class Quadruple:public pattern{ int quad, appd1, appd2; public: Quadruple(int quadruple, int appd1, int appd2, int length):pattern("Q", length){ this->quad = quadruple; this->appd1 = appd1; this->appd2 = appd2; } int getQuad() const{ return quad; } bool operator >(const Quadruple& qua){ if (this->getSize() != qua.getSize()) return false; else return quad > qua.getQuad(); } static bool ifExist(int card[], int qua_index, int appd1_index, int appd2_index, int appd_length){ return (card[qua_index] == QUA_LENGTH) && (card[appd1_index] >= appd_length) && (card[appd2_index] >= appd_length); } double getPow(const int counter[]){ int p = 0; for (int i = quad + 1 ; i != NUM_CARD; i++){ if (counter[i] == QUA_LENGTH) p++; } return getSize() * 2 * Power(p); } vector<int> toVec(){ vector<int> vec; for (int i = 0; i != QUA_LENGTH; i++) vec.push_back(quad); for (int i = 0; i != (getSize() - QUA_LENGTH) / 2; i++) vec.push_back(appd1); for (int i = 0; i != (getSize() - QUA_LENGTH) / 2; i++) vec.push_back(appd2); return vec; } }; #endif // PATTERNS
[ "noreply@github.com" ]
noreply@github.com
418eb9cf2f6215be9ed2d122bfc65766aa0875fe
96796bf99ecb822d5f105d2de7085a087980a036
/Lib/MSPDebugStack/DLL430_v3/src/TI/DLL430/FileWriterIntel.h
92f1d1e31008b95839057ed8dffc6c29c5e0a640
[ "LicenseRef-scancode-public-domain" ]
permissive
imammashur/MSPFETSim
bf04152e20c7be3a71b25a18eda2946de5251b3a
1313eedd83d93687b1ea8d2233cea8470cf86769
refs/heads/master
2023-09-02T03:15:27.132271
2021-11-14T03:07:00
2021-11-14T03:07:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,206
h
/* * FileWriterIntel.h * * File writer for Intel hex files * * Copyright (C) 2008 - 2014 Texas Instruments Incorporated - http://www.ti.com/ * * * 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 Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "FileWriter.h" namespace TI { namespace DLL430 { struct DataSegment; class FileWriterIntel : public FileWriter { public: explicit FileWriterIntel(const char* filename); virtual void write(const MemoryContent& src); private: void writeRecord(uint8_t size, uint16_t address, uint8_t type, const uint8_t* data); void writeSegment(const DataSegment& segment); std::ofstream file; }; } }
[ "dave@heytoaster.com" ]
dave@heytoaster.com
a1f055e662efd917d64e4f47c81e30e992b43ddb
a07d1ae886800fe3758203683d6067089322b78c
/src/armnn/test/TestNameAndDescriptorLayerVisitor.hpp
f1936d6847d0228b72ac6b9a3a365b4382148d7d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
oubotong/arm-secure-nn-1
7a896f15e20636493a485b5a8ea71081bb8af12a
a92eba03be9a4df62f21d2494869e74b44de3364
refs/heads/master
2023-03-17T17:22:54.972293
2020-04-14T14:36:58
2020-04-14T14:36:58
557,095,350
1
0
MIT
2022-10-25T04:11:50
2022-10-25T04:11:49
null
UTF-8
C++
false
false
26,015
hpp
// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include <armnn/ArmNN.hpp> #include "TestLayerVisitor.hpp" #include <boost/test/unit_test.hpp> namespace armnn { // Concrete TestLayerVisitor subclasses for layers taking Descriptor argument with overridden VisitLayer methods class TestPermuteLayerVisitor : public TestLayerVisitor { private: const PermuteDescriptor m_VisitorDescriptor; public: explicit TestPermuteLayerVisitor(const PermuteDescriptor& permuteDescriptor, const char* name = nullptr) : TestLayerVisitor(name) , m_VisitorDescriptor(permuteDescriptor.m_DimMappings) {}; void CheckDescriptor(const PermuteDescriptor& permuteDescriptor) { if (permuteDescriptor.m_DimMappings.GetSize() == m_VisitorDescriptor.m_DimMappings.GetSize()) { for (unsigned int i = 0; i < permuteDescriptor.m_DimMappings.GetSize(); ++i) { BOOST_CHECK_EQUAL(permuteDescriptor.m_DimMappings[i], m_VisitorDescriptor.m_DimMappings[i]); } } else { BOOST_ERROR("Unequal vector size for batchToSpaceNdDescriptor m_DimMappings."); } }; void VisitPermuteLayer(const IConnectableLayer* layer, const PermuteDescriptor& permuteDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(permuteDescriptor); CheckLayerName(name); }; }; class TestBatchToSpaceNdLayerVisitor : public TestLayerVisitor { private: BatchToSpaceNdDescriptor m_VisitorDescriptor; public: explicit TestBatchToSpaceNdLayerVisitor(const BatchToSpaceNdDescriptor& batchToSpaceNdDescriptor, const char* name = nullptr) : TestLayerVisitor(name) , m_VisitorDescriptor(batchToSpaceNdDescriptor.m_BlockShape, batchToSpaceNdDescriptor.m_Crops) { m_VisitorDescriptor.m_DataLayout = batchToSpaceNdDescriptor.m_DataLayout; }; void CheckDescriptor(const BatchToSpaceNdDescriptor& batchToSpaceNdDescriptor) { if (batchToSpaceNdDescriptor.m_BlockShape.size() == m_VisitorDescriptor.m_BlockShape.size()) { for (unsigned int i = 0; i < batchToSpaceNdDescriptor.m_BlockShape.size(); ++i) { BOOST_CHECK_EQUAL(batchToSpaceNdDescriptor.m_BlockShape[i], m_VisitorDescriptor.m_BlockShape[i]); } } else { BOOST_ERROR("Unequal vector size for batchToSpaceNdDescriptor m_BlockShape."); } if (batchToSpaceNdDescriptor.m_Crops.size() == m_VisitorDescriptor.m_Crops.size()) { for (unsigned int i = 0; i < batchToSpaceNdDescriptor.m_Crops.size(); ++i) { BOOST_CHECK_EQUAL(batchToSpaceNdDescriptor.m_Crops[i].first, m_VisitorDescriptor.m_Crops[i].first); BOOST_CHECK_EQUAL(batchToSpaceNdDescriptor.m_Crops[i].second, m_VisitorDescriptor.m_Crops[i].second); } } else { BOOST_ERROR("Unequal vector size for batchToSpaceNdDescriptor m_Crops."); } BOOST_CHECK(batchToSpaceNdDescriptor.m_DataLayout == m_VisitorDescriptor.m_DataLayout); } void VisitBatchToSpaceNdLayer(const IConnectableLayer* layer, const BatchToSpaceNdDescriptor& batchToSpaceNdDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(batchToSpaceNdDescriptor); CheckLayerName(name); }; }; class TestPooling2dLayerVisitor : public TestLayerVisitor { private: Pooling2dDescriptor m_VisitorDescriptor; public: explicit TestPooling2dLayerVisitor(const Pooling2dDescriptor& pooling2dDescriptor, const char* name = nullptr) : TestLayerVisitor(name) { m_VisitorDescriptor.m_PoolType = pooling2dDescriptor.m_PoolType; m_VisitorDescriptor.m_PadLeft = pooling2dDescriptor.m_PadLeft; m_VisitorDescriptor.m_PadRight = pooling2dDescriptor.m_PadRight; m_VisitorDescriptor.m_PadTop = pooling2dDescriptor.m_PadTop; m_VisitorDescriptor.m_PadBottom = pooling2dDescriptor.m_PadBottom; m_VisitorDescriptor.m_PoolWidth = pooling2dDescriptor.m_PoolWidth; m_VisitorDescriptor.m_PoolHeight = pooling2dDescriptor.m_PoolHeight; m_VisitorDescriptor.m_StrideX = pooling2dDescriptor.m_StrideX; m_VisitorDescriptor.m_StrideY = pooling2dDescriptor.m_StrideY; m_VisitorDescriptor.m_OutputShapeRounding = pooling2dDescriptor.m_OutputShapeRounding; m_VisitorDescriptor.m_PaddingMethod = pooling2dDescriptor.m_PaddingMethod; m_VisitorDescriptor.m_DataLayout = pooling2dDescriptor.m_DataLayout; }; void CheckDescriptor(const Pooling2dDescriptor& pooling2dDescriptor) { BOOST_CHECK(pooling2dDescriptor.m_PoolType == m_VisitorDescriptor.m_PoolType); BOOST_CHECK_EQUAL(pooling2dDescriptor.m_PadLeft, m_VisitorDescriptor.m_PadLeft); BOOST_CHECK_EQUAL(pooling2dDescriptor.m_PadRight, m_VisitorDescriptor.m_PadRight); BOOST_CHECK_EQUAL(pooling2dDescriptor.m_PadTop, m_VisitorDescriptor.m_PadTop); BOOST_CHECK_EQUAL(pooling2dDescriptor.m_PadBottom, m_VisitorDescriptor.m_PadBottom); BOOST_CHECK_EQUAL(pooling2dDescriptor.m_PoolWidth, m_VisitorDescriptor.m_PoolWidth); BOOST_CHECK_EQUAL(pooling2dDescriptor.m_PoolHeight, m_VisitorDescriptor.m_PoolHeight); BOOST_CHECK_EQUAL(pooling2dDescriptor.m_StrideX, m_VisitorDescriptor.m_StrideX); BOOST_CHECK_EQUAL(pooling2dDescriptor.m_StrideY, m_VisitorDescriptor.m_StrideY); BOOST_CHECK(pooling2dDescriptor.m_OutputShapeRounding == m_VisitorDescriptor.m_OutputShapeRounding); BOOST_CHECK(pooling2dDescriptor.m_PaddingMethod == m_VisitorDescriptor.m_PaddingMethod); BOOST_CHECK(pooling2dDescriptor.m_DataLayout == m_VisitorDescriptor.m_DataLayout); } void VisitPooling2dLayer(const IConnectableLayer* layer, const Pooling2dDescriptor& pooling2dDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(pooling2dDescriptor); CheckLayerName(name); }; }; class TestActivationLayerVisitor : public TestLayerVisitor { private: ActivationDescriptor m_VisitorDescriptor; public: explicit TestActivationLayerVisitor(const ActivationDescriptor& activationDescriptor, const char* name = nullptr) : TestLayerVisitor(name) { m_VisitorDescriptor.m_Function = activationDescriptor.m_Function; m_VisitorDescriptor.m_A = activationDescriptor.m_A; m_VisitorDescriptor.m_B = activationDescriptor.m_B; }; void CheckDescriptor(const ActivationDescriptor& activationDescriptor) { BOOST_CHECK(activationDescriptor.m_Function == m_VisitorDescriptor.m_Function); BOOST_CHECK_EQUAL(activationDescriptor.m_A, m_VisitorDescriptor.m_A); BOOST_CHECK_EQUAL(activationDescriptor.m_B, m_VisitorDescriptor.m_B); }; void VisitActivationLayer(const IConnectableLayer* layer, const ActivationDescriptor& activationDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(activationDescriptor); CheckLayerName(name); }; }; class TestNormalizationLayerVisitor : public TestLayerVisitor { private: NormalizationDescriptor m_VisitorDescriptor; public: explicit TestNormalizationLayerVisitor(const NormalizationDescriptor& normalizationDescriptor, const char* name = nullptr) : TestLayerVisitor(name) { m_VisitorDescriptor.m_NormChannelType = normalizationDescriptor.m_NormChannelType; m_VisitorDescriptor.m_NormMethodType = normalizationDescriptor.m_NormMethodType; m_VisitorDescriptor.m_NormSize = normalizationDescriptor.m_NormSize; m_VisitorDescriptor.m_Alpha = normalizationDescriptor.m_Alpha; m_VisitorDescriptor.m_Beta = normalizationDescriptor.m_Beta; m_VisitorDescriptor.m_K = normalizationDescriptor.m_K; m_VisitorDescriptor.m_DataLayout = normalizationDescriptor.m_DataLayout; }; void CheckDescriptor(const NormalizationDescriptor& normalizationDescriptor) { BOOST_CHECK(normalizationDescriptor.m_NormChannelType == m_VisitorDescriptor.m_NormChannelType); BOOST_CHECK(normalizationDescriptor.m_NormMethodType == m_VisitorDescriptor.m_NormMethodType); BOOST_CHECK_EQUAL(normalizationDescriptor.m_NormSize, m_VisitorDescriptor.m_NormSize); BOOST_CHECK_EQUAL(normalizationDescriptor.m_Alpha, m_VisitorDescriptor.m_Alpha); BOOST_CHECK_EQUAL(normalizationDescriptor.m_Beta, m_VisitorDescriptor.m_Beta); BOOST_CHECK_EQUAL(normalizationDescriptor.m_K, m_VisitorDescriptor.m_K); BOOST_CHECK(normalizationDescriptor.m_DataLayout == m_VisitorDescriptor.m_DataLayout); } void VisitNormalizationLayer(const IConnectableLayer* layer, const NormalizationDescriptor& normalizationDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(normalizationDescriptor); CheckLayerName(name); }; }; class TestSoftmaxLayerVisitor : public TestLayerVisitor { private: SoftmaxDescriptor m_VisitorDescriptor; public: explicit TestSoftmaxLayerVisitor(const SoftmaxDescriptor& softmaxDescriptor, const char* name = nullptr) : TestLayerVisitor(name) { m_VisitorDescriptor.m_Beta = softmaxDescriptor.m_Beta; }; void CheckDescriptor(const SoftmaxDescriptor& softmaxDescriptor) { BOOST_CHECK_EQUAL(softmaxDescriptor.m_Beta, m_VisitorDescriptor.m_Beta); } void VisitSoftmaxLayer(const IConnectableLayer* layer, const SoftmaxDescriptor& softmaxDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(softmaxDescriptor); CheckLayerName(name); }; }; class TestSplitterLayerVisitor : public TestLayerVisitor { private: ViewsDescriptor m_VisitorDescriptor; public: explicit TestSplitterLayerVisitor(const ViewsDescriptor& splitterDescriptor, const char* name = nullptr) : TestLayerVisitor(name) , m_VisitorDescriptor(splitterDescriptor.GetNumViews(), splitterDescriptor.GetNumDimensions()) { if (splitterDescriptor.GetNumViews() != m_VisitorDescriptor.GetNumViews()) { BOOST_ERROR("Unequal number of views in splitter descriptor."); } else if (splitterDescriptor.GetNumDimensions() != m_VisitorDescriptor.GetNumDimensions()) { BOOST_ERROR("Unequal number of dimensions in splitter descriptor."); } else { for (unsigned int i = 0; i < splitterDescriptor.GetNumViews(); ++i) { for (unsigned int j = 0; j < splitterDescriptor.GetNumDimensions(); ++j) { m_VisitorDescriptor.SetViewOriginCoord(i, j, splitterDescriptor.GetViewOrigin(i)[j]); m_VisitorDescriptor.SetViewSize(i, j, splitterDescriptor.GetViewSizes(i)[j]); } } } }; void CheckDescriptor(const ViewsDescriptor& splitterDescriptor) { BOOST_CHECK_EQUAL(splitterDescriptor.GetNumViews(), m_VisitorDescriptor.GetNumViews()); BOOST_CHECK_EQUAL(splitterDescriptor.GetNumDimensions(), m_VisitorDescriptor.GetNumDimensions()); if (splitterDescriptor.GetNumViews() != m_VisitorDescriptor.GetNumViews()) { BOOST_ERROR("Unequal number of views in splitter descriptor."); } else if (splitterDescriptor.GetNumDimensions() != m_VisitorDescriptor.GetNumDimensions()) { BOOST_ERROR("Unequal number of dimensions in splitter descriptor."); } else { for (unsigned int i = 0; i < splitterDescriptor.GetNumViews(); ++i) { for (unsigned int j = 0; j < splitterDescriptor.GetNumDimensions(); ++j) { BOOST_CHECK_EQUAL(splitterDescriptor.GetViewOrigin(i)[j], m_VisitorDescriptor.GetViewOrigin(i)[j]); BOOST_CHECK_EQUAL(splitterDescriptor.GetViewSizes(i)[j], m_VisitorDescriptor.GetViewSizes(i)[j]); } } } }; void VisitSplitterLayer(const IConnectableLayer* layer, const ViewsDescriptor& splitterDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(splitterDescriptor); CheckLayerName(name); }; }; class TestConcatLayerVisitor : public TestLayerVisitor { private: OriginsDescriptor m_VisitorDescriptor; public: explicit TestConcatLayerVisitor(const OriginsDescriptor& concatDescriptor, const char* name = nullptr) : TestLayerVisitor(name) , m_VisitorDescriptor(concatDescriptor.GetNumViews(), concatDescriptor.GetNumDimensions()) { m_VisitorDescriptor.SetConcatAxis(concatDescriptor.GetConcatAxis()); if (concatDescriptor.GetNumViews() != m_VisitorDescriptor.GetNumViews()) { BOOST_ERROR("Unequal number of views in splitter descriptor."); } else if (concatDescriptor.GetNumDimensions() != m_VisitorDescriptor.GetNumDimensions()) { BOOST_ERROR("Unequal number of dimensions in splitter descriptor."); } else { for (unsigned int i = 0; i < concatDescriptor.GetNumViews(); ++i) { for (unsigned int j = 0; j < concatDescriptor.GetNumDimensions(); ++j) { m_VisitorDescriptor.SetViewOriginCoord(i, j, concatDescriptor.GetViewOrigin(i)[j]); } } } }; void CheckDescriptor(const OriginsDescriptor& concatDescriptor) { BOOST_CHECK_EQUAL(concatDescriptor.GetNumViews(), m_VisitorDescriptor.GetNumViews()); BOOST_CHECK_EQUAL(concatDescriptor.GetNumDimensions(), m_VisitorDescriptor.GetNumDimensions()); BOOST_CHECK_EQUAL(concatDescriptor.GetConcatAxis(), m_VisitorDescriptor.GetConcatAxis()); if (concatDescriptor.GetNumViews() != m_VisitorDescriptor.GetNumViews()) { BOOST_ERROR("Unequal number of views in splitter descriptor."); } else if (concatDescriptor.GetNumDimensions() != m_VisitorDescriptor.GetNumDimensions()) { BOOST_ERROR("Unequal number of dimensions in splitter descriptor."); } else { for (unsigned int i = 0; i < concatDescriptor.GetNumViews(); ++i) { for (unsigned int j = 0; j < concatDescriptor.GetNumDimensions(); ++j) { BOOST_CHECK_EQUAL(concatDescriptor.GetViewOrigin(i)[j], m_VisitorDescriptor.GetViewOrigin(i)[j]); } } } } void VisitConcatLayer(const IConnectableLayer* layer, const OriginsDescriptor& concatDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(concatDescriptor); CheckLayerName(name); }; }; class TestResizeLayerVisitor : public TestLayerVisitor { private: ResizeDescriptor m_VisitorDescriptor; public: explicit TestResizeLayerVisitor(const ResizeDescriptor& descriptor, const char* name = nullptr) : TestLayerVisitor(name) { m_VisitorDescriptor.m_Method = descriptor.m_Method; m_VisitorDescriptor.m_TargetWidth = descriptor.m_TargetWidth; m_VisitorDescriptor.m_TargetHeight = descriptor.m_TargetHeight; m_VisitorDescriptor.m_DataLayout = descriptor.m_DataLayout; }; void CheckDescriptor(const ResizeDescriptor& descriptor) { BOOST_CHECK(descriptor.m_Method == m_VisitorDescriptor.m_Method); BOOST_CHECK(descriptor.m_TargetWidth == m_VisitorDescriptor.m_TargetWidth); BOOST_CHECK(descriptor.m_TargetHeight == m_VisitorDescriptor.m_TargetHeight); BOOST_CHECK(descriptor.m_DataLayout == m_VisitorDescriptor.m_DataLayout); } void VisitResizeLayer(const IConnectableLayer* layer, const ResizeDescriptor& descriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(descriptor); CheckLayerName(name); }; }; class TestL2NormalizationLayerVisitor : public TestLayerVisitor { private: L2NormalizationDescriptor m_VisitorDescriptor; public: explicit TestL2NormalizationLayerVisitor(const L2NormalizationDescriptor& desc, const char* name = nullptr) : TestLayerVisitor(name) { m_VisitorDescriptor.m_DataLayout = desc.m_DataLayout; }; void CheckDescriptor(const L2NormalizationDescriptor& desc) { BOOST_CHECK(desc.m_DataLayout == m_VisitorDescriptor.m_DataLayout); } void VisitL2NormalizationLayer(const IConnectableLayer* layer, const L2NormalizationDescriptor& desc, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(desc); CheckLayerName(name); }; }; class TestReshapeLayerVisitor : public TestLayerVisitor { private: const ReshapeDescriptor m_VisitorDescriptor; public: explicit TestReshapeLayerVisitor(const ReshapeDescriptor& reshapeDescriptor, const char* name = nullptr) : TestLayerVisitor(name) , m_VisitorDescriptor(reshapeDescriptor.m_TargetShape) {}; void CheckDescriptor(const ReshapeDescriptor& reshapeDescriptor) { BOOST_CHECK_MESSAGE(reshapeDescriptor.m_TargetShape == m_VisitorDescriptor.m_TargetShape, reshapeDescriptor.m_TargetShape << " compared to " << m_VisitorDescriptor.m_TargetShape); } void VisitReshapeLayer(const IConnectableLayer* layer, const ReshapeDescriptor& reshapeDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(reshapeDescriptor); CheckLayerName(name); }; }; class TestSpaceToBatchNdLayerVisitor : public TestLayerVisitor { private: SpaceToBatchNdDescriptor m_VisitorDescriptor; public: explicit TestSpaceToBatchNdLayerVisitor(const SpaceToBatchNdDescriptor& desc, const char* name = nullptr) : TestLayerVisitor(name) , m_VisitorDescriptor(desc.m_BlockShape, desc.m_PadList) { m_VisitorDescriptor.m_DataLayout = desc.m_DataLayout; }; void CheckDescriptor(const SpaceToBatchNdDescriptor& desc) { if (desc.m_BlockShape.size() == m_VisitorDescriptor.m_BlockShape.size()) { for (unsigned int i = 0; i < desc.m_BlockShape.size(); ++i) { BOOST_CHECK_EQUAL(desc.m_BlockShape[i], m_VisitorDescriptor.m_BlockShape[i]); } } else { BOOST_ERROR("Unequal vector size for SpaceToBatchNdDescriptor m_BlockShape."); } if (desc.m_PadList.size() == m_VisitorDescriptor.m_PadList.size()) { for (unsigned int i = 0; i < desc.m_PadList.size(); ++i) { BOOST_CHECK_EQUAL(desc.m_PadList[i].first, m_VisitorDescriptor.m_PadList[i].first); BOOST_CHECK_EQUAL(desc.m_PadList[i].second, m_VisitorDescriptor.m_PadList[i].second); } } else { BOOST_ERROR("Unequal vector size for SpaceToBatchNdDescriptor m_PadList."); } BOOST_CHECK(desc.m_DataLayout == m_VisitorDescriptor.m_DataLayout); } void VisitSpaceToBatchNdLayer(const IConnectableLayer* layer, const SpaceToBatchNdDescriptor& desc, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(desc); CheckLayerName(name); }; }; class TestMeanLayerVisitor : public TestLayerVisitor { private: const MeanDescriptor m_VisitorDescriptor; public: explicit TestMeanLayerVisitor(const MeanDescriptor& meanDescriptor, const char* name = nullptr) : TestLayerVisitor(name) , m_VisitorDescriptor(meanDescriptor.m_Axis, meanDescriptor.m_KeepDims) {}; void CheckDescriptor(const MeanDescriptor& meanDescriptor) { if (meanDescriptor.m_Axis.size() == m_VisitorDescriptor.m_Axis.size()) { for (unsigned int i = 0; i < meanDescriptor.m_Axis.size(); ++i) { BOOST_CHECK_EQUAL(meanDescriptor.m_Axis[i], m_VisitorDescriptor.m_Axis[i]); } } else { BOOST_ERROR("Unequal vector size for MeanDescriptor m_Axis."); } BOOST_CHECK_EQUAL(meanDescriptor.m_KeepDims, m_VisitorDescriptor.m_KeepDims); } void VisitMeanLayer(const IConnectableLayer* layer, const MeanDescriptor& meanDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(meanDescriptor); CheckLayerName(name); }; }; class TestPadLayerVisitor : public TestLayerVisitor { private: const PadDescriptor m_VisitorDescriptor; public: explicit TestPadLayerVisitor(const PadDescriptor& padDescriptor, const char* name = nullptr) : TestLayerVisitor(name) , m_VisitorDescriptor(padDescriptor.m_PadList) {}; void CheckDescriptor(const PadDescriptor& padDescriptor) { if (padDescriptor.m_PadList.size() == m_VisitorDescriptor.m_PadList.size()) { for (unsigned int i = 0; i < padDescriptor.m_PadList.size(); ++i) { BOOST_CHECK_EQUAL(padDescriptor.m_PadList[i].first, m_VisitorDescriptor.m_PadList[i].first); BOOST_CHECK_EQUAL(padDescriptor.m_PadList[i].second, m_VisitorDescriptor.m_PadList[i].second); } } else { BOOST_ERROR("Unequal vector size for SpaceToBatchNdDescriptor m_PadList."); } } void VisitPadLayer(const IConnectableLayer* layer, const PadDescriptor& padDescriptor, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(padDescriptor); CheckLayerName(name); }; }; class TestStridedSliceLayerVisitor : public TestLayerVisitor { private: StridedSliceDescriptor m_VisitorDescriptor; public: explicit TestStridedSliceLayerVisitor(const StridedSliceDescriptor& desc, const char* name = nullptr) : TestLayerVisitor(name) , m_VisitorDescriptor(desc.m_Begin, desc.m_End, desc.m_Stride) { m_VisitorDescriptor.m_BeginMask = desc.m_BeginMask; m_VisitorDescriptor.m_EndMask = desc.m_EndMask; m_VisitorDescriptor.m_ShrinkAxisMask = desc.m_ShrinkAxisMask; m_VisitorDescriptor.m_EllipsisMask = desc.m_EllipsisMask; m_VisitorDescriptor.m_NewAxisMask = desc.m_NewAxisMask; m_VisitorDescriptor.m_DataLayout = desc.m_DataLayout; }; void CheckDescriptor(const StridedSliceDescriptor& desc) { if (desc.m_Begin.size() == m_VisitorDescriptor.m_Begin.size()) { for (unsigned int i = 0; i < desc.m_Begin.size(); ++i) { BOOST_CHECK_EQUAL(desc.m_Begin[i], m_VisitorDescriptor.m_Begin[i]); } } else { BOOST_ERROR("Unequal vector size for StridedSliceDescriptor m_Begin."); } if (desc.m_End.size() == m_VisitorDescriptor.m_End.size()) { for (unsigned int i = 0; i < desc.m_End.size(); ++i) { BOOST_CHECK_EQUAL(desc.m_End[i], m_VisitorDescriptor.m_End[i]); } } else { BOOST_ERROR("Unequal vector size for StridedSliceDescriptor m_End."); } if (desc.m_Stride.size() == m_VisitorDescriptor.m_Stride.size()) { for (unsigned int i = 0; i < desc.m_Stride.size(); ++i) { BOOST_CHECK_EQUAL(desc.m_Stride[i], m_VisitorDescriptor.m_Stride[i]); } } else { BOOST_ERROR("Unequal vector size for StridedSliceDescriptor m_Stride."); } BOOST_CHECK_EQUAL(desc.m_BeginMask, m_VisitorDescriptor.m_BeginMask); BOOST_CHECK_EQUAL(desc.m_EndMask, m_VisitorDescriptor.m_EndMask); BOOST_CHECK_EQUAL(desc.m_ShrinkAxisMask, m_VisitorDescriptor.m_ShrinkAxisMask); BOOST_CHECK_EQUAL(desc.m_EllipsisMask, m_VisitorDescriptor.m_EllipsisMask); BOOST_CHECK_EQUAL(desc.m_NewAxisMask, m_VisitorDescriptor.m_NewAxisMask); BOOST_CHECK(desc.m_DataLayout == m_VisitorDescriptor.m_DataLayout); } void VisitStridedSliceLayer(const IConnectableLayer* layer, const StridedSliceDescriptor& desc, const char* name = nullptr) override { CheckLayerPointer(layer); CheckDescriptor(desc); CheckLayerName(name); }; }; } //namespace armnn
[ "i.am.renju.liu@gmail.com" ]
i.am.renju.liu@gmail.com
b4eeb458ce1f994b5b9490bbe0cc06d5aca2ce61
bfa93c468632492f8dc21965fd595018f3ed6e4a
/src/simulator/simulator.cc
1a255ca3499a485621c2be2e062f300efebc059e
[]
no_license
JacobSzwejbka/f1tenth_course
ef30f5d76e7bd8032127bfcfb8707b0b738b004a
f1720a0caf46df30d0dc3be89590d84d52c9fc6f
refs/heads/master
2020-12-20T09:04:22.104115
2020-01-24T00:38:35
2020-01-24T00:38:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,556
cc
//======================================================================== // This software is free: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License Version 3, // as published by the Free Software Foundation. // // This software 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 // Version 3 in the file COPYING that came with this distribution. // If not, see <http://www.gnu.org/licenses/>. //======================================================================== /*! \file simulator.h \brief C++ Implementation: Simulator \author Joydeep Biswas, (C) 2011 */ //======================================================================== #include <math.h> #include <stdio.h> #include <random> #include "eigen3/Eigen/Dense" #include "eigen3/Eigen/Geometry" #include "f1tenth_course/AckermannCurvatureDriveMsg.h" #include "geometry_msgs/Pose2D.h" #include "geometry_msgs/PoseWithCovarianceStamped.h" #include "gflags/gflags.h" #include "simulator.h" #include "config_reader/config_reader.h" #include "shared/math/geometry.h" #include "shared/math/line2d.h" #include "shared/math/math_util.h" #include "shared/ros/ros_helpers.h" #include "shared/util/timer.h" #include "vector_map.h" DEFINE_bool(localize, false, "Publish localization"); using Eigen::Rotation2Df; using Eigen::Vector2f; using f1tenth_course::AckermannCurvatureDriveMsg; using geometry::Heading; using geometry::line2f; using geometry_msgs::PoseWithCovarianceStamped; using math_util::AngleMod; using math_util::DegToRad; using math_util::RadToDeg; using std::atan2; using vector_map::VectorMap; CONFIG_STRING(cMapName, "map_name"); CONFIG_FLOAT(cCarLength, "car_length"); CONFIG_FLOAT(cCarWidth, "car_width"); CONFIG_FLOAT(cCarHeight, "car_height"); CONFIG_FLOAT(cRearAxleOffset, "rear_axle_offset"); CONFIG_FLOAT(cLaserLocX, "laser_loc.x"); CONFIG_FLOAT(cLaserLocY, "laser_loc.y"); CONFIG_FLOAT(cLaserLocZ, "laser_loc.z"); CONFIG_FLOAT(cStartX, "start_x"); CONFIG_FLOAT(cStartY, "start_y"); CONFIG_FLOAT(cStartAngle, "start_angle"); CONFIG_FLOAT(cDT, "delta_t"); CONFIG_FLOAT(cMinTurnR, "min_turn_radius"); CONFIG_FLOAT(cMaxAccel, "max_accel"); CONFIG_FLOAT(cMaxSpeed, "max_speed"); CONFIG_FLOAT(cLaserStdDev, "laser_noise_stddev"); CONFIG_FLOAT(cAngularErrorBias, "angular_error_bias"); CONFIG_FLOAT(cAngularErrorRate, "angular_error_rate"); config_reader::ConfigReader reader({"config/simulator.lua"}); Simulator::Simulator() : laser_noise_(0, 1), angular_error_(0, 1) { tLastCmd = GetMonotonicTime(); truePoseMsg.header.seq = 0; truePoseMsg.header.frame_id = "map"; } Simulator::~Simulator() { } void Simulator::init(ros::NodeHandle& n) { scanDataMsg.header.seq = 0; scanDataMsg.header.frame_id = "base_laser"; scanDataMsg.angle_min = DegToRad(-135.0); scanDataMsg.angle_max = DegToRad(135.0); scanDataMsg.range_min = 0.02; scanDataMsg.range_max = 10.0; scanDataMsg.angle_increment = DegToRad(0.25); scanDataMsg.intensities.clear(); scanDataMsg.time_increment = 0.0; scanDataMsg.scan_time = 0.05; odometryTwistMsg.header.seq = 0; odometryTwistMsg.header.frame_id = "odom"; odometryTwistMsg.child_frame_id = "base_footprint"; curLoc = Vector2f(cStartX, cStartY); curAngle = cStartAngle; initSimulatorVizMarkers(); drawMap(); driveSubscriber = n.subscribe( "/ackermann_curvature_drive", 1, &Simulator::DriveCallback, this); initSubscriber = n.subscribe( "/initialpose", 1, &Simulator::InitalLocationCallback, this); odometryTwistPublisher = n.advertise<nav_msgs::Odometry>("/odom",1); laserPublisher = n.advertise<sensor_msgs::LaserScan>("/scan", 1); mapLinesPublisher = n.advertise<visualization_msgs::Marker>( "/simulator_visualization", 6); posMarkerPublisher = n.advertise<visualization_msgs::Marker>( "/simulator_visualization", 6); truePosePublisher = n.advertise<geometry_msgs::PoseStamped>( "/simulator_true_pose", 1); localizationPublisher = n.advertise<geometry_msgs::Pose2D>( "/localization", 1); br = new tf::TransformBroadcaster(); } void Simulator::InitalLocationCallback(const PoseWithCovarianceStamped& msg) { curLoc = Vector2f(msg.pose.pose.position.x, msg.pose.pose.position.y); curAngle = 2.0 * atan2(msg.pose.pose.orientation.z, msg.pose.pose.orientation.w); printf("Set robot pose: %.2f,%.2f, %.1f\u00b0\n", curLoc.x(), curLoc.y(), RadToDeg(curAngle)); } /** * Helper method that initializes visualization_msgs::Marker parameters * @param vizMarker pointer to the visualization_msgs::Marker object * @param ns namespace for marker (string) * @param id id of marker (int) - must be unique for each marker; * 0, 1, and 2 are already used * @param type specifies type of marker (string); available options: * arrow (default), cube, sphere, cylinder, linelist, * linestrip, points * @param p stamped pose to define location and frame of marker * @param scale scale of the marker; see visualization_msgs::Marker * documentation for details on the parameters * @param duration lifetime of marker in RViz (double); use duration of 0.0 * for infinite lifetime * @param color vector of 4 float values representing color of marker; * 0: red, 1: green, 2: blue, 3: alpha */ void Simulator::initVizMarker(visualization_msgs::Marker& vizMarker, string ns, int id, string type, geometry_msgs::PoseStamped p, geometry_msgs::Point32 scale, double duration, vector<float> color) { vizMarker.header.frame_id = p.header.frame_id; vizMarker.header.stamp = ros::Time::now(); vizMarker.ns = ns; vizMarker.id = id; if (type == "arrow") { vizMarker.type = visualization_msgs::Marker::ARROW; } else if (type == "cube") { vizMarker.type = visualization_msgs::Marker::CUBE; } else if (type == "sphere") { vizMarker.type = visualization_msgs::Marker::SPHERE; } else if (type == "cylinder") { vizMarker.type = visualization_msgs::Marker::CYLINDER; } else if (type == "linelist") { vizMarker.type = visualization_msgs::Marker::LINE_LIST; } else if (type == "linestrip") { vizMarker.type = visualization_msgs::Marker::LINE_STRIP; } else if (type == "points") { vizMarker.type = visualization_msgs::Marker::POINTS; } else { vizMarker.type = visualization_msgs::Marker::ARROW; } vizMarker.pose = p.pose; vizMarker.points.clear(); vizMarker.scale.x = scale.x; vizMarker.scale.y = scale.y; vizMarker.scale.z = scale.z; vizMarker.lifetime = ros::Duration(duration); vizMarker.color.r = color.at(0); vizMarker.color.g = color.at(1); vizMarker.color.b = color.at(2); vizMarker.color.a = color.at(3); vizMarker.action = visualization_msgs::Marker::ADD; } void Simulator::initSimulatorVizMarkers() { geometry_msgs::PoseStamped p; geometry_msgs::Point32 scale; vector<float> color; color.resize(4); p.header.frame_id = "/map"; p.pose.orientation.w = 1.0; scale.x = 0.02; scale.y = 0.0; scale.z = 0.0; color[0] = 66.0 / 255.0; color[1] = 134.0 / 255.0; color[2] = 244.0 / 255.0; color[3] = 1.0; initVizMarker(lineListMarker, "map_lines", 0, "linelist", p, scale, 0.0, color); p.pose.position.z = 0.5 * cCarHeight; scale.x = cCarLength; scale.y = cCarWidth; scale.z = cCarHeight; color[0] = 94.0 / 255.0; color[1] = 156.0 / 255.0; color[2] = 255.0 / 255.0; color[3] = 0.8; initVizMarker(robotPosMarker, "robot_position", 1, "cube", p, scale, 0.0, color); } void Simulator::drawMap() { ros_helpers::ClearMarker(&lineListMarker); for (const line2f& l : map_.lines) { ros_helpers::DrawEigen2DLine(l.p0, l.p1, &lineListMarker); } } void Simulator::publishOdometry() { tf::Quaternion robotQ = tf::createQuaternionFromYaw(curAngle); odometryTwistMsg.header.stamp = ros::Time::now(); odometryTwistMsg.pose.pose.position.x = curLoc.x(); odometryTwistMsg.pose.pose.position.y = curLoc.y(); odometryTwistMsg.pose.pose.position.z = 0.0; odometryTwistMsg.pose.pose.orientation.x = robotQ.x(); odometryTwistMsg.pose.pose.orientation.y = robotQ.y(); odometryTwistMsg.pose.pose.orientation.z = robotQ.z();; odometryTwistMsg.pose.pose.orientation.w = robotQ.w(); odometryTwistMsg.twist.twist.angular.x = 0.0; odometryTwistMsg.twist.twist.angular.y = 0.0; odometryTwistMsg.twist.twist.angular.z = angVel; odometryTwistMsg.twist.twist.linear.x = vel * cos(curAngle); odometryTwistMsg.twist.twist.linear.y = vel * sin(curAngle); odometryTwistMsg.twist.twist.linear.z = 0.0; odometryTwistPublisher.publish(odometryTwistMsg); robotPosMarker.pose.position.x = curLoc.x() - cos(curAngle) * cRearAxleOffset; robotPosMarker.pose.position.y = curLoc.y() - sin(curAngle) * cRearAxleOffset; robotPosMarker.pose.position.z = 0.5 * cCarHeight; robotPosMarker.pose.orientation.w = 1.0; robotPosMarker.pose.orientation.x = robotQ.x(); robotPosMarker.pose.orientation.y = robotQ.y(); robotPosMarker.pose.orientation.z = robotQ.z(); robotPosMarker.pose.orientation.w = robotQ.w(); } void Simulator::publishLaser() { if (map_.file_name != cMapName) { map_.Load(cMapName); drawMap(); } scanDataMsg.header.stamp = ros::Time::now(); const Vector2f laserRobotLoc(cLaserLocX, cLaserLocY); const Vector2f laserLoc = curLoc + Rotation2Df(curAngle) * laserRobotLoc; const int num_rays = static_cast<int>( 1.0 + (scanDataMsg.angle_max - scanDataMsg.angle_min) / scanDataMsg.angle_increment); map_.GetPredictedScan(laserLoc, scanDataMsg.range_min, scanDataMsg.range_max, scanDataMsg.angle_min + curAngle, scanDataMsg.angle_max + curAngle, num_rays, &scanDataMsg.ranges); for (float& r : scanDataMsg.ranges) { if (r > scanDataMsg.range_max - 0.1) { r = scanDataMsg.range_max; continue; } r = max<float>(0.0, r + cLaserStdDev * laser_noise_(rng_)); } laserPublisher.publish(scanDataMsg); } void Simulator::publishTransform() { tf::Transform transform; tf::Quaternion q; transform.setOrigin(tf::Vector3(0.0,0.0,0.0)); transform.setRotation(tf::Quaternion(0.0, 0.0, 0.0, 1.0)); br->sendTransform(tf::StampedTransform(transform, ros::Time::now(), "/map", "/odom")); transform.setOrigin(tf::Vector3(curLoc.x(), curLoc.y(), 0.0)); q.setRPY(0.0,0.0,curAngle); transform.setRotation(q); br->sendTransform(tf::StampedTransform(transform, ros::Time::now(), "/odom", "/base_footprint")); transform.setOrigin(tf::Vector3(0.0 ,0.0, 0.0)); transform.setRotation(tf::Quaternion(0.0, 0.0, 0.0, 1.0)); br->sendTransform(tf::StampedTransform(transform, ros::Time::now(), "/base_footprint", "/base_link")); transform.setOrigin(tf::Vector3(cLaserLocX, cLaserLocY, cLaserLocZ)); transform.setRotation(tf::Quaternion(0.0, 0.0, 0.0, 1)); br->sendTransform(tf::StampedTransform(transform, ros::Time::now(), "/base_link", "/base_laser")); } void Simulator::publishVisualizationMarkers() { mapLinesPublisher.publish(lineListMarker); posMarkerPublisher.publish(robotPosMarker); } float AbsBound(float x, float bound) { if (x > 0.0 && x > bound) { return bound; } else if (x < 0.0 && x < -bound) { return -bound; } return x; } void Simulator::DriveCallback(const AckermannCurvatureDriveMsg& msg) { if (!isfinite(msg.velocity) || !isfinite(msg.curvature)) { printf("Ignoring non-finite drive values: %f %f\n", msg.velocity, msg.curvature); return; } last_cmd_ = msg; tLastCmd = GetMonotonicTime(); } void Simulator::update() { static const double kMaxCommandAge = 0.1; if (GetMonotonicTime() > tLastCmd + kMaxCommandAge) { last_cmd_.velocity = 0; } // Epsilon curvature corresponding to a very large radius of turning. static const float kEpsilonCurvature = 1.0 / 1E3; // Commanded speed bounded to motion limit. const float desired_vel = AbsBound(last_cmd_.velocity, cMaxSpeed); // Maximum magnitude of curvature according to turning limits. const float max_curvature = 1.0 / cMinTurnR; // Commanded curvature bounded to turning limit. const float desired_curvature = AbsBound(last_cmd_.curvature, max_curvature); // Indicates if the command is for linear motion. const bool linear_motion = (fabs(desired_curvature) < kEpsilonCurvature); const float dv_max = cDT * cMaxAccel; const float bounded_dv = AbsBound(desired_vel - vel, dv_max); vel = vel + bounded_dv; const float dist = vel * cDT; float dx = 0, dy = 0, dtheta = 0; if (linear_motion) { dx = dist; dy = 0; dtheta = cDT * cAngularErrorBias; } else { const float r = 1.0 / desired_curvature; dtheta = dist * desired_curvature + angular_error_(rng_) * cDT * cAngularErrorBias + angular_error_(rng_) * cAngularErrorRate * fabs(dist * desired_curvature); dx = r * sin(dtheta); dy = r * (1.0 - cos(dtheta)); } curLoc.x() += dx * cos(curAngle) - dy * sin(curAngle); curLoc.y() += dx * sin(curAngle) + dy * cos(curAngle); curAngle = AngleMod(curAngle + dtheta); truePoseMsg.header.stamp = ros::Time::now(); truePoseMsg.pose.position.x = curLoc.x(); truePoseMsg.pose.position.y = curLoc.y(); truePoseMsg.pose.position.z = 0; truePoseMsg.pose.orientation.w = cos(0.5 * curAngle); truePoseMsg.pose.orientation.z = sin(0.5 * curAngle); truePoseMsg.pose.orientation.x = 0; truePoseMsg.pose.orientation.y = 0; truePosePublisher.publish(truePoseMsg); } void Simulator::Run() { // Simulate time-step. update(); //publish odometry and status publishOdometry(); //publish laser rangefinder messages publishLaser(); // publish visualization marker messages publishVisualizationMarkers(); //publish tf publishTransform(); if (FLAGS_localize) { geometry_msgs::Pose2D localization_msg; localization_msg.x = curLoc.x(); localization_msg.y = curLoc.y(); localization_msg.theta = curAngle; localizationPublisher.publish(localization_msg); } }
[ "joydeepb@cs.utexas.edu" ]
joydeepb@cs.utexas.edu
4c95c4210b9e0586ac92a979a9bd05dda44694be
0440fcb4ff56e43c4faf855e441e70a99a30186a
/busmaster/Sources/FLEXRAY_ETAS_BOA/ClientBuffer.h
47446dfe34f94f1102797557ca3ed9b4d36d8ac5
[]
no_license
MarcSerraLear/UDS_Busmaster
0383d1d1349dc3d0e29762c1457821807f530b5d
9f624aa11ebc4041d6048088ac02960f38a80293
refs/heads/master
2020-05-17T12:35:02.189914
2014-04-14T13:44:27
2014-04-14T13:44:27
12,892,058
5
2
null
null
null
null
UTF-8
C++
false
false
2,296
h
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @file * ClientBuffer.h * * @brief * Declares the client buffer class. */ #pragma once #include "DataTypes/FLEXRAY_Datatypes.h" #include "DataTypes/MsgBufAll_DataTypes.h" #include "Include\Error.h" #include <vector> using namespace std; #ifdef _DEBUG static DWORD g_dwIxxatBufObjectCounter = 0; #endif #define MAX_BUFF_ALLOWED 16 /** * @class CClientBuffer * * @brief * Implements the client buffer class. This class includes a STL::vector * which holds the pointers to the CBaseCANBufFSE* objects. * Do not delete this CBaseCANBufFSE* objects because they were created * by another function and should deleted by the creator. * */ class CClientBuffer { public: DWORD dwClientID; ///< Identifier for the client HANDLE hClientHandle; ///< Handle of the client HANDLE hPipeFileHandle; ///< Handle of the pipe file string m_pacClientName; ///< Name of the client HRESULT AddMsgBuf(CBaseFLEXBufFSE* pBufObj); HRESULT RemoveMsgBuf(CBaseFLEXBufFSE* pBufObj); HRESULT RemoveAllMsgBuf(); CBaseFLEXBufFSE* GetSEBufferByIndex(int iBufIndex); int NumOfSEBuffers() { return m_BaseFLEXRAYBufFSEVector.size(); } CClientBuffer(); CClientBuffer(DWORD dwClntID, HANDLE hClntHandle, HANDLE hPipeHandle, string szClientName); ~CClientBuffer(); protected: typedef std::vector<CBaseFLEXBufFSE*> BaseFLEXRAYBufFSEVector; BaseFLEXRAYBufFSEVector m_BaseFLEXRAYBufFSEVector; //DWORD m_dwUniqueBufferID; ///< Key value for the clients, never decement this variable BOOL MsgBufExist(CBaseFLEXBufFSE* pBufObj); };
[ "mserrasunol@lear.com" ]
mserrasunol@lear.com
7e976e51d0ea358bd199810ecc0370951cec17ce
f6f15809ac70089ef4cfb1ade40e2dc58d239f81
/depends/i686-w64-mingw32/include/QtTest/5.9.8/QtTest/private/qtestresult_p.h
061ca5f311db00d2a4243a06f93659c4f957496c
[ "MIT" ]
permissive
lamyaim/bitgesell
fcc96f6765d3907ce923f411a1b2c6c4de9d55d6
64c24348f1ba8788fbffaf663b3df38d9b49a5d1
refs/heads/master
2023-04-30T08:16:40.735496
2020-12-10T05:23:08
2020-12-10T05:23:08
369,859,996
1
0
MIT
2021-05-22T16:50:56
2021-05-22T16:48:32
null
UTF-8
C++
false
false
4,033
h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtTest 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 QTESTRESULT_P_H #define QTESTRESULT_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 <QtTest/qtest_global.h> QT_BEGIN_NAMESPACE class QTestResultPrivate; class QTestData; class Q_TESTLIB_EXPORT QTestResult { public: static const char *currentTestObjectName(); static bool currentTestFailed(); static QTestData *currentTestData(); static QTestData *currentGlobalTestData(); static const char *currentTestFunction(); static const char *currentDataTag(); static const char *currentGlobalDataTag(); static void finishedCurrentTestData(); static void finishedCurrentTestDataCleanup(); static void finishedCurrentTestFunction(); static void reset(); static void setBlacklistCurrentTest(bool b); static void addFailure(const char *message, const char *file, int line); static bool compare(bool success, const char *failureMsg, char *val1, char *val2, const char *actual, const char *expected, const char *file, int line); static void setCurrentGlobalTestData(QTestData *data); static void setCurrentTestData(QTestData *data); static void setCurrentTestFunction(const char *func); static void setCurrentTestObject(const char *name); static void addSkip(const char *message, const char *file, int line); static bool expectFail(const char *dataIndex, const char *comment, QTest::TestFailMode mode, const char *file, int line); static bool verify(bool statement, const char *statementStr, const char *extraInfo, const char *file, int line); static void setSkipCurrentTest(bool value); static bool skipCurrentTest(); static void setCurrentAppName(const char *appName); static const char *currentAppName(); private: Q_DISABLE_COPY(QTestResult) }; QT_END_NAMESPACE #endif
[ "quentin.neveu@hotmail.ca" ]
quentin.neveu@hotmail.ca
52eb3a20ef08e8a0f0868941dedbf03fddaead0c
2bf7bdc88670901a995879c36fa1f65b1f56e56a
/plugins/statusBar/statusBar.cpp
9204b09f6a6489466ac54f5bfaa7725bfaf24b02
[]
no_license
stumathews/qtplugindocksys
67babba0a7694f545920dd836025289b2335fd52
750973cbc3a333780908c4ed8cb4156e9784d745
refs/heads/master
2021-07-05T06:57:30.000683
2017-09-29T15:27:06
2017-09-29T15:27:06
105,288,108
0
0
null
null
null
null
UTF-8
C++
false
false
825
cpp
#include "statusBar.h" #include <QtPlugin> #include <QObject> #include <QStatusBar> #include <QLabel> #include "mainWindowDockableInterface.h" #include <iostream> using namespace std; void StatusBar::constructObjects(){ statusBar = new QStatusBar(); } void StatusBar::loadMe(){ constructObjects(); setPluginName( "StatusBar" ); } bool StatusBar::recieveDockItemPlugin( QObject* foreignPlugin ){ cout << "Status Bar doesn't recieve dockItem plugins..." << endl; return true; } void StatusBar::loadMeAsForeignPlugin(){ statusBar->setSizeGripEnabled( true ); statusBar->showMessage( "StatusBar Plugin" ); statusBar->addPermanentWidget( new QLabel( "StatusBar Plugin" ) ); qobject_cast<MainWindowDockableInterface*>(getDockableObject())->updateTheStatusBar( statusBar ); } Q_EXPORT_PLUGIN2( statusBar, StatusBar )
[ "stumathews@gmail.com" ]
stumathews@gmail.com
bc168ccd77b22459dabfabf6836b06f1c6de87ff
4cd2487ce7ffe589d4f2aee87a4ceb09e511b93b
/opencv/sensors/OpenCVCamera.h
294d53044ac9bdb99502679a0145e983e3aaeb7b
[]
no_license
watson-intu/self-plugins
fbe903c44fb960355e215c6ed3b652c9d1d66f5d
69d3bd66004b7c809c83e553738474022e7cdcf9
refs/heads/develop
2021-01-20T12:50:10.275202
2017-09-16T06:16:32
2017-09-16T06:16:32
90,413,803
2
7
null
2017-09-16T06:16:33
2017-05-05T20:28:20
C++
UTF-8
C++
false
false
1,657
h
/** * Copyright 2017 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef OPENCV_CAMERA_H #define OPENCV_CAMERA_H #include "SelfInstance.h" #include "utils/ThreadPool.h" #include "utils/Time.h" #include "sensors/Camera.h" #include "opencv2/opencv.hpp" //! OpenCV implementation of the Camera class class OpenCVCamera : public Camera { public: RTTI_DECL(); OpenCVCamera() : m_CameraDevice(0), m_Width(320), m_Height(240), m_VideoCapture(NULL), m_bProcessing(false) {} //! ISerializable interface virtual void Serialize(Json::Value & json); virtual void Deserialize(const Json::Value & json); //! ISensor interface virtual bool OnStart(); virtual bool OnStop(); virtual void OnPause(); virtual void OnResume(); private: //! Types typedef std::list<VideoData *> DataQueue; //! Data cv::VideoCapture * m_VideoCapture; volatile bool m_bProcessing; TimerPool::ITimer::SP m_spWaitTimer; std::string m_CameraStream; int m_CameraDevice; int m_Width; int m_Height; void OnCaptureImage(); void OnSendData( IData * a_pData ); }; #endif // OPENCV_CAMERA_H
[ "rolyle@us.ibm.com" ]
rolyle@us.ibm.com
0c3f1b182f9b29599541bc6d0f6e7221b335237b
feba108a3e5d71098ed2cb3b1083b3215e87b6d9
/Airplane System/Airplane Client/Airplane Client/Airplane Client/Fuel.h
333fb3c3ccbe328f5598aa5d01aefd027a93e113
[]
no_license
hamza-saeed/cpp-airplane-system
d5414ef990902824eafa34e84cdb969dc2b1da5f
cfa90477683d3a926602840aff417297ae6e389f
refs/heads/master
2020-08-29T19:57:03.460787
2019-10-28T22:23:05
2019-10-28T22:23:05
218,156,145
0
0
null
null
null
null
UTF-8
C++
false
false
177
h
#pragma once #include "Sensors.h" class Fuel : public Sensors { public: //fuel capacity for Boeing double fuel = 177000; //methods void generate(); double returnFuel(); };
[ "hamzasaeed@protonmail.com" ]
hamzasaeed@protonmail.com
009c170b189f8e529ef79091dbf162c952db368e
c120f72a42d2f202fc50e3569ae217220359a49c
/.history/main_20210723144615.cpp
deacaccc0aa23041cf0f3837d3323a325189a651
[]
no_license
zlatkovnik/Crius
c5888fca8c2c572ce5b151adf6073f965b3914d6
414fb380823c5a38e33dd47818487290405ecde7
refs/heads/main
2023-07-07T04:35:12.126132
2021-08-09T14:51:03
2021-08-09T14:51:03
388,804,001
0
0
null
null
null
null
UTF-8
C++
false
false
6,984
cpp
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> #include <fstream> #include <streambuf> #include <sstream> void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } const char *vertexShaderSource = vertexSource.c_str(); const char *fragmentShaderSource; readFile("./res/shaders/basic.vert", vertexShaderSource); readFile("./res/shaders/basic.frag", fragmentShaderSource); unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); // check for shader compile errors int success; char infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } // fragment shader unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); // check for shader compile errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } // link shaders unsigned int shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); // check for linking errors glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { -0.5f, -0.5f, 0.0f, // left 0.5f, -0.5f, 0.0f, // right 0.0f, 0.5f, 0.0f // top }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind glBindBuffer(GL_ARRAY_BUFFER, 0); // You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. glBindVertexArray(0); // uncomment this call to draw in wireframe polygons. //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // draw our first triangle glUseProgram(shaderProgram); glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized glDrawArrays(GL_TRIANGLES, 0, 3); // glBindVertexArray(0); // no need to unbind it every time // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteProgram(shaderProgram); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } void readFile(std::string filename, char* buffer){ std::ifstream handler(filename); std::string stream; if(handler.is_open()) { std::string line; while(getline(handler, line)) { stream += line; } } handler.close(); const char *buffer = stream.c_str(); }
[ "zlatkovnik@dualsoft.net" ]
zlatkovnik@dualsoft.net
c3c8fe4638bc0d00a4328053a4d37ef7957bbc1a
724c0ee36c0e6262f143d965f2e5f894a31cbb16
/c,c++/hacker_rank/hacker_country.cpp
68b4d35f81dee33f90063ad1fe0b0d6d252b3f3f
[]
no_license
amit-mittal/Programming-Questions-Practice
bf5fe47ba1b074960ad33eb2e525baaf99a85336
899995ff49cdf1ef77cc9327feb2fbed7b5c94fe
refs/heads/master
2021-09-04T15:27:52.569111
2018-01-19T21:03:31
2018-01-19T21:03:31
117,618,138
2
0
null
null
null
null
UTF-8
C++
false
false
1,843
cpp
#include <cstdlib> #include <cstdio> #include <cstring> #include <iostream> #include <vector> #include <string> #include <set> #include <map> #include <cmath> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <utility> using namespace std; #define mod 1000000007 #define inf 2147483647 #define ninf -2147483648 #define FOR(i,a,b) for(int i=a;i<b;i++) #define s(a) scanf("%d",&a) #define sll(a) scanf("%lld",&a) #define ss(a) scanf("%s",a) #define p(a) printf("%d",a) #define pll(a) printf("%lld",a) #define ps(a) printf("%s",a) #define pc(a) printf("%c",a) #define nline printf("\n") #define space printf(" ") #define ll long long #define INF 10000000 ll a[501][501]; ll c[501][501]; ll gcd(ll a, ll b){ if(b==0) return a; else return gcd(b, a%b); } void relax(int i, int j, int k){ if((ll)(a[i][k]+a[k][j])*c[i][j]<=(ll)(a[i][j])*(c[i][k]+c[k][j])){ a[i][j] = a[i][k]+a[k][j]; c[i][j] = c[i][k]+c[k][j]; } } int main(){ int n; s(n); for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ sll(a[i][j]); if(a[i][j]==0) c[i][j] = 0; else c[i][j] = 1; } } for(int k=0;k<n;++k){ for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ relax(i, j, k); } } } ll num = INF; ll den = 0; /*for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ if(i==j) continue; if((a[i][j]+a[j][i])*den<num*(c[i][j]+c[j][i])){ num = a[i][j]+a[j][i]; den = c[i][j]+c[j][i]; } } }*/ for(int i=0;i<n;++i){ if(a[i][i]*den<num*c[i][i]){ num = a[i][i]; den = c[i][i]; } } /*for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ cout << a[i][j] << " "; } cout << endl; } for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ cout << c[i][j] << " "; } cout << endl; }*/ ll hcf = gcd(num, den); num/=hcf; den/=hcf; printf("%lld/%lld\n", num, den); return 0; }
[ "Administrator@Amit-Laptop.fareast.corp.microsoft.com" ]
Administrator@Amit-Laptop.fareast.corp.microsoft.com
6ac7d7b5721917e5c0e939e3394e8062903c16ac
993a4b71475061978574f361a703204fc37f5138
/phoneme_feature-mr1-rel-b04/cldc/src/vm/cpu/arm/CodeGenerator_arm.cpp
1bb098a6a514820bee9e452b7f4a6f6302ad98c0
[]
no_license
PhoneJ2ME/releases
1d93e51e0081a1d331ea0cf1c1f1e5d55f0914cc
6585f23149f090e0ff3a94ee61cae6bf2394e78b
refs/heads/master
2021-01-19T10:39:17.955758
2008-12-17T20:32:36
2008-12-17T20:32:36
82,216,780
4
1
null
null
null
null
UTF-8
C++
false
false
132,783
cpp
/* * * Portions Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. * *!c< * Copyright 2006 Intel Corporation. All rights reserved. *!c> */ #include "incls/_precompiled.incl" #if !ENABLE_THUMB_COMPILER #if ENABLE_COMPILER #include "incls/_CodeGenerator_arm.cpp.incl" class TempRegister { private: Assembler::Register _reg; public: TempRegister() { _reg = RegisterAllocator::allocate(); } TempRegister(Assembler::Register reg) : _reg(reg) { RegisterAllocator::allocate(reg); } ~TempRegister() { RegisterAllocator::dereference(_reg); } operator Assembler::Register() { return _reg; } // Simple accessor as a workaround for above UDC Assembler::Register reg() { return _reg; } }; class CompilerLiteralAccessor : public LiteralAccessor { public: virtual bool has_literal(int imm32, Assembler::Address1& result); virtual Assembler::Register get_literal(int imm32) { return frame()->get_literal(imm32, *this); } private: VirtualStackFrame* frame() { return Compiler::frame(); } }; void CodeGenerator::call_through_gp(address& target, bool speed JVM_TRAPS) { long offset = (long)&target - (long)&gp_base_label; call_from_compiled_code(gp, (int) offset, 0, /* indirect */true, speed JVM_NO_CHECK_AT_BOTTOM); } #if ENABLE_ISOLATES // Load task mirror, perform class initialization before hand if needed. // Barrier is not necessary when the class that holds the static variables: // - is a ROMIZED class, // - has no static initializer // - has a static initializer but it does not invoke any methods (therefore // no compiled method can see the class in the being initialized state) // Methods that are used in static initializers and that may hit a barrier // may also be tagged so that only tagged methods have to clear a barrier. // This however is harder to achieve. // // void CodeGenerator::load_task_mirror(Oop*klass, Value& statics_holder, bool needs_cib JVM_TRAPS) { { JavaClass::Raw jc = klass; statics_holder.assign_register(); get_mirror_list_base(statics_holder.lo_register()); // FieldAddress might destroy the value, so we create a defensive copy. Value statics_holder_copy; statics_holder.copy(statics_holder_copy); FieldAddress address(statics_holder_copy, jc().class_id() * sizeof(OopDesc *), T_OBJECT); ldr(statics_holder.lo_register(), address.lo_address_2()); } if (needs_cib) { Label class_is_initialized, need_init; // Can we make the flush conditional for get/put static ? // see if register usage cross compiled bytecode. flush_frame(); { // The marker cannot be treated as a constant value, as it would break // cross-compilation. Thus we load it from GP table. TempRegister tmp; get_task_class_init_marker(tmp); cmp(statics_holder.lo_register(), reg(tmp)); } b(class_is_initialized, ne); bind(need_init); // Call the runtime system. // pass klass as extra args, move in correct register beforehand // if necessary // Passing the klass in parameter. { // KEEP these brackets: without them the klass_parameter's destructor // would not be called before call_vm and cause an error. Value klass_parameter(T_OBJECT); klass_parameter.set_obj(klass); if (klass_parameter.lo_register() != r1) { call_vm_extra_arg(klass_parameter.lo_register()); } } call_vm((address) compiled_code_task_barrier, T_OBJECT JVM_CHECK); // Need to move mirror to expected register if (statics_holder.lo_register()!= r0) { mov(statics_holder.lo_register(), reg(r0)); } bind(class_is_initialized); } } void CodeGenerator::check_cib(Oop *klass JVM_TRAPS) { Label class_is_initialized, need_init; // IMPL_NOTE: Cannot make the flush conditionally. // see how this can be made conditional! flush_frame(); // add to the klass oop to get the address of the appropriate // task mirror table entry Value task_mirror(T_OBJECT); task_mirror.assign_register(); Value klass_value(T_OBJECT); klass_value.set_obj(klass); { JavaClass::Raw jc = klass; get_mirror_list_base(task_mirror.lo_register()); // FieldAddress might destroy the value, so we create a defensive copy. Value task_mirror_copy; task_mirror.copy(task_mirror_copy); FieldAddress address(task_mirror_copy, jc().class_id() * sizeof(OopDesc *), T_OBJECT); ldr(task_mirror.lo_register(), address.lo_address_2()); } { // The marker cannot be treated as a constant value, as it would break // cross-compilation. Thus we load it from GP table. TempRegister tmp; get_task_class_init_marker(tmp); cmp(task_mirror.lo_register(), reg(tmp)); b(class_is_initialized, ne); } bind(need_init); // Call the runtime system. // pass klass as extra args // flush_frame(); task_mirror.destroy(); if (klass_value.lo_register() != r1) { call_vm_extra_arg(klass_value.lo_register()); } klass_value.destroy(); call_vm((address) compiled_code_task_barrier, T_OBJECT JVM_CHECK); bind(class_is_initialized); } #endif extern "C" { extern address gp_base_label; } bool CompilerLiteralAccessor::has_literal(int imm32, Assembler::Address1& result) { LiteralElementStream les(frame()); for ( ; !les.eos() ; les.next()) { if (les.value() == imm32) { result = Assembler::reg(les.reg()); return true; } } // IMPL_NOTE: // This for loop should probably be deleted. It's just not worth it. for(les.reset(); !les.eos(); les.next()) { int value = les.value(); if (value == 0) { continue; } Assembler::Register rd = les.reg(); for (int i = 1; i < 31; i++) { if ((value >> i) == imm32) { result = Assembler::imm_shift(rd, Assembler::asr, i); return true; } else if ((value << i) == imm32) { result = Assembler::imm_shift(rd, Assembler::lsl, i); return true; } else if (((unsigned)value >> i) == (unsigned)imm32) { result = Assembler::imm_shift(rd, Assembler::lsr, i); return true; } else if ((int)_rotr(value, i) == imm32) { result = Assembler::imm_shift(rd, Assembler::ror, i); return true; } } } return false; } void CodeGenerator::save_state(CompilerState *compiler_state) { BinaryAssembler::save_state(compiler_state); } #if ENABLE_INLINE && ARM void CodeGenerator::restore_state(CompilerState *compiler_state) { BinaryAssembler::restore_state(compiler_state); } #endif void CodeGenerator::load_from_address(Value& result, BasicType type, MemoryAddress& address, Assembler::Condition cond) { write_literals_if_desperate(); // illegal types do not require any loading if (type == T_ILLEGAL) return; GUARANTEE(stack_type_for(type) == result.stack_type(), "types must match (taking stack types into account)"); result.assign_register(); const Register lo = result.lo_register(); switch(type) { case T_BOOLEAN: ldrsb (lo, address.lo_address_3(), cond); break; case T_CHAR: ldrh(lo, address.lo_address_3(), cond); break; case T_SHORT: ldrsh (lo, address.lo_address_3(), cond); break; case T_INT: // fall through case T_FLOAT: // fall through case T_ARRAY: // fall through case T_OBJECT: ldr(lo, address.lo_address_2(), cond); break; case T_LONG: // fall through case T_DOUBLE: ldr (lo, address.lo_address_2(), cond); ldr (result.hi_register(), address.hi_address_2(), cond); break; case T_BYTE: { // T_BYTE doesn't get compiled very often, so let's put it here. Gcc generates // better code to make it faster to compile the common case (loading 4-bytes). bool is_signed = true; Bytecodes::Code bc = method()->bytecode_at(bci()); int nextbci = bci() + Bytecodes::length_for(method(), bci()); int len = method()->code_size(); if (bc == Bytecodes::_baload && nextbci + 1 < len) { Bytecodes::Code bc1 = method()->bytecode_at(nextbci); Bytecodes::Code bc2 = method()->bytecode_at(nextbci+1); if ((bc1 == Bytecodes::_i2s && bc2 == Bytecodes::_iand) || (bc1 == Bytecodes::_iand && bc2 == Bytecodes::_i2s)) { // Detect a common code pattern: // sipush 0xff // aload array // iload index // baload array <<< we are here // iand // i2s // We can safely skip the iand and i2s bytecodes, and change the load // into an "unsigned load byte". The only case we cannot do this is // when the iand or i2s bytecode sits at a branch target, so we check it // with the Compiler::entry_count_for() lines below. if (Compiler::entry_count_for(nextbci) == 1 && Compiler::entry_count_for(nextbci+1) == 1) { // At this point, the operands to the baload bytecode have already // been popped. The top of stack is the operand to the iand. Value iand_operand(T_INT); int operand_index = frame()->virtual_stack_pointer(); frame()->value_at(iand_operand, operand_index); if (iand_operand.is_immediate() && iand_operand.as_int() == 0xff) { frame()->pop(); Compiler::closure()->set_next_bytecode_index(nextbci+2); is_signed = false; } } } else if (bc1 == Bytecodes::_sipush && method()->get_java_short(nextbci+1) == 0xff && Compiler::entry_count_for(nextbci) == 1 && nextbci + 3 < len && method()->bytecode_at(nextbci+3) == Bytecodes::_iand && Compiler::entry_count_for(nextbci+3) == 1) { // Detect a common code pattern: // aload array // iload index // baload array <<< we are here // sipush 0xff // iand Compiler::closure()->set_next_bytecode_index(nextbci+4); is_signed = false; } } if (is_signed) { ldrsb(lo, address.lo_address_3(), cond); } else { ldrb(lo, address.lo_address_2(), cond); } } break; default : SHOULD_NOT_REACH_HERE(); break; } } void CodeGenerator::store_to_address(Value& value, BasicType type, MemoryAddress& address) { write_literals_if_desperate(); // if the value to store isn't present there nothing left to do if (!value.is_present()) { return; } GUARANTEE(stack_type_for(type) == value.stack_type(), "types must match (taking stack types into account)"); Register reg; CompilerLiteralAccessor cla; if (value.is_immediate()) { reg = cla.get_literal(value.lo_bits()); // We must use ::reference, not ::allocate, since the latter flushes the // register from the frame! // We need to make sure that this register isn't flushed when doing the // address calculations. RegisterAllocator::reference(reg); } else { reg = value.lo_register(); } switch(type) { case T_BOOLEAN : // fall through case T_BYTE : strb(reg, address.lo_address_2()); break; case T_CHAR : // fall through case T_SHORT : strh(reg, address.lo_address_3()); break; case T_ARRAY : case T_OBJECT : GUARANTEE(value.in_register() || value.must_be_null(), "Only NULLs can be immediate"); if (!value.not_on_heap()) { // Need to do pointer setting address.write_barrier_prolog(); str(reg, address.lo_address_2()); // Free up register that's not needed any more. Pointer setting // uses up lots of registers, and we want to minimize pressure value.destroy(); address.write_barrier_epilog(); break; } // Fall through case T_FLOAT : case T_INT : str(reg, address.lo_address_2()); break; case T_DOUBLE : // fall through case T_LONG : str(reg, address.lo_address_2()); if (value.is_immediate()) { // Unreference the old literal. Get the new literal and reference it RegisterAllocator::dereference(reg); reg = cla.get_literal(value.hi_bits()); RegisterAllocator::reference(reg); } else { reg = value.hi_register(); } str(reg, address.hi_address_2()); break; default : SHOULD_NOT_REACH_HERE(); break; } if (value.is_immediate()) { RegisterAllocator::dereference(reg); } } #if ENABLE_NPCE && ARM void CodeGenerator::store_to_address_safe(Value& value, BasicType type, MemoryAddress& address) { bool need_npe_check=false; write_literals_if_desperate(); // if the value to store isn't present there nothing left to do if (!value.is_present()) { return; } GUARANTEE(stack_type_for(type) == value.stack_type(), "types must match (taking stack types into account)"); Register reg; CompilerLiteralAccessor cla; if (value.is_immediate()) { reg = cla.get_literal(value.lo_bits()); // We must use ::reference, not ::allocate, since the latter flushes the // register from the frame! // We need to make sure that this register isn't flushed when doing the // address calculations. RegisterAllocator::reference(reg); } else { reg = value.lo_register(); } jint old_code_size = 0; NullCheckStub::Raw last; CompilationQueueElementDesc* tmp = Compiler::current()->get_unlinked_exception_stub(bci()); if (tmp != NULL) { last = tmp; need_npe_check = true; } switch(type) { case T_BOOLEAN : // fall through case T_BYTE : strb(reg, address.lo_address_2()); break; case T_CHAR : // fall through case T_SHORT : strh(reg, address.lo_address_3()); break; case T_ARRAY : case T_OBJECT : GUARANTEE(value.in_register() || value.must_be_null(), "Only NULLs can be immediate"); if (!value.not_on_heap()) { // Need to do pointer setting address.write_barrier_prolog(); str(reg, address.lo_address_2()); if (need_npe_check) { record_npe_point(&last, -1) ; //NPCE record of object has been handler in special case. //No need to handle it in general case. need_npe_check = false; } // Free up register that's not needed any more. Pointer setting // uses up lots of registers, and we want to minimize pressure value.destroy(); address.write_barrier_epilog(); break; } // Fall through case T_FLOAT : case T_INT : str(reg, address.lo_address_2()); break; case T_DOUBLE : // fall through case T_LONG : str(reg, address.lo_address_2()); if (need_npe_check) { record_npe_point(&last, -1); old_code_size = code_size(); } if (value.is_immediate()) { // Unreference the old literal. Get the new literal and reference it RegisterAllocator::dereference(reg); reg = cla.get_literal(value.hi_bits()); RegisterAllocator::reference(reg); } else { reg = value.hi_register(); } str(reg, address.hi_address_2()); if ( need_npe_check ) { #if ENABLE_CODE_OPTIMIZER last().set_two_words((code_size()-old_code_size)>>2); #endif record_npe_point(NULL, -1) ; } break; default : SHOULD_NOT_REACH_HERE(); break; } if (need_npe_check && (type !=T_DOUBLE && type != T_LONG )) { record_npe_point(&last,-1) ; } if (value.is_immediate()) { RegisterAllocator::dereference(reg); } } #endif //NPCE void CodeGenerator::move(const Value& dst, const Value& src, const Condition cond) { // if the source isn't present there's nothing left to do if (!src.is_present()) return; GUARANTEE(dst.type() == src.type(), "type check"); GUARANTEE(dst.in_register(), "destination must be in register"); if (src.is_immediate()) { CompilerLiteralAccessor cla; /* move always 1 word */ mov_imm(dst.lo_register(), src.lo_bits(), &cla, cond); if (cond == al) { frame()->set_has_literal_value(dst.lo_register(), src.lo_bits()); } if (dst.is_two_word()) { mov_imm(dst.hi_register(), src.hi_bits(), &cla, cond); if (cond == al) { frame()->set_has_literal_value(dst.hi_register(), src.hi_bits()); } } } else { GUARANTEE(src.in_register(), "source must be in register"); /* move always 1 word */ mov_reg(dst.lo_register(), src.lo_register(), no_CC, cond); if (dst.is_two_word()) { mov_reg(dst.hi_register(), src.hi_register(), no_CC, cond); } } } void CodeGenerator::move(Value& dst, Oop* obj, Condition cond) { GUARANTEE(dst.type() == T_OBJECT || dst.type() == T_ARRAY, "type check"); ldr_oop(dst.lo_register(), obj, cond); } void CodeGenerator::move(Assembler::Register dst, Assembler::Register src, Condition cond) { mov_reg(dst, src, no_CC, cond); } #if ENABLE_REMEMBER_ARRAY_LENGTH & ARM void CodeGenerator::preload_parameter (Method* method) { Signature::Raw signature = method->signature(); for (SignatureStream ss(&signature, method->is_static()); !ss.eos(); ss.next()) { if (ss.type()==T_ARRAY) { Value value(ss.type()); frame()->value_at(value, ss.index()); break; } } } #endif void CodeGenerator::array_check(Value& array, Value& index JVM_TRAPS) { write_literals_if_desperate(); UsingFastOops fast_oops; bool null_check = need_null_check(array); NullCheckStub::Fast null_check_stub; #if ENABLE_REMEMBER_ARRAY_LENGTH Register length; bool first_time = !(array.is_not_first_time_access()); if (null_check) { null_check_stub = NullCheckStub::allocate_or_share(JVM_SINGLE_ARG_CHECK); #if ENABLE_NPCE record_npe_point(&null_check_stub); frame()->set_value_must_be_nonnull(array); length = frame()->get_bound(array.lo_register(), first_time, Assembler::al); #else cmp(array.lo_register(), zero); frame()->set_value_must_be_nonnull(array); length = frame()->get_bound(array.lo_register(), first_time, Assembler::ne); b(&null_check_stub, eq); #endif } else { length = frame()->get_bound(array.lo_register(), first_time, Assembler::al); } #else // !ENABLE_REMEMBER_ARRAY_LENGTH TempRegister length; if (null_check) { #if ENABLE_NPCE null_check_stub = NullCheckStub::allocate_or_share(JVM_SINGLE_ARG_CHECK); record_npe_point(&null_check_stub); frame()->set_value_must_be_nonnull(array); ldr_imm_index(length, array.lo_register(), Array::length_offset()); #else cmp(array.lo_register(), zero); frame()->set_value_must_be_nonnull(array); ldr(length, imm_index(array.lo_register(), Array::length_offset()), ne); int offset = get_inline_thrower_gp_index( ThrowExceptionStub::rte_null_pointer JVM_CHECK); if (offset > 0) { ldr(pc, imm_index(gp, offset), eq); } else { null_check_stub = NullCheckStub::allocate_or_share(JVM_SINGLE_ARG_CHECK); b(&null_check_stub, eq); } #endif } else { ldr_imm_index(length, array.lo_register(), Array::length_offset()); } #endif #if ENABLE_REMEMBER_ARRAY_CHECK && \ ENABLE_REMEMBER_ARRAY_LENGTH && ENABLE_NPCE if (!index.is_immediate() && index.stack_type() == T_INT) { if ( frame()->is_value_must_be_index_checked( length, index)) { #ifndef PRODUCT if(PrintCompiledCodeAsYouGo) { TTY_TRACE_CR(("Omit a array length checking")); } #endif return; } else { frame()->set_value_must_be_index_checked( length, index); } } #endif if (index.is_immediate()) { CompilerLiteralAccessor cla; cmp_imm(length, index.as_int(), &cla); } else { cmp(length, reg(index.lo_register())); } int offset = get_inline_thrower_gp_index( ThrowExceptionStub::rte_array_index_out_of_bounds JVM_CHECK); if (offset > 0) { ldr(pc, imm_index(gp, offset), ls); } else { IndexCheckStub::Raw index_check_stub = IndexCheckStub::allocate_or_share(JVM_SINGLE_ARG_CHECK); b(&index_check_stub, ls); } } int CodeGenerator::get_inline_thrower_gp_index(int rte JVM_TRAPS) { #if ENABLE_XSCALE_WMMX_INSTRUCTIONS || ENABLE_ARM_V6 // This optimization actually slows down XScale or ARM1136 because // "ldr<cond> pc, [gp, #xx]" is very slow even if the condition is false. return -1; #else bool allowed = is_inline_exception_allowed(rte JVM_CHECK_(-1)); if (!allowed) { return -1; } int locals = method()->max_locals(); if (locals < MAX_INLINE_THROWER_METHOD_LOCALS) { long offset; if (rte == ThrowExceptionStub::rte_null_pointer) { address &target = gp_compiler_throw_NullPointerException_0_ptr; offset = (long)&target - (long)&gp_base_label; } else { address &target = gp_compiler_throw_ArrayIndexOutOfBoundsException_0_ptr; offset = (long)&target - (long)&gp_base_label; } offset += long(locals) * BytesPerWord; return offset; } return -1; #endif } // Note: We cannot bailout in null_check, as null_check is used in // combination with other instructions. // This means that we do not have enough data to reconstruct the virtual // stack frame for the uncommon trap void CodeGenerator::null_check(const Value& object JVM_TRAPS) { cmp(object.lo_register(), zero); int offset = get_inline_thrower_gp_index(ThrowExceptionStub::rte_null_pointer JVM_CHECK); if (offset > 0) { ldr(pc, imm_index(gp, offset), eq); } else { NullCheckStub::Raw check_stub = NullCheckStub::allocate_or_share(JVM_SINGLE_ARG_NO_CHECK); if (check_stub.not_null()) { b(&check_stub, eq); } } } #if ENABLE_NPCE void CodeGenerator::null_check_by_signal(Value& object, bool fakeldr JVM_TRAPS) { NullCheckStub::Raw check_stub = NullCheckStub::allocate_or_share(JVM_SINGLE_ARG_NO_CHECK); if (check_stub.not_null()) { record_npe_point(&check_stub); if (fakeldr) { TempRegister dummy; #ifndef PRODUCT if(PrintCompiledCodeAsYouGo) { TTY_TRACE_CR((" generate a faked ldr instruction =>\n")); } #endif ldr_imm_index(dummy, object.lo_register(), 0); } } } void CodeGenerator::null_check_by_signal_quick(Value& object, BasicType type JVM_TRAPS) { NullCheckStub::Raw check_stub = NullCheckStub::allocate_or_share(JVM_SINGLE_ARG_NO_CHECK); #if ENABLE_CODE_OPTIMIZER && !ENABLE_THUMB_COMPILER if (check_stub.not_null()) { if (!check_stub().is_persistent() && (type == T_LONG || type == T_DOUBLE)) { check_stub().set_two_words(); } } #endif } #endif //ENABLE_NPCE /* In order to improve the pipeline on the ARM, we try to replace, * maybe_null_check(op) * code that uses op * with the code sequence * cond = maybe_null_check_1(op) * code that uses op, conditionalized on cond * maybe_null_check_2(cond) * * In particular, if the second line is a "ldr" instruction, that improves * the chances that there will be an instruction separating the register * whose value is loaded and the instruction that uses it. */ Assembler::Condition CodeGenerator::maybe_null_check_1(Value& object) { if (object.must_be_null()) { // flag was set when we did a set_obj cmp(r0, reg(r0)); // set CC to "eq" return ne; } else if (need_null_check(object)) { cmp(object.lo_register(), zero); frame()->set_value_must_be_nonnull(object); return ne; } else { return al; } } void CodeGenerator::maybe_null_check_2(Assembler::Condition cond JVM_TRAPS) { if (cond == ne) { int offset = get_inline_thrower_gp_index( ThrowExceptionStub::rte_null_pointer JVM_CHECK); if (offset > 0) { ldr(pc, imm_index(gp, offset), eq); } else { NullCheckStub::Raw error = NullCheckStub::allocate_or_share(JVM_SINGLE_ARG_NO_CHECK); if (error.not_null()) { b(&error, eq); } } } } #if ENABLE_NPCE Assembler::Condition CodeGenerator::maybe_null_check_1_signal(Value& object, bool& is_npe) { if (object.must_be_null()) { is_npe = true; return al; } else if (need_null_check(object)) { is_npe = true; frame()->set_value_must_be_nonnull(object); return al; } else { is_npe = false; return al; } } void CodeGenerator::maybe_null_check_2_signal(Assembler::Condition cond, bool is_npe JVM_TRAPS) { if (is_npe) { NullCheckStub::Raw error = NullCheckStub::allocate_or_share(JVM_SINGLE_ARG_NO_CHECK); if (error.not_null()) { record_npe_point(&error,-1); } } } void CodeGenerator::maybe_null_check_3_signal(Assembler::Condition cond, bool is_npe, BasicType type JVM_TRAPS) { if (cond == ne || is_npe ) { NullCheckStub::Raw error = NullCheckStub::allocate_or_share(JVM_SINGLE_ARG_NO_CHECK); if (error.not_null()) { if (is_npe) { if (type == T_LONG || type == T_DOUBLE) { record_npe_point(&error,-2); } else { record_npe_point(&error,-1); } } else { b(&error, eq); } } } } #endif //ENABLE_NPCE void CodeGenerator::overflow(const Assembler::Register& stack_pointer, const Assembler::Register& method_pointer) { if (USE_OVERFLOW_STUB) { if (method_pointer != Assembler::r0) { mov(r0, reg(method_pointer)); } if (stack_pointer != Assembler::r1) { mov(r1, reg(stack_pointer)); } int offset = (int)&gp_interpreter_method_entry_ptr - (int)&gp_base_label; ldr(pc, imm_index(gp, offset)); } else { (void)stack_pointer; (void)method_pointer; SHOULD_NOT_REACH_HERE(); } } void CodeGenerator::method_prolog(Method *method JVM_TRAPS) { int stack_bytes_needed = (method->max_execution_stack_count() * BytesPerStackElement) + JavaFrame::frame_desc_size(); // We check timer tick only if check for stack overflow. bool need_stack_and_timer_checks = true; if (method->is_native() || !method->access_flags().has_invoke_bytecodes()) { if (stack_bytes_needed < LeafMethodStackPadding) { // We're sure this method won't cause a stack overflow. // // IMPL_NOTE: leaf methods do not check for timer ticks. We need to // add timer ticks checks in non-leaf methods that make long // series of method calls inside straight-line code. need_stack_and_timer_checks = false; } } if (Compiler::omit_stack_frame()) { need_stack_and_timer_checks = false; } if (!need_stack_and_timer_checks) { // Just need to update method execution sensor if (!GenerateROMImage) { strb(gp, imm_index(gp, address(_method_execution_sensor) - address(&gp_base_label))); } } else { #if !ENABLE_TRAMPOLINE if (GenerateCompilerAssertions) { // Our calling convention guarantees method is in Register::callee. ldr_oop(r12, method); cmp(r12, reg(callee)); breakpoint(ne); } #endif COMPILER_COMMENT(("check for stack overflow and timer tick")); GUARANTEE(callee == r0 || callee == r1, "code assumption"); TempRegister stack_limit(r4); TempRegister tmp(r3); #if ENABLE_XSCALE_WMMX_TIMER_TICK && !ENABLE_TIMER_THREAD get_current_stack_limit(stack_limit); #else TempRegister timer_ticks(r2); get_rt_timer_ticks(timer_ticks); get_current_stack_limit(stack_limit); #endif if (!GenerateROMImage) { strb(gp, imm_index(gp, address(_method_execution_sensor) - address(&gp_base_label))); } #if ENABLE_XSCALE_WMMX_TIMER_TICK && !ENABLE_TIMER_THREAD textrcb(0); #else cmp(timer_ticks, imm(0)); #endif if (stack_bytes_needed < LeafMethodStackPadding && method->max_execution_stack_count() < 20) { // Don't need to do an exact check -- if we overwrite slightly over // current_stack_limit, we will write into the StackPadding area, and // thus will not write outside of the legal stack area. if (JavaStackDirection < 0) { cmp(stack_limit, reg(jsp), ls); } else { cmp(jsp, reg(stack_limit), ls); } } else { add_imm(tmp, jsp, JavaStackDirection * stack_bytes_needed); if (JavaStackDirection < 0) { cmp(stack_limit, reg(tmp), ls); } else { cmp(tmp, reg(stack_limit), ls); } } // We trap back to interpreter if // (JavaStackDirection < 0) -> // (timer_ticks > 0) || stack_limit > jsp) // // (JavaStackDirection > 0) -> // (timer_ticks > 0) || jsp > stack_limit) if (USE_OVERFLOW_STUB) { // On xscale, a conditional branch is faster than a conditional ldr pc Label stack_overflow, done; b(stack_overflow, hi); bind(done); // Not actually used on ARM port StackOverflowStub::Raw stub = StackOverflowStub::allocate(stack_overflow, done, r1, r0 JVM_CHECK); stub().insert(); // If we go to the stub, we can't be guaranteed it has preserved literals frame()->clear_literals(); } else { int offset = (int)&gp_interpreter_method_entry_ptr - (int)&gp_base_label; ldr(pc, imm_index(gp, offset), hi); } } } void CodeGenerator::method_entry(Method* method JVM_TRAPS) { // prolog does some or all of the following // - update execution sensor // - check timer ticks // - check stack overflow method_prolog(method JVM_CHECK); if (Compiler::omit_stack_frame()) { // The rest of method_entry deal with pushing the call frame, so // we can safely return here. GUARANTEE(!ENABLE_WTK_PROFILER, "Profiler always need call frame"); return; } COMPILER_COMMENT(("reserve space for locals & frame descriptor")); int extra_locals = method->max_locals() - method->size_of_parameters(); int jsp_shift = extra_locals*BytesPerStackElement + JavaFrame::frame_desc_size(); if (ENABLE_FULL_STACK && (JavaFrame::empty_stack_offset() == JavaFrame::return_address_offset()) && (JavaStackDirection < 0) && (has_room_for_imm(jsp_shift, 12))) { // We can save one instruction by using ARM pre-index addressing mode str(lr, imm_index(jsp, JavaStackDirection * jsp_shift, pre_indexed)); } else { add_imm(jsp, jsp, JavaStackDirection * jsp_shift); str(lr, imm_index(jsp, JavaFrame::return_address_offset() - JavaFrame::empty_stack_offset())); } // The new fp will be at jsp - JavaFrame::empty_stack_offset(). We need to // save the old value of fp before setting the new one str(fp, imm_index(jsp, JavaFrame::caller_fp_offset() - JavaFrame::empty_stack_offset())); sub_imm(fp, jsp, JavaFrame::empty_stack_offset()); if (method->access_flags().is_synchronized()) { if (method->access_flags().is_static()) { UsingFastOops fast_oops; // Get the class mirror object. #if ENABLE_ISOLATES TempRegister task_mirror(tmp0); InstanceClass::Fast klass = method->holder(); Value klass_value(T_OBJECT); klass_value.set_obj(&klass); if (StopAtRealMirrorAccess) { breakpoint(); } load_task_mirror(&klass, klass_value, true JVM_CHECK); // Now load the real mirror ldr_imm_index(r0, klass_value.lo_register(), TaskMirror::real_java_mirror_offset()); #else JavaClass::Fast klass = method->holder(); Instance::Fast mirror = klass().java_mirror(); COMPILER_COMMENT(("Static method. Synchronize on the class " "mirror object")); if (GenerateROMImage) { // ldr_oop handles classes correctly ldr_oop(r0, &klass); ldr_imm_index(r0, r0, JavaClass::java_mirror_offset()); } else { ldr_oop(r0, &mirror); } #endif } else { COMPILER_COMMENT(("Non-static method. Synchronize on the receiver")); LocationAddress obj(0, T_OBJECT); ldr(r0, obj.lo_address_2()); } call_through_gp(gp_shared_lock_synchronized_method_ptr JVM_CHECK); } else { // not synchronized if (method->access_flags().has_monitor_bytecodes()) { // Method isn't synchronized, but it has monitor bytecodes. COMPILER_COMMENT(("fill in the stack bottom pointer")); str(jsp, imm_index(fp, JavaFrame::stack_bottom_pointer_offset())); } else { if (GenerateCompilerAssertions) { COMPILER_COMMENT(("insert bogus stack bottom pointer")); mov(r0, imm_rotate(0xBA, 4)); // pretty bogus immediate str(r0, imm_index(fp, JavaFrame::stack_bottom_pointer_offset())); } } } #if ENABLE_WTK_PROFILER // we always call this callback, as profiler can be later dynamically // enabled using C API (JVM_SendProfilerCommand) call_vm((address)jprof_record_method_transition, T_VOID JVM_CHECK); #endif } void CodeGenerator::clear_stack() { if (method()->access_flags().is_synchronized() || method()->access_flags().has_monitor_bytecodes()) { // if the method is synchronized or has monitor bytecodes the // stack bottom pointer in the frame descriptor is filled in ldr_imm_index(jsp, fp, JavaFrame::stack_bottom_pointer_offset()); } else { // Used a fixed offset from the fp add_imm(jsp, fp, JavaFrame::empty_stack_offset()); } } void CodeGenerator::clear_object_location(jint index) { // The field is actual T_OBJECT, but T_INT is simpler to work with, and // the result is the same Value zero(T_INT); zero.set_int(0); LocationAddress address(index, T_INT); store_to_address(zero, T_INT, address); } void CodeGenerator::int_binary_do(Value& result, Value& op1, Value& op2, BytecodeClosure::binary_op op JVM_TRAPS) { write_literals_if_desperate(); GUARANTEE(!result.is_present(), "result must not be present"); GUARANTEE(op1.in_register(), "op1 must be in a register"); GUARANTEE(op2.is_immediate() || op2.in_register(), "op2 must be in a register or an immediate"); static const jubyte table[] = { /* bin_add */ _add, /* bin_sub */ _sub, /* bin_mul */ 0xff, /* bin_div */ 0xff, /* bin_rem */ 0xff, /* bin_shl */ 0xff, /* bin_shr */ 0xff, /* bin_ushr*/ 0xff, /* bin_and */ _andr, /* bin_or */ _orr, /* bin_xor */ _eor, /* bin_min */ 0xff, /* bin_max */ 0xff, /* bin_rsb */ _rsb, }; switch (op) { case BytecodeClosure::bin_sub : case BytecodeClosure::bin_rsb : case BytecodeClosure::bin_add : case BytecodeClosure::bin_and : case BytecodeClosure::bin_xor : case BytecodeClosure::bin_or : GUARANTEE(int(op) >= 0 && op < sizeof(table), "sanity"); GUARANTEE(table[op] != 0xff, "sanity"); arithmetic((Opcode)(table[op]), result, op1, op2); break; case BytecodeClosure::bin_shr : shift (asr, result, op1, op2); break; case BytecodeClosure::bin_shl : shift (lsl, result, op1, op2); break; case BytecodeClosure::bin_ushr : shift (lsr, result, op1, op2); break; case BytecodeClosure::bin_mul : imul (result, op1, op2 JVM_NO_CHECK_AT_BOTTOM); break; case BytecodeClosure::bin_min : case BytecodeClosure::bin_max : assign_register(result, op1); if (op2.is_immediate()) { op2.materialize(); } cmp(op1.lo_register(), reg(op2.lo_register())); mov_reg(result.lo_register(), op1.lo_register()); mov(result.lo_register(), reg(op2.lo_register()), ((op == BytecodeClosure::bin_min) ? gt : lt)); break; case BytecodeClosure::bin_div : idiv_rem (result, op1, op2, false JVM_NO_CHECK_AT_BOTTOM); break; case BytecodeClosure::bin_rem : idiv_rem (result, op1, op2, true JVM_NO_CHECK_AT_BOTTOM); break; default : SHOULD_NOT_REACH_HERE(); break; } } void CodeGenerator::int_unary_do(Value& result, Value& op1, BytecodeClosure::unary_op op JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); GUARANTEE(!result.is_present(), "result must not be present"); GUARANTEE(op1.in_register(), "op1 must be in a register"); assign_register(result, op1); const Register resReg = result.lo_register(); const Register opReg = op1.lo_register(); switch (op) { case BytecodeClosure::una_neg : rsb(resReg, opReg, zero); break; case BytecodeClosure::una_abs : add(resReg, opReg, zero, set_CC); rsb(resReg, opReg, zero, lt); break; default: SHOULD_NOT_REACH_HERE(); break; } } void CodeGenerator::long_binary_do(Value& result, Value& op1, Value& op2, BytecodeClosure::binary_op op JVM_TRAPS) { write_literals_if_desperate(); GUARANTEE(!result.is_present(), "result must not be present"); GUARANTEE(op1.in_register(), "op1 must be in a register"); GUARANTEE(op2.is_immediate() || op2.in_register(), "op2 must be in a register or an immediate"); static const jubyte table[] = { /* bin_add */ _add, _adc, /* bin_sub */ _sub, _sbc, /* bin_mul */ 0xff, 0xff, /* bin_div */ 0xff, 0xff, /* bin_rem */ 0xff, 0xff, /* bin_shl */ 0xff, 0xff, /* bin_shr */ 0xff, 0xff, /* bin_ushr*/ 0xff, 0xff, /* bin_and */ _andr,_andr, /* bin_or */ _orr, _orr, /* bin_xor */ _eor, _eor, /* bin_min */ 0xff, 0xff, /* bin_max */ 0xff, 0xff, /* bin_rsb */ _rsb, _rsc, }; switch (op) { case BytecodeClosure::bin_sub: case BytecodeClosure::bin_rsb: case BytecodeClosure::bin_add: case BytecodeClosure::bin_and: case BytecodeClosure::bin_xor: case BytecodeClosure::bin_or : { int i = ((int)op) * 2; larithmetic((Opcode)table[i], (Opcode)table[i+1], result, op1, op2); } break; case BytecodeClosure::bin_mul: lmul (result, op1, op2 JVM_NO_CHECK_AT_BOTTOM); break; case BytecodeClosure::bin_div: ldiv (result, op1, op2 JVM_NO_CHECK_AT_BOTTOM); break; case BytecodeClosure::bin_rem: lrem (result, op1, op2 JVM_NO_CHECK_AT_BOTTOM); break; case BytecodeClosure::bin_shr : lshift(asr, result, op1, op2); break; case BytecodeClosure::bin_shl : lshift(lsl, result, op1, op2); break; case BytecodeClosure::bin_ushr: lshift(lsr, result, op1, op2); break; case BytecodeClosure::bin_min: case BytecodeClosure::bin_max: { assign_register(result, op1); // This code isn't called very often, so we don't bother optimizing // the case that op2 is an immediate if (op2.is_immediate()) { op2.materialize(); } Register A1 = op1.lsw_register(); Register A2 = op1.msw_register(); Register B1 = op2.lsw_register(); Register B2 = op2.msw_register(); Register R1 = result.lsw_register(); Register R2 = result.msw_register(); TempRegister tmp; // Compare op1 and op2. Correctly set bits for lt, ge cmp( A1, reg(B1)); sbc(tmp, A2, reg(B2), set_CC); // Copy one of the results Assembler::Condition op1_is_result = ((op == BytecodeClosure::bin_min) ? lt : ge); Assembler::Condition op2_is_result = not_cond(op1_is_result); if (A1 != R1) { mov(R1, reg(A1), op1_is_result); mov(R2, reg(A2), op1_is_result); } mov( R1, reg(B1), op2_is_result); mov( R2, reg(B2), op2_is_result); break; } default : SHOULD_NOT_REACH_HERE(); break; } } void CodeGenerator::long_unary_do(Value& result, Value& op1, BytecodeClosure::unary_op op JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); GUARANTEE(!result.is_present(), "result must not be present"); GUARANTEE(op1.in_register(), "op1 must be in a register"); Label done; assign_register(result, op1); Register A1 = op1.lsw_register(); Register A2 = op1.msw_register(); Register R1 = result.lsw_register(); Register R2 = result.msw_register(); switch (op) { case BytecodeClosure::una_neg: rsb(R1, A1, zero, set_CC); rsc(R2, A2, zero); break; case BytecodeClosure::una_abs: mov_reg(R1, A1); add(R2, A2, zero, set_CC); b(done, ge); // If hi register >= 0, positive rsb(R1, A1, zero, set_CC); rsc(R2, A2, zero); bind(done); break; default: SHOULD_NOT_REACH_HERE(); break; } } void CodeGenerator::arithmetic(Opcode opcode, Value& result, Value& op1, Value& op2) { assign_register(result, op1); const Register resReg = result.lo_register(); const Register op1Reg = op1.lo_register(); if (op2.is_immediate()) { CompilerLiteralAccessor cla; arith_imm(opcode, resReg, op1Reg, op2.as_int(), &cla); } else { arith(opcode, resReg, op1Reg, reg(op2.lo_register())); } } void CodeGenerator::imul(Value& result, Value& op1, Value& op2 JVM_TRAPS) { JVM_IGNORE_TRAPS; // Check. Can we reuse op1.lo_register() in result? result.assign_register(); const Register resReg = result.lo_register(); const Register op1Reg = op1.lo_register(); if (op2.is_immediate()) { TempRegister tmp; mul_imm(resReg, op1Reg, op2.as_int(), tmp); } else { mul(resReg, op1Reg, op2.lo_register()); } } void CodeGenerator::idiv_rem(Value& result, Value& op1, Value& op2, bool isRemainder JVM_TRAPS) { Register resReg, invReg; int divisor = op2.in_register() ? 0 : op2.as_int(); bool negate = false; if (divisor < 0) { divisor = - divisor; // We only need to negate the result for division negate = !isRemainder; } if (op2.in_register()) { flush_frame(); setup_c_args(2, &op1, &op2, NULL); // Call the compiler stub. call_through_gp(gp_compiler_idiv_irem_ptr JVM_CHECK); Register result_register = isRemainder ? r0 : r1; RegisterAllocator::reference(result_register); result.set_register(result_register); } else if (divisor == 0) { ZeroDivisorCheckStub::Raw zero = ZeroDivisorCheckStub::allocate_or_share(JVM_SINGLE_ARG_CHECK); b(&zero); Compiler::current()->closure()->terminate_compilation(); } else if (divisor == 1) { if (isRemainder) { result.set_int(0); } else if (negate) { int_unary_do(result, op1, BytecodeClosure::una_neg JVM_NO_CHECK_AT_BOTTOM); } else { op1.copy(result); } } else if (divisor == 0x80000000 || is_power_of_2(divisor)) { int shift = (divisor == 0x80000000) ? 31 : exact_log2(divisor); assign_register(result, op1); resReg = result.lo_register(); add(resReg, op1.lo_register(), zero, set_CC); rsb(resReg, resReg, zero, lt); if (isRemainder) { if (is_rotated_imm(divisor - 1) || is_rotated_imm(~(divisor - 1))) { andr_imm(resReg, resReg, divisor - 1); } else { mov(resReg, imm_shift(resReg, lsl, (32 - shift))); mov(resReg, imm_shift(resReg, lsr, (32 - shift))); } } else { int shift = (divisor == 0x80000000) ? 31 : exact_log2(divisor); mov(resReg, imm_shift(resReg, lsr, shift)); } rsb(resReg, resReg, zero, negate ? ge : lt); } else { int shift = jvm_log2(divisor); // Calculate the (32+shift)-bit fixed-point inverse of the divisor jlong magic = (jlong) ((((julong)1) << (32 + shift)) - 1); jlong ldivisor = (jlong) ((julong) ((juint)divisor)); jlong inverse = (magic / ldivisor) + 1; // See if we can use ceiling(inverse/2); jlong inverse2 = (inverse + 1) >> 1; jlong inverse2_error = inverse2 * ldivisor - (((julong)1) << (31 + shift)); if (inverse2_error < (jlong) (((julong)1 << shift))) { inverse = inverse2; shift = shift - 1; } if (negate) { inverse = -inverse; } invReg = RegisterAllocator::allocate(); mov_imm(invReg, (int)inverse); if (!isRemainder && (inverse == (int)inverse)) { assign_register(result, op1); } else { // We need to use op1 after the multiplication result.assign_register(); } resReg = result.lo_register(); TempRegister tmp; // Calculate op1 * inverse >> (32 + shift) // Note that inverse is in the range -FFFFFFFF <= inverse <= FFFFFFFF if (inverse == (int)inverse) { // inverse is a normal integer, so we can just do a signed multiply smull(tmp, resReg, invReg, op1.lo_register(), set_CC); } else { // inverse is outside the range of a normal integer, so we have to // adjust the result smull(tmp, resReg, invReg, op1.lo_register()); arith(((inverse < 0) ? _sub : _add), resReg, resReg, reg(op1.lo_register()), set_CC); } mov(resReg, imm_shift(resReg, asr, shift)); add(resReg, resReg, one, mi); // Don't use neg! since V is uncertain if (isRemainder) { mul_imm(invReg, resReg, divisor, tmp); rsb(resReg, invReg, reg(op1.lo_register())); } RegisterAllocator::dereference(invReg); } } void CodeGenerator::shift(Shift shifter, Value& result, Value& op1, Value& op2) { if (op2.is_immediate()) { assign_register(result, op1); const Register resReg = result.lo_register(); // We have to treat 0 as a special case since "asr 0" and "lsr 0" // don't actually mean "shift right by zero" int shift = (op2.as_int() & 0x1f); if (shift == 0) { mov_reg(resReg, op1.lo_register()); } else { mov(resReg, imm_shift(op1.lo_register(), shifter, shift)); } } else { assign_register(result, op2); // result & op1 can't be same const Register resReg = result.lo_register(); andr(resReg, op2.lo_register(), imm(0x1f)); mov(resReg, reg_shift(op1.lo_register(), shifter, resReg)); } } #if ENABLE_FLOAT void CodeGenerator::float_binary_do(Value& result, Value& op1, Value& op2, BytecodeClosure::binary_op op JVM_TRAPS) { JVM_IGNORE_TRAPS; typedef JVM_SOFTFP_LINKAGE float (*runtime_func_type)(float, float); static const runtime_func_type funcs[] = { /* bin_add = 0 */ jvm_fadd, /* bin_sub = 1 */ jvm_fsub, /* bin_mul = 2 */ jvm_fmul, /* bin_div = 3 */ jvm_fdiv, /* bin_rem = 4 */ jvm_frem, }; GUARANTEE(int(op) >= int(BytecodeClosure::bin_add) && int(op) <= int(BytecodeClosure::bin_rem), "sanity"); runtime_func_type runtime_func = funcs[op]; if (op1.is_immediate() && op2.is_immediate()) { float result_imm = runtime_func(op1.as_float(), op2.as_float()); result.set_float(result_imm); } else { if ((op == BytecodeClosure::bin_add || op == BytecodeClosure::bin_mul) && ( (op1.in_register() && op1.lo_register() == r1) || (op2.in_register() && op2.lo_register() == r0))) { // Avoid register shuffling on the commutative operations. call_simple_c_runtime(result, (address)runtime_func, op2, op1); } else { call_simple_c_runtime(result, (address)runtime_func, op1, op2); } } } void CodeGenerator::float_unary_do(Value& result, Value& op1, BytecodeClosure::unary_op op JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); GUARANTEE(op == BytecodeClosure::una_neg || op == BytecodeClosure::una_abs, "Sanity") GUARANTEE(!result.is_present(), "result must not be present"); GUARANTEE(op1.in_register(), "op1 must be in a register"); assign_register(result, op1); Opcode opcode = ( op == BytecodeClosure::una_neg ? _eor : _bic); arith(opcode, result.lo_register(), op1.lo_register(), imm_rotate(2,2)); } void CodeGenerator::float_cmp (Value& result, BytecodeClosure::cond_op cond, Value& op1, Value& op2 JVM_TRAPS) { JVM_IGNORE_TRAPS; JVM_SOFTFP_LINKAGE int (*runtime_func)(float, float); switch (cond) { case BytecodeClosure::lt: runtime_func = jvm_fcmpl; break; case BytecodeClosure::gt: runtime_func = jvm_fcmpg; break; default : runtime_func = 0; SHOULD_NOT_REACH_HERE(); break; } if (op1.is_immediate() && op2.is_immediate()) { result.set_int(runtime_func(op1.as_float(), op2.as_float())); } else { call_simple_c_runtime(result, (address)runtime_func, op1, op2); } } void CodeGenerator::double_binary_do(Value& result, Value& op1, Value& op2, BytecodeClosure::binary_op op JVM_TRAPS) { JVM_IGNORE_TRAPS; typedef JVM_SOFTFP_LINKAGE double (*runtime_func_type)(double, double); static const runtime_func_type funcs[] = { /* bin_add = 0 */ jvm_dadd, /* bin_sub = 1 */ jvm_dsub, /* bin_mul = 2 */ jvm_dmul, /* bin_div = 3 */ jvm_ddiv, /* bin_rem = 4 */ jvm_drem, }; GUARANTEE(int(op) >= int(BytecodeClosure::bin_add) && int(op) <= int(BytecodeClosure::bin_rem), "sanity"); runtime_func_type runtime_func = funcs[op]; if (op1.is_immediate() && op2.is_immediate()) { jdouble result_imm = runtime_func(op1.as_double(), op2.as_double()); result.set_double(result_imm); } else { call_simple_c_runtime(result, (address)runtime_func, op1, op2); } } void CodeGenerator::double_unary_do(Value& result, Value& op1, BytecodeClosure::unary_op op JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); GUARANTEE(!result.is_present(), "result must not be present"); GUARANTEE(op1.in_register(), "op1 must be in a register"); GUARANTEE(op == BytecodeClosure::una_neg || op == BytecodeClosure::una_abs, "Sanity") assign_register(result, op1); Opcode opcode = (op == BytecodeClosure::una_neg) ? _eor : _bic; if (TARGET_MSW_FIRST_FOR_DOUBLE) { // The first word contains the sign bit arith(opcode, result.lo_register(), op1.lo_register(), imm_rotate(2,2)); mov_reg( result.hi_register(), op1.hi_register()); } else { // The second word contains the sign bit arith(opcode, result.hi_register(), op1.hi_register(), imm_rotate(2,2)); mov_reg( result.lo_register(), op1.lo_register()); } } void CodeGenerator::double_cmp(Value& result, BytecodeClosure::cond_op cond, Value& op1, Value& op2 JVM_TRAPS) { JVM_IGNORE_TRAPS; JVM_SOFTFP_LINKAGE int (*runtime_func)(double, double); switch (cond) { case BytecodeClosure::lt: runtime_func = jvm_dcmpl; break; case BytecodeClosure::gt: runtime_func = jvm_dcmpg; break; default : runtime_func = 0; SHOULD_NOT_REACH_HERE(); break; } if (op1.is_immediate() && op2.is_immediate()) { result.set_int(runtime_func(op1.as_double(), op2.as_double())); } else { call_simple_c_runtime(result, (address)runtime_func, op1, op2); } } #endif // Currently, this function is only used for floating point. // It is actually rather generic and can be used for any C function // that is guaranteed to never call into the VM. void CodeGenerator::vcall_simple_c_runtime(Value& result, address runtime_func, ...) { GUARANTEE(runtime_func != 0, "sanity check"); GUARANTEE(!Compiler::omit_stack_frame(), "cannot call runtime functions with omitted compiled frame"); int i; static const Register ctemps[] = { r0, r1, r2, r3, r12, lr }; for (i = 0; i < ARRAY_SIZE(ctemps); i++) { RegisterAllocator::reference(ctemps[i]); #if ENABLE_CSE RegisterAllocator::clear_notation(ctemps[i]); COMPILER_COMMENT(("clear reg %s", Disassembler::reg_name(ctemps[i]))); #endif } for (i = 0; i < ARRAY_SIZE(ctemps); i++) { frame()->unuse_register(ctemps[i]); } for (i = 0; i < ARRAY_SIZE(ctemps); i++) { RegisterAllocator::dereference(ctemps[i]); } va_list ap; va_start(ap, runtime_func); vsetup_c_args(ap); va_end(ap); mov_imm(r12, runtime_func); if (JavaStackDirection > 0 && sp == jsp) { // IMPL_NOTE: We don't have to move to the C stack for the functions written // in assembly language in Interpreter_arm.s. // fcmpl, fcmpg, dcmpl, dcmpg, jvm_i2f, jvm_i2d, jvm_f2i mov(lr, reg(jsp)); ldr_using_gp(sp, (address)&_primordial_sp); str(lr, imm_index(sp, -BytesPerWord, pre_indexed)); } int offset = code_size(); // offset of the next instruction add(lr, pc, imm_rotate(0,0)); #if ENABLE_THUMB_VM // IMPL_NOTE: use a macro or inlined function to make this #if block // go away. bx(r12); #else mov(pc, reg(r12)); #endif write_literals(); if (!has_overflown_compiled_method()) { *(int *)addr_at(offset) |= imm(code_size() - offset - 8); } if (JavaStackDirection > 0 && sp == jsp) { ldr_imm_index(jsp, sp); } // We use "reference" rather than "allocate" since the register allocator // might think these are still in use from arguments. RegisterAllocator::reference(r0); if (result.is_two_word()) { RegisterAllocator::reference(r1); result.set_registers(r0, r1); } else { result.set_register(r0); } } void CodeGenerator::i2b(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; GUARANTEE(value.in_register(), "Immediate case already handled"); write_literals_if_desperate(); assign_register(result, value); const Register v = value.lo_register(); const Register r = result.lo_register(); mov(r, imm_shift(v, lsl, BitsPerWord - BitsPerByte)); mov(r, imm_shift(r, asr, BitsPerWord - BitsPerByte)); } void CodeGenerator::i2c(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; GUARANTEE(value.in_register(), "Immediate case already handled"); write_literals_if_desperate(); assign_register(result, value); const Register v = value.lo_register(); const Register r = result.lo_register(); mov(r, imm_shift(v, lsl, BitsPerWord - BitsPerShort)); mov(r, imm_shift(r, lsr, BitsPerWord - BitsPerShort)); } void CodeGenerator::i2s(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; GUARANTEE(value.in_register(), "Immediate case already handled"); write_literals_if_desperate(); assign_register(result, value); const Register v = value.lo_register(); const Register r = result.lo_register(); mov(r, imm_shift(v, lsl, BitsPerWord - BitsPerShort)); mov(r, imm_shift(r, asr, BitsPerWord - BitsPerShort)); } void CodeGenerator::i2l(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; GUARANTEE(value.in_register(), "Immediate case already handled"); write_literals_if_desperate(); RegisterAllocator::reference(value.lo_register()); if (TARGET_MSW_FIRST_FOR_LONG) { result.set_registers(RegisterAllocator::allocate(), value.lo_register()); mov(result.lo_register(), imm_shift(result.hi_register(), asr, 31)); } else { result.set_registers(value.lo_register(), RegisterAllocator::allocate()); mov(result.hi_register(), imm_shift(result.lo_register(), asr, 31)); } } #if ENABLE_FLOAT void CodeGenerator::i2f(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); if (value.is_immediate()) { result.set_float(::jvm_i2f(value.as_int())); } else { call_simple_c_runtime(result, (address)::jvm_i2f, value); } } void CodeGenerator::i2d(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); if (value.is_immediate()) { result.set_double(::jvm_i2d(value.as_int())); } else { call_simple_c_runtime(result, (address)::jvm_i2d, value); } } void CodeGenerator::l2f(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); if (value.is_immediate()) { result.set_float(::jvm_l2f(value.as_long())); } else { call_simple_c_runtime(result, (address)::jvm_l2f, value); } } void CodeGenerator::l2d(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); if (value.is_immediate()) { result.set_double(::jvm_l2d(value.as_long())); } else { call_simple_c_runtime(result, (address)::jvm_l2d, value); } } void CodeGenerator::f2i(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); if (value.is_immediate()) { result.set_int(::jvm_f2i(value.as_float())); } else { call_simple_c_runtime(result, (address)::jvm_f2i, value); } } void CodeGenerator::f2l(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); if (value.is_immediate()) { result.set_long(::jvm_f2l(value.as_float())); } else { call_simple_c_runtime(result, (address)::jvm_f2l, value); } } void CodeGenerator::f2d(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); if (value.is_immediate()) { result.set_double(::jvm_f2d(value.as_float())); } else { call_simple_c_runtime(result, (address)::jvm_f2d, value); } } void CodeGenerator::d2i(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); if (value.is_immediate()) { result.set_int(::jvm_d2i(value.as_double())); } else { call_simple_c_runtime(result, (address)::jvm_d2i, value); } } void CodeGenerator::d2l(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); if (value.is_immediate()) { result.set_long(::jvm_d2l(value.as_double())); } else { call_simple_c_runtime(result, (address)::jvm_d2l, value); } } void CodeGenerator::d2f(Value& result, Value& value JVM_TRAPS) { JVM_IGNORE_TRAPS; write_literals_if_desperate(); if (value.is_immediate()) { result.set_float(::jvm_d2f(value.as_double())); } else { call_simple_c_runtime(result, (address)::jvm_d2f, value); } } #endif void CodeGenerator::larithmetic(Opcode opcode1, Opcode opcode2, Value& result, Value& op1, Value& op2) { write_literals_if_desperate(); assign_register(result, op1); // Remember that "lo" and "hi" refer to the address in memory. // For big endian machines, these are counter-intuitive Register A1 = op1.lsw_register(); Register A2 = op1.msw_register(); Register R1 = result.lsw_register(); Register R2 = result.msw_register(); // Setting set_CC in all cases wouldn't be bad, but the instruction // scheduler generates better code if we use set_CC sparingly CCMode mode = (opcode1 == opcode2) ? no_CC : set_CC; if (op2.is_immediate()) { CompilerLiteralAccessor cla; arith_imm(opcode1, R1, A1, op2.lsw_bits(), &cla, mode); arith_imm(opcode2, R2, A2, op2.msw_bits(), &cla); } else { arith(opcode1, R1, A1, reg(op2.lsw_register()), mode); arith(opcode2, R2, A2, reg(op2.msw_register())); } } void CodeGenerator::lmul(Value& result, Value& op1, Value& op2 JVM_TRAPS) { JVM_IGNORE_TRAPS; // Should eventually detect multiplication by small (0..10) and // by 32bit constants and generate better code for those cases. write_literals_if_desperate(); if (op1.is_immediate()) { op1.materialize(); } if (op2.is_immediate()) { op2.materialize(); } result.assign_register(); // Remember that "lo" and "hi" refer to the address in memory. // For big endian machines, these are counter-intuitive Register A1 = op1.lsw_register(); Register A2 = op1.msw_register(); Register B1 = op2.lsw_register(); Register B2 = op2.msw_register(); Register R1 = result.lsw_register(); Register R2 = result.msw_register(); // (A2*(2^32) + A1)*(B2*(2^32) + B1) = // A2*B2*(2^64) + A2*B1(2^32) + A1*B2*(2^32) + A1*B1 // ignore 2^64 term umull(R1, R2, A1, B1 ); // r = A1*B1 mla ( R2, A1, B2, R2); // r = A1*B2*(2^32) + A1*B1 mla ( R2, A2, B1, R2); // r = A2*B1*(2^32) + A1*B2*(2^32) + A1*B1 } void CodeGenerator::runtime_long_op(Value& result, Value& op1, Value& op2, bool check_zero, address routine JVM_TRAPS) { write_literals_if_desperate(); if (check_zero) { if (op2.in_register() || (op2.is_immediate() && op2.as_long() == 0)) { ZeroDivisorCheckStub::Raw zero = ZeroDivisorCheckStub::allocate_or_share(JVM_SINGLE_ARG_CHECK); if (op2.is_immediate()) { jmp(&zero); } else { TempRegister tmp; orr(tmp, op2.lo_register(), reg(op2.hi_register()), set_CC); b(&zero, eq); } } } call_simple_c_runtime(result, routine, op1, op2); } void CodeGenerator::ldiv(Value& result, Value& op1, Value& op2 JVM_TRAPS) { runtime_long_op(result, op1, op2, true, (address)jvm_ldiv JVM_NO_CHECK_AT_BOTTOM); } void CodeGenerator::lrem(Value& result, Value& op1, Value& op2 JVM_TRAPS) { runtime_long_op(result, op1, op2, true, (address)jvm_lrem JVM_NO_CHECK_AT_BOTTOM); } void CodeGenerator::lshift(Shift type, Value& result, Value& op1, Value& op2) { write_literals_if_desperate(); if (op2.is_immediate()) { lshift_imm(type, result, op1, op2.as_int() & 63); } else { lshift_reg(type, result, op1, op2); } } void CodeGenerator::lshift_reg(Shift type, Value& result, Value& op1, Value& op2) { result.assign_register(); if (op1.is_immediate()) { op1.materialize(); } // Remember that "lo" and "hi" refer to the address in memory. // For big endian machines, these are counter-intuitive Register A1 = op1.lsw_register(); Register A2 = op1.msw_register(); Register R1 = result.lsw_register(); Register R2 = result.msw_register(); TempRegister shift; Register unshift = (type == lsl ? R1 : R2); andr(shift, op2.lo_register(), imm(63)); // Calculate 32 - shift and see if shift is >= 32 rsb(unshift, shift, imm(32), set_CC); sub(shift, shift, imm(32), le); switch(type) { case lsl: mov(R2, reg_shift(A1, lsl, shift), le); mov(R1, zero, le); mov(R2, reg_shift(A2, lsl, shift), gt); orr(R2, R2, reg_shift(A1, lsr, unshift), gt); mov(R1, reg_shift(A1, lsl, shift), gt); break; case asr: case lsr: mov(R1, reg_shift(A2, type, shift), le); mov(R2, type == lsr ? zero : imm_shift(A2, asr, 31), le); mov(R1, reg_shift(A1, lsr, shift), gt); orr(R1, R1, reg_shift(A2, lsl, unshift), gt); mov(R2, reg_shift(A2, type, shift), gt); break; } } void CodeGenerator::lshift_imm(Shift type, Value& result, Value& op1, int shift) { GUARANTEE(0 <= shift && shift <= 63, "Code guarantee"); if (shift == 0) { op1.copy(result); return; } // We could use // assign_register(result, op1) // if shift == 1 || shift >= 32, since in those cases, there is no problem // with both using the same location. Not really worth it. result.assign_register(); Register A1 = op1.lsw_register(); Register A2 = op1.msw_register(); Register R1 = result.lsw_register(); Register R2 = result.msw_register(); if (shift == 1) { if (type == lsl) { // multiply by two add(R1, A1, reg(A1), set_CC); adc(R2, A2, reg(A2)); } else { mov(R2, imm_shift(A2, type, 1), set_CC); // C gets bit that falls off mov(R1, imm_shift(A1, ror, 0)); // That's A1, RRX } } else if (shift < 32) { if (type == lsl) { mov(R2, imm_shift(A2, lsl, shift)); orr(R2, R2, imm_shift(A1, lsr, 32 - shift)); mov(R1, imm_shift(A1, lsl, shift)); } else { mov(R1, imm_shift(A1, lsr, shift)); orr(R1, R1, imm_shift(A2, lsl, 32-shift)); mov(R2, imm_shift(A2, type, shift)); } } else { if (type == lsl) { mov(R2, imm_shift(A1, lsl, shift - 32)); mov(R1, zero); } else { // We have to be slightly careful here for shift == 32. // "lsl 0" does the right, but "asr 0" and "lsr 0" don't. mov(R1, imm_shift(A2, shift == 32 ? lsl : type, shift - 32)); mov(R2, type == lsr ? zero : imm_shift(A2, asr, 31)); } } } void CodeGenerator::cmp_values(Value& op1, Value& op2) { GUARANTEE(op1.in_register(), "op1 must be in a register"); GUARANTEE(op2.is_immediate() || op2.in_register(), "op2 must be in a register or an immediate"); const Register op1_lo_reg = op1.lo_register(); if (op2.is_immediate()) { CompilerLiteralAccessor cla; cmp_imm(op1_lo_reg, op2.as_int(), &cla); } else { cmp(op1_lo_reg, reg(op2.lo_register())); } } void CodeGenerator::branch_if_do(BytecodeClosure::cond_op condition, Value& op1, Value& op2, int destination JVM_TRAPS) { cmp_values(op1, op2); conditional_jump(condition, destination, true JVM_NO_CHECK_AT_BOTTOM); } void CodeGenerator::long_cmp(Value& result, Value& op1, Value& op2 JVM_TRAPS) { write_literals_if_desperate(); GUARANTEE(!op1.is_immediate() || !op2.is_immediate(), "Immediate case handled by generic code"); result.assign_register(); Register rreg = result.lo_register(); Value* arg1 = &op1; Value* arg2 = &op2; Value* temp; // Technically, lcmp is supposed to generate one of -1, 0, or +1. // But if we know that the next byte code is ifXX, we can product a value // that isn't correct, but is good enough for that bytecode. // // In the future, we could produce even better code by treating the // the lcmp and ifXX as a single byte code, without producing an // intermediate result. But the compiler is not yet set up to do that // easily int next_bci = Compiler::current()->closure()->next_bytecode_index(); bool negate = false; switch(method()->bytecode_at(next_bci)) { case Bytecodes::_ifeq: case Bytecodes::_ifne: // We want a value that is 0 if arg1 == arg2 and non-zero otherwise if (arg1->is_immediate()) { // The order of the arguments is immaterial temp = arg1; arg1 = arg2; arg2 = temp; } if (!arg2->is_immediate()) { eor(rreg, arg1->lsw_register(), reg(arg2->lsw_register()), set_CC); eor(rreg, arg1->msw_register(), reg(arg2->msw_register()), eq); } else { jlong value = arg2->as_long(); if (value == 0) { orr(rreg, arg1->lsw_register(), reg(arg1->msw_register())); } else { CompilerLiteralAccessor cla; eor_imm(rreg, arg1->lsw_register(), arg2->lsw_bits(), &cla, set_CC); eor_imm(rreg, arg1->msw_register(), arg2->msw_bits(), &cla, no_CC, eq); } } break; case Bytecodes::_ifle: case Bytecodes::_ifgt: negate = true; temp = arg1; arg1 = arg2; arg2 = temp; /* Fall through */ case Bytecodes::_iflt: case Bytecodes::_ifge: // if arg1 >= arg2, return value >= 0 (!negate) or <= 0 (negate) // if arg1 < arg2, return value < 0 (!negate) or > 0 (negate) // Note that in the !negate case, only the sign of the result is // important if (arg1->is_immediate()) { CompilerLiteralAccessor cla; // rreg is a temporary. We're just setting the condition codes rsb_imm(rreg, arg2->lsw_register(), arg1->lsw_bits(), &cla, set_CC); rsc_imm(rreg, arg2->msw_register(), arg1->msw_bits(), &cla, set_CC); } else if (!arg2->is_immediate()) { // rreg is a temporary. We're just setting the condition codes cmp( arg1->lsw_register(), reg(arg2->lsw_register())); sbc(rreg, arg1->msw_register(), reg(arg2->msw_register()), set_CC); } else if (arg2->as_long() == 0) { // Just use the high word of arg1 if (negate) { cmp(arg1->msw_register(), zero); } else { // We can use the high word of arg1 as result // Note, we have to copy arg1->msw_register() rather than using // it directly since an OSR might occur and bash arg1 with the // >>literally correct<< result of the comparison mov(rreg, reg(arg1->msw_register())); // Skip the code below break; } } else { CompilerLiteralAccessor cla; cmp_imm( arg1->lsw_register(), arg2->lsw_bits(), &cla); sbc_imm(rreg, arg1->msw_register(), arg2->msw_bits(), &cla, set_CC); } if (!negate) { // rreg contains the high word of arg1 - arg2, and the condition // codes indicate the sign of this result. The overflow bit indicates // that the sign bit of rreg is opposite the correct sign of arg1-arg2 mvn(rreg, reg(rreg), vs); } else { mov(rreg, one, lt); mov(rreg, zero, ge); } break; default: // Only in the test suite would lcmp be followed by something other // than ifxx. This just isn't worth worrying about. // // If in the future, we decide that this is worth compiling (hah!), then // use the code commented out below instead of the following three lines. frame()->push(op2); frame()->push(op1); go_to_interpreter(JVM_SINGLE_ARG_CHECK); break; #if NOT_CURRENTLY_USED if (op1.is_immediate()) { op1.materialize(); } if (op2.is_immediate()) { op2.materialize(); } const Register xlo = op1.lsw_register(); const Register xhi = op1.msw_register(); const Register ylo = op2.lsw_register(); const Register yhi = op2.msw_register(); const Register res = result.lsw_register(); TempRegister tmp; COMPILER_COMMENT(("subtract arguments and 'or' results")); sub(res , xlo, reg(ylo ), set_CC); sbc(tmp, xhi, reg(yhi ), set_CC); orr(tmp, res, reg(tmp), no_CC); COMPILER_COMMENT(("the condition codes are set correctly " "*only* for < and >=")); mvn(res, imm(0), lt); COMPILER_COMMENT(("wrong if ==, but fixed below")); mov(res, imm(1), ge); COMPILER_COMMENT(("correction for ==")); // Note: If we had an extra register besides tmp, we could keep // alive the result of the first subtraction and do the orr // here instead of the cmp. This would save one instruction. cmp(tmp, imm(0)); mov(res, imm(0), eq); break; #endif } } void CodeGenerator::check_bytecode_counter() { if (Deterministic) { Label det_done; Register reg = RegisterAllocator::allocate(); get_bytecode_counter(reg); sub(reg, reg, imm(1), set_CC); b(det_done, ne); #if ENABLE_XSCALE_WMMX_TIMER_TICK && !ENABLE_TIMER_THREAD wcmpeqb(wR0, wR0, wR0); #else get_rt_timer_ticks(reg); add(reg, reg, imm(1)); set_rt_timer_ticks(reg); #endif mov_imm(reg, RESCHEDULE_COUNT); bind(det_done); set_bytecode_counter(reg); RegisterAllocator::dereference(reg); } } void CodeGenerator::check_timer_tick(JVM_SINGLE_ARG_TRAPS) { Label timer_tick, done; COMPILER_COMMENT(("check for timer tick")); TempRegister tmp; #if ENABLE_XSCALE_WMMX_TIMER_TICK && !ENABLE_TIMER_THREAD textrcb(0); b(timer_tick, ne); #else get_rt_timer_ticks(tmp); cmp(tmp, imm(0)); b(timer_tick, ne); #endif write_literals_if_desperate(); bind(done); TimerTickStub::Raw stub = TimerTickStub::allocate(Compiler::bci(), timer_tick, done JVM_NO_CHECK); if (stub.not_null()) { stub().insert(); // If we go to the stub, we can't be guaranteed it has preserved literals frame()->clear_literals(); } } void CodeGenerator::check_cast(Value& object, Value& klass, int class_id JVM_TRAPS) { Label slow_case, done_checking; COMPILER_COMMENT(("Typecast type check")); frame()->push(object); // Since register allocation might cause spilling we have to allocate *all* // registers before checking for null object. TempRegister tmp1; TempRegister tmp2; COMPILER_COMMENT(("Check for NULL object, get its class if not null")); cmp(object.lo_register(), zero); ldr(tmp2, imm_index(object.lo_register()), ne); b(done_checking, eq); ldr(tmp2, imm_index(tmp2), ne); COMPILER_COMMENT(("Check the subtype caches")); ldr_imm_index(tmp1, tmp2, JavaClass::subtype_cache_1_offset()); ldr_imm_index(tmp2, tmp2, JavaClass::subtype_cache_2_offset()); cmp(tmp1, reg(klass.lo_register())); cmp(tmp2, reg(klass.lo_register()), ne); if (need_to_force_literals()) { b(done_checking, eq); b(slow_case, ne); write_literals(); } else { b(slow_case, ne); } bind(done_checking); CheckCastStub::insert(bci(), class_id, slow_case, done_checking JVM_CHECK); frame()->pop(object); // If we go to the stub, we can't be guaranteed it has preserved literals frame()->clear_literals(); } bool CodeGenerator::quick_check_cast(int class_id, Label& stub_label, Label& return_label JVM_TRAPS) { bind(stub_label); { PreserveVirtualStackFrameState state(frame() JVM_CHECK_0); // Check that [top of stack] is castable to class_id mov_imm(tmp0, class_id); call_through_gp(gp_compiler_checkcast_ptr JVM_CHECK_0); } jmp(return_label); return true; } bool CodeGenerator::quick_instance_of(int class_id JVM_TRAPS) { // Check that [top of stack] is instanceof class_id. The return value // (true or false) is stored in BinaryAssembler::return_register mov_imm(r0, class_id); call_through_gp(gp_compiler_instanceof_ptr JVM_CHECK_0); return true; } void CodeGenerator::instance_of(Value& result, Value& object, Value& klass, int class_id JVM_TRAPS) { Label slow_case, done_checking; result.assign_register(); COMPILER_COMMENT(("Instance-of type check")); frame()->push(object); // Since register allocation might cause spilling we have to allocate *all* // registers before checking for null object. TempRegister tmp1; TempRegister tmp2; COMPILER_COMMENT(("Check for NULL object; Get the class for the object")); cmp(object.lo_register(), zero); ldr(tmp2, imm_index(object.lo_register()), ne); mov(result.lo_register(), zero, eq); ldr(tmp2, imm_index(tmp2), ne); b(done_checking, eq); COMPILER_COMMENT(("Check the subtype caches")); ldr_imm_index(tmp1, tmp2, JavaClass::subtype_cache_1_offset()); ldr_imm_index(tmp2, tmp2, JavaClass::subtype_cache_2_offset()); cmp(tmp1, reg(klass.lo_register())); cmp(tmp2, reg(klass.lo_register()), ne); mov(result.lo_register(), one, eq); if (need_to_force_literals()) { b(done_checking, eq); b(slow_case, ne); write_literals(); } else { b(slow_case, ne); } bind(done_checking); InstanceOfStub::Raw stub = InstanceOfStub::allocate(bci(), class_id, slow_case, done_checking, result.lo_register() JVM_NO_CHECK); if (stub.not_null()) { stub().insert(); frame()->pop(object); // If we go to the stub, we can't be guaranteed it has preserved literals frame()->clear_literals(); } } void CodeGenerator::if_then_else(Value& result, BytecodeClosure::cond_op condition, Value& op1, Value& op2, ExtendedValue& result_true, ExtendedValue& result_false JVM_TRAPS) { JVM_IGNORE_TRAPS; cmp_values(op1, op2); // Destroy op1, op2 since quite often result_true is using same register op1.destroy(); op2.destroy(); if (result_true.is_value()) { assign_register(result, result_true.value()); } else { result.assign_register(); } Condition cond = convert_condition(condition); move(result, result_true, cond); move(result, result_false, not_cond(cond)); } void CodeGenerator::if_iinc(Value& result, BytecodeClosure::cond_op condition, Value& op1, Value& op2, Value& arg, int increment JVM_TRAPS) { JVM_IGNORE_TRAPS; cmp_values(op1, op2); // Destroy op1, op2 since quite often value is using the same register op1.destroy(); op2.destroy(); Condition cond = convert_condition(condition); if (arg.is_immediate()) { arg.materialize(); } assign_register(result, arg); // We hope that the following generates no code! move(result, arg); const Register reg = result.lo_register(); add_imm(reg, reg, increment, no_CC, cond); } void CodeGenerator::new_object(Value& result, JavaClass* klass JVM_TRAPS) { COMPILER_COMMENT(("new_object")); #ifdef AZZERT InstanceSize size = klass->instance_size(); GUARANTEE(size.is_fixed(), "Size must be fixed in order to do allocation"); #endif // Do flushing, and remember to unmap. flush_frame(); // Handle finalization by going slow-case for objects with finalizers. if (klass->has_finalizer()) { // _newobject(Thread&, raw_class); ldr_oop(r1, klass); call_vm((address) _newobject, T_OBJECT JVM_CHECK); } else { ldr_oop(r0, klass); call_through_gp(gp_compiler_new_object_ptr JVM_CHECK); } // The result is in r0 RegisterAllocator::reference(r0); result.set_register(r0); } void CodeGenerator::new_object_array(Value& result, JavaClass* element_class, Value& length JVM_TRAPS) { UsingFastOops fast_oops; JavaClass::Fast array_class = element_class->get_array_class(1 JVM_CHECK); JavaNear::Fast java_near = array_class().prototypical_near(); // Do flushing, and remember to unmap. flush_frame(); // Call the allocation routine. Value save_reg_for_oop(T_ILLEGAL); setup_c_args(2, &save_reg_for_oop, &length, NULL); ldr_oop(r0, &java_near); call_through_gp(gp_compiler_new_obj_array_ptr JVM_CHECK); // The result is in r0 RegisterAllocator::reference(r0); result.set_register(r0); } void CodeGenerator::new_basic_array(Value& result, BasicType type, Value& length JVM_TRAPS) { UsingFastOops fast_oops; // Do flushing, and remember to unmap. flush_frame(); TypeArrayClass* array_class = Universe::as_TypeArrayClass(type); JavaNear::Fast java_near = array_class->prototypical_near(); Value actual_length(T_INT); Value save_reg_for_oop(T_ILLEGAL); if (length.is_immediate()) { int value = length.as_int(); if (value < 0) { actual_length.set_int(0); } else { actual_length.set_int(ArrayDesc::allocation_size(value, array_class->scale())); } } else { // Try to allocate actual_length into r2, if possible if (length.lo_register() != r2) { actual_length.set_register(RegisterAllocator::allocate(r2)); } else { actual_length.assign_register(); } switch(array_class->scale()) { case 1: add(actual_length.lo_register(), length.lo_register(), imm(Array::base_offset() + BytesPerWord - 1)); bic(actual_length.lo_register(), actual_length.lo_register(), imm(3)); break; case 2: mov(actual_length.lo_register(), imm_shift(length.lo_register(), lsl, 1)); add(actual_length.lo_register(), actual_length.lo_register(), imm(Array::base_offset() + BytesPerWord - 1)); bic(actual_length.lo_register(), actual_length.lo_register(), imm(3)); break; default: mov(actual_length.lo_register(), imm_shift(length.lo_register(), lsl, jvm_log2(array_class->scale()))); add(actual_length.lo_register(), actual_length.lo_register(), imm(Array::base_offset())); break; } } setup_c_args(3, &save_reg_for_oop, &length, &actual_length, NULL); ldr_oop(r0, &java_near); call_through_gp(gp_compiler_new_type_array_ptr JVM_CHECK); // The result is in r0 RegisterAllocator::reference(r0); result.set_register(r0); } void CodeGenerator::new_multi_array(Value& result JVM_TRAPS) { flush_frame(); // Call the runtime system. call_vm((address) multianewarray, T_ARRAY JVM_CHECK); // The result is in r0 RegisterAllocator::reference(r0); result.set_register(r0); } void CodeGenerator::monitor_enter(Value& object JVM_TRAPS) { // For now we flush before calling the compiler monitor enter stub. flush_frame(); mov_reg(r0, object.lo_register()); call_through_gp(gp_shared_monitor_enter_ptr JVM_NO_CHECK_AT_BOTTOM); } void CodeGenerator::monitor_exit(Value& object JVM_TRAPS) { // For now we flush before calling the compiler monitor exit stub. flush_frame(); // Make sure the object is in register r0 (tos_val). mov_reg(r0, object.lo_register()); call_through_gp(gp_shared_monitor_exit_ptr JVM_NO_CHECK_AT_BOTTOM); } void CodeGenerator::return_result(Value& result JVM_TRAPS) { // unlocking of synchronized methods occurs with unlock_activation // setup result // Put the result into r0 or r0/r1 setup_c_args(1, &result, NULL); restore_last_frame(JVM_SINGLE_ARG_CHECK); int imm32; int tag; if (TaggedJavaStack) { tag = (int)::basic_type2tag(result.stack_type()); } else { tag = ::word_size_for(result.stack_type()); } if (TaggedJavaStack) { if (frame()->has_literal_value(method_return_type, imm32) && imm32 == tag){ // We can elide setting the stack type. This happens rather frequently! if (GenerateCompilerAssertions) { cmp(method_return_type, imm(MAKE_IMM(tag))); breakpoint(ne); } } else { mov(method_return_type, imm(MAKE_IMM(tag))); } } // We always return to Java code or an assembly language stub mov(pc, reg(lr)); write_literals(); } void CodeGenerator::return_void(JVM_SINGLE_ARG_TRAPS) { // unlocking of synchronized methods occurs with unlock_activation COMPILER_COMMENT(("return void")); restore_last_frame(JVM_SINGLE_ARG_CHECK); if (TaggedJavaStack) { GUARANTEE(uninitialized_tag == 0, "Same result Tagged Stack or Not"); int imm32; if (frame()->has_literal_value(method_return_type, imm32) && imm32 == 0) { // We can elide setting the stack type. This happens rather frequently! if (GenerateCompilerAssertions) { cmp(method_return_type, zero); breakpoint(ne); } } else { mov(method_return_type, zero); } } mov(pc, reg(lr)); // An excellent place to write literals write_literals(); } void CodeGenerator::return_error(Value& value JVM_TRAPS) { // This looks almost like return_void, except that we save // the return address in lr, and put the error into r0 COMPILER_COMMENT(("return with error")); mov_reg(r1, value.lo_register()); restore_last_frame(JVM_SINGLE_ARG_CHECK); long offset = (long)&gp_shared_call_vm_exception_ptr - (long)&gp_base_label; ldr(pc, imm_index(gp, offset)); write_literals(); } void CodeGenerator::restore_last_frame(JVM_SINGLE_ARG_TRAPS) { Method *m = method(); if (Compiler::omit_stack_frame()) { int params = m->size_of_parameters(); if (params > 0) { add_imm(jsp, jsp, - params * JavaStackDirection * BytesPerStackElement); } } else { jint locals = m->max_locals(); jint caller_jsp_offset_from_jsp = locals * BytesPerStackElement + JavaFrame::frame_desc_size(); if (!method()->access_flags().is_synchronized() && !method()->access_flags().has_monitor_bytecodes() && ENABLE_FULL_STACK && (frame()->stack_pointer() - locals) == -1 && (JavaFrame::empty_stack_offset() == JavaFrame::return_address_offset()) && (JavaStackDirection < 0) && (has_room_for_imm(caller_jsp_offset_from_jsp, 12))) { // Special case -- if jsp is already pointing to the return address, // we can save one instruction by using post-index addressing mode GUARANTEE(JavaFrame::caller_fp_offset() == 0, "Code assumption"); int fp_offset_from_caller_jsp = - (locals * BytesPerStackElement + JavaFrame::end_of_locals_offset()); // Fetch lr, and caller's jsp ldr(lr, imm_index(jsp, caller_jsp_offset_from_jsp, post_indexed)); // Restore caller's fp ldr_imm_index(fp, jsp, fp_offset_from_caller_jsp); } else { jint offset = JavaFrame::end_of_locals_offset() - locals * JavaStackDirection * BytesPerStackElement; // We can avoid loading a memory location by dead reckoning the new value // of jsp off of fp, then by pulling it out of the frame. ldr_imm_index(lr, fp, JavaFrame::return_address_offset()); mov(jsp, reg(fp)); GUARANTEE(JavaFrame::caller_fp_offset() == 0, "Code assumption"); if (!has_room_for_imm(abs(offset), 12)) { Compiler::abort_active_compilation(true JVM_THROW); } ldr(fp, imm_index(jsp, offset, post_indexed)); } } } // Throw exception in the simple case (the method is not synchronized, // has no monitor bytecodes, and no handler in the current method covers // this exception). void CodeGenerator::throw_simple_exception(int rte JVM_TRAPS) { long offset = 0; if (rte == ThrowExceptionStub::rte_null_pointer) { int params = method()->size_of_parameters(); if(Compiler::omit_stack_frame()) { address &target = gp_compiler_throw_NullPointerException_10_ptr; mov_imm(r0, - params * JavaStackDirection * BytesPerStackElement); offset = (long)&target - (long)&gp_base_label; } else { address &target = gp_compiler_throw_NullPointerException_ptr; mov_imm(r0, method()->max_locals()); offset = (long)&target - (long)&gp_base_label; } ldr_imm_index(pc, gp, offset); } else if (rte == ThrowExceptionStub::rte_array_index_out_of_bounds) { int params = method()->size_of_parameters(); if(Compiler::omit_stack_frame()) { address &target = gp_compiler_throw_ArrayIndexOutOfBoundsException_10_ptr; mov_imm(r0, - params * JavaStackDirection * BytesPerStackElement); offset = (long)&target - (long)&gp_base_label; } else { address &target = gp_compiler_throw_ArrayIndexOutOfBoundsException_ptr; mov_imm(r0, method()->max_locals()); offset = (long)&target - (long)&gp_base_label; } ldr_imm_index(pc, gp, offset); } else { // IMPL_NOTE: old code frame()->clear(); Value exception(T_OBJECT); call_vm(ThrowExceptionStub::exception_allocator(rte), T_OBJECT JVM_CHECK); exception.set_register( RegisterAllocator::allocate(Assembler::return_register)); return_error(exception JVM_NO_CHECK_AT_BOTTOM); } } void CodeGenerator::unlock_activation(JVM_SINGLE_ARG_TRAPS) { GUARANTEE(method()->access_flags().is_synchronized(), "Sanity check"); GUARANTEE(ROM::is_synchronized_method_allowed(method()), "sanity"); flush_frame(); call_through_gp(gp_shared_unlock_synchronized_method_ptr JVM_NO_CHECK_AT_BOTTOM); } void CodeGenerator::check_monitors(JVM_SINGLE_ARG_TRAPS) { // Make sure there are no locked monitors on the stack. Label unlocking_loop, unlocking_loop_entry; TempRegister lock; TempRegister object; TempRegister end; write_literals_if_desperate(); // Add the stub for the unlock exception. UnlockExceptionStub::Raw unlock_exception = UnlockExceptionStub::allocate_or_share(JVM_SINGLE_ARG_CHECK); CompilerLiteralAccessor cla; COMPILER_COMMENT(("Point at the object of the topmost stack lock")); ldr_imm_index(lock, fp, JavaFrame::stack_bottom_pointer_offset()); add_imm(end, fp, JavaFrame::pre_first_stack_lock_offset() + StackLock::size(), &cla); if (JavaStackDirection < 0) { add(lock, lock, imm(StackLock::size())); } // lock points at the object field of the first lock // end points to the object field of beyond the final lock b(unlocking_loop_entry); bind(unlocking_loop); cmp(object, zero); b(&unlock_exception, ne); bind(unlocking_loop_entry); cmp(lock, reg(end)); if (GenerateCompilerAssertions) { breakpoint(JavaStackDirection < 0 ? hi : lo); } ldr(object, imm_index(lock, -JavaStackDirection * (BytesPerWord + StackLock::size()), post_indexed), ne); b(unlocking_loop, ne); } void CodeGenerator::table_switch(Value& index, jint table_index, jint default_dest, jint low, jint high JVM_TRAPS) { GUARANTEE(index.in_register(), "Immediates handled by caller"); COMPILER_COMMENT(("tableswitch")); if (default_dest <= bci()) { // Negative offset in a branch table is not a usual case Compiler::abort_active_compilation(true JVM_THROW); } int table_size = high - low + 1; if (table_size >= MAX_TABLE_SWITCH_SIZE) { // Need to avoid overflow loading literals that have been used in preceding // bytecodes. Compiler::abort_active_compilation(true JVM_THROW); } int jump_table_bytes = table_size *sizeof(int); int total_bytes = jump_table_bytes + 128; // be conservative and use 128 byte pad write_literals_if_desperate(total_bytes); Register entry = RegisterAllocator::allocate(); sub_imm(entry, index.lo_register(), low); CompilerLiteralAccessor cla; cmp_imm(entry, high - low, &cla); add(pc, pc, imm_shift(entry, lsl, 2), ls); { // We fall through to here if not in the range low <= index <= high Label label; b(label, hi); CompilationContinuation::insert(default_dest, label JVM_CHECK); } for (int i = 0; i < (high - low + 1); i++) { // Create a branch for each target int jump_offset = method()->get_java_switch_int(4 * i + table_index + 12); if (jump_offset <= 0) { // Negative offset in a branch table is not a usual case Compiler::abort_active_compilation(true JVM_THROW); } Label label; b(label); CompilationContinuation::insert(bci() + jump_offset, label JVM_CHECK); } write_literals(); RegisterAllocator::dereference(entry); } bool CodeGenerator::dense_lookup_switch(Value& index, jint table_index, jint default_dest, jint num_of_pairs JVM_TRAPS) { int i, offset; int last_dense = -1; // For now we handle only dense tables with a low boundary of 0. for (i = 0, offset = table_index + 8; i < num_of_pairs; i++, offset += 8) { int key = method()->get_java_switch_int(offset); if (key != last_dense + 1) { break; } else { last_dense = key; } } int table_size = last_dense+1; if (table_size < 3) { // Not worth optimizing return false; } if (table_size > MAX_TABLE_SWITCH_SIZE) { // Avoid same literal overflow problem as in lookup_switch() return false; } // Same issue as in lookup_switch() -- force preceding literals to be written // if they are close to overflow. int jump_table_bytes = table_size *sizeof(int); int total_bytes = jump_table_bytes + 128; // be conservative and use 128 byte pad write_literals_if_desperate(total_bytes); CompilerLiteralAccessor cla; cmp_imm(index.lo_register(), last_dense, &cla); Label slow_lookup; add(pc, pc, imm_shift(index.lo_register(), lsl, 2), ls); b(slow_lookup, hi); // We fall through to here if !(0 <= index <= last_dense) for (i = 0, offset = table_index + 8; i <= last_dense; i++, offset += 8) { int jump_offset = method()->get_java_switch_int(offset + 4); Label label; b(label); CompilationContinuation::insert(bci() + jump_offset, label JVM_CHECK_0); } write_literals(); bind(slow_lookup); for (; i < num_of_pairs; i++, offset += 8) { int key = method()->get_java_switch_int(offset); int jump_offset = method()->get_java_switch_int(offset + 4); cmp_imm(index.lo_register(), key, &cla); conditional_jump(BytecodeClosure::eq, bci() + jump_offset, false JVM_CHECK_0); } branch(default_dest JVM_CHECK_0); return true; } void CodeGenerator::lookup_switch(Value& index, jint table_index, jint default_dest, jint num_of_pairs JVM_TRAPS) { // No need to do the same checking as in CodeGenerator::table_switch(), because // Literals are written inside conditional_jump(). int i, offset; // (1) Check for negative offsets for (i = 0, offset = table_index + 8; i < num_of_pairs; i++, offset += 8) { int jump_offset = method()->get_java_switch_int(offset + 4); if (jump_offset <= 0) { // Negative offset in a branch table is not a usual case Compiler::abort_active_compilation(true JVM_THROW); } } // (2) Compile dense tables with a branch table. bool dense_ok = dense_lookup_switch(index, table_index, default_dest, num_of_pairs JVM_CHECK); if (dense_ok) { return; } // (3) compile it the slow way CompilerLiteralAccessor cla; for (i = 0, offset = table_index + 8; i < num_of_pairs; i++, offset += 8) { int key = method()->get_java_switch_int(offset); int jump_offset = method()->get_java_switch_int(offset + 4); cmp_imm(index.lo_register(), key, &cla); conditional_jump(BytecodeClosure::eq, bci() + jump_offset, false JVM_CHECK); } branch(default_dest JVM_NO_CHECK_AT_BOTTOM); } #if NOT_CURRENTLY_USED void CodeGenerator::lookup_switch(Value& index, jint table_index, jint default_dest, jint num_of_pairs JVM_TRAPS) { lookup_switch(index.lo_register(), table_index, 0, num_of_pairs - 1, default_dest JVM_CHECK); branch(default_dest JVM_NO_CHECK_AT_BOTTOM); } void CodeGenerator::lookup_switch(Register index, jint table_index, jint start, jint end, jint default_dest JVM_TRAPS) { CompilerLiteralAccessor cla; #if USE_COMPILER_COMMENTS char buffer[200]; int num_of_pairs = method()->get_java_switch_int(table_index + 4); int low = (start == 0) ? -0x80000000 : method()->get_java_switch_int(8 * (start - 1) + table_index + 8) + 1; int high = (end + 1 == num_of_pairs) ? 0x7FFFFFFF : method()->get_java_switch_int(8 * (end + 1) + table_index + 8) - 1; jvm_sprintf(buffer, "0x%x <= r%d <= 0x%x", low, index, high); comment(buffer); frame()->dump(true); #endif if (end - start <= 4) { for (int i = start; i <= end; i++) { int key = method()->get_java_switch_int(8 * i + table_index + 8); int jump_bci = bci() + method()->get_java_switch_int(8 * i + table_index + 12); cmp_imm(index, key, &cla); conditional_jump(BytecodeClosure::eq, jump_bci, false JVM_CHECK); } // Allowed to fall through on default } else { Label larger, smaller_default; int i = (start + end) >> 1; int key = method()->get_java_switch_int(8 * i + table_index + 8); int jump_bci = bci() + method()->get_java_switch_int(8 * i + table_index + 12); cmp_imm(index, key, &cla); conditional_jump(BytecodeClosure::eq, jump_bci, false JVM_CHECK); b(larger, gt); { PreserveVirtualStackFrameState state(frame() JVM_CHECK); // Handle start .. i - 1 lookup_switch(index, table_index, start, i-1, default_dest JVM_CHECK); b(smaller_default); CompilationContinuation::insert(default_dest, smaller_default JVM_CHECK); } bind(larger); { PreserveVirtualStackFrameState state(frame() JVM_CHECK); // Handle start .. i - 1 lookup_switch(index, table_index, i+1, end, default_dest JVM_CHECK); // Allowed to fall through } } } #endif void CodeGenerator::invoke(Method* method, bool must_do_null_check JVM_TRAPS) { bool is_native = false; int size_of_parameters = method->size_of_parameters(); Value hold_method(T_OBJECT); Value hold_tmp(T_INT); RegisterAllocator::reference(lr); // tmp cannot be lr RegisterAllocator::reference(callee); // tmp cannot be Register::callee hold_tmp.assign_register(); RegisterAllocator::dereference(callee); RegisterAllocator::dereference(lr); Register tmp = hold_tmp.lo_register(); GUARANTEE(tmp != lr, "Must not have lr as temporary register"); GUARANTEE(tmp != callee, "Must not have callee as temporary register"); frame()->commit_changes(callee); if (must_do_null_check) { if (frame()->reveiver_must_be_nonnull(size_of_parameters)) { ldr_oop(callee, method); } else { Value receiver(T_OBJECT); Assembler::Condition cond; frame()->receiver(receiver, size_of_parameters); #if ENABLE_NPCE if (receiver.must_be_null()) { cond = maybe_null_check_1(receiver); ldr_oop(callee, method); maybe_null_check_2(cond JVM_CHECK); } else { bool is_npe; cond = maybe_null_check_1_signal(receiver, is_npe); #ifndef PRODUCT if (PrintCompiledCodeAsYouGo) { TTY_TRACE_CR((" generate a faked ldr instruction invoke=>\n")); } #endif ldr(tmp, imm_index(receiver.lo_register()), cond); maybe_null_check_2_signal(cond,is_npe JVM_CHECK); ldr_oop(callee, method); } #else cond = maybe_null_check_1(receiver); ldr_oop(callee, method); maybe_null_check_2(cond JVM_CHECK); #endif } } else { ldr_oop(callee, method); } // The method must be in callee when we enter it hold_method.set_register(RegisterAllocator::allocate(callee)); GUARANTEE(!frame()->is_mapping_something(callee), "Must be free"); #if CROSS_GENERATOR bool try_skip_lookup = true; // IMPL_NOTE: this needs to be fixed so that the AOT-compiled code can // directly invoke the method without a look up if (method->is_native() && method->get_native_code() == (address)Java_unimplemented) { // Used by AOT only: we are calling a MIDP native method, which // is not resolved during romization try_skip_lookup = false; } else if (method->is_quick_native() && method->get_quick_native_code() == (address)Java_unimplemented) { try_skip_lookup = false; } #else const bool try_skip_lookup = true; #endif if (try_skip_lookup && method->is_impossible_to_compile()) { // We don't need to hunt for the entry. Its current entry will not change const bool can_optimize_quick_natives = !ENABLE_WTK_PROFILER; if (can_optimize_quick_natives && method->is_quick_native()) { address native_code = method->get_quick_native_code(); // We actually only need to flush the end of the stack containing the // arguments, but we don't really have any way of doing that.. flush_frame(); if (size_of_parameters > 0) { add_imm(jsp, jsp, size_of_parameters * -JavaStackDirection * BytesPerStackElement); int offset = method->is_static() ? JavaFrame::arg_offset_from_sp(0) : JavaFrame::arg_offset_from_sp(-1); if (offset == 0) { set_kni_parameter_base(jsp); } else { add_imm(tmp, jsp, offset); set_kni_parameter_base(tmp); } } else { mov(tmp, zero); set_kni_parameter_base(tmp); } #ifdef AZZERT mov(tmp, one); set_jvm_in_quick_native_method(tmp); #endif Value result(T_INT); // this is a lie. But vcall wants something vcall_simple_c_runtime(result, (address)native_code, NULL); #ifdef AZZERT mov(tmp, zero); set_jvm_in_quick_native_method(tmp); #endif is_native = true; } else { address target = method->execution_entry(); mov_imm(tmp, target); flush_frame(); #if ENABLE_TRAMPOLINE && !CROSS_GENERATOR call_from_compiled_code(method, tmp, 0, size_of_parameters JVM_CHECK); #else call_from_compiled_code(tmp, 0, size_of_parameters JVM_CHECK); #endif } } else { { GUARANTEE(!frame()->is_mapping_something(tmp), "Must be free"); GUARANTEE(!frame()->is_mapping_something(callee), "Must be free"); CodeInterleaver weaver(this); // WARNING: Each of these instructions in the first part must be a // simple instruction that doesn't use literals or labels or anything // like that. Each of these instructions get interleaved with the // flush() below. // The first instruction of the flush() comes before the first // ldr(tmp...) below if (ObjectHeap::contains_moveable(method->obj()) && !GenerateROMImage) { ldr_imm_index(tmp, callee, Method::heap_execution_entry_offset()); } else { ldr_imm_index(tmp, callee, Method::variable_part_offset()); ldr_imm_index(tmp, tmp); } weaver.start_alternate(JVM_SINGLE_ARG_CHECK); flush_frame(); weaver.flush(); } // invoke the method #if ENABLE_TRAMPOLINE && !CROSS_GENERATOR call_from_compiled_code(method, tmp, 0, size_of_parameters JVM_CHECK); #else call_from_compiled_code(tmp, 0, size_of_parameters JVM_CHECK); #endif } Signature::Raw signature = method->signature(); adjust_for_invoke(method->size_of_parameters(), signature().return_type(), is_native); #if ENABLE_WTK_PROFILER flush_frame(); call_vm((address)jprof_record_method_transition, T_VOID JVM_CHECK); #endif } #if ENABLE_INLINE && ARM void CodeGenerator::virtual_method_override_verify( Method* method, ClassInfo* info JVM_TRAPS) { int size_of_parameters = method->size_of_parameters(); Assembler::Condition cond; Value hold_method(T_OBJECT); Value hold_tmp(T_INT); RegisterAllocator::reference(lr); // tmp cannot be lr hold_tmp.assign_register(); RegisterAllocator::dereference(lr); Register tmp = hold_tmp.lo_register(); { Value receiver(T_OBJECT); frame()->receiver(receiver, size_of_parameters); if (receiver.must_be_null()) { // The receiver is known to be null at compile time! go_to_interpreter(JVM_SINGLE_ARG_CHECK); return; } #if ENABLE_NPCE bool is_npce; cond = maybe_null_check_1_signal(receiver, is_npce); #else cond = maybe_null_check_1(receiver); #endif //ENABLE_NPCE ldr(tmp, imm_index(receiver.lo_register()), cond); #if ENABLE_NPCE maybe_null_check_2_signal(cond, is_npce JVM_CHECK); #else maybe_null_check_2(cond JVM_CHECK); #endif //ENABLE_NPCE } ldr(tmp, imm_index(tmp, JavaNear::class_info_offset())); TempRegister tmp2; ldr_oop(tmp2.reg(), info); cmp(tmp, reg(tmp2.reg())); } #endif void CodeGenerator::invoke_virtual(Method* method, int vtable_index, BasicType return_type JVM_TRAPS) { GUARANTEE(vtable_index >= 0, "Must be positive"); int size_of_parameters = method->size_of_parameters(); Assembler::Condition cond; Value hold_tmp(T_INT); RegisterAllocator::reference(lr); // tmp cannot be lr RegisterAllocator::reference(callee); // tmp cannot be Register::callee hold_tmp.assign_register(); RegisterAllocator::dereference(lr); RegisterAllocator::dereference(callee); Register tmp = hold_tmp.lo_register(); GUARANTEE(tmp != lr, "Must not have lr as temporary register"); GUARANTEE(tmp != callee, "Must not have callee as temporary register"); int load_near_offset; { Value receiver(T_OBJECT); frame()->receiver(receiver, size_of_parameters); if (receiver.must_be_null()) { // We are guaranteed to be in the test suite. The receiver is known to // be null at compile time! This just isn't worth worrying about go_to_interpreter(JVM_SINGLE_ARG_CHECK); return; } #if ENABLE_NPCE bool is_npe; cond = maybe_null_check_1_signal(receiver, is_npe); #else cond = maybe_null_check_1(receiver); #endif ldr(tmp, imm_index(receiver.lo_register()), cond); load_near_offset = code_size(); #if ENABLE_NPCE maybe_null_check_2_signal(cond,is_npe JVM_CHECK); #else maybe_null_check_2(cond JVM_CHECK); #endif } // This would flush callee to the stack if necessary. Value hold_method(T_OBJECT); hold_method.set_register(RegisterAllocator::allocate(callee)); const bool preload_class_info = (code_size() > load_near_offset); if (preload_class_info) { // Poor-boy's code scheduler. If some code appears after tmp was loaded, // tmp should be ready now (at least on ARM7/StrongARM). By loading it here // instead of inside the CodeInterleaver block below, sometimes we can // avoid one stall. ldr_imm_index(tmp, tmp, JavaNear::class_info_offset()); } { GUARANTEE(!frame()->is_mapping_something(tmp), "Must be free"); GUARANTEE(!frame()->is_mapping_something(callee), "Must be free"); CodeInterleaver weaver(this); // WARNING: Each of these instructions in the first part must be a // simple instruction that doesn't use literals or labels or anything // like that. Each of these instructions get interleaved with the // flush() below. // The first instruction of the flush() comes before the first // ldr(tmp...) below // // If the IMPL_NOTE below ever gets done, the constant must be generated // outside of the interleaver if it generates a literal. if (!preload_class_info) { ldr_imm_index(tmp, tmp, JavaNear::class_info_offset()); } // tmp = ClassInfo // IMPL_NOTE: how large can the constant be? // Do we need to compute it more slowly. See comment above const int offset = vtable_index * 4 + ClassInfoDesc::header_size(); if (!has_room_for_imm(abs(offset), 12)) { Compiler::abort_active_compilation(true JVM_THROW); } ldr_imm_index(callee, tmp, offset); if (ObjectHeap::contains_moveable(method->obj()) && !GenerateROMImage) { ldr_imm_index(tmp, callee, Method::heap_execution_entry_offset()); } else { ldr_imm_index(tmp, callee, Method::variable_part_offset()); ldr_imm_index(tmp, tmp); } weaver.start_alternate(JVM_SINGLE_ARG_CHECK); flush_frame(); weaver.flush(); } call_from_compiled_code(tmp, 0, size_of_parameters JVM_CHECK); adjust_for_invoke(size_of_parameters, return_type); #if ENABLE_WTK_PROFILER flush_frame(); call_vm((address)jprof_record_method_transition, T_VOID JVM_CHECK); #endif } void CodeGenerator::invoke_interface(JavaClass* klass, int itable_index, int parameters_size, BasicType return_type JVM_TRAPS) { UsingFastOops fast_oops; IncompatibleClassChangeStub::Fast icc_stub = IncompatibleClassChangeStub::allocate_or_share(JVM_SINGLE_ARG_CHECK); // Make sure that tmp0 isn't taken by receiver, below frame()->spill_register(tmp0); Value tmp(T_OBJECT); tmp.set_register(RegisterAllocator::allocate(tmp0)); // Check for NULL Assembler::Condition cond; Value receiver(T_OBJECT); frame()->receiver(receiver, parameters_size); if (receiver.must_be_null()) { // We are guaranteed to be in the test suite. The receiver is known to // be null at compile time! This just isn't worth worrying about go_to_interpreter(JVM_SINGLE_ARG_CHECK); return; } #if ENABLE_NPCE bool is_npe; cond = maybe_null_check_1_signal(receiver, is_npe); #else cond = maybe_null_check_1(receiver); #endif ldr(tmp0, imm_index(receiver.lo_register()), cond); #if ENABLE_NPCE maybe_null_check_2_signal(cond, is_npe JVM_CHECK); #else maybe_null_check_2(cond JVM_CHECK); #endif ldr(tmp0, imm_index(tmp0), cond); // Flush the virtual stack frame and unmap everything. flush_frame(); // tmp0: klass of receiver // tmp1: // tmp3: // tmp4: // tos_val: scratch ldr_imm_index(tmp0, tmp0, JavaClass::class_info_offset()); // tmp0: ClassInfo of receiver // Get the itable from the ClassInfo of the receiver object. ldrh(tmp1, imm_index3(tmp0, ClassInfo::vtable_length_offset())); ldrh(tmp4, imm_index3(tmp0, ClassInfo::itable_length_offset())); add_imm(tmp2, tmp0, ClassInfoDesc::header_size() - 2 * BytesPerWord); add(tmp2, tmp2, imm_shift(tmp1, lsl, 2)); // tmp2: itable entries mov_imm(tmp3, klass->class_id()); // tmp3: klass_index of interface // Lookup interface method table by linear search Label lookup, error; bind(lookup); sub(tmp4, tmp4, one, set_CC); ldr(tos_val, imm_index(tmp2, 2 *BytesPerWord, pre_indexed), ge); b(&icc_stub, lt); cmp(tos_val, reg(tmp3)); b(lookup, ne); // Found the itable entry - now get the method table offset from there ldr_imm_index(tmp1, tmp2, BytesPerWord); // Now get the method add_imm(callee, tmp0, BytesPerWord * itable_index); ldr(callee, add_index(callee, tmp1)); // Get the method entry from the method. // We require that Register::callee contain the method ldr_imm_index(tmp4, callee, Method::variable_part_offset()); ldr_imm_index(tmp4, tmp4); call_from_compiled_code(tmp4, 0, parameters_size JVM_CHECK); adjust_for_invoke(parameters_size, return_type); #if ENABLE_WTK_PROFILER flush_frame(); call_vm((address)jprof_record_method_transition, T_VOID JVM_CHECK); #endif } void CodeGenerator::adjust_for_invoke(int parameters_size, BasicType return_type, bool native) { if (!native) { if (TaggedJavaStack) { int tag = ::basic_type2tag(stack_type_for(return_type)); // Make sure the return value is tagged correctly // Only Java code sets the return type. Native code doesn't. if (GenerateCompilerAssertions) { cmp(method_return_type, imm(MAKE_IMM(tag))); breakpoint(ne); } frame()->set_has_literal_value(method_return_type, tag); } } // Pretend that we returned a void. frame()->adjust_for_invoke(parameters_size, T_VOID); if (return_type != T_VOID) { // Like magic, the actual return value(s) are in registers. Value result(return_type); RegisterAllocator::reference(r0); if (result.is_two_word()) { RegisterAllocator::reference(r1); result.set_registers(r0, r1); } else { result.set_register(r0); } frame()->push(result); } } void CodeGenerator::invoke_native(BasicType return_kind, address entry JVM_TRAPS) { Label redo; bind(redo); GUARANTEE(method()->max_locals() == method()->size_of_parameters(), "invoke_native can happen only in native method"); // Set _kni_parameter_base to point to first native param. Note that // this must be done in the redo loop: when the invokenative is being // redone, another native method may have executed and overwritten // _kni_parameter_base. if (method()->size_of_parameters() > 0) { LocationAddress base(0, T_OBJECT); // Type is immaterial int offset = base.get_fixed_offset(); // Offset from fp of first argument if (method()->is_static()) { // KNI-ism, fake parameter slot for static method offset += -JavaStackDirection * BytesPerStackElement; COMPILER_COMMENT(("Set _kni_parameter_base (static method)")); } else { COMPILER_COMMENT(("Set _kni_parameter_base (virtual method)")); } add_imm(tmp2, fp, offset); } else { GUARANTEE(method()->is_static(), "Of course"); mov(tmp2, zero); } set_kni_parameter_base(tmp2); #if ENABLE_PROFILER if (UseProfiler) { COMPILER_COMMENT(("Inform Profiler we're inside native method")); mov_imm(tmp1, 1); mov_imm(tmp2, (int)&_jvm_profiler_in_native_method); str(tmp1, imm_index(tmp2)); } #endif COMPILER_COMMENT(("invoke native method")); call_vm(entry, return_kind JVM_CHECK); COMPILER_COMMENT(("Check if native method needs redoing")); get_thread(tmp1); mov(tmp3, zero); ldr_imm_index(tmp2, tmp1, Thread::async_redo_offset()); str(tmp3, imm_index(tmp1, Thread::async_redo_offset())); cmp(tmp2, zero); b(redo, ne); COMPILER_COMMENT(("Clear Thread::async_info")); str(tmp3, imm_index(tmp1, Thread::async_info_offset())); #if ENABLE_PROFILER if (UseProfiler) { COMPILER_COMMENT(("Inform Profiler we're out of native method")); mov_imm(tmp1, 0); mov_imm(tmp2, (int)&_jvm_profiler_in_native_method); str(tmp1, imm_index(tmp2)); } #endif adjust_for_invoke(0, return_kind, true); } #if ENABLE_TRAMPOLINE && !CROSS_GENERATOR void CodeGenerator::call_from_compiled_code(Method* callee, Register dst, int offset, int parameters_size, bool indirect, bool speed JVM_TRAPS) { GUARANTEE(dst != lr, "Register lr will be destroyed"); if (indirect && speed) { ldr_imm_index(r12, dst, offset); dst = r12; offset = 0; indirect = false; } int code_offset = code_size(); // current pc add(lr, pc, imm_rotate(0,0)); // immediate filled in at bottom // This is never used to call C code directly. // We don't need to worry about THUMB if (indirect) { ldr_imm_index(pc, dst, offset); } else if (offset == 0) { // This instruction is faster than the "add" on the StrongArm mov(pc, reg(dst)); } else { add(pc, dst, imm(offset)); } write_literals(); write_call_info(parameters_size JVM_CHECK); if (callee && CompiledMethodCache::has_index((CompiledMethodDesc*)callee->execution_entry()) && ( callee->is_static() || callee->is_final() || callee->is_private()) ) { CompiledMethod *cm = compiled_method(); address target = callee->execution_entry(); BranchTable::append(cm->entry()+ code_offset + 4,(address) cm->obj(), (address) (target - CompiledMethodDesc::entry_offset()), *(int*) (cm->entry() + code_offset + 4)); } // Patch the "add" instruction to make lr point at following instruction if (!has_overflown_compiled_method()) { *(int *)addr_at(code_offset) |= imm(code_size() - code_offset - 8); } } #endif void CodeGenerator::call_from_compiled_code(Register dst, int offset, int parameters_size, bool indirect, bool speed JVM_TRAPS) { GUARANTEE(dst != lr, "Register lr will be destroyed"); if (indirect && speed) { ldr_imm_index(r12, dst, offset); dst = r12; offset = 0; indirect = false; } int code_offset = code_size(); // current pc add(lr, pc, imm_rotate(0,0)); // immediate filled in at bottom // This is never used to call C code directly. // We don't need to worry about THUMB if (indirect) { ldr_imm_index(pc, dst, offset); } else if (offset == 0) { // This instruction is faster than the "add" on the StrongArm mov(pc, reg(dst)); } else { add(pc, dst, imm(offset)); } write_literals(); write_call_info(parameters_size JVM_CHECK); // Patch the "add" instruction to make lr point at following instruction if (!has_overflown_compiled_method()) { *(int *)addr_at(code_offset) |= imm(code_size() - code_offset - 8); } } void CodeGenerator::write_call_info(int parameters_size JVM_TRAPS) { #if ENABLE_EMBEDDED_CALLINFO if (CallInfo::fits_compiled_compact_format(bci(), code_size(), frame()->virtual_stack_pointer() + 1) && frame()->fits_compiled_compact_format()) { CallInfo info = CallInfo::compiled_compact(bci(), code_size()); frame()->fill_in_tags(info, parameters_size); emit_ci(info); } else { { TypeArray::Raw extended_tag_info = frame()->generate_callinfo_stackmap(JVM_SINGLE_ARG_CHECK); for (int i = extended_tag_info().length() - 1; i >= 0; i--) { emit_int(extended_tag_info().int_at(i)); } } CallInfo info = CallInfo::compiled(bci(), code_size() JVM_CHECK); emit_ci(info); } #endif // ENABLE_EMBEDDED_CALLINFO #if ENABLE_APPENDED_CALLINFO append_callinfo_record(code_size() JVM_NO_CHECK_AT_BOTTOM); #endif (void)parameters_size; } bool CodeGenerator::quick_catch_exception(const Value &exception_obj, JavaClass* catch_type, int handler_bci JVM_TRAPS) { TempRegister tmp1; Label quick_case; int class_id = catch_type->class_id(); ldr(tmp1, imm_index(exception_obj.lo_register())); // near object ldr(tmp1, imm_index(tmp1, JavaNear::class_info_offset())); // class_info ldrh(tmp1, imm_index3(tmp1, ClassInfo::class_id_offset())); // class_id CompilerLiteralAccessor cla; cmp_imm(tmp1, class_id, &cla); b(quick_case, eq); QuickCatchStub::Raw stub = QuickCatchStub::allocate(bci(), exception_obj, handler_bci, quick_case JVM_CHECK_0); stub().insert(); // If we go to the stub, we can't be guaranteed it has preserved literals frame()->clear_literals(); return true; // successful! } void CodeGenerator::call_vm_extra_arg(const Register extra_arg) { mov_reg(r1, extra_arg); } void CodeGenerator::call_vm_extra_arg(const int extra_arg) { mov_imm(r1, extra_arg); } void CodeGenerator::call_vm(address entry, BasicType return_value_type JVM_TRAPS) { // all registers must be flushed (not necessarily unmapped) before calling // call_vm write_literals_if_desperate(); if (entry == (address)timer_tick) { call_through_gp(gp_compiler_timer_tick_ptr, false JVM_NO_CHECK_AT_BOTTOM); } else { if (return_value_type != T_ILLEGAL) { mov_imm(r3, entry); } COMPILER_COMMENT(("call vm")); if (stack_type_for(return_value_type) == T_OBJECT) { #if ENABLE_ISOLATES if (GenerateCompilerAssertions) { if (StopAtCIBHit && entry == (address)compiled_code_task_barrier) { breakpoint(); } } #endif call_through_gp(gp_shared_call_vm_oop_ptr, false JVM_NO_CHECK_AT_BOTTOM); } else if (return_value_type == T_ILLEGAL) { call_through_gp(gp_shared_call_vm_exception_ptr, false JVM_NO_CHECK_AT_BOTTOM); } else { call_through_gp(gp_shared_call_vm_ptr, false JVM_NO_CHECK_AT_BOTTOM); } } } void CodeGenerator::type_check(Value& array, Value& index, Value& object JVM_TRAPS) { Label slow_case, done_checking; COMPILER_COMMENT(("Array store type check")); frame()->push(array); frame()->push(index); frame()->push(object); // Since register allocation might cause spilling we have to allocate *all* // registers before checking for for null object. TempRegister tmp1; TempRegister tmp2; TempRegister tmp3; ldr_imm_index(tmp2, array.lo_register()); // Check for null object. cmp(object.lo_register(), zero); ldr(tmp1, imm_index(object.lo_register()), ne); b(done_checking, eq); // Get the class and the element class of the array ldr_imm_index(tmp2, tmp2); ldr_imm_index(tmp1, tmp1); ldr_imm_index(tmp2, tmp2, ObjArrayClass::element_class_offset()); // Fast check against the subtype check caches. ldr_imm_index(tmp3, tmp1, JavaClass::subtype_cache_1_offset()); ldr_imm_index(tmp1, tmp1, JavaClass::subtype_cache_2_offset()); cmp(tmp3, reg(tmp2)); cmp(tmp1, reg(tmp2), ne); if (need_to_force_literals()) { b(done_checking, eq); b(slow_case, ne); write_literals(); } else { b(slow_case, ne); } // Cache hit. bind(done_checking); TypeCheckStub::Raw stub = TypeCheckStub::allocate(bci(), slow_case, done_checking JVM_NO_CHECK); if (stub.not_null()) { stub().insert(); frame()->pop(object); frame()->pop(index); frame()->pop(array); // If we go to the stub, we can't be guaranteed it has preserved literals frame()->clear_literals(); } } CodeGenerator::Condition CodeGenerator::convert_condition(BytecodeClosure::cond_op cond) { GUARANTEE(0 == (int) BytecodeClosure::null && 1 == (int) BytecodeClosure::nonnull && 2 == (int) BytecodeClosure::eq && 3 == (int) BytecodeClosure::ne && 4 == (int) BytecodeClosure::lt && 5 == (int) BytecodeClosure::ge && 6 == (int) BytecodeClosure::gt && 7 == (int) BytecodeClosure::le, "sanity"); static const jubyte table[] = { /* case BytecodeClosure::null */ eq, /* case BytecodeClosure::nonnull*/ ne, /* case BytecodeClosure::eq */ eq, /* case BytecodeClosure::ne */ ne, /* case BytecodeClosure::lt */ lt, /* case BytecodeClosure::ge */ ge, /* case BytecodeClosure::gt */ gt, /* case BytecodeClosure::le */ le, }; GUARANTEE(int(BytecodeClosure::null) <= int(cond) && int(cond) <= int(BytecodeClosure::le), "sanity"); return (CodeGenerator::Condition)(table[cond]); } #if ENABLE_LOOP_OPTIMIZATION && ARM void CodeGenerator::conditional_jmp(Assembler::Condition cond, int destination JVM_TRAPS) { Label branch_taken; b(branch_taken, cond); COMPILER_COMMENT(("Creating continuation for target bci = %d",destination)); CompilationContinuation::insert(destination, branch_taken JVM_NO_CHECK); write_literals_if_desperate(); } #endif//#if ENABLE_LOOP_OPTIMIZATION && ARM void CodeGenerator::conditional_jump(BytecodeClosure::cond_op condition, int destination, bool assume_backward_jumps_are_taken JVM_TRAPS) { if (assume_backward_jumps_are_taken && destination < bci()) { Label fall_through; b(fall_through, not_cond(convert_condition(condition))); int next = bci() + Bytecodes::length_for(method(), bci()); CompilationContinuation::insert(next, fall_through JVM_CHECK); COMPILER_COMMENT(("Creating continuation for fallthrough to bci = %d", bci() + Bytecodes::length_for(method(), bci()))); branch(destination JVM_NO_CHECK_AT_BOTTOM); } else { Label branch_taken; b(branch_taken, convert_condition(condition)); COMPILER_COMMENT(("Creating continuation for target bci = %d", destination)); CompilationContinuation::insert(destination, branch_taken JVM_NO_CHECK_AT_BOTTOM); } write_literals_if_desperate(); } // This function is a little bit more complicated than it needs to be at // present, but it may do more work in the future. // // It takes the argCount *Value's passed and moves them into the registers. // It can handle both immediates and registers. void CodeGenerator::setup_c_args(int ignore, ...) { // Unfortunately, we need an ignored first argument. // Ansi C doesn't allow setup_c_args(...) va_list ap; va_start(ap, ignore); vsetup_c_args(ap); va_end(ap); } void CodeGenerator::vsetup_c_args(va_list ap) { int i, targetRegister, regCount, immCount; Register srcReg[6], dstReg[6]; Register dstImm[6]; jint srcImm[6]; regCount = immCount = 0; targetRegister = 0; for(;;) { Value* value = va_arg(ap, Value*); if (value == NULL) break; if (value->type() == T_ILLEGAL) { // just a place holder. We'll fill in the register late } else if (value->in_register()) { // Make a list of the values that need to be copied from // one register into another dstReg[regCount] = as_register(targetRegister); srcReg[regCount] = value->lo_register(); regCount++; if (value->is_two_word()) { dstReg[regCount] = as_register(targetRegister + 1); srcReg[regCount] = value->hi_register(); regCount++; } } else { dstImm[immCount] = as_register(targetRegister); srcImm[immCount] = value->lo_bits(); immCount++; if (value->is_two_word()) { dstImm[immCount] = as_register(targetRegister + 1); srcImm[immCount] = value->hi_bits(); immCount++; } } targetRegister += value->is_two_word() ? 2 : 1; } // Copy the info from srcReg to dstReg if (regCount > 0) { if (regCount == 1) { // This happens often enough to optimize and avoid all the work of // shuffling the registers mov_reg(dstReg[0], srcReg[0]); } else { shuffle_registers(dstReg, srcReg, regCount); } } // Write the immediate values. CompilerLiteralAccessor cla; for (i = 0; i < immCount; i++) { mov_imm(dstImm[i], srcImm[i], &cla); } } void CodeGenerator::shuffle_registers(Register* dstReg, Register* srcReg, int regCount) { int i, j; #ifdef AZZERT bool using_scratch = false; #endif // Allocate a scratch register that isn't one of our sources and isn't one // of our targets. The sources are already in Values, so we don't need to // "reference" them. for (i = 0; i < regCount; i++) { RegisterAllocator::reference(dstReg[i]); } TempRegister scratch; for (i = 0; i < regCount; i++) { RegisterAllocator::dereference(dstReg[i]); } // We need to copy srcReg[0..regCount-1] to dstReg[0..regCount-1]; // // There may be duplications about the srcReg's, but the dstReg's are // each unique. while (regCount > 0) { if (dstReg[0] == srcReg[0]) { regCount--; srcReg++; dstReg++; continue; } // Find a dstReg[i] which isn't also a srcReg. for (i = 0; i < regCount; i++) { for (j = 0; j < regCount; j++) { if (dstReg[i] == srcReg[j]) { goto continue_outer_for_loop; } } break; continue_outer_for_loop: ; } if (i < regCount) { // Nothing uses dstReg[i] as a source. It is safe to write to it. #ifdef AZZERT if (srcReg[i] == scratch) { GUARANTEE(using_scratch, "Where did it come from?"); using_scratch = false; } #endif mov(dstReg[i], reg(srcReg[i])); // This helps remove permutations. Change anything that had used // srcReg[i] as a source to instead use dstReg[i]. for (int j = 0; j < regCount; j++) { if (i != j && srcReg[j] == srcReg[i]) { srcReg[j] = dstReg[i]; } } // And decrement. . . . regCount--; dstReg[i] = dstReg[0]; dstReg++; srcReg[i] = srcReg[0]; srcReg++; } else { // srcReg[] and dstReg[] are permutations of each other. We need // to use the scratch register to break the permutation. #ifdef AZZERT GUARANTEE(!using_scratch, "Can't have a permutation with scratch"); using_scratch = true; #endif mov(scratch, reg(srcReg[0])); srcReg[0] = scratch.reg(); // Workaround for: srcReg[0] = scratch; } } } void CodeGenerator::load_from_object(Value& result, Value& object, jint offset, bool null_check JVM_TRAPS) { Assembler::Condition cond = al; #if ENABLE_NPCE bool is_npe; #endif if (null_check) { #if ENABLE_NPCE cond = maybe_null_check_1_signal(object, is_npe); #else cond = maybe_null_check_1(object); #endif } Value object_copy; object.copy(object_copy); FieldAddress address(object_copy, offset, result.type()); load_from_address(result, result.type(), address, cond); if (null_check) { #if ENABLE_NPCE maybe_null_check_3_signal(cond, is_npe, result.type() JVM_NO_CHECK_AT_BOTTOM); #else maybe_null_check_2(cond JVM_NO_CHECK_AT_BOTTOM); #endif } } void CodeGenerator::init_static_array(Value& result JVM_TRAPS) { JVM_IGNORE_TRAPS; // Flush the virtual stack frame. flush_frame(); const Register src = tos_tag; const Register dst = tos_val; const Register size = tmp0; RegisterAllocator::reference(src); RegisterAllocator::reference(dst); RegisterAllocator::reference(size); Method::Raw cur_method = Compiler::current()->current_compiled_method()->method(); ldr_oop(src, &cur_method); mov_reg(dst, result.lo_register()); if (GenerateCompilerAssertions) { cmp(dst, zero); breakpoint(eq); } add_imm(src, src, Method::base_offset() + bci() + 1); // Load type size shift. ldrb(tmp5, imm_index(src, 1, post_indexed)); // Load elements count low byte. ldrb(size, imm_index(src, 1, post_indexed)); // Load elements count hi byte. ldrb(tmp2, imm_index(src, 1, post_indexed)); ldr(tmp3, imm_index(dst, Array::length_offset())); //load array size orr(size, size, imm_shift(tmp2, lsl, BitsPerByte)); mov(size, reg_shift(size, lsl, tmp5)); add_imm(dst, dst, Array::base_offset()); Value src_val(T_INT); src_val.set_register(src); Value dst_val(T_INT); dst_val.set_register(dst); Value size_val(T_INT); size_val.set_register(size); call_simple_c_runtime(dst_val, (address)jvm_memcpy, dst_val, src_val, size_val); } void CodeGenerator::assign_register(Value& result, Value& op) { GUARANTEE(!result.is_present(), "result must not be present"); if (!op.in_register() || frame()->is_mapping_something(op.lo_register()) || (op.is_two_word() && frame()->is_mapping_something(op.hi_register()))) { result.assign_register(); } else { op.copy(result); } } #ifdef AZZERT void CodeGenerator::verify_location_is_constant(jint index, const Value& constant) { if (GenerateCompilerAssertions) { CompilerLiteralAccessor cla; LocationAddress address(index, constant.type()); TempRegister tmp; ldr(tmp, address.lo_address_2()); cmp_imm(tmp, constant.lo_bits(), &cla); if (constant.is_two_word()) { ldr(tmp, address.hi_address_2(), eq); cmp_imm(tmp, constant.hi_bits(), &cla, eq); } breakpoint(ne); } } #endif #if CROSS_GENERATOR && !ENABLE_ISOLATES void CodeGenerator::initialize_class(InstanceClass* klass JVM_TRAPS) { GUARANTEE(klass->not_null() && !klass->is_initialized(), "Should only be called for non-initialized classes"); // initialize_class(Thread&, raw_class); COMPILER_COMMENT(("Initialize class if needed")); COMPILER_COMMENT(("Flush frame")); flush_frame(); Label class_initialized; COMPILER_COMMENT(("Load class")); ldr_oop(r1, klass); COMPILER_COMMENT(("Quick check if the class is initialized")); ldr(r0, imm_index(r1, JavaClass::java_mirror_offset())); ldr(r0, imm_index(r0, JavaClassObj::status_offset())); tst(r0, imm(JavaClassObj::INITIALIZED)); b(class_initialized, ne); COMPILER_COMMENT(("Class is not initialized - initialize it")); call_vm((address) ::initialize_class, T_VOID JVM_NO_CHECK_AT_BOTTOM); bind(class_initialized); } #endif #endif #endif /*#if !ENABLE_THUMB_COMPILER*/
[ "rajaa@6dfe35fe-931f-0410-af5f-a91b034811cd" ]
rajaa@6dfe35fe-931f-0410-af5f-a91b034811cd
51b1196cad912d044ab2962c61f383a3212946b8
7a130f1d62d2f8adc2981dec1a6f08612e22fd0e
/include/Initializer.h
fdbb7242f9158f7bb224958483c4ff29587a0f44
[]
no_license
JHzss/myproject
df9afd8f3eafeabb69df2ddb7cb965ea387b533f
9a05c01d3f2785d58dd92abeb126a017a4222735
refs/heads/master
2020-04-07T12:08:36.411596
2018-05-10T06:40:44
2018-05-10T06:40:44
124,209,818
1
0
null
null
null
null
UTF-8
C++
false
false
368
h
// // Created by jh on 18-3-12. // #ifndef MYPROJECT_INITIALIZER_H #define MYPROJECT_INITIALIZER_H #include "myheader.h" #include "Frame.h" #include "KeyFrame.h" class Initializer { public: typedef shared_ptr<Initializer> Ptr; Initializer(); Initializer::Ptr creat(){ return Initializer::Ptr(new Initializer());} }; #endif //MYPROJECT_INITIALIZER_H
[ "978176585@qq.com" ]
978176585@qq.com
76f0f6c583ef3ecf67e312b5970cd7e61ae334e5
bf93758b90f349cc0b4d034a06c60595b299841c
/Level2/Just that song/Just that song/Source.cpp
55f3742878b4fbbf24a99b68dfb36a1b8398f604
[]
no_license
ZeroFive0505/Programmers
f2a9244385e90e1ccc9eb67da9fa8127b8a2219e
672898325cc71a59e6c098d9cd760b301616900d
refs/heads/master
2023-07-18T13:23:22.383262
2021-09-06T01:35:12
2021-09-06T01:35:12
366,214,131
0
0
null
null
null
null
UTF-8
C++
false
false
2,381
cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <map> using namespace std; string Converter(string melody, map<string, string>& conv) { string m; for (int i = 0; i < melody.size(); i++) { if (melody[i + 1] == '#') { string temp; temp.push_back(melody[i]); temp.push_back(melody[i + 1]); m += conv[temp]; i++; } else m += melody[i]; } return m; } string solution(string m, vector<string> musicinfos) { string answer = "(None)"; int startTime; int endTime; int maxTime = 0; map<string, string> conv; conv["C#"] = "1"; conv["D#"] = "2"; conv["F#"] = "3"; conv["G#"] = "4"; conv["A#"] = "5"; string melody = Converter(m, conv); for (int i = 0; i < musicinfos.size(); i++) { string startHour = musicinfos[i].substr(0, 2); string startMin = musicinfos[i].substr(3, 2); string endHour = musicinfos[i].substr(6, 2); string endMin = musicinfos[i].substr(9, 2); string song; string music; for (int j = 12; j < musicinfos[i].size(); j++) { if (musicinfos[i][j] == ',') { song = musicinfos[i].substr(12, j - 12); music = musicinfos[i].substr(j + 1); break; } } startTime = stoi(startHour) * 60 + stoi(startMin); endTime = stoi(endHour) * 60 + stoi(endMin); int duration = endTime - startTime; string tmp = Converter(music, conv); if (duration > tmp.size()) { music = tmp; for (int j = 1; j < duration / tmp.size(); j++) music += tmp; for (int j = 0; j < duration % tmp.size(); j++) music += tmp[j]; } else music = tmp.substr(0, duration); if (music.find(melody) != string::npos) { if (maxTime < duration) { maxTime = duration; answer = song; } } } return answer; } int main() { string m = "ABCDEFG"; vector<string> musicinfos = { "12:00,12:14,HELLO,CDEFGAB", "13:00,13:05,WORLD,ABCDEF" }; cout << solution(m, musicinfos) << "\n"; return 0; }
[ "kimyoung1218@gmail.com" ]
kimyoung1218@gmail.com
6b7b53bed53cbfece6e2cce5fa5169e3a00aa0d4
fd7b3ac3e54faa05cc2ef402b561a1d564dba5c0
/RaiderCraft/src/RaiderCraft/world/World.h
bca5595d3ca9d4a537841dd256e2e3ef8c880ab8
[]
no_license
GooseJS/Raider
125415249900e38bbdbca8c851cbc7e0e21339aa
f8128531ac14a9ea5aa54fe0051a4881514c8b1e
refs/heads/master
2020-04-17T20:54:11.665561
2019-02-01T18:00:53
2019-02-01T18:00:53
166,925,722
0
0
null
null
null
null
UTF-8
C++
false
false
1,950
h
#pragma once #include <map> #include "Chunk.h" namespace RaiderCraft { class ChunkProvider { private: std::unordered_map<uint64_t, Chunk*> _chunks; uint64_t chunkPosToChunkIndex(int chunkX, int chunkY, int chunkZ) { ChunkPos chunkPos(chunkX, chunkY, chunkZ); return chunkPos.totalValue; } public: ChunkProvider() {} ~ChunkProvider() { for (auto iter = _chunks.begin(); iter != _chunks.end(); iter++) { Chunk* chunk = _chunks.at(iter->first); delete chunk; } } Chunk* getChunkAt(int chunkX, int chunkY, int chunkZ) { auto chunkIter = _chunks.find(chunkPosToChunkIndex(chunkX, chunkY, chunkZ)); Chunk* chunk; if (chunkIter == _chunks.end()) { chunk = new Chunk(chunkX, chunkY, chunkZ); _chunks.insert(std::pair<uint64_t, Chunk*>(chunkPosToChunkIndex(chunkX, chunkY, chunkZ), chunk)); } else { chunk = chunkIter->second; } return chunk; } std::vector<Chunk*> getLoadedChunks() { std::vector<Chunk*> loadedChunks; for (auto &chunk : _chunks) { loadedChunks.push_back(chunk.second); } return loadedChunks; } }; class World { private: ChunkProvider _chunkProvider; int chunkPos(int blockPos) { return blockPos & RD_CHUNK_DIM - 1; } public: template <bool blockPos = false> Chunk* getChunkAt(int x, int y, int z) { if (blockPos) return _chunkProvider.getChunkAt(x >> 4, y >> 4, z >> 4); return _chunkProvider.getChunkAt(x, y, z); } int getBlockAt(int blockX, int blockY, int blockZ) { return getChunkAt<true>(blockX, blockY, blockZ)->getBlockAt(chunkPos(blockX), chunkPos(blockY), chunkPos(blockZ)); } void setBlockAt(int blockX, int blockY, int blockZ, int block) { getChunkAt<true>(blockX, blockY, blockZ)->setBlockAt(chunkPos(blockX), chunkPos(blockY), chunkPos(blockZ), block); } inline std::vector<Chunk*> getLoadedChunks() { return _chunkProvider.getLoadedChunks(); } }; }
[ "goosejshf@gmail.com" ]
goosejshf@gmail.com
4a6292705b96ecab3f774e98ca8ac6ef6bdb4465
20d96ad788f3c6872c5a2c3964dbc1d47f032e9c
/Lists/DoublyCircularList/tests_doubly_circular_list.cpp
4f6f2de1ee4892ce50518d0ff76a7353486fdc14
[]
no_license
joaofel-u/Data_Structures
214df26fc926d98ab3e5ae76ff99debb3697f23c
0d33cb833a53990f5d9f66ff28e3642f618df4fe
refs/heads/master
2020-03-14T17:38:51.860440
2018-05-22T00:27:58
2018-05-22T00:27:58
131,725,191
0
0
null
null
null
null
UTF-8
C++
false
false
4,915
cpp
// Copyright 2016 João Paulo Taylor Ienczak Zanette #include "gtest/gtest.h" #include "doubly_circular_list.hpp" int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } /** * Teste para lista circular */ class DoublyCircularListTest: public ::testing::Test { protected: /** * Lista para as operações de teste */ structures::DoublyCircularList<int> list{}; }; TEST_F(DoublyCircularListTest, BasicPushBack) { list.push_back(0); ASSERT_EQ(1u, list.size()); ASSERT_EQ(0, list.at(0)); list.push_back(-1); ASSERT_EQ(2u, list.size()); ASSERT_EQ(0, list.at(0)); ASSERT_EQ(-1, list.at(1)); } TEST_F(DoublyCircularListTest, PushBack) { for (auto i = 0; i < 10; ++i) { list.push_back(i); } ASSERT_EQ(10u, list.size()); for (auto i = 0u; i < 10u; ++i) { ASSERT_EQ(i, list.at(i)); } } TEST_F(DoublyCircularListTest, BasicPushFront) { list.push_front(0); ASSERT_EQ(1u,list.size()); ASSERT_EQ(0, list.at(0)); list.push_front(-1); ASSERT_EQ(2u, list.size()); ASSERT_EQ(-1, list.at(0)); ASSERT_EQ(0, list.at(1)); } TEST_F(DoublyCircularListTest, PushFront) { for (auto i = 0; i < 10; ++i) { list.push_front(i); } ASSERT_EQ(10u, list.size()); for (auto i = 0u; i < 10u; ++i) { ASSERT_EQ(9-i, list.at(i)); } } TEST_F(DoublyCircularListTest, Empty) { ASSERT_TRUE(list.empty()); } TEST_F(DoublyCircularListTest, NotEmpty) { ASSERT_TRUE(list.empty()); list.push_back(1); ASSERT_FALSE(list.empty()); } TEST_F(DoublyCircularListTest, Clear) { for (auto i = 0; i < 10; ++i) { list.push_back(i); } list.clear(); ASSERT_EQ(0u, list.size()); } TEST_F(DoublyCircularListTest, Find) { for (auto i = 0u; i < 10u; ++i) { list.push_back(i); } for (auto i = 0u; i < 10u; ++i) { ASSERT_EQ(i, list.find(i)); } ASSERT_EQ(list.size(), list.find(10)); } TEST_F(DoublyCircularListTest, Contains) { for (auto i = 0; i < 10; ++i) { list.push_back(i); } ASSERT_TRUE(list.contains(0)); ASSERT_TRUE(list.contains(5)); ASSERT_FALSE(list.contains(10)); } TEST_F(DoublyCircularListTest, AccessAt) { for (auto i = 0; i < 10; ++i) { list.push_back(i); } for (auto i = 0u; i < 10u; ++i) { ASSERT_EQ(i, list.at(i)); } list.clear(); for (auto i = 10; i > 0; --i) { list.push_back(i); } for (auto i = 0u; i < 10u; ++i) { ASSERT_EQ(10-i, list.at(i)); } } TEST_F(DoublyCircularListTest, AccessAtBoundCheck) { for (auto i = 0; i < 10; ++i) { list.push_back(i); } for (auto i = 0; i < 10; ++i) { ASSERT_NO_THROW(list.at(i)); } ASSERT_NO_THROW(list.at(0)); ASSERT_THROW(list.at(-1), std::out_of_range); } TEST_F(DoublyCircularListTest, Insert) { for (auto i = 0; i < 5; ++i) { list.push_back(i); } for (auto i = 6; i < 10; ++i) { list.push_back(i); } list.insert(5, 5u); for (auto i = 0; i < 10; ++i) { ASSERT_EQ(i, list.at(i)); } } TEST_F(DoublyCircularListTest, InsertSorted) { for (auto i = 9; i >= 0; --i) { list.insert_sorted(i); } for (auto i = 0; i < 10; ++i) { ASSERT_EQ(i, list.at(i)); } list.clear(); list.insert_sorted(10); list.insert_sorted(-10); list.insert_sorted(42); list.insert_sorted(0); ASSERT_EQ(-10, list.at(0)); ASSERT_EQ(0, list.at(1)); ASSERT_EQ(10, list.at(2)); ASSERT_EQ(42, list.at(3)); } TEST_F(DoublyCircularListTest, InsertionBounds) { ASSERT_THROW(list.insert(1u, 1), std::out_of_range); ASSERT_THROW(list.insert(-1, 1), std::out_of_range); } TEST_F(DoublyCircularListTest, EmptyPopBack) { ASSERT_THROW(list.pop_back(), std::out_of_range); } TEST_F(DoublyCircularListTest, PopBack) { for (auto i = 0; i < 10; ++i) { list.push_back(i); } for (auto i = 9; i >= 0; --i) { ASSERT_EQ(i, list.pop_back()); } ASSERT_TRUE(list.empty()); } TEST_F(DoublyCircularListTest, EmptyPopFront) { ASSERT_THROW(list.pop_front(), std::out_of_range); } TEST_F(DoublyCircularListTest, PopFront) { for (auto i = 9; i >= 0; --i) { list.push_front(i); } for (auto i = 0; i < 10; ++i) { ASSERT_EQ(i, list.pop_front()); } ASSERT_TRUE(list.empty()); } TEST_F(DoublyCircularListTest, PopAt) { for (auto i = 0; i < 10; ++i) { list.push_back(i); } ASSERT_EQ(5, list.pop(5)); ASSERT_EQ(6, list.pop(5)); ASSERT_EQ(8u, list.size()); ASSERT_THROW(list.pop(8), std::out_of_range); } TEST_F(DoublyCircularListTest, RemoveElement) { for (auto i = 0; i < 10; ++i) { list.push_back(i); } list.remove(4); ASSERT_EQ(9u, list.size()); ASSERT_FALSE(list.contains(4)); }
[ "felippe.uller@gmail.com" ]
felippe.uller@gmail.com
ca3438dd2a39978f5a89e52b3e143a0638bcaeed
595a0393f248360517402a7c5e35495eb4d3f32e
/Exercises/Blinking_to_Music_Blinks/Blinking_to_Music_Blinks_Kid_Code.ino
141e9fc58d4d7af09dea13ca3713576bc734fb82
[]
no_license
JNazare/cssi
9795c58eeba681f8ed57dc9e1df3702b767692bb
2cb29e748bb6dba453934f267f769fe43ef00b00
refs/heads/master
2021-01-18T09:30:30.889990
2013-07-24T01:00:16
2013-07-24T01:00:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,278
ino
/* blinks: 1, 2, 1&2 */ boolean on = false; int blink_count = 0; int count = 0; int ceiling = 50; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); //blue pinMode(12, OUTPUT); //yellow pinMode(11, OUTPUT); //red? } void loop() { //int ceiling = round(analogRead(A1)/10.24); int ceiling = 25; delay(2.5); int sensorValue = analogRead(A0); Serial.println(sensorValue); Serial.print(on); if (sensorValue > ceiling && !on) { on = true; if (count > 20) { if (blink_count <= 2) { Serial.print("here"); blink_count ++; } else { blink_count = 0; } count = 0; } //mMSerial.print(blink_count); if(blink_count == 0) { Serial.print(count); digitalWrite(13, HIGH); Serial.print("b0"); count ++; } else if (blink_count == 1) { digitalWrite(12, HIGH); Serial.print("b1"); count ++; } else if (blink_count == 2) { digitalWrite(11, HIGH); Serial.print("b2"); count ++; } } else if (sensorValue < ceiling && on) { on = false; digitalWrite(13, LOW); digitalWrite(12, LOW); digitalWrite(11, LOW); } delay(2.5); }
[ "pverrecchia@gmail.com" ]
pverrecchia@gmail.com
1814d3fb3976f7946bc218ff7458a72b2c3b0d96
04b1803adb6653ecb7cb827c4f4aa616afacf629
/third_party/blink/renderer/core/dom/document_or_shadow_root.h
57f569395aaea163d80a8a2c6ca41902d4cba5bf
[ "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
3,544
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOCUMENT_OR_SHADOW_ROOT_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOCUMENT_OR_SHADOW_ROOT_H_ #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/shadow_root.h" #include "third_party/blink/renderer/core/frame/use_counter.h" #include "third_party/blink/renderer/core/fullscreen/fullscreen.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" namespace blink { class DocumentOrShadowRoot { STATIC_ONLY(DocumentOrShadowRoot); public: static Element* activeElement(Document& document) { return document.ActiveElement(); } static Element* activeElement(ShadowRoot& shadow_root) { return shadow_root.ActiveElement(); } static StyleSheetList* styleSheets(Document& document) { return &document.StyleSheets(); } static StyleSheetList* styleSheets(ShadowRoot& shadow_root) { return &shadow_root.StyleSheets(); } static const HeapVector<Member<CSSStyleSheet>>& adoptedStyleSheets( TreeScope& tree_scope) { return tree_scope.AdoptedStyleSheets(); } static void setAdoptedStyleSheets( TreeScope& tree_scope, HeapVector<Member<CSSStyleSheet>>& adopted_style_sheets, ExceptionState& exception_state) { tree_scope.SetAdoptedStyleSheets(adopted_style_sheets, exception_state); } static DOMSelection* getSelection(TreeScope& tree_scope) { return tree_scope.GetSelection(); } static Element* elementFromPoint(TreeScope& tree_scope, double x, double y) { return tree_scope.ElementFromPoint(x, y); } static HeapVector<Member<Element>> elementsFromPoint(TreeScope& tree_scope, double x, double y) { return tree_scope.ElementsFromPoint(x, y); } static Element* pointerLockElement(Document& document) { UseCounter::Count(document, WebFeature::kDocumentPointerLockElement); const Element* target = document.PointerLockElement(); if (!target) return nullptr; // For Shadow DOM V0 compatibility: We allow returning an element in V0 // shadow tree, even though it leaks the Shadow DOM. // TODO(kochi): Once V0 code is removed, the following V0 check is // unnecessary. if (target && target->IsInV0ShadowTree()) { UseCounter::Count(document, WebFeature::kDocumentPointerLockElementInV0Shadow); return const_cast<Element*>(target); } return document.AdjustedElement(*target); } static Element* pointerLockElement(ShadowRoot& shadow_root) { // TODO(kochi): Once V0 code is removed, the following non-V1 check is // unnecessary. After V0 code is removed, we can use the same logic for // Document and ShadowRoot. if (!shadow_root.IsV1()) return nullptr; UseCounter::Count(shadow_root.GetDocument(), WebFeature::kShadowRootPointerLockElement); const Element* target = shadow_root.GetDocument().PointerLockElement(); if (!target) return nullptr; return shadow_root.AdjustedElement(*target); } static Element* fullscreenElement(TreeScope& scope) { return Fullscreen::FullscreenElementForBindingFrom(scope); } }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOCUMENT_OR_SHADOW_ROOT_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
9c66f18bf39fcfcb4b62ccaa3fd58de83fd39f03
7669a4f87d7322dd0fac42197d4684cb4a78891d
/STL_GraphicsEngine2/src/private/QuadUV.cpp
cea8206ded4bae6f9083cd0b58ed55a9f97e5766
[]
no_license
mingyu243/STL_GraphicsEngine2
0a96e0b7418809b59c8ba39e2883f3eae99c938c
695e6176954318efed857e85ab72f2339409080e
refs/heads/main
2023-03-18T16:40:21.144184
2021-03-08T08:10:48
2021-03-08T08:10:48
339,295,316
1
1
null
null
null
null
UHC
C++
false
false
1,585
cpp
#include "QuadUV.h" #include <VertexUV.h> QuadUV::QuadUV() { } QuadUV::~QuadUV() { } bool QuadUV::InitializeBuffers(ID3D11Device* device, ID3DBlob* vertexShaderBuffer) { // 정점 데이터 만들기. // 정점(Vertex) 배열. // 왼손 좌표계. VertexUV vertices[] = { VertexUV(Vector3f(-0.5f, -0.5f, 0.5f), Vector2f(0.0f, 1.0f)), VertexUV(Vector3f(-0.5f, 0.5f, 0.5f), Vector2f(0.0f, 0.0f)), VertexUV(Vector3f(0.5f, 0.5f, 0.5f), Vector2f(1.0f, 0.0f)), VertexUV(Vector3f(0.5f, -0.5f, 0.5f), Vector2f(1.0f, 1.0f)) }; if (vertexBuffer.Initialize(device, vertices, ARRAYSIZE(vertices), sizeof(VertexUV)) == false) { return false; } // 인덱스 버퍼 생성. unsigned int indices[] = { 0, 1, 2, // 시계 방향으로만 돌려주면 됌. 0, 2, 3 }; if (indexBuffer.Initialize(device, indices, ARRAYSIZE(indices)) == false) { return false; } // 정점에 대한 명세 만들기 (입력 레이아웃). D3D11_INPUT_ELEMENT_DESC layout[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0} // 앞에 position이 float 4개라서 12바이트니까 12. }; if (inputLayout.Initialize(device, layout, ARRAYSIZE(layout), vertexShaderBuffer) == false) { return false; } // 상수 버퍼. if (transform.Create(device) == false) { return false; } return true; }
[ "jmg6017@naver.com" ]
jmg6017@naver.com
508fa01578fdecb67237affef5332ef606c79fae
00c5584c2f7df4653fcf80fad31642e226d5be81
/src/base/net/http/HttpResponse.h
9725e8e601def31b4c8824fb8afcf67f53abf692
[]
no_license
konechnnyigellian/tensorflow
67fe7c0ab35a3f99426c3457dcbd2985967cb62a
050947d4d638a00e917f5d3b8463748735df0977
refs/heads/master
2022-12-29T22:56:43.092690
2020-10-18T18:24:55
2020-10-18T18:24:55
305,166,835
0
0
null
null
null
null
UTF-8
C++
false
false
996
h
/* TENSERflow Copyright 2020 Copyright 2020 Copyright 2020 Copyright 2020 Copyright 2020 Copyright 2020 Copyright 2020 Copyright 2020 Copyright 2020 * Copyright 2020 */ #ifndef TENSERFLOW_HTTPRESPONSE_H #define TENSERFLOW_HTTPRESPONSE_H #include <map> #include <string> namespace tenserflow { class HttpResponse { public: HttpResponse(uint64_t id, int statusCode = 200); inline int statusCode() const { return m_statusCode; } inline void setHeader(const std::string &key, const std::string &value) { m_headers.insert({ key, value }); } inline void setStatus(int code) { m_statusCode = code; } bool isAlive() const; void end(const char *data = nullptr, size_t size = 0); private: const uint64_t m_id; int m_statusCode; std::map<const std::string, const std::string> m_headers; }; } // namespace tenserflow #endif // TENSERFLOW_HTTPRESPONSE_H
[ "adminer@gmail.com" ]
adminer@gmail.com
52d9bf854dced8f82700656825753cdcf41cd74a
66ea31cadaec228b9abf9a2ca83b469af9dc1d0a
/src/Modules/Math/Tests/PortCachingUnitTest.cc
85a89b15162a6ea382fa4954c04caa5428724b5a
[ "MIT" ]
permissive
lsptb/SCIRun
2e2857411346f0b3a02a429089a5f693bae32dc9
fafd58173c20b7b14ed700dc978da649c328c014
refs/heads/master
2021-01-17T11:17:47.765711
2015-03-12T18:07:35
2015-03-12T18:07:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,083
cc
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <gtest/gtest.h> #include <gmock/gmock.h> #include <Dataflow/Network/Network.h> #include <Dataflow/Network/ModuleInterface.h> #include <Dataflow/Network/ModuleStateInterface.h> #include <Dataflow/Network/ConnectionId.h> #include <Dataflow/Network/Tests/MockNetwork.h> #include <Core/Datatypes/DenseMatrix.h> #include <Core/Datatypes/MatrixComparison.h> #include <Core/Datatypes/MatrixIO.h> #include <Modules/Basic/SendTestMatrix.h> #include <Modules/Basic/ReceiveTestMatrix.h> #include <Modules/Basic/NeedToExecuteTester.h> #include <Modules/Factory/HardCodedModuleFactory.h> #include <Core/Algorithms/Factory/HardCodedAlgorithmFactory.h> #include <Core/Algorithms/Math/EvaluateLinearAlgebraUnaryAlgo.h> #include <Core/Algorithms/Math/EvaluateLinearAlgebraBinaryAlgo.h> #include <Core/Algorithms/Math/ReportMatrixInfo.h> #include <Dataflow/Network/Tests/MockModuleState.h> #include <Dataflow/State/SimpleMapModuleState.h> #include <Core/Algorithms/Base/AlgorithmVariableNames.h> #include <Dataflow/Engine/Controller/NetworkEditorController.h> #include <Dataflow/Network/SimpleSourceSink.h> using namespace SCIRun; using namespace SCIRun::Modules::Basic; using namespace SCIRun::Modules::Factory; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Dataflow::Networks::Mocks; using namespace SCIRun::Dataflow::Engine; using namespace SCIRun::Core::Algorithms::Math; using namespace SCIRun::Dataflow::State; using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Logging; using ::testing::_; using ::testing::NiceMock; using ::testing::DefaultValue; using ::testing::Return; namespace { DenseMatrixHandle matrix1() { DenseMatrixHandle m(new DenseMatrix(3, 3)); for (int i = 0; i < m->rows(); ++i) for (int j = 0; j < m->cols(); ++j) (*m)(i, j) = 3.0 * i + j; return m; } DenseMatrixHandle matrix2() { DenseMatrixHandle m(new DenseMatrix(3, 3)); for (int i = 0; i < m->rows(); ++i) for (int j = 0; j < m->cols(); ++j) (*m)(i, j) = -2.0 * i + j; return m; } const DenseMatrix Zero(DenseMatrix::Zero(3,3)); } namespace Testing { class MockModuleReexecutionStrategy : public ModuleReexecutionStrategy { public: MOCK_CONST_METHOD0(needToExecute, bool()); }; typedef boost::shared_ptr<MockModuleReexecutionStrategy> MockModuleReexecutionStrategyPtr; class MockInputsChangedChecker : public InputsChangedChecker { public: MOCK_CONST_METHOD0(inputsChanged, bool()); }; typedef boost::shared_ptr<MockInputsChangedChecker> MockInputsChangedCheckerPtr; class MockStateChangedChecker : public StateChangedChecker { public: MOCK_CONST_METHOD0(newStatePresent, bool()); }; typedef boost::shared_ptr<MockStateChangedChecker> MockStateChangedCheckerPtr; class MockOutputPortsCachedChecker : public OutputPortsCachedChecker { public: MOCK_CONST_METHOD0(outputPortsCached, bool()); }; typedef boost::shared_ptr<MockOutputPortsCachedChecker> MockOutputPortsCachedCheckerPtr; } #if GTEST_HAS_COMBINE using ::testing::Bool; using ::testing::Values; using ::testing::Combine; class PortCachingUnitTest : public ::testing::TestWithParam < ::std::tr1::tuple<bool, bool> > { public: PortCachingUnitTest() : portCaching_(::std::tr1::get<0>(GetParam())), needToExecute_(::std::tr1::get<1>(GetParam())) { } protected: bool portCaching_, needToExecute_; }; INSTANTIATE_TEST_CASE_P( PortCachingUnitTestParameterized, PortCachingUnitTest, Combine(Bool(), Bool()) ); TEST_P(PortCachingUnitTest, TestWithMockReexecute) { ModuleFactoryHandle mf(new HardCodedModuleFactory); ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory); AlgorithmFactoryHandle af(new HardCodedAlgorithmFactory); NetworkEditorController controller(mf, sf, ExecutionStrategyFactoryHandle(), af, ReexecuteStrategyFactoryHandle()); auto network = controller.getNetwork(); ModuleHandle send = controller.addModule("SendTestMatrix"); ModuleHandle process = controller.addModule("NeedToExecuteTester"); ModuleHandle receive = controller.addModule("ReceiveTestMatrix"); EXPECT_EQ(3, network->nmodules()); network->connect(ConnectionOutputPort(send, 0), ConnectionInputPort(process, 0)); network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(receive, 0)); EXPECT_EQ(2, network->nconnections()); SendTestMatrixModule* sendModule = dynamic_cast<SendTestMatrixModule*>(send.get()); ASSERT_TRUE(sendModule != nullptr); NeedToExecuteTester* evalModule = dynamic_cast<NeedToExecuteTester*>(process.get()); ASSERT_TRUE(evalModule != nullptr); ASSERT_FALSE(evalModule->executeCalled_); DenseMatrixHandle input = matrix1(); sendModule->get_state()->setTransientValue("MatrixToSend", input); Testing::MockModuleReexecutionStrategyPtr mockNeedToExecute(new NiceMock<Testing::MockModuleReexecutionStrategy>); process->setReexecutionStrategy(mockNeedToExecute); { evalModule->resetFlags(); std::cout << "NeedToExecute = " << needToExecute_ << ", PortCaching = " << portCaching_ << std::endl; EXPECT_CALL(*mockNeedToExecute, needToExecute()).Times(1).WillOnce(Return(needToExecute_)); SimpleSink::setGlobalPortCachingFlag(portCaching_); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::NEGATE); send->execute(); process->execute(); if (needToExecute_) receive->execute(); else EXPECT_THROW(receive->execute(), NoHandleOnPortException); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_EQ(evalModule->expensiveComputationDone_, needToExecute_); if (portCaching_ && evalModule->expensiveComputationDone_) { // to simulate real life behavior EXPECT_CALL(*mockNeedToExecute, needToExecute()).Times(1).WillOnce(Return(false)); evalModule->resetFlags(); send->execute(); process->execute(); receive->execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); } } //std::cout << "Rest of test" << std::endl; EXPECT_CALL(*mockNeedToExecute, needToExecute()).WillRepeatedly(Return(true)); ReceiveTestMatrixModule* receiveModule = dynamic_cast<ReceiveTestMatrixModule*>(receive.get()); ASSERT_TRUE(receiveModule != nullptr); if (evalModule->expensiveComputationDone_) { ASSERT_TRUE(receiveModule->latestReceivedMatrix().get() != nullptr); } evalModule->resetFlags(); send->execute(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::TRANSPOSE); process->execute(); receive->execute(); EXPECT_EQ(*input, *receiveModule->latestReceivedMatrix()); evalModule->resetFlags(); send->execute(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::SCALAR_MULTIPLY); process->get_state()->setValue(Variables::ScalarValue, 2.0); process->execute(); receive->execute(); EXPECT_EQ(*input, *receiveModule->latestReceivedMatrix()); } class ReexecuteStrategyUnitTest : public ::testing::TestWithParam < ::std::tr1::tuple<bool, bool, bool> > { public: ReexecuteStrategyUnitTest() : inputsChanged_(::std::tr1::get<0>(GetParam())), stateChanged_(::std::tr1::get<1>(GetParam())), oportsCached_(::std::tr1::get<2>(GetParam())) { SCIRun::Core::Logging::Log::get().setVerbose(true); } protected: bool inputsChanged_, stateChanged_, oportsCached_; }; INSTANTIATE_TEST_CASE_P( ReexecuteStrategyUnitTestParameterized, ReexecuteStrategyUnitTest, Combine(Bool(), Bool(), Bool()) ); TEST_P(ReexecuteStrategyUnitTest, TestAllCombinationsWithMocks) { // plug in 3 substrategies: // StateChangedChecker // InputsChangedChecker // OPortCachedChecker // Class just does a disjunction of above 3 booleans Testing::MockInputsChangedCheckerPtr mockInputsChanged(new NiceMock<Testing::MockInputsChangedChecker>); ON_CALL(*mockInputsChanged, inputsChanged()).WillByDefault(Return(inputsChanged_)); Testing::MockStateChangedCheckerPtr mockStateChanged(new NiceMock<Testing::MockStateChangedChecker>); ON_CALL(*mockStateChanged, newStatePresent()).WillByDefault(Return(stateChanged_)); Testing::MockOutputPortsCachedCheckerPtr mockOutputPortsCached(new NiceMock<Testing::MockOutputPortsCachedChecker>); ON_CALL(*mockOutputPortsCached, outputPortsCached()).WillByDefault(Return(oportsCached_)); ModuleReexecutionStrategyHandle realNeedToExecute(new DynamicReexecutionStrategy(mockInputsChanged, mockStateChanged, mockOutputPortsCached)); std::cout << "NeedToExecute = " << true << ", inputsChanged_ = " << inputsChanged_ << ", stateChanged_ = " << stateChanged_ << ", oportsCached_ = " << oportsCached_ << std::endl; EXPECT_EQ(inputsChanged_ || stateChanged_ || !oportsCached_, realNeedToExecute->needToExecute()); } #if 0 TEST_P(ReexecuteStrategyUnitTest, TestNeedToExecuteWithRealInputsChanged) { ModuleFactoryHandle mf(new HardCodedModuleFactory); ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory); AlgorithmFactoryHandle af(new HardCodedAlgorithmFactory); NetworkEditorController controller(mf, sf, ExecutionStrategyFactoryHandle(), af); auto network = controller.getNetwork(); ModuleHandle send = controller.addModule("SendTestMatrix"); ModuleHandle process = controller.addModule("NeedToExecuteTester"); ModuleHandle receive = controller.addModule("ReceiveTestMatrix"); EXPECT_EQ(3, network->nmodules()); network->connect(ConnectionOutputPort(send, 0), ConnectionInputPort(process, 0)); network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(receive, 0)); EXPECT_EQ(2, network->nconnections()); SendTestMatrixModule* sendModule = dynamic_cast<SendTestMatrixModule*>(send.get()); ASSERT_TRUE(sendModule != nullptr); NeedToExecuteTester* evalModule = dynamic_cast<NeedToExecuteTester*>(process.get()); ASSERT_TRUE(evalModule != nullptr); ASSERT_FALSE(evalModule->executeCalled_); DenseMatrixHandle input = matrix1(); sendModule->get_state()->setTransientValue("MatrixToSend", input); std::cout << "RealInputsChanged, stateChanged = " << stateChanged_ << " oportsCached = " << oportsCached_ << std::endl; InputsChangedCheckerHandle realInputsChanged(new InputsChangedCheckerImpl(*evalModule)); Testing::MockStateChangedCheckerPtr mockStateChanged(new NiceMock<Testing::MockStateChangedChecker>); ON_CALL(*mockStateChanged, newStatePresent()).WillByDefault(Return(stateChanged_)); Testing::MockOutputPortsCachedCheckerPtr mockOutputPortsCached(new NiceMock<Testing::MockOutputPortsCachedChecker>); ON_CALL(*mockOutputPortsCached, outputPortsCached()).WillByDefault(Return(oportsCached_)); ModuleReexecutionStrategyHandle realNeedToExecuteWithPartialMocks(new DynamicReexecutionStrategy(realInputsChanged, mockStateChanged, mockOutputPortsCached)); process->setRexecutionStrategy(realNeedToExecuteWithPartialMocks); { SimpleSink::setGlobalPortCachingFlag(true); evalModule->resetFlags(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::NEGATE); bool initialNeedToExecute = realNeedToExecuteWithPartialMocks->needToExecute(); send->execute(); process->execute(); if (initialNeedToExecute) receive->execute(); else EXPECT_THROW(receive->execute(), NoHandleOnPortException); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_EQ(evalModule->expensiveComputationDone_, initialNeedToExecute); if (evalModule->expensiveComputationDone_) { //inputs haven't changed. evalModule->resetFlags(); send->execute(); process->execute(); receive->execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); DenseMatrixHandle input = matrix2(); sendModule->get_state()->setTransientValue("MatrixToSend", input); //inputs have changed evalModule->resetFlags(); send->execute(); process->execute(); receive->execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_TRUE(evalModule->expensiveComputationDone_); } } } TEST_P(ReexecuteStrategyUnitTest, TestNeedToExecuteWithRealStateChanged) { FAIL() << "todo"; ModuleFactoryHandle mf(new HardCodedModuleFactory); ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory); AlgorithmFactoryHandle af(new HardCodedAlgorithmFactory); NetworkEditorController controller(mf, sf, ExecutionStrategyFactoryHandle(), af); auto network = controller.getNetwork(); ModuleHandle send = controller.addModule("SendTestMatrix"); ModuleHandle process = controller.addModule("NeedToExecuteTester"); ModuleHandle receive = controller.addModule("ReceiveTestMatrix"); EXPECT_EQ(3, network->nmodules()); network->connect(ConnectionOutputPort(send, 0), ConnectionInputPort(process, 0)); network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(receive, 0)); EXPECT_EQ(2, network->nconnections()); SendTestMatrixModule* sendModule = dynamic_cast<SendTestMatrixModule*>(send.get()); ASSERT_TRUE(sendModule != nullptr); NeedToExecuteTester* evalModule = dynamic_cast<NeedToExecuteTester*>(process.get()); ASSERT_TRUE(evalModule != nullptr); ASSERT_FALSE(evalModule->executeCalled_); DenseMatrixHandle input = matrix1(); sendModule->get_state()->setTransientValue("MatrixToSend", input); Testing::MockInputsChangedCheckerPtr mockInputsChanged(new NiceMock<Testing::MockInputsChangedChecker>); ON_CALL(*mockInputsChanged, inputsChanged()).WillByDefault(Return(inputsChanged_)); Testing::MockStateChangedCheckerPtr mockStateChanged(new NiceMock<Testing::MockStateChangedChecker>); ON_CALL(*mockStateChanged, newStatePresent()).WillByDefault(Return(stateChanged_)); Testing::MockOutputPortsCachedCheckerPtr mockOutputPortsCached(new NiceMock<Testing::MockOutputPortsCachedChecker>); ON_CALL(*mockOutputPortsCached, outputPortsCached()).WillByDefault(Return(oportsCached_)); ModuleReexecutionStrategyHandle realNeedToExecuteWithPartialMocks(new DynamicReexecutionStrategy(mockInputsChanged, mockStateChanged, mockOutputPortsCached)); process->setRexecutionStrategy(realNeedToExecuteWithPartialMocks); { evalModule->resetFlags(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::NEGATE); send->execute(); process->execute(); if (realNeedToExecuteWithPartialMocks->needToExecute()) receive->execute(); else EXPECT_THROW(receive->execute(), NoHandleOnPortException); EXPECT_TRUE(evalModule->executeCalled_); //EXPECT_EQ(evalModule->expensiveComputationDone_, needToExecute_); if (evalModule->expensiveComputationDone_) { // to simulate real life behavior evalModule->resetFlags(); send->execute(); process->execute(); receive->execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); } } //std::cout << "Rest of test" << std::endl; ReceiveTestMatrixModule* receiveModule = dynamic_cast<ReceiveTestMatrixModule*>(receive.get()); ASSERT_TRUE(receiveModule != nullptr); if (evalModule->expensiveComputationDone_) { ASSERT_TRUE(receiveModule->latestReceivedMatrix().get() != nullptr); } evalModule->resetFlags(); send->execute(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::TRANSPOSE); process->execute(); receive->execute(); EXPECT_EQ(*input, *receiveModule->latestReceivedMatrix()); evalModule->resetFlags(); send->execute(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::SCALAR_MULTIPLY); process->get_state()->setValue(Variables::ScalarValue, 2.0); process->execute(); receive->execute(); EXPECT_EQ(*input, *receiveModule->latestReceivedMatrix()); } #endif #if 0 TEST_P(ReexecuteStrategyUnitTest, TestNeedToExecuteWithRealOportsCached) { FAIL() << "todo"; ModuleFactoryHandle mf(new HardCodedModuleFactory); ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory); AlgorithmFactoryHandle af(new HardCodedAlgorithmFactory); NetworkEditorController controller(mf, sf, ExecutionStrategyFactoryHandle(), af); auto network = controller.getNetwork(); ModuleHandle send = controller.addModule("SendTestMatrix"); ModuleHandle process = controller.addModule("NeedToExecuteTester"); ModuleHandle receive = controller.addModule("ReceiveTestMatrix"); EXPECT_EQ(3, network->nmodules()); network->connect(ConnectionOutputPort(send, 0), ConnectionInputPort(process, 0)); network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(receive, 0)); EXPECT_EQ(2, network->nconnections()); SendTestMatrixModule* sendModule = dynamic_cast<SendTestMatrixModule*>(send.get()); ASSERT_TRUE(sendModule != nullptr); NeedToExecuteTester* evalModule = dynamic_cast<NeedToExecuteTester*>(process.get()); ASSERT_TRUE(evalModule != nullptr); ASSERT_FALSE(evalModule->executeCalled_); DenseMatrixHandle input = matrix1(); sendModule->get_state()->setTransientValue("MatrixToSend", input); Testing::MockInputsChangedCheckerPtr mockInputsChanged(new NiceMock<Testing::MockInputsChangedChecker>); ON_CALL(*mockInputsChanged, inputsChanged()).WillByDefault(Return(inputsChanged_)); Testing::MockStateChangedCheckerPtr mockStateChanged(new NiceMock<Testing::MockStateChangedChecker>); ON_CALL(*mockStateChanged, newStatePresent()).WillByDefault(Return(stateChanged_)); Testing::MockOutputPortsCachedCheckerPtr mockOutputPortsCached(new NiceMock<Testing::MockOutputPortsCachedChecker>); ON_CALL(*mockOutputPortsCached, outputPortsCached()).WillByDefault(Return(oportsCached_)); ModuleReexecutionStrategyHandle realNeedToExecuteWithPartialMocks(new DynamicReexecutionStrategy(mockInputsChanged, mockStateChanged, mockOutputPortsCached)); process->setRexecutionStrategy(realNeedToExecuteWithPartialMocks); { evalModule->resetFlags(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::NEGATE); send->execute(); process->execute(); if (realNeedToExecuteWithPartialMocks->needToExecute()) receive->execute(); else EXPECT_THROW(receive->execute(), NoHandleOnPortException); EXPECT_TRUE(evalModule->executeCalled_); //EXPECT_EQ(evalModule->expensiveComputationDone_, needToExecute_); if (evalModule->expensiveComputationDone_) { // to simulate real life behavior evalModule->resetFlags(); send->execute(); process->execute(); receive->execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); } } //std::cout << "Rest of test" << std::endl; ReceiveTestMatrixModule* receiveModule = dynamic_cast<ReceiveTestMatrixModule*>(receive.get()); ASSERT_TRUE(receiveModule != nullptr); if (evalModule->expensiveComputationDone_) { ASSERT_TRUE(receiveModule->latestReceivedMatrix().get() != nullptr); } evalModule->resetFlags(); send->execute(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::TRANSPOSE); process->execute(); receive->execute(); EXPECT_EQ(*input, *receiveModule->latestReceivedMatrix()); evalModule->resetFlags(); send->execute(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::SCALAR_MULTIPLY); process->get_state()->setValue(Variables::ScalarValue, 2.0); process->execute(); receive->execute(); EXPECT_EQ(*input, *receiveModule->latestReceivedMatrix()); } #endif #endif class ReexecuteStrategySimpleUnitTest : public ::testing::Test { public: ReexecuteStrategySimpleUnitTest() : inputsChanged_(false), stateChanged_(true), oportsCached_(true) { SCIRun::Core::Logging::Log::get().setVerbose(true); } protected: bool inputsChanged_, stateChanged_, oportsCached_; }; TEST_F(ReexecuteStrategySimpleUnitTest, JustInputsChanged) { ModuleFactoryHandle mf(new HardCodedModuleFactory); ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory); AlgorithmFactoryHandle af(new HardCodedAlgorithmFactory); NetworkEditorController controller(mf, sf, ExecutionStrategyFactoryHandle(), af, ReexecuteStrategyFactoryHandle()); auto network = controller.getNetwork(); ModuleHandle send = controller.addModule("SendTestMatrix"); ModuleHandle process = controller.addModule("NeedToExecuteTester"); ModuleHandle receive = controller.addModule("ReceiveTestMatrix"); EXPECT_EQ(3, network->nmodules()); network->connect(ConnectionOutputPort(send, 0), ConnectionInputPort(process, 0)); network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(receive, 0)); EXPECT_EQ(2, network->nconnections()); SendTestMatrixModule* sendModule = dynamic_cast<SendTestMatrixModule*>(send.get()); ASSERT_TRUE(sendModule != nullptr); NeedToExecuteTester* evalModule = dynamic_cast<NeedToExecuteTester*>(process.get()); ASSERT_TRUE(evalModule != nullptr); ASSERT_FALSE(evalModule->executeCalled_); DenseMatrixHandle input = matrix1(); std::cout << "### first input has id: " << input->id() << std::endl; sendModule->get_state()->setTransientValue("MatrixToSend", input); std::cout << "RealInputsChanged, stateChanged = " << stateChanged_ << " oportsCached = " << oportsCached_ << std::endl; InputsChangedCheckerHandle realInputsChanged(new InputsChangedCheckerImpl(*evalModule)); Testing::MockStateChangedCheckerPtr mockStateChanged(new NiceMock<Testing::MockStateChangedChecker>); ON_CALL(*mockStateChanged, newStatePresent()).WillByDefault(Return(true)); Testing::MockOutputPortsCachedCheckerPtr mockOutputPortsCached(new NiceMock<Testing::MockOutputPortsCachedChecker>); ON_CALL(*mockOutputPortsCached, outputPortsCached()).WillByDefault(Return(true)); ModuleReexecutionStrategyHandle realNeedToExecuteWithPartialMocks(new DynamicReexecutionStrategy(realInputsChanged, mockStateChanged, mockOutputPortsCached)); process->setReexecutionStrategy(realNeedToExecuteWithPartialMocks); { SimpleSink::setGlobalPortCachingFlag(true); evalModule->resetFlags(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::NEGATE); bool initialNeedToExecute = realNeedToExecuteWithPartialMocks->needToExecute(); ASSERT_TRUE(initialNeedToExecute); //std::cout << "EXECUTION 1 1 1 1 1 1 1" << std::endl; send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_EQ(evalModule->expensiveComputationDone_, initialNeedToExecute); ASSERT_TRUE(evalModule->expensiveComputationDone_); ON_CALL(*mockStateChanged, newStatePresent()).WillByDefault(Return(false)); if (evalModule->expensiveComputationDone_) { //inputs haven't changed. evalModule->resetFlags(); //std::cout << "EXECUTION 2 2 2 2 2 2 2" << std::endl; send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_FALSE(realNeedToExecuteWithPartialMocks->needToExecute()); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); DenseMatrixHandle input = matrix2(); std::cout << "### second input has id: " << input->id() << std::endl; sendModule->get_state()->setTransientValue("MatrixToSend", input); //std::cout << "EXECUTION 3 3 3 3 3 3 3" << std::endl; //inputs have changed evalModule->resetFlags(); send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_TRUE(evalModule->expensiveComputationDone_); } } } TEST_F(ReexecuteStrategySimpleUnitTest, JustStateChanged) { ModuleFactoryHandle mf(new HardCodedModuleFactory); ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory); AlgorithmFactoryHandle af(new HardCodedAlgorithmFactory); NetworkEditorController controller(mf, sf, ExecutionStrategyFactoryHandle(), af, ReexecuteStrategyFactoryHandle()); auto network = controller.getNetwork(); ModuleHandle send = controller.addModule("SendTestMatrix"); ModuleHandle process = controller.addModule("NeedToExecuteTester"); ModuleHandle receive = controller.addModule("ReceiveTestMatrix"); EXPECT_EQ(3, network->nmodules()); network->connect(ConnectionOutputPort(send, 0), ConnectionInputPort(process, 0)); network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(receive, 0)); EXPECT_EQ(2, network->nconnections()); SendTestMatrixModule* sendModule = dynamic_cast<SendTestMatrixModule*>(send.get()); ASSERT_TRUE(sendModule != nullptr); NeedToExecuteTester* evalModule = dynamic_cast<NeedToExecuteTester*>(process.get()); ASSERT_TRUE(evalModule != nullptr); ASSERT_FALSE(evalModule->executeCalled_); DenseMatrixHandle input = matrix1(); sendModule->get_state()->setTransientValue("MatrixToSend", input); std::cout << "RealStateChanged, inputsChanged = " << inputsChanged_ << " oportsCached = " << oportsCached_ << std::endl; StateChangedCheckerHandle realStateChanged(new StateChangedCheckerImpl(*evalModule)); Testing::MockInputsChangedCheckerPtr mockInputsChanged(new NiceMock<Testing::MockInputsChangedChecker>); ON_CALL(*mockInputsChanged, inputsChanged()).WillByDefault(Return(inputsChanged_)); Testing::MockOutputPortsCachedCheckerPtr mockOutputPortsCached(new NiceMock<Testing::MockOutputPortsCachedChecker>); ON_CALL(*mockOutputPortsCached, outputPortsCached()).WillByDefault(Return(true)); ModuleReexecutionStrategyHandle realNeedToExecuteWithPartialMocks(new DynamicReexecutionStrategy(mockInputsChanged, realStateChanged, mockOutputPortsCached)); process->setReexecutionStrategy(realNeedToExecuteWithPartialMocks); { SimpleSink::setGlobalPortCachingFlag(true); evalModule->resetFlags(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::NEGATE); bool initialNeedToExecute = realNeedToExecuteWithPartialMocks->needToExecute(); ASSERT_TRUE(initialNeedToExecute); //std::cout << "EXECUTION 1 1 1 1 1 1 1" << std::endl; send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_EQ(evalModule->expensiveComputationDone_, initialNeedToExecute); ASSERT_TRUE(evalModule->expensiveComputationDone_); if (evalModule->expensiveComputationDone_) { //state hasn't changed. evalModule->resetFlags(); //std::cout << "EXECUTION 2 2 2 2 2 2 2" << std::endl; send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_FALSE(realNeedToExecuteWithPartialMocks->needToExecute()); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::TRANSPOSE); //std::cout << "EXECUTION 3 3 3 3 3 3 3" << std::endl; //state has changed evalModule->resetFlags(); send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_TRUE(evalModule->expensiveComputationDone_); } } } //TODO: port cache switch is not exposed, need to rework this anyway TEST_F(ReexecuteStrategySimpleUnitTest, DISABLED_JustOportsCached) { ModuleFactoryHandle mf(new HardCodedModuleFactory); ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory); AlgorithmFactoryHandle af(new HardCodedAlgorithmFactory); NetworkEditorController controller(mf, sf, ExecutionStrategyFactoryHandle(), af, ReexecuteStrategyFactoryHandle()); auto network = controller.getNetwork(); ModuleHandle send = controller.addModule("SendTestMatrix"); ModuleHandle process = controller.addModule("NeedToExecuteTester"); ModuleHandle receive = controller.addModule("ReceiveTestMatrix"); EXPECT_EQ(3, network->nmodules()); network->connect(ConnectionOutputPort(send, 0), ConnectionInputPort(process, 0)); auto oportId = network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(receive, 0)); EXPECT_EQ(2, network->nconnections()); SendTestMatrixModule* sendModule = dynamic_cast<SendTestMatrixModule*>(send.get()); ASSERT_TRUE(sendModule != nullptr); NeedToExecuteTester* evalModule = dynamic_cast<NeedToExecuteTester*>(process.get()); ASSERT_TRUE(evalModule != nullptr); ASSERT_FALSE(evalModule->executeCalled_); DenseMatrixHandle input = matrix1(); sendModule->get_state()->setTransientValue("MatrixToSend", input); //std::cout << "RealOportsCached, inputsChanged = " << inputsChanged_ << " stateChanged = " << stateChanged_ << std::endl; Testing::MockStateChangedCheckerPtr mockStateChanged(new NiceMock<Testing::MockStateChangedChecker>); ON_CALL(*mockStateChanged, newStatePresent()).WillByDefault(Return(stateChanged_)); Testing::MockInputsChangedCheckerPtr mockInputsChanged(new NiceMock<Testing::MockInputsChangedChecker>); ON_CALL(*mockInputsChanged, inputsChanged()).WillByDefault(Return(inputsChanged_)); OutputPortsCachedCheckerHandle realOportsCached(new OutputPortsCachedCheckerImpl(*evalModule)); ModuleReexecutionStrategyHandle realNeedToExecuteWithPartialMocks(new DynamicReexecutionStrategy(mockInputsChanged, mockStateChanged, realOportsCached)); process->setReexecutionStrategy(realNeedToExecuteWithPartialMocks); { SimpleSink::setGlobalPortCachingFlag(true); evalModule->resetFlags(); process->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::NEGATE); bool initialNeedToExecute = realNeedToExecuteWithPartialMocks->needToExecute(); ASSERT_TRUE(initialNeedToExecute); //std::cout << "@ @ @ @ @ @ @ @ @ @ EXECUTION 1 1 1 1 1 1 1" << std::endl; send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_EQ(evalModule->expensiveComputationDone_, initialNeedToExecute); ASSERT_TRUE(realOportsCached->outputPortsCached()); ASSERT_TRUE(evalModule->expensiveComputationDone_); evalModule->resetFlags(); //std::cout << "@ @ @ @ @ @ @ @ @ @ EXECUTION 2 2 2 2 2 2 2" << std::endl; send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_FALSE(realNeedToExecuteWithPartialMocks->needToExecute()); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); //Invalidate iport by disconnecting/reconnecting network->disconnect(oportId); EXPECT_EQ(1, network->nconnections()); network->connect(ConnectionOutputPort(process, 0), ConnectionInputPort(receive, 0)); EXPECT_EQ(2, network->nconnections()); //std::cout << "@ @ @ @ @ @ @ @ @ @ EXECUTION 3 3 3 3 3 3 3" << std::endl; evalModule->resetFlags(); EXPECT_TRUE(send->do_execute()); EXPECT_TRUE(process->do_execute()); EXPECT_TRUE(receive->do_execute()); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); //Invalidate oport by changing flag SimpleSink::setGlobalPortCachingFlag(false); //std::cout << "@ @ @ @ @ @ @ @ @ @ EXECUTION 4 4 4 4 4 4" << std::endl; evalModule->resetFlags(); send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_TRUE(evalModule->expensiveComputationDone_); } } TEST(PortCachingFunctionalTest, TestSourceSinkInputsChanged) { Log::get().setVerbose(true); ReexecuteStrategyFactoryHandle re(new DynamicReexecutionStrategyFactory(std::string())); ModuleFactoryHandle mf(new HardCodedModuleFactory); ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory); AlgorithmFactoryHandle af(new HardCodedAlgorithmFactory); NetworkEditorController controller(mf, sf, ExecutionStrategyFactoryHandle(), af, re); auto network = controller.getNetwork(); ModuleHandle send = controller.addModule("CreateLatVol"); ModuleHandle process = controller.addModule("NeedToExecuteTester"); ModuleHandle receive = controller.addModule("ReportFieldInfo"); EXPECT_EQ(3, network->nmodules()); network->connect(ConnectionOutputPort(send, 0), ConnectionInputPort(process, 1)); EXPECT_EQ(1, network->nconnections()); network->connect(ConnectionOutputPort(process, 1), ConnectionInputPort(receive, 0)); EXPECT_EQ(2, network->nconnections()); NeedToExecuteTester* evalModule = dynamic_cast<NeedToExecuteTester*>(process.get()); ASSERT_TRUE(evalModule != nullptr); EXPECT_FALSE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); std::cout << "@ @ @ @ @ @ @ @ @ @ EXECUTION 1 1 1 1 1 1" << std::endl; send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_TRUE(evalModule->expensiveComputationDone_); evalModule->resetFlags(); std::cout << "@ @ @ @ @ @ @ @ @ @ EXECUTION 2 2 2 2 2" << std::endl; send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); evalModule->resetFlags(); std::cout << "@ @ @ @ @ @ @ @ @ @ EXECUTION 3 3 3 3 3 3 3" << std::endl; send->do_execute(); process->do_execute(); receive->do_execute(); EXPECT_TRUE(evalModule->executeCalled_); EXPECT_FALSE(evalModule->expensiveComputationDone_); }
[ "dwhite@sci.utah.edu" ]
dwhite@sci.utah.edu
705fc283c6839a68613a8bcde5de473a7acf1eda
e1abbd2f8072f8f8bf8f4582b10ca1d025b13ad9
/Assets/StreamingAssets/Audio/GeneratedSoundBanks/Wwise_IDs.h
323186e748c4b79335bdd4e9c8357c6073e2809c
[]
no_license
aoleynikov678/ao-wwise-pooler
f1985a7b20c5b52de885c21cea733fbeb70dcdb7
2565385f083a3327ad87a7e4f2b00d00a2173c7b
refs/heads/master
2022-09-13T22:30:36.145276
2020-05-31T18:10:52
2020-05-31T18:10:52
268,312,817
1
0
null
null
null
null
UTF-8
C++
false
false
1,036
h
///////////////////////////////////////////////////////////////////////////////////////////////////// // // Audiokinetic Wwise generated include file. Do not edit. // ///////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __WWISE_IDS_H__ #define __WWISE_IDS_H__ #include <AK/SoundEngine/Common/AkTypes.h> namespace AK { namespace EVENTS { static const AkUniqueID AMBIENT = 77978275U; static const AkUniqueID KICKS = 138295086U; } // namespace EVENTS namespace BANKS { static const AkUniqueID INIT = 1355168291U; static const AkUniqueID MASTER = 4056684167U; } // namespace BANKS namespace BUSSES { static const AkUniqueID MASTER_AUDIO_BUS = 3803692087U; } // namespace BUSSES namespace AUDIO_DEVICES { static const AkUniqueID NO_OUTPUT = 2317455096U; static const AkUniqueID SYSTEM = 3859886410U; } // namespace AUDIO_DEVICES }// namespace AK #endif // __WWISE_IDS_H__
[ "a.o.oleynikov@gmail.com" ]
a.o.oleynikov@gmail.com
c488d361e3057bdf91cad9d17468a5723407e907
1e63895a52b4825ebde5ceecc69fe5ea28481cca
/01-introduction-to-c++/modules/004-arrays/code-part-4/004-Remove-Character.cpp
05ebdd78ce9715e3c387ca7af2c18dbbf6655214
[]
no_license
NikitaLandge51/codig-ninja-dsa-learning
f970bf12209b433aa329712031579fbb0f02a319
48f18a5fb8afd9a8b448a7e3e30f417440c01487
refs/heads/main
2023-07-01T10:50:52.744951
2021-07-23T06:01:19
2021-07-23T06:01:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,543
cpp
#include<iostream> using namespace std; /** * Remove character * - For a given a string(str) and a character X, write a function to remove * all the occurrences of X from the given string. * - The input string will remain unchanged if the given character(X) doesn't * exist in the input string. * * Input Format: * The first line of input contains a string without any leading and trailing spaces. * The second line of input contains a character(X) without any leading and trailing spaces. * Output Format: * The only line of output prints the updated string. * Note: * You are not required to print anything explicitly. It has already been taken care of. * * Constraints: * 0 <= N <= 10^6 * Where N is the length of the input string. * * Time Limit: 1 second * * Sample Input 1: * aabccbaa * a * Sample Output 1: * bccb * * Sample Input 2: * xxyyzxx * y * Sample Output 2: * xxzxx */ void removeAllOccurrencesOfChar(char input[], char c) { int i=0, j=0; while(input[j] != '\0'){ while(input[j] == c){ j++; } if(input[j] != '\0'){ int temp = input[i]; input[i] = input[j]; input[j] = temp; i++; j++; } } input[i] = '\0'; } int main(){ int size = 1e6; char str[size]; cin.getline(str, size); char c; cin >> c; removeAllOccurrencesOfChar(str, c); cout << str; }
[ "tarun.verma151@gmail.com" ]
tarun.verma151@gmail.com
634dfff0447c906bd947cd23967994ca3dd1d5f8
71f32ae68e26c4c0a7b4e52ea8220af608db8f08
/wowClassicXPCalculator/professionsModule.h
24ce24fbf9b821ed789a8a9d203531c94e22b1cd
[]
no_license
kapa123123/wowClassic-LevelingCalculator
0b2ae291ca59c7af6ccc7ba2c1192994be391cf4
50a6f148e27f085a0307b54e1f181b5d07335c85
refs/heads/master
2023-03-29T10:52:45.661874
2021-03-31T14:40:49
2021-03-31T14:40:49
352,649,111
0
0
null
null
null
null
UTF-8
C++
false
false
267
h
#pragma once class professions { public: int profXP; //Current XP int highestXP; //Needed XP int xpDatabase; //storing values to lvl char chosenProf; //Name the profession void pInput(); void pCalculation(); }; class p_Herb { public: void library(); };
[ "s5118418@bournemouth.ac.uk" ]
s5118418@bournemouth.ac.uk
130b59867246d681914fef07188ce04ab238d769
f6c49e0b0d481a43164c44818b1bce9f87f1bbca
/base/VuoComposition.hh
4993ed7fa7d9a582c43f4d907feff880d446aff5
[]
no_license
pooyaniazi/vuo
1425a968f63544347dc1661597a7957aac19ff38
cccc6057463c978f0bc355c00ca9752659198b70
refs/heads/master
2021-06-18T06:32:26.047326
2017-07-02T00:45:33
2017-07-02T00:45:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,197
hh
/** * @file * VuoComposition interface. * * @copyright Copyright © 2012–2016 Kosada Incorporated. * This interface description may be modified and distributed under the terms of the GNU Lesser General Public License (LGPL) version 2 or later. * For more information, see http://vuo.org/license. */ #ifndef VUOCOMPOSITION_HH #define VUOCOMPOSITION_HH #include "VuoBase.hh" class VuoCompilerComposition; class VuoRendererComposition; class VuoCable; class VuoNode; class VuoPort; class VuoPublishedPort; /** * A collection of nodes and the cables connecting them. */ class VuoComposition : public VuoBase<VuoCompilerComposition,VuoRendererComposition> { public: VuoComposition(void); void setName(string name); string getName(void); void setDirectory(string directory); string getDirectory(void); void setDescription(string description); string getDescription(void); void setCopyright(string copyright); string getCopyright(void); void addNode(VuoNode *node); void removeNode(VuoNode *node); void replaceNode(VuoNode *oldNode, VuoNode *newNode); set<VuoNode *> getNodes(void); void addCable(VuoCable *cable); void removeCable(VuoCable *cable); set<VuoCable *> getCables(void); void addPublishedInputPort(VuoPublishedPort *port, int index); void addPublishedOutputPort(VuoPublishedPort *port, int index); void removePublishedInputPort(int index); void removePublishedOutputPort(int index); vector<VuoPublishedPort *> getPublishedInputPorts(void); vector<VuoPublishedPort *> getPublishedOutputPorts(void); VuoPublishedPort * getPublishedInputPortWithName(string name); VuoPublishedPort * getPublishedOutputPortWithName(string name); int getIndexOfPublishedPort(VuoPublishedPort *port, bool isInput); static void parseHeader(const string &compositionAsString, string &name, string &description, string &copyright); private: string name; string directory; string description; string copyright; set<VuoNode *> nodes; set<VuoCable *> cables; vector<VuoPublishedPort *> publishedInputPorts; vector<VuoPublishedPort *> publishedOutputPorts; VuoPublishedPort * getPublishedPortWithName(string name, bool isInput); }; #endif // VUOCOMPOSITION_HH
[ "info@vuo.org" ]
info@vuo.org
41ffd90d5e9f8200676918c343ef6532f93d000d
f88d8da07e0b3f15d53deb673c552ac0588b67fc
/workspace/sdl_game/src/sandbox/assets/resources/raw/wood/RawWood.h
a246480371290181f035fdf40ce10302965efa93
[]
no_license
StevenJHulshof/sdl_sdk
cf285608c74471d2aa484b4116465816fee7e43c
5eb8c2c24ad314f9b62bc1e5f99058f015481f20
refs/heads/master
2021-08-30T11:05:09.973950
2017-12-13T22:14:29
2017-12-13T22:14:29
107,877,339
0
0
null
null
null
null
UTF-8
C++
false
false
215
h
#pragma once #include "RawResource.h" class RawWood: public RawResource { public: RawWood(int xPos, int yPos); virtual ~RawWood(); virtual void renderGraphics(); }; extern std::vector<RawWood*> gRawWoodPool;
[ "steven.j.hulshof@gmail.com" ]
steven.j.hulshof@gmail.com
d78e70b057fd7591dd85fb637243c02c43d67d9d
43a9f64427158c5bec8e9ce60233ba91b8c55f3e
/samples/RoundWindow/src/RoundApp.h
51a833cf6408ccb0ee025f8ab7d146ebbd9e5cdc
[]
no_license
CCCCCCCCZ/Win32xx
7e8647b74eaca47ef80cadd76d68dc036dabe709
2ef27b55e05931ebabf931f133387bc046f888dc
refs/heads/master
2020-06-07T13:29:41.006512
2019-06-22T07:33:53
2019-06-22T07:33:53
193,032,614
0
1
null
null
null
null
UTF-8
C++
false
false
481
h
///////////////////////////////////////// // RoundApp.h #ifndef ROUNDAPP_H #define ROUNDAPP_H #include "View.h" // Declaration of the CRoundApp class class CRoundApp : public CWinApp { public: CRoundApp(); virtual ~CRoundApp() {} virtual BOOL InitInstance(); CView& GetView() { return m_view; } private: CView m_view; }; // returns a pointer to the CRoundApp object inline CRoundApp& GetSimpleApp() { return static_cast<CRoundApp&>(GetApp()); } #endif
[ "czx_1991@qq.com" ]
czx_1991@qq.com
041acf0ed78b8727f043605fb0ac91cd08ea4755
ef66e297a49d04098d98a711ca3fda7b8a9a657c
/LeetCode/27-Remove Elements/solution.cpp
37c7c9f1e2240a1b82915ceaeb2a1216f86f867d
[]
no_license
breezy1812/MyCodes
34940357954dad35ddcf39aa6c9bc9e5cd1748eb
9e3d117d17025b3b587c5a80638cb8b3de754195
refs/heads/master
2020-07-19T13:36:05.270908
2018-12-15T08:54:30
2018-12-15T08:54:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
506
cpp
// Author: David // Email: youchen.du@gmail.com // Created: 2017-04-02 09:39 // Last modified: 2017-04-02 09:39 // Filename: solution.cpp // Description: class Solution { public: int removeElement(vector<int>& nums, int val) { int size = nums.size(); int removed = 0; for(int i = 0; i < size; i++) { if(nums[i] == val) removed++; else nums[i - removed] = nums[i]; } return size - removed; } };
[ "youchen.du@gmail.com" ]
youchen.du@gmail.com
5fa164c8d1dfcee1e321a53fee18c2fe127bd632
0851cf9dee9699a3296276705b45993e55c51592
/test/asan/TestCases/use-after-scope-goto.cc
351cbe995efb2070846203b6d1ee34882ae1f00c
[ "NCSA", "MIT", "LLVM-exception", "Apache-2.0" ]
permissive
apple/swift-compiler-rt
5e67c4ad59784faaa7a34b7e4824b8779e55ca48
f074ee37e8be92799cbc32bf7a8e12a3d1d4719f
refs/heads/stable
2023-03-16T10:46:27.831959
2019-10-25T22:47:20
2019-10-25T22:47:20
50,524,437
122
76
Apache-2.0
2019-10-25T22:47:21
2016-01-27T17:23:47
C
UTF-8
C++
false
false
874
cc
// RUN: %clangxx_asan -O0 -fsanitize-address-use-after-scope %s -o %t && %run %t // Function jumps over variable initialization making lifetime analysis // ambiguous. Asan should ignore such variable and program must not fail. #include <stdlib.h> int *ptr; void f1(int cond) { if (cond) goto label; int tmp; label: ptr = &tmp; *ptr = 5; } void f2(int cond) { switch (cond) { case 1: { ++cond; int tmp; ptr = &tmp; exit(0); case 2: ptr = &tmp; *ptr = 5; exit(0); } } } void f3(int cond) { { int tmp; goto l2; l1: ptr = &tmp; *ptr = 5; exit(0); } l2: goto l1; } void use(int *x) { static int c = 10; if (--c == 0) exit(0); (*x)++; } void f4() { { int x; l2: use(&x); goto l1; } l1: goto l2; } int main() { f1(1); f2(1); f3(1); f4(); return 0; }
[ "vitalybuka@google.com" ]
vitalybuka@google.com
16fddb286f1dad6a395b6bb0a2eae6427f71c5c9
182adfdfa907d3efc0395e293dcdbc46898d88eb
/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Collections_Generic_Dictionary_2_V2695984647.h
f8099fab14cdcfc3bbeb02e8604ed878733f3986
[]
no_license
Launchable/1.1.3New
d1962418cd7fa184300c62ebfd377630a39bd785
625374fae90e8339cec0007d4d7202328bfa03d9
refs/heads/master
2021-01-19T07:40:29.930695
2017-09-15T17:20:45
2017-09-15T17:20:45
100,642,705
0
0
null
null
null
null
UTF-8
C++
false
false
1,393
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object2689449295.h" // System.Collections.Generic.Dictionary`2<System.String,UnityEditor.XCodeEditor.PBXFrameworksBuildPhase> struct Dictionary_2_t3992924804; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/ValueCollection<System.String,UnityEditor.XCodeEditor.PBXFrameworksBuildPhase> struct ValueCollection_t2695984647 : public Il2CppObject { public: // System.Collections.Generic.Dictionary`2<TKey,TValue> System.Collections.Generic.Dictionary`2/ValueCollection::dictionary Dictionary_2_t3992924804 * ___dictionary_0; public: inline static int32_t get_offset_of_dictionary_0() { return static_cast<int32_t>(offsetof(ValueCollection_t2695984647, ___dictionary_0)); } inline Dictionary_2_t3992924804 * get_dictionary_0() const { return ___dictionary_0; } inline Dictionary_2_t3992924804 ** get_address_of_dictionary_0() { return &___dictionary_0; } inline void set_dictionary_0(Dictionary_2_t3992924804 * value) { ___dictionary_0 = value; Il2CppCodeGenWriteBarrier(&___dictionary_0, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "zk.launchable@gmail.com" ]
zk.launchable@gmail.com
38f08296f69201c836e37c65a9e5f33d09d68cbd
a083190746faad0ef619d3513649419aa973f218
/test/irradiance/gx/gx_view_port.h
6c085d2899e8f058e8e6ab5e16ccea540727db0d
[]
no_license
kingofthebongo2008/vitosha
1a29a7c832701d1b081c9c2daf51ef027ca9df99
f681c26d1c5d416a6a427fed56bfec1240868da2
refs/heads/master
2021-01-19T07:56:39.642285
2018-06-12T14:43:25
2018-06-12T14:43:25
2,626,725
1
2
null
null
null
null
UTF-8
C++
false
false
2,918
h
#ifndef __RENDER_VIEW_PORT_H__ #define __RENDER_VIEW_PORT_H__ #include <cstdint> #include "math/math_graphics.h" namespace gx { class view_port { public: view_port() : m_left(0), m_top(0), m_width(320), m_height(240), m_min_z(0.0f), m_max_z(1.0f) { } view_port( uint32_t left, uint32_t top, uint32_t width, uint32_t height, float min_z, float max_z) : m_left(static_cast<uint16_t> (left) ) , m_top(static_cast<uint16_t> (top) ) , m_width(static_cast<uint16_t> (width) ) , m_height(static_cast<uint16_t> (height) ) , m_min_z(min_z) , m_max_z(max_z) { } view_port( uint32_t left, uint32_t top, uint32_t width, uint32_t height) : m_left(static_cast<uint16_t> (left) ) , m_top(static_cast<uint16_t> (top) ) , m_width(static_cast<uint16_t> (width) ) , m_height(static_cast<uint16_t> (height) ) , m_min_z(0.0f) , m_max_z(1.0f) { } inline uint32_t get_height() const { return m_height; } inline uint32_t get_width() const { return m_width; } inline uint32_t get_left() const { return m_left; } inline uint32_t get_top() const { return m_top; } inline float get_min_z() const { return m_min_z; } inline float get_max_z() const { return m_max_z; } inline void set_dimensions(uint32_t width, uint32_t height) { m_width = static_cast<uint16_t>(width); m_height = static_cast<uint16_t>(height); } inline void set_offset(uint32_t left, uint32_t top) { m_left = static_cast<uint16_t>(left); m_top = static_cast<uint16_t>(top); } inline void set_depth(float min_z, float max_z) { m_min_z = min_z; m_max_z = max_z; } operator math::view_port() const { const math::view_port v = { static_cast<float> ( m_left ), static_cast<float> ( m_top ), static_cast<float> ( m_left + m_width ), static_cast<float> ( m_top + m_height ), m_min_z, m_max_z }; return v; } private: float m_min_z; float m_max_z; uint16_t m_left; uint16_t m_top; uint16_t m_width; uint16_t m_height; }; } #endif
[ "stefan.dyulgerov@gmail.com" ]
stefan.dyulgerov@gmail.com
795119ddb27aa67042bc2fff2a18fce9f0eff961
e1a6af52111a1dfa0ae053183e2b3d0180d1e9ec
/src/interfaces/node.h
d8ff0907a110c3d94a194b58ab4e6e17ee1fec99
[ "MIT" ]
permissive
UFO-ETL/ufo
df392b66b3f528a3442c2a26304e061fb6e1a631
e85dde0c8b12c1bf3357003afb77ea85b1476d6b
refs/heads/main
2023-03-12T04:27:35.910420
2021-03-05T06:54:21
2021-03-05T06:54:21
344,399,934
0
0
null
null
null
null
UTF-8
C++
false
false
7,642
h
// Copyright (c) 2018-2020 The UFO Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef UFO_INTERFACES_NODE_H #define UFO_INTERFACES_NODE_H #include <amount.h> // For CAmount #include <net.h> // For CConnman::NumConnections #include <net_types.h> // For banmap_t #include <netaddress.h> // For Network #include <support/allocators/secure.h> // For SecureString #include <util/translation.h> #include <functional> #include <memory> #include <stddef.h> #include <stdint.h> #include <string> #include <tuple> #include <vector> class BanMan; class CCoinControl; class CFeeRate; class CNodeStats; class Coin; class RPCTimerInterface; class UniValue; class proxyType; enum class SynchronizationState; struct CNodeStateStats; struct NodeContext; struct bilingual_str; namespace interfaces { class Handler; class WalletClient; struct BlockTip; //! Block and header tip information struct BlockAndHeaderTipInfo { int block_height; int64_t block_time; int header_height; int64_t header_time; double verification_progress; }; //! Top-level interface for a UFO node (UFOd process). class Node { public: virtual ~Node() {} //! Init logging. virtual void initLogging() = 0; //! Init parameter interaction. virtual void initParameterInteraction() = 0; //! Get warnings. virtual bilingual_str getWarnings() = 0; // Get log flags. virtual uint32_t getLogCategories() = 0; //! Initialize app dependencies. virtual bool baseInitialize() = 0; //! Start node. virtual bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info = nullptr) = 0; //! Stop node. virtual void appShutdown() = 0; //! Start shutdown. virtual void startShutdown() = 0; //! Return whether shutdown was requested. virtual bool shutdownRequested() = 0; //! Map port. virtual void mapPort(bool use_upnp, bool use_natpmp) = 0; //! Get proxy. virtual bool getProxy(Network net, proxyType& proxy_info) = 0; //! Get number of connections. virtual size_t getNodeCount(CConnman::NumConnections flags) = 0; //! Get stats for connected nodes. using NodesStats = std::vector<std::tuple<CNodeStats, bool, CNodeStateStats>>; virtual bool getNodesStats(NodesStats& stats) = 0; //! Get ban map entries. virtual bool getBanned(banmap_t& banmap) = 0; //! Ban node. virtual bool ban(const CNetAddr& net_addr, int64_t ban_time_offset) = 0; //! Unban node. virtual bool unban(const CSubNet& ip) = 0; //! Disconnect node by address. virtual bool disconnectByAddress(const CNetAddr& net_addr) = 0; //! Disconnect node by id. virtual bool disconnectById(NodeId id) = 0; //! Get total bytes recv. virtual int64_t getTotalBytesRecv() = 0; //! Get total bytes sent. virtual int64_t getTotalBytesSent() = 0; //! Get mempool size. virtual size_t getMempoolSize() = 0; //! Get mempool dynamic usage. virtual size_t getMempoolDynamicUsage() = 0; //! Get header tip height and time. virtual bool getHeaderTip(int& height, int64_t& block_time) = 0; //! Get num blocks. virtual int getNumBlocks() = 0; //! Get best block hash. virtual uint256 getBestBlockHash() = 0; //! Get last block time. virtual int64_t getLastBlockTime() = 0; //! Get verification progress. virtual double getVerificationProgress() = 0; //! Is initial block download. virtual bool isInitialBlockDownload() = 0; //! Get reindex. virtual bool getReindex() = 0; //! Get importing. virtual bool getImporting() = 0; //! Set network active. virtual void setNetworkActive(bool active) = 0; //! Get network active. virtual bool getNetworkActive() = 0; //! Get dust relay fee. virtual CFeeRate getDustRelayFee() = 0; //! Execute rpc command. virtual UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) = 0; //! List rpc commands. virtual std::vector<std::string> listRpcCommands() = 0; //! Set RPC timer interface if unset. virtual void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) = 0; //! Unset RPC timer interface. virtual void rpcUnsetTimerInterface(RPCTimerInterface* iface) = 0; //! Get unspent outputs associated with a transaction. virtual bool getUnspentOutput(const COutPoint& output, Coin& coin) = 0; //! Get wallet client. virtual WalletClient& walletClient() = 0; //! Register handler for init messages. using InitMessageFn = std::function<void(const std::string& message)>; virtual std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) = 0; //! Register handler for message box messages. using MessageBoxFn = std::function<bool(const bilingual_str& message, const std::string& caption, unsigned int style)>; virtual std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) = 0; //! Register handler for question messages. using QuestionFn = std::function<bool(const bilingual_str& message, const std::string& non_interactive_message, const std::string& caption, unsigned int style)>; virtual std::unique_ptr<Handler> handleQuestion(QuestionFn fn) = 0; //! Register handler for progress messages. using ShowProgressFn = std::function<void(const std::string& title, int progress, bool resume_possible)>; virtual std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) = 0; //! Register handler for number of connections changed messages. using NotifyNumConnectionsChangedFn = std::function<void(int new_num_connections)>; virtual std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) = 0; //! Register handler for network active messages. using NotifyNetworkActiveChangedFn = std::function<void(bool network_active)>; virtual std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) = 0; //! Register handler for notify alert messages. using NotifyAlertChangedFn = std::function<void()>; virtual std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) = 0; //! Register handler for ban list messages. using BannedListChangedFn = std::function<void()>; virtual std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) = 0; //! Register handler for block tip messages. using NotifyBlockTipFn = std::function<void(SynchronizationState, interfaces::BlockTip tip, double verification_progress)>; virtual std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) = 0; //! Register handler for header tip messages. using NotifyHeaderTipFn = std::function<void(SynchronizationState, interfaces::BlockTip tip, double verification_progress)>; virtual std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) = 0; //! Get and set internal node context. Useful for testing, but not //! accessible across processes. virtual NodeContext* context() { return nullptr; } virtual void setContext(NodeContext* context) { } }; //! Return implementation of Node interface. std::unique_ptr<Node> MakeNode(NodeContext* context = nullptr); //! Block tip (could be a header or not, depends on the subscribed signal). struct BlockTip { int block_height; int64_t block_time; uint256 block_hash; }; } // namespace interfaces #endif // UFO_INTERFACES_NODE_H
[ "xiaka53@vip.qq.com" ]
xiaka53@vip.qq.com
a299d8802f9b71ff9da158f5f3f03bc328448ec4
252cc6e1a46360c4d83d81552c4f21c3aa22681e
/module5/Project 3/SilverClient.h
13bff43936f07515801cb184d432019bb8d2d831
[]
no_license
cjglo/cs052
20c516426accd3a5e43829067f8793e62f57ce28
3f26cace59d498385e098b16397e86ac8cd45980
refs/heads/master
2022-12-11T14:53:32.045720
2020-08-26T22:56:50
2020-08-26T22:56:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,744
h
/* * SilverClient.h * * COSC 052 2020 * Project 3 * * Due on: August 2nd * Author: Christopher Gallo * * * In accordance with the class policies and Georgetown's * Honor Code, I certify that, with the exception of the * class resources and those items noted below, I have neither * given nor received any assistance on this project. * * References not otherwise commented within the program source code. * Note that you should not mention any help from the TAs, the professor, * or any code taken from the class textbooks. */ #ifndef SILVERCLIENT_H #define SILVERCLIENT_H #include "Client.h" /// The SilverClient is the first version of Client /// /// It has only two attributes: Name and Tenure /// getPoints() and getTier() made so that compiler does not through error with sort method /// Although the sort method would never call those functions, as the type is determined before /// that code meaning no SilverClient will be asked for Tier or Points. /// /// Relational Operator is built as a method, rather then a friend class SilverClient:public Client { public: /** * Main Constructor * \param tenure is passed to the Client constructor * \param name is passed to the Client constrcutor */ SilverClient(short tenure, string name): Client(tenure, name) { } /** * Get accessor used to determine type for relational operator * \return is either 0 or 1 or 2, depending on the Client derived class */ char getType() { return '0'; } /** * Stream to HTML, allows SilverClient to be formattedf into an html row * \param out& is the cout stream object */ ostream& htmlToStream(ostream &out); /** * Relational Operator * \param Client* is passed from the ClientList in the sort function to this operator */ virtual bool operator>(Client*); /** * As mentioned in the Client base class comments, the compiler with throw an error in Project 3 because * we call these methods from Client pointers (unlike Project2) so to prevent the error, all derived versions * of the class must have a copy of all methods, even though Gold will never get asked to getPoints() * \return is just 0, as it has no point attribute */ float getPoints() {return 0;} /** * Similarly to getPoints(), SilverClient needs a getTier() despite never having it be used. The compiler with throw an error in Project 3 because * we call these methods from Client pointers (unlike Project2) so to prevent the error, all derived versions * of the class must have a copy of all methods. * \return is the null character as SilverClient has no Tier attribute */ char getTier() {return '\0'; } }; #endif
[ "cjg100@georgetown.edu" ]
cjg100@georgetown.edu
474481958e31ebba887f44759be85f2645ce7891
84cb52133080521be2f524fbd2e51865fc9dd207
/src/headers/sprite.h
43761dde42c58d8859627458faf25b09aea7a544
[]
no_license
jcfausto/cavestory-remaking
ed383f22d68290f19f85b396ba9cf33851d1002c
f9cc5f4f6021458723b3e31ec0c641f55dceaa3b
refs/heads/master
2021-06-18T20:25:22.045121
2017-06-24T10:12:18
2017-06-24T10:12:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,092
h
/* * sprite.h * * Created on: 8 de jun de 2017 * Author: jcfausto * * Base class for sprites */ #ifndef HEADERS_SPRITE_H_ #define HEADERS_SPRITE_H_ #include <SDL2/SDL.h> #include <string> #include "rectangles.h" #include "globals.h" class Graphics; class Sprite { public: Sprite(); Sprite(Graphics &graphics, const std::string &filePath, int sourceX, int sourceY, int width, int height, float posX, float posY); virtual ~Sprite(); virtual void update(); void draw(Graphics &graphics, int x, int y); const Rectangle getBoundingBox() const; const sides::Side getCollisionSide(Rectangle &other) const; const inline float getX() const { return this->x_; } const inline float getY() const { return this->y_; } void setSourceRectangleX(int value); void setSourceRectangleY(int value); void setSourceRectangleW(int value); void setSourceRectangleH(int valie); protected: SDL_Rect sourceRectangle_; SDL_Texture* spriteSheet_; Rectangle boundingBox_; //Rectangle that goes around the entire sprite float x_, y_; private: }; #endif /* HEADERS_SPRITE_H_ */
[ "jcfausto@gmail.com" ]
jcfausto@gmail.com
10981450e6c086415cb960dcde04acb196211e5c
921c689451ff3b6e472cc6ae6a34774c4f57e68b
/llvm-2.8/tools/clang/test/SemaTemplate/instantiate-init.cpp
e292aa3c5f768d397dc5062304bfacc486853459
[ "NCSA" ]
permissive
xpic-toolchain/xpic_toolchain
36cae905bbf675d26481bee19b420283eff90a79
9e6d4276cc8145a934c31b0d3292a382fc2e5e92
refs/heads/master
2021-01-21T04:37:18.963215
2016-05-19T12:34:11
2016-05-19T12:34:11
29,474,690
4
0
null
null
null
null
UTF-8
C++
false
false
1,139
cpp
// RUN: %clang_cc1 -fsyntax-only -verify %s struct X0 { // expected-note 4{{candidate}} X0(int*, float*); // expected-note 4{{candidate}} }; template<typename T, typename U> X0 f0(T t, U u) { X0 x0(t, u); // expected-error{{no matching}} return X0(t, u); // expected-error{{no matching}} } void test_f0(int *ip, float *fp, double *dp) { f0(ip, fp); f0(ip, dp); // expected-note{{instantiation}} } template<typename Ret, typename T, typename U> Ret f1(Ret *retty, T t, U u) { Ret r0(t, u); // expected-error{{no matching}} return Ret(t, u); // expected-error{{no matching}} } void test_f1(X0 *x0, int *ip, float *fp, double *dp) { f1(x0, ip, fp); f1(x0, ip, dp); // expected-note{{instantiation}} } namespace PR6457 { template <typename T> struct X { explicit X(T* p = 0) { }; }; template <typename T> struct Y { Y(int, const T& x); }; struct A { }; template <typename T> struct B { B() : y(0, X<A>()) { } Y<X<A> > y; }; B<int> b; } namespace PR6657 { struct X { X (int, int) { } }; template <typename> void f0() { X x = X(0, 0); } void f1() { f0<int>(); } }
[ "helmutmanck@5227c84a-046b-4545-895e-fca5577db8e1" ]
helmutmanck@5227c84a-046b-4545-895e-fca5577db8e1
9bf01449f795599b7b11cc44f7c91b2afefbde74
dbfafcd7f4bce21529d8ddfc1c6e7c565fd594b3
/inference_tf.h
5aab58c61826452079b475db817cbf231c7ed0ce
[ "MIT" ]
permissive
fierval/fast_od
c877670f34276ff709a36602aa0be6e90c85e13d
5ae196951058b698ef66ba5bf9a04b8fbbed8698
refs/heads/master
2020-04-24T00:13:43.505747
2019-05-21T16:34:49
2019-05-21T16:34:49
171,560,009
8
1
null
null
null
null
UTF-8
C++
false
false
1,152
h
#pragma once #include "inference_base.h" using namespace std; using tensorflow::CallableOptions; using tensorflow::Tensor; using tensorflow::Session; class InferenceTensorflow : public InferenceBase { private: const string inputLayer = "image_tensor:0"; const vector<string> outputLayer = {"detection_boxes:0", "detection_scores:0", "detection_classes:0", "num_detections:0"}; CallableOptions opts; std::unique_ptr<tensorflow::Session> session; Session::CallableHandle feed_gpu_fetch_cpu; // Allocate input tensor on the gpu Tensor inputTensor; vector<Tensor> outputs; protected: int ReadGraph() override; int doInference(cv::cuda::GpuMat& d_frame) override; void visualize(cv::cuda::GpuMat &d_frame, double) override; public: InferenceTensorflow(const string &labelsFile, const string &graphFile, double threshScore = 0.5, double threshIOU = 0.8, int dbg = 0) : InferenceBase(labelsFile, graphFile, threshScore, threshIOU, dbg) , opts() { } int Init(string videoStream) override; virtual ~InferenceTensorflow() { session->ReleaseCallable(feed_gpu_fetch_cpu);} };
[ "fierval@gmail.com" ]
fierval@gmail.com
f60be588729054dd3cc78c4868a316f214bcb4f9
fa4ec990009e981b14ceec914fef08285f3ac4fd
/PREFXGD.cpp
951ddc5e6fdb1eee374167f2630af655406207d2
[]
no_license
writing-codes/Cpp-14
a77b59eeb99ef424dde6080ca1470671d8ebb9c5
07db7f62d2e477353c2434e16211ac54d0609eb9
refs/heads/master
2021-08-06T08:05:53.517249
2020-06-08T09:38:31
2020-06-08T09:38:31
186,038,503
1
0
null
null
null
null
UTF-8
C++
false
false
585
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main(){ ll t; cin>>t; while(t--){ string s; cin>>s; ll k,x; cin>>k>>x; map<char,ll> m; m['g']=1; m['o']=2; m['d']=1; for(int i=0;i<s.size();i++) { m[s[i]]++; } int count = 0; vector <int> v; map<char,ll>::iterator itr; for(itr=m.begin();itr!=m.end();itr++){ if(itr->second<=x) count++; else v.push_back(itr->second-x); } sort(v.begin(),v.end()); ll i=0; while(i<v.size()&&k>0){ k-=v[i]; if(k>=0) count++; } cout<<count<<endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
a36cdc7d0bd775830d31a7ce28b73f3bb2a3b0e2
5ef21290f945f6a41cfc56c7a709cd5b0b1e1bd2
/src/mdp/ssp_lao_star_cpu.cpp
720aa26ad2e46302c3dfb8d79714f11a38d6d5c8
[ "MIT" ]
permissive
peaceful-lukas/nova
61227e8cfc13c36b875aa48f5f8e27557b3bdd38
bfac486c83e4653610b7c1e309f20f0b89193676
refs/heads/master
2021-01-21T09:11:21.014105
2015-11-03T01:32:38
2015-11-03T01:32:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,692
cpp
/** * The MIT License (MIT) * * Copyright (c) 2015 Kyle Hollins Wray, University of Massachusetts * * 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 "ssp_lao_star_cpu.h" #include "error_codes.h" #include <stdio.h> #include <cstring> #include <cmath> #include <algorithm> #include <math.h> // This is determined by hardware, so what is below is a 'safe' guess. If this is // off, the program might return 'nan' or 'inf'. #define FLT_MAX 1e+35 void ssp_lao_star_bellman_update_state_cpu(unsigned int n, unsigned int ns, unsigned int m, const int *S, const float *T, const float *R, const float *V, unsigned int ne, const int *expanded, unsigned int s, float *VPrime, unsigned int *pi) { VPrime[s] = FLT_MAX; // Compute min_{a in A} Q(s, a). Recall, we are dealing with rewards R as positive costs. for (int a = 0; a < m; a++) { // Compute Q(s, a) for this action. float Qsa = R[s * m + a]; for (int i = 0; i < ns; i++) { int sp = S[s * m * ns + a * ns + i]; if (sp < 0) { break; } // Note: V is marked with a negative based on visitation. If it had not been // visited, then it means it is using the heuristic value. Qsa += T[s * m * ns + a * ns + i] * std::fabs(V[sp]); } if (a == 0 || Qsa < VPrime[s]) { VPrime[s] = Qsa; pi[s] = a; } } } void ssp_lao_star_reset_newly_expanded_states(unsigned int n, unsigned int m, unsigned int *pi) { for (unsigned int s = 0; s < n; s++) { pi[s] = m; } } void ssp_lao_star_reset_visited(unsigned int n, float *V, float *VPrime) { for (unsigned int s = 0; s < n; s++) { if (!std::signbit(V[s])) { V[s] = -V[s]; } if (!std::signbit(VPrime[s])) { VPrime[s] = -VPrime[s]; } } } void ssp_lao_star_bellman_residual_cpu(unsigned int ne, int *expanded, float epsilon, float *V, float *VPrime, bool *converged) { float residual = 0.0f; for (unsigned int i = 0; i < ne; i++) { int s = expanded[i]; if (s < 0) { break; } float sResidual = std::fabs(std::fabs(V[s]) - std::fabs(VPrime[s])); residual = std::max(residual, sResidual); } if (residual < epsilon) { *converged = true; } else { *converged = false; } } int ssp_lao_star_expand_cpu(MDP *mdp, unsigned int *numNewlyExpandedStates) { *numNewlyExpandedStates = 0; // First, reset the visited states. ssp_lao_star_reset_visited(mdp->n, mdp->V, mdp->VPrime); // Create a fringe state list (stack) variable, with just state s0. unsigned int nf = 1; unsigned int *fringe = new unsigned int[mdp->n]; fringe[0] = mdp->s0; // Iterate until there are no more elements on the fringe. while (nf != 0) { // Pop the last element off the stack. unsigned int s = fringe[nf - 1]; nf--; // Check if this state has been visited. If so, continue. if (!std::signbit(mdp->V[s]) || !std::signbit(mdp->VPrime[s])) { continue; } // Mark it as visited either way. mdp->V[s] = fabs(mdp->V[s]); mdp->VPrime[s] = fabs(mdp->VPrime[s]); // Check if this state is a goal. If so, continue. bool isGoal = false; for (unsigned int i = 0; i < mdp->ng; i++) { if (s == mdp->goals[i]) { isGoal = true; } } if (isGoal) { continue; } // Only increment this if we truly have never seen this state before over any iteration of this part. if (mdp->pi[s] == mdp->m) { (*numNewlyExpandedStates)++; // You have expanded this node and will perform an update! Remember this in the order of expansion. mdp->expanded[mdp->ne] = s; mdp->ne++; // This is a newly expanded state. Perform a Bellman update and mark it as visited in the process. // Store this for both V and VPrime so that the updates align properly... ssp_lao_star_bellman_update_state_cpu(mdp->n, mdp->ns, mdp->m, mdp->S, mdp->T, mdp->R, mdp->V, mdp->ne, mdp->expanded, s, mdp->VPrime, mdp->pi); mdp->V[s] = mdp->VPrime[s]; } else { // Otherwise, add all of its children to the fringe, as long as they are not already there, and the // overall set of expanded states. This follows the best action computed so far. for (unsigned int i = 0; i < mdp->ns; i++) { int sp = mdp->S[s * mdp->m * mdp->ns + mdp->pi[s] * mdp->ns + i]; if (sp < 0) { break; } // Only add it to the fringe if we have not visited it yet. Putting this here // will ensure our stack (fringe of size n) will never overflow. if (std::signbit(mdp->V[sp]) && std::signbit(mdp->VPrime[sp])) { fringe[nf] = sp; nf++; } } } } // At the end, in post order traversal, perform Bellman updates. for (int i = mdp->ne - 1; i >= 0; i--) { unsigned int s = mdp->expanded[i]; // Only actually perform the update if this is a visited expanded node. Recall that dead ends can be expanded, but will // eventually not be visited because the best action will be to avoid them. if (!std::signbit(mdp->V[s]) || !std::signbit(mdp->VPrime[s])) { if (mdp->currentHorizon % 2 == 0) { ssp_lao_star_bellman_update_state_cpu(mdp->n, mdp->ns, mdp->m, mdp->S, mdp->T, mdp->R, mdp->V, mdp->ne, mdp->expanded, s, mdp->VPrime, mdp->pi); } else { ssp_lao_star_bellman_update_state_cpu(mdp->n, mdp->ns, mdp->m, mdp->S, mdp->T, mdp->R, mdp->VPrime, mdp->ne, mdp->expanded, s, mdp->V, mdp->pi); } } else { if (mdp->currentHorizon % 2 == 0) { mdp->VPrime[s] = mdp->V[s]; } else { mdp->V[s] = mdp->VPrime[s]; } } } mdp->currentHorizon++; delete [] fringe; } int ssp_lao_star_check_convergence_cpu(MDP *mdp, bool *converged, bool *nonExpandedTipStateFound) { *converged = false; *nonExpandedTipStateFound = false; // First, reset the visited states. ssp_lao_star_reset_visited(mdp->n, mdp->V, mdp->VPrime); // Create a fringe state list (stack) variable, with just state s0. unsigned int nf = 1; unsigned int *fringe = new unsigned int[mdp->n]; fringe[0] = mdp->s0; // Iterate until there are no more elements on the fringe. while (nf != 0) { // Pop the last element off the stack. unsigned int s = fringe[nf - 1]; nf--; // Check if this state has been visited. If so, continue. if (!std::signbit(mdp->V[s]) || !std::signbit(mdp->VPrime[s])) { continue; } // Check if this state is a goal. If so, continue. bool isGoal = false; for (unsigned int i = 0; i < mdp->ng; i++) { if (s == mdp->goals[i]) { isGoal = true; } } if (isGoal) { continue; } // Mark it as visited if this is not a goal. mdp->V[s] = fabs(mdp->V[s]); mdp->VPrime[s] = fabs(mdp->VPrime[s]); // We have not converged if we truly have never seen this state before. if (mdp->pi[s] == mdp->m) { *nonExpandedTipStateFound = true; } else { // Otherwise, add all of its children to the fringe, as long as they are not already there, and the // overall set of expanded states. This follows the best action computed so far. for (unsigned int i = 0; i < mdp->ns; i++) { int sp = mdp->S[s * mdp->m * mdp->ns + mdp->pi[s] * mdp->ns + i]; if (sp < 0) { break; } // Only add it to the fringe if we have not visited it yet. Putting this here // will ensure our stack (fringe of size n) will never overflow. if (std::signbit(mdp->V[sp]) && std::signbit(mdp->VPrime[sp])) { fringe[nf] = sp; nf++; } } } } // At the end, in post order traversal, perform Bellman updates. Record if the policy has changed. bool anActionHasChanged = false; for (int i = mdp->ne - 1; i >= 0; i--) { unsigned int s = mdp->expanded[i]; unsigned int a = mdp->pi[s]; // Only actually perform the update if this is a visited expanded node. Recall that dead ends can be expanded, but will // eventually not be visited because the best action will be to avoid them. if (!std::signbit(mdp->V[s]) || !std::signbit(mdp->VPrime[s])) { if (mdp->currentHorizon % 2 == 0) { ssp_lao_star_bellman_update_state_cpu(mdp->n, mdp->ns, mdp->m, mdp->S, mdp->T, mdp->R, mdp->V, mdp->ne, mdp->expanded, s, mdp->VPrime, mdp->pi); } else { ssp_lao_star_bellman_update_state_cpu(mdp->n, mdp->ns, mdp->m, mdp->S, mdp->T, mdp->R, mdp->VPrime, mdp->ne, mdp->expanded, s, mdp->V, mdp->pi); } } else { if (mdp->currentHorizon % 2 == 0) { mdp->VPrime[s] = mdp->V[s]; } else { mdp->V[s] = mdp->VPrime[s]; } } // If the action changed after an update, then we have not converged. if (a != mdp->pi[s]) { anActionHasChanged = true; } } mdp->currentHorizon++; // Compute the Bellman residual and determine if it converged or not. But, this only is checked if an action // has not changed. If one did, then we have definitely not converged so don't bother checking. if (anActionHasChanged == false) { ssp_lao_star_bellman_residual_cpu(mdp->ne, mdp->expanded, mdp->epsilon, mdp->V, mdp->VPrime, converged); } delete [] fringe; return NOVA_SUCCESS; } int ssp_lao_star_complete_cpu(MDP *mdp, float *V, unsigned int *pi) { // Note: This 'wrapper' function is provided in order to maintain // the same structure as the GPU version. In the GPU version, // 'complete' performs the initilization and uninitialization of // the MDP object on the device as well. Here, we do not need that. return ssp_lao_star_execute_cpu(mdp, V, pi); } int ssp_lao_star_initialize_cpu(MDP *mdp, float *V) { // Reset the current horizon. mdp->currentHorizon = 0; // Create the variables. mdp->V = new float[mdp->n]; mdp->VPrime = new float[mdp->n]; mdp->pi = new unsigned int[mdp->n]; mdp->ne = 0; mdp->expanded = new int[mdp->n]; // Copy the data from the V provided, and set default values for pi. // Note that these values of V are the heuristics for each state. // Also, the default values for the expanded states are -1, meaning // no expanded state is defined for the index. memcpy(mdp->V, V, mdp->n * sizeof(float)); memcpy(mdp->VPrime, V, mdp->n * sizeof(float)); for (unsigned int i = 0; i < mdp->n; i++) { mdp->pi[i] = 0; mdp->expanded[i] = -1; } return NOVA_SUCCESS; } int ssp_lao_star_execute_cpu(MDP *mdp, float *V, unsigned int *pi) { int result; // First, ensure data is valid. if (mdp->n == 0 || mdp->ns == 0 || mdp->m == 0 || mdp->S == nullptr || mdp->T == nullptr || mdp->R == nullptr || mdp->horizon < 1 || mdp->epsilon < 0.0f || //mdp->ne != 0 || mdp->expanded != nullptr || V == nullptr || pi == nullptr) { fprintf(stderr, "Error[ssp_lao_star_execute_cpu]: %s\n", "Invalid arguments."); return NOVA_ERROR_INVALID_DATA; } result = ssp_lao_star_initialize_cpu(mdp, V); if (result != NOVA_SUCCESS) { fprintf(stderr, "Error[ssp_lao_star_execute_cpu]: %s\n", "Failed to initialize the CPU variables."); return result; } // Note: We mark a state as *never* expanded if its policy has an invalid action (i.e., index m). // The "expanded" list is wiped every time we expand and preserves "all valid states for the final policy". // Finally, the sign bit on V and VPrime mark if it was visited during each internal iteration of the expand // function below. Confusing, but required for an efficient GPU version which will follow. ssp_lao_star_reset_newly_expanded_states(mdp->n, mdp->m, mdp->pi); // We continue the process of expanding and testing convergence until convergence occurs. bool running = true; while (running) { // Expand Step: Perform DFS (greedy actions) and construct a tree from possible stochastic transitions. // This continues until you have: (1) expanded all states, and (2) have reached one of the goal states. unsigned int numNewlyExpandedStates = 1; while (numNewlyExpandedStates != 0) { // Perform DFS (greedy actions), but mark states as visited along the way too, so it doesn't revisit them. // This performs a Bellman update in postorder traversal through the tree of expanded nodes. result = ssp_lao_star_expand_cpu(mdp, &numNewlyExpandedStates); if (result != NOVA_SUCCESS) { fprintf(stderr, "Error[ssp_lao_star_execute_cpu]: %s\n", "Failed to perform Bellman update on the CPU."); return result; } } // Check Convergence Step: Run value iteration on expanded states until: (1) it converges (done), or (2) it has // an optimal action has a possible successor that was not yet expanded (break and continue). bool converged = false; bool nonExpandedTipStateFound = false; mdp->currentHorizon = 0; while (mdp->currentHorizon < mdp->horizon && !converged) { result = ssp_lao_star_check_convergence_cpu(mdp, &converged, &nonExpandedTipStateFound); if (result != NOVA_SUCCESS) { fprintf(stderr, "Error[ssp_lao_star_execute_cpu]: %s\n", "Failed to perform Bellman update on the CPU."); return result; } // If we converged, then break. Or if during iteration we ever expanded a tip state that was not valid, // then just stop here so we can add it during the expand step on the next pass through the outer loop. if (converged || nonExpandedTipStateFound) { break; } } // If we converged (or simply ran out of time) and all expanded tip states were valid, then we are done. if ((converged && !nonExpandedTipStateFound) || mdp->currentHorizon > mdp->horizon) { running = false; } } result = ssp_lao_star_get_policy_cpu(mdp, V, pi); if (result != NOVA_SUCCESS) { fprintf(stderr, "Error[ssp_lao_star_execute_cpu]: %s\n", "Failed to get the policy."); return result; } result = ssp_lao_star_uninitialize_cpu(mdp); if (result != NOVA_SUCCESS) { fprintf(stderr, "Error[ssp_lao_star_execute_cpu]: %s\n", "Failed to uninitialize the CPU variables."); return result; } return NOVA_SUCCESS; } int ssp_lao_star_uninitialize_cpu(MDP *mdp) { // Reset the current horizon and number of expanded states. mdp->currentHorizon = 0; mdp->ne = 0; // Free the expanded states set. if (mdp->expanded != nullptr) { delete [] mdp->expanded; } mdp->expanded = nullptr; // Free the memory for V, VPrime, and pi. if (mdp->V != nullptr) { delete [] mdp->V; } mdp->V = nullptr; if (mdp->VPrime != nullptr) { delete [] mdp->VPrime; } mdp->VPrime = nullptr; if (mdp->pi != nullptr) { delete [] mdp->pi; } mdp->pi = nullptr; return NOVA_SUCCESS; } int ssp_lao_star_get_policy_cpu(MDP *mdp, float *V, unsigned int *pi) { // Determine which is the source for V based on the current horizon. float *Vsrc = nullptr; if (mdp->currentHorizon % 2 == 0) { Vsrc = mdp->VPrime; } else { Vsrc = mdp->V; } // First, we assign all actions to invalid ones. The non-expanded states will have these values. for (unsigned int s = 0; s < mdp->n; s++) { pi[s] = mdp->m; } // Copy the final (or intermediate) result, both V and pi. This assumes memory has been allocated // for the variables provided. Importantly, only the values of the expanded states are copied. // The non-expanded states are left alone. Also, recall that V and pi in the SSP MDP are following // the order in which they were expanded. for (unsigned int i = 0; i < mdp->ne; i++) { unsigned int s = mdp->expanded[i]; // Only include the visited states as part of the final policy. These states are all reachable states // following the optimal policy. Recall that some states might be expanded early on in the process, // but are quickly abandoned. if (!std::signbit(mdp->V[s]) || !std::signbit(mdp->VPrime[s])) { V[s] = Vsrc[s]; pi[s] = mdp->pi[s]; } } return NOVA_SUCCESS; }
[ "kyle.hollins.wray@gmail.com" ]
kyle.hollins.wray@gmail.com
9c55d8c8533193ac2e99d699dab7adeef7448700
66f3dede3797ba1be1366def708befb161639cb0
/q1try2/q1try2.cpp
94574dff13462cedcb7f2586e4995759e3313cc2
[]
no_license
aditi-sharma-limelab/fordintern2021problems
9e49733515f5ea0da542c5a5e3cd168b3d7df7bf
f09614e55c9ff6f42af9c001530ab2dae8e0bfeb
refs/heads/master
2023-03-19T15:14:51.238393
2021-03-15T16:54:04
2021-03-15T16:54:04
347,267,382
0
0
null
null
null
null
UTF-8
C++
false
false
1,794
cpp
// q1try2.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <vector> #include <cstring> using namespace std; int distCalc(int x1, int y1, int x2, int y2) { int dist = abs(x1 - x2) + abs(y1 - y2); return dist; } void testSuite() { string check; cout << "If you would like to see the test suite, type 'yes'. Otherwise, type 'no'" << endl; cin >> check; if (check == "yes") { cout << "Test Points: (5,4) and (3,2)" << endl; cout << " Expected Value: 4" << endl; cout << " Actual Value: " << distCalc(5, 4, 3, 2) << endl << endl; cout << "Test Points: (-1,2) and (1,-2)" << endl; cout << " Expected Value: 6" << endl; cout << " Actual Value: " << distCalc(- 1, 2, 1, -2) << endl << endl; cout << "Test Points: (0,0) and (0,0)" << endl; cout << " Expected Value: 0" << endl; cout << " Actual Value: " << distCalc(0, 0, 0, 0) << endl << endl; cout << "Test Points: (1,3) and (-4,-7)" << endl; cout << " Expected Value: 15" << endl; cout << " Actual Value: " << distCalc(1, 3, -4, -7) << endl << endl; } } int main() { //test suite testSuite(); //point x and y values int x1; int y1; int x2; int y2; //enter values cout << "enter the x value of the first point" << endl; cin >> x1; cout << "enter the y value of the first point" << endl; cin >> y1; cout << "enter the x value of the second point" << endl; cin >> x2; cout << "enter the y value of the second point" << endl; cin >> y2; //return distance cout << "The distance between these points is: " << distCalc(x1, y1, x2, y2) << endl; }
[ "aditis@umich.edu" ]
aditis@umich.edu
bc2939744861e0cb5731adf833775fc486166ca0
f258062f932c15fa21bd49d554824dd59caf784a
/deps/3.1.3/darwin/include/wx/qt/filedlg.h
4c907aea833d726bdf385a247d441f3a5649b65c
[ "MIT" ]
permissive
kusti8/node-wx-napi
8e83a6bb28a9112a16d738eb13ba65e9d4f62b2d
00cf7560bfcb1dcf5680f8030e775f8e7dc1cf08
refs/heads/master
2022-02-09T16:07:01.372990
2020-01-12T21:33:08
2020-01-12T21:33:08
232,460,161
3
1
MIT
2022-01-22T10:11:27
2020-01-08T02:28:40
C++
UTF-8
C++
false
false
2,391
h
///////////////////////////////////////////////////////////////////////////// // Name: wx/qt/filedlg.h // Author: Sean D'Epagnier // Copyright: (c) 2014 Sean D'Epagnier // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_QT_FILEDLG_H_ #define _WX_QT_FILEDLG_H_ class QFileDialog; class WXDLLIMPEXP_CORE wxFileDialog : public wxFileDialogBase { public: wxFileDialog() { } wxFileDialog(wxWindow *parent, const wxString& message = wxFileSelectorPromptStr, const wxString& defaultDir = wxEmptyString, const wxString& defaultFile = wxEmptyString, const wxString& wildCard = wxFileSelectorDefaultWildcardStr, long style = wxFD_DEFAULT_STYLE, const wxPoint& pos = wxDefaultPosition, const wxSize& sz = wxDefaultSize, const wxString& name = wxFileDialogNameStr); bool Create(wxWindow *parent, const wxString& message = wxFileSelectorPromptStr, const wxString& defaultDir = wxEmptyString, const wxString& defaultFile = wxEmptyString, const wxString& wildCard = wxFileSelectorDefaultWildcardStr, long style = wxFD_DEFAULT_STYLE, const wxPoint& pos = wxDefaultPosition, const wxSize& sz = wxDefaultSize, const wxString& name = wxFileDialogNameStr); virtual wxString GetPath() const wxOVERRIDE; virtual void GetPaths(wxArrayString& paths) const wxOVERRIDE; virtual wxString GetFilename() const wxOVERRIDE; virtual void GetFilenames(wxArrayString& files) const wxOVERRIDE; virtual int GetFilterIndex() const wxOVERRIDE; virtual void SetMessage(const wxString& message) wxOVERRIDE; virtual void SetPath(const wxString& path) wxOVERRIDE; virtual void SetDirectory(const wxString& dir) wxOVERRIDE; virtual void SetFilename(const wxString& name) wxOVERRIDE; virtual void SetWildcard(const wxString& wildCard) wxOVERRIDE; virtual void SetFilterIndex(int filterIndex) wxOVERRIDE; virtual bool SupportsExtraControl() const wxOVERRIDE { return true; } virtual QFileDialog *GetQFileDialog() const; private: wxDECLARE_DYNAMIC_CLASS(wxFileDialog); }; #endif // _WX_QT_FILEDLG_H_
[ "hello@kusti8.com" ]
hello@kusti8.com
c242d85354d3c802548c5d5d213a6a03309f6383
70aede47d17414fe0b0e2c7fa5d77a8b58f6c2cf
/cpp05/ex00/Bureaucrat.cpp
78d36587081ab6d3c6e83157124d2348ca09e3f5
[]
no_license
MichelleJiam/cpp
8d857035cf8cf47547f52ddddf19b773aeb9975f
0a2c74ca01c05f0d05d89a9c56aab40420bdd4bc
refs/heads/master
2023-01-21T08:40:22.319406
2020-11-18T17:45:28
2020-11-18T17:45:28
283,498,437
1
0
null
null
null
null
UTF-8
C++
false
false
2,674
cpp
/* ************************************************************************** */ /* */ /* :::::::: */ /* Bureaucrat.cpp :+: :+: */ /* +:+ */ /* By: mjiam <mjiam@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2020/08/31 18:51:23 by mjiam #+# #+# */ /* Updated: 2020/09/17 16:22:21 by mjiam ######## odam.nl */ /* */ /* ************************************************************************** */ #include "Bureaucrat.hpp" Bureaucrat::Bureaucrat(void) { return; } Bureaucrat::Bureaucrat(std::string const &name, int grade) : _name(name) { _gradeTry(grade); return; } // try can also be done with function-try-block Bureaucrat::Bureaucrat(Bureaucrat const &other) : _name(other._name) { _gradeTry(other._grade); return; } Bureaucrat::~Bureaucrat(void) { return; } Bureaucrat &Bureaucrat::operator=(Bureaucrat const &other) { if (this != &other) _gradeTry(other._grade); return *this; } std::ostream &operator<<(std::ostream &o, Bureaucrat const &obj) { o << "<" << obj.getName() << ">, bureaucrat grade <" << obj.getGrade() << ">" << std::endl; return o; } int Bureaucrat::getGrade(void) const { return this->_grade; } std::string const Bureaucrat::getName(void) const { return this->_name; } void Bureaucrat::upGrade(void) { _gradeTry(this->_grade - 1); return; } void Bureaucrat::downGrade(void) { _gradeTry(this->_grade + 1); return; } void Bureaucrat::_gradeTry(int grade) { try { if (grade < 1) throw GradeTooHighException(); else if (grade > 150) throw GradeTooLowException(); this->_grade = grade; } catch (GradeTooHighException &e) { std::cout << e.what() << std::endl; } catch (GradeTooLowException &e) { std::cout << e.what() << std::endl; } return; } char const *Bureaucrat::GradeTooHighException::what( void) const throw() { return ("Grade is too high"); } char const *Bureaucrat::GradeTooLowException::what( void) const throw() { return ("Grade is too low"); }
[ "mjiam@student.codam.nl" ]
mjiam@student.codam.nl
464a569ed44ba0b9e244575c49d7a76ef392da2d
cf111b440f33ba9741ff45c60ac33dfade24e2ac
/Projects/Grafeo/attic/grafeo_cc_new/abstracttool.h
0ca998b6a87d86ba9388fc1fa1098daa847cfb0f
[ "Unlicense" ]
permissive
fredmorcos/attic
cd08e951f56c3b256899ef5ca4ccd030d3185bc1
36d5891a959cfc83f9eeef003b4e0b574dd7d7e1
refs/heads/master
2023-07-05T10:03:58.115062
2023-06-21T22:55:38
2023-06-22T07:07:58
154,962,425
4
1
Unlicense
2023-06-22T07:08:00
2018-10-27T12:30:38
JavaScript
UTF-8
C++
false
false
775
h
#ifndef ABSTRACTTOOL_H #define ABSTRACTTOOL_H #include <QObject> #include <QIcon> class QGraphicsScene; class QGraphicsSceneMouseEvent; class QKeyEvent; class AbstractTool : public QObject { private: QString m_toolName; QIcon m_toolIcon; public: AbstractTool(QObject *parent = 0); QString toolName(); QIcon toolIcon(); static QGraphicsScene *scene; virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) = 0; virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event) = 0; virtual void mousePressEvent(QGraphicsSceneMouseEvent *event) = 0; virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) = 0; virtual void keyPressEvent(QKeyEvent *event) = 0; virtual void keyReleaseEvent(QKeyEvent *event) = 0; }; #endif // ABSTRACTTOOL_H
[ "fred.morcos@gmail.com" ]
fred.morcos@gmail.com
d4e62fba9f630c7bf20cc11fc66294008151b420
56b32941415e9abe063d6e52754b665bf95c8d6a
/R-Portable/App/R-Portable/library/dplyr/include/dplyr/Gatherer.h
aaf1459af336ad017d4e211de32193f423d19649
[ "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "MIT" ]
permissive
voltek62/seo-viz-install
37ed82a014fc36e192d9a5e5aed7bd45327c8ff3
e7c63f4e2e4acebc1556912887ecd6a12b4458a0
refs/heads/master
2020-05-23T08:59:32.933837
2017-03-12T22:00:01
2017-03-12T22:00:01
84,758,190
1
0
MIT
2019-10-13T20:51:49
2017-03-12T21:20:14
C++
UTF-8
C++
false
false
10,955
h
#ifndef dplyr_Gatherer_H #define dplyr_Gatherer_H namespace dplyr { class Gatherer { public: virtual ~Gatherer(){} virtual SEXP collect() = 0 ; } ; template <int RTYPE, typename Data, typename Subsets> class GathererImpl : public Gatherer { public: typedef typename traits::storage_type<RTYPE>::type STORAGE ; typedef GroupedCallProxy<Data,Subsets> Proxy ; GathererImpl( RObject& first, SlicingIndex& indices, Proxy& proxy_, const Data& gdf_, int first_non_na_ ) : gdf(gdf_), proxy(proxy_), data(gdf.nrows(), Vector<RTYPE>::get_na() ), first_non_na(first_non_na_) { if( first_non_na < gdf.ngroups() ) grab( first, indices ) ; copy_most_attributes( data, first ) ; } SEXP collect(){ int ngroups = gdf.ngroups() ; if( first_non_na == ngroups ) return data ; typename Data::group_iterator git = gdf.group_begin() ; int i = 0 ; for(; i<first_non_na; i++) ++git ; ++git; i++ ; for(; i<ngroups; i++, ++git){ SlicingIndex indices = *git ; Shield<SEXP> subset( proxy.get( indices ) ) ; grab(subset, indices); } return data ; } private: inline void grab(SEXP subset, const SlicingIndex& indices){ int n = Rf_length(subset) ; if( is<LogicalVector>(subset) && all(is_na(LogicalVector(subset))).is_true() ){ grab_rep( Vector<RTYPE>::get_na(), indices ) ; } else { check_type(subset) ; if(n == indices.size() ){ grab_along( subset, indices ) ; } else if( n == 1) { grab_rep( Rcpp::internal::r_vector_start<RTYPE>(subset)[0], indices ) ; } else { stop ( "incompatible size (%d), expecting %d (the group size) or 1", n, indices.size()) ; } } } void grab_along( SEXP subset, const SlicingIndex& indices ){ int n = indices.size(); STORAGE* ptr = Rcpp::internal::r_vector_start<RTYPE>( subset ) ; for( int j=0; j<n; j++){ data[ indices[j] ] = ptr[j] ; } } void check_type(SEXP subset){ if( TYPEOF(subset) != RTYPE ){ stop( "incompatible types, expecting a %s vector", vector_class<RTYPE>() ) ; } } void grab_rep( STORAGE value, const SlicingIndex& indices ){ int n = indices.size(); for( int j=0; j<n; j++){ data[ indices[j] ] = value ; } } const Data& gdf ; Proxy& proxy ; Vector<RTYPE> data ; int first_non_na ; } ; template <typename Data, typename Subsets> class ListGatherer : public Gatherer { public: typedef GroupedCallProxy<Data,Subsets> Proxy ; ListGatherer( List first, SlicingIndex& indices, Proxy& proxy_, const Data& gdf_, int first_non_na_ ) : gdf(gdf_), proxy(proxy_), data(gdf.nrows()), first_non_na(first_non_na_) { if( first_non_na < gdf.ngroups() ){ perhaps_duplicate(first) ; grab( first, indices ) ; } copy_most_attributes( data, first ) ; } SEXP collect(){ int ngroups = gdf.ngroups() ; if( first_non_na == ngroups ) return data ; typename Data::group_iterator git = gdf.group_begin() ; int i = 0 ; for(; i<first_non_na; i++) ++git ; ++git; i++ ; for(; i<ngroups; i++, ++git){ SlicingIndex indices = *git ; List subset( proxy.get(indices) ) ; perhaps_duplicate(subset) ; grab(subset, indices); } return data ; } private: inline void perhaps_duplicate( List& x ){ int n = x.size() ; for( int i=0; i<n; i++){ SEXP xi = x[i] ; if( IS_DPLYR_SHRINKABLE_VECTOR(xi) ) { x[i] = Rf_duplicate(xi) ; } else if( TYPEOF(xi) == VECSXP ){ List lxi(xi) ; perhaps_duplicate( lxi ) ; } } } inline void grab(const List& subset, const SlicingIndex& indices){ int n = subset.size() ; if(n == indices.size() ){ grab_along( subset, indices ) ; } else if( n == 1) { grab_rep( subset[0], indices ) ; } else { stop ( "incompatible size (%d), expecting %d (the group size) or 1", n, indices.size()) ; } } void grab_along( const List& subset, const SlicingIndex& indices ){ int n = indices.size(); for( int j=0; j<n; j++){ data[ indices[j] ] = subset[j] ; } } void grab_rep( SEXP value, const SlicingIndex& indices ){ int n = indices.size(); for( int j=0; j<n; j++){ data[ indices[j] ] = value ; } } const Data& gdf ; Proxy& proxy ; List data ; int first_non_na ; } ; template <typename Data, typename Subsets> class FactorGatherer : public Gatherer { public: typedef GroupedCallProxy<Data,Subsets> Proxy ; typedef IntegerVector Factor; FactorGatherer( RObject& first, SlicingIndex& indices, Proxy& proxy_, const Data& gdf_, int first_non_na_ ) : levels(), data(gdf_.nrows(), NA_INTEGER), first_non_na(first_non_na_), proxy(proxy_), gdf(gdf_) { if( first_non_na < gdf.ngroups() ) grab( (SEXP)first, indices ) ; copy_most_attributes( data, first ) ; } inline SEXP collect(){ int ngroups = gdf.ngroups() ; typename Data::group_iterator git = gdf.group_begin() ; int i = 0 ; for(; i<first_non_na; i++) ++git ; for(; i<ngroups; i++, ++git){ SlicingIndex indices = *git ; Factor subset( proxy.get( indices ) ) ; grab(subset, indices); } CharacterVector levels_(levels_vector.begin(), levels_vector.end() ) ; data.attr("levels") = levels_ ; return data ; } private: dplyr_hash_map<SEXP, int> levels ; Factor data ; int first_non_na ; Proxy& proxy ; const Data& gdf ; std::vector<SEXP> levels_vector ; void grab( Factor f, const SlicingIndex& indices ){ // update levels if needed CharacterVector lev = f.attr("levels") ; std::vector<int> matches( lev.size() ) ; int nlevels = levels.size() ; for( int i=0; i<lev.size(); i++){ SEXP level = lev[i] ; if( !levels.count(level) ){ nlevels++ ; levels_vector.push_back(level) ; levels[level] = nlevels ; matches[i] = nlevels ; } else { matches[i] = levels[level] ; } } // grab data int n = indices.size() ; int nf = f.size() ; if( n == nf ){ for( int i=0; i<n; i++){ if( f[i] != NA_INTEGER ){ data[ indices[i] ] = matches[ f[i] - 1 ] ; } } } else if( nf == 1){ int value = NA_INTEGER ; if( f[0] != NA_INTEGER ){ value = matches[ f[0] - 1] ; for( int i=0; i<n; i++){ data[ indices[i] ] = value ; } } } else { stop( "incompatible size" ) ; } } } ; template <int RTYPE> class ConstantGathererImpl : public Gatherer { public: ConstantGathererImpl( Vector<RTYPE> constant, int n ) : value( n, Rcpp::internal::r_vector_start<RTYPE>(constant)[0] ) { copy_most_attributes( value, constant ) ; } inline SEXP collect() { return value ; } private: Vector<RTYPE> value ; } ; inline Gatherer* constant_gatherer(SEXP x, int n){ if( Rf_inherits(x, "POSIXlt" ) ){ stop("`mutate` does not support `POSIXlt` results"); } switch( TYPEOF(x) ){ case INTSXP: return new ConstantGathererImpl<INTSXP>( x, n ) ; case REALSXP: return new ConstantGathererImpl<REALSXP>( x, n ) ; case LGLSXP: return new ConstantGathererImpl<LGLSXP>( x, n ) ; case STRSXP: return new ConstantGathererImpl<STRSXP>( x, n ) ; case CPLXSXP: return new ConstantGathererImpl<CPLXSXP>( x, n ) ; case VECSXP: return new ConstantGathererImpl<STRSXP>( x, n ) ; default: break ; } stop("Unsupported vector type %s", Rf_type2char(TYPEOF(x))) ; return 0 ; } template <typename Data, typename Subsets> inline Gatherer* gatherer( GroupedCallProxy<Data,Subsets>& proxy, const Data& gdf, SEXP name ){ typename Data::group_iterator git = gdf.group_begin() ; SlicingIndex indices = *git ; RObject first( proxy.get(indices) ) ; if( Rf_inherits(first, "POSIXlt" ) ){ stop("`mutate` does not support `POSIXlt` results"); } int ng = gdf.ngroups() ; int i = 0 ; while( all_na(first) ){ i++ ; if( i == ng ) break ; ++git ; indices = *git ; first = proxy.get(indices) ; } switch( TYPEOF(first) ){ case INTSXP: { if( Rf_inherits(first, "factor")) return new FactorGatherer<Data, Subsets>( first, indices, proxy, gdf, i) ; return new GathererImpl<INTSXP,Data,Subsets> ( first, indices, proxy, gdf, i ) ; } case REALSXP: return new GathererImpl<REALSXP,Data,Subsets> ( first, indices, proxy, gdf, i ) ; case LGLSXP: return new GathererImpl<LGLSXP,Data,Subsets> ( first, indices, proxy, gdf, i ) ; case STRSXP: return new GathererImpl<STRSXP,Data,Subsets> ( first, indices, proxy, gdf, i ) ; case VECSXP: return new ListGatherer<Data,Subsets> ( List(first), indices, proxy, gdf, i ) ; case CPLXSXP: return new GathererImpl<CPLXSXP,Data,Subsets> ( first, indices, proxy, gdf, i ) ; default: break ; } check_supported_type(first, name); return 0; } } // namespace dplyr #endif
[ "vincent.terrasi@corp.ovh.com" ]
vincent.terrasi@corp.ovh.com
1cf6bea5c5e97231704631c1b346844aa72f9d02
5495b49642d3cb76b682e09cc4c7febc3938fcda
/MyCpro/MyCpro/myc++/include/back/vl_aud_manager.hpp
600c07cec19e26fb702ae114283d033db61af969
[]
no_license
DeXianLin/MyCPro
d04dd8bbad74080aa2a4640149e3df4b84f03a35
0c28f009d81c5fcc3e350397d076b3cf33cca87b
refs/heads/master
2023-05-29T04:48:27.965539
2021-06-16T06:11:54
2021-06-16T06:11:54
377,346,542
0
0
null
null
null
null
UTF-8
C++
false
false
6,237
hpp
#ifndef __VL_AUD_MANAGER_HPP__ #define __VL_AUD_MANAGER_HPP__ #include "vl_types.h" #include <pthread.h> #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> /** * 负责管理声音设备,单例模式 * 不同群之间共享一个媒体管理实例,但每个群可以有部分不同的语音配置。需要统一的参数如下: * 同一时间,只能有一个声音播放,也只能有一个录音。 * * 关于声音设备,不同群主要靠不同的语音Filter做处理 */ #define NUM_BUFFERS (2) #define MAX_VOLUME (32) typedef struct { vl_int16 init_vol; } vl_aud_dev_param; /** * 录音参数(每次启动录音时传入) */ typedef struct vl_aud_rec_param { /* 采样率,如 8000, 16000 ... */ vl_uint32 sample_rate; /* 声道数 */ vl_uint32 channel_cnt; /* 每个sample占用比特数 */ vl_uint32 bits_per_sample; /* 一帧数据的时长 */ vl_uint32 frm_duration; vl_aud_rec_param& operator=(const vl_aud_rec_param& param) { sample_rate = param.sample_rate; channel_cnt = param.channel_cnt; bits_per_sample = param.bits_per_sample; frm_duration = param.frm_duration; return * this; } bool operator==(const vl_aud_rec_param& param) { if(sample_rate == param.sample_rate && channel_cnt == param.channel_cnt && bits_per_sample == param.bits_per_sample && frm_duration == param.frm_duration) { return true; } else { return false; } } } vl_aud_rec_param; /** * 播放参数(每次启动播放流时传入) */ typedef struct vl_aud_ply_param { /* 采样率,如 8000, 16000 ... */ vl_uint32 sample_rate; /* 声道数 */ vl_uint32 channel_cnt; /* 每个sample占用比特数 */ vl_uint32 bits_per_sample; /* 影响缓存区大小,单位毫秒 */ vl_uint32 frm_duration; /* 标志从feeder中获取不到新的pcm时,是否自动释放播放设备,用于文件播放 */ vl_bool auto_release; /* 指定从那个声音通道播放, 设置为 <0 时候,默认使用music通道 */ SLint32 streamType; vl_aud_ply_param& operator=(const vl_aud_ply_param& param) { sample_rate = param.sample_rate; channel_cnt = param.channel_cnt; bits_per_sample = param.bits_per_sample; frm_duration = param.frm_duration; auto_release = param.auto_release; streamType = param.streamType; return * this; } bool operator==(const vl_aud_ply_param& param) { if(sample_rate == param.sample_rate && channel_cnt == param.channel_cnt && bits_per_sample == param.bits_per_sample && frm_duration == param.frm_duration && auto_release == param.auto_release && streamType == param.streamType) { return true; } else { return false; } } /* 用于判断新的参数是否需要重启播放器 */ vl_bool need_restart(const vl_aud_ply_param& new_param) { if((sample_rate != new_param.sample_rate) || (channel_cnt != new_param.channel_cnt) || (bits_per_sample != new_param.bits_per_sample) || (frm_duration != new_param.frm_duration)) { return VL_TRUE; } else { return VL_FALSE; } } } vl_aud_ply_param; /** * 提供pcm流接口,播放回调 */ class vl_aud_raw_frm_feeder { virtual vl_status get_pcm(vl_aud_ply_param * param, vl_uint8 * samples, vl_size * sample_count); }; /** * 录音回调接口 */ class vl_aud_raw_frm_consumer { virtual vl_status put_pcm(vl_aud_rec_param * param, const vl_uint8 * samples, vl_size * sample_count); }; /** * 声音设备管理类 * 不允许同时录音 * 不允许同时在同一个声道播放 */ class vl_aud_manager { public : /* 获取媒体设备管理实例 */ static vl_aud_manager& get_instance(vl_aud_dev_param * init_param); /* 请求播放 */ vl_status aquire_play(const vl_aud_ply_param& param, vl_aud_raw_frm_feeder * feeder, int * playerId); /* 加大音量 */ vl_status inc_volume(); /* 减少音量 */ vl_status dec_volume(); /* 设置音量, 音量值范围为32 */ vl_status set_volume(vl_int16 volume); /* 暂停播放 */ vl_status pause_play(int playerId); /* 恢复播放 */ vl_status resume_play(int playerId); /*开始播放, 传入aquire的id */ vl_status start_play(int playerId); /* 停止播放 */ vl_status stop_play(int playerId, vl_bool wait); /* 释放播放设备 */ vl_status release_play_dev(int playerId); /* 请求录音 */ vl_status aquire_record(const vl_aud_rec_param& param, vl_aud_raw_frm_consumer * consumer, int * recordId); /* 开始录音 */ vl_status start_record(int recordId); /* 停止录音 */ vl_status stop_record(int recordId); /* 释放录音设备 */ vl_status release_rec_dev(int recordId); private : vl_aud_manager(vl_aud_dev_param * init_param); virtual ~vl_aud_manager(); void reset(); vl_status reinitial(vl_aud_dev_param * init_param); void deinitial(); /* 等待缓冲区数据结束 */ void play_wait(); static vl_aud_manager * instance; /* opensl 可用 */ vl_bool isReady; /* 内部播放缓冲区 */ vl_bool playing; unsigned playerBufferSize; char *playerBuffer[NUM_BUFFERS]; int playerBufIdx; vl_aud_raw_frm_feeder * feeder; vl_aud_ply_param playerParam; int playerId; pthread_mutex_t playerLock; /* 内部录音缓冲区 */ vl_bool recording; unsigned recordBufferSize; char *recordBuffer[NUM_BUFFERS]; int recordBufIdx; vl_aud_raw_frm_consumer * consumer; vl_aud_rec_param recordParam; int recordId; pthread_mutex_t recordLock; /* 播放 + 录音公用引擎,private数据类型,不是用types */ SLObjectItf engineObject; SLEngineItf engineEngine; SLObjectItf outputMixObject; /* 播放 */ SLObjectItf playerObj; SLPlayItf playerPlay; SLVolumeItf playerVol; vl_int16 adjustVol; SLmillibel originVol; /* 录音 */ SLObjectItf recordObj; SLRecordItf recordRecord; /* 缓冲队列 */ SLAndroidSimpleBufferQueueItf playerBufQ; SLAndroidSimpleBufferQueueItf recordBufQ; }; vl_aud_manager* vl_aud_manager::instance = NULL; #endif
[ "285492845@qq.com" ]
285492845@qq.com
ecc79c4abdcf284b3f515e37485a7ec8f0e081d5
9d9c5684788b17ab14375b29f64bcfc29fb02ec9
/Week02Homework/Homework02(attempt):src/ofApp.cpp
180ee3e3cea331ae7797ae80835d429790cd67d1
[]
no_license
mylin04202/coding02
224ae2d9dd62aa82e90842032f8ecec83ce607c0
448c2dd5b0cff0c216f5123f8499885016063aa8
refs/heads/main
2023-04-02T22:19:20.026808
2021-04-11T22:20:33
2021-04-11T22:20:33
336,103,895
0
0
null
null
null
null
UTF-8
C++
false
false
2,038
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0, 0, 0); ofTranslate(ofGetWidth() / 2, ofGetHeight() / 2); ofNoFill(); ofSetLineWidth(2); ofSetRectMode(OF_RECTMODE_CENTER); ofGetMouseX(); ofGetMouseY(); ofSetColor(255,192+ofGetMouseX()*0.2,203+ofGetMouseY()*0.1); for (int i = 0; i < 30; i++){ ofRotateDeg(ofGetElapsedTimef()); ofScale(0.9); // ofDrawRectangle(0, 0, 500, 500); ofDrawBezier(0, 20, ofGetMouseX()*3+70, ofGetMouseX()*2+100, ofGetMouseX()*5, ofGetMouseY(), 340, 500); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
[ "noreply@github.com" ]
noreply@github.com
670bdc9369430b06a0450398075c7ce29fe206b0
faf000392639ed022045be6944b555a8402fb7c4
/Teach Yourself C++/Chapter 2/object pointers.cpp
b1f90712c7b0c1a7c815d3f2174ca007f5611b5c
[]
no_license
AliAkberAakash/Cpp
6a57f79b902737e113f247f1ea1ceabc512a4114
9d4da508e97dfc52eb45ada9606d68d37dbea179
refs/heads/master
2021-01-22T22:53:37.662718
2017-06-15T19:17:54
2017-06-15T19:17:54
85,589,175
0
0
null
null
null
null
UTF-8
C++
false
false
422
cpp
#include<iostream> #include<cstdio> class myClass { int a; public: void get_a(int x); void print(); }; void myClass::get_a(int x) { a=x; } void myClass::print() { printf("%d\n", a); } int main() { myClass ob1; myClass* p=NULL; p=&ob1; p->get_a(0); p->print(); p->get_a(1); p->print(); p->get_a(2); p->print(); p->get_a(3); p->print(); return 0; }
[ "cedward318@gmail.com" ]
cedward318@gmail.com
23923b5f3b5635620ceedc0b84f23515e34227e6
9f29a51abaef36255aae164864d5cac59de07291
/Source/Urho3D/Core/Condition.h
87e0b82887c3b58907ac22b761cac3ef36bfcba0
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
taohuadao/Urho3D
50213e52ba3f7490435de5fe9379695539d75630
b094fe3d1273b1136b918d5c81b225182de74d8f
refs/heads/master
2023-08-18T05:08:19.121954
2023-08-10T03:49:54
2023-08-10T03:49:54
324,118,542
0
0
MIT
2020-12-24T09:30:45
2020-12-24T09:30:45
null
UTF-8
C++
false
false
679
h
// Copyright (c) 2008-2022 the Urho3D project // License: MIT #pragma once #ifdef URHO3D_IS_BUILDING #include "Urho3D.h" #else #include <Urho3D/Urho3D.h> #endif namespace Urho3D { /// %Condition on which a thread can wait. class URHO3D_API Condition { public: /// Construct. Condition(); /// Destruct. ~Condition(); /// Set the condition. Will be automatically reset once a waiting thread wakes up. void Set(); /// Wait on the condition. void Wait(); private: #ifndef _WIN32 /// Mutex for the event, necessary for pthreads-based implementation. void* mutex_; #endif /// Operating system specific event. void* event_; }; }
[ "dao.taohua@gmail.com" ]
dao.taohua@gmail.com
ea7cb5cadff68101414ba1d0cf3c688dc8bed2e7
857e4b75e4f6e42b649de1b3c77cdc538208e789
/codechef/check.cpp
6f83e5420cc51986c1eb5886805b9704fea42918
[]
no_license
devikakrishnadas/OJ-problems
ce82d7f4961ae53d86f58a606fa4c4c13594df74
4367da34b2899a8ec8e1fe4b0d382a9d68c60c1e
refs/heads/master
2021-09-10T09:25:08.568751
2018-03-23T13:26:31
2018-03-23T13:26:31
103,985,719
0
0
null
null
null
null
UTF-8
C++
false
false
1,615
cpp
#include<bits/stdc++.h> #define ll long long #define vi vector<int> #define vc vector<char> #define vll vector<ll> #define pb push_back #define sf scanf #define ff first #define M 1000000007 #define ss second #define pf printf #define mp make_pair #define all(V) V.begin(),V.end() #define FOR(i,a,b) for(int i=a;i<b;i++) #define REP(i,n) FOR(i,0,n) ll bign = 1 << 22 ; ll totv = 77; ll base = 160; ll prime = 25 * bign + 1; using namespace std; ll ModE(ll a,ll mo,ll b) { if(b==0) return 1; else if(b==1) return a%mo; return (a*ModE(a*a,mo,b/2))%mo; else return (ModE(a*a,mo,b/2))%mo; } void arrange(vll &p, ll n,vll &q, vll &r) { for(int i=0;i<n;i++) { if(i%2 == 0) q.pb(p[i]); else r.pb(p[i]); } } vll FFT(vll p, ll n, ll w) { if(n <= 1) return p; vll q,r; arrange(p,n,q,r); q = FFT(q, n/2, (w*w)%prime); r = FFT(r, n/2, (w*w)%prime); ll w_ = 1; REP(i,n/2) { p[i] = (q[i] + (w_*r[i])%prime)%prime; p[i+n/2] = ((q[i] - (w_*r[i])%prime)%prime + prime)%prime; w_ = (w_*w)%prime; } return p; } double val[200][200][200] = {0}; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); vll p(bign); ll w = ModE(3,prime,25); cout<<prime<<endl; REP(i,4) { cin>>p[i]; } p = FFT(p,bign,w); cout<<"hello"<<endl; p = FFT(p,bign,ModE(w,prime,prime-2)); ll inv = ModE(bign,prime,prime-2); cout<<"inverse : "<<inv<<endl; REP(i,4) { cout<<p[i]<<" "; } cout<<endl; return 0; }
[ "devikakrishnadas97@gmail.com" ]
devikakrishnadas97@gmail.com
22e6024730f798303576d1499f47a848be6ed441
7a06c3640a7bbd05a2d9792d5cc7f858f19f890e
/Inc/Count_url.INC
60c2cc274ed2e3d4c063af66ae20e9c666ac8090
[]
no_license
Nyksu/72rus
7b7ce2b7a8763a81d48337b3c5ebd28581048219
13a272b5cc9d5c01013863c8ab6a8da9be3db222
refs/heads/master
2020-07-21T17:48:26.680302
2019-09-07T08:00:43
2019-09-07T08:00:43
206,935,286
0
0
null
null
null
null
UTF-8
C++
false
false
287
inc
<% function Count_url(tp,hiid){ var recs=CreateRecordSet() if (tp==5) {recs.Source="Select * from get_count_url("+hiid+")"} else {recs.Source="Select * from get_count_url_st("+hiid+","+tp+")"} recs.Open() retval=recs("COUNT_URL").Value recs.Close() delete recs return retval } %>
[ "nyksu@yandex.ru" ]
nyksu@yandex.ru
f08ee6b63c7d4db404fd46578001de03a9a8463d
2f6f4953d35e53d3d86ad4e959d9f032d4bb3c4c
/startalk_ui/gloableeventobject.h
df4c76bf2372a4afb0ed0dd39b33a219958f808d
[ "MIT" ]
permissive
xuepingiw/open_source_startalk
c9b6866b736d51798394486de2b6181a49f38466
44d962b04039f5660ec47a10313876a0754d3e72
refs/heads/master
2020-04-29T03:00:00.190179
2019-03-27T07:01:40
2019-03-27T07:01:40
175,791,902
0
0
MIT
2019-03-15T09:43:22
2019-03-15T09:43:18
null
UTF-8
C++
false
false
1,035
h
#ifndef GLOABLEEVENTOBJECT_H #define GLOABLEEVENTOBJECT_H #include <QObject> #include <QMoveEvent> class QuickReplyMsgItem; #include <QPushButton> #include <QLabel> class GloableEventObject : public QObject { Q_OBJECT public: static GloableEventObject* getInstance(); private: static GloableEventObject* pInstance; GloableEventObject(QObject *parent); ~GloableEventObject(); private: signals: void sgMainDialogMoved(QMoveEvent* event); void sgShake(); void sgMainDialogActivitied(bool activited); //recentItemview销毁的信号 void sgShowDeleteCatchMenu(); void sgQuickReplyUpdate(const QList<QuickReplyMsgItem*>& replymsgList); void sgQuickReplyGroupChange(); void sgQuickReplyAllContentChange(); void sgQuickReplyContentChange(const QString &groupCid); void sgInputTextChange(qreal val); void sgNewVersionPrompt(bool bPrompt); void sgFontSizeChange(quint16 nsize); void sgHideMainWidge(); void sgShowMainWidge(); void sgMainDlgMin(); }; #endif // GLOABLEEVENTOBJECT_H
[ "20832776@qunar.com" ]
20832776@qunar.com
cf5836e6ba4339be0124121932fc33d8280c84e7
d0323c74c26b3748f35b925bc2e6440806a30212
/SWEA/swea 1966.cpp
a36b0c28036723bbe23ebadbc006f12d5b173adc
[]
no_license
seung-jae-choi/chang-rok
56afc6ab19e3ea89335c0b86ce8b18db75e51e7e
cb335ef2b7eee113230852a4cb0ab373e705cf31
refs/heads/master
2022-04-24T13:08:39.850027
2020-04-22T08:38:48
2020-04-22T08:38:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
424
cpp
#include<iostream> #include<vector> #include<algorithm> using namespace std; int t; int n; vector<int> vi; int main() { cin >> t; for (int i = 1; i <= t; i++) { cin >> n; int num; for (int j = 0; j < n; j++) { cin >> num; vi.push_back(num); } sort(vi.begin(), vi.end()); cout << "#" << i << " "; for (int j = 0; j < n; j++) { cout << vi[j] << " "; } cout << "\n"; vi.clear(); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
649de68588eb4716a05ca2475acdfd6575f20413
b49616f91836142e8c6197357b58886f40d91a03
/thrust/detail/backend/generic/scalar/binary_search.h
16e9a61cb2cebe21840b8c57faab324e3dc85853
[]
no_license
gregorburger/solver-playground
1b7a5f40892920bf779f4aadfd8842bef7857e15
618767338f9ab1698d094290a361792a2f3e4797
refs/heads/master
2021-01-01T18:38:03.611575
2011-11-24T13:26:30
2011-11-24T13:26:30
2,835,689
1
0
null
null
null
null
UTF-8
C++
false
false
2,013
h
/* * Copyright 2008-2009 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <thrust/detail/config.h> #include <thrust/pair.h> namespace thrust { namespace detail { namespace backend { namespace generic { namespace scalar { template<typename RandomAccessIterator, typename T, typename BinaryPredicate> __host__ __device__ RandomAccessIterator lower_bound(RandomAccessIterator first, RandomAccessIterator last, const T &val, BinaryPredicate comp); template<typename RandomAccessIterator, typename T, typename BinaryPredicate> __host__ __device__ RandomAccessIterator upper_bound(RandomAccessIterator first, RandomAccessIterator last, const T &val, BinaryPredicate comp); template<typename RandomAccessIterator, typename T, typename BinaryPredicate> __host__ __device__ pair<RandomAccessIterator,RandomAccessIterator> equal_range(RandomAccessIterator first, RandomAccessIterator last, const T &val, BinaryPredicate comp); template<typename RandomAccessIterator, typename T, typename Compare> __host__ __device__ bool binary_search(RandomAccessIterator first, RandomAccessIterator last, const T &value, Compare comp); } // end scalar } // end generic } // end backend } // end detail } // end thrust #include <thrust/detail/backend/generic/scalar/binary_search.inl>
[ "gregor@iut-monster.(none)" ]
gregor@iut-monster.(none)
d98746d1e7de6fb9c849b956010dd9f3131d08f8
fbffead2071ba17d1bd9b24fcf55e67f2d34b0a1
/Outsbook - National Flag.cpp
4517b36928042da06042d52f564878748f704c0e
[]
no_license
Parthib13/Outsbook
620a152b672d0ed362a1b7d95327eb187f717e35
8fc58b330a36a7c9a914719960749d577864fd5c
refs/heads/master
2021-01-21T11:08:45.223844
2017-05-18T19:08:46
2017-05-18T19:08:46
91,728,332
0
0
null
null
null
null
UTF-8
C++
false
false
140
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int ans = (6*n)/10; cout<<ans<<endl; }
[ "noreply@github.com" ]
noreply@github.com
7c6138b18ba34347a6ed0f6f84cf7b33df8e6db8
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/CodeJamData/15/04/15.cpp
d39ae3f0aba0d88589fac22d713847bf18eed626
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
1,307
cpp
#include <cstdio> #include <algorithm> #include <cstring> #define f(x, y, z) for(int x = (y); x <= (z); ++x) #define g(x, y, z) for(int x = (y); x < (z); ++x) #define h(x, y, z) for(int x = (y); x >= (z); --x) typedef long long LL; int ans[22][22][22]; // 1 - first win // 0 - first lose // -1 - not calculated yet int main(){ memset(ans, 0xff, sizeof(ans)); int cnt = 0; f(x, 1, 20) f(r, 1, 20) f(c, 1, 20) if(ans[x][r][c] == -1){ if(ans[x][c][r] != -1) ans[x][r][c] = ans[x][c][r]; else if(x >= 7) ans[x][r][c] = 1; else if(r * c % x != 0) ans[x][r][c] = 1; else if(r < x && c < x) ans[x][r][c] = 1; else if(r >= x && c >= x) ans[x][r][c] = 0; else if(x == 1) ans[x][r][c] = 0; else if(x == 2) ans[x][r][c] = 0; else if(x == 3) ans[x][r][c] = (r <= 1); else if(x == 4) ans[x][r][c] = (r <= 2); else if(x == 5){ if(r <= 2) ans[x][r][c] = 1; else if(r == 3) ans[x][r][c] = (c < 10); else ans[x][r][c] = 0; }else ans[x][r][c] = (r <= 3); } f(x, 1, 20) f(r, 1, 20) f(c, 1, 20) if(ans[x][r][c] < 0 || ans[x][r][c] > 1) printf("WTF?\n"); int T; scanf("%d", &T); f(_, 1, T){ int x, l, r; scanf("%d%d%d", &x, &l, &r); if(ans[x][l][r]) printf("Case #%d: RICHARD\n", _); else printf("Case #%d: GABRIEL\n", _); } return 0; }
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
b848584a7077e8b3214f1ff34c997aaa66334238
bae8345d8835227ae177fef069c0797f78112c05
/main.cpp
af190d50554e7c546f70f97b4419644fa2721933
[]
no_license
wutongjie23hao/personal-document-manage-system
8bf4f5bf199cc948bb9f42198cc15c1dccc65794
97833eb3e73b2c518784e6be4336d92ef5f016cc
refs/heads/master
2016-09-06T14:10:36.507705
2015-05-24T13:04:47
2015-05-24T13:04:47
35,885,023
0
0
null
null
null
null
UTF-8
C++
false
false
735
cpp
#include <QApplication> #include "mainwindow.h" #include "login.h" //#include "employeeform.h" //#include "mainform.h" #include <QSqlDatabase> #include <QMessageBox> #include <QSqlError> int main(int argc, char *argv[]) { QSqlDatabase dbconn = QSqlDatabase::addDatabase("QSQLITE"); dbconn.setDatabaseName("mytest8.db"); if(!dbconn.open()) { QMessageBox::critical(0, QObject::tr("Database Error"), dbconn.lastError().text()); return 0; } QApplication app(argc, argv); MainWindow *dialog = new MainWindow; LoginDlg loginDlg; if (loginDlg.exec()==QDialog::Accepted) { dialog->show(); return app.exec(); } else return 0; }
[ "840585194@qq.com" ]
840585194@qq.com