blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
abdaed1b9b8a17e05d4c80de39d70ffb5ed652f0
6145fc4a2b8aa73c79e9d607182936ff44014d82
/ex2/shader.hpp
7998ba7a5fcd6608fa6a42ce48c0266144c72a4c
[]
no_license
Treekay/Learn-CG
1af4ccd861b1d0588aed5dd5f675b62e9d99abc0
1fba1fdd64d941bee5157dbac148cdba93065bac
refs/heads/master
2020-04-27T01:36:55.378066
2019-06-13T04:06:55
2019-06-13T04:06:55
173,970,610
0
0
null
null
null
null
GB18030
C++
false
false
4,053
hpp
#ifndef SHADER_H #define SHADER_H #include <glad/glad.h>; // 包含glad来获取所有的必须OpenGL头文件 #include <string> #include <fstream> #include <sstream> #include <iostream> class Shader { public: // 程序ID unsigned int ID; // 构造器读取并构建着色器 Shader(const GLchar* vertexPath, const GLchar* fragmentPath) { // 1. 从文件路径中获取顶点/片段着色器 std::string vertexCode; std::string fragmentCode; std::ifstream vShaderFile; std::ifstream fShaderFile; // 保证ifstream对象可以抛出异常: vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { // 打开文件 vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // 读取文件的缓冲内容到数据流中 vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // 关闭文件处理器 vShaderFile.close(); fShaderFile.close(); // 转换数据流到string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); } catch (std::ifstream::failure e) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl; } const char* vShaderCode = vertexCode.c_str(); const char* fShaderCode = fragmentCode.c_str(); // 2. 编译着色器 unsigned int vertex, fragment; int success; char infoLog[512]; // 顶点着色器 vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); // 打印编译错误 glGetShaderiv(vertex, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertex, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; }; // 片段着色器 fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); // 打印编译错误 glGetShaderiv(fragment, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragment, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } // 着色器程序 ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); glLinkProgram(ID); // 打印连接错误(如果有的话) glGetProgramiv(ID, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(ID, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } // 删除着色器,它们已经链接到我们的程序中了,已经不再需要了 glDeleteShader(vertex); glDeleteShader(fragment); } // 使用/激活程序 void use() { glUseProgram(ID); } // uniform工具函数 void setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } void setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } void setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } private: // 检查着色器连接和编译错误 void checkCompileErrors(unsigned int shader, std::string type) { int success; char infoLog[1024]; if (type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } } }; #endif
[ "823334594@qq.com" ]
823334594@qq.com
b124b7717fe0280f9303fd9867fa49fa9eae2656
87759e4daae094217fd4c71e53857a0d6af4da59
/generated-tests/forward.cpp
94bbd7123d2907295f16e667de6af16351e79ddd
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
codexnetwork/eosio-wasm-spec-tests
0b87d1d5402f92442db01dabce912a286161f56e
db1c839233fad04e725ee500199faa131027c199
refs/heads/master
2020-09-10T02:12:53.992966
2019-11-12T15:51:18
2019-11-12T15:51:18
221,623,659
0
0
MIT
2019-11-14T06:02:25
2019-11-14T06:02:24
null
UTF-8
C++
false
false
824
cpp
#include <wasm_spec_tests.hpp> const string wasm_str_forward_0 = base_dir + "/eosio-wasm-spec-tests/generated-tests/wasms/forward.0.wasm"; std::vector<uint8_t> wasm_forward_0= read_wasm(wasm_str_forward_0.c_str()); BOOST_DATA_TEST_CASE(forward_0_pass, boost::unit_test::data::xrange(0,1), index) { try { TESTER tester; tester.produce_block(); tester.create_account( N(wasmtest) ); tester.produce_block(); tester.set_code(N(wasmtest), wasm_forward_0); tester.produce_block(); action test; test.account = N(wasmtest); test.name = account_name((uint64_t)index); test.authorization = {{N(wasmtest), config::active_name}}; push_action(tester, std::move(test), N(wasmtest).to_uint64_t()); tester.produce_block(); BOOST_REQUIRE_EQUAL( tester.validate(), true ); } FC_LOG_AND_RETHROW() }
[ "jeffreyssmith2nd@gmail.com" ]
jeffreyssmith2nd@gmail.com
20f542ad93b50143fc86759c3d5f5ddae4868795
452dafe3f2c76d22a33098634016c1e323456a67
/Problems/34B.cpp
bdef6eb74d0a66a903d92651d2f35d71b51ef5f5
[]
no_license
nikakogho/codeforces
6c87b4d7b640808813e405d5ce6e129bd527f5df
b6261f5a83e221de190f6daec3ba932e45d1acca
refs/heads/master
2023-03-21T19:34:58.401874
2021-03-06T15:49:16
2021-03-06T15:49:16
345,130,987
0
0
null
null
null
null
UTF-8
C++
false
false
258
cpp
#include <bits/stdc++.h> using namespace std; int main() { short n, m; cin >> n >> m; short arr[n]; for(int i = 0; i < n; i++) cin >> arr[i]; sort(arr, arr + n); int sum = 0; for(int i = 0; i < m && arr[i] < 0; i++) sum -= arr[i]; cout << sum; }
[ "nikakoghuashvili@gmail.com" ]
nikakoghuashvili@gmail.com
fd58dc025d200df297ea0f9d3e5d337d1bfc6b19
59f00d4f6fccb6b1103c5aa54f43a6e4d4f8bfc5
/src/common-plugin-analyze/MassBankToolsPlugin/cWizard/ExtDB/LinkDBAccessClass.cpp
3a91353ca6b35b9481b3cd7c3fa12e2fc7cd3332
[]
no_license
tomas-pluskal/masspp
9c9492443bb796533bcb27fe52a0a60e4ba62160
808bf095215e549e7eb5317c02c04dfb2ceaba15
refs/heads/master
2021-01-01T05:33:44.483127
2015-06-07T12:54:17
2015-06-07T12:54:17
33,917,190
0
1
null
null
null
null
SHIFT_JIS
C++
false
false
7,232
cpp
/** * @file DBAccessClass * @brief Data Processing List Box Informations * * @author M.Fukuda * @date 2013.02.26 * * Copyright(C) 2006-2014 Eisai Co., Ltd. All rights reserved. * * @ note -===================================== * Link DBの値を統括する。 * (has-a) DBACCSelectDialog : 選択のコンボボックス */ #include "../rel_stdafx.h" #include "LinkDBAccessClass.h" #include "LinkDBSelectDialog.h" #include "../calcFunc/StrFunc.h" #include "ExternalDbSearchDialog.h" #include "NameSelectToAccession.h" using namespace kome::massbank::wizard; #include <crtdbg.h> #ifdef _DEBUG #define new new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define malloc( s ) _malloc_dbg( s, _NORMAL_BLOCK, __FILE__, __LINE__ ) #endif // _DEBUG DBAccClass::DBAccClass() : DBLArr_() { init(); // 参考URLとして デモURLを合成して URL値に持っておく。 std::for_each(DBLArr_.begin(),DBLArr_.end(),[&](DBLinks& tgt){tgt.setURL("ACCESSION");}); } void DBAccClass::init() { DBLArr_.push_back(DBLinks("CAS", "http://webbook.nist.gov/cgi/cbook.cgi?Str2File=C","")); DBLArr_.push_back(DBLinks("CHEBI", "http://www.ebi.ac.uk/chebi/saveStructure.do?defaultImage=true&chebiId=","")); DBLArr_.push_back(DBLinks("CHEMSPIDER","http://www.chemspider.com/FilesHandler.ashx?type=str&striph=yes&id=","")); DBLArr_.push_back(DBLinks("KEGG", "http://www.genome.jp/dbget-bin/www_bget?-f+m+","")); DBLArr_.push_back(DBLinks("KNAPSACK", "http://knapsack3d.sakura.ne.jp/mol3d/",".3d.mol")); DBLArr_.push_back(DBLinks("LIPIDMAPS", "http://www.lipidmaps.org/data/LMSDRecord.php?LMID=","&Mode=Download")); DBLArr_.push_back(DBLinks("PUBCHEM", "http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=","&disopt=DisplaySDF")); kome::plugin::PluginManager& plgMgr = kome::plugin::PluginManager::getInstance(); unsigned int num = plgMgr.getNumberOfFunctionItems("EXTERNAL_DB"); for(unsigned int i = 0; i < num; i++) { // external DB kome::plugin::PluginFunctionItem* item = plgMgr.getFunctionItem("EXTERNAL_DB", i); if( item != NULL ) { void* pt = item->getCall()->invoke(NULL).prim.pt; kome::ident::ExternalDB* db = (kome::ident::ExternalDB*)pt; if (db != nullptr) { extDbs_.push_back(db); } } } } // 対象IDのDB名を返す(String) std::string DBAccClass::getNames(const unsigned int idx) const { return DBLArr_[idx].dbName; } // 対象IDのDB名を返す(const char*) const char* DBAccClass::getName(const unsigned int idx) const { return DBLArr_[idx].dbName.c_str(); } std::string DBAccClass::getsURL(const unsigned int idx) const { return DBLArr_[idx].dbName; } // 対象IDのURLをかえす。(デモURLが返る) const char* DBAccClass::getURL(const unsigned int idx) const { return DBLArr_[idx].URL.c_str(); } // Data List からの値(listStr)を分解して、 // ComboBoxの選択画面 (DBACCSelectDialog)を呼び出す。 // 何か選ばれたら、ルールに従って URLを合成して文字列として返す。 const std::string DBAccClass::setListArrStrs(const std::string& listStr) { if (listStr.empty() || listStr == "none") return ""; typedef std::pair<std::string, std::string> strPAIR; std::vector<strPAIR> dbcomArr; // DBName, AccessionのPair std::vector<std::string> lineTokens, innerTokens; // Data List からの値(listStr)を分解。コンボボックスの値の準備 kome::plugin::SettingsValue::separateListValue(listStr.c_str(), lineTokens); std::for_each(lineTokens.begin(), lineTokens.end(), [&](const std::string& tmp) { innerTokens.clear(); kome::plugin::SettingsValue::separateListValue(tmp.c_str(), innerTokens); std::string dbn = kome::plugin::SettingsValue::convertToDisplayingString(innerTokens[0].c_str()); std::string acc = kome::plugin::SettingsValue::convertToDisplayingString(innerTokens[1].c_str()); dbcomArr.push_back(strPAIR(dbn,acc)); }); // コンボボックスを表示。 // 登録順のIDを貰うルールなので登録後、(登録内部)でソートしないこと。 DBACCSelectDialog dlg(kome::window::WindowTool::getMainWindow(), dbcomArr); std::string URL(""); if(dlg.ShowModal() == wxID_OK) { // OKをクリックされたのでダイアログからIDを貰う。 int sid = dlg.getSelectId(); // 変な値かエラーが返ってきた。 if (sid < 0) return URL; std::string dbKey = ext::tranceLowerToUpper(dbcomArr.at(sid).first); std::string accKey = dbcomArr.at(sid).second; // DB名が一致するものをリストから探し、 // URLにアクセッションを挟み込んで URLとして返す。 // LINK に登録されたときに 大文字小文字で異なる可能性有。 URL = getURL(dbKey,accKey); } return URL; } const std::string DBAccClass::getURL( const std::string& exdb, const std::string& accession ) { std::string url(""); std::for_each(DBLArr_.begin(), DBLArr_.end(),[&](const DBLinks& dblks){ if(exdb.compare(dblks.dbName) == 0) { url = dblks.URLHead + accession + dblks.URLTail; }}); return url; } const bool DBAccClass::callSearchKeyWordtoExDB( std::string& searchedKeyword, std::vector<std::string>& refRsts ) { // get LinkDBArr from Panels SearchExternalDbDialog dlg(kome::window::WindowTool::getMainWindow(), extDbs_, searchedKeyword); if(dlg.ShowModal() == wxID_OK) { std::vector<kome::ident::ExternalDB*> extDbs; dlg.getExtDbs(extDbs); searchedKeyword = dlg.getSearchKeyword(); kome::window::DialogProgress progress( kome::window::WindowTool::getMainWindow(), "Get Extra DB.."); progress.setInformation("Information", "Get Extra DB.."); unsigned int extDbcount = extDbs.size(); progress.setRange(0, extDbcount); progress.setPosition(0); unsigned int progcnt(0); std::vector<kome::ident::ExternalDB::SearchResult> results; for each(auto& edb in extDbs) { progcnt++; progress.setPosition(progcnt); progress.setStatus( FMT("Access... %s [%d/%d]", edb->getName(), progcnt, extDbcount).c_str()); results.clear(); edb->search(results, searchedKeyword.c_str()); for each(auto& rst in results) { refRsts.push_back(edb->getName()); refRsts.push_back(rst.name); refRsts.push_back(rst.accession); } } progress.fill(); return true; } return false; } const bool DBAccClass::getKeyWordSearchResults( std::string& nameVal, std::string& linksVal, std::string& accURL ) { std::vector<std::string> refRsts; if(this->callSearchKeyWordtoExDB(searchedKeyword_, refRsts)) { NameSelectToAccessionDialog ddlg( kome::window::WindowTool::getMainWindow(), searchedKeyword_, refRsts); if(ddlg.ShowModal() == wxID_OK) { std::string extdb = ddlg.getDBName(); std::string accession = ddlg.getAccession(); accURL = getURL(extdb, accession); linksVal = "[[" + extdb + "]:[" + accession + "]]"; std::string tmp = "[" + ddlg.getInfoName() + "]"; tmp = replacestring(tmp.c_str(), ",", "\\,"); nameVal = tmp; return true; } } return false; }
[ "Satoshi Tanaka@localhost" ]
Satoshi Tanaka@localhost
c54c965f5f8f2dbcee8cbfa62964fc89ad6e62f3
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/enduser/netmeeting/t120/mst123/scfcall.cpp
96a1e3a2d8bf9fa179a79f180370cc567b7c9f14
[]
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
44,690
cpp
#include "precomp.h" DEBUG_FILEZONE(ZONE_T120_T123PSTN); /* SCFCall.cpp * * Copyright (c) 1994-1995 by DataBeam Corporation, Lexington, KY * * Abstract: * This class is instantiated by the SCF class. For each call that the * local site or remote site initiates, a SCFCall object is instantiated. * SCF can can manage 254 different calls simultaneously. For each call * there is a specific Q.933 based protocol that must occur to make the * connection valid. This object sends and receives the Q.933 packets. * * Private Instance Variables: * m_pSCF - Address of the owner of this object * Lower_Layer - Address of the layer below this layer * m_nMsgBase - The owner of this object gives it a base * number to use for OwnerCallbacks () * Maximum_Packet_Size - Maximum transmittable packet size * Packet_Pending - Tells which packet is to be transmitted * next. * Link_Originator - TRUE is this site initiated the call * * Write_Buffer - Address of write buffer * Send_Priority - TRUE if we are suppose to respond to the * priority requested by the remote site * * Call_Reference - Call reference number of this call. * DLCI - Holds the suggested and confirmed DLCI for * this call. * Priority - Holds the suggested and confirmed priority * for this call. * * State - Holds the current state of the call. * Release_Cause - Reason the the breakup of the link. * Default_Priority - Default priority of a non-specified call. * * T303_Timeout - T303 timeout value. * T303_Handle - System timer handle to T303 timer * T303_Active - TRUE if the timer is currently active * T303_Count - Number of T303 Timeouts * * T313_Timeout - T313 timeout value * T313_Handle - System timer handle to T313 timer * T313_Active - TRUE if the timer is currently active. * * Caveats: * None. * * Authors: * James W. Lawwill */ #include "scf.h" #include "scfcall.h" /* * SCFCall::SCFCall ( * PTransportResources transport_resources, * IObject * owner_object * IProtocolLayer * lower_layer, * USHORT message_base, * PDataLinkParameters datalink_struct, * PMemoryManager data_request_memory_manager, * BOOL * initialized) * * Public * * Functional Description: * This is the SCFCall constructor. This routine initializes all * variables and allocates write buffer space. */ SCFCall::SCFCall ( CLayerSCF *owner_object, IProtocolLayer * lower_layer, USHORT message_base, PDataLinkParameters datalink_struct, PMemoryManager data_request_memory_manager, BOOL * initialized) { TRACE_OUT(("SCFCall::SCFCall")); m_pSCF = owner_object; Lower_Layer = lower_layer; m_nMsgBase = message_base; Data_Request_Memory_Manager = data_request_memory_manager; *initialized = TRUE; DataLink_Struct.k_factor = datalink_struct->k_factor; DataLink_Struct.default_k_factor = datalink_struct->default_k_factor; DataLink_Struct.n201 = datalink_struct->n201; DataLink_Struct.default_n201 = datalink_struct->default_n201; /* ** T200 is represented in milliseconds, we need to convert it to ** tenths of seconds. */ DataLink_Struct.t200 = datalink_struct->t200 / 100; DataLink_Struct.default_t200 = datalink_struct->default_t200 / 100; Lower_Layer -> GetParameters ( &Maximum_Packet_Size, &Lower_Layer_Prepend, &Lower_Layer_Append); Packet_Pending = NO_PACKET; Link_Originator = FALSE; State = NOT_CONNECTED; Received_Priority = FALSE; Received_K_Factor = FALSE; Received_N201 = FALSE; Received_T200 = FALSE; DLC_Identifier = 0; T303_Active = FALSE; T313_Active = FALSE; /* ** Get configuration data */ T303_Timeout = DEFAULT_T303_TIMEOUT; T313_Timeout = DEFAULT_T313_TIMEOUT; Default_Priority = DEFAULT_PRIORITY; } /* * SCFCall::~SCFCall (void) * * Public * * Functional Description: * This is the SCFCall destructor. This routine cleans up the mess */ SCFCall::~SCFCall (void) { if (T303_Active) { StopTimerT303 (); } if (T313_Active) { StopTimerT313 (); } } /* * SCFCall::ConnectRequest ( * CallReference call_reference, * DLCI dlci, * USHORT priority) * * Public * * Functional Description: * This function is called when SCF wants to initiate a call. * As a result, we queue a SETUP command to be sent out. */ SCFCallError SCFCall::ConnectRequest( CallReference call_reference, DLCI dlci, TransportPriority priority) { TRACE_OUT(("SCFCall::ConnectRequest")); Call_Reference = call_reference; DLC_Identifier = dlci; Priority = priority; Link_Originator = TRUE; if (State == NOT_CONNECTED) Packet_Pending = SETUP; return (SCFCALL_NO_ERROR); } /* * SCFCallError SCFCall::ConnectResponse ( * BOOL valid_dlci) * * Public * * Functional Description: * This function is called in response to a NETWORK_CONNECT_INDICATION * callback to the owner of this object. Previously, the remote site * sent us a SETUP packet with a suggested DLCI. This DLCI is sent to * the owner in the NETWORK_CONNECT_INDICATION call. The owner calls * this function with a BOOL , telling us if the DLCI was valid. */ SCFCallError SCFCall::ConnectResponse ( BOOL valid_dlci) { TRACE_OUT(("SCFCall::ConnectResponse")); if (valid_dlci) { /* ** This DLCI can be used in a link. If the remote site did not ** request a priority, we set it to Default_Priority */ if (Priority == 0xffff) Priority = Default_Priority; Packet_Pending = CONNECT; } else { /* ** Queue up a RELEASE COMPLETE packet */ Packet_Pending = RELEASE_COMPLETE; Release_Cause = REQUESTED_CHANNEL_UNAVAILABLE; } return (SCFCALL_NO_ERROR); } /* * SCFCallError SCFCall::DisconnectRequest () * * Public * * Functional Description: * This function is called when the SCF wants to terminate the call */ SCFCallError SCFCall::DisconnectRequest () { TRACE_OUT(("SCFCall::DisconnectRequest")); /* ** Queue up the Release Complete */ if (State != NOT_CONNECTED) { Packet_Pending = RELEASE_COMPLETE; Release_Cause = NORMAL_USER_DISCONNECT; } return (SCFCALL_NO_ERROR); } /* * BOOL SCFCall::ProcessSetup ( * CallReference call_reference, * LPBYTE packet_address, * USHORT packet_length) * * Public * * Functional Description: * This function processes an incoming SETUP packet */ BOOL SCFCall::ProcessSetup ( CallReference call_reference, LPBYTE packet_address, USHORT packet_length) { USHORT length; BOOL packet_successful; USHORT remainder_length; USHORT n201; USHORT k_factor; USHORT t200; NetworkConnectStruct connect_struct; TRACE_OUT(("SCFCall::ProcessSetup")); if (State != NOT_CONNECTED) return (FALSE); Call_Reference = call_reference; packet_successful = TRUE; remainder_length = packet_length; /* ** Bearer capability element */ if (*(packet_address++) != BEARER_CAPABILITY) return (FALSE); remainder_length--; length = *(packet_address++); remainder_length--; if (length != 3) return (FALSE); /* ** Verify that the Bearer Capability is correct */ if (*(packet_address) != (EXTENSION | CODING_STANDARD | INFORMATION_TRANSFER_CAPABILITY)) { return (FALSE); } if (*(packet_address + 1) != (EXTENSION | TRANSFER_MODE)) { return (FALSE); } if (*(packet_address + 2) != (EXTENSION | LAYER_2_IDENT | USER_INFORMATION_LAYER_2)) { return (FALSE); } packet_address += length; remainder_length -= length; /* ** DLCI element */ if (*(packet_address++) != DLCI_ELEMENT) return (FALSE); remainder_length--; length = *(packet_address++); if (length != 2) return (FALSE); remainder_length--; /* ** If the Preferred/Exclusive bit is set, its illegal */ if (((*(packet_address) & PREFERRED_EXCLUSIVE) == PREFERRED_EXCLUSIVE) || ((*(packet_address + 1) & EXTENSION) == 0)) { return (FALSE); } DLC_Identifier = (*(packet_address) & 0x3f) << 4; DLC_Identifier |= ((*(packet_address + 1) & 0x78) >> 3); packet_address += length; remainder_length -= length; Priority = 0xffff; /* ** Go thru each of the elements and decode them */ while (remainder_length) { switch (*(packet_address++)) { case X213_PRIORITY: length = *(packet_address++); remainder_length--; if (((*(packet_address) & EXTENSION) == 1) || ((*(packet_address + 1) & EXTENSION) == 0)) { ERROR_OUT(("SCFCall: ProcessSetup: SETUP packet: Illegal X.213 priority")); return (FALSE); } Priority = (*packet_address & 0x0f); packet_address += length; remainder_length -= length; Received_Priority = TRUE; break; case LINK_LAYER_CORE_PARAMETERS: length = *(packet_address++); remainder_length -= (length + 1); while (length) { switch (*(packet_address++)) { case FMIF_SIZE: /* ** N201 is a Q922 parameter. It is the number of ** maximum information bytes in a packet */ n201 = ((*packet_address << 7) | (*(packet_address + 1) & 0x7f)); if ((*(packet_address+1) & EXTENSION) == EXTENSION) { length -= 2; packet_address += 2; } else { packet_address += 4; length -= 4; } /* ** If the requested n201 value is less than our ** value, it will be our new N201, otherwise send ** our N201 back as the arbitrated value. */ if (n201 < DataLink_Struct.n201) DataLink_Struct.n201 = n201; Received_N201 = TRUE; TRACE_OUT(("SCFCALL: ProcessSetup: n201 = %d", DataLink_Struct.n201)); break; default: while ((*(packet_address++) & EXTENSION) == 0) length--; length--; break; } length--; } break; case LINK_LAYER_PROTOCOL_PARAMETERS: length = *(packet_address++); remainder_length -= (length + 1); while (length) { switch (*(packet_address++)) { case TRANSMIT_WINDOW_SIZE_IDENTIFIER: /* ** The Window size is the maximum number of ** outstanding packets at any one time */ k_factor = *packet_address & 0x7f; packet_address++; length--; /* ** If the requested k_factor value is less than our ** value, it will be our new k_factor, otherwise ** send our k_factor back as the arbitrated value. */ if (k_factor < DataLink_Struct.k_factor) DataLink_Struct.k_factor = k_factor; Received_K_Factor = TRUE; TRACE_OUT(("SCFCALL: ProcessSetup: k_factor = %d", DataLink_Struct.k_factor)); break; case RETRANSMISSION_TIMER_IDENTIFIER: /* ** t200 is the timeout value before retransmission */ t200 = ((*packet_address << 7) | (*(packet_address + 1) & 0x7f)); packet_address += 2; length -= 2; /* ** If the requested t200 value is too small, ** value, it will be our new T200, otherwise ** send our T200 back as the arbitrated value. */ if (t200 > DataLink_Struct.t200) DataLink_Struct.t200 = t200; Received_T200 = TRUE; TRACE_OUT(("SCFCALL: ProcessSetup: t200 = %d", DataLink_Struct.t200)); break; default: while ((*(packet_address++) & EXTENSION) == 0) length--; length--; break; } length--; } break; case END_TO_END_DELAY: case CALLING_PARTY_SUBADDRESS: case CALLED_PARTY_SUBADDRESS: default: TRACE_OUT(("SCFCall: ProcessSetup: SETUP packet: Option 0x%x" "requested, but not supported", *(packet_address-1))); length = *(packet_address); packet_address += (length + 1); remainder_length -= (length + 1); break; } remainder_length--; } if (Received_N201 == FALSE) DataLink_Struct.n201 = DataLink_Struct.default_n201; if (Received_K_Factor == FALSE) DataLink_Struct.k_factor = DataLink_Struct.default_k_factor; if (Received_T200 == FALSE) DataLink_Struct.t200 = DataLink_Struct.default_t200; if (packet_successful) { /* ** If the packet was successfully decoded, tell the owner the requested ** DLCI and priority. */ connect_struct.dlci = DLC_Identifier; connect_struct.priority = Priority; connect_struct.datalink_struct = &DataLink_Struct; /* ** Convert t200 into milliseconds */ DataLink_Struct.t200 *= 100; m_pSCF->OwnerCallback(m_nMsgBase + NETWORK_CONNECT_INDICATION, 0, 0, &connect_struct); DataLink_Struct.t200 /= 100; } return (packet_successful); } /* * BOOL SCFCall::ProcessConnect ( * LPBYTE packet_address, * USHORT packet_length) * * Public * * Functional Description: * This function processes an incoming CONNECT packet */ BOOL SCFCall::ProcessConnect ( LPBYTE packet_address, USHORT packet_length) { TRACE_OUT(("SCFCall::ProcessConnect")); BOOL packet_successful; USHORT length; DLCI exclusive_dlci; USHORT remainder_length; USHORT k_factor; USHORT t200; if (State != SETUP_SENT) { ERROR_OUT(("SCFCall: ProcessConnect: Call in wrong state")); return (FALSE); } remainder_length = packet_length; packet_successful = TRUE; /* ** DLCI element */ if (*(packet_address++) != DLCI_ELEMENT) { ERROR_OUT(("SCFCall: ProcessConnect: DLCI_ELEMENT not in packet")); return (FALSE); } remainder_length--; length = *(packet_address++); if (length != 2) { ERROR_OUT(("SCFCall: ProcessConnect: DLCI length must be 2")); return (FALSE); } remainder_length--; /* ** If the Preferred/Exclusive bit is not set, its illegal */ if (((*(packet_address) & PREFERRED_EXCLUSIVE) == 0) || ((*(packet_address + 1) & EXTENSION) == 0)) { ERROR_OUT(("SCFCall: CONNECT: Illegal DLCI")); return (FALSE); } /* ** Get the DLCI */ exclusive_dlci = (*(packet_address) & 0x3f) << 4; exclusive_dlci |= ((*(packet_address + 1) & 0x78) >> 3); packet_address += length; remainder_length -= length; /* ** Go thru each of the elements and decode them */ while (remainder_length != 0) { switch (*(packet_address++)) { case X213_PRIORITY: length = *(packet_address++); remainder_length--; if ((*(packet_address) & EXTENSION) == 0) { ERROR_OUT(("SCFCall: DataIndication: CONNECT packet: Illegal X.213 priority")); return (FALSE); } Priority = (*packet_address & 0x0f); packet_address += length; remainder_length -= length; break; case LINK_LAYER_CORE_PARAMETERS: length = *(packet_address++); remainder_length -= (length + 1); while (length) { switch (*(packet_address++)) { case FMIF_SIZE: /* ** FMIF_Size is the max. number of bytes allowed in ** a information packet */ DataLink_Struct.n201 = ((*packet_address << 7) | (*(packet_address + 1) & 0x7f)); if ((*(packet_address+1) & EXTENSION) == EXTENSION) { length -= 2; packet_address += 2; } else { packet_address += 4; length -= 4; } Received_N201 = TRUE; TRACE_OUT(("SCFCALL: ProcessConnect: n201 = %d", DataLink_Struct.n201)); break; default: while ((*(packet_address++) & EXTENSION) == 0) length--; length--; break; } length--; } break; case LINK_LAYER_PROTOCOL_PARAMETERS: length = *(packet_address++); remainder_length -= (length + 1); while (length) { switch (*(packet_address++)) { case TRANSMIT_WINDOW_SIZE_IDENTIFIER: /* ** The Window size is the maximum number of ** outstanding packets at any one time */ k_factor = *packet_address & 0x7f; packet_address++; length--; DataLink_Struct.k_factor = k_factor; Received_K_Factor = TRUE; TRACE_OUT(("SCFCALL: ProcessConnect: k_factor = %d", DataLink_Struct.k_factor)); break; case RETRANSMISSION_TIMER_IDENTIFIER: /* ** t200 is the timeout value before retransmission */ t200 = ((*packet_address << 7) | (*(packet_address + 1) & 0x7f)); packet_address += 2; length -= 2; DataLink_Struct.t200 = t200; Received_T200 = TRUE; TRACE_OUT(("SCFCALL: ProcessConnect: t200 = %d", DataLink_Struct.t200)); break; default: while ((*(packet_address++) & EXTENSION) == 0) length--; length--; break; } length--; } break; case END_TO_END_DELAY: case CALLING_PARTY_SUBADDRESS: case CALLED_PARTY_SUBADDRESS: default: TRACE_OUT(("SCFCall: DataIndication: CONNECT packet: Option " "requested, but not supported", *(packet_address-1))); length = *(packet_address++); remainder_length--; packet_address += length; remainder_length -= length; break; } remainder_length--; } if (Received_N201 == FALSE) DataLink_Struct.n201 = DataLink_Struct.default_n201; if (Received_K_Factor == FALSE) DataLink_Struct.k_factor = DataLink_Struct.default_k_factor; if (Received_T200 == FALSE) DataLink_Struct.t200 = DataLink_Struct.default_t200; /* ** If the packet was successfully decoded, queue up the CONNECT ACK */ if (packet_successful) { Packet_Pending = CONNECT_ACKNOWLEDGE; StopTimerT303 (); } return (packet_successful); } /* * BOOL SCFCall::ProcessConnectAcknowledge ( * LPBYTE, * USHORT) * * Public * * Functional Description: * This function processes an incoming CONNECT ACK packet * */ BOOL SCFCall::ProcessConnectAcknowledge ( LPBYTE, USHORT) { TRACE_OUT(("SCFCall::ProcessConnectAcknowledge")); if (State != CONNECT_SENT) return (FALSE); StopTimerT313 (); return (TRUE); } /* * BOOL SCFCall::ProcessReleaseComplete ( * LPBYTE packet_address, * USHORT) * * Public * * Functional Description: * This function processes an incoming RELEASE COMPLETE */ BOOL SCFCall::ProcessReleaseComplete ( LPBYTE packet_address, USHORT) { TRACE_OUT(("SCFCall::ProcessReleaseComplete")); USHORT cause = 0; if (State == NOT_CONNECTED) return (FALSE); if (*(packet_address++) == CAUSE) { packet_address++; if ((*(packet_address++) & EXTENSION) == 0) packet_address++; cause = *(packet_address++) & (~EXTENSION); TRACE_OUT(("SCFCall: Disconnect: cause = %d", cause)); } State = NOT_CONNECTED; /* ** Tell the owner about the Disconnection */ m_pSCF->OwnerCallback(m_nMsgBase + NETWORK_DISCONNECT_INDICATION, (void *) DLC_Identifier, (void *) (ULONG_PTR)(((Link_Originator << 16) | cause))); return (TRUE); } /* * void SCFCall::PollTransmitter ( * USHORT data_to_transmit, * USHORT * pending_data); * * Public * * Functional Description: * This function is called to transmit any queued up packets */ void SCFCall::PollTransmitter ( USHORT data_to_transmit, USHORT * pending_data) { // TRACE_OUT(("SCFCall::PollTransmitter")); NetworkConnectStruct connect_struct; if (data_to_transmit & PROTOCOL_CONTROL_DATA) { switch (Packet_Pending) { case SETUP: SendSetup (); break; case CONNECT: SendConnect (); break; case CONNECT_ACKNOWLEDGE: SendConnectAcknowledge (); if (Packet_Pending != CONNECT_ACKNOWLEDGE) { /* ** If the CONNECT ACK packet was sent, notify the owner */ connect_struct.dlci = DLC_Identifier; connect_struct.priority = Priority; connect_struct.datalink_struct = &DataLink_Struct; /* ** Convert t200 to milliseconds */ DataLink_Struct.t200 *= 100; m_pSCF->OwnerCallback(m_nMsgBase + NETWORK_CONNECT_CONFIRM, 0, 0, &connect_struct); DataLink_Struct.t200 /= 100; } break; case RELEASE_COMPLETE: SendReleaseComplete (); if (Packet_Pending != RELEASE_COMPLETE) { /* ** If the RELEASE COMPLETE packet was sent, notify ** the owner */ m_pSCF->OwnerCallback(m_nMsgBase + NETWORK_DISCONNECT_INDICATION, (void *) DLC_Identifier, (void *) ((((ULONG_PTR) Link_Originator) << 16) | Release_Cause)); } break; } if (Packet_Pending != NO_PACKET) *pending_data = PROTOCOL_CONTROL_DATA; else *pending_data = 0; } return; } /* * void SCFCall::SendSetup (void); * * Functional Description * This function attempts to send out a SETUP packet. The T303 timer * is started. If a CONNECT is not received before the timer expires, * we terminate the link. * * Formal Parameters * None * * Return Value * None * * Side Effects * If this function is able to send a SETUP packet to the lower layer, * it sets the Packet_Pending variable to NO_PACKET * * Caveats * None */ void SCFCall::SendSetup (void) { TRACE_OUT(("SCFCall::SendSetup")); LPBYTE packet_address; ULONG bytes_accepted; USHORT total_length; PMemory memory; total_length = SETUP_PACKET_SIZE + Lower_Layer_Prepend + Lower_Layer_Append; memory = Data_Request_Memory_Manager -> AllocateMemory ( NULL, total_length); if (memory == NULL) return; packet_address = memory -> GetPointer (); packet_address += Lower_Layer_Prepend; *(packet_address++) = Q931_PROTOCOL_DISCRIMINATOR; *(packet_address++) = 1; *(packet_address++) = (UChar) Call_Reference; *(packet_address++) = SETUP; /* ** Bearer Capability */ *(packet_address++) = BEARER_CAPABILITY; *(packet_address++) = 3; *(packet_address++) = EXTENSION | CODING_STANDARD | INFORMATION_TRANSFER_CAPABILITY; *(packet_address++) = EXTENSION | TRANSFER_MODE; *(packet_address++) = EXTENSION | LAYER_2_IDENT | USER_INFORMATION_LAYER_2; /* ** DLCI */ *(packet_address++) = DLCI_ELEMENT; *(packet_address++) = 2; *(packet_address++) = (DLC_Identifier >> 4); *(packet_address++) = EXTENSION | ((DLC_Identifier & 0x0f) << 3); /* ** Link Layer Core Parameters */ *(packet_address++) = LINK_LAYER_CORE_PARAMETERS; *(packet_address++) = 3; *(packet_address++) = FMIF_SIZE; *(packet_address++) = (DataLink_Struct.n201 >> 7); *(packet_address++) = EXTENSION | (DataLink_Struct.n201 & 0x7f); /* ** Link Layer Protocol Parameters */ *(packet_address++) = LINK_LAYER_PROTOCOL_PARAMETERS; *(packet_address++) = 5; *(packet_address++) = TRANSMIT_WINDOW_SIZE_IDENTIFIER; *(packet_address++) = EXTENSION | DataLink_Struct.k_factor; *(packet_address++) = RETRANSMISSION_TIMER_IDENTIFIER; *(packet_address++) = (DataLink_Struct.t200 >> 7) & 0x7f; *(packet_address++) = EXTENSION | (DataLink_Struct.t200 & 0x7f); /* ** X.213 Priority */ *(packet_address++) = X213_PRIORITY; *(packet_address++) = 2; *(packet_address++) = (UChar) Priority; /* ** The next byte contains the lowest priority acceptable, 0 */ *(packet_address++) = EXTENSION | 0; /* ** Attempt to send the packet down */ Lower_Layer -> DataRequest ( 0, memory, &bytes_accepted); if (bytes_accepted == total_length) { T303_Count = 0; Packet_Pending = NO_PACKET; State = SETUP_SENT; StartTimerT303 (); } Data_Request_Memory_Manager -> FreeMemory (memory); } /* * void SCFCall::SendConnect (void); * * Functional Description * This function attempts to send out a CONNECT packet. The T313 timer * is started. If a CONNECT ACK is not received before the timer expires, * we terminate the link. * * Formal Parameters * None * * Return Value * None * * Side Effects * If this function is able to send a CONNECT packet to the lower layer, * it sets the Packet_Pending variable to NO_PACKET * * Caveats * None * */ void SCFCall::SendConnect (void) { TRACE_OUT(("SCFCall::SendConnect")); LPBYTE packet_address; LPBYTE length_address; ULONG bytes_accepted; USHORT total_length; PMemory memory; total_length = CONNECT_PACKET_BASE_SIZE + Lower_Layer_Prepend + Lower_Layer_Append; if (Received_N201) total_length += 5; if (Received_K_Factor || Received_T200) { total_length += 2; if (Received_K_Factor) total_length += 2; if (Received_T200) total_length += 3; } if (Received_Priority) total_length += 3; /* ** Prepare the CONNECT command and send it to the lower layer */ memory = Data_Request_Memory_Manager -> AllocateMemory ( NULL, total_length); if (memory == NULL) return; packet_address = memory -> GetPointer (); packet_address += Lower_Layer_Prepend; *(packet_address++) = Q931_PROTOCOL_DISCRIMINATOR; *(packet_address++) = 1; *(packet_address++) = REMOTE_CALL_REFERENCE | Call_Reference; *(packet_address++) = CONNECT; /* ** DLCI */ *(packet_address++) = DLCI_ELEMENT; *(packet_address++) = 2; *(packet_address++) = PREFERRED_EXCLUSIVE | (DLC_Identifier >> 4); *(packet_address++) = EXTENSION | ((DLC_Identifier & 0x0f) << 3); if (Received_N201) { /* ** Link Layer Core Parameters */ *(packet_address++) = LINK_LAYER_CORE_PARAMETERS; *(packet_address++) = 3; *(packet_address++) = FMIF_SIZE; *(packet_address++) = (DataLink_Struct.n201 >> 7); *(packet_address++) = EXTENSION | (DataLink_Struct.n201 & 0x7f); } else DataLink_Struct.n201 = DataLink_Struct.default_n201; if (Received_K_Factor || Received_T200) { /* ** Link Layer Protocol Parameters */ *(packet_address++) = LINK_LAYER_PROTOCOL_PARAMETERS; length_address = packet_address; *(packet_address++) = 0; if (Received_K_Factor) { *length_address += 2; *(packet_address++) = TRANSMIT_WINDOW_SIZE_IDENTIFIER; *(packet_address++) = EXTENSION | DataLink_Struct.k_factor; } if (Received_T200) { *length_address += 3; *(packet_address++) = RETRANSMISSION_TIMER_IDENTIFIER; *(packet_address++) = (DataLink_Struct.t200 >> 7) & 0x7f; *(packet_address++) = EXTENSION | (DataLink_Struct.t200 & 0x7f); } } if (Received_K_Factor == FALSE) DataLink_Struct.k_factor = DataLink_Struct.default_k_factor; if (Received_T200 == FALSE) DataLink_Struct.t200 = DataLink_Struct.default_t200; if (Received_Priority) { /* ** X.213 Priority */ *(packet_address++) = X213_PRIORITY; *(packet_address++) = 1; *(packet_address++) = (BYTE) (EXTENSION | Priority); } /* ** Attempt to send the packet to the lower layer */ Lower_Layer -> DataRequest ( 0, memory, &bytes_accepted); if (bytes_accepted == total_length) { StartTimerT313 (); Packet_Pending = NO_PACKET; State = CONNECT_SENT; } Data_Request_Memory_Manager -> FreeMemory (memory); } /* * void SCFCall::SendConnectAcknowledge (void); * * Functional Description * This function attempts to send out a CONNECT ACKNOWLEDGE packet * * Formal Parameters * None * * Return Value * None * * Side Effects * If this function is able to send the packet to the lower layer, * it sets the Packet_Pending variable to NO_PACKET * * Caveats * None * */ void SCFCall::SendConnectAcknowledge (void) { TRACE_OUT(("SCFCall::SendConnectAcknowledge")); LPBYTE packet_address; USHORT total_length; PMemory memory; ULONG bytes_accepted; total_length = CONNECT_ACK_PACKET_SIZE + Lower_Layer_Prepend + Lower_Layer_Append; /* ** Prepare the command and send it to the lower layer */ memory = Data_Request_Memory_Manager -> AllocateMemory ( NULL, total_length); if (memory == NULL) return; packet_address = memory -> GetPointer (); packet_address += Lower_Layer_Prepend; *(packet_address++) = Q931_PROTOCOL_DISCRIMINATOR; *(packet_address++) = 1; *(packet_address++) = (UChar) Call_Reference; *(packet_address++) = CONNECT_ACKNOWLEDGE; Lower_Layer -> DataRequest ( 0, memory, &bytes_accepted); if (bytes_accepted == total_length) { State = CALL_ESTABLISHED; Packet_Pending = NO_PACKET; } Data_Request_Memory_Manager -> FreeMemory (memory); } /* * void SCFCall::SendReleaseComplete (void); * * Functional Description * This function attempts to send out a RELEASE COMPLETE packet * * Formal Parameters * None * * Return Value * None * * Side Effects * If this function is able to send a RELEASE COMPLETE packet to the lower * layer, it sets the Packet_Pending variable to NO_PACKET * * Caveats * None * */ void SCFCall::SendReleaseComplete (void) { TRACE_OUT(("SCFCall::SendReleaseComplete")); LPBYTE packet_address; ULONG bytes_accepted; USHORT total_length; PMemory memory; total_length = RELEASE_COMPLETE_PACKET_SIZE + Lower_Layer_Prepend + Lower_Layer_Append; /* ** Prepare the command and send it to the lower layer */ memory = Data_Request_Memory_Manager -> AllocateMemory ( NULL, total_length); if (memory == NULL) return; packet_address = memory -> GetPointer (); packet_address += Lower_Layer_Prepend; *(packet_address++) = Q931_PROTOCOL_DISCRIMINATOR; *(packet_address++) = 1; if (Link_Originator) *(packet_address++) = (UChar) Call_Reference; else *(packet_address++) = 0x80 | Call_Reference; *(packet_address++) = RELEASE_COMPLETE; /* ** Append the CAUSE for the link breakup */ *(packet_address++) = CAUSE; *(packet_address++) = 2; *(packet_address++) = EXTENSION; *(packet_address++) = EXTENSION | Release_Cause; Lower_Layer -> DataRequest ( 0, memory, &bytes_accepted); if (bytes_accepted == total_length) { State = NOT_CONNECTED; Packet_Pending = NO_PACKET; } Data_Request_Memory_Manager -> FreeMemory (memory); } /* * void SCFCall::StartTimerT303 (void); * * Functional Description * This function Starts the T303 Timer. This is started when we send * out the SETUP packet. It is stopped when we receive a CONNECT * packet. If it expires we terminate the link. * * Formal Parameters * None * * Return Value * None * * Side Effects * None * * Caveats * None * */ void SCFCall::StartTimerT303 (void) { TRACE_OUT(("SCFCall::StartTimerT303")); if (T303_Active) StopTimerT303 (); T303_Handle = g_pSystemTimer->CreateTimerEvent( T303_Timeout, TIMER_EVENT_ONE_SHOT, this, (PTimerFunction) &SCFCall::T303Timeout); T303_Active = TRUE; } /* * void SCFCall::StopTimerT303 (void); * * Functional Description * This function stops the T303 Timer. This is called when we receive * the CONNECT packet. As a result, we stop the timer. * * Formal Parameters * None * * Return Value * None * * Side Effects * None * * Caveats * None * */ void SCFCall::StopTimerT303 (void) { TRACE_OUT(("SCFCall::StopTimerT303")); if (T303_Active) { g_pSystemTimer->DeleteTimerEvent(T303_Handle); T303_Active = FALSE; } } /* * void SCFCall::T303Timeout ( * TimerEventHandle); * * Functional Description * This function is called by the System timer when the T303 timeout * expires. As a result, we terminate the link. * * Formal Parameters * None used * * Return Value * None * * Side Effects * None * * Caveats * None * */ void SCFCall::T303Timeout ( TimerEventHandle) { TRACE_OUT(("SCFCall: T303Timeout")); if (T303_Count >= 1) State = NOT_CONNECTED; T303_Count++; Packet_Pending = RELEASE_COMPLETE; Release_Cause = NORMAL_USER_DISCONNECT; } /* * void SCFCall::StartTimerT313 (void); * * Functional Description * This function Starts the T313 Timer. This is started when we send * out the CONNECT packet. It is stopped when we receive a CONNECT ACK * packet. If it expires we terminate the link. * * Formal Parameters * None * * Return Value * None * * Side Effects * None * * Caveats * None * */ void SCFCall::StartTimerT313 (void) { TRACE_OUT(("SCFCall: StartTimerT313")); if (T313_Active) StopTimerT313 (); T313_Handle = g_pSystemTimer->CreateTimerEvent( T313_Timeout, TIMER_EVENT_ONE_SHOT, this, (PTimerFunction) &SCFCall::T313Timeout); T313_Active = TRUE; } /* * void SCFCall::StopTimerT313 (void); * * Functional Description * This function stops the T313 Timer. This is called when we receive * the CONNECT ACK packet. As a result, we stop the timer. * * Formal Parameters * None * * Return Value * None * * Side Effects * None * * Caveats * None * */ void SCFCall::StopTimerT313 (void) { TRACE_OUT(("SCFCall: StopTimerT313")); if (T313_Active) { g_pSystemTimer->DeleteTimerEvent(T313_Handle); T313_Active = FALSE; } } /* * void SCFCall::T313Timeout ( * TimerEventHandle); * * Functional Description * This function is called by the System timer when the T313 timeout * expires. As a result, we terminate the link. * * Formal Parameters * None used * * Return Value * None * * Side Effects * None * * Caveats * None * */ void SCFCall::T313Timeout ( TimerEventHandle) { TRACE_OUT(("SCFCall: T313Timeout")); State = NOT_CONNECTED; Packet_Pending = RELEASE_COMPLETE; Release_Cause = NORMAL_USER_DISCONNECT; }
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
17485ae21398e1fa4aaa6343d03f4d07215ee1fa
a12d23f3349de5e460fdd577d458e7ab2f4e1046
/CF Global Round 15 - Subsequence Permutation (A).cpp
224f89329c190b38f2c79324ef3e5a4006b17567
[]
no_license
TheKing003KS/Codeforces-Solutions
17a1580f492c5f3a6f8ea368fa2e183ab70266c4
74f4920d4f009eadbdf8a558989c2917fd1bce85
refs/heads/main
2023-07-26T13:09:05.909928
2021-08-23T07:29:28
2021-08-23T07:29:28
398,503,592
1
0
null
null
null
null
UTF-8
C++
false
false
1,153
cpp
// Problem Link: https://codeforces.com/contest/1552/problem/A #include<iostream> #include<limits.h> #include<math.h> #include<vector> #include<string> #include<queue> #include<stack> #include<set> #include<map> #include<unordered_set> #include<unordered_map> #include<algorithm> using namespace std; #define ll long long int #define ull unsigned long long int #define modulo 1000000007 #define mp make_pair #define pb push_back int main() { ll tests; cin >> tests; while(tests--) { int n; cin >> n; string str; cin >> str; vector<int> tab(26,0); for(int i = 0; i < n; i++) { tab[str[i]-'a']++; } string temp; for(int i = 0; i < 26; i++) { while(tab[i] > 0) { temp += ('a'+i); tab[i]--; } } int count = 0; for(int i = 0; i < str.length(); i++) { if(str[i] != temp[i]) {count++;} } cout << count; cout << "\n"; } return 0; }
[ "noreply@github.com" ]
TheKing003KS.noreply@github.com
50815dd4cdbf43e4f8d974ca98fe4f5262c73912
51fe8343b5e3fe8de4e379bd3b48fb1f165c76f8
/OpenGL/Classes/UniformDerived.cpp
359805d6b3ef64d2970d4bf3756c8f6cbd2d9b38
[]
no_license
belazaras/teardrop
961c5c59e490ea939781d31f708954e7f31fd671
0a92714538d3be67d4d4b17734f92d805fc6030d
refs/heads/master
2021-01-01T05:41:12.641750
2015-08-11T11:00:44
2015-08-11T11:00:44
39,625,019
0
1
null
null
null
null
UTF-8
C++
false
false
237
cpp
#include "UniformDerived.h" // Specializations: void UniformFloat::updateImpl(GLuint location) { //glUniform1f(); } //void UniformFVec3::updateImpl(GLuint location) //{ // glUniform3f(location, 1, GL_FALSE, (GLfloat)*m_elements); //}
[ "belazaras@live.com" ]
belazaras@live.com
2cd745fc908dfd889ed846bb2050b08a241a919a
4a598ca49e4be7c15609a94df9118bf2974a1318
/src/walletdb.cpp
772e46d18331bedbb573fbfb9184655c45f39ef8
[ "MIT" ]
permissive
LordSoylent/SMNCoin
b41796e0dbb5484a7fa0821d2e273e198f8c9aff
01918f456f726a9240df4ccfffdd3626f9ddba4f
refs/heads/master
2020-03-28T19:23:47.897382
2018-06-05T00:17:59
2018-06-05T00:17:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
44,603
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletdb.h" #include "base58.h" #include "protocol.h" #include "serialize.h" #include "sync.h" #include "util.h" #include "utiltime.h" #include "wallet.h" #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/scoped_ptr.hpp> #include <boost/thread.hpp> #include <fstream> using namespace boost; using namespace std; static uint64_t nAccountingEntryNumber = 0; // // CWalletDB // bool CWalletDB::WriteName(const string& strAddress, const string& strName) { nWalletDBUpdated++; return Write(make_pair(string("name"), strAddress), strName); } bool CWalletDB::EraseName(const string& strAddress) { // This should only be used for sending addresses, never for receiving addresses, // receiving addresses must always have an address book entry if they're not change return. nWalletDBUpdated++; return Erase(make_pair(string("name"), strAddress)); } bool CWalletDB::WritePurpose(const string& strAddress, const string& strPurpose) { nWalletDBUpdated++; return Write(make_pair(string("purpose"), strAddress), strPurpose); } bool CWalletDB::ErasePurpose(const string& strPurpose) { nWalletDBUpdated++; return Erase(make_pair(string("purpose"), strPurpose)); } bool CWalletDB::WriteTx(uint256 hash, const CWalletTx& wtx) { nWalletDBUpdated++; return Write(std::make_pair(std::string("tx"), hash), wtx); } bool CWalletDB::EraseTx(uint256 hash) { nWalletDBUpdated++; return Erase(std::make_pair(std::string("tx"), hash)); } bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta) { nWalletDBUpdated++; if (!Write(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta, false)) return false; // hash pubkey/privkey to accelerate wallet load std::vector<unsigned char> vchKey; vchKey.reserve(vchPubKey.size() + vchPrivKey.size()); vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end()); vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end()); return Write(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false); } bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata& keyMeta) { const bool fEraseUnencryptedKey = true; nWalletDBUpdated++; if (!Write(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta)) return false; if (!Write(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false)) return false; if (fEraseUnencryptedKey) { Erase(std::make_pair(std::string("key"), vchPubKey)); Erase(std::make_pair(std::string("wkey"), vchPubKey)); } return true; } bool CWalletDB::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey) { nWalletDBUpdated++; return Write(std::make_pair(std::string("mkey"), nID), kMasterKey, true); } bool CWalletDB::WriteCScript(const uint160& hash, const CScript& redeemScript) { nWalletDBUpdated++; return Write(std::make_pair(std::string("cscript"), hash), redeemScript, false); } bool CWalletDB::WriteWatchOnly(const CScript& dest) { nWalletDBUpdated++; return Write(std::make_pair(std::string("watchs"), dest), '1'); } bool CWalletDB::EraseWatchOnly(const CScript& dest) { nWalletDBUpdated++; return Erase(std::make_pair(std::string("watchs"), dest)); } bool CWalletDB::WriteMultiSig(const CScript& dest) { nWalletDBUpdated++; return Write(std::make_pair(std::string("multisig"), dest), '1'); } bool CWalletDB::EraseMultiSig(const CScript& dest) { nWalletDBUpdated++; return Erase(std::make_pair(std::string("multisig"), dest)); } bool CWalletDB::WriteBestBlock(const CBlockLocator& locator) { nWalletDBUpdated++; return Write(std::string("bestblock"), locator); } bool CWalletDB::ReadBestBlock(CBlockLocator& locator) { return Read(std::string("bestblock"), locator); } bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext) { nWalletDBUpdated++; return Write(std::string("orderposnext"), nOrderPosNext); } // presstab HyperStake bool CWalletDB::WriteStakeSplitThreshold(uint64_t nStakeSplitThreshold) { nWalletDBUpdated++; return Write(std::string("stakeSplitThreshold"), nStakeSplitThreshold); } //presstab HyperStake bool CWalletDB::WriteMultiSend(std::vector<std::pair<std::string, int> > vMultiSend) { nWalletDBUpdated++; bool ret = true; for (unsigned int i = 0; i < vMultiSend.size(); i++) { std::pair<std::string, int> pMultiSend; pMultiSend = vMultiSend[i]; if (!Write(std::make_pair(std::string("multisend"), i), pMultiSend, true)) ret = false; } return ret; } //presstab HyperStake bool CWalletDB::EraseMultiSend(std::vector<std::pair<std::string, int> > vMultiSend) { nWalletDBUpdated++; bool ret = true; for (unsigned int i = 0; i < vMultiSend.size(); i++) { std::pair<std::string, int> pMultiSend; pMultiSend = vMultiSend[i]; if (!Erase(std::make_pair(std::string("multisend"), i))) ret = false; } return ret; } //presstab HyperStake bool CWalletDB::WriteMSettings(bool fMultiSendStake, bool fMultiSendMasternode, int nLastMultiSendHeight) { nWalletDBUpdated++; std::pair<bool, bool> enabledMS(fMultiSendStake, fMultiSendMasternode); std::pair<std::pair<bool, bool>, int> pSettings(enabledMS, nLastMultiSendHeight); return Write(std::string("msettingsv2"), pSettings, true); } //presstab HyperStake bool CWalletDB::WriteMSDisabledAddresses(std::vector<std::string> vDisabledAddresses) { nWalletDBUpdated++; bool ret = true; for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) { if (!Write(std::make_pair(std::string("mdisabled"), i), vDisabledAddresses[i])) ret = false; } return ret; } //presstab HyperStake bool CWalletDB::EraseMSDisabledAddresses(std::vector<std::string> vDisabledAddresses) { nWalletDBUpdated++; bool ret = true; for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) { if (!Erase(std::make_pair(std::string("mdisabled"), i))) ret = false; } return ret; } bool CWalletDB::WriteAutoCombineSettings(bool fEnable, CAmount nCombineThreshold) { nWalletDBUpdated++; std::pair<bool, CAmount> pSettings; pSettings.first = fEnable; pSettings.second = nCombineThreshold; return Write(std::string("autocombinesettings"), pSettings, true); } bool CWalletDB::WriteDefaultKey(const CPubKey& vchPubKey) { nWalletDBUpdated++; return Write(std::string("defaultkey"), vchPubKey); } bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool) { return Read(std::make_pair(std::string("pool"), nPool), keypool); } bool CWalletDB::WritePool(int64_t nPool, const CKeyPool& keypool) { nWalletDBUpdated++; return Write(std::make_pair(std::string("pool"), nPool), keypool); } bool CWalletDB::ErasePool(int64_t nPool) { nWalletDBUpdated++; return Erase(std::make_pair(std::string("pool"), nPool)); } bool CWalletDB::WriteMinVersion(int nVersion) { return Write(std::string("minversion"), nVersion); } bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account) { account.SetNull(); return Read(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account) { return Write(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry) { return Write(std::make_pair(std::string("acentry"), std::make_pair(acentry.strAccount, nAccEntryNum)), acentry); } bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry) { return WriteAccountingEntry(++nAccountingEntryNumber, acentry); } CAmount CWalletDB::GetAccountCreditDebit(const string& strAccount) { list<CAccountingEntry> entries; ListAccountCreditDebit(strAccount, entries); CAmount nCreditDebit = 0; BOOST_FOREACH (const CAccountingEntry& entry, entries) nCreditDebit += entry.nCreditDebit; return nCreditDebit; } void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries) { bool fAllAccounts = (strAccount == "*"); Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << std::make_pair(std::string("acentry"), std::make_pair((fAllAccounts ? string("") : strAccount), uint64_t(0))); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "acentry") break; CAccountingEntry acentry; ssKey >> acentry.strAccount; if (!fAllAccounts && acentry.strAccount != strAccount) break; ssValue >> acentry; ssKey >> acentry.nEntryNo; entries.push_back(acentry); } pcursor->close(); } DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet) { LOCK(pwallet->cs_wallet); // Old wallets didn't have any defined order for transactions // Probably a bad idea to change the output of this // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. typedef pair<CWalletTx*, CAccountingEntry*> TxPair; typedef multimap<int64_t, TxPair> TxItems; TxItems txByTime; for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0))); } list<CAccountingEntry> acentries; ListAccountCreditDebit("", acentries); BOOST_FOREACH (CAccountingEntry& entry, acentries) { txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } int64_t& nOrderPosNext = pwallet->nOrderPosNext; nOrderPosNext = 0; std::vector<int64_t> nOrderPosOffsets; for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it) { CWalletTx* const pwtx = (*it).second.first; CAccountingEntry* const pacentry = (*it).second.second; int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos; if (nOrderPos == -1) { nOrderPos = nOrderPosNext++; nOrderPosOffsets.push_back(nOrderPos); if (pwtx) { if (!WriteTx(pwtx->GetHash(), *pwtx)) return DB_LOAD_FAIL; } else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } else { int64_t nOrderPosOff = 0; BOOST_FOREACH (const int64_t& nOffsetStart, nOrderPosOffsets) { if (nOrderPos >= nOffsetStart) ++nOrderPosOff; } nOrderPos += nOrderPosOff; nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1); if (!nOrderPosOff) continue; // Since we're changing the order, write it back if (pwtx) { if (!WriteTx(pwtx->GetHash(), *pwtx)) return DB_LOAD_FAIL; } else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } } WriteOrderPosNext(nOrderPosNext); return DB_LOAD_OK; } class CWalletScanState { public: unsigned int nKeys; unsigned int nCKeys; unsigned int nKeyMeta; bool fIsEncrypted; bool fAnyUnordered; int nFileVersion; vector<uint256> vWalletUpgrade; CWalletScanState() { nKeys = nCKeys = nKeyMeta = 0; fIsEncrypted = false; fAnyUnordered = false; nFileVersion = 0; } }; bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CWalletScanState& wss, string& strType, string& strErr) { try { // Unserialize // Taking advantage of the fact that pair serialization // is just the two items serialized one after the other ssKey >> strType; if (strType == "name") { string strAddress; ssKey >> strAddress; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].name; } else if (strType == "purpose") { string strAddress; ssKey >> strAddress; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].purpose; } else if (strType == "tx") { uint256 hash; ssKey >> hash; CWalletTx wtx; ssValue >> wtx; CValidationState state; // false because there is no reason to go through the zerocoin checks for our own wallet if (!(CheckTransaction(wtx, false, false, state) && (wtx.GetHash() == hash) && state.IsValid())) return false; // Undo serialize changes in 31600 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703) { if (!ssValue.empty()) { char fTmp; char fUnused; ssValue >> fTmp >> fUnused >> wtx.strFromAccount; strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount, hash.ToString()); wtx.fTimeReceivedIsTxTime = fTmp; } else { strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString()); wtx.fTimeReceivedIsTxTime = 0; } wss.vWalletUpgrade.push_back(hash); } if (wtx.nOrderPos == -1) wss.fAnyUnordered = true; pwallet->AddToWallet(wtx, true); } else if (strType == "acentry") { string strAccount; ssKey >> strAccount; uint64_t nNumber; ssKey >> nNumber; if (nNumber > nAccountingEntryNumber) nAccountingEntryNumber = nNumber; if (!wss.fAnyUnordered) { CAccountingEntry acentry; ssValue >> acentry; if (acentry.nOrderPos == -1) wss.fAnyUnordered = true; } } else if (strType == "watchs") { CScript script; ssKey >> script; char fYes; ssValue >> fYes; if (fYes == '1') pwallet->LoadWatchOnly(script); // Watch-only addresses have no birthday information for now, // so set the wallet birthday to the beginning of time. pwallet->nTimeFirstKey = 1; } else if (strType == "multisig") { CScript script; ssKey >> script; char fYes; ssValue >> fYes; if (fYes == '1') pwallet->LoadMultiSig(script); // MultiSig addresses have no birthday information for now, // so set the wallet birthday to the beginning of time. pwallet->nTimeFirstKey = 1; } else if (strType == "key" || strType == "wkey") { CPubKey vchPubKey; ssKey >> vchPubKey; if (!vchPubKey.IsValid()) { strErr = "Error reading wallet database: CPubKey corrupt"; return false; } CKey key; CPrivKey pkey; uint256 hash = 0; if (strType == "key") { wss.nKeys++; ssValue >> pkey; } else { CWalletKey wkey; ssValue >> wkey; pkey = wkey.vchPrivKey; } // Old wallets store keys as "key" [pubkey] => [privkey] // ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key // using EC operations as a checksum. // Newer wallets store keys as "key"[pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while // remaining backwards-compatible. try { ssValue >> hash; } catch (...) { } bool fSkipCheck = false; if (hash != 0) { // hash pubkey/privkey to accelerate wallet load std::vector<unsigned char> vchKey; vchKey.reserve(vchPubKey.size() + pkey.size()); vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end()); vchKey.insert(vchKey.end(), pkey.begin(), pkey.end()); if (Hash(vchKey.begin(), vchKey.end()) != hash) { strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt"; return false; } fSkipCheck = true; } if (!key.Load(pkey, vchPubKey, fSkipCheck)) { strErr = "Error reading wallet database: CPrivKey corrupt"; return false; } if (!pwallet->LoadKey(key, vchPubKey)) { strErr = "Error reading wallet database: LoadKey failed"; return false; } } else if (strType == "mkey") { unsigned int nID; ssKey >> nID; CMasterKey kMasterKey; ssValue >> kMasterKey; if (pwallet->mapMasterKeys.count(nID) != 0) { strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID); return false; } pwallet->mapMasterKeys[nID] = kMasterKey; if (pwallet->nMasterKeyMaxID < nID) pwallet->nMasterKeyMaxID = nID; } else if (strType == "ckey") { vector<unsigned char> vchPubKey; ssKey >> vchPubKey; vector<unsigned char> vchPrivKey; ssValue >> vchPrivKey; wss.nCKeys++; if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey)) { strErr = "Error reading wallet database: LoadCryptedKey failed"; return false; } wss.fIsEncrypted = true; } else if (strType == "keymeta") { CPubKey vchPubKey; ssKey >> vchPubKey; CKeyMetadata keyMeta; ssValue >> keyMeta; wss.nKeyMeta++; pwallet->LoadKeyMetadata(vchPubKey, keyMeta); // find earliest key creation time, as wallet birthday if (!pwallet->nTimeFirstKey || (keyMeta.nCreateTime < pwallet->nTimeFirstKey)) pwallet->nTimeFirstKey = keyMeta.nCreateTime; } else if (strType == "defaultkey") { ssValue >> pwallet->vchDefaultKey; } else if (strType == "pool") { int64_t nIndex; ssKey >> nIndex; CKeyPool keypool; ssValue >> keypool; pwallet->setKeyPool.insert(nIndex); // If no metadata exists yet, create a default with the pool key's // creation time. Note that this may be overwritten by actually // stored metadata for that key later, which is fine. CKeyID keyid = keypool.vchPubKey.GetID(); if (pwallet->mapKeyMetadata.count(keyid) == 0) pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime); } else if (strType == "version") { ssValue >> wss.nFileVersion; if (wss.nFileVersion == 10300) wss.nFileVersion = 300; } else if (strType == "cscript") { uint160 hash; ssKey >> hash; CScript script; ssValue >> script; if (!pwallet->LoadCScript(script)) { strErr = "Error reading wallet database: LoadCScript failed"; return false; } } else if (strType == "orderposnext") { ssValue >> pwallet->nOrderPosNext; } else if (strType == "stakeSplitThreshold") //presstab HyperStake { ssValue >> pwallet->nStakeSplitThreshold; } else if (strType == "multisend") //presstab HyperStake { unsigned int i; ssKey >> i; std::pair<std::string, int> pMultiSend; ssValue >> pMultiSend; if (CBitcoinAddress(pMultiSend.first).IsValid()) { pwallet->vMultiSend.push_back(pMultiSend); } } else if (strType == "msettingsv2") //presstab HyperStake { std::pair<std::pair<bool, bool>, int> pSettings; ssValue >> pSettings; pwallet->fMultiSendStake = pSettings.first.first; pwallet->fMultiSendMasternodeReward = pSettings.first.second; pwallet->nLastMultiSendHeight = pSettings.second; } else if (strType == "mdisabled") //presstab HyperStake { std::string strDisabledAddress; ssValue >> strDisabledAddress; pwallet->vDisabledAddresses.push_back(strDisabledAddress); } else if (strType == "autocombinesettings") { std::pair<bool, CAmount> pSettings; ssValue >> pSettings; pwallet->fCombineDust = pSettings.first; pwallet->nAutoCombineThreshold = pSettings.second; } else if (strType == "destdata") { std::string strAddress, strKey, strValue; ssKey >> strAddress; ssKey >> strKey; ssValue >> strValue; if (!pwallet->LoadDestData(CBitcoinAddress(strAddress).Get(), strKey, strValue)) { strErr = "Error reading wallet database: LoadDestData failed"; return false; } } } catch (...) { return false; } return true; } static bool IsKeyType(string strType) { return (strType == "key" || strType == "wkey" || strType == "mkey" || strType == "ckey"); } DBErrors CWalletDB::LoadWallet(CWallet* pwallet) { pwallet->vchDefaultKey = CPubKey(); CWalletScanState wss; bool fNoncriticalErrors = false; DBErrors result = DB_LOAD_OK; try { LOCK(pwallet->cs_wallet); int nMinVersion = 0; if (Read((string) "minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); } // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { LogPrintf("Error getting wallet database cursor\n"); return DB_CORRUPT; } while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { LogPrintf("Error reading next record from wallet database\n"); return DB_CORRUPT; } // Try to be tolerant of single corrupt records: string strType, strErr; if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr)) { // losing keys is considered a catastrophic error, anything else // we assume the user can live with: if (IsKeyType(strType)) result = DB_CORRUPT; else { // Leave other errors alone, if we try to fix them we might make things worse. fNoncriticalErrors = true; // ... but do warn the user there is something wrong. if (strType == "tx") // Rescan if there is a bad transaction record: SoftSetBoolArg("-rescan", true); } } if (!strErr.empty()) LogPrintf("%s\n", strErr); } pcursor->close(); } catch (boost::thread_interrupted) { throw; } catch (...) { result = DB_CORRUPT; } if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR; // Any wallet corruption at all: skip any rewriting or // upgrading, we don't want to make it worse. if (result != DB_LOAD_OK) return result; LogPrintf("nFileVersion = %d\n", wss.nFileVersion); LogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n", wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys); // nTimeFirstKey is only reliable if all keys have metadata if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta) pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value' BOOST_FOREACH (uint256 hash, wss.vWalletUpgrade) WriteTx(hash, pwallet->mapWallet[hash]); // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc: if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000)) return DB_NEED_REWRITE; if (wss.nFileVersion < CLIENT_VERSION) // Update WriteVersion(CLIENT_VERSION); if (wss.fAnyUnordered) result = ReorderTransactions(pwallet); return result; } DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash, vector<CWalletTx>& vWtx) { pwallet->vchDefaultKey = CPubKey(); bool fNoncriticalErrors = false; DBErrors result = DB_LOAD_OK; try { LOCK(pwallet->cs_wallet); int nMinVersion = 0; if (Read((string) "minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); } // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { LogPrintf("Error getting wallet database cursor\n"); return DB_CORRUPT; } while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { LogPrintf("Error reading next record from wallet database\n"); return DB_CORRUPT; } string strType; ssKey >> strType; if (strType == "tx") { uint256 hash; ssKey >> hash; CWalletTx wtx; ssValue >> wtx; vTxHash.push_back(hash); vWtx.push_back(wtx); } } pcursor->close(); } catch (boost::thread_interrupted) { throw; } catch (...) { result = DB_CORRUPT; } if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR; return result; } DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet, vector<CWalletTx>& vWtx) { // build list of wallet TXs vector<uint256> vTxHash; DBErrors err = FindWalletTx(pwallet, vTxHash, vWtx); if (err != DB_LOAD_OK) return err; // erase each wallet TX BOOST_FOREACH (uint256& hash, vTxHash) { if (!EraseTx(hash)) return DB_CORRUPT; } return DB_LOAD_OK; } void ThreadFlushWalletDB(const string& strFile) { // Make this thread recognisable as the wallet flushing thread RenameThread("somnio-wallet"); static bool fOneThread; if (fOneThread) return; fOneThread = true; if (!GetBoolArg("-flushwallet", true)) return; unsigned int nLastSeen = nWalletDBUpdated; unsigned int nLastFlushed = nWalletDBUpdated; int64_t nLastWalletUpdate = GetTime(); while (true) { MilliSleep(500); if (nLastSeen != nWalletDBUpdated) { nLastSeen = nWalletDBUpdated; nLastWalletUpdate = GetTime(); } if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2) { TRY_LOCK(bitdb.cs_db, lockDb); if (lockDb) { // Don't do this if any databases are in use int nRefCount = 0; map<string, int>::iterator mi = bitdb.mapFileUseCount.begin(); while (mi != bitdb.mapFileUseCount.end()) { nRefCount += (*mi).second; mi++; } if (nRefCount == 0) { boost::this_thread::interruption_point(); map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile); if (mi != bitdb.mapFileUseCount.end()) { LogPrint("db", "Flushing wallet.dat\n"); nLastFlushed = nWalletDBUpdated; int64_t nStart = GetTimeMillis(); // Flush wallet.dat so it's self contained bitdb.CloseDb(strFile); bitdb.CheckpointLSN(strFile); bitdb.mapFileUseCount.erase(mi++); LogPrint("db", "Flushed wallet.dat %dms\n", GetTimeMillis() - nStart); } } } } } } bool BackupWallet(const CWallet& wallet, const string& strDest) { if (!wallet.fFileBacked) return false; while (true) { { LOCK(bitdb.cs_db); if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0) { // Flush log data to the dat file bitdb.CloseDb(wallet.strWalletFile); bitdb.CheckpointLSN(wallet.strWalletFile); bitdb.mapFileUseCount.erase(wallet.strWalletFile); // Copy wallet.dat filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile; filesystem::path pathDest(strDest); if (filesystem::is_directory(pathDest)) pathDest /= wallet.strWalletFile; try { #if BOOST_VERSION >= 158000 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists); #else std::ifstream src(pathSrc.string(), std::ios::binary); std::ofstream dst(pathDest.string(), std::ios::binary); dst << src.rdbuf(); #endif LogPrintf("copied wallet.dat to %s\n", pathDest.string()); return true; } catch (const filesystem::filesystem_error& e) { LogPrintf("error copying wallet.dat to %s - %s\n", pathDest.string(), e.what()); return false; } } } MilliSleep(100); } return false; } // // Try to (very carefully!) recover wallet.dat if there is a problem. // bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys) { // Recovery procedure: // move wallet.dat to wallet.timestamp.bak // Call Salvage with fAggressive=true to // get as much data as possible. // Rewrite salvaged data to wallet.dat // Set -rescan so any missing transactions will be // found. int64_t now = GetTime(); std::string newFilename = strprintf("wallet.%d.bak", now); int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL, newFilename.c_str(), DB_AUTO_COMMIT); if (result == 0) LogPrintf("Renamed %s to %s\n", filename, newFilename); else { LogPrintf("Failed to rename %s to %s\n", filename, newFilename); return false; } std::vector<CDBEnv::KeyValPair> salvagedData; bool allOK = dbenv.Salvage(newFilename, true, salvagedData); if (salvagedData.empty()) { LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename); return false; } LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size()); bool fSuccess = allOK; boost::scoped_ptr<Db> pdbCopy(new Db(&dbenv.dbenv, 0)); int ret = pdbCopy->open(NULL, // Txn pointer filename.c_str(), // Filename "main", // Logical db name DB_BTREE, // Database type DB_CREATE, // Flags 0); if (ret > 0) { LogPrintf("Cannot create database file %s\n", filename); return false; } CWallet dummyWallet; CWalletScanState wss; DbTxn* ptxn = dbenv.TxnBegin(); BOOST_FOREACH (CDBEnv::KeyValPair& row, salvagedData) { if (fOnlyKeys) { CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); string strType, strErr; bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue, wss, strType, strErr); if (!IsKeyType(strType)) continue; if (!fReadOK) { LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr); continue; } } Dbt datKey(&row.first[0], row.first.size()); Dbt datValue(&row.second[0], row.second.size()); int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE); if (ret2 > 0) fSuccess = false; } ptxn->commit(0); pdbCopy->close(0); return fSuccess; } bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename) { return CWalletDB::Recover(dbenv, filename, false); } bool CWalletDB::WriteDestData(const std::string& address, const std::string& key, const std::string& value) { nWalletDBUpdated++; return Write(std::make_pair(std::string("destdata"), std::make_pair(address, key)), value); } bool CWalletDB::EraseDestData(const std::string& address, const std::string& key) { nWalletDBUpdated++; return Erase(std::make_pair(std::string("destdata"), std::make_pair(address, key))); } bool CWalletDB::WriteZerocoinSpendSerialEntry(const CZerocoinSpend& zerocoinSpend) { return Write(make_pair(string("zcserial"), zerocoinSpend.GetSerial()), zerocoinSpend, true); } bool CWalletDB::EraseZerocoinSpendSerialEntry(const CBigNum& serialEntry) { return Erase(make_pair(string("zcserial"), serialEntry)); } bool CWalletDB::ReadZerocoinSpendSerialEntry(const CBigNum& bnSerial) { CZerocoinSpend spend; return Read(make_pair(string("zcserial"), bnSerial), spend); } bool CWalletDB::WriteZerocoinMint(const CZerocoinMint& zerocoinMint) { CDataStream ss(SER_GETHASH, 0); ss << zerocoinMint.GetValue(); uint256 hash = Hash(ss.begin(), ss.end()); Erase(make_pair(string("zerocoin"), hash)); return Write(make_pair(string("zerocoin"), hash), zerocoinMint, true); } bool CWalletDB::ReadZerocoinMint(const CBigNum &bnPubCoinValue, CZerocoinMint& zerocoinMint) { CDataStream ss(SER_GETHASH, 0); ss << bnPubCoinValue; uint256 hash = Hash(ss.begin(), ss.end()); return Read(make_pair(string("zerocoin"), hash), zerocoinMint); } bool CWalletDB::EraseZerocoinMint(const CZerocoinMint& zerocoinMint) { CDataStream ss(SER_GETHASH, 0); ss << zerocoinMint.GetValue(); uint256 hash = Hash(ss.begin(), ss.end()); return Erase(make_pair(string("zerocoin"), hash)); } bool CWalletDB::ArchiveMintOrphan(const CZerocoinMint& zerocoinMint) { CDataStream ss(SER_GETHASH, 0); ss << zerocoinMint.GetValue(); uint256 hash = Hash(ss.begin(), ss.end());; if (!Write(make_pair(string("zco"), hash), zerocoinMint)) { LogPrintf("%s : failed to database orphaned zerocoin mint\n", __func__); return false; } if (!Erase(make_pair(string("zerocoin"), hash))) { LogPrintf("%s : failed to erase orphaned zerocoin mint\n", __func__); return false; } return true; } bool CWalletDB::UnarchiveZerocoin(const CZerocoinMint& mint) { CDataStream ss(SER_GETHASH, 0); ss << mint.GetValue(); uint256 hash = Hash(ss.begin(), ss.end());; if (!Erase(make_pair(string("zco"), hash))) { LogPrintf("%s : failed to erase archived zerocoin mint\n", __func__); return false; } return WriteZerocoinMint(mint); } std::list<CZerocoinMint> CWalletDB::ListMintedCoins(bool fUnusedOnly, bool fMaturedOnly, bool fUpdateStatus) { std::list<CZerocoinMint> listPubCoin; Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; vector<CZerocoinMint> vOverWrite; vector<CZerocoinMint> vArchive; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << make_pair(string("zerocoin"), uint256(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error(std::string(__func__)+" : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "zerocoin") break; uint256 value; ssKey >> value; CZerocoinMint mint; ssValue >> mint; if (fUnusedOnly) { if (mint.IsUsed()) continue; //double check that we have no record of this serial being used if (ReadZerocoinSpendSerialEntry(mint.GetSerialNumber())) { mint.SetUsed(true); vOverWrite.emplace_back(mint); continue; } } if (fMaturedOnly || fUpdateStatus) { //if there is not a record of the block height, then look it up and assign it if (!mint.GetHeight()) { CTransaction tx; uint256 hashBlock; if(!GetTransaction(mint.GetTxHash(), tx, hashBlock, true)) { LogPrintf("%s failed to find tx for mint txid=%s\n", __func__, mint.GetTxHash().GetHex()); vArchive.emplace_back(mint); continue; } //if not in the block index, most likely is unconfirmed tx if (mapBlockIndex.count(hashBlock)) { mint.SetHeight(mapBlockIndex[hashBlock]->nHeight); vOverWrite.emplace_back(mint); } else if (fMaturedOnly){ continue; } } //not mature if (mint.GetHeight() > chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations()) { if (!fMaturedOnly) listPubCoin.emplace_back(mint); continue; } //if only requesting an update (fUpdateStatus) then skip the rest and add to list if (fMaturedOnly) { // check to make sure there are at least 3 other mints added to the accumulators after this if (chainActive.Height() < mint.GetHeight() + 1) continue; CBlockIndex *pindex = chainActive[mint.GetHeight() + 1]; int nMintsAdded = 0; while(pindex->nHeight < chainActive.Height() - 30) { // 30 just to make sure that its at least 2 checkpoints from the top block nMintsAdded += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), mint.GetDenomination()); if(nMintsAdded >= Params().Zerocoin_RequiredAccumulation()) break; pindex = chainActive[pindex->nHeight + 1]; } if(nMintsAdded < Params().Zerocoin_RequiredAccumulation()) continue; } } listPubCoin.emplace_back(mint); } pcursor->close(); //overwrite any updates for (CZerocoinMint mint : vOverWrite) { if(!this->WriteZerocoinMint(mint)) LogPrintf("%s failed to update mint from tx %s\n", __func__, mint.GetTxHash().GetHex()); } // archive mints for (CZerocoinMint mint : vArchive) { if (!this->ArchiveMintOrphan(mint)) LogPrintf("%s failed to archive mint from %s\n", __func__, mint.GetTxHash().GetHex()); } return listPubCoin; } // Just get the Serial Numbers std::list<CBigNum> CWalletDB::ListMintedCoinsSerial() { std::list<CBigNum> listPubCoin; std::list<CZerocoinMint> listCoins = ListMintedCoins(true, false, false); for ( auto& coin : listCoins) { listPubCoin.push_back(coin.GetSerialNumber()); } return listPubCoin; } std::list<CZerocoinSpend> CWalletDB::ListSpentCoins() { std::list<CZerocoinSpend> listCoinSpend; Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << make_pair(string("zcserial"), CBigNum(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error(std::string(__func__)+" : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "zcserial") break; CBigNum value; ssKey >> value; CZerocoinSpend zerocoinSpendItem; ssValue >> zerocoinSpendItem; listCoinSpend.push_back(zerocoinSpendItem); } pcursor->close(); return listCoinSpend; } // Just get the Serial Numbers std::list<CBigNum> CWalletDB::ListSpentCoinsSerial() { std::list<CBigNum> listPubCoin; std::list<CZerocoinSpend> listCoins = ListSpentCoins(); for ( auto& coin : listCoins) { listPubCoin.push_back(coin.GetSerial()); } return listPubCoin; } std::list<CZerocoinMint> CWalletDB::ListArchivedZerocoins() { std::list<CZerocoinMint> listMints; Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << make_pair(string("zco"), CBigNum(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error(std::string(__func__)+" : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "zco") break; uint256 value; ssKey >> value; CZerocoinMint mint; ssValue >> mint; listMints.push_back(mint); } pcursor->close(); return listMints; }
[ "root@vultr.guest" ]
root@vultr.guest
e9c03422bd5962e326c45b5beff005e4e3ab7f5f
7515ba50ced3d1e1ddbfb80ec3f22575b50b6875
/include/SDL_Wrapper/SDL_Audio.hpp
e38ac539b637895ca19082f1ae58ea22acc834cf
[]
no_license
shcalbers/sdl-game
724e7f24443906aacb0388dc67eca3e1346cb72c
a1d496fb2c4b17d8e236d0fa367162110a77fa76
refs/heads/master
2021-04-14T23:37:59.892998
2020-03-22T21:39:19
2020-03-22T21:39:19
249,277,141
0
0
null
null
null
null
UTF-8
C++
false
false
822
hpp
#ifndef SDL_AUDIO_HEADER #define SDL_AUDIO_HEADER #include "SDL.h" #include "SDL_mixer.h" #include <memory> using namespace std; class AudioEffect { public: //AudioEffect(); AudioEffect(const char * file_name, int loops); AudioEffect(const AudioEffect &) = delete; AudioEffect & operator=(const AudioEffect &) = delete; void Play(void); void Pause(void); void Resume(void); void Halt(void); ~AudioEffect(); private: struct AudioEffectData; unique_ptr<AudioEffectData> _data; }; class Audio { public: //Audio(); Audio(const char * Audio_File_name, int loops); Audio(const Audio &) = delete; Audio & operator=(const Audio &) = delete; void Play(void); void Pause(void); void Resume(void); void Halt(void); ~Audio(); private: struct AudioData; unique_ptr<AudioData> _data; }; #endif
[ "34623185+shcalbers@users.noreply.github.com" ]
34623185+shcalbers@users.noreply.github.com
41729529c690a5461268489649ea77b236e4bdc9
bea876bddfcb07514040618e6465e6ba3abc1f5f
/Lecture03/problem3/Person.cpp
9bd1e37b57a59a285beb045e602be0c5e08679c4
[]
no_license
Choi-Jinwoo/dgsw.algorithm_2
8ab70ae3ca6d76cbd762647f5d444abc47856bbe
7ecae7a56a81c9b6479b966b78fc16479d1b4ee8
refs/heads/master
2023-08-20T10:18:25.488151
2021-11-02T09:17:37
2021-11-02T09:17:37
268,756,982
1
0
null
null
null
null
UTF-8
C++
false
false
160
cpp
// // Created by 최진우 on 2020/06/09. // #include "Person.h" Person::Person(int room, std::string name) { this->room = room; this->name = name; }
[ "49791336+Choi-Jinwoo@users.noreply.github.com" ]
49791336+Choi-Jinwoo@users.noreply.github.com
57508ea4b4105dd1ea27fa5c168d717fb01fb746
c8eaf2bb14f26c87f175ea182f5b618ef5dd9412
/src/arithmetic/pattern_match.h
a236e65a83122f3f7b295d2d0f2088275e5b96f5
[ "Apache-2.0", "Zlib", "MIT", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSD-2-Clause" ]
permissive
wweic/tvm
4050d5e64ca1aff9b8d8a5726c9815772e0bf2ae
49d31443c4b65c814a3da6decc363a881c05b372
refs/heads/master
2021-05-15T22:02:24.605696
2020-01-15T22:44:14
2020-01-15T22:44:14
106,635,229
0
0
null
2017-10-12T02:37:48
2017-10-12T02:37:48
null
UTF-8
C++
false
false
23,445
h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file tvm/arithmetic/pattern_match.h * * \brief Internal tool for expression-template based pattern matching. * * It helps to simplify pattern matching and rewrites. * All the patterns are generated via expression template during compile time, * so the result code should be as efficient as manually written pattern match code. * * The code below shows how to use the pattern matcher. * * \code * * // max(x + z, y + z) => max(x, y) + z * arith::PVar<Expr> x, y, z; * * // The following code tries to match the declared pattern. * // Match will fill the result of match into PVar if successful. * // Note that z occurs twice in the pattern, * // an equality check is performed to ensure each occurance of z * // is equivalent to each other. * if (max(x + z, y + z).Match(expr)) { * // Eval evaluates a pattern with the current matched value. * // The filled value is valid until the next call to Match. * return (max(x, y) + z).Eval(); * } * * tvm::Var tx, ty; * arith::PVar<IntImm> c; * arith::PVar<Var> v; * // We can match integer and Var, both of which are * // special case container of Expr * CHECK((v * c).Match(tx * 3)); * CHECK_EQ(c.Eval()->value, 3); * // cannot match c to ty * CHECK(!(v * c).Match(tx * ty)); * * \endcode * * \note The pattern matcher is not threadsafe, * do not use the same PVar in multiple threads. * * Please be aware that the filled value in a PVar * can be overriden in the next call to Match. */ #ifndef TVM_ARITHMETIC_PATTERN_MATCH_H_ #define TVM_ARITHMETIC_PATTERN_MATCH_H_ #include <tvm/ir_pass.h> #include <tuple> #include "const_fold.h" namespace tvm { namespace arith { /*! * \brief Base class of all the patterns. * * There are two major member functions supported by each pattern. * - Match: checks if value matches the pattern. * - Eval: construct a new value based on matched values in PVar. * * We use curiously recurring template pattern to construct * expression templates. * * \tparam Derived The type of the derived class. */ template<typename Derived> class Pattern { public: /*! * \brief Nested storage type in the expression. * * Depending on the Derived class, * Nested can be Derived (nest by value) or * const Derived& (nest by reference). * * The trick of Nested typedef originates from Eigen. * * \note We use nest by value for intermediate expressions, * and nest by reference for PVars. */ using Nested = Derived; /*! * \brief Check if value matches the current pattern. * * This call also populates the PVars with matched value. * The values in PVars are valid until the next call to Match. * * \return whether value matches the pattern. */ template<typename NodeType> bool Match(const NodeType& value) const { derived().InitMatch_(); return derived().Match_(value); } /*! \return Derived instance of current class. */ const Derived& derived() const { return *static_cast<const Derived*>(this); } }; /*! * \brief Default deep equality checker * \tparam T the comparison point. */ template<typename T> class PEqualChecker { public: bool operator()(const T& lhs, const T& rhs) const { return lhs == rhs; } }; template<> class PEqualChecker<PrimExpr> { public: bool operator()(const PrimExpr& lhs, const PrimExpr& rhs) const { if (lhs.same_as(rhs)) return true; return ir::Equal(lhs, rhs); } }; template<> class PEqualChecker<IntImm> { public: bool operator()(const IntImm& lhs, const IntImm& rhs) const { return lhs->value == rhs->value; } }; template<> class PEqualChecker<Var> { public: bool operator()(const Var& lhs, const Var& rhs) const { return lhs.same_as(rhs); } }; /*! * \brief Pattern variable container. * * PVar is used as a "hole" in the pattern that can be matched. * * \tparam T the type of the hole. * * \note PVar is not thread safe. * Do not use the same PVar in multiple threads. */ template<typename T> class PVar : public Pattern<PVar<T> > { public: // Store PVars by reference in the expression. using Nested = const PVar<T>&; void InitMatch_() const { filled_ = false; } bool Match_(const T& value) const { if (!filled_) { value_ = value; filled_ = true; return true; } else { return PEqualChecker<T>()(value_, value); } } template<typename NodeRefType, typename = typename std::enable_if< std::is_base_of<NodeRefType, T>::value>::type> bool Match_(const NodeRefType& value) const { if (const auto* ptr = value.template as<typename T::ContainerType>()) { return Match_(GetRef<T>(ptr)); } else { return false; } } T Eval() const { CHECK(filled_); return value_; } protected: /*! \brief The matched value */ mutable T value_; /*! \brief whether the variable has been filled */ mutable bool filled_{false}; }; /*! * \brief Constant Pattern variable container. * * \tparam T the type of the hole. */ template<typename T> class PConst : public Pattern<PConst<T> > { public: PConst(T value) // NOLINT(*) : value_(value) {} void InitMatch_() const {} bool Match_(const T& value) const { return PEqualChecker<T>()(value_, value); } T Eval() const { return value_; } private: const T value_; }; /*! * \brief Pattern binary expression. * \tparam NodeType The AST node type. * \tparam TA The pattern type of the first operand. * \tparam TB The pattern type of the second operand. */ template<typename NodeType, typename TA, typename TB> class PBinaryExpr : public Pattern<PBinaryExpr<NodeType, TA, TB> > { public: PBinaryExpr(const TA& a, const TB& b) : a_(a), b_(b) {} void InitMatch_() const { a_.InitMatch_(); b_.InitMatch_(); } bool Match_(const ObjectRef& node) const { if (const NodeType* ptr = node.as<NodeType>()) { if (!a_.Match_(ptr->a)) return false; if (!b_.Match_(ptr->b)) return false; return true; } else { return false; } } PrimExpr Eval() const { PrimExpr lhs = a_.Eval(); PrimExpr rhs = b_.Eval(); PrimExpr ret = TryConstFold<NodeType>(lhs, rhs); if (ret.defined()) return ret; return NodeType::make(lhs, rhs); } private: typename TA::Nested a_; typename TB::Nested b_; }; template<typename TA> class PConstWithTypeLike : public Pattern<PConstWithTypeLike<TA> > { public: PConstWithTypeLike(const TA& ref, int64_t value) : ref_(ref), value_(value) {} void InitMatch_() const {} bool Match_(const ObjectRef& node) const { if (const ir::IntImmNode* ptr = node.as<ir::IntImmNode>()) { return ptr->value == value_; } else { return false; } } PrimExpr Eval() const { return make_const(ref_.Eval().dtype(), value_); } private: typename TA::Nested ref_; int64_t value_; }; #define TVM_PATTERN_BINARY_OP_EX(FuncName, NodeName, CheckStep) \ template<typename TA, typename TB> \ inline PBinaryExpr<NodeName, TA, TB> \ FuncName(const Pattern<TA>& a, const Pattern<TB>& b) { \ CheckStep; \ return PBinaryExpr<NodeName, TA, TB>(a.derived(), b.derived()); \ } \ template<typename TA> \ inline PBinaryExpr<NodeName, TA, PConstWithTypeLike<TA> > \ FuncName(const Pattern<TA>& a, int64_t b) { \ CheckStep; \ return FuncName(a, PConstWithTypeLike<TA>(a.derived(), b)); \ } \ template<typename TA> \ inline PBinaryExpr<NodeName, PConstWithTypeLike<TA>, TA> \ FuncName(int64_t b, const Pattern<TA>& a) { \ CheckStep; \ return FuncName(PConstWithTypeLike<TA>(a.derived(), b), a); \ } #define TVM_PATTERN_BINARY_OP(FuncName, NodeName) \ TVM_PATTERN_BINARY_OP_EX(FuncName, NodeName, ) // raise ambiguity error for operator overload of / and % TVM_PATTERN_BINARY_OP_EX(operator/, ir::DivNode, DivAmbiguityError(a)); TVM_PATTERN_BINARY_OP_EX(operator%, ir::ModNode, DivAmbiguityError(a)); // arithmetic expressions TVM_PATTERN_BINARY_OP(operator+, ir::AddNode); TVM_PATTERN_BINARY_OP(operator-, ir::SubNode); TVM_PATTERN_BINARY_OP(operator*, ir::MulNode); TVM_PATTERN_BINARY_OP(min, ir::MinNode); TVM_PATTERN_BINARY_OP(max, ir::MaxNode); TVM_PATTERN_BINARY_OP(div, ir::DivNode); TVM_PATTERN_BINARY_OP(truncdiv, ir::DivNode); TVM_PATTERN_BINARY_OP(truncmod, ir::ModNode); TVM_PATTERN_BINARY_OP(floordiv, ir::FloorDivNode); TVM_PATTERN_BINARY_OP(floormod, ir::FloorModNode); // logical expressions TVM_PATTERN_BINARY_OP(operator>, ir::GTNode); TVM_PATTERN_BINARY_OP(operator>=, ir::GENode); TVM_PATTERN_BINARY_OP(operator<, ir::LTNode); TVM_PATTERN_BINARY_OP(operator<=, ir::LENode); TVM_PATTERN_BINARY_OP(operator==, ir::EQNode); TVM_PATTERN_BINARY_OP(operator!=, ir::NENode); TVM_PATTERN_BINARY_OP(operator&&, ir::AndNode); TVM_PATTERN_BINARY_OP(operator||, ir::OrNode); /*! * \brief Pattern not expression. * \tparam TA The pattern type of the true operand. */ template<typename TA> class PNotExpr : public Pattern<PNotExpr<TA> > { public: explicit PNotExpr(const TA& value) : value_(value) {} void InitMatch_() const { value_.InitMatch_(); } bool Match_(const ObjectRef& node) const { if (const ir::NotNode* ptr = node.as<ir::NotNode>()) { if (!value_.Match_(ptr->a)) return false; return true; } else { return false; } } PrimExpr Eval() const { return ir::NotNode::make(value_.Eval()); } private: typename TA::Nested value_; }; template<typename TA> inline PNotExpr<TA> operator!(const Pattern<TA>& value) { return PNotExpr<TA>(value.derived()); } // select /*! * \brief Pattern select expression. * \tparam TCond The pattern type of the condition. * \tparam TA The pattern type of the true operand. * \tparam TB The pattern type of the false operand. */ template<typename TCond, typename TA, typename TB> class PSelectExpr : public Pattern<PSelectExpr<TCond, TA, TB> > { public: PSelectExpr(const TCond& condition, const TA& true_value, const TB& false_value) : condition_(condition), true_value_(true_value), false_value_(false_value) {} void InitMatch_() const { condition_.InitMatch_(); true_value_.InitMatch_(); false_value_.InitMatch_(); } bool Match_(const ObjectRef& node) const { if (const ir::SelectNode* ptr = node.as<ir::SelectNode>()) { if (!condition_.Match_(ptr->condition)) return false; if (!true_value_.Match_(ptr->true_value)) return false; if (!false_value_.Match_(ptr->false_value)) return false; return true; } else { return false; } } PrimExpr Eval() const { return ir::SelectNode::make( condition_.Eval(), true_value_.Eval(), false_value_.Eval()); } private: typename TCond::Nested condition_; typename TA::Nested true_value_; typename TB::Nested false_value_; }; /*! * \brief Construct a select pattern. * * \param condition The condition expression. * \param true_value The value when condition is true. * \param true_value The value when condition is false. * * \return The result pattern. * * \tparam TCond The pattern type of the condition. * \tparam TA The pattern type of the true operand. * \tparam TB The pattern type of the false operand. */ template<typename TCond, typename TA, typename TB> inline PSelectExpr<TCond, TA, TB> select(const Pattern<TCond>& condition, const Pattern<TA>& true_value, const Pattern<TB>& false_value) { return PSelectExpr<TCond, TA, TB>( condition.derived(), true_value.derived(), false_value.derived()); } /*! * \brief Pattern cast expression. * \tparam DType The Pattern type of dtype. * \tparam TA The pattern type of the first operand. */ template<typename DType, typename TA> class PCastExpr : public Pattern<PCastExpr<DType, TA> > { public: PCastExpr(const DType& dtype, const TA& value) : dtype_(dtype), value_(value) { } void InitMatch_() const { dtype_.InitMatch_(); value_.InitMatch_(); } bool Match_(const ObjectRef& node) const { if (const ir::CastNode* ptr = node.as<ir::CastNode>()) { if (!dtype_.Match_(ptr->dtype)) return false; if (!value_.Match_(ptr->value)) return false; return true; } else { return false; } } PrimExpr Eval() const { return ir::CastNode::make(dtype_.Eval(), value_.Eval()); } private: typename DType::Nested dtype_; typename TA::Nested value_; }; /*! * \brief Construct a cast pattern. * * \param dtype The target data type, can be PVar<Type> or PConst<Type>. * \param value The input type. * * \return The result pattern. * * \tparam DType The pattern type of type. * \tparam TA The pattern type of value. */ template<typename DType, typename TA> inline PCastExpr<DType, TA> cast(const Pattern<DType>& dtype, const Pattern<TA>& value) { return PCastExpr<DType, TA>(dtype.derived(), value.derived()); } /*! * \brief Pattern ramp expression. * \tparam TBase The pattern type of the base. * \tparam TStride The pattern type of the stride. * \tparam TLanes The pattern type of the lanes. */ template<typename TBase, typename TStride, typename TLanes> class PRampExpr : public Pattern<PRampExpr<TBase, TStride, TLanes> > { public: PRampExpr(const TBase& base, const TStride& stride, const TLanes& lanes) : base_(base), stride_(stride), lanes_(lanes) { } void InitMatch_() const { base_.InitMatch_(); stride_.InitMatch_(); lanes_.InitMatch_(); } bool Match_(const ObjectRef& node) const { if (const ir::RampNode* ptr = node.as<ir::RampNode>()) { if (!base_.Match_(ptr->base)) return false; if (!stride_.Match_(ptr->stride)) return false; if (!lanes_.Match_(ptr->lanes)) return false; return true; } else { return false; } } PrimExpr Eval() const { return ir::RampNode::make(base_.Eval(), stride_.Eval(), lanes_.Eval()); } private: typename TBase::Nested base_; typename TStride::Nested stride_; typename TLanes::Nested lanes_; }; /*! * \brief Construct a ramp pattern. * * \param base The base pattern. * \param stride The stride pattern. * \param lanes The lanes pattern. * * \return The result pattern. * * \tparam TBase The pattern type of the base. * \tparam TStride The pattern type of the stride. * \tparam TLanes The pattern type of the lanes. */ template<typename TBase, typename TStride, typename TLanes> inline PRampExpr<TBase, TStride, TLanes> ramp(const Pattern<TBase>& base, const Pattern<TStride>& stride, const Pattern<TLanes>& lanes) { return PRampExpr<TBase, TStride, TLanes>( base.derived(), stride.derived(), lanes.derived()); } /*! * \brief Pattern broadcast expression. * \tparam TA The pattern type of the value. * \tparam TLanes The pattern type of the lanes. */ template<typename TA, typename TLanes> class PBroadcastExpr : public Pattern<PBroadcastExpr<TA, TLanes> > { public: PBroadcastExpr(const TA& value, const TLanes& lanes) : value_(value), lanes_(lanes) { } void InitMatch_() const { value_.InitMatch_(); lanes_.InitMatch_(); } bool Match_(const ObjectRef& node) const { if (const ir::BroadcastNode* ptr = node.as<ir::BroadcastNode>()) { if (!value_.Match_(ptr->value)) return false; if (!lanes_.Match_(ptr->lanes)) return false; return true; } else { return false; } } PrimExpr Eval() const { return ir::BroadcastNode::make(value_.Eval(), lanes_.Eval()); } private: typename TA::Nested value_; typename TLanes::Nested lanes_; }; /*! * \brief Construct a broadcast pattern. * * \param value The value pattern. * \param lanes The lanes pattern. * * \return The result pattern. * * \tparam TA The pattern type of the value. * \tparam TLanes The pattern type of the lanes. */ template<typename TA, typename TLanes> inline PBroadcastExpr<TA, TLanes> broadcast(const Pattern<TA>& value, const Pattern<TLanes>& lanes) { return PBroadcastExpr<TA, TLanes>(value.derived(), lanes.derived()); } // internal namespace namespace detail { // implementation details for CallExpr template<bool stop, std::size_t I, typename F> struct tuple_for_each_dispatcher { template<typename TTuple> static void run(F& f, const TTuple& tuple) { // NOLINT(*) f(I, std::get<I>(tuple)); tuple_for_each_dispatcher< (I + 1) == std::tuple_size<TTuple>::value, (I + 1), F> ::run(f, tuple); } }; template<std::size_t I, typename F> struct tuple_for_each_dispatcher<true, I, F> { template<typename TTuple> static void run(F& f, const TTuple& tuple) {} // NOLINT(*) }; template<typename F, typename TTuple> inline void tuple_for_each(F& f, const TTuple& tuple) { // NOLINT(*) tuple_for_each_dispatcher<std::tuple_size<TTuple>::value == 0, 0, F> ::run(f, tuple); } struct PCallExprInitMatchFunctor { template<typename T> void operator()(size_t i, const T& pattern) const { pattern.InitMatch_(); } }; struct PCallExprMatchFunctor { const ir::CallNode* call_; bool matched_{true}; explicit PCallExprMatchFunctor(const ir::CallNode* call) : call_(call) {} template<typename T> void operator()(size_t i, const T& pattern) { matched_ = matched_ && pattern.Match_(call_->args[i]); } }; struct PCallExprEvalArgsFunctor { Array<PrimExpr> args_; template<typename T> void operator()(size_t i, const T& pattern) { args_.push_back(pattern.Eval()); } }; } // namespace detail /*! * \brief Pattern CallExpr expression. * \tparam Op The operator functor class. * \tparam TArgs The arguments. * \note Op functor contains the name of the function and * the implementation of Eval. */ template<typename Op, typename ...TArgs> class PCallExpr : public Pattern<PCallExpr<Op, TArgs...> > { public: explicit PCallExpr(const TArgs&... args) : args_(args...) { } void InitMatch_() const { detail::PCallExprInitMatchFunctor finit; detail::tuple_for_each(finit, args_); } bool Match_(const ObjectRef& node) const { if (const ir::CallNode* ptr = node.as<ir::CallNode>()) { if (ptr->args.size() != sizeof...(TArgs)) return false; if (ptr->name != Op::kName) return false; detail::PCallExprMatchFunctor fmatch(ptr); detail::tuple_for_each(fmatch, args_); return fmatch.matched_; } else { return false; } } PrimExpr Eval() const { detail::PCallExprEvalArgsFunctor feval_args; detail::tuple_for_each(feval_args, args_); return Op::Eval(feval_args.args_); } private: std::tuple<typename TArgs::Nested...> args_; }; // arithemetic intrinsics #define TVM_PATTERN_BINARY_INTRIN(FuncName, OpName, IntrinStr) \ struct OpName { \ static PrimExpr Eval(Array<PrimExpr> args) { \ return ir::CallNode::make(args[0].dtype(), kName, args, \ ir::CallNode::PureIntrinsic); \ } \ static constexpr const char* kName = IntrinStr; \ }; \ template<typename TA, typename TB> \ inline PCallExpr<OpName, TA, TB> \ FuncName(const Pattern<TA>& a, const Pattern<TB>& b) { \ return PCallExpr<OpName, TA, TB>(a.derived(), b.derived()); \ } TVM_PATTERN_BINARY_INTRIN(operator<<, PLeftShiftOp, "shift_left"); TVM_PATTERN_BINARY_INTRIN(operator>>, PRightShiftOp, "shift_right"); TVM_PATTERN_BINARY_INTRIN(operator&, PBitwiseAndOp, "bitwise_and"); TVM_PATTERN_BINARY_INTRIN(operator|, PBitwiseOrOp, "bitwise_or"); TVM_PATTERN_BINARY_INTRIN(operator^, PBitwiseXorOp, "bitwise_xor"); // unary intrinsics #define TVM_PATTERN_UNARY_INTRIN(FuncName, OpName, IntrinStr) \ struct OpName { \ static PrimExpr Eval(Array<PrimExpr> args) { \ return ir::CallNode::make(args[0].dtype(), kName, args, \ ir::CallNode::PureIntrinsic); \ } \ static constexpr const char* kName = IntrinStr; \ }; \ template<typename TA> \ inline PCallExpr<OpName, TA> \ FuncName(const Pattern<TA>& a) { \ return PCallExpr<OpName, TA>(a.derived()); \ } TVM_PATTERN_UNARY_INTRIN(operator~, PBitwiseNotOp, "bitwise_not"); // if_then_else struct PIfThenElseOp { static PrimExpr Eval(Array<PrimExpr> args) { return ir::CallNode::make( args[1].dtype(), kName, args, ir::CallNode::PureIntrinsic); } static constexpr const char* kName = "tvm_if_then_else"; }; /*! * \brief Construct a if_then_else pattern. * * \param cond The condition expression. * \param true_value The value when condition is true. * \param true_value The value when condition is false. * * \return The result pattern. * * \tparam TCond The pattern type of the condition. * \tparam TA The pattern type of the true operand. * \tparam TB The pattern type of the false operand. */ template<typename TCond, typename TA, typename TB> inline PCallExpr<PIfThenElseOp, TCond, TA, TB> if_then_else(const Pattern<TCond>& cond, const Pattern<TA>& true_value, const Pattern<TB>& false_value) { return PCallExpr<PIfThenElseOp, TCond, TA, TB>( cond.derived(), true_value.derived(), false_value.derived()); } } // namespace arith } // namespace tvm #endif // TVM_ARITHMETIC_PATTERN_MATCH_H_
[ "noreply@github.com" ]
wweic.noreply@github.com
09d3e0d1a09de1d84a6f2eb3129989bc44c2686a
4a733728d963da15fbc41b98ecf70e1a2e7a92de
/Labs/student/student.cpp
45bd43fb64d675f9a268377b60e7327c4089ef39
[]
no_license
bcao4/385-workspace
ae6557eca1750f74b9c3e1016f5ba0b7ea19c070
1530fa55cc9ae9e311da75152b890f2f9be0a29d
refs/heads/main
2023-01-12T02:52:51.182593
2020-11-10T20:05:30
2020-11-10T20:05:30
311,772,061
0
0
null
null
null
null
UTF-8
C++
false
false
3,173
cpp
/******************************************************************************* * Name : student.cpp * Author : Brandon Cao * Version : 1.0 * Date : September 4th, 2019 * Description : Student class with names, gpa, and id. Lists all students and finds students with a GPA lower than 1.0. * Pledge : I pledge my honor that I have abided by the Stevens Honor System. ******************************************************************************/ #include <iostream> #include <iomanip> #include <vector> using namespace std; class Student { public: Student(string first, string last, float gpa, int id) : first_{first}, last_{last}, gpa_{gpa}, id_{id} {}; //Methods string full_name() const { return first_ + " " + last_; } int id() const { return id_; } float gpa() const { return gpa_; } void set_gpa(float gpa) { gpa_ = gpa; } void set_id(int id) { id_ = id; } void print_info() const { cout<<full_name()<<", GPA: "<<fixed<<setprecision(2)<<gpa_<<", ID: "<<id_<<endl; } private: string first_; string last_; float gpa_; int id_; }; /** * Takes a vector of Student objects, and returns a new vector * with all Students whose GPA is < 1.0. */ vector<Student> failing_students; vector<Student> find_failing_students(const vector<Student> &students) { // Iterates through the students vector, appending each student whose gpa is // less than 1.0 to the failing_students vector. for(size_t i = 0; i < students.size(); i++) { if(students[i].gpa() < 1.0) { failing_students.push_back(students[i]); } } return failing_students; } /** * Takes a vector of Student objects and prints them to the screen. */ void print_students(const vector<Student> &students) { // Iterates through the students vector, calling print_info() for each student. for(size_t i = 0; i < students.size(); i++) { students[i].print_info(); } } /** * Allows the user to enter information for multiple students, then * find those students whose GPA is below 1.0 and prints them to the * screen. */ int main() { string first_name, last_name; float gpa; int id; char repeat; vector<Student> students; do { cout << "Enter student's first name: "; cin >> first_name; cout << "Enter student's last name: "; cin >> last_name; gpa = -1; while (gpa < 0 || gpa > 4) { cout << "Enter student's GPA (0.0-4.0): "; cin >> gpa; } cout << "Enter student's ID: "; cin >> id; students.push_back(Student(first_name, last_name, gpa, id)); cout << "Add another student to database (Y/N)? "; cin >> repeat; } while (repeat == 'Y' || repeat == 'y'); cout << endl << "All students:" << endl; print_students(students); cout << endl << "Failing students:"; if(find_failing_students(students).size() == 0) { cout<<" None"<<endl; } else { cout<<endl; print_students(failing_students); } return 0; }
[ "brandoncao74@gmail.com" ]
brandoncao74@gmail.com
2c7cf3e2b4518037fa005e7653578cce151a84cd
24f26275ffcd9324998d7570ea9fda82578eeb9e
/ui/message_center/views/message_view.cc
e54d4da784b097f847dcb4ab1f185d7d10ebe71c
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
14,454
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/message_center/views/message_view.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/shadow_util.h" #include "ui/gfx/shadow_value.h" #include "ui/message_center/message_center.h" #include "ui/message_center/public/cpp/message_center_constants.h" #include "ui/message_center/views/notification_background_painter.h" #include "ui/message_center/views/notification_control_buttons_view.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/style/platform_style.h" #include "ui/views/widget/widget.h" #if defined(OS_WIN) #include "ui/base/win/shell.h" #endif namespace message_center { namespace { constexpr SkColor kBorderColor = SkColorSetARGB(0x1F, 0x0, 0x0, 0x0); // Creates a text for spoken feedback from the data contained in the // notification. base::string16 CreateAccessibleName(const Notification& notification) { if (!notification.accessible_name().empty()) return notification.accessible_name(); // Fall back to a text constructed from the notification. std::vector<base::string16> accessible_lines = { notification.title(), notification.message(), notification.context_message()}; std::vector<NotificationItem> items = notification.items(); for (size_t i = 0; i < items.size() && i < kNotificationMaximumItems; ++i) { accessible_lines.push_back(items[i].title + base::ASCIIToUTF16(" ") + items[i].message); } return base::JoinString(accessible_lines, base::ASCIIToUTF16("\n")); } bool ShouldShowAeroShadowBorder() { #if defined(OS_WIN) return ui::win::IsAeroGlassEnabled(); #else return false; #endif } } // namespace // static const char MessageView::kViewClassName[] = "MessageView"; class MessageView::HighlightPathGenerator : public views::HighlightPathGenerator { public: HighlightPathGenerator() = default; // views::HighlightPathGenerator: SkPath GetHighlightPath(const views::View* view) override { return static_cast<const MessageView*>(view)->GetHighlightPath(); } private: DISALLOW_COPY_AND_ASSIGN(HighlightPathGenerator); }; MessageView::MessageView(const Notification& notification) : notification_id_(notification.id()), slide_out_controller_(this, this) { SetFocusBehavior(FocusBehavior::ALWAYS); focus_ring_ = views::FocusRing::Install(this); views::HighlightPathGenerator::Install( this, std::make_unique<HighlightPathGenerator>()); // TODO(amehfooz): Remove explicit color setting after native theme changes. focus_ring_->SetColor(gfx::kGoogleBlue500); // Paint to a dedicated layer to make the layer non-opaque. SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); UpdateWithNotification(notification); UpdateCornerRadius(0, 0); // If Aero is enabled, set shadow border. if (ShouldShowAeroShadowBorder()) { const auto& shadow = gfx::ShadowDetails::Get(2, 0); gfx::Insets ninebox_insets = gfx::ShadowValue::GetBlurRegion(shadow.values); SetBorder(views::CreateBorderPainter( views::Painter::CreateImagePainter(shadow.ninebox_image, ninebox_insets), -gfx::ShadowValue::GetMargin(shadow.values))); } } MessageView::~MessageView() { RemovedFromWidget(); } void MessageView::UpdateWithNotification(const Notification& notification) { pinned_ = notification.pinned(); base::string16 new_accessible_name = CreateAccessibleName(notification); if (new_accessible_name != accessible_name_) { accessible_name_ = new_accessible_name; NotifyAccessibilityEvent(ax::mojom::Event::kTextChanged, true); } slide_out_controller_.set_slide_mode(CalculateSlideMode()); } void MessageView::SetIsNested() { DCHECK(!is_nested_) << "MessageView::SetIsNested() is called twice wrongly."; is_nested_ = true; // Update enability since it might be changed by "is_nested" flag. slide_out_controller_.set_slide_mode(CalculateSlideMode()); slide_out_controller_.set_update_opacity(false); SetBorder(views::CreateRoundedRectBorder( kNotificationBorderThickness, kNotificationCornerRadius, kBorderColor)); if (GetControlButtonsView()) GetControlButtonsView()->ShowCloseButton(GetMode() != Mode::PINNED); } void MessageView::CloseSwipeControl() { slide_out_controller_.CloseSwipeControl(); } void MessageView::SlideOutAndClose(int direction) { slide_out_controller_.SlideOutAndClose(direction); } void MessageView::SetExpanded(bool expanded) { // Not implemented by default. } bool MessageView::IsExpanded() const { // Not implemented by default. return false; } bool MessageView::IsAutoExpandingAllowed() const { // Allowed by default. return true; } bool MessageView::IsManuallyExpandedOrCollapsed() const { // Not implemented by default. return false; } void MessageView::SetManuallyExpandedOrCollapsed(bool value) { // Not implemented by default. } void MessageView::UpdateCornerRadius(int top_radius, int bottom_radius) { SetCornerRadius(top_radius, bottom_radius); SetBackground(views::CreateBackgroundFromPainter( std::make_unique<NotificationBackgroundPainter>(top_radius, bottom_radius))); SchedulePaint(); } SkPath MessageView::GetHighlightPath() const { gfx::Rect rect(GetBoundsInScreen().size()); // Shrink focus ring size by -kFocusHaloInset on each side to draw // them on top of the notifications. We need to do this because TrayBubbleView // has a layer that masks to bounds due to which the focus ring can not extend // outside the view. This is not required on the bottom most notification's // bottom side. int inset = -views::PlatformStyle::kFocusHaloInset; int bottom_inset = bottom_radius_ == 0 ? inset : 0; rect.Inset(gfx::Insets(inset, inset, bottom_inset, inset)); int top_radius = std::max(0, top_radius_ - inset); int bottom_radius = std::max(0, bottom_radius_ - inset); SkScalar radii[8] = {top_radius, top_radius, // top-left top_radius, top_radius, // top-right bottom_radius, bottom_radius, // bottom-right bottom_radius, bottom_radius}; // bottom-left return SkPath().addRoundRect(gfx::RectToSkRect(rect), radii); } void MessageView::OnContainerAnimationStarted() { // Not implemented by default. } void MessageView::OnContainerAnimationEnded() { // Not implemented by default. } void MessageView::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ax::mojom::Role::kButton; node_data->AddStringAttribute( ax::mojom::StringAttribute::kRoleDescription, l10n_util::GetStringUTF8( IDS_MESSAGE_NOTIFICATION_SETTINGS_BUTTON_ACCESSIBLE_NAME)); node_data->SetName(accessible_name_); } bool MessageView::OnMousePressed(const ui::MouseEvent& event) { return true; } bool MessageView::OnMouseDragged(const ui::MouseEvent& event) { return true; } void MessageView::OnMouseReleased(const ui::MouseEvent& event) { if (!event.IsOnlyLeftMouseButton()) return; MessageCenter::Get()->ClickOnNotification(notification_id_); } bool MessageView::OnKeyPressed(const ui::KeyEvent& event) { if (event.flags() != ui::EF_NONE) return false; if (event.key_code() == ui::VKEY_RETURN) { MessageCenter::Get()->ClickOnNotification(notification_id_); return true; } else if ((event.key_code() == ui::VKEY_DELETE || event.key_code() == ui::VKEY_BACK)) { MessageCenter::Get()->RemoveNotification(notification_id_, true /* by_user */); return true; } return false; } bool MessageView::OnKeyReleased(const ui::KeyEvent& event) { // Space key handling is triggerred at key-release timing. See // ui/views/controls/buttons/button.cc for why. if (event.flags() != ui::EF_NONE || event.key_code() != ui::VKEY_SPACE) return false; MessageCenter::Get()->ClickOnNotification(notification_id_); return true; } void MessageView::OnPaint(gfx::Canvas* canvas) { if (ShouldShowAeroShadowBorder()) { // If the border is shadow, paint border first. OnPaintBorder(canvas); // Clip at the border so we don't paint over it. canvas->ClipRect(GetContentsBounds()); OnPaintBackground(canvas); } else { views::View::OnPaint(canvas); } } void MessageView::OnBlur() { views::View::OnBlur(); // We paint a focus indicator. SchedulePaint(); } const char* MessageView::GetClassName() const { return kViewClassName; } void MessageView::OnGestureEvent(ui::GestureEvent* event) { switch (event->type()) { case ui::ET_GESTURE_TAP_DOWN: { SetDrawBackgroundAsActive(true); break; } case ui::ET_GESTURE_TAP_CANCEL: case ui::ET_GESTURE_END: { SetDrawBackgroundAsActive(false); break; } case ui::ET_GESTURE_TAP: { SetDrawBackgroundAsActive(false); MessageCenter::Get()->ClickOnNotification(notification_id_); event->SetHandled(); return; } default: { // Do nothing } } if (!event->IsScrollGestureEvent() && !event->IsFlingScrollEvent()) return; if (scroller_) scroller_->OnGestureEvent(event); event->SetHandled(); } void MessageView::RemovedFromWidget() { if (!focus_manager_) return; focus_manager_->RemoveFocusChangeListener(this); focus_manager_ = nullptr; } void MessageView::AddedToWidget() { focus_manager_ = GetFocusManager(); if (focus_manager_) focus_manager_->AddFocusChangeListener(this); } ui::Layer* MessageView::GetSlideOutLayer() { return is_nested_ ? layer() : GetWidget()->GetLayer(); } void MessageView::OnSlideStarted() { for (auto& observer : slide_observers_) { observer.OnSlideStarted(notification_id_); } } void MessageView::OnSlideChanged(bool in_progress) { for (auto& observer : slide_observers_) { observer.OnSlideChanged(notification_id_); } } void MessageView::AddSlideObserver(MessageView::SlideObserver* observer) { slide_observers_.AddObserver(observer); } void MessageView::RemoveSlideObserver(MessageView::SlideObserver* observer) { slide_observers_.RemoveObserver(observer); } void MessageView::OnSlideOut() { MessageCenter::Get()->RemoveNotification(notification_id_, true /* by_user */); for (auto& observer : slide_observers_) observer.OnSlideOut(notification_id_); } void MessageView::OnWillChangeFocus(views::View* before, views::View* now) {} void MessageView::OnDidChangeFocus(views::View* before, views::View* now) { if (Contains(before) || Contains(now) || (GetControlButtonsView() && (GetControlButtonsView()->Contains(before) || GetControlButtonsView()->Contains(now)))) { UpdateControlButtonsVisibility(); } } views::SlideOutController::SlideMode MessageView::CalculateSlideMode() const { if (disable_slide_) return views::SlideOutController::SlideMode::kNone; switch (GetMode()) { case Mode::SETTING: return views::SlideOutController::SlideMode::kNone; case Mode::PINNED: return views::SlideOutController::SlideMode::kPartial; case Mode::NORMAL: return views::SlideOutController::SlideMode::kFull; } NOTREACHED(); return views::SlideOutController::SlideMode::kFull; } MessageView::Mode MessageView::GetMode() const { if (setting_mode_) return Mode::SETTING; // Only nested notifications can be pinned. Standalones (i.e. popups) can't // be. if (pinned_ && is_nested_) return Mode::PINNED; return Mode::NORMAL; } float MessageView::GetSlideAmount() const { return slide_out_controller_.gesture_amount(); } void MessageView::SetSettingMode(bool setting_mode) { setting_mode_ = setting_mode; slide_out_controller_.set_slide_mode(CalculateSlideMode()); UpdateControlButtonsVisibility(); } void MessageView::DisableSlideForcibly(bool disable) { disable_slide_ = disable; slide_out_controller_.set_slide_mode(CalculateSlideMode()); } void MessageView::SetSlideButtonWidth(int control_button_width) { slide_out_controller_.SetSwipeControlWidth(control_button_width); } void MessageView::SetCornerRadius(int top_radius, int bottom_radius) { top_radius_ = top_radius; bottom_radius_ = bottom_radius; } void MessageView::OnCloseButtonPressed() { MessageCenter::Get()->RemoveNotification(notification_id_, true /* by_user */); } void MessageView::OnSettingsButtonPressed(const ui::Event& event) { MessageCenter::Get()->ClickOnSettingsButton(notification_id_); } void MessageView::OnSnoozeButtonPressed(const ui::Event& event) { // No default implementation for snooze. } bool MessageView::ShouldShowControlButtons() const { #if defined(OS_CHROMEOS) // Users on ChromeOS are used to the Settings and Close buttons not being // visible at all times, but users on other platforms expect them to be // visible. auto* control_buttons_view = GetControlButtonsView(); return control_buttons_view && (control_buttons_view->IsAnyButtonFocused() || (GetMode() != Mode::SETTING && IsMouseHovered())); #else return true; #endif } void MessageView::UpdateControlButtonsVisibility() { auto* control_buttons_view = GetControlButtonsView(); if (control_buttons_view) control_buttons_view->ShowButtons(ShouldShowControlButtons()); } void MessageView::SetDrawBackgroundAsActive(bool active) { background()->SetNativeControlColor(active ? kHoveredButtonBackgroundColor : kNotificationBackgroundColor); SchedulePaint(); } } // namespace message_center
[ "rjkroege@chromium.org" ]
rjkroege@chromium.org
8192f29692c19337b7958cba56b1290e2655c848
5838cf8f133a62df151ed12a5f928a43c11772ed
/NT/net/mmc/dhcp/mscopepp.cpp
cd4cf03e43a68caf183b39857a64e8ae58b14ffa
[]
no_license
proaholic/Win2K3
e5e17b2262f8a2e9590d3fd7a201da19771eb132
572f0250d5825e7b80920b6610c22c5b9baaa3aa
refs/heads/master
2023-07-09T06:15:54.474432
2021-08-11T09:09:14
2021-08-11T09:09:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,342
cpp
/**********************************************************************/ /** Microsoft Windows/NT **/ /** Copyright(c) Microsoft Corporation, 1997 - 1999 **/ /**********************************************************************/ /* MScopePP.cpp This file contains all of the implementation for the scope property page. FILE HISTORY: */ #include "stdafx.h" #include "nodes.h" #include "mscopepp.h" #include "mscope.h" #include "server.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // // CMScopeProperties holder // ///////////////////////////////////////////////////////////////////////////// CMScopeProperties::CMScopeProperties ( ITFSNode * pNode, IComponentData * pComponentData, ITFSComponentData * pTFSCompData, LPCTSTR pszSheetName ) : CPropertyPageHolderBase(pNode, pComponentData, pszSheetName) { //ASSERT(pFolderNode == GetContainerNode()); m_bAutoDeletePages = FALSE; // we have the pages as embedded members m_liVersion.QuadPart = 0; AddPageToList((CPropertyPageBase*) &m_pageGeneral); AddPageToList((CPropertyPageBase*) &m_pageLifetime); Assert(pTFSCompData != NULL); m_spTFSCompData.Set(pTFSCompData); } CMScopeProperties::~CMScopeProperties() { RemovePageFromList((CPropertyPageBase*) &m_pageGeneral, FALSE); RemovePageFromList((CPropertyPageBase*) &m_pageLifetime, FALSE); } void CMScopeProperties::SetVersion ( LARGE_INTEGER & liVersion ) { m_liVersion = liVersion; } ///////////////////////////////////////////////////////////////////////////// // CScopePropGeneral property page IMPLEMENT_DYNCREATE(CMScopePropGeneral, CPropertyPageBase) CMScopePropGeneral::CMScopePropGeneral() : CPropertyPageBase(CMScopePropGeneral::IDD) { //{{AFX_DATA_INIT(CMScopePropGeneral) m_strComment = _T(""); m_strName = _T(""); //}}AFX_DATA_INIT m_bUpdateInfo = FALSE; m_bUpdateLease = FALSE; m_bUpdateRange = FALSE; m_bUpdateTTL = FALSE; m_uImage = 0; } CMScopePropGeneral::~CMScopePropGeneral() { } void CMScopePropGeneral::DoDataExchange(CDataExchange* pDX) { CPropertyPageBase::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMScopePropGeneral) DDX_Control(pDX, IDC_EDIT_SCOPE_NAME, m_editName); DDX_Control(pDX, IDC_EDIT_SCOPE_COMMENT, m_editComment); DDX_Control(pDX, IDC_EDIT_TTL, m_editTTL); DDX_Control(pDX, IDC_RADIO_LEASE_UNLIMITED, m_radioUnlimited); DDX_Control(pDX, IDC_RADIO_LEASE_LIMITED, m_radioLimited); DDX_Control(pDX, IDC_EDIT_LEASE_MINUTES, m_editMinutes); DDX_Control(pDX, IDC_EDIT_LEASE_HOURS, m_editHours); DDX_Control(pDX, IDC_EDIT_LEASE_DAYS, m_editDays); DDX_Control(pDX, IDC_SPIN_TTL, m_spinTTL); DDX_Control(pDX, IDC_SPIN_LEASE_HOURS, m_spinHours); DDX_Control(pDX, IDC_SPIN_LEASE_MINUTES, m_spinMinutes); DDX_Control(pDX, IDC_SPIN_LEASE_DAYS, m_spinDays); DDX_Text(pDX, IDC_EDIT_SCOPE_COMMENT, m_strComment); DDX_Text(pDX, IDC_EDIT_SCOPE_NAME, m_strName); //}}AFX_DATA_MAP DDX_Control(pDX, IDC_IPADDR_START, m_ipaStart); DDX_Control(pDX, IDC_IPADDR_END, m_ipaEnd); } BEGIN_MESSAGE_MAP(CMScopePropGeneral, CPropertyPageBase) //{{AFX_MSG_MAP(CMScopePropGeneral) ON_BN_CLICKED(IDC_RADIO_LEASE_LIMITED, OnRadioLeaseLimited) ON_BN_CLICKED(IDC_RADIO_LEASE_UNLIMITED, OnRadioLeaseUnlimited) ON_EN_CHANGE(IDC_EDIT_LEASE_DAYS, OnChangeEditLeaseDays) ON_EN_CHANGE(IDC_EDIT_LEASE_HOURS, OnChangeEditLeaseHours) ON_EN_CHANGE(IDC_EDIT_LEASE_MINUTES, OnChangeEditLeaseMinutes) ON_EN_CHANGE(IDC_EDIT_TTL, OnChangeEditTTL) ON_EN_CHANGE(IDC_EDIT_SCOPE_COMMENT, OnChangeEditScopeComment) ON_EN_CHANGE(IDC_EDIT_SCOPE_NAME, OnChangeEditScopeName) //}}AFX_MSG_MAP ON_EN_CHANGE(IDC_IPADDR_START, OnChangeIpAddrStart) ON_EN_CHANGE(IDC_IPADDR_END, OnChangeIpAddrStart) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMScopePropGeneral message handlers BOOL CMScopePropGeneral::OnInitDialog() { CPropertyPageBase::OnInitDialog(); m_ipaStart.SetAddress(m_ScopeCfg.m_dwStartAddress); m_ipaEnd.SetAddress(m_ScopeCfg.m_dwEndAddress); m_spinMinutes.SetRange(0, 59); m_spinHours.SetRange(0, 23); m_spinDays.SetRange(0, 999); m_editMinutes.LimitText(2); m_editHours.LimitText(2); m_editDays.LimitText(3); // Limit the name and comment field to 255 chars CEdit *pEditName = reinterpret_cast<CEdit *>(GetDlgItem( IDC_EDIT_SCOPE_NAME )); if ( 0 != pEditName ) { pEditName->LimitText( MAX_NAME_LENGTH ); // max characters for superscope name } CEdit *pEditComment = reinterpret_cast<CEdit *>(GetDlgItem( IDC_EDIT_SCOPE_COMMENT )); if ( 0 != pEditComment ) { pEditComment->LimitText( MAX_NAME_LENGTH ); // max characters for superscope name } // fill in the name & comment m_editName.SetWindowText(m_SubnetInfo.SubnetName); m_editComment.SetWindowText(m_SubnetInfo.SubnetComment); // fill in lease time info if (m_ScopeCfg.m_dwLeaseTime != DHCP_INFINIT_LEASE) { int nDays, nHours, nMinutes; UtilConvertLeaseTime(m_ScopeCfg.m_dwLeaseTime, &nDays, &nHours, &nMinutes); m_spinDays.SetPos(nDays); m_spinHours.SetPos(nHours); m_spinMinutes.SetPos(nMinutes); } // setup the lease time controls ActivateDuration (m_ScopeCfg.m_dwLeaseTime != DHCP_INFINIT_LEASE); m_radioUnlimited.SetCheck(m_ScopeCfg.m_dwLeaseTime == DHCP_INFINIT_LEASE); m_radioLimited.SetCheck(m_ScopeCfg.m_dwLeaseTime != DHCP_INFINIT_LEASE); // set the ttl m_spinTTL.SetRange(1, 255); m_spinTTL.SetPos(m_SubnetInfo.TTL); // load the correct icon for (int i = 0; i < ICON_IDX_MAX; i++) { if (g_uIconMap[i][1] == m_uImage) { HICON hIcon = LoadIcon(AfxGetResourceHandle(), MAKEINTRESOURCE(g_uIconMap[i][0])); if (hIcon) ((CStatic *) GetDlgItem(IDC_STATIC_ICON))->SetIcon(hIcon); break; } } SetDirty(FALSE); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CMScopePropGeneral::OnRadioLeaseLimited() { ActivateDuration(TRUE); SetDirty(TRUE); } void CMScopePropGeneral::OnRadioLeaseUnlimited() { ActivateDuration(FALSE); SetDirty(TRUE); } BOOL CMScopePropGeneral::OnApply() { // this gets the name and comment UpdateData(); // grab the lease time DWORD dwLeaseTime; if (m_radioUnlimited.GetCheck()) { dwLeaseTime = DHCP_INFINIT_LEASE; } else { dwLeaseTime = UtilConvertLeaseTime(m_spinDays.GetPos(), m_spinHours.GetPos(), m_spinMinutes.GetPos()); } if (dwLeaseTime == 0) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); DhcpMessageBox(IDS_ERR_NO_DURATION_SPECIFIED); m_editDays.SetFocus(); return FALSE; } if (dwLeaseTime != m_ScopeCfg.m_dwLeaseTime) { m_bUpdateLease = TRUE; m_ScopeCfgTemp.m_dwLeaseTime = dwLeaseTime; } m_bUpdateInfo = (m_editName.GetModify() || m_editComment.GetModify()); // grab the TTL CString strTemp; DWORD dwTemp; m_editTTL.GetWindowText(strTemp); FCvtAsciiToInteger((LPCTSTR) strTemp, &dwTemp); m_SubnetInfoTemp.TTL = LOBYTE(LOWORD(dwTemp)); if ( (dwTemp < 1) || (dwTemp > 255) ) { // invalid TTL specified AfxMessageBox(IDS_INVALID_TTL); m_editTTL.SetFocus(); m_editTTL.SetSel(0,-1); return FALSE; } if (m_SubnetInfo.TTL != m_SubnetInfoTemp.TTL) { m_bUpdateInfo = TRUE; } // grab the addresses if (m_ipaStart.GetModify() || m_ipaEnd.GetModify() ) { m_bUpdateRange = TRUE; m_ipaStart.GetAddress(&m_ScopeCfgTemp.m_dwStartAddress); m_ipaEnd.GetAddress(&m_ScopeCfgTemp.m_dwEndAddress); } // call the base on apply which does the thread switch for us // and we come back through OnPropertyChange BOOL bRet = CPropertyPageBase::OnApply(); if (bRet == FALSE) { // Something bad happened... grab the error code AFX_MANAGE_STATE(AfxGetStaticModuleState( )); ::DhcpMessageBox(GetHolder()->GetError()); } m_editName.SetModify(FALSE); m_editComment.SetModify(FALSE); m_editTTL.SetModify(FALSE); return bRet; } BOOL CMScopePropGeneral::OnPropertyChange(BOOL bScope, LONG_PTR *ChangeMask) { CDhcpMScope * pScope; SPITFSNode spNode; DWORD dwError = 0; spNode = GetHolder()->GetNode(); pScope = GETHANDLER(CDhcpMScope, spNode); BEGIN_WAIT_CURSOR; // // Check to see if we need to update the least time // if (m_bUpdateLease) { // Lease time changed, update on server dwError = pScope->SetLeaseTime(m_ScopeCfgTemp.m_dwLeaseTime); if (dwError != ERROR_SUCCESS) { GetHolder()->SetError(dwError); } else { m_ScopeCfg.m_dwLeaseTime = m_ScopeCfgTemp.m_dwLeaseTime; m_bUpdateLease = FALSE; } } // // Now check the allocation range // if (m_bUpdateRange) { // need to update the address pool allocation range DHCP_IP_RANGE dhcpIpRange; dhcpIpRange.StartAddress = m_ScopeCfgTemp.m_dwStartAddress; dhcpIpRange.EndAddress = m_ScopeCfgTemp.m_dwEndAddress; dwError = pScope->UpdateIpRange(&dhcpIpRange); if (dwError != ERROR_SUCCESS) { GetHolder()->SetError(dwError); } else { m_ScopeCfg.m_dwStartAddress = m_ScopeCfgTemp.m_dwStartAddress; m_ScopeCfg.m_dwEndAddress = m_ScopeCfgTemp.m_dwEndAddress; m_bUpdateRange = FALSE; } } // // Update the name and comment if necessary // LPCTSTR pNewName = NULL; CString strDisplay, strOldComment; strOldComment = pScope->GetComment(); if (m_bUpdateInfo) { // update the comment m_SubnetInfoTemp.SubnetComment = m_strComment; pScope->SetComment(m_strComment); // name m_SubnetInfoTemp.SubnetName = m_strName; pNewName = (LPCTSTR) m_strName; *ChangeMask = SCOPE_PANE_CHANGE_ITEM_DATA; // Lease time changed, update on server dwError = pScope->SetTTL(m_SubnetInfoTemp.TTL); // try to set the new info dwError = pScope->SetInfo(pNewName); if (dwError != ERROR_SUCCESS) { // failed, revert to old info pScope->SetComment(strOldComment); GetHolder()->SetError(dwError); } else { // success, rebuild display name pScope->BuildDisplayName(&strDisplay, pNewName); pScope->SetDisplayName(strDisplay); m_SubnetInfo = m_SubnetInfoTemp; m_bUpdateInfo = FALSE; } } END_WAIT_CURSOR; return FALSE; } void CMScopePropGeneral::OnChangeEditLeaseDays() { ValidateLeaseTime(); SetDirty(TRUE); } void CMScopePropGeneral::OnChangeEditLeaseHours() { ValidateLeaseTime(); SetDirty(TRUE); } void CMScopePropGeneral::OnChangeEditLeaseMinutes() { ValidateLeaseTime(); SetDirty(TRUE); } void CMScopePropGeneral::OnChangeEditTTL() { SetDirty(TRUE); } void CMScopePropGeneral::OnChangeEditScopeComment() { SetDirty(TRUE); } void CMScopePropGeneral::OnChangeEditScopeName() { SetDirty(TRUE); } void CMScopePropGeneral::OnChangeIpAddrStart() { SetDirty(TRUE); } void CMScopePropGeneral::OnChangeIpAddrEnd() { SetDirty(TRUE); } // // Helpers // void CMScopePropGeneral::ActivateDuration ( BOOL fActive ) { m_spinMinutes.EnableWindow(fActive); m_spinHours.EnableWindow(fActive); m_spinDays.EnableWindow(fActive); m_editMinutes.EnableWindow(fActive); m_editHours.EnableWindow(fActive); m_editDays.EnableWindow(fActive); GetDlgItem(IDC_STATIC_DAYS)->EnableWindow(fActive); GetDlgItem(IDC_STATIC_HOURS)->EnableWindow(fActive); GetDlgItem(IDC_STATIC_MINUTES)->EnableWindow(fActive); } void CMScopePropGeneral::ValidateLeaseTime() { CString strText; if (IsWindow(m_editHours.GetSafeHwnd())) { m_editHours.GetWindowText(strText); // check to see if the value is greater than the max if (_ttoi(strText) > HOURS_MAX) { LPTSTR pBuf = strText.GetBuffer(5); _itot(HOURS_MAX, pBuf, 10); strText.ReleaseBuffer(); m_editHours.SetWindowText(strText); m_spinHours.SetPos(HOURS_MAX); MessageBeep(MB_ICONEXCLAMATION); } } if (IsWindow(m_editMinutes.GetSafeHwnd())) { m_editMinutes.GetWindowText(strText); // check to see if the value is greater than the max if (_ttoi(strText) > MINUTES_MAX) { LPTSTR pBuf = strText.GetBuffer(5); _itot(MINUTES_MAX, pBuf, 10); strText.ReleaseBuffer(); m_editMinutes.SetWindowText(strText); m_spinMinutes.SetPos(MINUTES_MAX); MessageBeep(MB_ICONEXCLAMATION); } } } ///////////////////////////////////////////////////////////////////////////// // CMScopePropLifetime property page IMPLEMENT_DYNCREATE(CMScopePropLifetime, CPropertyPageBase) CMScopePropLifetime::CMScopePropLifetime() : CPropertyPageBase(CMScopePropLifetime::IDD) { //{{AFX_DATA_INIT(CMScopePropLifetime) //}}AFX_DATA_INIT m_Expiry.dwLowDateTime = DHCP_DATE_TIME_INFINIT_LOW; m_Expiry.dwHighDateTime = DHCP_DATE_TIME_INFINIT_HIGH; } CMScopePropLifetime::~CMScopePropLifetime() { } void CMScopePropLifetime::DoDataExchange(CDataExchange* pDX) { CPropertyPageBase::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMScopePropLifetime) DDX_Control(pDX, IDC_RADIO_MSCOPE_FINITE, m_radioFinite); DDX_Control(pDX, IDC_RADIO_MSCOPE_INFINITE, m_radioInfinite); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMScopePropLifetime, CPropertyPageBase) //{{AFX_MSG_MAP(CMScopePropLifetime) ON_NOTIFY(DTN_DATETIMECHANGE, IDC_DATETIMEPICKER_TIME, OnDatetimechangeDatetimepickerTime) ON_NOTIFY(DTN_DATETIMECHANGE, IDC_DATETIMEPICKER_DATE, OnDatetimechangeDatetimepickerDate) ON_BN_CLICKED(IDC_RADIO_MSCOPE_INFINITE, OnRadioScopeInfinite) ON_BN_CLICKED(IDC_RADIO_MSCOPE_FINITE, OnRadioMscopeFinite) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMScopePropLifetime message handlers BOOL CMScopePropLifetime::OnInitDialog() { CPropertyPageBase::OnInitDialog(); if ( (m_Expiry.dwLowDateTime == DHCP_DATE_TIME_INFINIT_LOW) && (m_Expiry.dwHighDateTime == DHCP_DATE_TIME_INFINIT_HIGH) ) { m_radioInfinite.SetCheck(TRUE); } else { SYSTEMTIME st; FILETIME ft; m_radioFinite.SetCheck(TRUE); FileTimeToLocalFileTime((FILETIME *) &m_Expiry, &ft); FileTimeToSystemTime(&ft, &st); ::SendMessage(GetDlgItem(IDC_DATETIMEPICKER_DATE)->GetSafeHwnd(), DTM_SETSYSTEMTIME, 0, (LPARAM) &st); ::SendMessage(GetDlgItem(IDC_DATETIMEPICKER_TIME)->GetSafeHwnd(), DTM_SETSYSTEMTIME, 0, (LPARAM) &st); } UpdateControls(); SetDirty(FALSE); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } BOOL CMScopePropLifetime::OnApply() { DATE_TIME datetime; if (m_radioInfinite.GetCheck()) { datetime.dwLowDateTime = DHCP_DATE_TIME_INFINIT_LOW; datetime.dwHighDateTime = DHCP_DATE_TIME_INFINIT_HIGH; } else { SYSTEMTIME stDate, stTime; ::SendMessage(GetDlgItem(IDC_DATETIMEPICKER_DATE)->GetSafeHwnd(), DTM_GETSYSTEMTIME, 0, (LPARAM) &stDate); ::SendMessage(GetDlgItem(IDC_DATETIMEPICKER_TIME)->GetSafeHwnd(), DTM_GETSYSTEMTIME, 0, (LPARAM) &stTime); SYSTEMTIME systemtime; systemtime.wYear = stDate.wYear; systemtime.wMonth = stDate.wMonth; systemtime.wDayOfWeek = stDate.wDayOfWeek; systemtime.wDay = stDate.wDay; systemtime.wHour = stTime.wHour; systemtime.wMinute = stTime.wMinute; systemtime.wSecond = stTime.wSecond; systemtime.wMilliseconds = 0; FILETIME ft; ::SystemTimeToFileTime(&systemtime, &ft); ::LocalFileTimeToFileTime(&ft, (LPFILETIME) &datetime); } CDhcpMScope * pScope; SPITFSNode spNode; DWORD dwError = 0; spNode = GetHolder()->GetNode(); pScope = GETHANDLER(CDhcpMScope, spNode); pScope->SetLifetime(&datetime); dwError = pScope->SetInfo(NULL); if (dwError != ERROR_SUCCESS) { DhcpMessageBox(dwError); return FALSE; } return CPropertyPageBase::OnApply(); } void CMScopePropLifetime::UpdateControls() { BOOL fEnable = TRUE; if (m_radioInfinite.GetCheck()) { fEnable = FALSE; } GetDlgItem(IDC_DATETIMEPICKER_DATE)->EnableWindow(fEnable); GetDlgItem(IDC_DATETIMEPICKER_TIME)->EnableWindow(fEnable); } void CMScopePropLifetime::OnDatetimechangeDatetimepickerTime(NMHDR* pNMHDR, LRESULT* pResult) { SetDirty(TRUE); *pResult = 0; } void CMScopePropLifetime::OnDatetimechangeDatetimepickerDate(NMHDR* pNMHDR, LRESULT* pResult) { SetDirty(TRUE); *pResult = 0; } void CMScopePropLifetime::OnRadioScopeInfinite() { SetDirty(TRUE); UpdateControls(); } void CMScopePropLifetime::OnRadioMscopeFinite() { SetDirty(TRUE); UpdateControls(); }
[ "blindtiger@foxmail.com" ]
blindtiger@foxmail.com
18368fb287a0fb663a736002787bf98ac696c41b
ecda5557b9fba866a5ab675cb5c879249e80b77e
/day03/ex03/ScavTrap.hpp
b238724bbdc165226373a98c3bd9f1321397c140
[]
no_license
julekgwa/Piscine-CPP
3e53cb963e9639c39633fec7becec8b6c937c048
30d37fcb9a6040c2eaa103b008743815729a6e49
refs/heads/master
2021-01-22T06:19:36.610877
2017-06-02T14:38:49
2017-06-02T14:38:49
92,543,662
1
0
null
null
null
null
UTF-8
C++
false
false
365
hpp
#ifndef SCAVTRAP_HPP #define SCAVTRAP_HPP #include "ClapTrap.hpp" #include <iostream> #include <cstdlib> class ScavTrap : public ClapTrap { public: ScavTrap(void); ScavTrap(std::string); ScavTrap(ScavTrap const &); ScavTrap &operator=(ScavTrap const &); ~ScavTrap(void); void challengeNewcomer(std::string const &target); }; #endif
[ "julekgwa@e4r1p3.jnb.42.fr" ]
julekgwa@e4r1p3.jnb.42.fr
f0412818e431a68a5767e5b3a2ebd1c5140d2cce
005f6e37941b66536f6719a7bb94ab4d3d7cf418
/src/prx_utilities/prx/utilities/statistics/image.cpp
8a770eae350f8b7f81d3940be5c07c9413be4e9b
[]
no_license
warehouse-picking-automation-challenges/ru_pracsys
c56b9a873218fefb91658e08b74c4a1bc7e16628
786ce2e3e0d70d01c951028a90c117a0f23d0804
refs/heads/master
2021-05-31T05:52:33.396310
2016-02-07T22:34:39
2016-02-07T22:34:39
39,845,771
4
2
null
null
null
null
UTF-8
C++
false
false
3,874
cpp
/** * @file image.cpp * * @copyright Software License Agreement (BSD License) * Copyright (c) 2013, Rutgers the State University of New Jersey, New Brunswick * All Rights Reserved. * For a full description see the file named LICENSE. * * Authors: Andrew Dobson, Andrew Kimmel, Athanasios Krontiris, Zakary Littlefield, Kostas Bekris * * Email: pracsys@googlegroups.com */ #include "prx/utilities/statistics/image.hpp" namespace prx { namespace util { image_t::image_t( unsigned w, unsigned h ) { width = w; height = h; image.resize(width * height * 4); clear(); zero_x = width/2; zero_y = height/2; max_x = width/2 - 1; max_y = height/2 - 1; min_x = -max_x; min_y = -max_y; } image_t::~image_t() { } void image_t::clear() { for(unsigned y = 0; y < height; y++) for(unsigned x = 0; x < width; x++) { image[4 * width * y + 4 * x + 0] = 0; image[4 * width * y + 4 * x + 1] = 0; image[4 * width * y + 4 * x + 2] = 255; image[4 * width * y + 4 * x + 3] = 255; } } void image_t::color_pixel( int coord_x, int coord_y, unsigned char red, unsigned char green, unsigned char blue ) { if( min_x <= coord_x && max_x >= coord_x ) if( min_y <= coord_y && max_y >= coord_y ) { int x_value = coord_x + zero_x; int y_value = coord_y + zero_y; unsigned char old_red = image[4 * width * y_value + 4 * x_value + 0 ]; if( old_red == 0 || old_red > red ) { image[4 * width * y_value + 4 * x_value + 0 ] = red; image[4 * width * y_value + 4 * x_value + 1 ] = green; image[4 * width * y_value + 4 * x_value + 2 ] = blue; } } } void image_t::encode( const char* filename ) { const int dimx = width, dimy = height; int i, j; FILE *fp = fopen(filename, "wb"); /* b - binary mode */ (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = image[4 * width * j + 4 * i + 0 ]; /* red */ color[1] = image[4 * width * j + 4 * i + 1 ]; /* green */ color[2] = image[4 * width * j + 4 * i + 2 ]; /* blue */ (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return; // lodepng::encode(filename, image, width, height); } double image_t::statistics( int* counter ) { double color = 0; *counter = 0; for(unsigned y = 0; y < height; y++) for(unsigned x = 0; x < width; x++) { unsigned char red = image[4 * width * y + 4 * x + 0 ]; if( red != 0 ) { color += red; *counter = *counter + 1; } } return color/ (double)(*counter); } } }
[ "kostas.bekris@cs.rutgers.edu" ]
kostas.bekris@cs.rutgers.edu
07bbbc39db54c570b0cbccd94698839886119250
d99ab6e8586f76c6e6bdec1b2fba73e7d892f5e8
/ACM/Algorithms/segmenttree.cpp
e35c42be866e47d1432d32056354604f868426f3
[]
no_license
jindalshivam09/cppcodes
661d368c77793a0c8170397711c1eec9eeff1e27
c2913c4d3e144de7a0a60749b675e2f661d5b07b
refs/heads/master
2021-05-16T02:39:47.452998
2020-07-26T18:45:42
2020-07-26T18:45:42
23,185,118
1
0
null
null
null
null
UTF-8
C++
false
false
4,910
cpp
// Program to show segment tree operations like construction, query and update #include <stdio.h> #include <math.h> // A utility function to get the middle index from corner indexes. int getMid(int s, int e) { return s + (e -s)/2; } /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int *st, int ss, int se, int qs, int qe, int index) { // If segment of this node is a part of given range, then return the // sum of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return getSumUtil(st, ss, mid, qs, qe, 2*index+1) + getSumUtil(st, mid+1, se, qs, qe, 2*index+2); } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, index, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range */ void updateValueUtil(int *st, int ss, int se, int i, int diff, int index) { // Base Case: If the input index lies outside the range of this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update the value // of the node and its children st[index] = st[index] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2*index + 1); updateValueUtil(st, mid+1, se, i, diff, 2*index + 2); } } // The function to update a value in input array and segment tree. // It uses updateValueUtil() to update the value in segment tree void updateValue(int arr[], int *st, int n, int i, int new_val) { // Check for erroneous input index if (i < 0 || i > n-1) { printf("Invalid Input"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n-1, i, diff, 0); } // Return sum of elements in range from index qs (quey start) to // qe (query end). It mainly uses getSumUtil() int getSum(int *st, int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf("Invalid Input"); return -1; } return getSumUtil(st, 0, n-1, qs, qe, 0); } // A recursive function that constructs Segment Tree for array[ss..se]. // si is index of current node in segment tree st int constructSTUtil(int arr[], int ss, int se, int *st, int si) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + constructSTUtil(arr, mid+1, se, st, si*2+2); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int *constructST(int arr[], int n) { // Allocate memory for segment tree int x = (int)(ceil(log2(n))); //Height of segment tree int max_size = 2*(int)pow(2, x) - 1; //Maximum size of segment tree int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n-1, st, 0); // Return the constructed segment tree return st; } // Driver program to test above functions int main() { int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array int *st = constructST(arr, n); // Print sum of values in array from index 1 to 3 printf("Sum of values in given range = %d\n", getSum(st, n, 1, 3)); // Update: set arr[1] = 10 and update corresponding segment // tree nodes updateValue(arr, st, n, 1, 10); // Find sum after the value is updated printf("Updated sum of values in given range = %d\n", getSum(st, n, 1, 3)); return 0; }
[ "jindalshivam09@gmail.com" ]
jindalshivam09@gmail.com
29ad95785610f9b6d5357a89948575dc5d07e2fc
fe4f0f8a36b14c838fbdd78a5908d7f6e0c8f2fb
/chromaKeying/chromaKeying.cpp
95f0acb8220ebbb9f59a51dca0e312fcf0e31975
[]
no_license
JujuDel/FancyOpenCV
e2a0d0196d36120edb0ca56415342c74b76279c2
0add33e9f4fbf8a6db0e5ff902acd3f0c9efbdea
refs/heads/master
2022-12-31T23:14:10.727144
2020-10-25T15:48:24
2020-10-25T15:48:24
268,362,515
0
0
null
null
null
null
UTF-8
C++
false
false
13,729
cpp
#include <iostream> #include <vector> #include <string> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> // ########## CONST ########## const char *g_windowImg{ "Chroma Keying" }; const char *g_windowParam{ "Parameters" }; const int g_fps{ 20 }; const cv::Size g_size{ 900, 600 }; // ########## PARAMETERS ########## // bool g_isVideoPlaying{ false }; bool g_isSamplingFrame{ true }; // For dragging bool g_dragging = false; cv::Point g_corner1, g_corner2; // Images cv::Mat g_imgFg, g_imgBg; // Array of vectors of pairs min/max for BGR colors std::vector<std::pair<double, double>> g_BGR[3]; bool goBack() { if (g_BGR[0].empty()) return false; g_BGR[0].pop_back(); g_BGR[1].pop_back(); g_BGR[2].pop_back(); return true; } // Tolerance bool g_isToleranceUp{ true }; int g_tolerance{ 0 }; std::string const g_buttonText{ "Click here to change tolerance" }; cv::Mat3b g_button; #define BUTTONTEXT (g_isToleranceUp ? "Tolerance Up" : "Tolerance Down") //! Adaptative text // Color Cast int g_colorCast{ 0 }; // Softness int g_softness{ 0 }; // ########## UTILITIES ########## // Do min/max with different types template<typename T1, typename T2> T1 myMin(const T1 &a, const T2 &b) { return a < b ? a : b; } template<typename T1, typename T2> T1 myMax(const T1 &a, const T2 &b) { return a > b ? a : b; } // Display pair content template<typename T1, typename T2> std::ostream & operator << (std::ostream &out, const std::pair<T1, T2> &p) { out << "(Min: " << p.first << "; Max: " << p.second << ")"; return out; } std::string myLower(std::string text) { std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c){ return std::tolower(c); }); return text; } // ########## FORWARD DECLARATIONS ########## // Callbacks void onMouse(int event, int x, int y, int flags, void* userdata); void onButton(int event, int x, int y, int flags, void* userdata); void onTolerance(int, void*); void onSoftness(int, void*); void onColorCast(int, void*); // Displays void header(); void writeTextButton(); void drawOverlayMessage(cv::Mat &img, const char *text); void printBGR(); // Apply Chroma Keying void chromaKeying(const cv::Mat &bg, const cv::Mat &fg, cv::Mat &dst); // Sample the current frame void samplingFrame(const cv::Mat &img, char &keyPressed); // ########## MAIN ########## int main() { // Display some text header(); // Read the videos cv::VideoCapture videoFg("greenscreen-demo.mp4"); cv::VideoCapture videoBg("newBackground.mp4"); // Check if the videos opened successfully if ( !videoFg.isOpened() || !videoBg.isOpened() ) { std::cout << "/!\\ Error opening video files /!\\" << std::endl; return -1; } // Param's window cv::namedWindow(g_windowParam); // Trackabars cv::createTrackbar("Tolerance", g_windowParam, &g_tolerance, 100, onTolerance); cv::createTrackbar("Softness", g_windowParam, &g_softness, 100, onSoftness); cv::createTrackbar("Color cast", g_windowParam, &g_colorCast, 50, onColorCast); // Mouse callback cv::setMouseCallback(g_windowParam, onButton); writeTextButton(); cv::imshow(g_windowParam, g_button); // Main window cv::namedWindow(g_windowImg); // Mouse callback cv::setMouseCallback(g_windowImg, onMouse); char keyPressed; while (keyPressed != 27) { // Capture frame-by-frame videoFg >> g_imgFg; videoBg >> g_imgBg; // If the frame is empty, break immediately if (g_imgFg.empty() || g_imgBg.empty()) break; // Resize the frames cv::resize(g_imgFg, g_imgFg, g_size); cv::resize(g_imgBg, g_imgBg, g_size); // Apply chromaKeying cv::Mat dst; chromaKeying(g_imgBg, g_imgFg, dst); if (!g_isVideoPlaying) { // Sample the current frame samplingFrame(dst, keyPressed); } else { // Draw the rectangle if (g_dragging) cv::rectangle(dst, g_corner1, g_corner2, cv::Scalar(255,255,0), 2, cv::LINE_AA); // Display the frame drawOverlayMessage( dst, "Press SPACE to pause the video" ); cv::imshow( g_windowImg, dst ); keyPressed = (char) cv::waitKey(g_fps); } // Restart videos if (keyPressed == 'R' || keyPressed == 'r') { videoFg.release(); videoBg.release(); videoFg = cv::VideoCapture("greenscreen-demo.mp4"); videoBg = cv::VideoCapture("greenscreen-asteroid.mp4"); std::cout << "Videos restarted" << std::endl; } // Z if (keyPressed == 'Z' || keyPressed == 'z') if (goBack()) std::cout << "Color sampling cancelled" << std::endl; else std::cout << "Nothing to cancel" << std::endl; // Spacebar if (keyPressed == 32) { // Pause/Play the video g_isVideoPlaying = !g_isVideoPlaying; g_isSamplingFrame = !g_isVideoPlaying; std::cout << (g_isVideoPlaying ? "Play" : "Pause") << std::endl; } // Print values if (keyPressed == 'P' || keyPressed == 'p') { std::cout << "Values:" << std::endl; printBGR(); } } // When everything done, release the video capture object videoFg.release(); videoBg.release(); if (keyPressed != 27) { std::string ans; std::cout << "End of video reached. Restart?" << std::endl; std::cout << "(Y/N)? "; std::getline(std::cin, ans); ans = myLower(ans); if (ans == "y" || ans == "yes" || ans == "o") main(); } // Closes all the frames cv::destroyAllWindows(); return 0; } // ########## CALLBACKS ########## void onMouse(int action, int x, int y, int flags, void* userdata) { if ( action == cv::EVENT_LBUTTONDOWN ) { // Register the selected point g_corner1 = cv::Point(x,y); g_corner2 = g_corner1; // Allow dragging g_dragging = true; } else if ( action == cv::EVENT_LBUTTONUP ) { // Cancel dragging g_dragging = false; // Extract the selected region cv::Point l_Size{ g_corner1 - g_corner2 }; int l_width{ std::abs(l_Size.x) }; int l_height{ std::abs(l_Size.y) }; // Update the background remover if (l_width < 2 || l_height < 2) { cv::Vec3b pix{ g_imgFg.at<cv::Vec3b>(g_corner1) }; for (int i = 0; i < 3; ++i) { if (g_BGR[i].empty()) { g_BGR[i].push_back(std::pair<double, double>(pix[i], pix[i])); } else { g_BGR[i].push_back(std::pair<double, double>( myMin(g_BGR[i].back().first, pix[i]), myMax(g_BGR[i].back().second, pix[i]) )); } } } else { int l_x{ std::min(g_corner1.x, g_corner2.x) }; int l_y{ std::min(g_corner1.y, g_corner2.y) }; cv::Mat ROI{ cv::Mat(g_imgFg, cv::Rect(l_x, l_y, l_width, l_height)) }; // Get the 3 channels cv::Mat BGR[3]; cv::split(ROI, BGR); for (int i = 0; i < 3; ++i) { // Find the global max and min in the channel double l_min, l_max; cv::minMaxLoc(BGR[i], &l_min, &l_max); // Update the background remover if (g_BGR[i].empty()) { g_BGR[i].push_back(std::pair<double, double>(l_min, l_max)); } else { g_BGR[i].push_back(std::pair<double, double>( std::min(g_BGR[i].back().first, l_min), std::max(g_BGR[i].back().second, l_max) )); } } } std::cout << "Color sampling done" << std::endl; // Sampling is done g_isSamplingFrame = false; } else if ( g_dragging ) { // Update the selected region x = std::min(g_size.width, std::max(0, x)); y = std::min(g_size.height, std::max(0, y)); g_corner2 = cv::Point(x,y); } } void onButton(int action, int x, int y, int flags, void* userdata) { if (action == cv::EVENT_LBUTTONDOWN) { g_tolerance = 0; g_isToleranceUp = !g_isToleranceUp; cv::createTrackbar("Tolerance", g_windowParam, &g_tolerance, 100, onTolerance); writeTextButton(); cv::imshow(g_windowParam, g_button); // Call onTolerance callback onTolerance(0, 0); } } void onTolerance(int, void*) { // To force display updates g_isSamplingFrame = false; } void onSoftness(int, void*) { // To force display updates g_isSamplingFrame = false; if (g_softness != 0) g_softness = 100 - g_softness; std::cout << "Not yet implemented..." << std::endl; } void onColorCast(int, void*) { // To force display updates g_isSamplingFrame = false; } // ########## DISPLAYS ########## void header() { std::cout << std::endl; std::cout << "##################################" << std::endl; std::cout << "# #" << std::endl; std::cout << "# Chroma Keying Tool #" << std::endl; std::cout << "# Julien DELCLOS #" << std::endl; std::cout << "# #" << std::endl; std::cout << "##################################" << std::endl; std::cout << std::endl; std::cout << "Press 'R' on the image to restart the videos." << std::endl; std::cout << std::endl; std::cout << "Press 'P' on the image to print the sampling values." << std::endl; std::cout << std::endl; std::cout << "Press 'Z' on the image to cancel the last sampling." << std::endl; std::cout << std::endl; std::cout << "Press 'SPACE' on the image to Play/Pause the video." << std::endl; std::cout << std::endl; std::cout << "Press 'ESC' on the image to quit." << std::endl; std::cout << std::endl; std::cout << "------------ LOG ------------" << std::endl; std::cout << std::endl; } void printBGR() { if (g_BGR[0].empty()) { std::cout << " no values" << std::endl; return; } std::cout << " B: " << g_BGR[0].back() << std::endl; std::cout << " G: " << g_BGR[1].back() << std::endl; std::cout << " R: " << g_BGR[2].back() << std::endl; } void writeTextButton() { g_button = cv::Mat3b( 50, 410, cv::Vec3b(125, 125, 125) ); int fontFace{ cv::FONT_HERSHEY_SIMPLEX }; double fontScale{ 0.5 }; int thickness{ 1 }; cv::Size smallTextSize{ cv::getTextSize(g_buttonText, fontFace, fontScale, thickness, NULL) }; cv::Size bigTextSize{ cv::getTextSize(BUTTONTEXT, fontFace, fontScale, 2, NULL) }; // Center the text cv::Point smallTextOrg( (410 - smallTextSize.width)/2, smallTextSize.height ); cv::Point bigTextOrg( (410 - bigTextSize.width)/2, 50 - bigTextSize.height ); cv::putText(g_button, g_buttonText, smallTextOrg, fontFace, fontScale, cv::Scalar(255,255,255), thickness, 8); cv::putText(g_button, BUTTONTEXT, bigTextOrg, fontFace, fontScale, cv::Scalar(255,255,255), 2, 8); } void drawOverlayMessage(cv::Mat &img, const char *text) { cv::Mat overlay{ img.clone() }; int fontFace{ cv::FONT_HERSHEY_SIMPLEX }; double fontScale{ 1 }; int thickness{ 2 }; int baseline{ 0 }; cv::Size textSize{ cv::getTextSize(text, fontFace, fontScale, thickness, &baseline) }; baseline += thickness; // Center the text cv::Point textOrg( (img.cols - textSize.width)/2, 30 ); // Draw the box cv::rectangle( overlay, textOrg + cv::Point(0, baseline), textOrg + cv::Point(textSize.width, -50), cv::Scalar(0,0,255), -1 ); // Overlay the box cv::addWeighted(overlay, 0.5, img, 0.5, 0, img); // Put the text cv::putText(img, text, textOrg, fontFace, fontScale, cv::Scalar(255, 255, 255), thickness, 8); } // ########## SAMPLING ########## void samplingFrame(const cv::Mat &img, char &keyPressed) { // Enable the looping g_isSamplingFrame = true; while (g_isSamplingFrame && keyPressed != 27) { cv::Mat l_img{ img.clone() }; drawOverlayMessage( l_img, "Select the background to remove" ); if (g_dragging) { // Draw the rectangle cv::rectangle(l_img, g_corner1, g_corner2, cv::Scalar(255,255,0), 2, cv::LINE_AA); } cv::imshow( g_windowImg, l_img ); keyPressed = (char) cv::waitKey(20); if (keyPressed == 'N' || keyPressed == 'n' || keyPressed == 'Z' || keyPressed == 'z' || keyPressed == 'P' || keyPressed == 'p' || keyPressed == 'R' || keyPressed == 'r' || keyPressed == 32) break; } } // ########## CHROMA KEYING ########## void performSoftness(const cv::Mat &fg, cv::Mat &mask) { #if 0 cv::Mat fg_gray; cv::cvtColor(fg, fg_gray, cv::COLOR_BGR2GRAY); cv::blur(fg_gray, fg_gray, cv::Size(3,3)); if (g_softness != 0) { cv::Mat canny; cv::Canny(fg_gray, canny, g_softness, g_softness*3, 3); //cv::imshow("Canny", canny); } #endif // Topic ongoing } void constructMask(const cv::Mat &fg, cv::Mat &mask) { mask = cv::Mat(fg.rows, fg.cols, CV_8UC1); double meanG{ (g_BGR[1].back().second + g_BGR[1].back().first) / 2.0 }; double tolG_m{ g_tolerance * meanG / 100.0 }; double tolG_M{ g_tolerance * meanG / 100.0}; if (g_isToleranceUp) tolG_m *= -1; else tolG_M *= -1; for (int y = 0; y < fg.rows; y++) { for (int x = 0; x < fg.cols; x++) { cv::Vec3b pix{ fg.at<cv::Vec3b>(y, x) }; if (pix.val[0] >= g_BGR[0].back().first && pix.val[0] <= g_BGR[0].back().second && pix.val[2] >= g_BGR[2].back().first && pix.val[2] <= g_BGR[2].back().second && pix.val[1] >= g_BGR[1].back().first + tolG_m && pix.val[1] <= g_BGR[1].back().second + tolG_M) { mask.at<uchar>(y,x) = 0; } else { mask.at<uchar>(y,x) = 255; } } } // Color casting cv::Mat kernel{ cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(2 * g_colorCast + 1, 2 * g_colorCast + 1)) }; cv::morphologyEx(mask, mask, cv::MORPH_CLOSE, kernel); //cv::imshow("Mask", mask); } void chromaKeying(const cv::Mat &bg, const cv::Mat &fg, cv::Mat &dst) { assert(bg.size() == fg.size()); if (g_BGR[0].empty()) { dst = fg; } else { cv::Mat mask; constructMask(fg, mask); performSoftness(fg, mask); dst = cv::Mat(fg.rows, fg.cols, CV_8UC3); for (int y = 0; y < fg.rows; y++) { for (int x = 0; x < fg.cols; x++) { if (mask.at<uchar>(y,x) == 255) dst.at<cv::Vec3b>(y,x) = fg.at<cv::Vec3b>(y,x); else dst.at<cv::Vec3b>(y,x) = bg.at<cv::Vec3b>(y,x); } } } }
[ "julien.delclos@gmail.com" ]
julien.delclos@gmail.com
bd8b138be4ac3f0c82bb6999858fa85e5dbf37df
15e82c71ee530486bd9c381dcfed35159f5de52b
/main.cpp
b36f1f9795598534e397baf50966c317fbe1baa5
[]
no_license
2017302335/BUAA_Compiler
c30a4247fd47c1ea84253fbedaffeb8b4a30d29e
f95305b33dc0895ed672d73ddc97fad669f8794b
refs/heads/master
2021-06-12T20:57:07.971226
2020-01-08T07:31:21
2020-01-08T07:31:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,384
cpp
#include <iostream> #include <fstream> #include "lexical.h" #include "grammer.h" #include "midCode.h" #include "mipsCode.h" #include "function.h" #include "optimize.h" using namespace std; extern string filecontent; //文件的内容 ifstream inputfile; ofstream outputfile; ofstream errorfile; ofstream midCodefile; ofstream mipsCodefile; int debug = 1; bool error = false; int main() { inputfile.open("testfile.txt", ios::in); outputfile.open("output.txt", ios::out); errorfile.open("error.txt", ios::out); midCodefile.open("midCode.txt", ios::out); mipsCodefile.open("mips.txt", ios::out); string tmpIn; while (getline(inputfile, tmpIn)) { //读取文件内容 filecontent.append(tmpIn); filecontent.append("\n"); } int re = getsym(); if (re < 0) { //error() } else { if (procedure()) { //success //cout << "True!" << endl; } else { //error() } } if (!error) { //midCodefile.open("midCode.txt", ios::out); //mipsCodefile.open("mips.txt", ios::out); if (debug) { showFuncMidCode(); } splitBlock(); if (debug) { showFuncBlock(); } outputMidCode(); genMips(); outputMipsCode(); //midCodefile.close(); //mipsCodefile.close(); if (debug) { showGlobal(); showAll(); showString(); } } inputfile.close(); outputfile.close(); errorfile.close(); midCodefile.close(); mipsCodefile.close(); return 0; }
[ "jwjiang_buaa@163.com" ]
jwjiang_buaa@163.com
f60831ce94c3dcacfe1dc7f44369129923e98232
532db02b9b3bfdf2fc56f90aec32f46035a6edfb
/SoEattempt3/SoEattempt3.cpp
2c362bd75f25457778f7a7d264e155cfff496038
[]
no_license
RoachCode/scions
a272d3c17add4412275cb29beceb518d4a7a4626
0487242cbf45b8dcf9be1070d59a88ba347281b7
refs/heads/main
2023-07-25T07:50:03.130457
2023-07-10T12:38:44
2023-07-10T12:38:44
310,966,830
0
0
null
null
null
null
UTF-8
C++
false
false
3,249
cpp
#include <iostream> #include <Windows.h> #include <random> #include <cstdlib> #include <ctime> #include <algorithm> // std::count #include <vector> #include <string> #include <limits.h> #include "getrandom.h" // Generates random integer. Call with "getRandom(int upperBoundRdm)" // Prints MP stat. Uses input "currentMP" - "spellCost". //#define ENABLE_DEBUG int currentMP(int counter, int spellCost) { #ifdef ENABLE_DEBUG std::cerr << "currentMP() called\n"; #endif int maxMP{ 30 }; return maxMP - (counter * spellCost); // 30 is a placeholder for max mp } void printMP(int currentMP, int spellCost) { #ifdef ENABLE_DEBUG std::cerr << "printMP(int currentMP, int spellCost) called\n"; #endif int currMP{ currentMP }; int spCost{ spellCost }; int special{ currMP - spCost }; if (special < 0) { special; } std:: cout << special; } int counter(int notUsingMP) { #ifdef ENABLE_DEBUG std::cerr << "counter(int notUsingMP) called\n"; #endif static int counter = 3; // value will be cost of mp spell int z{ ++counter - notUsingMP }; // value of nUMP 0 when using spell, otherwise 1 if reading mp return z; } int magMissile() { #ifdef ENABLE_DEBUG std::cerr << "magMissile() called\n"; #endif int main(); int spellCost{ 1 }; // gets multiplied by 3 if (currentMP(counter(4), spellCost) < spellCost) { int main(); std::cout << "\nOUT OF MANA\n"; return main(); } else if (currentMP((counter(4)), spellCost) >= spellCost) { int upperBound{ 20 }; //20 is a placeholder for max damage int ran{ getRandom(upperBound) }; if (ran == 0) { std::cout << "\nMAGIC DAMAGE:" << '\n' << "MISS\n"; std::cout << "MP: "; printMP(currentMP(counter(4), spellCost), spellCost); std::cout << " / 30 \n"; // 30 is a placeholder return main(); } else { std::cout << "\nMAGIC MISSILE DAMAGE:" << '\n' << ran << '\n'; std::cout << "MP: "; printMP(currentMP(counter(4), spellCost), spellCost); std::cout << " / 30 \n"; // 30 is a placeholder int dam{ ran + 0 }; //stats return dam; } } } int attack() { #ifdef ENABLE_DEBUG std::cerr << "attack() called\n"; #endif int main(); int spellCost{ 0 }; int upperBound{ 15 }; //15 is a placeholder int ran{ getRandom(upperBound) }; if (ran == 0) { std::cout << "\nATTACK DAMAGE:" << '\n' << "MISS\n"; return main(); } else { std::cout << "\nATTACK DAMAGE:" << '\n' << ran << '\n'; int dam{ ran + 0 }; //stats return dam; } } int bugbearHP(int dam) { int main(); static int previousHP{ 140 }; int currEnemyHP{ previousHP - dam }; previousHP = currEnemyHP; if (previousHP > 0) { std::cout << "\nBUGBEAR HP: " << previousHP << " / 140"; return main(); } if (previousHP < 0) { previousHP = 0; } if (previousHP == 0) { std::cout << "\nBUGBEAR DEAD"; previousHP = 140; return main(); } } int main() { std::cout << "\n [a] TO ATTACK\n [m] TO USE MAGIC MISSILE\n" << '\n'; char input; std::cin >> input; if (input == 'a') { int dam{ attack() }; bugbearHP(dam); return main(); } else if (input == 'm') { int dam{ magMissile() }; bugbearHP(dam); return main(); } else { std::cout << "\nINVALID ENTRY\n"; return main(); } }
[ "74122730+RoachCode@users.noreply.github.com" ]
74122730+RoachCode@users.noreply.github.com
31a1f8464b1e35efb2476c6055a8abb2bbe9a0fd
75fcc54907b3543e08f8a27521a55810bce0b839
/src/server/JoinCommand.cpp
b26e414bd7a0677dbfce0fd274da1fa92a36f0f8
[]
no_license
omerz10/Reversi-Project---Backend
f7273dfe411515302c2346404fb99f7e8a1ba942
5bebd2acf6b528a80a9b765128cc83de5810c676
refs/heads/master
2021-09-05T07:59:29.881341
2018-01-25T12:47:20
2018-01-25T12:47:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,321
cpp
// // Created by David Nakash on 24/12/2017. // #include "JoinCommand.h" #define DATALEN 512 pthread_mutex_t joinMutex; void JoinCommand::execute(ClientThread *clientT, string args) { char buffer1[DATALEN] = ""; char buffer2[DATALEN] = ""; char buffer3[DATALEN] = ""; bool found = false; // iterator unsigned long sizeOfVector = this->controller->getJoinableGames().size(); unsigned long i; for (i = 0; i < sizeOfVector; i++) { if (this->controller->getJoinableGames()[i] == args) { found = true; break; } } if (found) { pthread_mutex_lock(&joinMutex); // insert 2nd player into the game this->controller->joinGame(args, clientT); this->controller->deleteJoinableGame(i); pthread_mutex_unlock(&joinMutex); cout << "Server completed connection with 2 players.." << endl << "-------- The Game '" << args << "' Begins --------" << endl; strcpy(buffer1, "secondJoined"); // send if (write(this->controller->getGames()[args].player1.clientSocket, &buffer1, DATALEN) == -1) { throw ("Error: sending to player 1"); } strcpy(buffer2, "join"); // send if (write(this->controller->getGames()[args].player2.clientSocket, &buffer2, DATALEN) == -1) { throw ("Error: sending to player 2"); } pthread_mutex_lock(&joinMutex); clientT->status = Playing; // the players will now start playing with each other this->controller->getClientThread(args, 1)->status = Playing; this->controller->getClientThread(args, 2)->status = Playing; pthread_mutex_unlock(&joinMutex); strcpy(buffer3, "startGame"); if (write(this->controller->getGames()[args].player2.clientSocket, &buffer3, DATALEN) == -1) { throw ("Error: sending to player 2"); } this->controller->runOneGame(args); } else { // return error value char buffer4[DATALEN] = ""; strcpy(buffer4, "cantJoin"); if (write(clientT->clientSocket, &buffer4, DATALEN) == -1) { throw ("Error: sending to player 1"); } } } JoinCommand::JoinCommand(Controller *controller) { this->controller = controller; }
[ "omerz1990@gmail.com" ]
omerz1990@gmail.com
7c566ba8e89a1ba9bfa36c328c514cd131c9b081
109fb932c640fabc2410a31af45df04cccd2c4cf
/OutOOP.cpp
b55b770a9c1fe0dbdfc2f216ab47e0981e8846a6
[]
no_license
the-lenin/MethodLab_OOP
587a07729df95b861361451faa5ee119333f2ba2
987a3059bd753bc54504fe5edafda50e578d3b06
refs/heads/master
2021-01-21T11:26:40.645924
2017-06-09T06:04:11
2017-06-09T06:04:11
91,741,792
0
0
null
null
null
null
UTF-8
C++
false
false
357
cpp
#include "main.h" namespace languages { void oop::Out(ofstream &ofst) { CheckOutFile(ofst); ofst << "It is OOP language: has "; switch (a) { case 0: ofst << "single"; break; case 1: ofst << "multiple"; break; case 2: ofst << "interface"; break; default: break; } ofst << " inharitance,"; ofst << endl; } }
[ "z315@bk.ru" ]
z315@bk.ru
249cce1a01e69aee5a60514e93ae682941fb2348
afc255608753ab472bb0c8d953fb0361bc4ab635
/BLUE_ENGINE/Circle.cpp
729d8df3f5412ecc0ac0e15c06ebe9a34e827ca9
[]
no_license
Nero-TheThrill/-Game-waybackhome_built-with-customengine
23e8e9866c5e822ed6c507232a9ca25e4a7746ad
70beab0fb81c203701a143244d65aff89b08d104
refs/heads/master
2023-08-21T03:02:28.904343
2021-11-02T11:01:50
2021-11-02T11:01:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
785
cpp
/* * File Name : Circle.cpp * Primary Author : Park Jinwon * Secondary Author : * Brief: It includes information about circle collision state * * Copyright (C) 2019 DigiPen Institute of Technology. */ #include "Circle.h" namespace BLUE { Circle::Circle() : Component(ComponentType_CIRCLE) { } Circle::~Circle() { } void Circle::Init() { center = Point2D{ 0,0 }; radius = 1; } Point2D Circle::GetPos() const { return center; } void Circle::SetPos(Point2D newPoint) { center.x = newPoint.x; center.y = newPoint.y; } float Circle::GetRadius() const { return radius; } void Circle::SetRadius(float newRadius) { radius = newRadius; } }
[ "imjinwoo98@gmail.com" ]
imjinwoo98@gmail.com
b0b57faf2ebd2bc86098af90373f43a53f8bd8d0
ed714b26e037a151678bdccaa94af3a7e2207db1
/src/sensorGPS.ino
2c274cab141e0608b5d562764e8c3154e573381b
[]
no_license
pierresimon/stratoflight_mk_ii
b5e79cf08ad9f71ed936bb923d5d5ca1f8ead567
38db4e24985808a595017a9c1db10eb60eddba3c
refs/heads/master
2021-07-10T00:08:58.924304
2017-10-09T14:08:32
2017-10-09T14:08:32
106,288,776
0
0
null
null
null
null
UTF-8
C++
false
false
1,754
ino
/* Sketch-Part for gps-sensor Projekt "Stratoflight MK2" 2017 by Pierre Simon, Frederik Simon */ #include <Gpsneo.h> Gpsneo gps; /*-----------------------------------------------------------------------*/ boolean setupSensorGPS() { //writeLog(2,"Init gps-sensor..."); //writeLog(2,strOK); return true; } /*-----------------------------------------------------------------------*/ void getGPSData(String &retVal) { /*char latitude[15]; char latitudHemisphere[2]; char longitude[15]; char longitudMeridiano[15]; */ char time[10]; char status[3]; char latitud[11]; char latitudHemisphere[3]; char longitud[11]; char longitudMeridiano[3]; char speedKnots[10]; char trackAngle[8]; char date[10]; char magneticVariation[10]; char magneticVariationOrientation[3]; gps.getDataGPRMC(time, status, latitud, latitudHemisphere, longitud, longitudMeridiano, speedKnots, trackAngle, date, magneticVariation, magneticVariationOrientation); //gps.getDataGPRMC(latitude, latitudHemisphere, longitude, longitudMeridiano); retVal.concat(latitud); retVal.concat(";"); retVal.concat(latitudHemisphere); retVal.concat(";"); retVal.concat(longitud); retVal.concat(";"); retVal.concat(longitudMeridiano); retVal.concat(";"); retVal.concat(speedKnots); retVal.concat(";"); retVal.concat(trackAngle); retVal.concat(";"); retVal.concat(date); retVal.concat(";"); retVal.concat(magneticVariation); retVal.concat(";"); retVal.concat(magneticVariationOrientation); retVal.concat(";"); }
[ "pierre.simon@outlook.de" ]
pierre.simon@outlook.de
0e87abbe40b98cc9cc463bafc40d679691068322
bb2c7310facb77e8fa0bf1cdbc7a90f41366f838
/Log.cpp
37ed93596d0f4e276d528ecd5ae98e13ca6b4e59
[]
no_license
Gwennin/LogWriter
07dc8ecb9bd0fccb45811879c579d5c715a88f27
4c7a4f5ae7d6055d888922236f8b44f59e58706a
refs/heads/master
2016-09-06T02:35:57.557957
2012-08-17T16:33:01
2012-08-17T16:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,900
cpp
#include <cstdlib> #include "Utils.h" #include "LogWriter_Private.h" #include "Enums.h" #include "Log.h" using namespace std; using namespace Logger; LogWriter * Log::_writer = 0; LogLevel Log::_lastLogLevel = UnknownLevel; tm * Log::_lastday = Utils::getDay(); string Log::_logPath = "./"; LogNameStyle Log::_logNameStyle = UnknownName; void Log::log(const string message, const LogLevel level) { if ((_logPath.length() == 0) || (_logNameStyle == UnknownName) || (_logNameStyle > NumericLogLevel_Date)) { throw "Set LogPath & LogNameStyle before using the log method's.'"; } tm * today = Utils::getDay(); if ((_writer == 0) || ((_lastLogLevel != level) && (_logNameStyle != Date)) || (_lastday < today)) { if (_writer != 0) { delete _writer; } _writer = new LogWriter(_logPath, _logNameStyle, level); _lastLogLevel = level; _lastday = today; } _writer->writeLog(message, level); } void Log::setLogPath(const string path) { if (path.length() > 0) { _logPath = path; if (_writer != 0) { delete _writer; _writer = 0; } } else { throw "LogPath must not be empty."; } } void Log::setLogNameStyle(const string stringLogNameStyle) { if ((stringLogNameStyle.length() > 0) && (stringLogNameStyle != "UnknownName")) { _logNameStyle = Utils::stringToLogNameStyle(stringLogNameStyle); if (_writer != 0) { delete _writer; _writer = 0; } } else { throw "StringLogNameStyle must not be empty or equal to 'UnknownName'."; } } void Log::setLogNameStyle(const LogNameStyle enumLogNameStyle) { if ((enumLogNameStyle != UnknownName) && (enumLogNameStyle <= NumericLogLevel_Date)) { _logNameStyle = enumLogNameStyle; if (_writer != 0) { delete _writer; _writer = 0; } } else { throw "EnumLogNameStyle can't be equal to 'UnknownName'"; } } void Log::close() { if (_writer != 0) { delete _writer; _writer = 0; } }
[ "minig@MiniGLinDev.localdomain" ]
minig@MiniGLinDev.localdomain
2ddb4e60d963b51e7484d9ec70e5d57a7fb264c4
884d8fd8d4e2bc5a71852de7131a7a6476bf9c48
/grid-test/export/macos/obj/src/flixel/tweens/motion/CubicMotion.cpp
818900487b851688ededfc45173bd9f742b51778
[ "Apache-2.0" ]
permissive
VehpuS/learning-haxe-and-haxeflixel
69655276f504748347decfea66b91a117a722f6c
cb18c074720656797beed7333eeaced2cf323337
refs/heads/main
2023-02-16T07:45:59.795832
2021-01-07T03:01:46
2021-01-07T03:01:46
324,458,421
0
0
null
null
null
null
UTF-8
C++
false
true
9,945
cpp
// Generated by Haxe 4.1.4 #include <hxcpp.h> #ifndef INCLUDED_flixel_FlxBasic #include <flixel/FlxBasic.h> #endif #ifndef INCLUDED_flixel_tweens_FlxTween #include <flixel/tweens/FlxTween.h> #endif #ifndef INCLUDED_flixel_tweens_FlxTweenManager #include <flixel/tweens/FlxTweenManager.h> #endif #ifndef INCLUDED_flixel_tweens_motion_CubicMotion #include <flixel/tweens/motion/CubicMotion.h> #endif #ifndef INCLUDED_flixel_tweens_motion_Motion #include <flixel/tweens/motion/Motion.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_fcae3222e31e2270_6_new,"flixel.tweens.motion.CubicMotion","new",0x5990902e,"flixel.tweens.motion.CubicMotion.new","flixel/tweens/motion/CubicMotion.hx",6,0x44d248a3) HX_LOCAL_STACK_FRAME(_hx_pos_fcae3222e31e2270_34_setMotion,"flixel.tweens.motion.CubicMotion","setMotion",0x132089c6,"flixel.tweens.motion.CubicMotion.setMotion","flixel/tweens/motion/CubicMotion.hx",34,0x44d248a3) HX_LOCAL_STACK_FRAME(_hx_pos_fcae3222e31e2270_49_update,"flixel.tweens.motion.CubicMotion","update",0x63341afb,"flixel.tweens.motion.CubicMotion.update","flixel/tweens/motion/CubicMotion.hx",49,0x44d248a3) namespace flixel{ namespace tweens{ namespace motion{ void CubicMotion_obj::__construct( ::Dynamic Options, ::flixel::tweens::FlxTweenManager manager){ HX_STACKFRAME(&_hx_pos_fcae3222e31e2270_6_new) HXLINE( 18) this->_tt = ((Float)0); HXLINE( 17) this->_ttt = ((Float)0); HXLINE( 16) this->_bY = ((Float)0); HXLINE( 15) this->_bX = ((Float)0); HXLINE( 14) this->_aY = ((Float)0); HXLINE( 13) this->_aX = ((Float)0); HXLINE( 12) this->_toY = ((Float)0); HXLINE( 11) this->_toX = ((Float)0); HXLINE( 10) this->_fromY = ((Float)0); HXLINE( 9) this->_fromX = ((Float)0); HXLINE( 6) super::__construct(Options,manager); } Dynamic CubicMotion_obj::__CreateEmpty() { return new CubicMotion_obj; } void *CubicMotion_obj::_hx_vtable = 0; Dynamic CubicMotion_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< CubicMotion_obj > _hx_result = new CubicMotion_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool CubicMotion_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x21dceb90) { if (inClassId<=(int)0x104846c5) { return inClassId==(int)0x00000001 || inClassId==(int)0x104846c5; } else { return inClassId==(int)0x21dceb90; } } else { return inClassId==(int)0x648124a2; } } ::flixel::tweens::motion::CubicMotion CubicMotion_obj::setMotion(Float fromX,Float fromY,Float aX,Float aY,Float bX,Float bY,Float toX,Float toY,Float duration){ HX_STACKFRAME(&_hx_pos_fcae3222e31e2270_34_setMotion) HXLINE( 35) this->x = (this->_fromX = fromX); HXLINE( 36) this->y = (this->_fromY = fromY); HXLINE( 37) this->_aX = aX; HXLINE( 38) this->_aY = aY; HXLINE( 39) this->_bX = bX; HXLINE( 40) this->_bY = bY; HXLINE( 41) this->_toX = toX; HXLINE( 42) this->_toY = toY; HXLINE( 43) this->duration = duration; HXLINE( 44) this->start(); HXLINE( 45) return ::hx::ObjectPtr<OBJ_>(this); } HX_DEFINE_DYNAMIC_FUNC9(CubicMotion_obj,setMotion,return ) void CubicMotion_obj::update(Float elapsed){ HX_STACKFRAME(&_hx_pos_fcae3222e31e2270_49_update) HXLINE( 50) this->super::update(elapsed); HXLINE( 51) this->x = ((((((this->scale * this->scale) * this->scale) * ((this->_toX + (( (Float)(3) ) * (this->_aX - this->_bX))) - this->_fromX)) + (((( (Float)(3) ) * this->scale) * this->scale) * ((this->_fromX - (( (Float)(2) ) * this->_aX)) + this->_bX))) + ((( (Float)(3) ) * this->scale) * (this->_aX - this->_fromX))) + this->_fromX); HXLINE( 55) this->y = ((((((this->scale * this->scale) * this->scale) * ((this->_toY + (( (Float)(3) ) * (this->_aY - this->_bY))) - this->_fromY)) + (((( (Float)(3) ) * this->scale) * this->scale) * ((this->_fromY - (( (Float)(2) ) * this->_aY)) + this->_bY))) + ((( (Float)(3) ) * this->scale) * (this->_aY - this->_fromY))) + this->_fromY); HXLINE( 59) if (this->finished) { HXLINE( 61) this->postUpdate(); } } ::hx::ObjectPtr< CubicMotion_obj > CubicMotion_obj::__new( ::Dynamic Options, ::flixel::tweens::FlxTweenManager manager) { ::hx::ObjectPtr< CubicMotion_obj > __this = new CubicMotion_obj(); __this->__construct(Options,manager); return __this; } ::hx::ObjectPtr< CubicMotion_obj > CubicMotion_obj::__alloc(::hx::Ctx *_hx_ctx, ::Dynamic Options, ::flixel::tweens::FlxTweenManager manager) { CubicMotion_obj *__this = (CubicMotion_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(CubicMotion_obj), true, "flixel.tweens.motion.CubicMotion")); *(void **)__this = CubicMotion_obj::_hx_vtable; __this->__construct(Options,manager); return __this; } CubicMotion_obj::CubicMotion_obj() { } ::hx::Val CubicMotion_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"_aX") ) { return ::hx::Val( _aX ); } if (HX_FIELD_EQ(inName,"_aY") ) { return ::hx::Val( _aY ); } if (HX_FIELD_EQ(inName,"_bX") ) { return ::hx::Val( _bX ); } if (HX_FIELD_EQ(inName,"_bY") ) { return ::hx::Val( _bY ); } if (HX_FIELD_EQ(inName,"_tt") ) { return ::hx::Val( _tt ); } break; case 4: if (HX_FIELD_EQ(inName,"_toX") ) { return ::hx::Val( _toX ); } if (HX_FIELD_EQ(inName,"_toY") ) { return ::hx::Val( _toY ); } if (HX_FIELD_EQ(inName,"_ttt") ) { return ::hx::Val( _ttt ); } break; case 6: if (HX_FIELD_EQ(inName,"_fromX") ) { return ::hx::Val( _fromX ); } if (HX_FIELD_EQ(inName,"_fromY") ) { return ::hx::Val( _fromY ); } if (HX_FIELD_EQ(inName,"update") ) { return ::hx::Val( update_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"setMotion") ) { return ::hx::Val( setMotion_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val CubicMotion_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"_aX") ) { _aX=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"_aY") ) { _aY=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"_bX") ) { _bX=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"_bY") ) { _bY=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"_tt") ) { _tt=inValue.Cast< Float >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"_toX") ) { _toX=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"_toY") ) { _toY=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"_ttt") ) { _ttt=inValue.Cast< Float >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"_fromX") ) { _fromX=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"_fromY") ) { _fromY=inValue.Cast< Float >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void CubicMotion_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("_fromX",ef,5e,75,02)); outFields->push(HX_("_fromY",f0,5e,75,02)); outFields->push(HX_("_toX",7e,ab,23,3f)); outFields->push(HX_("_toY",7f,ab,23,3f)); outFields->push(HX_("_aX",f6,6a,48,00)); outFields->push(HX_("_aY",f7,6a,48,00)); outFields->push(HX_("_bX",d5,6b,48,00)); outFields->push(HX_("_bY",d6,6b,48,00)); outFields->push(HX_("_ttt",f5,af,23,3f)); outFields->push(HX_("_tt",9f,7b,48,00)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo CubicMotion_obj_sMemberStorageInfo[] = { {::hx::fsFloat,(int)offsetof(CubicMotion_obj,_fromX),HX_("_fromX",ef,5e,75,02)}, {::hx::fsFloat,(int)offsetof(CubicMotion_obj,_fromY),HX_("_fromY",f0,5e,75,02)}, {::hx::fsFloat,(int)offsetof(CubicMotion_obj,_toX),HX_("_toX",7e,ab,23,3f)}, {::hx::fsFloat,(int)offsetof(CubicMotion_obj,_toY),HX_("_toY",7f,ab,23,3f)}, {::hx::fsFloat,(int)offsetof(CubicMotion_obj,_aX),HX_("_aX",f6,6a,48,00)}, {::hx::fsFloat,(int)offsetof(CubicMotion_obj,_aY),HX_("_aY",f7,6a,48,00)}, {::hx::fsFloat,(int)offsetof(CubicMotion_obj,_bX),HX_("_bX",d5,6b,48,00)}, {::hx::fsFloat,(int)offsetof(CubicMotion_obj,_bY),HX_("_bY",d6,6b,48,00)}, {::hx::fsFloat,(int)offsetof(CubicMotion_obj,_ttt),HX_("_ttt",f5,af,23,3f)}, {::hx::fsFloat,(int)offsetof(CubicMotion_obj,_tt),HX_("_tt",9f,7b,48,00)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *CubicMotion_obj_sStaticStorageInfo = 0; #endif static ::String CubicMotion_obj_sMemberFields[] = { HX_("_fromX",ef,5e,75,02), HX_("_fromY",f0,5e,75,02), HX_("_toX",7e,ab,23,3f), HX_("_toY",7f,ab,23,3f), HX_("_aX",f6,6a,48,00), HX_("_aY",f7,6a,48,00), HX_("_bX",d5,6b,48,00), HX_("_bY",d6,6b,48,00), HX_("_ttt",f5,af,23,3f), HX_("_tt",9f,7b,48,00), HX_("setMotion",78,fb,04,2b), HX_("update",09,86,05,87), ::String(null()) }; ::hx::Class CubicMotion_obj::__mClass; void CubicMotion_obj::__register() { CubicMotion_obj _hx_dummy; CubicMotion_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("flixel.tweens.motion.CubicMotion",3c,a1,e5,54); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(CubicMotion_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< CubicMotion_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = CubicMotion_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = CubicMotion_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace flixel } // end namespace tweens } // end namespace motion
[ "vehpus@gmail.com" ]
vehpus@gmail.com
ed61192b4e9fe222480fe0ab52f6dbc07175180d
6ea50d800eaf5690de87eea3f99839f07c662c8b
/ver.0.15.0.1/j_Animal.h
af844b6c73aeaedd6c9af6374058faa0206cb35b
[]
no_license
Toku555/MCPE-Headers
73eefeab8754a9ce9db2545fb0ea437328cade9e
b0806aebd8c3f4638a1972199623d1bf686e6497
refs/heads/master
2021-01-15T20:53:23.115576
2016-09-01T15:38:27
2016-09-01T15:38:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
218
h
#pragma once namespace j{ class Animal{ public: void addAdditionalSaveData(CompoundTag &); void aiStep(void); void hurt(EntityDamageSource const&,int); void readAdditionalSaveData(CompoundTag const&); } };
[ "sinigami3427@gmail.com" ]
sinigami3427@gmail.com
d513157c92d5024564a2b00f67a8f9f139600de2
e43548aa992ff92482d51efcb0549ea89ee4ca42
/engine/StaticMesh.h
f50a83ce0b10e64969135882eb79c02d0055b4e3
[]
no_license
BB-Cat/-
7b0d0a9c7c487b1e6c62b5a51b6dd46281b17841
1cf9e8741601bb537dd779fc65da0943e5233ec4
refs/heads/main
2023-02-27T19:42:05.746205
2021-02-05T11:40:07
2021-02-05T11:40:07
310,175,460
0
0
null
null
null
null
UTF-8
C++
false
false
795
h
#pragma once #include "Mesh.h" #include <vector> #include "Subset.h" //static mesh class which pulls data from .OBJ files class StaticMesh: public Mesh { public: StaticMesh(const wchar_t* full_path); StaticMesh(const wchar_t* full_path, bool is_flipped); ~StaticMesh(); virtual void renderMesh(float elapsed_time, Vec3 scale, Vec3 position, Vec3 rotation, int shader, bool is_textured, float animation_speed = 1.0f) override; private: //creates a full filepath for a related file such as an MTL file from another file's filepath in the same folder std::wstring createFilepath(std::wstring orig_path, UINT size_orig, const wchar_t* target_file, UINT size_target); void loadMtlFile(std::wstring full_path); private: std::vector<Subset_Obj> m_subs; std::vector<Material_Obj> m_mats; };
[ "rockmanrollforte@outlook.com" ]
rockmanrollforte@outlook.com
2cc176dccfa66a1a3b9cb49e614ad96932819341
8a0b44880ac10007dbf591befe7238bc376d1944
/exp/hexa_duty_cycle/idw_modifier.hpp
75796277458720a7470d74823c965c3d985068fa
[]
no_license
resibots/tarapore_2016_gecco
7a50eef016fe3932c72e52f8a01cbd04c440994b
5ff35cf8ac0442e59b4125e804472bf37116fe56
refs/heads/master
2021-01-10T05:08:17.186002
2016-04-14T13:47:33
2016-04-14T13:47:33
55,916,222
2
0
null
null
null
null
UTF-8
C++
false
false
3,221
hpp
#ifndef IDW_MODIFIER_HPP #define IDW_MODIFIER_HPP #include "idw.hpp" int generation = -1; namespace sferes { namespace modifier_div { template<typename Phen,typename Center > struct _parallel_disparity { typedef std::vector<boost::shared_ptr<Phen> > pop_t; pop_t _pop; std::vector< Center >& _centers; IDW _model; _parallel_disparity(pop_t& pop,std::vector< Center >& centers,IDW model) : _pop(pop), _centers(centers),_model(model){} _parallel_disparity(const _parallel_disparity& ev) : _pop(ev._pop), _centers(ev._centers),_model(ev._model) {} void operator() (const parallel::range_t& r) const { for (size_t i = r.begin(); i != r.end(); ++i) { float output = 0.0f; if (_pop[i]->fit().objs()[0] <= -10000) output=-1000; else { _model.predict( _centers, _pop[i]->fit().legs_features, output); } int l = _pop[i]->fit().objs().size()-2; _pop[i]->fit().set_obj(l, output); } } }; } template<typename Center, typename Params = stc::_Params, typename Exact = stc::Itself> class IdwModifier : public stc::Any<Exact> { private: std::vector< Center > centers; IDW model; int transfer_number; public: template<typename Ea> void apply(Ea& ea) { if (generation == -1) transfer_number = 0; ++generation; std::cout << "G" << generation << std::endl; /*if(transfer_number >= Params::surrogate::max_transfer_number) { std::cout << "Max. number of transfers reached." << std::endl; return; }*/ if (generation % 25 == 0) { ++transfer_number; //RANDOM TRANSFER unsigned int transferred; do { #ifdef MAX_TRANSFER //select an individual with at least 50% of max. fitness (on 0th obj.) transferred = 0; double max = ea.pop()[0]->fit().objs()[0]; for (int i=1;i < ea.pop().size();++i) { if (max < ea.pop()[i]->fit().objs()[0]) { transferred = i; max = ea.pop()[i]->fit().objs()[0]; } } do { transferred = sferes::misc::rand<unsigned int>(ea.pop().size()); } while(ea.pop()[transferred]->fit().objs()[0]<0.5*max); #else //random selection transferred = sferes::misc::rand<unsigned int>(ea.pop().size()); #endif } while (ea.pop()[transferred]->fit().objs()[0]<=-10000); Center center = *ea.pop()[transferred]; center.fit().transfer(center,transfer_number); centers.push_back(center); //if addition model.learn(centers); } // parallel compute disparity parallel::init(); parallel::p_for(parallel::range_t(0, ea.pop().size()), modifier_div::_parallel_disparity<typename Ea::phen_t,Center>(ea.pop(),centers,model)); } }; } #endif
[ "mouret@isir.upmc.fr" ]
mouret@isir.upmc.fr
02b10420c302437181fbf78579ff907f4ed2b17c
475079ba8272c955354616374f87c4f9aa750895
/program/program/shop.cpp
29a352104bc25f60aed1215124b8f6bc4c6d2f85
[]
no_license
yusjoel/magic-tower-AI
1bed4d44f38b2bffe09e5bd6d5e65f41a9245c2b
45e9b7253ed06de73b999798a8a146b54e909923
refs/heads/master
2020-08-03T15:23:38.109711
2020-03-16T02:09:38
2020-03-16T02:09:38
211,799,346
3
0
null
2019-09-30T07:17:52
2019-09-30T07:17:52
null
UTF-8
C++
false
false
562
cpp
#include "stdafx.h" void c_shop::init(FILE* file) { // start=_start; delta=_delta; hp=_hp; atk=_atk; def=_def; mdef=_mdef; fscanf_s(file, "%d%d%d%d%d%d", &start, &delta, &hp, &atk, &def, &mdef); times=0; } int c_shop::needMoney() { return start+times*delta; } int c_shop::getHpPoint() { return hp; } int c_shop::getAtkPoint() { return atk; } int c_shop::getDefPoint() { return def; } int c_shop::getMDefPoint() { return mdef; } void c_shop::output(FILE* file) { fprintf_s(file, "%d %d %d %d %d %d\n\n", needMoney(), delta, hp, atk, def, mdef); }
[ "ckcz123@126.com" ]
ckcz123@126.com
803105bdf2389c583fe777c48d4f837ed6ba3f4f
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_3/processor2/20/phi
68414a20d0f6da5b7c2aa9ad3e18c70889411230
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
26,451
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "20"; object phi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 3 -1 0 0 0 0]; internalField nonuniform List<scalar> 1646 ( -0.00265964 -0.000890478 -0.000828829 -0.00247452 -0.00255775 -0.00093072 -0.000767772 -0.00233237 -0.000832028 -0.00241027 -0.00249162 -0.000734734 -0.00219623 -0.000796479 -0.00227062 -0.000860269 -0.00234647 -0.00242371 -0.000706408 -0.00206352 -0.000767743 -0.00213489 -0.000831411 -0.00220695 -0.000897746 -0.00228014 -0.00235399 -0.000677839 -0.00193383 -0.000738788 -0.00200257 -0.000802231 -0.00207145 -0.000868291 -0.00214089 -0.000937253 -0.00221118 -0.00228198 -0.000647892 -0.00180705 -0.000708253 -0.00187347 -0.000771211 -0.00193961 -0.000836814 -0.00200585 -0.000905178 -0.00207253 -0.00097648 -0.00213987 -0.00220773 -0.00067592 -0.0017475 -0.000738148 -0.00181124 -0.00080306 -0.0018747 -0.000870703 -0.0019382 -0.000941164 -0.00200207 -0.00101454 -0.0020665 -0.00213146 -0.000641914 -0.00162458 -0.000703198 -0.00168621 -0.000767205 -0.00174723 -0.000833947 -0.00180796 -0.000903462 -0.00186869 -0.000975807 -0.00192972 -0.00105103 -0.00199127 -0.00205338 -0.000606472 -0.00150466 -0.000666631 -0.00156442 -0.000729551 -0.00162329 -0.000795223 -0.00168156 -0.000863654 -0.00173952 -0.00093487 -0.00179747 -0.00100891 -0.00185569 -0.0010858 -0.00191439 -0.00197367 -0.000569861 -0.00138773 -0.000628736 -0.00144579 -0.000690412 -0.00150274 -0.000754864 -0.00155884 -0.00082208 -0.00161435 -0.000892062 -0.00166954 -0.000964826 -0.00172471 -0.00104039 -0.00178012 -0.00111879 -0.00183599 -0.00189246 -0.000589796 -0.00133028 -0.000650087 -0.0013855 -0.000713186 -0.00143964 -0.000779065 -0.00149296 -0.000847709 -0.0015457 -0.000919115 -0.00159814 -0.00099329 -0.00165053 -0.00107025 -0.00170316 -0.00115001 -0.00175623 -0.0018099 -0.000550083 -0.00121792 -0.000608859 -0.00127151 -0.00067048 -0.00132387 -0.000734907 -0.00137522 -0.000802111 -0.00142576 -0.000872074 -0.00147574 -0.000944788 -0.00152542 -0.00102026 -0.00157506 -0.00109849 -0.00162493 -0.0011795 -0.00167522 -0.000566995 -0.00116079 -0.000627018 -0.00121148 -0.000689882 -0.00126101 -0.000755546 -0.00130955 -0.00082398 -0.00135732 -0.000895161 -0.00140456 -0.000969079 -0.0014515 -0.00104573 -0.00149841 -0.00112513 -0.00154553 -0.00159306 -0.000524756 -0.00105341 -0.000583061 -0.00110248 -0.000644249 -0.00115029 -0.000708272 -0.00119699 -0.000775088 -0.00124274 -0.00084466 -0.00128775 -0.000916966 -0.00133225 -0.000991992 -0.00137648 -0.00106974 -0.00142067 -0.0011502 -0.00146506 -0.00150985 -0.000538863 -0.000996943 -0.000598261 -0.00104308 -0.000660537 -0.00108802 -0.000725639 -0.00113188 -0.000793522 -0.00117485 -0.000864149 -0.00121712 -0.000937493 -0.00125891 -0.00101354 -0.00130043 -0.00109229 -0.00134192 -0.00117374 -0.00138361 -0.00049468 -0.000895003 -0.000552167 -0.000939457 -0.000612584 -0.000982666 -0.000675872 -0.00102473 -0.000741975 -0.00106578 -0.000810847 -0.00110598 -0.000882447 -0.00114552 -0.000956749 -0.00118461 -0.00103374 -0.00122344 -0.0011134 -0.00126225 -0.00130125 -0.000506218 -0.000839555 -0.000564657 -0.000881018 -0.000626021 -0.000921302 -0.000690247 -0.000960504 -0.000757277 -0.000998752 -0.000827061 -0.0010362 -0.000899559 -0.00107303 -0.000974743 -0.00110942 -0.00105259 -0.00114559 -0.00113311 -0.00118174 -0.00046067 -0.000743582 -0.000517004 -0.000783222 -0.000576325 -0.000821696 -0.000638565 -0.000859062 -0.000703658 -0.000895412 -0.000771542 -0.000930867 -0.000842167 -0.000965575 -0.000915491 -0.000999702 -0.000991485 -0.00103343 -0.00107013 -0.00106695 -0.00110044 -0.00046988 -0.000689489 -0.000527032 -0.00072607 -0.000587167 -0.00076156 -0.000650214 -0.000796015 -0.000716103 -0.000829523 -0.000784773 -0.000862198 -0.000856169 -0.000894178 -0.00093025 -0.000925621 -0.00100699 -0.000956694 -0.00108636 -0.000987574 -0.00101844 -0.00042355 -0.000600086 -0.000478394 -0.000634645 -0.000536297 -0.000668168 -0.000597179 -0.000700678 -0.000660965 -0.000732229 -0.000727583 -0.000762905 -0.00079697 -0.000792811 -0.000869071 -0.000822077 -0.000943843 -0.000850849 -0.00102125 -0.000879282 -0.00110129 -0.00090754 -0.000430676 -0.000547693 -0.000486207 -0.000579114 -0.000544795 -0.00060958 -0.000606358 -0.000639115 -0.000670817 -0.000667771 -0.000738098 -0.000695623 -0.000808137 -0.000722772 -0.000880878 -0.000749337 -0.000956276 -0.00077545 -0.0010343 -0.000801257 -0.000826905 -0.000437163 -0.000494681 -0.000493316 -0.000522961 -0.000552524 -0.000550372 -0.000614702 -0.000576937 -0.000679769 -0.000602704 -0.000747649 -0.000627742 -0.000818277 -0.000652145 -0.000891594 -0.000676019 -0.000967557 -0.000699487 -0.00104614 -0.000722678 -0.000745729 -0.000443008 -0.000441111 -0.000499719 -0.00046625 -0.000559482 -0.000490608 -0.000622211 -0.000514208 -0.000687823 -0.000537093 -0.000756239 -0.000559326 -0.000827392 -0.000580992 -0.000901224 -0.000602186 -0.000977692 -0.000623019 -0.00105676 -0.000643607 -0.00066407 -0.000394144 -0.000364363 -0.000448207 -0.000387048 -0.000505412 -0.000409044 -0.000565668 -0.000430352 -0.000628885 -0.000450991 -0.000694978 -0.000471 -0.000763868 -0.000490437 -0.000835485 -0.000509374 -0.000909773 -0.000527898 -0.000986687 -0.000546106 -0.00106619 -0.000564099 -0.000581984 -0.000398265 -0.000313104 -0.000452759 -0.000332553 -0.000510396 -0.000351407 -0.000571082 -0.000369667 -0.000634724 -0.000387349 -0.000701236 -0.000404488 -0.000770538 -0.000421135 -0.00084256 -0.000437352 -0.000917244 -0.000453214 -0.000994545 -0.000468805 -0.00107443 -0.000484212 -0.0004018 -0.000261478 -0.000456664 -0.00027769 -0.00051467 -0.000293402 -0.000575722 -0.000308614 -0.000639728 -0.000323343 -0.000706598 -0.000337618 -0.000776252 -0.000351481 -0.000848619 -0.000364984 -0.000923642 -0.000378192 -0.00100127 -0.000391173 -0.000404001 -0.000404748 -0.000209548 -0.000459918 -0.00022252 -0.000518231 -0.000235089 -0.000579589 -0.000247256 -0.000643896 -0.000259036 -0.000711064 -0.00027045 -0.000781011 -0.000281534 -0.000853665 -0.00029233 -0.000928968 -0.000302889 -0.00100687 -0.000313266 -0.000323522 -0.000407107 -0.000157374 -0.000462523 -0.000167104 -0.000521081 -0.000176531 -0.000582682 -0.000185655 -0.000647231 -0.000194487 -0.000714636 -0.000203045 -0.000784816 -0.000211354 -0.000857699 -0.000219447 -0.000933226 -0.000227362 -0.00101135 -0.000235141 -0.000242828 -0.000408877 -0.000105018 -0.000464477 -0.000111505 -0.000523218 -0.000117789 -0.000585002 -0.000123871 -0.000649731 -0.000129758 -0.000717314 -0.000135462 -0.000787669 -0.000141 -0.000860723 -0.000146393 -0.000936417 -0.000151668 -0.00101471 -0.000156851 -0.000161975 -0.000410058 -5.25392e-05 -0.000465779 -5.57829e-05 -0.000524643 -5.8925e-05 -0.000586549 -6.1966e-05 -0.000651398 -6.49091e-05 -0.000719099 -6.77605e-05 -0.00078957 -7.05288e-05 -0.000862738 -7.3225e-05 -0.000938544 -7.58616e-05 -0.00101694 -7.84529e-05 -8.10139e-05 -0.000358109 3.84956e-11 -0.000410648 4.07518e-11 -0.000466431 4.28755e-11 -0.000525356 4.48736e-11 -0.000587322 4.6727e-11 -0.000652231 4.84432e-11 -0.000719992 5.00247e-11 -0.000790521 5.14761e-11 -0.000863746 5.28064e-11 -0.000939607 5.4024e-11 -0.00101806 5.51384e-11 5.6161e-11 -0.000358109 -0.000410648 5.25392e-05 -0.000466431 5.5783e-05 -0.000525356 5.89251e-05 -0.000587322 6.19661e-05 -0.000652231 6.49092e-05 -0.000719992 6.77606e-05 -0.000790521 7.05289e-05 -0.000863746 7.32251e-05 -0.000939607 7.58617e-05 -0.00101806 7.8453e-05 8.1014e-05 -0.000410058 0.000105018 -0.000465779 0.000111505 -0.000524643 0.000117789 -0.000586549 0.000123871 -0.000651398 0.000129758 -0.000719099 0.000135462 -0.00078957 0.000141 -0.000862738 0.000146393 -0.000938544 0.000151668 -0.00101694 0.000156852 0.000161975 -0.000408877 0.000157374 -0.000464477 0.000167104 -0.000523218 0.000176531 -0.000585002 0.000185655 -0.000649731 0.000194487 -0.000717314 0.000203045 -0.000787669 0.000211354 -0.000860723 0.000219447 -0.000936417 0.000227362 -0.00101471 0.000235141 0.000242829 -0.000407107 0.000209548 -0.000462523 0.00022252 -0.000521081 0.000235089 -0.000582682 0.000247257 -0.000647231 0.000259036 -0.000714636 0.00027045 -0.000784816 0.000281534 -0.000857699 0.00029233 -0.000933226 0.000302889 -0.00101135 0.000313266 0.000323522 -0.000404748 0.000261479 -0.000459918 0.00027769 -0.000518231 0.000293402 -0.000579589 0.000308614 -0.000643896 0.000323343 -0.000711064 0.000337618 -0.000781011 0.000351481 -0.000853665 0.000364985 -0.000928968 0.000378192 -0.00100687 0.000391173 0.000404001 -0.0004018 0.000313104 -0.000456664 0.000332553 -0.00051467 0.000351408 -0.000575722 0.000369667 -0.000639728 0.000387349 -0.000706598 0.000404488 -0.000776252 0.000421135 -0.000848619 0.000437352 -0.000923642 0.000453214 -0.00100127 0.000468805 0.000484212 -0.000398265 0.000364363 -0.000452759 0.000387048 -0.000510396 0.000409044 -0.000571082 0.000430352 -0.000634724 0.000450991 -0.000701236 0.000471 -0.000770538 0.000490437 -0.00084256 0.000509374 -0.000917244 0.000527898 -0.000994545 0.000546106 -0.00107443 0.000564099 0.000581984 -0.000394144 -0.000448207 0.000441111 -0.000505412 0.00046625 -0.000565668 0.000490608 -0.000628885 0.000514208 -0.000694978 0.000537093 -0.000763868 0.000559327 -0.000835485 0.000580992 -0.000909773 0.000602186 -0.000986687 0.000623019 -0.00106619 0.000643607 0.00066407 -0.000443008 0.000494681 -0.000499719 0.000522961 -0.000559482 0.000550372 -0.000622211 0.000576937 -0.000687823 0.000602704 -0.000756239 0.000627743 -0.000827392 0.000652145 -0.000901224 0.000676019 -0.000977692 0.000699487 -0.00105676 0.000722679 0.000745729 -0.000437163 0.000547693 -0.000493316 0.000579114 -0.000552524 0.00060958 -0.000614702 0.000639115 -0.000679769 0.000667771 -0.000747649 0.000695623 -0.000818277 0.000722772 -0.000891594 0.000749337 -0.000967557 0.00077545 -0.00104614 0.000801257 0.000826905 -0.000430676 0.000600086 -0.000486207 0.000634645 -0.000544795 0.000668168 -0.000606358 0.000700678 -0.000670817 0.00073223 -0.000738098 0.000762905 -0.000808137 0.000792811 -0.000880878 0.000822077 -0.000956276 0.000850849 -0.0010343 0.000879282 0.00090754 -0.00042355 -0.000478394 0.000689489 -0.000536297 0.00072607 -0.000597179 0.00076156 -0.000660965 0.000796015 -0.000727583 0.000829523 -0.00079697 0.000862198 -0.000869071 0.000894178 -0.000943843 0.000925621 -0.00102125 0.000956694 -0.00110129 0.000987575 0.00101844 -0.00046988 0.000743582 -0.000527032 0.000783222 -0.000587167 0.000821696 -0.000650214 0.000859062 -0.000716103 0.000895412 -0.000784773 0.000930867 -0.000856169 0.000965575 -0.00093025 0.000999702 -0.00100699 0.00103343 -0.00108636 0.00106695 0.00110044 -0.00046067 -0.000517004 0.000839555 -0.000576325 0.000881018 -0.000638565 0.000921302 -0.000703658 0.000960504 -0.000771542 0.000998752 -0.000842167 0.0010362 -0.000915491 0.00107303 -0.000991485 0.00110942 -0.00107013 0.00114559 0.00118174 -0.000506218 0.000895003 -0.000564657 0.000939457 -0.000626021 0.000982666 -0.000690247 0.00102473 -0.000757277 0.00106578 -0.000827061 0.00110598 -0.000899559 0.00114552 -0.000974743 0.00118461 -0.00105259 0.00122344 -0.00113311 0.00126225 0.00130125 -0.00049468 -0.000552167 0.000996943 -0.000612584 0.00104308 -0.000675872 0.00108802 -0.000741975 0.00113189 -0.000810847 0.00117486 -0.000882447 0.00121712 -0.000956749 0.00125891 -0.00103374 0.00130043 -0.0011134 0.00134192 0.00138361 -0.000538863 0.00105341 -0.000598261 0.00110248 -0.000660537 0.00115029 -0.000725639 0.00119699 -0.000793522 0.00124274 -0.000864149 0.00128775 -0.000937493 0.00133225 -0.00101354 0.00137648 -0.00109229 0.00142067 -0.00117374 0.00146506 0.00150985 -0.000524756 -0.000583061 0.00116079 -0.000644249 0.00121148 -0.000708272 0.00126101 -0.000775088 0.00130955 -0.00084466 0.00135732 -0.000916966 0.00140456 -0.000991992 0.0014515 -0.00106974 0.00149841 -0.0011502 0.00154553 0.00159306 -0.000566995 0.00121792 -0.000627018 0.00127151 -0.000689882 0.00132387 -0.000755546 0.00137522 -0.00082398 0.00142576 -0.000895161 0.00147574 -0.000969079 0.00152542 -0.00104573 0.00157506 -0.00112513 0.00162493 -0.00120729 0.00167522 0.0017261 -0.000550083 -0.000608859 0.00133028 -0.00067048 0.0013855 -0.000734907 0.00143965 -0.000802111 0.00149296 -0.000872074 0.0015457 -0.000944788 0.00159814 -0.00102026 0.00165053 -0.00109849 0.00170316 -0.0011795 0.00175623 0.0018099 -0.000589796 -0.000650087 0.00144579 -0.000713186 0.00150274 -0.000779065 0.00155884 -0.000847709 0.00161435 -0.000919115 0.00166954 -0.00099329 0.00172471 -0.00107025 0.00178012 -0.00115001 0.00183599 0.00189246 -0.000628736 0.00150466 -0.000690412 0.00156442 -0.000754864 0.00162329 -0.00082208 0.00168156 -0.000892062 0.00173952 -0.000964826 0.00179747 -0.00104039 0.00185569 -0.00111879 0.00191439 0.00197367 -0.000606472 -0.000666631 0.00162458 -0.000729551 0.00168621 -0.000795223 0.00174723 -0.000863654 0.00180796 -0.00093487 0.00186869 -0.00100891 0.00192972 -0.0010858 0.00199127 0.00205338 -0.000641914 -0.000703198 0.0017475 -0.000767205 0.00181124 -0.000833947 0.0018747 -0.000903462 0.0019382 -0.000975807 0.00200207 -0.00105103 0.0020665 0.00213146 -0.00067592 0.00180705 -0.000738148 0.00187347 -0.00080306 0.00193961 -0.000870703 0.00200585 -0.000941164 0.00207253 -0.00101454 0.00213987 0.00220773 -0.000647892 -0.000708253 0.00193383 -0.000771211 0.00200257 -0.000836814 0.00207145 -0.000905178 0.00214089 -0.00097648 0.00221118 0.00228198 -0.000677839 -0.000738788 0.00206352 -0.000802231 0.00213489 -0.000868291 0.00220695 -0.000937253 0.00228014 0.00235399 -0.000706408 -0.000767743 0.00219623 -0.000831411 0.00227062 -0.000897746 0.00234647 0.00242371 -0.000734734 -0.000796479 0.00233237 -0.000860269 0.00241027 0.00249162 -0.000767772 -0.000832028 0.00247452 0.00255775 -0.000828829 0.00265964 -0.00093072 -0.000890478 -0.000893859 -0.0053613 -0.000932748 -0.00546725 -0.000965646 -0.00554719 -0.00099239 -0.00562014 -0.00101326 -0.00568713 -0.00102884 -0.0057486 -0.0010397 -0.00580418 -0.00104639 -0.00585358 -0.00104941 -0.00589683 -0.0010492 -0.00593414 -0.00104617 -0.00596593 -0.00104065 -0.00599267 -0.00103296 -0.00601491 -0.00102334 -0.00603316 -0.00101205 -0.00604795 -0.000999259 -0.00605974 -0.000985159 -0.00606896 -0.000969894 -0.00607597 -0.00608111 -0.000942742 -0.00530903 -0.000981694 -0.0054283 -0.00101477 -0.00551412 -0.0010414 -0.00559351 -0.00106195 -0.00566658 -0.00107714 -0.00573341 -0.00108756 -0.00579375 -0.00109377 -0.00584737 -0.00109626 -0.00589434 -0.00109547 -0.00593493 -0.0010918 -0.0059696 -0.00108558 -0.00599889 -0.00107714 -0.00602335 -0.00106674 -0.00604357 -0.00105462 -0.00606008 -0.00104097 -0.00607339 -0.00102598 -0.00608394 -0.0010098 -0.00609215 -0.000992571 -0.00609834 -0.000974402 -0.00610282 -0.000955396 -0.00610585 -0.000935643 -0.00610764 -0.000915221 -0.00610837 -0.000894198 -0.0061082 -0.000872638 -0.00610726 -0.000850594 -0.00610568 -0.000828116 -0.00610354 -0.000805248 -0.00610093 -0.000782029 -0.00609793 -0.000758497 -0.00609461 -0.000734684 -0.00609102 -0.000710618 -0.00608721 -0.000686328 -0.00608324 -0.000661838 -0.00607915 -0.00063717 -0.00607497 -0.000612343 -0.00607075 -0.000587377 -0.0060665 -0.000562288 -0.00606227 -0.000537092 -0.00605807 -0.000511802 -0.00605394 -0.000486431 -0.00604989 -0.000460991 -0.00604595 -0.000435492 -0.00604213 -0.000409943 -0.00603844 -0.000384354 -0.00603491 -0.000358733 -0.00603154 -0.000333087 -0.00602835 -0.000307423 -0.00602536 -0.000281747 -0.00602256 -0.000256066 -0.00601997 -0.000230385 -0.0060176 -0.000204708 -0.00601545 -0.000179042 -0.00601352 -0.00015339 -0.00601184 -0.000127758 -0.00601039 -0.000102148 -0.00600919 -7.65645e-05 -0.00600823 -5.10113e-05 -0.00600753 -2.54904e-05 -0.00600707 -0.00600686 -0.000989902 -0.00524985 -0.00103168 -0.00538652 -0.00106365 -0.00548214 -0.00108898 -0.00556819 -0.00110855 -0.00564701 -0.00112295 -0.00571901 -0.00113271 -0.00578399 -0.00113833 -0.00584176 -0.00114024 -0.00589242 -0.00113887 -0.0059363 -0.00113459 -0.00597388 -0.00112775 -0.00600573 -0.00111864 -0.00603246 -0.00110754 -0.00605467 -0.00109468 -0.00607294 -0.00108027 -0.0010645 -0.00104751 -0.00102944 -0.00101042 -0.000990551 -0.000969917 -0.000948603 -0.000926679 -0.000904208 -0.000881247 -0.000857845 -0.00083405 -0.0008099 -0.000785434 -0.000760685 -0.000735683 -0.000710457 -0.00068503 -0.000659426 -0.000633666 -0.000607768 -0.000581749 -0.000555626 -0.000529412 -0.00050312 -0.000476762 -0.000450349 -0.00042389 -0.000397395 -0.000370872 -0.000344328 -0.000317771 -0.000291206 -0.000264641 -0.00023808 -0.000211528 -0.000184992 -0.000158474 -0.000131981 -0.000105515 -7.90813e-05 -5.26828e-05 -2.63232e-05 0.0116668 0.011361 0.0110402 0.0107135 0.0103841 0.0100533 0.00972187 0.0093908 0.00906127 0.00873452 0.00841178 0.00809421 0.00778285 0.00747859 0.0116668 0.00524985 0.011361 0.00538652 0.0110402 0.00548214 0.0107135 0.00556819 0.0103841 0.00564701 0.0100533 0.00571901 0.00972187 0.00578399 0.0093908 0.00584176 0.00906127 0.00589243 0.00873452 0.0059363 0.00841178 0.00597388 0.00809421 0.00600573 0.00778285 0.00603246 0.00747859 0.00605467 0.00718215 0.00607294 0.00689407 0.0060878 0.00661473 0.00609972 0.00634435 0.00610914 0.00608301 0.00611641 0.00583068 0.00612184 0.00558725 0.00612572 0.0053525 0.00612827 0.00512618 0.00612968 0.00490798 0.00613012 0.00469758 0.00612973 0.00449463 0.00612864 0.00429877 0.00612694 0.00410965 0.00612472 0.00392691 0.00612208 0.0037502 0.00611907 0.0035792 0.00611576 0.00341357 0.00611221 0.00325301 0.00610847 0.00309722 0.00610458 0.00294591 0.00610058 0.00279881 0.00609651 0.00265567 0.0060924 0.00251624 0.00608829 0.00238028 0.0060842 0.00224758 0.00608016 0.0021179 0.00607619 0.00199106 0.00607231 0.00186686 0.00606854 0.00174511 0.0060649 0.00162562 0.0060614 0.00150823 0.00605807 0.00139277 0.0060549 0.00127909 0.00605191 0.00116701 0.00604912 0.00105641 0.00604653 0.000947115 0.00604416 0.000838999 0.006042 0.00073192 0.00604006 0.00062574 0.00603836 0.000520327 0.00603689 0.00041555 0.00603566 0.000311278 0.00603467 0.000207385 0.00603392 0.000103748 0.00603342 0.00603318 -0.000989902 0.00530903 -0.00103168 0.0054283 -0.00106365 0.00551412 -0.00108898 0.00559351 -0.00110855 0.00566659 -0.00112295 0.00573341 -0.00113271 0.00579375 -0.00113833 0.00584737 -0.00114024 0.00589434 -0.00113887 0.00593493 -0.00113459 0.0059696 -0.00112775 0.00599889 -0.00111864 0.00602335 -0.00110754 0.00604357 -0.00109468 0.00606008 -0.00108027 0.00607339 -0.0010645 0.00608395 -0.00104751 0.00609215 -0.00102944 0.00609834 -0.00101042 0.00610282 -0.000990551 0.00610585 -0.000969917 0.00610764 -0.000948603 0.00610837 -0.000926679 0.0061082 -0.000904208 0.00610726 -0.000881247 0.00610568 -0.000857846 0.00610354 -0.00083405 0.00610093 -0.0008099 0.00609793 -0.000785434 0.00609461 -0.000760685 0.00609102 -0.000735683 0.00608721 -0.000710457 0.00608324 -0.00068503 0.00607915 -0.000659426 0.00607497 -0.000633666 0.00607075 -0.000607768 0.0060665 -0.000581749 0.00606227 -0.000555626 0.00605807 -0.000529412 0.00605394 -0.00050312 0.00604989 -0.000476762 0.00604595 -0.000450349 0.00604213 -0.00042389 0.00603844 -0.000397395 0.00603491 -0.000370872 0.00603154 -0.000344328 0.00602835 -0.000317771 0.00602536 -0.000291206 0.00602256 -0.000264641 0.00601997 -0.00023808 0.0060176 -0.000211528 0.00601545 -0.000184992 0.00601352 -0.000158474 0.00601184 -0.000131981 0.00601039 -0.000105515 0.00600919 -7.90813e-05 0.00600823 -5.26828e-05 0.00600753 -2.63232e-05 0.00600707 0.00600686 -0.000942742 0.0053613 -0.000981694 0.00546725 -0.00101477 0.00554719 -0.0010414 0.00562014 -0.00106195 -0.00107714 -0.00108756 -0.00109377 -0.00109626 -0.00109547 -0.0010918 -0.00108558 -0.00107714 -0.00106674 -0.00105462 -0.00104097 -0.00102598 -0.0010098 -0.000992571 -0.000974402 -0.000955396 -0.000935643 -0.000915221 -0.000894198 -0.000872638 -0.000850594 -0.000828116 -0.000805248 -0.000782029 -0.000758497 -0.000734684 -0.000710618 -0.000686328 -0.000661838 -0.00063717 -0.000612343 -0.000587377 -0.000562289 -0.000537092 -0.000511802 -0.000486431 -0.000460991 -0.000435492 -0.000409943 -0.000384354 -0.000358733 -0.000333087 -0.000307423 -0.000281747 -0.000256066 -0.000230385 -0.000204708 -0.000179042 -0.00015339 -0.000127758 -0.000102148 -7.65645e-05 -5.10113e-05 -2.54904e-05 -0.000893859 -0.000932748 -0.000965646 ) ; boundaryField { inlet { type calculated; value nonuniform 0(); } outlet { type calculated; value nonuniform 0(); } cylinder { type calculated; value nonuniform 0(); } top { type symmetryPlane; value uniform 0; } bottom { type symmetryPlane; value uniform 0; } defaultFaces { type empty; value nonuniform 0(); } procBoundary2to1 { type processor; value nonuniform List<scalar> 193 ( -0.00089816 -0.000928182 -0.000967461 -0.00100927 -0.00105073 -0.0010908 -0.00112911 -0.00116551 -0.00119999 -0.00123258 -0.0017261 -0.0012633 -0.00120729 -0.00123341 -0.00125792 -0.00142567 -0.00119576 -0.0012163 -0.00121806 -0.00115142 -0.00116836 -0.00118394 -0.000935786 -0.00111494 -0.00112731 -0.00113842 -0.00114828 -0.00115689 -0.000499527 -0.00108148 -0.00108735 -0.00109204 -0.00109556 -0.0010979 -0.00109907 -0.00109907 -0.0010979 -0.00109556 -0.00109204 -0.00108735 -0.00108148 -0.000499527 -0.00115689 -0.00114828 -0.00113842 -0.00112731 -0.00111494 -0.000935786 -0.00118394 -0.00116836 -0.00115142 -0.00121806 -0.0012163 -0.00119576 -0.00142567 -0.00125792 -0.00123341 -0.00164116 -0.00129222 -0.0012633 -0.00123258 -0.00119999 -0.00116551 -0.00112911 -0.0010908 -0.00105073 -0.00100927 -0.000967461 -0.000928182 -0.00089816 -0.0060878 -0.00609972 -0.00610914 -0.00611641 -0.00612184 -0.00612572 -0.00612827 -0.00612968 -0.00613012 -0.00612973 -0.00612864 -0.00612694 -0.00612472 -0.00612208 -0.00611907 -0.00611576 -0.00611221 -0.00610847 -0.00610458 -0.00610058 -0.00609651 -0.0060924 -0.00608829 -0.0060842 -0.00608016 -0.00607619 -0.00607231 -0.00606854 -0.0060649 -0.0060614 -0.00605807 -0.0060549 -0.00605191 -0.00604912 -0.00604653 -0.00604416 -0.006042 -0.00604006 -0.00603836 -0.00603689 -0.00603566 -0.00603467 -0.00603392 -0.00603342 -0.00603318 -0.00499794 -0.0119187 -0.00508072 -0.00516134 -0.00524148 -0.00531766 -0.0053882 -0.00545255 -0.0055107 -0.0055629 -0.00560955 -0.00565114 -0.00568816 -0.0057211 -0.00575041 0.00718215 -0.0057765 -0.0119187 -0.00499794 -0.00508072 -0.00516134 -0.00524149 -0.00531766 -0.0053882 -0.00545255 -0.0055107 -0.0055629 -0.00560955 -0.00565114 -0.00568816 -0.0057211 -0.00575041 -0.0057765 -0.00579972 -0.00582038 -0.00583875 -0.00585507 -0.00586952 -0.00588229 -0.00589352 -0.00590336 -0.00591193 -0.00591933 -0.00592569 -0.00593108 -0.0059356 -0.00593934 -0.00594237 -0.00594476 -0.00594659 -0.00594791 -0.00594878 -0.00594927 -0.00594941 -0.00594926 -0.00594886 -0.00594824 -0.00594745 -0.00594651 -0.00594547 -0.00594434 -0.00594314 -0.00594192 -0.00594068 -0.00593944 -0.00593823 -0.00593705 -0.00593593 -0.00593487 -0.00593388 -0.00593298 -0.00593218 -0.00593147 -0.00593088 -0.0059304 -0.00593003 -0.00592979 -0.00592943 ) ; } procBoundary2to3 { type processor; value nonuniform List<scalar> 222 ( 0.00274528 0.000844031 0.000804838 0.00255387 0.000749478 0.00239471 0.000705427 0.00225598 0.000674986 0.00212256 0.000647365 0.0019923 0.000619368 0.00186481 0.000590131 0.000616364 0.00168313 0.000583363 0.00156203 0.000549099 0.00144377 0.000513821 0.000532347 0.00127381 0.000494194 0.00050986 0.00110877 0.00046939 0.0004824 0.000949496 0.000440187 0.00045077 0.000796856 0.000407396 0.000415788 0.000651794 0.000371841 0.000378284 0.00038415 0.000389438 0.000415194 0.000343313 0.000347006 0.000350175 0.000352818 0.000354933 0.000356521 0.000357579 4.91963e-05 0.000308912 0.000308912 4.91964e-05 0.000357579 0.000356521 0.000354933 0.000352818 0.000350175 0.000347006 0.000343313 0.000415194 0.000389438 0.00038415 0.000378284 0.000371841 0.000651794 0.000415788 0.000407396 0.000796856 0.00045077 0.000440187 0.000949496 0.0004824 0.00046939 0.00110877 0.00050986 0.000494194 0.00127381 0.000532347 0.00138773 0.000569861 0.000549099 0.00156203 0.000583363 0.00168313 0.000616364 0.000590131 0.00186481 0.000619368 0.0019923 0.000647365 0.00212256 0.000674986 0.00225598 0.000705427 0.00239471 0.000749478 0.00255387 0.000804838 0.00274528 0.000844031 0.00541113 0.00550614 0.00558009 0.00564688 0.005708 0.00576417 0.00581503 0.00586027 0.00589985 0.00593394 0.0059629 0.00598716 0.00600721 0.00602355 0.00603665 0.00604696 0.00605486 0.00606071 0.00606481 -0.000953594 0.00608466 0.00608685 0.00608788 0.00608795 0.00608718 0.0060857 0.00608363 0.00608106 0.00607806 0.00607471 0.00607107 0.0060672 0.00606315 0.00605895 0.00605466 0.0060503 0.00604592 0.00604154 0.00603718 0.00603288 0.00602865 0.00602452 0.00602051 0.00601663 0.00601289 0.00600932 0.00600592 0.00600271 0.00599969 0.00599688 0.00599429 0.00599191 0.00598977 0.00598786 0.00598619 0.00598476 0.00598358 0.00598265 0.00598197 0.00598154 0.00598137 0.00568713 0.0057486 0.00580418 0.00585358 0.00589683 0.00593414 0.00596593 0.00599267 0.00601491 0.00603316 0.00604795 0.00605974 0.00606896 0.00607597 0.00608111 0.00608466 0.00608685 0.00608788 0.00608795 0.00608718 0.0060857 0.00608363 0.00608106 0.00607806 0.00607471 0.00607107 0.0060672 0.00606315 0.00605895 0.00605466 0.0060503 0.00604592 0.00604154 0.00603718 0.00603288 0.00602865 0.00602452 0.00602051 0.00601663 0.00601289 0.00600932 0.00600592 0.00600271 0.00599969 0.00599688 0.00599429 0.00599191 0.00598977 0.00598786 0.00598619 0.00598476 0.00598358 0.00598265 0.00598197 0.00598154 0.00598137 0.00541113 0.00550614 0.00558009 -0.00099239 0.00564688 ) ; } } // ************************************************************************* //
[ "chaseh13@login4.stampede2.tacc.utexas.edu" ]
chaseh13@login4.stampede2.tacc.utexas.edu
003b554e1146a524fb6aeb5aed5451ab408cd22e
c4044427638e507b7cafcd0348db5c5354db9982
/include/utils_test.cc
4f322457f0b9699c5c82e9ecd9a0118e684a865a
[]
no_license
kevinwkt/authenticator
d12d7fc76dd666b8da20bf6a3ca7d81aaff4c988
7b3915eec3cce6bda5458292c38146372eb3fd3e
refs/heads/master
2021-01-01T11:35:06.235360
2020-02-13T00:39:39
2020-02-13T00:39:39
239,260,886
0
0
null
null
null
null
UTF-8
C++
false
false
11,132
cc
#define CATCH_CONFIG_MAIN #include <iostream> #include "catch.hpp" #include "json.hpp" #include "globals.h" #include "utils.h" TEST_CASE("ErrorToViolation") { SECTION("Make sure each enum has the corresponding correct message") { REQUIRE(ErrorToViolation(kOk) == "Ok"); REQUIRE(ErrorToViolation(kAccountAlreadyInitialized) == "account-already-initialized"); REQUIRE(ErrorToViolation(kAccountNotInitialized) == "account-not-initialized"); REQUIRE(ErrorToViolation(kCardNotActive) == "card-not-active"); REQUIRE(ErrorToViolation(kInsufficientLimit) == "insufficient-limit"); REQUIRE(ErrorToViolation(kHighFrequencySmallInterval) == "high-frequency-small-interval"); REQUIRE(ErrorToViolation(kDoubledTransaction) == "doubled-transaction"); } } TEST_CASE("ParseISO8601") { // Create input dates in 2 different ISO8601 forms. const std::string standardIso1 = "1997-08-14T01:24:21+00:00"; const std::string standardIso2 = "2019-02-13T10:00:00.000Z"; const std::string standardIso3 = "2016-07-30T09:27:06+00:00"; const std::string standardIso4 = "2008-06-10T18:55:24.000Z"; const std::string standardIso5 = "2020-01-13T01:02:13.000Z"; // Create expected outputs in ull form. const unsigned long long standardUnix1 = 871521861; const unsigned long long standardUnix2 = 1550052000; const unsigned long long standardUnix3 = 1469870826; const unsigned long long standardUnix4 = 1213124124; SECTION("Parsing standard datetime from example") { REQUIRE((unsigned long long)ParseISO8601(standardIso1) == standardUnix1); REQUIRE((unsigned long long)ParseISO8601(standardIso2) == standardUnix2); REQUIRE((unsigned long long)ParseISO8601(standardIso3) == standardUnix3); REQUIRE((unsigned long long)ParseISO8601(standardIso4) == standardUnix4); } } TEST_CASE("IsTransactionFrequent") { // Create test vector with base transactions. std::vector<nlohmann::json> small_transactions{ { {"merchant", "a"}, {"amount", 10}, {"time", "2008-06-10T18:55:24.000z"}, }, }; std::vector<nlohmann::json> big_transactions{ { {"merchant", "a"}, {"amount", 10}, {"time", "2008-06-10T18:55:24.000z"}, }, { {"merchant", "b"}, {"amount", 20}, {"time", "2008-06-10T18:55:26.000z"}, }, { {"merchant", "c"}, {"amount", 20}, {"time", "2008-06-10T18:55:26.000z"}, }, }; SECTION("Checking for frequent transactions when transaction vector size is " "less than kMaxFrequency") { nlohmann::json random_incoming_transaction = { {"merchant", "c"}, {"amount", 10}, {"time", "2008-06-10T18:55:30.000Z"}, }; nlohmann::json window_edge_transaction = { {"merchant", "c"}, {"amount", 10}, {"time", "2008-06-10T18:55:31.000Z"}, }; // Incoming transaction is inside the 2 minute window but there are only 2 // transactions. Must return false. REQUIRE(IsTransactionFrequent(small_transactions, random_incoming_transaction) == false); // Incoming transaction is on the edge of the 2 minute window but there are // only 2 transactions. Must return false. REQUIRE(IsTransactionFrequent(small_transactions, window_edge_transaction) == false); } SECTION("Checking for frequent transactions based on basic examples with " "default parameters") { nlohmann::json before_window_edge_transaction = { {"merchant", "c"}, {"amount", 10}, {"time", "2008-06-10T18:57:23.000Z"}, }; nlohmann::json window_edge_transaction = { {"merchant", "c"}, {"amount", 10}, {"time", "2008-06-10T18:57:24.000Z"}, }; nlohmann::json after_window_edge_transaction = { {"merchant", "c"}, {"amount", 10}, {"time", "2008-06-10T18:57:25.000Z"}, }; // Incoming transaction is the 4th inside the 2 minute window. Must return // true. REQUIRE(IsTransactionFrequent(big_transactions, before_window_edge_transaction) == true); // Incoming transaction is the 4th on the edge of the 2 minute window. Must // return false since it is 2 min inclusive. REQUIRE(IsTransactionFrequent(big_transactions, window_edge_transaction) == false); // Incoming transaction is the 4th outside of the 2 minute window. Must // return false. REQUIRE(IsTransactionFrequent(big_transactions, after_window_edge_transaction) == false); } SECTION("Checking for frequent transactions based on basic examples with " "custom parameters") { nlohmann::json before_window_transaction = { {"merchant", "c"}, {"amount", 10}, {"time", "2008-06-10T18:55:25.000Z"}, }; nlohmann::json on_window_transaction = { {"merchant", "c"}, {"amount", 10}, {"time", "2008-06-10T18:55:34.000Z"}, }; nlohmann::json after_window_transaction = { {"merchant", "c"}, {"amount", 10}, {"time", "2008-06-10T18:55:35.000Z"}, }; // Create a frequency of 1 transaction every 10 seconds. (Rate-limit) const int kWindow = 10; const int kMaxFrequency = 1; // Incoming transaction is the 2nd inside the 10 second window where limit // is 1. Must return true. REQUIRE(IsTransactionFrequent(small_transactions, before_window_transaction, kWindow, kMaxFrequency) == true); // Incoming transaction is the 2nd on the 10 second window where limit is 1. // Must return false. REQUIRE(IsTransactionFrequent(small_transactions, on_window_transaction, kWindow, kMaxFrequency) == false); // Incoming transaction is the 2nd after the 10 second window where limit // is 1. Must return false. REQUIRE(IsTransactionFrequent(small_transactions, after_window_transaction, kWindow, kMaxFrequency) == false); } } TEST_CASE("IsTransactionSimilar") { // Create test vector with base transactions. std::vector<nlohmann::json> no_transactions{}; std::vector<nlohmann::json> small_transactions{ { {"merchant", "a"}, {"amount", 20}, {"time", "2008-06-10T18:55:26.000z"}, }, }; std::vector<nlohmann::json> big_transactions{ { {"merchant", "a"}, {"amount", 10}, {"time", "2008-06-10T18:55:24.000z"}, }, { {"merchant", "c"}, {"amount", 20}, {"time", "2008-06-10T18:55:26.000z"}, }, { {"merchant", "c"}, {"amount", 20}, {"time", "2008-06-10T18:55:277000z"}, }, }; SECTION("Checking for repeated transactions when transaction vector size is " "less than kMaxRepetition") { nlohmann::json random_incoming_transaction = { {"merchant", "c"}, {"amount", 10}, {"time", "2008-06-10T18:55:30.000Z"}, }; std::unordered_map<std::string, std::vector<nlohmann::json>> map_txn; // Incoming transaction handles when kMaxRepetition (1) is greater than // transactions.size(). REQUIRE(IsTransactionSimilar(map_txn, random_incoming_transaction) == false); } SECTION("Checking for repeated transactions using business rules and common " "examples") { // Create map from the transactions within small_transactions. std::unordered_map<std::string, std::vector<nlohmann::json>> map_txn; std::stringstream ss; for (int i = 0; i < small_transactions.size(); ++i) { for (const auto &el : small_transactions[i].items()) { if (el.key() != "time") { ss << el.key() << ":" << el.value() << ":"; } } map_txn[ss.str()].push_back(small_transactions[i]); ss.str(std::string()); } nlohmann::json before_window_transaction = { {"merchant", "a"}, {"amount", 20}, {"time", "2008-06-10T18:57:25.000Z"}, }; nlohmann::json on_window_transaction = { {"merchant", "a"}, {"amount", 20}, {"time", "2008-06-10T18:57:26.000Z"}, }; nlohmann::json after_window_transaction = { {"merchant", "a"}, {"amount", 20}, {"time", "2008-06-10T18:57:27.000Z"}, }; // Incoming transaction is inside the 2 minute window and previous // transaction is similar. Must return true. REQUIRE(IsTransactionSimilar(map_txn, before_window_transaction) == true); // Incoming transaction is on the edge of the 2 minute window and previous // transaction is similar. Must return false (120s is valid; not similar). REQUIRE(IsTransactionSimilar(map_txn, on_window_transaction) == false); // Incoming transaction is after the 2 minute window and previous // transaction is similar. Must return false. REQUIRE(IsTransactionSimilar(map_txn, after_window_transaction) == false); } SECTION("Checking for repeated transactions using custom business rules and " "common examples") { // Create map from the transactions within big_transactions. std::unordered_map<std::string, std::vector<nlohmann::json>> map_txn; std::stringstream ss; for (int i = 0; i < big_transactions.size(); ++i) { for (const auto &el : big_transactions[i].items()) { if (el.key() != "time") { ss << el.key() << ":" << el.value() << ":"; } } map_txn[ss.str()].push_back(big_transactions[i]); ss.str(std::string()); } nlohmann::json before_window_transaction = { {"merchant", "c"}, {"amount", 20}, {"time", "2008-06-10T18:55:27.000Z"}, }; nlohmann::json on_window_transaction = { {"merchant", "c"}, {"amount", 20}, {"time", "2008-06-10T18:55:36.000Z"}, }; nlohmann::json after_window_transaction = { {"merchant", "c"}, {"amount", 20}, {"time", "2008-06-10T18:55:37.000Z"}, }; // Create a frequency of 2 similar transaction every 10 seconds. // (Rate-limit) const int kWindow = 10; const int kMaxRepetition = 2; // Incoming transaction is inside the 10 seconds window but there are only 2 // transactions. Must return true. REQUIRE(IsTransactionSimilar(map_txn, before_window_transaction, kWindow, kMaxRepetition) == true); // Incoming transaction is on the edge of the 10 seconds window but there // are only 2 transactions. Must return false. REQUIRE(IsTransactionSimilar(map_txn, on_window_transaction, kWindow, kMaxRepetition) == false); // Incoming transaction is after the 10 seconds window but there are only 2 // transactions. Must return false. REQUIRE(IsTransactionSimilar(map_txn, after_window_transaction, kWindow, kMaxRepetition) == false); } }
[ "kaero@Kyungtaks-MacBook-Pro.local" ]
kaero@Kyungtaks-MacBook-Pro.local
fe96395bc9800cab9c1d54322f9c72f4a515b599
21a23e713a7121f1553d45a9bcf9c320f6e5a235
/src/src/GeorgeCoenExecutor.h
9af90d37e629a2595eea326e0653a095b6cdd40c
[]
no_license
Shtivi/RDR2-Bounties-Expansion
0615941076dd0b5c331a0c76a1ec7070f6d9345c
cfe60086beb08e053d206db4bc352ce451b69ebd
refs/heads/master
2021-07-18T13:41:06.739209
2021-05-15T13:58:12
2021-05-15T13:58:12
248,749,278
4
5
null
2020-10-20T17:06:11
2020-03-20T12:24:57
C++
UTF-8
C++
false
false
501
h
#pragma once class GeorgeCoenExecutor : public BaseMissionExecutor { private: Vector3 campfirePos; Object campfire; Ped horse; GuardsGroup* enemiesGroup; vector<Ped> horses; public: GeorgeCoenExecutor(BountyMissionData missionData, MapAreasManager* areasMgr); void update(); protected: void prepareSet(); Ped spawnTarget(); void onTargetLocated(); void cleanup(); private: void releaseUnnecessaryEntities(); void addHorse(Ped horse); void addHorse(const char* model, Vector3 pos); };
[ "noreply@github.com" ]
Shtivi.noreply@github.com
ec55711b7b9ffa9406c40680533ab7ef5677a5c0
20bf4b243fb673900f781838ec51ca98f6cca8fa
/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc
3509b31219cad527e29dc77c9abae7947bf0666c
[ "BSD-3-Clause" ]
permissive
andylin810/chromium
76f7169a43b0154963caff7d926e58bf7b2afeac
716d7ea4b7362febf5383d8ccea2180ae4cd88a5
refs/heads/master
2022-12-24T13:13:12.296359
2020-03-13T13:08:17
2020-03-13T13:08:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,600
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/settings/safety_check_handler.h" #include <string> #include <unordered_map> #include "base/bind.h" #include "base/optional.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/user_action_tester.h" #include "base/util/type_safety/strong_alias.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h" #include "chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.h" #include "chrome/browser/extensions/test_extension_service.h" #include "chrome/browser/ui/webui/help/test_version_updater.h" #include "chrome/common/extensions/api/passwords_private.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/crx_file/id_util.h" #include "components/password_manager/core/browser/bulk_leak_check_service.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/core/common/safe_browsing_prefs.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/test_web_ui.h" #include "extensions/browser/extension_prefs.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_CHROMEOS) #include "ui/chromeos/devicetype_utils.h" #endif // Components for building event strings. constexpr char kUpdates[] = "updates"; constexpr char kPasswords[] = "passwords"; constexpr char kSafeBrowsing[] = "safe-browsing"; constexpr char kExtensions[] = "extensions"; namespace { using Enabled = util::StrongAlias<class EnabledTag, bool>; using UserCanDisable = util::StrongAlias<class UserCanDisableTag, bool>; class TestingSafetyCheckHandler : public SafetyCheckHandler { public: using SafetyCheckHandler::AllowJavascript; using SafetyCheckHandler::DisallowJavascript; using SafetyCheckHandler::set_web_ui; TestingSafetyCheckHandler( std::unique_ptr<VersionUpdater> version_updater, password_manager::BulkLeakCheckService* leak_service, extensions::PasswordsPrivateDelegate* passwords_delegate, extensions::ExtensionPrefs* extension_prefs, extensions::ExtensionServiceInterface* extension_service) : SafetyCheckHandler(std::move(version_updater), leak_service, passwords_delegate, extension_prefs, extension_service) {} }; class TestPasswordsDelegate : public extensions::TestPasswordsPrivateDelegate { public: void SetNumCompromisedCredentials(int compromised_password_count) { compromised_password_count_ = compromised_password_count; } void SetPasswordCheckState( extensions::api::passwords_private::PasswordCheckState state) { state_ = state; } std::vector<extensions::api::passwords_private::CompromisedCredential> GetCompromisedCredentials() override { std::vector<extensions::api::passwords_private::CompromisedCredential> compromised(compromised_password_count_); for (int i = 0; i < compromised_password_count_; ++i) { compromised[i].username = "test" + base::NumberToString(i); } return compromised; } extensions::api::passwords_private::PasswordCheckStatus GetPasswordCheckStatus() override { extensions::api::passwords_private::PasswordCheckStatus status; status.state = state_; return status; } private: int compromised_password_count_ = 0; extensions::api::passwords_private::PasswordCheckState state_ = extensions::api::passwords_private::PASSWORD_CHECK_STATE_IDLE; }; class TestSafetyCheckExtensionService : public TestExtensionService { public: void AddExtensionState(const std::string& extension_id, Enabled enabled, UserCanDisable user_can_disable) { state_map_.emplace(extension_id, ExtensionState{enabled.value(), user_can_disable.value()}); } bool IsExtensionEnabled(const std::string& extension_id) const override { auto it = state_map_.find(extension_id); if (it == state_map_.end()) { return false; } return it->second.enabled; } bool UserCanDisableInstalledExtension( const std::string& extension_id) override { auto it = state_map_.find(extension_id); if (it == state_map_.end()) { return false; } return it->second.user_can_disable; } private: struct ExtensionState { bool enabled; bool user_can_disable; }; std::unordered_map<std::string, ExtensionState> state_map_; }; } // namespace class SafetyCheckHandlerTest : public ChromeRenderViewHostTestHarness { public: void SetUp() override; // Returns a |base::DictionaryValue| for safety check status update that // has the specified |component| and |new_state| if it exists; nullptr // otherwise. const base::DictionaryValue* GetSafetyCheckStatusChangedWithDataIfExists( const std::string& component, int new_state); std::string GenerateExtensionId(char char_to_repeat); void VerifyDisplayString(const base::DictionaryValue* event, const base::string16& expected); void VerifyDisplayString(const base::DictionaryValue* event, const std::string& expected); protected: TestVersionUpdater* version_updater_ = nullptr; std::unique_ptr<password_manager::BulkLeakCheckService> test_leak_service_; TestPasswordsDelegate test_passwords_delegate_; extensions::ExtensionPrefs* test_extension_prefs_ = nullptr; TestSafetyCheckExtensionService test_extension_service_; content::TestWebUI test_web_ui_; std::unique_ptr<TestingSafetyCheckHandler> safety_check_; private: // Replaces any instances of browser name (e.g. Google Chrome, Chromium, // etc) with "browser" to make sure tests work both on Chromium and // Google Chrome. void ReplaceBrowserName(base::string16* s); }; void SafetyCheckHandlerTest::SetUp() { ChromeRenderViewHostTestHarness::SetUp(); // The unique pointer to a TestVersionUpdater gets moved to // SafetyCheckHandler, but a raw pointer is retained here to change its // state. auto version_updater = std::make_unique<TestVersionUpdater>(); test_leak_service_ = std::make_unique<password_manager::BulkLeakCheckService>( nullptr, nullptr); version_updater_ = version_updater.get(); test_web_ui_.set_web_contents(web_contents()); test_extension_prefs_ = extensions::ExtensionPrefs::Get(profile()); safety_check_ = std::make_unique<TestingSafetyCheckHandler>( std::move(version_updater), test_leak_service_.get(), &test_passwords_delegate_, test_extension_prefs_, &test_extension_service_); test_web_ui_.ClearTrackedCalls(); safety_check_->set_web_ui(&test_web_ui_); safety_check_->AllowJavascript(); } const base::DictionaryValue* SafetyCheckHandlerTest::GetSafetyCheckStatusChangedWithDataIfExists( const std::string& component, int new_state) { for (const auto& it : test_web_ui_.call_data()) { const content::TestWebUI::CallData& data = *it; if (data.function_name() != "cr.webUIListenerCallback") { continue; } std::string event; if ((!data.arg1()->GetAsString(&event)) || event != "safety-check-" + component + "-status-changed") { continue; } const base::DictionaryValue* dictionary = nullptr; if (!data.arg2()->GetAsDictionary(&dictionary)) { continue; } int cur_new_state; if (dictionary->GetInteger("newState", &cur_new_state) && cur_new_state == new_state) { return dictionary; } } return nullptr; } std::string SafetyCheckHandlerTest::GenerateExtensionId(char char_to_repeat) { return std::string(crx_file::id_util::kIdSize * 2, char_to_repeat); } void SafetyCheckHandlerTest::VerifyDisplayString( const base::DictionaryValue* event, const base::string16& expected) { base::string16 display; ASSERT_TRUE(event->GetString("displayString", &display)); ReplaceBrowserName(&display); // Need to also replace any instances of Chrome and Chromium in the // expected string due to an edge case on ChromeOS, where a device name // is "Chrome", which gets replaced in the display string. base::string16 expected_replaced = expected; ReplaceBrowserName(&expected_replaced); EXPECT_EQ(expected_replaced, display); } void SafetyCheckHandlerTest::VerifyDisplayString( const base::DictionaryValue* event, const std::string& expected) { VerifyDisplayString(event, base::ASCIIToUTF16(expected)); } void SafetyCheckHandlerTest::ReplaceBrowserName(base::string16* s) { base::ReplaceSubstringsAfterOffset(s, 0, base::ASCIIToUTF16("Google Chrome"), base::ASCIIToUTF16("Browser")); base::ReplaceSubstringsAfterOffset(s, 0, base::ASCIIToUTF16("Chrome"), base::ASCIIToUTF16("Browser")); base::ReplaceSubstringsAfterOffset(s, 0, base::ASCIIToUTF16("Chromium"), base::ASCIIToUTF16("Browser")); } TEST_F(SafetyCheckHandlerTest, PerformSafetyCheck_MetricsRecorded) { base::UserActionTester user_action_tester; safety_check_->PerformSafetyCheck(); EXPECT_EQ(1, user_action_tester.GetActionCount("SafetyCheck.Started")); } TEST_F(SafetyCheckHandlerTest, CheckUpdates_Checking) { version_updater_->SetReturnedStatus(VersionUpdater::Status::CHECKING); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kUpdates, static_cast<int>(SafetyCheckHandler::UpdateStatus::kChecking)); ASSERT_TRUE(event); VerifyDisplayString(event, base::UTF8ToUTF16("Running…")); } TEST_F(SafetyCheckHandlerTest, CheckUpdates_Updated) { version_updater_->SetReturnedStatus(VersionUpdater::Status::UPDATED); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kUpdates, static_cast<int>(SafetyCheckHandler::UpdateStatus::kUpdated)); ASSERT_TRUE(event); #if defined(OS_CHROMEOS) base::string16 expected = base::ASCIIToUTF16("Your ") + ui::GetChromeOSDeviceName() + base::ASCIIToUTF16(" is up to date"); VerifyDisplayString(event, expected); #else VerifyDisplayString(event, "Browser is up to date"); #endif } TEST_F(SafetyCheckHandlerTest, CheckUpdates_Updating) { version_updater_->SetReturnedStatus(VersionUpdater::Status::UPDATING); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kUpdates, static_cast<int>(SafetyCheckHandler::UpdateStatus::kUpdating)); ASSERT_TRUE(event); #if defined(OS_CHROMEOS) VerifyDisplayString(event, "Updating your device"); #else VerifyDisplayString(event, "Updating Browser"); #endif } TEST_F(SafetyCheckHandlerTest, CheckUpdates_Relaunch) { version_updater_->SetReturnedStatus(VersionUpdater::Status::NEARLY_UPDATED); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kUpdates, static_cast<int>(SafetyCheckHandler::UpdateStatus::kRelaunch)); ASSERT_TRUE(event); #if defined(OS_CHROMEOS) VerifyDisplayString( event, "Nearly up to date! Restart your device to finish updating."); #else VerifyDisplayString(event, "Nearly up to date! Relaunch Browser to finish " "updating. Incognito windows won't reopen."); #endif } TEST_F(SafetyCheckHandlerTest, CheckUpdates_DisabledByAdmin) { version_updater_->SetReturnedStatus( VersionUpdater::Status::DISABLED_BY_ADMIN); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kUpdates, static_cast<int>(SafetyCheckHandler::UpdateStatus::kDisabledByAdmin)); ASSERT_TRUE(event); VerifyDisplayString( event, "Updates are managed by <a target=\"_blank\" " "href=\"https://support.google.com/accounts/answer/6208960\">your " "administrator</a>"); } TEST_F(SafetyCheckHandlerTest, CheckUpdates_FailedOffline) { version_updater_->SetReturnedStatus(VersionUpdater::Status::FAILED_OFFLINE); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kUpdates, static_cast<int>(SafetyCheckHandler::UpdateStatus::kFailedOffline)); ASSERT_TRUE(event); VerifyDisplayString(event, "Browser can't check for updates. Try checking your " "internet connection."); } TEST_F(SafetyCheckHandlerTest, CheckUpdates_Failed) { version_updater_->SetReturnedStatus(VersionUpdater::Status::FAILED); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kUpdates, static_cast<int>(SafetyCheckHandler::UpdateStatus::kFailed)); ASSERT_TRUE(event); VerifyDisplayString( event, "Browser didn't update, something went wrong. <a target=\"_blank\" " "href=\"https://support.google.com/chrome/answer/111996\">Fix " "Browser " "update problems and failed updates.</a>"); } TEST_F(SafetyCheckHandlerTest, CheckSafeBrowsing_Enabled) { Profile::FromWebUI(&test_web_ui_) ->GetPrefs() ->SetBoolean(prefs::kSafeBrowsingEnabled, true); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kSafeBrowsing, static_cast<int>(SafetyCheckHandler::SafeBrowsingStatus::kEnabled)); ASSERT_TRUE(event); VerifyDisplayString(event, "Safe Browsing is up to date and protecting you from " "harmful sites and downloads"); } TEST_F(SafetyCheckHandlerTest, CheckSafeBrowsing_Disabled) { Profile::FromWebUI(&test_web_ui_) ->GetPrefs() ->SetBoolean(prefs::kSafeBrowsingEnabled, false); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kSafeBrowsing, static_cast<int>(SafetyCheckHandler::SafeBrowsingStatus::kDisabled)); ASSERT_TRUE(event); VerifyDisplayString( event, "Safe Browsing is off. To stay safe on the web, turn it on."); } TEST_F(SafetyCheckHandlerTest, CheckSafeBrowsing_DisabledByAdmin) { TestingProfile::FromWebUI(&test_web_ui_) ->AsTestingProfile() ->GetTestingPrefService() ->SetManagedPref(prefs::kSafeBrowsingEnabled, std::make_unique<base::Value>(false)); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kSafeBrowsing, static_cast<int>( SafetyCheckHandler::SafeBrowsingStatus::kDisabledByAdmin)); ASSERT_TRUE(event); VerifyDisplayString( event, "<a target=\"_blank\" " "href=\"https://support.google.com/accounts/answer/6208960\">Your " "administrator</a> has turned off Safe Browsing"); } TEST_F(SafetyCheckHandlerTest, CheckSafeBrowsing_DisabledByExtension) { TestingProfile::FromWebUI(&test_web_ui_) ->AsTestingProfile() ->GetTestingPrefService() ->SetExtensionPref(prefs::kSafeBrowsingEnabled, std::make_unique<base::Value>(false)); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kSafeBrowsing, static_cast<int>( SafetyCheckHandler::SafeBrowsingStatus::kDisabledByExtension)); ASSERT_TRUE(event); VerifyDisplayString(event, "An extension has turned off Safe Browsing"); } TEST_F(SafetyCheckHandlerTest, CheckPasswords_ObserverRemovedAfterError) { safety_check_->PerformSafetyCheck(); // First, a "running" change of state. test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kRunning); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kChecking)); ASSERT_TRUE(event); VerifyDisplayString(event, base::UTF8ToUTF16("Running…")); // Second, an "offline" state. test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kNetworkError); const base::DictionaryValue* event2 = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kOffline)); ASSERT_TRUE(event2); VerifyDisplayString(event2, "Browser can't check your passwords. Try checking your " "internet connection."); // Another error, but since the previous state is terminal, the handler // should no longer be observing the BulkLeakCheckService state. test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kServiceError); const base::DictionaryValue* event3 = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kOffline)); ASSERT_TRUE(event3); } TEST_F(SafetyCheckHandlerTest, CheckPasswords_InterruptedAndRefreshed) { safety_check_->PerformSafetyCheck(); // Password check running. test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kRunning); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kChecking)); ASSERT_TRUE(event); VerifyDisplayString(event, base::UTF8ToUTF16("Running…")); // The check gets interrupted and the page is refreshed. safety_check_->DisallowJavascript(); safety_check_->AllowJavascript(); // Another run of the safety check. safety_check_->PerformSafetyCheck(); test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kRunning); const base::DictionaryValue* event2 = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kChecking)); ASSERT_TRUE(event2); test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kSignedOut); const base::DictionaryValue* event3 = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kSignedOut)); ASSERT_TRUE(event3); VerifyDisplayString( event3, "Browser can't check your passwords because you're not signed in"); } TEST_F(SafetyCheckHandlerTest, CheckPasswords_StartedTwice) { safety_check_->PerformSafetyCheck(); safety_check_->PerformSafetyCheck(); // First, a "running" change of state. test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kRunning); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kChecking)); ASSERT_TRUE(event); // Then, a network error. test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kNetworkError); const base::DictionaryValue* event2 = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kOffline)); EXPECT_TRUE(event2); VerifyDisplayString(event2, "Browser can't check your passwords. Try checking your " "internet connection."); } TEST_F(SafetyCheckHandlerTest, CheckPasswords_Safe) { safety_check_->PerformSafetyCheck(); // First, a "running" change of state. test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kRunning); EXPECT_TRUE(GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kChecking))); // Second, a "safe" state. test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kIdle); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kSafe)); EXPECT_TRUE(event); VerifyDisplayString(event, "No compromised passwords found"); } TEST_F(SafetyCheckHandlerTest, CheckPasswords_CompromisedExist) { constexpr int kCompromised = 7; test_passwords_delegate_.SetNumCompromisedCredentials(kCompromised); safety_check_->PerformSafetyCheck(); // First, a "running" change of state. test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kRunning); EXPECT_TRUE(GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kChecking))); // Compromised passwords found state. test_leak_service_->set_state_and_notify( password_manager::BulkLeakCheckService::State::kIdle); const base::DictionaryValue* event2 = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>( SafetyCheckHandler::PasswordsStatus::kCompromisedExist)); ASSERT_TRUE(event2); VerifyDisplayString( event2, base::NumberToString(kCompromised) + " compromised passwords"); } TEST_F(SafetyCheckHandlerTest, CheckPasswords_Error) { safety_check_->PerformSafetyCheck(); EXPECT_TRUE(test_passwords_delegate_.StartPasswordCheckTriggered()); static_cast<password_manager::BulkLeakCheckService::Observer*>( safety_check_.get()) ->OnStateChanged( password_manager::BulkLeakCheckService::State::kServiceError); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>(SafetyCheckHandler::PasswordsStatus::kError)); ASSERT_TRUE(event); VerifyDisplayString(event, "Browser can't check your passwords. Try again later."); } TEST_F(SafetyCheckHandlerTest, CheckPasswords_RunningOneCompromised) { test_passwords_delegate_.SetPasswordCheckState( extensions::api::passwords_private::PASSWORD_CHECK_STATE_RUNNING); test_passwords_delegate_.SetStartPasswordCheckReturnSuccess(false); test_passwords_delegate_.SetNumCompromisedCredentials(1); safety_check_->PerformSafetyCheck(); EXPECT_TRUE(test_passwords_delegate_.StartPasswordCheckTriggered()); static_cast<password_manager::BulkLeakCheckService::Observer*>( safety_check_.get()) ->OnStateChanged(password_manager::BulkLeakCheckService::State::kIdle); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kPasswords, static_cast<int>( SafetyCheckHandler::PasswordsStatus::kCompromisedExist)); ASSERT_TRUE(event); VerifyDisplayString(event, "1 compromised password"); } TEST_F(SafetyCheckHandlerTest, CheckExtensions_NoExtensions) { safety_check_->PerformSafetyCheck(); EXPECT_TRUE(GetSafetyCheckStatusChangedWithDataIfExists( kExtensions, static_cast<int>( SafetyCheckHandler::ExtensionsStatus::kNoneBlocklisted))); } TEST_F(SafetyCheckHandlerTest, CheckExtensions_NoneBlocklisted) { std::string extension_id = GenerateExtensionId('a'); scoped_refptr<const extensions::Extension> extension = extensions::ExtensionBuilder(extension_id).Build(); test_extension_prefs_->OnExtensionInstalled( extension.get(), extensions::Extension::State::ENABLED, syncer::StringOrdinal(), ""); test_extension_prefs_->SetExtensionBlacklistState( extension_id, extensions::NOT_BLACKLISTED); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kExtensions, static_cast<int>( SafetyCheckHandler::ExtensionsStatus::kNoneBlocklisted)); EXPECT_TRUE(event); VerifyDisplayString(event, "You're protected from potentially harmful extensions"); } TEST_F(SafetyCheckHandlerTest, CheckExtensions_BlocklistedAllDisabled) { std::string extension_id = GenerateExtensionId('a'); scoped_refptr<const extensions::Extension> extension = extensions::ExtensionBuilder("test0").SetID(extension_id).Build(); test_extension_prefs_->OnExtensionInstalled( extension.get(), extensions::Extension::State::DISABLED, syncer::StringOrdinal(), ""); test_extension_prefs_->SetExtensionBlacklistState( extension_id, extensions::BLACKLISTED_MALWARE); test_extension_service_.AddExtensionState(extension_id, Enabled(false), UserCanDisable(false)); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kExtensions, static_cast<int>( SafetyCheckHandler::ExtensionsStatus::kBlocklistedAllDisabled)); EXPECT_TRUE(event); VerifyDisplayString( event, "1 potentially harmful extension is off. You can also remove it."); } TEST_F(SafetyCheckHandlerTest, CheckExtensions_BlocklistedReenabledAllByUser) { std::string extension_id = GenerateExtensionId('a'); scoped_refptr<const extensions::Extension> extension = extensions::ExtensionBuilder("test0").SetID(extension_id).Build(); test_extension_prefs_->OnExtensionInstalled( extension.get(), extensions::Extension::State::ENABLED, syncer::StringOrdinal(), ""); test_extension_prefs_->SetExtensionBlacklistState( extension_id, extensions::BLACKLISTED_POTENTIALLY_UNWANTED); test_extension_service_.AddExtensionState(extension_id, Enabled(true), UserCanDisable(true)); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kExtensions, static_cast<int>(SafetyCheckHandler::ExtensionsStatus:: kBlocklistedReenabledAllByUser)); EXPECT_TRUE(event); VerifyDisplayString(event, "You turned 1 potentially harmful extension back on"); } TEST_F(SafetyCheckHandlerTest, CheckExtensions_BlocklistedReenabledAllByAdmin) { std::string extension_id = GenerateExtensionId('a'); scoped_refptr<const extensions::Extension> extension = extensions::ExtensionBuilder("test0").SetID(extension_id).Build(); test_extension_prefs_->OnExtensionInstalled( extension.get(), extensions::Extension::State::ENABLED, syncer::StringOrdinal(), ""); test_extension_prefs_->SetExtensionBlacklistState( extension_id, extensions::BLACKLISTED_POTENTIALLY_UNWANTED); test_extension_service_.AddExtensionState(extension_id, Enabled(true), UserCanDisable(false)); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kExtensions, static_cast<int>(SafetyCheckHandler::ExtensionsStatus:: kBlocklistedReenabledAllByAdmin)); VerifyDisplayString(event, "Your administrator turned 1 potentially harmful " "extension back on"); } TEST_F(SafetyCheckHandlerTest, CheckExtensions_BlocklistedReenabledSomeByUser) { std::string extension_id = GenerateExtensionId('a'); scoped_refptr<const extensions::Extension> extension = extensions::ExtensionBuilder("test0").SetID(extension_id).Build(); test_extension_prefs_->OnExtensionInstalled( extension.get(), extensions::Extension::State::ENABLED, syncer::StringOrdinal(), ""); test_extension_prefs_->SetExtensionBlacklistState( extension_id, extensions::BLACKLISTED_POTENTIALLY_UNWANTED); test_extension_service_.AddExtensionState(extension_id, Enabled(true), UserCanDisable(true)); std::string extension2_id = GenerateExtensionId('b'); scoped_refptr<const extensions::Extension> extension2 = extensions::ExtensionBuilder("test1").SetID(extension2_id).Build(); test_extension_prefs_->OnExtensionInstalled( extension2.get(), extensions::Extension::State::ENABLED, syncer::StringOrdinal(), ""); test_extension_prefs_->SetExtensionBlacklistState( extension2_id, extensions::BLACKLISTED_POTENTIALLY_UNWANTED); test_extension_service_.AddExtensionState(extension2_id, Enabled(true), UserCanDisable(false)); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kExtensions, static_cast<int>(SafetyCheckHandler::ExtensionsStatus:: kBlocklistedReenabledSomeByUser)); EXPECT_TRUE(event); VerifyDisplayString(event, "You turned 1 potentially harmful extension back " "on. Your administrator " "turned 1 potentially harmful extension back on."); } TEST_F(SafetyCheckHandlerTest, CheckExtensions_Error) { // One extension in the error state. std::string extension_id = GenerateExtensionId('a'); scoped_refptr<const extensions::Extension> extension = extensions::ExtensionBuilder("test0").SetID(extension_id).Build(); test_extension_prefs_->OnExtensionInstalled( extension.get(), extensions::Extension::State::ENABLED, syncer::StringOrdinal(), ""); test_extension_prefs_->SetExtensionBlacklistState( extension_id, extensions::BLACKLISTED_UNKNOWN); test_extension_service_.AddExtensionState(extension_id, Enabled(true), UserCanDisable(true)); // Another extension blocklisted. std::string extension2_id = GenerateExtensionId('b'); scoped_refptr<const extensions::Extension> extension2 = extensions::ExtensionBuilder("test1").SetID(extension2_id).Build(); test_extension_prefs_->OnExtensionInstalled( extension2.get(), extensions::Extension::State::ENABLED, syncer::StringOrdinal(), ""); test_extension_prefs_->SetExtensionBlacklistState( extension2_id, extensions::BLACKLISTED_POTENTIALLY_UNWANTED); test_extension_service_.AddExtensionState(extension2_id, Enabled(true), UserCanDisable(false)); safety_check_->PerformSafetyCheck(); const base::DictionaryValue* event = GetSafetyCheckStatusChangedWithDataIfExists( kExtensions, static_cast<int>(SafetyCheckHandler::ExtensionsStatus::kError)); EXPECT_TRUE(event); VerifyDisplayString(event, "Browser can't check your extensions. Try again later."); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ef4779052e84be749605dcd88b07a3796f752a3e
aefd1312f95eaffefeca732521d1a7e09badf4c0
/2nd smes/dfefgtrg.cpp
80efaf784a90dee9a2ae3a1af462cd37816b5d5b
[]
no_license
IT-WALA-BOY/final-project
2d18cbaf7858673d6ea0c97827f8908b6ffa05cb
f9e5b534d50574aa619d2f3645bce0c5ab904894
refs/heads/main
2023-03-15T10:35:30.056086
2021-03-14T08:40:37
2021-03-14T08:40:37
343,029,572
2
1
null
null
null
null
UTF-8
C++
false
false
771
cpp
#include<iostream> using namespace std; //forward function declaration int hidden(int num1, int num2); int compute(int one, int two); int main(){ cout<<hidden(30,20) <<" " << compute(10,hidden(30,20)) << endl; int x = 2, y = 8; cout<<compute(y,x) <<endl; return 0; } //calculate the hidden value based on num1 and num2 int hidden(int num1, int num2) { //if num1 more than20 //divide num2 by 10 and assign to num1 if (num1 > 20) num1 = num2 / 10; else if (num2 > 20)//if num2 more than 20 divide num1 by 20 num2 = num1 / 20; else return num1 - num2; return num1 * num2; } int compute(int one, int two) { int secret = one; for (int i = one + 1; i <= two % 2; i++) secret = secret + i * i; return secret; }
[ "bsitbeve@gmail.com" ]
bsitbeve@gmail.com
630b92860eff3a05a72da4c61fbc030138f5e5b8
6e507c901947ca9e3564e4adbe8c0c9f778bfb91
/SeedEngine_16_model/Engine/Engine.h
63fa78cc1b0a9b2cae98dc88dbe803d5e95af5f3
[]
no_license
poigwym/SeedEngine
0b07960721d01ec99a0a06b9fda43bfeabd4d3be
06f72d35a9c0e610f8f0801fbc62d9440a592e8a
refs/heads/master
2021-01-10T04:37:20.414481
2016-03-03T14:28:53
2016-03-03T14:28:53
51,929,020
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,276
h
#pragma once #include"prequest.h" namespace Seed { class Engine; class Game { protected: Engine *engine; public: Game() { engine = 0; } virtual ~Game() {} inline void setEngine(Engine *e){ engine = e; } virtual void init(){} virtual void update(){} virtual void render(){} virtual void clear(){} }; class Engine { protected: HINSTANCE mhInstance; HWND mHWND; Game *game; Timer *timer; Window *mWindow; RenderingEngine *mRenderingEngine; SceneManager *mSceneGM; TextureManager* mTextureGM; MaterialManager* mMaterialGM; public: Engine(const HINSTANCE &hInstance, Game *game) : mhInstance(hInstance), game(game) { if (game) game->setEngine(this); } virtual ~Engine() { clear(); } bool init(); void update(); void render(); void clear(); Window* getWindow() { return mWindow; } // ¿ªÅÜ void loop(); void run(); inline RenderingEngine* getRenderingEngine() const { return mRenderingEngine; } inline SceneManager* getSceneManager() const { return mSceneGM; } inline TextureManager* getTextureGM() { return mTextureGM; } }; } // namespace //=========================for game window ================================= typedef HINSTANCE WindowID; int main(WindowID id);
[ "873944287@qq.com" ]
873944287@qq.com
e6331b5394491e8dfbd4200c22c4e17b39a240b5
0d4c7ba938f78f0a5416ceb7cab0d0f3fabf47ce
/Buses/CSchedule.cpp
886081f093dc35db76eb3ce6e4cbbff66787eed9
[]
no_license
femoiseev/algo-2sem
deaecb1654ad878ed0c1d1d248aa8c8c307cb248
c9f03d7b6da46a87df0626cc3834153d3b354d0e
refs/heads/master
2021-06-04T22:11:09.902602
2016-08-21T16:43:40
2016-08-21T16:43:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,105
cpp
// // Created by Teodor Moiseev on 09.05.16. // #include "CSchedule.h" #include <set> int CSchedule::day_length = 24; void CSchedule::AddEdge(size_t start, size_t end, int start_time, int end_time) { // Добавление маршрута.в CEdge* new_edge = new CEdge(start_time, end_time, nodes[end]); nodes[start]->edges.push_back(new_edge); } int CSchedule::FindShortestWay(size_t start, size_t end, int start_time) { // Используем алгоритм Дейкстры int res = -1; nodes[start]->time = start_time; std::set<CNode*> set; // Создаем сет вершин set.insert(nodes[start]); while(!set.empty()) { // Пока сет не пустой CNode* cur = *set.begin(); // Достаем из него минимум set.erase(set.begin()); if(cur->number == end) { // Если это конец, то возвращаем время пути до него res = cur->time - start_time; break; } int day_time = cur->time % day_length; for(int i = 0; i < cur->edges.size(); i++) { // Иначе перебираем все рейсы из текущей CNode* next = cur->edges[i]->end; int arrive_time = cur->time; arrive_time += (cur->edges[i]->start_time - day_time + day_length) % day_length; // Считаем, сколько времени мы будем ждать выезда arrive_time += (cur->edges[i]->end_time - cur->edges[i]->start_time + day_length) % day_length; // Считаем, сколько времени мы будем ехать if(arrive_time < next->time || next->time == -1) { // Если надо обновить кратчайший путь, то обновляем set.erase(next); next->time = arrive_time; set.insert(next); } } } for(int i = 0; i < nodes.size(); i++) { // Возвращаем граф в исходное состояние nodes[i]->time = -1; } return res; }
[ "femoiseev@gmail.com" ]
femoiseev@gmail.com
e74e19fc7ec29f199860c0c12a0187d589e9ff44
cf4edf395e40dd1f0eb191c26d9c9466c325138c
/M5Stack/examples/9-2NXM5SerialTest/9-2NXM5SerialTest.ino
12810e862bd6eab857a25f3efad356f3960b9e7b
[]
no_license
inexglobal/nx-m5stack
9734668eef3ed16cba46166673d45ea99215a12f
b8a13d33c5eee1e72797076ad4e34f2a1a792a0a
refs/heads/master
2020-08-30T16:30:48.443383
2020-05-07T07:13:11
2020-05-07T07:13:11
218,432,960
0
0
null
null
null
null
UTF-8
C++
false
false
1,677
ino
#include <M5Stack.h> void setup() { M5.begin(); Serial.begin(115200); //กำหนดอัตราส่งข้อมูล 115200 bps M5.Lcd.setCursor(100, 0, 4); M5.Lcd.print("Serial"); } int x , y = 0; void loop() { if (Serial.available()) { String topic = ""; String msg = ""; while (Serial.available()) { //;วนทำซ้ำจนกว่าจะอ่านข้อมูลเสร็จ //อ่านและเก็บเฉพาะข้อความที่มีเครื่องหมาย = อยู่ด้านหลังข้อความ topic = Serial.readStringUntil('='); //อ่านและเก็บเฉพาะข้อความที่ \n อยู่ด้านหลังข้อความ (\n หมายถึงขึ้นบรรทัดใหม่) msg = Serial.readStringUntil('\n'); msg.trim(); //ตัดช่องว่างหัวและท้ายข้อความออก } if (topic == "x") { x = msg.toInt(); //เปลี่ยนข้อความให้เป็นตัวเลข } if (topic == "y") { y = msg.toInt(); //เปลี่ยนข้อความให้เป็นตัวเลข } M5.Lcd.setCursor(0, 40, 4); //แสดงผลลัพธ์ออกทางหน้าจอ M5.Lcd.printf("x = %d \ny = %d \nsum= %d \n", x, y, x + y); //แสดงผลลัพธ์ไปยัง Serila Monitor Serial.printf("x = %d \ny = %d \nsum= %d \n", x, y, x + y); } delay(1000); }
[ "noreply@github.com" ]
inexglobal.noreply@github.com
d8e88f66d2264d87e989109c69babcaed02968bb
c1a465c982b9440401bc73776048bf49d2cfac93
/clang-tools-extra/test/clang-tidy/checkers/bsl-op-mixed-increment-decrement.cpp
886f102de5b9e44a09c9239a10c4b9dff932d3f9
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
Bareflank/llvm-project
5a250ef0fd95d07fa236c484ec13b3c9165e6498
288e1910531a9a65aed8e453bf16c2ba04fbcc43
refs/heads/bsl-tidy
2022-03-21T17:16:06.952336
2022-02-04T15:32:53
2022-02-04T15:32:53
244,096,908
7
5
null
2022-02-04T15:32:54
2020-03-01T06:09:12
C++
UTF-8
C++
false
false
768
cpp
int i = 0; int j = ++i + 2; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use of '++' is mixed with other operations [bsl-op-mixed-increment-decrement] int p = j++; void f() { int buf[10]; p = buf[--j]; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of '--' is mixed with other operations [bsl-op-mixed-increment-decrement] if (int k = i; ++k) { // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use of '++' is mixed with other operations [bsl-op-mixed-increment-decrement] } do { i--; } while (i-- > 0); // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: use of '--' is mixed with other operations [bsl-op-mixed-increment-decrement] for (int q = 0; q < 10; q++) { } for (auto &e : buf) { e = 42; } }
[ "connojd@protonmail.com" ]
connojd@protonmail.com
55bb37492cbb07d8c670e044a4c3e4ec8f47188e
7c4c33c1916c6a96355b93dcef4cf9f80e3b2658
/trafficlights.h
67b8e5685ecd5062e2dfcf417ad9de0554f7de7f
[]
no_license
AlternatingCurrent/TrafficSimulator
a1849cea237af3cf11fd44070a695f7f7ce4b1be
af5fcf36020d83b45832c2f68368333990dc4e4b
refs/heads/master
2021-01-13T00:50:13.956450
2015-11-18T23:53:12
2015-11-18T23:53:12
43,818,143
0
1
null
null
null
null
UTF-8
C++
false
false
903
h
#ifndef TRAFFICLIGHTS_H #define TRAFFICLIGHTS_H #include <QGraphicsPixmapItem> #include <QGraphicsRectItem> #include <QGraphicsItem> #include <QPoint> #include <QObject> #include <QString> #include "subject.h" class trafficlights: public QObject, public QGraphicsPixmapItem { Q_OBJECT public: trafficlights(Subject *aVehicle, QGraphicsItem * parent =0); double distanceTo(QGraphicsItem * item); void cross_road(int pedestrianNo); bool trafficLightOn; bool getTrafficLightsState(); bool get_has_vehicle(); void setPosOfLights(int x, int y); int getPos(QString x); public slots: void acquire_target(); void traffic_light_timer(); void traffic_light_concurrency_timer(); private: void setUp(); int pedestrianCount; QGraphicsRectItem * area; QPointF destination; bool has_vehicle; int xPos; int yPos; }; #endif // TRAFFICLIGHTS_H
[ "juan_condon1@hotmail.com" ]
juan_condon1@hotmail.com
121d9f2a8308c6cced15efd0e25f7673ad8bf80c
1266254e5763ec1dbbd861fa2045bcef1edbcec6
/SurgSim/Math/UnitTests/KalmanFilterTests.cpp
3f1989cc0b0353d9e794abadbdedc1dacfd4abd8
[ "Bitstream-Vera", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
simquest/opensurgsim
0a443f8e54b276f4e41ed991b2fcb3d2b0c0b5a7
bd30629f2fd83f823632293959b7654275552fa9
refs/heads/master
2022-02-13T15:05:47.744267
2020-11-24T14:27:19
2020-11-24T14:27:19
24,512,532
30
11
Apache-2.0
2022-02-03T20:18:01
2014-09-26T19:25:40
C++
UTF-8
C++
false
false
4,506
cpp
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// \file /// Tests for the KalmanFilter.cpp functions. #include <boost/math/special_functions/fpclassify.hpp> #include <gtest/gtest.h> #include "SurgSim/Math/KalmanFilter.h" #include "SurgSim/Math/Matrix.h" #include "SurgSim/Math/Vector.h" typedef Eigen::Matrix<double, 1, 1> Vector1d; typedef Eigen::Matrix<double, 1, 1, Eigen::RowMajor> Matrix11d; namespace SurgSim { namespace Math { TEST(KalmanFilterTests, 1DConstant) { auto kalman = std::make_shared<KalmanFilter<1, 1>>(); EXPECT_TRUE(boost::math::isnan(kalman->getState()[0])); const Vector1d initialState = Vector1d::Zero(); kalman->setInitialState(initialState); // the state is a scalar, and we have an initial guess for it EXPECT_DOUBLE_EQ(initialState[0], kalman->getState()[0]); kalman->setInitialStateCovariance(Matrix11d::Constant(1000.0)); // the uncertainty about initial guess is high kalman->setStateTransition(Matrix11d::Constant(1.0)); // we predict the true state will stay constant kalman->setObservationMatrix(Matrix11d::Constant(1.0)); // we observe the actual state plus measurement error kalman->setProcessNoiseCovariance(Matrix11d::Constant(0.0001)); // the noise in the prediction action is low kalman->setMeasurementNoiseCovariance(Matrix11d::Constant(0.1)); // the assumed measurement noise const double measurements[] = {0.9, 0.8, 1.1, 1, 0.95, 1.05, 1.2, 0.9, 0.85, 1.15}; for (double measurement : measurements) { kalman->update(Vector1d::Constant(measurement)); } const double result = 0.99046032523740679; EXPECT_NEAR(result , kalman->getState()[0], 1e-9); // The state doesn't change unless there's an update. EXPECT_NEAR(result, kalman->getState()[0], 1e-9); // Updating a constant model without a measurement shouldn't change the state. EXPECT_NEAR(result, kalman->update()[0], 1e-9); } TEST(KalmanFilterTests, 1DVelocity) { auto kalman = std::make_shared<KalmanFilter<2, 1>>(); // The state is the position and velocity, and here's our initial guess. const Vector2d initialState = Vector2d::Zero(); kalman->setInitialState(initialState); const Matrix22d initialStateCovariance = 1000.0 * Matrix22d::Identity(); kalman->setInitialStateCovariance(initialStateCovariance); // The new position is the old position plus velocity times dt. The velocity is constant. const double dt = 0.1; Matrix22d stateTransition; stateTransition << 1.0, dt, 0.0, 1.0; kalman->setStateTransition(stateTransition); // The measurements are of the position, plus measurement error. Eigen::Matrix<double, 1, 2, Eigen::RowMajor> observationMatrix; observationMatrix.setIdentity(); kalman->setObservationMatrix(observationMatrix); const double velocityNoise = 0.001; // Assume the noise is only in the velocity, so a continuous noise model of [0, 0; 0, velocityNoise], then // approximate that by a time-discrete process to get... Matrix22d processNoise; processNoise << dt * dt * dt * velocityNoise / 3.0, dt * dt * velocityNoise / 2.0, dt * dt * velocityNoise / 3.0, dt * velocityNoise; kalman->setProcessNoiseCovariance(processNoise); kalman->setMeasurementNoiseCovariance(Matrix11d::Constant(0.1)); const double measurements[] = {0.11, 0.29, 0.32, 0.5, 0.58, 0.54}; for (double measurement : measurements) { kalman->update(Vector1d::Constant(measurement)); } // check the state const double position = 0.61844193701221828; EXPECT_NEAR(position, kalman->getState()[0], 1e-9); const double velocity = 0.91376229444025137; EXPECT_NEAR(velocity, kalman->getState()[1], 1e-9); // The state doesn't change unless there's an update. EXPECT_NEAR(position, kalman->getState()[0], 1e-9); // Updating without a measurement will predict ahead. EXPECT_NEAR(position + velocity * dt, kalman->update()[0], 1e-9); EXPECT_NEAR(velocity, kalman->getState()[1], 1e-9); } }; // namespace Math }; // namespace SurgSim
[ "rbeasley@simquest.com" ]
rbeasley@simquest.com
73e1cb5e1eb723f6256f80641933f330ed14b93e
bee5fa0038db0a6f86eb448c89b95d76ca48bdcf
/ScoreBoard.h
fb47aef7262ed13c4c31af48101cedf0a3391fb1
[]
no_license
RKartodijoyo/QTBasketballScoreV2
695e615d3bdffa20d9e5cdc7f2d7129ed89f5cd3
9102e740702a77ac139846741df43dfe4afdb8cf
refs/heads/master
2020-04-11T07:25:27.585225
2018-12-14T12:35:53
2018-12-14T12:35:53
161,609,727
0
1
null
null
null
null
UTF-8
C++
false
false
2,636
h
#pragma once #include <QWidget> #include <QTime> #include <QTimer> #include<chrono> namespace score { namespace cr = std::chrono; class Team { private: int m_score = 0; int m_foul = 0; QString m_name; public: Team() { } Team(int score, int foul) : m_score(score), m_foul(foul) { } ~Team() { } bool add_score(int add) { m_score = std::max(m_score + add, 0); return add != 0; } bool add_foul(int add) { m_foul = std::max(m_foul + add, 0); return add != 0; } int score() const { return m_score; } void score(int _score) { m_score = _score; } int foul() const { return m_foul; } void foul(int _foul) { m_foul = _foul; } void name(const QString& str) { m_name = str; } const QString& name() const { return m_name; } }; class Board : public QObject { Q_OBJECT public: Board(); ~Board() { } int home_score() const { return m_home.score(); } int home_foul() const { return m_home.foul(); } int away_score() const { return m_away.score(); } int away_foul() const { return m_away.foul(); } void home_name(const QString& str); const QString& home_name() const; void away_name(const QString& str); const QString& away_name() const; void update_home(Team* add); void update_away(Team* add); void reset_score(); void reset_foul(); void start_timer(); void pause_timer(); void reset_timer(); void dec_round(); void inc_round(); int round() const; void set_timer_for(cr::milliseconds ms); void add_timer_time(cr::milliseconds ms); QString get_time() const; int twenty_four() const; void reset_twenty_four(); void reset_fourteen(); void play_tet_sound() const; enum class changed { home_score, home_foul, home_name, away_score, away_foul, away_name, round, timer, twenty_four, }; signals: void on_changed(changed change); private slots: void internal_on_second_tick(); void on_timeout(); private: Team m_home; Team m_away; int m_round = 1; QTime m_time; cr::seconds m_seconds; QTimer m_timer_second; int m_24 = 24; }; }
[ "noreply@github.com" ]
RKartodijoyo.noreply@github.com
acb3eeb300a1c3c0ea0c5966aea1770173424553
6aa1bc3546f7faae763435de41671e0d2749e987
/include/crab/analysis/graphs/sccg.hpp
63157848583e60031966adc31d50b2329ee355b8
[ "Apache-2.0" ]
permissive
numairmansur/crab
5e4e75a37be850cb63686ad51c46baf64c28e210
316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7
refs/heads/master
2020-12-11T08:41:32.929259
2020-01-14T10:19:12
2020-01-14T10:19:12
233,804,159
0
0
NOASSERTION
2020-01-14T09:26:09
2020-01-14T09:26:08
null
UTF-8
C++
false
false
11,274
hpp
#pragma once #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/strong_components.hpp> #include <boost/range/iterator_range.hpp> #include <boost/iterator/transform_iterator.hpp> #include <memory> #include <unordered_map> #include <crab/common/debug.hpp> #include <crab/common/types.hpp> /* Strongly connected component graph */ namespace crab { namespace analyzer { namespace graph_algo { template< typename G> class scc_graph { public: typedef typename G::node_t node_t; private: /// --- begin internal representation of the scc_graph struct vertex_t { std::size_t m_comp; node_t m_repr;}; typedef boost::adjacency_list<boost::setS, //disallow parallel edges boost::vecS, boost::bidirectionalS, boost::property<boost::vertex_color_t, boost::default_color_type, vertex_t> > scc_graph_t; typedef std::shared_ptr<scc_graph_t> scc_graph_ptr; typedef typename boost::graph_traits<scc_graph_t>::vertex_descriptor vertex_descriptor_t; typedef typename boost::graph_traits<scc_graph_t>::edge_descriptor edge_descriptor_t; typedef typename boost::graph_traits<scc_graph_t>::vertex_iterator vertex_iterator; typedef typename boost::graph_traits<scc_graph_t>::out_edge_iterator out_edge_iterator; typedef typename boost::graph_traits<scc_graph_t>::in_edge_iterator in_edge_iterator; /// --- end internal representation of the scc_graph typedef std::unordered_map<node_t, std::size_t> component_map_t; typedef std::unordered_map<std::size_t, vertex_descriptor_t> comp_to_vertex_map_t; typedef std::unordered_map<std::size_t, std::vector<node_t>> comp_members_map_t; // Wrapper for edges // XXX: BGL complains if we use std::pair<edge_t,edge_t> template<typename T> struct Edge { T m_s; T m_d; Edge(){ } Edge(T s, T d): m_s(s), m_d(d) { } T Src() const { return m_s; } T Dest() const { return m_d; } bool operator==(const Edge<T> &o) const { return(m_s == o.Src() && m_d == o.Dest()); } bool operator!=(const Edge<T> &o) const { return !(*this == o); } }; // input graph G m_g; // if true all members in the same SCC are sorted in // pre-order, otherwise post-order. bool m_same_scc_order; // output dag scc_graph_ptr m_sccg; // map each m_g node to a SCC id component_map_t m_comp_map; // map each SCC id to an internal m_sccg's node id comp_to_vertex_map_t m_comp_to_vertex_map; // map each SCC id to a vector of m_g's nodes (its members) comp_members_map_t m_comp_members_map; public: typedef Edge<node_t> edge_t; private: struct MkNode : public std::unary_function< vertex_descriptor_t, node_t > { scc_graph_t* _g; MkNode(): _g(nullptr) { } MkNode(scc_graph_t* g): _g(g) { } node_t& operator()(const vertex_descriptor_t& v) const { return (*_g)[v].m_repr; } }; struct MkEdge : public std::unary_function< edge_descriptor_t, Edge<node_t> > { scc_graph_t *_g; MkEdge(): _g(nullptr) {} MkEdge(scc_graph_t *g): _g(g) { } Edge<node_t> operator()(const edge_descriptor_t& e) const { node_t& s = (*_g) [boost::source(e, *_g)].m_repr; node_t& t =(*_g) [boost::target(e, *_g)].m_repr; return Edge<node_t>(s,t); } }; std::size_t get_comp_id(const node_t&n) const { auto it = m_comp_map.find(n); assert (it != m_comp_map.end()); return it->second; } struct preorder_visitor: public boost::default_dfs_visitor { std::vector<node_t> m_order_vs; void discover_vertex(node_t v, G g) { m_order_vs.push_back(v); } }; struct postorder_visitor: public boost::default_dfs_visitor { std::vector<node_t> m_order_vs; void finish_vertex(node_t v, G g) { m_order_vs.push_back(v); } }; template<typename OrderVis> std::vector<node_t> sort() const { typedef std::unordered_map< node_t, boost::default_color_type > color_map_t; color_map_t color; for (auto v : boost::make_iterator_range(vertices(m_g))) { color[v] = boost::default_color_type(); } boost::associative_property_map< color_map_t > cm(color); // find root node_t root; bool root_found = false; for (auto v: boost::make_iterator_range(vertices(m_g))) { if (in_degree(v, m_g) == 0) { root = v; root_found = true; break; } } OrderVis vis; if (root_found) boost::detail::depth_first_visit_impl(m_g, root, vis, cm, boost::detail::nontruth2()); for (auto u: boost::make_iterator_range(vertices(m_g))) { if (get(cm, u) == boost::default_color_type::white_color) boost::detail::depth_first_visit_impl(m_g, u, vis, cm, boost::detail::nontruth2()); } assert(vis.m_order_vs.size() == num_vertices(m_g)); return vis.m_order_vs; } bool check_comp_map() { // --- Check that all vertices in the graph m_g are keys in // the component map for (auto v: boost::make_iterator_range(vertices(m_g))) { auto it = m_comp_map.find(v); if (it == m_comp_map.end()) return false; } return true; } public: typedef boost::transform_iterator<MkNode, vertex_iterator> node_iterator; typedef boost::transform_iterator<MkEdge, in_edge_iterator> pred_iterator; typedef boost::transform_iterator<MkEdge, out_edge_iterator> succ_iterator; scc_graph(G g, bool order = false /*default post-order*/) : m_g(g), m_same_scc_order(order), m_sccg(std::make_shared<scc_graph_t>()) { CRAB_LOG("sccg", crab::outs() << g << "\n"); typedef std::unordered_map< node_t, node_t > root_map_t; typedef std::unordered_map< node_t, boost::default_color_type > color_map_t; typedef boost::associative_property_map< component_map_t > property_component_map_t; typedef boost::associative_property_map< root_map_t > property_root_map_t; typedef boost::associative_property_map< color_map_t > property_color_map_t; component_map_t discover_time; root_map_t _root_map; color_map_t color_map; for (auto const &v : boost::make_iterator_range (vertices(m_g))) { m_comp_map [v] = 0; color_map [v] = boost::default_color_type(); discover_time [v] = 0; _root_map [v] = node_t(); } boost::strong_components(m_g, property_component_map_t(m_comp_map), root_map(property_root_map_t(_root_map)) .color_map(property_color_map_t(color_map)) .discover_time_map(property_component_map_t(discover_time))); CRAB_LOG("sccg", crab::outs() << "comp map: \n"; for (auto p: m_comp_map) { crab::outs() <<"\t" << p.first << " --> " << p.second << "\n"; }); // build SCC Dag for (auto p : m_comp_map) { auto it = m_comp_to_vertex_map.find(p.second ); if (it != m_comp_to_vertex_map.end()) continue; vertex_descriptor_t v = add_vertex(*m_sccg); (*m_sccg) [v].m_comp = p.second; m_comp_to_vertex_map.insert(std::make_pair(p.second, v)); CRAB_LOG("sccg", crab::outs() << "Added scc graph node " << p.second << "--- id=" << v << "\n";); } for (const node_t &u : boost::make_iterator_range(vertices(m_g))) { for (auto e : boost::make_iterator_range(out_edges(u, m_g))) { const node_t &d = target(e, m_g); if (m_comp_map [u] == m_comp_map [d]) continue; auto res = add_edge(m_comp_to_vertex_map[m_comp_map [u]], m_comp_to_vertex_map[m_comp_map [d]], *m_sccg); if(res.second) CRAB_LOG("sccg", crab::outs() << "Added scc graph edge " << m_comp_map [u] << " --> " << m_comp_map [d] << "\n"); } } assert(check_comp_map()); // Build a map from scc id to their node members for (auto v:(m_same_scc_order ? sort<preorder_visitor>() : sort<postorder_visitor>())) { std::size_t id = m_comp_map [v]; auto it = m_comp_members_map.find(id); if (it != m_comp_members_map.end()) { it->second.push_back(v); } else { std::vector<node_t> comp_mems; comp_mems.push_back(v); m_comp_members_map.insert(std::make_pair(id, comp_mems)); // update the representative in m_sccg // // The representative is similar to the values in the // root_map's entries. However, we found cases where two members // of the same SCC have assigned a different root. I // think this contradicts to what the BOOST doc says but // I didn't have time to figure out the problem so we // choose our own representative. (*m_sccg) [m_comp_to_vertex_map[id]].m_repr = v; } } CRAB_LOG("sccg", crab::outs() << "Built SCC graph \n"; write(crab::outs()); ); } // return the members of the scc component that contains n std::vector<node_t>& get_component_members(const node_t& n) { return m_comp_members_map[m_comp_map [n]]; } std::pair<node_iterator, node_iterator> nodes() const { auto p = boost::vertices(*m_sccg); return std::make_pair(make_transform_iterator(p.first, MkNode(&*m_sccg)), make_transform_iterator(p.second, MkNode(&*m_sccg))); } std::pair<succ_iterator, succ_iterator> succs(const node_t &n) const { auto It = m_comp_to_vertex_map.find(get_comp_id(n)); if (It == m_comp_to_vertex_map.end()) CRAB_ERROR("Sccg could not find node!"); auto p = boost::out_edges(It->second, *m_sccg); return std::make_pair(make_transform_iterator(p.first, MkEdge(&*m_sccg)), make_transform_iterator(p.second, MkEdge(&*m_sccg))); } std::pair<pred_iterator, pred_iterator> preds(const node_t &n) const { auto It = m_comp_to_vertex_map.find(get_comp_id(n)); if (It == m_comp_to_vertex_map.end()) CRAB_ERROR("Sccg could not find node!"); auto p = boost::in_edges(It->second, *m_sccg); return std::make_pair(make_transform_iterator(p.first, MkEdge(&*m_sccg)), make_transform_iterator(p.second, MkEdge(&*m_sccg))); } std::size_t num_nodes() const { return boost::num_vertices(*m_sccg); } std::size_t num_succs(const node_t &n) const { auto It = m_comp_to_vertex_map.find(get_comp_id(n)); if (It == m_comp_to_vertex_map.end()) CRAB_ERROR("Sccg could not find node!"); return boost::out_degree(It->second, *m_sccg); } std::size_t num_preds(const node_t &n) const { auto It = m_comp_to_vertex_map.find(get_comp_id(n)); if (It == m_comp_to_vertex_map.end()) CRAB_ERROR("Sccg could not find node!"); return boost::in_degree(It->second, *m_sccg); } void write(crab_os& o) const { o << "SCCG=\nvertices={"; for (auto v: boost::make_iterator_range(nodes())) o << v << ";"; o << "}\n"; o <<"edges=\n"; for (auto v: boost::make_iterator_range(nodes())){ if (num_succs(v) > 0) { for (auto e: boost::make_iterator_range(succs(v))) { o << e.Src() << "--> " << e.Dest() << "\n"; } } } CRAB_LOG("sccg", o << "Component map: \n"; for(auto p: m_comp_map) { o <<"\t" << p.first << " --> SCC ID " << p.second << "\n"; }); } }; } // end namespace graph_algo } // end namespace analyzer } // end namespace crab
[ "navasjorgea@gmail.com" ]
navasjorgea@gmail.com
505b1ed31475eecc6f11a424a57b116ed9fad060
bbfd75cc3ae72be4bf0203a4cef546d864c669dd
/signal_box.h
58e9448086084d69273798f6e3c7886e17cb53ff
[]
no_license
TakoSquid/blah-thingy
694dda36b75e2f661b8ae479c0c0fe4caba61e11
1e1a104a4234c463c91e7bb0c9ee08aff6d4c4a9
refs/heads/master
2023-05-07T02:12:30.581737
2021-05-30T21:03:56
2021-05-30T21:03:56
363,951,173
0
0
null
null
null
null
UTF-8
C++
false
false
446
h
#pragma once #include <functional> #include <set> #include "world.h" namespace BT { class SignalBox : public Component { public: SignalBox(); void addSignalBox(SignalBox* signal_box); void removeSignalBox(SignalBox* signal_box); void activate(); void debug() override; const Vector<SignalBox*> get_listeners() const; std::function<void(SignalBox* self)> on_signal_action; private: std::set<SignalBox*> signal_boxes; }; }
[ "pierrelouis.hernio@gmail.com" ]
pierrelouis.hernio@gmail.com
ad8aa94d6357c42a3edd1f448cd37888126c1009
d35b065f5ff72c736c7ce4472b8c36bca76b8ad7
/oop/Domain.h
bddd8f7af77d4d5f256d02391330f7fbecd8619b
[]
no_license
vitorvilela/multigrid
292144a5445d15472308e49b10fc19f6c0b39861
a20ffcc99b814646d7dc61a21e3aca93eb6be5c5
refs/heads/master
2020-04-25T16:17:26.096070
2019-02-27T17:53:38
2019-02-27T17:53:38
172,905,687
0
0
null
null
null
null
UTF-8
C++
false
false
333
h
/* Domain.h */ #ifndef Domain_H #define Domain_H class Domain { public: Domain(double W = 0.0, double E = 1.0); void setWest(double); void setEast(double); double getWest() const { return WEST; } double getEast() const { return EAST; } private: double WEST; double EAST; }; #endif
[ "noreply@github.com" ]
vitorvilela.noreply@github.com
6d2893321ef3089543dffcacb8d23a5ab4a27bf9
5843ce7e16ecce5f812fe4e91cff3c815d0b97b7
/portal/Protocols/DHCP.h
d4a7768744c67b69552038a5ad2878ff9c09cafc
[]
no_license
venkatarajasekhar/libportal
f64dc5b20f2aae80fb7264b1c7607b3ef477e213
960cffa2138ee8d26d91455099e5379cfa1412b4
refs/heads/master
2020-06-26T18:19:10.146708
2016-10-31T00:35:51
2016-10-31T00:35:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,359
h
#ifndef DHCP_H_ #define DHCP_H_ #include "../Layer.h" #include "RawLayer.h" #include "DHCPOptions.h" namespace Portal { class DHCP: public Layer { void DefineProtocol(); Constructor GetConstructor() const { return DHCP::DHCPConstFunc; }; static Layer* DHCPConstFunc() { return new DHCP; }; void Portal(); void ReDefineActiveFields(); void ParseLayerData(ParseInfo* info); static const byte FieldOperationCode = 0; static const byte FieldHardwareType = 1; static const byte FieldHardwareLength = 2; static const byte FieldHopCount = 3; static const byte FieldTransactionID = 4; static const byte FieldNumberOfSeconds = 5; static const byte FieldFlags = 6; static const byte FieldClientIP = 7; static const byte FieldYourIP = 8; static const byte FieldServerIP = 9; static const byte FieldGatewayIP = 10; static const byte FieldClientMAC = 11; static const byte FieldZeroPadding = 12; static const byte FieldServerHostName = 13; static const byte FieldBootFile = 14; void PrintPayload(std::ostream& str) const; public: /* Some constant of the DHCP protocol */ static const byte Request; static const byte Reply; enum { PROTO = 0xfff4 }; DHCP(); DHCP(const DHCP& dhcp) : Layer(dhcp) { /* Copy the Options */ std::vector<DHCPOptions*>::const_iterator it_opt; for(it_opt = dhcp.Options.begin() ; it_opt != dhcp.Options.end() ; it_opt++) this->Options.push_back((*it_opt)->Clone()); }; /* Assignment operator of this class */ DHCP& operator=(const DHCP& right) { /* Copy the Options */ std::vector<DHCPOptions*>::const_iterator it_opt; /* Delete the current options */ for(it_opt = Options.begin() ; it_opt != Options.end() ; it_opt++) delete (*it_opt); /* And copy the new ones */ for(it_opt = right.Options.begin() ; it_opt != right.Options.end() ; it_opt++) this->Options.push_back((*it_opt)->Clone()); /* Call the assignment operator of the base class */ Layer::operator=(right); /* Return */ return *this; } Layer& operator=(const Layer& right) { /* Sanity check */ if (GetName() != right.GetName()) throw std::runtime_error("Cannot convert " + right.GetName() + " to " + GetName()); const DHCP* right_ptr = dynamic_cast< const DHCP* >(&right); DHCP::operator=(*right_ptr); /* Call the assignment operator of the base class */ Layer::operator=(right); /* Return */ return *this; } void SetOperationCode(const byte& value) { SetFieldValue(FieldOperationCode,value); }; void SetHardwareType(const byte& value) { SetFieldValue(FieldHardwareType,value); }; void SetHardwareLength(const byte& value) { SetFieldValue(FieldHardwareLength,value); }; void SetHopCount(const byte& value) { SetFieldValue(FieldHopCount,value); }; void SetTransactionID(const word& value) { SetFieldValue(FieldTransactionID,value); }; void SetNumberOfSeconds(const short_word& value) { SetFieldValue(FieldNumberOfSeconds,value); }; void SetFlags(const short_word& value) { SetFieldValue(FieldFlags,value); }; void SetClientIP(const std::string& value) { SetFieldValue(FieldClientIP,value); }; void SetYourIP(const std::string& value) { SetFieldValue(FieldYourIP,value); }; void SetServerIP(const std::string& value) { SetFieldValue(FieldServerIP,value); }; void SetGatewayIP(const std::string& value) { SetFieldValue(FieldGatewayIP,value); }; void SetClientMAC(const std::string& value) { SetFieldValue(FieldClientMAC,value); }; void SetZeroPadding(const std::vector<byte> & value) { SetFieldValue(FieldZeroPadding,value); }; void SetServerHostName(const std::string& value) { SetFieldValue(FieldServerHostName,value); }; void SetBootFile(const std::string& value) { SetFieldValue(FieldBootFile,value); }; byte GetOperationCode() const { return GetFieldValue<byte>(FieldOperationCode); }; byte GetHardwareType() const { return GetFieldValue<byte>(FieldHardwareType); }; byte GetHardwareLength() const { return GetFieldValue<byte>(FieldHardwareLength); }; byte GetHopCount() const { return GetFieldValue<byte>(FieldHopCount); }; word GetTransactionID() const { return GetFieldValue<word>(FieldTransactionID); }; short_word GetNumberOfSeconds() const { return GetFieldValue<short_word>(FieldNumberOfSeconds); }; short_word GetFlags() const { return GetFieldValue<short_word>(FieldFlags); }; std::string GetClientIP() const { return GetFieldValue<std::string>(FieldClientIP); }; std::string GetYourIP() const { return GetFieldValue<std::string>(FieldYourIP); }; std::string GetServerIP() const { return GetFieldValue<std::string>(FieldServerIP); }; std::string GetGatewayIP() const { return GetFieldValue<std::string>(FieldGatewayIP); }; std::string GetClientMAC() const { return GetFieldValue<std::string>(FieldClientMAC); }; std::vector<byte> GetZeroPadding() const { return GetFieldValue<std::vector<byte> >(FieldZeroPadding); }; std::string GetServerHostName() const { return GetFieldValue<std::string>(FieldServerHostName); }; std::string GetBootFile() const { return GetFieldValue<std::string>(FieldBootFile); }; /* DHCP Options */ std::vector<DHCPOptions*> Options; /* Set the field values from data of a Raw Layer */ void FromRaw(const RawLayer& raw_layer); ~DHCP() { /* Destructor */ }; }; } #endif /* DHCP_H_ */
[ "snrhcn@d.local" ]
snrhcn@d.local
bcaa83a7f4c8c5d199eb6cc6130091251f4e1798
de1644ee4099a698e7f3d86f46c789fdf66d0a4d
/UnitTests/FoundationTest/Basics/Types/BitflagsTest.cpp
3871b2d2fdc6ff21fc0c83964055e7df47bfc729
[ "CC-BY-3.0" ]
permissive
eltld/ezEngine
5cbe56c0f033763e1c9478c39e5979ac01430ec6
3230235249dd2769f166872b753efd6bd8347c98
refs/heads/master
2021-01-12T13:22:24.959311
2016-03-28T20:41:35
2016-03-28T20:41:35
72,212,613
0
1
null
2016-10-28T14:05:10
2016-10-28T14:05:10
null
UTF-8
C++
false
false
2,167
cpp
#include <PCH.h> namespace { // declare bitflags using macro magic EZ_DECLARE_FLAGS(ezUInt32, AutoFlags, Bit1, Bit2, Bit3, Bit4); // declare bitflags manually struct ManualFlags { typedef ezUInt32 StorageType; enum Enum { Bit1 = EZ_BIT(0), Bit2 = EZ_BIT(1), Bit3 = EZ_BIT(2), Bit4 = EZ_BIT(3), Default = Bit1 | Bit2 }; struct Bits { StorageType Bit1 : 1; StorageType Bit2 : 1; StorageType Bit3 : 1; StorageType Bit4 : 1; }; }; EZ_DECLARE_FLAGS_OPERATORS(ManualFlags); } EZ_CHECK_AT_COMPILETIME(sizeof(ezBitflags<AutoFlags>) == 4); EZ_CREATE_SIMPLE_TEST(Basics, Bitflags) { EZ_TEST_BOOL(AutoFlags::Count == 4); ezBitflags<AutoFlags> flags = AutoFlags::Bit1 | AutoFlags::Bit4; EZ_TEST_BOOL(flags.IsSet(AutoFlags::Bit4)); EZ_TEST_BOOL(flags.AreAllSet(AutoFlags::Bit1 | AutoFlags::Bit4)); EZ_TEST_BOOL(flags.IsAnySet(AutoFlags::Bit1 | AutoFlags::Bit2)); flags.Add(AutoFlags::Bit3); EZ_TEST_BOOL(flags.IsSet(AutoFlags::Bit3)); flags.Remove(AutoFlags::Bit1); EZ_TEST_BOOL(!flags.IsSet(AutoFlags::Bit1)); flags.Toggle(AutoFlags::Bit4); EZ_TEST_BOOL(flags.AreAllSet(AutoFlags::Bit3)); flags.AddOrRemove(AutoFlags::Bit2, true); flags.AddOrRemove(AutoFlags::Bit3, false); EZ_TEST_BOOL(flags.AreAllSet(AutoFlags::Bit2)); flags.Add(AutoFlags::Bit1); ezBitflags<ManualFlags> manualFlags = ManualFlags::Default; EZ_TEST_BOOL(manualFlags.AreAllSet(ManualFlags::Bit1 | ManualFlags::Bit2)); EZ_TEST_BOOL(manualFlags.GetValue() == flags.GetValue()); ezBitflags<AutoFlags> flags2 = AutoFlags::Bit1 & AutoFlags::Bit4; EZ_TEST_BOOL(flags2.GetValue() == 0); EZ_TEST_BLOCK(ezTestBlock::Enabled, "operator|=") { ezBitflags<AutoFlags> f = AutoFlags::Bit1 | AutoFlags::Bit2; f |= AutoFlags::Bit3; EZ_TEST_BOOL(f.GetValue() == (AutoFlags::Bit1 | AutoFlags::Bit2 | AutoFlags::Bit3).GetValue()); } EZ_TEST_BLOCK(ezTestBlock::Enabled, "operator&=") { ezBitflags<AutoFlags> f = AutoFlags::Bit1 | AutoFlags::Bit2 | AutoFlags::Bit3; f &= AutoFlags::Bit3; EZ_TEST_BOOL(f.GetValue() == AutoFlags::Bit3); } }
[ "jan@krassnigg.de" ]
jan@krassnigg.de
b4e185ccd3194e63837831902a4e0fab33e3e5a1
7d1bbcfc89bcc60614a2a2338e74d8b0fa48669f
/leetcode/math/263_ugly_number.cpp
3c406afa9339cf3d9a2d62fb3b01f2092c4d8478
[]
no_license
Nana0606/basic-algorithms
3dcfb6554fe28fb8ea007c76e2e0b1aac9012035
f78317a934d945c1f468c28a7fc65d1560fc880f
refs/heads/master
2020-03-23T20:09:21.548501
2019-05-27T01:47:29
2019-05-27T01:47:29
142,024,882
1
0
null
null
null
null
UTF-8
C++
false
false
433
cpp
# include <iostream> using namespace std; bool isUgly(int num) { if (num <= 0) return false; if (num == 1) return true; while (num != 1){ if (num % 2 == 0){ num /= 2; } else if (num % 3 == 0){ num /= 3; } else if (num % 5 == 0){ num /= 5; } else{ return false; } } return true; } int main(){ int n = 14; bool result = isUgly(n); cout << result << endl; return 0; }
[ "“paopaotanglee@126.com”" ]
“paopaotanglee@126.com”
17e9cd11e18b64bbc72ed94357bdb7d38bfb9bf3
b35c4dde7e55c03517375d31814c53206a2d5249
/src/GpuBuffer.hpp
3ffc3d05f96938b706d3c4187018700f6aadd5bf
[ "MIT" ]
permissive
ronsaldo/radiosity_test
74e90a22e594c44a0c279ac274c6696ebe20c3c0
d66a6c1106929f03b5ca9e035449fa4de23f79cc
refs/heads/master
2021-01-19T09:49:11.833157
2017-04-10T15:02:18
2017-04-10T15:02:18
87,789,633
1
0
null
null
null
null
UTF-8
C++
false
false
1,029
hpp
#ifndef RADIOSITY_TEST_GPU_BUFFER_HPP #define RADIOSITY_TEST_GPU_BUFFER_HPP #include "Object.hpp" #include "GLCommon.hpp" namespace RadiosityTest { DECLARE_CLASS(GpuBuffer); /** * The allowable mapping usages. */ enum class GpuBufferMapAccess { ReadOnly = 0, WriteOnly, ReadWrite }; /** * I represent a buffer that resides in GPU accessible memory. */ class GpuBuffer: public Object { public: GpuBuffer(); ~GpuBuffer(); GLenum getHandle() const { return handle; } void setPersistentStorage(size_t capacity, GpuBufferMapAccess newMappingAccess); void setUploadedStorage(size_t capacity); void setImmutableContent(size_t size, const void *content); size_t getCapacity() const { return capacity; } void *map(); void unmap(); private: GLuint handle; size_t capacity; void *mappedPointer; size_t mapCount; GpuBufferMapAccess mappingAccess; }; } // End of namespace RadiosityTest #endif //RADIOSITY_TEST_GPU_BUFFER_HPP
[ "roniesalg@gmail.com" ]
roniesalg@gmail.com
bc7fb12c8226d98ad0664db113ec5af586d1c532
be6a9fe5190e9d589fb5a93e1f41f1a0c4f2385c
/bezier.cpp
73193b465ea98bb09cf08cc21c7e4b94f24ee82d
[]
no_license
joseuishuisaq/grafica
42b87c1bfb264a3991213e6b5ef6ebd45995594e
768f3e68decb57fc6256df2112a7fd0775ea40aa
refs/heads/master
2020-11-27T08:47:40.313155
2019-12-21T05:25:34
2019-12-21T05:25:34
229,375,427
0
0
null
null
null
null
UTF-8
C++
false
false
3,117
cpp
#include <iostream> #include <stdlib.h> #include <GL/glut.h> #include <math.h> using namespace std; class Punto { public: float x, y; void setxy(float x2, float y2) { x = x2; y = y2; } //operator overloading for '=' sign const Punto & operator=(const Punto &rPunto) { x = rPunto.x; y = rPunto.y; return *this; } }; int factorial(int n) { if (n<=1) return(1); else n=n*factorial(n-1); return n; } float binomial_coff(float n,float k) { float ans; ans = factorial(n) / (factorial(k)*factorial(n-k)); return ans; } Punto abc[20]; int SCREEN_HEIGHT = 500; int Puntos = 0; int clicks = 4; void myInit() { glClearColor(1.0,1.0,1.0,0.0); glColor3f(0.0,0.0,0.0); glPuntoSize(3); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0,640.0,0.0,500.0); } void punto(int x, int y) { glBegin(GL_PuntoS); glVertex2i(x,y); glEnd(); glFlush(); } void linea(Punto p1, Punto p2) { glBegin(GL_LINES); glVertex2f(p1.x, p1.y); glVertex2f(p2.x, p2.y); glEnd(); glFlush(); } Punto drawBezier(Punto PT[], double t) { Punto P; P.x = pow((1 - t), 3) * PT[0].x + 3 * t * pow((1 -t), 2) * PT[1].x + 3 * (1-t) * pow(t, 2)* PT[2].x + pow (t, 3)* PT[3].x; P.y = pow((1 - t), 3) * PT[0].y + 3 * t * pow((1 -t), 2) * PT[1].y + 3 * (1-t) * pow(t, 2)* PT[2].y + pow (t, 3)* PT[3].y; return P; } Punto drawBezierGeneralized(Punto PT[], double t) { Punto P; P.x = 0; P.y = 0; for (int i = 0; i<clicks; i++) { P.x = P.x + binomial_coff((float)(clicks - 1), (float)i) * pow(t, (double)i) * pow((1 - t), (clicks - 1 - i)) * PT[i].x; P.y = P.y + binomial_coff((float)(clicks - 1), (float)i) * pow(t, (double)i) * pow((1 - t), (clicks - 1 - i)) * PT[i].y; } //cout<<P.x<<endl<<P.y; //cout<<endl<<endl; return P; } void myMouse(int button, int state, int x, int y) { if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { abc[Puntos].setxy((float)x,(float)(SCREEN_HEIGHT - y)); Puntos++; punto(x, SCREEN_HEIGHT - y); if(Puntos == clicks) { glColor3f(0.2,1.0,0.0); for(int k=0;k<clicks-1;k++) linea(abc[k], abc[k+1]); Punto p1 = abc[0]; for(double t = 0.0;t <= 1.0; t += 0.02) { Punto p2 = drawBezierGeneralized(abc,t); cout<<p1.x<<" , "<<p1.y<<endl; cout<<p2.x<<" , "<<p2.y<<endl; cout<<endl; linea(p1, p2); p1 = p2; } glColor3f(0.0,0.0,0.0); Puntos = 0; } } } void myDisplay() { glClear(GL_COLOR_BUFFER_BIT); glFlush(); } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(640,500); glutInitWindowPosition(100,150); glutCreateWindow("Bezier Curve"); glutMouseFunc(myMouse); glutDisplayFunc(myDisplay); myInit(); glutMainLoop(); return 0; }
[ "noreply@github.com" ]
joseuishuisaq.noreply@github.com
b3b2df3560630a59f23cc21afb68a81d36516bd2
d7c77018b0c5e7d1e6e24d82fa905a1ac5b0a85e
/PbInfo/cifrecomune.cpp
1607a0ebdcdfac79c27e1ed5f72dd709f334e98f
[]
no_license
muresangabriel-alexander/cplusplus-competitive
9396cff60c6be0f5ae3d307f58e350423e336764
4a17656ccbea58d779bf5bd74aed5edb9c579ca6
refs/heads/master
2021-04-28T07:57:22.419138
2018-02-20T18:42:59
2018-02-20T18:42:59
122,238,407
1
0
null
null
null
null
UTF-8
C++
false
false
225
cpp
#include <iostream> #include <cmath> using namespace std; int main() { int a,b; cin>>a>>b; if(a%10==b%10 || a/10==b/10 || a/10==b%10 || a%10==b/10)cout<<"da"; else cout<<"nu"; return 0; }
[ "muresangabriel.alexandru@gmail.com" ]
muresangabriel.alexandru@gmail.com
5ea30deaf07180daef7385c1e4e8a5eeb3087862
086c69827926fd7f51a763f9479fc45bb244b11b
/timemachine/cpp/src/context.hpp
861f0056a786bee60d8c4d7be2b9a2c2755f7b0e
[ "Apache-2.0" ]
permissive
lgsmith/timemachine
6966fe5d9f5f897f1776e6d062596ae0940069ae
a2f0450eaaa7b7bf2109e449b94d7ce0d930ed6a
refs/heads/master
2020-06-18T21:05:16.606914
2019-07-08T19:05:06
2019-07-08T19:05:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,776
hpp
#pragma once #include <vector> #include "optimizer.hpp" #include "potential.hpp" namespace timemachine { // a context is a triple of <System, State, Parameters> // the context does take ownership of any of the input arguments // this is meant to be one-shot. You are not allowed to set any internals // once this context has been initialized. This is for safety and ensuring // that the internal derivatives are kept in sync. template <typename RealType> class Context { private: const std::vector<Potential<RealType>*> system_; const Optimizer<RealType> *optimizer_; RealType *d_params_; // these are really immutable int *d_gather_param_idxs_; // these are really immutable RealType *d_x_t_; RealType *d_v_t_; RealType *d_dx_dp_t_; RealType *d_dv_dp_t_; RealType *d_E_; RealType *d_dE_dx_; RealType *d_dE_dp_; RealType *d_d2E_dx2_; RealType *d_d2E_dxdp_; int step_; int N_; int P_; int DP_; public: Context( const std::vector<Potential<RealType>* > system, const Optimizer<RealType> *optimizer, const RealType *h_params, const RealType *h_x0, const RealType *h_v0, const int N, const int P, const int *h_param_gather_idxs, const int DP); int num_atoms() const { return N_; }; int num_params() const { return P_; }; int num_dparams() const { return DP_; }; void step(); void get_E(RealType *buffer) const; void get_dE_dx(RealType *buffer) const; void get_dE_dp(RealType *buffer) const; void get_x(RealType *buffer) const; void get_v(RealType *buffer) const; void get_dx_dp(RealType *buffer) const; void get_dv_dp(RealType *buffer) const; ~Context(); }; }
[ "proteneer@gmail.com" ]
proteneer@gmail.com
631ee062b9ebed4544bb42bbf36c06ae772085b4
31cae2a7831b352fafe6b5b831619a6cbe22ad7e
/src/JSON/JSONObject.hh
892c060051837969d3d20c570b0653b8c51b00f3
[]
no_license
Antonito/cpp_gkrellm
b2cfb09575cef3cae28c610d804eaa1f4c8c8df3
fc57c9433a8dfe0215ff833170ca845ba0cbbcdf
refs/heads/master
2021-05-01T05:36:29.378495
2017-01-23T00:57:14
2017-01-23T00:57:14
79,757,457
1
0
null
null
null
null
UTF-8
C++
false
false
615
hh
#ifndef JSONOBJECT_HH_ #define JSONOBJECT_HH_ #include <map> #include <string> #include "JSONIElement.hh" namespace JSON { class Object : public IElement { public: Object(); virtual ~Object(); virtual std::string str(std::string const &c = "\"") const; virtual IElement &operator[](size_t index); virtual IElement &operator[](std::string const &prop); void addProperty(std::string const &prop, IElement *elem); void removeProperty(std::string const &prop); size_t size() const; private: std::map<std::string, IElement *> m_properties; }; } #endif // !JSONOBJECT_HH_
[ "ludovic.petrenko@epitech.eu" ]
ludovic.petrenko@epitech.eu
e861005fe948e006085621ef8fdb02c620a7b99c
af41d261aca676f6394f5144c07a54163dc2f8d6
/test/blackbox/rpcdds_fastrtps/Inheritance/InheritanceServerExample.cxx
eae2b309cd86c98f353340154b5895a84cd8b6f4
[ "Apache-2.0" ]
permissive
eProsima/RPC
8db60788dc11581a537d3a0b0d618712149b6f02
85274fa21290c5382044904d459afd17b38ebca7
refs/heads/master
2023-06-15T02:11:52.032899
2022-05-23T10:16:33
2022-05-23T10:16:33
23,354,606
55
32
Apache-2.0
2023-06-05T13:45:12
2014-08-26T14:29:12
C++
UTF-8
C++
false
false
2,493
cxx
/************************************************************************* * Copyright (c) 2013 eProsima. All rights reserved. * * This generated file is licensed to you under the terms described in the * fastrpc_LICENSE file included in this fastrpc distribution. * ************************************************************************* * * @file InheritanceServerExample.cxx * This source file shows a simple example of how to create a server for an interface. * * This file was generated by the tool fastrpcgen. */ #include "InheritanceServer.h" #include <strategies/ThreadPoolStrategy.h> #include "InheritanceDDSProtocol.h" #include <transports/dds/RTPSServerTransport.h> #include <exceptions/Exceptions.h> #include <utils/Utilities.h> #include "InheritanceServerImplExample.h" #include <iostream> using namespace eprosima::rpc; using namespace ::exception; using namespace ::strategy; using namespace ::transport::dds; using namespace ::protocol::dds; int main(int argc, char **argv) { unsigned int threadPoolSize = 5; ThreadPoolStrategy *pool = NULL; InheritanceProtocol *protocol = NULL; RTPSServerTransport *transport = NULL; ModuleA::Interface1Server *server1 = NULL; ModuleA::Interface2Server *server2 = NULL; ModuleB::Interface3Server *server3 = NULL; Interface1ServerImplExample servant1; Interface2ServerImplExample servant2; Interface3ServerImplExample servant3; // Create and initialize the server for interface "ModuleB::Interface3". try { pool = new ThreadPoolStrategy(threadPoolSize); protocol = new InheritanceProtocol(); transport = new RTPSServerTransport("InheritanceService", "Instance"); server1 = new ModuleA::Interface1Server(*pool, *transport, *protocol, servant1); server2 = new ModuleA::Interface2Server(*pool, *transport, *protocol, servant2); server3 = new ModuleB::Interface3Server(*pool, *transport, *protocol, servant3); server1->serve(); server2->serve(); server3->serve(); } catch(InitializeException &ex) { std::cout << ex.what() << std::endl; return -1; } while(1) { eprosima::rpc::sleep(10000); } // Stop and delete the server. server1->stop(); server2->stop(); server3->stop(); delete server1; delete server2; delete server3; delete protocol; delete transport; delete pool; return 0; }
[ "RicardoGonzalez@eprosima.com" ]
RicardoGonzalez@eprosima.com
a284843091048c0af541ff72628862b5b4e6f1dc
a2bc4234280b841a1a990328f86473a819413726
/cpp05/ex00/Bureaucrat.cpp
dbb8c9aed5ee52a0213041fff5de5677a2464e46
[]
no_license
rhc716/cpp_module
9861f34aa06963e3d3a552279ae106203bb459de
ff2ddb13267a16cea8ebfb3c519575d143565008
refs/heads/master
2023-04-09T17:49:44.739682
2021-04-15T11:53:55
2021-04-15T11:53:55
350,720,402
0
0
null
null
null
null
UTF-8
C++
false
false
2,520
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Bureaucrat.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hroh <hroh@student.42seoul.kr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/05 15:34:29 by hroh #+# #+# */ /* Updated: 2021/04/05 18:56:26 by hroh ### ########.fr */ /* */ /* ************************************************************************** */ #include "Bureaucrat.hpp" Bureaucrat::Bureaucrat(std::string const &name, int grade) { if (grade < 1) throw Bureaucrat::GradeTooHighException(); else if (grade > 150) throw Bureaucrat::GradeTooLowException(); this->name = name; this->grade = grade; } Bureaucrat::Bureaucrat(Bureaucrat const &old_obj) { if (old_obj.grade < 1) throw Bureaucrat::GradeTooHighException(); else if (old_obj.grade > 150) throw Bureaucrat::GradeTooLowException(); this->name = old_obj.name; this->grade = old_obj.grade; } Bureaucrat::~Bureaucrat() { } Bureaucrat &Bureaucrat::operator=(Bureaucrat const &old_obj) { if (old_obj.grade < 1) throw Bureaucrat::GradeTooHighException(); else if (old_obj.grade > 150) throw Bureaucrat::GradeTooLowException(); this->name = old_obj.name; this->grade = old_obj.grade; return (*this); } std::string const &Bureaucrat::getName() const { return (this->name); } int Bureaucrat::getGrade() const { return (this->grade); } void Bureaucrat::increase_grade() { if (this->grade - 1 < 1) throw Bureaucrat::GradeTooHighException(); else this->grade--; } void Bureaucrat::decrease_grade() { if (this->grade + 1 > 150) throw Bureaucrat::GradeTooLowException(); else this->grade++; } std::ostream &operator<<(std::ostream &out, Bureaucrat const &obj) { out << "<" << obj.getName() << ">, bureaucrat grade <" << obj.getGrade() << ">" << std::endl; return (out); } const char* Bureaucrat::GradeTooHighException::what() const throw() { return ("Grade is Too High"); } const char* Bureaucrat::GradeTooLowException::what() const throw() { return ("Grade is Too Low"); }
[ "jack716@naver.com" ]
jack716@naver.com
a6f7d13f85e306e0e56b2add9c9fdb049d9f2505
0a884ca9a0134979666e4d3352bda5432098aed2
/src/components/model.hpp
dced628127916ed46426898d10d173c7568bee24
[ "MIT" ]
permissive
mattvchandler/mazerun
f78e6d6610c0bc9722e064843492464a28675672
2aa9a5766973993c2a83061d3a004691c2b07c09
refs/heads/master
2020-04-09T18:03:48.159643
2019-06-18T19:42:12
2019-06-18T19:42:12
24,897,424
1
0
null
null
null
null
UTF-8
C++
false
false
2,485
hpp
// model.hpp // imported model component // Copyright 2015 Matthew Chandler // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef MODEL_HPP #define MODEL_HPP #include <functional> #include <string> #include <unordered_map> #include <SFML/System.hpp> #include "components/component.hpp" #include "components/material.hpp" #include "opengl/gl_wrappers.hpp" class Model: public Component, public sf::NonCopyable { public: virtual ~Model(); static Model * create(const std::string & filename, const bool casts_shadow); virtual void draw(const std::function<void(const Material &)> & set_material) const; bool casts_shadow = true; protected: struct Mesh { GLsizei count = 0; std::size_t index = 0; GLint base_vert = 0; const Material * mat; }; Model(const bool casts_shadow); Model(const std::string & filename, const bool casts_shadow); GL_vertex_array _vao; GL_buffer _vbo; GL_buffer _ebo; std::vector<Mesh> _meshes; std::vector<Material> _mats; std::string _key; }; struct Model_cache { std::unordered_map<std::string, std::unique_ptr<Model>> mdl_index; }; class Model_cache_locator { public: Model_cache_locator() = delete; ~Model_cache_locator() = delete; static void init(Model_cache * cache); static Model_cache & get(); private: static Model_cache _default_model_cache; static Model_cache * _cache; }; #endif // MODEL_HPP
[ "tardarsauce@gmail.com" ]
tardarsauce@gmail.com
80c6087cb0beb63b86c0899abcf641e2787b31ee
b73b4cffebc5499b233e65552bec88fae172550d
/uva10284.cpp
888bc5bd89738e8b58cb11155d1b8a8c960f7d34
[]
no_license
yunomeow/UVaPractice
f01bbb20da270b17a27e4e52314683b5860c4532
1139ce17195c4bef810a261fee4cc454815d9c01
refs/heads/master
2020-03-27T23:54:12.642666
2018-09-04T14:58:06
2018-09-04T14:58:06
147,356,848
0
0
null
null
null
null
UTF-8
C++
false
false
3,354
cpp
#include <iostream> #include <cctype> using namespace std; int use[10][10]; char MAP[10][10]; int dir[16][2] = {1,0 ,0,1 ,-1,0 ,0,-1, 1,1,1,-1 ,-1,-1 ,-1,1, 1,2 ,-1,2 ,1,-2 ,-1,-2, 2,1 ,-2,1 ,2,-1 ,-2,-1 }; int ok(int x,int y){ if(x >= 0 && y >= 0 && x < 8 && y < 8)return 1; return 0; } void print(){ for(int i=0;i<8;i++){ for(int j=0;j<8;j++){ cout << use[i][j]; } cout <<"\n"; } cout <<"\n"; } void move(int x,int y){ int nx,ny; if(MAP[x][y] == 0)return; use[x][y] = 1; if(MAP[x][y] == 'k' || MAP[x][y] == 'K'){ for(int i=0;i<8;i++){ nx = x + dir[i][0]; ny = y + dir[i][1]; if(ok(nx,ny))use[nx][ny] = 1; } }else if(MAP[x][y] == 'r' || MAP[x][y] == 'R'){ for(int i=0;i<4;i++){ nx = x + dir[i][0]; ny = y + dir[i][1]; while(ok(nx,ny) && MAP[nx][ny] == 0){ use[nx][ny] = 1; nx = nx + dir[i][0]; ny = ny + dir[i][1]; } } }else if(MAP[x][y] == 'n' || MAP[x][y] == 'N'){ for(int i=8;i<16;i++){ nx = x + dir[i][0]; ny = y + dir[i][1]; if(ok(nx,ny))use[nx][ny] = 1; } }else if(MAP[x][y] == 'b' || MAP[x][y] == 'B'){ for(int i=4;i<8;i++){ nx = x + dir[i][0]; ny = y + dir[i][1]; while(ok(nx,ny) && MAP[nx][ny] == 0){ use[nx][ny] = 1; nx = nx + dir[i][0]; ny = ny + dir[i][1]; } } }else if(MAP[x][y] == 'q' || MAP[x][y] == 'Q'){ for(int i=0;i<8;i++){ nx = x + dir[i][0]; ny = y + dir[i][1]; while(ok(nx,ny) && MAP[nx][ny] == 0){ use[nx][ny] = 1; nx = nx + dir[i][0]; ny = ny + dir[i][1]; } } }else if(MAP[x][y] == 'p'){ nx = x + dir[4][0]; ny = y + dir[4][1]; //cout << "nx : " << nx << " ny: " << ny << "\n"; if(ok(nx,ny))use[nx][ny] = 1; nx = x + dir[5][0]; ny = y + dir[5][1]; //cout << "nx : " << nx << " ny: " << ny << "\n"; if(ok(nx,ny))use[nx][ny] = 1; }else if(MAP[x][y] == 'P'){ nx = x + dir[6][0]; ny = y + dir[6][1]; if(ok(nx,ny))use[nx][ny] = 1; nx = x + dir[7][0]; ny = y + dir[7][1]; if(ok(nx,ny))use[nx][ny] = 1; } // cout << "x: " << x << " y: " << y << " "<< MAP[x][y]<<"\n"; // print(); } int main (){ string str; while(cin >> str){ int x=0,y=0; fill(&use[0][0],&use[9][0],0); fill(&MAP[0][0],&MAP[9][0],0); for(int i=0;i<str.size();i++){ if(str[i] == '/')continue; if(isdigit(str[i])){ y+=str[i]-'0'; }else{ MAP[x][y] = str[i]; y++; } if(y == 8){ x++; y = 0; } } for(int i=0;i<8;i++){ for(int j=0;j<8;j++){ move(i,j); } } int ans = 0; for(int i=0;i<8;i++){ for(int j=0;j<8;j++){ if(use[i][j] == 0)ans++; } } cout << ans << "\n"; } return 0; }
[ "yunomeow.jp@gmail.com" ]
yunomeow.jp@gmail.com
b98666e60ec698ff265e458c6f9421eb2cf0c35e
4e8548ed98d96146297393e623cb38fbcc77371b
/dbcon/dmlpackage/dmlobject.cpp
66041825b87ec84c699dd0a3297836eb6060675e
[]
no_license
hans511002/erydb_rep
9d5a0be919e5d026e921c7fbe000dc70dc7d7ab6
a2c391b3c36745cb690ce33a22d8794371493ef2
refs/heads/master
2021-01-15T12:02:01.093382
2018-08-09T10:57:26
2018-08-09T10:57:26
99,639,427
0
0
null
null
null
null
UTF-8
C++
false
false
1,054
cpp
/* Copyright (C) 2014 EryDB, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /*********************************************************************** * $Id: dmlobject.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * * ***********************************************************************/ #include "dmlobject.h" namespace dmlpackage { DMLObject::DMLObject() { } DMLObject::~DMLObject() { } } // namespace dmlpackage
[ "hans511002@sohu.com" ]
hans511002@sohu.com
057df0277e08378dc6c55d4eb5d25c588106ca6e
d1aceae1db7554c376acb027854109c61edc3b9e
/cpp/src/examples/ucx_join_example.cpp
12c2ee8c84ef825f8194c4c0734fc66bb7627103
[ "Apache-2.0" ]
permissive
emg110/cylon
64bfe73615b6c7445853601ab9fd6d2f4cb61958
8ab8b2d6f3e087d5e5d666f8606e1c08df2fc4c4
refs/heads/main
2023-07-22T17:50:09.710118
2021-09-11T12:52:41
2021-09-11T12:52:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,851
cpp
/* * 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 <glog/logging.h> #include <chrono> #include <cylon/net/ucx/ucx_communicator.hpp> #include <cylon/ctx/cylon_context.hpp> #include <cylon/table.hpp> int main(int argc, char *argv[]) { if (argc < 3) { LOG(ERROR) << "There should be two arguments with paths to csv files"; return 1; } auto start_start = std::chrono::steady_clock::now(); auto mpi_config = std::make_shared<cylon::net::UCXConfig>(); auto ctx = cylon::CylonContext::InitDistributed(mpi_config); std::shared_ptr<cylon::Table> first_table, second_table, joined; auto read_options = cylon::io::config::CSVReadOptions().UseThreads(false).BlockSize(1 << 30); auto status = cylon::FromCSV(ctx, argv[1], first_table, read_options); if (!status.is_ok()) { LOG(INFO) << "Table reading failed " << argv[1]; ctx->Finalize(); return 1; } status = cylon::FromCSV(ctx, argv[2], second_table, read_options); if (!status.is_ok()) { LOG(INFO) << "Table reading failed " << argv[2]; ctx->Finalize(); return 1; } auto read_end_time = std::chrono::steady_clock::now(); LOG(INFO) << "Read tables in " << std::chrono::duration_cast<std::chrono::milliseconds>( read_end_time - start_start).count() << "[ms]"; auto join_config = cylon::join::config::JoinConfig(cylon::join::config::JoinType::INNER, {0, 1}, {0, 1}, cylon::join::config::JoinAlgorithm::SORT, "l_", "r_"); status = cylon::DistributedJoin(first_table, second_table, join_config, joined); if (!status.is_ok()) { LOG(INFO) << "Table join failed "; ctx->Finalize(); return 1; } auto join_end_time = std::chrono::steady_clock::now(); LOG(INFO) << "First table had : " << first_table->Rows() << " and Second table had : " << second_table->Rows() << ", Joined has : " << joined->Rows(); LOG(INFO) << "Join done in " << std::chrono::duration_cast<std::chrono::milliseconds>( join_end_time - read_end_time).count() << "[ms]"; ctx->Finalize(); return 0; }
[ "noreply@github.com" ]
emg110.noreply@github.com
c7b1c44f318fc6b76c38cdcfb3ae9403d9063289
7ca865d5c1fedc22c02f2ae59dcdf18f0fa521b7
/src/IL_infomat_twin_misconly.cpp
cd3de99bd4a707f8fe4e8fde0ca764c780a22fbb
[]
no_license
QihuangZhang/GeneErrorMis
c8b7ce0693a105d0c81ea0b547a9f49b92c53793
a6389642ead11efe5b662a10bbc85d9efcbed99e
refs/heads/master
2021-07-09T19:07:54.903820
2021-03-20T03:26:55
2021-03-20T03:26:55
236,824,708
1
0
null
null
null
null
UTF-8
C++
false
false
7,221
cpp
# include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericMatrix IL_infomat_twin_misconly(NumericVector w, NumericVector v, NumericVector Y1star, NumericVector Y2star, NumericMatrix Covariates, int isY2in, NumericMatrix CovMis2, double rho, NumericVector beta1, NumericVector beta2, NumericVector alpha1, NumericVector alpha0, double sigma, double sigma_g){ int i,j,k,t,l,s; const int nS= w.length(); int nsam=Covariates.nrow(); int ncov=Covariates.ncol(); int ncovMis=CovMis2.ncol(); NumericVector Y1(nsam),mta_1(nsam); NumericVector mta_20(nsam),mta_21(nsam),mta_20expit(nsam),mta_21expit(nsam); NumericVector eta1(nsam),eta2(nsam),eta1all(nsam),eta2all(nsam); NumericVector fkkt(nsam/2); double eta2exp,uk1,uk2; double fip_1p,fip_2p,fip0_1p,fip0_2p,fip1_1p,fip1_2p,f2i1,f2i0,f1i,weightjk; double ui11,ui12,ui2; const int indexbeta1 = beta1.length(); const int indexbeta2 = indexbeta1+beta2.length(); const int indexalpha1 = indexbeta2+alpha1.length(); const int indexalpha0 = indexalpha1+alpha0.length(); const int indexsigma = indexalpha0+1; const int indexsigmag = indexsigma+1; const double weightPi = pow(M_PI,-0.5*3); NumericMatrix scores(nsam/2,indexsigmag),scoreswtd(nsam/2,indexsigmag),infoMat(indexsigmag,indexsigmag); sigma = fabs(sigma); sigma_g = fabs(sigma_g); for(i = 0; i < nsam/2; ++i){ fkkt(i)=0; } for(i = 0; i < nsam; ++i) { eta1(i) = 0; eta2(i) = 0; mta_21(i) = 0; mta_20(i) = 0; for (j = 0; j < ncov; ++j){ eta1(i) += beta1(j) * Covariates(i,j); eta2(i) += beta2(j) * Covariates(i,j); } for (j = 0; j < ncovMis; ++j){ mta_21(i) += alpha1(j) * CovMis2(i,j); mta_20(i) += alpha0(j) * CovMis2(i,j); } mta_20expit(i) = exp(mta_20(i))/(1+exp(mta_20(i))); mta_21expit(i) = exp(mta_21(i))/(1+exp(mta_21(i))); if (mta_20expit(i) != mta_20expit(i)) {mta_20expit(i) = 1;} if (mta_21expit(i) != mta_21expit(i)) {mta_21expit(i) = 1;} } for (j = 0; j < indexsigmag; ++j){ for (k = 0; k < indexsigmag; ++k){ infoMat(j,k) = 0; } } for(i = 0; i < nsam/2; ++i){ for(k = 0; k < nS; ++k){ for(l = 0; l < nS; ++l){ for(s = 0; s < nS; ++s){ weightjk = w(k) * w(l) * w(s) * weightPi; ui11 = sqrt(2*(1-rho)) * sigma_g * v(k); ui12 = sqrt(2*(1-rho)) * sigma_g * v(l); ui2 = sqrt(2*(rho)) * sigma_g * v(s); //person 1 uk1 = ui11 + ui2; eta1all(i) = eta1(i) + uk1; eta2exp = eta2(i) + uk1; eta2all(i) = exp(eta2exp) / (1 + exp(eta2exp)); if (eta2all(i) != eta2all(i)) { eta2all(i)=1 ;} f1i = ( 1 / (fabs(sigma) * sqrt(2*M_PI)) )* exp( -0.5 * pow( (Y1star(i)-eta1all(i))/fabs(sigma), 2.0 )); f2i1 = pow(mta_21expit(i), 1-Y2star(i)) * pow(1-mta_21expit(i), Y2star(i)) ; f2i0 = pow(mta_20expit(i), Y2star(i)) * pow(1-mta_20expit(i), 1-Y2star(i)) ; fip0_1p = f1i * f2i0 * (1-eta2all(i)); fip1_1p = f1i * f2i1 * eta2all(i); fip_1p = fip0_1p + fip1_1p; // Person 2 uk2 = ui12 + ui2; eta1all(i + nsam/2) = eta1(i + nsam/2) + uk2; eta2exp = eta2(i + nsam/2) + uk2; eta2all(i + nsam/2) = exp(eta2exp) / (1 + exp(eta2exp)); if (eta2all(i + nsam/2) != eta2all(i + nsam/2)) { eta2all(i + nsam/2)=1 ;} f1i = ( 1 / (fabs(sigma) * sqrt(2*M_PI)) )* exp( -0.5 * pow( (Y1star(i + nsam/2)-eta1all(i + nsam/2))/fabs(sigma), 2.0 )); f2i1 = pow(mta_21expit(i + nsam/2), 1-Y2star(i + nsam/2)) * pow(1-mta_21expit(i + nsam/2), Y2star(i + nsam/2)) ; f2i0 = pow(mta_20expit(i + nsam/2), Y2star(i + nsam/2)) * pow(1-mta_20expit(i + nsam/2), 1-Y2star(i + nsam/2)) ; fip0_2p = f1i * f2i0 * (1-eta2all(i + nsam/2)); fip1_2p = f1i * f2i1 * eta2all(i + nsam/2); fip_2p = fip0_2p + fip1_2p; for(t = 0; t < beta1.length(); ++t){ scores(i,t) += weightjk * (Covariates(i,t) * (Y1star(i)-eta1all(i)) + Covariates(i + nsam/2,t) * (Y1star(i + nsam/2)-eta1all(i + nsam/2))) / pow(sigma,2) * fip_1p * fip_2p;} for(t = 0; t< beta2.length(); ++t){ scores(i,indexbeta1+t) += weightjk * (Covariates(i,t) * ((0 - eta2all(i)) * fip0_1p + (1 - eta2all(i)) * fip1_1p) * fip_2p + Covariates(i + nsam/2,t) * ((0 - eta2all(i + nsam/2)) * fip0_2p + (1 - eta2all(i + nsam/2)) * fip1_2p) * fip_1p) ; } for(t = 0; t < alpha1.length(); ++t){ scores(i,indexbeta2+t) += weightjk * (CovMis2(i,t) * ((1-Y2star(i)) - mta_21expit(i)) * fip1_1p * fip_2p + CovMis2(i + nsam/2,t) * ((1-Y2star(i + nsam/2)) - mta_21expit(i + nsam/2)) * fip1_2p * fip_1p); } for(t = 0; t< alpha0.length(); ++t){ scores(i,indexalpha1+t) += weightjk * (CovMis2(i,t) * (Y2star(i) - mta_20expit(i)) * fip0_1p * fip_2p + CovMis2(i + nsam/2,t) * (Y2star(i + nsam/2) - mta_20expit(i + nsam/2)) * fip0_2p * fip_1p); } scores(i,indexsigma-1) += weightjk * (-2/sigma + pow((Y1star(i) - eta1all(i)),2)/pow(sigma,3) + pow((Y1star(i + nsam/2) - eta1all(i + nsam/2)),2)/pow(sigma,3))* fip_1p * fip_2p; scores(i,indexsigmag-1) += weightjk * (-3/sigma_g + (ui11*ui11+ui12*ui12)/pow(sigma_g,3)/(1-rho) + ui2*ui2/pow(sigma_g,3)/rho) * fip_1p * fip_2p; fkkt(i) += weightjk * fip_1p * fip_2p; } } } } for (i = 0; i < nsam/2; ++i){ for (j = 0; j < indexsigmag; ++j){ scoreswtd(i,j) = scores(i,j) / fkkt(i); } for (j = 0; j < indexsigmag; ++j){ for (k = 0; k < indexsigmag; ++k){ infoMat(j,k) += scoreswtd(i,j)*scoreswtd(i,k); } } } return(infoMat); } // You can include R code blocks in C++ files processed with sourceCpp // (useful for testing and development). The R code will be automatically // run after the compilation. // /*** R # # sigma_g<-2 # set.seed(2018) # u<-mvrnorm(n=1000,mu=rep(0,dim(RR_new)[1]),Sigma=RR_new*(sigma_g^2)) # random1<-matrix(rnorm(nsample*nrepeat,mean=0,sd=abs(sigma)),ncol=nrepeat) # random2<-matrix(runif(nsample*nrepeat,min=0,max=1),ncol=nrepeat) # # nsam<-dim(Covariates)[1] # # beta1<-c(1,1,1) # beta2<-c(1,1,0.1) # lambda<-c(1,1) # gamma<-c(14,0.1,0.1) # alpha0<-c(0.01,0.01) # alpha1<-c(0.01,0.01) # sigma<-sigma_e<-sigma_g<-2 # # CovMea1<- as.matrix(cbind(Covariates_all[,c("Intercept")])) # CovMis2<- as.matrix(cbind(Covariates_all[,c("Intercept","BMD")])) # Covariates<- as.matrix(cbind(Covariates_all[,c("Intercept","X","BW")]) # # Re<-logLikelihood_indep_c(u,random1,random2,Y1star,Y2star,Covariates,CovMea1,1,1,CovMis2, # beta1,beta2,lambda,gamma,alpha1,alpha0,sigma,sigma_e) # Re # set.seed(2018) */
[ "qihuang.zh@gmail.com" ]
qihuang.zh@gmail.com
b4ae60bafd6850e58f6ec2619da9b7fb5035e174
56082c3eb04c9b7db33a5dc9649fbdd1d8198565
/Settings.cpp
825434baf534ac0f3262f6898fdf2830ff2d1cab
[]
no_license
TimurZnamenity/StreamMath
6ff164233586133dc0645cff2609bb9bca1e7744
07f3c326b15a3d7da46ba03aa7404c07187a2c8b
refs/heads/master
2022-08-27T16:38:33.586748
2020-05-27T15:28:42
2020-05-27T15:28:42
267,260,106
0
0
null
null
null
null
UTF-8
C++
false
false
1,244
cpp
#include "Settings.hpp" #include <QFile> #include <QDebug> #include <QJsonObject> #include <QJsonDocument> #include <QJsonArray> Settings::Settings() { } QString Settings::value(QString key) { QFile settingsFile { "settings.json" }; if ( !settingsFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) { qDebug() << "Unable to open Input Data File"; return ""; } auto settingsText = settingsFile.readAll(); QJsonObject jsonObj; QJsonDocument jsonDoc; QJsonParseError parseError; // если пустой текст if( settingsText.isEmpty() ) // возвращаем пустую строку return ""; jsonDoc = QJsonDocument::fromJson(settingsText, &parseError); if(parseError.error != QJsonParseError::NoError) { qDebug() << settingsText; qWarning() << "Json parse error: " << parseError.errorString(); } else { if(jsonDoc.isObject()) jsonObj = jsonDoc.object(); else if (jsonDoc.isArray()) jsonObj["non_field_errors"] = jsonDoc.array(); } // разбираем объект if( jsonObj[key].isUndefined() ) return ""; return jsonObj[key].toString(); }
[ "cdx@list.ru" ]
cdx@list.ru
c9a9995d66528a08f30b740f8e3b69b24634fe08
20049d88e2e8f0e1904efc561103c1d84d21507a
/sachuk.ilya/common/rectangle.cpp
8daddc444005540b2b3095483795fc97c6e284e1
[]
no_license
gogun/Labs-for-SPbSPU-C-course-during-2019
5442a69152add3e66f02a7541e8dc8dd817f38a1
16ade47b859517a48d0fdb2e9704464bce4cc355
refs/heads/master
2022-01-09T16:02:54.728830
2019-06-06T11:06:33
2019-06-06T11:06:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,215
cpp
#include "rectangle.hpp" #include <iostream> #include <stdexcept> sachuk::Rectangle::Rectangle(const point_t & point, double w, double h): center_(point), width_(w), height_(h) { if ((width_ <= 0) || (height_ <= 0)) { throw std::invalid_argument("Invalid arguments"); } } double sachuk::Rectangle::getArea() const { return width_ * height_; } void sachuk::Rectangle::move(const point_t & point) { center_ = point; } void sachuk::Rectangle::move(double dx, double dy) { center_.x += dx; center_.y += dy; } sachuk::rectangle_t sachuk::Rectangle::getFrameRect() const { return {width_, height_, center_}; } void sachuk::Rectangle::scale(double multiplier) { if (multiplier <= 0) { throw std::invalid_argument("Multiplier must be positive"); } else { width_ *= multiplier; height_ *= multiplier; } } void sachuk::Rectangle::printInfo() const { std::cout << "Rectangle:"; std::cout << " Width=" << getFrameRect().width << ";"; std::cout << " Height=" << getFrameRect().height << std::endl; std::cout << "X=" << getFrameRect().pos.x << ";"; std::cout << "Y=" << getFrameRect().pos.y << std::endl; std::cout << "Area=" << getArea() << std::endl << std::endl; }
[ "ilya-sachuk@mail.ru" ]
ilya-sachuk@mail.ru
399fc283b54615e1fd3052547700466b79a8c123
d9fbb96ac2afd5d250809a5f510fdeba955aea77
/mixed programs/the remainder.cpp
076fea5d99fe1065461fe9eceb45bf4873085611
[]
no_license
collab-tripti/competitive
02cb83c88f4b83aa1edffd4fd15de3b021aa5834
c8047e4ad6e1a0bf926225c9da3c76e921ad2c97
refs/heads/master
2022-07-16T10:48:41.688964
2020-05-19T09:31:16
2020-05-19T09:31:16
261,931,469
1
0
null
null
null
null
UTF-8
C++
false
false
228
cpp
#include<iostream> using namespace std; int main() { int t; cin >> t; int a[t],b[t],o[t]; for(int i=0;i<t;i++) { cin >> a[i]>>b[i]; o[i]=a[i]%b[i]; } for(int i=0;i<t;i++) { cout << o[i] << endl; } return 0; }
[ "Triaa@penguin" ]
Triaa@penguin
de6d698e7a651e37f180483768b505a39752bd16
de2b4084bbc70d7b5ae9c01e63709c4dbbba9288
/AlgoSpot/11_Data_Structure/ITES.cpp
7636fe14b925649b0831adb2e510f13da619fd65
[]
no_license
hanky3/HLP_CodeJam
fc8d62d6611f56af899a18af26936a3d832be7f5
e11c5cda4f576d8f41df50322fd4f9ddd0b51490
refs/heads/master
2021-05-08T10:20:24.451982
2018-12-18T00:44:27
2018-12-18T00:44:27
119,838,216
0
0
null
null
null
null
UTF-8
C++
false
false
1,929
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <vector> #include <map> #include <algorithm> #include <queue> using namespace std; #define INF 0x0FFFFFFF #define MAX_V 1001 FILE *fpInput = NULL; FILE *fpOutput = NULL; int K, N; unsigned long long previousNum; int randomGenerator(int index) { unsigned long long mod = pow(2, 32); if (index == 0) { previousNum = 1983; return (int)previousNum; } previousNum = ((previousNum%mod) * 214013 + 2531011) % mod; return (previousNum % 10000) + 1; } int numOfPartialSum() { int currentSum = 0; int partialSumCnt = 0; queue<int> numberList; for (int index = 0; index < N; index++) { int signal = randomGenerator(index); numberList.push(signal); currentSum += signal; while (currentSum >= K) { if (currentSum == K) partialSumCnt++; currentSum -= numberList.front(); numberList.pop(); } } return partialSumCnt; } // Solve the problem(read the input file / and retrieves the result void solveProblem(char *filename, bool isFile) { // gFpOutput = fopen("Test.txt", "w"); if (!isFile) { fpInput = stdin; fpOutput = stdout; } else { string inputFileName = string(filename); string outFileName = inputFileName.substr(0, inputFileName.find_last_of(".")) + ".out"; fpInput = fopen(inputFileName.c_str(), "r"); fpOutput = fopen(outFileName.c_str(), "w"); } int testCase = 0; fscanf(fpInput, "%d", &testCase); for (int i = 0; i < testCase; i++) { fscanf(fpInput, "%d %d\n", &K, &N); // result calculation int ret = numOfPartialSum(); fprintf(fpOutput, "%d", ret); if (isFile) printf("%d", ret); fprintf(fpOutput, "\n"); if (isFile) printf("\n"); } if (isFile) { fclose(fpInput); fclose(fpOutput); } // fclose(gFpOutput); } int main(int argc, char **argv) { #ifdef _FILE_ solveProblem(argv[1], true); #else solveProblem("", false); #endif return 0; }
[ "34890345+hanky3@users.noreply.github.com" ]
34890345+hanky3@users.noreply.github.com
b045d5187e5e0b03ad44281b2fe12c77917a9ac4
066aa9c40e49b0b5dd796cf7e2e4a9b1fca538a9
/torch_glow/src/ShapeInferenceEngine.cpp
ff92274ba8bbc6b8a0079329eb8d1e2b04792f8d
[ "Apache-2.0" ]
permissive
Qturing/glow
4d9617ec3a2758afd2eac336e89378bc409f36a0
70bfa5ae290af743132db4ea357a64d06e7c2418
refs/heads/master
2023-02-09T23:29:54.404119
2021-01-05T23:31:48
2021-01-05T23:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
58,887
cpp
// Copyright 2004-present Facebook. All Rights Reserved. #include <ATen/WrapDimUtils.h> #include <iostream> #include <string> #include <torch/script.h> #include <unordered_set> #include <vector> #include "ShapeInferenceEngine.h" #include "glow/Support/Error.h" #include "glow/Support/Support.h" DEFINE_string(shapeInferenceOpBlocklist, "", "Ops to skip shape inference"); DEFINE_int32(max_feature_length, -1, "max feature length"); DEFINE_int32(max_batch_size, -1, "max batch size"); namespace glow { static std::vector<std::string> splitStr(const std::string &s, const char delimiter = ',') { std::vector<std::string> substrings; size_t start = 0; bool lastWasSplit = true; for (size_t i = 0; i < s.size(); i++) { if (lastWasSplit && s[i] == ' ') { start = i + 1; continue; } lastWasSplit = false; if (s[i] == delimiter) { substrings.push_back(s.substr(start, i - start)); start = i + 1; lastWasSplit = true; } } if (start < s.size() - 1) { substrings.push_back(s.substr(start, s.size() - start)); } return substrings; } ShapeInferenceEngine::ShapeInferenceEngine( const torch::jit::Graph &graph, const at::ArrayRef<at::IValue> &inputs, const std::string &fusionNodeSymbol) : graph_(graph), inputs_(inputs), fusionNodeSymbol_(fusionNodeSymbol) { if (!FLAGS_shapeInferenceOpBlocklist.empty()) { auto ret = splitStr(FLAGS_shapeInferenceOpBlocklist); for (const auto &s : ret) { blockList_.insert(s); } } }; void ShapeInferenceEngine::getNodeInputShape(const torch::jit::Node *node, MetaStack &inputMetas) { for (auto input : node->inputs()) { auto it = shapeMap_.find(input); CHECK(it != shapeMap_.end()) << "Node: " << node->kind() << " input " << input->debugName(); inputMetas.emplace_back(shapeMap_[input]); } } const MetaStack &ShapeInferenceEngine::getGraphOutputShape() { return outputShape_; } const std::unordered_map<const torch::jit::Value *, VariableMeta> & ShapeInferenceEngine::getVariableMap() { return shapeMap_; } Error ShapeInferenceEngine::shapeOnNode(const torch::jit::Node *node) { /// Get op symbol const auto kind = node->kind(); const std::string symbol = kind.toQualString(); if (blockList_.count(symbol)) { // Skip shape inference for this node. If other nodes have dependency // on this one then later their shape inference would fail explicitly. LOG_FIRST_N(INFO, 1) << "Skip shape inference for " << symbol; return Error::success(); } /// Extract shapes of inputs from shape mapping MetaStack inputMetas; /// The outputs of each Op shape function include the shape and data /// type, and the shape could be either the shape or int value /// generated by prim::consant or prim::ListContruct. TensorOutput tensorOutput; TensorListOutput tensorListOutput; getNodeInputShape(node, inputMetas); // Get output shape or int value of the ops without actual computation if (symbol == "glow::fused_stack") { int64_t dim = node->i(at::attr::dim); ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, fusedStack(inputMetas, dim)); } else if (symbol == "glow::fused_broadcast_stack") { int64_t dim = node->i(at::attr::dim); ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, fusedBroadcastStack(inputMetas, dim)); } else if (symbol == "glow::fused_broadcast_cat") { int64_t dim = node->i(at::attr::dim); ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, fusedBroadcastConcat(inputMetas, dim)); } else if (symbol == "glow::fused_split") { ASSIGN_VALUE_OR_RETURN_ERR(tensorListOutput, fusedSplit(inputMetas)); } else if (symbol == "quantized::embedding_bag_byte_rowwise_offsets") { ASSIGN_VALUE_OR_RETURN_ERR( tensorOutput, quantizedEmbeddingBagByteRowwiseOffsets(inputMetas)); } else if (symbol == "quantized::embedding_bag_4bit_rowwise_offsets") { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, embeddingBag4BitRowwiseOffsets(inputMetas)); } else if (symbol == "glow::unpacked_quantized_linear") { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, glowUnpackedQuantizedLinear(inputMetas)); } else if (symbol == "fb::lengths_to_offsets") { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, lengthsToOffsets(inputMetas)); } else if (symbol == "fb::simple_embedding_bag_sum") { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, embeddingBag(inputMetas)); } else if (symbol == "fb::glow_embedding_bag") { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, glowEmbeddingBag(inputMetas)); } else if (symbol == "fb::fast_gather") { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, fastGather(inputMetas)); } else if (symbol == "fb::lengths_range") { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, lengthsRange(inputMetas)); } else if (symbol == "aten::quantize_per_tensor") { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, quantizePerTensor(inputMetas)); } else if (symbol == "aten::dequantize") { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, dequantize(inputMetas)); } else if (symbol == "quantized::mul") { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, quantizedMul(inputMetas)); } else { switch (kind) { case c10::prim::Constant: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, primConstant(node)); break; } case c10::aten::tanh: case c10::aten::relu: case c10::aten::sigmoid: { RETURN_ERR_IF_NOT(inputMetas.size() == 1, "Expected 1 input shape for operators."); tensorOutput.shapeOrIntValues = inputMetas[0].shape<TensorShape>(), tensorOutput.dtype = inputMetas[0].dtype; break; } case c10::aten::sub: case c10::aten::pow: case c10::aten::mul: case c10::aten::add: case c10::aten::div: case c10::aten::rsub: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, binaryOp(inputMetas)); break; } case c10::aten::mm: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, mm(inputMetas)); break; } case c10::aten::addmm: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, addmm(inputMetas)); break; } case c10::aten::bmm: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, bmm(inputMetas)); break; } case c10::aten::t: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, t(inputMetas)); break; } case c10::aten::transpose: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, transpose(inputMetas)); break; } case c10::aten::flatten: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, flatten(inputMetas)); break; } case c10::prim::FusedConcat: { int64_t dim = node->i(at::attr::dim); ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, fusedConcat(inputMetas, dim)); break; } case c10::prim::ConstantChunk: { int64_t chunks = node->i(at::attr::chunks); int64_t dim = node->i(at::attr::dim); ASSIGN_VALUE_OR_RETURN_ERR(tensorListOutput, constantChunk(inputMetas, chunks, dim)); break; } case c10::aten::chunk: { ASSIGN_VALUE_OR_RETURN_ERR(tensorListOutput, chunk(inputMetas)); break; } case c10::prim::ListConstruct: { ASSIGN_VALUE_OR_RETURN_ERR(tensorListOutput, listConstruct(inputMetas)); break; } case c10::aten::slice: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, slice(inputMetas)); break; } case c10::aten::reshape: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, reshape(inputMetas)); break; } case c10::aten::cat: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, cat(inputMetas)); break; } case c10::aten::permute: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, permute(inputMetas)); break; } case c10::aten::embedding_bag: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, embeddingBag(inputMetas)); break; } case c10::aten::matmul: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, matmul(inputMetas)); break; } case c10::aten::stack: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, stack(inputMetas)); break; } case c10::aten::to: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, to(inputMetas)); break; } case c10::aten::sum: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, sum(inputMetas)); break; } case c10::prim::dtype: { ASSIGN_VALUE_OR_RETURN_ERR(tensorOutput, primDtype(inputMetas)); break; } case c10::prim::ListUnpack: { ASSIGN_VALUE_OR_RETURN_ERR(tensorListOutput, listUnpack(inputMetas)); break; } default: { return MAKE_ERR(strFormat("Node's operator %s is not supported", kind.toQualString())); } } } /// Put output into map /// For \p prim::Constant, the output could be either Tensor or NumberType. /// If the output is TensorType, store the \p outputShapesOrValues /// into VariableMeta.listOfShape; /// Else store the \p outputShapesOrValues into VariableMeta.intValue. /// For \p prim::ListConstruct, if the output is a Scalar[], Bool[], /// Store the shape of \p outputShapesOrValues into VariableMeta.listOfShape /// store the value of \p outputShapesOrValues into VariableMeta.intValue /// Else the output is Tensor[], Store the list of shape /// \p outputShapesOrValues into VariableMeta.listOfShape /// For \p aten::embedding_bag, since the output is a std::tuple<Tensor, /// Tensor, Tensor, Tensor>(ret, offset2bag, bag_size, bag_size), and for now, /// only the ret tensor shape needed, the embeddingBag() only generate the ret /// shape. /// For \p c10::aten::chunk, the output is tensor[], /// Store the shapes \p outputShapesOrValues into VariableMeta.listOfShape if (kind == c10::prim::Constant || kind == c10::prim::dtype) { if (node->output()->type()->isSubtypeOf(at::TensorType::get())) { shapeMap_[node->output()].listOfShape.emplace_back( std::move(tensorOutput.shapeOrIntValues)); shapeMap_[node->output()].dtype = tensorOutput.dtype; } else { shapeMap_[node->output()].listOfShape.emplace_back((TensorShape){1}); shapeMap_[node->output()].intValue = std::move(tensorOutput.shapeOrIntValues); shapeMap_[node->output()].dtype = tensorOutput.dtype; } } else if (kind == c10::prim::ListConstruct) { auto elem_type = node->output()->type()->cast<c10::ListType>()->getElementType(); if (elem_type->kind() == at::TensorType::Kind || (elem_type->kind() == at::OptionalType::Kind && elem_type->cast<c10::OptionalType>()->getElementType()->kind() == at::TensorType::Kind)) { shapeMap_[node->output()].listOfShape.emplace_back( std::move(tensorListOutput.shape)); shapeMap_[node->output()].dtype = tensorListOutput.dtype; } else { shapeMap_[node->output()].listOfShape.emplace_back((TensorShape){ static_cast<long>(tensorListOutput.shape[0].size()), 1}); shapeMap_[node->output()].intValue = std::move(tensorListOutput.shape[0]); shapeMap_[node->output()].dtype = tensorListOutput.dtype; } } else if (symbol == "fb::glow_embedding_bag") { shapeMap_[node->output()].listOfShape.emplace_back( std::move(tensorOutput.shapeOrIntValues)); shapeMap_[node->output()].dtype = tensorOutput.dtype; } else if (kind == c10::aten::embedding_bag || symbol == "fb::simple_embedding_bag_sum") { shapeMap_[node->output(0)].listOfShape.emplace_back( std::move(tensorOutput.shapeOrIntValues)); shapeMap_[node->output(0)].dtype = tensorOutput.dtype; } else if (kind == c10::aten::chunk) { shapeMap_[node->output()].listOfShape.emplace_back( std::move(tensorListOutput.shape)); shapeMap_[node->output()].dtype = tensorListOutput.dtype; } else if (tensorOutput.shapeOrIntValues.size() > 0) { shapeMap_[node->output()].listOfShape.emplace_back( std::move(tensorOutput.shapeOrIntValues)); shapeMap_[node->output()].dtype = tensorOutput.dtype; } else { for (int i = 0; i < node->outputs().size(); i++) { shapeMap_[node->output(i)].listOfShape.emplace_back( std::move(tensorListOutput.shape[i])); shapeMap_[node->output(i)].dtype = tensorListOutput.dtype; } } return Error::success(); } Error ShapeInferenceEngine::runRecursively( const torch::jit::Graph &graph, const at::ArrayRef<torch::jit::IValue> &inputs) { // Populate input shapes RETURN_IF_ERR(getGraphInputShapeType(graph, inputs)); /// Run shape inference for each node for (auto *node : graph.nodes()) { if (node->hasAttribute(torch::jit::attr::Subgraph)) { std::string kind = node->kind().toQualString(); CHECK_EQ(kind.find(fusionNodeSymbol_), 0); // After fusion the input Value of the subgraph and // input Value of the fusion node are different // in memory objects. Therefore we populate inputMeta // beforehand and pass it to recursive run. std::vector<torch::jit::IValue> subgraphInputs; for (auto i : node->inputs()) { auto it = shapeMap_.find(i); CHECK(it != shapeMap_.end()); // Only support tensor input for now // TODO Add support for other input types, e.g., tensor list subgraphInputs.push_back( torch::empty(it->second.shape<TensorShape>(), torch::TensorOptions().dtype(it->second.dtype))); } const at::ArrayRef<torch::jit::IValue> inputRefs(subgraphInputs); auto subgraph = node->g(torch::jit::attr::Subgraph); RETURN_IF_ERR(runRecursively(*subgraph, subgraphInputs)); CHECK_EQ(subgraph->outputs().size(), node->outputs().size()); for (int i = 0; i < subgraph->outputs().size(); ++i) { shapeMap_[node->outputs()[i]] = shapeMap_[subgraph->outputs()[i]]; } } else { RETURN_IF_ERR(shapeOnNode(node)); } } return Error::success(); } Error ShapeInferenceEngine::run() { RETURN_ERR_IF_NOT( inputs_.size() == graph_.inputs().size() || (inputs_.size() + 1 == graph_.inputs().size() && graph_.inputs()[0]->type()->is_module()), "Number of inputs mismatch between Graph and actual inputs"); /// Put graph input into shape mapping RETURN_IF_ERR(runRecursively(graph_, inputs_)); /// Extract output from shape mapping RETURN_IF_ERR(generateGraphOutputShape()); return Error::success(); } void ShapeInferenceEngine::printShapeMap() { for (auto elem : shapeMap_) { std::cout << elem.first->debugName() << ":[ "; if (elem.second.listOfShape[0].type() == typeid(TensorShape)) { const TensorShape &shape = elem.second.shape<TensorShape>(); for (auto value : shape) { std::cout << value << " "; } } else if (elem.second.listOfShape[0].type() == typeid(TensorListShape)) { const TensorListShape &shapes = elem.second.shape<TensorListShape>(); for (auto shape : shapes) { std::cout << "[ "; for (auto value : shape) { std::cout << value << " "; } std::cout << "]"; } } else { std::cout << "Type doesn't support yet."; } std::cout << "]" << std::endl; } } /// If the input is tensor, store the shape info only; /// Else If the input is bool or int, store the value, and set shape as 1. /// Else if the input is intlist, store the intlist, and set shape as [sizeof /// intlist, 1] /// Else return an error Error ShapeInferenceEngine::getGraphInputShapeType( const torch::jit::Graph &graph, const at::ArrayRef<torch::jit::IValue> &inputs) { int has_self = 0; if (!graph.inputs().empty() && graph.inputs()[0]->type()->is_module()) { has_self = 1; } for (auto i = 0; i < inputs.size(); i++) { auto gInName = graph.inputs()[i + has_self]; auto input = inputs[i]; TensorShape shape = {}; std::vector<int64_t> intValue = {}; c10::ScalarType dtype; if (input.isTensor()) { auto ptTensor = input.toTensor(); for (auto s : ptTensor.sizes()) { shape.emplace_back(s); } dtype = ptTensor.scalar_type(); } else if (input.isBool() || input.isInt()) { shape = {1}; intValue = {input.toInt()}; dtype = input.isBool() ? c10::ScalarType::Bool : c10::ScalarType::Int; } else if (input.isIntList()) { intValue = input.toIntVector(); shape = {static_cast<long>(intValue.size()), 1}; dtype = c10::ScalarType::Int; } else { return MAKE_ERR("Input type doesn't support yet."); } shapeMap_[gInName].listOfShape.emplace_back(std::move(shape)); shapeMap_[gInName].intValue = intValue; shapeMap_[gInName].dtype = dtype; } return Error::success(); } Error ShapeInferenceEngine::generateGraphOutputShape() { for (auto output : graph_.outputs()) { auto it = shapeMap_.find(output); if (it == shapeMap_.end()) { if (!blockList_.empty()) { LOG(WARNING) << "Some output shape is missing. Likely due to " "blockList. Clearing the output shape vector."; outputShape_.clear(); return Error::success(); } else { return MAKE_ERR("Unexpected missing shape for output."); } } outputShape_.emplace_back(it->second); } return Error::success(); } /// The \p prim::Constant may have multiple types of output, eg. /// int = prim::Constant[value=0]() /// Float(1:1) = prim::Constant[value={0}]() /// bool = prim::Constant[value=0]() /// None = prim::Constant() /// int[] = prim::Constant[value=[1,2,3]]() /// Tensor = prim::Constant[value= <Tensor>]() /// If the output is a tensor, return shape info and dtype; /// Else, return the value and dtype. Expected<TensorOutput> ShapeInferenceEngine::primConstant(const torch::jit::Node *node) { TensorShape shapeOrValue; c10::ScalarType dtype; at::TypePtr type = node->output()->type(); if (type->isSubtypeOf(at::FloatType::get())) { /// The float type will not affect the shape /// Set value as 1 shapeOrValue = {1}; dtype = c10::ScalarType::Float; } else if (type->isSubtypeOf(at::IntType::get())) { shapeOrValue = {node->i(at::attr::value)}; dtype = c10::ScalarType::Int; } else if (type->isSubtypeOf(at::BoolType::get())) { shapeOrValue = {node->i(at::attr::value)}; dtype = c10::ScalarType::Bool; } else if (type->isSubtypeOf(at::NoneType::get())) { shapeOrValue = {}; dtype = c10::ScalarType::Undefined; } else if (type->isSubtypeOf(at::TensorType::get())) { at::Tensor t = node->t(at::attr::value); for (auto s : t.sizes()) { shapeOrValue.emplace_back(s); } dtype = t.scalar_type(); } else if (type->isSubtypeOf(at::ListType::ofInts())) { dtype = c10::ScalarType::Int; shapeOrValue = node->ival(at::attr::value).toIntVector(); } else if (type->isSubtypeOf(at::StringType::get())) { shapeOrValue = {1}; dtype = c10::ScalarType::Char; } else { LOG(ERROR) << "Got " << *type; return MAKE_ERR("Type not supported"); } TensorOutput output; output.shapeOrIntValues = shapeOrValue; output.dtype = dtype; return output; } /** * aten::add(Tensor self, Tensor or Scalar other, Scalar alpha=1) -> Tensor * aten::pow(Tensor self, Tensor or Scalar other, Scalar alpha=1) -> Tensor * aten::mul(Tensor self, Tensor or Scalar other, Scalar alpha=1) -> Tensor * variableMetas: 0: self, 1: other */ Expected<TensorOutput> ShapeInferenceEngine::binaryOp(const MetaStack &variableMetas) { if (variableMetas.size() != 2 && variableMetas.size() != 3) { return MAKE_ERR("Expected two or three inputs shapes of this operation."); } const TensorShape &t0 = variableMetas[0].shape<TensorShape>(); const TensorShape &t1 = variableMetas[1].shape<TensorShape>(); auto d0 = t0.size(); auto d1 = t1.size(); TensorOutput output; output.dtype = variableMetas[0].dtype; /// One input is Scalar if (d1 == 1) { output.shapeOrIntValues = t0; return output; } size_t dim = std::max(d0, d1); TensorShape shape(dim); for (auto i = 0; i < dim; i++) { auto j = -1 - i; if (i >= d0 || t0[d0 + j] == 1) { shape[dim + j] = t1[d1 + j]; } else if (i >= d1 || t1[d1 + j] == 1) { shape[dim + j] = t0[d0 + j]; } else { if (t1[d1 + j] != t0[d0 + j]) { return MAKE_ERR( strFormat("The size of tensor a (%zu) must match the size of " "tensor b (%zu)at non-singleton dimension 1.", t0[d0 + j], t1[d1 + j])); } shape[dim + j] = t1[d1 + j]; } } output.shapeOrIntValues = shape; return output; } /** * aten::mm(Tensor self, Tensor mat2) -> Tensor * variableMetas: 0: self, 1: mat2 */ Expected<TensorOutput> ShapeInferenceEngine::mm(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT(variableMetas.size() == 2, "Expected two inputs shapes of this operation."); const TensorShape &t0 = variableMetas[0].shape<TensorShape>(); const TensorShape &t1 = variableMetas[1].shape<TensorShape>(); if (!(t1.size() == 2 && t0.size() == 2)) { return MAKE_ERR("Expected 2-dimensional tensor."); } if (t0[1] != t1[0]) { return MAKE_ERR( strFormat("The size of tensor a (%zu) at dimension 1 must match the " "size of tensor b (%zu) at dimension 0.", t0[1], t1[0])); } TensorOutput output; TensorShape shape = {t0[0], t1[1]}; output.shapeOrIntValues = shape; output.dtype = variableMetas[0].dtype; return output; } /** * aten::bmm(Tensor self, Tensor mat2) -> Tensor * variableMetas: 0: self, 1: mat2 */ Expected<TensorOutput> ShapeInferenceEngine::bmm(const MetaStack &variableMetas) { if (variableMetas.size() != 2) { return MAKE_ERR("Expected two inputs shapes of this operation."); } const TensorShape &t0 = variableMetas[0].shape<TensorShape>(); const TensorShape &t1 = variableMetas[1].shape<TensorShape>(); if (!(t0.size() == 3 && t1.size() == 3)) { return MAKE_ERR("Expected 3-dimensional tensor."); } if (t0[0] != t1[0]) { return MAKE_ERR("Expected tensors to have same size at dimension 0"); } if (t0[2] != t1[1]) { return MAKE_ERR(strFormat("The size of tensor a (%zu) at dimension 2 must" "match the size of tensor b (%zu) at dimension 1", t0[2], t1[1])); } TensorOutput output; TensorShape shape = {t0[0], t0[1], t1[2]}; output.shapeOrIntValues = shape; output.dtype = variableMetas[0].dtype; return output; } /** * aten::addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor * variableMetas: 0: self, 1: mat1, 2: mat2 */ Expected<TensorOutput> ShapeInferenceEngine::addmm(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT(variableMetas.size() >= 3, strFormat("Expected at least three inputs shapes, got %zu.", variableMetas.size())); const VariableMeta &t0 = variableMetas[0]; const VariableMeta &t1 = variableMetas[1]; const VariableMeta &t2 = variableMetas[2]; VariableMeta t; // For Scalar type, the shape.size() is 1 if (t2.shape<TensorShape>().size() == 1) { t = variableMetas[1]; } else { const MetaStack &mmShape = {t1, t2}; TensorOutput mmOutput; ASSIGN_VALUE_OR_RETURN_ERR(mmOutput, mm(mmShape)); t.listOfShape.emplace_back(std::move(mmOutput.shapeOrIntValues)); } return binaryOp({t0, std::move(t)}); } /** * aten::t(Tensor self) -> Tensor * refer to https://pytorch.org/docs/master/generated/torch.t */ Expected<TensorOutput> ShapeInferenceEngine::t(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 1, strFormat("Expected one input, got %zu.", variableMetas.size())); const TensorShape &t0 = variableMetas[0].shape<TensorShape>(); auto d0 = t0.size(); TensorOutput output; output.dtype = variableMetas[0].dtype; /// 0-D or 1-D tensor: Same shape if (d0 == 1) { output.shapeOrIntValues = t0; return output; /// 2-D tensor: Transpose } else if (d0 == 2) { TensorShape shape{t0[1], t0[0]}; output.shapeOrIntValues = shape; return output; /// >2-D tensor: Invalid input } else { return MAKE_ERR(strFormat("Expected tensor <= 2-D, got %zu-D.", d0)); } } Expected<TensorOutput> ShapeInferenceEngine::sum(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 4, strFormat("Expected Four input, got %zu.", variableMetas.size())); // TODO: @hwwang T80910607 Only support None dtype (4th argument) RETURN_ERR_IF_NOT(variableMetas[3].intValue.size() == 0 and variableMetas[3].dtype == c10::ScalarType::Undefined, "Only support 4th arugment of aten::sum operator is None"); const auto &t0 = variableMetas[0].shape<TensorShape>(); auto dims = variableMetas[1].intValue; bool include_dim = variableMetas[2].intValue[0]; TensorShape shape; for (int i = 0; i < t0.size(); i++) { if (std::find(dims.begin(), dims.end(), i) != dims.end()) { if (include_dim) { shape.push_back(1); } else { continue; } } else { shape.push_back(t0[i]); } } TensorOutput output; output.dtype = variableMetas[0].dtype; output.shapeOrIntValues = shape; return output; } /** * aten::transpose(Tensor self, int dim0, int dim1) => Tensor * variableMetas: 0: self, 1: dim0, 2: dim1 * refer to https://pytorch.org/docs/master/generated/torch.transpose **/ Expected<TensorOutput> ShapeInferenceEngine::transpose(const MetaStack &variableMetas) { if (variableMetas.size() != 3) { return MAKE_ERR( strFormat("Expect 3 inputs, get %zu", variableMetas.size())); } RETURN_ERR_IF_NOT(variableMetas[1].intValue.size() == 1, "Expect 1 int dimension"); RETURN_ERR_IF_NOT(variableMetas[2].intValue.size() == 1, "Expect 1 int dimension"); TensorShape shape = variableMetas[0].shape<TensorShape>(); int64_t inDims = shape.size(); int64_t dim0 = variableMetas[1].intValue[0]; int64_t dim1 = variableMetas[2].intValue[0]; // convert to positive dimension dim0 = at::maybe_wrap_dim(dim0, inDims); dim1 = at::maybe_wrap_dim(dim1, inDims); std::swap(shape[dim0], shape[dim1]); TensorOutput output; output.shapeOrIntValues = shape; output.dtype = variableMetas[0].dtype; return output; } /** * aten::cat(Tensors tensors, int dim=0) => Tensor * 0:variableMetas, 1: dim * refer to https://pytorch.org/docs/master/generated/torch.cat **/ Expected<TensorOutput> ShapeInferenceEngine::cat(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 2, strFormat("Expected 2 inputs, got %zu.", variableMetas.size())); const TensorListShape &tensorListShapes = variableMetas[0].shape<TensorListShape>(); std::vector<int64_t> shape = tensorListShapes[0]; TensorOutput output; output.dtype = variableMetas[0].dtype; // Hanlde the single input case if (tensorListShapes.size() == 1) { output.shapeOrIntValues = shape; return output; } // Convert negtive dimension to positive, then check the dim range. int64_t dim = variableMetas[1].intValue[0]; int64_t inDims = shape.size(); dim = at::maybe_wrap_dim(dim, inDims); // Handle multiple input cases. // Verify all inputs dimenions are the same execpt the dimension applies cat. for (int i = 1; i < tensorListShapes.size(); ++i) { RETURN_ERR_IF_NOT(inDims == tensorListShapes[i].size(), "All inputs must have the same number of dimensions."); for (int j = 0; j < inDims; j++) { if (j == dim) { continue; } else { RETURN_ERR_IF_NOT( shape[j] == tensorListShapes[i][j], strFormat("Sizes of tensors must match except in dimension %zu.", dim)); } } } for (int i = 1; i < tensorListShapes.size(); ++i) shape[dim] += tensorListShapes[i][dim]; output.shapeOrIntValues = shape; return output; } /** * aten::flatten(Tensor self, int start_dim, int end_dim) => Tensor * variableMetas: 0: self, 1: start_dim, 2: end_dim * refer to: https://pytorch.org/docs/master/generated/torch.flatten **/ Expected<TensorOutput> ShapeInferenceEngine::flatten(const MetaStack &variableMetas) { if (variableMetas.size() != 3) { return MAKE_ERR( strFormat("Expect 3 inputs, get %zu", variableMetas.size())); } RETURN_ERR_IF_NOT(variableMetas[1].intValue.size() == 1, "Expect 1 int dimension"); RETURN_ERR_IF_NOT(variableMetas[2].intValue.size() == 1, "Expect 1 int dimension"); const TensorShape &t = variableMetas[0].shape<TensorShape>(); int64_t inDims = t.size(); int64_t startDim = variableMetas[1].intValue[0]; int64_t endDim = variableMetas[2].intValue[0]; // convert to positive dimension startDim = at::maybe_wrap_dim(startDim, inDims); endDim = at::maybe_wrap_dim(endDim, inDims); if (startDim > endDim) { return MAKE_ERR("start dimension should not be larger than end dimension"); } TensorShape shape; for (int i = 0; i < startDim; i++) { shape.push_back(t[i]); } int64_t flattenDim = 1; for (int i = startDim; i <= endDim; i++) { flattenDim *= t[i]; } shape.push_back(flattenDim); for (int i = endDim + 1; i < inDims; i++) { shape.push_back(t[i]); } TensorOutput output; output.dtype = variableMetas[0].dtype; output.shapeOrIntValues = shape; return output; } /** * prim::ConstantChunk[int chunks, int dim](Tensor self) -> Tensors * variableMetas: 0: self */ Expected<TensorListOutput> ShapeInferenceEngine::constantChunk(const MetaStack &variableMetas, int64_t chunks, int64_t dim) { RETURN_ERR_IF_NOT( variableMetas.size() == 1, strFormat("Expected one input, got %zu.", variableMetas.size())); const TensorShape &t = variableMetas[0].shape<TensorShape>(); /// Convert dim into positive int64_t inDims = t.size(); dim = at::maybe_wrap_dim(dim, inDims); /// For constant chunk, the size of the last chunk one may smaller than the /// others int64_t c = (t[dim] + chunks - 1) / chunks; int64_t r = t[dim] - c * (chunks - 1); TensorListShape resShapes; for (int i = 0; i < chunks; i++) { TensorShape shape = t; shape[dim] = (i == chunks - 1) ? r : c; resShapes.emplace_back(shape); } TensorListOutput output; output.dtype = variableMetas[0].dtype; output.shape = resShapes; return output; } static inline c10::ScalarType promote_skip_undefined(c10::ScalarType a, c10::ScalarType b) { if (a == c10::ScalarType::Undefined) { return b; } if (b == c10::ScalarType::Undefined) { return a; } return c10::promoteTypes(a, b); } /** * prim::FusedConcat[int dim](Tensor self, Tensor mat1, Tensor mat2, ...) -> * Tensor variableMetas: 0: self, 1: mat1, 2: mat2, ... */ Expected<TensorOutput> ShapeInferenceEngine::fusedConcat(const MetaStack &variableMetas, int64_t dim) { RETURN_ERR_IF_NOT( variableMetas.size() >= 1, strFormat("Expected at least 1 inputs, got %zu.", variableMetas.size())); TensorOutput output; output.dtype = variableMetas[0].dtype; if (variableMetas.size() == 1) { output.shapeOrIntValues = variableMetas[0].shape<TensorShape>(); return output; } TensorShape shape = variableMetas[0].shape<TensorShape>(); /// Convert negtive dimension to positive, then check the dim range. int64_t inDims = shape.size(); dim = at::maybe_wrap_dim(dim, inDims); /// Handle multiple inputs cases for (int i = 1; i < variableMetas.size(); ++i) { const TensorShape &t = variableMetas[i].shape<TensorShape>(); RETURN_ERR_IF_NOT(inDims == t.size(), "All inputs must have the same number of dimensions."); for (int j = 0; j < inDims; j++) { if (j == dim) { shape[dim] += t[dim]; } else { RETURN_ERR_IF_NOT( shape[j] == t[j], strFormat("Sizes of tensors must match except in dimension %zu.", dim)); } } } output.shapeOrIntValues = shape; return output; } /** * prim::FusedBroadcastConcat[int dim](Tensor self, Tensor mat1, Tensor mat2, * ...) -> Tensor variableMetas: 0: self, 1: mat1, 2: mat2, ... */ Expected<TensorOutput> ShapeInferenceEngine::fusedBroadcastConcat(const MetaStack &variableMetas, int64_t dim) { RETURN_ERR_IF_NOT( variableMetas.size() >= 1, strFormat("Expected at least 1 inputs, got %zu.", variableMetas.size())); TensorOutput output; output.shapeOrIntValues = variableMetas[0].shape<TensorShape>(); output.dtype = variableMetas[0].dtype; if (variableMetas.size() == 1) { return output; } /// Convert negtive dimension to positive, then check the dim range. int64_t inDims = output.shapeOrIntValues.size(); dim = at::maybe_wrap_dim(dim, inDims); /// Handle multiple inputs cases for (int i = 1; i < variableMetas.size(); ++i) { const TensorShape &s = variableMetas[i].shape<TensorShape>(); output.dtype = promote_skip_undefined(output.dtype, variableMetas[i].dtype); for (int j = 0; j < inDims; j++) { if (j == dim) { output.shapeOrIntValues[j] += s[j]; } else if (s[j] != 1) { output.shapeOrIntValues[j] = s[j]; } } } return output; } /** * aten::slice(Tensor self, int dim, int start, int end, int step) * variableMetas: 0: self, 1: dim, 2: start, 3: end, 4: step. */ Expected<TensorOutput> ShapeInferenceEngine::slice(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 5, strFormat("Expected 5 inputs, got %zu.", variableMetas.size())); for (int i = 1; i < 5; i++) { RETURN_ERR_IF_NOT(variableMetas[i].intValue.size() == 1, "Expected int in Slice."); } int64_t dim = variableMetas[1].intValue[0]; int64_t start = variableMetas[2].intValue[0]; int64_t end = variableMetas[3].intValue[0]; int64_t step = variableMetas[4].intValue[0]; TensorShape shape = variableMetas[0].shape<TensorShape>(); int64_t inDims = shape[dim]; TensorOutput output; output.dtype = variableMetas[0].dtype; /// Check if the start or end dim out of the input dimension if (start >= inDims || end <= -inDims) { shape[dim] = 0; output.shapeOrIntValues = shape; return output; } /// Convert start dim into positive if (start <= -inDims) { start = 0; } else if (start > -inDims && start < 0) { start += inDims; } /// Convert end dim into positive if (end > inDims) { end = inDims; } else if (end > -inDims && end < 0) { end += inDims; } if (start >= end) { shape[dim] = 0; output.shapeOrIntValues = shape; return output; } shape[dim] = (end - start) / step; if ((end - start) % step) { shape[dim] += 1; } output.shapeOrIntValues = shape; return output; } /** * aten::reshape(Tensor self, int[] shape) -> Tensor * variableMetas: 0: self, 1: shape */ Expected<TensorOutput> ShapeInferenceEngine::reshape(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 2, strFormat("Expected two inputs shapes, got %zu.", variableMetas.size())); int64_t s0 = 1; int64_t s1 = 1; const TensorShape &t = variableMetas[0].shape<TensorShape>(); /// Flag for multiple negative index int64_t negIndex = -1; for (auto i : t) { s0 *= i; } for (int i = 0; i < variableMetas[1].intValue.size(); i++) { s1 *= variableMetas[1].intValue[i]; if (variableMetas[1].intValue[i] == -1) { if (negIndex == -1) { negIndex = i; } else { return MAKE_ERR("Unable to infer undetermined dimension"); } } } RETURN_ERR_IF_NOT(s0 % s1 == 0, "Reshape size is invalid for input size."); TensorShape shape = variableMetas[1].intValue; if (negIndex != -1) { shape[negIndex] = -s0 / s1; } TensorOutput output; output.dtype = variableMetas[0].dtype; output.shapeOrIntValues = shape; return output; } /** * aten::permute(Tensor self, int[] shape) -> Tensor * variableMetas: 0: self, 1: shape */ Expected<TensorOutput> ShapeInferenceEngine::permute(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 2, strFormat("Expected two inputs shapes, got %zu.", variableMetas.size())); const TensorShape &t = variableMetas[0].shape<TensorShape>(); int64_t inDims = t.size(); RETURN_ERR_IF_NOT(inDims == variableMetas[1].intValue.size(), "Shuffle for permute must has the same number of " "dimensions as the input tensor."); TensorShape shape; for (int64_t dim : variableMetas[1].intValue) { RETURN_ERR_IF_NOT(dim >= 0, "Negative shuffle dimensions not supported by Glow yet."); RETURN_ERR_IF_NOT( dim < inDims, "All shuffle dimensions must be less than the rank of the input."); shape.emplace_back(t[dim]); } TensorOutput output; output.dtype = variableMetas[0].dtype; output.shapeOrIntValues = shape; return output; } /** * prim::ListContruct(Scalar/Bool/Tensor self, Scalar/Bool/Tensor v1, * Scalar/Bool/Tensor v2, ...) -> Scalar[]/Bool[]/Tensor[] * variableMetas: 0: self, 1: v1, 2: v2, ... */ Expected<TensorListOutput> ShapeInferenceEngine::listConstruct(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() >= 1, strFormat("Expected at least 1 inputs, got %zu.", variableMetas.size())); TensorListShape listValueOrShape(1); if (variableMetas[0].intValue.size() == 1) { // scalar or bool for (auto ele : variableMetas) { RETURN_ERR_IF_NOT(ele.intValue.size() == 1, "Expected int type input in listConstruct."); listValueOrShape[0].emplace_back(ele.intValue[0]); } } else { // tensor listValueOrShape.resize(variableMetas.size()); for (int i = 0; i < variableMetas.size(); i++) { listValueOrShape[i] = variableMetas[i].shape<TensorShape>(); } } TensorListOutput output; output.dtype = variableMetas[0].dtype; output.shape = listValueOrShape; return output; } /** * glow::fused_stack[dim=1](Tensor self, Tensor mat1, Tensor mat2, ...) * variableMetas: 0: self, 1: mat1, 2: mat2, ... */ Expected<TensorOutput> ShapeInferenceEngine::fusedStack(const MetaStack &variableMetas, int64_t dim) { RETURN_ERR_IF_NOT( variableMetas.size() >= 1, strFormat("Expected at least 1 inputs, got %zu.", variableMetas.size())); TensorOutput output; TensorShape shape = variableMetas[0].shape<TensorShape>(); output.dtype = variableMetas[0].dtype; if (variableMetas.size() == 1) { output.shapeOrIntValues = shape; return output; } int64_t inDims = shape.size(); /// glow::fused_stack will add one more dim dim = at::maybe_wrap_dim(dim, inDims + 1); for (auto eleShape : variableMetas) { RETURN_ERR_IF_NOT(eleShape.shape<TensorShape>() == shape, "All inputs must have same shape"); } shape.insert(shape.begin() + dim, variableMetas.size()); output.shapeOrIntValues = shape; return output; } /** * glow::fused_stack[dim=1](Tensor self, Tensor mat1, Tensor mat2, ...) * variableMetas: 0: self, 1: mat1, 2: mat2, ... */ Expected<TensorOutput> ShapeInferenceEngine::fusedBroadcastStack(const MetaStack &variableMetas, int64_t dim) { RETURN_ERR_IF_NOT( variableMetas.size() >= 1, strFormat("Expected at least 1 inputs, got %zu.", variableMetas.size())); TensorOutput output; output.shapeOrIntValues = variableMetas[0].shape<TensorShape>(); output.dtype = variableMetas[0].dtype; if (variableMetas.size() == 1) { return output; } int64_t inDims = output.shapeOrIntValues.size(); /// Handle multiple inputs cases for (int i = 1; i < variableMetas.size(); ++i) { const TensorShape &s = variableMetas[i].shape<TensorShape>(); output.dtype = promote_skip_undefined(output.dtype, variableMetas[i].dtype); for (int j = 0; j < inDims; j++) { if (s[j] != 1) { output.shapeOrIntValues[j] = s[j]; } } } output.shapeOrIntValues.insert(output.shapeOrIntValues.begin() + dim, variableMetas.size()); return output; } /** * glow::fused_split(Tensor input, int num_splits, int dim) -> Tensor[] */ Expected<TensorListOutput> ShapeInferenceEngine::fusedSplit(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 3, strFormat("Expected Three input, got %zu.", variableMetas.size())); int64_t numSplit = variableMetas[1].intValue[0]; int64_t dim = variableMetas[2].intValue[0]; const auto &inputTensorShape = variableMetas[0].shape<TensorShape>(); /// Convert dim into positive int64_t inDimSize = inputTensorShape.size(); dim = at::maybe_wrap_dim(dim, inDimSize); RETURN_ERR_IF_NOT( inputTensorShape[dim] % numSplit == 0, strFormat("Expected dimension size could be evenly " "divieded by numSplit, got dimSize %long and numSplit %long", inputTensorShape[dim], numSplit)); RETURN_ERR_IF_NOT(numSplit > 0, strFormat("Expected numSplit is larger than 0")); TensorShape elementShape = inputTensorShape; elementShape[dim] = inputTensorShape[dim] / numSplit; TensorListShape resShapes(numSplit, elementShape); TensorListOutput output; output.dtype = variableMetas[0].dtype; output.shape = resShapes; return output; } /** * aten::_embedding_bag(Tensor weight, * Tensor indices, * Tensor offsets, * bool scale_grad_by_freq=False, * int mode=0, * bool sparse=False, * Tensor? per_sample_weights=None, * bool include_last_offset=False) * -> (Tensor, Tensor, Tensor, Tensor) */ /// Since the first output tensor is the result, and we only need the shape of /// result Return the shape of the first tensor only /// In glow, the include_last_offset is always True. Expected<TensorOutput> ShapeInferenceEngine::embeddingBag(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 8, strFormat("Expected 8 inputs, got %zu.", variableMetas.size())); TensorShape shape; const TensorShape &t0 = variableMetas[0].shape<TensorShape>(); const TensorShape &t1 = variableMetas[1].shape<TensorShape>(); const TensorShape &t2 = variableMetas[2].shape<TensorShape>(); if (t1.size() == 1) { RETURN_ERR_IF_NOT(t2.size() == 1, strFormat("Expected 1D offset, got %zu.", t2.size())); shape = {t2[0] - static_cast<int>(((hasEndOffset_) ? 1 : 0)), t0[1]}; } else if (t1.size() == 2) { shape = {t1[0], t0[1]}; } else { return MAKE_ERR("Only support 1D and 2D Input in Embedding bag."); } TensorOutput output; output.shapeOrIntValues = shape; output.dtype = c10::ScalarType::Float; return output; } /** * fb::glow_embedding_bag(Tensor indices, * Tensor offsets, * string? weight_qualname=None, * int num_embeddings, * int embedding_dim, * Tensor? per_sample_weights=None, * bool include_last_offset=True) * -> Tensor */ /// In glow, the include_last_offset is always True. Expected<TensorOutput> ShapeInferenceEngine::glowEmbeddingBag(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 7, strFormat("Expected 7 inputs, got %zu.", variableMetas.size())); TensorShape shape; const auto &indicesShape = variableMetas[0].shape<TensorShape>(); const auto &offsetSahpe = variableMetas[1].shape<TensorShape>(); int64_t embeddingDim = variableMetas[4].intValue[0]; RETURN_ERR_IF_NOT( indicesShape.size() == 1, strFormat("Expected 1D input, got %zu.", indicesShape.size())); RETURN_ERR_IF_NOT( offsetSahpe.size() == 1, strFormat("Expected 1D offset, got %zu.", offsetSahpe.size())); shape = {offsetSahpe[0] - static_cast<int>(((hasEndOffset_) ? 1 : 0)), embeddingDim}; TensorOutput output; output.shapeOrIntValues = shape; output.dtype = c10::ScalarType::Float; return output; } /** * quantized::embedding_bag_byte_rowwise_offsets(Tensor weight, * Tensor indices, * Tensor offsets, * bool scale_grad_by_freq=False, * int mode=0, * bool sparse=False, * Tensor? per_sample_weights=None, * Tensor? compressed_indices_mapping, * bool include_last_offset=True) * -> Tensor; */ /// In glow, the include_last_offset is always True. Expected<TensorOutput> ShapeInferenceEngine::quantizedEmbeddingBagByteRowwiseOffsets( const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 9, strFormat("Expected 9 inputs, got %zu.", variableMetas.size())); const TensorShape &t0 = variableMetas[0].shape<TensorShape>(); const TensorShape &t2 = variableMetas[2].shape<TensorShape>(); /// variableMetas[0].shape[1] - 8 is to account for scale and bias /// 4-byte scale, 4-byte zero_offset TensorShape shape = {t2[0] - static_cast<int>(((hasEndOffset_) ? 1 : 0)), t0[1] - 8}; TensorOutput output; output.shapeOrIntValues = shape; output.dtype = c10::ScalarType::Float; return output; } /** * aten::chuck(Tensor self, int chunks, int dim) -> Tensor[] * refer to: https://pytorch.org/docs/master/generated/torch.chunk */ Expected<TensorListOutput> ShapeInferenceEngine::chunk(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 3, strFormat("Expected one input, got %zu.", variableMetas.size())); const TensorShape &t = variableMetas[0].shape<TensorShape>(); int64_t chunks = variableMetas[1].intValue[0]; int64_t dim = variableMetas[2].intValue[0]; /// Convert dim into positive int64_t inDims = t.size(); dim = at::maybe_wrap_dim(dim, inDims); /// For constant chunk, the size of the last chunk one may smaller than the /// others int64_t c = (t[dim] + chunks - 1) / chunks; int64_t r = t[dim] - c * (chunks - 1); TensorListShape resShapes; for (int i = 0; i < chunks; i++) { TensorShape shape = t; shape[dim] = (i == chunks - 1) ? r : c; resShapes.emplace_back(shape); } TensorListOutput output; output.shape = resShapes; output.dtype = variableMetas[0].dtype; return output; } /* * glow::unpacked_quantized_linear(Tensor a_quant, Tensor w_quant, Tensor " "b, float r_scale, int r_zero_point) -> Tensor"; Input: (N, *, in_features) where * means any number of additional dimensions Weight: (out_features, in_features) Bias: (out_features) Output: (N, *, out_features) */ Expected<TensorOutput> ShapeInferenceEngine::glowUnpackedQuantizedLinear( const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 5, strFormat("Expected 5 inputs,got %zu", variableMetas.size())); TensorShape outputShape; const TensorShape &inputShape = variableMetas[0].shape<TensorShape>(); const int64_t &weightShape = variableMetas[1].shape<TensorShape>()[0]; outputShape = inputShape; // Replace last element with weightShape if (outputShape.size() > 0) { outputShape.back() = weightShape; } TensorOutput output; output.shapeOrIntValues = outputShape; output.dtype = c10::ScalarType::QUInt8; return output; } /* * fb::embedding_bag_4bit_rowwise_offsets(Tensor weight, * Tensor indices, * Tensor offsets, * bool scale_grad_by_freq=False, * int mode=0, * bool sparse=False, * Tensor? per_sample_weights=None, * Tensor? compressed_indices_mapping, * bool include_last_offset=True) * -> Tensor; */ /// In glow, the include_last_offset is always True. Expected<TensorOutput> ShapeInferenceEngine::embeddingBag4BitRowwiseOffsets( const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 9, strFormat("Expected 9 inputs, got %zu.", variableMetas.size())); /// variableMetas[0].shape[1] - 4 is to account for scale and offsets /// Note: 2-byte fp16 scale and 2-byte zero_offset /// *2 which accounts for the packed fp16 weights const TensorShape &weightShape = variableMetas[0].shape<TensorShape>(); const TensorShape &offsetsShape = variableMetas[2].shape<TensorShape>(); TensorOutput output; output.shapeOrIntValues = {offsetsShape[0] - static_cast<int>(((hasEndOffset_) ? 1 : 0)), (weightShape[1] - 4) * 2}; output.dtype = c10::ScalarType::Float; return output; } /** * aten::stack(Tensor[] tensors, int dim) -> Tensor * refer to: https://pytorch.org/docs/stable/generated/torch.stack */ Expected<TensorOutput> ShapeInferenceEngine::stack(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 2, strFormat("Expected 2 input, got %zu.", variableMetas.size())); const TensorListShape &shapes = variableMetas[0].shape<TensorListShape>(); TensorShape shape = shapes[0]; // Convert negtive dimension to positive, then check the dim range. int64_t dim = variableMetas[1].intValue[0]; int64_t inDims = shape.size(); dim = at::maybe_wrap_dim(dim, inDims); // Verify the shapes of all input tensors. for (int i = 1; i < shapes.size(); i++) { RETURN_ERR_IF_NOT(shape == shapes[i], "All tensors need to be of the same shape."); } shape.insert(shape.begin() + dim, shapes.size()); TensorOutput output; output.shapeOrIntValues = shape; output.dtype = variableMetas[0].dtype; return output; } /** * prim::ListUnpack(Tensor[] tensors) -> Tensor, ..., Tensor */ Expected<TensorListOutput> ShapeInferenceEngine::listUnpack(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 1, strFormat("Expected 1 input, got %zu.", variableMetas.size())); std::vector<TensorShape> shapes; const TensorListShape &t = variableMetas[0].shape<TensorListShape>(); for (int i = 0; i < t.size(); i++) { shapes.emplace_back(t[i]); } TensorListOutput output; output.shape = shapes; output.dtype = variableMetas[0].dtype; return output; } /* * aten::to(Tensor input, int dtype, bool non_block, bool copy, * MemoryFormat? memory_format) -> Tensor */ Expected<TensorOutput> ShapeInferenceEngine::to(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 4 || variableMetas.size() == 5, strFormat("Expected 4 or 5 input, got %zu.", variableMetas.size())); const TensorShape &t = variableMetas[0].shape<TensorShape>(); // input shape int32_t dtype = variableMetas[1].intValue[0]; TensorOutput output; output.shapeOrIntValues = t; output.dtype = static_cast<c10::ScalarType>(dtype); return output; } /* * fb::lengths_to_offsets(Tensor lengths, bool include_last_offset) -> Tensor, */ Expected<TensorOutput> ShapeInferenceEngine::lengthsToOffsets(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 2, strFormat("Expected 2 input, got %zu.", variableMetas.size())); const TensorShape &t = variableMetas[0].shape<TensorShape>(); // input shape RETURN_ERR_IF_NOT(t.size() == 1, strFormat("Expected input dim is 1, got %zu.", t.size())); bool include_last_offset = variableMetas[1].intValue[0]; RETURN_ERR_IF_NOT(include_last_offset == true, strFormat("Expected include_last_offset is true, got %d.", include_last_offset)); TensorOutput output; output.shapeOrIntValues = t; output.shapeOrIntValues[0] += 1; // include last offset output.dtype = variableMetas[0].dtype; return output; } /* * prim::dtype(Tensor input) -> Int, */ Expected<TensorOutput> ShapeInferenceEngine::primDtype(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 1, strFormat("Expected 1 input, got %zu.", variableMetas.size())); int dtype = static_cast<int>(variableMetas[0].dtype); TensorOutput output; output.shapeOrIntValues = {dtype}; output.dtype = c10::ScalarType::Int; return output; } /* * fb::fast_gather(Tensor input, Tensor indices) -> Tensor */ Expected<TensorOutput> ShapeInferenceEngine::fastGather(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 2, strFormat("Expected 2 input, got %zu.", variableMetas.size())); const auto &t0 = variableMetas[0].shape<TensorShape>(); const auto &t1 = variableMetas[1].shape<TensorShape>(); // suppose t0 = [d1, d2, ..., dm], t1 = [D1, D2, ..., Dn] // the result shape will be [D1, D2, ..., Dn, d2, ..., dm] TensorShape shape = t1; for (int i = 1; i < t0.size(); i++) { shape.emplace_back(t0[i]); } TensorOutput output; output.shapeOrIntValues = shape; output.dtype = variableMetas[0].dtype; return output; } /* * fb::lengths_range(Tensor input, int[]? shape) -> Int, * e.g. max_feature_length = 200, max_batch_size = 32 * input: [2, 3] * original output: [0, 1, 0, 1, 2] * output after update: [0, 1, ..., 200, ] * 32 */ Expected<TensorOutput> ShapeInferenceEngine::lengthsRange(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 2, strFormat("Expected 2 inputs, got %zu.", variableMetas.size())); RETURN_ERR_IF_NOT( FLAGS_max_batch_size > 0, strFormat("Expected max_batch_size > 0, got %d.", FLAGS_max_batch_size)); RETURN_ERR_IF_NOT(FLAGS_max_batch_size >= variableMetas[0].shape<TensorShape>()[0], strFormat("Expected max_batch_size > input tensor length, " "got max_batch_size %d, input tensor length %zu.", FLAGS_max_batch_size, variableMetas[0].shape<TensorShape>()[0])); RETURN_ERR_IF_NOT(FLAGS_max_feature_length > 0, strFormat("Expected max_feature_length > 0, got %d.", FLAGS_max_feature_length)); TensorOutput output; output.shapeOrIntValues = {FLAGS_max_batch_size * FLAGS_max_feature_length}; output.dtype = variableMetas[0].dtype; return output; } /* * quantize_per_tensor(Tensor self, float scale, int zero_point, ScalarType * dtype) -> Tensor */ Expected<TensorOutput> ShapeInferenceEngine::quantizePerTensor(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 4, strFormat("Expected 4 inputs, got %zu.", variableMetas.size())); const auto &inputShape = variableMetas[0].shape<TensorShape>(); const int convertedTypeValue = variableMetas[3].intValue[0]; TensorOutput output; output.shapeOrIntValues = inputShape; output.dtype = static_cast<c10::ScalarType>(convertedTypeValue); return output; } /* * aten::dequantize(Tensor qtensor) -> Tensor */ Expected<TensorOutput> ShapeInferenceEngine::dequantize(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 1, strFormat("Expected 1 inputs, got %zu.", variableMetas.size())); const auto &inputShape = variableMetas[0].shape<TensorShape>(); TensorOutput output; output.shapeOrIntValues = inputShape; output.dtype = c10::ScalarType::Float; return output; } /* * quantized::mul(%a_quant, %b_quant, %scale, %zero_point) -> Tensor */ Expected<TensorOutput> ShapeInferenceEngine::quantizedMul(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 4, strFormat("Expected 4 inputs, got %zu.", variableMetas.size())); const auto &inputShape = variableMetas[0].shape<TensorShape>(); const auto &weightShape = variableMetas[1].shape<TensorShape>(); RETURN_ERR_IF_NOT(inputShape.size() > 0, "Expected input shape size is larger than 0"); RETURN_ERR_IF_NOT(weightShape.size() == 2, "Expected weight is two dimensional tension"); RETURN_ERR_IF_NOT( inputShape.back() == weightShape[1], "Expected the last dimension matches between input and weight"); TensorOutput output; output.shapeOrIntValues = inputShape; output.shapeOrIntValues.back() = weightShape[0]; output.dtype = variableMetas[0].dtype; return output; } /* * aten::matmul(Tensor input, Tensor other) -> Tensor */ Expected<TensorOutput> ShapeInferenceEngine::matmul(const MetaStack &variableMetas) { RETURN_ERR_IF_NOT( variableMetas.size() == 2, strFormat("Expected 2 inputs, got %zu.", variableMetas.size())); const auto &inputOneShape = variableMetas[0].shape<TensorShape>(); const auto &inputTwoShape = variableMetas[1].shape<TensorShape>(); RETURN_ERR_IF_NOT(inputOneShape.size() == 3, strFormat("Only support input as 3-d tensor, got %zu.", inputOneShape.size())); RETURN_ERR_IF_NOT(inputTwoShape.size() == 3, strFormat("Only support input as 3-d tensor, got %zu.", inputTwoShape.size())); RETURN_ERR_IF_NOT(inputOneShape[2] == inputTwoShape[1], "The 3rd dim of first input should be the same as 2nd dim " "of second input."); TensorShape shapes; // TODO hwwang T81654300, add support for inputs with differnt dimensions. shapes.emplace_back(std::max(inputOneShape[0], inputTwoShape[0])); shapes.emplace_back(inputOneShape[1]); shapes.emplace_back(inputTwoShape[2]); TensorOutput output; output.shapeOrIntValues = shapes; output.dtype = variableMetas[0].dtype; return output; } } // namespace glow
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
b5ef985e1aed03b91cce651ae8759440b1fecdc9
66d8fe190115560dedddc237767a8414cf86e5b7
/131044021_HW4/main.cpp
677b6156e7baefa132c3d42027d02ce95628ef0e
[]
no_license
busrarslan/Object_Oriented_Programming_Hws
53880c04ef507a9ce3edfe6b8b5b2eb42ceb2108
8debbc93e47a529533b8a67eaecbde00938e8b95
refs/heads/master
2021-01-01T16:32:43.062426
2017-07-20T16:22:43
2017-07-20T16:22:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,105
cpp
/* * File: main.cpp * Author: Busra Arslan 131044021 * HW4 * Description: * CPU, CPUProgram , Memory ve Computer classlarinda istenilen tum fonksiyonlar yazildi. * Constructorlar kullanildi. * Private olarak kullanilan tum degerlere setter ve getter yazildi. * Sorting kodu yazilmisti. Test edildi. * option 0 halt oldugundaki registerlarin son halini ekrana basar. * option 1 tüm satirlardaki register degisimlerini ve son halini ekrana basar. * option 2 hem tum instructionlari ekrana basar hemde her satir icin memoryi ekrana basar * memorynin son halinde de verilen sayilarin kucukten buyuge siralandigi gorulur. * Verilen testler disinda kendi yazdigim testleri comment icine aldim. * Main tamamen sizin istediginiz gibidir. getLine(0) >> 0'dan baslamaktadir. */ #include <iostream> #include <stdlib.h> #include <fstream> //dosya okuma kutuphanesi #include <string> //cpp string kutuphanesi #include "requiredIncs.h" using namespace std; ///////////////////////////////////MAIN/////////////////////////////// int main(int argc, char** argv){ if (argc != 3) { cout<< "Lutfen filename ve option giriniz: " << endl; exit(0); } ////////////////////////////////////////////////////////////////////////// //command line parameters const char* filename = argv[1]; int option = atoi(argv[2]); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Testing class Memory cout << "Testing class Memory" << endl; cout << "////////////////////////////////////////////////////////////////////////// " << endl; Memory myMemory(option); //initialization memory //index, value myMemory.setMem(0, 100); cout << myMemory.getMem(0) << endl; //should print in a way that similar to this: //Memory Values: //[0] -> 100 //[1] -> 0 //[2] -> 0 //. //. //[49] -> 0 myMemory.printAll(); cout << "////////////////////////////////////////////////////////////////////////// " << endl; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Testing class CPU cout << "Testing class CPU" << endl; cout << "////////////////////////////////////////////////////////////////////////// " << endl; CPU myCPU(option); myCPU.execute("MOV #0, R1", myMemory); myCPU.execute("MOV R1, #1", myMemory); // //myTest // myCPU.execute("MOV #0, R3", myMemory); // myCPU.execute("MOV R1, #5", myMemory); // myCPU.execute("ADD R4, R1", myMemory); // myCPU.execute("MOV R4, #7", myMemory); // myCPU.execute("ADD R3, #5", myMemory); //should print in a way that similar to this: //CPU Register Values: //[0] -> 100 //[1] -> 0 //[2] -> 0 //[3] -> 0 //[4] -> 0 myCPU.print(); //should print in a way that similar to this: //Memory Values: //[0] -> 100 //[1] -> 100 //[2] -> 0 //. //. //[49] -> 0 myMemory.printAll(); cout << "////////////////////////////////////////////////////////////////////////// " << endl; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Testing class CPUProgram cout << "Testing class CPUProgram " << endl; cout << "////////////////////////////////////////////////////////////////////////// " << endl; CPUProgram myCPUProgram(option); myCPUProgram.ReadFile(filename); //ilk satirim 1 den basladigi icin bu kismi boye duzenledim //1 den basladigi icinde -1 yazmaya gerek olmadi. cout << myCPUProgram.getLine(0) << endl; cout << myCPUProgram.getLine(myCPUProgram.size() -1) << endl; cout << "////////////////////////////////////////////////////////////////////////// " << endl; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Testing class Computer cout << "Testing class Computer " << endl; cout << "////////////////////////////////////////////////////////////////////////// " << endl; Computer myComputer1(myCPU, myCPUProgram, myMemory, option); Computer myComputer2(option); myComputer2.setCPU( myComputer1.getCPU()); myComputer2.setCPUProgram(myComputer1.getCPUProgram()); myComputer2.setMemory(myComputer1.getMemory()); myComputer2.execute(); cout << "////////////////////////////////////////////////////////////////////////// " << endl; ////////////////////////////////////////////////////////////////////////// return 0; }
[ "noreply@github.com" ]
busrarslan.noreply@github.com
c366d104c6b976bf29079f5c7f049683060b5ff8
c7bb17447090c359eb9ce240c58189bc934a19a2
/ouzel/graphics/opengl/windows/OGLRenderDeviceWin.cpp
5738a13f29f057cc77f77f5cfcfb51010837ff60
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
jaccen2007/ouzel
f06ee604c250d19f6ab23e4414b097ebbbd1e013
6981f79f6ddf5fb93d4cacf6e6357383a0cf7d2f
refs/heads/master
2022-01-08T15:04:10.811120
2019-07-19T12:35:16
2019-07-19T12:35:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,409
cpp
// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #include "core/Setup.h" #if defined(_WIN32) && OUZEL_COMPILE_OPENGL #include <system_error> #include "GL/glcorearb.h" #include "GL/glext.h" #include "GL/wglext.h" #include "OGLRenderDeviceWin.hpp" #include "core/Engine.hpp" #include "core/Window.hpp" #include "core/windows/NativeWindowWin.hpp" #include "utils/Log.hpp" static constexpr LPCWSTR TEMP_WINDOW_CLASS_NAME = L"TempWindow"; static LRESULT CALLBACK windowProc(HWND window, UINT msg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(window, msg, wParam, lParam); } namespace ouzel { namespace graphics { namespace opengl { class TempContext final { public: TempContext() { HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); WNDCLASSW wc; wc.style = CS_OWNDC; wc.lpfnWndProc = windowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = instance; wc.hIcon = 0; wc.hCursor = 0; wc.hbrBackground = 0; wc.lpszMenuName = nullptr; wc.lpszClassName = TEMP_WINDOW_CLASS_NAME; if (!(windowClass = RegisterClassW(&wc))) throw std::system_error(GetLastError(), std::system_category(), "Failed to register window class"); if (!(window = CreateWindowW(TEMP_WINDOW_CLASS_NAME, L"TempWindow", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, instance, 0))) throw std::system_error(GetLastError(), std::system_category(), "Failed to create window"); if (!(deviceContext = GetDC(window))) throw std::runtime_error("Failed to get device context"); PIXELFORMATDESCRIPTOR pixelFormatDesc; pixelFormatDesc.nSize = sizeof(pixelFormatDesc); pixelFormatDesc.nVersion = 1; pixelFormatDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pixelFormatDesc.iPixelType = PFD_TYPE_RGBA; pixelFormatDesc.cColorBits = 24; pixelFormatDesc.cRedBits = 0; pixelFormatDesc.cRedShift = 0; pixelFormatDesc.cGreenBits = 0; pixelFormatDesc.cGreenShift = 0; pixelFormatDesc.cBlueBits = 0; pixelFormatDesc.cBlueShift = 0; pixelFormatDesc.cAlphaBits = 0; pixelFormatDesc.cAlphaShift = 0; pixelFormatDesc.cAccumBits = 0; pixelFormatDesc.cAccumRedBits = 0; pixelFormatDesc.cAccumGreenBits = 0; pixelFormatDesc.cAccumBlueBits = 0; pixelFormatDesc.cAccumAlphaBits = 0; pixelFormatDesc.cDepthBits = 0; pixelFormatDesc.cStencilBits = 0; pixelFormatDesc.cAuxBuffers = 0; pixelFormatDesc.iLayerType = PFD_MAIN_PLANE; pixelFormatDesc.bReserved = 0; pixelFormatDesc.dwLayerMask = 0; pixelFormatDesc.dwVisibleMask = 0; pixelFormatDesc.dwDamageMask = 0; int pixelFormat = ChoosePixelFormat(deviceContext, &pixelFormatDesc); if (!pixelFormat) throw std::system_error(GetLastError(), std::system_category(), "Failed to choose pixel format"); if (!SetPixelFormat(deviceContext, pixelFormat, &pixelFormatDesc)) throw std::system_error(GetLastError(), std::system_category(), "Failed to set pixel format"); if (!(renderContext = wglCreateContext(deviceContext))) throw std::system_error(GetLastError(), std::system_category(), "Failed to create OpenGL context"); if (!wglMakeCurrent(deviceContext, renderContext)) throw std::system_error(GetLastError(), std::system_category(), "Failed to set current OpenGL context"); } ~TempContext() { if (renderContext) { wglMakeCurrent(deviceContext, nullptr); wglDeleteContext(renderContext); } if (window) { if (deviceContext) ReleaseDC(window, deviceContext); DestroyWindow(window); } if (windowClass) UnregisterClassW(TEMP_WINDOW_CLASS_NAME, GetModuleHandleW(nullptr)); } TempContext(const TempContext&) = delete; TempContext& operator=(const TempContext&) = delete; TempContext(TempContext&&) = delete; TempContext& operator=(TempContext&&) = delete; private: ATOM windowClass = 0; HWND window = 0; HDC deviceContext = 0; HGLRC renderContext = 0; }; RenderDeviceWin::RenderDeviceWin(const std::function<void(const Event&)>& initCallback): RenderDevice(initCallback) { } RenderDeviceWin::~RenderDeviceWin() { running = false; CommandBuffer commandBuffer; commandBuffer.pushCommand(std::make_unique<PresentCommand>()); submitCommandBuffer(std::move(commandBuffer)); if (renderThread.isJoinable()) renderThread.join(); if (renderContext) { wglMakeCurrent(deviceContext, nullptr); wglDeleteContext(renderContext); } if (deviceContext) { NativeWindowWin* windowWin = static_cast<NativeWindowWin*>(window->getNativeWindow()); ReleaseDC(windowWin->getNativeWindow(), deviceContext); } } void RenderDeviceWin::init(Window* newWindow, const Size2U& newSize, uint32_t newSampleCount, SamplerFilter newTextureFilter, uint32_t newMaxAnisotropy, bool newSrgb, bool newVerticalSync, bool newDepth, bool newStencil, bool newDebugRenderer) { TempContext tempContext; NativeWindowWin* windowWin = static_cast<NativeWindowWin*>(newWindow->getNativeWindow()); deviceContext = GetDC(windowWin->getNativeWindow()); if (!deviceContext) throw std::runtime_error("Failed to get window's device context"); std::vector<std::string> extensions; if (PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringProc = reinterpret_cast<PFNWGLGETEXTENSIONSSTRINGARBPROC>(wglGetProcAddress("wglGetExtensionsStringARB"))) { if (const char* extensionsPtr = wglGetExtensionsStringProc(deviceContext)) extensions = explodeString(std::string(reinterpret_cast<const char*>(extensionsPtr)), ' '); engine->log(Log::Level::All) << "Supported WGL extensions: " << extensions; } PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatProc = nullptr; PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsProc = nullptr; for (const std::string& extension : extensions) { if (extension == "WGL_ARB_pixel_format") wglChoosePixelFormatProc = reinterpret_cast<PFNWGLCHOOSEPIXELFORMATARBPROC>(wglGetProcAddress("wglChoosePixelFormatARB")); else if (extension == "WGL_ARB_create_context") wglCreateContextAttribsProc = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>(wglGetProcAddress("wglCreateContextAttribsARB")); } int pixelFormat = 0; PIXELFORMATDESCRIPTOR pixelFormatDesc; pixelFormatDesc.nSize = sizeof(pixelFormatDesc); pixelFormatDesc.nVersion = 1; pixelFormatDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_GENERIC_ACCELERATED; pixelFormatDesc.iPixelType = PFD_TYPE_RGBA; pixelFormatDesc.cColorBits = 24; pixelFormatDesc.cRedBits = 0; pixelFormatDesc.cRedShift = 0; pixelFormatDesc.cGreenBits = 0; pixelFormatDesc.cGreenShift = 0; pixelFormatDesc.cBlueBits = 0; pixelFormatDesc.cBlueShift = 0; pixelFormatDesc.cAlphaBits = 0; pixelFormatDesc.cAlphaShift = 0; pixelFormatDesc.cAccumBits = 0; pixelFormatDesc.cAccumRedBits = 0; pixelFormatDesc.cAccumGreenBits = 0; pixelFormatDesc.cAccumBlueBits = 0; pixelFormatDesc.cAccumAlphaBits = 0; pixelFormatDesc.cDepthBits = newDepth ? 24 : 0; pixelFormatDesc.cStencilBits = 0; pixelFormatDesc.cAuxBuffers = 0; pixelFormatDesc.iLayerType = PFD_MAIN_PLANE; pixelFormatDesc.bReserved = 0; pixelFormatDesc.dwLayerMask = 0; pixelFormatDesc.dwVisibleMask = 0; pixelFormatDesc.dwDamageMask = 0; if (wglChoosePixelFormatProc) { const int attributeList[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 24, WGL_ALPHA_BITS_ARB, 8, WGL_DEPTH_BITS_ARB, newDepth ? 24 : 0, WGL_STENCIL_BITS_ARB, newStencil ? 8 : 0, WGL_SAMPLE_BUFFERS_ARB, newSampleCount > 0 ? 1 : 0, WGL_SAMPLES_ARB, static_cast<int>(newSampleCount), WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, newSrgb ? 1 : 0, 0, }; UINT numFormats; if (!wglChoosePixelFormatProc(deviceContext, attributeList, nullptr, 1, &pixelFormat, &numFormats)) throw std::system_error(GetLastError(), std::system_category(), "Failed to choose pixel format"); } else { pixelFormat = ChoosePixelFormat(deviceContext, &pixelFormatDesc); if (!pixelFormat) throw std::system_error(GetLastError(), std::system_category(), "Failed to choose pixel format"); } if (!SetPixelFormat(deviceContext, pixelFormat, &pixelFormatDesc)) throw std::system_error(GetLastError(), std::system_category(), "Failed to set pixel format"); if (wglCreateContextAttribsProc) { for (int openGLVersion = 4; openGLVersion >= 2; --openGLVersion) { std::vector<int> contextAttribs = { WGL_CONTEXT_MAJOR_VERSION_ARB, openGLVersion, WGL_CONTEXT_MINOR_VERSION_ARB, 0, }; if (newDebugRenderer) { contextAttribs.push_back(WGL_CONTEXT_FLAGS_ARB); contextAttribs.push_back(WGL_CONTEXT_DEBUG_BIT_ARB); } contextAttribs.push_back(0); renderContext = wglCreateContextAttribsProc(deviceContext, 0, contextAttribs.data()); if (renderContext) { engine->log(Log::Level::Info) << "OpenGL " << openGLVersion << " context created"; break; } } } else renderContext = wglCreateContext(deviceContext); if (!renderContext) throw std::runtime_error("Failed to create OpenGL context"); if (!wglMakeCurrent(deviceContext, renderContext)) throw std::system_error(GetLastError(), std::system_category(), "Failed to set current OpenGL context"); RenderDevice::init(newWindow, newSize, newSampleCount, newTextureFilter, newMaxAnisotropy, newSrgb, newVerticalSync, newDepth, newStencil, newDebugRenderer); if (!wglMakeCurrent(deviceContext, nullptr)) throw std::system_error(GetLastError(), std::system_category(), "Failed to unset OpenGL context"); running = true; renderThread = Thread(&RenderDeviceWin::renderMain, this); } void RenderDeviceWin::present() { if (!SwapBuffers(deviceContext)) throw std::system_error(GetLastError(), std::system_category(), "Failed to swap buffers"); } void RenderDeviceWin::renderMain() { Thread::setCurrentThreadName("Render"); if (!wglMakeCurrent(deviceContext, renderContext)) throw std::system_error(GetLastError(), std::system_category(), "Failed to set current OpenGL context"); while (running) { try { process(); } catch (const std::exception& e) { engine->log(Log::Level::Error) << e.what(); } } } } // namespace opengl } // namespace graphics } // namespace ouzel #endif
[ "elviss@elviss.lv" ]
elviss@elviss.lv
d5f2a5d1910fe26b6d6912bfd5cc77264bbc6e23
b3840f19a2fc41a5634420219ec3d8ddfc9c1dcc
/UI Source code/ArduEye_UI/main.cpp
c011afcc7ea468f3a0ef3b488f4d894e23cbf471
[]
no_license
centeye/ArduEye-Serial-UI
bf8cd6fb8dc06c68331e09ad91405b7839da5d26
c0232c05dc959b77d454306f101cc644a7044761
refs/heads/master
2021-01-01T05:53:06.524780
2011-10-26T01:07:05
2011-10-26T01:07:05
2,240,247
1
1
null
null
null
null
UTF-8
C++
false
false
328
cpp
/* Main.cpp - main event loop. This function is a generic Qt UI event loop */ #include <QtGui/QApplication> #include "ArduEye_UI.h" #include <QtDebug> int main(int argc, char *argv[]) { QByteArray Dat, OutDat; QApplication a(argc, argv); ArduEyeUI w; w.show(); return a.exec(); }
[ "alison.nj.leonard@gmail.com" ]
alison.nj.leonard@gmail.com
a72e38742cedeac9f5ef4066b5c7d979e03d671a
0a3b180c27b93f54e856758f9ea898498bfb86cf
/src/uvloop.cpp
b64cf4e4de406a261bd8ea628f96094188f15c8d
[]
no_license
AmyrAhmady/samp-node
b009a7ff3d63d352c0aee349b746a8ab39b90a4d
671643925c824c4be1d84f722ce4a0fcc4551814
refs/heads/master
2022-01-16T19:30:11.513487
2021-12-28T08:33:25
2021-12-28T08:33:25
241,878,597
83
17
null
2021-12-02T22:50:05
2020-02-20T12:28:52
C++
UTF-8
C++
false
false
376
cpp
#include "uvloop.hpp" UvLoop::UvLoop(const std::string& loopTag) : m_loopName(loopTag) { uv_loop_init(&m_loop); m_loop.data = this; uv_run(&m_loop, UV_RUN_NOWAIT); } UvLoop::~UvLoop() { uv_async_t async; uv_stop(&m_loop); uv_async_init(&m_loop, &async, [](uv_async_t*) { }); uv_async_send(&async); uv_close(reinterpret_cast<uv_handle_t*>(&async), nullptr); }
[ "amirabgta@gmail.com" ]
amirabgta@gmail.com
406241cbaf0bbd5572116c7a1141b90af11e8556
577e4132f254be45d8c406677385723042be817e
/src/entity.hpp
9d7df73affe2db7002ec2ea53404cf5f9f534457
[]
no_license
shrapx/ludum_dare_32
7004eb5828434a7761b30387957cf8ae42467861
1d79661ed0b2aeb8253a426c4d588a9fbe52c465
refs/heads/master
2020-04-05T02:18:25.834639
2015-04-20T16:40:57
2015-04-20T16:40:57
34,112,487
0
0
null
null
null
null
UTF-8
C++
false
false
448
hpp
#ifndef _ENTITY_HPP_ #define _ENTITY_HPP_ using namespace std; class EntityBase : public sf::Sprite { public: sf::Vector2f tile_position; sf::Vector2f tile_unit_pos; sf::Vector2f tile_normal; sf::Vector2f water_vector; float water_age=0; float water_y; float tile_angle; int anim_frames = 0; int rotate_frames = 0; float walk_anim_marker; float water; float water_max; }; class Entity : public EntityBase { }; #endif
[ "shrapx@gmail.com" ]
shrapx@gmail.com
71e3fffb55ccb1fa5acbd6e28a190caca16e942d
b883e65d19362c6db8b593e0631a7e4a5f29776e
/server.h
2e62064fa7e6f19974299a97e0dc4a101f12e859
[]
no_license
kpa0art/primetech
4835451683ec270d0c1e8507c4917a872ab271d7
7ab1309e4e286fe36991be047248c24bb37b072a
refs/heads/main
2023-02-20T13:15:48.753043
2021-01-12T00:51:39
2021-01-12T00:51:39
324,782,678
0
0
null
null
null
null
UTF-8
C++
false
false
1,333
h
#pragma once #include <string> #include <netdb.h> #include <stdexcept> #include <cstring> #include <iostream> #include <unistd.h> #include <memory> #include <vector> #include <map> #include <arpa/inet.h> #include "package.h" #include "file_builder.h" #include "logger.h" //#define DEBUG using namespace std::chrono; class Server { public: Server(const std::string& addr, int port, const std::string &dir, Logger& logger); ~Server(); int get_socket() const; int get_port() const; std::string get_directory() const; std::string get_address() const; void work(); private: int m_socket; std::string m_dir; int m_port; std::string m_addr; Logger& m_logger; addrinfo *m_addrinfo; std::map<std::string, time_point<system_clock>> m_keys_black_list; std::map<std::string, std::unique_ptr<FileBuilder>> m_fb_store; std::vector<std::unique_ptr<Package>> m_pkg_store; void clear_file_builders_store_by_timeout(); void clear_keys_black_list_by_timeout(); bool allow_key(const std::string& key); FileBuilder* find_or_create_file_builder(const std::string& key); int timed_recvfrom(char *buf, int buf_len, sockaddr_in &addr, socklen_t &addr_len, int max_waiting_time_ms); int process_package(Package& package, const std::string& key); };
[ "kpa0art.work@gmail.com" ]
kpa0art.work@gmail.com
85d6784a75a96da84d40ecf527a4a610b1fac96a
de90599856ce6994cce2f760947e610c363b9f1f
/Data Structures And Algorithms/Algorithms/Sorting/Insertion Sort/Src/Main.cpp
4ae426ec35e9d5973613309730b56ee3e28014c4
[]
no_license
CarMoli/CPlusPlusProgramming
eb72c819d09d2fec0cbafbf5b7db493d9ef1f646
154b7d03a521b8efbdc8401077c7fae42b45cf69
refs/heads/master
2023-04-19T19:56:12.038271
2021-04-28T03:17:47
2021-04-28T03:17:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,679
cpp
#include <iostream> class InsertionSort { protected: int arr[5]; public: InsertionSort(); void inputInertionSort(); virtual void insertionSortConditionAscending(); virtual void insertionSortConditionDescending(); }; InsertionSort::InsertionSort() { arr[5] = 0; } void InsertionSort::inputInertionSort() { std::cout << "Enter 5 random numbers: "; for (size_t i = 0; i < 5; i++) { std::cin >> arr[i]; } } void InsertionSort::insertionSortConditionAscending() { int a = 0, key; for (int i = 1; i < 5; i++) { key = arr[i]; //Picking the elements a = (i - 1); while ((a >= 0) && (arr[a] > key)) { arr[a + 1] = arr[a]; a--; } arr[a + 1] = key; } std::cout << "Sorting values ascending: "; for (size_t i = 0; i < 5; i++) { std::cout << arr[i] << " "; } std::cout << "\n"; } void InsertionSort::insertionSortConditionDescending() { int b = 0, key; for (int i = 1; i < 5; i++) { key = arr[i]; b = (i - 1); while ((b >= 0) && (arr[b] < key)) { arr[b + 1] = arr[b]; b--; } arr[b + 1] = key; } std::cout << "Sorting values descending: "; for (size_t i = 0; i < 5; i++) { std::cout << arr[i] << " "; } } int main(int argc, char const *argv[]) { InsertionSort *IS = new InsertionSort(); IS->inputInertionSort(); IS->insertionSortConditionAscending(); IS->insertionSortConditionDescending(); return 0; }
[ "69786531+BillyFrcs@users.noreply.github.com" ]
69786531+BillyFrcs@users.noreply.github.com
c09f6363ef8961f36f23fe375501fe36658f21c4
1c589bc1ed95b7459c5bb1550b0b8aee4ad53b1f
/Lab 5/source/BaseGame.cpp
8a6260018a4ba72bf47adeaa4fabaf8cb4d54f29
[]
no_license
p12194892/robot_assignment
d9df0766b35ced561a3fa179cb67482319002c4b
8a5fd43deaa6de9d2786f1440d8cf3fcc9efc1c9
refs/heads/master
2021-06-08T21:36:26.186256
2017-01-09T13:52:45
2017-01-09T13:52:45
74,667,585
0
0
null
null
null
null
UTF-8
C++
false
false
12,810
cpp
#include "BaseGame.h" #include <vector> #include <glm\glm.hpp> #include <glm\gtc\type_ptr.hpp> #include "CameraComponent.h" #include <glm\glm.hpp> #include <glm\gtc\matrix_transform.hpp> #include <glm\gtc\type_ptr.hpp> #include <glm/gtx/transform.hpp> #include "tinyxml2.h" #include <iostream> using namespace tinyxml2; //!< Default constructor BaseGame::BaseGame() {} //!< Creates objects to be used in the simulation void BaseGame::createObjects() { std::cout << "Loading Objects into the scene" << std::endl << std::endl; //Creating box m_box = new MeshComponent("Box Model"); m_read->resetData(); m_read->ReadFile("resources/obj/cube.obj"); m_box->setVertrices(m_read->getVertexPoints()); m_box->setIndices(m_read->getIndices()); m_box->setNormals(m_read->getNormals()); m_box->setStartPos(glm::vec3(20.0, -37.0, 0.0)); m_box->Load(m_programHandle); m_box->translateModelMat(m_box->getStartPos()); m_box->scaleModelMat(glm::vec3(3)); //Creating man m_man = new MeshComponent("Man Model"); m_read->resetData(); m_read->ReadFile("resources/obj/man.obj"); m_man->setVertrices(m_read->getVertexPoints()); m_man->setIndices(m_read->getIndices()); m_man->setNormals(m_read->getNormals()); m_man->setStartPos(glm::vec3(20.0, -34.0, 0.0)); m_man->Load(m_programHandle); m_man->translateModelMat(m_man->getStartPos()); m_man->scaleModelMat(glm::vec3(4)); //Creating cone m_cone = new MeshComponent("Cone Model"); m_read->resetData(); m_read->ReadFile("resources/obj/cone.obj"); m_cone->setVertrices(m_read->getVertexPoints()); m_cone->setIndices(m_read->getIndices()); m_cone->setNormals(m_read->getNormals()); m_cone->setStartPos(glm::vec3(-20.0, -40.0, -30.0)); m_cone->Load(m_programHandle); m_cone->translateModelMat(m_cone->getStartPos()); m_cone->scaleModelMat(glm::vec3(2)); //Creating character m_character = new MeshComponent("BB8 Model"); m_read->resetData(); m_read->ReadFile("resources/obj/bb8.obj"); m_character->setVertrices(m_read->getVertexPoints()); m_character->setIndices(m_read->getIndices()); m_character->setNormals(m_read->getNormals()); m_character->setStartPos(glm::vec3(0.0, -40.0, -20.0)); m_character->Load(m_programHandle); m_character->translateModelMat(m_character->getStartPos()); m_character->scaleModelMat(glm::vec3(0.0625)); //Creating garlic press m_garlicpress = new MeshComponent("Garlic Press Model"); m_read->resetData(); m_read->ReadFile("resources/obj/garlicpress.obj"); m_garlicpress->setVertrices(m_read->getVertexPoints()); m_garlicpress->setIndices(m_read->getIndices()); m_garlicpress->setNormals(m_read->getNormals()); m_garlicpress->setStartPos(glm::vec3(-20.0, -34.0, 0.0)); m_garlicpress->Load(m_programHandle); m_garlicpress->translateModelMat(m_garlicpress->getStartPos()); m_garlicpress->scaleModelMat(glm::vec3(0.5)); //Making the splash screen gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bSplashScreenState"), true); m_splashScreenComponent = new UIComponent(m_programHandle); m_splashScreenComponent->setTextureUnit(0); m_splashScreenComponent->loadTexture("resources/shader/sign.png", "tex"); m_splashScreenComponent->translateModelMat(glm::vec3(-2.0, -27.0, 18.0)); m_splashScreenComponent->scaleModelMat(glm::vec3(13)); //Making the menu screen gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bMenu"), false); m_menuScreenComponent = new UIComponent(m_programHandle); m_menuScreenComponent->setTextureUnit(1); m_menuScreenComponent->loadTexture("resources/shader/menu.png", "menutexture"); m_menuScreenComponent->translateModelMat(glm::vec3(-2.0, -27.0, 18.0)); m_menuScreenComponent->scaleModelMat(glm::vec3(13)); //Making start button gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bbuttontexture"), false); m_buttonStart = new Button(m_programHandle); m_buttonStart->setTextureUnit(2); m_buttonStart->loadTexture("resources/shader/button1.png", "buttontex"); m_buttonStart->translateModelMat(glm::vec3(-2.0, -26.6, 18.0)); m_buttonStart->scaleModelMat(glm::vec3(3.0f, 1.0f, 0.0f)); //Making exit button gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bexitButton"), false); m_buttonExit = new Button(m_programHandle); m_buttonExit->setTextureUnit(3); m_buttonExit->loadTexture("resources/shader/button2.png", "exitButtonTex"); m_buttonExit->translateModelMat(glm::vec3(-2.0, -27.4, 18.0)); m_buttonExit->scaleModelMat(glm::vec3(3.0f, 1.0f, 0.0f)); //Making instruction button gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bmoreButton"), false); m_buttonInstruction = new Button(m_programHandle); m_buttonInstruction->setTextureUnit(4); m_buttonInstruction->loadTexture("resources/shader/button3.png", "moreButtonTex"); m_buttonInstruction->translateModelMat(glm::vec3(-2.0, -27.0, 18.0)); m_buttonInstruction->scaleModelMat(glm::vec3(3.0f, 1.0f, 0.0f)); //Create the room to hold the scene gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "drawRcube"), false); m_room = new Cube(m_programHandle); m_room->setTextureUnit(5); m_room->scaleModelMat(glm::vec3(40)); m_room->cubeMap("resources/cubemap", "cube_texture"); //Creating box gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bDrawRubix"), false); m_box2 = new MeshComponent("Box Model 2"); m_read->resetData(); m_read->ReadFile("resources/obj/cube.obj"); m_box2->setVertrices(m_read->getVertexPoints()); m_box2->setIndices(m_read->getIndices()); m_box2->setNormals(m_read->getNormals()); m_box2->setStartPos(glm::vec3(-20.0, -37.0, 0.0)); m_box2->Load(m_programHandle); m_box2->setTextureUnit(6); m_box2->cubeMap("resources/rmap", "cube_texture2"); m_box2->translateModelMat(m_box2->getStartPos()); m_box2->scaleModelMat(glm::vec3(3)); //Creating instructions screen gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bcontrolScreen"), false); m_instructionsComponent = new UIComponent(m_programHandle); m_instructionsComponent->setTextureUnit(7); m_instructionsComponent->loadTexture("resources/shader/controls.png", "controlTex"); m_instructionsComponent->translateModelMat(glm::vec3(-2.0, -27.0, 18.0)); m_instructionsComponent->scaleModelMat(glm::vec3(13)); //Creating Back Button gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bbackbutton"), false); m_backButton = new Button(m_programHandle); m_backButton->setTextureUnit(8); m_backButton->loadTexture("resources/shader/back.png", "buttonBackTex"); m_backButton->translateModelMat(glm::vec3(-2.0, -27.8, 18.0)); // m_backButton->scaleModelMat(glm::vec3(.0f)); //Creating Mickey Mouse //gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bPattern"), false); m_mouse = new MeshComponent("Mickey Mouse Model"); m_read->resetData(); m_read->ReadFile("resources/obj/mouse.obj"); m_mouse->setVertrices(m_read->getVertexPoints()); m_mouse->setIndices(m_read->getIndices()); m_mouse->setNormals(m_read->getNormals()); m_mouse->setStartPos(glm::vec3(20.0, -40.0, -30.0)); m_mouse->Load(m_programHandle); m_mouse->translateModelMat(m_mouse->getStartPos()); m_mouse->scaleModelMat(glm::vec3(6)); //Create Robot character m_robot = new Robot(m_programHandle); m_robot->setSpeed(0.001f); m_robot->setAnimationAngle(0.2f); m_robot->setStartPos(glm::vec3(0.0, -24.0, 0.0)); m_robot->setVariableWalkAngle(0.0); //Clears the data being read in from OBJ files m_read->resetData(); //Putting the objects into a containter to traverse through m_objects.push_back(m_box); m_objects.push_back(m_man); m_objects.push_back(m_cone); //m_objects.push_back(m_box2); m_objects.push_back(m_garlicpress); m_objects.push_back(m_mouse); m_objects.push_back(m_character); m_objects.push_back(m_box); //Lighting stuff //compileAndLinkShader(); //Set up the lighting //setLightParams(camera); } //!< Render mesh objects void BaseGame::render(CameraComponent camera) { gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); switch (m_cGameState) { //Splash screen state case 0: gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bSplashScreenState"), true); m_splashScreenComponent->updateModelMatrix(camera, m_programHandle); m_splashScreenComponent->draw(); break; case 1: //Menu Screen state gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bSplashScreenState"), false); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "col"), 3); //Start Buttons gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bbuttontexture"), true); m_buttonStart->updateModelMatrix(camera, m_programHandle); m_buttonStart->draw(); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bbuttontexture"), false); //Exit Button gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bexitButton"), true); m_buttonExit->updateModelMatrix(camera, m_programHandle); m_buttonExit->draw(); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bexitButton"), false); //Instruction Button gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bmoreButton"), true); m_buttonInstruction->updateModelMatrix(camera, m_programHandle); m_buttonInstruction->draw(); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bmoreButton"), false); //Menu gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bMenu"), true); m_menuScreenComponent->updateModelMatrix(camera, m_programHandle); m_menuScreenComponent->draw(); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bMenu"), false); break; case 2: //Simulation game state //Tells the shader not to render the splash screen or menu screen gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bSplashScreenState"), false); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bMenu"), false); //Room gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "drawRcube"), true); m_room->updateModelMatrix(camera, m_programHandle); m_room->draw(); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "drawRcube"), false); for (int i = 0; i < m_objects.size(); i++) { // Draw what is on the objects list gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "col"), i); m_objects.at(i)->updateModelMatrix(camera, m_programHandle); m_objects.at(i)->draw(); } //Draw robot m_robot->drawRobot(camera, m_programHandle); //drawing box test to see if textures are working gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bDrawRubix"), true); m_box2->updateModelMatrix(camera, m_programHandle); m_box2->draw(); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bDrawRubix"), false); //Drawing mickey in pattern wrapper /*gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bPattern"), true); m_mouse->updateModelMatrix(camera, m_programHandle); m_mouse->draw(); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bPattern"), false);*/ //Setting material properties for the cube /* prog.setUniform("Kd", 0.0f, 1.0f, 0.0f); prog.setUniform("Ld", 0.0f, 1.0f, 0.0f); prog.setUniform("Ka", 0.0f, 1.0f, 0.0f); prog.setUniform("La", 0.0f, 0.1f, 0.0f); prog.setUniform("Ks", 1.0f, 1.0f, 1.0f); prog.setUniform("Ls", 0.2f, 0.2f, 0.2f);*/ //gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE); break; case 3: //render for game state 3 //Back button gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bbackbutton"), true); m_backButton->updateModelMatrix(camera, m_programHandle); m_backButton->draw(); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bbackbutton"), false); //Controls screen gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bcontrolScreen"), true); m_menuScreenComponent->updateModelMatrix(camera, m_programHandle); m_menuScreenComponent->draw(); gl::Uniform1i(gl::GetUniformLocation(m_programHandle, "bcontrolScreen"), false); break; } } //!< Detects when a key is press void BaseGame::keyPress(bool b, char c) { m_bKeyPress = b; m_robot->changeDirection(c); } //!< Obtains the current game state char BaseGame::getGameState() { // 0 = splash screen, 1 = simulation return m_cGameState; } //!< Changes the game state void BaseGame::changeGameState(int i) { m_cGameState = i; } /*void GameLogic::setLightParams(QuatCamera camera) { //vec3 worldLight = vec3(-5.0f, -5.0f, 5.0f); // prog.setUniform("Ld", 1.0f, 1.0f, 1.0f); // prog.setUniform("LightPosition", camera.view() * vec4(worldLight,1.0) ); // prog.setUniform("LightPosition", worldLight); }*/ /*void GameLogic::compileAndLinkShader() { try { prog.compileShader("resources/shader/basic.vert"); prog.compileShader("resources/shader/basic.frag"); prog.link(); prog.validate(); prog.use(); } catch (GLSLProgramException & e) { cerr << e.what() << endl; exit(EXIT_FAILURE); } }*/
[ "p12194892@my365.dmu.ac.uk" ]
p12194892@my365.dmu.ac.uk
87f477e7d1c979c2343287100a9623ffb1a804b0
f2e1ef881c5835fce122f8076f484c0475bff9df
/include/LuminoEngine/Runtime/FlatCommon.h
76d7aa96ed3b0d19074c234623bf3d06ef14a02b
[ "MIT" ]
permissive
lp249839965/Lumino
def5d41f32d4a3f3c87966719fd5ded954b348cc
94b1919f1579610fc6034c371cf96e7e8517c5e9
refs/heads/master
2023-02-13T09:33:22.868358
2020-12-22T15:30:55
2020-12-22T15:30:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,486
h
#pragma once #if !defined(LN_FLAT_API) #if defined(_WIN32) && defined(LUMINO_BUILD_DLL) #define LN_FLAT_API __declspec(dllexport) #elif defined(__GNUC__) && defined(LUMINO_BUILD_DLL) #define LN_FLAT_API __attribute__((visibility("default"))) #else #define LN_FLAT_API #endif #endif #define LNI_FUNC_TRY_BEGIN try { //#define LNI_FUNC_TRY_END_RETURN } \ // catch (ln::Exception& e) { \ // return ln::Runtime::processException(&e); \ // } \ // catch (...) { \ // return LN_ERROR_UNKNOWN; \ // } \ // return LN_OK; #define LNI_FUNC_TRY_END_RETURN } \ catch (ln::Exception& e) { \ return ln::Runtime::processException(&e); \ } \ return LN_OK; // NOTE: HSP ランタイムは エラーを例外で通知していくので、catch (...) で処理してしまうとよくわからないままプロセスが終了してしまう。 #define LNI_BOOL_TO_LNBOOL(x) (x) ? LN_TRUE : LN_FALSE #define LNI_LNBOOL_TO_BOOL(x) (x != LN_FALSE) #define LNI_CREATE_OBJECT(out, type, initFunc, ...) { auto ptr = ::ln::makeObject<type>(__VA_ARGS__); *out = ::ln::Runtime::makeObjectWrap(ptr, true); } #define LNI_HANDLE_TO_OBJECT(type, h) static_cast<type*>((h) ? ::ln::Runtime::getObject(h) : nullptr) #define LNI_OBJECT_TO_HANDLE(obj) ::ln::Runtime::makeObjectWrap(obj, false) #define LNI_OBJECT_TO_HANDLE_FROM_STRONG_REFERENCE(obj) ::ln::Runtime::makeObjectWrap(obj, true) #define LNI_STRING_TO_STRPTR_UTF16(str) ::ln::Runtime::getUTF16StringPtr(str) #define LNI_STRING_TO_STRPTR_A(str) ::ln::Runtime::getAStringPtr(str) #define LNI_ASTRPTR_TO_STRING(str) ::ln::String::fromCString(str, -1, ::ln::Runtime::getAStringEncoding()) #define LNI_REFERENCE_RETAINED (1) #define LNI_REFERENCE_RELEASED (2) #ifdef __cplusplus extern "C" { #endif // __cplusplus //------------------------------------------------------------------------------ #include <stdint.h> /** Lumino のオブジェクトを識別するための値です。0 (LN_NULL_HANDLE) は無効値です。 */ typedef uint32_t LNHandle; typedef void* LNUserData; typedef char16_t LNChar; #define LN_NULL_HANDLE 0 /** 結果・エラーコード */ typedef enum tagLNResult { /** 成功 */ LN_OK = 0, /** 不明なエラー */ LN_ERROR_UNKNOWN = -1, /** */ LN_RUNTIME_UNINITIALIZED = -2, /** */ LN_ERROR_INVALID_ARGUMENT = -3, } LNResult; /** 真偽値 */ typedef enum tagLNBool { /** 偽 */ LN_FALSE = 0, /** 真 */ LN_TRUE = 1, } LNBool; /** ログの通知レベル */ typedef enum tagLNLogLevel { LN_LOG_LEVEL_UNKNOWN = 0, LN_LOG_LEVEL_VERBOSE, LN_LOG_LEVEL_DEBUG, LN_LOG_LEVEL_INFO, LN_LOG_LEVEL_WARN, LN_LOG_LEVEL_ERROR, LN_LOG_LEVEL_FATAL, } LNLogLevel; //============================================================================== // Internal API typedef void(*LNRuntimeFinalizedCallback)(); typedef void(*LNReferenceCountTrackerCallback)(LNHandle handle, int method, int count); typedef void(*LNRuntimeGetTypeInfoIdCallback)(LNHandle handle, int* outTypeInfoId); typedef struct tagLNRuntimeSettings { LNRuntimeFinalizedCallback runtimeFinalizedCallback; LNReferenceCountTrackerCallback referenceCountTrackerCallback; LNRuntimeGetTypeInfoIdCallback runtimeGetTypeInfoIdCallback; } LNRuntimeSettings; extern LN_FLAT_API void LNRuntime_Initialize(const LNRuntimeSettings* settings); extern LN_FLAT_API void LNRuntime_Finalize(); inline const char* LNRuntime_GetLastErrorMessage() { return ""; } // TODO: extern LN_FLAT_API void LNRuntime_SetManagedObjectId(LNHandle handle, int64_t id); extern LN_FLAT_API int64_t LNRuntime_GetManagedObjectId(LNHandle handle); extern LN_FLAT_API int64_t LNRuntime_GetManagedTypeInfoId(LNHandle handle); //extern LN_FLAT_API void LNRuntime_SetReferenceCountTracker(LNReferenceCountTrackerCallback callback); extern LN_FLAT_API void LNRuntime_SetReferenceTrackEnabled(LNHandle handle); //extern LN_FLAT_API void LNRuntime_SetRuntimeFinalizedCallback(LNRuntimeFinalizedCallback callback); //extern LN_FLAT_API void LNRuntime_SetRuntimeCreateInstanceCallback(LNRuntimeCreateInstanceCallback callback); //extern LN_FLAT_API void LNRuntime_SetRuntimeGetTypeInfoIdCallback(LNRuntimeGetTypeInfoIdCallback callback); extern LN_FLAT_API void LNRuntime_RunAppInternal(LNHandle app); extern LN_FLAT_API void LNRuntime_DumpInfo(); extern LN_FLAT_API void LNInternalEngineSettings_SetEngineResourcesPathA(const char* path); typedef void(*LNTypeInfoCreateInstanceCallback)(int typeInfoId, LNHandle* outHandle); extern LN_FLAT_API LNResult LNTypeInfo_Acquire(const LNChar* typeName, int* outTypeInfoId); extern LN_FLAT_API LNResult LNTypeInfo_AcquireA(const char* typeName, int* outTypeInfoId); extern LN_FLAT_API LNResult LNTypeInfo_Find(const LNChar* typeName, int* outTypeInfoId); extern LN_FLAT_API LNResult LNTypeInfo_FindA(const char* typeName, int* outTypeInfoId); extern LN_FLAT_API LNResult LNTypeInfo_SetBaseClass(int typeInfoId, int baseClassTypeInfoId); extern LN_FLAT_API LNResult LNTypeInfo_SetCreateInstanceCallback(int typeInfoId, LNTypeInfoCreateInstanceCallback callback); extern LN_FLAT_API LNResult LNTypeInfo_SetManagedTypeInfoId(int typeInfoId, int managedTypeInfoId); extern LN_FLAT_API LNResult LNTypeInfo_GetManagedTypeInfoId(int typeInfoId, int* outManagedTypeInfoId); typedef uint64_t LNSubinstanceId; typedef LNSubinstanceId(*LNSubinstanceAllocFunc)(LNHandle object); typedef void(*LNSubinstanceFreeFunc)(LNHandle object, LNSubinstanceId subinstanceId); //============================================================================== /** @brief 全てのオブジェクトのベースクラスです。 */ /** @brief オブジェクトを解放します。 @param[in] obj : オブジェクトハンドル @details 指定されたオブジェクトの参照を解放します。 */ LN_FLAT_API LNResult LNObject_Release(LNHandle obj); /** * @brief オブジェクトの参照を取得します。 * @param[in] obj : オブジェクトハンドル * @details 指定されたオブジェクトの参照カウントをインクリメントします。 */ LN_FLAT_API LNResult LNObject_Retain(LNHandle obj); /** * @brief ネイティブオブジェクトの参照カウントを取得します。これは内部的に使用される関数です。 * @param[in] obj : オブジェクトハンドル */ LN_FLAT_API LNResult LNObject_GetReferenceCount(LNHandle object, int* outReturn); LN_FLAT_API int32_t _LNObject_GetReferenceCount(LNHandle obj); // class LNWS_XXXX のインスタンスに対して set できる。 // Engine 内部で new されたインスタンスに対して呼び出すことはできない。 // Managed 側で Engine のクラスを継承して新たな型を作ったとき、それを登録するために使用する。 LN_FLAT_API LNResult LNObject_SetTypeInfoId(LNHandle obj, int typeInfoId); //============================================================================== LN_FLAT_API void LNLog_SetLevel(LNLogLevel level); LN_FLAT_API void LNLog_Write(LNLogLevel level, const LNChar* tag, const LNChar* text); LN_FLAT_API void LNLog_WriteA(LNLogLevel level, const char* tag, const char* text); LN_FLAT_API void LNLog_PrintA(LNLogLevel level, const char* tag, const char* format, ...); #ifdef __cplusplus } // extern "C" #endif // __cplusplus
[ "lriki.net@gmail.com" ]
lriki.net@gmail.com
503a7f78fa10d3de03e84d939ccc648450f3ed4d
fb136dc7a713fd6751395f842d70ef9b400ff4f3
/Year3/CCS/MCP/Assignment/karman3.cpp
fd2afc8678e7262da53fe89c83ec92de480067ce
[]
no_license
ehockedy/backup
a1ae35c30b7b29ef9c29e32cb1689b2a38e3ca01
de7590711ab59b58481807a2c94288756832d60e
refs/heads/master
2020-07-21T19:25:47.937301
2017-04-24T23:39:22
2017-04-24T23:39:22
73,841,581
0
0
null
null
null
null
UTF-8
C++
false
false
69,815
cpp
/* ======================================================================= This example follows the book from Griebel et al on Computational Fluid Dynamics. It realises a test setup from TUM's CFD lab. (C) 2016 Tobias Weinzierl ======================================================================= Getting started with the Karman vortex strees (1) Compile the code with g++ -O3 karman.cpp -o karman (2) Try a dry run ./karman You should see a usage instruction. Lets start with (3) ./karman 10 0.001 800 It will run for a while (up to several hours - depends on your computer). Please note that you can work with finer meshes (increase first parameter) for all your development but then you miss some of the interesting physics. For reasonably accurate results, you should use 20 instead of 10. It then however can happen that your code runs for more than a day. So at least decrease the final time (see constant below) for any speed tests. Once you've completed this example, you might want to try: ./karman 10 0.001 1600 ./karman 10 0.001 10000 ./karman 15 0.001 1600 ./karman 15 0.001 10000 ./karman 20 0.001 1600 ./karman 20 0.001 10000 The last parameter is the Reynolds number. It determines how viscous your fluid is. Very high Reynolds numbers make the fluid resemble gas, low Reynolds numbers make it act like honey. (4) Open Paraview - Select all the vtk files written and press Apply. You should see the bounding box of the setup, i.e. a cube. - Select first the vtk files in the left menu and then Filters/Alphabetical/Stream Tracer and press Apply. - Press the Play button. Already in the first time snapshot you should see how the fluid flows through the domain (the lines you see are streamlines, i.e. they visualise the flow direction) - If you want to see the obstacle: select the output files in the left window. Select Filter/Threshold. In the bottom left window there's a pulldown menu Scalars where you have to select obstacle. Filter values between 0 and 0.1 and press apply. The idea is that each cell has a number: 0 means obstacle, 1 fluid cell. So if you filter out all the 1 guys, then you end up with the obstacle. - If you want to get an impression of the pressure distribution, select the output files in the left window. Apply the filter Slice. By default, its x normal vector is set to 1. For our setup, it is better to make the z component equal one. Press apply and ensure that you have selected pressure for the output. When you run the code it might become necessary to press the button "Rescale to Data Range" in the toolbar for the pressure as the pressure increases over time. - Also very convenient to study the flow field is the glyph mode. Select the input data to the left and apply the filter Glyph. It puts little arrows into the domain that visualise the flow direction and its magnitude. By default, these glyphs are too big. Use the Properties window to the left and reduce the Scale Factor to 0.02, e.g. - For Scientific Computing: If you have implemented another equation on top of the flow field (should be called ink here here) to get an idea what the solution looks like. Alternatively, you can use threshold or the contour line filter. Paraview is pretty powerful (though sometimes not very comfortable to use). However, you find plenty of tutorials on YouTube, e.g. (5) Start programming - There is already a field ink in the code that you can use to represent your chemical substance. - It has the dimension numberOfCellsPerAxis+1 x numberOfCellsPerAxis+1 x numberOfCellsPerAxis+1. - The ink is already visualised (though it is zero right now), so you have a visual debugging tool at hands. - I suggest to start with a pure Poisson equation, i.e. to neglect the impact of ux, uy and uz, and then to add those terms to the equation. - Do all your realisation in updateInk() please. You can also set the boundary conditions there. */ #include <stdlib.h> #include <stdio.h> #include <iostream> #include <string> #include <sstream> #include <fstream> #include <cmath> #include <algorithm> #include <math.h> #include <vector> using namespace std; /** * Number of cell we have per axis */ int numberOfCellsPerAxisX; int numberOfCellsPerAxisY; int numberOfCellsPerAxisZ; /** * Velocity of fluid along x,y and z direction */ double* ux; double* uy; double* uz; /** * Helper along x,y and z direction */ double* Fx; double* Fy; double* Fz; /** * Pressure in the cell */ double* p; double* rhs; /** * A marker that is required for the Scientific Computing module. */ double* ink; //Q2 std::vector<std::vector<int> > boxes; bool* boxHasBoundary; bool* boxIsNotInside; vector<double> filler (6*6*6, 0); vector<vector<double> > ghostBoxes; /** * Is cell inside domain */ bool* cellIsInside; double timeStepSize; double ReynoldsNumber = 0; const int MaxComputePIterations = 20000; const int MinAverageComputePIterations = 200; const int IterationsBeforeTimeStepSizeIsAltered = 64; const double ChangeOfTimeStepSize = 0.1; const double PPESolverThreshold = 1e-6; std::vector<int> numToBoundaryDirs(int num) //This converts a base 10 number to a vector of its binary value. Num must be <= 32. The binary values correspond to the possible values of [x, -x, y, -y, z, -z], the 6 possible directions that a boundary is to a cell { if(num == 0) { return std::vector<int> (6,0); } else { int val = num; std::vector<int> dir(6); //[x, -x, y, -y, z, -z] int maximum = (int)floor(log2(num)); //Since need to start filling up from back, may not be the case that the number can be %2 enough times to fill the array, so this is the number of times it can. for(int i = 0 ; i <= maximum ; i++) { //int sign = (int)floor((pow(-1.0, maximum-i))); //whether it is in the positive or negative direction int isBoundary = (int)(val%2); //whether that number os a 1 in the binary position and hence indicated that that direction has a boundary dir.at(i) = isBoundary;//sign * isBoudary; val = (int)floor(val/2.0); } for(int j = maximum+1 ; j < 6; j++) { dir.at(j) = 0; } return dir; } } /** * Switch on to have a couple of security checks */ //#define CheckVariableValues /** * This is a small macro that I use to ensure that something is valid. There's * a more sophisticated version of this now in the C++ standard (and there are * many libs that have way more mature assertion functions), but it does the * job. Please comment it out if you do runtime measurements - you can do so by * commenting out the define statement above. */ void assertion( bool condition, int line ) { #ifdef CheckVariableValues if (!condition) { std::cerr << "assertion failed in line " << line << std::endl; exit(-1); } #endif } /** * Maps the three coordinates onto one cell index. */ int getCellIndex(int ix, int iy, int iz) { assertion(ix>=0,__LINE__); assertion(ix<numberOfCellsPerAxisX+2,__LINE__); assertion(iy>=0,__LINE__); assertion(iy<numberOfCellsPerAxisY+2,__LINE__); assertion(iz>=0,__LINE__); assertion(iz<numberOfCellsPerAxisZ+2,__LINE__); return ix+iy*(numberOfCellsPerAxisX+2)+iz*(numberOfCellsPerAxisX+2)*(numberOfCellsPerAxisY+2); } int getGhostIndex(int ix, int iy, int iz) { return ix + iy*6 + iz*6*6; } /** * Maps the three coordinates onto one vertex index. * Please note that we hold only the inner and boundary vertices. */ int getVertexIndex(int ix, int iy, int iz) { assertion(ix>=0,__LINE__); assertion(ix<numberOfCellsPerAxisX+1,__LINE__); assertion(iy>=0,__LINE__); assertion(iy<numberOfCellsPerAxisY+1,__LINE__); assertion(iz>=0,__LINE__); assertion(iz<numberOfCellsPerAxisZ+1,__LINE__); return ix+iy*(numberOfCellsPerAxisX+1)+iz*(numberOfCellsPerAxisX+1)*(numberOfCellsPerAxisY+1); } /** * Gives you the face with the number ix,iy,iz. * * Takes into account that there's one more face in X direction than numberOfCellsPerAxisX. */ int getFaceIndexX(int ix, int iy, int iz) { assertion(ix>=0,__LINE__); assertion(ix<numberOfCellsPerAxisX+3,__LINE__); assertion(iy>=0,__LINE__); assertion(iy<numberOfCellsPerAxisY+2,__LINE__); assertion(iz>=0,__LINE__); assertion(iz<numberOfCellsPerAxisZ+2,__LINE__); return ix+iy*(numberOfCellsPerAxisX+3)+iz*(numberOfCellsPerAxisX+3)*(numberOfCellsPerAxisY+2); } int getFaceIndexY(int ix, int iy, int iz) { assertion(ix>=0,__LINE__); assertion(ix<numberOfCellsPerAxisX+2,__LINE__); assertion(iy>=0,__LINE__); assertion(iy<numberOfCellsPerAxisY+3,__LINE__); assertion(iz>=0,__LINE__); assertion(iz<numberOfCellsPerAxisZ+2,__LINE__); return ix+iy*(numberOfCellsPerAxisX+2)+iz*(numberOfCellsPerAxisX+2)*(numberOfCellsPerAxisY+2); } int getFaceIndexZ(int ix, int iy, int iz) { assertion(ix>=0,__LINE__); assertion(ix<numberOfCellsPerAxisX+2,__LINE__); assertion(iy>=0,__LINE__); assertion(iy<numberOfCellsPerAxisY+2,__LINE__); assertion(iz>=0,__LINE__); assertion(iz<numberOfCellsPerAxisZ+3,__LINE__); return ix+iy*(numberOfCellsPerAxisX+2)+iz*(numberOfCellsPerAxisX+2)*(numberOfCellsPerAxisY+2); } /** * We use always numberOfCellsPerAxisX=numberOfCellsPerAxisY and we make Z 5 * times bigger, i.e. we always work with cubes. We also assume that the whole * setup always has exactly the height 1. */ double getH() { return 1.0/static_cast<double>(numberOfCellsPerAxisY); } /** * There are two types of errors/bugs that really hunt us in these codes: We * either have programmed something wrong (use wrong indices) or we make a * tiny little error in one of the computations. The first type of errors is * covered by assertions. The latter type is realised in this routine, where * we do some consistency checks. */ void validateThatEntriesAreBounded(const std::string& callingRoutine) { #ifdef CheckVariableValues for (int ix=0; ix<numberOfCellsPerAxisX+2; ix++) for (int iy=0; iy<numberOfCellsPerAxisY+2; iy++) for (int iz=0; iz<numberOfCellsPerAxisZ+2; iz++) { if ( std::abs(p[ getCellIndex(ix,iy,iz)])>1e10 ) { std::cerr << "error in routine " + callingRoutine + " in p[" << ix << "," << iy << "," << iz << "]" << std::endl; exit(-1); } } for (int ix=0; ix<numberOfCellsPerAxisX+3; ix++) for (int iy=0; iy<numberOfCellsPerAxisY+2; iy++) for (int iz=0; iz<numberOfCellsPerAxisZ+2; iz++) { if ( std::abs(ux[ getFaceIndexX(ix,iy,iz)])>1e10 ) { std::cerr << "error in routine " + callingRoutine + " in ux[" << ix << "," << iy << "," << iz << "]" << std::endl; exit(-1); } if ( std::abs(Fx[ getFaceIndexX(ix,iy,iz)])>1e10 ) { std::cerr << "error in routine " + callingRoutine + " in Fx[" << ix << "," << iy << "," << iz << "]" << std::endl; exit(-1); } } for (int ix=0; ix<numberOfCellsPerAxisX+2; ix++) for (int iy=0; iy<numberOfCellsPerAxisY+3; iy++) for (int iz=0; iz<numberOfCellsPerAxisZ+2; iz++) { if ( std::abs(uy[ getFaceIndexY(ix,iy,iz)])>1e10 ) { std::cerr << "error in routine " + callingRoutine + " in uy[" << ix << "," << iy << "," << iz << "]" << std::endl; exit(-1); } if ( std::abs(Fy[ getFaceIndexY(ix,iy,iz)])>1e10 ) { std::cerr << "error in routine " + callingRoutine + " in Fy[" << ix << "," << iy << "," << iz << "]" << std::endl; exit(-1); } } for (int ix=0; ix<numberOfCellsPerAxisX+2; ix++) for (int iy=0; iy<numberOfCellsPerAxisY+2; iy++) for (int iz=0; iz<numberOfCellsPerAxisZ+3; iz++) { if ( std::abs(uz[ getFaceIndexZ(ix,iy,iz)])>1e10 ) { std::cerr << "error in in routine " + callingRoutine + " uz[" << ix << "," << iy << "," << iz << "]: " << uz[ getFaceIndexZ(ix,iy,iz)] << std::endl; exit(-1); } if ( std::abs(Fz[ getFaceIndexZ(ix,iy,iz)])>1e10 ) { std::cerr << "error in in routine " + callingRoutine + " Fz[" << ix << "," << iy << "," << iz << "]" << std::endl; exit(-1); } } #endif } /** * Plot a vtk file. This function probably never has to be changed when you do * your assessment. */ void plotVTKFile() { static int vtkFileCounter = 0; std::ostringstream outputFileName; outputFileName << "output-" << vtkFileCounter << ".vtk"; std::ofstream out; out.open( outputFileName.str().c_str() ); std::cout << "\t write " << outputFileName.str(); out << "# vtk DataFile Version 2.0" << std::endl << "Tobias Weinzierl: CPU, Manycore and Cluster Computing" << std::endl << "ASCII" << std::endl << std::endl; out << "DATASET STRUCTURED_POINTS" << std::endl << "DIMENSIONS " << numberOfCellsPerAxisX+1 << " " << numberOfCellsPerAxisY+1 << " " << numberOfCellsPerAxisZ+1 << std::endl << std::endl; out << "ORIGIN 0 0 0 " << std::endl << std::endl; out << "SPACING " << getH() << " " << getH() << " " << getH() << " " << std::endl << std::endl; const int numberOfVertices = (numberOfCellsPerAxisX+1) * (numberOfCellsPerAxisY+1) * (numberOfCellsPerAxisZ+1); out << "POINT_DATA " << numberOfVertices << std::endl << std::endl; out << "VECTORS velocity float" << std::endl; for (int iz=1; iz<numberOfCellsPerAxisZ+2; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+2; iy++) { for (int ix=1; ix<numberOfCellsPerAxisX+2; ix++) { out << 0.25 * ( ux[ getFaceIndexX(ix,iy-1,iz-1) ] + ux[ getFaceIndexX(ix,iy-0,iz-1) ] + ux[ getFaceIndexX(ix,iy-1,iz-0) ] + ux[ getFaceIndexX(ix,iy,iz) ] ) << " "; out << 0.25 * ( uy[ getFaceIndexY(ix-1,iy,iz-1) ] + uy[ getFaceIndexY(ix-0,iy,iz-1) ] + uy[ getFaceIndexY(ix-1,iy,iz-0) ] + uy[ getFaceIndexY(ix,iy,iz) ] ) << " "; out << 0.25 * ( uz[ getFaceIndexZ(ix-1,iy-1,iz) ] + uz[ getFaceIndexZ(ix-0,iy-1,iz) ] + uz[ getFaceIndexZ(ix-1,iy-0,iz) ] + uz[ getFaceIndexZ(ix,iy,iz) ] ) << std::endl; } } } out << std::endl << std::endl; // // For debugging, it sometimes pays off to see F. Usually not required - notably not for this year's // assignments // #ifdef CheckVariableValues out << "VECTORS F float" << std::endl; for (int iz=1; iz<numberOfCellsPerAxisZ+2; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+2; iy++) { for (int ix=1; ix<numberOfCellsPerAxisX+2; ix++) { out << 0.25 * ( Fx[ getFaceIndexX(ix,iy-1,iz-1) ] + Fx[ getFaceIndexX(ix,iy-0,iz-1) ] + Fx[ getFaceIndexX(ix,iy-1,iz-0) ] + Fx[ getFaceIndexX(ix,iy,iz) ] ) << " "; out << 0.25 * ( Fy[ getFaceIndexY(ix-1,iy,iz-1) ] + Fy[ getFaceIndexY(ix-0,iy,iz-1) ] + Fy[ getFaceIndexY(ix-1,iy,iz-0) ] + Fy[ getFaceIndexY(ix,iy,iz) ] ) << " "; out << 0.25 * ( Fz[ getFaceIndexZ(ix-1,iy-1,iz) ] + Fz[ getFaceIndexZ(ix-0,iy-1,iz) ] + Fz[ getFaceIndexZ(ix-1,iy-0,iz) ] + Fz[ getFaceIndexZ(ix,iy,iz) ] ) << std::endl; } } } out << std::endl << std::endl; #endif out << "SCALARS ink float 1" << std::endl; out << "LOOKUP_TABLE default" << std::endl; for (int iz=0; iz<numberOfCellsPerAxisZ+1; iz++) { for (int iy=0; iy<numberOfCellsPerAxisY+1; iy++) { for (int ix=0; ix<numberOfCellsPerAxisX+1; ix++) { out << ink[ getVertexIndex(ix,iy,iz) ] << std::endl; } } } out << std::endl << std::endl; const int numberOfCells = numberOfCellsPerAxisX * numberOfCellsPerAxisY * numberOfCellsPerAxisZ; out << "CELL_DATA " << numberOfCells << std::endl << std::endl; out << "SCALARS pressure float 1" << std::endl; out << "LOOKUP_TABLE default" << std::endl; for (int iz=1; iz<numberOfCellsPerAxisZ+1; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+1; iy++) { for (int ix=1; ix<numberOfCellsPerAxisX+1; ix++) { out << p[ getCellIndex(ix,iy,iz) ] << std::endl; } } } out << "SCALARS obstacle float 1" << std::endl; out << "LOOKUP_TABLE default" << std::endl; for (int iz=1; iz<numberOfCellsPerAxisZ+1; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+1; iy++) { for (int ix=1; ix<numberOfCellsPerAxisX+1; ix++) { out << cellIsInside[ getCellIndex(ix,iy,iz) ] << std::endl; } } } // // For debugging, it sometimes pays off to see the rhs of the pressure // Poisson equation. Usually not required - notably not for this year's // assignments // #ifdef CheckVariableValues out << "SCALARS rhs float 1" << std::endl; out << "LOOKUP_TABLE default" << std::endl; for (int iz=1; iz<numberOfCellsPerAxisZ+1; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+1; iy++) { for (int ix=1; ix<numberOfCellsPerAxisX+1; ix++) { out << rhs[ getCellIndex(ix,iy,iz) ] << std::endl; } } } #endif out.close(); vtkFileCounter++; } /** * Computes a helper velocity. See book of Griebel for details. */ void computeF() { const double alpha = timeStepSize / getH(); for (int iz=1; iz<numberOfCellsPerAxisZ+2-1; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+2-1; iy++) { for (int ix=2; ix<numberOfCellsPerAxisX+3-2; ix++) { if ( cellIsInside[getCellIndex(ix-1,iy,iz)] && cellIsInside[getCellIndex(ix,iy,iz)] ) { const double diffusiveTerm = + (-1.0 * ux[ getFaceIndexX(ix-1,iy,iz) ] + 2.0 * ux[ getFaceIndexX(ix,iy,iz) ] - 1.0 * ux[ getFaceIndexX(ix+1,iy,iz) ] ) + (-1.0 * ux[ getFaceIndexX(ix,iy-1,iz) ] + 2.0 * ux[ getFaceIndexX(ix,iy,iz) ] - 1.0 * ux[ getFaceIndexX(ix,iy+1,iz) ] ) + (-1.0 * ux[ getFaceIndexX(ix,iy,iz-1) ] + 2.0 * ux[ getFaceIndexX(ix,iy,iz) ] - 1.0 * ux[ getFaceIndexX(ix,iy,iz+1) ] ); const double convectiveTerm = + ( (ux[ getFaceIndexX(ix,iy,iz) ]+ux[ getFaceIndexX(ix+1,iy,iz) ])*(ux[ getFaceIndexX(ix,iy,iz) ]+ux[ getFaceIndexX(ix+1,iy,iz) ]) - (ux[ getFaceIndexX(ix-1,iy,iz) ]+ux[ getFaceIndexX(ix,iy,iz) ]) *(ux[ getFaceIndexX(ix-1,iy,iz) ]+ux[ getFaceIndexX(ix,iy,iz) ]) ) + ( (uy[ getFaceIndexY(ix,iy,iz) ]+uy[ getFaceIndexY(ix+1,iy,iz) ])*(ux[ getFaceIndexX(ix,iy,iz) ]+ux[ getFaceIndexX(ix,iy+1,iz) ]) - (uy[ getFaceIndexY(ix,iy-1,iz) ]+uy[ getFaceIndexY(ix+1,iy-1,iz) ])*(ux[ getFaceIndexX(ix,iy-1,iz) ]+ux[ getFaceIndexX(ix,iy,iz) ]) ) + ( (uz[ getFaceIndexZ(ix,iy,iz) ]+uz[ getFaceIndexZ(ix+1,iy,iz) ])*(ux[ getFaceIndexX(ix,iy,iz) ]+ux[ getFaceIndexX(ix,iy,iz+1) ]) - (uz[ getFaceIndexZ(ix,iy,iz-1) ]+uz[ getFaceIndexZ(ix+1,iy,iz-1) ])*(ux[ getFaceIndexX(ix,iy,iz-1) ]+ux[ getFaceIndexX(ix,iy,iz) ]) ) + alpha * ( std::abs(ux[ getFaceIndexX(ix,iy,iz) ]+ux[ getFaceIndexX(ix+1,iy,iz) ])*(ux[ getFaceIndexX(ix,iy,iz) ]-ux[ getFaceIndexX(ix+1,iy,iz) ]) - std::abs(ux[ getFaceIndexX(ix-1,iy,iz) ]+ux[ getFaceIndexX(ix,iy,iz) ]) *(ux[ getFaceIndexX(ix-1,iy,iz) ]-ux[ getFaceIndexX(ix,iy,iz) ]) ) + alpha * ( std::abs(uy[ getFaceIndexY(ix,iy,iz) ]+uy[ getFaceIndexY(ix+1,iy,iz) ])*(ux[ getFaceIndexX(ix,iy,iz) ]-ux[ getFaceIndexX(ix,iy+1,iz) ]) - std::abs(uy[ getFaceIndexY(ix,iy-1,iz) ]+uy[ getFaceIndexY(ix+1,iy-1,iz) ])*(ux[ getFaceIndexX(ix,iy-1,iz) ]-ux[ getFaceIndexX(ix,iy,iz) ]) ) + alpha * ( std::abs(uz[ getFaceIndexZ(ix,iy,iz) ]+uz[ getFaceIndexZ(ix+1,iy,iz) ])*(ux[ getFaceIndexX(ix,iy,iz) ]-ux[ getFaceIndexX(ix,iy,iz+1) ]) - std::abs(uz[ getFaceIndexZ(ix,iy,iz-1) ]+uz[ getFaceIndexZ(ix+1,iy,iz-1) ])*(ux[ getFaceIndexX(ix,iy,iz-1) ]-ux[ getFaceIndexX(ix,iy,iz) ]) ) ; Fx[ getFaceIndexX(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ] - timeStepSize/ReynoldsNumber * 1.0/getH()/getH() * diffusiveTerm - timeStepSize * 1.0/getH()/4.0 * convectiveTerm; } } } } for (int iz=1; iz<numberOfCellsPerAxisZ+2-1; iz++) { for (int iy=2; iy<numberOfCellsPerAxisY+3-2; iy++) { for (int ix=1; ix<numberOfCellsPerAxisX+2-1; ix++) { if ( cellIsInside[getCellIndex(ix,iy-1,iz)] && cellIsInside[getCellIndex(ix,iy,iz)] ) { const double diffusiveTerm = + (-1.0 * uy[ getFaceIndexY(ix-1,iy,iz) ] + 2.0 * uy[ getFaceIndexY(ix,iy,iz) ] - 1.0 * uy[ getFaceIndexY(ix+1,iy,iz) ] ) + (-1.0 * uy[ getFaceIndexY(ix,iy-1,iz) ] + 2.0 * uy[ getFaceIndexY(ix,iy,iz) ] - 1.0 * uy[ getFaceIndexY(ix,iy+1,iz) ] ) + (-1.0 * uy[ getFaceIndexY(ix,iy,iz-1) ] + 2.0 * uy[ getFaceIndexY(ix,iy,iz) ] - 1.0 * uy[ getFaceIndexY(ix,iy,iz+1) ] ) ; const double convectiveTerm = + ( (ux[ getFaceIndexX(ix,iy,iz) ]+ux[ getFaceIndexX(ix,iy+1,iz) ])*(uy[ getFaceIndexY(ix,iy,iz) ]+uy[ getFaceIndexY(ix+1,iy,iz) ]) - (ux[ getFaceIndexX(ix-1,iy,iz) ]+ux[ getFaceIndexX(ix-1,iy+1,iz) ]) *(uy[ getFaceIndexY(ix-1,iy,iz) ]+uy[ getFaceIndexY(ix,iy,iz) ]) ) + ( (uy[ getFaceIndexY(ix,iy,iz) ]+uy[ getFaceIndexY(ix,iy+1,iz) ])*(uy[ getFaceIndexY(ix,iy,iz) ]+uy[ getFaceIndexY(ix,iy+1,iz) ]) - (uy[ getFaceIndexY(ix,iy-1,iz) ]+uy[ getFaceIndexY(ix,iy,iz) ]) *(uy[ getFaceIndexY(ix,iy-1,iz) ]+uy[ getFaceIndexY(ix,iy,iz) ]) ) + ( (uz[ getFaceIndexZ(ix,iy,iz) ]+uz[ getFaceIndexZ(ix,iy+1,iz) ])*(uy[ getFaceIndexY(ix,iy,iz) ]+uy[ getFaceIndexY(ix,iy,iz+1) ]) - (uz[ getFaceIndexZ(ix,iy,iz-1) ]+uz[ getFaceIndexZ(ix,iy+1,iz-1) ]) *(uy[ getFaceIndexY(ix,iy,iz-1) ]+uy[ getFaceIndexY(ix,iy,iz) ]) ) + alpha * ( std::abs(ux[ getFaceIndexX(ix,iy,iz) ]+ux[ getFaceIndexX(ix,iy+1,iz) ])*(uy[ getFaceIndexY(ix,iy,iz) ]-uy[ getFaceIndexY(ix+1,iy,iz) ]) - std::abs(ux[ getFaceIndexX(ix-1,iy,iz) ]+ux[ getFaceIndexX(ix-1,iy+1,iz) ]) *(uy[ getFaceIndexY(ix-1,iy,iz) ]-uy[ getFaceIndexY(ix,iy,iz) ]) ) + alpha * ( std::abs(uy[ getFaceIndexY(ix,iy,iz) ]+uy[ getFaceIndexY(ix,iy+1,iz) ])*(uy[ getFaceIndexY(ix,iy,iz) ]-uy[ getFaceIndexY(ix,iy+1,iz) ]) - std::abs(uy[ getFaceIndexY(ix,iy-1,iz) ]+uy[ getFaceIndexY(ix,iy,iz) ]) *(uy[ getFaceIndexY(ix,iy-1,iz) ]-uy[ getFaceIndexY(ix,iy,iz) ]) ) + alpha * ( std::abs(uz[ getFaceIndexZ(ix,iy,iz) ]+uz[ getFaceIndexZ(ix,iy+1,iz) ])*(uy[ getFaceIndexY(ix,iy,iz) ]-uy[ getFaceIndexY(ix,iy,iz+1) ]) - std::abs(uz[ getFaceIndexZ(ix,iy,iz-1) ]+uz[ getFaceIndexZ(ix,iy+1,iz-1) ]) *(uy[ getFaceIndexY(ix,iy,iz-1) ]-uy[ getFaceIndexY(ix,iy,iz) ]) ) ; Fy[ getFaceIndexY(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ] - timeStepSize/ReynoldsNumber * 1.0/getH()/getH() * diffusiveTerm - timeStepSize * 1.0/getH()/4.0 * convectiveTerm; } } } } for (int iz=2; iz<numberOfCellsPerAxisZ+3-2; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+2-1; iy++) { for (int ix=1; ix<numberOfCellsPerAxisX+2-1; ix++) { if ( cellIsInside[getCellIndex(ix,iy,iz-1)] && cellIsInside[getCellIndex(ix,iy,iz)] ) { const double diffusiveTerm = + (-1.0 * uz[ getFaceIndexZ(ix-1,iy,iz) ] + 2.0 * uz[ getFaceIndexZ(ix,iy,iz) ] - 1.0 * uz[ getFaceIndexZ(ix+1,iy,iz) ] ) + (-1.0 * uz[ getFaceIndexZ(ix,iy-1,iz) ] + 2.0 * uz[ getFaceIndexZ(ix,iy,iz) ] - 1.0 * uz[ getFaceIndexZ(ix,iy+1,iz) ] ) + (-1.0 * uz[ getFaceIndexZ(ix,iy,iz-1) ] + 2.0 * uz[ getFaceIndexZ(ix,iy,iz) ] - 1.0 * uz[ getFaceIndexZ(ix,iy,iz+1) ] ) ; const double convectiveTerm = + ( (ux[ getFaceIndexX(ix,iy,iz) ]+ux[ getFaceIndexX(ix,iy,iz+1) ])*(uz[ getFaceIndexZ(ix,iy,iz) ]+uz[ getFaceIndexZ(ix+1,iy,iz) ]) - (ux[ getFaceIndexX(ix-1,iy,iz) ]+ux[ getFaceIndexX(ix-1,iy,iz+1) ]) *(uz[ getFaceIndexZ(ix-1,iy,iz) ]+uz[ getFaceIndexZ(ix,iy,iz) ]) ) + ( (uy[ getFaceIndexY(ix,iy,iz) ]+uy[ getFaceIndexY(ix,iy,iz+1) ])*(uz[ getFaceIndexZ(ix,iy,iz) ]+uz[ getFaceIndexZ(ix,iy+1,iz) ]) - (uy[ getFaceIndexY(ix,iy-1,iz) ]+uy[ getFaceIndexY(ix,iy-1,iz+1) ]) *(uz[ getFaceIndexZ(ix,iy-1,iz) ]+uz[ getFaceIndexZ(ix,iy,iz) ]) ) + ( (uz[ getFaceIndexZ(ix,iy,iz) ]+uz[ getFaceIndexZ(ix,iy,iz+1) ])*(uz[ getFaceIndexZ(ix,iy,iz) ]+uz[ getFaceIndexZ(ix,iy,iz+1) ]) - (uz[ getFaceIndexZ(ix,iy,iz-1) ]+uz[ getFaceIndexZ(ix,iy,iz) ]) *(uz[ getFaceIndexZ(ix,iy,iz-1) ]+uz[ getFaceIndexZ(ix,iy,iz) ]) ) + alpha * ( std::abs(ux[ getFaceIndexX(ix,iy,iz) ]+ux[ getFaceIndexX(ix,iy,iz+1) ])*(uz[ getFaceIndexZ(ix,iy,iz) ]-uz[ getFaceIndexZ(ix+1,iy,iz) ]) - std::abs(ux[ getFaceIndexX(ix-1,iy,iz) ]+ux[ getFaceIndexX(ix-1,iy,iz+1) ]) *(uz[ getFaceIndexZ(ix-1,iy,iz) ]-uz[ getFaceIndexZ(ix,iy,iz) ]) ) + alpha * ( std::abs(uy[ getFaceIndexY(ix,iy,iz) ]+uy[ getFaceIndexY(ix,iy,iz+1) ])*(uz[ getFaceIndexZ(ix,iy,iz) ]-uz[ getFaceIndexZ(ix,iy+1,iz) ]) - std::abs(uy[ getFaceIndexY(ix,iy-1,iz) ]+uy[ getFaceIndexY(ix,iy-1,iz+1) ]) *(uz[ getFaceIndexZ(ix,iy-1,iz) ]-uz[ getFaceIndexZ(ix,iy,iz) ]) ) + alpha * ( std::abs(uz[ getFaceIndexZ(ix,iy,iz) ]+uz[ getFaceIndexZ(ix,iy,iz+1) ])*(uz[ getFaceIndexZ(ix,iy,iz) ]-uz[ getFaceIndexZ(ix,iy,iz+1) ]) - std::abs(uz[ getFaceIndexZ(ix,iy,iz-1) ]+uz[ getFaceIndexZ(ix,iy,iz) ]) *(uz[ getFaceIndexZ(ix,iy,iz-1) ]-uz[ getFaceIndexZ(ix,iy,iz) ]) ) ; Fz[ getFaceIndexZ(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ] - timeStepSize/ReynoldsNumber * 1.0/getH()/getH() * diffusiveTerm - timeStepSize * 1.0/getH()/4.0 * convectiveTerm; } } } } validateThatEntriesAreBounded( "computeF" ); } /** * Compute the right-hand side. This basically means how much a flow would * violate the incompressibility if there were no pressure. */ void computeRhs() { for (int iz=1; iz<numberOfCellsPerAxisZ+2-1; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+2-1; iy++) { for (int ix=1; ix<numberOfCellsPerAxisX+2-1; ix++) { if ( cellIsInside[getCellIndex(ix,iy,iz)] ) { rhs[ getCellIndex(ix,iy,iz) ] = 1.0/timeStepSize/getH()* ( Fx[getFaceIndexX(ix+1,iy,iz)] - Fx[getFaceIndexX(ix,iy,iz)] + Fy[getFaceIndexY(ix,iy+1,iz)] - Fy[getFaceIndexY(ix,iy,iz)] + Fz[getFaceIndexZ(ix,iy,iz+1)] - Fz[getFaceIndexZ(ix,iy,iz)] ); } } } } } /** * Set boundary conditions for pressure. The values of the pressure at the * domain boundary might depend on the pressure itself. So if we update it * in the algorithm, we afterwards have to reset the boundary conditions * again. */ void setPressureBoundaryConditions() { int ix, iy, iz; // Neumann Boundary conditions for p //Following 3 forfor loops can be parallelised within each forfor since the 2 acessed cells are different. //Cannot parallise the 3 forfors though sice the initially acesses cell is can be the same e.g. (0,0,0) //Probably CPU since its only dealing with small pieces of data, and due to parallization that frequent accessing of data will no longer be a concern //Boundaries at opposite x ends - // ______ // /| z| // /_|___/_| // | / y | // |/__x_|/ //So this does the left and right sides of the above cube //Can do part 2 here //Since boxes split up into 4x4x4 can do a box at a time, but vectorized //So store each edge box in a struct that stores x, y, z, and which face it is (can store multiple faces if corner/edge) - this specifies which parts of the box can be ignored //Then for each box, using vectorization can process the boundary conditions for 4 values all in 1 go - or even 16 since only dependent on the values in the direction perpendicular to that face for (iy = 0; iy<numberOfCellsPerAxisY + 2; iy++) { for (iz = 0; iz<numberOfCellsPerAxisZ + 2; iz++) { ix = 0; p[getCellIndex(ix, iy, iz)] = p[getCellIndex(ix + 1, iy, iz)]; ix = numberOfCellsPerAxisX + 1; p[getCellIndex(ix, iy, iz)] = p[getCellIndex(ix - 1, iy, iz)]; } } //top and bottom for (ix = 0; ix<numberOfCellsPerAxisX + 2; ix++) { for (iz = 0; iz<numberOfCellsPerAxisZ + 2; iz++) { iy = 0; p[getCellIndex(ix, iy, iz)] = p[getCellIndex(ix, iy + 1, iz)]; iy = numberOfCellsPerAxisY + 1; p[getCellIndex(ix, iy, iz)] = p[getCellIndex(ix, iy - 1, iz)]; } } //front and back for (ix = 0; ix<numberOfCellsPerAxisX + 2; ix++) { for (iy = 0; iy<numberOfCellsPerAxisY + 2; iy++) { iz = 0; p[getCellIndex(ix, iy, iz)] = p[getCellIndex(ix, iy, iz + 1)]; iz = numberOfCellsPerAxisZ + 1; p[getCellIndex(ix, iy, iz)] = p[getCellIndex(ix, iy, iz - 1)]; } } // Normalise pressure at rhs to zero for (iy = 1; iy<numberOfCellsPerAxisY + 2 - 1; iy++) { for (iz = 1; iz<numberOfCellsPerAxisZ + 2 - 1; iz++) { p[getCellIndex(numberOfCellsPerAxisX + 1, iy, iz)] = 0.0; } } int count = 0; int count2 = 0; /*int counter = 0; int counter2 = 0; int counter3 = 0;*/ // Pressure conditions around obstacle //Q2 //Go through all 4x4x4 i.e. iz/iy/ix+=4, then iterate from 0 to 3 and store if any of those cells are on a boundary. This is done once //Then in this part of the code, if at least 1 of the cells in the 4x4x4 is on a boundary we go through each direction (x/y/z) // and fully vectorize any computations i.e. 16 cells at a time (so a square/plane in the 4x4x4 box) by having the direction as the first for loop, // then pragma simd the 2nd and 3rd loops, and this is done 4 times for each layer in the first direction, and done for each direction for (iz = 1; iz<numberOfCellsPerAxisZ + 1; iz = iz + 4) { for (iy = 1; iy<numberOfCellsPerAxisY + 1; iy = iy + 4) { for (ix = 2; ix<numberOfCellsPerAxisX + 1; ix = ix + 4) { //std::cout << getCellIndex(ix,iy,iz) << std::endl; //std::cout << iz << " " << iy << " " << ix << std::endl; //std::cout << /*for(int x=0; x<4; x++){ //#pragma simd for(int y=0; y<4; y++){ //#pragma simd for(int z=0; z<4; z++){ //std::cout << iz+z << " " << iy+y << " " << ix+x << std::endl; counter2++; } } }*/ if (boxHasBoundary[getCellIndex(ix, iy, iz)]) //If this box has at least 1 cell with a boudary { count2++; for (int z = 0; z<4 && iz + z<numberOfCellsPerAxisZ + 1; z++) { //#pragma simd for (int x = 0; x<4 && ix + x<numberOfCellsPerAxisX + 1; x++) { //#pragma simd for (int y = 0; y<4 && iy + y<numberOfCellsPerAxisY + 1; y++) { p[getCellIndex(ix + x, iy + y, iz + z + boxes[getCellIndex(ix + x, iy + y, iz + z)][4])] = p[getCellIndex(ix + x, iy + y, iz + z)]; p[getCellIndex(ix + x, iy + y, iz + z - boxes[getCellIndex(ix + x, iy + y, iz + z)][5])] = p[getCellIndex(ix + x, iy + y, iz + z)]; } } } for (int y = 0; y<4 && iy + y<numberOfCellsPerAxisY + 1; y++) { //#pragma simd / for (int z = 0; z<4 && iz + z<numberOfCellsPerAxisZ + 1; z++) { //#pragma simd //ivdep for (int x = 0; x<4 && ix + x<numberOfCellsPerAxisX + 1; x++) { p[getCellIndex(ix + x, iy + y + boxes[getCellIndex(ix + x, iy + y, iz + z)][2], iz + z)] = p[getCellIndex(ix + x, iy + y, iz + z)]; p[getCellIndex(ix + x, iy + y - boxes[getCellIndex(ix + x, iy + y, iz + z)][3], iz + z)] = p[getCellIndex(ix + x, iy + y, iz + z)]; } } } for (int x = 0; x<4 && ix + x<numberOfCellsPerAxisX + 1; x++) { //#pragma simd for (int y = 0; y<4 && iy + y<numberOfCellsPerAxisY + 1; y++) { //#pragma simd for (int z = 0; z<4 && iz + z<numberOfCellsPerAxisZ + 1; z++) { //count++; p[getCellIndex(ix + x + boxes[getCellIndex(ix + x, iy + y, iz + z)][0], iy + y, iz + z)] = p[getCellIndex(ix + x, iy + y, iz + z)]; p[getCellIndex(ix + x - boxes[getCellIndex(ix + x, iy + y, iz + z)][1], iy + y, iz + z)] = p[getCellIndex(ix + x, iy + y, iz + z)]; } } } } else { count++;// = count + 64; } } } } } void setupBoxes() { int counter = 0; for (int iz=1; iz<numberOfCellsPerAxisZ+1; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+1; iy++) { for (int ix=2; ix<numberOfCellsPerAxisX+1; ix++) { if (cellIsInside[getCellIndex(ix,iy,iz)]) { int count = 0; if ( !cellIsInside[getCellIndex(ix-1,iy,iz)] ) { // right neighbour count = count + (int)pow(2, 1); counter++; //std::cout << iz << " " << iy << " " << ix-1 << std::endl; } if ( !cellIsInside[getCellIndex(ix+1,iy,iz)] ) { // left neighbour count = count + (int)pow(2, 0); counter++; //std::cout << iz << " " << iy << " " << ix+1 << std::endl; } if ( !cellIsInside[getCellIndex(ix,iy-1,iz)] ) { // top neighbour count = count + (int)pow(2, 3); counter++; //std::cout << iz << " " << iy-1 << " " << ix << std::endl; } if ( !cellIsInside[getCellIndex(ix,iy+1,iz)] ) { // bottom neighbour count = count + (int)pow(2, 2); counter++; //std::cout << iz << " " << iy+1 << " " << ix << std::endl; } if ( !cellIsInside[getCellIndex(ix,iy,iz-1)] ) { // front neighbour count = count + (int)pow(2, 5); counter++; //std::cout << iz-1 << " " << iy << " " << ix << std::endl; } if ( !cellIsInside[getCellIndex(ix,iy,iz+1)] ) { // back neighbour count = count + (int)pow(2, 4); counter++; //std::cout << iz+1 << " " << iy << " " << ix << std::endl; } //if(count>0){std::cout << count << " " << ix << " " << iy << " " << iz << std::endl;} boxes[getCellIndex(ix,iy,iz)] = numToBoundaryDirs(count); /*if(count >0) { std::cout << std::endl << count << " "; for(int q = 0 ; q < 6 ; q++) { std::cout << boxes[getCellIndex(ix,iy,iz)][q]; } }*/ } else{ //std::cout << " " << ix << " " << iy << " " << iz << std::endl; boxes[getCellIndex(ix,iy,iz)] = numToBoundaryDirs(0); } } } } //std::cout << "counter = " << counter << std::endl; int count = 0; int count2 = 0; //whether a box has a boundary within it, and hence whether pressure around the object needs to be set in each box for (int iz=1; iz<numberOfCellsPerAxisZ+1; iz=iz+4) { for (int iy=1; iy<numberOfCellsPerAxisY+1; iy=iy+4) { for (int ix=2; ix<numberOfCellsPerAxisX+1; ix=ix+4) { bool hasBoundary = false; bool notIn = true; for(int a = 0 ; a < 4 && ix+a<numberOfCellsPerAxisX+1; a++){ for(int b = 0 ; b < 4 && iy+b<numberOfCellsPerAxisY+1; b++){ for(int c = 0 ; c < 4 && iz+c<numberOfCellsPerAxisZ+1; c++){ //std::cout << ix+a << " " << iy+b << " " << iz+c << std::endl; //std::cout << cellIsInside[getCellIndex(ix+a,iy+b,iz+c)] << std::endl; if(cellIsInside[getCellIndex(ix+a,iy+b,iz+c)]){ notIn = false; if ( !cellIsInside[getCellIndex(ix+a+1,iy+b,iz+c)] ) { hasBoundary = true; } if ( !cellIsInside[getCellIndex(ix+a-1,iy+b,iz+c)] ) { hasBoundary = true; } if ( !cellIsInside[getCellIndex(ix+a,iy+b+1,iz+c)] ) { hasBoundary = true; } if ( !cellIsInside[getCellIndex(ix+a,iy+b-1,iz+c)] ) { hasBoundary = true; } if ( !cellIsInside[getCellIndex(ix+a,iy+b,iz+c+1)] ) { hasBoundary = true; } if ( !cellIsInside[getCellIndex(ix+a,iy+b,iz+c-1)] ) { hasBoundary = true; } } } } } boxHasBoundary[getCellIndex(ix,iy,iz)] = hasBoundary; boxIsNotInside[getCellIndex(ix, iy, iz)] = notIn; if(hasBoundary){count2++;} else{count++;} } } } //q3 set up ghost boxes /*int boxNum = 0; vector<vector<double> >::iterator it; for (int iz = 1; iz < numberOfCellsPerAxisZ + 1; iz = iz + 4) { for (int iy = 1; iy < numberOfCellsPerAxisY + 1; iy = iy + 4) { for (int ix = 2; ix < numberOfCellsPerAxisX + 1; ix = ix + 4) { boxNum = getCellIndex(ix, iy, iz); vector<double> gb (getGhostIndex(5,5,5),0.0); it = ghostBoxes.begin(); ghostBoxes.insert(it+boxNum, gb); vector<double>::iterator it2; //cout << ghostBoxes.size() << endl; for (int a = 0; a < 6 && ix + a < numberOfCellsPerAxisX + 1; a++) { for (int b = 0; b < 6 && iy + b < numberOfCellsPerAxisY + 1; b++) { for (int c = 0; c < 6 && iz + c < numberOfCellsPerAxisZ + 1; c++) { it2 = ghostBoxes.at(boxNum).begin(); ghostBoxes.at(boxNum).insert(it2+getGhostIndex(a,b,c), 0.0); } } } //boxNum++; } } }*/ //std::cout << count << " " << count2 << std::endl; } /** * Determine the new pressure. The operation depends on properly set pressure * boundary conditions. See setPressureBoundaryConditions(). * * @return Number of iterations required or max number plus one if we had to * stop iterating as the solver diverged. */ int computeP() { double globalResidual = 1.0; double firstResidual = 1.0; double previousGlobalResidual = 2.0; int iterations = 0; while( ( std::abs(globalResidual-previousGlobalResidual)>PPESolverThreshold && iterations<MaxComputePIterations && std::abs(globalResidual)>PPESolverThreshold && (globalResidual/firstResidual>PPESolverThreshold) ) || (iterations%2==1) // we have alternating omega, so we allow only even iteration counts ) { const double omega = iterations%2==0 ? 1.2 : 0.8; setPressureBoundaryConditions(); previousGlobalResidual = globalResidual; globalResidual = 0.0; //update contents of ghost blocks int ghostBoxCounter = 0; for (int iz = 1; iz < numberOfCellsPerAxisZ + 1; iz = iz + 4) { for (int iy = 1; iy < numberOfCellsPerAxisY + 1; iy = iy + 4) { for (int ix = 2; ix < numberOfCellsPerAxisX + 1; ix = ix + 4) { ghostBoxCounter = getCellIndex(ix, iy, iz); //if (!boxIsNotInside[getCellIndex(ix, iy, iz)]) { //cout << ghostBoxCounter << " " << ix << " " << iy << " " << iz << endl; for (int z = 0; z < 4 && iz + z < numberOfCellsPerAxisZ +1; z++) {//+1s removed (after numOf...) for (int y = 0; y < 4 && iy + y < numberOfCellsPerAxisY +1; y++) { for (int x = 0; x < 4 && ix + x < numberOfCellsPerAxisX +1; x++) { ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(x + 1, y + 1, z + 1)) = p[getCellIndex(ix + x, iy + y, iz + z)]; /*if (z > 0) { cout << p[getCellIndex(ix + x, iy + y, iz + z)] << " " << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(x + 1, y + 1, z + 1)) << " "; cout << p[getCellIndex(ix + x, iy + y, iz + z-1)] << " " << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(x + 1, y + 1, z + 1 - 1)) << endl; }*/ //cout << p[getCellIndex(ix + x, iy + y, iz + z)] << " "; //cout << ix+x << " " << iy+y << " " << iz+z << " " << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(x+1, y+1, z+1)) << endl; } } } } } } /*std::cout << "25, 5, 2: " << p[getCellIndex(25, 5, 2)] << std::endl; std::cout << "25, 5, 2: " << ghostBoxes.at(getCellIndex(25,5,1)).at(getGhostIndex(0,0,1)) << std::endl; std::cout << "3, 1, 1: " << p[getCellIndex(3, 1, 1)] << std::endl; std::cout << "3, 1, 1: " << ghostBoxes.at(getCellIndex(1, 1, 1)).at(getGhostIndex(2, 0, 0)) << std::endl; cout << endl;*/ //Update outer layer ghost cells for (int iz = 1; iz < numberOfCellsPerAxisZ + 1; iz = iz + 4) { for (int iy = 1; iy < numberOfCellsPerAxisY + 1; iy = iy + 4) { for (int ix = 2; ix < numberOfCellsPerAxisX + 1; ix = ix + 4) { ghostBoxCounter = getCellIndex(ix, iy, iz); for (int c = 0; c < 6 && iz + c < numberOfCellsPerAxisZ+2; c++) { //+2 because of the extra layers for (int b = 0; b < 6 && iy + b < numberOfCellsPerAxisY+2; b++) { try { //cout << ix << " " << iy << " " << iz; double temp = ghostBoxes.at(getCellIndex(ix - 4, iy, iz)).at(getGhostIndex(4, b, c)); if (temp >= 0){ ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(0, b, c)) = temp; //CHANGE GHOST BOX COUNTER -1 } //cout << ix << " " << iy << " " << iz << " " << cout << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(0, b, c)) << endl; } catch (exception e) //If there is not a ghostBoxCounter-1 th box { //cout << "1"; ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(0, b, c)) = ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(1, b, c)); } try { //cout << ix << " " << iy << " " << iz; double temp = ghostBoxes.at(getCellIndex(ix + 4, iy, iz)).at(getGhostIndex(1, b, c)); if (temp >= 0) { ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(5, b, c)) = temp; } //cout << ix << " " << iy << " " << iz << " " <<cout << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(5, b, c)) << endl; } catch (exception e) { int boundary = 5-(numberOfCellsPerAxisX - ix);// min((ix + 6), numberOfCellsPerAxisX) - ix - 1; //cout << "ix" << ix << " " << numberOfCellsPerAxisX << " " << boundary << endl; //cout << "2"; ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(boundary, b, c)) = ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(boundary-1, b, c)); } //cout << getGhostIndex(0, b, c) << ", "; //cout << getGhostIndex(5, b, c) << ", "; //counter++; } } for (int b = 0; b < 6 && iy + b < numberOfCellsPerAxisY+2; b++) { for (int a = 0; a < 6 && ix + a < numberOfCellsPerAxisX+2; a++) { try { //cout << ix << " " << iy << " " << iz; double temp = ghostBoxes.at(getCellIndex(ix, iy, iz - 4)).at(getGhostIndex(a, b, 4)); if (temp >= 0) { ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, 0)) = temp; } //cout << ix << " " << iy << " " << iz << " " << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, 0)) << endl; } catch (exception e) { //cout << "3"; ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, 0)) = ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, 1)); } try { //cout << ix << " " << iy << " " << iz << " " << a << " " << b << " "; //cout << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, 5)) << endl; double temp = ghostBoxes.at(getCellIndex(ix, iy, iz + 4)).at(getGhostIndex(a, b, 1)); if (temp >= 0) { ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, 5)) = temp; } //cout << ix << " " << iy << " " << iz << " " << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, 5)) << endl; } catch (exception e) { int boundary = 5-(numberOfCellsPerAxisZ - iz);// min((iz + 6), numberOfCellsPerAxisZ) - iz - 1; //cout << "iz" << iz << " " << numberOfCellsPerAxisZ << " " << boundary << endl; //cout << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, 4)) << endl; ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, boundary)) = ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, boundary-1)); } //ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, 0)); //ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, b, 5)); //cout << getGhostIndex(a, b, 0) << ", "; //cout << getGhostIndex(a, b, 5) << ", "; //counter++; } } for (int a = 0; a < 6 && ix + a < numberOfCellsPerAxisX+2; a++) { for (int c = 0; c < 6 && iz + c < numberOfCellsPerAxisZ+2; c++) { try { //cout << ix << " " << iy << " " << iz; double temp = ghostBoxes.at(getCellIndex(ix, iy - 4, iz)).at(getGhostIndex(a, 4, c)); if (temp >= 0) { ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, 0, c)) = temp; } //cout << ix << " " << iy << " " << iz << " " << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, 0, c)) << endl; } catch (exception e) { //cout << "5"; ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, 0, c)) = ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, 1, c)); } try { //cout << ix << " " << iy << " " << iz; double temp = ghostBoxes.at(getCellIndex(ix, iy + 4, iz)).at(getGhostIndex(a, 1, c)); if (temp >= 0) { ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, 5, c)) = temp; } //cout << ix << " " << iy << " " << iz << " " << ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, 5, c)) << endl; } catch (exception e) { int boundary = 5-(numberOfCellsPerAxisY - iy);// min((iy + 6), numberOfCellsPerAxisY) - iy - 1; //cout << "iy" << iy << " " << numberOfCellsPerAxisY << " " << boundary << endl; //cout << "6"; ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, boundary, c)) = ghostBoxes.at(ghostBoxCounter).at(getGhostIndex(a, boundary-1, c)); } //ghostBoxes[ghostBoxCounter)[getGhostIndex(a, 0, c)); //ghostBoxes[ghostBoxCounter)[getGhostIndex(a, 5, c)); //cout << getGhostIndex(a, 0, c) << ", "; //cout << getGhostIndex(a, 5, c) << ", "; //counter++; } } //cout << counter << endl << endl; //counter = 0; //ghostBoxCounter++; } } } //This is the bottleneck of this function (and hence whole code) //Cannot be parrallelised like this since the same cell could be manipulated at the same time //However, can be vectorized - the 7 getCellIndex below can be executed at the same time - simd ghostBoxCounter = 0; for (int iz=1; iz<numberOfCellsPerAxisZ+1; iz = iz+4) { for (int iy=1; iy<numberOfCellsPerAxisY+1; iy = iy+4) { for (int ix=2; ix<numberOfCellsPerAxisX+1; ix = ix+4) { //if (!boxIsNotInside[getCellIndex(ix, iy, iz)]) { ghostBoxCounter = getCellIndex(ix, iy, iz); //Get the index of the box stored in the vector at ix,iy,iz for (int c = 1; c < 5 && iz + c-1 < numberOfCellsPerAxisZ + 1 ; c++) { //Iterate through the inner 4x4x4 box for (int b = 1; b < 5 && iy + b-1 < numberOfCellsPerAxisY + 1 ; b++) { for (int a = 1; a < 5 && ix + a-1 < numberOfCellsPerAxisX + 1 ; a++) { //std::cout << ix << " " << iy << " " << iz << " " << a << " " << b << " " << c << std::endl; //cout << getCellIndex(ix, iy, iz) << " " << ghostBoxes.size() << " " << getGhostIndex(a, b, c) << endl; if (cellIsInside[getCellIndex(ix+a-1, iy+b-1, iz+c-1)]) { //-1 is because of the =1 offset from the ghost layer double residual = rhs[getCellIndex(ix + a - 1, iy + b - 1, iz + c - 1)] + 1.0 / getH() / getH()* ( -1.0 * ghostBoxes[ghostBoxCounter][getGhostIndex(a - 1, b, c)] //Ghost index gives the index in the vector that is ghost box - 1.0 * ghostBoxes[ghostBoxCounter][getGhostIndex(a + 1, b, c)] //Use the values from the ghost box to calculate residual - 1.0 * ghostBoxes[ghostBoxCounter][getGhostIndex(a, b - 1, c)] - 1.0 * ghostBoxes[ghostBoxCounter][getGhostIndex(a, b + 1, c)] - 1.0 * ghostBoxes[ghostBoxCounter][getGhostIndex(a, b, c - 1)] - 1.0 * ghostBoxes[ghostBoxCounter][getGhostIndex(a, b, c + 1)] + 6.0 * ghostBoxes[ghostBoxCounter][getGhostIndex(a, b, c)] ); globalResidual += residual * residual; p[getCellIndex(ix + a-1, iy + b-1, iz + c-1)] += -omega * residual / 6.0 * getH() * getH(); //Update both the p and ghostBox ghostBoxes[ghostBoxCounter][getGhostIndex(a, b, c)] += -omega * residual / 6.0 * getH() * getH(); //cout << getCellIndex(ix + a - 1, iy + b - 1, iz + c - 1) << " " << ghostBoxCounter << " " << getGhostIndex(a, b, c) << endl; //cout << ix + a-1 << " " << iy + b-1 << " " << iz + c-1 << " " << ghostBoxes[ghostBoxCounter][getGhostIndex(a, b, c)] << endl; //std::cout << ix << " " << iy << " " << iz << std::endl; } } } } //} //ghostBoxCounter++; } } } //int counter = 0; //cout << endl << endl << endl; globalResidual = std::sqrt(globalResidual); firstResidual = firstResidual==0 ? globalResidual : firstResidual; iterations++; } //std::cout << p[getCellIndex(25, 5, 2)] << std::endl; /*IO TURNED OFF FOR PROFILING std::cout << "iterations n=" << iterations << ", |res(n)|_2=" << globalResidual << ", |res(n-1)|_2=" << previousGlobalResidual << ", |res(n-1)|_2-|res(n)|_2=" << (previousGlobalResidual-globalResidual); */ return iterations; } /** * @todo Your job if you attend the Scientific Computing submodule. Otherwise empty. */ void updateInk() { } /** * Once we have F and a valid pressure p, we may update the velocities. */ void setNewVelocities() { for (int iz=1; iz<numberOfCellsPerAxisZ+2-1; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+2-1; iy++) { for (int ix=2; ix<numberOfCellsPerAxisX+3-2; ix++) { ux[ getFaceIndexX(ix,iy,iz) ] = Fx[ getFaceIndexX(ix,iy,iz) ] - timeStepSize/getH() * ( p[getCellIndex(ix,iy,iz)] - p[getCellIndex(ix-1,iy,iz)]); } } } for (int iz=1; iz<numberOfCellsPerAxisZ+2-1; iz++) { for (int iy=2; iy<numberOfCellsPerAxisY+3-2; iy++) { for (int ix=1; ix<numberOfCellsPerAxisX+2-1; ix++) { uy[ getFaceIndexY(ix,iy,iz) ] = Fy[ getFaceIndexY(ix,iy,iz) ] - timeStepSize/getH() * ( p[getCellIndex(ix,iy,iz)] - p[getCellIndex(ix,iy-1,iz)]); } } } for (int iz=2; iz<numberOfCellsPerAxisZ+3-2; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+2-1; iy++) { for (int ix=1; ix<numberOfCellsPerAxisX+2-1; ix++) { uz[ getFaceIndexZ(ix,iy,iz) ] = Fz[ getFaceIndexZ(ix,iy,iz) ] - timeStepSize/getH() * ( p[getCellIndex(ix,iy,iz)] - p[getCellIndex(ix,iy,iz-1)]); } } } } /** * Setup our scenario, i.e. initialise all the big arrays and set the * right boundary conditions. This is something you might want to change in * part three of the assessment. */ void setupScenario() { const int numberOfCells = (numberOfCellsPerAxisX+2) * (numberOfCellsPerAxisY+2) * (numberOfCellsPerAxisZ+2); const int numberOfGhostCells = ((numberOfCellsPerAxisX + (ceil(numberOfCellsPerAxisX / 4) * 2) + 2) * (numberOfCellsPerAxisY + (ceil(numberOfCellsPerAxisY / 4) * 2) + 2) * (numberOfCellsPerAxisZ + (ceil(numberOfCellsPerAxisZ / 4) * 2) + 2)); const int numberOfFacesX = (numberOfCellsPerAxisX+3) * (numberOfCellsPerAxisY+2) * (numberOfCellsPerAxisZ+2); const int numberOfFacesY = (numberOfCellsPerAxisX+2) * (numberOfCellsPerAxisY+3) * (numberOfCellsPerAxisZ+2); const int numberOfFacesZ = (numberOfCellsPerAxisX+2) * (numberOfCellsPerAxisY+2) * (numberOfCellsPerAxisZ+3); ux = 0; uy = 0; uz = 0; Fx = 0; Fy = 0; Fz = 0; p = 0; rhs = 0; ink = 0; ux = new (std::nothrow) double[numberOfFacesX]; uy = new (std::nothrow) double[numberOfFacesY]; uz = new (std::nothrow) double[numberOfFacesZ]; Fx = new (std::nothrow) double[numberOfFacesX]; Fy = new (std::nothrow) double[numberOfFacesY]; Fz = new (std::nothrow) double[numberOfFacesZ]; p = new (std::nothrow) double[numberOfCells]; rhs = new (std::nothrow) double[numberOfCells]; boxHasBoundary = new (std::nothrow) bool[numberOfCells]; boxIsNotInside = new (std::nothrow) bool[numberOfCells]; //std::cout << "numCells = " << numberOfCells << std::endl; ghostBoxes = vector<vector<double> >(numberOfCells, filler);// ((ceil(numberOfCellsPerAxisX / 4.0) * ceil(numberOfCellsPerAxisY / 4.0) * ceil(numberOfCellsPerAxisZ / 4.0)), filler); ink = new (std::nothrow) double[(numberOfCellsPerAxisX+1) * (numberOfCellsPerAxisY+1) * (numberOfCellsPerAxisZ+1)]; cellIsInside = new (std::nothrow) bool[numberOfCells]; if ( ux == 0 || uy == 0 || uz == 0 || Fx == 0 || Fy == 0 || Fz == 0 || p == 0 || rhs == 0 ) { std::cerr << "could not allocate memory. Perhaps not enough memory free?" << std::endl; exit(-1); } for (int i=0; i<(numberOfCellsPerAxisX+1) * (numberOfCellsPerAxisY+1) * (numberOfCellsPerAxisZ+1); i++) { ink[i] = 0.0; } for (int i=0; i<numberOfCells; i++) { p[i] = 0.0; cellIsInside[i] = true; } for (int i=0; i<numberOfFacesX; i++) { ux[i]=0; Fx[i]=0; } for (int i=0; i<numberOfFacesY; i++) { uy[i]=0; Fy[i]=0; } for (int i=0; i<numberOfFacesZ; i++) { uz[i]=0; Fz[i]=0; } // // Insert the obstacle that forces the fluid to do something interesting. // int sizeOfObstacle = numberOfCellsPerAxisY/3; int xOffsetOfObstacle = sizeOfObstacle*2; if (sizeOfObstacle<2) sizeOfObstacle = 2; int zDelta = numberOfCellsPerAxisZ<=8 ? 0 : sizeOfObstacle/3; for (int iz=1 + zDelta; iz<numberOfCellsPerAxisZ+2-zDelta; iz++) { cellIsInside[ getCellIndex(xOffsetOfObstacle, sizeOfObstacle+1,iz) ] = false; cellIsInside[ getCellIndex(xOffsetOfObstacle+1, sizeOfObstacle+1,iz) ] = false; for (int ii=0; ii<sizeOfObstacle; ii++) { cellIsInside[ getCellIndex(xOffsetOfObstacle+ii, sizeOfObstacle+ii+2,iz) ] = false; cellIsInside[ getCellIndex(xOffsetOfObstacle+ii+1,sizeOfObstacle+ii+2,iz) ] = false; cellIsInside[ getCellIndex(xOffsetOfObstacle+ii+2,sizeOfObstacle+ii+2,iz) ] = false; } cellIsInside[ getCellIndex(xOffsetOfObstacle+sizeOfObstacle+0, 2*sizeOfObstacle+2,iz) ] = false; cellIsInside[ getCellIndex(xOffsetOfObstacle+sizeOfObstacle+1, 2*sizeOfObstacle+2,iz) ] = false; } validateThatEntriesAreBounded("setupScenario()"); boxes.resize(numberOfCells); setupBoxes(); } /** * Clean up the system */ void freeDataStructures() { delete[] p; delete[] ink; delete[] rhs; delete[] ux; delete[] uy; delete[] uz; delete[] Fx; delete[] Fy; delete[] Fz; delete[] cellIsInside; delete[] boxHasBoundary; delete[] boxIsNotInside; ux = 0; uy = 0; uz = 0; Fx = 0; Fy = 0; Fz = 0; p = 0; rhs = 0; ink = 0; boxHasBoundary = 0; boxIsNotInside = 0; } /** * - Handle all the velocities at the domain boundaries. We either * realise no-slip or free-slip. * * - Set the inflow and outflow profile. * * - Fix all the F values. Along the boundary, the F values equal the * velocity values. * */ void setVelocityBoundaryConditions(double time) { int ix, iy, iz; validateThatEntriesAreBounded("setVelocityBoundaryConditions(double)[in]"); const bool UseNoSlip = true; // We ensure that no fluid leaves the domain. For this, we set the velocities // along the boundary to zero. Furthermore, we ensure that the tangential // components of all velocities are zero. For this, we set the ghost/virtual // velocities to minus the original one. If we interpolate linearly in-between, // we obtain zero tangential speed. for (iy=0; iy<numberOfCellsPerAxisY+2; iy++) { for (iz=0; iz<numberOfCellsPerAxisZ+2; iz++) { ix=0; ux[ getFaceIndexX(ix,iy,iz) ] = 0.0; ix=1; ux[ getFaceIndexX(ix,iy,iz) ] = 0.0; ix=0; uy[ getFaceIndexY(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * uy[ getFaceIndexY(ix+1,iy,iz) ]; uz[ getFaceIndexZ(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * uz[ getFaceIndexZ(ix+1,iy,iz) ]; ix=numberOfCellsPerAxisX+2; ux[ getFaceIndexX(ix,iy,iz) ] = 0.0; ix=numberOfCellsPerAxisX+1; ux[ getFaceIndexX(ix,iy,iz) ] = 0.0; ix=numberOfCellsPerAxisX+1; uy[ getFaceIndexY(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * uy[ getFaceIndexY(ix-1,iy,iz) ]; uz[ getFaceIndexZ(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * uz[ getFaceIndexZ(ix-1,iy,iz) ]; } } for (ix=0; ix<numberOfCellsPerAxisX+2; ix++) { for (iz=0; iz<numberOfCellsPerAxisZ+2; iz++) { iy=0; uy[ getFaceIndexY(ix,iy,iz) ] = 0.0; iy=1; uy[ getFaceIndexY(ix,iy,iz) ] = 0.0; iy=0; ux[ getFaceIndexX(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * ux[ getFaceIndexX(ix,iy+1,iz) ]; uz[ getFaceIndexZ(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * uz[ getFaceIndexZ(ix,iy+1,iz) ]; iy=numberOfCellsPerAxisY+2; uy[ getFaceIndexY(ix,iy,iz) ] = 0.0; iy=numberOfCellsPerAxisY+1; uy[ getFaceIndexY(ix,iy,iz) ] = 0.0; iy=numberOfCellsPerAxisY+1; ux[ getFaceIndexX(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * ux[ getFaceIndexX(ix,iy-1,iz) ]; uz[ getFaceIndexZ(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * uz[ getFaceIndexZ(ix,iy-1,iz) ]; } } for (ix=0; ix<numberOfCellsPerAxisX+2; ix++) { for (iy=0; iy<numberOfCellsPerAxisY+2; iy++) { iz=0; uz[ getFaceIndexZ(ix,iy,iz) ] = 0.0; iz=1; uz[ getFaceIndexZ(ix,iy,iz) ] = 0.0; iz=0; ux[ getFaceIndexX(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * ux[ getFaceIndexX(ix,iy,iz+1) ]; uy[ getFaceIndexY(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * uy[ getFaceIndexY(ix,iy,iz+1) ]; iz=numberOfCellsPerAxisZ+2; uz[ getFaceIndexZ(ix,iy,iz) ] = 0.0; iz=numberOfCellsPerAxisZ+1; uz[ getFaceIndexZ(ix,iy,iz) ] = 0.0; iz=numberOfCellsPerAxisZ+1; ux[ getFaceIndexX(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * ux[ getFaceIndexX(ix,iy,iz-1) ]; uy[ getFaceIndexY(ix,iy,iz) ] = (UseNoSlip ? -1.0 : 1.0) * uy[ getFaceIndexY(ix,iy,iz-1) ]; } } validateThatEntriesAreBounded("setVelocityBoundaryConditions(double)[no slip set]"); // Don't switch on in-flow immediately but slowly induce it into the system // const double inputProfileScaling = std::min(time*10.0,1.0); // const double inputProfileScaling = 1.0; for (iy=1; iy<numberOfCellsPerAxisY+2-1; iy++) { for (iz=1; iz<numberOfCellsPerAxisZ+2-1; iz++) { const double yDistance = (iy-1) * (1.0/numberOfCellsPerAxisY); const double zDistance = (iz-1) * (1.0/numberOfCellsPerAxisZ); const double inflow = UseNoSlip ? inputProfileScaling * yDistance * (1.0-yDistance) * zDistance * (1.0-zDistance) : inputProfileScaling; ix=0; ux[ getFaceIndexX(ix,iy,iz) ] = inflow; uy[ getFaceIndexY(ix,iy,iz) ] = 0.0; uz[ getFaceIndexZ(ix,iy,iz) ] = 0.0; ix=1; ux[ getFaceIndexX(ix,iy,iz) ] = inflow; uy[ getFaceIndexY(ix,iy,iz) ] = 0.0; uz[ getFaceIndexZ(ix,iy,iz) ] = 0.0; // outflow ux[ getFaceIndexX(numberOfCellsPerAxisX+2,iy,iz) ] = ux[ getFaceIndexX(numberOfCellsPerAxisX,iy,iz) ]; ux[ getFaceIndexX(numberOfCellsPerAxisX+1,iy,iz) ] = ux[ getFaceIndexX(numberOfCellsPerAxisX,iy,iz) ]; uy[ getFaceIndexY(numberOfCellsPerAxisX+1,iy,iz) ] = uy[ getFaceIndexY(numberOfCellsPerAxisX+0,iy,iz) ]; uz[ getFaceIndexZ(numberOfCellsPerAxisX+1,iy,iz) ] = uz[ getFaceIndexZ(numberOfCellsPerAxisX+0,iy,iz) ]; } } validateThatEntriesAreBounded("setVelocityBoundaryConditions(double)[inflow set]"); // // Once all velocity boundary conditions are set, me can fix the F values // for (iy=0; iy<numberOfCellsPerAxisY+2; iy++) { for (iz=0; iz<numberOfCellsPerAxisZ+2; iz++) { ix=0; Fx[ getFaceIndexX(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; Fy[ getFaceIndexY(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ]; Fz[ getFaceIndexZ(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; //Fy[ getFaceIndex^(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; //Fz[ getFaceIndexZ(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ]; ix=1; Fx[ getFaceIndexX(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; ix=numberOfCellsPerAxisX+1; Fx[ getFaceIndexX(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; Fy[ getFaceIndexY(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ]; Fz[ getFaceIndexZ(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; //Fy[ getFaceIndexY(ix,iy,iz) ] = uz[ getFaceIndexY(ix,iy,iz) ]; //Fz[ getFaceIndexZ(ix,iy,iz) ] = uy[ getFaceIndexZ(ix,iy,iz) ]; ix=numberOfCellsPerAxisX+2; Fx[ getFaceIndexX(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; } } for (ix=0; ix<numberOfCellsPerAxisX+2; ix++) { for (iz=0; iz<numberOfCellsPerAxisZ+2; iz++) { iy=0; Fy[ getFaceIndexY(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ]; Fx[ getFaceIndexX(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; Fz[ getFaceIndexZ(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; //Fx[ getFaceIndexX(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; //Fz[ getFaceIndexZ(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; iy=1; Fy[ getFaceIndexY(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ] ; iy=numberOfCellsPerAxisY+1; Fy[ getFaceIndexY(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ]; Fx[ getFaceIndexX(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; Fz[ getFaceIndexZ(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; //Fx[ getFaceIndexX(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; //Fz[ getFaceIndexZ(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; iy=numberOfCellsPerAxisY+2; Fy[ getFaceIndexY(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ]; } } for (ix=0; ix<numberOfCellsPerAxisX+2; ix++) { for (iy=0; iy<numberOfCellsPerAxisY+2; iy++) { iz=0; Fz[ getFaceIndexZ(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; Fx[ getFaceIndexX(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; Fy[ getFaceIndexY(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ]; //Fx[ getFaceIndexX(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ]; //Fy[ getFaceIndexY(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; iz=1; Fz[ getFaceIndexZ(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; iz=numberOfCellsPerAxisZ+1; Fz[ getFaceIndexZ(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; Fx[ getFaceIndexX(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; Fy[ getFaceIndexY(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ]; //Fx[ getFaceIndexX(ix,iy,iz) ] = uy[ getFaceIndexY(ix,iy,iz) ]; //Fy[ getFaceIndexY(ix,iy,iz) ] = ux[ getFaceIndexX(ix,iy,iz) ]; iz=numberOfCellsPerAxisZ+2; Fz[ getFaceIndexZ(ix,iy,iz) ] = uz[ getFaceIndexZ(ix,iy,iz) ]; } } // // Handle the obstacle // for (int iz=1; iz<numberOfCellsPerAxisZ+2-1; iz++) { for (int iy=1; iy<numberOfCellsPerAxisY+2-1; iy++) { for (int ix=2; ix<numberOfCellsPerAxisX+3-2; ix++) { if (cellIsInside[getCellIndex(ix,iy,iz)]) { if ( !cellIsInside[getCellIndex(ix-1,iy,iz)] ) { // left neighbour ux[ getFaceIndexX(ix,iy,iz) ] = 0.0; ux[ getFaceIndexX(ix-1,iy,iz) ] = 0.0; Fx[ getFaceIndexX(ix,iy,iz) ] = 0.0; uy[ getFaceIndexY(ix-1,iy,iz) ] = -uy[ getFaceIndexY(ix,iy,iz) ]; uz[ getFaceIndexZ(ix-1,iy,iz) ] = -uz[ getFaceIndexZ(ix,iy,iz) ]; } if ( !cellIsInside[getCellIndex(ix+1,iy,iz)] ) { // right neighbour ux[ getFaceIndexX(ix+1,iy,iz) ] = 0.0; ux[ getFaceIndexX(ix+2,iy,iz) ] = 0.0; Fx[ getFaceIndexX(ix+1,iy,iz) ] = 0.0; uy[ getFaceIndexY(ix+1,iy,iz) ] = -uy[ getFaceIndexY(ix,iy,iz) ]; uz[ getFaceIndexZ(ix+1,iy,iz) ] = -uz[ getFaceIndexZ(ix,iy,iz) ]; } if ( !cellIsInside[getCellIndex(ix,iy-1,iz)] ) { // bottom neighbour uy[ getFaceIndexY(ix,iy,iz) ] = 0.0; uy[ getFaceIndexY(ix,iy-1,iz) ] = 0.0; Fy[ getFaceIndexY(ix,iy,iz) ] = 0.0; ux[ getFaceIndexX(ix,iy-1,iz) ] = -ux[ getFaceIndexX(ix,iy,iz) ]; uz[ getFaceIndexZ(ix,iy-1,iz) ] = -uz[ getFaceIndexZ(ix,iy,iz) ]; } if ( !cellIsInside[getCellIndex(ix,iy+1,iz)] ) { // top neighbour uy[ getFaceIndexY(ix,iy+1,iz) ] = 0.0; uy[ getFaceIndexY(ix,iy+2,iz) ] = 0.0; Fy[ getFaceIndexY(ix,iy+1,iz) ] = 0.0; ux[ getFaceIndexX(ix,iy+1,iz) ] = -ux[ getFaceIndexX(ix,iy,iz) ]; uz[ getFaceIndexZ(ix,iy+1,iz) ] = -uz[ getFaceIndexZ(ix,iy,iz) ]; } if ( !cellIsInside[getCellIndex(ix,iy,iz-1)] ) { // front neighbour uz[ getFaceIndexZ(ix,iy,iz) ] = 0.0; uz[ getFaceIndexZ(ix,iy,iz-1) ] = 0.0; Fz[ getFaceIndexZ(ix,iy,iz) ] = 0.0; ux[ getFaceIndexX(ix,iy,iz-1) ] = -ux[ getFaceIndexX(ix,iy,iz) ]; uy[ getFaceIndexY(ix,iy,iz-1) ] = -uy[ getFaceIndexY(ix,iy,iz) ]; } if ( !cellIsInside[getCellIndex(ix,iy,iz+1)] ) { // right neighbour uz[ getFaceIndexZ(ix,iy,iz+1) ] = 0.0; uz[ getFaceIndexZ(ix,iy,iz+2) ] = 0.0; Fz[ getFaceIndexZ(ix,iy,iz+1) ] = 0.0; ux[ getFaceIndexX(ix,iy,iz+1) ] = -ux[ getFaceIndexX(ix,iy,iz) ]; uy[ getFaceIndexY(ix,iy,iz+1) ] = -uy[ getFaceIndexY(ix,iy,iz) ]; } } } } } validateThatEntriesAreBounded("setVelocityBoundaryConditions(double)[out]"); } int main (int argc, char *argv[]) { if (argc!=4) { std::cout << "Usage: executable number-of-elements-per-axis time-steps-between-plots reynolds-number" << std::endl; std::cout << " number-of-elements-per-axis Resolution. Start with 20, but try to increase as much as possible later." << std::endl; std::cout << " time-between-plots Determines how many files are written. Set to 0 to switch off plotting (for performance studies)." << std::endl; std::cout << " reynolds-number Use something in-between 1 and 1000. Determines viscosity of fluid." << std::endl; return 1; } //int originalNum = atoi(argv[1]); numberOfCellsPerAxisY = atoi(argv[1]); numberOfCellsPerAxisZ = numberOfCellsPerAxisY / 2; numberOfCellsPerAxisX = numberOfCellsPerAxisY * 5; //numberOfCellsPerAxisY = originalNum + 2* ceil(originalNum /4); //numberOfCellsPerAxisZ = (originalNum / 2) + 2 * ceil((originalNum / 2) / 4); //numberOfCellsPerAxisX = (originalNum * 5) + 2 * ceil((originalNum * 5) / 4); double timeBetweenPlots = atof(argv[2]); ReynoldsNumber = atof(argv[3]); std::cout << "Re=" << ReynoldsNumber << std::endl; std::cout << "create " << numberOfCellsPerAxisX << "x" << numberOfCellsPerAxisY << "x" << numberOfCellsPerAxisZ << " grid" << std::endl; setupScenario(); // dt <= C Re dx^2 // whereas the CFD lab at TUM uses // const double MaximumTimeStepSize = 0.8 * std::min( ReynoldsNumber/2.0/(3.0/numberOfCellsPerAxisY/numberOfCellsPerAxisY), 1.0/numberOfCellsPerAxisY ); const double TimeStepSizeConstant = 1e-4; const double MaximumTimeStepSize = TimeStepSizeConstant * ReynoldsNumber / numberOfCellsPerAxisY / numberOfCellsPerAxisY; const double MinimalTimeStepSize = MaximumTimeStepSize / 800; timeStepSize = MaximumTimeStepSize; std::cout << "start with time step size " << timeStepSize << std::endl; setVelocityBoundaryConditions(0.0); std::cout << "velocity start conditions are set"; if (timeBetweenPlots>0.0) { plotVTKFile(); } std::cout << std::endl; // /*for (int q = 1 ; q < 64 ; q++) { for(int qq = 0 ; qq < 6 ;qq++) { std::cout << numToBoundaryDirs(q)[qq]; } std::cout << std::endl; }*/ // double t = 0.0; double tOfLastSnapshot = 0.0; int timeStepCounter = 0; int numberOfTimeStepsWithOnlyOneIteration = 0; while (t<0.05) { //20 //IO OFF FOR PROFILING //std::cout << "time step " << timeStepCounter << ": t=" << t << "\t dt=" << timeStepSize << "\t"; //Ensure that fluid enters the domain, is allowed to leave, and that no fluid goes through the walls setVelocityBoundaryConditions(t); //Initialise all helper variables for the fluid that is called F //These helper variables also hold the information that one fluid call drage other fluid cells with it computeF(); //Initialise all helper variables for the pressure that are called rhs here computeRhs(); //Computer the pressure that shoud be high where fluid bumps into the walls. //Where the pressure is low, it sucks in the fluid // 1/100th of the startup phase is tackled with overrelaxation; afterwards, // we use underrelaxation as we are interested in the pressure gradient, i.e. // we want to have a smooth solution int innerIterationsRequired = computeP(); std::cout << t << std::endl; std::cout << "25, 5, 2: " << p[getCellIndex(25, 5, 2)] << std::endl; std::cout << "3, 1, 1: " << p[getCellIndex(3, 1, 1)] << std::endl; std::cout << "50, 10, 5: " << p[getCellIndex(50, 10, 5)] << std::endl; std::cout << "4, 9, 4: " << p[getCellIndex(4, 9, 4)] << std::endl << std::endl; /*for(int qq = 0 ; qq < 6 qq++) { std::cout << numToBoundaryDirs(23)[qq]; }*/ //With the helper variables F and the pressure at hand, we can determine what the fluid looks like in the next time step setNewVelocities(); updateInk(); if (timeBetweenPlots>0.0 && (t-tOfLastSnapshot>timeBetweenPlots)) { plotVTKFile(); //IO OFF FOR PROFILING std::cout << t << std::endl; tOfLastSnapshot = t; } if (innerIterationsRequired>=MinAverageComputePIterations) { numberOfTimeStepsWithOnlyOneIteration--; } else if (innerIterationsRequired<=std::max(MinAverageComputePIterations/10,2) ) { numberOfTimeStepsWithOnlyOneIteration++; } else { numberOfTimeStepsWithOnlyOneIteration /= 2; } if (numberOfTimeStepsWithOnlyOneIteration>IterationsBeforeTimeStepSizeIsAltered && timeStepSize < MaximumTimeStepSize) { timeStepSize *= (1.0+ChangeOfTimeStepSize); numberOfTimeStepsWithOnlyOneIteration = 0; std::cout << "\t time step size seems to be too small. Increased to " << timeStepSize << " to speed up simulation"; } else if (numberOfTimeStepsWithOnlyOneIteration<-IterationsBeforeTimeStepSizeIsAltered && timeStepSize>MinimalTimeStepSize) { timeStepSize /= 2.0; numberOfTimeStepsWithOnlyOneIteration = 0; std::cout << "\t time step size seems to be too big. Reduced to " << timeStepSize << " to keep simulation stable"; } t += timeStepSize; timeStepCounter++; //std::cout << std::endl; } std::cout << "free data structures" << std::endl; freeDataStructures(); return 0; }
[ "edhockedy@hotmail.com" ]
edhockedy@hotmail.com
d0730e8ffe25c44508b1087dbc0f42f08fa21f60
ea537927ff592c52b8ae13ffff69f1b3c58e4d48
/video/opengl/OpenGL_shader_depth.cpp
a311b0b108dad75a45b26376b402711724199f7d
[ "MIT" ]
permissive
124327288/YuYu
eacbcbd496ee5032dcf4fdc4fc2dbc4c7b767e1e
f3598899ae5e6892a6b5d546bb0849f5d6a3c5a8
refs/heads/main
2023-02-26T03:07:04.273960
2021-01-25T20:56:28
2021-01-25T20:56:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,838
cpp
#include "yy.h" #include "OpenGL.h" #include "OpenGL_shader.h" #include "OpenGL_shader_depth.h" #include "math/mat.h" OpenGLShaderDepth::OpenGLShaderDepth() { m_program = 0; m_VAO = 0; m_uniform_World = 0; m_uniform_LightView = 0; m_uniform_LightProjection = 0; } OpenGLShaderDepth::~OpenGLShaderDepth() { if( m_VAO ) gglDeleteVertexArrays(1,&m_VAO); if( m_program ) gglDeleteProgram(m_program); } bool OpenGLShaderDepth::init() { const char * text_v = "#version 130\n" "in vec3 inputPosition;\n" "in vec2 inputTexCoord;\n" "in vec3 inputNormal;\n" "in vec3 inputBinormal;\n" "in vec3 inputTangent;\n" "out vec2 texCoord;\n" "out vec4 vertexPosition;\n" "uniform mat4 World;\n" "uniform mat4 LightView;\n" "uniform mat4 LightProjection;\n" "void main(){\n" "vertexPosition = (LightProjection * LightView * World) * vec4(inputPosition.xyz,1.0f);\n" "gl_Position = vertexPosition;\n" "texCoord.x = inputTexCoord.x;\n" "texCoord.y = 1.f - inputTexCoord.y;\n" "}\n"; const char * text_f = "#version 130\n" "in vec2 texCoord;\n" "in vec4 vertexPosition;\n" "out vec4 color;\n" "uniform sampler2D diffuseTexture;\n" "void main(){\n" "vec4 diffuse_texture = texture(diffuseTexture,texCoord);\n" "if(diffuse_texture.w < 1.f){\n" "discard;\n" "}\n" "color = vec4(vertexPosition.x, vertexPosition.y, vertexPosition.z, 1.f);\n" "}\n"; if( !createShader(text_v, text_f, nullptr, m_program) ) return false; glUseProgram(m_program); m_uniform_World = glGetUniformLocation(m_program, "World"); m_uniform_LightView = glGetUniformLocation(m_program, "LightView"); m_uniform_LightProjection = glGetUniformLocation(m_program, "LightProjection"); glUniform1i(glGetUniformLocation(m_program, "diffuseTexture"), 0); glGenVertexArrays(1, &m_VAO); return true; }
[ "artembasov@outlook.com" ]
artembasov@outlook.com
535368fd9b512e647251baa4aeb43a1b20f66b7a
45a481fd0d3037f0dc9ba24a8f2180d7891bcbc0
/GeometricTools/GTEngine/Source/Graphics/DX11/GteDX11Texture2.cpp
809180eb36c092babf6b65f6bb60b4be8332fe42
[]
no_license
macga/maskito-ios
92cca5a2ac3ab8a9120bb4ad014d2e8eda171e07
2cc752efd60204fd2226bbac60182bb6b4d30462
refs/heads/master
2021-06-08T05:43:19.064682
2016-12-01T03:44:56
2016-12-01T03:44:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,556
cpp
// Geometric Tools LLC, Redmond WA 98052 // Copyright (c) 1998-2015 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 2.0.0 (2015/09/23) #include <GTEnginePCH.h> #include <Graphics/DX11/GteDX11Texture2.h> using namespace gte; DX11Texture2::~DX11Texture2() { } DX11Texture2::DX11Texture2(ID3D11Device* device, Texture2 const* texture) : DX11TextureSingle(texture) { // Specify the texture description. D3D11_TEXTURE2D_DESC desc; desc.Width = texture->GetWidth(); desc.Height = texture->GetHeight(); desc.MipLevels = texture->GetNumLevels(); desc.ArraySize = 1; desc.Format = static_cast<DXGI_FORMAT>(texture->GetFormat()); desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.MiscFlags = (texture->IsShared() ? D3D11_RESOURCE_MISC_SHARED : D3D11_RESOURCE_MISC_NONE); Resource::Usage usage = texture->GetUsage(); if (usage == Resource::IMMUTABLE) { desc.Usage = D3D11_USAGE_IMMUTABLE; desc.CPUAccessFlags = D3D11_CPU_ACCESS_NONE; } else if (usage == Resource::DYNAMIC_UPDATE) { desc.Usage = D3D11_USAGE_DYNAMIC; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; } else // usage == Resource::SHADER_OUTPUT { desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; desc.CPUAccessFlags = D3D11_CPU_ACCESS_NONE; } if (texture->WantAutogenerateMipmaps() && !texture->IsShared()) { desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags |= D3D11_BIND_RENDER_TARGET; desc.CPUAccessFlags = D3D11_CPU_ACCESS_NONE; desc.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; } // Create the texture. ID3D11Texture2D* dxTexture = nullptr; HRESULT hr; if (texture->GetData()) { unsigned int const numSubresources = texture->GetNumSubresources(); std::vector<D3D11_SUBRESOURCE_DATA> data(numSubresources); for (unsigned int index = 0; index < numSubresources; ++index) { auto sr = texture->GetSubresource(index); data[index].pSysMem = sr.data; data[index].SysMemPitch = sr.rowPitch; data[index].SysMemSlicePitch = 0; } hr = device->CreateTexture2D(&desc, &data[0], &dxTexture); } else { hr = device->CreateTexture2D(&desc, nullptr, &dxTexture); } CHECK_HR_RETURN_VOID("Failed to create texture"); mDXObject = dxTexture; // Create views of the texture. CreateSRView(device, desc); if (texture->GetUsage() == Resource::SHADER_OUTPUT) { CreateUAView(device, desc); } // Create a staging texture if requested. if (texture->GetCopyType() != Resource::COPY_NONE) { CreateStaging(device, desc); } } DX11Texture2::DX11Texture2(ID3D11Device* device, DX11Texture2 const* dxSharedTexture) : DX11TextureSingle(dxSharedTexture->GetTexture()) { ID3D11Texture2D* dxShared = dxSharedTexture->CreateSharedDXObject(device); mDXObject = dxShared; D3D11_TEXTURE2D_DESC desc; dxShared->GetDesc(&desc); CreateSRView(device, desc); if (dxSharedTexture->GetTexture()->GetUsage() == Resource::SHADER_OUTPUT) { CreateUAView(device, desc); } } DX11GraphicsObject* DX11Texture2::Create(ID3D11Device* device, GraphicsObject const* object) { if (object->GetType() == GT_TEXTURE2) { return new DX11Texture2(device, static_cast<Texture2 const*>(object)); } LogError("Invalid object type."); return nullptr; } DX11Texture2::DX11Texture2(Texture2 const* texture) : DX11TextureSingle(texture) { } Texture2* DX11Texture2::GetTexture() const { return static_cast<Texture2*>(mGTObject); } ID3D11Texture2D* DX11Texture2::GetDXTexture() const { return static_cast<ID3D11Texture2D*>(mDXObject); } ID3D11Texture2D* DX11Texture2::CreateSharedDXObject(ID3D11Device* device) const { IDXGIResource* resource = nullptr; HRESULT hr = mDXObject->QueryInterface(__uuidof(IDXGIResource), (void**)&resource); CHECK_HR_RETURN("QueryInterface failed", nullptr); HANDLE handle = nullptr; hr = resource->GetSharedHandle(&handle); resource->Release(); CHECK_HR_RETURN("GetSharedHandle failed", nullptr); ID3D11Texture2D* dxShared = nullptr; hr = device->OpenSharedResource(handle, __uuidof(ID3D11Texture2D), (void**)&dxShared); CHECK_HR_RETURN("OpenSharedResource failed", nullptr); return dxShared; } void DX11Texture2::CreateStaging(ID3D11Device* device, D3D11_TEXTURE2D_DESC const& tx) { D3D11_TEXTURE2D_DESC desc; desc.Width = tx.Width; desc.Height = tx.Height; desc.MipLevels = tx.MipLevels; desc.ArraySize = tx.ArraySize; desc.Format = tx.Format; desc.SampleDesc.Count = tx.SampleDesc.Count; desc.SampleDesc.Quality = tx.SampleDesc.Quality; desc.Usage = D3D11_USAGE_STAGING; desc.BindFlags = D3D11_BIND_NONE; desc.CPUAccessFlags = msStagingAccess[GetTexture()->GetCopyType()]; desc.MiscFlags = D3D11_RESOURCE_MISC_NONE; HRESULT hr = device->CreateTexture2D(&desc, nullptr, reinterpret_cast<ID3D11Texture2D**>(&mStaging)); CHECK_HR_RETURN_NONE("Failed to create staging texture"); } void DX11Texture2::CreateSRView(ID3D11Device* device, D3D11_TEXTURE2D_DESC const& tx) { D3D11_SHADER_RESOURCE_VIEW_DESC desc; desc.Format = tx.Format; desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; desc.Texture2D.MostDetailedMip = 0; desc.Texture2D.MipLevels = tx.MipLevels; HRESULT hr = device->CreateShaderResourceView(GetDXTexture(), &desc, &mSRView); CHECK_HR_RETURN_NONE("Failed to create shader resource view"); } void DX11Texture2::CreateUAView(ID3D11Device* device, D3D11_TEXTURE2D_DESC const& tx) { D3D11_UNORDERED_ACCESS_VIEW_DESC desc; desc.Format = tx.Format; desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; desc.Texture2D.MipSlice = 0; HRESULT hr = device->CreateUnorderedAccessView(GetDXTexture(), &desc, &mUAView); CHECK_HR_RETURN_NONE("Failed to create unordered access view"); }
[ "gpj@foursquare.com" ]
gpj@foursquare.com
26ffc53b710fbd6d4fec51b179b15710ad4ca8ab
6c755bc109be462652ebd321145aa930f20726cd
/1/1_Cuatrimestre/FP/Practicas/Sesion_7/Opcionales/Ejercicio_33_(Numero_feliz).cpp
00b1c617a03b88917d2ae1b352cce750d89a8c4d
[]
no_license
jagolu/Universidad
150dcbc66a087dd09849b126076f92e022faeba7
e26fa9847167ab3919d700bcb975e0b1fd813839
refs/heads/master
2021-01-19T00:40:38.709662
2019-07-02T15:01:58
2019-07-02T15:01:58
73,117,449
0
1
null
null
null
null
UTF-8
C++
false
false
502
cpp
#include <iostream> #include <cmath> using namespace std; int main(){ int n, n2, n3=0, i, cifra, m=0; cout<<"Introduzca un numero entero: "; cin>>n; do{ n2=n; n3=0; for(i=1;i<=n;i=i*10){ cifra=n2%10; n2=n2/10; n3=n3+(pow(cifra,2)); } if(n3>=10){ n=n3; } else if(n2==0){ n=1; } m=m+1; }while(n>=10); if((n3==1 || n3==7) && m>=3){ cout<<"El numero es feliz. De grado: "<<m<<endl; } else{ cout<<"El numero es infeliz"<<endl; } system("pause"); }
[ "javo14795@gmail.com" ]
javo14795@gmail.com
b43c68741cac1b216bca75b72cfe401cb366fe5b
eaa0e6c89f2ee0e5f3990edc0621e9d4caf92d97
/src/runtime_lib/infra_julienne/nibble.h
08d12c6cd45ebf31828e47f79b248b4ed4c9f4e3
[ "MIT" ]
permissive
ldhulipala/graphit
4fc4060c6de26caa559096681e2176e730ac647c
708cb2947518d6aebaa62407ebe97d08a9030f4d
refs/heads/master
2020-09-10T22:03:05.422041
2019-11-15T21:10:38
2019-11-15T21:10:38
221,845,762
0
0
NOASSERTION
2019-11-15T04:44:56
2019-11-15T04:44:55
null
UTF-8
C++
false
false
11,740
h
// This code is part of the project "Smaller and Faster: Parallel // Processing of Compressed Graphs with Ligra+", presented at the IEEE // Data Compression Conference, 2015. // Copyright (c) 2015 Julian Shun, Laxman Dhulipala and Guy Blelloch // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights (to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef JULIENNE_BYTECODE_H #define JULIENNE_BYTECODE_H typedef unsigned char uchar; #include <iostream> #include <fstream> #include <stdlib.h> #include <cmath> #include "parallel.h" #include "utils.h" #include <stdio.h> #include <string.h> #define LAST_BIT_SET(b) (b & (0x8)) #define EDGE_SIZE_PER_BYTE 3 #define decode_val_nibblecode(_arr, _location, _result) \ { \ _result = 0; \ int shift = 0; \ int cont = 1; \ while(cont) { \ int tmp = _arr[(*_location>>1)]; \ /* get appropriate nibble based on location but avoid conditional */ \ tmp = (tmp >> (!((*_location)++ & 1) << 2)); \ _result |= ((long)(tmp & 0x7) << shift); \ shift +=3; \ cont = tmp & 0x8; \ } \ } \ /* Nibble-encodes a value, with params: start : pointer to byte arr offset : offset into start, in number of 1/2 bytes val : the val to encode */ long encode_nibbleval(uchar* start, long offset, long val) { uchar currNibble = val & 0x7; while (val > 0) { uchar toWrite = currNibble; val = val >> 3; currNibble = val & 0x7; if(val > 0) toWrite |= 0x8; if(offset & 1) { start[offset/2] |= toWrite; } else { start[offset/2] = (toWrite << 4); } offset++; } return offset; } /** Decodes the first edge, which is specially sign encoded. */ inline uintE decode_first_edge(uchar* &start, long* location, uintE source) { long val; decode_val_nibblecode(start, location, val) long sign = val & 1; val >>= 1; // get rid of sign long result = source; if (sign) result += val; else result -= val; return result; } /* Decodes an edge, but does not add back the */ inline uintE decode_next_edge(uchar* &start, long* location) { long val; decode_val_nibblecode(start, location, val); return val; } /* The main decoding work-horse. First eats the specially coded first edge, and then eats the remaining |d-1| many edges that are normally coded. */ template <class T> inline void decode(T t, uchar* edgeArr, const uintE &source, const uintT &degree, const bool par=true) { uintE edgesRead = 0; long location = 0; if (degree > 0) { uintE startEdge = decode_first_edge(edgeArr, &location, source); uintE prevEdge = startEdge; if (!t.srcTarg(source,startEdge,edgesRead)) { return; } for (edgesRead = 1; edgesRead < degree; edgesRead++) { uintE edgeRead = decode_next_edge(edgeArr, &location); uintE edge = edgeRead + prevEdge; prevEdge = edge; if (!t.srcTarg(source, edge, edgesRead)) { break; } } } } //decode edges for weighted graph template <class T> inline void decodeWgh(T t, uchar* edgeStart, const uintE &source,const uintT &degree, const bool par=true) { uintT edgesRead = 0; long location = 0; if (degree > 0) { // Eat first edge, which is compressed specially uintE startEdge = decode_first_edge(edgeStart,&location,source); intE weight = decode_first_edge(edgeStart,&location,0); if (!t.srcTarg(source,startEdge, weight, edgesRead)) { return; } for (edgesRead = 1; edgesRead < degree; edgesRead++) { uintE edgeRead = decode_next_edge(edgeStart, &location); uintE edge = startEdge + edgeRead; startEdge = edge; intE weight = decode_first_edge(edgeStart,&location,0); if (!t.srcTarg(source, edge, weight, edgesRead)) { break; } } } } /* Takes: 1. The edge array of chars to write into 2. The current offset into this array 3. The vertices degree 4. The vertices vertex number 5. The array of saved out-edges we're compressing Returns: The new offset into the edge array */ long sequentialCompressEdgeSet(uchar *edgeArray, long currentOffset, uintT degree, uintE vertexNum, uintE *savedEdges) { if (degree > 0) { // Compress the first edge whole, which is signed difference coded long preCompress = (long) savedEdges[0] - vertexNum; long toCompress = labs(preCompress); intE sign = 1; if (preCompress < 0) { sign = 0; } toCompress = (toCompress << 1) | sign; long temp = currentOffset; currentOffset = encode_nibbleval(edgeArray, currentOffset, toCompress); long val; //for debugging only //decode_val_nibblecode(edgeArray,&temp,val); //if(val != toCompress) {cout << "decoding error! got "<<val<<" but should've been "<<(savedEdges[0])<<" " <<vertexNum<<" "<<preCompress<<" " << labs(preCompress)<<" " << toCompress<<" " << (val >> 1)<<endl; exit(0);} for (uintT edgeI=1; edgeI < degree; edgeI++) { // Store difference between cur and prev edge. uintE difference = savedEdges[edgeI] - savedEdges[edgeI - 1]; temp = currentOffset; currentOffset = encode_nibbleval(edgeArray, currentOffset, difference); //for debugging only //decode_val_nibblecode(edgeArray,&temp,val); //if(val != difference) {cout << "decoding error! got "<<val<<" but should've been "<<(savedEdges[0])<<" " <<vertexNum<<" "<<difference<<endl; exit(0);} } } return currentOffset; } /* Compresses the edge set in parallel. */ static inline uintE *parallelCompressEdges(uintE *edges, uintT *offsets, long n, long m, uintE* Degrees) { cout << "parallel compressing, (n,m) = (" << n << "," << m << ")" << endl; uintE **edgePts = newA(uintE*, n); long *charsUsedArr = newA(long, n); long *compressionStarts = newA(long, n+1); {parallel_for(long i=0; i<n; i++) { charsUsedArr[i] = ceil((Degrees[i] * 9) / 8) + 4; }} long toAlloc = sequence::plusScan(charsUsedArr,charsUsedArr,n); uintE* iEdges = newA(uintE,toAlloc); {parallel_for(long i=0; i<n; i++) { edgePts[i] = iEdges+charsUsedArr[i]; long charsUsed = sequentialCompressEdgeSet((uchar *)(iEdges+charsUsedArr[i]), 0, Degrees[i], i, edges + offsets[i]); // convert units from #1/2 bytes -> #bytes, round up to make it //byte-aligned charsUsed = (charsUsed+1) / 2; charsUsedArr[i] = charsUsed; }} long totalSpace = sequence::plusScan(charsUsedArr, compressionStarts, n); compressionStarts[n] = totalSpace; // in bytes free(charsUsedArr); uchar *finalArr = newA(uchar, totalSpace); cout << "total space requested is : " << totalSpace << endl; float avgBitsPerEdge = (float)totalSpace*8 / (float)m; cout << "Average bits per edge: " << avgBitsPerEdge << endl; {parallel_for(long i=0; i<n; i++) { long o = compressionStarts[i]; memcpy(finalArr + o, (uchar *)(edgePts[i]), compressionStarts[i+1]-o); offsets[i] = o; }} offsets[n] = totalSpace; free(iEdges); free(edgePts); free(compressionStarts); cout << "finished compressing, bytes used = " << totalSpace << endl; cout << "would have been, " << (m * 4) << endl; return ((uintE*)finalArr); } typedef pair<uintE,intE> intEPair; /* Takes: 1. The edge array of chars to write into 2. The current offset into this array 3. The vertices degree 4. The vertices vertex number 5. The array of saved out-edges we're compressing Returns: The new offset into the edge array */ long sequentialCompressWeightedEdgeSet (uchar *edgeArray, long currentOffset, uintT degree, uintE vertexNum, intEPair *savedEdges) { if (degree > 0) { // Compress the first edge whole, which is signed difference coded //target ID intE preCompress = savedEdges[0].first - vertexNum; intE toCompress = abs(preCompress); intE sign = 1; if (preCompress < 0) { sign = 0; } toCompress = (toCompress<<1)|sign; currentOffset = encode_nibbleval(edgeArray, currentOffset, toCompress); //weight intE weight = savedEdges[0].second; if (weight < 0) sign = 0; else sign = 1; toCompress = (abs(weight)<<1)|sign; currentOffset = encode_nibbleval(edgeArray, currentOffset, toCompress); for (uintT edgeI=1; edgeI < degree; edgeI++) { // Store difference between cur and prev edge. uintE difference = savedEdges[edgeI].first - savedEdges[edgeI - 1].first; //compress difference currentOffset = encode_nibbleval(edgeArray, currentOffset, difference); //compress weight weight = savedEdges[edgeI].second; if (weight < 0) sign = 0; else sign = 1; toCompress = (abs(weight)<<1)|sign; currentOffset = encode_nibbleval(edgeArray, currentOffset, toCompress); } // Increment nWritten after all of vertex n's neighbors are written } return currentOffset; } /* Compresses the weighted edge set in parallel. */ static inline uchar *parallelCompressWeightedEdges(intEPair *edges, uintT *offsets, long n, long m, uintE* Degrees) { cout << "parallel compressing, (n,m) = (" << n << "," << m << ")" << endl; uintE **edgePts = newA(uintE*, n); long *charsUsedArr = newA(long, n); long *compressionStarts = newA(long, n+1); {parallel_for(long i=0; i<n; i++) { charsUsedArr[i] = 2*(ceil((Degrees[i] * 9) / 8) + 4); //to change }} long toAlloc = sequence::plusScan(charsUsedArr,charsUsedArr,n); uintE* iEdges = newA(uintE,toAlloc); {parallel_for(long i=0; i<n; i++) { edgePts[i] = iEdges+charsUsedArr[i]; long charsUsed = sequentialCompressWeightedEdgeSet((uchar *)(iEdges+charsUsedArr[i]), 0, Degrees[i], i, edges + offsets[i]); charsUsed = (charsUsed+1) / 2; charsUsedArr[i] = charsUsed; }} // produce the total space needed for all compressed lists in # of 1/2 bytes long totalSpace = sequence::plusScan(charsUsedArr, compressionStarts, n); compressionStarts[n] = totalSpace; free(charsUsedArr); uchar *finalArr = newA(uchar, totalSpace); cout << "total space requested is : " << totalSpace << endl; float avgBitsPerEdge = (float)totalSpace*8 / (float)m; cout << "Average bits per edge: " << avgBitsPerEdge << endl; {parallel_for(long i=0; i<n; i++) { long o = compressionStarts[i]; memcpy(finalArr + o, (uchar *)(edgePts[i]), compressionStarts[i+1]-o); offsets[i] = o; }} offsets[n] = totalSpace; free(iEdges); free(edgePts); free(compressionStarts); cout << "finished compressing, bytes used = " << totalSpace << endl; cout << "would have been, " << (m * 8) << endl; return finalArr; } #endif
[ "ajaybr@mit.edu" ]
ajaybr@mit.edu
59169c338a180995a5bf39757c02b519fee7345f
dceab0b4e5bfb68bf6de77c6327b6c77b9e00bd4
/Gemini/Engine/Graphics/Sprite.cpp
86a646eea710b85e9edbb1f47fe59558ec1146a5
[ "MIT" ]
permissive
drahenshaw/Gemini
2596855c258f118b3a731d93221b04bfaf7c3da3
71a4f215daf1dd10c9076aaacc1292a6a039b89b
refs/heads/master
2021-10-19T09:20:29.775020
2019-02-20T00:37:02
2019-02-20T00:37:02
167,228,597
0
0
null
null
null
null
UTF-8
C++
false
false
4,218
cpp
#include "Sprite.h" #include "../Engine.h" const int GEMINI_DEFAULT_SPEED = 100; //Constructs a Textureless Sprite Sprite::Sprite() { position_ = Vector3(0); rotation_ = 0; speed_ = GEMINI_DEFAULT_SPEED; scale_ = Vector3(1); size_ = Vector3(0); } //Constructs Sprite with Texture Sprite::Sprite(std::string file_path, Error * error) { texture_ = Texture(file_path, error); position_ = Vector3(0); rotation_ = 0; speed_ = GEMINI_DEFAULT_SPEED; scale_ = Vector3(1); size_ = Vector3((float)texture_.get_width(), (float)texture_.get_height(), 1); } //Constructs Sprite with Texture and Starting Position Sprite::Sprite(std::string file_path, Vector3 position, Error * error) { texture_ = Texture(file_path, error); position_ = position; rotation_ = 0; speed_ = GEMINI_DEFAULT_SPEED; scale_ = Vector3(1); size_ = Vector3((float)texture_.get_width(), (float)texture_.get_height(), 1); } void Sprite::Update() { } //void Sprite::Render() //{ // //Enable 2D Texture Operations and Bind those Operations to member texture_ // glEnable(GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, texture_.get_id()); // glLoadIdentity(); // // //Matrix Operations are done in reverse order to properly center them // //TRANSLATE -> ROTATE -> SCALE // glTranslatef(position_.x_, position_.y_, 0); // glRotatef(rotation_, 0, 0, 1); // glScalef(scale_.x_, scale_.y_, 1); // // //Rendering // glColor4f(1, 1, 1, 1); // //Begin and End allow for texture coordinates to be updated. // glBegin(GL_QUADS); // { // //Assigning the texture vertices to the corners of the image // glTexCoord2f(0, 0); glVertex2i(-texture_.get_width() / 2, -texture_.get_height() / 2); // glTexCoord2f(1, 0); glVertex2i( texture_.get_width() / 2, -texture_.get_height() / 2); // glTexCoord2f(1, 1); glVertex2i( texture_.get_width() / 2, texture_.get_height() / 2); // glTexCoord2f(0, 1); glVertex2i(-texture_.get_width() / 2, texture_.get_height() / 2); // } // glEnd(); // // //Disable 2D Texture Operations // glDisable(GL_TEXTURE_2D); //} void Sprite::Render() { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture_.get_id()); glLoadIdentity(); //TRANSLATE -> ROTATE -> SCALE glTranslatef(position_.x_, position_.y_, 0); glRotatef(rotation_, 0, 0, 1); glScalef(scale_.x_, scale_.y_, 1); // Rendering // Set the Color - Default is 1,1,1,1 which renders original colors glColor4f(1, 1, 1, 1); glBegin(GL_QUADS); { glTexCoord2f(0, 0); glVertex2i(-texture_.get_width() / 2, -texture_.get_height() / 2); glTexCoord2f(1, 0); glVertex2i( texture_.get_width() / 2, -texture_.get_height() / 2); glTexCoord2f(1, 1); glVertex2i( texture_.get_width() / 2, texture_.get_height() / 2); glTexCoord2f(0, 1); glVertex2i(-texture_.get_width() / 2, texture_.get_height() / 2); } glEnd(); glDisable(GL_TEXTURE_2D); } //Adjust speed by a relative amount void Sprite::ChangeSpeedBy(float x) { speed_ += x; } //Adjust speed to an absolute amount void Sprite::ChangeSpeedTo(float x) { speed_ = x; } //Move to a given position void Sprite::MoveTo(Vector3 v) { position_ = v; } void Sprite::MoveBy(Vector3 v) { position_ = position_ + (v * Engine::get_dT()); } void Sprite::MoveLeft() { position_ = position_ - Vector3(speed_ * Engine::get_dT(), 0, 0); } void Sprite::MoveRight() { position_ = position_ + Vector3(speed_ * Engine::get_dT(), 0, 0); } void Sprite::MoveUp() { position_ = position_ + Vector3(0, speed_ * Engine::get_dT(), 0); } void Sprite::MoveDown() { position_ = position_ - Vector3(0, speed_ * Engine::get_dT(), 0); } void Sprite::RotateTo(float rotation) { rotation_ = rotation; } void Sprite::RotateBy(float rotation) { rotation_ = rotation_ + (rotation * Engine::get_dT()); } void Sprite::setScale(float globalScale) { scale_ = Vector3(globalScale); } void Sprite::setScale(Vector3 v) { scale_ = v; } void Sprite::FlipHorizontal() { scale_.x_ = -scale_.x_; } void Sprite::FlipVertical() { scale_.y_ = -scale_.y_; } Vector3 * Sprite::get_position() { return &position_; } float * Sprite::get_rotation() { return &rotation_; } Vector3 * Sprite::get_scale() { return &scale_; } Vector3 * Sprite::get_size() { return &size_; }
[ "drahenshaw@gmail.com" ]
drahenshaw@gmail.com
cae36d0ad92fffac3eb8f03d01e91c0c209a0347
c08bd267d70647131a856d0b2ec4e29c1db85218
/EDA 1er año/PeliculasResuelto.cpp
389aa27bd9a4e61c9760340d13622b08844355e2
[]
no_license
Vantile/EDA
e93b7513347e6eaa1dd4173f3218578b82ee761f
03d9b35a1094f3d0d206bb7d2f483bc620422a39
refs/heads/master
2020-05-21T02:35:40.518130
2017-11-24T22:29:02
2017-11-24T22:29:02
84,556,239
0
0
null
null
null
null
UTF-8
C++
false
false
4,410
cpp
#include <iostream> #include <iomanip> #include <vector> #include <stdexcept> #include <string> #include <algorithm> using namespace std; class Horas { public: Horas() { horas = 0; minutos = 0; segundos = 0; } Horas(int h, int m, int s) { if (h <= 23 && h >= 0 && m >= 0 && m <= 59 && s >= 0 && s <= 59) { horas = h; minutos = m; segundos = s; } else throw invalid_argument("ERROR"); } bool operator< (const Horas &a) const { bool aux = false; if (horas < a.horas) aux = true; else if (horas == a.horas) { if (minutos < a.minutos) aux = true; else if (minutos == a.minutos) { if (segundos < a.segundos) aux = true; } } return aux; } const bool operator==(const Horas &a) { bool aux = false; if (a.horas == horas && a.minutos == minutos && a.segundos == segundos) aux = true; return aux; } const bool operator<= (const Horas &a) { bool aux = false; if (horas < a.horas) aux = true; else if (horas == a.horas) { if (minutos < a.minutos) aux = true; else if (minutos == a.minutos) { if (segundos < a.segundos) aux = true; else if (segundos == a.segundos) aux = true; } } return aux; } const Horas& operator+(const Horas &a) { this->segundos += a.segundos; if (this->segundos >= 60) { this->minutos++; this->segundos = this->segundos % 60; } this->minutos += a.minutos; if (this->minutos >= 60) { this->horas++; this->minutos = this->minutos % 60; } this->horas += a.horas; if (this->horas >= 24) throw "Error"; return *this; } void copiar(const Horas &h) { horas = h.horas; minutos = h.minutos; segundos = h.segundos; } friend istream& operator>>(istream &i, Horas &h); friend ostream& operator<<(ostream &o, const Horas &h); private: int horas; int minutos; int segundos; }; class Peliculas { public: Peliculas() { finaliz = Horas(); titulo = ""; } Peliculas(Horas f, string t) { finaliz = Horas(); finaliz.copiar(f); titulo = t; } Peliculas(Horas i, Horas d, string t) { finaliz = Horas(0, 0, 0); finaliz.copiar(i + d); titulo = t; } bool operator<(const Peliculas& a) const { bool aux = false; if (this->finaliz < a.finaliz) aux = true; return aux; } const bool operator==(const Peliculas &a) { bool aux = false; if (this->finaliz == a.finaliz && this->titulo == a.titulo) aux = true; return aux; } void copiar(Peliculas &p) { this->finaliz = p.finaliz; this->titulo = p.titulo; } friend istream& operator>>(istream &i, Peliculas &p); friend ostream& operator<<(ostream &o, const Peliculas &p); friend void ordAlpha(vector<Peliculas> &v); private: Horas finaliz; string titulo; }; istream& operator>>(istream &i, Horas &h) // operator>> de Horas. { char aux; int hs, m, s; i >> hs >> aux >> m >> aux >> s; if (hs <= 23 && hs >= 0 && m <= 59 && m >= 0 && s <= 59 && s >= 0) { h.horas = hs; h.minutos = m; h.segundos = s; } else throw invalid_argument("ERROR extractor"); i.ignore(); return i; } istream& operator>>(istream &i, Peliculas &p) // operator>> de Peliculas. { Horas ini, dur; string titulo; i >> ini; i >> dur; getline(i, titulo); p.finaliz = ini + dur; p.titulo = titulo; return i; } ostream& operator<<(ostream &o, const Horas &h) // operator<< de Horas. { o << setfill('0') << setw(2) << h.horas << ":" << setfill('0') << setw(2) << h.minutos << ":" << setfill('0') << setw(2) << h.segundos; return o; } ostream& operator<<(ostream &o, const Peliculas &p) // operator<< de Peliculas. { o << p.finaliz << " " << p.titulo; return o; } void ordAlpha(vector<Peliculas> &v) { unsigned int i = 0; Peliculas aux; while (i < v.size() - 1) { if (v[i].finaliz == v[i + 1].finaliz && v[i].titulo > v[i + 1].titulo) { aux.copiar(v[i]); v[i].copiar(v[i + 1]); v[i + 1].copiar(aux); } i++; } } void cine(unsigned const int numPelis) { vector<Peliculas> v; Peliculas pelicula; unsigned int i = 0; while (i < numPelis) { try { cin >> pelicula; v.push_back(pelicula); } catch (...) { } i++; } sort(v.begin(), v.end()); ordAlpha(v); i = 0; while (i < v.size()) { cout << v[i] << endl; i++; } cout << "---" << endl; } int main() { unsigned int numPelis = 0; cin >> numPelis; while (numPelis != 0) { cine(numPelis); cin >> numPelis; } }
[ "vantilesyfon@gmail.com" ]
vantilesyfon@gmail.com
49edea0f8861162c07b8020aee089aa0da632acc
622e2dca03240309e1e2195366b9507661602b28
/Challenges Bitmasking/Counting set bits/solution.cpp
4a2423d668b1211d47db88703c9485b7d82a7ca3
[]
no_license
akash350poria/CodingBlocks
511c8357f7ae5b7f7daf319faf7ac30ece073521
0a6be9476519f84b592de0dbe38f995a799aadbf
refs/heads/master
2023-03-03T08:13:37.829766
2021-02-12T15:29:40
2021-02-12T15:29:40
291,919,811
1
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include <iostream> using namespace std; int countBits(int n) { int ans = 0; while (n > 0) { n = n & (n - 1); ans++; } return ans; } int main() { int t; cin >> t; int n; while (t--) { cin >> n; cout << countBits(n) << endl; } return 0; }
[ "akash350poria@gmail.com" ]
akash350poria@gmail.com
204c1c842bd219cfc72af6b0e28ebaad7dcc5978
cdb55dbdd700a3f456bc67775374dd2a5f99f049
/test/src/physics/collision/narrowphase/algorithm/epa/EPAConvexObjectTest.h
cce5abca291eb70a809858ac7a81060ac9c70434
[ "MIT" ]
permissive
wangscript007/urchinEngine
1bfd6fb9ae6ed30154d29b082856101b9a8ef202
88f5f70d319299e2df6c006cdeabd6bfb622437b
refs/heads/master
2022-12-30T18:06:53.231268
2020-10-07T19:03:56
2020-10-07T19:03:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
388
h
#ifndef URCHINENGINE_EPACONVEXOBJECTTEST_H #define URCHINENGINE_EPACONVEXOBJECTTEST_H #include <cppunit/TestFixture.h> #include <cppunit/Test.h> class EPAConvexObjectTest : public CppUnit::TestFixture { public: static CppUnit::Test *suite(); void overlapSphereAndBox(); void overlapCapsuleAndTriangle(); void overlapTriangleAndCapsule(); }; #endif
[ "petitg1987@gmail.com" ]
petitg1987@gmail.com
b8dfe7068b4fe40e9ae7220f0a8b7aaf8fa11a5c
164e709dcf03ce4769c3ba8f874da0666c35bc03
/RtTpsRenderLibrary/graphic_object/tps_rl_hot_spots_graphicobject.cpp
192549fcc106c08878feae944d0bab930db4cd98
[]
no_license
liq07lzucn/tps
b343894bcfd59a71be48bd47d6eff6e010464457
a3be6dc50c5f9a2ff448ecff3f5df1956e26ad4f
refs/heads/master
2021-06-23T16:35:01.349523
2017-08-30T08:09:02
2017-08-30T08:09:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,969
cpp
//////////////////////////////////////////////////////////////// /// Copyright (c) Shanghai United Imaging Healthcare Inc., 2013 /// All rights reserved. /// /// \author LI Song song.li@united-imaging.com /// /// \file tps_rl_hotspots_graphicobject.cpp /// /// \brief class CrosshairGraphicObejct implementation /// /// \version 1.0 /// /// \date 2014/07/07 //////////////////////////////////////////////////////////////// #include "StdAfx.h" #include "RtTpsRenderLibrary/tps_rl_hot_spots_graphicobject.h" TPS_BEGIN_NAMESPACE HotSpotsGraphicObject::HotSpotsGraphicObject(): m_bVisible(true) { } HotSpotsGraphicObject::~HotSpotsGraphicObject() { } bool HotSpotsGraphicObject::Initialize() { return true; } bool HotSpotsGraphicObject::Finalize() { return true; } HotColdContourPointer HotSpotsGraphicObject::GetVecPointsByNameAndPlanUid(const std::string& windowName, const std::string& planUid) { if (planUid.empty()) return nullptr; std::map<std::string, HotColdContourPointer>::iterator it; if (windowName == "Axial") { if (m_spVecPoints_Axial_Map.size() <= 0) { return nullptr; } else { it = m_spVecPoints_Axial_Map.find(planUid); if (it == m_spVecPoints_Axial_Map.end()) { return nullptr; } return m_spVecPoints_Axial_Map[planUid]; } } else if (windowName == "Sagittal") { if (m_spVecPoints_Sagittal_Map.size() <= 0) { return nullptr; } else { it = m_spVecPoints_Sagittal_Map.find(planUid); if (it == m_spVecPoints_Sagittal_Map.end()) { return nullptr; } return m_spVecPoints_Sagittal_Map[planUid]; } } else if (windowName == "Coronal") { if (m_spVecPoints_Coronal_Map.size() <= 0) { return nullptr; } else { it = m_spVecPoints_Coronal_Map.find(planUid); if (it == m_spVecPoints_Coronal_Map.end()) { return nullptr; } return m_spVecPoints_Coronal_Map[planUid]; } } else { return nullptr; } } void HotSpotsGraphicObject::ClearVecPointsByPlanUid(const std::string& planUid) { if (planUid.empty()) return; std::map<std::string, HotColdContourPointer>::iterator it = m_spVecPoints_Axial_Map.find(planUid); if (it != m_spVecPoints_Axial_Map.end()) { m_spVecPoints_Axial_Map.erase(it); } it = m_spVecPoints_Coronal_Map.find(planUid); if (it != m_spVecPoints_Coronal_Map.end()) { m_spVecPoints_Coronal_Map.erase(it); } it = m_spVecPoints_Sagittal_Map.find(planUid); if (it != m_spVecPoints_Sagittal_Map.end()) { m_spVecPoints_Sagittal_Map.erase(it); } } TPS_END_NAMESPACE
[ "genius52@qq.com" ]
genius52@qq.com
4ef4df39456a15810f5542b597b5ebcc5b23bca4
6f20136c14684eb6f1ede09da49074ef9f3b4c8c
/robot2018/src/Commands/Chassis/Turn.cpp
93f27cfeb6cdbbb48f7314214309c7ccbe8e92d3
[]
no_license
Team3835Vulcan/robot-2018
952e8024e0b28a347e9d5cd29a2451f8d364fcc6
180bf153327f67e594cf1c55f548863d7c8d87be
refs/heads/master
2021-03-27T16:31:40.225482
2018-06-05T12:09:15
2018-06-05T12:09:15
116,581,372
1
0
null
2018-01-11T19:05:00
2018-01-07T16:34:02
C++
UTF-8
C++
false
false
1,412
cpp
#include "Turn.h" #include <Subsystems/Chassis/Chassis.h> #include <cmath> Turn::Turn(double angle) : m_angle(angle), m_controller(0,0,0), m_timeout(angle/45.0) { // Use Requires() here to declare subsystem dependencies m_controller.SetPID(0.025,0,0.0015); m_controller.SetInputRange(0,360); m_controller.SetOutputRange(-1,1); m_controller.SetTolerance(1); Requires(&Chassis::GetInstance()); } // Called just before this Command runs the first time void Turn::Initialize() { t.Reset(); m_controller.Reset(); m_controller.SetSetpoint(std::fmod( Chassis::GetInstance().GetAngle() + m_angle, 360.0)); m_controller.Enable(); t.Start(); } // Called repeatedly when this Command is scheduled to run void Turn::Execute() { m_controller.Calculate(Chassis::GetInstance().GetAngle()); double output = -m_controller.GetOutput(); Chassis::GetInstance().TankDrive(output, -output); } // Make this return true when this Command no longer needs to run execute() bool Turn::IsFinished() { return m_controller.IsOnTarget() || t.Get() >= m_timeout; } // Called once after isFinished returns true void Turn::End() { m_controller.Disable(); Chassis::GetInstance().TankDrive(0, 0); t.Stop(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run void Turn::Interrupted() { m_controller.Disable(); Chassis::GetInstance().TankDrive(0, 0); t.Stop(); }
[ "nd.strahilevitz@gmail.com" ]
nd.strahilevitz@gmail.com
a8b4645bb6c9ffa6ac2d8757caed3644784c3b5a
872e493bb8649ab40f94264d1d5e26e572c7946f
/MediaPlayer(Server)/title.cpp
8c977605e0f47f987ef88ca382598ce12cc6964d
[]
no_license
MasterDjefer/MediaPlayer
276e2b35cc62bd7b51dfc7d2d737b798867a5140
a2667f05d1ed292a2e846b12d3b11fc941f693fe
refs/heads/master
2020-04-17T15:03:00.961355
2019-02-02T20:06:29
2019-02-02T20:06:29
166,683,058
0
0
null
null
null
null
UTF-8
C++
false
false
153
cpp
#include "title.h" Title::Title(const QString title) : MusicInfo(title) { } QString Title::toString() const { return QString("Title: " + mData); }
[ "kostia210@gmail.com" ]
kostia210@gmail.com
b62bd4e4dd738c34ce9ad72966adfb74070880ac
003675a2e2be3f835efd723626f0ee6d862e914f
/Codeforces/A/1333A.cpp
090af292e40129d3c1ddae63e8177c86436337ff
[]
no_license
AkibShahrear/Competitive-Programming
6f4b26af1ae011d3cf45885dc86c4f64fca4334d
7fba94f669881dd7e7cb63b264c288c380c5d544
refs/heads/main
2023-08-12T16:57:41.020418
2021-10-18T19:49:44
2021-10-18T19:49:44
323,955,265
0
0
null
2020-12-23T17:17:59
2020-12-23T16:49:51
null
UTF-8
C++
false
false
500
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,m; cin>>n>>m; char a[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(i==0 && j==0) { cout<<'W'; } else{ cout<<'B'; } } cout<<'\n'; } } }
[ "noreply@github.com" ]
AkibShahrear.noreply@github.com
5f8e7510e26649471c5b50b3ef816b4f908a88d9
e7f09311ac30590f7ac7a21b626ad74641d7b80b
/src/object.cpp
65e118b86eea4070f7dfc68ba597acc811041a64
[]
no_license
Smedase-White/mp2-lab3-stack
929d3e1ed168d5f829b3f9510a8d2437cf70317d
bcd4404d30fbfec383a912748a9ce5002851d979
refs/heads/master
2023-01-29T18:06:42.967119
2020-12-04T14:10:32
2020-12-04T14:10:32
318,536,311
0
0
null
2020-12-07T12:59:53
2020-12-04T14:11:54
C++
UTF-8
C++
false
false
2,144
cpp
#include "objects.h" #include <string> Number::Number(int _num) { setType(tNumber); num = _num; } Number::Number(Object& o) { setType(tNumber); num = o.getSomething(); } int Number::getSomething() { return num; } int Number::getSomething(const int num) { return num; } int Number::getSomething(const int num1, const int num2) { return num; } ostream& operator<<(ostream& out, const Number& n) { out << n.num << " "; return out; } string Number::getString() { return std::to_string(getSomething()); } Operation::Operation(char symb) { setType(tOperation); switch (symb) { case '+': op = new Add<int>(); break; case '-': op = new Sub<int>(); break; case '*': op = new Mul<int>(); break; case '/': op = new Div<int>(); break; default: throw logic_error("Invalid operation"); break; } } Operation::Operation(Object& o) { setType(tOperation); switch (o.getSomething(1)) { case '+': op = new Add<int>(); break; case '-': op = new Sub<int>(); break; case '*': op = new Mul<int>(); break; case '/': op = new Div<int>(); break; default: throw logic_error("Invalid operation"); break; } } Operation::~Operation() { delete op; } int Operation::getSomething() { return op->getPriority(); } int Operation::getSomething(const int num) { return op->getSymbol(); } int Operation::getSomething(const int num1, const int num2) { return op->doOp(num1, num2); } ostream& operator<<(ostream& out, const Operation& op) { out << (char)op.op->getSymbol() << " "; return out; } string Operation::getString() { string s; s.insert(0, 1, (char)getSomething(1)); return s; } Bracket::Bracket(bool _is) { setType(tBrackets); isOpen = _is; } Bracket::Bracket(Object& o) { setType(tBrackets); isOpen = o.getSomething(); } int Bracket::getSomething() { return isOpen; } int Bracket::getSomething(const int num) { return isOpen; } int Bracket::getSomething(const int num1, const int num2) { return isOpen; } ostream& operator<<(ostream& out, const Bracket& b) { if (b.isOpen) out << "( "; else out << ") "; return out; } string Bracket::getString() { if (isOpen) return "("; else return ")"; }
[ "unconfigured@null.spigotmc.org" ]
unconfigured@null.spigotmc.org
8e43335e606313b972fe04b4dc3a768a9920ceab
5a0d25eb307984f564527bc1875933b9b68f612e
/ptz/tour8/G/g_prec.cpp
d236ba1c88fe8a6fd22478dc6befebf068c3c81f
[]
no_license
ssmike/acm
b42e74f7456e7961ccf1fda36b3e2cf90b2b6076
c9ce1876ce3a3ad23846923a2bce85b53dc64c82
refs/heads/master
2016-09-09T22:19:19.502341
2015-08-21T17:04:32
2015-08-21T17:04:32
30,544,731
0
0
null
null
null
null
UTF-8
C++
false
false
11,536
cpp
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <iostream> #include <cassert> #include <cmath> #include <string> #include <queue> #include <set> #include <map> #include <cstdlib> using namespace std; #define INF 1e+9 #define mp make_pair #define pb push_back #define fi first #define fs first #define se second #define i64 long long #define li long long #define lint long long #define pii pair<int, int> #define vi vector<int> #define forn(i, n) for (int i = 0; i < (int)n; i++) #define fore(i, b, e) for (int i = (int)b; i <= (int)e; i++) #define TASKNAME "greater" void solve(int test_number); int main() { ios_base::sync_with_stdio(false); cout.setf(ios::fixed); cout.precision(9); cerr.setf(ios::fixed); cerr.precision(3); #ifdef LOCAL freopen("inp", "r", stdin); //freopen("outp", "w", stdout); #else freopen(TASKNAME ".in", "r", stdin); freopen(TASKNAME ".out", "w", stdout); #endif //int n = 1; // scanf("%d", &n); int i = 1; while(true) solve(i); } const double arr[] = { 0.2500000000, 0.2500000000, 0.3333333333, 0.3333333333, 0.3750000000, 0.3750000000, 0.4000000000, 0.4000000000, 0.4166666667, 0.4166666667, 0.4285714286, 0.4285714286, 0.4375000000, 0.4375000000, 0.4444444444, 0.4444444444, 0.4500000000, 0.4500000000, 0.3125000000, 0.3125000000, 0.4197530864, 0.4074074074, 0.4453125000, 0.4296875000, 0.4640000000, 0.4464000000, 0.4714506173, 0.4498456790, 0.4752186589, 0.4556434819, 0.4794921875, 0.4572753906, 0.4798049078, 0.4587715287, 0.4825000000, 0.4601000000, 0.3437500000, 0.3437500000, 0.4513031550, 0.4320987654, 0.4733886719, 0.4453125000, 0.4813440000, 0.4466560000, 0.4821459191, 0.4486454047, 0.4847470017, 0.4497020799, 0.4870758057, 0.4495086670, 0.4862647029, 0.4474984053, 0.4860210000, 0.4487690000, 0.3632812500, 0.3632812500, 0.4657826551, 0.4415485444, 0.4824829102, 0.4500732422, 0.4881945600, 0.4486016000, 0.4883729376, 0.4430863959, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3769531250, 0.3769531250, 0.4737760165, 0.4466290708, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3872070312, 0.3872070312, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, 0.2500000000, 0.2500000000, 0.3333333333, 0.3333333333, 0.3750000000, 0.3750000000, 0.4000000000, 0.4000000000, 0.4166666667, 0.4166666667, 0.4285714286, 0.4285714286, 0.4375000000, 0.4375000000, 0.4444444444, 0.4444444444, 0.4500000000, 0.4500000000, 0.3125000000, 0.3125000000, 0.4197530864, 0.4074074074, 0.4453125000, 0.4296875000, 0.4640000000, 0.4464000000, 0.4714506173, 0.4498456790, 0.4752186589, 0.4556434819, 0.4794921875, 0.4572753906, 0.4798049078, 0.4587715287, 0.4825000000, 0.4601000000, 0.3437500000, 0.3437500000, 0.4513031550, 0.4320987654, 0.4733886719, 0.4453125000, 0.4813440000, 0.4466560000, 0.4821459191, 0.4486454047, 0.4847470017, 0.4497020799, 0.4870758057, 0.4495086670, 0.4862647029, 0.4474984053, 0.4860210000, 0.4487690000, 0.3632812500, 0.3632812500, 0.4657826551, 0.4415485444, 0.4824829102, 0.4500732422, 0.4881945600, 0.4486016000, 0.4883729376, 0.4430863959, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3769531250, 0.3769531250, 0.4737760165, 0.4466290708, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3872070312, 0.3872070312, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, 0.2500000000, 0.2500000000, 0.3333333333, 0.3333333333, 0.3750000000, 0.3750000000, 0.4000000000, 0.4000000000, 0.4166666667, 0.4166666667, 0.4285714286, 0.4285714286, 0.4375000000, 0.4375000000, 0.4444444444, 0.4444444444, 0.4500000000, 0.4500000000, 0.3125000000, 0.3125000000, 0.4197530864, 0.4074074074, 0.4453125000, 0.4296875000, 0.4640000000, 0.4464000000, 0.4714506173, 0.4498456790, 0.4752186589, 0.4556434819, 0.4794921875, 0.4572753906, 0.4798049078, 0.4587715287, 0.4825000000, 0.4601000000, 0.3437500000, 0.3437500000, 0.4513031550, 0.4320987654, 0.4733886719, 0.4453125000, 0.4813440000, 0.4466560000, 0.4821459191, 0.4486454047, 0.4847470017, 0.4497020799, 0.4870758057, 0.4495086670, 0.4862647029, 0.4474984053, 0.4860210000, 0.4487690000, 0.3632812500, 0.3632812500, 0.4657826551, 0.4415485444, 0.4824829102, 0.4500732422, 0.4881945600, 0.4486016000, 0.4883729376, 0.4430863959, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3769531250, 0.3769531250, 0.4737760165, 0.4466290708, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3872070312, 0.3872070312, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, 0.2500000000, 0.2500000000, 0.3333333333, 0.3333333333, 0.3750000000, 0.3750000000, 0.4000000000, 0.4000000000, 0.4166666667, 0.4166666667, 0.4285714286, 0.4285714286, 0.4375000000, 0.4375000000, 0.4444444444, 0.4444444444, 0.4500000000, 0.4500000000, 0.3125000000, 0.3125000000, 0.4197530864, 0.4074074074, 0.4453125000, 0.4296875000, 0.4640000000, 0.4464000000, 0.4714506173, 0.4498456790, 0.4752186589, 0.4556434819, 0.4794921875, 0.4572753906, 0.4798049078, 0.4587715287, 0.4825000000, 0.4601000000, 0.3437500000, 0.3437500000, 0.4513031550, 0.4320987654, 0.4733886719, 0.4453125000, 0.4813440000, 0.4466560000, 0.4821459191, 0.4486454047, 0.4847470017, 0.4497020799, 0.4870758057, 0.4495086670, 0.4862647029, 0.4474984053, 0.4860210000, 0.4487690000, 0.3632812500, 0.3632812500, 0.4657826551, 0.4415485444, 0.4824829102, 0.4500732422, 0.4881945600, 0.4486016000, 0.4883729376, 0.4430863959, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3769531250, 0.3769531250, 0.4737760165, 0.4466290708, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3872070312, 0.3872070312, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, 0.2500000000, 0.2500000000, 0.3333333333, 0.3333333333, 0.3750000000, 0.3750000000, 0.4000000000, 0.4000000000, 0.4166666667, 0.4166666667, 0.4285714286, 0.4285714286, 0.4375000000, 0.4375000000, 0.4444444444, 0.4444444444, 0.4500000000, 0.4500000000, 0.3125000000, 0.3125000000, 0.4197530864, 0.4074074074, 0.4453125000, 0.4296875000, 0.4640000000, 0.4464000000, 0.4714506173, 0.4498456790, 0.4752186589, 0.4556434819, 0.4794921875, 0.4572753906, 0.4798049078, 0.4587715287, 0.4825000000, 0.4601000000, 0.3437500000, 0.3437500000, 0.4513031550, 0.4320987654, 0.4733886719, 0.4453125000, 0.4813440000, 0.4466560000, 0.4821459191, 0.4486454047, 0.4847470017, 0.4497020799, 0.4870758057, 0.4495086670, 0.4862647029, 0.4474984053, 0.4860210000, 0.4487690000, 0.3632812500, 0.3632812500, 0.4657826551, 0.4415485444, 0.4824829102, 0.4500732422, 0.4881945600, 0.4486016000, 0.4883729376, 0.4430863959, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3769531250, 0.3769531250, 0.4737760165, 0.4466290708, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3872070312, 0.3872070312, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, 0.2500000000, 0.2500000000, 0.3333333333, 0.3333333333, 0.3750000000, 0.3750000000, 0.4000000000, 0.4000000000, 0.4166666667, 0.4166666667, 0.4285714286, 0.4285714286, 0.4375000000, 0.4375000000, 0.4444444444, 0.4444444444, 0.4500000000, 0.4500000000, 0.3125000000, 0.3125000000, 0.4197530864, 0.4074074074, 0.4453125000, 0.4296875000, 0.4640000000, 0.4464000000, 0.4714506173, 0.4498456790, 0.4752186589, 0.4556434819, 0.4794921875, 0.4572753906, 0.4798049078, 0.4587715287, 0.4825000000, 0.4601000000, 0.3437500000, 0.3437500000, 0.4513031550, 0.4320987654, 0.4733886719, 0.4453125000, 0.4813440000, 0.4466560000, 0.4821459191, 0.4486454047, 0.4847470017, 0.4497020799, 0.4870758057, 0.4495086670, 0.4862647029, 0.4474984053, 0.4860210000, 0.4487690000, 0.3632812500, 0.3632812500, 0.4657826551, 0.4415485444, 0.4824829102, 0.4500732422, 0.4881945600, 0.4486016000, 0.4883729376, 0.4430863959, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3769531250, 0.3769531250, 0.4737760165, 0.4466290708, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3872070312, 0.3872070312, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 0.3952636719, 0.3952636719, -1.0, -1.0, -1.0, -1.0, }; void solve(int test_number) { int d, b; scanf("%d%d", &d, &b); if (d == 0) exit(0); int pos = (d - 1) * (18) + (b - 2) * 2; double ans1 = arr[pos]; double ans2 = arr[pos + 1]; printf("%.10lf %.10lf\n", ans1, ans2); //scanf("%d%d", &d, &b); //printf("%.5lf\n", arr[1][1]); }
[ "surinmike@gmail.com" ]
surinmike@gmail.com
54c4c18b77012fe74b2cacb2fcdc8bea6c8fe1fb
ded3e1f3d432a8b9e5cf96f87b1e7858705bcb95
/2017校招真题/18.cpp
eccbc314245f57732bff3021332e3e0b3e994818
[]
no_license
VikingStudyHard/practiceOnHDU
8998b190938a4178cc661c9a927ce177e240a26e
24852abc53578ce7aae44def41632f5193ce0393
refs/heads/master
2021-04-03T08:38:27.827994
2018-08-20T05:01:47
2018-08-20T05:01:47
124,825,061
0
0
null
null
null
null
UTF-8
C++
false
false
1,085
cpp
/* 数字游戏 题目描述 小易邀请你玩一个数字游戏,小易给你一系列的整数。你们俩使用这些整数玩游戏。每次小易会任意说一个数字出来,然后你需要从这一系列数字中选取一部分出来让它们的和等于小易所说的数字。 例如: 如果{2,1,2,7}是你有的一系列数,小易说的数字是11.你可以得到方案2+2+7 = 11.如果顽皮的小易想坑你,他说的数字是6,那么你没有办法拼凑出和为6 现在小易给你n个数,让你找出无法从n个数中选取部分求和的数字中的最小数(从1开始)。 输入描述: 输入第一行为数字个数n (n ≤ 20) 第二行为n个数xi (1 ≤ xi ≤ 100000) 输出描述: 输出最小不能由n个数选取求和组成的数 */ #include<iostream> #include<algorithm> using namespace std; int main(){ int n; int x[21]; scanf("%d",&n); for(int i = 0;i<n;i++){ scanf("%d",&x[i]); } sort(x,x+n); int miss = 0; for(int i = 0;i<n;i++){ if(x[i]>miss+1){ break; } miss+=x[i]; } printf("%d\n",miss+1); return 0; }
[ "viking@VikingdeMacBook-Pro.local" ]
viking@VikingdeMacBook-Pro.local
7155583958cbd979affc75278964c4e6b2eefb0d
ac5f5e0a90616d21f87fd94bf6ca1819aa9fd2fd
/src/DirectionalLight.h
ad84ce69e760df29b1a036edcfa777cd3225fcb2
[]
no_license
Sondro/Proccraft
625ef139b98dcddb87c93a07091b504dc75d10a3
8138ea188018ce20b22fa0b44034e55c05e0d1db
refs/heads/master
2023-03-28T06:59:35.285197
2021-03-31T16:22:22
2021-03-31T16:22:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
442
h
#pragma once #include "Light.h" class DirectionalLight : public Light { public: DirectionalLight(); DirectionalLight(GLfloat red, GLfloat green, GLfloat blue, GLfloat aIntensity, GLfloat dIntensity, GLfloat xdir, GLfloat yDir, GLfloat zDir); ~DirectionalLight(); void UseLight(GLuint ambientIntensityLocation, GLuint ambientColorLocation, GLuint diffuseIntensityLocation, GLuint directionLocation); private: glm::vec3 direction; };
[ "fredrik96.johansson@gmail.com" ]
fredrik96.johansson@gmail.com
55d365ca3977a2f44d9c87b207acf22eb8b7b7a3
f38983a3a5232e7696e2fb0d1e4a842cda2b7c1b
/src/DAF/DA/SearchTableEntry.cc
5ab93f94e6cf72e464cb0f116ca1bbf92c7d0586
[ "MIT" ]
permissive
Miguel-A/RinaSim
4a1e59486c9b3fc0e9b3dd7b5078f0c717f219de
70ff28dc05e8250ca28c438290cf8c08f8a94a23
refs/heads/master
2016-08-12T17:06:59.946220
2015-10-14T20:33:09
2015-10-14T20:33:18
44,920,027
1
0
null
null
null
null
UTF-8
C++
false
false
2,112
cc
// The MIT License (MIT) // // Copyright (c) 2014-2016 Brno University of Technology, PRISTINE project // // 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 <SearchTableEntry.h> SearchTableEntry::SearchTableEntry(const APN& napn) : Apn(napn) { } SearchTableEntry::~SearchTableEntry() { PeerDAs.clear(); } const APN& SearchTableEntry::getApn() const { return Apn; } void SearchTableEntry::setApn(const APN& apn) { Apn = apn; } const APNList& SearchTableEntry::getPeers() const { return PeerDAs; } bool SearchTableEntry::operator ==(const SearchTableEntry& other) const { return Apn == other.Apn && PeerDAs == other.PeerDAs; } std::string SearchTableEntry::info() const { std::ostringstream os; os << "APN: " << Apn << ", Peer DifAllocs: " << PeerDAs; return os.str(); } void SearchTableEntry::setPeers(const APNList& peerDas) { PeerDAs = peerDas; } void SearchTableEntry::addPeer(const APN& peer) { PeerDAs.push_back(peer); } std::ostream& operator <<(std::ostream& os, const SearchTableEntry& ste) { return os << ste.info(); }
[ "ivesely@fit.vutbr.cz" ]
ivesely@fit.vutbr.cz
b3d07f05583335738efd72490c17224af4cb6624
490385b0147e9e4e3f3ad98556fcf7ce9550ac8d
/OACreater_userStudy_/OACreater/Sparse_coordinate_matrix.h
be75b1ba443924a0c383a37433002d11b5ebb674
[]
no_license
xiaokn/OACreater_
a6d797cfa6dc7091eecf017c45a2ca86576e5c48
102b0d6cdf75aa84b7401b2bbecc817b2362e3ac
refs/heads/master
2020-04-14T21:00:47.458268
2019-01-04T14:01:00
2019-01-04T14:01:00
164,114,206
0
0
null
null
null
null
UTF-8
C++
false
false
5,734
h
// Copyright (c) 2006 Hong Kong University of Science & Technology // All rights reserved. // // This file is part of CholmodWrapper // (http://ihome.ust.hk/~fuhb/software.htm#cholmod_wrapper); // 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; version 2.1 of the License. // See the file LICENSE.LGPL distributed with CholmodWrapper. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // Author(s) : Hongbo Fu, fuplus@gmail.com, 2006 // ===================================================================== #ifndef SPARSE_COORDINATE_MATRIX_H #define SPARSE_COORDINATE_MATRIX_H #include <list> #include <algorithm> /// The class Sparse_coordinate_matrix is a sparse matrix representation /// in coordinate storage format (i, j, value). /// It supports duplicate entries, which will be summed finally. /// /// Concept: Model of the SparseLinearAlgebraTraits_d::Matrix concept. template <class T> class Sparse_coordinate_matrix { // -- private types ---------------------------- private: struct Triplet_entry ///< triplet: (i, j, value) { int i, j; // row and column index T value; Triplet_entry() : i(0), j(0), value(T()) {} Triplet_entry(int r, int c, T val) : i(r), j(c), value(val) {} }; /// Predicate: determine if the coordinates of two triplets are the same struct Triplet_entry_zero_element_predicate { bool operator () (const Triplet_entry& right) { if (right.value == 0) return true; else return false; } }; typedef std::list<Triplet_entry> Triplets_container; // -- public types ----------------------------- public: typedef T NT; typedef typename Triplets_container::iterator Coordinate_iterator; typedef typename Triplets_container::const_iterator Coordinate_const_iterator; // -- public operations ------------------------ public: /// Create a square matrix initialized with zeros. Sparse_coordinate_matrix(int dim, bool symmetric = false) : m_symmetric(symmetric) { assert(dim > 0); m_row_dimension = dim; m_column_dimension = dim; } /// Create a rectangular matrix initialized with zeros. Sparse_coordinate_matrix( int rows, ///< Matrix dimensions. int columns, bool symmetric = false) : m_symmetric(symmetric) { assert(rows > 0 && columns > 0); if (symmetric) assert(rows == columns); // must be a square matrix m_row_dimension = rows; m_column_dimension = columns; } /// Return the matrix number of rows int row_dimension() const { return m_row_dimension; } /// Return the matrix number of columns int column_dimension() const { return m_column_dimension; } /// Is a symmetric matrix? bool is_symmetric() const { return m_symmetric; } /// Write access to a matrix coefficient: a_ij <- val. /// /// @note The efficiency of \c set_coef is much slower than that of \c add_coef /// So I strongly recommend using add_coef instead of set_coef. /// /// Preconditions: /// - 0 <= i < row_dimension. /// - 0 <= j < column_dimension. void set_coef(int i, int j, T val) { reset_coef_to_zero(i, j); add_coef(i, j, val); } /// Write access to a matrix coefficient: /// if(exist(a_ij)) /// a_ij <- a_ij + val; /// else /// a_ij <- val; /// /// Optimization for symmetric matrices: /// Sparse_coordinate_matrix stores only the lower triangle /// add_coef() does nothing if (i, j) belongs to the upper triangle. /// /// Preconditions: /// - 0 <= i < row_dimension. /// - 0 <= j < column_dimension. void add_coef(int i, int j, T val) { assert(i < m_row_dimension && j < m_column_dimension); if (val == 0) return; // do nothing if (m_symmetric && j > i) return; // do nothing m_coordinates.push_back(Triplet_entry(i, j, val)); } /// Return an upper bound of number of non-zero elements. /// Since we allow duplicate entries, it is not efficient to directly count nnz. size_t upper_bound_of_nnz() const { return m_coordinates.size(); } /// Iterators for traverse the list of triplets Coordinate_iterator coords_begin() { return m_coordinates.begin(); } Coordinate_const_iterator coords_begin() const { return m_coordinates.begin(); } Coordinate_iterator coords_end() { return m_coordinates.end(); } Coordinate_const_iterator coords_end() const { return m_coordinates.end(); } void remove_bogus_nonzero_entries() { m_coordinates.erase( // iterator of begin std::remove_if( m_coordinates.begin(), m_coordinates.end(), Triplet_entry_zero_element_predicate()), // iterator of end m_coordinates.end()); } // -- private operations ----------------------- private: /// set val(i, j) = 0; void reset_coef_to_zero(int i, int j) { assert(i < m_row_dimension && j < m_column_dimension); // simulating removing effect by setting their values to zero for (Coordinate_iterator it = coords_begin(); it != coords_end(); ++it) if (it->i == i && it->j == j) it->value = 0; } // -- private variables ------------------------ private: // Matrix dimensions int m_row_dimension; int m_column_dimension; Triplets_container m_coordinates; bool m_symmetric; }; #endif // SPARSE_COORDINATE_MATRIX_H // =====================================================================
[ "yanguohang@sensetime.com" ]
yanguohang@sensetime.com
61831c25290f88049ce47e0917b8f542a7b35fbb
e827a18e7c6fa35e4b103237a9ffab7ebf69a7fa
/freicar_map_sr/src/logic/right_of_way.cpp
da0f295a11b2e28d9bc3bb9838a23c27f811aec9
[]
no_license
Qanadilo1/speed_racers_comp_test
0515463e3cbe614916cf14f79504281273d0b8e0
6d311f091dc73151b2a0336e779724a7557b1c15
refs/heads/master
2023-03-27T08:35:21.419852
2021-03-25T08:23:22
2021-03-25T08:23:22
348,695,713
1
2
null
null
null
null
UTF-8
C++
false
false
8,401
cpp
#include "freicar_map/logic/right_of_way.h" #include "map_core/freicar_map.h" #include <Eigen/Dense> #include <bitset> #include <cmath> #include <tf2/LinearMath/Quaternion.h> #include <tf2/LinearMath/Matrix3x3.h> #include <tuple> namespace freicar { namespace logic { /* some lanes before junctions are very short. sometimes the agents are not considered because they're on the preceding lane to the short lane which causes "crashes" at junctions since they're not observed. this function returns the correct junction id as well as their distance to that junction. */ static std::pair<int, float> GetCorrectJunctionID(const JunctionAgent& observed_agent, map::Map& map_instance){ auto observed_lane = map_instance.FindLaneByUuid(observed_agent.lane_uuid); int j_id = map_instance.GetCurrentJunctionID(observed_agent.lane_uuid); // on a junction if (j_id != -1) return std::make_pair(j_id, 0.0f); j_id = map_instance.GetUpcomingJunctionID(observed_agent.lane_uuid); float distance = observed_lane->GetLength() - observed_agent.lane_offset; if (j_id != -1) { // if stopping at junction return std::make_pair(j_id, distance); } auto next_lane = observed_lane->GetConnection(mapobjects::Lane::Connection::STRAIGHT); if (!next_lane) return std::make_pair(-1, 0.0f); j_id = map_instance.GetUpcomingJunctionID(next_lane->GetUuid().GetUuidValue()); if (j_id != -1) { distance += next_lane->GetLength(); return std::make_pair(j_id, distance); } return std::make_pair(-1, 0.0f); } /* returns whether this agent is on the right hand side of an observer */ bool JunctionAgent::IsOnRightHandSideOf(const JunctionAgent& observer_agent) const { auto observer_lane = map::Map::GetInstance().FindLaneByUuid(observer_agent.lane_uuid); auto observer_pts = observer_lane->GetPointsByReference(); auto p_l1 = observer_pts.back(); auto p_l2 = observer_pts[observer_pts.size() - 2]; float yaw = std::atan2(p_l1.y() - p_l2.y(), p_l1.x() - p_l2.x()); // getting the pose of this agent in observer_agent's frame. if y > 0, it's on LHS Eigen::Matrix3f observer_tf; observer_tf << std::cos(yaw), -std::sin(yaw), observer_agent.current_pose.transform.translation.x, std::sin(yaw), std::cos(yaw), observer_agent.current_pose.transform.translation.y, 0 , 0 , 1; Eigen::Vector3f old_pos(current_pose.transform.translation.x, current_pose.transform.translation.y, 1); Eigen::Vector3f new_pos = observer_tf.inverse() * old_pos; if (new_pos.y() == 0) std::cout << "[ERROR] 0.000001 chance of hitting this edge case" << std::endl; if (new_pos.y() > 0) return false; return true; } /* checks the whether the first agent has priority over observed agent. IMPORTANT: usually observed_agent does not have an intent, so only the intent of the current agent is checked, but further functionallity can be added easily */ bool JunctionAgent::HasRightOfWay(const JunctionAgent& observed_agent, bool ignore_intent) const { enum JunctionSign : int { AGENT_STOP = 0b0001, OBSERVED_STOP = 0b0010, AGENT_ROW = 0b0100, OBSERVED_ROW = 0b1000, NONE = 0b0000 }; int junction_signs = JunctionSign::NONE; auto agent_lane_signs = map::Map::GetInstance().FindLaneByUuid(lane_uuid)->GetRoadSigns(); auto observed_lane = map::Map::GetInstance().FindLaneByUuid(observed_agent.lane_uuid); std::vector<const mapobjects::Roadsign*> observed_lane_signs; // if the lane leads to a junction if (map::Map::GetInstance().GetUpcomingJunctionID(observed_agent.lane_uuid) != -1) observed_lane_signs = observed_lane->GetRoadSigns(); // if the next lane does else { auto observed_next_lane = observed_lane->GetConnection(mapobjects::Lane::STRAIGHT); if (!observed_next_lane) { std::cout << "ERROR: observed agent should've been filtered out in the calling function" << std::endl; return true; } observed_lane_signs = observed_next_lane->GetRoadSigns(); } for (auto agent_sign : agent_lane_signs) { if (agent_sign->GetSignType() == "Stop") junction_signs |= JunctionSign::AGENT_STOP; if (agent_sign->GetSignType() == "RightOfWay") junction_signs |= JunctionSign::AGENT_ROW; } for (auto observed_sign : observed_lane_signs) { if (observed_sign->GetSignType() == "Stop") junction_signs |= JunctionSign::OBSERVED_STOP; if (observed_sign->GetSignType() == "RightOfWay") junction_signs |= JunctionSign::OBSERVED_ROW; } switch (junction_signs) { case AGENT_STOP | OBSERVED_STOP: case AGENT_ROW | OBSERVED_ROW: if (this->IsOnRightHandSideOf(observed_agent) && // current on RHS of observed !observed_agent.IsOnRightHandSideOf(*this)) { return true; } else if (!this->IsOnRightHandSideOf(observed_agent) && // observed on RHS of current observed_agent.IsOnRightHandSideOf(*this)) { // if (this->intent == Intent::GOING_RIGHT) // exception to RHS the rule // return true; return false; } else if (!this->IsOnRightHandSideOf(observed_agent) && // both on LHS of eachother !observed_agent.IsOnRightHandSideOf(*this)) { if (!ignore_intent && this->intent == Intent::GOING_LEFT) return false; else if (this->intent == Intent::GOING_STRAIGHT || this->intent == Intent::GOING_RIGHT || ignore_intent) return true; else std::cout << "[WARNING] unhandled case: " << name << " and " << observed_agent.name << " on LHS w/ unknown intent" << std::endl; } else std::cout << "[WARNING] unhandled case: " << name << " and " << observed_agent.name << " on RHS" << std::endl; break; // case AGENT_STOP: // case OBSERVED_ROW: case AGENT_STOP | OBSERVED_ROW: return false; // case AGENT_ROW: // case OBSERVED_STOP: case AGENT_ROW | OBSERVED_STOP: return true; default: std::cout << "[WARNING] unhandled case: " << name << " and " << observed_agent.name << ", " << std::bitset<8>(junction_signs) << std::endl; break; } return false; } /* returns whether the given agent has right of way over the vector of observed agents */ // TODO: replace agent' heading with that of the last two lane nodes std::tuple<bool, bool, std::string> GetRightOfWay(const JunctionAgent& agent, const std::vector<JunctionAgent>& observed_agents, bool consider_velocities, bool ignore_intent) { auto &map_instance = map::Map::GetInstance(); auto current_junction = map_instance.GetUpcomingJunctionID(agent.lane_uuid); // if on the junction, we're the winner anyway. otherwise if not leading to a junction // skip the whole thing if (current_junction == -1) { if (map_instance.GetCurrentJunctionID(agent.lane_uuid) != -1) return std::make_tuple(true, true, agent.name); return std::make_tuple(false, false, agent.name); } for (auto& observed_agent : observed_agents) { // if on the same or prev lane, observed agent is irrelevant for right of way auto observed_lane = map_instance.FindLaneByUuid(observed_agent.lane_uuid); auto observed_next = observed_lane->GetConnection(mapobjects::Lane::STRAIGHT); bool observed_on_prev_lane = observed_next && observed_next->GetUuid().GetUuidValue() == agent.lane_uuid; if (observed_agent.lane_uuid == agent.lane_uuid || observed_on_prev_lane) { continue; } // if the observed agent is off road if (observed_agent.lane_uuid == "?") { continue; } auto [observed_junction, dist_to_junction] = GetCorrectJunctionID(observed_agent, map_instance); // if not at the same junction if (current_junction != observed_junction) { continue; } else { // observed agent is on the junction if (observed_lane->IsJunctionLane()) { return std::make_tuple(false, true, observed_agent.name); } else { // if too far away from junction (2.5 meters) if (dist_to_junction > 2.5f) { continue; } } } bool ignoring_traffic_rules = false; if (consider_velocities) { auto dx = observed_lane->GetLength() - observed_agent.lane_offset; auto velo = std::sqrt(observed_agent.vx() * observed_agent.vx() + observed_agent.vy() * observed_agent.vy() + observed_agent.vz() * observed_agent.vz()); if (velo > 1e-2 && (dx / velo) < 0.5f) { ignoring_traffic_rules = true; } } if (!agent.HasRightOfWay(observed_agent, ignore_intent) || ignoring_traffic_rules) { return std::make_tuple(false, false, observed_agent.name); } } return std::make_tuple(true, false, agent.name); } } // namespace logic } // namespace freicar
[ "mkqanadilo@hotmail.com" ]
mkqanadilo@hotmail.com
d65fe1dce1b3a3cd0191b6ddee9449b934dbf2de
8419eaa22e58a2efbb7bdf1bccfc66a9e3288d75
/tensorflow/compiler/xla/service/hlo_module.cc
6103cab3e7e73079ef9e65b4ada181aa088c4541
[ "Apache-2.0" ]
permissive
PipelineAI/tensorflow
f539227fd5d3f304b4f246877e35303dbd388a0c
5d8e69768230ea8765a7c78cf1fa22c3ab2a4757
refs/heads/master
2021-05-05T21:54:02.830548
2018-01-15T04:30:05
2018-01-15T04:30:05
115,791,564
0
1
Apache-2.0
2018-01-15T05:38:46
2017-12-30T11:08:37
C++
UTF-8
C++
false
false
21,654
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 "tensorflow/compiler/xla/service/hlo_module.h" #include <iterator> #include <set> #include <sstream> #include <unordered_map> #include <unordered_set> #include <utility> #include "tensorflow/compiler/xla/map_util.h" #include "tensorflow/compiler/xla/ptr_util.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/types.h" namespace xla { HloModule::HloModule(const string& name, const VersionedComputationHandle& entry_computation_handle, const HloModuleConfig& config) : name_(NameUniquer::GetSanitizedName(name)), config_(config), has_entry_computation_handle_(true), entry_computation_handle_(entry_computation_handle) {} HloModule::HloModule(const string& name) : name_(NameUniquer::GetSanitizedName(name)) {} HloModule::HloModule(const string& name, const HloModuleConfig& config) : name_(NameUniquer::GetSanitizedName(name)), config_(config) {} HloComputation* HloModule::AddComputationInternal( std::unique_ptr<HloComputation> computation, bool is_entry, bool uniquify_names) { if (is_entry) { CHECK_EQ(nullptr, entry_computation_); entry_computation_ = computation.get(); // If the module configuration has no entry layout computation set, create a // default one based on the program shape. if (!config_.has_entry_computation_layout()) { config_.SetDefaultComputationLayout( entry_computation_->ComputeProgramShape()); } } if (uniquify_names) { computation->UniquifyName(&computation_name_uniquer_); for (auto* instruction : computation->instructions()) { instruction->UniquifyName(&instruction_name_uniquer_); } } else { // Don't uniquify the names of the computation or instruction, but we must // run the names through the uniquifiers to prevent future name collisions // for computations and instructions created later. computation_name_uniquer_.GetUniqueName(computation->name()); for (auto* instruction : computation->instructions()) { instruction_name_uniquer_.GetUniqueName(instruction->name()); } } // Pick unique IDs for each instruction. for (auto* instruction : computation->instructions()) { instruction->SetUniqueId(NewUniqueInstructionId()); } computation->set_parent(this); computations_.push_back(std::move(computation)); return computations_.back().get(); } HloComputation* HloModule::AddEntryComputation( std::unique_ptr<HloComputation> computation) { return AddComputationInternal(std::move(computation), /*is_entry=*/true, /*uniquify_names=*/true); } Status HloModule::RemoveEmbeddedComputation(HloComputation* to_remove) { auto it = std::find_if(computations_.begin(), computations_.end(), [&to_remove](const std::unique_ptr<HloComputation>& comp) { return comp.get() == to_remove; }); TF_RET_CHECK(it->get() == to_remove); computations_.erase(it); return Status::OK(); } HloComputation* HloModule::AddEmbeddedComputation( std::unique_ptr<HloComputation> computation) { return AddComputationInternal(std::move(computation), /*is_entry=*/false, /*uniquify_names=*/true); } void HloModule::ReplaceComputations( const std::unordered_map<HloComputation*, HloComputation*>& replacements) { // Replace all uses of non-canonical computations with their // representatives. std::vector<std::unique_ptr<HloComputation>> new_computations; new_computations.reserve(computations_.size()); for (std::unique_ptr<HloComputation>& computation : computations_) { for (auto* instruction : computation->instructions()) { switch (instruction->opcode()) { case HloOpcode::kCall: case HloOpcode::kMap: case HloOpcode::kReduce: case HloOpcode::kReduceWindow: { HloComputation* new_arg = tensorflow::gtl::FindWithDefault( replacements, instruction->to_apply(), nullptr); if (new_arg != nullptr) { instruction->set_to_apply(new_arg); } break; } case HloOpcode::kWhile: { HloComputation* new_condition = tensorflow::gtl::FindWithDefault( replacements, instruction->while_condition(), nullptr); if (new_condition != nullptr) { instruction->set_while_condition(new_condition); } HloComputation* new_body = tensorflow::gtl::FindWithDefault( replacements, instruction->while_body(), nullptr); if (new_body != nullptr) { instruction->set_while_body(new_body); } break; } case HloOpcode::kSelectAndScatter: { HloComputation* new_select = tensorflow::gtl::FindWithDefault( replacements, instruction->select(), nullptr); if (new_select != nullptr) { instruction->set_select(new_select); } HloComputation* new_scatter = tensorflow::gtl::FindWithDefault( replacements, instruction->scatter(), nullptr); if (new_scatter != nullptr) { instruction->set_scatter(new_scatter); } break; } default: break; } } if (replacements.find(computation.get()) == replacements.end()) { new_computations.push_back(std::move(computation)); } } // Replace entry_computation if necessary. entry_computation_ = tensorflow::gtl::FindWithDefault( replacements, entry_computation_, entry_computation_); computations_ = std::move(new_computations); } string HloModule::ToString(const HloPrintOptions& options) const { std::ostringstream s; s << "HloModule " << name() << "\n\n"; for (const HloComputation* computation : MakeComputationPostOrder()) { if (computation == entry_computation()) { s << "ENTRY "; } s << computation->ToString(options) << "\n\n"; } return s.str(); } HloModuleProto HloModule::ToProto() const { HloModuleProto proto; proto.set_name(name_); proto.set_entry_computation_name(entry_computation_->name()); for (const HloComputation* computation : MakeComputationPostOrder()) { // Fusion computations are added when the fusion instructions are created by // HloInstruction::CreateFromProto. if (computation->IsFusionComputation()) { continue; } HloComputationProto computation_proto = computation->ToProto(); proto.add_computations()->Swap(&computation_proto); } return proto; } namespace { // Construct a ProgramShape matching the shape of the parameters and root of the // given module's entry computation. StatusOr<ProgramShape> ProgramShapeFromProto(const HloModuleProto& module) { const HloComputationProto* entry_computation = nullptr; for (const HloComputationProto& computation : module.computations()) { if (computation.name() == module.entry_computation_name()) { entry_computation = &computation; break; } } TF_RET_CHECK(entry_computation != nullptr) << "No computation with entry computation name" << module.entry_computation_name(); tensorflow::gtl::FlatMap<int64, std::pair<string, const Shape*>> parameters; const HloInstructionProto* root = nullptr; for (const HloInstructionProto& instruction : entry_computation->instructions()) { if (instruction.name() == entry_computation->root_name()) { TF_RET_CHECK(root == nullptr) << "Entry computation has more than " "one instruction with (root) name " << instruction.name(); root = &instruction; } if (instruction.opcode() == HloOpcodeString(HloOpcode::kParameter)) { TF_RET_CHECK(!ContainsKey(parameters, instruction.parameter_number())) << "Entry computation has more than one parameter instruction " "with parameter number " << instruction.parameter_number(); parameters[instruction.parameter_number()] = {instruction.name(), &instruction.shape()}; } } TF_RET_CHECK(root != nullptr) << "Entry computation is missing root instruction named " << entry_computation->root_name(); ProgramShape program_shape; *program_shape.mutable_result() = root->shape(); for (int64 i = 0; i < parameters.size(); ++i) { TF_RET_CHECK(ContainsKey(parameters, i)) << "Entry computation missing parameter number " << i; const string& name = parameters.at(i).first; const Shape& shape = *parameters.at(i).second; *program_shape.add_parameters() = shape; program_shape.add_parameter_names(name); } return std::move(program_shape); } } // namespace /* static */ StatusOr<std::unique_ptr<HloModule>> HloModule::CreateFromProto( const HloModuleProto& proto, const HloModuleConfig& module_config, const VersionedComputationHandle& entry_computation_handle) { // The ProgramShape in the passed in module config must match the shapes of // the entry parameters and root. TF_ASSIGN_OR_RETURN(ProgramShape expected_program_shape, ProgramShapeFromProto(proto)); TF_RET_CHECK(expected_program_shape.parameters_size() == module_config.entry_computation_layout().parameter_count()); for (int i = 0; i < expected_program_shape.parameters_size(); ++i) { const Shape& parameter_shape = module_config.entry_computation_layout().parameter_layout(i).shape(); TF_RET_CHECK( ShapeUtil::Equal(expected_program_shape.parameters(i), parameter_shape)) << "HloModuleConfig has different shape for parameter " << i << " than the HLO module. Expected: " << ShapeUtil::HumanStringWithLayout( expected_program_shape.parameters(i)) << ", actual: " << ShapeUtil::HumanStringWithLayout(parameter_shape); } const Shape& result_shape = module_config.entry_computation_layout().result_layout().shape(); TF_RET_CHECK(ShapeUtil::Equal(expected_program_shape.result(), result_shape)) << "HloModuleConfig has different result shape than the HLO module. " "Expected: " << ShapeUtil::HumanStringWithLayout(expected_program_shape.result()) << ", actual: " << ShapeUtil::HumanStringWithLayout(result_shape); auto module = MakeUnique<HloModule>(proto.name(), entry_computation_handle, module_config); tensorflow::gtl::FlatMap<string, HloComputation*> computation_map; for (const HloComputationProto& computation_proto : proto.computations()) { TF_ASSIGN_OR_RETURN( std::unique_ptr<HloComputation> computation, HloComputation::CreateFromProto( module.get(), computation_proto, computation_map, /*add_fused_computation=*/ [&module](std::unique_ptr<HloComputation> fused_computation) { module->AddComputationInternal(std::move(fused_computation), /*is_entry=*/false, /*uniquify_names=*/false); })); CHECK_NE(computation.get(), nullptr); TF_RET_CHECK(!ContainsKey(computation_map, computation->name())); string computation_name = computation->name(); // Don't uniquify names because we want names to be stable across // serialization and deserialization. computation_map[computation_name] = module->AddComputationInternal( std::move(computation), /*is_entry=*/proto.entry_computation_name() == computation_name, /*uniquify_names=*/false); } TF_RET_CHECK(module->entry_computation_ != nullptr); // Because we didn't uniquify the names, double-check that the instruction and // computation names are unique from the proto. tensorflow::gtl::FlatSet<string> computation_names; tensorflow::gtl::FlatSet<string> instruction_names; for (HloComputation* computation : module->computations()) { if (computation->IsFusionComputation()) { continue; } TF_RET_CHECK(!ContainsKey(computation_names, computation->name())) << "Computation name is not unique: " << computation->name(); computation_names.insert(computation->name()); for (HloInstruction* instruction : computation->instructions()) { TF_RET_CHECK(!ContainsKey(instruction_names, instruction->name())) << "Instruction name is not unique: " << instruction->name(); instruction_names.insert(instruction->name()); } } return std::move(module); } /* static */ StatusOr<HloModuleConfig> HloModule::CreateModuleConfigFromProto( const HloModuleProto& module) { TF_ASSIGN_OR_RETURN(ProgramShape program_shape, ProgramShapeFromProto(module)); HloModuleConfig module_config(program_shape); // The module config is constructed with default layouts regardless of what is // passed in via the ProgramShape. Set the layouts to the appropriate values. ComputationLayout* entry_layout = module_config.mutable_entry_computation_layout(); for (int64 i = 0; i < entry_layout->parameter_count(); ++i) { TF_RETURN_IF_ERROR( entry_layout->mutable_parameter_layout(i)->CopyLayoutFromShape( program_shape.parameters(i))); } TF_RETURN_IF_ERROR(entry_layout->mutable_result_layout()->CopyLayoutFromShape( program_shape.result())); return module_config; } namespace { // Returns whether `hlo` is used outside the given subcomputation. // `instructions_in_subcomputation` is the instruction set of the given // subcomputation. bool IsUsedOutsideSubcomputation( const HloInstruction& hlo, const std::unordered_set<HloInstruction*>& instructions_in_subcomputation) { for (HloInstruction* user : hlo.users()) { if (!instructions_in_subcomputation.count(user)) { return true; } } return false; } } // anonymous namespace HloInstruction* HloModule::OutlineExpressionFromComputation( tensorflow::gtl::ArraySlice<HloInstruction*> instructions_to_outline, const string& outlined_computation_name, HloComputation* computation) { auto builder = HloComputation::Builder(outlined_computation_name); // A map from original instructions to their counterparts in the new outlined // function. std::unordered_map<HloInstruction*, HloInstruction*> outlined_instructions; // A set that contains all instructions to be outlined. std::unordered_set<HloInstruction*> instruction_set_to_outline( instructions_to_outline.begin(), instructions_to_outline.end()); std::vector<HloInstruction*> arguments; std::vector<HloInstruction*> outputs; int64 parameter_count = 0; for (HloInstruction* instruction_to_outline : instructions_to_outline) { // Clone the original instruction. HloInstruction* outlined_instruction = builder.AddInstruction(instruction_to_outline->Clone()); // Replace its operands to their counterparts in the new function. for (int64 operand_num = 0; operand_num < outlined_instruction->operand_count(); ++operand_num) { HloInstruction* old_operand = outlined_instruction->mutable_operand(operand_num); HloInstruction** operand_slot = &(outlined_instructions[old_operand]); if (*operand_slot == nullptr) { // Because instructions_to_outline is in topological order, if // old_operand is not in outlined_instructions, old_operand must be an // input of the outlined subcomputation and thus should be represented // as a parameter in the new function. arguments.push_back(old_operand); *operand_slot = builder.AddInstruction(HloInstruction::CreateParameter( parameter_count, old_operand->shape(), "")); ++parameter_count; } TF_CHECK_OK( outlined_instruction->ReplaceOperandWith(operand_num, *operand_slot)); } // Insert the new instruction into the outlined_instructions map. InsertOrDie(&outlined_instructions, instruction_to_outline, outlined_instruction); // Mark instruction_to_outline an output if it is used outside the // subcomputation or is the output of the original computation (i.e. used // externally). if (instruction_to_outline->user_count() == 0 || IsUsedOutsideSubcomputation(*instruction_to_outline, instruction_set_to_outline)) { outputs.push_back(instruction_to_outline); } } if (outputs.size() != 1) { string error_message = "The subcomputation to outline has multiple outputs:\n"; for (HloInstruction* output : outputs) { tensorflow::strings::StrAppend(&error_message, output->ToString(), "\n"); } LOG(FATAL) << error_message; } HloInstruction* output = outputs[0]; // Creates a call to the nested computation. HloComputation* nested_computation = AddEmbeddedComputation( builder.Build(FindOrDie(outlined_instructions, output))); HloInstruction* call = computation->AddInstruction(HloInstruction::CreateCall( output->shape(), arguments, nested_computation)); VLOG(2) << "Outlining the following instructions"; for (auto* instruction_to_outline : instructions_to_outline) { VLOG(2) << " " << instruction_to_outline->ToString(); } VLOG(2) << "as a call " << call->ToString(); VLOG(2) << "to " << nested_computation->ToString(); TF_CHECK_OK(output->ReplaceAllUsesWith(call)); for (auto i = instructions_to_outline.rbegin(); i != instructions_to_outline.rend(); ++i) { TF_CHECK_OK(computation->RemoveInstruction(*i)); } return call; } std::list<HloComputation*> HloModule::MakeComputationPostOrder() const { // First determine all root computations by building a set of nonroot // computations (computations which are called by an instruction in the // module). std::set<HloComputation*> nonroot_computations; for (auto& computation : computations_) { for (auto* instruction : computation->instructions()) { for (HloComputation* called_computation : instruction->called_computations()) { nonroot_computations.insert(called_computation); } } } // Keep track of computations which have already been added to the post // order. This prevents duplication as an embedded computation may be called // from two different root computations. std::set<HloComputation*> added_computations; std::list<HloComputation*> post_order; for (auto& computation : computations_) { if (nonroot_computations.count(computation.get()) == 0) { for (HloComputation* embedded_computation : computation->MakeEmbeddedComputationsList()) { if (added_computations.count(embedded_computation) == 0) { post_order.push_back(embedded_computation); added_computations.insert(embedded_computation); } } // Root computations should only be encountered once. CHECK_EQ(0, added_computations.count(computation.get())); post_order.push_back(computation.get()); added_computations.insert(computation.get()); } } CHECK_EQ(post_order.size(), computations_.size()); return post_order; } std::vector<HloComputation*> HloModule::MakeNonfusionComputations() const { std::vector<HloComputation*> result; for (auto* c : computations()) { if (c->IsFusionComputation()) { continue; } result.push_back(c); } return result; } std::unique_ptr<HloModule> HloModule::Clone(const string& suffix) const { VLOG(1) << "Cloning module :" << name_ << " --> " << suffix << "\n"; auto module = MakeUnique<HloModule>(name_ + "-" + suffix); module->config_ = config_; module->entry_computation_handle_ = entry_computation_handle_; module->has_entry_computation_handle_ = has_entry_computation_handle_; std::unordered_map<HloComputation*, HloComputation*> clone_map; for (auto& computation : computations_) { auto cloned_computation = computation->Clone(suffix); InsertOrDie(&clone_map, computation.get(), cloned_computation.get()); if (entry_computation_ == computation.get()) { module->AddEntryComputation(std::move(cloned_computation)); } else { module->AddEmbeddedComputation(std::move(cloned_computation)); } } for (auto& cloned_computation : module->computations_) { for (auto* instruction : cloned_computation->instructions()) { // Rewrite instruction's called_computation to point to the cloned // computations. instruction->ReplaceCalledComputations( [&](HloComputation* hlo) { return FindOrDie(clone_map, hlo); }); } } return module; } uint64 HloModule::RandomNew64() const { tensorflow::mutex_lock l(rng_mutex_); return rng_(); } } // namespace xla
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
63e2f1321da4a030f0c6ecdb8523d7c23896808d
7e96610cc01da9082e6c00c2f8304da78fee5af0
/src/server/scripts/Commands/cs_reload.cpp
b5dde93a499c47cc455d62e2fda618e703686a21
[]
no_license
ralphhorizon/bfacore-1
f945d24bafcb84f12d875c17aa8e948bddcb46ed
8085d551669a164aa7fbade55081058451cb8024
refs/heads/master
2023-01-06T23:21:35.959674
2020-10-24T20:17:16
2020-10-24T20:17:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
62,717
cpp
/* * Copyright (C) 2020 BfaCore * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData Name: reload_commandscript %Complete: 100 Comment: All reload related commands Category: commandscripts EndScriptData */ #include "AccountMgr.h" #include "AchievementMgr.h" #include "AreaTriggerDataStore.h" #include "AuctionHouseMgr.h" #include "BattlegroundMgr.h" #include "CharacterTemplateDataStore.h" #include "Chat.h" #include "ConversationDataStore.h" #include "CreatureTextMgr.h" #include "DatabaseEnv.h" #include "DisableMgr.h" #include "GameObject.h" #include "ItemEnchantmentMgr.h" #include "Language.h" #include "LFGMgr.h" #include "Log.h" #include "LootMgr.h" #include "MapManager.h" #include "ObjectMgr.h" #include "ScriptMgr.h" #include "SkillDiscovery.h" #include "SkillExtraItems.h" #include "SmartAI.h" #include "SpellMgr.h" #include "SupportMgr.h" #include "WardenCheckMgr.h" #include "WaypointManager.h" #include "World.h" #include "WorldSession.h" class reload_commandscript : public CommandScript { public: reload_commandscript() : CommandScript("reload_commandscript") { } std::vector<ChatCommand> GetCommands() const override { static std::vector<ChatCommand> reloadAllCommandTable = { { "achievement", rbac::RBAC_PERM_COMMAND_RELOAD_ALL_ACHIEVEMENT, true, &HandleReloadAllAchievementCommand, "" }, { "area", rbac::RBAC_PERM_COMMAND_RELOAD_ALL_AREA, true, &HandleReloadAllAreaCommand, "" }, { "gossips", rbac::RBAC_PERM_COMMAND_RELOAD_ALL_GOSSIP, true, &HandleReloadAllGossipsCommand, "" }, { "item", rbac::RBAC_PERM_COMMAND_RELOAD_ALL_ITEM, true, &HandleReloadAllItemCommand, "" }, { "locales", rbac::RBAC_PERM_COMMAND_RELOAD_ALL_LOCALES, true, &HandleReloadAllLocalesCommand, "" }, { "loot", rbac::RBAC_PERM_COMMAND_RELOAD_ALL_LOOT, true, &HandleReloadAllLootCommand, "" }, { "npc", rbac::RBAC_PERM_COMMAND_RELOAD_ALL_NPC, true, &HandleReloadAllNpcCommand, "" }, { "quest", rbac::RBAC_PERM_COMMAND_RELOAD_ALL_QUEST, true, &HandleReloadAllQuestCommand, "" }, { "scripts", rbac::RBAC_PERM_COMMAND_RELOAD_ALL_SCRIPTS, true, &HandleReloadAllScriptsCommand, "" }, { "spell", rbac::RBAC_PERM_COMMAND_RELOAD_ALL_SPELL, true, &HandleReloadAllSpellCommand, "" }, { "", rbac::RBAC_PERM_COMMAND_RELOAD_ALL, true, &HandleReloadAllCommand, "" }, }; static std::vector<ChatCommand> reloadCommandTable = { { "auctions", rbac::RBAC_PERM_COMMAND_RELOAD_AUCTIONS, true, &HandleReloadAuctionsCommand, "" }, { "access_requirement", rbac::RBAC_PERM_COMMAND_RELOAD_ACCESS_REQUIREMENT, true, &HandleReloadAccessRequirementCommand, "" }, { "achievement_reward", rbac::RBAC_PERM_COMMAND_RELOAD_ACHIEVEMENT_REWARD, true, &HandleReloadAchievementRewardCommand, "" }, { "all", rbac::RBAC_PERM_COMMAND_RELOAD_ALL, true, nullptr, "", reloadAllCommandTable }, { "areatrigger_involvedrelation", rbac::RBAC_PERM_COMMAND_RELOAD_AREATRIGGER_INVOLVEDRELATION, true, &HandleReloadQuestAreaTriggersCommand, "" }, { "areatrigger_tavern", rbac::RBAC_PERM_COMMAND_RELOAD_AREATRIGGER_TAVERN, true, &HandleReloadAreaTriggerTavernCommand, "" }, { "areatrigger_teleport", rbac::RBAC_PERM_COMMAND_RELOAD_AREATRIGGER_TELEPORT, true, &HandleReloadAreaTriggerTeleportCommand, "" }, { "areatrigger_template", rbac::RBAC_PERM_COMMAND_RELOAD_AREATRIGGER_TEMPLATE, true, &HandleReloadAreaTriggerTemplateCommand, "" }, { "autobroadcast", rbac::RBAC_PERM_COMMAND_RELOAD_AUTOBROADCAST, true, &HandleReloadAutobroadcastCommand, "" }, { "battleground_template", rbac::RBAC_PERM_COMMAND_RELOAD_BATTLEGROUND_TEMPLATE, true, &HandleReloadBattlegroundTemplate, "" }, { "character_template", rbac::RBAC_PERM_COMMAND_RELOAD_CHARACTER_TEMPLATE, true, &HandleReloadCharacterTemplate, "" }, { "command", rbac::RBAC_PERM_COMMAND_RELOAD_COMMAND, true, &HandleReloadCommandCommand, "" }, { "conditions", rbac::RBAC_PERM_COMMAND_RELOAD_CONDITIONS, true, &HandleReloadConditions, "" }, { "config", rbac::RBAC_PERM_COMMAND_RELOAD_CONFIG, true, &HandleReloadConfigCommand, "" }, { "conversation_template", rbac::RBAC_PERM_COMMAND_RELOAD_CONVERSATION_TEMPLATE, true, &HandleReloadConversationTemplateCommand, "" }, { "creature_text", rbac::RBAC_PERM_COMMAND_RELOAD_CREATURE_TEXT, true, &HandleReloadCreatureText, "" }, { "creature_questender", rbac::RBAC_PERM_COMMAND_RELOAD_CREATURE_QUESTENDER, true, &HandleReloadCreatureQuestEnderCommand, "" }, { "creature_linked_respawn", rbac::RBAC_PERM_COMMAND_RELOAD_CREATURE_LINKED_RESPAWN, true, &HandleReloadLinkedRespawnCommand, "" }, { "creature_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_CREATURE_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesCreatureCommand, "" }, { "creature_onkill_reward", rbac::RBAC_PERM_COMMAND_RELOAD_CREATURE_ONKILL_REWARD, true, &HandleReloadOnKillRewardCommand, "" }, { "creature_queststarter", rbac::RBAC_PERM_COMMAND_RELOAD_CREATURE_QUESTSTARTER, true, &HandleReloadCreatureQuestStarterCommand, "" }, { "creature_summon_groups", rbac::RBAC_PERM_COMMAND_RELOAD_CREATURE_SUMMON_GROUPS, true, &HandleReloadCreatureSummonGroupsCommand, "" }, { "creature_template", rbac::RBAC_PERM_COMMAND_RELOAD_CREATURE_TEMPLATE, true, &HandleReloadCreatureTemplateCommand, "" }, { "criteria_data", rbac::RBAC_PERM_COMMAND_RELOAD_CRITERIA_DATA, true, &HandleReloadCriteriaDataCommand, "" }, { "disables", rbac::RBAC_PERM_COMMAND_RELOAD_DISABLES, true, &HandleReloadDisablesCommand, "" }, { "disenchant_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_DISENCHANT_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesDisenchantCommand, "" }, { "event_scripts", rbac::RBAC_PERM_COMMAND_RELOAD_EVENT_SCRIPTS, true, &HandleReloadEventScriptsCommand, "" }, { "fishing_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_FISHING_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesFishingCommand, "" }, { "graveyard_zone", rbac::RBAC_PERM_COMMAND_RELOAD_GRAVEYARD_ZONE, true, &HandleReloadGameGraveyardZoneCommand, "" }, { "game_tele", rbac::RBAC_PERM_COMMAND_RELOAD_GAME_TELE, true, &HandleReloadGameTeleCommand, "" }, { "gameobject_questender", rbac::RBAC_PERM_COMMAND_RELOAD_GAMEOBJECT_QUESTENDER, true, &HandleReloadGOQuestEnderCommand, "" }, { "gameobject_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_GAMEOBJECT_QUEST_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesGameobjectCommand, "" }, { "gameobject_queststarter", rbac::RBAC_PERM_COMMAND_RELOAD_GAMEOBJECT_QUESTSTARTER, true, &HandleReloadGOQuestStarterCommand, "" }, { "gossip_menu", rbac::RBAC_PERM_COMMAND_RELOAD_GOSSIP_MENU, true, &HandleReloadGossipMenuCommand, "" }, { "gossip_menu_option", rbac::RBAC_PERM_COMMAND_RELOAD_GOSSIP_MENU_OPTION, true, &HandleReloadGossipMenuOptionCommand, "" }, { "item_random_bonus_list_template", rbac::RBAC_PERM_COMMAND_RELOAD_ITEM_RANDOM_BONUS_LIST_TEMPLATE, true, &HandleReloadItemRandomBonusListTemplatesCommand, "" }, { "item_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_ITEM_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesItemCommand, "" }, { "lfg_dungeon_rewards", rbac::RBAC_PERM_COMMAND_RELOAD_LFG_DUNGEON_REWARDS, true, &HandleReloadLfgRewardsCommand, "" }, { "locales_achievement_reward", rbac::RBAC_PERM_COMMAND_RELOAD_LOCALES_ACHIEVEMENT_REWARD, true, &HandleReloadLocalesAchievementRewardCommand, "" }, { "locales_creature", rbac::RBAC_PERM_COMMAND_RELOAD_LOCALES_CRETURE, true, &HandleReloadLocalesCreatureCommand, "" }, { "locales_creature_text", rbac::RBAC_PERM_COMMAND_RELOAD_LOCALES_CRETURE_TEXT, true, &HandleReloadLocalesCreatureTextCommand, "" }, { "locales_gameobject", rbac::RBAC_PERM_COMMAND_RELOAD_LOCALES_GAMEOBJECT, true, &HandleReloadLocalesGameobjectCommand, "" }, { "locales_gossip_menu_option", rbac::RBAC_PERM_COMMAND_RELOAD_LOCALES_GOSSIP_MENU_OPTION, true, &HandleReloadLocalesGossipMenuOptionCommand, "" }, { "locales_page_text", rbac::RBAC_PERM_COMMAND_RELOAD_LOCALES_PAGE_TEXT, true, &HandleReloadLocalesPageTextCommand, "" }, { "locales_points_of_interest", rbac::RBAC_PERM_COMMAND_RELOAD_LOCALES_POINTS_OF_INTEREST, true, &HandleReloadLocalesPointsOfInterestCommand, "" }, { "mail_level_reward", rbac::RBAC_PERM_COMMAND_RELOAD_MAIL_LEVEL_REWARD, true, &HandleReloadMailLevelRewardCommand, "" }, { "mail_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_MAIL_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesMailCommand, "" }, { "milling_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_MILLING_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesMillingCommand, "" }, { "npc_spellclick_spells", rbac::RBAC_PERM_COMMAND_RELOAD_NPC_SPELLCLICK_SPELLS, true, &HandleReloadSpellClickSpellsCommand, "" }, { "npc_vendor", rbac::RBAC_PERM_COMMAND_RELOAD_NPC_VENDOR, true, &HandleReloadNpcVendorCommand, "" }, { "page_text", rbac::RBAC_PERM_COMMAND_RELOAD_PAGE_TEXT, true, &HandleReloadPageTextsCommand, "" }, { "pickpocketing_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_PICKPOCKETING_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesPickpocketingCommand, "" }, { "points_of_interest", rbac::RBAC_PERM_COMMAND_RELOAD_POINTS_OF_INTEREST, true, &HandleReloadPointsOfInterestCommand, "" }, { "prospecting_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_PROSPECTING_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesProspectingCommand, "" }, { "quest_greeting", rbac::RBAC_PERM_COMMAND_RELOAD_QUEST_GREETING, true, &HandleReloadQuestGreetingCommand, "" }, { "quest_locale", rbac::RBAC_PERM_COMMAND_RELOAD_QUEST_LOCALE, true, &HandleReloadQuestLocaleCommand, "" }, { "quest_poi", rbac::RBAC_PERM_COMMAND_RELOAD_QUEST_POI, true, &HandleReloadQuestPOICommand, "" }, { "quest_template", rbac::RBAC_PERM_COMMAND_RELOAD_QUEST_TEMPLATE, true, &HandleReloadQuestTemplateCommand, "" }, { "rbac", rbac::RBAC_PERM_COMMAND_RELOAD_RBAC, true, &HandleReloadRBACCommand, "" }, { "reference_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_REFERENCE_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesReferenceCommand, "" }, { "reserved_name", rbac::RBAC_PERM_COMMAND_RELOAD_RESERVED_NAME, true, &HandleReloadReservedNameCommand, "" }, { "reputation_reward_rate", rbac::RBAC_PERM_COMMAND_RELOAD_REPUTATION_REWARD_RATE, true, &HandleReloadReputationRewardRateCommand, "" }, { "reputation_spillover_template", rbac::RBAC_PERM_COMMAND_RELOAD_SPILLOVER_TEMPLATE, true, &HandleReloadReputationRewardRateCommand, "" }, { "skill_discovery_template", rbac::RBAC_PERM_COMMAND_RELOAD_SKILL_DISCOVERY_TEMPLATE, true, &HandleReloadSkillDiscoveryTemplateCommand, "" }, { "scene_template", rbac::RBAC_PERM_COMMAND_RELOAD_SCENE_TEMPLATE, true, &HandleReloadSceneTemplateCommand, "" }, { "skill_extra_item_template", rbac::RBAC_PERM_COMMAND_RELOAD_SKILL_EXTRA_ITEM_TEMPLATE, true, &HandleReloadSkillExtraItemTemplateCommand, "" }, { "skill_fishing_base_level", rbac::RBAC_PERM_COMMAND_RELOAD_SKILL_FISHING_BASE_LEVEL, true, &HandleReloadSkillFishingBaseLevelCommand, "" }, { "skinning_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_SKINNING_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesSkinningCommand, "" }, { "scrapping_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_SKINNING_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesScrappingCommand, "" }, { "smart_scripts", rbac::RBAC_PERM_COMMAND_RELOAD_SMART_SCRIPTS, true, &HandleReloadSmartScripts, "" }, { "spell_required", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_REQUIRED, true, &HandleReloadSpellRequiredCommand, "" }, { "spell_area", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_AREA, true, &HandleReloadSpellAreaCommand, "" }, { "spell_group", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_GROUP, true, &HandleReloadSpellGroupsCommand, "" }, { "spell_learn_spell", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_LEARN_SPELL, true, &HandleReloadSpellLearnSpellCommand, "" }, { "spell_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesSpellCommand, "" }, { "spell_linked_spell", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_LINKED_SPELL, true, &HandleReloadSpellLinkedSpellCommand, "" }, { "spell_pet_auras", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_PET_AURAS, true, &HandleReloadSpellPetAurasCommand, "" }, { "spell_proc", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_PROC, true, &HandleReloadSpellProcsCommand, "" }, { "spell_script_names", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_SCRIPT_NAMES, true, &HandleReloadScriptNamesCommand, "" }, { "spell_scripts", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_SCRIPTS, true, &HandleReloadSpellScriptsCommand, "" }, { "spell_target_position", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_TARGET_POSITION, true, &HandleReloadSpellTargetPositionCommand, "" }, { "spell_threats", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_THREATS, true, &HandleReloadSpellThreatsCommand, "" }, { "spell_group_stack_rules", rbac::RBAC_PERM_COMMAND_RELOAD_SPELL_GROUP_STACK_RULES, true, &HandleReloadSpellGroupStackRulesCommand, "" }, { "support", rbac::RBAC_PERM_COMMAND_RELOAD_SUPPORT_SYSTEM, true, &HandleReloadSupportSystemCommand, "" }, { "trainer", rbac::RBAC_PERM_COMMAND_RELOAD_TRAINER, true, &HandleReloadTrainerCommand, "" }, { "trinity_string", rbac::RBAC_PERM_COMMAND_RELOAD_TRINITY_STRING, true, &HandleReloadTrinityStringCommand, "" }, { "warden_action", rbac::RBAC_PERM_COMMAND_RELOAD_WARDEN_ACTION, true, &HandleReloadWardenactionCommand, "" }, { "waypoint_scripts", rbac::RBAC_PERM_COMMAND_RELOAD_WAYPOINT_SCRIPTS, true, &HandleReloadWpScriptsCommand, "" }, { "waypoint_data", rbac::RBAC_PERM_COMMAND_RELOAD_WAYPOINT_DATA, true, &HandleReloadWpCommand, "" }, { "vehicle_accessory", rbac::RBAC_PERM_COMMAND_RELOAD_VEHICLE_ACCESORY, true, &HandleReloadVehicleAccessoryCommand, "" }, { "vehicle_template_accessory", rbac::RBAC_PERM_COMMAND_RELOAD_VEHICLE_TEMPLATE_ACCESSORY, true, &HandleReloadVehicleTemplateAccessoryCommand, "" }, { "script_params", rbac::RBAC_PERM_COMMAND_RELOAD, true, &HandleReloadScriptParamsCommand, "" }, }; static std::vector<ChatCommand> commandTable = { { "reload", rbac::RBAC_PERM_COMMAND_RELOAD, true, nullptr, "", reloadCommandTable }, }; return commandTable; } //reload commands static bool HandleReloadSupportSystemCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Support System Tables..."); sSupportMgr->LoadBugTickets(); sSupportMgr->LoadComplaintTickets(); sSupportMgr->LoadSuggestionTickets(); handler->SendGlobalGMSysMessage("DB tables `gm_*` reloaded."); return true; } static bool HandleReloadAllCommand(ChatHandler* handler, const char* /*args*/) { HandleReloadSkillFishingBaseLevelCommand(handler, ""); HandleReloadAllAchievementCommand(handler, ""); HandleReloadAllAreaCommand(handler, ""); HandleReloadAllLootCommand(handler, ""); HandleReloadAllNpcCommand(handler, ""); HandleReloadAllQuestCommand(handler, ""); HandleReloadAllSpellCommand(handler, ""); HandleReloadAllItemCommand(handler, ""); HandleReloadAllGossipsCommand(handler, ""); HandleReloadAllLocalesCommand(handler, ""); HandleReloadAccessRequirementCommand(handler, ""); HandleReloadMailLevelRewardCommand(handler, ""); HandleReloadCommandCommand(handler, ""); HandleReloadReservedNameCommand(handler, ""); HandleReloadTrinityStringCommand(handler, ""); HandleReloadGameTeleCommand(handler, ""); HandleReloadCreatureSummonGroupsCommand(handler, ""); HandleReloadVehicleAccessoryCommand(handler, ""); HandleReloadVehicleTemplateAccessoryCommand(handler, ""); HandleReloadAutobroadcastCommand(handler, ""); HandleReloadBattlegroundTemplate(handler, ""); HandleReloadCharacterTemplate(handler, ""); return true; } static bool HandleReloadAllAchievementCommand(ChatHandler* handler, const char* /*args*/) { HandleReloadCriteriaDataCommand(handler, ""); HandleReloadAchievementRewardCommand(handler, ""); return true; } static bool HandleReloadAllAreaCommand(ChatHandler* handler, const char* /*args*/) { //HandleReloadQuestAreaTriggersCommand(handler, ""); -- reloaded in HandleReloadAllQuestCommand HandleReloadAreaTriggerTeleportCommand(handler, ""); HandleReloadAreaTriggerTavernCommand(handler, ""); HandleReloadGameGraveyardZoneCommand(handler, ""); return true; } static bool HandleReloadAllLootCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables..."); LoadLootTables(); handler->SendGlobalGMSysMessage("DB tables `*_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadAllNpcCommand(ChatHandler* handler, const char* args) { if (*args != 'a') // will be reloaded from all_gossips HandleReloadTrainerCommand(handler, "a"); HandleReloadNpcVendorCommand(handler, "a"); HandleReloadPointsOfInterestCommand(handler, "a"); HandleReloadSpellClickSpellsCommand(handler, "a"); return true; } static bool HandleReloadAllQuestCommand(ChatHandler* handler, const char* /*args*/) { HandleReloadQuestAreaTriggersCommand(handler, "a"); HandleReloadQuestGreetingCommand(handler, "a"); HandleReloadQuestPOICommand(handler, "a"); HandleReloadQuestTemplateCommand(handler, "a"); TC_LOG_INFO("misc", "Re-Loading Quests Relations..."); sObjectMgr->LoadQuestStartersAndEnders(); handler->SendGlobalGMSysMessage("DB tables `*_queststarter` and `*_questender` reloaded."); return true; } static bool HandleReloadAllScriptsCommand(ChatHandler* handler, const char* /*args*/) { if (sMapMgr->IsScriptScheduled()) { handler->PSendSysMessage("DB scripts used currently, please attempt reload later."); handler->SetSentErrorMessage(true); return false; } TC_LOG_INFO("misc", "Re-Loading Scripts..."); HandleReloadEventScriptsCommand(handler, "a"); HandleReloadSpellScriptsCommand(handler, "a"); handler->SendGlobalGMSysMessage("DB tables `*_scripts` reloaded."); HandleReloadWpScriptsCommand(handler, "a"); HandleReloadWpCommand(handler, "a"); return true; } static bool HandleReloadAllSpellCommand(ChatHandler* handler, const char* /*args*/) { HandleReloadSkillDiscoveryTemplateCommand(handler, "a"); HandleReloadSkillExtraItemTemplateCommand(handler, "a"); HandleReloadSpellRequiredCommand(handler, "a"); HandleReloadSpellAreaCommand(handler, "a"); HandleReloadSpellGroupsCommand(handler, "a"); HandleReloadSpellLearnSpellCommand(handler, "a"); HandleReloadSpellLinkedSpellCommand(handler, "a"); HandleReloadSpellProcsCommand(handler, "a"); HandleReloadSpellTargetPositionCommand(handler, "a"); HandleReloadSpellThreatsCommand(handler, "a"); HandleReloadSpellGroupStackRulesCommand(handler, "a"); HandleReloadSpellPetAurasCommand(handler, "a"); return true; } static bool HandleReloadAllGossipsCommand(ChatHandler* handler, const char* args) { HandleReloadGossipMenuCommand(handler, "a"); HandleReloadGossipMenuOptionCommand(handler, "a"); if (*args != 'a') // already reload from all_scripts HandleReloadPointsOfInterestCommand(handler, "a"); return true; } static bool HandleReloadAllItemCommand(ChatHandler* handler, const char* /*args*/) { HandleReloadPageTextsCommand(handler, "a"); HandleReloadItemRandomBonusListTemplatesCommand(handler, "a"); return true; } static bool HandleReloadAllLocalesCommand(ChatHandler* handler, const char* /*args*/) { HandleReloadLocalesAchievementRewardCommand(handler, "a"); HandleReloadLocalesCreatureCommand(handler, "a"); HandleReloadLocalesCreatureTextCommand(handler, "a"); HandleReloadLocalesGameobjectCommand(handler, "a"); HandleReloadLocalesGossipMenuOptionCommand(handler, "a"); HandleReloadLocalesPageTextCommand(handler, "a"); HandleReloadLocalesPointsOfInterestCommand(handler, "a"); HandleReloadQuestLocaleCommand(handler, "a"); return true; } static bool HandleReloadConfigCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading config settings..."); sWorld->LoadConfigSettings(true); sMapMgr->InitializeVisibilityDistanceInfo(); handler->SendGlobalGMSysMessage("World config settings reloaded."); return true; } static bool HandleReloadAccessRequirementCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Access Requirement definitions..."); sObjectMgr->LoadAccessRequirements(); handler->SendGlobalGMSysMessage("DB table `access_requirement` reloaded."); return true; } static bool HandleReloadCriteriaDataCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Additional Criteria Data..."); sCriteriaMgr->LoadCriteriaData(); handler->SendGlobalGMSysMessage("DB table `criteria_data` reloaded."); return true; } static bool HandleReloadAchievementRewardCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Achievement Reward Data..."); sAchievementMgr->LoadRewards(); handler->SendGlobalGMSysMessage("DB table `achievement_reward` reloaded."); return true; } static bool HandleReloadAreaTriggerTavernCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Tavern Area Triggers..."); sObjectMgr->LoadTavernAreaTriggers(); handler->SendGlobalGMSysMessage("DB table `areatrigger_tavern` reloaded."); return true; } static bool HandleReloadAreaTriggerTeleportCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading AreaTrigger teleport definitions..."); sObjectMgr->LoadAreaTriggerTeleports(); handler->SendGlobalGMSysMessage("DB table `areatrigger_teleport` reloaded."); return true; } static bool HandleReloadAutobroadcastCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Autobroadcasts..."); sWorld->LoadAutobroadcasts(); handler->SendGlobalGMSysMessage("DB table `autobroadcast` reloaded."); return true; } static bool HandleReloadBattlegroundTemplate(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Battleground Templates..."); sBattlegroundMgr->LoadBattlegroundTemplates(); handler->SendGlobalGMSysMessage("DB table `battleground_template` reloaded."); return true; } static bool HandleReloadCharacterTemplate(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Character Templates..."); sCharacterTemplateDataStore->LoadCharacterTemplates(); handler->SendGlobalGMSysMessage("DB table `character_template` and `character_template_class` reloaded."); return true; } static bool HandleReloadCommandCommand(ChatHandler* handler, const char* /*args*/) { ChatHandler::invalidateCommandTable(); handler->SendGlobalGMSysMessage("DB table `command` will be reloaded at next chat command use."); return true; } static bool HandleReloadOnKillRewardCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading creature award reputation definitions..."); sObjectMgr->LoadRewardOnKill(); handler->SendGlobalGMSysMessage("DB table `creature_onkill_reward` reloaded."); return true; } static bool HandleReloadCreatureSummonGroupsCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Reloading creature summon groups..."); sObjectMgr->LoadTempSummons(); handler->SendGlobalGMSysMessage("DB table `creature_summon_groups` reloaded."); return true; } static bool HandleReloadCreatureTemplateCommand(ChatHandler* handler, const char* args) { if (!*args) return false; Tokenizer entries(std::string(args), ' '); for (Tokenizer::const_iterator itr = entries.begin(); itr != entries.end(); ++itr) { uint32 entry = atoul(*itr); WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_TEMPLATE); stmt->setUInt32(0, entry); stmt->setUInt32(1, 0); PreparedQueryResult result = WorldDatabase.Query(stmt); if (!result) { handler->PSendSysMessage(LANG_COMMAND_CREATURETEMPLATE_NOTFOUND, entry); continue; } CreatureTemplate const* cInfo = sObjectMgr->GetCreatureTemplate(entry); if (!cInfo) { handler->PSendSysMessage(LANG_COMMAND_CREATURESTORAGE_NOTFOUND, entry); continue; } TC_LOG_INFO("misc", "Reloading creature template entry %u", entry); Field* fields = result->Fetch(); sObjectMgr->LoadCreatureTemplate(fields); sObjectMgr->CheckCreatureTemplate(cInfo); } sObjectMgr->InitializeQueriesData(QUERY_DATA_CREATURES); handler->SendGlobalGMSysMessage("Creature template reloaded."); return true; } static bool HandleReloadCreatureQuestStarterCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`creature_queststarter`)"); sObjectMgr->LoadCreatureQuestStarters(); handler->SendGlobalGMSysMessage("DB table `creature_queststarter` reloaded."); return true; } static bool HandleReloadLinkedRespawnCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Loading Linked Respawns... (`creature_linked_respawn`)"); sObjectMgr->LoadLinkedRespawn(); handler->SendGlobalGMSysMessage("DB table `creature_linked_respawn` (creature linked respawns) reloaded."); return true; } static bool HandleReloadCreatureQuestEnderCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`creature_questender`)"); sObjectMgr->LoadCreatureQuestEnders(); handler->SendGlobalGMSysMessage("DB table `creature_questender` reloaded."); return true; } static bool HandleReloadGossipMenuCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `gossip_menu` Table!"); sObjectMgr->LoadGossipMenu(); handler->SendGlobalGMSysMessage("DB table `gossip_menu` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadGossipMenuOptionCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `gossip_menu_option` Table!"); sObjectMgr->LoadGossipMenuItems(); handler->SendGlobalGMSysMessage("DB table `gossip_menu_option` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadGOQuestStarterCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`gameobject_queststarter`)"); sObjectMgr->LoadGameobjectQuestStarters(); handler->SendGlobalGMSysMessage("DB table `gameobject_queststarter` reloaded."); return true; } static bool HandleReloadGOQuestEnderCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`gameobject_questender`)"); sObjectMgr->LoadGameobjectQuestEnders(); handler->SendGlobalGMSysMessage("DB table `gameobject_questender` reloaded."); return true; } static bool HandleReloadQuestAreaTriggersCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest Area Triggers..."); sObjectMgr->LoadQuestAreaTriggers(); handler->SendGlobalGMSysMessage("DB table `areatrigger_involvedrelation` (quest area triggers) reloaded."); return true; } static bool HandleReloadQuestGreetingCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest Greeting ... "); sObjectMgr->LoadQuestGreetings(); handler->SendGlobalGMSysMessage("DB table `quest_greeting` reloaded."); return true; } static bool HandleReloadQuestTemplateCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest Templates..."); sObjectMgr->LoadQuests(); sObjectMgr->InitializeQueriesData(QUERY_DATA_QUESTS); handler->SendGlobalGMSysMessage("DB table `quest_template` (quest definitions) reloaded."); /// dependent also from `gameobject` but this table not reloaded anyway TC_LOG_INFO("misc", "Re-Loading GameObjects for quests..."); sObjectMgr->LoadGameObjectForQuests(); handler->SendGlobalGMSysMessage("Data GameObjects for quests reloaded."); return true; } static bool HandleReloadLootTemplatesCreatureCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`creature_loot_template`)"); LoadLootTemplates_Creature(); LootTemplates_Creature.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `creature_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesDisenchantCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`disenchant_loot_template`)"); LoadLootTemplates_Disenchant(); LootTemplates_Disenchant.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `disenchant_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesFishingCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`fishing_loot_template`)"); LoadLootTemplates_Fishing(); LootTemplates_Fishing.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `fishing_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesGameobjectCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`gameobject_loot_template`)"); LoadLootTemplates_Gameobject(); LootTemplates_Gameobject.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `gameobject_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesItemCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`item_loot_template`)"); LoadLootTemplates_Item(); LootTemplates_Item.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `item_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesMillingCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`milling_loot_template`)"); LoadLootTemplates_Milling(); LootTemplates_Milling.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `milling_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesPickpocketingCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`pickpocketing_loot_template`)"); LoadLootTemplates_Pickpocketing(); LootTemplates_Pickpocketing.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `pickpocketing_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesProspectingCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`prospecting_loot_template`)"); LoadLootTemplates_Prospecting(); LootTemplates_Prospecting.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `prospecting_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesMailCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`mail_loot_template`)"); LoadLootTemplates_Mail(); LootTemplates_Mail.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `mail_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesReferenceCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`reference_loot_template`)"); LoadLootTemplates_Reference(); handler->SendGlobalGMSysMessage("DB table `reference_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesScrappingCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`scrapping_loot_template`)"); sObjectMgr->LoadItemScrappingLoot(); LoadLootTemplates_Scrapping(); LootTemplates_Scrapping.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `scrapping_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesSkinningCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`skinning_loot_template`)"); LoadLootTemplates_Skinning(); LootTemplates_Skinning.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `skinning_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadLootTemplatesSpellCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`spell_loot_template`)"); LoadLootTemplates_Spell(); LootTemplates_Spell.CheckLootRefs(); handler->SendGlobalGMSysMessage("DB table `spell_loot_template` reloaded."); sConditionMgr->LoadConditions(true); return true; } static bool HandleReloadTrinityStringCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading trinity_string Table!"); sObjectMgr->LoadTrinityStrings(); handler->SendGlobalGMSysMessage("DB table `trinity_string` reloaded."); return true; } static bool HandleReloadWardenactionCommand(ChatHandler* handler, const char* /*args*/) { if (!sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED)) { handler->SendSysMessage("Warden system disabled by config - reloading warden_action skipped."); handler->SetSentErrorMessage(true); return false; } TC_LOG_INFO("misc", "Re-Loading warden_action Table!"); sWardenCheckMgr->LoadWardenOverrides(); handler->SendGlobalGMSysMessage("DB table `warden_action` reloaded."); return true; } static bool HandleReloadTrainerCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `trainer` Table!"); sObjectMgr->LoadTrainers(); sObjectMgr->LoadCreatureDefaultTrainers(); handler->SendGlobalGMSysMessage("DB table `trainer` reloaded."); handler->SendGlobalGMSysMessage("DB table `trainer_locale` reloaded."); handler->SendGlobalGMSysMessage("DB table `trainer_spell` reloaded."); handler->SendGlobalGMSysMessage("DB table `creature_default_trainer` reloaded."); return true; } static bool HandleReloadNpcVendorCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `npc_vendor` Table!"); sObjectMgr->LoadVendors(); handler->SendGlobalGMSysMessage("DB table `npc_vendor` reloaded."); return true; } static bool HandleReloadPointsOfInterestCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `points_of_interest` Table!"); sObjectMgr->LoadPointsOfInterest(); handler->SendGlobalGMSysMessage("DB table `points_of_interest` reloaded."); return true; } static bool HandleReloadQuestPOICommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest POI ..." ); sObjectMgr->LoadQuestPOI(); sObjectMgr->InitializeQueriesData(QUERY_DATA_POIS); handler->SendGlobalGMSysMessage("DB Table `quest_poi` and `quest_poi_points` reloaded."); return true; } static bool HandleReloadSpellClickSpellsCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `npc_spellclick_spells` Table!"); sObjectMgr->LoadNPCSpellClickSpells(); handler->SendGlobalGMSysMessage("DB table `npc_spellclick_spells` reloaded."); return true; } static bool HandleReloadReservedNameCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Loading ReservedNames... (`reserved_name`)"); sObjectMgr->LoadReservedPlayersNames(); handler->SendGlobalGMSysMessage("DB table `reserved_name` (player reserved names) reloaded."); return true; } static bool HandleReloadReputationRewardRateCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `reputation_reward_rate` Table!" ); sObjectMgr->LoadReputationRewardRate(); handler->SendGlobalSysMessage("DB table `reputation_reward_rate` reloaded."); return true; } static bool HandleReloadReputationSpilloverTemplateCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `reputation_spillover_template` Table!" ); sObjectMgr->LoadReputationSpilloverTemplate(); handler->SendGlobalSysMessage("DB table `reputation_spillover_template` reloaded."); return true; } static bool HandleReloadSkillDiscoveryTemplateCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Skill Discovery Table..."); LoadSkillDiscoveryTable(); handler->SendGlobalGMSysMessage("DB table `skill_discovery_template` (recipes discovered at crafting) reloaded."); return true; } static bool HandleReloadSkillPerfectItemTemplateCommand(ChatHandler* handler, const char* /*args*/) { // latched onto HandleReloadSkillExtraItemTemplateCommand as it's part of that table group (and i don't want to chance all the command IDs) TC_LOG_INFO("misc", "Re-Loading Skill Perfection Data Table..."); LoadSkillPerfectItemTable(); handler->SendGlobalGMSysMessage("DB table `skill_perfect_item_template` (perfect item procs when crafting) reloaded."); return true; } static bool HandleReloadSkillExtraItemTemplateCommand(ChatHandler* handler, const char* args) { TC_LOG_INFO("misc", "Re-Loading Skill Extra Item Table..."); LoadSkillExtraItemTable(); handler->SendGlobalGMSysMessage("DB table `skill_extra_item_template` (extra item creation when crafting) reloaded."); return HandleReloadSkillPerfectItemTemplateCommand(handler, args); } static bool HandleReloadSkillFishingBaseLevelCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Skill Fishing base level requirements..."); sObjectMgr->LoadFishingBaseSkillLevel(); handler->SendGlobalGMSysMessage("DB table `skill_fishing_base_level` (fishing base level for zone/subzone) reloaded."); return true; } static bool HandleReloadSpellAreaCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading SpellArea Data..."); sSpellMgr->LoadSpellAreas(); handler->SendGlobalGMSysMessage("DB table `spell_area` (spell dependences from area/quest/auras state) reloaded."); return true; } static bool HandleReloadSpellRequiredCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Required Data... "); sSpellMgr->LoadSpellRequired(); handler->SendGlobalGMSysMessage("DB table `spell_required` reloaded."); return true; } static bool HandleReloadSpellGroupsCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Groups..."); sSpellMgr->LoadSpellGroups(); handler->SendGlobalGMSysMessage("DB table `spell_group` (spell groups) reloaded."); return true; } static bool HandleReloadSpellLearnSpellCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Learn Spells..."); sSpellMgr->LoadSpellLearnSpells(); handler->SendGlobalGMSysMessage("DB table `spell_learn_spell` reloaded."); return true; } static bool HandleReloadSpellLinkedSpellCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Linked Spells..."); sSpellMgr->LoadSpellLinked(); handler->SendGlobalGMSysMessage("DB table `spell_linked_spell` reloaded."); return true; } static bool HandleReloadSpellProcsCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Proc conditions and data..."); sSpellMgr->LoadSpellProcs(); handler->SendGlobalGMSysMessage("DB table `spell_proc` (spell proc conditions and data) reloaded."); return true; } static bool HandleReloadSpellTargetPositionCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell target coordinates..."); sSpellMgr->LoadSpellTargetPositions(); handler->SendGlobalGMSysMessage("DB table `spell_target_position` (destination coordinates for spell targets) reloaded."); return true; } static bool HandleReloadSpellThreatsCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Aggro Spells Definitions..."); sSpellMgr->LoadSpellThreats(); handler->SendGlobalGMSysMessage("DB table `spell_threat` (spell aggro definitions) reloaded."); return true; } static bool HandleReloadSpellGroupStackRulesCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Group Stack Rules..."); sSpellMgr->LoadSpellGroupStackRules(); handler->SendGlobalGMSysMessage("DB table `spell_group_stack_rules` (spell stacking definitions) reloaded."); return true; } static bool HandleReloadSpellPetAurasCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell pet auras..."); sSpellMgr->LoadSpellPetAuras(); handler->SendGlobalGMSysMessage("DB table `spell_pet_auras` reloaded."); return true; } static bool HandleReloadPageTextsCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Page Text..."); sObjectMgr->LoadPageTexts(); handler->SendGlobalGMSysMessage("DB table `page_text` reloaded."); return true; } static bool HandleReloadItemRandomBonusListTemplatesCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Random item bonus list definitions..."); LoadItemRandomBonusListTemplates(); handler->SendGlobalGMSysMessage("DB table `item_random_bonus_list_template` reloaded."); return true; } static bool HandleReloadEventScriptsCommand(ChatHandler* handler, const char* args) { if (sMapMgr->IsScriptScheduled()) { handler->SendSysMessage("DB scripts used currently, please attempt reload later."); handler->SetSentErrorMessage(true); return false; } if (*args != 'a') TC_LOG_INFO("misc", "Re-Loading Scripts from `event_scripts`..."); sObjectMgr->LoadEventScripts(); if (*args != 'a') handler->SendGlobalGMSysMessage("DB table `event_scripts` reloaded."); return true; } static bool HandleReloadWpScriptsCommand(ChatHandler* handler, const char* args) { if (sMapMgr->IsScriptScheduled()) { handler->SendSysMessage("DB scripts used currently, please attempt reload later."); handler->SetSentErrorMessage(true); return false; } if (*args != 'a') TC_LOG_INFO("misc", "Re-Loading Scripts from `waypoint_scripts`..."); sObjectMgr->LoadWaypointScripts(); if (*args != 'a') handler->SendGlobalGMSysMessage("DB table `waypoint_scripts` reloaded."); return true; } static bool HandleReloadWpCommand(ChatHandler* handler, const char* args) { if (*args != 'a') TC_LOG_INFO("misc", "Re-Loading Waypoints data from 'waypoints_data'"); sWaypointMgr->Load(); if (*args != 'a') handler->SendGlobalGMSysMessage("DB Table 'waypoint_data' reloaded."); return true; } static bool HandleReloadScriptNamesCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Reloading spell_script_names..."); sObjectMgr->LoadSpellScriptNames(); sObjectMgr->ValidateSpellScripts(); handler->SendGlobalGMSysMessage("spell script names reloaded."); return true; } static bool HandleReloadSpellScriptsCommand(ChatHandler* handler, const char* args) { if (sMapMgr->IsScriptScheduled()) { handler->SendSysMessage("DB scripts used currently, please attempt reload later."); handler->SetSentErrorMessage(true); return false; } if (*args != 'a') TC_LOG_INFO("misc", "Re-Loading Scripts from `spell_scripts`..."); sObjectMgr->LoadSpellScripts(); if (*args != 'a') handler->SendGlobalGMSysMessage("DB table `spell_scripts` reloaded."); return true; } static bool HandleReloadGameGraveyardZoneCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Graveyard-zone links..."); sObjectMgr->LoadGraveyardZones(); handler->SendGlobalGMSysMessage("DB table `graveyard_zone` reloaded."); return true; } static bool HandleReloadGameTeleCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Game Tele coordinates..."); sObjectMgr->LoadGameTele(); handler->SendGlobalGMSysMessage("DB table `game_tele` reloaded."); return true; } static bool HandleReloadDisablesCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading disables table..."); DisableMgr::LoadDisables(); TC_LOG_INFO("misc", "Checking quest disables..."); DisableMgr::CheckQuestDisables(); handler->SendGlobalGMSysMessage("DB table `disables` reloaded."); return true; } static bool HandleReloadLocalesAchievementRewardCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Locales Achievement Reward Data..."); sAchievementMgr->LoadRewardLocales(); handler->SendGlobalGMSysMessage("DB table `locales_achievement_reward` reloaded."); return true; } static bool HandleReloadLfgRewardsCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading lfg dungeon rewards..."); sLFGMgr->LoadRewards(); handler->SendGlobalGMSysMessage("DB table `lfg_dungeon_rewards` reloaded."); return true; } static bool HandleReloadLocalesCreatureCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Locales Creature ..."); sObjectMgr->LoadCreatureLocales(); handler->SendGlobalGMSysMessage("DB table `locales_creature` reloaded."); return true; } static bool HandleReloadLocalesCreatureTextCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Locales Creature Texts..."); sCreatureTextMgr->LoadCreatureTextLocales(); handler->SendGlobalGMSysMessage("DB table `locales_creature_text` reloaded."); return true; } static bool HandleReloadLocalesGameobjectCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Locales Gameobject ... "); sObjectMgr->LoadGameObjectLocales(); handler->SendGlobalGMSysMessage("DB table `locales_gameobject` reloaded."); return true; } static bool HandleReloadLocalesGossipMenuOptionCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Locales Gossip Menu Option ... "); sObjectMgr->LoadGossipMenuItemsLocales(); handler->SendGlobalGMSysMessage("DB table `locales_gossip_menu_option` reloaded."); return true; } static bool HandleReloadLocalesPageTextCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Locales Page Text ... "); sObjectMgr->LoadPageTextLocales(); handler->SendGlobalGMSysMessage("DB table `locales_page_text` reloaded."); return true; } static bool HandleReloadLocalesPointsOfInterestCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Locales Points Of Interest ... "); sObjectMgr->LoadPointOfInterestLocales(); handler->SendGlobalGMSysMessage("DB table `locales_points_of_interest` reloaded."); return true; } static bool HandleReloadQuestLocaleCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest Locale ... "); sObjectMgr->LoadQuestTemplateLocale(); sObjectMgr->LoadQuestObjectivesLocale(); sObjectMgr->LoadQuestGreetingLocales(); sObjectMgr->LoadQuestOfferRewardLocale(); sObjectMgr->LoadQuestRequestItemsLocale(); handler->SendGlobalGMSysMessage("DB table `quest_template_locale` reloaded."); handler->SendGlobalGMSysMessage("DB table `quest_objectives_locale` reloaded."); handler->SendGlobalGMSysMessage("DB table `quest_greeting_locale` reloaded."); handler->SendGlobalGMSysMessage("DB table `quest_offer_reward_locale` reloaded."); handler->SendGlobalGMSysMessage("DB table `quest_request_items_locale` reloaded."); return true; } static bool HandleReloadMailLevelRewardCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Player level dependent mail rewards..."); sObjectMgr->LoadMailLevelRewards(); handler->SendGlobalGMSysMessage("DB table `mail_level_reward` reloaded."); return true; } static bool HandleReloadAuctionsCommand(ChatHandler* handler, const char* /*args*/) { ///- Reload dynamic data tables from the database TC_LOG_INFO("misc", "Re-Loading Auctions..."); sAuctionMgr->LoadAuctions(); handler->SendGlobalGMSysMessage("Auctions reloaded."); return true; } static bool HandleReloadConditions(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Conditions..."); sConditionMgr->LoadConditions(true); handler->SendGlobalGMSysMessage("Conditions reloaded."); return true; } static bool HandleReloadCreatureText(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Creature Texts..."); sCreatureTextMgr->LoadCreatureTexts(); handler->SendGlobalGMSysMessage("Creature Texts reloaded."); return true; } static bool HandleReloadSmartScripts(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Smart Scripts..."); sSmartScriptMgr->LoadSmartAIFromDB(); if (WorldSession* session = handler->GetSession()) { std::list<Creature*> creatures; session->GetPlayer()->GetCreatureListInGrid(creatures); for (Creature* creature : creatures) creature->AIM_Initialize(); std::list<GameObject*> gameObjects; session->GetPlayer()->GetGameObjectListWithEntryInGrid(gameObjects, 0); for (GameObject* gameObject : gameObjects) gameObject->AIM_Initialize(); } handler->SendGlobalGMSysMessage("Smart Scripts reloaded."); return true; } static bool HandleReloadVehicleAccessoryCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Reloading vehicle_accessory table..."); sObjectMgr->LoadVehicleAccessories(); handler->SendGlobalGMSysMessage("Vehicle accessories reloaded."); return true; } static bool HandleReloadVehicleTemplateAccessoryCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Reloading vehicle_template_accessory table..."); sObjectMgr->LoadVehicleTemplateAccessories(); handler->SendGlobalGMSysMessage("Vehicle template accessories reloaded."); return true; } static bool HandleReloadAreaTriggerTemplateCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Reloading areatrigger_template table..."); sAreaTriggerDataStore->LoadAreaTriggerTemplates(); handler->SendGlobalGMSysMessage("AreaTrigger templates reloaded. Already spawned AT won't be affected. New scriptname need a reboot."); return true; } static bool HandleReloadSceneTemplateCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Reloading scene_template table..."); sObjectMgr->LoadSceneTemplates(); handler->SendGlobalGMSysMessage("Scenes templates reloaded. New scriptname need a reboot."); return true; } static bool HandleReloadConversationTemplateCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Reloading conversation_* tables..."); sConversationDataStore->LoadConversationTemplates(); handler->SendGlobalGMSysMessage("Conversation templates reloaded."); return true; } static bool HandleReloadRBACCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Reloading RBAC tables..."); sAccountMgr->LoadRBAC(); sWorld->ReloadRBAC(); handler->SendGlobalGMSysMessage("RBAC data reloaded."); return true; } static bool HandleReloadScriptParamsCommand(ChatHandler* handler, const char* /*args*/) { TC_LOG_INFO("misc", "Reloading script_params table..."); sObjectMgr->LoadScriptParams(); handler->SendGlobalGMSysMessage("Script params reloaded."); return true; } }; void AddSC_reload_commandscript() { new reload_commandscript(); }
[ "zemetskia@gmail.com" ]
zemetskia@gmail.com
929f29ed80129ade2298b7ddbe53cde070b34c45
90047daeb462598a924d76ddf4288e832e86417c
/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc
47375a5b74c6493c06905f19cdf40f20fb99a61b
[ "BSD-3-Clause" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
6,787
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/api/messaging/native_message_host.h" #include <memory> #include <string> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/location.h" #include "base/macros.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/arc/extensions/arc_support_message_host.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/constants.h" #include "extensions/common/url_pattern.h" #include "net/url_request/url_request_context_getter.h" #include "remoting/base/auto_thread_task_runner.h" #include "remoting/host/chromoting_host_context.h" #include "remoting/host/it2me/it2me_native_messaging_host.h" #include "remoting/host/policy_watcher.h" #include "ui/gfx/native_widget_types.h" #include "url/gurl.h" namespace extensions { namespace { // A simple NativeMessageHost that mimics the implementation of // chrome/test/data/native_messaging/native_hosts/echo.py. It is currently // used for testing by ExtensionApiTest::NativeMessagingBasic. const char* const kEchoHostOrigins[] = { // ScopedTestNativeMessagingHost::kExtensionId "chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"}; class EchoHost : public NativeMessageHost { public: static std::unique_ptr<NativeMessageHost> Create() { return std::unique_ptr<NativeMessageHost>(new EchoHost()); } EchoHost() : message_number_(0), client_(NULL) {} void Start(Client* client) override { client_ = client; } void OnMessage(const std::string& request_string) override { std::unique_ptr<base::Value> request_value = base::JSONReader::Read(request_string); std::unique_ptr<base::DictionaryValue> request( static_cast<base::DictionaryValue*>(request_value.release())); if (request_string.find("stopHostTest") != std::string::npos) { client_->CloseChannel(kNativeHostExited); } else if (request_string.find("bigMessageTest") != std::string::npos) { client_->CloseChannel(kHostInputOuputError); } else { ProcessEcho(*request); } }; scoped_refptr<base::SingleThreadTaskRunner> task_runner() const override { return base::ThreadTaskRunnerHandle::Get(); }; private: void ProcessEcho(const base::DictionaryValue& request) { base::DictionaryValue response; response.SetInteger("id", ++message_number_); response.Set("echo", request.CreateDeepCopy()); response.SetString("caller_url", kEchoHostOrigins[0]); std::string response_string; base::JSONWriter::Write(response, &response_string); client_->PostMessageFromNativeHost(response_string); } int message_number_; Client* client_; DISALLOW_COPY_AND_ASSIGN(EchoHost); }; struct BuiltInHost { const char* const name; const char* const* const allowed_origins; int allowed_origins_count; std::unique_ptr<NativeMessageHost> (*create_function)(); }; std::unique_ptr<NativeMessageHost> CreateIt2MeHost() { std::unique_ptr<remoting::It2MeHostFactory> host_factory( new remoting::It2MeHostFactory()); std::unique_ptr<remoting::ChromotingHostContext> context = remoting::ChromotingHostContext::CreateForChromeOS( make_scoped_refptr(g_browser_process->system_request_context()), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::IO), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::UI), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::FILE)); std::unique_ptr<remoting::PolicyWatcher> policy_watcher = remoting::PolicyWatcher::Create(g_browser_process->policy_service(), context->file_task_runner()); std::unique_ptr<NativeMessageHost> host( new remoting::It2MeNativeMessagingHost( /*needs_elevation=*/false, std::move(policy_watcher), std::move(context), std::move(host_factory))); return host; } // If you modify the list of allowed_origins, don't forget to update // remoting/host/it2me/com.google.chrome.remote_assistance.json.jinja2 // to keep the two lists in sync. // TODO(kelvinp): Load the native messaging manifest as a resource file into // chrome and fetch the list of allowed_origins from the manifest (see // crbug/424743). const char* const kRemotingIt2MeOrigins[] = { "chrome-extension://ljacajndfccfgnfohlgkdphmbnpkjflk/", "chrome-extension://gbchcmhmhahfdphkhkmpfmihenigjmpp/", "chrome-extension://kgngmbheleoaphbjbaiobfdepmghbfah/", "chrome-extension://odkaodonbgfohohmklejpjiejmcipmib/", "chrome-extension://dokpleeekgeeiehdhmdkeimnkmoifgdd/", "chrome-extension://ajoainacpilcemgiakehflpbkbfipojk/", "chrome-extension://hmboipgjngjoiaeicfdifdoeacilalgc/", "chrome-extension://inomeogfingihgjfjlpeplalcfajhgai/", "chrome-extension://hpodccmdligbeohchckkeajbfohibipg/"}; static const BuiltInHost kBuiltInHost[] = { {"com.google.chrome.test.echo", // ScopedTestNativeMessagingHost::kHostName kEchoHostOrigins, arraysize(kEchoHostOrigins), &EchoHost::Create}, {"com.google.chrome.remote_assistance", kRemotingIt2MeOrigins, arraysize(kRemotingIt2MeOrigins), &CreateIt2MeHost}, {arc::ArcSupportMessageHost::kHostName, arc::ArcSupportMessageHost::kHostOrigin, 1, &arc::ArcSupportMessageHost::Create}, }; bool MatchesSecurityOrigin(const BuiltInHost& host, const std::string& extension_id) { GURL origin(std::string(kExtensionScheme) + "://" + extension_id); for (int i = 0; i < host.allowed_origins_count; i++) { URLPattern allowed_origin(URLPattern::SCHEME_ALL, host.allowed_origins[i]); if (allowed_origin.MatchesSecurityOrigin(origin)) { return true; } } return false; } } // namespace std::unique_ptr<NativeMessageHost> NativeMessageHost::Create( gfx::NativeView native_view, const std::string& source_extension_id, const std::string& native_host_name, bool allow_user_level, std::string* error) { for (unsigned int i = 0; i < arraysize(kBuiltInHost); i++) { const BuiltInHost& host = kBuiltInHost[i]; std::string name(host.name); if (name == native_host_name) { if (MatchesSecurityOrigin(host, source_extension_id)) { return (*host.create_function)(); } *error = kForbiddenError; return nullptr; } } *error = kNotFoundError; return nullptr; } } // namespace extensions
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
05f574c41ec79332a1cab06814420cc3269b8733
cf9977e49ac1f133f583ae016a0283b4f47a0801
/kpegasus/emul.cpp
523e0efb4d73acbab9e8185841d2c78fc2ffbad0
[]
no_license
blaquee/pegasus
e67bdb279d6bfce678278b42235ca3a4c460821f
23b482b36a755b361e06b6292263523839be3faa
refs/heads/master
2021-01-16T00:50:01.165831
2017-08-08T13:44:27
2017-08-08T13:44:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,534
cpp
#define _CRT_SECURE_NO_WARNINGS #include <unicorn/unicorn.h> #include <engextcpp.hpp> #include <Windows.h> #include <stdio.h> #include <list> #include <memory> #include <strsafe.h> #include <interface.h> #include <engine.h> #include <windbg_engine_linker.h> #include <emulator.h> #pragma comment(lib, "unicorn_static_x64.lib") std::shared_ptr<engine::debugger> g_emulator; static void hook_unmap_memory(uc_engine *uc, uc_mem_type type, uint64_t address, int size, int64_t value, void *user_data) { if (type == UC_MEM_WRITE_UNMAPPED || type == UC_MEM_READ_UNMAPPED) { emulation_debugger::page unknown_page; unsigned char *unknown_dump = g_emulator->load_page(address, &unknown_page.base, &unknown_page.size); std::shared_ptr<void> dump_closer(unknown_dump, free); if (unknown_dump) { uc_mem_map(uc, unknown_page.base, unknown_page.size, UC_PROT_ALL); uc_mem_write(uc, unknown_page.base, unknown_dump, unknown_page.size); return; } unsigned char dump[16] = { 0, }; address += 0x1; uc_err err; if ((err = uc_mem_read(uc, address, dump, 16)) == 0) return; size_t resize = g_emulator->alignment((size_t)address, 0x1000); uc_mem_region *um = nullptr; uint32_t count = 0; if (uc_mem_regions(uc, &um, &count) != 0) return; uc_mem_region b; for (unsigned int i = 0; i < count; ++i) { if (um[i].end < resize && um[i + 1].begin >= resize) { b.begin = um[i].begin; b.end = um[i].end; break; } } unsigned long long base = b.end + 1; size_t size = resize - base; err = uc_mem_map(uc, base, size, UC_PROT_ALL); } } static void hook_fetch_memory(uc_engine *uc, uc_mem_type type, uint64_t address, int size, int64_t value, void *user_data) { if (type == UC_MEM_FETCH_UNMAPPED) { emulation_debugger::page unknown_page; unsigned char *unknown_dump = g_emulator->load_page(address, &unknown_page.base, &unknown_page.size); std::shared_ptr<void> dump_closer(unknown_dump, free); if (unknown_dump) { uc_err err; if((err = uc_mem_map(uc, unknown_page.base, unknown_page.size, UC_PROT_ALL)) == 0) { uc_mem_write(uc, unknown_page.base, unknown_dump, unknown_page.size); } } } } /// /// /// EXT_CLASS_COMMAND(EmulationEngine, attach, "", "{;e,o;;;}") { if (g_emulator) { detach(); g_emulator.reset(); } if (!engine::create<emulation_debugger>(g_emulator)) return; if (g_emulator->attach()) dprintf("attach process\n"); } EXT_CLASS_COMMAND(EmulationEngine, detach, "", "{;e,o;;;}") { if (!g_emulator) return; if (g_emulator->clear_ring3()) dprintf("clear ring3 partition\n"); else dprintf("clear fail..\n"); g_emulator.reset(); } EXT_CLASS_COMMAND(EmulationEngine, trace, "", "{bp;ed,o;bp;;}") { bool strange = false; unsigned long long bp = GetArgU64("bp", FALSE); if(!g_emulator->is_64_cpu()) { if (g_Ext->IsCurMachine64()) g_Ext->ExecuteSilent("!wow64exts.sw"); if (g_emulator->trace32(nullptr, bp, hook_unmap_memory, hook_fetch_memory, nullptr, nullptr)) { if (g_emulator->is_64_cpu()) dprintf("switch wow64cpu=>64bit\n"); } else dprintf("break\n"); } else { if (g_Ext->IsCurMachine32()) g_Ext->ExecuteSilent("!wow64exts.sw"); if (g_emulator->trace64(nullptr, bp, hook_unmap_memory, hook_fetch_memory, nullptr, nullptr)) { if (g_emulator->is_64_cpu()) dprintf("switch wow64cpu=>64bit\n"); } else dprintf("break\n"); } } EXT_CLASS_COMMAND(EmulationEngine, regs, "", "{;e,o;;;}") { if (!g_emulator) return; g_emulator->current_regs(); }
[ "0a777h@gmail.com" ]
0a777h@gmail.com
f732d554934e41f32727f31b39887e5f1e537bfe
d6ebb95483c205b5dd2987ff778b778a1dcd0033
/Car.cpp
a27ca4b0eed496281f946ff83b2afb1b477372ef
[]
no_license
Kristjan-O-Ragnarsson/CPP6
d999ec8f90f9b438cd84780ca7bd7776ee8355a9
8b27d4dd2c71caa9b1ff3a322838aa0775617815
refs/heads/master
2020-04-05T21:21:45.433033
2018-11-12T14:33:12
2018-11-12T14:33:12
157,217,351
0
0
null
null
null
null
UTF-8
C++
false
false
416
cpp
// // Created by Lenovo on 12.11.2018. // #include "Car.h" Car::Car() { for(int i = 0; i < 4; i++){ w[i] = Wheel(); } for(int i = 0; i < 10 ; i ++){ int t = i+2; l[i] = Light(t/2); } } void Car::print() { e.print(); for(int i = 0;i < 4; i++){ w[i].print(); } c.print(); for(int i = 0; i < 10; i++){ l[i].print(); } b.print(); }
[ "kristjanra262@nemi.tskoli.is" ]
kristjanra262@nemi.tskoli.is
7cc053c991c84a23592051e553e5c833dccdd06e
d561fb973fcb9ee5c2b006dc9f736400b8d07d6a
/10851.cpp
8774aec26ed8d35aa0246332afda706631426efa
[]
no_license
pnikic/Hacking-uva
02947286d02a64a3b9ec7326c4581a11724d27fa
cf236c0239f5fba9f934e8431441cadd919ce13d
refs/heads/master
2020-06-21T22:34:40.688518
2018-11-04T12:46:19
2018-11-04T12:46:19
74,769,347
0
0
null
null
null
null
UTF-8
C++
false
false
548
cpp
#include <iostream> #include <string> using namespace std; int main() { int n; cin >> n; for (int i = 0; i < n; ++i) { string s, S[8]; cin >> s; for (int k = 0; k < 8; ++k) cin >> S[k]; cin >> s; string res; for (int j = 1; j < S[0].size() - 1; ++j) { int x = 0; for (int k = 0; k < 8; ++k) if (S[k][j] == '\\') x += 1 << k; res += char(x); } cout << res << '\n'; } }
[ "pnikic@mathos.hr" ]
pnikic@mathos.hr