blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
e655777debebbedb337dfd260417110a5feb0867
838dc19e767fcc83913489a4a7662e89ce3fa510
/game/tools/particleeditor/source/textureuvdialoggui.cpp
aa2d9d255607d46a59f02dceca91c7784487fdc6
[ "MIT" ]
permissive
justinctlam/MarbleStrike
b757df8c7f7b5961d87fd5f9b5c59e6af777e70e
64fe36a5a4db2b299983b0e2556ab1cd8126259b
refs/heads/master
2020-09-13T23:49:12.139990
2016-09-04T04:02:50
2016-09-04T04:02:50
67,262,851
0
2
null
null
null
null
UTF-8
C++
false
false
7,298
cpp
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version Apr 16 2008) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #include "textureuvdialoggui.h" /////////////////////////////////////////////////////////////////////////// TextureUVDialogGui::TextureUVDialogGui( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); wxBoxSizer* bSizer5; bSizer5 = new wxBoxSizer( wxVERTICAL ); wxFlexGridSizer* fgSizer3; fgSizer3 = new wxFlexGridSizer( 2, 2, 0, 0 ); fgSizer3->SetFlexibleDirection( wxBOTH ); fgSizer3->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); m_button4 = new wxButton( this, wxID_ANY, wxT("Zoom (+)"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer3->Add( m_button4, 0, wxALL, 5 ); m_button5 = new wxButton( this, wxID_ANY, wxT("Zoom (-)"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer3->Add( m_button5, 0, wxALL, 5 ); bSizer5->Add( fgSizer3, 0, 0, 5 ); mImagePanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); bSizer5->Add( mImagePanel, 1, wxEXPAND | wxALL, 5 ); wxFlexGridSizer* fgSizer6; fgSizer6 = new wxFlexGridSizer( 2, 3, 0, 0 ); fgSizer6->SetFlexibleDirection( wxBOTH ); fgSizer6->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); m_staticText9 = new wxStaticText( this, wxID_ANY, wxT("Width/Height:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText9->Wrap( -1 ); fgSizer6->Add( m_staticText9, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextUVWidth = new wxTextCtrl( this, UV_PROPERTIES_WIDTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); fgSizer6->Add( mTextUVWidth, 0, wxALL, 5 ); mTextUVHeight = new wxTextCtrl( this, UV_PROPERTIES_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); fgSizer6->Add( mTextUVHeight, 0, wxALL, 5 ); m_staticText11 = new wxStaticText( this, wxID_ANY, wxT("Position:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText11->Wrap( -1 ); fgSizer6->Add( m_staticText11, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextUVX = new wxTextCtrl( this, UV_PROPERTIES_POSITION_X, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); fgSizer6->Add( mTextUVX, 0, wxALL, 5 ); mTextUVY = new wxTextCtrl( this, UV_PROPERTIES_POSITION_Y, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); fgSizer6->Add( mTextUVY, 0, wxALL, 5 ); bSizer5->Add( fgSizer6, 0, wxALIGN_CENTER_HORIZONTAL, 5 ); wxFlexGridSizer* fgSizer2; fgSizer2 = new wxFlexGridSizer( 1, 2, 0, 0 ); fgSizer2->SetFlexibleDirection( wxBOTH ); fgSizer2->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); m_button1 = new wxButton( this, wxID_ANY, wxT("OK"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer2->Add( m_button1, 0, wxALL, 5 ); m_button2 = new wxButton( this, wxID_ANY, wxT("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer2->Add( m_button2, 0, wxALL, 5 ); bSizer5->Add( fgSizer2, 0, wxALIGN_CENTER_HORIZONTAL, 5 ); this->SetSizer( bSizer5 ); this->Layout(); // Connect Events this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( TextureUVDialogGui::OnInitDialog ) ); m_button4->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( TextureUVDialogGui::OnButtonClickMagnified ), NULL, this ); m_button5->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( TextureUVDialogGui::OnButtonClickMinified ), NULL, this ); mImagePanel->Connect( wxEVT_ERASE_BACKGROUND, wxEraseEventHandler( TextureUVDialogGui::OnEraseBackground ), NULL, this ); mImagePanel->Connect( wxEVT_KEY_DOWN, wxKeyEventHandler( TextureUVDialogGui::OnKeyDownImagePanel ), NULL, this ); mImagePanel->Connect( wxEVT_KEY_UP, wxKeyEventHandler( TextureUVDialogGui::OnKeyUpImagePanel ), NULL, this ); mImagePanel->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( TextureUVDialogGui::OnLeftDownImagePanel ), NULL, this ); mImagePanel->Connect( wxEVT_LEFT_UP, wxMouseEventHandler( TextureUVDialogGui::OnLeftUpImagePanel ), NULL, this ); mImagePanel->Connect( wxEVT_MOTION, wxMouseEventHandler( TextureUVDialogGui::OnMotionImagePanel ), NULL, this ); mImagePanel->Connect( wxEVT_PAINT, wxPaintEventHandler( TextureUVDialogGui::OnPaint ), NULL, this ); mTextUVWidth->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( TextureUVDialogGui::OnTextEnter ), NULL, this ); mTextUVHeight->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( TextureUVDialogGui::OnTextEnter ), NULL, this ); mTextUVX->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( TextureUVDialogGui::OnTextEnter ), NULL, this ); mTextUVY->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( TextureUVDialogGui::OnTextEnter ), NULL, this ); m_button1->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( TextureUVDialogGui::OnButtonClickOK ), NULL, this ); m_button2->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( TextureUVDialogGui::OnButtonClickCancel ), NULL, this ); } TextureUVDialogGui::~TextureUVDialogGui() { // Disconnect Events this->Disconnect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( TextureUVDialogGui::OnInitDialog ) ); m_button4->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( TextureUVDialogGui::OnButtonClickMagnified ), NULL, this ); m_button5->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( TextureUVDialogGui::OnButtonClickMinified ), NULL, this ); mImagePanel->Disconnect( wxEVT_ERASE_BACKGROUND, wxEraseEventHandler( TextureUVDialogGui::OnEraseBackground ), NULL, this ); mImagePanel->Disconnect( wxEVT_KEY_DOWN, wxKeyEventHandler( TextureUVDialogGui::OnKeyDownImagePanel ), NULL, this ); mImagePanel->Disconnect( wxEVT_KEY_UP, wxKeyEventHandler( TextureUVDialogGui::OnKeyUpImagePanel ), NULL, this ); mImagePanel->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( TextureUVDialogGui::OnLeftDownImagePanel ), NULL, this ); mImagePanel->Disconnect( wxEVT_LEFT_UP, wxMouseEventHandler( TextureUVDialogGui::OnLeftUpImagePanel ), NULL, this ); mImagePanel->Disconnect( wxEVT_MOTION, wxMouseEventHandler( TextureUVDialogGui::OnMotionImagePanel ), NULL, this ); mImagePanel->Disconnect( wxEVT_PAINT, wxPaintEventHandler( TextureUVDialogGui::OnPaint ), NULL, this ); mTextUVWidth->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( TextureUVDialogGui::OnTextEnter ), NULL, this ); mTextUVHeight->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( TextureUVDialogGui::OnTextEnter ), NULL, this ); mTextUVX->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( TextureUVDialogGui::OnTextEnter ), NULL, this ); mTextUVY->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( TextureUVDialogGui::OnTextEnter ), NULL, this ); m_button1->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( TextureUVDialogGui::OnButtonClickOK ), NULL, this ); m_button2->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( TextureUVDialogGui::OnButtonClickCancel ), NULL, this ); }
[ "justin.t.lam@gmail.com" ]
justin.t.lam@gmail.com
bdf694f121f4caa4b6240b17cab28d62563261e7
27bd16b410dbd6aa669012cc5dc36c96532d04e0
/C++ Code/tcpServerSocket.cpp
f19004c107e7111087043259778aff4fb7ed7283
[]
no_license
amroot96/CS457-sockets-and-threads
2600eef11f1448af61b46e97ade70b01ac977fc7
8586f256be71264f46975e0e59a4b5ab69d56b6b
refs/heads/master
2020-03-29T06:56:42.659444
2018-12-22T16:13:00
2018-12-22T16:13:00
149,647,057
0
0
null
null
null
null
UTF-8
C++
false
false
2,242
cpp
#include "tcpServerSocket.h" #include "tcpUserSocket.h" using namespace std; cs457::tcpServerSocket::tcpServerSocket(uint portNumber): port(portNumber), address("") { init(); setSocketOptions(); }; cs457::tcpServerSocket::tcpServerSocket(string networkAddress, uint portNumber): address(networkAddress), port(portNumber) { init(); setSocketOptions(); }; int cs457::tcpServerSocket::bindSocket() { socklen_t size = sizeof(serverAddress); return ::bind(serverSocket,(struct sockaddr *)&serverAddress,size); } int cs457::tcpServerSocket::listenSocket() { return listen(serverSocket,14); } tuple<shared_ptr<cs457::tcpUserSocket>,int> cs457::tcpServerSocket::acceptSocket() { shared_ptr<cs457::tcpUserSocket> userSocket = make_shared<tcpUserSocket>(); socklen_t len = userSocket.get()->getLenghtPointer(); int client_fd = accept(serverSocket,(struct sockaddr *)userSocket.get()->getAddressPointer(),&len); userSocket.get()->setSocket(client_fd); //get ip and port // you can always get it like this: getsockname(sockfd, (struct sockaddr *) &my_addr, &len); //but you already have it char userIPv4[16]; sockaddr_in * userAddress = (sockaddr_in *) userSocket.get()->getAddressPointer(); inet_ntop(AF_INET, &(userAddress->sin_addr), userIPv4, INET_ADDRSTRLEN); auto clientPort = ntohs(userAddress->sin_port); userSocket.get()->setUserInfoIPv4(string(userIPv4),clientPort); return make_tuple(userSocket,client_fd); } void cs457::tcpServerSocket::init() { serverSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); const char * cstr = address.c_str(); int val =0; bzero(&serverAddress,sizeof(serverAddress)); serverAddress.sin_family = AF_INET; if (address == "") addr.s_addr = htonl(INADDR_ANY); else { val = inet_aton(cstr,&addr); serverAddress.sin_addr = addr; string addresscpy(inet_ntoa(addr)); address = addresscpy; } serverAddress.sin_port = htons(port); } void cs457::tcpServerSocket::setSocketOptions() { int optval = 1; setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int)); }
[ "amroot@rams.colostate.edu" ]
amroot@rams.colostate.edu
dcbb72ab5832e9470330d6b17b09df34deefa161
99acb431893f7eac93183152fce8d19c9653b59b
/components/query_tiles/internal/tile_config.h
2c9e3c05f8b1e995989a9c7391adf395a92e4c93
[ "BSD-3-Clause" ]
permissive
PDi-Communication-Systems-Inc/chromium
0a4e7634056369fe32ef75beb6cdb47e0641a9dc
fd11f6f060bf073509855e13c215d64d3c3a1a15
refs/heads/master
2023-04-17T05:37:17.394483
2020-05-14T13:19:32
2020-05-14T13:19:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,366
h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_QUERY_TILES_INTERNAL_TILE_CONFIG_H_ #define COMPONENTS_QUERY_TILES_INTERNAL_TILE_CONFIG_H_ #include <memory> #include <string> #include "base/time/time.h" #include "components/query_tiles/internal/tile_types.h" #include "url/gurl.h" namespace query_tiles { // Default URL string for GetQueryTiles RPC. extern const char kDefaultGetQueryTilePath[]; // Finch parameter key for experiment tag to be passed to the server. extern const char kExperimentTagKey[]; // Finch parameter key for base server URL to retrieve the tiles. extern const char kBaseURLKey[]; // Finch parameter key for expire duration in seconds. extern const char kExpireDurationKey[]; // Finch parameter key for expire duration in seconds. extern const char kIsUnmeteredNetworkRequiredKey[]; // Finch parameter key for image prefetch mode. extern const char kImagePrefetchModeKey[]; // Finch parameter key for the minimum interval to next schedule. extern const char kNextScheduleMinIntervalKey[]; // Finch parameter key for random window. extern const char kMaxRandomWindowKey[]; // Finch parameter key for one off task window. extern const char kOneoffTaskWindowKey[]; class TileConfig { public: // Gets the URL for the Query Tiles server. static GURL GetQueryTilesServerUrl(); // Gets whether running the background task requires unmeter network // condition. static bool GetIsUnMeteredNetworkRequired(); // Gets the experiment tag to be passed to server. static std::string GetExperimentTag(); // Gets the maximum duration for holding current group's info and images. static base::TimeDelta GetExpireDuration(); // Gets the image prefetch mode to determine how many images will be // prefetched in background task. static ImagePrefetchMode GetImagePrefetchMode(); // Get the interval of schedule window in ms. static int GetScheduleIntervalInMs(); // Get the maxmium window for randomization in ms. static int GetMaxRandomWindowInMs(); // Get the schedule window duration from start to end in one-off task params // in ms. static int GetOneoffTaskWindowInMs(); }; } // namespace query_tiles #endif // COMPONENTS_QUERY_TILES_INTERNAL_TILE_CONFIG_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
cf069219b9c9838d08da027a0579f2f071126b6a
ead66af34e18519c0fdde87b9b593bcf5a01c0db
/CH2/2-12.cpp
1ffde08bed7864ff6f53107a621572ca40c92124
[]
no_license
gcspanda/cpp-training
24d467279391a2b4522d551b670a3d5ee78d1176
defd83c218b57441dd8744f04e6222c478b88420
refs/heads/master
2022-11-09T13:35:33.388051
2020-06-22T12:54:16
2020-06-22T12:54:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
193
cpp
#include <iostream> using namespace std; int main() { double v, a; double length; cin >> v >> a; length = v * v * 1.0 / (2 * a); cout << length << endl; return 0; }
[ "2470977889@qq.com" ]
2470977889@qq.com
69e8e6f07572421e91c9b4d4bf6383e625dce3b6
ba5470cf158b705ed48b2d9a7c3677bfdd42b7d1
/src/Hardsting/Hardsting.cpp
deff8be51916225db6feb4eeadf3854daedb917b
[]
no_license
joacomf/hardsting
4a7e89d09571b93549ac2b55b70c85b264601fa5
08778df097b75067de44cc448d454b9e973bea7d
refs/heads/master
2022-07-05T20:38:11.562693
2020-05-12T23:31:14
2020-05-12T23:31:14
261,639,807
0
0
null
null
null
null
UTF-8
C++
false
false
3,222
cpp
#include "Hardsting.hpp" Hardsting::Hardsting(Framework* framework) { this->framework = framework; this->framework->consola("Comienzan las pruebas\n"); } void Hardsting::presiono_(int boton){ string nombre = string("Presiono componente en el pin " + literal(boton)); Paso* paso = new Paso(nombre); paso->inicio(this->framework->microsegundos()); this->framework->escribir(boton, ALTO); paso->fin(this->framework->microsegundos()); paso->exito(true); escenario->nuevo(paso); this->framework->demorar(DELAY_COMPESACION); } void Hardsting::suelto_(int boton){ string nombre = string("Suelto componente en el pin " + literal(boton)); Paso* paso = new Paso(nombre); paso->inicio(this->framework->microsegundos()); this->framework->escribir(boton, BAJO); paso->fin(this->framework->microsegundos()); paso->exito(true); escenario->nuevo(paso); this->framework->demorar(DELAY_COMPESACION); } bool Hardsting::deberia_encender_(int led, int microsegundos) { string nombre = string("Enciende LED en el pin " + literal(led)); Paso* paso = new Paso(nombre); paso->inicio(this->framework->microsegundos()); long tiempo_inicial = this->framework->milisegundos(); while(this->framework->milisegundos() - tiempo_inicial < microsegundos){ if (this->framework->leer(led) == ALTO) { paso->fin(this->framework->microsegundos()); paso->exito(true); this->escenario->nuevo(paso); return true; } } paso->fin(this->framework->microsegundos()); this->escenario->nuevo(paso); return false; } bool Hardsting::deberia_apagar_(int led, int microsegundos) { string nombre = string("Apaga LED en el pin " + literal(led)); Paso* paso = new Paso(nombre); paso->inicio(this->framework->microsegundos()); long tiempo_inicial = this->framework->milisegundos(); while(this->framework->milisegundos() - tiempo_inicial < microsegundos){ if (this->framework->leer(led) == BAJO) { paso->fin(this->framework->microsegundos()); paso->exito(true); this->escenario->nuevo(paso); return true; } } paso->fin(this->framework->microsegundos()); this->escenario->nuevo(paso); return false; } void Hardsting::pin_de_entrada(int pin) { this->framework->configurar_pin_entrada(pin); } void Hardsting::pin_de_salida(int pin) { this->framework->configurar_pin_salida(pin); this->framework->escribir(pin, BAJO); } void Hardsting::empieza(string nombre) { this->framework->consola("Empieza TEST: " + nombre); } void Hardsting::termina(string nombre) { this->framework->consola("Termina " + nombre + "\n"); } string Hardsting::imprimir_reporte() { string reporteFinal = string(); list<Escenario>::iterator escenario; for (escenario = this->escenarios.begin(); escenario != this->escenarios.end(); ++escenario) { reporteFinal.append(escenario->imprimirFinal()); reporteFinal.append("\n"); } this->framework->consola(reporteFinal); return reporteFinal; } void Hardsting::nuevo_escenario(const char *nombreDeEscenario) { this->escenario = new Escenario(nombreDeEscenario); } void Hardsting::termina_escenario() { this->escenarios.push_back(*this->escenario); }
[ "joaquin.moreno@grupoesfera.com.ar" ]
joaquin.moreno@grupoesfera.com.ar
5c75e350c099e57d86a7bc25c49ec8a88d24f491
72ed63c92ff6b2c66eb26f9bb8fe42f9c30b6dcc
/C/259 C语言_联合体(共用体).cpp
0d8cb761c21e04118fbd68ad8842451a7e625640
[]
no_license
wangjunjie1107/CodeTesting
ceee7adbf73d357cb3b93e751682e05b83b54328
2e614831877f30db109e5b669a1d77bb17208a5a
refs/heads/master
2020-07-15T04:59:36.138974
2019-10-30T00:39:29
2019-10-30T00:39:29
205,484,180
0
0
null
null
null
null
GB18030
C++
false
false
506
cpp
#include<stdio.h> #include<string.h> #include<stdlib.h> union vars { double a; float b; int c; short d; char f; char arr[12]; }var; int main() { //共用体大小16个字节,其中4个字节无效 //16 = 2 * 8; //根据最大数据类型,找最大字节长度 //double 最大,占8个字节,arr[12],使用两个double //因此是16个字节 //共用体中最后一块被赋值的,是准确的 //之前赋值的数据会被覆盖 printf("%d\n", sizeof(var)); return 0; }
[ "980353691@qq.com" ]
980353691@qq.com
b9fa21bfa5c1a826b60d383087b465b17e9af2fc
77f0dc068f1a8353ffc23ffd3457c4af8507b114
/lang/c/tic/code/Chap9b/intstack.h
808f97c0d393fcb472afdaa7526676ebf800b310
[]
no_license
hclife/code-base
aa549a2b6a33b3ed1f0932801f0eb85eca3461de
f22ba81b8d363c50c3ac3fa5409e8fb3440cda83
refs/heads/master
2021-07-18T19:23:05.828540
2021-05-16T10:24:32
2021-05-16T10:24:32
83,208,177
0
0
null
null
null
null
UTF-8
C++
false
false
259
h
// intstack.h: A Stack class for ints class StackOfInt { public: StackOInt(int); void push(int); int pop(); int top() const; int size() const; ~StackOfInt(); private: int *data; int length; int ptr; };
[ "huangchao1317@163.com" ]
huangchao1317@163.com
0b3facc245062840d52a138b232a432718c657bc
7aaedfdf0e9f0abb1b25a3ce665eaca75843b3f4
/BlockL.cpp
29fdfd4fbf1a2dd5027299d8116088327aad595c
[ "MIT" ]
permissive
janwasko/tetris
0dfc2ed33781c74b0b0bbeb19ad7fc9de4ce1b65
227cbe4c87d1b51563a2612f520c1a45477836a4
refs/heads/master
2021-12-14T19:36:33.162807
2017-01-20T23:26:20
2017-01-20T23:26:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
314
cpp
#include "BlockL.h" std::vector<Point> BlockL::getRelativePoints() { std::vector<Point> points; points.push_back(Point(-1, 1)); points.push_back(Point(-1, 0)); points.push_back(Point(0, 0)); points.push_back(Point(1, 0)); return points; } sf::Color BlockL::getColor() { return sf::Color(225, 165, 0); }
[ "noreply@github.com" ]
noreply@github.com
0b011620a0e30597bb5cd902e698c17332337df2
ed5bb620fe82f37173cb689793b89b87fa3d798a
/src/Orbis/Video/RenderMode.h
ec8eaad397879ae14aa08f54e86fb2e6657b4da4
[ "MIT" ]
permissive
perezite/orbis
afb1e50ba91920fb1da80bf1524a4d6386ae3e37
b22c2608c5b75ca3627feb17e86202b6b80e1ead
refs/heads/master
2021-03-24T13:22:46.214972
2019-04-26T17:02:02
2019-04-26T17:02:02
53,759,613
0
0
null
null
null
null
UTF-8
C++
false
false
158
h
#pragma once #include "../Libraries/GL.h" namespace orb { enum class RenderMode : GLenum { Triangles = GL_TRIANGLES, Lines = GL_LINES }; }
[ "simulo2000@gmail.com" ]
simulo2000@gmail.com
e69b371796ac7e0f921d608d64a3223a3fc97b65
7cea11670669ab04c6bbbcfd66c35da8c249cc2a
/source/main.cpp
6c02c113f2b5b797047f01667e3b8c0f913392de
[]
no_license
kjain1810/OpenGL-Object-Rendering
1989b7df7d287d00d1a1ded5dcf611bf338916ea
26b9d7f39bccabd7ba3fcb937e743be2690f6bd2
refs/heads/master
2023-03-26T07:12:04.715188
2021-03-16T08:29:01
2021-03-16T08:29:01
347,723,133
0
0
null
null
null
null
UTF-8
C++
false
false
9,529
cpp
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include "object.hpp" #include "utils.hpp" #include "camera.hpp" const char *vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec3 aColor;\n" "out vec3 ourColor;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos, 1.0);\n" " gl_Position = projection * view * model * vec4(aPos, 1.0);\n" " ourColor = aColor;\n" "}\n\0"; const char *fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "in vec3 ourColor;\n" "void main()\n" "{\n" " FragColor = vec4(ourColor, 1.0f);\n" "}\n\0"; void framebuffer_size_callback(GLFWwindow *window, int width, int height); int processInput(GLFWwindow *, int &, Camera &, glm::mat4 &, Object[]); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; int main() { // glfw: initialize and configure // how to handle the windows n all are done with this // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Assignment 0", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers connect to opengl implementaion from driver // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } glEnable(GL_DEPTH_TEST); // build and compile our shader program // ------------------------------------ // vertex shader unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); // check for shader compile errors int success; char infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } // fragment shader unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); // check for shader compile errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } // link shaders unsigned int shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); // check for linking errors glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ Object objects[] = {createDecagonalPrism(), createHexDiPyramid(), createSqPyramid()}; int cur = 0; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // first parameter is for number of buffer objects to create // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). objects[cur].bindBuffer(VAO, VBO); // as we only have a single shader, we could also just activate our shader once beforehand if we want to glUseProgram(shaderProgram); // create camera and render objects Camera cam; glm::mat4 projection = glm::mat4(1.0f); projection = glm::perspective(glm::radians(45.0f), (float)800 / (float)600, 0.1f, 100.0f); objects[cur].applyMVP(shaderProgram, cam, projection); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- int pressed = processInput(window, cur, cam, projection, objects); // if a button was pressed, re-render objects if (pressed) { objects[cur].applyMVP(shaderProgram, cam, projection); objects[cur].bindBuffer(VAO, VBO); } // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); objects[cur].draw(VAO); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteProgram(shaderProgram); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- int processInput(GLFWwindow *window, int &cur, Camera &cam, glm::mat4 &projection, Object objects[]) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); else if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS && cur != 0) cur = 0; else if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS && cur != 1) cur = 1; else if (glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS && cur != 2) cur = 2; else if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) objects[cur].moveXn(); else if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) objects[cur].moveXp(); else if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) objects[cur].moveYn(); else if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) objects[cur].moveYp(); else if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) objects[cur].moveZn(); else if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) objects[cur].moveZp(); else if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS) objects[cur].rotate(); else if (glfwGetKey(window, GLFW_KEY_PAGE_UP) == GLFW_PRESS) cam.moveYn(); else if (glfwGetKey(window, GLFW_KEY_PAGE_DOWN) == GLFW_PRESS) cam.moveYp(); else if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) cam.moveXn(); else if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) cam.moveXp(); else if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) cam.moveZn(); else if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) cam.moveZp(); else if (glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS) objects[cur].rotateCamera(cam); else if (glfwGetKey(window, GLFW_KEY_I) == GLFW_PRESS) objects[cur].predef(1, cam); else if (glfwGetKey(window, GLFW_KEY_O) == GLFW_PRESS) objects[cur].predef(2, cam); else if (glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS) objects[cur].predef(3, cam); else // return 0 if no button was pressed return 0; return 1; // return 1 if a button was pressed } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); }
[ "kunaljain.2000@yahoo.in" ]
kunaljain.2000@yahoo.in
4efedcaa4f1ebab9d587341cb0b1bff650ee8d4b
1cb73a0dece5dc21e8e7e4f88f96d1ad9e92da1a
/Eigen/rotate_around_center.cpp
4cf2e97d8447f76df2d0577a14807ebbe7574306
[]
no_license
keineahnung2345/cpp-code-snippets
c2af1c7eaaddc2f0c262022743f6d42fec7fede4
d2b48129f2c1bae1940a213517bfa3597c802aee
refs/heads/master
2023-08-16T17:13:55.414432
2023-08-16T02:07:24
2023-08-16T02:07:24
160,354,272
52
16
null
null
null
null
UTF-8
C++
false
false
1,017
cpp
#define _USE_MATH_DEFINES #include <cmath> #include <iostream> #include <Eigen/Core> #include <Eigen/Geometry> // https://stackoverflow.com/questions/38274455/eigen-perform-an-3d-rotation-around-an-axis-w-and-anchored-at-a-point-p // https://stackoverflow.com/questions/1727881/how-to-use-the-pi-constant-in-c // https://stackoverflow.com/questions/6563810/m-pi-works-with-math-h-but-not-with-cmath-in-visual-studio int main(int argc, char** argv) { Eigen::Vector3f point(0, 0, 1); Eigen::Vector3f axis(1, 0, 0); float theta = 90.0f / 180.0f * M_PI; Eigen::Vector3f rotation_center(0, 1, 0); Eigen::Affine3f affine = Eigen::Translation3f(rotation_center) * Eigen::AngleAxisf(theta, axis) * Eigen::Translation3f(-rotation_center); std::cout << "original point: " << point << std::endl; std::cout << "rotated point: " << affine * point << std::endl; return 0; } /* original point: 0 0 1 rotated point: 0 0 -1 */
[ "noreply@github.com" ]
noreply@github.com
9e14646ac780e85f06fa1de37dc06d1177417d30
509aa79f8b1054a37c0eaf5786826b140695980a
/Module2/2BezierSurface/glwidget.h
ef1c20cbf307e3702795374d068f4f6dfe4654b3
[]
no_license
MariKush/MFCG
e5171c0ec38f5fc86819174fb962dfdc30ed0b09
a2bc141216c6e630c329f346de6041120a3f3506
refs/heads/master
2022-07-31T22:01:50.722977
2020-05-19T19:31:03
2020-05-19T19:31:03
262,397,477
0
0
null
null
null
null
UTF-8
C++
false
false
276
h
#ifndef GLWIDGET_H #define GLWIDGET_H #include <QGLWidget> class GLWidget : public QGLWidget { Q_OBJECT public: explicit GLWidget(QWidget *parent = 0); protected: void initializeGL(); void paintGL(); void resizeGL(int w, int h); }; #endif // GLWIDGET_H
[ "43176370+MariKush@users.noreply.github.com" ]
43176370+MariKush@users.noreply.github.com
d18b6e6bb54a8d236abaf42c36fbf806d1c96c76
a3f84a4e1e2ee6e4384177645836533d2bb1214b
/tests/swizzle_generator.cpp
8ac2921391041b226c5e081d051116f7677a5fd5
[ "MIT" ]
permissive
ArcEarth/HLSLM
30e37d576853c3881ccc828ee6a79445545f14e6
c6bab2aa6f2052ae44863b05adeb506aa51ece65
refs/heads/master
2021-01-13T00:53:41.491296
2016-10-14T20:17:53
2016-10-14T20:17:53
52,214,390
0
0
null
null
null
null
UTF-8
C++
false
false
1,922
cpp
#include <iostream> #include <algorithm> #include <numeric> template <typename Iterator> inline bool next_combination(Iterator first, Iterator k, Iterator last); template <typename Iterator> inline bool next_combination(const Iterator first, Iterator k, const Iterator last) { /* Credits: Thomas Draper */ // http://stackoverflow.com/a/5097100/8747 if ((first == last) || (first == k) || (last == k)) return false; Iterator itr1 = first; Iterator itr2 = last; ++itr1; if (last == itr1) return false; itr1 = last; --itr1; itr1 = k; --itr2; while (first != itr1) { if (*--itr1 < *itr2) { Iterator j = k; while (!(*itr1 < *j)) ++j; std::iter_swap(itr1, j); ++itr1; ++j; itr2 = k; std::rotate(itr1, j, last); while (last != j) { ++j; ++itr2; } std::rotate(k, itr2, last); return true; } } std::rotate(first, k, last); return false; } //char elems[] = { 'x','y','z','w' }; char elems[] = { 'x','y','z','w' }; char* argelems[] = { "0","1","2","3" }; int n = std::size(elems); char* macro = "_MAKE_SWS_"; int arr[4]; char name[5]; using namespace std; // print arr[0-l) void print(int l) { cout << macro << '('; name[l] = '\0'; for (int i = 0; i < l; i++) { name[i] = elems[arr[i]]; } cout << name; for (int i = 0; i < l; i++) { cout << "," << argelems[arr[i]]; } cout << ')' << endl; } void gen_len(int cl, int l) { for (int i = 0; i < n; i++) { arr[cl - 1] = i; if (cl > 1) gen_len(cl - 1, l); else print(l); } } int main(int argc, char** argv) { if (argc >= 2) n = atoi(argv[1]); if (argc >= 3) macro = argv[2]; for (int l = 1; l <= n; l++) { //gen_len(l, l); std::iota(arr, arr + n, 0); // remove the identity if (l == n) next_permutation(arr, arr + l); do { do { print(l); } while (next_permutation(arr, arr + l)); } while (next_combination(arr, arr + l, arr + n)); } }
[ "ArcEarth@outlook.com" ]
ArcEarth@outlook.com
811183622a8ca91fcc79c7a469edc672e708c3d7
a0c4f8fb19989f00b0fcc9822f8d0b87f8cbbd03
/SFML Tutorial Pong/SFML Tutorial Pong/Ball.h
1d56ee5a13461954155fb4dcb5130594d23fcb04
[]
no_license
Plankton555/HelloSFML
b2b4601206ee06d783214996678ee83ab9b2bf0c
f7f7fba3594b6b5ad3c7dc74ce6a78df3b971c00
refs/heads/master
2021-01-04T00:01:06.200431
2020-03-06T15:55:59
2020-03-06T15:55:59
240,292,547
0
0
null
null
null
null
UTF-8
C++
false
false
399
h
#pragma once #include <SFML/Graphics.hpp> using namespace sf; class Ball { private: Vector2f position; RectangleShape ballShape; float xVelocity = 0.2f; float yVelocity = 0.2f; public: Ball(float startX, float startY); FloatRect getPosition(); RectangleShape getShape(); float getXVelocity(); void reboundSides(); void reboundBatOrTop(); void hitBottom(); void update(); };
[ "bjorn.pm@plankter.se" ]
bjorn.pm@plankter.se
79e998e93ad9b8434ae6ff0882083a7e4eb2383f
3165f32fffa0bbb40426ec3b7f1684706f7704c8
/atcoder/abc/172/a.cpp
a45b0b14dadcdce2b0820af1e2e174259254b4a8
[]
no_license
daikimiura/hobby
953197b975827b2f35f29d2e0e23d55dc505cf00
c93d6f8def3afb60f0c50b70f3dfa988c301d28f
refs/heads/master
2021-06-19T04:49:35.644057
2021-01-19T12:40:35
2021-01-19T12:40:35
160,904,485
0
0
null
null
null
null
UTF-8
C++
false
false
623
cpp
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define repi(i, a, b) for (int i = int(a); i < int(b); ++i) typedef long long ll; long long mod = 1e9 + 7; const int iINF = 0x3f3f3f3f; const long long INF = 1LL << 60; using namespace std; using pint = pair<int, int>; template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; } template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; } int main() { int a; cin >> a; cout << a + a * a + a * a * a << endl; return 0; }
[ "daikiii5555@gmail.com" ]
daikiii5555@gmail.com
bcbfd450da336003abc6aac733e00cd9a29e2be7
94a7746859ffd59aebfce960ed86ba66f5a85afd
/proTrinketBreadBoardTest/proTrinketBreadBoardTest.ino
3a9dc729139495f25a2bd2726611af96905e3f69
[]
no_license
tomwallace/arduino
a0c979489cfa55a7afc48930f44a9fd2b303162b
0ad189699c8bb9c5b89cb4684a45fba7de37b406
refs/heads/master
2023-07-08T08:40:12.983637
2023-07-02T20:37:03
2023-07-02T20:37:03
60,378,041
0
0
null
null
null
null
UTF-8
C++
false
false
4,139
ino
#define WORT_PUMP_LIGHT 3 #define WATER_PUMP_LIGHT 4 #define ALARM 5 #define ALARM_SOUND HIGH #define ALARM_SILENT LOW #define ACTIVATE_INTERVAL 3000 #define ON_LENGTH 2000 #define RIGHT_BUTTON_LIGHT 6 #define LEFT_BUTTON_LIGHT 8 #define RIGHT_BUTTON 14 #define LEFT_BUTTON 12 #define BOIL_SENSOR 9 #define MASH_SENSOR_ONE 10 #define MASH_SENSOR_TWO 11 long StartTimeMillis = 0; int StartWortPumpLight = 0; int StopWortPumpLight = 0; int StartWaterPumpLight = 0; int StopWaterPumpLight = 0; int StartAlarm = 0; int StopAlarm = 0; int StartRightButtonLight = 0; int StopRightButtonLight = 0; int StartLeftButtonLight = 0; int StopLeftButtonLight = 0; void setup() { // put your setup code here, to run once: // Buttons are pull-up resistors pinMode(RIGHT_BUTTON, INPUT_PULLUP); pinMode(LEFT_BUTTON, INPUT_PULLUP); pinMode(ALARM, OUTPUT); pinMode(WORT_PUMP_LIGHT, OUTPUT); pinMode(WATER_PUMP_LIGHT, OUTPUT); pinMode(LEFT_BUTTON_LIGHT, OUTPUT); pinMode(RIGHT_BUTTON_LIGHT, OUTPUT); StartTimeMillis = millis(); StartWortPumpLight = StartTimeMillis + ACTIVATE_INTERVAL; StopWortPumpLight = StartWortPumpLight + ON_LENGTH; StartWaterPumpLight = StopWortPumpLight + ACTIVATE_INTERVAL; StopWaterPumpLight = StartWaterPumpLight + ON_LENGTH; StartAlarm = StopWaterPumpLight + ACTIVATE_INTERVAL; StopAlarm = StartAlarm + ON_LENGTH; StartRightButtonLight = StopAlarm + ACTIVATE_INTERVAL; StopRightButtonLight = StartRightButtonLight + ON_LENGTH; StartLeftButtonLight = StopRightButtonLight + ACTIVATE_INTERVAL; StopLeftButtonLight = StartLeftButtonLight + ON_LENGTH; } void loop() { // put your main code here, to run repeatedly: // Get current clock unsigned long currentMillis = millis(); // If in initial start up evaluation, i.e. less than the last time the last light is turned on if (currentMillis <= StopLeftButtonLight) { // Wort Pump Light if ((currentMillis >= StartWortPumpLight) && (currentMillis <= StopWortPumpLight)) { digitalWrite(WORT_PUMP_LIGHT, HIGH); } else { digitalWrite(WORT_PUMP_LIGHT, LOW); } // Water Pump Light if ((currentMillis >= StartWaterPumpLight) && (currentMillis <= StopWaterPumpLight)) { digitalWrite(WATER_PUMP_LIGHT, HIGH); } else { digitalWrite(WATER_PUMP_LIGHT, LOW); } // Alarm if ((currentMillis >= StartAlarm) && (currentMillis <= StopAlarm)) { digitalWrite(ALARM, ALARM_SOUND); } else { digitalWrite(ALARM, ALARM_SILENT); } // Right Button Light if ((currentMillis >= StartRightButtonLight) && (currentMillis <= StopRightButtonLight)) { digitalWrite(RIGHT_BUTTON_LIGHT, HIGH); } else { digitalWrite(RIGHT_BUTTON_LIGHT, LOW); } // Left Button Light if ((currentMillis >= StartLeftButtonLight) && (currentMillis <= StopLeftButtonLight)) { digitalWrite(LEFT_BUTTON_LIGHT, HIGH); } else { digitalWrite(LEFT_BUTTON_LIGHT, LOW); } } // Now do the button evaluation else { // TODO: This currently controls the light on the Trinket - the actual light stays on all the time // Right Button if (digitalRead(RIGHT_BUTTON) == LOW) { digitalWrite(RIGHT_BUTTON_LIGHT, HIGH); } else { digitalWrite(RIGHT_BUTTON_LIGHT, LOW); } // Left Button if (digitalRead(LEFT_BUTTON) == LOW) { digitalWrite(LEFT_BUTTON_LIGHT, HIGH); } else { digitalWrite(LEFT_BUTTON_LIGHT, LOW); } // Boil Sensor Button - activate if HIGH - Sound Alarm if (digitalRead(BOIL_SENSOR) == HIGH) { digitalWrite(ALARM, ALARM_SOUND); } else { digitalWrite(ALARM, ALARM_SILENT); } // Mash Sensor One Button - activate if HIGH - Light Water Pump Light if (digitalRead(MASH_SENSOR_ONE) == HIGH) { digitalWrite(WATER_PUMP_LIGHT, HIGH); } else { digitalWrite(WATER_PUMP_LIGHT, LOW); } // Mash Sensor Two Button - activate if HIGH - Light Wart Pump Light if (digitalRead(MASH_SENSOR_TWO) == HIGH) { digitalWrite(WORT_PUMP_LIGHT, HIGH); } else { digitalWrite(WORT_PUMP_LIGHT, LOW); } } }
[ "thomaspwallace@gmail.com" ]
thomaspwallace@gmail.com
d753adf3f0930d472ffd6e8c0aa641a9f0ff31c7
8c03bbacf612ae6df5a2360c515d89333932307c
/chrome/browser/sharing/click_to_call/click_to_call_context_menu_observer.cc
af199e488640276d2cf1f91f520a8626438d9601
[ "BSD-3-Clause" ]
permissive
AlexBrowning/chromium
9c6e953f3aa95ce5233e6369c186cef99c93688a
d55b27720d40319cac36fc64592ea6c8638b5f60
refs/heads/master
2023-03-15T14:35:37.129770
2019-09-04T07:13:35
2019-09-04T07:13:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,451
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/sharing/click_to_call/click_to_call_context_menu_observer.h" #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu.h" #include "chrome/browser/sharing/click_to_call/click_to_call_ui_controller.h" #include "chrome/browser/sharing/click_to_call/feature.h" #include "chrome/browser/sharing/sharing_constants.h" #include "chrome/browser/sharing/sharing_metrics.h" #include "chrome/grit/generated_resources.h" #include "components/sync_device_info/device_info.h" #include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/paint_vector_icon.h" ClickToCallContextMenuObserver::SubMenuDelegate::SubMenuDelegate( ClickToCallContextMenuObserver* parent) : parent_(parent) {} ClickToCallContextMenuObserver::SubMenuDelegate::~SubMenuDelegate() = default; bool ClickToCallContextMenuObserver::SubMenuDelegate::IsCommandIdEnabled( int command_id) const { // All supported commands are enabled in sub menu. return true; } void ClickToCallContextMenuObserver::SubMenuDelegate::ExecuteCommand( int command_id, int event_flags) { if (command_id < kSubMenuFirstDeviceCommandId || command_id > kSubMenuLastDeviceCommandId) return; int device_index = command_id - kSubMenuFirstDeviceCommandId; parent_->SendClickToCallMessage(device_index); } ClickToCallContextMenuObserver::ClickToCallContextMenuObserver( RenderViewContextMenuProxy* proxy) : proxy_(proxy), controller_(ClickToCallUiController::GetOrCreateFromWebContents( proxy_->GetWebContents())) {} ClickToCallContextMenuObserver::~ClickToCallContextMenuObserver() = default; void ClickToCallContextMenuObserver::BuildMenu( const std::string& phone_number, SharingClickToCallEntryPoint entry_point) { DCHECK(!phone_number.empty()); phone_number_ = phone_number; entry_point_ = entry_point; controller_->UpdateDevices(); const std::vector<std::unique_ptr<syncer::DeviceInfo>>& devices = controller_->devices(); LogClickToCallDevicesToShow(kSharingClickToCallUiContextMenu, devices.size()); if (devices.empty()) return; proxy_->AddSeparator(); if (devices.size() == 1) { #if defined(OS_MACOSX) proxy_->AddMenuItem( IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE, l10n_util::GetStringFUTF16( IDS_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE, base::UTF8ToUTF16(devices[0]->client_name()))); #else proxy_->AddMenuItemWithIcon( IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE, l10n_util::GetStringFUTF16( IDS_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE, base::UTF8ToUTF16(devices[0]->client_name())), vector_icons::kCallIcon); #endif } else { BuildSubMenu(); #if defined(OS_MACOSX) proxy_->AddSubMenu( IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES, l10n_util::GetStringUTF16( IDS_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES), sub_menu_model_.get()); #else proxy_->AddSubMenuWithStringIdAndIcon( IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES, IDS_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES, sub_menu_model_.get(), vector_icons::kCallIcon); #endif } proxy_->AddSeparator(); } void ClickToCallContextMenuObserver::BuildSubMenu() { sub_menu_model_ = std::make_unique<ui::SimpleMenuModel>(&sub_menu_delegate_); int command_id = kSubMenuFirstDeviceCommandId; for (const auto& device : controller_->devices()) { if (command_id > kSubMenuLastDeviceCommandId) break; sub_menu_model_->AddItem(command_id++, base::UTF8ToUTF16(device->client_name())); } } bool ClickToCallContextMenuObserver::IsCommandIdSupported(int command_id) { size_t device_count = controller_->devices().size(); if (device_count == 0) return false; if (device_count == 1) { return command_id == IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE; } else { return command_id == IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES; } } bool ClickToCallContextMenuObserver::IsCommandIdEnabled(int command_id) { // All supported commands are enabled. return true; } void ClickToCallContextMenuObserver::ExecuteCommand(int command_id) { if (command_id == IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE) { DCHECK(controller_->devices().size() == 1); SendClickToCallMessage(0); } } void ClickToCallContextMenuObserver::SendClickToCallMessage( int chosen_device_index) { DCHECK(entry_point_); const std::vector<std::unique_ptr<syncer::DeviceInfo>>& devices = controller_->devices(); if (chosen_device_index >= static_cast<int>(devices.size())) return; LogClickToCallSelectedDeviceIndex(kSharingClickToCallUiContextMenu, chosen_device_index); controller_->OnDeviceSelected(phone_number_, *devices[chosen_device_index], *entry_point_); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
feafe943108c4a662ddabe8e70d37c89eb9fa1ca
7bb2e375234db3b74ae60907b4d5000e5d1adfaf
/point.h
6ef0c9cdbc1b4469ae0493f33bfa2092581dad7f
[]
no_license
VSGolubev-bald/oop_exercise_05
818bb067d3e994b4afe052b377c5aa7b768237b7
8934d8818563f3ecd9c5be6598e07d2759835b9a
refs/heads/master
2020-09-12T15:26:24.292405
2020-01-09T09:43:07
2020-01-09T09:43:07
222,465,533
0
0
null
null
null
null
UTF-8
C++
false
false
949
h
#ifndef LAB5_POINT_H #define LAB5_POINT_H #include <iostream> #include <algorithm> #include "cmath" template<class T> struct point { T x; T y; double VectNorm(point l, point r) const; double VectProd(point l, point r) const; }; template<class T> std::istream& operator>> (std::istream& is, point<T>& p) { is >> p.x >> p.y; return is; } template<class T> std::ostream& operator<< (std::ostream& os, const point<T>& p) { os << p.x << ' ' << p.y; return os; } template<class T> point<T> operator-(const point<T> l, const point<T> r) { point<T> res; res.x = r.x - l.x; res.y = r.y - l.y; return res; } template<class T> double VectProd(point<T> l, point<T> r) { return std::abs(l.x * r.y - r.x * l.y); } template<class T> double VectNorm(point<T> l, point<T> r) { point<T> vect = operator-(l,r); double res = sqrt(vect.x* vect.x + vect.y * vect.y); return res; } #endif //LAB5_POINT_H
[ "vladimirgolubev.jj@gmail.com" ]
vladimirgolubev.jj@gmail.com
872b2be219acfe6359a5c9f50d106a092f28ddf4
e721bf0432a0c76af7f78ead065716f97120e3b0
/random/sutta.cpp
3be43f0971251e8fd5831dac650fac7fe39b64aa
[]
no_license
sakthi-netizen/geek
8e3b82494210a8e2c0539276fe4936311c5de4fb
54e83be2bc1394746a799abbdce10b99419d425d
refs/heads/master
2023-04-12T19:01:04.398036
2021-04-30T14:24:11
2021-04-30T14:24:11
361,199,363
0
0
null
null
null
null
UTF-8
C++
false
false
975
cpp
#include <bits/stdc++.h> using namespace std; void dfs(int u, vector<int> adj[], int* vis, int* inDeg, int* outDeg) { vis[u] = 1; for (auto v : adj[u]) { outDeg[u] = 1; inDeg[v] = 1; if (vis[v] == 0) { dfs(v, adj, vis, inDeg, outDeg); } } } int findMinimumEdges(int source[], int N, int M, int dest[]) { vector<int> adj[N + 1]; for (int i = 0; i < M; i++) { adj[i].push_back(dest[i]); } int inDeg[N + 1] = { 0 }; int outDeg[N + 1] = { 0 }; int vis[N + 1] = { 0 }; dfs(1, adj, vis, inDeg, outDeg); int minEdges = 0; int totalIndegree = 0; int totalOutdegree = 0; for (int i = 1; i <= N; i++) { if (inDeg[i] == 1) totalIndegree++; if (outDeg[i] == 1) totalOutdegree++; } minEdges = max(N - totalIndegree, N - totalOutdegree); return minEdges; } int main() { int N = 5, M = 4; int source[] = { 1, 1, 3, 4}; int destination[] = { 2, 3, 4, 5 }; cout << findMinimumEdges(source, N, M, destination); return 0; }
[ "m.srisakthi2001@gmail.com" ]
m.srisakthi2001@gmail.com
0fbe15f952e304b1c58271677aaa8831feeeb14a
1d9df1156e49f768ed2633641075f4c307d24ad2
/content/browser/loader/resource_dispatcher_host_impl.cc
24e36549bce02edc4be2a526101f4a8a5c16baab
[ "BSD-3-Clause" ]
permissive
GSIL-Monitor/platform.framework.web.chromium-efl
8056d94301c67a8524f6106482087fd683c889ce
e156100b0c5cfc84c19de612dbdb0987cddf8867
refs/heads/master
2022-10-26T00:23:44.061873
2018-10-30T03:41:51
2018-10-30T03:41:51
161,171,104
0
1
BSD-3-Clause
2022-10-20T23:50:20
2018-12-10T12:24:06
C++
UTF-8
C++
false
false
115,377
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. // See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading #include "content/browser/loader/resource_dispatcher_host_impl.h" #include <stddef.h> #include <algorithm> #include <memory> #include <set> #include <utility> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/debug/alias.h" #include "base/feature_list.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/shared_memory.h" #include "base/message_loop/message_loop.h" #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/task_scheduler/post_task.h" #include "base/task_scheduler/task_traits.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/threading/thread_task_runner_handle.h" #include "base/timer/timer.h" #include "content/browser/appcache/appcache_interceptor.h" #include "content/browser/appcache/appcache_navigation_handle_core.h" #include "content/browser/appcache/chrome_appcache_service.h" #include "content/browser/bad_message.h" #include "content/browser/browsing_data/clear_site_data_throttle.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/frame_host/navigation_request_info.h" #include "content/browser/loader/async_resource_handler.h" #include "content/browser/loader/detachable_resource_handler.h" #include "content/browser/loader/intercepting_resource_handler.h" #include "content/browser/loader/loader_delegate.h" #include "content/browser/loader/mime_sniffing_resource_handler.h" #include "content/browser/loader/mojo_async_resource_handler.h" #include "content/browser/loader/navigation_resource_handler.h" #include "content/browser/loader/navigation_resource_throttle.h" #include "content/browser/loader/navigation_url_loader_impl_core.h" #include "content/browser/loader/null_resource_controller.h" #include "content/browser/loader/redirect_to_file_resource_handler.h" #include "content/browser/loader/resource_loader.h" #include "content/browser/loader/resource_message_filter.h" #include "content/browser/loader/resource_request_info_impl.h" #include "content/browser/loader/resource_requester_info.h" #include "content/browser/loader/resource_scheduler.h" #include "content/browser/loader/stream_resource_handler.h" #include "content/browser/loader/sync_resource_handler.h" #include "content/browser/loader/throttling_resource_handler.h" #include "content/browser/loader/upload_data_stream_builder.h" #include "content/browser/loader/wake_lock_resource_throttle.h" #include "content/browser/resource_context_impl.h" #include "content/browser/service_worker/foreign_fetch_request_handler.h" #include "content/browser/service_worker/link_header_support.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/service_worker/service_worker_navigation_handle_core.h" #include "content/browser/service_worker/service_worker_request_handler.h" #include "content/browser/streams/stream.h" #include "content/browser/streams/stream_context.h" #include "content/browser/streams/stream_registry.h" #include "content/common/net/url_request_service_worker_data.h" #include "content/common/resource_messages.h" #include "content/common/site_isolation_policy.h" #include "content/common/view_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/global_request_id.h" #include "content/public/browser/navigation_ui_data.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/resource_dispatcher_host_delegate.h" #include "content/public/browser/resource_request_details.h" #include "content/public/browser/resource_throttle.h" #include "content/public/browser/stream_handle.h" #include "content/public/browser/stream_info.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/content_features.h" #include "content/public/common/resource_request.h" #include "content/public/common/resource_request_body.h" #include "content/public/common/resource_request_completion_status.h" #include "ipc/ipc_message_macros.h" #include "ipc/ipc_message_start.h" #include "net/base/auth.h" #include "net/base/load_flags.h" #include "net/base/mime_util.h" #include "net/base/net_errors.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "net/base/upload_data_stream.h" #include "net/base/url_util.h" #include "net/cert/cert_status_flags.h" #include "net/cookies/cookie_monster.h" #include "net/http/http_request_headers.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" #include "net/log/net_log_with_source.h" #include "net/ssl/client_cert_store.h" #include "net/ssl/ssl_cert_request_info.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" #include "net/url_request/url_request_job_factory.h" #include "ppapi/features/features.h" #include "storage/browser/blob/blob_data_handle.h" #include "storage/browser/blob/blob_storage_context.h" #include "storage/browser/blob/blob_url_request_job_factory.h" #include "storage/browser/blob/shareable_file_reference.h" #include "storage/browser/fileapi/file_permission_policy.h" #include "storage/browser/fileapi/file_system_context.h" #include "url/third_party/mozilla/url_parse.h" #include "url/url_constants.h" #if defined(S_TERRACE_SUPPORT) #include "content/public/browser/terrace_content_bridge.h" #endif #if defined(USE_TTRACE) #include <ttrace.h> #endif using base::Time; using base::TimeDelta; using base::TimeTicks; using storage::ShareableFileReference; using SyncLoadResultCallback = content::ResourceDispatcherHostImpl::SyncLoadResultCallback; // ---------------------------------------------------------------------------- namespace { constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation = net::DefineNetworkTrafficAnnotation("resource_dispatcher_host", R"( semantics { sender: "Resource Dispatcher Host" description: "Navigation-initiated request or renderer process initiated " "request, which includes all resources for normal page loads, " "chrome URLs, resources for installed extensions, as well as " "downloads." trigger: "Navigating to a URL or downloading a file. A webpage, " "ServiceWorker, chrome:// page, or extension may also initiate " "requests in the background." data: "Anything the initiator wants to send." destination: OTHER } policy { cookies_allowed: YES cookies_store: "user or per-app cookie store" setting: "These requests cannot be disabled." policy_exception_justification: "Not implemented. Without these requests, Chrome will be unable to " "load any webpage." })"); } // namespace namespace content { namespace { static ResourceDispatcherHostImpl* g_resource_dispatcher_host; // The interval for calls to ResourceDispatcherHostImpl::UpdateLoadStates const int kUpdateLoadStatesIntervalMsec = 250; // The interval for calls to RecordOutstandingRequestsStats. const int kRecordOutstandingRequestsStatsIntervalSec = 60; // Maximum byte "cost" of all the outstanding requests for a renderer. // See declaration of |max_outstanding_requests_cost_per_process_| for details. // This bound is 25MB, which allows for around 6000 outstanding requests. const int kMaxOutstandingRequestsCostPerProcess = 26214400; // The number of milliseconds after noting a user gesture that we will // tag newly-created URLRequest objects with the // net::LOAD_MAYBE_USER_GESTURE load flag. This is a fairly arbitrary // guess at how long to expect direct impact from a user gesture, but // this should be OK as the load flag is a best-effort thing only, // rather than being intended as fully accurate. const int kUserGestureWindowMs = 3500; // Ratio of |max_num_in_flight_requests_| that any one renderer is allowed to // use. Arbitrarily chosen. const double kMaxRequestsPerProcessRatio = 0.45; // TODO(jkarlin): The value is high to reduce the chance of the detachable // request timing out, forcing a blocked second request to open a new connection // and start over. Reduce this value once we have a better idea of what it // should be and once we stop blocking multiple simultaneous requests for the // same resource (see bugs 46104 and 31014). const int kDefaultDetachableCancelDelayMs = 30000; // Aborts a request before an URLRequest has actually been created. void AbortRequestBeforeItStarts( IPC::Sender* sender, const SyncLoadResultCallback& sync_result_handler, int request_id, mojom::URLLoaderClientPtr url_loader_client) { if (sync_result_handler) { SyncLoadResult result; result.error_code = net::ERR_ABORTED; sync_result_handler.Run(&result); } else { // Tell the renderer that this request was disallowed. ResourceRequestCompletionStatus request_complete_data; request_complete_data.error_code = net::ERR_ABORTED; request_complete_data.exists_in_cache = false; // No security info needed, connection not established. request_complete_data.completion_time = base::TimeTicks(); request_complete_data.encoded_data_length = 0; request_complete_data.encoded_body_length = 0; if (url_loader_client) { url_loader_client->OnComplete(request_complete_data); } else { sender->Send( new ResourceMsg_RequestComplete(request_id, request_complete_data)); } } } #if defined(S_TERRACE_SUPPORT) void AbortRequestBeforeItStarts( IPC::Sender* sender, const SyncLoadResultCallback& sync_result_handler, int request_id, int error_code, mojom::URLLoaderClientPtr url_loader_client) { if (sync_result_handler) { SyncLoadResult result; result.error_code = error_code; sync_result_handler.Run(&result); } else { // Tell the renderer that this request was disallowed. ResourceRequestCompletionStatus request_complete_data; request_complete_data.error_code = error_code; request_complete_data.exists_in_cache = false; // No security info needed, connection not established. request_complete_data.completion_time = base::TimeTicks(); request_complete_data.encoded_data_length = 0; request_complete_data.encoded_body_length = 0; if (url_loader_client) { url_loader_client->OnComplete(request_complete_data); } else { sender->Send( new ResourceMsg_RequestComplete(request_id, request_complete_data)); } } } #endif void RemoveDownloadFileFromChildSecurityPolicy(int child_id, const base::FilePath& path) { ChildProcessSecurityPolicyImpl::GetInstance()->RevokeAllPermissionsForFile( child_id, path); } bool IsValidatedSCT( const net::SignedCertificateTimestampAndStatus& sct_status) { return sct_status.status == net::ct::SCT_STATUS_OK; } // Returns the PreviewsState after requesting it from the delegate. The // PreviewsState is a bitmask of potentially several Previews optimizations. // If previews_to_allow is set to anything other than PREVIEWS_UNSPECIFIED, // it is either the values passed in for a sub-frame to use, or if this is // the main frame, it is a limitation on which previews to allow. PreviewsState GetPreviewsState(PreviewsState previews_to_allow, ResourceDispatcherHostDelegate* delegate, const net::URLRequest& request, ResourceContext* resource_context, bool is_main_frame) { // If previews have already been turned off, or we are inheriting values on a // sub-frame, don't check any further. if (previews_to_allow & PREVIEWS_OFF || previews_to_allow & PREVIEWS_NO_TRANSFORM || !is_main_frame || !delegate) { return previews_to_allow; } // Get the mask of previews we could apply to the current navigation. PreviewsState previews_state = delegate->GetPreviewsState(request, resource_context, previews_to_allow); return previews_state; } // Sends back the result of a synchronous loading result to the renderer through // Chrome IPC. void HandleSyncLoadResult(base::WeakPtr<ResourceMessageFilter> filter, std::unique_ptr<IPC::Message> sync_result, const SyncLoadResult* result) { if (!filter) return; if (result) { ResourceHostMsg_SyncLoad::WriteReplyParams(sync_result.get(), *result); } else { sync_result->set_reply_error(); } filter->Send(sync_result.release()); } // Used to log the cache flags for back-forward navigation requests. // Because this enum is used to back a histogrma, DO NOT REMOVE OR RENAME VALUES // in this enum. Instead, add a new one at the end. // TODO(clamy): Remove this once we know the reason behind PlzNavigate's // regression on PLT for back forward navigations. enum HistogramCacheFlag { HISTOGRAM_VALIDATE_CACHE, HISTOGRAM_BYPASS_CACHE, HISTOGRAM_SKIP_CACHE_VALIDATION, HISTOGRAM_ONLY_FROM_CACHE, HISTOGRAM_DISABLE_CACHE, HISTOGRAM_CACHE_FLAG_MAX = HISTOGRAM_DISABLE_CACHE, }; void RecordCacheFlags(HistogramCacheFlag flag) { UMA_HISTOGRAM_ENUMERATION("Navigation.BackForward.CacheFlags", flag, HISTOGRAM_CACHE_FLAG_MAX); } void LogBackForwardNavigationFlagsHistogram(int load_flags) { if (load_flags & net::LOAD_VALIDATE_CACHE) RecordCacheFlags(HISTOGRAM_VALIDATE_CACHE); if (load_flags & net::LOAD_BYPASS_CACHE) RecordCacheFlags(HISTOGRAM_BYPASS_CACHE); if (load_flags & net::LOAD_SKIP_CACHE_VALIDATION) RecordCacheFlags(HISTOGRAM_SKIP_CACHE_VALIDATION); if (load_flags & net::LOAD_ONLY_FROM_CACHE) RecordCacheFlags(HISTOGRAM_ONLY_FROM_CACHE); if (load_flags & net::LOAD_DISABLE_CACHE) RecordCacheFlags(HISTOGRAM_DISABLE_CACHE); } } // namespace ResourceDispatcherHostImpl::LoadInfo::LoadInfo() {} ResourceDispatcherHostImpl::LoadInfo::LoadInfo(const LoadInfo& other) = default; ResourceDispatcherHostImpl::LoadInfo::~LoadInfo() {} ResourceDispatcherHostImpl::HeaderInterceptorInfo::HeaderInterceptorInfo() {} ResourceDispatcherHostImpl::HeaderInterceptorInfo::~HeaderInterceptorInfo() {} ResourceDispatcherHostImpl::HeaderInterceptorInfo::HeaderInterceptorInfo( const HeaderInterceptorInfo& other) {} // static ResourceDispatcherHost* ResourceDispatcherHost::Get() { return g_resource_dispatcher_host; } ResourceDispatcherHostImpl::ResourceDispatcherHostImpl( CreateDownloadHandlerIntercept download_handler_intercept, const scoped_refptr<base::SingleThreadTaskRunner>& io_thread_runner) : request_id_(-1), is_shutdown_(false), num_in_flight_requests_(0), max_num_in_flight_requests_(base::SharedMemory::GetHandleLimit()), max_num_in_flight_requests_per_process_(static_cast<int>( max_num_in_flight_requests_ * kMaxRequestsPerProcessRatio)), max_outstanding_requests_cost_per_process_( kMaxOutstandingRequestsCostPerProcess), largest_outstanding_request_count_seen_(0), largest_outstanding_request_per_process_count_seen_(0), delegate_(nullptr), loader_delegate_(nullptr), allow_cross_origin_auth_prompt_(false), create_download_handler_intercept_(download_handler_intercept), main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()), io_thread_task_runner_(io_thread_runner) { DCHECK(main_thread_task_runner_->BelongsToCurrentThread()); DCHECK(!g_resource_dispatcher_host); g_resource_dispatcher_host = this; ANNOTATE_BENIGN_RACE( &last_user_gesture_time_, "We don't care about the precise value, see http://crbug.com/92889"); io_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&ResourceDispatcherHostImpl::OnInit, base::Unretained(this))); update_load_states_timer_ = base::MakeUnique<base::RepeatingTimer>(); // Monitor per-tab outstanding requests only if OOPIF is not enabled, because // the routing id doesn't represent tabs in OOPIF modes. if (!SiteIsolationPolicy::UseDedicatedProcessesForAllSites() && !SiteIsolationPolicy::IsTopDocumentIsolationEnabled() && !SiteIsolationPolicy::AreIsolatedOriginsEnabled()) { record_outstanding_requests_stats_timer_ = base::MakeUnique<base::RepeatingTimer>(); } } // The default ctor is only used by unittests. It is reasonable to assume that // the main thread and the IO thread are the same for unittests. ResourceDispatcherHostImpl::ResourceDispatcherHostImpl() : ResourceDispatcherHostImpl(CreateDownloadHandlerIntercept(), base::ThreadTaskRunnerHandle::Get()) {} ResourceDispatcherHostImpl::~ResourceDispatcherHostImpl() { DCHECK(outstanding_requests_stats_map_.empty()); DCHECK(outstanding_requests_per_tab_map_.empty()); DCHECK(g_resource_dispatcher_host); DCHECK(main_thread_task_runner_->BelongsToCurrentThread()); g_resource_dispatcher_host = NULL; } // static ResourceDispatcherHostImpl* ResourceDispatcherHostImpl::Get() { return g_resource_dispatcher_host; } void ResourceDispatcherHostImpl::SetDelegate( ResourceDispatcherHostDelegate* delegate) { delegate_ = delegate; } void ResourceDispatcherHostImpl::SetAllowCrossOriginAuthPrompt(bool value) { allow_cross_origin_auth_prompt_ = value; } void ResourceDispatcherHostImpl::CancelRequestsForContext( ResourceContext* context) { DCHECK(io_thread_task_runner_->BelongsToCurrentThread()); DCHECK(context); // Note that request cancellation has side effects. Therefore, we gather all // the requests to cancel first, and then we start cancelling. We assert at // the end that there are no more to cancel since the context is about to go // away. typedef std::vector<std::unique_ptr<ResourceLoader>> LoaderList; LoaderList loaders_to_cancel; for (LoaderMap::iterator i = pending_loaders_.begin(); i != pending_loaders_.end();) { ResourceLoader* loader = i->second.get(); if (loader->GetRequestInfo()->GetContext() == context) { loaders_to_cancel.push_back(std::move(i->second)); IncrementOutstandingRequestsMemory(-1, *loader->GetRequestInfo()); pending_loaders_.erase(i++); } else { ++i; } } for (BlockedLoadersMap::iterator i = blocked_loaders_map_.begin(); i != blocked_loaders_map_.end();) { BlockedLoadersList* loaders = i->second.get(); if (loaders->empty()) { // This can happen if BlockRequestsForRoute() has been called for a route, // but we haven't blocked any matching requests yet. ++i; continue; } ResourceRequestInfoImpl* info = loaders->front()->GetRequestInfo(); if (info->GetContext() == context) { std::unique_ptr<BlockedLoadersList> deleter(std::move(i->second)); blocked_loaders_map_.erase(i++); for (auto& loader : *loaders) { info = loader->GetRequestInfo(); // We make the assumption that all requests on the list have the same // ResourceContext. DCHECK_EQ(context, info->GetContext()); IncrementOutstandingRequestsMemory(-1, *info); loaders_to_cancel.push_back(std::move(loader)); } } else { ++i; } } #ifndef NDEBUG for (const auto& loader : loaders_to_cancel) { // There is no strict requirement that this be the case, but currently // downloads, streams, detachable requests, transferred requests, and // browser-owned requests are the only requests that aren't cancelled when // the associated processes go away. It may be OK for this invariant to // change in the future, but if this assertion fires without the invariant // changing, then it's indicative of a leak. DCHECK( loader->GetRequestInfo()->IsDownload() || loader->GetRequestInfo()->is_stream() || (loader->GetRequestInfo()->detachable_handler() && loader->GetRequestInfo()->detachable_handler()->is_detached()) || loader->GetRequestInfo()->requester_info()->IsBrowserSideNavigation() || loader->is_transferring() || loader->GetRequestInfo()->GetResourceType() == RESOURCE_TYPE_SERVICE_WORKER); } #endif loaders_to_cancel.clear(); } void ResourceDispatcherHostImpl::ClearLoginDelegateForRequest( net::URLRequest* request) { ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); if (info) { ResourceLoader* loader = GetLoader(info->GetGlobalRequestID()); if (loader) loader->ClearLoginDelegate(); } } void ResourceDispatcherHostImpl::RegisterInterceptor( const std::string& http_header, const std::string& starts_with, const InterceptorCallback& interceptor) { DCHECK(!http_header.empty()); DCHECK(interceptor); // Only one interceptor per header is supported. DCHECK(http_header_interceptor_map_.find(http_header) == http_header_interceptor_map_.end()); HeaderInterceptorInfo interceptor_info; interceptor_info.starts_with = starts_with; interceptor_info.interceptor = interceptor; http_header_interceptor_map_[http_header] = interceptor_info; } void ResourceDispatcherHostImpl::ReprioritizeRequest( net::URLRequest* request, net::RequestPriority priority) { scheduler_->ReprioritizeRequest(request, priority); } void ResourceDispatcherHostImpl::Shutdown() { DCHECK(main_thread_task_runner_->BelongsToCurrentThread()); io_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&ResourceDispatcherHostImpl::OnShutdown, base::Unretained(this))); } std::unique_ptr<ResourceHandler> ResourceDispatcherHostImpl::CreateResourceHandlerForDownload( net::URLRequest* request, bool is_content_initiated, bool must_download, bool is_new_request) { DCHECK(!create_download_handler_intercept_.is_null()); // TODO(ananta) // Find a better way to create the download handler and notifying the // delegate of the download start. std::unique_ptr<ResourceHandler> handler = create_download_handler_intercept_.Run(request); handler = HandleDownloadStarted(request, std::move(handler), is_content_initiated, must_download, is_new_request); return handler; } std::unique_ptr<ResourceHandler> ResourceDispatcherHostImpl::MaybeInterceptAsStream( const base::FilePath& plugin_path, net::URLRequest* request, ResourceResponse* response, std::string* payload) { payload->clear(); ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); const std::string& mime_type = response->head.mime_type; GURL origin; if (!delegate_ || !delegate_->ShouldInterceptResourceAsStream( request, plugin_path, mime_type, &origin, payload)) { return std::unique_ptr<ResourceHandler>(); } StreamContext* stream_context = GetStreamContextForResourceContext(info->GetContext()); std::unique_ptr<StreamResourceHandler> handler(new StreamResourceHandler( request, stream_context->registry(), origin, false)); info->set_is_stream(true); std::unique_ptr<StreamInfo> stream_info(new StreamInfo); stream_info->handle = handler->stream()->CreateHandle(); stream_info->original_url = request->url(); stream_info->mime_type = mime_type; // Make a copy of the response headers so it is safe to pass across threads; // the old handler (AsyncResourceHandler) may modify it in parallel via the // ResourceDispatcherHostDelegate. if (response->head.headers.get()) { stream_info->response_headers = new net::HttpResponseHeaders(response->head.headers->raw_headers()); } delegate_->OnStreamCreated(request, std::move(stream_info)); return std::move(handler); } ResourceDispatcherHostLoginDelegate* ResourceDispatcherHostImpl::CreateLoginDelegate( ResourceLoader* loader, net::AuthChallengeInfo* auth_info) { if (!delegate_) return NULL; return delegate_->CreateLoginDelegate(auth_info, loader->request()); } bool ResourceDispatcherHostImpl::HandleExternalProtocol(ResourceLoader* loader, const GURL& url) { if (!delegate_) return false; ResourceRequestInfoImpl* info = loader->GetRequestInfo(); if (!IsResourceTypeFrame(info->GetResourceType())) return false; const net::URLRequestJobFactory* job_factory = info->GetContext()->GetRequestContext()->job_factory(); if (!url.is_valid() || job_factory->IsHandledProtocol(url.scheme())) return false; return delegate_->HandleExternalProtocol(url, info); } void ResourceDispatcherHostImpl::DidStartRequest(ResourceLoader* loader) { // Make sure we have the load state monitors running. if (!update_load_states_timer_->IsRunning() && scheduler_->HasLoadingClients()) { update_load_states_timer_->Start( FROM_HERE, TimeDelta::FromMilliseconds(kUpdateLoadStatesIntervalMsec), this, &ResourceDispatcherHostImpl::UpdateLoadInfo); } if (record_outstanding_requests_stats_timer_ && !record_outstanding_requests_stats_timer_->IsRunning()) { record_outstanding_requests_stats_timer_->Start( FROM_HERE, TimeDelta::FromSeconds(kRecordOutstandingRequestsStatsIntervalSec), this, &ResourceDispatcherHostImpl::RecordOutstandingRequestsStats); } } void ResourceDispatcherHostImpl::DidReceiveRedirect( ResourceLoader* loader, const GURL& new_url, ResourceResponse* response) { ResourceRequestInfoImpl* info = loader->GetRequestInfo(); if (delegate_) { delegate_->OnRequestRedirected( new_url, loader->request(), info->GetContext(), response); } // Don't notify WebContents observers for requests known to be // downloads; they aren't really associated with the Webcontents. // Note that not all downloads are known before content sniffing. if (info->IsDownload()) return; // Notify the observers on the UI thread. net::URLRequest* request = loader->request(); std::unique_ptr<ResourceRedirectDetails> detail(new ResourceRedirectDetails( loader->request(), !!request->ssl_info().cert, new_url)); loader_delegate_->DidGetRedirectForResourceRequest( info->GetWebContentsGetterForRequest(), std::move(detail)); } void ResourceDispatcherHostImpl::DidReceiveResponse( ResourceLoader* loader, ResourceResponse* response) { ResourceRequestInfoImpl* info = loader->GetRequestInfo(); net::URLRequest* request = loader->request(); if (request->was_fetched_via_proxy() && request->was_fetched_via_spdy() && request->url().SchemeIs(url::kHttpScheme)) { scheduler_->OnReceivedSpdyProxiedHttpResponse( info->GetChildID(), info->GetRouteID()); } ProcessRequestForLinkHeaders(request); if (delegate_) delegate_->OnResponseStarted(request, info->GetContext(), response); // Don't notify WebContents observers for requests known to be // downloads; they aren't really associated with the Webcontents. // Note that not all downloads are known before content sniffing. if (info->IsDownload()) return; // Notify the observers on the UI thread. std::unique_ptr<ResourceRequestDetails> detail(new ResourceRequestDetails( request, !!request->ssl_info().cert)); loader_delegate_->DidGetResourceResponseStart( info->GetWebContentsGetterForRequest(), std::move(detail)); } void ResourceDispatcherHostImpl::DidFinishLoading(ResourceLoader* loader) { ResourceRequestInfoImpl* info = loader->GetRequestInfo(); // Record final result of all resource loads. if (info->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME) { // This enumeration has "3" appended to its name to distinguish it from // older versions. UMA_HISTOGRAM_SPARSE_SLOWLY( "Net.ErrorCodesForMainFrame3", -loader->request()->status().error()); if (loader->request()->status().error() == net::ERR_ABORTED) { UMA_HISTOGRAM_CUSTOM_COUNTS("Net.ErrAborted.SentBytes", loader->request()->GetTotalSentBytes(), 1, 50000000, 50); UMA_HISTOGRAM_CUSTOM_COUNTS("Net.ErrAborted.ReceivedBytes", loader->request()->GetTotalReceivedBytes(), 1, 50000000, 50); } if (loader->request()->url().SchemeIsCryptographic()) { if (loader->request()->url().host_piece() == "www.google.com") { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.ErrorCodesForHTTPSGoogleMainFrame2", -loader->request()->status().error()); } if (net::IsTLS13ExperimentHost(loader->request()->url().host_piece())) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.ErrorCodesForTLS13ExperimentMainFrame", -loader->request()->status().error()); } int num_valid_scts = std::count_if( loader->request()->ssl_info().signed_certificate_timestamps.begin(), loader->request()->ssl_info().signed_certificate_timestamps.end(), IsValidatedSCT); UMA_HISTOGRAM_COUNTS_100( "Net.CertificateTransparency.MainFrameValidSCTCount", num_valid_scts); } } else { if (info->GetResourceType() == RESOURCE_TYPE_IMAGE) { UMA_HISTOGRAM_SPARSE_SLOWLY( "Net.ErrorCodesForImages", -loader->request()->status().error()); } // This enumeration has "2" appended to distinguish it from older versions. UMA_HISTOGRAM_SPARSE_SLOWLY( "Net.ErrorCodesForSubresources2", -loader->request()->status().error()); } if (delegate_) delegate_->RequestComplete(loader->request()); // Destroy the ResourceLoader. RemovePendingRequest(info->GetChildID(), info->GetRequestID()); } std::unique_ptr<net::ClientCertStore> ResourceDispatcherHostImpl::CreateClientCertStore(ResourceLoader* loader) { return delegate_->CreateClientCertStore( loader->GetRequestInfo()->GetContext()); } void ResourceDispatcherHostImpl::OnInit() { // In some tests |delegate_| does not get set, when that happens assume the // scheduler is enabled. bool enable_resource_scheduler = delegate_ ? delegate_->ShouldUseResourceScheduler() : true; scheduler_.reset(new ResourceScheduler(enable_resource_scheduler)); } void ResourceDispatcherHostImpl::OnShutdown() { DCHECK(io_thread_task_runner_->BelongsToCurrentThread()); is_shutdown_ = true; pending_loaders_.clear(); // Make sure we shutdown the timers now, otherwise by the time our destructor // runs if the timer is still running the Task is deleted twice (once by // the MessageLoop and the second time by RepeatingTimer). update_load_states_timer_.reset(); record_outstanding_requests_stats_timer_.reset(); // Clear blocked requests if any left. // Note that we have to do this in 2 passes as we cannot call // CancelBlockedRequestsForRoute while iterating over // blocked_loaders_map_, as it modifies it. std::set<GlobalFrameRoutingId> ids; for (const auto& blocked_loaders : blocked_loaders_map_) { std::pair<std::set<GlobalFrameRoutingId>::iterator, bool> result = ids.insert(blocked_loaders.first); // We should not have duplicates. DCHECK(result.second); } for (const auto& routing_id : ids) { CancelBlockedRequestsForRoute(routing_id); } scheduler_.reset(); } bool ResourceDispatcherHostImpl::OnMessageReceived( const IPC::Message& message, ResourceRequesterInfo* requester_info) { DCHECK(io_thread_task_runner_->BelongsToCurrentThread()); bool handled = true; IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(ResourceDispatcherHostImpl, message, requester_info) IPC_MESSAGE_HANDLER(ResourceHostMsg_RequestResource, OnRequestResource) IPC_MESSAGE_HANDLER_WITH_PARAM_DELAY_REPLY(ResourceHostMsg_SyncLoad, OnSyncLoad) IPC_MESSAGE_HANDLER(ResourceHostMsg_ReleaseDownloadedFile, OnReleaseDownloadedFile) IPC_MESSAGE_HANDLER(ResourceHostMsg_CancelRequest, OnCancelRequest) IPC_MESSAGE_HANDLER(ResourceHostMsg_DidChangePriority, OnDidChangePriority) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (!handled && IPC_MESSAGE_ID_CLASS(message.type()) == ResourceMsgStart) { base::PickleIterator iter(message); int request_id = -1; bool ok = iter.ReadInt(&request_id); DCHECK(ok); GlobalRequestID id(requester_info->child_id(), request_id); DelegateMap::iterator it = delegate_map_.find(id); if (it != delegate_map_.end()) { for (auto& delegate : *it->second) { if (delegate.OnMessageReceived(message)) { handled = true; break; } } } // As the unhandled resource message effectively has no consumer, mark it as // handled to prevent needless propagation through the filter pipeline. handled = true; } return handled; } void ResourceDispatcherHostImpl::OnRequestResource( ResourceRequesterInfo* requester_info, int routing_id, int request_id, const ResourceRequest& request_data, net::MutableNetworkTrafficAnnotationTag traffic_annotation) { OnRequestResourceInternal( requester_info, routing_id, request_id, false /* is_sync_load */, request_data, nullptr, nullptr, net::NetworkTrafficAnnotationTag(traffic_annotation)); } void ResourceDispatcherHostImpl::OnRequestResourceInternal( ResourceRequesterInfo* requester_info, int routing_id, int request_id, bool is_sync_load, const ResourceRequest& request_data, mojom::URLLoaderRequest mojo_request, mojom::URLLoaderClientPtr url_loader_client, const net::NetworkTrafficAnnotationTag& traffic_annotation) { DCHECK(requester_info->IsRenderer() || requester_info->IsNavigationPreload()); // When logging time-to-network only care about main frame and non-transfer // navigations. // PlzNavigate: this log happens from NavigationRequest::OnRequestStarted // instead. if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME && request_data.transferred_request_request_id == -1 && !IsBrowserSideNavigationEnabled() && loader_delegate_) { loader_delegate_->LogResourceRequestTime(TimeTicks::Now(), requester_info->child_id(), request_data.render_frame_id, request_data.url); } BeginRequest(requester_info, request_id, request_data, is_sync_load, SyncLoadResultCallback(), routing_id, std::move(mojo_request), std::move(url_loader_client), traffic_annotation); } // Begins a resource request with the given params on behalf of the specified // child process. Responses will be dispatched through the given receiver. The // process ID is used to lookup WebContentsImpl from routing_id's in the case of // a request from a renderer. request_context is the cookie/cache context to be // used for this request. // // If sync_result is non-null, then a SyncLoad reply will be generated, else // a normal asynchronous set of response messages will be generated. void ResourceDispatcherHostImpl::OnSyncLoad( ResourceRequesterInfo* requester_info, int request_id, const ResourceRequest& request_data, IPC::Message* sync_result) { SyncLoadResultCallback callback = base::Bind(&HandleSyncLoadResult, requester_info->filter()->GetWeakPtr(), base::Passed(WrapUnique(sync_result))); BeginRequest(requester_info, request_id, request_data, true /* is_sync_load */, callback, sync_result->routing_id(), nullptr, nullptr, kTrafficAnnotation); } bool ResourceDispatcherHostImpl::IsRequestIDInUse( const GlobalRequestID& id) const { if (pending_loaders_.find(id) != pending_loaders_.end()) return true; for (const auto& blocked_loaders : blocked_loaders_map_) { for (const auto& loader : *blocked_loaders.second.get()) { ResourceRequestInfoImpl* info = loader->GetRequestInfo(); if (info->GetGlobalRequestID() == id) return true; } } return false; } void ResourceDispatcherHostImpl::UpdateRequestForTransfer( ResourceRequesterInfo* requester_info, int route_id, int request_id, const ResourceRequest& request_data, LoaderMap::iterator iter, mojom::URLLoaderRequest mojo_request, mojom::URLLoaderClientPtr url_loader_client) { DCHECK(requester_info->IsRenderer()); int child_id = requester_info->child_id(); ResourceRequestInfoImpl* info = iter->second->GetRequestInfo(); GlobalFrameRoutingId old_routing_id(request_data.transferred_request_child_id, info->GetRenderFrameID()); GlobalRequestID old_request_id(request_data.transferred_request_child_id, request_data.transferred_request_request_id); GlobalFrameRoutingId new_routing_id(child_id, request_data.render_frame_id); GlobalRequestID new_request_id(child_id, request_id); // Clear out data that depends on |info| before updating it. // We always need to move the memory stats to the new process. In contrast, // stats.num_requests is only tracked for some requests (those that require // file descriptors for their shared memory buffer). IncrementOutstandingRequestsMemory(-1, *info); bool should_update_count = info->counted_as_in_flight_request(); if (should_update_count) IncrementOutstandingRequestsCount(-1, info); DCHECK(pending_loaders_.find(old_request_id) == iter); std::unique_ptr<ResourceLoader> loader = std::move(iter->second); ResourceLoader* loader_ptr = loader.get(); pending_loaders_.erase(iter); // ResourceHandlers should always get state related to the request from the // ResourceRequestInfo rather than caching it locally. This lets us update // the info object when a transfer occurs. info->UpdateForTransfer(route_id, request_data.render_frame_id, request_data.origin_pid, request_id, requester_info, std::move(mojo_request), std::move(url_loader_client)); // Update maps that used the old IDs, if necessary. Some transfers in tests // do not actually use a different ID, so not all maps need to be updated. pending_loaders_[new_request_id] = std::move(loader); IncrementOutstandingRequestsMemory(1, *info); if (should_update_count) IncrementOutstandingRequestsCount(1, info); if (old_routing_id != new_routing_id) { if (blocked_loaders_map_.find(old_routing_id) != blocked_loaders_map_.end()) { blocked_loaders_map_[new_routing_id] = std::move(blocked_loaders_map_[old_routing_id]); blocked_loaders_map_.erase(old_routing_id); } } if (old_request_id != new_request_id) { DelegateMap::iterator it = delegate_map_.find(old_request_id); if (it != delegate_map_.end()) { // Tell each delegate that the request ID has changed. for (auto& delegate : *it->second) delegate.set_request_id(new_request_id); // Now store the observer list under the new request ID. delegate_map_[new_request_id] = delegate_map_[old_request_id]; delegate_map_.erase(old_request_id); } } AppCacheInterceptor::CompleteCrossSiteTransfer( loader_ptr->request(), child_id, request_data.appcache_host_id, requester_info); ServiceWorkerRequestHandler* handler = ServiceWorkerRequestHandler::GetHandler(loader_ptr->request()); if (handler) { if (!handler->SanityCheckIsSameContext( requester_info->service_worker_context())) { bad_message::ReceivedBadMessage( requester_info->filter(), bad_message::RDHI_WRONG_STORAGE_PARTITION); } else { handler->CompleteCrossSiteTransfer( child_id, request_data.service_worker_provider_id); } } } void ResourceDispatcherHostImpl::CompleteTransfer( ResourceRequesterInfo* requester_info, int request_id, const ResourceRequest& request_data, int route_id, mojom::URLLoaderRequest mojo_request, mojom::URLLoaderClientPtr url_loader_client) { DCHECK(requester_info->IsRenderer()); // Caller should ensure that |request_data| is associated with a transfer. DCHECK(request_data.transferred_request_child_id != -1 || request_data.transferred_request_request_id != -1); if (!IsResourceTypeFrame(request_data.resource_type)) { // Transfers apply only to navigational requests - the renderer seems to // have sent bogus IPC data. bad_message::ReceivedBadMessage( requester_info->filter(), bad_message::RDH_TRANSFERRING_NONNAVIGATIONAL_REQUEST); return; } // Attempt to find a loader associated with the deferred transfer request. LoaderMap::iterator it = pending_loaders_.find( GlobalRequestID(request_data.transferred_request_child_id, request_data.transferred_request_request_id)); if (it == pending_loaders_.end()) { // Renderer sent transferred_request_request_id and/or // transferred_request_child_id that doesn't have a corresponding entry on // the browser side. // TODO(lukasza): https://crbug.com/659613: Need to understand the scenario // that can lead here (and then attempt to reintroduce a renderer kill // below). return; } ResourceLoader* pending_loader = it->second.get(); if (!pending_loader->is_transferring()) { // Renderer sent transferred_request_request_id and/or // transferred_request_child_id that doesn't correspond to an actually // transferring loader on the browser side. base::debug::Alias(pending_loader); bad_message::ReceivedBadMessage(requester_info->filter(), bad_message::RDH_REQUEST_NOT_TRANSFERRING); return; } // If the request is transferring to a new process, we can update our // state and let it resume with its existing ResourceHandlers. UpdateRequestForTransfer(requester_info, route_id, request_id, request_data, it, std::move(mojo_request), std::move(url_loader_client)); pending_loader->CompleteTransfer(); } void ResourceDispatcherHostImpl::BeginRequest( ResourceRequesterInfo* requester_info, int request_id, const ResourceRequest& request_data, bool is_sync_load, const SyncLoadResultCallback& sync_result_handler, // only valid for sync int route_id, mojom::URLLoaderRequest mojo_request, mojom::URLLoaderClientPtr url_loader_client, const net::NetworkTrafficAnnotationTag& traffic_annotation) { DCHECK(requester_info->IsRenderer() || requester_info->IsNavigationPreload()); int child_id = requester_info->child_id(); // Reject request id that's currently in use. if (IsRequestIDInUse(GlobalRequestID(child_id, request_id))) { // Navigation preload requests have child_id's of -1 and monotonically // increasing request IDs allocated by MakeRequestID. DCHECK(requester_info->IsRenderer()); bad_message::ReceivedBadMessage(requester_info->filter(), bad_message::RDH_INVALID_REQUEST_ID); return; } // PlzNavigate: reject invalid renderer main resource request. bool is_navigation_stream_request = IsBrowserSideNavigationEnabled() && IsResourceTypeFrame(request_data.resource_type); if (is_navigation_stream_request && !request_data.resource_body_stream_url.SchemeIs(url::kBlobScheme)) { // The resource_type of navigation preload requests must be SUB_RESOURCE. DCHECK(requester_info->IsRenderer()); bad_message::ReceivedBadMessage(requester_info->filter(), bad_message::RDH_INVALID_URL); return; } // Reject invalid priority. if (request_data.priority < net::MINIMUM_PRIORITY || request_data.priority > net::MAXIMUM_PRIORITY) { // The priority of navigation preload requests are copied from the original // request priority which must be checked beforehand. DCHECK(requester_info->IsRenderer()); bad_message::ReceivedBadMessage(requester_info->filter(), bad_message::RDH_INVALID_PRIORITY); return; } // If we crash here, figure out what URL the renderer was requesting. // http://crbug.com/91398 char url_buf[128]; base::strlcpy(url_buf, request_data.url.spec().c_str(), arraysize(url_buf)); base::debug::Alias(url_buf); #if defined(USE_TTRACE) int ttrace_key_loader = 1 << 1; traceAsyncBegin(TTRACE_TAG_WEB, ttrace_key_loader, "LOADER:LOADING >> url: %s", request_data.url.spec().substr(0, 128).c_str()); #endif // If the request that's coming in is being transferred from another process, // we want to reuse and resume the old loader rather than start a new one. if (request_data.transferred_request_child_id != -1 || request_data.transferred_request_request_id != -1) { CompleteTransfer(requester_info, request_id, request_data, route_id, std::move(mojo_request), std::move(url_loader_client)); return; } ResourceContext* resource_context = NULL; net::URLRequestContext* request_context = NULL; requester_info->GetContexts(request_data.resource_type, &resource_context, &request_context); // Parse the headers before calling ShouldServiceRequest, so that they are // available to be validated. if (is_shutdown_ || !ShouldServiceRequest(child_id, request_data, request_data.headers, requester_info, resource_context)) { AbortRequestBeforeItStarts(requester_info->filter(), sync_result_handler, request_id, std::move(url_loader_client)); return; } BlobHandles blob_handles; if (!is_navigation_stream_request) { storage::BlobStorageContext* blob_context = GetBlobStorageContext(requester_info->blob_storage_context()); // Resolve elements from request_body and prepare upload data. if (request_data.request_body.get()) { // |blob_context| could be null when the request is from the plugins // because ResourceMessageFilters created in PluginProcessHost don't have // the blob context. if (blob_context) { // Get BlobHandles to request_body to prevent blobs and any attached // shareable files from being freed until upload completion. These data // will be used in UploadDataStream and ServiceWorkerURLRequestJob. if (!GetBodyBlobDataHandles(request_data.request_body.get(), resource_context, &blob_handles)) { AbortRequestBeforeItStarts(requester_info->filter(), sync_result_handler, request_id, std::move(url_loader_client)); return; } } } // Check if we have a registered interceptor for the headers passed in. If // yes then we need to mark the current request as pending and wait for the // interceptor to invoke the callback with a status code indicating whether // the request needs to be aborted or continued. for (net::HttpRequestHeaders::Iterator it(request_data.headers); it.GetNext();) { HeaderInterceptorMap::iterator index = http_header_interceptor_map_.find(it.name()); if (index != http_header_interceptor_map_.end()) { HeaderInterceptorInfo& interceptor_info = index->second; bool call_interceptor = true; if (!interceptor_info.starts_with.empty()) { call_interceptor = base::StartsWith(it.value(), interceptor_info.starts_with, base::CompareCase::INSENSITIVE_ASCII); } if (call_interceptor) { interceptor_info.interceptor.Run( it.name(), it.value(), child_id, resource_context, base::Bind( &ResourceDispatcherHostImpl::ContinuePendingBeginRequest, base::Unretained(this), base::WrapRefCounted(requester_info), request_id, request_data, is_sync_load, sync_result_handler, route_id, request_data.headers, base::Passed(std::move(mojo_request)), base::Passed(std::move(url_loader_client)), base::Passed(std::move(blob_handles)), traffic_annotation)); return; } } } } ContinuePendingBeginRequest(requester_info, request_id, request_data, is_sync_load, sync_result_handler, route_id, request_data.headers, std::move(mojo_request), std::move(url_loader_client), std::move(blob_handles), traffic_annotation, HeaderInterceptorResult::CONTINUE); } void ResourceDispatcherHostImpl::ContinuePendingBeginRequest( scoped_refptr<ResourceRequesterInfo> requester_info, int request_id, const ResourceRequest& request_data, bool is_sync_load, const SyncLoadResultCallback& sync_result_handler, // only valid for sync int route_id, const net::HttpRequestHeaders& headers, mojom::URLLoaderRequest mojo_request, mojom::URLLoaderClientPtr url_loader_client, BlobHandles blob_handles, const net::NetworkTrafficAnnotationTag& traffic_annotation, HeaderInterceptorResult interceptor_result) { DCHECK(requester_info->IsRenderer() || requester_info->IsNavigationPreload()); DCHECK(!sync_result_handler || is_sync_load); if (interceptor_result != HeaderInterceptorResult::CONTINUE) { if (requester_info->IsRenderer() && interceptor_result == HeaderInterceptorResult::KILL) { // TODO(ananta): Find a way to specify the right error code here. Passing // in a non-content error code is not safe, but future header interceptors // might say to kill for reasons other than illegal origins. bad_message::ReceivedBadMessage(requester_info->filter(), bad_message::RDH_ILLEGAL_ORIGIN); } AbortRequestBeforeItStarts(requester_info->filter(), sync_result_handler, request_id, std::move(url_loader_client)); return; } int child_id = requester_info->child_id(); storage::BlobStorageContext* blob_context = nullptr; bool allow_download = false; bool do_not_prompt_for_login = false; bool report_raw_headers = false; int load_flags = BuildLoadFlagsForRequest(request_data, is_sync_load); bool is_navigation_stream_request = IsBrowserSideNavigationEnabled() && IsResourceTypeFrame(request_data.resource_type); ResourceContext* resource_context = NULL; net::URLRequestContext* request_context = NULL; requester_info->GetContexts(request_data.resource_type, &resource_context, &request_context); // Allow the observer to block/handle the request. if (delegate_ && !delegate_->ShouldBeginRequest(request_data.method, request_data.url, request_data.resource_type, resource_context)) { AbortRequestBeforeItStarts(requester_info->filter(), sync_result_handler, request_id, std::move(url_loader_client)); return; } // Construct the request. std::unique_ptr<net::URLRequest> new_request = request_context->CreateRequest( is_navigation_stream_request ? request_data.resource_body_stream_url : request_data.url, request_data.priority, nullptr, traffic_annotation); if (is_navigation_stream_request) { // PlzNavigate: Always set the method to GET when gaining access to the // stream that contains the response body of a navigation. Otherwise the // data that was already fetched by the browser will not be transmitted to // the renderer. new_request->set_method("GET"); } else { // Log that this request is a service worker navigation preload request // here, since navigation preload machinery has no access to netlog. // TODO(falken): Figure out how mojom::URLLoaderClient can // access the request's netlog. if (requester_info->IsNavigationPreload()) { new_request->net_log().AddEvent( net::NetLogEventType::SERVICE_WORKER_NAVIGATION_PRELOAD_REQUEST); } new_request->set_method(request_data.method); new_request->set_site_for_cookies(request_data.site_for_cookies); // The initiator should normally be present, unless this is a navigation in // a top-level frame. It may be null for some top-level navigations (eg: // browser-initiated ones). DCHECK(request_data.request_initiator.has_value() || request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME); new_request->set_initiator(request_data.request_initiator); if (request_data.originated_from_service_worker) { new_request->SetUserData(URLRequestServiceWorkerData::kUserDataKey, base::MakeUnique<URLRequestServiceWorkerData>()); } // If the request is a MAIN_FRAME request, the first-party URL gets updated // on redirects. if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) { new_request->set_first_party_url_policy( net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT); } // For PlzNavigate, this request has already been made and the referrer was // checked previously. So don't set the referrer for this stream request, or // else it will fail for SSL redirects since net/ will think the blob:https // for the stream is not a secure scheme (specifically, in the call to // ComputeReferrerForRedirect). const Referrer referrer( request_data.referrer, request_data.referrer_policy); Referrer::SetReferrerForRequest(new_request.get(), referrer); new_request->SetExtraRequestHeaders(headers); #if defined(S_TERRACE_SUPPORT) if (TerraceContentBridge::Get().TrackerBlockResourceFilter( new_request->url(), new_request->site_for_cookies(), request_data.resource_type, child_id)) { AbortRequestBeforeItStarts(requester_info->filter(), sync_result_handler, request_id, net::ERR_BLOCKED_BY_TRACKER_BLOCK, std::move(url_loader_client)); return; } if (TerraceContentBridge::Get().ContentBlockerPopupResourceFilter( new_request->url(), request_data.resource_type, child_id, request_data.render_frame_id) || TerraceContentBridge::Get().ContentBlockerResourceFilter( new_request->url(), new_request->site_for_cookies(), request_data.resource_type, route_id, child_id, request_data.transition_type, requester_info->filter())) { AbortRequestBeforeItStarts( requester_info->filter(), sync_result_handler, request_id, net::ERR_BLOCKED_BY_CONTENT_BLOCKER, std::move(url_loader_client)); return; } #endif blob_context = GetBlobStorageContext(requester_info->blob_storage_context()); // Resolve elements from request_body and prepare upload data. if (request_data.request_body.get()) { new_request->set_upload(UploadDataStreamBuilder::Build( request_data.request_body.get(), blob_context, requester_info->file_system_context(), base::CreateSingleThreadTaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}) .get())); } allow_download = request_data.allow_download && IsResourceTypeFrame(request_data.resource_type); do_not_prompt_for_login = request_data.do_not_prompt_for_login; // Raw headers are sensitive, as they include Cookie/Set-Cookie, so only // allow requesting them if requester has ReadRawCookies permission. ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); report_raw_headers = request_data.report_raw_headers; if (report_raw_headers && !policy->CanReadRawCookies(child_id) && !requester_info->IsNavigationPreload()) { // For navigation preload, the child_id is -1 so CanReadRawCookies would // return false. But |report_raw_headers| of the navigation preload // request was copied from the original request, so this check has already // been carried out. // TODO: crbug.com/523063 can we call bad_message::ReceivedBadMessage // here? VLOG(1) << "Denied unauthorized request for raw headers"; report_raw_headers = false; } if (request_data.resource_type == RESOURCE_TYPE_PREFETCH || request_data.resource_type == RESOURCE_TYPE_FAVICON) { do_not_prompt_for_login = true; } if (request_data.resource_type == RESOURCE_TYPE_IMAGE && HTTP_AUTH_RELATION_BLOCKED_CROSS == HttpAuthRelationTypeOf(request_data.url, request_data.site_for_cookies)) { // Prevent third-party image content from prompting for login, as this // is often a scam to extract credentials for another domain from the // user. Only block image loads, as the attack applies largely to the // "src" property of the <img> tag. It is common for web properties to // allow untrusted values for <img src>; this is considered a fair thing // for an HTML sanitizer to do. Conversely, any HTML sanitizer that didn't // filter sources for <script>, <link>, <embed>, <object>, <iframe> tags // would be considered vulnerable in and of itself. do_not_prompt_for_login = true; load_flags |= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY; } // Sync loads should have maximum priority and should be the only // requets that have the ignore limits flag set. if (is_sync_load) { DCHECK_EQ(request_data.priority, net::MAXIMUM_PRIORITY); DCHECK_NE(load_flags & net::LOAD_IGNORE_LIMITS, 0); } else { DCHECK_EQ(load_flags & net::LOAD_IGNORE_LIMITS, 0); } } new_request->SetLoadFlags(load_flags); // Update the previews state, but only if this is not using PlzNavigate. PreviewsState previews_state = request_data.previews_state; if (!IsBrowserSideNavigationEnabled()) { previews_state = GetPreviewsState( request_data.previews_state, delegate_, *new_request, resource_context, request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME); } // Make extra info and read footer (contains request ID). ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl( requester_info, route_id, -1, // frame_tree_node_id request_data.origin_pid, request_id, request_data.render_frame_id, request_data.is_main_frame, request_data.resource_type, request_data.transition_type, request_data.should_replace_current_entry, false, // is download false, // is stream allow_download, request_data.has_user_gesture, request_data.enable_load_timing, request_data.enable_upload_progress, do_not_prompt_for_login, request_data.keepalive, request_data.referrer_policy, request_data.visibility_state, resource_context, report_raw_headers, !is_sync_load, previews_state, request_data.request_body, request_data.initiated_in_secure_context); extra_info->SetBlobHandles(std::move(blob_handles)); // Request takes ownership. extra_info->AssociateWithRequest(new_request.get()); if (new_request->url().SchemeIs(url::kBlobScheme)) { // Hang on to a reference to ensure the blob is not released prior // to the job being started. storage::BlobProtocolHandler::SetRequestedBlobDataHandle( new_request.get(), requester_info->blob_storage_context() ->context() ->GetBlobDataFromPublicURL(new_request->url())); } std::unique_ptr<ResourceHandler> handler; if (is_navigation_stream_request) { // PlzNavigate: do not add ResourceThrottles for main resource requests from // the renderer. Decisions about the navigation should have been done in // the initial request. handler = CreateBaseResourceHandler( new_request.get(), std::move(mojo_request), std::move(url_loader_client), request_data.resource_type); } else { // Initialize the service worker handler for the request. We don't use // ServiceWorker for synchronous loads to avoid renderer deadlocks. const ServiceWorkerMode service_worker_mode = is_sync_load ? ServiceWorkerMode::NONE : request_data.service_worker_mode; ServiceWorkerRequestHandler::InitializeHandler( new_request.get(), requester_info->service_worker_context(), blob_context, child_id, request_data.service_worker_provider_id, service_worker_mode != ServiceWorkerMode::ALL, request_data.fetch_request_mode, request_data.fetch_credentials_mode, request_data.fetch_redirect_mode, request_data.fetch_integrity, request_data.resource_type, request_data.fetch_request_context_type, request_data.fetch_frame_type, request_data.request_body); ForeignFetchRequestHandler::InitializeHandler( new_request.get(), requester_info->service_worker_context(), blob_context, child_id, request_data.service_worker_provider_id, service_worker_mode, request_data.fetch_request_mode, request_data.fetch_credentials_mode, request_data.fetch_redirect_mode, request_data.fetch_integrity, request_data.resource_type, request_data.fetch_request_context_type, request_data.fetch_frame_type, request_data.request_body, request_data.initiated_in_secure_context); // Have the appcache associate its extra info with the request. AppCacheInterceptor::SetExtraRequestInfo( new_request.get(), requester_info->appcache_service(), child_id, request_data.appcache_host_id, request_data.resource_type, request_data.should_reset_appcache); handler = CreateResourceHandler( requester_info.get(), new_request.get(), request_data, sync_result_handler, route_id, child_id, resource_context, std::move(mojo_request), std::move(url_loader_client)); } if (handler) BeginRequestInternal(std::move(new_request), std::move(handler)); } std::unique_ptr<ResourceHandler> ResourceDispatcherHostImpl::CreateResourceHandler( ResourceRequesterInfo* requester_info, net::URLRequest* request, const ResourceRequest& request_data, const SyncLoadResultCallback& sync_result_handler, int route_id, int child_id, ResourceContext* resource_context, mojom::URLLoaderRequest mojo_request, mojom::URLLoaderClientPtr url_loader_client) { DCHECK(requester_info->IsRenderer() || requester_info->IsNavigationPreload()); // Construct the IPC resource handler. std::unique_ptr<ResourceHandler> handler; if (sync_result_handler) { // download_to_file is not supported for synchronous requests. if (request_data.download_to_file) { DCHECK(requester_info->IsRenderer()); bad_message::ReceivedBadMessage(requester_info->filter(), bad_message::RDH_BAD_DOWNLOAD); return std::unique_ptr<ResourceHandler>(); } DCHECK(!mojo_request.is_pending()); DCHECK(!url_loader_client); handler.reset(new SyncResourceHandler(request, sync_result_handler, this)); } else { handler = CreateBaseResourceHandler(request, std::move(mojo_request), std::move(url_loader_client), request_data.resource_type); // The RedirectToFileResourceHandler depends on being next in the chain. if (request_data.download_to_file) { handler.reset( new RedirectToFileResourceHandler(std::move(handler), request)); } } bool start_detached = request_data.download_to_network_cache_only; // Prefetches and <a ping> requests outlive their child process. if (!sync_result_handler && (start_detached || request_data.resource_type == RESOURCE_TYPE_PREFETCH || request_data.keepalive)) { auto timeout = base::TimeDelta::FromMilliseconds(kDefaultDetachableCancelDelayMs); int timeout_set_by_finch_in_sec = base::GetFieldTrialParamByFeatureAsInt( features::kFetchKeepaliveTimeoutSetting, "timeout_in_sec", 0); // Adopt only "reasonable" values. if (timeout_set_by_finch_in_sec > 0 && timeout_set_by_finch_in_sec < 60 * 60) { timeout = base::TimeDelta::FromSeconds(timeout_set_by_finch_in_sec); } std::unique_ptr<DetachableResourceHandler> detachable_handler = base::MakeUnique<DetachableResourceHandler>(request, timeout, std::move(handler)); if (start_detached) detachable_handler->Detach(); handler = std::move(detachable_handler); } return AddStandardHandlers(request, request_data.resource_type, resource_context, request_data.fetch_request_context_type, request_data.fetch_mixed_content_context_type, requester_info->appcache_service(), child_id, route_id, std::move(handler), nullptr, nullptr); } std::unique_ptr<ResourceHandler> ResourceDispatcherHostImpl::CreateBaseResourceHandler( net::URLRequest* request, mojom::URLLoaderRequest mojo_request, mojom::URLLoaderClientPtr url_loader_client, ResourceType resource_type) { std::unique_ptr<ResourceHandler> handler; if (mojo_request.is_pending()) { handler.reset(new MojoAsyncResourceHandler( request, this, std::move(mojo_request), std::move(url_loader_client), resource_type)); } else { handler.reset(new AsyncResourceHandler(request, this)); } return handler; } std::unique_ptr<ResourceHandler> ResourceDispatcherHostImpl::AddStandardHandlers( net::URLRequest* request, ResourceType resource_type, ResourceContext* resource_context, RequestContextType fetch_request_context_type, blink::WebMixedContentContextType fetch_mixed_content_context_type, AppCacheService* appcache_service, int child_id, int route_id, std::unique_ptr<ResourceHandler> handler, NavigationURLLoaderImplCore* navigation_loader_core, std::unique_ptr<StreamHandle> stream_handle) { // The InterceptingResourceHandler will replace its next handler with an // appropriate one based on the MIME type of the response if needed. It // should be placed at the end of the chain, just before |handler|. handler.reset(new InterceptingResourceHandler(std::move(handler), request)); InterceptingResourceHandler* intercepting_handler = static_cast<InterceptingResourceHandler*>(handler.get()); std::vector<std::unique_ptr<ResourceThrottle>> throttles; // Add a NavigationResourceThrottle for navigations. // PlzNavigate: the throttle is unnecessary as communication with the UI // thread is handled by the NavigationResourceHandler below. if (!IsBrowserSideNavigationEnabled() && IsResourceTypeFrame(resource_type)) { throttles.push_back(base::MakeUnique<NavigationResourceThrottle>( request, delegate_, fetch_request_context_type, fetch_mixed_content_context_type)); } if (delegate_) { delegate_->RequestBeginning(request, resource_context, appcache_service, resource_type, &throttles); } if (request->has_upload()) { // Request wake lock while uploading data. throttles.push_back( base::MakeUnique<WakeLockResourceThrottle>(request->url().host())); } // The Clear-Site-Data throttle. std::unique_ptr<ResourceThrottle> clear_site_data_throttle = ClearSiteDataThrottle::MaybeCreateThrottleForRequest(request); if (clear_site_data_throttle) throttles.push_back(std::move(clear_site_data_throttle)); // TODO(ricea): Stop looking this up so much. ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); throttles.push_back(scheduler_->ScheduleRequest(child_id, route_id, info->IsAsync(), request)); // Split the handler in two groups: the ones that need to execute // WillProcessResponse before mime sniffing and the others. std::vector<std::unique_ptr<ResourceThrottle>> pre_mime_sniffing_throttles; std::vector<std::unique_ptr<ResourceThrottle>> post_mime_sniffing_throttles; for (auto& throttle : throttles) { if (throttle->MustProcessResponseBeforeReadingBody()) { pre_mime_sniffing_throttles.push_back(std::move(throttle)); } else { post_mime_sniffing_throttles.push_back(std::move(throttle)); } } throttles.clear(); // Add the post mime sniffing throttles. handler.reset(new ThrottlingResourceHandler( std::move(handler), request, std::move(post_mime_sniffing_throttles))); if (IsBrowserSideNavigationEnabled() && IsResourceTypeFrame(resource_type)) { DCHECK(navigation_loader_core); DCHECK(stream_handle); // PlzNavigate // Add a NavigationResourceHandler that will control the flow of navigation. handler.reset(new NavigationResourceHandler( request, std::move(handler), navigation_loader_core, delegate(), std::move(stream_handle))); } else { DCHECK(!navigation_loader_core); DCHECK(!stream_handle); } PluginService* plugin_service = nullptr; #if BUILDFLAG(ENABLE_PLUGINS) plugin_service = PluginService::GetInstance(); #endif // Insert a buffered event handler to sniff the mime type. // Note: all ResourceHandler following the MimeSniffingResourceHandler // should expect OnWillRead to be called *before* OnResponseStarted as // part of the mime sniffing process. handler.reset(new MimeSniffingResourceHandler( std::move(handler), this, plugin_service, intercepting_handler, request, fetch_request_context_type)); // Add the pre mime sniffing throttles. handler.reset(new ThrottlingResourceHandler( std::move(handler), request, std::move(pre_mime_sniffing_throttles))); return handler; } void ResourceDispatcherHostImpl::OnReleaseDownloadedFile( ResourceRequesterInfo* requester_info, int request_id) { UnregisterDownloadedTempFile(requester_info->child_id(), request_id); } void ResourceDispatcherHostImpl::OnDidChangePriority( ResourceRequesterInfo* requester_info, int request_id, net::RequestPriority new_priority, int intra_priority_value) { ResourceLoader* loader = GetLoader(requester_info->child_id(), request_id); // The request may go away before processing this message, so |loader| can // legitimately be null. if (!loader) return; scheduler_->ReprioritizeRequest(loader->request(), new_priority, intra_priority_value); } void ResourceDispatcherHostImpl::RegisterDownloadedTempFile( int child_id, int request_id, const base::FilePath& file_path) { scoped_refptr<ShareableFileReference> reference = ShareableFileReference::Get(file_path); DCHECK(reference.get()); registered_temp_files_[child_id][request_id] = reference; ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( child_id, reference->path()); // When the temp file is deleted, revoke permissions that the renderer has // to that file. This covers an edge case where the file is deleted and then // the same name is re-used for some other purpose, we don't want the old // renderer to still have access to it. // // We do this when the file is deleted because the renderer can take a blob // reference to the temp file that outlives the url loaded that it was // loaded with to keep the file (and permissions) alive. reference->AddFinalReleaseCallback( base::Bind(&RemoveDownloadFileFromChildSecurityPolicy, child_id)); } void ResourceDispatcherHostImpl::UnregisterDownloadedTempFile( int child_id, int request_id) { DeletableFilesMap& map = registered_temp_files_[child_id]; DeletableFilesMap::iterator found = map.find(request_id); if (found == map.end()) return; map.erase(found); // Note that we don't remove the security bits here. This will be done // when all file refs are deleted (see RegisterDownloadedTempFile). } bool ResourceDispatcherHostImpl::Send(IPC::Message* message) { delete message; return false; } void ResourceDispatcherHostImpl::OnCancelRequest( ResourceRequesterInfo* requester_info, int request_id) { CancelRequestFromRenderer( GlobalRequestID(requester_info->child_id(), request_id)); } ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo( int child_id, int render_view_route_id, int render_frame_route_id, PreviewsState previews_state, bool download, ResourceContext* context) { return new ResourceRequestInfoImpl( ResourceRequesterInfo::CreateForDownloadOrPageSave(child_id), render_view_route_id, -1, // frame_tree_node_id 0, MakeRequestID(), render_frame_route_id, false, // is_main_frame RESOURCE_TYPE_SUB_RESOURCE, ui::PAGE_TRANSITION_LINK, false, // should_replace_current_entry download, // is_download false, // is_stream download, // allow_download false, // has_user_gesture false, // enable_load_timing false, // enable_upload_progress false, // do_not_prompt_for_login false, // keepalive blink::kWebReferrerPolicyDefault, blink::kWebPageVisibilityStateVisible, context, false, // report_raw_headers true, // is_async previews_state, // previews_state nullptr, // body false); // initiated_in_secure_context } void ResourceDispatcherHostImpl::OnRenderViewHostCreated( int child_id, int route_id, net::URLRequestContextGetter* url_request_context_getter) { scheduler_->OnClientCreated(child_id, route_id, url_request_context_getter->GetURLRequestContext() ->network_quality_estimator()); } void ResourceDispatcherHostImpl::OnRenderViewHostDeleted(int child_id, int route_id) { scheduler_->OnClientDeleted(child_id, route_id); } void ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading(int child_id, int route_id, bool is_loading) { scheduler_->OnLoadingStateChanged(child_id, route_id, !is_loading); } void ResourceDispatcherHostImpl::MarkAsTransferredNavigation( const GlobalRequestID& id, const base::Closure& on_transfer_complete_callback) { GetLoader(id)->MarkAsTransferring(on_transfer_complete_callback); } void ResourceDispatcherHostImpl::ResumeDeferredNavigation( const GlobalRequestID& id) { ResourceLoader* loader = GetLoader(id); // The response we were meant to resume could have already been canceled. if (loader) loader->CompleteTransfer(); } // The object died, so cancel and detach all requests associated with it except // for downloads and detachable resources, which belong to the browser process // even if initiated via a renderer. void ResourceDispatcherHostImpl::CancelRequestsForProcess(int child_id) { CancelRequestsForRoute( GlobalFrameRoutingId(child_id, MSG_ROUTING_NONE /* cancel all */)); registered_temp_files_.erase(child_id); } void ResourceDispatcherHostImpl::CancelRequestsForRoute( const GlobalFrameRoutingId& global_routing_id) { // Since pending_requests_ is a map, we first build up a list of all of the // matching requests to be cancelled, and then we cancel them. Since there // may be more than one request to cancel, we cannot simply hold onto the map // iterators found in the first loop. // Find the global ID of all matching elements. int child_id = global_routing_id.child_id; int route_id = global_routing_id.frame_routing_id; bool cancel_all_routes = (route_id == MSG_ROUTING_NONE); bool any_requests_transferring = false; std::vector<GlobalRequestID> matching_requests; for (const auto& loader : pending_loaders_) { if (loader.first.child_id != child_id) continue; // Added for http://crbug.com/754704; remove when that bug is resolved. loader.second->AssertURLRequestPresent(); ResourceRequestInfoImpl* info = loader.second->GetRequestInfo(); CHECK(info); GlobalRequestID id(child_id, loader.first.request_id); DCHECK(id == loader.first); // Don't cancel navigations that are expected to live beyond this process. if (IsTransferredNavigation(id)) any_requests_transferring = true; if (cancel_all_routes || route_id == info->GetRenderFrameID()) { if (info->detachable_handler()) { if (base::FeatureList::IsEnabled( features::kKeepAliveRendererForKeepaliveRequests) && info->keepalive()) { // If the feature is enabled, the renderer process's lifetime is // prolonged so there's no need to detach. if (cancel_all_routes) { // If the process is going to shut down for other reasons, we need // to cancel the request. matching_requests.push_back(id); } } else { // Otherwise, use DetachableResourceHandler's functionality. info->detachable_handler()->Detach(); } } else if (!info->IsDownload() && !info->is_stream() && !IsTransferredNavigation(id)) { matching_requests.push_back(id); } } } // Remove matches. for (size_t i = 0; i < matching_requests.size(); ++i) { LoaderMap::iterator iter = pending_loaders_.find(matching_requests[i]); // Although every matching request was in pending_requests_ when we built // matching_requests, it is normal for a matching request to be not found // in pending_requests_ after we have removed some matching requests from // pending_requests_. For example, deleting a net::URLRequest that has // exclusive (write) access to an HTTP cache entry may unblock another // net::URLRequest that needs exclusive access to the same cache entry, and // that net::URLRequest may complete and remove itself from // pending_requests_. So we need to check that iter is not equal to // pending_requests_.end(). if (iter != pending_loaders_.end()) RemovePendingLoader(iter); } // Don't clear the blocked loaders or offline policy maps if any of the // requests in route_id are being transferred to a new process, since those // maps will be updated with the new route_id after the transfer. Otherwise // we will lose track of this info when the old route goes away, before the // new one is created. if (any_requests_transferring) return; // Now deal with blocked requests if any. if (!cancel_all_routes) { if (blocked_loaders_map_.find(global_routing_id) != blocked_loaders_map_.end()) { CancelBlockedRequestsForRoute(global_routing_id); } } else { // We have to do all render frames for the process |child_id|. // Note that we have to do this in 2 passes as we cannot call // CancelBlockedRequestsForRoute while iterating over // blocked_loaders_map_, as blocking requests modifies the map. std::set<GlobalFrameRoutingId> routing_ids; for (const auto& blocked_loaders : blocked_loaders_map_) { if (blocked_loaders.first.child_id == child_id) routing_ids.insert(blocked_loaders.first); } for (const GlobalFrameRoutingId& route_id : routing_ids) { CancelBlockedRequestsForRoute(route_id); } } } // Cancels the request and removes it from the list. void ResourceDispatcherHostImpl::RemovePendingRequest(int child_id, int request_id) { LoaderMap::iterator i = pending_loaders_.find( GlobalRequestID(child_id, request_id)); if (i == pending_loaders_.end()) { NOTREACHED() << "Trying to remove a request that's not here"; return; } RemovePendingLoader(i); } void ResourceDispatcherHostImpl::RemovePendingLoader( const LoaderMap::iterator& iter) { ResourceRequestInfoImpl* info = iter->second->GetRequestInfo(); // Remove the memory credit that we added when pushing the request onto // the pending list. IncrementOutstandingRequestsMemory(-1, *info); pending_loaders_.erase(iter); } void ResourceDispatcherHostImpl::CancelRequest(int child_id, int request_id) { ResourceLoader* loader = GetLoader(child_id, request_id); if (!loader) { // We probably want to remove this warning eventually, but I wanted to be // able to notice when this happens during initial development since it // should be rare and may indicate a bug. DVLOG(1) << "Canceling a request that wasn't found"; return; } RemovePendingRequest(child_id, request_id); } ResourceDispatcherHostImpl::OustandingRequestsStats ResourceDispatcherHostImpl::GetOutstandingRequestsStats( const ResourceRequestInfoImpl& info) { OutstandingRequestsStatsMap::iterator entry = outstanding_requests_stats_map_.find(info.GetChildID()); OustandingRequestsStats stats = { 0, 0 }; if (entry != outstanding_requests_stats_map_.end()) stats = entry->second; return stats; } void ResourceDispatcherHostImpl::UpdateOutstandingRequestsStats( const ResourceRequestInfoImpl& info, const OustandingRequestsStats& stats) { if (stats.memory_cost == 0 && stats.num_requests == 0) outstanding_requests_stats_map_.erase(info.GetChildID()); else outstanding_requests_stats_map_[info.GetChildID()] = stats; } void ResourceDispatcherHostImpl::IncrementOutstandingRequestsPerTab( int count, const ResourceRequestInfoImpl& info) { auto key = std::make_pair(info.GetChildID(), info.GetRouteID()); OutstandingRequestsPerTabMap::iterator entry = outstanding_requests_per_tab_map_.insert(std::make_pair(key, 0)).first; entry->second += count; DCHECK_GE(entry->second, 0); if (entry->second == 0) outstanding_requests_per_tab_map_.erase(entry); } ResourceDispatcherHostImpl::OustandingRequestsStats ResourceDispatcherHostImpl::IncrementOutstandingRequestsMemory( int count, const ResourceRequestInfoImpl& info) { DCHECK_EQ(1, abs(count)); // Retrieve the previous value (defaulting to 0 if not found). OustandingRequestsStats stats = GetOutstandingRequestsStats(info); // Insert/update the total; delete entries when their count reaches 0. stats.memory_cost += count * info.memory_cost(); DCHECK_GE(stats.memory_cost, 0); UpdateOutstandingRequestsStats(info, stats); return stats; } ResourceDispatcherHostImpl::OustandingRequestsStats ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount( int count, ResourceRequestInfoImpl* info) { DCHECK_EQ(1, abs(count)); num_in_flight_requests_ += count; // Keep track of whether this request is counting toward the number of // in-flight requests for this process, in case we need to transfer it to // another process. This should be a toggle. DCHECK_NE(info->counted_as_in_flight_request(), count > 0); info->set_counted_as_in_flight_request(count > 0); OustandingRequestsStats stats = GetOutstandingRequestsStats(*info); stats.num_requests += count; DCHECK_GE(stats.num_requests, 0); UpdateOutstandingRequestsStats(*info, stats); IncrementOutstandingRequestsPerTab(count, *info); if (num_in_flight_requests_ > largest_outstanding_request_count_seen_) { largest_outstanding_request_count_seen_ = num_in_flight_requests_; UMA_HISTOGRAM_COUNTS_1M( "Net.ResourceDispatcherHost.OutstandingRequests.Total", largest_outstanding_request_count_seen_); } if (stats.num_requests > largest_outstanding_request_per_process_count_seen_) { largest_outstanding_request_per_process_count_seen_ = stats.num_requests; UMA_HISTOGRAM_COUNTS_1M( "Net.ResourceDispatcherHost.OutstandingRequests.PerProcess", largest_outstanding_request_per_process_count_seen_); } if (num_in_flight_requests_ > peak_outstanding_request_count_) peak_outstanding_request_count_ = num_in_flight_requests_; if (HasRequestsFromMultipleActiveTabs() && num_in_flight_requests_ > peak_outstanding_request_count_multitab_) { peak_outstanding_request_count_multitab_ = num_in_flight_requests_; } return stats; } bool ResourceDispatcherHostImpl::HasSufficientResourcesForRequest( net::URLRequest* request) { ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); OustandingRequestsStats stats = IncrementOutstandingRequestsCount(1, info); if (stats.num_requests > max_num_in_flight_requests_per_process_) return false; if (num_in_flight_requests_ > max_num_in_flight_requests_) return false; return true; } void ResourceDispatcherHostImpl::FinishedWithResourcesForRequest( net::URLRequest* request) { ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); IncrementOutstandingRequestsCount(-1, info); } void ResourceDispatcherHostImpl::BeginNavigationRequest( ResourceContext* resource_context, net::URLRequestContext* request_context, storage::FileSystemContext* upload_file_system_context, const NavigationRequestInfo& info, std::unique_ptr<NavigationUIData> navigation_ui_data, NavigationURLLoaderImplCore* loader, ServiceWorkerNavigationHandleCore* service_worker_handle_core, AppCacheNavigationHandleCore* appcache_handle_core) { // PlzNavigate: BeginNavigationRequest currently should only be used for the // browser-side navigations project. CHECK(IsBrowserSideNavigationEnabled()); ResourceType resource_type = info.is_main_frame ? RESOURCE_TYPE_MAIN_FRAME : RESOURCE_TYPE_SUB_FRAME; // Do not allow browser plugin guests to navigate to non-web URLs, since they // cannot swap processes or grant bindings. Do not check external protocols // here because they're checked in // ChromeResourceDispatcherHostDelegate::HandleExternalProtocol. ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); bool is_external_protocol = info.common_params.url.is_valid() && !resource_context->GetRequestContext()->job_factory()->IsHandledProtocol( info.common_params.url.scheme()); bool non_web_url_in_guest = info.is_for_guests_only && !policy->IsWebSafeScheme(info.common_params.url.scheme()) && !is_external_protocol; if (is_shutdown_ || non_web_url_in_guest || (delegate_ && !delegate_->ShouldBeginRequest( info.common_params.method, info.common_params.url, resource_type, resource_context))) { loader->NotifyRequestFailed(false, net::ERR_ABORTED, base::nullopt, false); return; } int load_flags = info.begin_params.load_flags; load_flags |= net::LOAD_VERIFY_EV_CERT; if (info.is_main_frame) load_flags |= net::LOAD_MAIN_FRAME_DEPRECATED; // TODO(davidben): BuildLoadFlagsForRequest includes logic for // CanSendCookiesForOrigin and CanReadRawCookies. Is this needed here? // Sync loads should have maximum priority and should be the only // requests that have the ignore limits flag set. DCHECK(!(load_flags & net::LOAD_IGNORE_LIMITS)); std::unique_ptr<net::URLRequest> new_request; new_request = request_context->CreateRequest( info.common_params.url, net::HIGHEST, nullptr, kTrafficAnnotation); new_request->set_method(info.common_params.method); new_request->set_site_for_cookies(info.site_for_cookies); new_request->set_initiator(info.begin_params.initiator_origin); if (info.is_main_frame) { new_request->set_first_party_url_policy( net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT); } Referrer::SetReferrerForRequest(new_request.get(), info.common_params.referrer); net::HttpRequestHeaders headers; headers.AddHeadersFromString(info.begin_params.headers); new_request->SetExtraRequestHeaders(headers); new_request->SetLoadFlags(load_flags); storage::BlobStorageContext* blob_context = GetBlobStorageContext( GetChromeBlobStorageContextForResourceContext(resource_context)); // Resolve elements from request_body and prepare upload data. ResourceRequestBody* body = info.common_params.post_data.get(); BlobHandles blob_handles; if (body) { if (!GetBodyBlobDataHandles(body, resource_context, &blob_handles)) { new_request->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES); loader->NotifyRequestFailed(false, net::ERR_ABORTED, base::nullopt, false); return; } new_request->set_upload(UploadDataStreamBuilder::Build( body, blob_context, upload_file_system_context, base::CreateSingleThreadTaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}) .get())); } PreviewsState previews_state = GetPreviewsState(info.common_params.previews_state, delegate_, *new_request, resource_context, info.is_main_frame); // Make extra info and read footer (contains request ID). // // TODO(davidben): Associate the request with the FrameTreeNode and/or tab so // that IO thread -> UI thread hops will work. ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl( ResourceRequesterInfo::CreateForBrowserSideNavigation( service_worker_handle_core ? service_worker_handle_core->context_wrapper() : scoped_refptr<ServiceWorkerContextWrapper>()), -1, // route_id info.frame_tree_node_id, -1, // request_data.origin_pid, MakeRequestID(), -1, // request_data.render_frame_id, info.is_main_frame, resource_type, info.common_params.transition, // should_replace_current_entry. This was only maintained at layer for // request transfers and isn't needed for browser-side navigations. false, false, // is download false, // is stream info.common_params.allow_download, info.begin_params.has_user_gesture, true, // enable_load_timing false, // enable_upload_progress false, // do_not_prompt_for_login false, // keepalive info.common_params.referrer.policy, info.page_visibility_state, resource_context, info.report_raw_headers, true, // is_async previews_state, info.common_params.post_data, // TODO(mek): Currently initiated_in_secure_context is only used for // subresource requests, so it doesn't matter what value it gets here. // If in the future this changes this should be updated to somehow get a // meaningful value. false); // initiated_in_secure_context extra_info->SetBlobHandles(std::move(blob_handles)); extra_info->set_navigation_ui_data(std::move(navigation_ui_data)); // Request takes ownership. extra_info->AssociateWithRequest(new_request.get()); if (new_request->url().SchemeIs(url::kBlobScheme)) { // Hang on to a reference to ensure the blob is not released prior // to the job being started. storage::BlobProtocolHandler::SetRequestedBlobDataHandle( new_request.get(), blob_context->GetBlobDataFromPublicURL(new_request->url())); } RequestContextFrameType frame_type = info.is_main_frame ? REQUEST_CONTEXT_FRAME_TYPE_TOP_LEVEL : REQUEST_CONTEXT_FRAME_TYPE_NESTED; ServiceWorkerRequestHandler::InitializeForNavigation( new_request.get(), service_worker_handle_core, blob_context, info.begin_params.skip_service_worker, resource_type, info.begin_params.request_context_type, frame_type, info.are_ancestors_secure, info.common_params.post_data, extra_info->GetWebContentsGetterForRequest()); // Have the appcache associate its extra info with the request. if (appcache_handle_core) { AppCacheInterceptor::SetExtraRequestInfoForHost( new_request.get(), appcache_handle_core->host(), resource_type, false); } StreamContext* stream_context = GetStreamContextForResourceContext(resource_context); // Note: the stream should be created with immediate mode set to true to // ensure that data read will be flushed to the reader as soon as it's // available. Otherwise, we risk delaying transmitting the body of the // resource to the renderer, which will delay parsing accordingly. std::unique_ptr<ResourceHandler> handler( new StreamResourceHandler(new_request.get(), stream_context->registry(), new_request->url().GetOrigin(), true)); std::unique_ptr<StreamHandle> stream_handle = static_cast<StreamResourceHandler*>(handler.get()) ->stream() ->CreateHandle(); // TODO(davidben): Fix the dependency on child_id/route_id. Those are used // by the ResourceScheduler. currently it's a no-op. handler = AddStandardHandlers( new_request.get(), resource_type, resource_context, info.begin_params.request_context_type, info.begin_params.mixed_content_context_type, appcache_handle_core ? appcache_handle_core->GetAppCacheService() : nullptr, -1, // child_id -1, // route_id std::move(handler), loader, std::move(stream_handle)); BeginRequestInternal(std::move(new_request), std::move(handler)); } void ResourceDispatcherHostImpl::SetLoaderDelegate( LoaderDelegate* loader_delegate) { loader_delegate_ = loader_delegate; } void ResourceDispatcherHostImpl::OnRenderFrameDeleted( const GlobalFrameRoutingId& global_routing_id) { CancelRequestsForRoute(global_routing_id); } void ResourceDispatcherHostImpl::OnRequestResourceWithMojo( ResourceRequesterInfo* requester_info, int32_t routing_id, int32_t request_id, uint32_t options, const ResourceRequest& request, mojom::URLLoaderRequest mojo_request, mojom::URLLoaderClientPtr url_loader_client, const net::NetworkTrafficAnnotationTag& traffic_annotation) { DCHECK_EQ(mojom::kURLLoadOptionNone, options & ~mojom::kURLLoadOptionSynchronous); bool is_sync_load = options & mojom::kURLLoadOptionSynchronous; OnRequestResourceInternal(requester_info, routing_id, request_id, is_sync_load, request, std::move(mojo_request), std::move(url_loader_client), traffic_annotation); } // static int ResourceDispatcherHostImpl::CalculateApproximateMemoryCost( net::URLRequest* request) { // The following fields should be a minor size contribution (experimentally // on the order of 100). However since they are variable length, it could // in theory be a sizeable contribution. int strings_cost = 0; for (net::HttpRequestHeaders::Iterator it(request->extra_request_headers()); it.GetNext();) { strings_cost += it.name().length() + it.value().length(); } strings_cost += request->original_url().parsed_for_possibly_invalid_spec().Length() + request->referrer().size() + request->method().size(); // Note that this expression will typically be dominated by: // |kAvgBytesPerOutstandingRequest|. return kAvgBytesPerOutstandingRequest + strings_cost; } void ResourceDispatcherHostImpl::BeginRequestInternal( std::unique_ptr<net::URLRequest> request, std::unique_ptr<ResourceHandler> handler) { DCHECK(!request->is_pending()); ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request.get()); // Log metrics for back-forward navigations. // TODO(clamy): Remove this once we understand the reason behind the // back-forward PLT regression with PlzNavigate if ((info->GetPageTransition() & ui::PAGE_TRANSITION_FORWARD_BACK) && IsResourceTypeFrame(info->GetResourceType()) && request->url().SchemeIsHTTPOrHTTPS()) { LogBackForwardNavigationFlagsHistogram(request->load_flags()); } if ((TimeTicks::Now() - last_user_gesture_time_) < TimeDelta::FromMilliseconds(kUserGestureWindowMs)) { request->SetLoadFlags(request->load_flags() | net::LOAD_MAYBE_USER_GESTURE); } // Add the memory estimate that starting this request will consume. info->set_memory_cost(CalculateApproximateMemoryCost(request.get())); // If enqueing/starting this request will exceed our per-process memory // bound, abort it right away. OustandingRequestsStats stats = IncrementOutstandingRequestsMemory(1, *info); if (stats.memory_cost > max_outstanding_requests_cost_per_process_) { // We call "CancelWithError()" as a way of setting the net::URLRequest's // status -- it has no effect beyond this, since the request hasn't started. request->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES); bool was_resumed = false; // TODO(mmenke): Get rid of NullResourceController and do something more // reasonable. handler->OnResponseCompleted( request->status(), base::MakeUnique<NullResourceController>(&was_resumed)); // TODO(darin): The handler is not ready for us to kill the request. Oops! DCHECK(was_resumed); IncrementOutstandingRequestsMemory(-1, *info); // A ResourceHandler must not outlive its associated URLRequest. handler.reset(); return; } std::unique_ptr<ResourceLoader> loader(new ResourceLoader( std::move(request), std::move(handler), this)); GlobalFrameRoutingId id(info->GetChildID(), info->GetRenderFrameID()); BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.find(id); if (iter != blocked_loaders_map_.end()) { // The request should be blocked. iter->second->push_back(std::move(loader)); return; } StartLoading(info, std::move(loader)); } void ResourceDispatcherHostImpl::InitializeURLRequest( net::URLRequest* request, const Referrer& referrer, bool is_download, int render_process_host_id, int render_view_routing_id, int render_frame_routing_id, PreviewsState previews_state, ResourceContext* context) { DCHECK(io_thread_task_runner_->BelongsToCurrentThread()); DCHECK(!request->is_pending()); Referrer::SetReferrerForRequest(request, referrer); ResourceRequestInfoImpl* info = CreateRequestInfo( render_process_host_id, render_view_routing_id, render_frame_routing_id, previews_state, is_download, context); // Request takes ownership. info->AssociateWithRequest(request); } void ResourceDispatcherHostImpl::BeginURLRequest( std::unique_ptr<net::URLRequest> request, std::unique_ptr<ResourceHandler> handler, bool is_download, bool is_content_initiated, bool do_not_prompt_for_login, ResourceContext* context) { DCHECK(io_thread_task_runner_->BelongsToCurrentThread()); DCHECK(!request->is_pending()); ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request.get()); DCHECK(info); info->set_do_not_prompt_for_login(do_not_prompt_for_login); // TODO(ananta) // Find a better place for notifying the delegate about the download start. if (is_download && delegate()) { // TODO(ananta) // Investigate whether the blob logic should apply for the SaveAs case and // if yes then move the code below outside the if block. if (request->original_url().SchemeIs(url::kBlobScheme) && !storage::BlobProtocolHandler::GetRequestBlobDataHandle( request.get())) { ChromeBlobStorageContext* blob_context = GetChromeBlobStorageContextForResourceContext(context); storage::BlobProtocolHandler::SetRequestedBlobDataHandle( request.get(), blob_context->context()->GetBlobDataFromPublicURL( request->original_url())); } handler = HandleDownloadStarted( request.get(), std::move(handler), is_content_initiated, true /* force_download */, true /* is_new_request */); } BeginRequestInternal(std::move(request), std::move(handler)); } int ResourceDispatcherHostImpl::MakeRequestID() { DCHECK(io_thread_task_runner_->BelongsToCurrentThread()); return --request_id_; } void ResourceDispatcherHostImpl::CancelRequestFromRenderer( GlobalRequestID request_id) { // When the old renderer dies, it sends a message to us to cancel its // requests. if (IsTransferredNavigation(request_id)) return; ResourceLoader* loader = GetLoader(request_id); // It is possible that the request has been completed and removed from the // loader queue but the client has not processed the request completed message // before issuing a cancel. This happens frequently for beacons which are // canceled in the response received handler. if (!loader) return; loader->CancelRequest(true); } void ResourceDispatcherHostImpl::StartLoading( ResourceRequestInfoImpl* info, std::unique_ptr<ResourceLoader> loader) { ResourceLoader* loader_ptr = loader.get(); DCHECK(pending_loaders_[info->GetGlobalRequestID()] == nullptr); pending_loaders_[info->GetGlobalRequestID()] = std::move(loader); loader_ptr->StartRequest(); } void ResourceDispatcherHostImpl::OnUserGesture() { last_user_gesture_time_ = TimeTicks::Now(); } net::URLRequest* ResourceDispatcherHostImpl::GetURLRequest( const GlobalRequestID& id) { ResourceLoader* loader = GetLoader(id); if (!loader) return NULL; return loader->request(); } // static bool ResourceDispatcherHostImpl::LoadInfoIsMoreInteresting(const LoadInfo& a, const LoadInfo& b) { // Set |*_uploading_size| to be the size of the corresponding upload body if // it's currently being uploaded. uint64_t a_uploading_size = 0; if (a.load_state.state == net::LOAD_STATE_SENDING_REQUEST) a_uploading_size = a.upload_size; uint64_t b_uploading_size = 0; if (b.load_state.state == net::LOAD_STATE_SENDING_REQUEST) b_uploading_size = b.upload_size; if (a_uploading_size != b_uploading_size) return a_uploading_size > b_uploading_size; return a.load_state.state > b.load_state.state; } // static void ResourceDispatcherHostImpl::UpdateLoadStateOnUI( LoaderDelegate* loader_delegate, std::unique_ptr<LoadInfoList> infos) { DCHECK(Get()->main_thread_task_runner_->BelongsToCurrentThread()); std::unique_ptr<LoadInfoMap> info_map = PickMoreInterestingLoadInfos(std::move(infos)); for (const auto& load_info: *info_map) { loader_delegate->LoadStateChanged( load_info.first, load_info.second.url, load_info.second.load_state, load_info.second.upload_position, load_info.second.upload_size); } } // static std::unique_ptr<ResourceDispatcherHostImpl::LoadInfoMap> ResourceDispatcherHostImpl::PickMoreInterestingLoadInfos( std::unique_ptr<LoadInfoList> infos) { std::unique_ptr<LoadInfoMap> info_map(new LoadInfoMap); for (const auto& load_info : *infos) { WebContents* web_contents = load_info.web_contents_getter.Run(); if (!web_contents) continue; auto existing = info_map->find(web_contents); if (existing == info_map->end() || LoadInfoIsMoreInteresting(load_info, existing->second)) { (*info_map)[web_contents] = load_info; } } return info_map; } std::unique_ptr<ResourceDispatcherHostImpl::LoadInfoList> ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes() { std::unique_ptr<LoadInfoList> infos(new LoadInfoList); for (const auto& loader : pending_loaders_) { net::URLRequest* request = loader.second->request(); net::UploadProgress upload_progress = request->GetUploadProgress(); LoadInfo load_info; load_info.web_contents_getter = loader.second->GetRequestInfo()->GetWebContentsGetterForRequest(); load_info.url = request->url(); load_info.load_state = request->GetLoadState(); load_info.upload_size = upload_progress.size(); load_info.upload_position = upload_progress.position(); infos->push_back(load_info); } return infos; } void ResourceDispatcherHostImpl::UpdateLoadInfo() { std::unique_ptr<LoadInfoList> infos(GetLoadInfoForAllRoutes()); // Stop the timer if there are no more pending requests. Future new requests // will restart it as necessary. // Also stop the timer if there are no loading clients, to avoid waking up // unnecessarily when there is a long running (hanging get) request. if (infos->empty() || !scheduler_->HasLoadingClients()) { update_load_states_timer_->Stop(); return; } // We need to be able to compare all requests to find the most important one // per tab. Since some requests may be navigation requests and we don't have // their render frame routing IDs yet (which is what we have for subresource // requests), we must go to the UI thread and compare the requests using their // WebContents. main_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(UpdateLoadStateOnUI, loader_delegate_, base::Passed(&infos))); } void ResourceDispatcherHostImpl::RecordOutstandingRequestsStats() { if (peak_outstanding_request_count_ != 0) { UMA_HISTOGRAM_COUNTS_1M( "Net.ResourceDispatcherHost.PeakOutstandingRequests", peak_outstanding_request_count_); peak_outstanding_request_count_ = num_in_flight_requests_; } if (peak_outstanding_request_count_multitab_ != 0) { UMA_HISTOGRAM_COUNTS_1M( "Net.ResourceDispatcherHost.PeakOutstandingRequests.MultiTabLoading", peak_outstanding_request_count_multitab_); peak_outstanding_request_count_multitab_ = HasRequestsFromMultipleActiveTabs() ? num_in_flight_requests_ : 0; } } void ResourceDispatcherHostImpl::BlockRequestsForRoute( const GlobalFrameRoutingId& global_routing_id) { DCHECK(io_thread_task_runner_->BelongsToCurrentThread()); DCHECK(blocked_loaders_map_.find(global_routing_id) == blocked_loaders_map_.end()) << "BlockRequestsForRoute called multiple time for the same RFH"; blocked_loaders_map_[global_routing_id] = base::MakeUnique<BlockedLoadersList>(); } void ResourceDispatcherHostImpl::ResumeBlockedRequestsForRoute( const GlobalFrameRoutingId& global_routing_id) { ProcessBlockedRequestsForRoute(global_routing_id, false); } void ResourceDispatcherHostImpl::CancelBlockedRequestsForRoute( const GlobalFrameRoutingId& global_routing_id) { ProcessBlockedRequestsForRoute(global_routing_id, true); } void ResourceDispatcherHostImpl::ProcessBlockedRequestsForRoute( const GlobalFrameRoutingId& global_routing_id, bool cancel_requests) { BlockedLoadersMap::iterator iter = blocked_loaders_map_.find(global_routing_id); if (iter == blocked_loaders_map_.end()) { // It's possible to reach here if the renderer crashed while an interstitial // page was showing. return; } BlockedLoadersList* loaders = iter->second.get(); std::unique_ptr<BlockedLoadersList> deleter(std::move(iter->second)); // Removing the vector from the map unblocks any subsequent requests. blocked_loaders_map_.erase(iter); for (std::unique_ptr<ResourceLoader>& loader : *loaders) { ResourceRequestInfoImpl* info = loader->GetRequestInfo(); if (cancel_requests) { IncrementOutstandingRequestsMemory(-1, *info); } else { StartLoading(info, std::move(loader)); } } } ResourceDispatcherHostImpl::HttpAuthRelationType ResourceDispatcherHostImpl::HttpAuthRelationTypeOf( const GURL& request_url, const GURL& first_party) { if (!first_party.is_valid()) return HTTP_AUTH_RELATION_TOP; if (net::registry_controlled_domains::SameDomainOrHost( first_party, request_url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) return HTTP_AUTH_RELATION_SAME_DOMAIN; if (allow_cross_origin_auth_prompt()) return HTTP_AUTH_RELATION_ALLOWED_CROSS; return HTTP_AUTH_RELATION_BLOCKED_CROSS; } bool ResourceDispatcherHostImpl::allow_cross_origin_auth_prompt() { return allow_cross_origin_auth_prompt_; } bool ResourceDispatcherHostImpl::IsTransferredNavigation( const GlobalRequestID& id) const { ResourceLoader* loader = GetLoader(id); return loader ? loader->is_transferring() : false; } ResourceLoader* ResourceDispatcherHostImpl::GetLoader( const GlobalRequestID& id) const { DCHECK(io_thread_task_runner_->BelongsToCurrentThread()); LoaderMap::const_iterator i = pending_loaders_.find(id); if (i == pending_loaders_.end()) return NULL; return i->second.get(); } ResourceLoader* ResourceDispatcherHostImpl::GetLoader(int child_id, int request_id) const { return GetLoader(GlobalRequestID(child_id, request_id)); } void ResourceDispatcherHostImpl::RegisterResourceMessageDelegate( const GlobalRequestID& id, ResourceMessageDelegate* delegate) { DelegateMap::iterator it = delegate_map_.find(id); if (it == delegate_map_.end()) { it = delegate_map_.insert( std::make_pair( id, new base::ObserverList<ResourceMessageDelegate>)) .first; } it->second->AddObserver(delegate); } void ResourceDispatcherHostImpl::UnregisterResourceMessageDelegate( const GlobalRequestID& id, ResourceMessageDelegate* delegate) { DCHECK(base::ContainsKey(delegate_map_, id)); DelegateMap::iterator it = delegate_map_.find(id); DCHECK(it->second->HasObserver(delegate)); it->second->RemoveObserver(delegate); if (!it->second->might_have_observers()) { delete it->second; delegate_map_.erase(it); } } int ResourceDispatcherHostImpl::BuildLoadFlagsForRequest( const ResourceRequest& request_data, bool is_sync_load) { int load_flags = request_data.load_flags; // Although EV status is irrelevant to sub-frames and sub-resources, we have // to perform EV certificate verification on all resources because an HTTP // keep-alive connection created to load a sub-frame or a sub-resource could // be reused to load a main frame. load_flags |= net::LOAD_VERIFY_EV_CERT; if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) { load_flags |= net::LOAD_MAIN_FRAME_DEPRECATED; } else if (request_data.resource_type == RESOURCE_TYPE_PREFETCH) { load_flags |= net::LOAD_PREFETCH; } if (is_sync_load) load_flags |= net::LOAD_IGNORE_LIMITS; return load_flags; } bool ResourceDispatcherHostImpl::ShouldServiceRequest( int child_id, const ResourceRequest& request_data, const net::HttpRequestHeaders& headers, ResourceRequesterInfo* requester_info, ResourceContext* resource_context) { ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); bool is_navigation_stream_request = IsBrowserSideNavigationEnabled() && IsResourceTypeFrame(request_data.resource_type); // Check if the renderer is permitted to request the requested URL. // PlzNavigate: no need to check the URL here. The browser already picked the // right renderer to send the request to. The original URL isn't used, as the // renderer is fetching the stream URL. Checking the original URL doesn't work // in case of redirects across schemes, since the original URL might not be // granted to the final URL's renderer. if (!is_navigation_stream_request && !policy->CanRequestURL(child_id, request_data.url)) { VLOG(1) << "Denied unauthorized request for " << request_data.url.possibly_invalid_spec(); return false; } // Check if the renderer is using an illegal Origin header. If so, kill it. std::string origin_string; bool has_origin = headers.GetHeader("Origin", &origin_string) && origin_string != "null"; if (has_origin) { GURL origin(origin_string); if (!policy->CanSetAsOriginHeader(child_id, origin)) { VLOG(1) << "Killed renderer for illegal origin: " << origin_string; bad_message::ReceivedBadMessage(requester_info->filter(), bad_message::RDH_ILLEGAL_ORIGIN); return false; } } // Check if the renderer is permitted to upload the requested files. if (!policy->CanReadRequestBody(child_id, requester_info->file_system_context(), request_data.request_body)) { NOTREACHED() << "Denied unauthorized upload"; return false; } return true; } std::unique_ptr<ResourceHandler> ResourceDispatcherHostImpl::HandleDownloadStarted( net::URLRequest* request, std::unique_ptr<ResourceHandler> handler, bool is_content_initiated, bool must_download, bool is_new_request) { if (delegate()) { const ResourceRequestInfoImpl* request_info( ResourceRequestInfoImpl::ForRequest(request)); std::vector<std::unique_ptr<ResourceThrottle>> throttles; delegate()->DownloadStarting(request, request_info->GetContext(), is_content_initiated, true, is_new_request, &throttles); if (!throttles.empty()) { handler.reset(new ThrottlingResourceHandler(std::move(handler), request, std::move(throttles))); } } return handler; } bool ResourceDispatcherHostImpl::HasRequestsFromMultipleActiveTabs() { if (outstanding_requests_per_tab_map_.size() < 2) return false; int active_tabs = 0; for (auto iter = outstanding_requests_per_tab_map_.begin(); iter != outstanding_requests_per_tab_map_.end(); ++iter) { if (iter->second > 2) { active_tabs++; if (active_tabs >= 2) return true; } } return false; } } // namespace content
[ "RetZero@desktop" ]
RetZero@desktop
1516b2c4d6a3c8f20a16624268688cf0664f7d01
f3fde434ef4ed897ca706c87247fd251a6cf5575
/codechef/launchtime_june20/incrdec.cpp
b8fb3a3281f98dca6a32246d67f9c7777aed27ee
[]
no_license
sabkabaap1/competitive-programming
1ada55b8747e256fedb1a028754206d079fb78fc
a881a7d18f4ffda36ee799e50e8092a0a29fadfd
refs/heads/master
2022-11-11T18:08:40.435908
2020-07-03T11:06:27
2020-07-03T11:06:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
865
cpp
/* PROBLEM LINK:> #include "macro.h" #include <iostream> #include <bits/stdc++.h> #include "../../macro.h" */ #include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin>>t; while(t--){ int n; cin>>n; int arr[n]; for(int i=0; i<n; i++) cin>>arr[i]; sort(arr, arr+n); int res[n] = {0}; int i=0, k=0; while(i<n){ res[k++] = arr[i]; i+=2; } if(i-2==n-1) i = n-2; else i = n-1; while(i>=0){ res[k++] = arr[i]; i-=2; } // checking for no case i=0; int flag=1; while(i+1<n){ if(res[i]==res[i+1]){ flag=0; break; } i+=1; } if(flag){ cout<<"YES\n"; for(int i=0; i<n; i++) cout<<res[i]<<" "; cout<<"\n"; } else{ cout<<"NO\n"; } } return 0; }
[ "replituser@example.com" ]
replituser@example.com
0e91b25969e357237033b0dbc18d4d0a61a67ce2
e3ebf4e00fa30086821843b5b04fced69aa35353
/краскал.cpp
02da65a487db7ef0d5f672a1e83c9cc84f3d1c62
[]
no_license
DisaDisa/school_codes
3729c3fe1b08d0668a0ffcbcb058be0bbd4c3899
e79e0fde408c7c2c9c8a0b9590ffba65e63f6f97
refs/heads/master
2020-04-05T08:26:33.941312
2018-11-08T13:07:41
2018-11-08T13:07:41
156,715,865
0
0
null
null
null
null
UTF-8
C++
false
false
1,395
cpp
#include <fstream> #include <cstdio> #include <cstdlib> #include <string> #include <vector> #include <set> #include <algorithm> #include <iomanip> #include <map> #include <cmath> #include <queue> using namespace std; #pragma comment (linker, "/STACK:64000000") typedef long long ll; #if _DEBUG ifstream cin ("input.txt"); ofstream cout("output.txt"); #else ifstream cin ("oil.in"); ofstream cout("oil.out"); #endif struct str { int from, to, w; bool operator < (const str x) const { if(w < x.w) return true; return false; } }; vector <str> s; const int maxx = 20000; int parent[maxx + 2], size[maxx + 2]; int find_set(int v) { if(v == parent[v]) return v; return parent[v] = find_set(parent[v]); } void make_set (int v) { parent[v] = v; size[v] = 1; } int ans = 0; void union_set (int a,int b, int w) { a = find_set(a); b = find_set(b); if(a != b) { if(size[a] < size[b]) swap(a, b); parent[b] = a; size[a] += size[b]; ans = max(w, ans); } } int main() { int n, m; cin >> n >> m; for(int i = 0; i < m; i++) { int x, y, z; cin >> x >> y >> z; str q; q.from = x; q.to = y; q.w = z; s.push_back(q); q.from = y; q.to = x; s.push_back(q); } for(int i = 1; i <= n; i++) { make_set(i); } sort(s.begin(), s.end()); for(int i = 0; i < s.size(); i++) { union_set(s[i].from, s[i].to, s[i].w); } cout << ans; return 0; }
[ "denisarhipov97@gmail.com" ]
denisarhipov97@gmail.com
eed0b4e5995e46e162010a5c61f0f1adf95c2d2a
120cfe04c3123d6ddf7982c2b53304d41a92635a
/MapleStory/MapleStory/Power_Elixir.h
5ac1bf072e0203a1a1c85f5da308975ce62c7bd0
[]
no_license
chominju/MapleStory
d5ba0edfda71a8ff29265f0abae0c2de17b2fac7
be52e4f007a908edd47ceb02650cda8e6244e4e9
refs/heads/master
2023-05-15T02:03:54.658221
2021-06-03T13:12:09
2021-06-03T13:12:09
365,113,563
0
0
null
null
null
null
UHC
C++
false
false
433
h
#pragma once #include "Item.h" class CPower_Elixir : public CItem { private: explicit CPower_Elixir(); public: virtual ~CPower_Elixir(); // CGameObject을(를) 통해 상속됨 virtual int Ready_GameObject() override; virtual void Late_Update_GameObject() override; virtual void Release_GameObject() override; static CGameObject * Create(float posX, float posY); static CItem * Create(); virtual int Get_ItemInfoHp(); };
[ "colorday3908@gmail.com" ]
colorday3908@gmail.com
9c43495d790a9b0294f1dfee1906141a08572006
4e90a7d75fb3be1cf27a857347b85af174affe31
/ds8.cpp
1a47cfe1023a624273e9aa950419f280f338a2b8
[]
no_license
jayantawasthi575/dsalgo450
a5fb60c11d2013cf64bb44acb99c50a12ef0b6e3
1c4d0b2cd8bd3aa883668e19e0a2eb1b0a84952f
refs/heads/master
2023-08-31T06:39:00.114795
2021-10-10T17:49:01
2021-10-10T17:49:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
711
cpp
class Solution{ public: // arr: input array // n: size of array //Function to find the sum of contiguous subarray with maximum sum. int maxSubarraySum(int arr[], int n){ int max=0; int cur=0; int l=0; for(int i=0;i<n;i++) { if(arr[i]<0) { l++; } cur=cur+arr[i]; if(cur>max) { max=cur; } if(cur<0) { cur=0; } } if(l==n) { max=arr[0]; cur=arr[0]; for(int j=1;j<n;j++) { cur=cur+arr[j]; if(cur>max) { max=cur; } } } return max; } };
[ "jayantawasthi5@gmail.com" ]
jayantawasthi5@gmail.com
338891154f3b585ac99a0df6cf5efbf61984648b
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-sso/source/SSOErrorMarshaller.cpp
702ee8c979130d0a009e84caf07acaa67c8964fb
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
586
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/core/client/AWSError.h> #include <aws/sso/SSOErrorMarshaller.h> #include <aws/sso/SSOErrors.h> using namespace Aws::Client; using namespace Aws::SSO; AWSError<CoreErrors> SSOErrorMarshaller::FindErrorByName(const char* errorName) const { AWSError<CoreErrors> error = SSOErrorMapper::GetErrorForName(errorName); if(error.GetErrorType() != CoreErrors::UNKNOWN) { return error; } return AWSErrorMarshaller::FindErrorByName(errorName); }
[ "sdavtaker@users.noreply.github.com" ]
sdavtaker@users.noreply.github.com
5b3ff65d2e217cbbc2fb2b5a6ad50f5121a7de2f
24bc4990e9d0bef6a42a6f86dc783785b10dbd42
/chrome/browser/ui/views/tabs/compound_tab_container.h
9875950438fac9ca56c29fdf9f230b45275733e0
[ "BSD-3-Clause" ]
permissive
nwjs/chromium.src
7736ce86a9a0b810449a3b80a4af15de9ef9115d
454f26d09b2f6204c096b47f778705eab1e3ba46
refs/heads/nw75
2023-08-31T08:01:39.796085
2023-04-19T17:25:53
2023-04-19T17:25:53
50,512,158
161
201
BSD-3-Clause
2023-05-08T03:19:09
2016-01-27T14:17:03
null
UTF-8
C++
false
false
10,561
h
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_TABS_COMPOUND_TAB_CONTAINER_H_ #define CHROME_BROWSER_UI_VIEWS_TABS_COMPOUND_TAB_CONTAINER_H_ #include <memory> #include "base/memory/raw_ptr.h" #include "chrome/browser/ui/views/tabs/tab_container.h" #include "chrome/browser/ui/views/tabs/tab_container_controller.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/gfx/geometry/point.h" #include "ui/views/view_targeter_delegate.h" class TabHoverCardController; class TabDragContextBase; // Composes two TabContainers into one, keeping the pinned tabs in one container // and the unpinned tabs in the other. // Indices in the public and private API are all in overall indices, unless // specifically noted otherwise as being relative to a specific container. class CompoundTabContainer : public TabContainer, public views::ViewTargeterDelegate { public: METADATA_HEADER(CompoundTabContainer); CompoundTabContainer(raw_ref<TabContainerController> controller, TabHoverCardController* hover_card_controller, TabDragContextBase* drag_context, TabSlotController& tab_slot_controller, views::View* scroll_contents_view); ~CompoundTabContainer() override; // TabContainer: void SetAvailableWidthCallback( base::RepeatingCallback<int()> available_width_callback) override; Tab* AddTab(std::unique_ptr<Tab> tab, int model_index, TabPinned pinned) override; void MoveTab(int from_model_index, int to_model_index) override; void RemoveTab(int index, bool was_active) override; void SetTabPinned(int model_index, TabPinned pinned) override; void SetActiveTab(absl::optional<size_t> prev_active_index, absl::optional<size_t> new_active_index) override; Tab* RemoveTabFromViewModel(int model_index) override; Tab* AddTabToViewModel(Tab* tab, int model_index, TabPinned pinned) override; void ReturnTabSlotView(TabSlotView* view) override; void ScrollTabToVisible(int model_index) override; void ScrollTabContainerByOffset(int offset) override; void OnGroupCreated(const tab_groups::TabGroupId& group) override; void OnGroupEditorOpened(const tab_groups::TabGroupId& group) override; void OnGroupMoved(const tab_groups::TabGroupId& group) override; void OnGroupContentsChanged(const tab_groups::TabGroupId& group) override; void OnGroupVisualsChanged( const tab_groups::TabGroupId& group, const tab_groups::TabGroupVisualData* old_visuals, const tab_groups::TabGroupVisualData* new_visuals) override; void OnGroupClosed(const tab_groups::TabGroupId& group) override; void ToggleTabGroup(const tab_groups::TabGroupId& group, bool is_collapsing, ToggleTabGroupCollapsedStateOrigin origin) override; void UpdateTabGroupVisuals(tab_groups::TabGroupId group_id) override; void NotifyTabGroupEditorBubbleOpened() override; void NotifyTabGroupEditorBubbleClosed() override; absl::optional<int> GetModelIndexOf( const TabSlotView* slot_view) const override; Tab* GetTabAtModelIndex(int index) const override; int GetTabCount() const override; absl::optional<int> GetModelIndexOfFirstNonClosingTab( Tab* tab) const override; void UpdateHoverCard( Tab* tab, TabSlotController::HoverCardUpdateType update_type) override; void HandleLongTap(ui::GestureEvent* event) override; bool IsRectInContentArea(const gfx::Rect& rect) override; absl::optional<ZOrderableTabContainerElement> GetLeadingElementForZOrdering() const override; absl::optional<ZOrderableTabContainerElement> GetTrailingElementForZOrdering() const override; void OnTabSlotAnimationProgressed(TabSlotView* view) override; void OnTabCloseAnimationCompleted(Tab* tab) override; void InvalidateIdealBounds() override; void AnimateToIdealBounds() override; bool IsAnimating() const override; void CancelAnimation() override; void CompleteAnimationAndLayout() override; int GetAvailableWidthForTabContainer() const override; void EnterTabClosingMode(absl::optional<int> override_width, CloseTabSource source) override; void ExitTabClosingMode() override; void SetTabSlotVisibility() override; bool InTabClose() override; TabGroupViews* GetGroupViews(tab_groups::TabGroupId group_id) const override; const std::map<tab_groups::TabGroupId, std::unique_ptr<TabGroupViews>>& get_group_views_for_testing() const override; int GetActiveTabWidth() const override; int GetInactiveTabWidth() const override; gfx::Rect GetIdealBounds(int model_index) const override; gfx::Rect GetIdealBounds(tab_groups::TabGroupId group) const override; // views::View gfx::Size GetMinimumSize() const override; views::SizeBounds GetAvailableSize(const View* child) const override; gfx::Size CalculatePreferredSize() const override; views::View* GetTooltipHandlerForPoint(const gfx::Point& point) override; void Layout() override; void PaintChildren(const views::PaintInfo& paint_info) override; void ChildPreferredSizeChanged(views::View* child) override; // BrowserRootView::DropTarget: BrowserRootView::DropIndex GetDropIndex( const ui::DropTargetEvent& event) override; BrowserRootView::DropTarget* GetDropTarget( gfx::Point loc_in_local_coords) override; views::View* GetViewForDrop() override; void HandleDragUpdate( const absl::optional<BrowserRootView::DropIndex>& index) override; void HandleDragExited() override; // views::ViewTargeterDelegate: views::View* TargetForRect(views::View* root, const gfx::Rect& rect) override; // Notifies this CompoundTabContainer that `tab_slot_view` must be animated to // `target_bounds`. `pinned` indicates whether these bounds are relative to // `pinned_tab_container_` or `unpinned_tab_container_`. void UpdateAnimationTarget(TabSlotView* tab_slot_view, gfx::Rect target_bounds, TabPinned pinned); private: int NumPinnedTabs() const; // Returns true iff `index` is a valid index in the joint viewmodel index // space of the two TabContainers, i.e. if there's a Tab view that corresponds // to `index`. These index spaces are different when the model has added or // removed a tab but we haven't finished processing that change ourselves. bool IsValidViewModelIndex(int index) const; // Moves the tab at `from_model_index` from whichever TabContainer currently // holds it into the other TabContainer, inserting it into that container at // the index that corresponds to `to_model_index`. void TransferTabBetweenContainers(int from_model_index, int to_model_index); // Converts `ideal_bounds` from `unpinned_tab_container_`'s coordinate space // into local coordinate space. References ideal bounds instead of current // bounds to correctly account for any ongoing animations in the pinned tab // container. gfx::Rect ConvertUnpinnedContainerIdealBoundsToLocal( gfx::Rect ideal_bounds) const; // Animates `tab` to `ideal_bounds` using `bounds_animator_`. Retargets an // existing animation if one is already running. void AnimateTabTo(Tab* tab, gfx::Rect ideal_bounds); // Returns the child TabContainer that should contain `view`. NB this can be // different from `view->parent()` e.g. while `view` is being dragged. raw_ref<TabContainer> GetTabContainerFor(TabSlotView* view) const; // Returns the child TabContainer that should handle text drag and drop events // at `point_in_local_coords`. TabContainer* GetTabContainerForDrop(gfx::Point point_in_local_coords) const; // Returns the child TabContainer that contains `point_in_local_coords`, or // nullptr if neither contain it. If both contain it, chooses based on where // `point_in_local_coords` is within the overlap area. TabContainer* GetTabContainerAt(gfx::Point point_in_local_coords) const; // Returns the x position that `unpinned_tab_container_` should be at after // any running animations finish. int GetUnpinnedContainerIdealLeadingX() const; int GetAvailableWidthForUnpinnedTabContainer() const; // Computes the size of this compound container assuming the pinned and // unpinned containers have the given sizes. gfx::Size GetCombinedSizeForTabContainerSizes(gfx::Size pinned_size, gfx::Size unpinned_size) const; // Private getter to retrieve the visible rect of the scroll container. absl::optional<gfx::Rect> GetVisibleContentRect() const; // Animates and scrolls the tab container from the start_edge to the // target_edge. If the target_edge is beyond the tab strip it will be clamped // bounds of the tabstrip. void AnimateScrollToShowXCoordinate(const int start_edge, const int target_edge); const raw_ref<TabContainerController> controller_; // Adapts `pinned_tab_container_`'s interactions with the model to account for // it only holding pinned tabs. const std::unique_ptr<TabContainerController> pinned_tab_container_controller_; // The TabContainer that holds the pinned tabs. const raw_ref<TabContainer> pinned_tab_container_; // Adapts `unpinned_tab_container_`'s interactions with the model to account // for it only holding unpinned tabs. const std::unique_ptr<TabContainerController> unpinned_tab_container_controller_; // The TabContainer that holds the unpinned tabs. const raw_ref<TabContainer> unpinned_tab_container_; base::RepeatingCallback<int()> available_width_callback_; const raw_ptr<TabHoverCardController, DanglingUntriaged> hover_card_controller_; // The View that is to be scrolled by |tab_scrolling_animation_|. May be // nullptr in tests. const raw_ptr<views::View> scroll_contents_view_; // Responsible for animating the scroll of the tab container. std::unique_ptr<gfx::LinearAnimation> tab_scrolling_animation_; // Animates tabs between pinned and unpinned states. views::BoundsAnimator bounds_animator_; // The sub-container that handled the last drag/drop update, if any. Used to // ensure HandleDragExited is called when necessary. raw_ptr<TabContainer> current_text_drop_target_ = nullptr; }; #endif // CHROME_BROWSER_UI_VIEWS_TABS_COMPOUND_TAB_CONTAINER_H_
[ "roger@nwjs.io" ]
roger@nwjs.io
d2a8d3b5c7b5c6aa9d8b873b74b5e448f3db59ec
b32fa3fc321c82dbcc28d0fa1c2526202ef5f929
/Modeling_tool/asmodeling-10/test/image/PFMImage.h
7bb51ab03176f56d8977bc8893d97cf48e18a118
[]
no_license
BaiGang/codeplex-archived-vrthesis-2010
ce43246029acc3079d92c1e594dc6ea5194e5c2a
b06b45f50491a76feca4363faeef4da51cf143a7
refs/heads/master
2020-12-30T16:48:03.962166
2012-10-01T21:49:39
2012-10-01T21:49:39
91,037,422
0
0
null
null
null
null
GB18030
C++
false
false
1,537
h
/******************************************************************** created: 2007/06/18 created: 18:6:2007 21:27 filename: J:\HuYong\SVBRDF\CommonTools\image\PFMImage.h file path: J:\HuYong\SVBRDF\CommonTools\image file base: PFMImage file ext: h author: HuYong purpose: Portable Float Map 文件 *********************************************************************/ #pragma once #include "image.h" class PFMImage : public Image { public: //拷贝构造函数 PFMImage(const PFMImage& pfmImage); //赋值函数 PFMImage& operator=(const PFMImage& pfmImage); //pfmType为0时代表grayscale,其余代表color PFMImage(int width, int height, int pfmType, float* pixel); PFMImage(int type);//type为0代表单通道,为1代表3通道 virtual ~PFMImage(void); //u代表横坐标,v代表纵坐标,图像左上角为(0,0)点,v从上到下,u从左到右,与HDRShop中相同 virtual PixelFormat GetPixel(int u, int v) const; virtual bool ReadImage(const char *strFileName); virtual bool WriteImage(const char *strFileName); //传入的数据必须为RGB3通道值 void SetPixelData(const float* pixel, int width, int height); float* GetPixelDataBuffer(void); virtual void SetPixel(int u, int v, PixelFormat pf); virtual void ClearImage(void); private: bool WriteToGrayscalePFM(const char *strFileName); bool WriteToColorPFM(const char *strFileName); private: float* m_pPixel; int m_type;//m_type为0时代表grayscale,其余代表color, };
[ "SND\\papagessy_cp" ]
SND\papagessy_cp
2a11ce5cd34fde579b26f215568ab188dc45f5f5
e59a173cecfc497b7087ac9dbf71bb285e850377
/Massive3/main.cpp
446547f9c40787bf24cabab2ff9287a3d3f184ea
[]
no_license
Chenics/myfirstrep
0b52f72fef87157e33feadda19f190ab20e99f54
bf19dc77480ee88ffeb672e20642d9ae0568bf91
refs/heads/master
2020-03-30T04:13:02.830620
2018-10-05T15:20:32
2018-10-05T15:20:32
150,730,531
0
0
null
null
null
null
UTF-8
C++
false
false
244
cpp
#include <iostream> using namespace std; int f (int* arr; int size) int a = 0; { if (arr[i] % 2 == 0) { a = a + arr[i]; } return a; } int main() { cout << < endl; return 0; }
[ "ilya100111@mail.ru" ]
ilya100111@mail.ru
6d8c24528a3d7ab1044aeb897d3e85655ad76e0b
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/TAO/performance-tests/POA/Implicit_Activation/collocated.cpp
8aa76f08e8c96e3809125ec0d69ffe162e397201
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-sun-iiop" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
4,668
cpp
#include "Simple.h" #include "ace/Get_Opt.h" #include "ace/Sched_Params.h" #include "ace/High_Res_Timer.h" #include "ace/Sched_Params.h" #include "ace/Stats.h" #include "ace/Sample_History.h" #include "ace/OS_NS_errno.h" int niterations = 10000; int do_dump_history = 0; int parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("hi:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'h': do_dump_history = 1; break; case 'i': niterations = ACE_OS::atoi (get_opts.opt_arg ()); break; case '?': default: ACE_ERROR_RETURN ((LM_ERROR, "usage: %s " "-i <niterations> " "-h " "\n", argv [0]), -1); } // Indicates successful parsing of the command line return 0; } int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { int priority = (ACE_Sched_Params::priority_min (ACE_SCHED_FIFO) + ACE_Sched_Params::priority_max (ACE_SCHED_FIFO)) / 2; priority = ACE_Sched_Params::next_priority (ACE_SCHED_FIFO, priority); // Enable FIFO scheduling, e.g., RT scheduling class on Solaris. if (ACE_OS::sched_params (ACE_Sched_Params (ACE_SCHED_FIFO, priority, ACE_SCOPE_PROCESS)) != 0) { if (ACE_OS::last_error () == EPERM) { ACE_DEBUG ((LM_DEBUG, "server (%P|%t): user is not superuser, " "test runs in time-shared class\n")); } else ACE_ERROR ((LM_ERROR, "server (%P|%t): sched_params failed\n")); } try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); CORBA::Object_var poa_object = orb->resolve_initial_references("RootPOA"); if (CORBA::is_nil (poa_object.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Unable to initialize the POA.\n"), 1); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in ()); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); poa_manager->activate (); if (parse_args (argc, argv) != 0) return 1; Test::Simple_Sequence references (niterations); references.length (niterations); ACE_Sample_History activation (niterations); ACE_DEBUG ((LM_DEBUG, "High resolution timer calibration....")); ACE_High_Res_Timer::global_scale_factor_type gsf = ACE_High_Res_Timer::global_scale_factor (); ACE_DEBUG ((LM_DEBUG, "done\n")); ACE_DEBUG ((LM_DEBUG, "Activating %d objects\n", niterations)); for (int i = 0; i != niterations; ++i) { ACE_hrtime_t start = ACE_OS::gethrtime (); Simple *simple_impl; ACE_NEW_RETURN (simple_impl, Simple, 1); PortableServer::ServantBase_var owner_transfer(simple_impl); references[i] = simple_impl->_this (); ACE_hrtime_t now = ACE_OS::gethrtime (); activation.sample (now - start); } ACE_DEBUG ((LM_DEBUG, "Activations completed\n")); if (do_dump_history) { activation.dump_samples (ACE_TEXT("ACTIVATION_HISTORY"), gsf); } ACE_Basic_Stats activation_stats; activation.collect_basic_stats (activation_stats); activation_stats.dump_results (ACE_TEXT("Activation"), gsf); ACE_Sample_History destruction (niterations); ACE_DEBUG ((LM_DEBUG, "Destroying %d objects\n", niterations)); for (int j = 0; j != niterations; ++j) { ACE_hrtime_t start = ACE_OS::gethrtime (); references[j]->destroy (); ACE_hrtime_t now = ACE_OS::gethrtime (); destruction.sample (now - start); } ACE_DEBUG ((LM_DEBUG, "Destructions completed\n")); if (do_dump_history) { destruction.dump_samples (ACE_TEXT("DESTRUCTION_HISTORY"), gsf); } ACE_Basic_Stats destruction_stats; destruction.collect_basic_stats (destruction_stats); destruction_stats.dump_results (ACE_TEXT("Destruction"), gsf); root_poa->destroy (1, 1); orb->destroy (); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); return 1; } return 0; }
[ "lihuibin705@163.com" ]
lihuibin705@163.com
7398937c9840111bc6010d66437f0760b8b21efb
aa5bde78ca59672ec5f7953100a511f14dc23716
/xdbd-sql-parser/XdbdSqlDeleteFunction.cpp
c0cd1ddc27384c98b965646a83279e444631c989
[]
no_license
miranvodnik/xdbd
5dbb530a7db3b8575cbe87e37bbe90e2a7b5bced
ae4ab6bb53b11c307951c6b9c67bbfa59cb42c5c
refs/heads/main
2023-04-03T18:51:18.963054
2021-04-18T14:36:21
2021-04-18T14:36:21
358,135,606
0
0
null
null
null
null
UTF-8
C++
false
false
16,046
cpp
/* * XdbdSqlDeleteFunction.cpp * * Created on: 13. nov. 2015 * Author: miran */ #include <sqlxdbd.h> #include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include "XdbdSqlDeleteFunction.h" #include "XdbdMessageQueue.h" namespace xml_db_daemon { XdbdSqlDeleteFunction::XdbdSqlDeleteFunction(sql_statement* p_sql_statement, int ecount) { Reset (); m_sql_statement = p_sql_statement; } XdbdSqlDeleteFunction::~XdbdSqlDeleteFunction() { for (compset::iterator it = m_compset.begin(); it != m_compset.end(); ++it) { delete *it; } m_compset.clear(); int i = 0; for (compset::iterator it = m_dynpars.begin(); it != m_dynpars.end(); ++it, ++i) { // all XdbdSqlComparison objects are already deleted within m_compset } m_dynpars.clear(); Reset (); } void XdbdSqlDeleteFunction::Reset() { m_sql_statement = 0; m_sql_delete_statement = 0; m_sql_table = 0; m_sql_expression = 0; m_tabinfo = 0; m_resultSize = 0; m_eindex = 0; m_shmSize = 0; m_hdrSize = 0; m_parCount = 0; m_parsSize = 0; m_colCount = 0; m_colsSize = 0; m_rowCount = 0; } int XdbdSqlDeleteFunction::Prepare (XdbdShmSegment* shmSegment, bool create) { m_sql_statement->Traverse(this); if (create) CreatePreparedSet (shmSegment); return ((m_tabinfo == 0) || (m_sql_table == 0)) ? -1 : 0; } int XdbdSqlDeleteFunction::BindParameters (XdbdShmSegment* shmSegment) { int csize = m_compset.size(); for (int i = 0; i < csize; ++i) { XdbdSqlComparison* comp = m_compset[i]; XdbdXmlTableInfo* tabinfo = comp->tabinfo(); if (tabinfo == 0) { xdbdErrReport (SC_XDBD, SC_ERR, err_info("null table info")); continue; } XdbdXmlColumnInfo* colinfo = comp->colinfo(); if (colinfo == 0) { xdbdErrReport (SC_XDBD, SC_ERR, err_info("null column info")); continue; } if (chkcolflag (colinfo->columnToRecord(comp->data()), 2, colinfo->index(), COLPARVALUE) != 0) continue; unsigned char* data = new unsigned char [tabinfo->resSize()]; memset (data, 0, tabinfo->resSize()); XdbdXmlColumnInfo::colrng range = XdbdXmlDataBase::ExecComparison(colinfo, colinfo->recordToColumn(data), comp->data(), colinfo->realLength(), comp->sqlSyntaxContext()); comp->data(data + colinfo->position()); comp->range(range); } unsigned char* addr = (unsigned char*) shmSegment->shmAddr(); addr += 6 * sizeof (int); unsigned char* pars = xdbdalign (addr + (m_parCount + m_colCount) * 3 * sizeof (int), unsigned char*); int offset = 0; for (int i = 0; (i < m_parCount); ++i, addr += 3 * sizeof (int)) { int psize = ((int*)addr)[1]; int plen = ((int*)addr)[2]; XdbdSqlComparison* comp = m_dynpars[i]; XdbdXmlTableInfo* tabinfo = comp->tabinfo(); if (tabinfo == 0) { xdbdErrReport (SC_XDBD, SC_ERR, err_info("null table info")); continue; } XdbdXmlColumnInfo* colinfo = comp->colinfo(); if (colinfo == 0) { xdbdErrReport (SC_XDBD, SC_ERR, err_info("null column info")); continue; } unsigned char* data = new unsigned char [tabinfo->resSize()]; memset (data, 0, tabinfo->resSize()); XdbdXmlColumnInfo::colrng range = XdbdXmlDataBase::ExecComparison(colinfo, data + colinfo->position(), pars + offset, plen, comp->sqlSyntaxContext()); comp->data(data + colinfo->position()); comp->range(range); shmSegment->DisplayParameter(i, pars + offset, plen, colinfo->colType()); offset += psize; } return 0; } int XdbdSqlDeleteFunction::Execute (XdbdShmSegment* shmSegment) { int result = -1; if (m_tabinfo == 0) return result; try { m_tabinfo->LockTable(); BindParameters (shmSegment); result = (m_sql_delete_statement->kind() > sql_delete_statement::g_sql_delete_statement_2) ? ExecuteUnconditionalDeleteStatement (shmSegment) : ExecuteConditionalDeleteStatement (shmSegment); m_tabinfo->UnlockTable(); } catch (...) { m_tabinfo->UnlockTable(); } return result; } int XdbdSqlDeleteFunction::ExecuteConditionalDeleteStatement (XdbdShmSegment* shmSegment) { set < unsigned char* > resultSet; int setcount = 0; for (cmpset::iterator ci = m_cmpset.begin(); ci != m_cmpset.end(); ++ci, ++setcount) { XdbdSqlComparison* scomp = 0; unsigned long v = *ci; while (true) { unsigned long mask = 1; bool inc = false; for (int i = 0; i < m_eindex; ++i, mask <<= 1) { XdbdSqlComparison* comp = m_compset[i]; inc = comp->incIndex(); if ((v & mask) == 0) continue; if (inc) continue; if ((scomp == 0) || (comp->resultCount() < scomp->resultCount())) scomp = comp; } if (scomp != 0) break; } if ((scomp == 0) || (scomp->resultCount() == 0)) continue; XdbdXmlColumnInfo::colrng range = scomp->range(); if (scomp->invert()) { XdbdXmlColumnInfo* scolinfo = scomp->colinfo(); XdbdXmlColumnInfo::colrng rng; rng = XdbdXmlColumnInfo::colrng (scolinfo->begin(), range.first); ExecuteCompChecks (scomp, rng, v, resultSet); rng = XdbdXmlColumnInfo::colrng (range.second, scolinfo->end()); ExecuteCompChecks (scomp, rng, v, resultSet); } else ExecuteCompChecks (scomp, range, v, resultSet); } int count = resultSet.size(); DeleteResultSet(shmSegment, count, resultSet); return 0; } int XdbdSqlDeleteFunction::ExecuteCompChecks (XdbdSqlComparison* scomp, XdbdXmlColumnInfo::colrng range, unsigned long v, set < unsigned char* > & resultSet) { for (XdbdXmlColumnInfo::colidx idx = range.first; idx != range.second; ++idx) { unsigned char* rowaddr = idx->second; if (*rowaddr == 'D') continue; int i; unsigned long mask = 1; for (i = 0; i < m_eindex; ++i, mask <<= 1) { if ((v & mask) == 0) continue; XdbdSqlComparison* comp = m_compset[i]; if (comp == scomp) continue; if (comp->tabinfo() != scomp->tabinfo()) continue; XdbdXmlColumnInfo* colinfo = comp->colinfo(); if (colinfo->isTrue()) continue; unsigned char* data = colinfo->recordToColumn(rowaddr); colset < XdbdXmlColumnInfo > ::cmpcol fcomp (colinfo); bool accept = false; switch (comp->sqlSyntaxContext()) { case sql_eq_expression_Context: { accept = (!fcomp (data, comp->data()) && !fcomp (comp->data(), data)); } break; case sql_ne_expression_Context: { accept = (fcomp (data, comp->data()) || fcomp (comp->data(), data)); } break; case sql_lt_expression_Context: { accept = (fcomp (data, comp->data())); } break; case sql_le_expression_Context: { accept = (!fcomp (comp->data(), data)); } break; case sql_gt_expression_Context: { accept = (fcomp (comp->data(), data)); } break; case sql_ge_expression_Context: { accept = (!fcomp (data, comp->data())); } break; case sql_like_expression_Context: { accept = true; // (!fcomp (data, comp->data())); } break; case sql_is_eq_expression_Context: { accept = (!fcomp (data, comp->data()) && !fcomp (comp->data(), data)); } break; case sql_is_ne_expression_Context: { accept = (fcomp (data, comp->data()) || fcomp (comp->data(), data)); } break; default: break; } if (!accept) break; } if (i != m_eindex) continue; if (resultSet.find(rowaddr) == resultSet.end()) resultSet.insert(rowaddr); } return 0; } int XdbdSqlDeleteFunction::ExecuteUnconditionalDeleteStatement (XdbdShmSegment* shmSegment) { int count = 0; set < unsigned char* > resultSet; for (XdbdXmlTableInfo::col_iterator cit = m_tabinfo->col_begin(); (count < 100) && (cit != m_tabinfo->col_end()); cit++) { XdbdXmlColumnInfo* colinfo = *cit; for (XdbdXmlColumnInfo::colidx idx = colinfo->begin(); (count < 100) && (idx != colinfo->end()); ++count, ++idx) { resultSet.insert (idx->second); } } DeleteResultSet(shmSegment, count, resultSet); return 0; } int XdbdSqlDeleteFunction::CreatePreparedSet (XdbdShmSegment* shmSegment) { int result = -1; do { m_parCount = m_dynpars.size(); m_colCount = m_tabinfo->resCount(); m_hdrSize = xdbdalign (((m_colCount + m_parCount) * 3 + 6) * sizeof (int), long) + xdbdalign (m_parsSize + m_resultSize, long); if (m_hdrSize <= 0) break; unsigned char* shmAddr = (unsigned char*) shmSegment->Resize (m_hdrSize); unsigned char* addr = shmAddr; if (addr == MAP_FAILED) { xdbdErrReport (SC_XDBD, SC_ERR, err_info ("mmap (%d) failed, errno = %d"), m_hdrSize, errno); break; } unsigned char* buff = addr; ((int*)buff) [g_shmSizeIndex] = m_hdrSize; ((int*)buff) [g_parCountIndex] = m_parCount; ((int*)buff) [g_parSizeIndex] = m_parsSize; ((int*)buff) [g_colCountIndex] = m_colCount; ((int*)buff) [g_colSizeIndex] = m_resultSize; ((int*)buff) [g_rowCountIndex] = 0; buff += 6 * sizeof (int); for (compset::iterator it = m_dynpars.begin(); it != m_dynpars.end(); ++it, buff += 3 * sizeof (int)) { XdbdXmlColumnInfo* colinfo = (*it)->colinfo(); ((int*)buff)[0] = (int) colinfo->colType(); ((int*)buff)[1] = (int) colinfo->realLength(); ((int*)buff)[2] = (int) colinfo->maxLength(); } for (XdbdXmlTableInfo::col_iterator it = m_tabinfo->col_begin(); it != m_tabinfo->col_end(); ++it, buff += 3 * sizeof (int)) { XdbdXmlColumnInfo* colinfo = *it; ((int*)buff)[0] = (int) colinfo->colType(); ((int*)buff)[1] = (int) colinfo->realLength(); ((int*)buff)[2] = (int) colinfo->maxLength(); } shmSegment->hdrSize(m_hdrSize); result = 0; #if defined (_DEBUG) dump (addr, shmsize); #endif } while (false); return result; } int XdbdSqlDeleteFunction::DeleteResultSet (XdbdShmSegment* shmSegment, int count, set < unsigned char* > &resultSet) { do { int rescount = m_tabinfo->resCount(); if ((rescount <= 0) || (m_resultSize <= 0)) break; unsigned char* addr = (unsigned char*) shmSegment->shmAddr(); if (addr == MAP_FAILED) CreatePreparedSet(shmSegment); addr = (unsigned char*) shmSegment->shmAddr(); if (addr == MAP_FAILED) { xdbdErrReport (SC_XDBD, SC_ERR, err_info ("cannot create shared memory chunk")); break; } m_shmSize = m_hdrSize + count * m_resultSize; addr = (unsigned char*) shmSegment->Resize(m_shmSize); if (addr == MAP_FAILED) { xdbdErrReport (SC_XDBD, SC_ERR, err_info ("mmap (%d) failed, errno = %d"), m_shmSize, errno); break; } int ressize = m_tabinfo->resSize(); unsigned char* ptr = addr + m_hdrSize; for (set < unsigned char* > ::iterator it = resultSet.begin(); it != resultSet.end(); ++it) { unsigned char* rowaddr = *it; memcpy (ptr, rowaddr + m_tabinfo->colhdrSize(), m_resultSize); for (XdbdXmlTableInfo::col_iterator it = m_tabinfo->col_begin(); it != m_tabinfo->col_end(); ++it) (*it)->dilite(rowaddr); ptr += m_resultSize; m_tabinfo->freeCol(rowaddr); unsigned char* oldData = (unsigned char*) malloc (ressize); if (oldData == 0) { xdbdErrReport (SC_XDBD, SC_ERR, err_info ("malloc (%d) failed, errno = %d"), ressize, errno); break; } // memcpy (rowaddr, "DD", sizeof(short)); memcpy (oldData, rowaddr, ressize); if (XdbdXmlDataBase::TriggerStatus()) XdbdMessageQueue::Put (new XdbdDeleteTriggerJob (m_tabinfo, oldData, ressize)); else XdbdXmlDataBase::SaveTrgJob (new XdbdDeleteTriggerJob (m_tabinfo, oldData, ressize)); } #if defined (_DEBUG) dump (addr, shmsize); #endif } while (false); return 0; } #define CLASSNAME XdbdSqlDeleteFunction #define sql_delete_statement_CallbackDefined void CLASSNAME::Invoke_sql_delete_statement_Callback (SqlCallbackReason reason, unsigned int kind, sql_delete_statement* p_sql_delete_statement) { switch (reason) { case DefaultCallbackReason: break; case TraversalPrologueCallbackReason: m_sql_delete_statement = p_sql_delete_statement; break; case TraversalEpilogueCallbackReason: { m_parsSize = 0; for (compset::iterator it = m_dynpars.begin(); it != m_dynpars.end(); ++it) { XdbdXmlColumnInfo* colinfo = (*it)->colinfo(); if (colinfo == 0) continue; m_parsSize += colinfo->realLength(); } m_resultSize = m_tabinfo->resSize() - m_tabinfo->colhdrSize(); } break; } } #define sql_table_part_CallbackDefined void CLASSNAME::Invoke_sql_table_part_Callback (SqlCallbackReason reason, unsigned int kind, sql_table_part* p_sql_table_part) { switch (reason) { case DefaultCallbackReason: break; case TraversalPrologueCallbackReason: { m_sql_table = p_sql_table_part->get_sql_table(); m_tabinfo = XdbdXmlDataBase::GetTableInfo(m_sql_table->get_char()); } break; case TraversalEpilogueCallbackReason: break; } } #define sql_expression_part_CallbackDefined void CLASSNAME::Invoke_sql_expression_part_Callback (SqlCallbackReason reason, unsigned int kind, sql_expression_part* p_sql_expression_part) { switch (reason) { case DefaultCallbackReason: break; case TraversalPrologueCallbackReason: { m_sql_expression = p_sql_expression_part->get_sql_expression(); } break; case TraversalEpilogueCallbackReason: break; } } #define sql_or_expression_CallbackDefined void CLASSNAME::Invoke_sql_or_expression_Callback (SqlCallbackReason reason, unsigned int kind, sql_or_expression* p_sql_or_expression) { switch (reason) { case DefaultCallbackReason: break; case TraversalPrologueCallbackReason: break; case TraversalEpilogueCallbackReason: if (kind == sql_or_expression::g_sql_or_expression_2) { cmpsize rsize = m_cmpptr.back(); m_cmpptr.pop_back(); cmpsize lsize = m_cmpptr.back(); m_cmpptr.pop_back(); m_cmpptr.push_back(make_pair (lsize.first, rsize.second)); } break; } } #define sql_and_expression_CallbackDefined void CLASSNAME::Invoke_sql_and_expression_Callback (SqlCallbackReason reason, unsigned int kind, sql_and_expression* p_sql_and_expression) { switch (reason) { case DefaultCallbackReason: break; case TraversalPrologueCallbackReason: break; case TraversalEpilogueCallbackReason: if (kind == sql_and_expression::g_sql_and_expression_2) { cmpsize rsize = m_cmpptr.back(); m_cmpptr.pop_back(); cmpsize lsize = m_cmpptr.back(); m_cmpptr.pop_back(); cmpset cset; for (cmpset::size_type l = lsize.first; l < lsize.second; ++l) { for (cmpset::size_type r = rsize.first; r < rsize.second; ++r) { unsigned long v = m_cmpset[l] | m_cmpset[r]; cset.push_back(v); } } for (cmpset::size_type l = lsize.first; l < lsize.second; ++l) { m_cmpset.pop_back(); } for (cmpset::size_type r = rsize.first; r < rsize.second; ++r) { m_cmpset.pop_back(); } cmpset::size_type size = m_cmpset.size(); for (cmpset::iterator it = cset.begin(); it != cset.end(); ++it) { m_cmpset.push_back(*it); } m_cmpptr.push_back(make_pair (size, m_cmpset.size())); cset.clear(); } break; } } #define sql_comp_expression_CallbackDefined void CLASSNAME::Invoke_sql_comp_expression_Callback (SqlCallbackReason reason, unsigned int kind, sql_comp_expression* p_sql_comp_expression) { switch (reason) { case DefaultCallbackReason: break; case TraversalPrologueCallbackReason: break; case TraversalEpilogueCallbackReason: { if (kind > sql_comp_expression::g_sql_comp_expression_7) break; XdbdXmlColumnInfo* colinfo = 0; unsigned char* data = 0; ssize_t dsize = 0; SqlSyntaxContext sqlSyntaxContext = SqlFirstSyntaxContext; bool invert = false; XdbdXmlColumnInfo::colrng range = XdbdXmlDataBase::PrepareComparison (m_tabinfo, p_sql_comp_expression, colinfo, data, dsize, sqlSyntaxContext, invert); XdbdSqlComparison* comp = new XdbdSqlComparison (range, m_tabinfo, colinfo, (colinfo == 0) ? 0 : data + colinfo->position(), dsize, sqlSyntaxContext, invert); m_compset.push_back (comp); if ((((ssize_t)sql_constant::g_sql_constant_4) + dsize) == 0) m_dynpars.push_back (comp); cmpset::size_type size = m_cmpset.size(); unsigned long v = 0; v |= (1 << m_eindex++); m_cmpset.push_back(v); m_cmpptr.push_back(make_pair(size, size + 1)); } break; } } #include "SqlCompilerCallbackImpls.template" } /* namespace xml_db_daemon */
[ "root@LAPTOP-BFNOOAN1.localdomain" ]
root@LAPTOP-BFNOOAN1.localdomain
e0ccf64da2289c390dfc7d47178bfece913eeea9
71103c66a80781b87242c0db88c57f1b055dae67
/CVDlibTest/stdafx.cpp
63179a2541e44c00cfba03b2f4badd74bd422d71
[]
no_license
matsuneA212/FaceSnow
de94f6bb525367fad0c3fdacfd68df69fbd7fa29
edc5dcf7da5fc43ed128dbc90de29d3d55e3ccc0
refs/heads/master
2020-12-02T07:59:49.844175
2017-07-10T09:57:48
2017-07-10T09:57:48
96,758,586
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
266
cpp
// stdafx.cpp : 標準インクルード CVDlibTest.pch のみを // 含むソース ファイルは、プリコンパイル済みヘッダーになります。 // stdafx.obj にはプリコンパイルされた型情報が含まれます。 #include "stdafx.h"
[ "apple-rain.0212@ezweb.ne.jp" ]
apple-rain.0212@ezweb.ne.jp
9974197443a53f83d70cee6958c870eda87cb5de
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/third_party/WebKit/Source/platform/fonts/mac/FontMac.cpp
b0fd0274743fb0550b469d39d4f234edf0af4cae
[ "MIT", "BSD-3-Clause", "GPL-1.0-or-later", "LGPL-2.0-or-later", "Apache-2.0" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
7,178
cpp
/* * Copyright (c) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "platform/fonts/Font.h" #include "platform/LayoutTestSupport.h" #include "platform/fonts/FontSmoothingMode.h" #include "platform/fonts/GlyphBuffer.h" #include "platform/fonts/SimpleFontData.h" #include "platform/graphics/GraphicsContext.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkTypeface.h" #include "third_party/skia/include/ports/SkTypeface_mac.h" namespace WebCore { bool Font::canReturnFallbackFontsForComplexText() { return true; } bool Font::canExpandAroundIdeographsInComplexText() { return true; } static void setupPaint(SkPaint* paint, const SimpleFontData* fontData, const Font* font, bool shouldAntialias, bool shouldSmoothFonts) { const FontPlatformData& platformData = fontData->platformData(); const float textSize = platformData.m_size >= 0 ? platformData.m_size : 12; paint->setAntiAlias(shouldAntialias); paint->setEmbeddedBitmapText(false); paint->setTextSize(SkFloatToScalar(textSize)); paint->setVerticalText(platformData.orientation() == Vertical); SkTypeface* typeface = SkCreateTypefaceFromCTFont(platformData.ctFont()); SkAutoUnref autoUnref(typeface); paint->setTypeface(typeface); paint->setFakeBoldText(platformData.m_syntheticBold); paint->setTextSkewX(platformData.m_syntheticOblique ? -SK_Scalar1 / 4 : 0); paint->setAutohinted(false); // freetype specific paint->setLCDRenderText(shouldSmoothFonts); paint->setSubpixelText(true); #if OS(MACOSX) // When using CoreGraphics, disable hinting when webkit-font-smoothing:antialiased is used. // See crbug.com/152304 if (font->fontDescription().fontSmoothing() == Antialiased) paint->setHinting(SkPaint::kNo_Hinting); #endif if (font->fontDescription().textRenderingMode() == GeometricPrecision) paint->setHinting(SkPaint::kNo_Hinting); } // TODO: This needs to be split into helper functions to better scope the // inputs/outputs, and reduce duplicate code. // This issue is tracked in https://bugs.webkit.org/show_bug.cgi?id=62989 void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font, const GlyphBuffer& glyphBuffer, unsigned from, unsigned numGlyphs, const FloatPoint& point, const FloatRect& textRect) const { COMPILE_ASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t), GlyphBufferGlyphSize_equals_uint16_t); bool shouldSmoothFonts = true; bool shouldAntialias = true; switch (fontDescription().fontSmoothing()) { case Antialiased: shouldSmoothFonts = false; break; case SubpixelAntialiased: break; case NoSmoothing: shouldAntialias = false; shouldSmoothFonts = false; break; case AutoSmoothing: // For the AutoSmooth case, don't do anything! Keep the default settings. break; } if (!shouldUseSmoothing() || isRunningLayoutTest()) { shouldSmoothFonts = false; shouldAntialias = false; } const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from); SkScalar x = SkFloatToScalar(point.x()); SkScalar y = SkFloatToScalar(point.y()); if (font->platformData().orientation() == Vertical) y += SkFloatToScalar(font->fontMetrics().floatAscent(IdeographicBaseline) - font->fontMetrics().floatAscent()); // FIXME: text rendering speed: // Android has code in their WebCore fork to special case when the // GlyphBuffer has no advances other than the defaults. In that case the // text drawing can proceed faster. However, it's unclear when those // patches may be upstreamed to WebKit so we always use the slower path // here. const GlyphBufferAdvance* adv = glyphBuffer.advances(from); SkAutoSTMalloc<32, SkPoint> storage(numGlyphs); SkPoint* pos = storage.get(); for (unsigned i = 0; i < numGlyphs; i++) { pos[i].set(x, y); x += SkFloatToScalar(adv[i].width()); y += SkFloatToScalar(adv[i].height()); } if (font->platformData().orientation() == Vertical) { gc->save(); gc->rotate(-0.5 * SK_ScalarPI); SkMatrix rotator; rotator.reset(); rotator.setRotate(90); rotator.mapPoints(pos, numGlyphs); } TextDrawingModeFlags textMode = gc->textDrawingMode(); // We draw text up to two times (once for fill, once for stroke). if (textMode & TextModeFill) { SkPaint paint; gc->setupPaintForFilling(&paint); setupPaint(&paint, font, this, shouldAntialias, shouldSmoothFonts); gc->adjustTextRenderMode(&paint); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); gc->drawPosText(glyphs, numGlyphs * sizeof(uint16_t), pos, textRect, paint); } if ((textMode & TextModeStroke) && gc->strokeStyle() != NoStroke && gc->strokeThickness() > 0) { SkPaint paint; gc->setupPaintForStroking(&paint); setupPaint(&paint, font, this, shouldAntialias, shouldSmoothFonts); gc->adjustTextRenderMode(&paint); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); if (textMode & TextModeFill) { // If we also filled, we don't want to draw shadows twice. // See comment in FontChromiumWin.cpp::paintSkiaText() for more details. paint.setLooper(0); } gc->drawPosText(glyphs, numGlyphs * sizeof(uint16_t), pos, textRect, paint); } if (font->platformData().orientation() == Vertical) gc->restore(); } } // namespace WebCore
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
8a01029854b9f1e4827ff0e6e7da367bd6536e9c
a61b700bad6423416c84b5a5f32b87fb47c2c453
/codeforces/dominos.cpp
ee76c34e9809528dc33c42c38df56e5741d2eb75
[]
no_license
dpirad007/Competitive_pracs
3d8a5ab66dfa902cf7b2714b2a38ee913a86ca09
64c00ca30eb15bc4ac4dad8390648a304b05dd33
refs/heads/master
2022-04-16T01:23:42.916058
2020-04-12T06:31:05
2020-04-12T06:31:05
255,022,611
0
0
null
null
null
null
UTF-8
C++
false
false
490
cpp
#include<bits/stdc++.h> using namespace std; int main() { long long r,c,count=0,sol,fin,sol1; cin>>r>>c; if(r%2==0) { sol1=r/2; count+=c; count*=sol1; } else if(r==1) { sol=c%2; fin=c-sol; count+=fin/2; } else { sol1=r-1; sol1=sol1/2; count+=c; count*=sol1; sol=c%2; fin=c-sol; count+=fin/2; } cout<<count<<endl; return 0; }
[ "dionpinto000@gmail.com" ]
dionpinto000@gmail.com
69dab00191f87c5cc0354494ed70983962fcd391
8831e007ca6e66a66006d505946851afa3157cfb
/Middlewares/ST/touchgfx/framework/include/touchgfx/Unicode.hpp
4cf200eadd5a34db50c21c6080f865750f9abc24
[]
no_license
4ms/touchgfx-f429-makefile
58b6d533cd740f74ec5d6e5364b32183dd43d21c
c1efa6b1992e291374bfcdff4656128f15be2493
refs/heads/main
2023-08-03T02:51:38.140206
2021-09-23T00:11:14
2021-09-23T00:11:14
409,393,108
0
0
null
null
null
null
UTF-8
C++
false
false
22,648
hpp
/****************************************************************************** * Copyright (c) 2018(-2021) STMicroelectronics. * All rights reserved. * * This file is part of the TouchGFX 4.17.0 distribution. * * This software is licensed under terms that can be found in the LICENSE file in * the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * *******************************************************************************/ /** * @file touchgfx/Unicode.hpp * * Declares the touchgfx::Unicode class. */ #ifndef TOUCHGFX_UNICODE_HPP #define TOUCHGFX_UNICODE_HPP #include <stdarg.h> #include <touchgfx/hal/Types.hpp> namespace touchgfx { /** * This class provides simple helper functions for working with strings which are stored as a * null-terminated array of 16-bit characters. */ class Unicode { public: /** Use the UnicodeChar typename when referring to characters in a string. */ typedef uint16_t UnicodeChar; /** * Gets the length of a null-terminated Unicode string. * * @param str The string in question. * * @return Length of string. */ static uint16_t strlen(const UnicodeChar* str); /** * Gets the length of a null-terminated string. * * @param str The string. * * @return Length of string. */ static uint16_t strlen(const char* str); /** * Copy a string to a destination buffer, UnicodeChar to UnicodeChar version. Stops * after copying maxchars Unicode characters or after copying the ending zero * termination UnicodeChar. * * @param [out] dst The destination buffer. Must have a size of at least maxchars. * @param [in] src The source string. * @param maxchars Maximum number of UnicodeChars to copy. * * @return The number of characters copied (excluding null-termination if encountered) * * @note If there is no null-termination among the first n UnicodeChars of src, the string * placed in destination will NOT be null-terminated! */ static uint16_t strncpy(UnicodeChar* RESTRICT dst, const UnicodeChar* RESTRICT src, uint16_t maxchars); /** * Copy a string to a destination buffer, char to UnicodeChar version. Stops after * copying maxchars Unicode characters or after copying the ending null-termination * UnicodeChar. * * @param [out] dst The destination buffer. Must have a size of at least maxchars. * @param [in] src The source string. * @param maxchars Maximum number of chars to copy. * * @return The number of characters copied (excluding null-termination if encountered) * * @note If there is no null-termination among the first n UnicodeChars of src, the string * placed in destination will NOT be null-terminated! */ static uint16_t strncpy(UnicodeChar* RESTRICT dst, const char* RESTRICT src, uint16_t maxchars); /** * Integer to ASCII conversion. Supports radix 2 to radix 36. * * @param value to convert. * @param [out] buffer to place result in. * @param bufferSize Size of buffer (number of UnicodeChar's). * @param radix to use (8 for octal, 10 for decimal, 16 for hex) */ static void itoa(int32_t value, UnicodeChar* buffer, uint16_t bufferSize, int radix); /** * Integer to ASCII conversion. Supports radix 2 to radix 36. * * @param value to convert. * @param [out] buffer to place result in. * @param bufferSize Size of buffer (number of UnicodeChar's). * @param radix to use (8 for octal, 10 for decimal, 16 for hex) */ static void utoa(uint32_t value, UnicodeChar* buffer, uint16_t bufferSize, int radix); /** * String to integer conversion. Starts conversion at the start of the string. Running * digits from here are converted. Only radix 10 supported. * * @param s Radix 10, null-terminated Unicode string to convert. * * @return The converted integer value of the string, 0 if the string does not start * with a digit. */ static int atoi(const UnicodeChar* s); /** * Formats a string and adds null termination. The string is formatted like when the * standard printf is used. * * Support formats: \%c (element type: char), \%s (element type: null-terminated * UnicodeChar list), \%u, \%i, \%d, \%o, \%x (all these are integers formatted in radix * 10, 10, 10, 8, 16 respectively). * * The number formats (\%u, \%i, \%d, \%o and \%x) all support \%[0][length]X to specify * the size of the generated field (length) and whether the number should be prefixed * with zeros (or blanks). * * @param [out] dst Buffer for the formatted string. * @param dstSize Size of the dst buffer measured by number of UnicodeChars the buffer * can hold. * @param [in] format The format string. * @param ... The values to insert in the format string. * * @return pointer to the first element in the buffer where the formatted string is * placed. * * @see snprintfFloat, snprintfFloats * * @note \%f is not supported by this function because floats are converted to doubles when * given as parameters in a variable argument list (va_list). Use snprintfFloat * or snprintfFloats instead. */ static UnicodeChar* snprintf(UnicodeChar* dst, uint16_t dstSize, const UnicodeChar* format, ...); /** * Variant of snprintf. * * @param [out] dst Buffer for the formatted string. * @param dstSize Size of the dst buffer measured by number of UnicodeChars the buffer * can hold. * @param [in] format The format string. * @param pArg The values to insert in the format string. * * @return pointer to the first element in the buffer where the formatted string is * placed. * * @see snprintf */ static UnicodeChar* vsnprintf(UnicodeChar* dst, uint16_t dstSize, const UnicodeChar* format, va_list pArg); /** * Formats a string and adds null termination. The string is formatted like when the * standard printf is used. * * Support formats: \%c (element type: char), \%s (element type: null-terminated * UnicodeChar list), \%u, \%i, \%d, \%o, \%x (all these are integers formatted in radix * 10, 10, 10, 8, 16 respectively). * * The number formats (\%u, \%i, \%d, \%o and \%x) all support * * \%[flags][width][.precision]X * * Where flags can be: * - '-': left justify the field (see width). * - '+': force sign. * - ' ': insert space if value is positive. * - '0': left pad with zeros instead of spaces (see width). * * Where width is the desired width of the output. If the value is larger, more * characters may be generated, but not more than the parameter dstSize. If width is '*' * the actual width is read from the parameters passed to this function. * * Where precision is the number of number of digits after the decimal point, default is * 3. Use "\%.f" to not generate any numbers after the decimal point. If precision is '*' * the actual precision is read from the parameters passed to this function. * * @param [out] dst Buffer for the formatted string. * @param dstSize Size of the dst buffer measured by number of UnicodeChars the buffer * can hold. * @param [in] format The format string. * @param ... The values to insert in the format string. * * @return pointer to the first element in the buffer where the formatted string is * placed. * * @see snprintfFloat, snprintfFloats * * @note \%f is not supported by this function because floats are converted to doubles when * given as parameters in a variable argument list (va_list). Use snprintfFloat or * snprintfFloats instead. * * @see snprintfFloat, snprintfFloats */ static UnicodeChar* snprintf(UnicodeChar* dst, uint16_t dstSize, const char* format, ...); /** * Variant of snprintf. * * @param [out] dst Buffer for the formatted string. * @param dstSize Size of the dst buffer measured by number of UnicodeChars the buffer * can hold. * @param [in] format The format string. * @param pArg The values to insert in the format string. * * @return pointer to the first element in the buffer where the formatted string is * placed. * * @see snprintf */ static UnicodeChar* vsnprintf(UnicodeChar* dst, uint16_t dstSize, const char* format, va_list pArg); /** * Variant of snprintf for floats only. The format supports several \%f with * flags/modifiers. The following is supported: * * \%[flags][width][.precision]f * * Where flags can be: * - '-': left justify the field (see width). * - '+': force sign. * - ' ': insert space if value is positive * - '\#': insert decimal point even if there are not decimals * - '0': left pad with zeros instead of spaces (see width) * * Where width is the desired width of the output. If the value is larger, more * characters may be generated, but not more than the parameter dstSize. If width is '*' * the actual width is read from the list of values passed to this function. * * Where precision is the number of number of digits after the decimal point, default is * 3. Use "\%.f" to not generate any numbers after the decimal point. If precision is '*' * the actual precision is read from the list of values passed to this function. * @code{.cpp} * float param1[3] = { 6.0f, 4.0f, 3.14159f }; * Unicode::snprintfFloats(buffer, 20, "%*.*f", param1); * // buffer="3.1416" float param2[2] = { 3.14159f, -123.4f }; * Unicode::snprintfFloats(buffer, 20, "%f %f", param2); * // buffer="3.142 -123.400" * @endcode * * @param [out] dst Buffer for the formatted string. * @param dstSize Size of the dst buffer measured by number of UnicodeChars the buffer * can hold. * @param [in] format The format string containing %f's. * @param [in] values The floating point values to insert for %f. The number of elements in * the array must match the number of %f's in the format string. * * @return pointer to the first element in the buffer where the formatted string is * placed. * * @see snprintf, snprintfFloat */ static UnicodeChar* snprintfFloats(UnicodeChar* dst, uint16_t dstSize, const UnicodeChar* format, const float* values); /** * Variant of snprintfFloats() for exactly one float only. * * The number format supports only one \%f with flags/modifiers. The following is * supported: * * \%[flags][width][.precision]f * * Where flags can be: * - '-': left justify the field (see width). * - '+': force sign. * - ' ': insert space if value is positive. * - '\#': insert decimal point even if there are not decimals. * - '0': left pad with zeros instead of spaces (see width). * * Where width is the desired width of the output. If the value is larger, more * characters may be generated, but not more than the parameter dstSize. * * Where precision is the number of number of digits after the decimal point, default is * "3". Use "\%.f" to not generate any numbers after the decimal point. * @code{.cpp} * Unicode::UnicodeChar buffer[20]; * Unicode::snprintfFloat(buffer, 20, "%6.4f", 3.14159f); * // buffer="3.1416" * Unicode::snprintfFloat(buffer, 20, "%#6.f", 3.14159f); * // buffer=" 3." * Unicode::snprintfFloat(buffer, 20, "%6f", 3.14159f); * // buffer=" 3.142" * Unicode::snprintfFloat(buffer, 20, "%+06.f", 3.14159f); * // buffer="+00003" * @endcode * * If more control over the output is needed, see snprintfFloats which can have more * than a single "\%f" in the string and also supports "*" in place of a number. * * @param [out] dst Buffer for the formatted string. * @param dstSize Size of the dst buffer measured by number of UnicodeChars the buffer * can hold. * @param [in] format The format string containing exactly on occurrence of %f. * @param value The floating point value to insert for %f. * * @return pointer to the first element in the buffer where the formatted string is * placed. * * @see snprintf, snprintfFloats */ static UnicodeChar* snprintfFloat(UnicodeChar* dst, uint16_t dstSize, const UnicodeChar* format, const float value) { return snprintfFloats(dst, dstSize, format, &value); } /** * Variant of snprintf for floats only. The format supports several \%f with * flags/modifiers. The following is supported: * * \%[flags][width][.precision]f * * Where flags can be: * - '-': left justify the field (see width). * - '+': force sign. * - ' ': insert space if value is positive * - '\#': insert decimal point even if there are not decimals * - '0': left pad with zeros instead of spaces (see width) * * Where width is the desired width of the output. If the value is larger, more * characters may be generated, but not more than the parameter dstSize. If width is '*' * the actual width is read from the list of values passed to this function. * * Where precision is the number of number of digits after the decimal point, default is * 3. Use "\%.f" to not generate any numbers after the decimal point. If precision is '*' * the actual precision is read from the list of values passed to this function. * @code{.cpp} * float param1[3] = { 6.0f, 4.0f, 3.14159f }; * Unicode::snprintfFloats(buffer, 20, "%*.*f", param1); * // buffer="3.1416" float param2[2] = { 3.14159f, -123.4f }; * Unicode::snprintfFloats(buffer, 20, "%f %f", param2); * // buffer="3.142 -123.400" * @endcode * * @param [out] dst Buffer for the formatted string. * @param dstSize Size of the dst buffer measured by number of UnicodeChars the buffer * can hold. * @param [in] format The format string containing %f's. * @param [in] values The floating point values to insert for %f. The number of elements in * the array must match the number of %f's in the format string. * * @return pointer to the first element in the buffer where the formatted string is * placed. * * @see snprintf, snprintfFloat */ static UnicodeChar* snprintfFloats(UnicodeChar* dst, uint16_t dstSize, const char* format, const float* values); /** * Variant of snprintfFloats() for exactly one float only. * * The number format supports only one \%f with flags/modifiers. The following is * supported: * * \%[flags][width][.precision]f * * Where flags can be: * - '-': left justify the field (see width). * - '+': force sign. * - ' ': insert space if value is positive. * - '\#': insert decimal point even if there are not decimals. * - '0': left pad with zeros instead of spaces (see width). * * Where width is the desired width of the output. If the value is larger, more * characters may be generated, but not more than the parameter dstSize. * * Where precision is the number of number of digits after the decimal point, default is * "3". Use "\%.f" to not generate any numbers after the decimal point. * @code{.cpp} * Unicode::UnicodeChar buffer[20]; * Unicode::snprintfFloat(buffer, 20, "%6.4f", 3.14159f); * // buffer="3.1416" * Unicode::snprintfFloat(buffer, 20, "%#6.f", 3.14159f); * // buffer=" 3." * Unicode::snprintfFloat(buffer, 20, "%6f", 3.14159f); * // buffer=" 3.142" * Unicode::snprintfFloat(buffer, 20, "%+06.f", 3.14159f); * // buffer="+00003" * @endcode * * If more control over the output is needed, see snprintfFloats which can have more * than a single "\%f" in the string and also supports "*" in place of a number. * * @param [out] dst Buffer for the formatted string. * @param dstSize Size of the dst buffer measured by number of UnicodeChars the buffer * can hold. * @param [in] format The format string containing exactly on occurrence of %f. * @param value The floating point value to insert for %f. * * @return pointer to the first element in the buffer where the formatted string is * placed. * * @see snprintf, snprintfFloats */ static UnicodeChar* snprintfFloat(UnicodeChar* dst, uint16_t dstSize, const char* format, const float value) { return snprintfFloats(dst, dstSize, format, &value); } /** * Compares up to maxchars characters in two strings. One character from each buffer is * compared, one at a time until the characters differ, until a terminating null- * character is reached, or until maxchars characters match in both strings, whichever * happens first. * * @param str1 The first string. * @param str2 The second string. * @param maxchars The maximum number of chars to compare. * * @return Returns an integral value indicating the relationship between the strings: A * zero value indicates that the characters compared in both strings are all * equal. A value greater than zero indicates that the first character that does * not match has a greater value in str1 than in str2; And a value less than * zero indicates the opposite. */ static int strncmp(const UnicodeChar* RESTRICT str1, const UnicodeChar* RESTRICT str2, uint16_t maxchars); /** * Like strncmp except that ignore any whitespaces in the two strings. * * @param str1 The first string. * @param str2 The second string. * @param maxchars The maximum number of chars to compare. * * @return Returns an integral value indicating the relationship between the strings: A * zero value indicates that the characters compared in both strings are all * equal. A value greater than zero indicates that the first character that does * not match has a greater value in str1 than in str2; And a value less than * zero indicates the opposite. */ static int strncmp_ignore_whitespace(const UnicodeChar* RESTRICT str1, const UnicodeChar* RESTRICT str2, uint16_t maxchars); /** * Convert a string from UTF8 to Unicode. The conversion stops if there is no more room * in the destination or if the terminating zero character has been converted. * * @param utf8 The UTF8 string. * @param [out] dst The destination buffer for the converted string. * @param maxchars The maximum number of chars that the dst array can hold. * * @return The number of characters successfully converted from UTF8 to Unicode * including the terminating zero. */ static uint16_t fromUTF8(const uint8_t* utf8, UnicodeChar* dst, uint16_t maxchars); /** * Converts a string from Unicode to UTF8. The conversion stops if there is no more room * in the destination or if the terminating zero character has been converted. U+10000 * through U+10FFFF are skipped. * * @param unicode The Unicode string. * @param [out] utf8 The destination buffer for the converted string. * @param maxbytes The maximum number of bytes that the UTF8 array can hold. * * @return The number of characters successfully converted from Unicode to UTF8 * including the terminating zero. */ static uint16_t toUTF8(const UnicodeChar* unicode, uint8_t* utf8, uint16_t maxbytes); private: static void composeString(const UnicodeChar*& bufptr, UnicodeChar sign, UnicodeChar formatChar, bool hasPrecision, bool zeroPrefix, int precision, bool hasWidth, int width, bool alignLeft, int& charNumber, uint16_t dstSize, UnicodeChar* dst); static void parseFlagsAndPrecision(const UnicodeChar*& ucFormat, const char*& cFormat, UnicodeChar& sign, bool& alignLeft, bool& forceDecimalPoint, bool& zeroPrefix, bool& hasWidth, int& width, bool& hasPrecision, int& precision); static const UnicodeChar* skip_spaces(const UnicodeChar* str); static const UnicodeChar* skip_whitespace(const UnicodeChar* str); FORCE_INLINE_FUNCTION static UnicodeChar peekChar(const UnicodeChar* ucFormat, const char* cFormat); FORCE_INLINE_FUNCTION static void nextChar(const UnicodeChar*& ucFormat, const char*& cFormat); static UnicodeChar* vsnprintf(UnicodeChar* dst, uint16_t dstSize, const UnicodeChar* ucFormat, const char* cFormat, va_list pArg); static UnicodeChar* snprintfFloats(UnicodeChar* dst, uint16_t dstSize, const UnicodeChar* ucFormat, const char* cFormat, const float* values); }; } // namespace touchgfx #endif // TOUCHGFX_UNICODE_HPP
[ "danngreen1@gmail.com" ]
danngreen1@gmail.com
8b6d73deb680f18f4e40358be8a85b9debce5c0d
ae98aeef3da6c8c3605bec3498371e1de566c295
/thirdparty/arduino/libraries/Temboo/src/utility/TembooTimer.h
f2b444f447ebdc2ca56445996e54c0de20d9c155
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "EPL-1.0", "Apache-2.0", "BSD-3-Clause" ]
permissive
enklu/commons-avr
a7cf2119e8e0ad88d4e2a1edf201fb300c238696
352e1d33b22f2a2bb066c767c3c5755146700b18
refs/heads/master
2023-06-06T21:07:31.967106
2017-11-22T19:47:59
2017-11-22T19:47:59
111,247,797
1
1
MIT
2021-07-01T14:29:50
2017-11-18T23:23:54
C++
UTF-8
C++
false
false
1,756
h
/* ############################################################################### # # Temboo CoAP Edge Device library # # Copyright (C) 2015, Temboo 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. # ############################################################################### */ #ifndef TEMBOOTIMER_H_ #define TEMBOOTIMER_H_ class TembooTimer { public: TembooTimer() { this->m_startTimeMillis = 0; this->m_durationMillis = 0; } TembooTimer(uint32_t m_durationMillis) { this->start(m_durationMillis); } bool expired() { return leftMillis() == 0; } void start(uint32_t m_durationMillis) { this->m_startTimeMillis = getMillis(); this->m_durationMillis = m_durationMillis; } uint32_t leftMillis() { uint32_t elapsedMillis = getMillis() - this->m_startTimeMillis; return elapsedMillis < this->m_durationMillis ? (this->m_durationMillis - elapsedMillis) : 0; } protected: uint32_t getMillis() { return millis(); } uint32_t m_startTimeMillis; uint32_t m_durationMillis; }; #endif /* TEMBOOTIMER_H_ */
[ "bmj465@gmail.com" ]
bmj465@gmail.com
0ed768af28d8196c8b7754e796fae70ff7fa84bf
f5b936c57a82a479983a2adc71c2abe7d6b3ec9b
/Codeforces/round449/b.cpp
866a4b2c9b75502410252ae5b765272f89832ea1
[]
no_license
FranciscoThiesen/OldProblems
002e2099fcb7f0c874f3d8927a60d1644521bbdf
809747fceb5a75127aae832697d6f91b63d234f5
refs/heads/master
2021-08-31T16:20:28.969377
2017-12-22T02:07:05
2017-12-22T02:07:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,596
cpp
/*input 100001 1000000000000000000 */ #include <bits/stdc++.h> using namespace std; #define rep(i,a,n) for(int (i) = (a); (i) < (n); ++(i)) #define per(i,a,n) for(int (i) = (n-1); (i) >= (a); --(i)) #define fi first #define se second #define pb push_back #define mt make_tuple #define mp make_pair #define all(v) (v).begin(), (v).end() #define SZ(a) ((int)(a.size())) #define init() ios::sync_with_stdio(0);cin.tie(0); typedef unsigned long long ull; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; const int inf = 0x3f3f3f3f; const int neginf = 0xc0c0c0c0; int mod = 1000000007; ll powmod(ll a, ll b){ ll res = 1; a %= mod; assert(b>=0); for(;b;b>>=1){ if(b&1) res = (res*a)%mod; a = (a*a)%mod;} return res; } ll brute(int tot){ ll dgSz = 2; vector<vector<ll> > nums(1000); vector<ll> prevPrev; vector<ll> st{0,11,22,33,44,55,66,77,88,99}; nums[2] = vector<ll>{0,11,22,33,44,55,66,77,88,99}; ll seen = 0; ll sum = 0; tot++; while(tot){ vector<ll> nxt; ll nxDg = dgSz + 2; // if(nxDg == 4){ // rep(i,1,10){ // nxt.pb(1000 * i + i); // } // } for(const ll& v : nums[dgSz]){ sum += (v % mod); sum %= mod; tot--; if(tot == 0) return (sum % mod); } //cout << endl << endl; rep(i,1,10){ for(int k = 2; k < nxDg; k += 2){ for(const ll& v : nums[k]){ ll q = (i*powmod(10, nxDg-1) + v*powmod(10, (nxDg - k)/2) + i)%mod; nums[nxDg].pb(q); } } } if(tot == 0) return sum%mod; dgSz = nxDg; } return sum % mod; } int main(){ init(); int k; cin >> k >> mod; cout << brute(k) << endl; return 0; }
[ "franciscogthiesen@gmail.com" ]
franciscogthiesen@gmail.com
191df7bac1953cf40d19b2c3af716fd13a8b22e5
e5a8017f190452feca566465e5496a05ca9bcfd1
/pro14.cpp
087c30aff3df43fff432fc4d34896f355c102eb2
[]
no_license
ljh123294/ch10
d3055135115f5bd450ac06cd31a94eed498412a5
ac1e9783f675c6db921e763a4f3f1c9fb2f699db
refs/heads/master
2023-06-12T17:56:06.569224
2021-07-05T16:41:29
2021-07-05T16:41:29
382,989,696
0
0
null
null
null
null
UTF-8
C++
false
false
149
cpp
#include <iostream> using namespace std; int main() { auto add_int = [](int x, int y) { return x + y; }; cout << add_int(1, 2) << endl; }
[ "2441396301@qq.com" ]
2441396301@qq.com
be2fe28d27a321f87910786b6981a84aad787a9c
c2b6bd54bef3c30e53c846e9cf57f1e44f8410df
/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Predicate_1_gen1132419410.h
41c3eeb682ebeb1e1d07fe65e1761e686a3d7833
[]
no_license
PriyeshWani/CrashReproduce-5.4p1
549a1f75c848bf9513b2f966f2f500ee6c75ba42
03dd84f7f990317fb9026cbcc3873bc110b1051e
refs/heads/master
2021-01-11T12:04:21.140491
2017-01-24T14:01:29
2017-01-24T14:01:29
79,388,416
0
0
null
null
null
null
UTF-8
C++
false
false
696
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_MulticastDelegate3201952435.h" // System.Object struct Il2CppObject; // System.IAsyncResult struct IAsyncResult_t1999651008; // System.AsyncCallback struct AsyncCallback_t163412349; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Predicate`1<System.Object> struct Predicate_1_t1132419410 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "priyeshwani@gmail.com" ]
priyeshwani@gmail.com
cd9335f20147c878d493aa886be0dd59252a237b
5ff791c9d373f4403905078fe8624940044b6e38
/src/pol/undercover/interface/TradeScreen.h
400967964d252858aee7c0bb3b677a15c923769d
[]
no_license
rocking-around/PoL1.62.002
029eb63f341b9b88bc574ae430c7eaba9f943026
919abd5afa7eef92dc52d4e1d1e858b906cc577f
refs/heads/master
2023-03-21T00:20:25.192498
2020-03-19T08:46:56
2020-03-19T08:46:56
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,732
h
/*********************************************************************** Paradise Cracked Copyright by MiST land 2001 ------------------------------------------------------------------ Description: ------------------------------------------------------------------ Author: Pavel A.Duvanov Date: 13.03.2001 ************************************************************************/ #ifndef _TRADE_SCREEN_H_ #define _TRADE_SCREEN_H_ #include "Dialog.h" class TradeScreenController; class CommodityItem; class SlotScroller; class SlotsEngine; class TradeScreen : public Dialog { public: static const char* m_pDialogName; static const char* m_PortraitPath; static const char* m_PortraitExt; private: TradeScreenController* m_Controller; SlotsEngine* m_SlotsEngine; CommodityItem* m_CommodityItem; SlotScroller* m_GroundScroller; SlotScroller* m_TradeScroller; public: TradeScreen(); virtual ~TradeScreen(); public: // уведомление об изменении состояния системы void OnSystemChange(void); private: void OnChange(Widget* pChild); void OnButton(Button *pButton); void OnStatic(Static *pStatic); public: //****************** ВНЕШНИЙ ИНТЕРФЕЙС С ЛОГИКОЙ *********************// // установить контроллер логики для интерфейса void SetController(TradeScreenController* controller); // получить указатель на механизм работы со слотами SlotsEngine* GetSlotsEngine(void) const {return m_SlotsEngine;} // **** кнопка управления персонажем **** enum BUTTON { B_UNLOAD, B_BACK, B_PREV_HERO, B_NEXT_HERO, B_PREV_THING, B_NEXT_THING, B_BUY, B_SELL, MAX_BUTTON }; // показать/скрыть кнопки void EnableButton(BUTTON id,bool enable); enum SCROLLER { S_TRADE_TO_UP, S_TRADE_TO_DOWN, S_GND_TO_LEFT, S_GND_TO_RIGHT, MAX_SCROLLER }; enum SHEET { S_GUNS, S_AMMO, S_EQUIP, S_GREN, S_ARMOR, MAX_SHEET }; // показать/скрыть закладки void EnableSheet(SHEET id,bool enable); enum SHEET_STATE {SS_NORMAL,SS_PUSHED}; void SetSheetState(SHEET sheet,SHEET_STATE ss); enum SLOT { S_TRADE, S_GROUND, S_BACKPACK, S_KNEE_LEFT, S_KNEE_RIGHT, S_HANDS, S_BODY, S_IMPLANT, S_HEAD, MAX_SLOT, S_NONE }; // установка свойств предмета торговца на продажу enum COMMODITY_STATE { CS_NORMAL = 0, CS_HIGHLIGHTED = 1<<1, CS_GRAYED = 1<<2, CS_NORANK = 1<<3 }; struct CommodityTraits { std::string m_Name; // имя предмета std::string m_SystemName; // путь/идентификатор картинки std::string m_Text; // текстовое поле на предмете std::string m_Cost; // цена std::string m_BuyRank; // необходимое звание unsigned int m_State; // состояние - (подсвеченное или нет) int m_Quantity; // кол-во предметов у торговца }; void SetCommodityTraits(const CommodityTraits& ct); // описание торговца struct TraderTraits { const char* m_Portrait; const char* m_Description; }; void SetTraderTraits(const TraderTraits& t); // описание персонажа struct HeroTraits { int m_WeightCurrent; int m_WeightMax; }; // установить текстовое значение void SetHeroTraits(const HeroTraits& t); // стоимость продажи и покупки enum TEXT { T_HERO_NAME, T_HERO_MONEY, T_SALE_COST, T_HERO_RANK }; void SetText(TEXT id,const char* value); private: // создаем слоты для раскладки итемов void CreateSlots(void); // массив кнопок Button* m_Buttons[MAX_BUTTON]; // массив скроллеров Static* m_Scrollers[MAX_SCROLLER]; // массив закладок Static* m_Sheets[MAX_SHEET]; #ifdef _DEBUG_SLOTS_ENGINE // отображение виджета и всех дочерних виджетов void Render(WidgetView* pView); #endif }; //**********************************************************************// // class TradeScreenController class TradeScreenController { public: enum HANGING_MODE {HM_START,HM_FINISH}; virtual ~TradeScreenController(){}; public: virtual void OnCommodityClick(void) = 0; virtual void OnCommodityHanging(HANGING_MODE hm) = 0; virtual void OnButtonClick(TradeScreen::BUTTON id) = 0; virtual void OnSheetClick(TradeScreen::SHEET id) = 0; }; #endif //_TRADE_SCREEN_H_
[ "43969955+Hyski@users.noreply.github.com" ]
43969955+Hyski@users.noreply.github.com
5bf8937415ce6df8063384a107a9bc428fc388a5
9a94e85ef2820d626cd76123b9aa49190c991003
/HSPF_MRO_ANDR/build/iOS/Preview/include/Fuse.Elements.XFunction.h
9bfb392aa063ba622a42ad10292fec83cb45dc3c
[]
no_license
jaypk-104/FUSE
448db1717a29052f7b551390322a6167dfea34cd
0464afa07998eea8de081526a9337bd9af42dcf3
refs/heads/master
2023-03-13T14:32:43.855977
2021-03-18T01:57:10
2021-03-18T01:57:10
348,617,284
0
0
null
null
null
null
UTF-8
C++
false
false
1,487
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Elements/1.12.0/LayoutFunctions.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Elements.XYBaseLayoutFunction.h> #include <Fuse.ISourceLocation.h> #include <Fuse.Reactive.IExpression.h> namespace g{namespace Fuse{namespace Elements{struct Element;}}} namespace g{namespace Fuse{namespace Elements{struct XFunction;}}} namespace g{namespace Fuse{namespace Reactive{struct Expression;}}} namespace g{namespace Fuse{struct PlacedArgs;}} namespace g{namespace Uno{struct Float4;}} namespace g{ namespace Fuse{ namespace Elements{ // public sealed class XFunction // { ::g::Fuse::Elements::XYBaseLayoutFunction_type* XFunction_typeof(); void XFunction__ctor_3_fn(XFunction* __this, ::g::Fuse::Reactive::Expression* element); void XFunction__GetCurrentValue_fn(XFunction* __this, ::g::Fuse::Elements::Element* elm, uObject** __retval); void XFunction__GetValue_fn(XFunction* __this, ::g::Fuse::PlacedArgs* args, uObject** __retval); void XFunction__New1_fn(::g::Fuse::Reactive::Expression* element, XFunction** __retval); void XFunction__TryCompute_fn(XFunction* __this, ::g::Uno::Float4* v, int32_t* sz, uObject** value, bool* __retval); struct XFunction : ::g::Fuse::Elements::XYBaseLayoutFunction { void ctor_3(::g::Fuse::Reactive::Expression* element); static XFunction* New1(::g::Fuse::Reactive::Expression* element); }; // } }}} // ::g::Fuse::Elements
[ "sommelier0052@gmail.com" ]
sommelier0052@gmail.com
c63a53e830296a28ac06aab6991595576313d798
3cf1b7c5d273d74f9dc8efd4aa55ab08346439c5
/02_simd_lab/matvec_avx.cpp
1ab309332e4d9eb0c64cc45223950d7f388bd126
[]
no_license
jeonggunlee/GeomexSoft
d80f116c4e8c3a45503520bebb47f8d29a78cc04
c610cf752786d0e1e889006b309a3cfa3c293172
refs/heads/master
2022-10-08T01:15:13.316370
2022-09-14T13:39:44
2022-09-14T13:39:44
97,666,807
0
1
null
null
null
null
UTF-8
C++
false
false
1,986
cpp
#include <stdafx.h> #include <iostream> #include <xmmintrin.h> #include <immintrin.h> #include <chrono> void avx_matvec(float* x, float* y, float* z, size_t n){ __m256 a, b; // float* vecCon = (float*)_mm_malloc(8 * sizeof(float), 32); __declspec(align(32)) float vecCon[8]; for (size_t i = 0; i < n; i ++){ // Sets all the elements of a float32 vector to zero and returns the float32 vector. __m256 acc = _mm256_setzero_ps(); for (size_t j = 0; j < n; j += 8){ a = _mm256_load_ps(x + n*i + j); b = _mm256_load_ps(y + j); acc = _mm256_add_ps(acc, _mm256_mul_ps(a, b)); //acc = _mm256_fmadd_ps(a, b, acc); } acc = _mm256_hadd_ps(acc, acc); acc = _mm256_hadd_ps(acc, acc); acc = _mm256_hadd_ps(acc, acc); _mm256_store_ps(vecCon, acc); z[i] = vecCon[0]; } } int main(){ size_t n = 8192; // sse requires 32 bytes aligned memory float* x = (float*)_mm_malloc(n*n*sizeof(float), 32); float* y = (float*)_mm_malloc(n*sizeof(float), 32); float* z = (float*)_mm_malloc(n*sizeof(float), 32); for (size_t i = 0; i < n; ++i){ for (size_t j = 0; j < n; ++j) x[n*i + j] = i*0.45; y[i] = 1 + i*0.76; z[i] = 0.; } auto start = std::chrono::system_clock::now(); for (size_t i = 0; i < n; ++i) { z[i] = 0.0; for (size_t j = 0; j < n; ++j) z[i] += x[n*i + j] * y[j]; } std::chrono::duration<double> time = std::chrono::system_clock::now() - start; std::cout << "W/O AVX = " << time.count() << std::endl; for(size_t i = n-10; i < n; ++i) std::cout << z[i] << " "; std::cout << std::endl; start = std::chrono::system_clock::now(); avx_matvec(x,y,z,n); time = std::chrono::system_clock::now() - start; std::cout << "AVX = " << time.count() << std::endl; for(size_t i = n-10; i < n; ++i) std::cout << z[i] << " "; std::cout << std::endl; _mm_free(x); _mm_free(y); _mm_free(z); return 0; }
[ "noreply@github.com" ]
noreply@github.com
6693eb12cbfedc8f01cbbf347dca6acb782033a7
8ad5578d27673c6ea1ad84ea2dc6a9b8275e59d0
/cs251-project04-bstt/test01.cpp
e26179e6eee17e74a98f2ff3e067c0af040bb794
[]
no_license
dpchavez/Binary-Search-Tree
3a136e1d0d9b0a4716e45fc228239b4d0556d7bd
482bc31c98f1ea3f4cde32601e61b92823187422
refs/heads/main
2023-03-01T01:22:48.453381
2021-02-13T05:16:38
2021-02-13T05:16:38
338,502,764
0
0
null
null
null
null
UTF-8
C++
false
false
789
cpp
/*test01.cpp*/ // // Unit tests for threaded binary search tree // #include <iostream> #include <vector> #include "bstt.h" #include "catch.hpp" using namespace std; TEST_CASE("(1) empty tree") { bstt<int, int> tree; bstt<int, int> tree2; int key = 0; REQUIRE(tree.size() == 0); REQUIRE(tree2.size() == 0); tree.insert(1,2); tree.insert(3,8); tree.insert(5,1); tree.insert(20,3); tree.insert(29,100); tree.insert(30,100); tree.insert(70,100); tree.insert(50,100); tree2 = tree; REQUIRE(tree2.size() == 8); cout <<"--------------TREE 1 DUMP ----------------------"<< endl; tree.dump(cout); cout <<"--------------TREE 2 DUMP ----------------------"<< endl; tree2.dump(cout); tree.begin(); while (tree.next(key)) { cout << key << endl; } }
[ "noreply@github.com" ]
noreply@github.com
db4cea24ce3f12d580c3b148a1d5f62cd0805e17
da93fd008ad562305f6e40347377b44452b13a0c
/myhttpd.cpp
588d5b39cac4f99288691a51752e8c5aaa9fb924
[]
no_license
sean8purdue/HttpServer
16760b5c846d14a2a82db77794fd6892f76a6e41
df861f615fce6aa3e13ece54e7a60b17a8e51cf0
refs/heads/master
2020-12-24T07:59:26.767144
2016-11-12T05:42:20
2016-11-12T05:42:20
73,205,297
0
0
null
null
null
null
UTF-8
C++
false
false
41
cpp
int main( int argc, char **argv) { }
[ "sean8purdue@gmail.com" ]
sean8purdue@gmail.com
b28fded70c1639ba10671032da0a4ee97457d526
b42f6b685b95584721494171b9ef8be8f9b1a11c
/src/ofxUltralight.cpp
d42be6713ed1126bcb4d875bd6e39d6166fc9290
[]
no_license
danielmorena/ofxUltralight-byun
58119bdb87d753f5bd0c4e72d859b973af5901c4
c32bf8209c6d4e7e93d32566076fcc1264a851d7
refs/heads/master
2020-07-05T22:08:13.276406
2019-08-15T09:04:26
2019-08-15T09:04:26
null
0
0
null
null
null
null
UHC
C++
false
false
4,456
cpp
#include "ofxUltralight.hpp" char const * glErrorString(GLenum const err) noexcept { switch (err) { // OpenGL 2.0+ Errors: case GL_NO_ERROR: return "GL_NO_ERROR"; case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; case GL_INVALID_VALUE: return "GL_INVALID_VALUE"; case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION"; case GL_STACK_OVERFLOW: return "GL_STACK_OVERFLOW"; case GL_STACK_UNDERFLOW: return "GL_STACK_UNDERFLOW"; case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY"; // OpenGL 3.0+ Errors case GL_INVALID_FRAMEBUFFER_OPERATION: return "GL_INVALID_FRAMEBUFFER_OPERATION"; default: return "UNKNOWN ERROR"; } } ofxUltralight::ofxUltralight() { auto& platform = ultralight::Platform::instance(); Config config; { /*///맑은 고딕 config.font_family_standard = "Malgun Gothic"; config.font_family_fixed = "Malgun Gothic"; config.font_family_serif = "Malgun Gothic"; config.font_family_sans_serif = "Malgun Gothic"; */ //나눔고딕 config.font_family_standard = "NanumGothic"; config.font_family_fixed = "NanumGothicCoding"; config.font_family_serif = "NanumMyeongjo"; config.font_family_sans_serif = "NanumBarunGothic"; //PC 크롬 - 구글 창에서 검색어 렌더링 오류 있음 //config.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"; //Samsung Browser 7.2 on Android 8.1 Samsung Galaxy S9 Plus config.user_agent = "Mozilla/5.0 (Linux; Android 8.1.0; SM-G965F Build/OPM2.171019.029) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/7.2 Chrome/59.0.3071.125 Mobile Safari/537.36"; } platform.set_config(config); gpu_driver = make_shared<GPUDriverGL>(1); platform.set_gpu_driver(gpu_driver.get()); renderer = Renderer::Create(); } void ofxUltralight::update() { renderer->Update(); //여기서 아마 web 엔진이 view를 업데이트 하고 for (auto& asset : assets) { //renderer->Update() 다음, renderer->Render() 전에 불러야 함 asset.needs_redraw = asset.view->needs_paint(); } renderer->Render(); //여기서 아마 업데이트 된 view를 그리기 위한 command 를 발주 gpu_driver->DrawCommandList(); //여기서 아마 fbo에 실제로 그리기 auto driver = dynamic_pointer_cast<GPUDriverGL>(gpu_driver); auto frame_map = driver->GetFrameMap(); auto texture_map = driver->GetTextureMap(); for (int i = 0; i < assets.size(); i++) { auto& asset = assets[i]; if (asset.needs_redraw) { //점유율 최소화 asset.needs_redraw = false; auto render_target = asset.view->render_target(); GLuint fbo_id = frame_map[render_target.render_buffer_id]; GLuint tex_id = texture_map[render_target.texture_id]; CopyTextureFromFBO(fbo_id, *asset.tex); ReadTextureToPBO(tex_id, asset.pbo_id, asset.mat_rgba); cv::cvtColor(asset.mat_rgba, asset.mat_bgr, cv::COLOR_RGBA2BGR); } } } GLuint GeneratePBOReader(int width, int height, int numChannels) { int data_size = width * height * numChannels; GLuint pbo; glGenBuffers(1, &pbo); glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo); glBufferData(GL_PIXEL_PACK_BUFFER, data_size, NULL, GL_STATIC_READ); glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); return pbo; } void ReadTextureToPBO(GLuint tex_id, GLuint pbo_id[2], OUT cv::Mat & pixel_data) { int data_size = pixel_data.total() * pixel_data.elemSize(); glFinish(); //gpu 불러오기 버퍼 glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo_id[0]); glBindTexture(GL_TEXTURE_2D, tex_id); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)0 // buffer에서 시작하는 byte 단위 offset. cpu memory가 아니다! ); glBindTexture(GL_TEXTURE_2D, 0); //cpu 쓰기 버퍼 glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo_id[1]); GLubyte* mappedBuffer = (GLubyte*)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY); if (mappedBuffer) { memcpy((void*)pixel_data.data, mappedBuffer, data_size); glUnmapBuffer(GL_PIXEL_PACK_BUFFER); } glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); std::swap(pbo_id[0], pbo_id[1]); //버퍼 스왑 } void CopyTextureFromFBO(GLuint fbo_id, OUT ofTexture & tex) { int tex_id = tex.texData.textureID; int tex_target = tex.texData.textureTarget; glBindFramebuffer(GL_FRAMEBUFFER, fbo_id); glBindTexture(tex_target, tex_id); glCopyTexSubImage2D(tex_target, 0, 0, 0, 0, 0, tex.getWidth(), tex.getHeight()); //sub가 더 빠르다? glBindTexture(tex_target, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); }
[ "innoian92@gmail.com" ]
innoian92@gmail.com
09cea734dfdd90552dcb91399706307603a6cd56
920fe9cbd17610ff64891a23fc0a68386569dc10
/Scavenger.cpp
a7abe373e101c8978bb100942fbb8bedde3bd7ea
[]
no_license
LedesmaFran/WikiStrategyPattern
e9ba560e68db2e134e1826161e662617a541f35a
283657ad2db645961229095d05afec054b121a5b
refs/heads/master
2020-05-26T01:25:43.223677
2019-05-22T14:54:22
2019-05-22T14:54:22
188,060,797
0
0
null
null
null
null
UTF-8
C++
false
false
83
cpp
#include "Scavenger.h" Scavenger::Scavenger() { } Scavenger::~Scavenger() { }
[ "fledesma@itba.edu.ar" ]
fledesma@itba.edu.ar
81b7264568893517b6fa8f84de15bc3f106f861d
2b71504f52ceab03f6a1ccbef167515ca788aa55
/Projeto nº 05/_01_-_Acendendo_todos_os_LEDs/_01_-_Acendendo_todos_os_LEDs.ino
05fc4c54d9ae0ac6e0eeed39147259d8d30f1056
[]
no_license
fbryan/fontes
8840c0047d5b5f207c7721d5c464bd97e9b19bfc
d2acb356cce738b09746823e3262225a5fc55be2
refs/heads/master
2020-04-06T06:57:05.645332
2016-09-08T13:32:51
2016-09-08T13:32:51
62,343,801
4
3
null
null
null
null
UTF-8
C++
false
false
303
ino
void setup() { pinMode(2,OUTPUT); pinMode(3,OUTPUT); pinMode(4,OUTPUT); pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); } void loop() { digitalWrite(2,HIGH); digitalWrite(3,HIGH); digitalWrite(4,HIGH); digitalWrite(8,LOW); digitalWrite(9,LOW); digitalWrite(10,LOW); }
[ "fbryan@terra.com.br" ]
fbryan@terra.com.br
28b1e6ea8ed9c59922bfd900ddbd32ef775c8d90
10b4db1d4f894897b5ee435780bddfdedd91caf7
/thrift/compiler/test/fixtures/py3/gen-py3/empty/metadata.cpp
7d29244ecd3b0e02cd629a49b0491950b7e5c310
[ "Apache-2.0" ]
permissive
SammyEnigma/fbthrift
04f4aca77a64c65f3d4537338f7fbf3b8214e06a
31d7b90e30de5f90891e4a845f6704e4c13748df
refs/heads/master
2021-11-11T16:59:04.628193
2021-10-12T11:19:22
2021-10-12T11:20:27
211,245,426
1
0
Apache-2.0
2021-07-15T21:12:07
2019-09-27T05:50:42
C++
UTF-8
C++
false
false
532
cpp
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "src/gen-py3/empty/metadata.h" namespace cpp2 { ::apache::thrift::metadata::ThriftMetadata empty_getThriftModuleMetadata() { ::apache::thrift::metadata::ThriftServiceMetadataResponse response; ::apache::thrift::metadata::ThriftMetadata& metadata = *response.metadata_ref(); ::apache::thrift::detail::md::ServiceMetadata<NullServiceSvIf>::gen(response); return metadata; } } // namespace cpp2
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
7eeb774835f6b17e796bb81bd2e75ca4374807bd
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/wget/hunk_3869.cpp
c5405cd1cdd376baba1c861bacaff1d90fe5a5e6
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,131
cpp
msgid "%s: Couldn't find usable socket driver.\n" msgstr "%s: Kunde inte hitta användbar uttagsdrivrutin (socket driver).\n" -#: src/netrc.c:334 +#: src/netrc.c:367 #, c-format msgid "%s: %s:%d: warning: \"%s\" token appears before any machine name\n" msgstr "%s: %s:%d: varning: \"%s\"-märke förekommer framför alla maskinnamn\n" -#: src/netrc.c:365 +#: src/netrc.c:398 #, c-format msgid "%s: %s:%d: unknown token \"%s\"\n" msgstr "%s: %s:%d: okänt märke \"%s\"\n" -#: src/netrc.c:429 +#: src/netrc.c:462 #, c-format msgid "Usage: %s NETRC [HOSTNAME]\n" msgstr "Användning: %s NETRC [VÄRDDATORNAMN]\n" -#: src/netrc.c:439 +#: src/netrc.c:472 #, c-format msgid "%s: cannot stat %s: %s\n" msgstr "%s: kan inte ta status på %s: %s\n" -#: src/recur.c:449 src/retr.c:462 -#, c-format -msgid "Removing %s.\n" -msgstr "Tar bort %s.\n" - -#: src/recur.c:450 +#: src/recur.c:506 #, c-format msgid "Removing %s since it should be rejected.\n" msgstr "Tar bort %s eftersom den skulle ha avvisats.\n" -#: src/recur.c:609 +#: src/recur.c:680 msgid "Loading robots.txt; please ignore errors.\n" msgstr "Laddar robots.txt; vänligen ignorera fel.\n" -#: src/retr.c:193 +#: src/retr.c:217 #, c-format -msgid "\n [ skipping %dK ]" -msgstr "\n [ hoppar över %dK ]" +msgid "" +"\n" +" [ skipping %dK ]" +msgstr "" +"\n" +" [ hoppar över %dK ]" -#: src/retr.c:344 +#: src/retr.c:399 msgid "Could not find proxy host.\n" msgstr "Kunde inte hitta proxy-värden.\n" -#: src/retr.c:355 +#: src/retr.c:413 #, c-format msgid "Proxy %s: Must be HTTP.\n" msgstr "Proxy %s: Måste vara HTTP.\n" -#: src/retr.c:398 -#, c-format -msgid "%s: Redirection to itself.\n" +#: src/retr.c:507 +#, fuzzy, c-format +msgid "%s: Redirection cycle detected.\n" msgstr "%s: Omdirigering till sig själv.\n" -#: src/retr.c:483 -msgid "Giving up.\n\n" -msgstr "Ger upp.\n\n" - -#: src/retr.c:483 -msgid "Retrying.\n\n" -msgstr "Försöker igen.\n\n" - -#: src/url.c:940 -#, c-format -msgid "Error (%s): Link %s without a base provided.\n" -msgstr "Fel (%s): Länk %s given utan en bas.\n" +#: src/retr.c:601 +msgid "" +"Giving up.\n" +"\n" +msgstr "" +"Ger upp.\n" +"\n" -#: src/url.c:955 -#, c-format -msgid "Error (%s): Base %s relative, without referer URL.\n" -msgstr "Fel (%s): Basen %s relativ utan hänvisar-URL.\n" +#: src/retr.c:601 +msgid "" +"Retrying.\n" +"\n" +msgstr "" +"Försöker igen.\n" +"\n" -#: src/url.c:1373 +#: src/url.c:1325 #, c-format msgid "Converting %s... " msgstr "Konverterar %s... " -#: src/url.c:1378 src/url.c:1389 +#: src/url.c:1338 +msgid "nothing to do.\n" +msgstr "" + +#: src/url.c:1346 src/url.c:1370 #, c-format msgid "Cannot convert links in %s: %s\n" msgstr "Kan inte konvertera länkar i %s: %s\n" -#: src/utils.c:71 +#: src/url.c:1361 +#, fuzzy, c-format +msgid "Unable to delete `%s': %s\n" +msgstr "Misslyckades med att ta bort symboliska länken \"%s\": %s\n" + +#: src/url.c:1558 +#, fuzzy, c-format +msgid "Cannot back up %s as %s: %s\n" +msgstr "Kan inte konvertera länkar i %s: %s\n" + +#: src/utils.c:94 #, c-format msgid "%s: %s: Not enough memory.\n" msgstr "%s: %s: Ej tillräckligt med minne.\n" -#: src/utils.c:203 +#: src/utils.c:392 msgid "Unknown/unsupported protocol" msgstr "Okänt/ej understött protokoll" -#: src/utils.c:206 +#: src/utils.c:395 msgid "Invalid port specification" msgstr "Ogiltig portspecifikation" -#: src/utils.c:209 +#: src/utils.c:398 msgid "Invalid host name" msgstr "Ogiltigt värddatornamn" -#: src/utils.c:430 +#: src/utils.c:619 #, c-format msgid "Failed to unlink symlink `%s': %s\n" msgstr "Misslyckades med att ta bort symboliska länken \"%s\": %s\n" + +#~ msgid "" +#~ "Local file `%s' is more recent, not retrieving.\n" +#~ "\n" +#~ msgstr "" +#~ "Lokala filen \"%s\" är nyare, hämtar inte.\n" +#~ "\n" + +#~ msgid "Error (%s): Link %s without a base provided.\n" +#~ msgstr "Fel (%s): Länk %s given utan en bas.\n" + +#~ msgid "Error (%s): Base %s relative, without referer URL.\n" +#~ msgstr "Fel (%s): Basen %s relativ utan hänvisar-URL.\n"
[ "993273596@qq.com" ]
993273596@qq.com
9d9993a2efc2e0db6123754c7f744517655e649c
2d36522eb41d861d52fd4236cf6936fae451db32
/Shooter/Game/Game.h
452a2020092509fa5aa84783c2f8d627ff7c26ce
[ "BSD-2-Clause-Views" ]
permissive
michaelschrandt/personal_projects
3c7413cd1f2d8a9a2603cd484b76ed70a3c32b2c
7d4200176a7ebbff3233a86c870da910217c3a4e
refs/heads/master
2016-09-06T17:30:00.932703
2013-01-03T23:56:15
2013-01-03T23:56:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
897
h
#pragma once #include "SFML/System.hpp" #include "SFML/Graphics.hpp" #include "SFML/Audio.hpp" #include "EnumMissile.h" #include "StateMachine.h" #include "KeyMap.h" #include <iostream> #include <sstream> #include <string> const bool DEBUG = false; const int FPS = 60; const int GRAVITY = 800; const int TILE_W = 32; const int SCREEN_W = 640; const int SCREEN_H = 480; const int VISIBLE_W = 640; const int VISIBLE_H = 440; class Game { public: Game(); ~Game(); void play(); sf::SoundBuffer* bulletSoundBuffers; sf::Sound* bulletSounds; sf::Texture bulletSelectTexture; sf::Texture bulletHudTexture; sf::Texture bulletspritesheet; sf::Sprite bulletSelect; sf::Sprite bulletHud; sf::RenderWindow window; sf::Font font; sf::Clock clock; sf::Time time; sf::Rect<int> mapView; KeyMap keymap; private: StateMachine machine; void displayfps(); void init(); void deinit(); };
[ "mikevs@live.com" ]
mikevs@live.com
69970203d01c0372fdcdb195f6b11033901580bc
806608bf545d0d17aafae1128f946118cfaca215
/experiments/Carlo/MenuBar/MainWindow.cpp
ec129725e3a61d8937f058ed118e07a2d94fc9c0
[]
no_license
CFornari/CIDIA-GUI
4ec487681a1831dcbf830e1ff6d29ca435a05f3d
b95bc6be99823424897ed2cfe8e0315e8aab59d5
refs/heads/master
2022-12-04T23:09:17.814236
2020-08-20T00:47:09
2020-08-20T00:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
#include "MainWindow.h" #include "ui_MainWindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; }
[ "pop_os@pop-os.localdomain" ]
pop_os@pop-os.localdomain
f2590b7dec4e6a6b54885632afd6e3044e297f97
09491c8d8a9de4a26211021e3f1071c605cf98db
/D-category/1178D.cpp
0dca1efa2fa54c631ef953c78fd300e46734b1ea
[]
no_license
autul2017831021/Codeforces-Solved-Problem
03b81dc4968eea36cd890db55db42fa75cfd706c
ad65a028c5f52ca110a69c50069ba62edeb0da4b
refs/heads/master
2023-02-22T15:44:14.176042
2021-01-12T10:24:58
2021-01-12T10:24:58
285,258,651
5
0
null
null
null
null
UTF-8
C++
false
false
2,158
cpp
/* YOU VIRGIN ASSHOLE WHY ARE YOU HERE? */ #include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef vector<pair<ll,ll> > vp; typedef vector<ll> vc; typedef map<ll,ll> ml; typedef ostringstream OS ; typedef stringstream SS ; typedef double dl; #define pb push_back #define bg begin() #define en end() #define rbg rbegin() #define ren rend() #define sz size() #define r0 return 0; #define F first #define S second #define inf 10000000000000000000 #define ninf -1000000000 #define its (*it).S #define itf (*it).F #define nl printf("\n") #define sp printf(" ") #define yes printf("YES\n") #define no printf("NO\n") #define mone printf("-1\n") #define ne cin>> #define de cout<< #define hoynai cout<<"hoynai"<<endl; #define mod 1000000007 #define FAST_FUCK ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); bool pusu(pair<ll,ll>a,pair<ll,ll>b) { return b.second>a.second; } string ntos(ll n) { OS str1 ; str1 << n ; return str1.str(); } ll ston(string s) { ll x ; SS str1(s); str1 >> x ; return x ; } ll bigmod(ll x, ll y) { ll res = 1; while(y>0) { if(y&1) res = (res*x)%mod; y=y>>1; x= (x*x)%mod; } return res; } ll Pow(ll x, ll y) { ll res = 1; while(y>0) { if(y&1) res = (res*x); y=y>>1; x= (x*x); } return res; } ll lcm(ll a,ll b) { return (a*b)/(__gcd(a,b)); } bool isPrime(ll x) { for(ll i=2;i<=sqrt(x);i++) { if(x%i==0) return false; } return true; } main() { ll n,j=1;ne n; bool f[2000]={0}; ll lagbe=n; while(!isPrime(lagbe))lagbe++; de lagbe;nl; for(int i=1;i<=n;i++){ if(i==n) { de n;sp;de j;nl; } else{ de i;sp;de i+1;nl; } lagbe--; } while(lagbe) { if(!f[j] && !f[j+2] && j+2<=n){ de j;sp;de j+2;nl; f[j]=1;f[j+2]=1; lagbe--; } j++; } }
[ "noreply@github.com" ]
noreply@github.com
21264c0691e71cf5a61177d23e9d5761747284db
2536dc36d24a6c4783597f00e57fdd899189c4cb
/PlaywitPermutations.cpp
de5c60811c98f1cdfde3fc3903fa6f0e2207f910
[ "MIT" ]
permissive
aaryan0348/E-Lab-Object-Oriented-Programming
363a2375cba9e89c5d50a0d84a3cc7cb644a9f6c
29f3ca80dbf2268441b5b9e426415650a607195a
refs/heads/master
2020-07-11T23:34:14.945864
2019-09-04T09:17:20
2019-09-04T09:17:20
204,666,504
0
0
MIT
2019-08-27T14:50:35
2019-08-27T09:20:35
null
UTF-8
C++
false
false
213
cpp
#include <iostream> #include <algorithm> using namespace std; int main() { string s; cin>>s; do { cout << s << '\n'; } while(next_permutation(s.begin(), s.end())); return 0; }
[ "noreply@github.com" ]
noreply@github.com
881eec18581a9b78256c386fd176ceb6efdb4c68
ebb70b0cbe7626366077cbb66a58334aaf880f49
/slm_models/gecode.framework/Versions/44/include/kernel/chb.hpp
2d343e64d91cc64f17c98365ed0cc5cdc83b0f72
[ "MIT" ]
permissive
slemouton/gecodeMCP
fa06936f5159a56829a61825e90b3a297fef78dd
d038c52ffcf7351048fe5a018cee29c432d8184f
refs/heads/master
2021-07-10T22:33:26.858361
2021-05-05T21:03:55
2021-05-05T21:03:55
60,289,358
1
1
MIT
2019-01-12T16:58:17
2016-06-02T18:52:11
C++
UTF-8
C++
false
false
13,514
hpp
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Christian Schulte <schulte@gecode.org> * * Copyright: * Christian Schulte, 2017 * * Last modified: * $Date: 2017-03-09 19:51:58 +1100 (Thu, 09 Mar 2017) $ by $Author: schulte $ * $Revision: 15565 $ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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 <cfloat> namespace Gecode { /** * \brief Class for CHB management * * The idea is taken from: Exponential Recency Weighted Average * Branching Heuristic for SAT Solvers, Jia Hui Liang, Vijay Ganesh, * Pascal Poupart, Krzysztof Czarnecki, AAAI 2016, pages 3434-3440. * */ class CHB { protected: template<class View> class Recorder; /// View information class Info { public: /// Last failure unsigned long long int lf; /// Q-score double qs; }; /// Object for storing chb information class Storage : public HeapAllocated { public: /// Mutex to synchronize globally shared access Support::Mutex m; /// How many references exist for this object unsigned int use_cnt; /// Number of chb values int n; /// CHB information Info* chb; /// Number of failures unsigned long long int nf; /// Alpha value double alpha; /// Allocate CHB info template<class View> Storage(Home home, ViewArray<View>& x, typename BranchTraits<typename View::VarType>::Merit bm); /// Delete object ~Storage(void); /// Bump failure count and alpha void bump(void); /// Update chb information at position \a i void update(int i, bool failed); }; /// Pointer to storage object Storage* storage; /// Update chb value at position \a i void update(int i); /// Acquire mutex void acquire(void); /// Release mutex void release(void); /// Bump failure count and alpha void bump(void); /// Update chb information at position \a i void update(int i, bool failed); public: /// \name Constructors and initialization //@{ /** * \brief Construct as not yet intialized * * The only member functions that can be used on a constructed but not * yet initialized chb storage is init and the assignment operator. * */ CHB(void); /// Copy constructor GECODE_KERNEL_EXPORT CHB(const CHB& a); /// Assignment operator GECODE_KERNEL_EXPORT CHB& operator =(const CHB& a); /// Initialize for views \a x and Q-score as defined by \a bm template<class View> CHB(Home home, ViewArray<View>& x, typename BranchTraits<typename View::VarType>::Merit bm); /// Initialize for views \a x and Q-score as defined by \a bm template<class View> void init(Home home, ViewArray<View>& x, typename BranchTraits<typename View::VarType>::Merit bm); /// Test whether already initialized operator bool(void) const; /// Default (empty) chb information GECODE_KERNEL_EXPORT static const CHB def; //@} /// \name Update and delete chb information //@{ /// Updating during cloning GECODE_KERNEL_EXPORT void update(Space& home, bool share, CHB& a); /// Destructor GECODE_KERNEL_EXPORT ~CHB(void); //@} /// \name Information access //@{ /// Return chb value at position \a i double operator [](int i) const; /// Return number of chb values int size(void) const; //@} }; /// Propagator for recording chb information template<class View> class CHB::Recorder : public NaryPropagator<View,PC_GEN_NONE> { protected: using NaryPropagator<View,PC_GEN_NONE>::x; /// Advisor with index and change information class Idx : public Advisor { protected: /// Index and mark information int _info; public: /// Constructor for creation Idx(Space& home, Propagator& p, Council<Idx>& c, int i); /// Constructor for cloning \a a Idx(Space& home, bool share, Idx& a); /// Mark advisor as modified void mark(void); /// Mark advisor as unmodified void unmark(void); /// Whether advisor's view has been marked bool marked(void) const; /// Get index of view int idx(void) const; }; /// Access to chb information CHB chb; /// The advisor council Council<Idx> c; /// Constructor for cloning \a p Recorder(Space& home, bool share, Recorder<View>& p); public: /// Constructor for creation Recorder(Home home, ViewArray<View>& x, CHB& chb); /// Copy propagator during cloning virtual Propagator* copy(Space& home, bool share); /// Cost function (record so that propagator runs last) virtual PropCost cost(const Space& home, const ModEventDelta& med) const; /// Schedule function virtual void reschedule(Space& home); /// Give advice to propagator virtual ExecStatus advise(Space& home, Advisor& a, const Delta& d); /// Give advice to propagator when \a home has failed virtual void advise(Space& home, Advisor& a); /// Perform propagation virtual ExecStatus propagate(Space& home, const ModEventDelta& med); /// Delete propagator and return its size virtual size_t dispose(Space& home); /// Post chb recorder propagator static ExecStatus post(Home home, ViewArray<View>& x, CHB& chb); }; /** * \brief Print chb values enclosed in curly brackets * \relates CHB */ template<class Char, class Traits> std::basic_ostream<Char,Traits>& operator <<(std::basic_ostream<Char,Traits>& os, const CHB& a); /* * Advisor for chb recorder * */ template<class View> forceinline CHB::Recorder<View>::Idx::Idx(Space& home, Propagator& p, Council<Idx>& c, int i) : Advisor(home,p,c), _info(i << 1) {} template<class View> forceinline CHB::Recorder<View>::Idx::Idx(Space& home, bool share, Idx& a) : Advisor(home,share,a), _info(a._info) { } template<class View> forceinline void CHB::Recorder<View>::Idx::mark(void) { _info |= 1; } template<class View> forceinline bool CHB::Recorder<View>::Idx::marked(void) const { return (_info & 1) != 0; } template<class View> forceinline void CHB::Recorder<View>::Idx::unmark(void) { assert(marked()); _info -= 1; } template<class View> forceinline int CHB::Recorder<View>::Idx::idx(void) const { return _info >> 1; } /* * Posting of chb recorder propagator * */ template<class View> forceinline CHB::Recorder<View>::Recorder(Home home, ViewArray<View>& x, CHB& chb0) : NaryPropagator<View,PC_GEN_NONE>(home,x), chb(chb0), c(home) { home.notice(*this,AP_DISPOSE); for (int i=x.size(); i--; ) if (!x[i].assigned()) x[i].subscribe(home,*new (home) Idx(home,*this,c,i), true); } template<class View> forceinline ExecStatus CHB::Recorder<View>::post(Home home, ViewArray<View>& x, CHB& chb) { (void) new (home) Recorder<View>(home,x,chb); return ES_OK; } /* * CHB value storage * */ template<class View> forceinline CHB::Storage::Storage(Home home, ViewArray<View>& x, typename BranchTraits<typename View::VarType>::Merit bm) : use_cnt(1), n(x.size()), chb(heap.alloc<Info>(x.size())), nf(0U), alpha(Kernel::Config::chb_alpha_init) { if (bm) { for (int i=n; i--; ) { typename View::VarType xi(x[i].varimp()); chb[i].lf = 0U; chb[i].qs = bm(home,xi,i); } } else { for (int i=n; i--; ) { chb[i].lf = 0U; chb[i].qs = Kernel::Config::chb_qscore_init; } } } forceinline void CHB::Storage::bump(void) { nf++; if (alpha > Kernel::Config::chb_alpha_limit) { alpha -= Kernel::Config::chb_alpha_decrement; } } forceinline void CHB::Storage::update(int i, bool failed) { if (failed) { chb[i].lf = nf; double reward = 1.0 / (nf - chb[i].lf + 1); chb[i].qs = (1.0 - alpha) * chb[i].qs + alpha * reward; } else { double reward = 0.9 / (nf - chb[i].lf + 1); chb[i].qs = (1.0 - alpha) * chb[i].qs + alpha * reward; } } forceinline CHB::Storage::~Storage(void) { heap.free<Info>(chb,n); } /* * CHB * */ forceinline double CHB::operator [](int i) const { assert((i >= 0) && (i < storage->n)); return storage->chb[i].qs; } forceinline int CHB::size(void) const { return storage->n; } forceinline void CHB::acquire(void) { storage->m.acquire(); } forceinline void CHB::release(void) { storage->m.release(); } forceinline void CHB::bump(void) { storage->bump(); } forceinline void CHB::update(int i, bool failed) { storage->update(i,failed); } forceinline CHB::CHB(void) : storage(NULL) {} forceinline CHB::operator bool(void) const { return storage != NULL; } template<class View> forceinline CHB::CHB(Home home, ViewArray<View>& x, typename BranchTraits<typename View::VarType>::Merit bm) { assert(storage == NULL); storage = new Storage(home,x,bm); (void) Recorder<View>::post(home,x,*this); } template<class View> forceinline void CHB::init(Home home, ViewArray<View>& x, typename BranchTraits<typename View::VarType>::Merit bm) { assert(storage == NULL); storage = new Storage(home,x,bm); (void) Recorder<View>::post(home,x,*this); } template<class Char, class Traits> std::basic_ostream<Char,Traits>& operator <<(std::basic_ostream<Char,Traits>& os, const CHB& chb) { std::basic_ostringstream<Char,Traits> s; s.copyfmt(os); s.width(0); s << '{'; if (chb.size() > 0) { s << chb[0]; for (int i=1; i<chb.size(); i++) s << ", " << chb[i]; } s << '}'; return os << s.str(); } /* * Propagation for chb recorder * */ template<class View> forceinline CHB::Recorder<View>::Recorder(Space& home, bool share, Recorder<View>& p) : NaryPropagator<View,PC_GEN_NONE>(home,share,p) { chb.update(home, share, p.chb); c.update(home, share, p.c); } template<class View> Propagator* CHB::Recorder<View>::copy(Space& home, bool share) { return new (home) Recorder<View>(home, share, *this); } template<class View> inline size_t CHB::Recorder<View>::dispose(Space& home) { // Delete access to chb information home.ignore(*this,AP_DISPOSE); chb.~CHB(); // Cancel remaining advisors for (Advisors<Idx> as(c); as(); ++as) x[as.advisor().idx()].cancel(home,as.advisor(),true); c.dispose(home); (void) NaryPropagator<View,PC_GEN_NONE>::dispose(home); return sizeof(*this); } template<class View> PropCost CHB::Recorder<View>::cost(const Space&, const ModEventDelta&) const { return PropCost::record(); } template<class View> void CHB::Recorder<View>::reschedule(Space& home) { View::schedule(home,*this,ME_GEN_ASSIGNED); } template<class View> ExecStatus CHB::Recorder<View>::advise(Space&, Advisor& a, const Delta&) { static_cast<Idx&>(a).mark(); return ES_NOFIX; } template<class View> void CHB::Recorder<View>::advise(Space&, Advisor& a) { static_cast<Idx&>(a).mark(); } template<class View> ExecStatus CHB::Recorder<View>::propagate(Space& home, const ModEventDelta&) { // Lock chb information chb.acquire(); if (home.failed()) { chb.bump(); for (Advisors<Idx> as(c); as(); ++as) { int i = as.advisor().idx(); if (as.advisor().marked()) { as.advisor().unmark(); chb.update(i,true); if (x[i].assigned()) as.advisor().dispose(home,c); } } } else { for (Advisors<Idx> as(c); as(); ++as) { int i = as.advisor().idx(); if (as.advisor().marked()) { as.advisor().unmark(); chb.update(i,false); if (x[i].assigned()) as.advisor().dispose(home,c); } } } chb.release(); return c.empty() ? home.ES_SUBSUMED(*this) : ES_FIX; } } // STATISTICS: kernel-branch
[ "lemouton@ircam.Fr" ]
lemouton@ircam.Fr
cf7e5121279faa4856e554f248800df5c608a075
264757831869af06356fce91e83d62ea735eddb2
/packages/ros2/src/MetaPublisher.hpp
9f9585d9eb0dca0306f180cc42fc51bf3f89995f
[ "Apache-2.0" ]
permissive
lijian8/soss
7f7c837cfa75b4fa75b571d08631005aea8a6417
457ceef0598053ced2b5ad87beadcc25f0b42151
refs/heads/main
2023-03-29T09:05:42.280652
2021-03-29T10:35:04
2021-03-29T10:35:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,232
hpp
/* * Copyright (C) 2019 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef SOSS__ROS2__SRC__METAPUBLISHER_HPP #define SOSS__ROS2__SRC__METAPUBLISHER_HPP #include <soss/SystemHandle.hpp> #include <rclcpp/node.hpp> namespace soss { namespace ros2 { //============================================================================== std::shared_ptr<TopicPublisher> make_meta_publisher( const xtypes::DynamicType& message_type, rclcpp::Node& node, const std::string& topic_name, const rmw_qos_profile_t& qos_profile, const YAML::Node& configuration); } // namespace ros2 } // namespace soss #endif // SOSS__ROS2__SRC__METAPUBLISHER_HPP
[ "noreply@github.com" ]
noreply@github.com
e5c8e11d7baae2c7a47301ce53364443b90c339b
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_5/W+RW+RR+WW+poal+poaa+poll+L.c.cbmc.cpp
c30b99310b802bae1f290aa54c75c489a199e5a9
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
51,439
cpp
// Global variabls: // 4:atom_2_X0_1:1 // 0:vars:3 // 3:atom_1_X0_2:1 // 5:atom_2_X2_0:1 // Local global variabls: // 0:thr0:1 // 1:thr1:1 // 2:thr2:1 // 3:thr3:1 #define ADDRSIZE 6 #define LOCALADDRSIZE 4 #define NTHREAD 5 #define NCONTEXT 5 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // Declare arrays for intial value version in contexts int local_mem[LOCALADDRSIZE]; // Dumping initializations local_mem[0+0] = 0; local_mem[1+0] = 0; local_mem[2+0] = 0; local_mem[3+0] = 0; int cstart[NTHREAD]; int creturn[NTHREAD]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NTHREAD*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NTHREAD*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NTHREAD*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NTHREAD*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NTHREAD*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NTHREAD*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NTHREAD*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NTHREAD*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NTHREAD*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NTHREAD]; int cdy[NTHREAD]; int cds[NTHREAD]; int cdl[NTHREAD]; int cisb[NTHREAD]; int caddr[NTHREAD]; int cctrl[NTHREAD]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; buff(3,4) = 0; pw(3,4) = 0; cr(3,4) = 0; iw(3,4) = 0; cw(3,4) = 0; cx(3,4) = 0; is(3,4) = 0; cs(3,4) = 0; crmax(3,4) = 0; buff(3,5) = 0; pw(3,5) = 0; cr(3,5) = 0; iw(3,5) = 0; cw(3,5) = 0; cx(3,5) = 0; is(3,5) = 0; cs(3,5) = 0; crmax(3,5) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); buff(4,0) = 0; pw(4,0) = 0; cr(4,0) = 0; iw(4,0) = 0; cw(4,0) = 0; cx(4,0) = 0; is(4,0) = 0; cs(4,0) = 0; crmax(4,0) = 0; buff(4,1) = 0; pw(4,1) = 0; cr(4,1) = 0; iw(4,1) = 0; cw(4,1) = 0; cx(4,1) = 0; is(4,1) = 0; cs(4,1) = 0; crmax(4,1) = 0; buff(4,2) = 0; pw(4,2) = 0; cr(4,2) = 0; iw(4,2) = 0; cw(4,2) = 0; cx(4,2) = 0; is(4,2) = 0; cs(4,2) = 0; crmax(4,2) = 0; buff(4,3) = 0; pw(4,3) = 0; cr(4,3) = 0; iw(4,3) = 0; cw(4,3) = 0; cx(4,3) = 0; is(4,3) = 0; cs(4,3) = 0; crmax(4,3) = 0; buff(4,4) = 0; pw(4,4) = 0; cr(4,4) = 0; iw(4,4) = 0; cw(4,4) = 0; cx(4,4) = 0; is(4,4) = 0; cs(4,4) = 0; crmax(4,4) = 0; buff(4,5) = 0; pw(4,5) = 0; cr(4,5) = 0; iw(4,5) = 0; cw(4,5) = 0; cx(4,5) = 0; is(4,5) = 0; cs(4,5) = 0; crmax(4,5) = 0; cl[4] = 0; cdy[4] = 0; cds[4] = 0; cdl[4] = 0; cisb[4] = 0; caddr[4] = 0; cctrl[4] = 0; cstart[4] = get_rng(0,NCONTEXT-1); creturn[4] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(4+0,0) = 0; mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(3+0,0) = 0; mem(5+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; mem(0,1) = meminit(0,1); co(0,1) = coinit(0,1); delta(0,1) = deltainit(0,1); mem(0,2) = meminit(0,2); co(0,2) = coinit(0,2); delta(0,2) = deltainit(0,2); mem(0,3) = meminit(0,3); co(0,3) = coinit(0,3); delta(0,3) = deltainit(0,3); mem(0,4) = meminit(0,4); co(0,4) = coinit(0,4); delta(0,4) = deltainit(0,4); co(1,0) = 0; delta(1,0) = -1; mem(1,1) = meminit(1,1); co(1,1) = coinit(1,1); delta(1,1) = deltainit(1,1); mem(1,2) = meminit(1,2); co(1,2) = coinit(1,2); delta(1,2) = deltainit(1,2); mem(1,3) = meminit(1,3); co(1,3) = coinit(1,3); delta(1,3) = deltainit(1,3); mem(1,4) = meminit(1,4); co(1,4) = coinit(1,4); delta(1,4) = deltainit(1,4); co(2,0) = 0; delta(2,0) = -1; mem(2,1) = meminit(2,1); co(2,1) = coinit(2,1); delta(2,1) = deltainit(2,1); mem(2,2) = meminit(2,2); co(2,2) = coinit(2,2); delta(2,2) = deltainit(2,2); mem(2,3) = meminit(2,3); co(2,3) = coinit(2,3); delta(2,3) = deltainit(2,3); mem(2,4) = meminit(2,4); co(2,4) = coinit(2,4); delta(2,4) = deltainit(2,4); co(3,0) = 0; delta(3,0) = -1; mem(3,1) = meminit(3,1); co(3,1) = coinit(3,1); delta(3,1) = deltainit(3,1); mem(3,2) = meminit(3,2); co(3,2) = coinit(3,2); delta(3,2) = deltainit(3,2); mem(3,3) = meminit(3,3); co(3,3) = coinit(3,3); delta(3,3) = deltainit(3,3); mem(3,4) = meminit(3,4); co(3,4) = coinit(3,4); delta(3,4) = deltainit(3,4); co(4,0) = 0; delta(4,0) = -1; mem(4,1) = meminit(4,1); co(4,1) = coinit(4,1); delta(4,1) = deltainit(4,1); mem(4,2) = meminit(4,2); co(4,2) = coinit(4,2); delta(4,2) = deltainit(4,2); mem(4,3) = meminit(4,3); co(4,3) = coinit(4,3); delta(4,3) = deltainit(4,3); mem(4,4) = meminit(4,4); co(4,4) = coinit(4,4); delta(4,4) = deltainit(4,4); co(5,0) = 0; delta(5,0) = -1; mem(5,1) = meminit(5,1); co(5,1) = coinit(5,1); delta(5,1) = deltainit(5,1); mem(5,2) = meminit(5,2); co(5,2) = coinit(5,2); delta(5,2) = deltainit(5,2); mem(5,3) = meminit(5,3); co(5,3) = coinit(5,3); delta(5,3) = deltainit(5,3); mem(5,4) = meminit(5,4); co(5,4) = coinit(5,4); delta(5,4) = deltainit(5,4); // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !38, metadata !DIExpression()), !dbg !44 // br label %label_1, !dbg !45 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !43), !dbg !46 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !39, metadata !DIExpression()), !dbg !47 // call void @llvm.dbg.value(metadata i64 2, metadata !42, metadata !DIExpression()), !dbg !47 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !48 // ST: Guess // : Release iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l21_c3 old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l21_c3 // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); ASSUME(cw(1,0) >= cr(1,4+0)); ASSUME(cw(1,0) >= cr(1,0+0)); ASSUME(cw(1,0) >= cr(1,0+1)); ASSUME(cw(1,0) >= cr(1,0+2)); ASSUME(cw(1,0) >= cr(1,3+0)); ASSUME(cw(1,0) >= cr(1,5+0)); ASSUME(cw(1,0) >= cw(1,4+0)); ASSUME(cw(1,0) >= cw(1,0+0)); ASSUME(cw(1,0) >= cw(1,0+1)); ASSUME(cw(1,0) >= cw(1,0+2)); ASSUME(cw(1,0) >= cw(1,3+0)); ASSUME(cw(1,0) >= cw(1,5+0)); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 2; mem(0,cw(1,0)) = 2; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; is(1,0) = iw(1,0); cs(1,0) = cw(1,0); ASSUME(creturn[1] >= cw(1,0)); // ret i8* null, !dbg !49 ret_thread_1 = (- 1); goto T1BLOCK_END; T1BLOCK_END: // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !52, metadata !DIExpression()), !dbg !62 // br label %label_2, !dbg !50 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !61), !dbg !64 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !54, metadata !DIExpression()), !dbg !65 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) acquire, align 8, !dbg !53 // LD: Guess // : Acquire old_cr = cr(2,0); cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l27_c15 // Check ASSUME(active[cr(2,0)] == 2); ASSUME(cr(2,0) >= iw(2,0)); ASSUME(cr(2,0) >= 0); ASSUME(cr(2,0) >= cdy[2]); ASSUME(cr(2,0) >= cisb[2]); ASSUME(cr(2,0) >= cdl[2]); ASSUME(cr(2,0) >= cl[2]); ASSUME(cr(2,0) >= cx(2,0)); ASSUME(cr(2,0) >= cs(2,4+0)); ASSUME(cr(2,0) >= cs(2,0+0)); ASSUME(cr(2,0) >= cs(2,0+1)); ASSUME(cr(2,0) >= cs(2,0+2)); ASSUME(cr(2,0) >= cs(2,3+0)); ASSUME(cr(2,0) >= cs(2,5+0)); // Update creg_r0 = cr(2,0); crmax(2,0) = max(crmax(2,0),cr(2,0)); caddr[2] = max(caddr[2],0); if(cr(2,0) < cw(2,0)) { r0 = buff(2,0); ASSUME((!(( (cw(2,0) < 1) && (1 < crmax(2,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(2,0) < 2) && (2 < crmax(2,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(2,0) < 3) && (3 < crmax(2,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(2,0) < 4) && (4 < crmax(2,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(2,0) != co(0,cr(2,0))) { ASSUME(cr(2,0) >= old_cr); } pw(2,0) = co(0,cr(2,0)); r0 = mem(0,cr(2,0)); } cl[2] = max(cl[2],cr(2,0)); ASSUME(creturn[2] >= cr(2,0)); // call void @llvm.dbg.value(metadata i64 %0, metadata !56, metadata !DIExpression()), !dbg !65 // %conv = trunc i64 %0 to i32, !dbg !54 // call void @llvm.dbg.value(metadata i32 %conv, metadata !53, metadata !DIExpression()), !dbg !62 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !57, metadata !DIExpression()), !dbg !68 // call void @llvm.dbg.value(metadata i64 1, metadata !59, metadata !DIExpression()), !dbg !68 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !56 // ST: Guess // : Release iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l28_c3 old_cw = cw(2,0+1*1); cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l28_c3 // Check ASSUME(active[iw(2,0+1*1)] == 2); ASSUME(active[cw(2,0+1*1)] == 2); ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(cw(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cw(2,0+1*1) >= old_cw); ASSUME(cw(2,0+1*1) >= cr(2,0+1*1)); ASSUME(cw(2,0+1*1) >= cl[2]); ASSUME(cw(2,0+1*1) >= cisb[2]); ASSUME(cw(2,0+1*1) >= cdy[2]); ASSUME(cw(2,0+1*1) >= cdl[2]); ASSUME(cw(2,0+1*1) >= cds[2]); ASSUME(cw(2,0+1*1) >= cctrl[2]); ASSUME(cw(2,0+1*1) >= caddr[2]); ASSUME(cw(2,0+1*1) >= cr(2,4+0)); ASSUME(cw(2,0+1*1) >= cr(2,0+0)); ASSUME(cw(2,0+1*1) >= cr(2,0+1)); ASSUME(cw(2,0+1*1) >= cr(2,0+2)); ASSUME(cw(2,0+1*1) >= cr(2,3+0)); ASSUME(cw(2,0+1*1) >= cr(2,5+0)); ASSUME(cw(2,0+1*1) >= cw(2,4+0)); ASSUME(cw(2,0+1*1) >= cw(2,0+0)); ASSUME(cw(2,0+1*1) >= cw(2,0+1)); ASSUME(cw(2,0+1*1) >= cw(2,0+2)); ASSUME(cw(2,0+1*1) >= cw(2,3+0)); ASSUME(cw(2,0+1*1) >= cw(2,5+0)); // Update caddr[2] = max(caddr[2],0); buff(2,0+1*1) = 1; mem(0+1*1,cw(2,0+1*1)) = 1; co(0+1*1,cw(2,0+1*1))+=1; delta(0+1*1,cw(2,0+1*1)) = -1; is(2,0+1*1) = iw(2,0+1*1); cs(2,0+1*1) = cw(2,0+1*1); ASSUME(creturn[2] >= cw(2,0+1*1)); // %cmp = icmp eq i32 %conv, 2, !dbg !57 creg__r0__2_ = max(0,creg_r0); // %conv1 = zext i1 %cmp to i32, !dbg !57 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !60, metadata !DIExpression()), !dbg !62 // store i32 %conv1, i32* @atom_1_X0_2, align 4, !dbg !58, !tbaa !59 // ST: Guess iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l30_c15 old_cw = cw(2,3); cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l30_c15 // Check ASSUME(active[iw(2,3)] == 2); ASSUME(active[cw(2,3)] == 2); ASSUME(sforbid(3,cw(2,3))== 0); ASSUME(iw(2,3) >= creg__r0__2_); ASSUME(iw(2,3) >= 0); ASSUME(cw(2,3) >= iw(2,3)); ASSUME(cw(2,3) >= old_cw); ASSUME(cw(2,3) >= cr(2,3)); ASSUME(cw(2,3) >= cl[2]); ASSUME(cw(2,3) >= cisb[2]); ASSUME(cw(2,3) >= cdy[2]); ASSUME(cw(2,3) >= cdl[2]); ASSUME(cw(2,3) >= cds[2]); ASSUME(cw(2,3) >= cctrl[2]); ASSUME(cw(2,3) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,3) = (r0==2); mem(3,cw(2,3)) = (r0==2); co(3,cw(2,3))+=1; delta(3,cw(2,3)) = -1; ASSUME(creturn[2] >= cw(2,3)); // ret i8* null, !dbg !63 ret_thread_2 = (- 1); goto T2BLOCK_END; T2BLOCK_END: // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !79, metadata !DIExpression()), !dbg !91 // br label %label_3, !dbg !52 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !90), !dbg !93 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !81, metadata !DIExpression()), !dbg !94 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) acquire, align 8, !dbg !55 // LD: Guess // : Acquire old_cr = cr(3,0+1*1); cr(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l36_c15 // Check ASSUME(active[cr(3,0+1*1)] == 3); ASSUME(cr(3,0+1*1) >= iw(3,0+1*1)); ASSUME(cr(3,0+1*1) >= 0); ASSUME(cr(3,0+1*1) >= cdy[3]); ASSUME(cr(3,0+1*1) >= cisb[3]); ASSUME(cr(3,0+1*1) >= cdl[3]); ASSUME(cr(3,0+1*1) >= cl[3]); ASSUME(cr(3,0+1*1) >= cx(3,0+1*1)); ASSUME(cr(3,0+1*1) >= cs(3,4+0)); ASSUME(cr(3,0+1*1) >= cs(3,0+0)); ASSUME(cr(3,0+1*1) >= cs(3,0+1)); ASSUME(cr(3,0+1*1) >= cs(3,0+2)); ASSUME(cr(3,0+1*1) >= cs(3,3+0)); ASSUME(cr(3,0+1*1) >= cs(3,5+0)); // Update creg_r1 = cr(3,0+1*1); crmax(3,0+1*1) = max(crmax(3,0+1*1),cr(3,0+1*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+1*1) < cw(3,0+1*1)) { r1 = buff(3,0+1*1); ASSUME((!(( (cw(3,0+1*1) < 1) && (1 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,1)> 0)); ASSUME((!(( (cw(3,0+1*1) < 2) && (2 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,2)> 0)); ASSUME((!(( (cw(3,0+1*1) < 3) && (3 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,3)> 0)); ASSUME((!(( (cw(3,0+1*1) < 4) && (4 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,4)> 0)); } else { if(pw(3,0+1*1) != co(0+1*1,cr(3,0+1*1))) { ASSUME(cr(3,0+1*1) >= old_cr); } pw(3,0+1*1) = co(0+1*1,cr(3,0+1*1)); r1 = mem(0+1*1,cr(3,0+1*1)); } cl[3] = max(cl[3],cr(3,0+1*1)); ASSUME(creturn[3] >= cr(3,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !83, metadata !DIExpression()), !dbg !94 // %conv = trunc i64 %0 to i32, !dbg !56 // call void @llvm.dbg.value(metadata i32 %conv, metadata !80, metadata !DIExpression()), !dbg !91 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !85, metadata !DIExpression()), !dbg !97 // %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) acquire, align 8, !dbg !58 // LD: Guess // : Acquire old_cr = cr(3,0+2*1); cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l37_c15 // Check ASSUME(active[cr(3,0+2*1)] == 3); ASSUME(cr(3,0+2*1) >= iw(3,0+2*1)); ASSUME(cr(3,0+2*1) >= 0); ASSUME(cr(3,0+2*1) >= cdy[3]); ASSUME(cr(3,0+2*1) >= cisb[3]); ASSUME(cr(3,0+2*1) >= cdl[3]); ASSUME(cr(3,0+2*1) >= cl[3]); ASSUME(cr(3,0+2*1) >= cx(3,0+2*1)); ASSUME(cr(3,0+2*1) >= cs(3,4+0)); ASSUME(cr(3,0+2*1) >= cs(3,0+0)); ASSUME(cr(3,0+2*1) >= cs(3,0+1)); ASSUME(cr(3,0+2*1) >= cs(3,0+2)); ASSUME(cr(3,0+2*1) >= cs(3,3+0)); ASSUME(cr(3,0+2*1) >= cs(3,5+0)); // Update creg_r2 = cr(3,0+2*1); crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+2*1) < cw(3,0+2*1)) { r2 = buff(3,0+2*1); ASSUME((!(( (cw(3,0+2*1) < 1) && (1 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,1)> 0)); ASSUME((!(( (cw(3,0+2*1) < 2) && (2 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,2)> 0)); ASSUME((!(( (cw(3,0+2*1) < 3) && (3 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,3)> 0)); ASSUME((!(( (cw(3,0+2*1) < 4) && (4 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,4)> 0)); } else { if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) { ASSUME(cr(3,0+2*1) >= old_cr); } pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1)); r2 = mem(0+2*1,cr(3,0+2*1)); } cl[3] = max(cl[3],cr(3,0+2*1)); ASSUME(creturn[3] >= cr(3,0+2*1)); // call void @llvm.dbg.value(metadata i64 %1, metadata !87, metadata !DIExpression()), !dbg !97 // %conv4 = trunc i64 %1 to i32, !dbg !59 // call void @llvm.dbg.value(metadata i32 %conv4, metadata !84, metadata !DIExpression()), !dbg !91 // %cmp = icmp eq i32 %conv, 1, !dbg !60 creg__r1__1_ = max(0,creg_r1); // %conv5 = zext i1 %cmp to i32, !dbg !60 // call void @llvm.dbg.value(metadata i32 %conv5, metadata !88, metadata !DIExpression()), !dbg !91 // store i32 %conv5, i32* @atom_2_X0_1, align 4, !dbg !61, !tbaa !62 // ST: Guess iw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l39_c15 old_cw = cw(3,4); cw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l39_c15 // Check ASSUME(active[iw(3,4)] == 3); ASSUME(active[cw(3,4)] == 3); ASSUME(sforbid(4,cw(3,4))== 0); ASSUME(iw(3,4) >= creg__r1__1_); ASSUME(iw(3,4) >= 0); ASSUME(cw(3,4) >= iw(3,4)); ASSUME(cw(3,4) >= old_cw); ASSUME(cw(3,4) >= cr(3,4)); ASSUME(cw(3,4) >= cl[3]); ASSUME(cw(3,4) >= cisb[3]); ASSUME(cw(3,4) >= cdy[3]); ASSUME(cw(3,4) >= cdl[3]); ASSUME(cw(3,4) >= cds[3]); ASSUME(cw(3,4) >= cctrl[3]); ASSUME(cw(3,4) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,4) = (r1==1); mem(4,cw(3,4)) = (r1==1); co(4,cw(3,4))+=1; delta(4,cw(3,4)) = -1; ASSUME(creturn[3] >= cw(3,4)); // %cmp6 = icmp eq i32 %conv4, 0, !dbg !66 creg__r2__0_ = max(0,creg_r2); // %conv7 = zext i1 %cmp6 to i32, !dbg !66 // call void @llvm.dbg.value(metadata i32 %conv7, metadata !89, metadata !DIExpression()), !dbg !91 // store i32 %conv7, i32* @atom_2_X2_0, align 4, !dbg !67, !tbaa !62 // ST: Guess iw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l41_c15 old_cw = cw(3,5); cw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l41_c15 // Check ASSUME(active[iw(3,5)] == 3); ASSUME(active[cw(3,5)] == 3); ASSUME(sforbid(5,cw(3,5))== 0); ASSUME(iw(3,5) >= creg__r2__0_); ASSUME(iw(3,5) >= 0); ASSUME(cw(3,5) >= iw(3,5)); ASSUME(cw(3,5) >= old_cw); ASSUME(cw(3,5) >= cr(3,5)); ASSUME(cw(3,5) >= cl[3]); ASSUME(cw(3,5) >= cisb[3]); ASSUME(cw(3,5) >= cdy[3]); ASSUME(cw(3,5) >= cdl[3]); ASSUME(cw(3,5) >= cds[3]); ASSUME(cw(3,5) >= cctrl[3]); ASSUME(cw(3,5) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,5) = (r2==0); mem(5,cw(3,5)) = (r2==0); co(5,cw(3,5))+=1; delta(5,cw(3,5)) = -1; ASSUME(creturn[3] >= cw(3,5)); // ret i8* null, !dbg !68 ret_thread_3 = (- 1); goto T3BLOCK_END; T3BLOCK_END: // Dumping thread 4 int ret_thread_4 = 0; cdy[4] = get_rng(0,NCONTEXT-1); ASSUME(cdy[4] >= cstart[4]); T4BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !107, metadata !DIExpression()), !dbg !115 // br label %label_4, !dbg !48 goto T4BLOCK1; T4BLOCK1: // call void @llvm.dbg.label(metadata !114), !dbg !117 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !108, metadata !DIExpression()), !dbg !118 // call void @llvm.dbg.value(metadata i64 1, metadata !110, metadata !DIExpression()), !dbg !118 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) release, align 8, !dbg !51 // ST: Guess // : Release iw(4,0+2*1) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STIW _l47_c3 old_cw = cw(4,0+2*1); cw(4,0+2*1) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STCOM _l47_c3 // Check ASSUME(active[iw(4,0+2*1)] == 4); ASSUME(active[cw(4,0+2*1)] == 4); ASSUME(sforbid(0+2*1,cw(4,0+2*1))== 0); ASSUME(iw(4,0+2*1) >= 0); ASSUME(iw(4,0+2*1) >= 0); ASSUME(cw(4,0+2*1) >= iw(4,0+2*1)); ASSUME(cw(4,0+2*1) >= old_cw); ASSUME(cw(4,0+2*1) >= cr(4,0+2*1)); ASSUME(cw(4,0+2*1) >= cl[4]); ASSUME(cw(4,0+2*1) >= cisb[4]); ASSUME(cw(4,0+2*1) >= cdy[4]); ASSUME(cw(4,0+2*1) >= cdl[4]); ASSUME(cw(4,0+2*1) >= cds[4]); ASSUME(cw(4,0+2*1) >= cctrl[4]); ASSUME(cw(4,0+2*1) >= caddr[4]); ASSUME(cw(4,0+2*1) >= cr(4,4+0)); ASSUME(cw(4,0+2*1) >= cr(4,0+0)); ASSUME(cw(4,0+2*1) >= cr(4,0+1)); ASSUME(cw(4,0+2*1) >= cr(4,0+2)); ASSUME(cw(4,0+2*1) >= cr(4,3+0)); ASSUME(cw(4,0+2*1) >= cr(4,5+0)); ASSUME(cw(4,0+2*1) >= cw(4,4+0)); ASSUME(cw(4,0+2*1) >= cw(4,0+0)); ASSUME(cw(4,0+2*1) >= cw(4,0+1)); ASSUME(cw(4,0+2*1) >= cw(4,0+2)); ASSUME(cw(4,0+2*1) >= cw(4,3+0)); ASSUME(cw(4,0+2*1) >= cw(4,5+0)); // Update caddr[4] = max(caddr[4],0); buff(4,0+2*1) = 1; mem(0+2*1,cw(4,0+2*1)) = 1; co(0+2*1,cw(4,0+2*1))+=1; delta(0+2*1,cw(4,0+2*1)) = -1; is(4,0+2*1) = iw(4,0+2*1); cs(4,0+2*1) = cw(4,0+2*1); ASSUME(creturn[4] >= cw(4,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !111, metadata !DIExpression()), !dbg !120 // call void @llvm.dbg.value(metadata i64 1, metadata !113, metadata !DIExpression()), !dbg !120 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !53 // ST: Guess // : Release iw(4,0) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STIW _l48_c3 old_cw = cw(4,0); cw(4,0) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STCOM _l48_c3 // Check ASSUME(active[iw(4,0)] == 4); ASSUME(active[cw(4,0)] == 4); ASSUME(sforbid(0,cw(4,0))== 0); ASSUME(iw(4,0) >= 0); ASSUME(iw(4,0) >= 0); ASSUME(cw(4,0) >= iw(4,0)); ASSUME(cw(4,0) >= old_cw); ASSUME(cw(4,0) >= cr(4,0)); ASSUME(cw(4,0) >= cl[4]); ASSUME(cw(4,0) >= cisb[4]); ASSUME(cw(4,0) >= cdy[4]); ASSUME(cw(4,0) >= cdl[4]); ASSUME(cw(4,0) >= cds[4]); ASSUME(cw(4,0) >= cctrl[4]); ASSUME(cw(4,0) >= caddr[4]); ASSUME(cw(4,0) >= cr(4,4+0)); ASSUME(cw(4,0) >= cr(4,0+0)); ASSUME(cw(4,0) >= cr(4,0+1)); ASSUME(cw(4,0) >= cr(4,0+2)); ASSUME(cw(4,0) >= cr(4,3+0)); ASSUME(cw(4,0) >= cr(4,5+0)); ASSUME(cw(4,0) >= cw(4,4+0)); ASSUME(cw(4,0) >= cw(4,0+0)); ASSUME(cw(4,0) >= cw(4,0+1)); ASSUME(cw(4,0) >= cw(4,0+2)); ASSUME(cw(4,0) >= cw(4,3+0)); ASSUME(cw(4,0) >= cw(4,5+0)); // Update caddr[4] = max(caddr[4],0); buff(4,0) = 1; mem(0,cw(4,0)) = 1; co(0,cw(4,0))+=1; delta(0,cw(4,0)) = -1; is(4,0) = iw(4,0); cs(4,0) = cw(4,0); ASSUME(creturn[4] >= cw(4,0)); // ret i8* null, !dbg !54 ret_thread_4 = (- 1); goto T4BLOCK_END; T4BLOCK_END: // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // %thr3 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !130, metadata !DIExpression()), !dbg !159 // call void @llvm.dbg.value(metadata i8** %argv, metadata !131, metadata !DIExpression()), !dbg !159 // %0 = bitcast i64* %thr0 to i8*, !dbg !72 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !72 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !132, metadata !DIExpression()), !dbg !161 // %1 = bitcast i64* %thr1 to i8*, !dbg !74 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !74 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !136, metadata !DIExpression()), !dbg !163 // %2 = bitcast i64* %thr2 to i8*, !dbg !76 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !76 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !137, metadata !DIExpression()), !dbg !165 // %3 = bitcast i64* %thr3 to i8*, !dbg !78 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %3) #7, !dbg !78 // call void @llvm.dbg.declare(metadata i64* %thr3, metadata !138, metadata !DIExpression()), !dbg !167 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !139, metadata !DIExpression()), !dbg !168 // call void @llvm.dbg.value(metadata i64 0, metadata !141, metadata !DIExpression()), !dbg !168 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !81 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l58_c3 old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l58_c3 // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !142, metadata !DIExpression()), !dbg !170 // call void @llvm.dbg.value(metadata i64 0, metadata !144, metadata !DIExpression()), !dbg !170 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !83 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l59_c3 old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l59_c3 // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !145, metadata !DIExpression()), !dbg !172 // call void @llvm.dbg.value(metadata i64 0, metadata !147, metadata !DIExpression()), !dbg !172 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !85 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l60_c3 old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l60_c3 // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // store i32 0, i32* @atom_1_X0_2, align 4, !dbg !86, !tbaa !87 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l61_c15 old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l61_c15 // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // store i32 0, i32* @atom_2_X0_1, align 4, !dbg !91, !tbaa !87 // ST: Guess iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l62_c15 old_cw = cw(0,4); cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l62_c15 // Check ASSUME(active[iw(0,4)] == 0); ASSUME(active[cw(0,4)] == 0); ASSUME(sforbid(4,cw(0,4))== 0); ASSUME(iw(0,4) >= 0); ASSUME(iw(0,4) >= 0); ASSUME(cw(0,4) >= iw(0,4)); ASSUME(cw(0,4) >= old_cw); ASSUME(cw(0,4) >= cr(0,4)); ASSUME(cw(0,4) >= cl[0]); ASSUME(cw(0,4) >= cisb[0]); ASSUME(cw(0,4) >= cdy[0]); ASSUME(cw(0,4) >= cdl[0]); ASSUME(cw(0,4) >= cds[0]); ASSUME(cw(0,4) >= cctrl[0]); ASSUME(cw(0,4) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,4) = 0; mem(4,cw(0,4)) = 0; co(4,cw(0,4))+=1; delta(4,cw(0,4)) = -1; ASSUME(creturn[0] >= cw(0,4)); // store i32 0, i32* @atom_2_X2_0, align 4, !dbg !92, !tbaa !87 // ST: Guess iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l63_c15 old_cw = cw(0,5); cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l63_c15 // Check ASSUME(active[iw(0,5)] == 0); ASSUME(active[cw(0,5)] == 0); ASSUME(sforbid(5,cw(0,5))== 0); ASSUME(iw(0,5) >= 0); ASSUME(iw(0,5) >= 0); ASSUME(cw(0,5) >= iw(0,5)); ASSUME(cw(0,5) >= old_cw); ASSUME(cw(0,5) >= cr(0,5)); ASSUME(cw(0,5) >= cl[0]); ASSUME(cw(0,5) >= cisb[0]); ASSUME(cw(0,5) >= cdy[0]); ASSUME(cw(0,5) >= cdl[0]); ASSUME(cw(0,5) >= cds[0]); ASSUME(cw(0,5) >= cctrl[0]); ASSUME(cw(0,5) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,5) = 0; mem(5,cw(0,5)) = 0; co(5,cw(0,5))+=1; delta(5,cw(0,5)) = -1; ASSUME(creturn[0] >= cw(0,5)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !93 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call5 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !94 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call6 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !95 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %call7 = call i32 @pthread_create(i64* noundef %thr3, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t3, i8* noundef null) #7, !dbg !96 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[4] >= cdy[0]); // %4 = load i64, i64* %thr0, align 8, !dbg !97, !tbaa !98 r4 = local_mem[0]; // %call8 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !100 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %5 = load i64, i64* %thr1, align 8, !dbg !101, !tbaa !98 r5 = local_mem[1]; // %call9 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !102 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %6 = load i64, i64* %thr2, align 8, !dbg !103, !tbaa !98 r6 = local_mem[2]; // %call10 = call i32 @pthread_join(i64 noundef %6, i8** noundef null), !dbg !104 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // %7 = load i64, i64* %thr3, align 8, !dbg !105, !tbaa !98 r7 = local_mem[3]; // %call11 = call i32 @pthread_join(i64 noundef %7, i8** noundef null), !dbg !106 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[4]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !149, metadata !DIExpression()), !dbg !191 // %8 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !108 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l75_c13 // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r8 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r8 = buff(0,0); ASSUME((!(( (cw(0,0) < 1) && (1 < crmax(0,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(0,0) < 2) && (2 < crmax(0,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(0,0) < 3) && (3 < crmax(0,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(0,0) < 4) && (4 < crmax(0,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r8 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %8, metadata !151, metadata !DIExpression()), !dbg !191 // %conv = trunc i64 %8 to i32, !dbg !109 // call void @llvm.dbg.value(metadata i32 %conv, metadata !148, metadata !DIExpression()), !dbg !159 // %cmp = icmp eq i32 %conv, 2, !dbg !110 creg__r8__2_ = max(0,creg_r8); // %conv12 = zext i1 %cmp to i32, !dbg !110 // call void @llvm.dbg.value(metadata i32 %conv12, metadata !152, metadata !DIExpression()), !dbg !159 // %9 = load i32, i32* @atom_1_X0_2, align 4, !dbg !111, !tbaa !87 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l77_c13 // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r9 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r9 = buff(0,3); ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0)); ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0)); ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0)); ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0)); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r9 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i32 %9, metadata !153, metadata !DIExpression()), !dbg !159 // %10 = load i32, i32* @atom_2_X0_1, align 4, !dbg !112, !tbaa !87 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l78_c13 // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r10 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r10 = buff(0,4); ASSUME((!(( (cw(0,4) < 1) && (1 < crmax(0,4)) )))||(sforbid(4,1)> 0)); ASSUME((!(( (cw(0,4) < 2) && (2 < crmax(0,4)) )))||(sforbid(4,2)> 0)); ASSUME((!(( (cw(0,4) < 3) && (3 < crmax(0,4)) )))||(sforbid(4,3)> 0)); ASSUME((!(( (cw(0,4) < 4) && (4 < crmax(0,4)) )))||(sforbid(4,4)> 0)); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r10 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // call void @llvm.dbg.value(metadata i32 %10, metadata !154, metadata !DIExpression()), !dbg !159 // %11 = load i32, i32* @atom_2_X2_0, align 4, !dbg !113, !tbaa !87 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l79_c13 // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r11 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r11 = buff(0,5); ASSUME((!(( (cw(0,5) < 1) && (1 < crmax(0,5)) )))||(sforbid(5,1)> 0)); ASSUME((!(( (cw(0,5) < 2) && (2 < crmax(0,5)) )))||(sforbid(5,2)> 0)); ASSUME((!(( (cw(0,5) < 3) && (3 < crmax(0,5)) )))||(sforbid(5,3)> 0)); ASSUME((!(( (cw(0,5) < 4) && (4 < crmax(0,5)) )))||(sforbid(5,4)> 0)); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r11 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // call void @llvm.dbg.value(metadata i32 %11, metadata !155, metadata !DIExpression()), !dbg !159 // %and = and i32 %10, %11, !dbg !114 creg_r12 = max(creg_r10,creg_r11); r12 = r10 & r11; // call void @llvm.dbg.value(metadata i32 %and, metadata !156, metadata !DIExpression()), !dbg !159 // %and13 = and i32 %9, %and, !dbg !115 creg_r13 = max(creg_r12,creg_r9); r13 = r9 & r12; // call void @llvm.dbg.value(metadata i32 %and13, metadata !157, metadata !DIExpression()), !dbg !159 // %and14 = and i32 %conv12, %and13, !dbg !116 creg_r14 = max(creg__r8__2_,creg_r13); r14 = (r8==2) & r13; // call void @llvm.dbg.value(metadata i32 %and14, metadata !158, metadata !DIExpression()), !dbg !159 // %cmp15 = icmp eq i32 %and14, 1, !dbg !117 creg__r14__1_ = max(0,creg_r14); // br i1 %cmp15, label %if.then, label %if.end, !dbg !119 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg__r14__1_); if((r14==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([112 x i8], [112 x i8]* @.str.1, i64 0, i64 0), i32 noundef 83, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !120 // unreachable, !dbg !120 r15 = 1; goto T0BLOCK_END; T0BLOCK2: // %12 = bitcast i64* %thr3 to i8*, !dbg !123 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %12) #7, !dbg !123 // %13 = bitcast i64* %thr2 to i8*, !dbg !123 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %13) #7, !dbg !123 // %14 = bitcast i64* %thr1 to i8*, !dbg !123 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %14) #7, !dbg !123 // %15 = bitcast i64* %thr0 to i8*, !dbg !123 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %15) #7, !dbg !123 // ret i32 0, !dbg !124 ret_thread_0 = 0; goto T0BLOCK_END; T0BLOCK_END: ASSUME(meminit(0,1) == mem(0,0)); ASSUME(coinit(0,1) == co(0,0)); ASSUME(deltainit(0,1) == delta(0,0)); ASSUME(meminit(0,2) == mem(0,1)); ASSUME(coinit(0,2) == co(0,1)); ASSUME(deltainit(0,2) == delta(0,1)); ASSUME(meminit(0,3) == mem(0,2)); ASSUME(coinit(0,3) == co(0,2)); ASSUME(deltainit(0,3) == delta(0,2)); ASSUME(meminit(0,4) == mem(0,3)); ASSUME(coinit(0,4) == co(0,3)); ASSUME(deltainit(0,4) == delta(0,3)); ASSUME(meminit(1,1) == mem(1,0)); ASSUME(coinit(1,1) == co(1,0)); ASSUME(deltainit(1,1) == delta(1,0)); ASSUME(meminit(1,2) == mem(1,1)); ASSUME(coinit(1,2) == co(1,1)); ASSUME(deltainit(1,2) == delta(1,1)); ASSUME(meminit(1,3) == mem(1,2)); ASSUME(coinit(1,3) == co(1,2)); ASSUME(deltainit(1,3) == delta(1,2)); ASSUME(meminit(1,4) == mem(1,3)); ASSUME(coinit(1,4) == co(1,3)); ASSUME(deltainit(1,4) == delta(1,3)); ASSUME(meminit(2,1) == mem(2,0)); ASSUME(coinit(2,1) == co(2,0)); ASSUME(deltainit(2,1) == delta(2,0)); ASSUME(meminit(2,2) == mem(2,1)); ASSUME(coinit(2,2) == co(2,1)); ASSUME(deltainit(2,2) == delta(2,1)); ASSUME(meminit(2,3) == mem(2,2)); ASSUME(coinit(2,3) == co(2,2)); ASSUME(deltainit(2,3) == delta(2,2)); ASSUME(meminit(2,4) == mem(2,3)); ASSUME(coinit(2,4) == co(2,3)); ASSUME(deltainit(2,4) == delta(2,3)); ASSUME(meminit(3,1) == mem(3,0)); ASSUME(coinit(3,1) == co(3,0)); ASSUME(deltainit(3,1) == delta(3,0)); ASSUME(meminit(3,2) == mem(3,1)); ASSUME(coinit(3,2) == co(3,1)); ASSUME(deltainit(3,2) == delta(3,1)); ASSUME(meminit(3,3) == mem(3,2)); ASSUME(coinit(3,3) == co(3,2)); ASSUME(deltainit(3,3) == delta(3,2)); ASSUME(meminit(3,4) == mem(3,3)); ASSUME(coinit(3,4) == co(3,3)); ASSUME(deltainit(3,4) == delta(3,3)); ASSUME(meminit(4,1) == mem(4,0)); ASSUME(coinit(4,1) == co(4,0)); ASSUME(deltainit(4,1) == delta(4,0)); ASSUME(meminit(4,2) == mem(4,1)); ASSUME(coinit(4,2) == co(4,1)); ASSUME(deltainit(4,2) == delta(4,1)); ASSUME(meminit(4,3) == mem(4,2)); ASSUME(coinit(4,3) == co(4,2)); ASSUME(deltainit(4,3) == delta(4,2)); ASSUME(meminit(4,4) == mem(4,3)); ASSUME(coinit(4,4) == co(4,3)); ASSUME(deltainit(4,4) == delta(4,3)); ASSUME(meminit(5,1) == mem(5,0)); ASSUME(coinit(5,1) == co(5,0)); ASSUME(deltainit(5,1) == delta(5,0)); ASSUME(meminit(5,2) == mem(5,1)); ASSUME(coinit(5,2) == co(5,1)); ASSUME(deltainit(5,2) == delta(5,1)); ASSUME(meminit(5,3) == mem(5,2)); ASSUME(coinit(5,3) == co(5,2)); ASSUME(deltainit(5,3) == delta(5,2)); ASSUME(meminit(5,4) == mem(5,3)); ASSUME(coinit(5,4) == co(5,3)); ASSUME(deltainit(5,4) == delta(5,3)); ASSERT(r15== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
478efec6b163d7eec299fbc5c8599d2a76731d35
98157b3124db71ca0ffe4e77060f25503aa7617f
/codeforces/368_2/c.cpp
b913d46dfd93b2d0fdd156010f09f20f4a53fbab
[]
no_license
wiwitrifai/competitive-programming
c4130004cd32ae857a7a1e8d670484e236073741
f4b0044182f1d9280841c01e7eca4ad882875bca
refs/heads/master
2022-10-24T05:31:46.176752
2022-09-02T07:08:05
2022-09-02T07:08:35
59,357,984
37
4
null
null
null
null
UTF-8
C++
false
false
286
cpp
#include <bits/stdc++.h> using namespace std; int main() { long long n; cin >> n; if (n < 3) cout << -1 << endl; else if (n & 1) cout << (n * n - 1) / 2 << " " << (n * n + 1)/2 << endl; else cout << (n * n / 4 - 1) << " " << (n * n /4 + 1) << endl; return 0; }
[ "wiwitrifai@gmail.com" ]
wiwitrifai@gmail.com
e79cf7a40d8d6139af39028900e55f8695478676
19a0bb9ba76357ee3e3fec3368676872ba0fe52f
/components/consent_auditor/consent_auditor.h
2247c0bebfee5c6c14cea1c415ab1cd4ab5a0de8
[ "BSD-3-Clause" ]
permissive
C351/chromium
f2cf547e5a3bd7dfe85090189a811f8afdce2519
efb6eca4dfa14ea18a449c2f0c3c659dd1d5ce01
refs/heads/master
2023-02-26T14:46:38.518313
2018-02-25T03:16:38
2018-02-25T03:16:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,903
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_CONSENT_AUDITOR_CONSENT_AUDITOR_H_ #define COMPONENTS_CONSENT_AUDITOR_CONSENT_AUDITOR_H_ #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "components/keyed_service/core/keyed_service.h" namespace syncer { class UserEventService; } namespace sync_pb { class UserEventSpecifics; } class PrefService; class PrefRegistrySimple; namespace consent_auditor { // These enum is used in histograms. Entries should not be renumbered and // numeric values should never be reused. enum class Feature { CHROME_SYNC = 0, // TODO(crbug.com/645032): There is currently just one supported feature, but // histograms with only one bucket are not supported. Remove this hack when // more features are added, or when crbug.com/645032 is fixed. FEATURE_COUNT = 2 }; enum class ConsentStatus { NOT_GIVEN, GIVEN }; class ConsentAuditor : public KeyedService { public: ConsentAuditor(PrefService* pref_service, syncer::UserEventService* user_event_service, const std::string& app_version, const std::string& app_locale); ~ConsentAuditor() override; // KeyedService: void Shutdown() override; // Registers the preferences needed by this service. static void RegisterProfilePrefs(PrefRegistrySimple* registry); // Records a consent for |feature| for the signed-in GAIA account. // Consent text consisted of strings with |consent_grd_ids|, and the UI // element the user clicked had the ID |confirmation_grd_id|. // Whether the consent was GIVEN or NOT_GIVEN is passed as |status|. void RecordGaiaConsent(Feature feature, const std::vector<int>& description_grd_ids, int confirmation_grd_id, ConsentStatus status); // Records that the user consented to a |feature|. The user was presented with // |description_text| and accepted it by interacting |confirmation_text| // (e.g. clicking on a button; empty if not applicable). // Returns true if successful. void RecordLocalConsent(const std::string& feature, const std::string& description_text, const std::string& confirmation_text); private: std::unique_ptr<sync_pb::UserEventSpecifics> ConstructUserConsent( Feature feature, const std::vector<int>& description_grd_ids, int confirmation_grd_id, ConsentStatus status); PrefService* pref_service_; syncer::UserEventService* user_event_service_; std::string app_version_; std::string app_locale_; DISALLOW_COPY_AND_ASSIGN(ConsentAuditor); }; } // namespace consent_auditor #endif // COMPONENTS_CONSENT_AUDITOR_CONSENT_AUDITOR_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
af12d24abe7c29795caf249a3a569e295a7b2d5d
067da28279c40f4a0a9cc5749b7826bda044a772
/cpp/files/gut/part-21/timing.h
b3b36168d61d8ff74f80db9847fe604f12f9ad34
[]
no_license
gzuliani/gzuliani.github.io
0fcaf30034530a5e73ccd47c2b4970a061d9bb8a
f6a0b9f333298f539a436a7bf3cdb198bcc34e23
refs/heads/master
2023-04-17T00:14:57.503185
2023-04-05T18:49:47
2023-04-05T18:49:47
203,596,069
0
0
null
null
null
null
UTF-8
C++
false
false
1,856
h
#ifndef GUT_TIMING_H #define GUT_TIMING_H #define GUT_HAS_CHRONO #if defined(_MSC_VER) && (_MSC_VER <= 1600) #undef GUT_HAS_CHRONO #endif #ifdef GUT_HAS_CHRONO #include "timing-chrono.h" #else #include "timing-custom.h" #endif #define GUT_DURATION(expr_) \ [&] { \ gut::Timer timer_; \ (void)(expr_); \ return timer_.elapsedTime(); \ }() #define SHOULD_LAST_AT_MOST(expr_, limit_) \ GUT_BEGIN \ auto duration_ = GUT_DURATION(expr_); \ if (duration_ > limit_) \ WARN( \ std::string(#expr_) \ + " took " \ + gut::toString(gut::match_duration(duration_, limit_)) \ + " (expected less than " \ + gut::toString(gut::match_duration(limit_, duration_)) \ + ")"); \ GUT_END #define LASTS_AT_MOST(expr_, limit_) \ GUT_BEGIN \ auto duration_ = GUT_DURATION(expr_); \ if (duration_ > limit_) \ gut::theListener.failure( \ gut::DurationFailure( \ #expr_, \ gut::match_duration(duration_, limit_), \ gut::match_duration(limit_, duration_), \ __FILE__, \ __LINE__)); \ GUT_END #define REQUIRE_LASTS_AT_MOST(expr_, limit_) \ GUT_BEGIN \ auto duration_ = GUT_DURATION(expr_); \ if (duration_ > limit_) { \ gut::theListener.failure( \ gut::FatalDurationFailure( \ #expr_, \ gut::match_duration(duration_, limit_), \ gut::match_duration(limit_, duration_), \ __FILE__, \ __LINE__)); \ throw gut::AbortTest(); \ } \ GUT_END #endif // GUT_TIMING_H
[ "gianfranco.zuliani@gmail.com" ]
gianfranco.zuliani@gmail.com
c74d2c58a6aed94b4ce54ce8c19b69938e643609
67ea3f01e6cd4b9d3551d5f31184130efe61b471
/Lib/Kernels/Matrix.h
c565067a289388af60b74211f34bf9765695d60e
[ "MIT" ]
permissive
ASR-Engineering-Consulting/V3DLib
a4d33c9436aed34eeef412935753252b86c820fc
393cc112866b64019830f66984663d1731ecb68e
refs/heads/main
2023-05-07T21:57:54.957983
2021-05-31T06:58:28
2021-05-31T06:58:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,320
h
#ifndef _V3DLIB_KERNELS_MATRIX_H_ #define _V3DLIB_KERNELS_MATRIX_H_ #include "V3DLib.h" #include "Support/Helpers.h" //////////////////////////////////////////////////////////////////////////////// // Kernel code definitions for Matrix //////////////////////////////////////////////////////////////////////////////// namespace kernels { using namespace V3DLib; //////////////////////////////////////////////////////////////////////////////// // Class DotVector //////////////////////////////////////////////////////////////////////////////// /** * Kernel helper class for loading in a sequence of values into QPU registers * * A Number of registers in the register file are allocated for the sequence. * These registers are indexed to retain the order. * 16 consequent values are loaded into the vector of a register. * * The goal here is to have the entire sequence of values loaded into the QPU * register file, so that it can be reused. * This, of course, places an upper limit on the length of the sequence. */ class DotVector { public: DotVector(int size); void load(Float::Ptr input); void save(Float::Ptr dst); void dot_product(Float::Ptr rhs, Float &result); void dft_dot_product(Int const &k, Complex &result); size_t size() const { return elements.size(); } Float &operator[] (int index) { return elements[index]; } Float const &operator[] (int index) const { return elements[index]; } private: std::vector<Float> elements; }; //////////////////////////////////////////////////////////////////////////////// // API functions //////////////////////////////////////////////////////////////////////////////// enum MatrixReadMethod { DEFAULT, // No prefetch DO_PREFETCH, NO_READWRITE }; void square_matrix_mult_scalar(int N, float *dst, float *a, float *b); void matrix_mult(Float::Ptr dst, Float::Ptr a, Float::Ptr b); using FuncType = decltype(matrix_mult); FuncType *matrix_mult_decorator(int dimension, MatrixReadMethod read_method = DO_PREFETCH); FuncType *matrix_mult_decorator( Float::Array2D &a, Float::Array2D &b, Float::Array2D &result, MatrixReadMethod read_method = DO_PREFETCH); /////////////////////////////////////////////////////////////////////////////// // Complex arrays /////////////////////////////////////////////////////////////////////////////// class ComplexDotVector { public: ComplexDotVector(int size) : re(size), im(size) {} size_t size() const; void load(Complex::Ptr const &rhs); void load(Float::Ptr const &rhs); void save(Complex::Ptr output) { re.save(output.re()); im.save(output.im()); } void dot_product(Complex::Ptr rhs, Complex &result); void dft_dot_product(Int const &k, Complex &result); private: DotVector re; DotVector im; }; void complex_matrix_mult(Complex::Ptr dst, Complex::Ptr a, Complex::Ptr b); using ComplexFuncType = decltype(complex_matrix_mult); ComplexFuncType *complex_matrix_mult_decorator( Complex::Array2D &a, Complex::Array2D &b, Complex::Array2D &result, MatrixReadMethod read_method = DO_PREFETCH ); /////////////////////////////////////////////////////////////////////////////// // DFT /////////////////////////////////////////////////////////////////////////////// using DftFuncType = void (*)(Complex::Ptr dst, Complex::Ptr a); DftFuncType dft_inline_decorator( Complex::Array2D &a, Complex::Array2D &result, MatrixReadMethod read_method = DO_PREFETCH ); using DftFuncType2 = void (*)(Complex::Ptr dst, Float::Ptr a); DftFuncType2 dft_inline_decorator( Float::Array &a, Complex::Array2D &result, MatrixReadMethod read_method = DO_PREFETCH ); } // namespace kernels namespace V3DLib { /** * Do block matrix multiplication * * Currently, the matrices are each split into 2 blocks. * This serves as a proof of concept; in due time it, is possible * to split them into any number of block matrices, thereby allowing * arbitrary dimensions for the matrices (multiples of 16, always). */ class Matrix { using KernelType = V3DLib::Kernel<Float::Ptr, Float::Ptr, Float::Ptr>; using BlockKernelType = V3DLib::Kernel<Float::Ptr, Float::Ptr, Float::Ptr, Int>; public: enum { DEFAULT_NUM_BLOCKS = -1, // Let instance figure out itself whether to use full or block mult // Following values are empirically determined (i.e. by trying out) // There is actually some point in lowering the max value for vc4, because block mult is more efficient MAX_FULL_BLOCKS_VC4 = 800, // Highest dimension where full mult can be used for vc4 MAX_FULL_BLOCKS_V3D = 800, // Highest dimension where full mult can be used for v3d }; Matrix(Float::Array2D &a, Float::Array2D &b); void setNumQPUs(int val); void num_blocks(int val); Float::Array2D &result() { return m_result; } void mult(); BlockKernelType &kernel() { return *m_k; } void compile() { init_block(); } bool has_errors() const { return m_k_first_vc4->has_errors() || m_k->has_errors(); } private: int m_num_blocks = DEFAULT_NUM_BLOCKS; Float::Array2D &m_a; Float::Array2D &m_b; Float::Array2D m_result; std::unique_ptr<BlockKernelType> m_k; std::unique_ptr<BlockKernelType> m_k_first_vc4; void init_block(); int num_blocks() const; }; } // namespace V3DLib #endif // _V3DLIB_KERNELS_MATRIX_H_
[ "wrijnders@gmail.com" ]
wrijnders@gmail.com
84a3cb7df2c095041963ac2dae4c4eb4d6828a29
309975d60e30260f2e02d11e71eaaf6e08b93659
/Modules/MemoryProfilerService/Sources/MemoryProfilerService/ServiceInfo.h
528f751d901ff2abcccefa991fb22b6bff41b233
[]
permissive
BlitzModder/dava.engine
e83b038a9d24b37c00b095e83ffdfd8cd497823c
0c7a16e627fc0d12309250d6e5e207333b35361e
refs/heads/development
2023-03-15T12:30:32.342501
2018-02-19T11:09:02
2018-02-19T11:09:02
122,161,150
4
3
BSD-3-Clause
2018-02-20T06:00:07
2018-02-20T06:00:07
null
UTF-8
C++
false
false
137
h
#pragma once #include <Network/ServiceRegistrar.h> namespace DAVA { namespace Net { const ServiceID MEMORY_PROFILER_SERVICE_ID = 1; } }
[ "m_molokovskih@wargaming.net" ]
m_molokovskih@wargaming.net
4dc8180ce9abfc78c2358f48c6b52fc742c6ed7c
45364deefe009a0df9e745a4dd4b680dcedea42b
/SDK/FSD_Cheat_VanityList_parameters.hpp
d60349e156de7d44fc2e505fbe631587317e3465
[]
no_license
RussellJerome/DeepRockGalacticSDK
5ae9b59c7324f2a97035f28545f92773526ed99e
f13d9d8879a645c3de89ad7dc6756f4a7a94607e
refs/heads/master
2022-11-26T17:55:08.185666
2020-07-26T21:39:30
2020-07-26T21:39:30
277,796,048
0
0
null
null
null
null
UTF-8
C++
false
false
1,930
hpp
#pragma once // DeepRockGalactic SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "FSD_Cheat_VanityList_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Cheat_VanityList.Cheat_VanityList_C.Set Vanity List struct UCheat_VanityList_C_Set_Vanity_List_Params { TArray<class UVanityItem*>* vanityItems; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm) EVanitySlot* Vanity_Class_type; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function Cheat_VanityList.Cheat_VanityList_C.On State change struct UCheat_VanityList_C_On_State_change_Params { bool* Is_Checked; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UVanityItem** Vanity; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) EVanitySlot* Vanity_Type; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function Cheat_VanityList.Cheat_VanityList_C.ExecuteUbergraph_Cheat_VanityList struct UCheat_VanityList_C_ExecuteUbergraph_Cheat_VanityList_Params { int* EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "darkmanvoo@gmail.com" ]
darkmanvoo@gmail.com
63067cbb5acaee260d541843cf39171c4f3fc763
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/boost/mpl/vector/aux_/preprocessed/typeof_based/vector20_c.hpp
ac110b79147b6391240572ce37ae24c72ff2ee8c
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,829
hpp
 // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Preprocessed version of "sstd/boost/mpl/vector/vector20_c.hpp" header // -- DO NOT modify by hand! namespace boost { namespace mpl { template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10 > struct vector11_c : v_item< integral_c< T,C10 > , vector10_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9 > > { typedef vector11_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10 , T C11 > struct vector12_c : v_item< integral_c< T,C11 > , vector11_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10 > > { typedef vector12_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10 , T C11, T C12 > struct vector13_c : v_item< integral_c< T,C12 > , vector12_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11 > > { typedef vector13_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10 , T C11, T C12, T C13 > struct vector14_c : v_item< integral_c< T,C13 > , vector13_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12 > > { typedef vector14_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10 , T C11, T C12, T C13, T C14 > struct vector15_c : v_item< integral_c< T,C14 > , vector14_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12,C13 > > { typedef vector15_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10 , T C11, T C12, T C13, T C14, T C15 > struct vector16_c : v_item< integral_c< T,C15 > , vector15_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12,C13,C14 > > { typedef vector16_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10 , T C11, T C12, T C13, T C14, T C15, T C16 > struct vector17_c : v_item< integral_c< T,C16 > , vector16_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12,C13,C14,C15 > > { typedef vector17_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10 , T C11, T C12, T C13, T C14, T C15, T C16, T C17 > struct vector18_c : v_item< integral_c< T,C17 > , vector17_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12,C13,C14,C15,C16 > > { typedef vector18_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10 , T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18 > struct vector19_c : v_item< integral_c< T,C18 > , vector18_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12,C13,C14,C15,C16,C17 > > { typedef vector19_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9, T C10 , T C11, T C12, T C13, T C14, T C15, T C16, T C17, T C18, T C19 > struct vector20_c : v_item< integral_c< T,C19 > , vector19_c< T,C0,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12,C13,C14,C15,C16,C17,C18 > > { typedef vector20_c type; typedef T value_type; }; }}
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
5a758339ee04426cb951951d09a8a6776e3ba6a3
99f6da83c5beb159db74356665813818ba13c7ea
/text/text_buffer_range_unittest.cc
d2b8ddf7aaa9fbf039bef12ea6dd154887949165
[ "ISC" ]
permissive
abarth/zi
140246dedaf348638b76818ea4c5c148b40fc6ec
1cdd73a36c8d79d1e1c6fc7ff7195b0ad0b8214f
refs/heads/master
2020-12-24T06:08:23.929452
2016-08-19T07:53:36
2016-08-19T07:53:36
64,037,301
2
0
null
null
null
null
UTF-8
C++
false
false
2,973
cc
// Copyright (c) 2016, Google Inc. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #include "text/text_buffer_range.h" #include <string> #include "gtest/gtest.h" namespace zi { namespace { TEST(TextBufferRange, Default) { TextBufferRange range; EXPECT_TRUE(range.is_empty()); EXPECT_EQ(0u, range.start()); EXPECT_EQ(0u, range.end()); EXPECT_EQ(0u, range.length()); EXPECT_FALSE(range.is_dirty()); } TEST(TextBufferRange, Control) { TextBufferRange range(4, 7); EXPECT_FALSE(range.is_empty()); EXPECT_EQ(4u, range.start()); EXPECT_EQ(7u, range.end()); EXPECT_EQ(3u, range.length()); EXPECT_FALSE(range.is_dirty()); range.ShiftForward(2); EXPECT_EQ(6u, range.start()); EXPECT_EQ(9u, range.end()); EXPECT_FALSE(range.is_dirty()); range.ShiftBackward(1); EXPECT_EQ(5u, range.start()); EXPECT_EQ(8u, range.end()); EXPECT_FALSE(range.is_dirty()); range.PushFront(3); EXPECT_EQ(2u, range.start()); EXPECT_EQ(8u, range.end()); EXPECT_TRUE(range.is_dirty()); range.MarkClean(); EXPECT_FALSE(range.is_dirty()); range.PushFront(3); EXPECT_EQ(0u, range.start()); EXPECT_EQ(8u, range.end()); EXPECT_TRUE(range.is_dirty()); range.MarkClean(); EXPECT_FALSE(range.is_dirty()); range.ShiftBackward(1); EXPECT_EQ(0u, range.start()); EXPECT_EQ(8u, range.end()); EXPECT_FALSE(range.is_dirty()); range.PopFront(2); EXPECT_EQ(2u, range.start()); EXPECT_EQ(8u, range.end()); EXPECT_TRUE(range.is_dirty()); range.MarkClean(); EXPECT_FALSE(range.is_dirty()); range.PopFront(7); EXPECT_EQ(9u, range.start()); EXPECT_EQ(9u, range.end()); EXPECT_TRUE(range.is_dirty()); EXPECT_TRUE(range.is_empty()); range.MarkClean(); EXPECT_FALSE(range.is_dirty()); range.PushBack(5); EXPECT_EQ(9u, range.start()); EXPECT_EQ(14u, range.end()); EXPECT_TRUE(range.is_dirty()); range.MarkClean(); EXPECT_FALSE(range.is_dirty()); range.PopBack(4); EXPECT_EQ(9u, range.start()); EXPECT_EQ(10u, range.end()); EXPECT_TRUE(range.is_dirty()); range.MarkClean(); EXPECT_FALSE(range.is_dirty()); range.PopBack(4); EXPECT_EQ(6u, range.start()); EXPECT_EQ(6u, range.end()); EXPECT_TRUE(range.is_dirty()); range.MarkClean(); EXPECT_FALSE(range.is_dirty()); } } // namespace } // namespace zi
[ "abarth@chromium.org" ]
abarth@chromium.org
69ef3d816a279b122c1f871827c761a583425f6f
710ac923ad7aaaf3c59882a057a2ebbe159ef135
/Ogre-1.9a/OgreMain/src/OgreAxisAlignedBox.cpp
dba2f74a995b4d0bfbdd45d6eb8605e4f252b998
[]
no_license
lennonchan/OgreKit
3e8ec4b0f21653cb668d5cd7d58acc8d45de6a96
ac5ca9b9731ce5f8eb145e7a8414e781f34057ab
refs/heads/master
2021-01-01T06:04:40.107584
2013-04-19T05:02:42
2013-04-19T05:02:42
9,538,177
1
3
null
null
null
null
UTF-8
C++
false
false
1,577
cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2012 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreAxisAlignedBox.h" namespace Ogre { const AxisAlignedBox AxisAlignedBox::BOX_NULL; const AxisAlignedBox AxisAlignedBox::BOX_INFINITE(AxisAlignedBox::EXTENT_INFINITE); }
[ "qinlong.mkl@gmail.com" ]
qinlong.mkl@gmail.com
b6cc2bab2fc0538fd9eafd3b55d99072f06c5313
6a9f099663aca2eea9795df7c5306fb0996ee36a
/ProviderClient/OrderView.cpp
c0b640808f4f0b898dfb1f51a404befce6fb77c2
[]
no_license
Galytskyi/iCafe
f741e3adc60601fcfefb7ef455f636507861147f
e259f8a3a2ee00ce4ecb361d1646c556fe770d5d
refs/heads/master
2020-03-28T20:34:39.839396
2018-11-01T07:30:47
2018-11-01T07:30:47
148,613,893
0
0
null
null
null
null
UTF-8
C++
false
false
16,900
cpp
#include "OrderView.h" #include <QApplication> #include <QScreen> #include <QHeaderView> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QMessageBox> #include <QEvent> #include <QResizeEvent> #include <QPainter> #include "Options.h" #include "../lib/wassert.h" // ------------------------------------------------------------------------------------------------------------------- // // OrderItem // // ------------------------------------------------------------------------------------------------------------------- OrderDelegate::OrderDelegate(QObject *parent) : QStyledItemDelegate(parent) { m_dpi = QApplication::screens().at(0)->logicalDotsPerInch() / 1.5; m_iconSize = m_dpi / 1.5; m_iconSmallSize = m_iconSize / 2; m_providerNameFont = new QFont("Arial", 14, 10); m_providerAddressFont = new QFont("Arial", 10, 10); m_dotsBlackPixmap = QPixmap(":/icons/MenuBlack.png"); m_dotsGrayPixmap = QPixmap(":/icons/MenuGray.png"); m_tablePixmap = QPixmap(":/icons/Table.png"); m_dinnerPixmap = QPixmap(":/icons/Dinner.png"); } // ------------------------------------------------------------------------------------------------------------------- void OrderDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { Order::Item order = qvariant_cast<Order::Item>(index.data(Qt::UserRole)); QSize cellSize = QFontMetrics(painter->font()).size(Qt::TextSingleLine,"A"); if ((option.state & QStyle::State_Selected) != 0) { if ((option.state & QStyle::State_HasFocus) != 0) { painter->fillRect(option.rect, Qt::white); } else { painter->fillRect(option.rect, QColor(0xE0, 0xFF, 0xFF)); } } if (theOptions.platformType() == PLATFORM_TYPE_ANDROID) { QString orderState; QString orderPhone; switch(order.state()) { case Order::STATE_ORDER_OK: orderState = tr("Заказ принят"); orderPhone = tr("Номер телефона: %1").arg("+380"+QString::number(order.phone())); painter->fillRect(option.rect, QColor(0xDE, 0xFF, 0xB8)); break; case Order::STATE_ORDER_CANCEL: orderState = tr("Заказ отменен"); orderPhone = tr("Номер телефона: %1").arg("+380"+QString::number(order.phone())); painter->fillRect(option.rect, QColor(0xFF, 0xA0, 0xA0)); break; case Order::STATE_ORDER_PROCESSING: orderState = tr("Ожидает ответа"); orderPhone= tr("Номер телефона: +38 (***) **-**-***"); painter->fillRect(option.rect, QColor(0xff, 0xfa, 0xd1)); break; } int midDots_x = option.rect.right() - m_iconSmallSize - 20; int midDots_y = option.rect.top() + cellSize.height(); if ((option.state & QStyle::State_Selected) == 0) { painter->drawPixmap(midDots_x, midDots_y, m_iconSmallSize, m_iconSmallSize, m_dotsGrayPixmap); } else { painter->drawPixmap(midDots_x, midDots_y, m_iconSmallSize, m_iconSmallSize, m_dotsBlackPixmap); } // order data // QRect orderDataRect = option.rect; orderDataRect.adjust(m_dpi*1.5, cellSize.height(), -m_dpi, 0); QFont simpleFont = painter->font(); QFont boldFont = painter->font(); boldFont.setBold(true); Order::Time32 orderTime = order.orderTime(); QString orderDataStr = tr("%1 человек(a)").arg(order.people()) + tr(", на %1").arg(QString().sprintf("%02d:%02d", orderTime.hour, orderTime.minute)); switch(order.type()) { case Order::TYPE_TABLE: orderDataStr.insert(0, tr("Столик для ")); break; case Order::TYPE_DINNER: orderDataStr.insert(0, tr("Обед для ")); break; default: wassert(0); break; } painter->setFont(boldFont); painter->setPen(QColor(0x0, 0x0, 0x0)); painter->drawText(orderDataRect, Qt::AlignLeft, orderDataStr); painter->setFont(simpleFont); //orderDataRect.adjust(0, cellSize.height()/2, 0, 0); orderDataRect.adjust(0, cellSize.height()*1.5, 0, 0); painter->setPen(QColor(0x70, 0x70, 0x70)); painter->drawText(orderDataRect, Qt::AlignLeft, orderPhone ); // Order time // painter->setPen(QColor(0x00, 0x00, 0x00)); int coordState_x = m_dpi*1.5 / 2 - m_iconSize / 2; int coordState_y = option.rect.y() + cellSize.height()/2; if (orderState.isEmpty() == false) { switch (order.type()) { case Order::TYPE_TABLE: painter->drawPixmap(coordState_x, coordState_y + cellSize.height()/2, m_iconSize, m_iconSize, m_tablePixmap); break; case Order::TYPE_DINNER: painter->drawPixmap(coordState_x, coordState_y + cellSize.height()/2, m_iconSize, m_iconSize, m_dinnerPixmap); break; } Order::Time32 orderTime = order.orderTime(); QString orderTimeStr = QString().sprintf("%02d:%02d", orderTime.hour, orderTime.minute); QRect timeOrderRect = orderDataRect; timeOrderRect.adjust(0, cellSize.height()/2, 0, 0); timeOrderRect.setLeft(option.rect.left()); timeOrderRect.setRight(m_dpi*1.5); painter->drawText(timeOrderRect, Qt::AlignCenter, orderTimeStr); } // order state // QRect stateOrderRect = orderDataRect; stateOrderRect.adjust(0, cellSize.height()*1.5, 0, 0); stateOrderRect.setLeft(option.rect.left()); stateOrderRect.setRight(option.rect.right() - 30); painter->drawText(stateOrderRect, Qt::AlignRight, orderState); } else { QString orderState; QString orderPhone; switch(order.state()) { case Order::STATE_ORDER_OK: orderState = tr("Заказ принят"); orderPhone = tr("Номер телефона: %1").arg("+380"+QString::number(order.phone())); painter->fillRect(option.rect, QColor(0xDE, 0xFF, 0xB8)); break; case Order::STATE_ORDER_CANCEL: orderState = tr("Заказ отменен"); orderPhone = tr("Номер телефона: %1").arg("+380"+QString::number(order.phone())); painter->fillRect(option.rect, QColor(0xFF, 0xA0, 0xA0)); break; case Order::STATE_ORDER_PROCESSING: orderState = tr("Ожидает ответа"); orderPhone= tr("Номер телефона: +38 (***) **-**-***"); painter->fillRect(option.rect, QColor(0xff, 0xfa, 0xd1)); break; } int midDots_x = option.rect.right() - m_iconSmallSize - 20; int midDots_y = option.rect.top() + 10; if ((option.state & QStyle::State_Selected) == 0) { painter->drawPixmap(midDots_x, midDots_y, m_iconSmallSize, m_iconSmallSize, m_dotsGrayPixmap); } else { painter->drawPixmap(midDots_x, midDots_y, m_iconSmallSize, m_iconSmallSize, m_dotsBlackPixmap); } // order data // QRect orderDataRect = option.rect; orderDataRect.adjust(m_dpi, 5, -m_dpi, 0); Order::Time32 orderTime = order.orderTime(); QString orderDataStr = tr("%1 человек(a)").arg(order.people()) + tr(", на %1").arg(QString().sprintf("%02d:%02d", orderTime.hour, orderTime.minute)); switch(order.type()) { case Order::TYPE_TABLE: orderDataStr.insert(0, tr("Столик для ")); break; case Order::TYPE_DINNER: orderDataStr.insert(0, tr("Обед для ")); break; default: wassert(0); break; } painter->setFont(*m_providerNameFont); painter->setPen(QColor(0x0, 0x0, 0x0)); painter->drawText(orderDataRect, Qt::AlignLeft, orderDataStr); QSize cellSize = QFontMetrics(*m_providerNameFont).size(Qt::TextSingleLine,"A"); orderDataRect.adjust(0, cellSize.height() + 10, 0, 0); painter->setFont(*m_providerAddressFont); painter->setPen(QColor(0x70, 0x70, 0x70)); painter->drawText(orderDataRect, Qt::AlignLeft, orderPhone ); // order state // QRect stateOrderRect = orderDataRect; stateOrderRect.adjust(0, 10,0,0); stateOrderRect.setLeft(option.rect.right() - 500); stateOrderRect.setRight(option.rect.right() - 30); painter->setPen(QColor(0x40, 0x40, 0x40)); painter->drawText(stateOrderRect, Qt::AlignRight, orderState); // Order time // if (orderState.isEmpty() == false) { int icon_x = m_dpi / 2 - m_iconSize / 2; switch (order.type()) { case Order::TYPE_TABLE: painter->drawPixmap(icon_x, option.rect.y() + 3, m_iconSize, m_iconSize, m_tablePixmap); break; case Order::TYPE_DINNER: painter->drawPixmap(icon_x, option.rect.y() + 3 , m_iconSize, m_iconSize, m_dinnerPixmap); break; } QRect timeOrderRect = stateOrderRect; timeOrderRect.setLeft(0); timeOrderRect.setRight(m_dpi); Order::Time32 orderTime = order.orderTime(); QString orderTimeStr = QString().sprintf("%02d:%02d", orderTime.hour, orderTime.minute); painter->setPen(QColor(0x40, 0x40, 0x40)); painter->drawText(timeOrderRect, Qt::AlignCenter, orderTimeStr); } } } // ------------------------------------------------------------------------------------------------------------------- // // OrderTable // // ------------------------------------------------------------------------------------------------------------------- OrderTable::OrderTable(QObject*) { } // ------------------------------------------------------------------------------------------------------------------- OrderTable::~OrderTable() { m_orderList.clear(); } // ------------------------------------------------------------------------------------------------------------------- int OrderTable::columnCount(const QModelIndex&) const { return ORDER_COLUMN_COUNT; } // ------------------------------------------------------------------------------------------------------------------- int OrderTable::rowCount(const QModelIndex&) const { return m_orderList.count(); } // ------------------------------------------------------------------------------------------------------------------- QVariant OrderTable::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) { return QVariant(); } QVariant result = QVariant(); if (orientation == Qt::Horizontal) { if (section >= 0 && section < ORDER_COLUMN_COUNT) { result = OrderColumn[section]; } } if (orientation == Qt::Vertical) { result = QString("%1").arg(section + 1); } return result; } // ------------------------------------------------------------------------------------------------------------------- QVariant OrderTable::data(const QModelIndex &index, int role) const { if (index.isValid() == false) { return QVariant(); } int row = index.row(); if (row < 0 || row >= m_orderList.count()) { return QVariant(); } int column = index.column(); if (column < 0 || column > ORDER_COLUMN_COUNT) { return QVariant(); } Order::Item order = m_orderList.at(row); if (order.isEmpty() == true || order.isValid() == false) { return QVariant(); } if (role == Qt::UserRole) { QVariant var; var.setValue(order); return var; } return QVariant(); } // ------------------------------------------------------------------------------------------------------------------- QString OrderTable::text(int row, int column, const Order::Item& order) const { if (row < 0 || row >= m_orderList.count()) { return QString(); } if (column < 0 || column > ORDER_COLUMN_COUNT) { return QString(); } QString result; switch (column) { case ORDER_COLUMN_NAME: { Order::Time32 orderTime = order.orderTime(); result = tr(" %1 человек").arg(order.people()) + tr(", на: %1").arg(QString().sprintf("%02d:%02d", orderTime.hour, orderTime.minute)) + QString("\n"); if (order.state() == Order::STATE_ORDER_OK) { result += tr(" Номер телеофна: %1").arg(QString::number(order.phone())); } else { result += tr(" Номер телефона: +38 (***) **-**-***"); } } break; default: wassert(0); break; } return result; } // ------------------------------------------------------------------------------------------------------------------- void OrderTable::updateRow(int row) { if (row < 0 || row >= m_orderList.count()) { return; } for (int column = 0; column < ORDER_COLUMN_COUNT; column ++) { QModelIndex cellIndex = index(row, column); emit dataChanged(cellIndex, cellIndex, QVector<int>() << Qt::DisplayRole); } } // ------------------------------------------------------------------------------------------------------------------- void OrderTable::updateColumn(int column) { if (column < 0 || column >= ORDER_COLUMN_COUNT) { return; } int count = m_orderList.count(); for (int row = 0; row < count; row ++) { QModelIndex cellIndex = index(row, column); emit dataChanged(cellIndex, cellIndex, QVector<int>() << Qt::DisplayRole); } } // ------------------------------------------------------------------------------------------------------------------- Order::Item OrderTable::order(int index) const { if (index < 0 || index >= count()) { return Order::Item(); } return m_orderList[index]; } // ------------------------------------------------------------------------------------------------------------------- void OrderTable::set(int index, const Order::Item& order) { if (index < 0 || index >= count()) { return; } m_orderList[index] = order; } // ------------------------------------------------------------------------------------------------------------------- void OrderTable::set(const QList<Order::Item>& list_add) { int count = list_add.count(); if (count == 0) { return; } beginInsertRows(QModelIndex(), 0, count - 1); m_orderList = list_add; endInsertRows(); } // ------------------------------------------------------------------------------------------------------------------- void OrderTable::append(const Order::Item &order) { if (order.isEmpty() == true || order.isValid() == false) { return; } beginInsertRows(QModelIndex(), 0, 0); m_orderList.append(order); endInsertRows(); } // ------------------------------------------------------------------------------------------------------------------- void OrderTable::remove(int index) { if (index < 0 || index >= count()) { return; } beginRemoveRows(QModelIndex(), index, index); m_orderList.removeAt(index); endRemoveRows(); } // ------------------------------------------------------------------------------------------------------------------- void OrderTable::clear() { int count = m_orderList.count(); if (count == 0) { return; } beginRemoveRows(QModelIndex(), 0, count - 1); m_orderList.clear(); endRemoveRows(); } // ------------------------------------------------------------------------------------------------------------------- // // OrderView // // ------------------------------------------------------------------------------------------------------------------- OrderView::OrderView() { setModel(&m_table); horizontalHeader()->hide(); verticalHeader()->hide(); setSelectionMode(QAbstractItemView::SingleSelection); OrderDelegate* textDelegate = new OrderDelegate(this); setItemDelegateForColumn(ORDER_COLUMN_NAME, textDelegate); if (theOptions.platformType() == PLATFORM_TYPE_ANDROID) { QSize cellSize = QFontMetrics(font()).size(Qt::TextSingleLine,"A"); verticalHeader()->setDefaultSectionSize(cellSize.height() * ORDER_COLUMN_STR_COUNT); } else { QFont* listFont = new QFont("Arial", 14, 2); setFont(*listFont); QSize cellSize = QFontMetrics(font()).size(Qt::TextSingleLine,"A"); verticalHeader()->setDefaultSectionSize(cellSize.height()*3); } m_table.set(theOrderBase.orderList()); } // ------------------------------------------------------------------------------------------------------------------- OrderView::~OrderView() { } // ------------------------------------------------------------------------------------------------------------------- void OrderView::appentToList(const Order::Item& order) { m_table.append(order); } // ------------------------------------------------------------------------------------------------------------------- void OrderView::changeState(const Order::Item& order) { int count = m_table.count(); for(int i = 0; i < count; i++) { if (m_table.order(i).handle().ID == order.handle().ID) { m_table.set(i, order); m_table.updateRow(i); break; } } } // ------------------------------------------------------------------------------------------------------------------- void OrderView::removeFromList(quint64 orderID) { int count = m_table.count(); for(int i = 0; i < count; i++) { if (m_table.order(i).handle().ID == orderID) { m_table.remove(i); break; } } } // ------------------------------------------------------------------------------------------------------------------- bool OrderView::event(QEvent* e) { if (e->type() == QEvent::Resize) { QResizeEvent* resizeEvent = static_cast<QResizeEvent*>(e); setColumnWidth(ORDER_COLUMN_NAME, resizeEvent->size().width()); } return QTableView::event(e); } // -------------------------------------------------------------------------------------------------------------------
[ "Galytskyi@gmail.com" ]
Galytskyi@gmail.com
df1d24331cd08c2406ffc7d1d2223be5c5aafe16
74e24051a3f9716f37db97d17afb74393926c1f9
/week 1/ex01.2/main.cpp
8bc5b32d773520ce7d1b8fb2e8c1260a4ae5a659
[]
no_license
luong-komorebi/CS162
8c959b35530bdb08ed2e1fd5e5b711c09002afd2
1cebaa695e22ac9adb79b05b3ad68f32a8cc2bc3
refs/heads/master
2021-06-10T18:29:01.040818
2016-12-23T18:02:28
2016-12-23T18:02:28
59,766,529
1
0
null
2023-09-07T08:43:15
2016-05-26T16:35:22
C++
UTF-8
C++
false
false
500
cpp
#include <iostream> #include <math.h> using namespace std; #include "fraction.h" int main(){ cout << " hello and welcome to my program" ; Complex c1, c2; inputComplex ( c1); cout << endl; outputComplex( c1); cout << endl; inputComplex ( c2); cout << endl; outputComplex( c2); cout << endl; add2Complex( c1, c2); cout << endl; substract2Complex( c1, c2); cout << " c1: "; absComplex(c1); cout << " c2: "; absComplex(c2); cout << endl; ssComplex(c1,c2); cout << endl; return 0; }
[ "vo.tran.thanh.luong@gmail.com" ]
vo.tran.thanh.luong@gmail.com
96c1bf0349fcb503d3008c6a9e238aae41558cdd
c4df621c96893985f75bfe7399237f0bc54e963d
/pc/copTest/linklist.h
6d140a9f84fa1c1278fdc5b087de94cb04be5db1
[]
no_license
coploftbas/XDraw
612fe331fa58f8b6b2a167ea7220d6a7c7534d9b
4b0c317af80ca296520636d12290218f6d80b6bc
refs/heads/master
2020-03-30T20:33:15.816151
2015-04-26T15:14:50
2015-04-26T15:14:50
151,592,924
0
0
null
2018-10-04T15:19:49
2018-10-04T15:19:49
null
UTF-8
C++
false
false
334
h
#ifndef LINKLIST #define LINKLIST #include <QtGui> #include <QtCore> #include <iostream> #include <cstring> typedef struct node { qreal id; std::string label;// = "MyLabel"; qreal x; qreal y; qreal width; qreal height; std::string color;// = "A4A4A4"; struct node *next; }LNK_LST; #endif // LINKLIST
[ "coploftbas@gmail.com" ]
coploftbas@gmail.com
ffe1f7ee1a0a6043f6a433189d5e0717ffdc730d
43a2fbc77f5cea2487c05c7679a30e15db9a3a50
/Cpp/External/SDK/BP_RailingLight_SmallShip_Wheel_classes.h
4d9386a1d99806cedfdc6ddc5ea5260f040a8b05
[]
no_license
zH4x/SoT-Insider-SDK
57e2e05ede34ca1fd90fc5904cf7a79f0259085c
6bff738a1b701c34656546e333b7e59c98c63ad7
refs/heads/main
2023-06-09T23:10:32.929216
2021-07-07T01:34:27
2021-07-07T01:34:27
383,638,719
0
0
null
null
null
null
UTF-8
C++
false
false
872
h
#pragma once // Name: SoT-Insider, Version: 1.102.2382.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_RailingLight_SmallShip_Wheel.BP_RailingLight_SmallShip_Wheel_C // 0x0000 (FullSize[0x0749] - InheritedSize[0x0749]) class ABP_RailingLight_SmallShip_Wheel_C : public ABP_InteractableShipRailingLight_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_RailingLight_SmallShip_Wheel.BP_RailingLight_SmallShip_Wheel_C"); return ptr; } void AfterRead(); void BeforeDelete(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "Massimo.linker@gmail.com" ]
Massimo.linker@gmail.com
e8465aad9ef204d57c1ed51b84c2983ce5c4b28b
d8fc8a50fbedfc80c2ba8bbc57697763751d7144
/src/main.cpp
e6a29f2cfd9532b468191bef49b341887be993a1
[]
no_license
sid-dey/racebot
1163bea502107af0f8b88fdd64bc8c5663576c20
5a2b7d8d20c953bec0e073882619b18c49fbf230
refs/heads/main
2023-03-21T19:41:59.158879
2021-03-11T00:44:01
2021-03-11T00:44:01
346,533,853
0
0
null
null
null
null
UTF-8
C++
false
false
230
cpp
#include <iostream> #include "Racecar.hpp" #include <vector> int main() { std::vector<double> initial_condition{1, 2, 3, 4}; Racecar r1(initial_condition); std::cout << "initial_condition" << std::endl; return 0; }
[ "siddey@umich.edu" ]
siddey@umich.edu
a84b39f7800c8e69e0fb92040fd9479802e9d52f
4d4e21a5d850560049ca638b0224a6a483d5b9cd
/C++/152_Combinations.cpp
947a1dbd9dc60c73962d7c3022d7364bf46ac432
[]
no_license
gky2009514/lintcode
08fec3baa5b3cb9547d72fc78d16fea348fa55a5
050bbb80de079a923d4435e84964d7022196f642
refs/heads/master
2020-05-17T21:45:52.468525
2015-09-07T03:09:56
2015-09-07T03:09:56
35,482,338
1
1
null
null
null
null
UTF-8
C++
false
false
731
cpp
class Solution { public: /** * @param n: Given the range of numbers * @param k: Given the numbers of combinations * @return: All the combinations of k numbers out of 1..n */ vector<vector<int> > combine(int n, int k) { vector<vector<int> > res; this->k = k, this->n = n; getCom(1, res); return res; } private: int k, n; vector<int> com; void getCom(int m, vector<vector<int> > &r) { if (com.size() >= k) { r.push_back(com); return; } if (m > n || n - m + 1 < k - com.size()) return; com.push_back(m); getCom(m + 1, r); com.pop_back(); getCom(m + 1, r); } };
[ "729756565@qq.com" ]
729756565@qq.com
df95423a5ba91748419a764c3cd78cec9e057dbe
407d194b52fe9cf75cca9d6f3c162a565549a1ae
/Diagnostic/mdsd/mdscommands/CmdXmlCommon.hh
5b1e16b100d9933b15f6918b0df257d238d26e0e
[ "Apache-2.0", "MIT" ]
permissive
Azure/azure-linux-extensions
808761f927045f00548aa68e38d4bec8651c0eba
3cea1567fc4f4eb5beea9884153e92d70610394d
refs/heads/master
2023-08-27T14:06:05.775617
2023-08-23T01:56:05
2023-08-23T01:56:05
19,841,123
300
314
Apache-2.0
2023-09-14T04:21:26
2014-05-16T01:38:49
Python
UTF-8
C++
false
false
732
hh
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #ifndef __CMDXMLCOMMON_HH__ #define __CMDXMLCOMMON_HH__ #include <string> #include <vector> namespace mdsd { class CmdXmlCommon { public: static std::string GetRootContainerName() { return s_rootContainerName; } static void SetRootContainerName(std::string name) { s_rootContainerName = std::move(name); } private: static std::string s_rootContainerName; }; namespace details { void ValidateCmdBlobParamsList( const std::vector<std::vector<std::string>>& paramsList, const std::string & verbName, size_t totalParams ); } // namespace details } // namespace mdsd #endif // __CMDXMLCOMMON_HH__
[ "noreply@github.com" ]
noreply@github.com
7373429bfb3544718d3e8f7fe654ce12b5d7b3f7
645c8a660c9fa9c8a0a05d357a60815c56b14f11
/ThreadOO/includes/CLASS_Thread.h
e06054e10f1ab2b4ec5407f8ad0c4746a6963ac7
[]
no_license
andyvincent/Garry-s-Mod-Extensions
706167ce0a20f8e17f732ca6ebb4dca13259d247
8b10f8fbd666471550fa0b7833ba048e266eb446
refs/heads/master
2020-04-05T23:25:02.972421
2010-05-26T16:18:23
2010-05-26T16:18:23
643,728
0
1
null
null
null
null
UTF-8
C++
false
false
2,041
h
#ifndef _CLASS_THREAD_H_ #define _CLASS_THREAD_H_ #include "PlatformSpecific.h" #include <vector> #include <map> #include "CLASS_Mutex.h" void msleep(unsigned int milli); /*! \brief Thread class */ class Thread { public: static Thread* currentThread(); /*! \brief Generic event notification */ typedef struct { unsigned int id; void* data; } EventData; /*! \brief Constructor */ Thread(void); /*! \brief Destructor */ virtual ~Thread(void); /*! \brief Start the thread */ virtual bool start(); /*! \brief Wait for the thread to complete */ virtual void wait(); /*! \brief Called before the thread is run */ virtual bool init(); /*! \brief Activity to perform */ virtual int run() = 0; /*! \brief Called after the thread has run */ virtual void exit(); /*! \brief Check if the thread is still running */ inline bool isRunning() { return m_running; } /*! \brief Get the full list of posted events. */ void getEvents(std::vector<EventData>& events); /*! \brief Get a single event. */ bool getEvent(EventData& event); /*! \brief Post an event to the list */ void postEvent(int eventID, void* data = 0); /*! \brief Check if there are any events. */ bool hasEvents(); private: /*! \brief Clear any variables when the thread finishes */ void done(); bool m_running; #ifdef WIN32 typedef HANDLE ThreadHandleType; DWORD m_threadID; /*! \brief Thread entry point (windows) */ static DWORD WINAPI threadProc(void* p); #elif LINUX typedef pthread_t ThreadHandleType; static void* threadProc(void* p); #else #error Unhandled Platform! #endif ThreadHandleType m_thread; static Mutex s_activeThreadMutex; static std::map<ThreadHandleType, Thread*> s_activeThreads; typedef std::map<ThreadHandleType, Thread*>::iterator ThreadIterator; Mutex m_eventList; std::vector<EventData> m_events; void setActive(bool b); }; #endif //_CLASS_THREAD_H_
[ "andy.i.vincent@gmail.com" ]
andy.i.vincent@gmail.com
82f305799db57495e8eb1bf494cce8ee290f1f18
658994d544a2382ca32693efe96c0853b8048bbd
/src/codec/CodecPhaseShiftNStep.h
4568608876950986df35113cff2ff0119092ef90
[]
no_license
sparsebase/slstudio
5a9822b0a86c1f5f3c0bdc2cd48be33b32e95916
3f439f6b62dd6e7dd572d5fb331e4446e29e87dc
refs/heads/master
2020-04-06T04:32:58.319797
2016-02-06T06:37:09
2016-02-06T06:37:09
44,309,659
2
2
null
2016-06-02T20:19:45
2015-10-15T10:08:28
C++
UTF-8
C++
false
false
838
h
#ifndef CODECPhaseShiftNStep_H #define CODECPhaseShiftNStep_H #include "Codec.h" // 8 step phase shifting codec with phase unwrapping class EncoderPhaseShiftNStep : public Encoder { public: EncoderPhaseShiftNStep(unsigned int _screenCols, unsigned int _screenRows, CodecDir _dir); // Encoding cv::Mat getEncodingPattern(unsigned int depth); private: std::vector<cv::Mat> patterns; }; class DecoderPhaseShiftNStep : public Decoder { public: DecoderPhaseShiftNStep(unsigned int _screenCols, unsigned int _screenRows, CodecDir _dir); // Decoding void setFrame(unsigned int depth, cv::Mat frame); void decodeFrames(cv::Mat &up, cv::Mat &vp, cv::Mat &mask, cv::Mat &shading); private: std::vector<cv::Mat> frames; }; #endif // CODECPhaseShiftNStep_H
[ "jakw@dtu.dk" ]
jakw@dtu.dk
d917108a7b13cab387e66f43cd4b8ecb8a0b0d1b
80b8b1e1743e2ac72c361414e80cd9b2f5bcf075
/CTCI150/Chapter2/2.3.cpp
d42b11aa3db23c5aa3cad62bb12608a15d9a4200
[]
no_license
abcd1236386/Programming
41fb8ea7b7d261cd8bf7f29850197cf6bddf4c59
7985094979c113f7f0c4bb77c4ec86406825cff5
refs/heads/master
2021-01-20T04:37:11.164418
2015-03-10T13:05:02
2015-03-10T13:05:02
25,914,597
0
0
null
null
null
null
UTF-8
C++
false
false
696
cpp
/* Auther:haozy Problem:2.3 Language:C++ Description:remove a middle node of link list */ #include<iostream> #include<fstream> #include<vector> #include<algorithm> #include<map> #include<set> #include<string> #include<cstring> using namespace std; struct list { list *next; int val; }; void remove(list * p) { if(p==NULL||p->next==NULL) return ; list *n=p->next; p->next=n->next; p->val=n->val; } int main(){ list nd[5]; for(int i=0;i<5;i++) { nd[i].next=nd+i+1; nd[i].val=i; } nd[4].next=0; remove(nd+2); list *t=nd; while(t){ cout<<t->val<<' '; t=t->next; } cout<<endl; }
[ "450522366@qq.com" ]
450522366@qq.com
5e476126450b2f04c1e2ea853ef5643c6186bbc0
20efa2aea40e691b5985b7a0524cb9e44c9ace8a
/common/src/pvlist.hh
8bdb33f8db4f0f31dae94b017ecb77b0128c5c82
[ "BSD-2-Clause" ]
permissive
gad23/codesloop
1834e4ef6d8905cb2aef58a08bd43c834c6f825d
cee4f07bd0c36a89f1cd034585f4bbab8a0075a8
refs/heads/master
2021-01-16T19:49:33.881743
2009-06-05T18:48:17
2009-06-05T18:48:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,020
hh
/* Copyright (c) 2008,2009, David Beck Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _csl_common_pvlist_hh_included_ #define _csl_common_pvlist_hh_included_ /** @file pvlist.hh @brief Very simple pointer store (a list of pointer vectors/arrays) pvlist is intended for uses when many small memory allocation is done and they are not deallocated up to the end of the task. Then these memory blocks could be deallocated together. The memory blocks would not be iterated over. Free function is provided but not recommended, because it is slow. pvlist is a template class that could use different template policies for freeing its data. 3 are provided: nop_destructor that does nothing, free_destructor and delete_destructor. the design goal of pvlist is to be fast for the outlined specific case, thus: 1) should have minimal overhead when instantiated 2) should have minimal overhead when adding new pointers 3) should have minimal overhead when destroyed on the downside pvlist has minimal functionality, thus: 1) fast lookup of pointers is not possible, because that involves list traversal 2) changing pointers can be slow for large pointer collections */ #include <stdlib.h> #include <stdio.h> #ifdef __cplusplus namespace csl { namespace common { /** @brief policy for pvlist template This policy is handful when pvlist stores pointers that should not be freed, like pointers to static data or pointers that are owned by other instance. */ template <typename T> struct nop_destructor { inline void destruct(T ** p, size_t n) { } inline void destruct(T * p) { } }; /** @brief policy for pvlist template This policy is handful when pvlist stores pointers that are malloced. */ template <typename T> struct free_destructor { inline void destruct(T * p) { if( p ) ::free( p ); } inline void destruct(T ** p, size_t n) { for( size_t i=0;i<n;++i ) if( p[i] ) ::free( p[i] ); } }; /** @brief policy for pvlist template This policy is handful when pvlist stores pointers that are allocated by new. */ template <typename T> struct delete_destructor { inline void destruct(T * p) { if( p ) delete p; } inline void destruct(T ** p, size_t n) { for( size_t i=0;i<n;++i ) if( p[i] ) delete p[i]; } }; /** @brief template class to collect many allocations that should be freed together The design of this class is driven by the need of a very simple pool class that can collect a few dynamically allocated pointers and free them together. The overhead of this object should be minimal for a few cases, while others possible uses are not optimized. It should be fast to declare this object alone, so if not used its overhead should be minimal. Also if only a few pointers are stored, it should be pretty fast too. The I parameter can be used to tune how many pointers should be statically allocated. They are allocated on the stack rather then on the heap. To summarize these benefits: 1) should have minimal overhead when instantiated 2) should have minimal overhead when adding new pointers 3) should have minimal overhead when destroyed On the downside: It is possible to get or set pointers in pvlist but its performance is slow for large collections. O(n/I) The T parameter is used for setting what type of pointer will be stored. If T is set to type_t then pvlist receives type_t*-s. */ template < size_t I=64, typename T=void, typename D=nop_destructor<T> > class pvlist { public: enum { block_size = I }; typedef T item_type_t; /** @brief returns the blocksize=I that was statically declared */ inline size_t bs() { return block_size; } struct iterator; friend struct iterator; private: struct item { T * ptrs_[block_size]; size_t used_; item * next_; inline item( ) : used_(0), next_(0) { } }; item head_; item * tail_; size_t n_items_; inline item * ensure_item() { if( tail_->used_ == block_size ) { item * old_tail = tail_; tail_ = new item(); old_tail->next_ = tail_; } return tail_; } public: /** @brief pvlist iterator very simple, forward only iterator */ class iterator { private: item * i_; size_t pos_; iterator() {} public: ~iterator() {} /** @brief initializer constructor */ iterator(item * i, size_t pos) : i_(i), pos_(pos) {} /** @brief copy constructor */ iterator(const iterator & other) : i_(other.i_), pos_(other.pos_) {} /** @brief copy operator */ iterator & operator=(const iterator & other) { i_ = other.i_; pos_ = other.pos_; return *this; } /** @brief creates an iterator of ls @param ls is the pvlist to be iterated over */ iterator(pvlist & ls) : i_(&(ls.head_)), pos_(0) { { if(!ls.n_items_) i_ = 0; } } /** @brief checks equality */ bool operator==(const iterator & other) { return ((i_ == other.i_ && pos_ == other.pos_) ? true : false ); } /** @brief checks if not equal */ bool operator!=(const iterator & other) { return (!(operator==(other))); } /** @brief step forward */ void operator++() { if( i_ == 0 ) { i_ = 0; pos_ = 0; } else if( pos_ == (i_->used_-1) ) { i_ = i_->next_; pos_ = 0; } else { ++pos_; } } /** @brief sets the iterator to end */ void zero() { i_ = 0; pos_ = 0; } /** @brief returns the pointed item */ item_type_t * operator*() { if( i_ ) { return i_->ptrs_[pos_]; } else { return 0; } } }; /** @brief pvlist const iterator very simple, forward only constant iterator */ class const_iterator { private: const item * i_; size_t pos_; const_iterator() {} public: ~const_iterator() {} /** @brief initializer constructor */ const_iterator(const item * i, size_t pos) : i_(i), pos_(pos) {} /** @brief copy constructor */ const_iterator(const const_iterator & other) : i_(other.i_), pos_(other.pos_) {} /** @brief copy operator */ const_iterator & operator=(const const_iterator & other) { i_ = other.i_; pos_ = other.pos_; return *this; } /** @brief creates an iterator of ls @param ls is the pvlist to be iterated over */ const_iterator(const pvlist & ls) : i_(&(ls.head_)), pos_(0) { if(!ls.n_items_) i_ = 0; } /** @brief checks equality */ bool operator==(const const_iterator & other) const { return ((i_ == other.i_ && pos_ == other.pos_) ? true : false ); } /** @brief checks if not equal */ bool operator!=(const const_iterator & other) const { return (!(operator==(other))); } /** @brief step forward */ void operator++() { if( i_ == 0 ) { i_ = 0; pos_ = 0; } else if( pos_ == (i_->used_-1) ) { i_ = i_->next_; pos_ = 0; } else { ++pos_; } } /** @brief sets the iterator to end */ void zero() { i_ = 0; pos_ = 0; } /** @brief returns the pointed item */ const item_type_t * operator*() const { if( i_ ) { return i_->ptrs_[pos_]; } else { return 0; } } }; /** @brief returns iterator pointed at the beginning of the container */ iterator begin() { iterator ret(*this); return ret; } /** @brief returns iterator represents the end of this container */ iterator end() { iterator ret(*this); ret.zero(); return ret; } /** @brief returns iterator represents the last item in this container */ iterator last() { if( !n_items_ || !tail_ || !(tail_->used_) ) { return end(); } else { iterator ret(tail_,tail_->used_-1); return ret; } } /** @brief returns a constant iterator pointed at the beginning of the container */ const_iterator const_begin() const { const_iterator ret(*this); return ret; } /** @brief returns a constant iterator pointed at the beginning of the container */ const_iterator begin() const { return const_begin(); } /** @brief returns a constant iterator represents the end of this container */ const_iterator const_end() const { const_iterator ret(*this); ret.zero(); return ret; } /** @brief returns a constant iterator represents the end of this container */ const_iterator end() const { return const_end(); } /** @brief returns a constant iterator represents the last item in this container */ const_iterator const_last() const { if( !n_items_ || !tail_ || !(tail_->used_) ) { return end(); } else { const_iterator ret(tail_,tail_->used_-1); return ret; } } /** @brief returns a constant iterator represents the last item in this container */ const_iterator last() const { return const_last(); } public: /** @brief constructor */ inline pvlist() : tail_(&head_), n_items_(0) { } /** @brief destructor */ inline ~pvlist() { free_all(); } /** @brief number of items stored @return the number of items */ inline size_t n_items() const { return n_items_; } /** @brief number of items stored @return the number of items same as n_items() */ inline size_t size() const { return n_items_; } /** @brief call the destruct() function on each items and frees internal memory */ inline void free_all() { D d; d.destruct( head_.ptrs_, head_.used_ ); item * i = head_.next_; while( i ) { item * o = i; i = i->next_; d.destruct( o->ptrs_, o->used_ ); delete o; } head_.used_ = 0; head_.next_ = 0; tail_ = &head_; n_items_ = 0; } /** @brief search for a pointer in pvlist @param p the pointer to be searched */ inline bool find(T * p) { item * i = &head_; while( i ) { for( size_t ii=0;ii<(i->used_); ++ii ) { if( i->ptrs_[ii] == p ) { return true; } } i = i->next_; } return false; } /** @brief free()-s p and set all p's occurence to NULL @param p the pointer to be destructed @return true if pointer found and freed this function iterates through the whole collection, the first occurence of p will be destructed() and if more found then they will be set to NULL this function does not touch the number of items, it rather replaces the destructed pointers with NULL */ inline bool free(T * p) { bool freed=false; D d; item * i = &head_; while( i ) { for( size_t ii=0;ii<(i->used_); ++ii ) { if( i->ptrs_[ii] == p ) { if( !freed ) { d.destruct( i->ptrs_[ii] ); freed = true; } i->ptrs_[ii] = 0; } } i = i->next_; } return freed; } /** @brief free()-s p first occurence and returns @param p the pointer to be destructed @return true if pointer found and freed this function iterates through the collection untill p was found, then it destructs that, sets that occurence to NULL and returns immediately if more then one occuernce of p exists in the collection they wont be touched so they may lead to memory corruption problems. care must be taken.... this function does not touch the number of items, it rather replaces the destructed pointer with NULL */ inline bool free_one(T * p) { D d; item * i = &head_; while( i ) { for( size_t ii=0;ii<(i->used_); ++ii ) { if( i->ptrs_[ii] == p ) { d.destruct( i->ptrs_[ii] ); i->ptrs_[ii] = 0; return true; } } i = i->next_; } return false; } /** @brief adds an item to the end of the list @param p the pointer to be appended the number of stored items will be increased by 1 after calling this function */ inline void push_back(T * p) { item * i = ensure_item(); i->ptrs_[i->used_] = p; ++(i->used_); ++n_items_; } /** @brief gets the item at the specified position @param which is the desired position @return T * which is the item at that position or NULL of the position is invalid */ inline T * get_at(size_t which) const { if( which >= n_items_ ) return 0; size_t pn = which/block_size; /* first page go fast */ if( !pn ) return (which < head_.used_ ? head_.ptrs_[which] : 0); /* iterate through pages */ const item * pt = &head_; while( pt->next_ && pn > 0 ) { --pn; pt = pt->next_; } /* not enough pages */ if( pn ) return 0; size_t rm = which%block_size; return (rm < pt->used_ ? pt->ptrs_[rm] : 0); } /** @brief sets the item at the specified position @param which is the desired position @param ptr is the pointer to be set @return true if successful, false if the position is invalid */ inline bool set_at(size_t which, T * ptr) { if( which >= n_items_ ) return false; size_t pn = which/block_size; /* first page go fast */ if( !pn ) { if( which >= head_.used_ ) return false; head_.ptrs_[which] = ptr; return true; } /* iterate through pages */ item * pt = &head_; while( pt->next_ && pn > 0 ) { --pn; pt = pt->next_; } /* not enough pages */ if( pn ) return false; size_t rm = which%block_size; if( rm < pt->used_ ) { pt->ptrs_[rm] = ptr; return true; } else { return false; } } /** @brief prints some debug information to STDOUT */ inline void debug() { printf("== pvlist::debug ==\n"); item * pt = &head_; while( pt ) { printf( " item:\n" " -- ptrs : %p\n" " -- used : %ld\n" " -- next : %p\n" " ---- : ", pt->ptrs_, (unsigned long)pt->used_, pt->next_ ); for( size_t i=0;i<pt->used_;++i ) printf("%p ",pt->ptrs_[i]); printf("\n"); pt = pt->next_; } } }; } } #endif /* __cplusplus */ #endif /* _csl_common_pvlist_hh_included_ */
[ "codesloop@beckground.hu" ]
codesloop@beckground.hu
21496b5b6265c1943559ca62b08b505a1eec74f3
ab5c7e0a0d6f699f24f4ace5244c1f64acbe3563
/core/test/lib/boost/boost/graph/adjacency_list.hpp
9dffdff3d26ec568a1ece763782ae5abc97fa82c
[ "MIT" ]
permissive
tmpfork/lib-ledger-core
e7c9d0426fe944c0f6a81d74744796e87542fa8a
8741e84f38f863fd941d3bd56a470f37eb36da04
refs/heads/master
2020-04-21T09:42:37.184675
2019-01-23T13:15:43
2019-01-23T13:15:43
169,459,374
0
0
MIT
2019-02-06T18:58:46
2019-02-06T18:58:46
null
UTF-8
C++
false
false
14,817
hpp
//======================================================================= // Copyright 1997, 1998, 1999, 2000 University of Notre Dame. // Copyright 2010 Thomas Claveirole // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek, Thomas Claveirole // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef BOOST_GRAPH_ADJACENCY_LIST_HPP #define BOOST_GRAPH_ADJACENCY_LIST_HPP #include <boost/config.hpp> #include <vector> #include <list> #include <set> #include <boost/unordered_set.hpp> #if !defined BOOST_NO_SLIST # ifdef BOOST_SLIST_HEADER # include BOOST_SLIST_HEADER # else # include <slist> # endif #endif #include <boost/scoped_ptr.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graph_mutability_traits.hpp> #include <boost/graph/graph_selectors.hpp> #include <boost/property_map/property_map.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/not.hpp> #include <boost/mpl/bool.hpp> #include <boost/graph/detail/edge.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/detail/workaround.hpp> #include <boost/graph/properties.hpp> #include <boost/graph/named_graph.hpp> namespace boost { //=========================================================================== // Selectors for the VertexList and EdgeList template parameters of // adjacency_list, and the container_gen traits class which is used // to map the selectors to the container type used to implement the // graph. #if !defined BOOST_NO_SLIST struct slistS {}; #endif struct vecS { }; struct listS { }; struct setS { }; struct mapS { }; struct multisetS { }; struct multimapS { }; struct hash_setS { }; struct hash_mapS { }; struct hash_multisetS { }; struct hash_multimapS { }; template <class Selector, class ValueType> struct container_gen { }; template <class ValueType> struct container_gen<listS, ValueType> { typedef std::list<ValueType> type; }; #if !defined BOOST_NO_SLIST template <class ValueType> struct container_gen<slistS, ValueType> { typedef BOOST_STD_EXTENSION_NAMESPACE::slist<ValueType> type; }; #endif template <class ValueType> struct container_gen<vecS, ValueType> { typedef std::vector<ValueType> type; }; template <class ValueType> struct container_gen<mapS, ValueType> { typedef std::set<ValueType> type; }; template <class ValueType> struct container_gen<setS, ValueType> { typedef std::set<ValueType> type; }; template <class ValueType> struct container_gen<multisetS, ValueType> { typedef std::multiset<ValueType> type; }; template <class ValueType> struct container_gen<multimapS, ValueType> { typedef std::multiset<ValueType> type; }; template <class ValueType> struct container_gen<hash_setS, ValueType> { typedef boost::unordered_set<ValueType> type; }; template <class ValueType> struct container_gen<hash_mapS, ValueType> { typedef boost::unordered_set<ValueType> type; }; template <class ValueType> struct container_gen<hash_multisetS, ValueType> { typedef boost::unordered_multiset<ValueType> type; }; template <class ValueType> struct container_gen<hash_multimapS, ValueType> { typedef boost::unordered_multiset<ValueType> type; }; template <class StorageSelector> struct parallel_edge_traits { }; template <> struct parallel_edge_traits<vecS> { typedef allow_parallel_edge_tag type; }; template <> struct parallel_edge_traits<listS> { typedef allow_parallel_edge_tag type; }; #if !defined BOOST_NO_SLIST template <> struct parallel_edge_traits<slistS> { typedef allow_parallel_edge_tag type; }; #endif template <> struct parallel_edge_traits<setS> { typedef disallow_parallel_edge_tag type; }; template <> struct parallel_edge_traits<multisetS> { typedef allow_parallel_edge_tag type; }; template <> struct parallel_edge_traits<hash_setS> { typedef disallow_parallel_edge_tag type; }; // mapS is obsolete, replaced with setS template <> struct parallel_edge_traits<mapS> { typedef disallow_parallel_edge_tag type; }; template <> struct parallel_edge_traits<hash_mapS> { typedef disallow_parallel_edge_tag type; }; template <> struct parallel_edge_traits<hash_multisetS> { typedef allow_parallel_edge_tag type; }; template <> struct parallel_edge_traits<hash_multimapS> { typedef allow_parallel_edge_tag type; }; namespace detail { template <class Directed> struct is_random_access { enum { value = false}; typedef mpl::false_ type; }; template <> struct is_random_access<vecS> { enum { value = true }; typedef mpl::true_ type; }; } // namespace detail template <typename Selector> struct is_distributed_selector: mpl::false_ {}; //=========================================================================== // The adjacency_list_traits class, which provides a way to access // some of the associated types of an adjacency_list type without // having to first create the adjacency_list type. This is useful // when trying to create interior vertex or edge properties who's // value type is a vertex or edge descriptor. template <class OutEdgeListS = vecS, class VertexListS = vecS, class DirectedS = directedS, class EdgeListS = listS> struct adjacency_list_traits { typedef typename detail::is_random_access<VertexListS>::type is_rand_access; typedef typename DirectedS::is_bidir_t is_bidir; typedef typename DirectedS::is_directed_t is_directed; typedef typename mpl::if_<is_bidir, bidirectional_tag, typename mpl::if_<is_directed, directed_tag, undirected_tag >::type >::type directed_category; typedef typename parallel_edge_traits<OutEdgeListS>::type edge_parallel_category; typedef std::size_t vertices_size_type; typedef void* vertex_ptr; typedef typename mpl::if_<is_rand_access, vertices_size_type, vertex_ptr>::type vertex_descriptor; typedef detail::edge_desc_impl<directed_category, vertex_descriptor> edge_descriptor; private: // Logic to figure out the edges_size_type struct dummy {}; typedef typename container_gen<EdgeListS, dummy>::type EdgeContainer; typedef typename DirectedS::is_bidir_t BidirectionalT; typedef typename DirectedS::is_directed_t DirectedT; typedef typename mpl::and_<DirectedT, typename mpl::not_<BidirectionalT>::type >::type on_edge_storage; public: typedef typename mpl::if_<on_edge_storage, std::size_t, typename EdgeContainer::size_type >::type edges_size_type; }; } // namespace boost #include <boost/graph/detail/adjacency_list.hpp> namespace boost { //=========================================================================== // The adjacency_list class. // template <class OutEdgeListS = vecS, // a Sequence or an AssociativeContainer class VertexListS = vecS, // a Sequence or a RandomAccessContainer class DirectedS = directedS, class VertexProperty = no_property, class EdgeProperty = no_property, class GraphProperty = no_property, class EdgeListS = listS> class adjacency_list : public detail::adj_list_gen< adjacency_list<OutEdgeListS,VertexListS,DirectedS, VertexProperty,EdgeProperty,GraphProperty,EdgeListS>, VertexListS, OutEdgeListS, DirectedS, VertexProperty, EdgeProperty, GraphProperty, EdgeListS>::type, // Support for named vertices public graph::maybe_named_graph< adjacency_list<OutEdgeListS,VertexListS,DirectedS, VertexProperty,EdgeProperty,GraphProperty,EdgeListS>, typename adjacency_list_traits<OutEdgeListS, VertexListS, DirectedS, EdgeListS>::vertex_descriptor, VertexProperty> { public: typedef GraphProperty graph_property_type; typedef typename lookup_one_property<GraphProperty, graph_bundle_t>::type graph_bundled; typedef VertexProperty vertex_property_type; typedef typename lookup_one_property<VertexProperty, vertex_bundle_t>::type vertex_bundled; typedef EdgeProperty edge_property_type; typedef typename lookup_one_property<EdgeProperty, edge_bundle_t>::type edge_bundled; private: typedef adjacency_list self; typedef typename detail::adj_list_gen< self, VertexListS, OutEdgeListS, DirectedS, vertex_property_type, edge_property_type, GraphProperty, EdgeListS >::type Base; public: typedef typename Base::stored_vertex stored_vertex; typedef typename Base::vertices_size_type vertices_size_type; typedef typename Base::edges_size_type edges_size_type; typedef typename Base::degree_size_type degree_size_type; typedef typename Base::vertex_descriptor vertex_descriptor; typedef typename Base::edge_descriptor edge_descriptor; typedef OutEdgeListS out_edge_list_selector; typedef VertexListS vertex_list_selector; typedef DirectedS directed_selector; typedef EdgeListS edge_list_selector; adjacency_list(const GraphProperty& p = GraphProperty()) : m_property(new graph_property_type(p)) { } adjacency_list(const adjacency_list& x) : Base(x), m_property(new graph_property_type(*x.m_property)) { } adjacency_list& operator=(const adjacency_list& x) { // TBD: probably should give the strong guarantee if (&x != this) { Base::operator=(x); // Copy/swap the ptr since we can't just assign it... property_ptr p(new graph_property_type(*x.m_property)); m_property.swap(p); } return *this; } // Required by Mutable Graph adjacency_list(vertices_size_type num_vertices, const GraphProperty& p = GraphProperty()) : Base(num_vertices), m_property(new graph_property_type(p)) { } // Required by Iterator Constructible Graph template <class EdgeIterator> adjacency_list(EdgeIterator first, EdgeIterator last, vertices_size_type n, edges_size_type = 0, const GraphProperty& p = GraphProperty()) : Base(n, first, last), m_property(new graph_property_type(p)) { } template <class EdgeIterator, class EdgePropertyIterator> adjacency_list(EdgeIterator first, EdgeIterator last, EdgePropertyIterator ep_iter, vertices_size_type n, edges_size_type = 0, const GraphProperty& p = GraphProperty()) : Base(n, first, last, ep_iter), m_property(new graph_property_type(p)) { } void swap(adjacency_list& x) { // Is there a more efficient way to do this? adjacency_list tmp(x); x = *this; *this = tmp; } void clear() { this->clearing_graph(); Base::clear(); } #ifndef BOOST_GRAPH_NO_BUNDLED_PROPERTIES // Directly access a vertex or edge bundle vertex_bundled& operator[](vertex_descriptor v) { return get(vertex_bundle, *this)[v]; } const vertex_bundled& operator[](vertex_descriptor v) const { return get(vertex_bundle, *this)[v]; } edge_bundled& operator[](edge_descriptor e) { return get(edge_bundle, *this)[e]; } const edge_bundled& operator[](edge_descriptor e) const { return get(edge_bundle, *this)[e]; } graph_bundled& operator[](graph_bundle_t) { return get_property(*this); } graph_bundled const& operator[](graph_bundle_t) const { return get_property(*this); } #endif // protected: (would be protected if friends were more portable) typedef scoped_ptr<graph_property_type> property_ptr; property_ptr m_property; }; #define ADJLIST_PARAMS \ typename OEL, typename VL, typename D, typename VP, typename EP, \ typename GP, typename EL #define ADJLIST adjacency_list<OEL,VL,D,VP,EP,GP,EL> template<ADJLIST_PARAMS, typename Tag, typename Value> inline void set_property(ADJLIST& g, Tag tag, Value const& value) { get_property_value(*g.m_property, tag) = value; } template<ADJLIST_PARAMS, typename Tag> inline typename graph_property<ADJLIST, Tag>::type& get_property(ADJLIST& g, Tag tag) { return get_property_value(*g.m_property, tag); } template<ADJLIST_PARAMS, typename Tag> inline typename graph_property<ADJLIST, Tag>::type const& get_property(ADJLIST const& g, Tag tag) { return get_property_value(*g.m_property, tag); } // dwa 09/25/00 - needed to be more explicit so reverse_graph would work. template <class Directed, class Vertex, class OutEdgeListS, class VertexListS, class DirectedS, class VertexProperty, class EdgeProperty, class GraphProperty, class EdgeListS> inline Vertex source(const detail::edge_base<Directed,Vertex>& e, const adjacency_list<OutEdgeListS, VertexListS, DirectedS, VertexProperty, EdgeProperty, GraphProperty, EdgeListS>&) { return e.m_source; } template <class Directed, class Vertex, class OutEdgeListS, class VertexListS, class DirectedS, class VertexProperty, class EdgeProperty, class GraphProperty, class EdgeListS> inline Vertex target(const detail::edge_base<Directed,Vertex>& e, const adjacency_list<OutEdgeListS, VertexListS, DirectedS, VertexProperty, EdgeProperty, GraphProperty, EdgeListS>&) { return e.m_target; } // Mutability Traits template <ADJLIST_PARAMS> struct graph_mutability_traits<ADJLIST> { typedef mutable_property_graph_tag category; }; // Can't remove vertices from adjacency lists with VL==vecS template <typename OEL, typename D, typename VP, typename EP, typename GP, typename EL> struct graph_mutability_traits< adjacency_list<OEL,vecS,D,VP,EP,GP,EL> > { typedef add_only_property_graph_tag category; }; #undef ADJLIST_PARAMS #undef ADJLIST } // namespace boost #endif // BOOST_GRAPH_ADJACENCY_LIST_HPP
[ "pollastri.p@gmail.com" ]
pollastri.p@gmail.com
b35d791a508a01a88ab8ef42b40b4e21f00c7f23
298fbf762760adad1bb9a566c3965900ba5a94f5
/Count Number of Binary Strings.cpp
5ef2d31eeed245b835fea050ba7107976ec2ba0c
[]
no_license
jyoti-varshney7/JAVA_QUESTION
24a61717153a086e2c1a59cce0fd636ec828a34f
bb8625cebbc3c323bc2520c56cadea4f0658f8f1
refs/heads/main
2023-07-08T21:49:04.138471
2021-08-06T07:17:19
2021-08-06T07:17:19
373,594,316
3
0
null
null
null
null
UTF-8
C++
false
false
886
cpp
// You are provided an integers N. You need to count all possible distinct binary strings of length N such that there are no consecutive 1’s. // Input Format // First line contains integer t which is number of test case. For each test case, it contains an integer n which is the the length of Binary String. // Constraints // 1<=t<=100 1<=n<=90 // Output Format // Print the number of all possible binary strings. // Sample Input // 2 // 2 // 3 // Sample Output // 3 // 5 // Explanation // 1st test case : 00, 01, 10 2nd test case : 000, 001, 010, 100, 101 //No of binary strings #include<iostream> using namespace std; int main(){ long long int t,dp[1005],i; cin>>t; dp[1]=2; dp[2]=3; for(i=3;i<1000;i++){ dp[i]=dp[i-1]+dp[i-2]; } while(t--){ int n; cin>>n; // string s; // cout<<count(n,"",0); cout<<dp[n]; cout<<endl; } }
[ "noreply@github.com" ]
noreply@github.com
2f10e15e2a73c174998624e3477595fbda6af74a
5ebd5cee801215bc3302fca26dbe534e6992c086
/blazetest/src/mathtest/hermitianmatrix/SparseRealTest1.cpp
72c132965f3cf643acbe2c278553eadbc58b18d4
[ "BSD-3-Clause" ]
permissive
mhochsteger/blaze
c66d8cf179deeab4f5bd692001cc917fe23e1811
fd397e60717c4870d942055496d5b484beac9f1a
refs/heads/master
2020-09-17T01:56:48.483627
2019-11-20T05:40:29
2019-11-20T05:41:35
223,951,030
0
0
null
null
null
null
UTF-8
C++
false
false
178,970
cpp
//================================================================================================= /*! // \file src/mathtest/hermitianmatrix/SparseRealTest1.cpp // \brief Source file for the HermitianMatrix sparse real test (part 1) // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/StaticMatrix.h> #include <blazetest/mathtest/hermitianmatrix/SparseRealTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif namespace blazetest { namespace mathtest { namespace hermitianmatrix { //================================================================================================= // // CONSTRUCTORS // //================================================================================================= //************************************************************************************************* /*!\brief Constructor for the HermitianMatrix sparse real test. // // \exception std::runtime_error Operation error detected. */ SparseRealTest::SparseRealTest() { testConstructors(); testAssignment(); testAddAssign(); testSubAssign(); testSchurAssign(); testMultAssign(); } //************************************************************************************************* //================================================================================================= // // TEST FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Test of the HermitianMatrix constructors. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of all constructors of the HermitianMatrix specialization. // In case an error is detected, a \a std::runtime_error exception is thrown. */ void SparseRealTest::testConstructors() { //===================================================================================== // Row-major default constructor //===================================================================================== // Default constructor (CompressedMatrix) { test_ = "Row-major HermitianMatrix default constructor (CompressedMatrix)"; const HT herm; checkRows ( herm, 0UL ); checkColumns ( herm, 0UL ); checkNonZeros( herm, 0UL ); } //===================================================================================== // Row-major size constructor //===================================================================================== // Size constructor (CompressedMatrix) { test_ = "Row-major HermitianMatrix size constructor (CompressedMatrix)"; const HT herm( 2UL ); checkRows ( herm, 2UL ); checkColumns ( herm, 2UL ); checkNonZeros( herm, 0UL ); } //===================================================================================== // Row-major list initialization //===================================================================================== // Complete initializer list { test_ = "Row-major HermitianMatrix initializer list constructor (complete list)"; const HT herm{ { 1, 2, 3 }, { 2, 4, 0 }, { 3, 0, 6 } }; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != 2 || herm(0,2) != 3 || herm(1,0) != 2 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 3 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 2 3 )\n( 2 4 0 )\n( 3 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Incomplete initializer list { test_ = "Row-major HermitianMatrix initializer list constructor (incomplete list)"; const HT herm{ { 1, 2, 3 }, { 2, 4 }, { 3, 0, 6 } }; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != 2 || herm(0,2) != 3 || herm(1,0) != 2 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 3 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 2 3 )\n( 2 4 0 )\n( 3 0 6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major copy constructor //===================================================================================== // Copy constructor (0x0) { test_ = "Row-major HermitianMatrix copy constructor (0x0)"; const HT herm1; const HT herm2( herm1 ); checkRows ( herm2, 0UL ); checkColumns ( herm2, 0UL ); checkNonZeros( herm2, 0UL ); } // Copy constructor (3x3) { test_ = "Row-major HermitianMatrix copy constructor (3x3)"; HT herm1( 3UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; const HT herm2( herm1 ); checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major move constructor //===================================================================================== // Move constructor (0x0) { test_ = "Row-major HermitianMatrix move constructor (0x0)"; HT herm1; HT herm2( std::move( herm1 ) ); checkRows ( herm2, 0UL ); checkColumns ( herm2, 0UL ); checkNonZeros( herm2, 0UL ); } // Move constructor (3x3) { test_ = "Row-major HermitianMatrix move constructor (3x3)"; HT herm1( 3UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; HT herm2( std::move( herm1 ) ); checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major conversion constructor //===================================================================================== // Conversion constructor (0x0) { test_ = "Row-major HermitianMatrix conversion constructor (0x0)"; const blaze::DynamicMatrix<int,blaze::rowMajor> mat; const HT herm( mat ); checkRows ( herm, 0UL ); checkColumns ( herm, 0UL ); checkNonZeros( herm, 0UL ); } // Conversion constructor (symmetric) { test_ = "Row-major HermitianMatrix conversion constructor (symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { 7, 0, 3 } } ); const HT herm( mat ); checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != -4 || herm(0,2) != 7 || herm(1,0) != -4 || herm(1,1) != 2 || herm(1,2) != 0 || herm(2,0) != 7 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Conversion constructor (non-symmetric) { test_ = "Row-major HermitianMatrix conversion constructor (non-symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { -5, 0, 3 } } ); try { const HT herm( mat ); std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Setup of non-symmetric HermitianMatrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Conversion constructor (HermitianMatrix) { test_ = "Row-major HermitianMatrix conversion constructor (HermitianMatrix)"; blaze::HermitianMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> > herm1; herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; const HT herm2( herm1 ); checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major default constructor //===================================================================================== // Default constructor (CompressedMatrix) { test_ = "Column-major HermitianMatrix default constructor (CompressedMatrix)"; const OHT herm; checkRows ( herm, 0UL ); checkColumns ( herm, 0UL ); checkNonZeros( herm, 0UL ); } //===================================================================================== // Column-major size constructor //===================================================================================== // Size constructor (CompressedMatrix) { test_ = "Column-major HermitianMatrix size constructor (CompressedMatrix)"; const OHT herm( 2UL ); checkRows ( herm, 2UL ); checkColumns ( herm, 2UL ); checkNonZeros( herm, 0UL ); } //===================================================================================== // Column-major list initialization //===================================================================================== // Complete initializer list { test_ = "Column-major HermitianMatrix initializer list constructor (complete list)"; const OHT herm{ { 1, 2, 3 }, { 2, 4, 0 }, { 3, 0, 6 } }; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != 2 || herm(0,2) != 3 || herm(1,0) != 2 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 3 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 2 3 )\n( 2 4 0 )\n( 3 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Incomplete initializer list { test_ = "Column-major HermitianMatrix initializer list constructor (incomplete list)"; const OHT herm{ { 1, 2, 3 }, { 2, 4 }, { 3, 0, 6 } }; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != 2 || herm(0,2) != 3 || herm(1,0) != 2 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 3 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 2 3 )\n( 2 4 0 )\n( 3 0 6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major copy constructor //===================================================================================== // Copy constructor (0x0) { test_ = "Column-major HermitianMatrix copy constructor (0x0)"; const OHT herm1; const OHT herm2( herm1 ); checkRows ( herm2, 0UL ); checkColumns ( herm2, 0UL ); checkNonZeros( herm2, 0UL ); } // Copy constructor (3x3) { test_ = "Column-major HermitianMatrix copy constructor (3x3)"; OHT herm1( 3UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; const OHT herm2( herm1 ); checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major move constructor //===================================================================================== // Move constructor (0x0) { test_ = "Column-major HermitianMatrix move constructor (0x0)"; OHT herm1; OHT herm2( std::move( herm1 ) ); checkRows ( herm2, 0UL ); checkColumns ( herm2, 0UL ); checkNonZeros( herm2, 0UL ); } // Move constructor (3x3) { test_ = "Column-major HermitianMatrix move constructor (3x3)"; OHT herm1( 3UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; OHT herm2( std::move( herm1 ) ); checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major conversion constructor //===================================================================================== // Conversion constructor (0x0) { test_ = "Column-major HermitianMatrix conversion constructor (0x0)"; const blaze::DynamicMatrix<int,blaze::columnMajor> mat; const OHT herm( mat ); checkRows ( herm, 0UL ); checkColumns ( herm, 0UL ); checkNonZeros( herm, 0UL ); } // Conversion constructor (symmetric) { test_ = "Column-major HermitianMatrix conversion constructor (symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { 7, 0, 3 } } ); const OHT herm( mat ); checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != -4 || herm(0,2) != 7 || herm(1,0) != -4 || herm(1,1) != 2 || herm(1,2) != 0 || herm(2,0) != 7 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Conversion constructor (non-symmetric) { test_ = "Column-major HermitianMatrix conversion constructor (non-symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { -5, 0, 3 } } ); try { const OHT herm( mat ); std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Setup of non-symmetric HermitianMatrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Conversion constructor (HermitianMatrix) { test_ = "Column-major HermitianMatrix conversion constructor (HermitianMatrix)"; blaze::HermitianMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> > herm1; herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; const OHT herm2( herm1 ); checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the HermitianMatrix assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of all assignment operators of the HermitianMatrix specialization. // In case an error is detected, a \a std::runtime_error exception is thrown. */ void SparseRealTest::testAssignment() { //===================================================================================== // Row-major list assignment //===================================================================================== // Complete initializer list { test_ = "Row-major HermitianMatrix initializer list assignment (complete list)"; HT herm; herm = { { 1, 2, 3 }, { 2, 4, 0 }, { 3, 0, 6 } }; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != 2 || herm(0,2) != 3 || herm(1,0) != 2 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 3 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 2 3 )\n( 2 4 0 )\n( 3 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Incomplete initializer list { test_ = "Row-major HermitianMatrix initializer list assignment (incomplete list)"; HT herm; herm = { { 1, 2, 3 }, { 2, 4 }, { 3, 0, 6 } }; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != 2 || herm(0,2) != 3 || herm(1,0) != 2 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 3 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 2 3 )\n( 2 4 0 )\n( 3 0 6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major copy assignment //===================================================================================== // Copy assignment (0x0) { test_ = "Row-major HermitianMatrix copy assignment (0x0)"; HT herm1, herm2; herm2 = herm1; checkRows ( herm2, 0UL ); checkColumns ( herm2, 0UL ); checkNonZeros( herm2, 0UL ); } // Copy assignment (3x3) { test_ = "Row-major HermitianMatrix copy assignment (3x3)"; HT herm1( 3UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; HT herm2; herm2 = herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major move assignment //===================================================================================== // Move assignment (0x0) { test_ = "Row-major HermitianMatrix move assignment (0x0)"; HT herm1, herm2; herm2 = std::move( herm1 ); checkRows ( herm2, 0UL ); checkColumns ( herm2, 0UL ); checkNonZeros( herm2, 0UL ); } // Move assignment (3x3) { test_ = "Row-major HermitianMatrix move assignment (3x3)"; HT herm1( 3UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; HT herm2; herm2 = std::move( herm1 ); checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major dense matrix assignment //===================================================================================== // Conversion assignment (0x0) { test_ = "Row-major HermitianMatrix dense matrix assignment (0x0)"; const blaze::DynamicMatrix<int,blaze::rowMajor> mat; HT herm; herm = mat; checkRows ( herm, 0UL ); checkColumns ( herm, 0UL ); checkNonZeros( herm, 0UL ); } // Row-major/row-major dense matrix assignment (symmetric) { test_ = "Row-major/row-major HermitianMatrix dense matrix assignment (symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { 7, 0, 3 } } ); HT herm; herm = mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != -4 || herm(0,2) != 7 || herm(1,0) != -4 || herm(1,1) != 2 || herm(1,2) != 0 || herm(2,0) != 7 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix assignment (symmetric) { test_ = "Row-major/column-major HermitianMatrix dense matrix assignment (symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { 7, 0, 3 } } ); HT herm; herm = mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != -4 || herm(0,2) != 7 || herm(1,0) != -4 || herm(1,1) != 2 || herm(1,2) != 0 || herm(2,0) != 7 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major dense matrix assignment (non-symmetric) { test_ = "Row-major/row-major HermitianMatrix dense matrix assignment (non-symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { -5, 0, 3 } } ); try { HT herm; herm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix assignment (non-symmetric) { test_ = "Row-major/column-major HermitianMatrix dense matrix assignment (non-symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { -5, 0, 3 } } ); try { HT herm; herm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix assignment (HermitianMatrix) { test_ = "Row-major/row-major HermitianMatrix dense matrix assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> > herm1; herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; HT herm2; herm2 = herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix assignment (HermitianMatrix) { test_ = "Row-major/column-major HermitianMatrix dense matrix assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> > herm1; herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; HT herm2; herm2 = herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major sparse matrix assignment //===================================================================================== // Conversion assignment (0x0) { test_ = "Row-major HermitianMatrix sparse matrix assignment (0x0)"; const blaze::CompressedMatrix<int,blaze::rowMajor> mat; HT herm; herm = mat; checkRows ( herm, 0UL ); checkColumns ( herm, 0UL ); checkNonZeros( herm, 0UL ); } // Row-major/row-major sparse matrix assignment (symmetric) { test_ = "Row-major/row-major HermitianMatrix sparse matrix assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 8UL ); mat(0,0) = 1; mat(0,1) = -4; mat(0,2) = 7; mat(1,0) = -4; mat(1,1) = 2; mat(2,0) = 7; mat(2,2) = 3; mat.insert( 1UL, 2UL, 0 ); HT herm; herm = mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 8UL ); if( herm(0,0) != 1 || herm(0,1) != -4 || herm(0,2) != 7 || herm(1,0) != -4 || herm(1,1) != 2 || herm(1,2) != 0 || herm(2,0) != 7 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix assignment (symmetric) { test_ = "Row-major/column-major HermitianMatrix sparse matrix assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 8UL ); mat(0,0) = 1; mat(0,1) = -4; mat(0,2) = 7; mat(1,0) = -4; mat(1,1) = 2; mat(2,0) = 7; mat(2,2) = 3; mat.insert( 1UL, 2UL, 0 ); HT herm; herm = mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 8UL ); if( herm(0,0) != 1 || herm(0,1) != -4 || herm(0,2) != 7 || herm(1,0) != -4 || herm(1,1) != 2 || herm(1,2) != 0 || herm(2,0) != 7 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major sparse matrix assignment (non-symmetric) { test_ = "Row-major/row-major HermitianMatrix sparse matrix assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 7UL ); mat(0,0) = 1; mat(0,1) = -4; mat(0,2) = 7; mat(1,0) = -4; mat(1,1) = 2; mat(2,0) = -5; mat(2,2) = 3; try { HT herm; herm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix assignment (non-symmetric) { test_ = "Row-major/column-major HermitianMatrix sparse matrix assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 7UL ); mat(0,0) = 1; mat(0,1) = -4; mat(0,2) = 7; mat(1,0) = -4; mat(1,1) = 2; mat(2,0) = -5; mat(2,2) = 3; try { HT herm; herm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix assignment (HermitianMatrix) { test_ = "Row-major/row-major HermitianMatrix sparse matrix assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > herm1( 3UL, 7UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; HT herm2; herm2 = herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix assignment (HermitianMatrix) { test_ = "Row-major/column-major HermitianMatrix sparse matrix assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > herm1( 3UL, 7UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; HT herm2; herm2 = herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major list assignment //===================================================================================== // Complete initializer list { test_ = "Column-major HermitianMatrix initializer list assignment (complete list)"; OHT herm; herm = { { 1, 2, 3 }, { 2, 4, 0 }, { 3, 0, 6 } }; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != 2 || herm(0,2) != 3 || herm(1,0) != 2 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 3 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 2 3 )\n( 2 4 0 )\n( 3 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Incomplete initializer list { test_ = "Column-major HermitianMatrix initializer list assignment (incomplete list)"; OHT herm; herm = { { 1, 2, 3 }, { 2, 4 }, { 3, 0, 6 } }; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != 2 || herm(0,2) != 3 || herm(1,0) != 2 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 3 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 2 3 )\n( 2 4 0 )\n( 3 0 6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major copy assignment //===================================================================================== // Copy assignment (0x0) { test_ = "Column-major HermitianMatrix copy assignment (0x0)"; OHT herm1, herm2; herm2 = herm1; checkRows ( herm2, 0UL ); checkColumns ( herm2, 0UL ); checkNonZeros( herm2, 0UL ); } // Copy assignment (3x3) { test_ = "Column-major HermitianMatrix copy assignment (3x3)"; OHT herm1( 3UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; OHT herm2; herm2 = herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major move assignment //===================================================================================== // Move assignment (0x0) { test_ = "Column-major HermitianMatrix move assignment (0x0)"; OHT herm1, herm2; herm2 = std::move( herm1 ); checkRows ( herm2, 0UL ); checkColumns ( herm2, 0UL ); checkNonZeros( herm2, 0UL ); } // Move assignment (3x3) { test_ = "Column-major HermitianMatrix move assignment (3x3)"; OHT herm1( 3UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; OHT herm2; herm2 = std::move( herm1 ); checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix assignment //===================================================================================== // Conversion assignment (0x0) { test_ = "Column-major HermitianMatrix dense matrix assignment (0x0)"; const blaze::DynamicMatrix<int,blaze::columnMajor> mat; OHT herm; herm = mat; checkRows ( herm, 0UL ); checkColumns ( herm, 0UL ); checkNonZeros( herm, 0UL ); } // Column-major/row-major dense matrix assignment (symmetric) { test_ = "Column-major/row-major HermitianMatrix dense matrix assignment (symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { 7, 0, 3 } } ); OHT herm; herm = mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != -4 || herm(0,2) != 7 || herm(1,0) != -4 || herm(1,1) != 2 || herm(1,2) != 0 || herm(2,0) != 7 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix assignment (symmetric) { test_ = "Column-major/column-major HermitianMatrix dense matrix assignment (symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { 7, 0, 3 } } ); OHT herm; herm = mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 7UL ); if( herm(0,0) != 1 || herm(0,1) != -4 || herm(0,2) != 7 || herm(1,0) != -4 || herm(1,1) != 2 || herm(1,2) != 0 || herm(2,0) != 7 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major dense matrix assignment (non-symmetric) { test_ = "Column-major/row-major HermitianMatrix dense matrix assignment (non-symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat( { { 1, -4, 7 }, {-4, 2, 0 }, {-5, 0, 3 } } ); try { OHT herm; herm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix assignment (non-symmetric) { test_ = "Column-major/column-major HermitianMatrix dense matrix assignment (non-symmetric)"; const blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat( { { 1, -4, 7 }, { -4, 2, 0 }, { -5, 0, 3 } } ); try { OHT herm; herm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix assignment (HermitianMatrix) { test_ = "Column-major/row-major HermitianMatrix dense matrix assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> > herm1; herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; OHT herm2; herm2 = herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix assignment (HermitianMatrix) { test_ = "Column-major/column-major HermitianMatrix dense matrix assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> > herm1; herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; OHT herm2; herm2 = herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major sparse matrix assignment //===================================================================================== // Conversion assignment (0x0) { test_ = "Column-major HermitianMatrix sparse matrix assignment (0x0)"; const blaze::CompressedMatrix<int,blaze::columnMajor> mat; OHT herm; herm = mat; checkRows ( herm, 0UL ); checkColumns ( herm, 0UL ); checkNonZeros( herm, 0UL ); } // Column-major/row-major sparse matrix assignment (symmetric) { test_ = "Column-major/row-major HermitianMatrix sparse matrix assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 8UL ); mat(0,0) = 1; mat(0,1) = -4; mat(0,2) = 7; mat(1,0) = -4; mat(1,1) = 2; mat(2,0) = 7; mat(2,2) = 3; mat.insert( 1UL, 2UL, 0 ); OHT herm; herm = mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 8UL ); if( herm(0,0) != 1 || herm(0,1) != -4 || herm(0,2) != 7 || herm(1,0) != -4 || herm(1,1) != 2 || herm(1,2) != 0 || herm(2,0) != 7 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix assignment (symmetric) { test_ = "Column-major/column-major HermitianMatrix sparse matrix assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 8UL ); mat(0,0) = 1; mat(0,1) = -4; mat(0,2) = 7; mat(1,0) = -4; mat(1,1) = 2; mat(2,0) = 7; mat(2,2) = 3; mat.insert( 1UL, 2UL, 0 ); OHT herm; herm = mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkNonZeros( herm, 8UL ); if( herm(0,0) != 1 || herm(0,1) != -4 || herm(0,2) != 7 || herm(1,0) != -4 || herm(1,1) != 2 || herm(1,2) != 0 || herm(2,0) != 7 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major sparse matrix assignment (non-symmetric) { test_ = "Column-major/row-major HermitianMatrix sparse matrix assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 7UL ); mat(0,0) = 1; mat(0,1) = -4; mat(0,2) = 7; mat(1,0) = -4; mat(1,1) = 2; mat(2,0) = -5; mat(2,2) = 3; try { OHT herm; herm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix assignment (non-symmetric) { test_ = "Column-major/column-major HermitianMatrix sparse matrix assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 7UL ); mat(0,0) = 1; mat(0,1) = -4; mat(0,2) = 7; mat(1,0) = -4; mat(1,1) = 2; mat(2,0) = -5; mat(2,2) = 3; try { OHT herm; herm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix assignment (HermitianMatrix) { test_ = "Column-major/row-major HermitianMatrix sparse matrix assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > herm1( 3UL, 7UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; OHT herm2; herm2 = herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix assignment (HermitianMatrix) { test_ = "Column-major/column-major HermitianMatrix sparse matrix assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > herm1( 3UL, 7UL ); herm1(0,0) = 1; herm1(0,1) = -4; herm1(0,2) = 7; herm1(1,1) = 2; herm1(2,2) = 3; OHT herm2; herm2 = herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkNonZeros( herm2, 7UL ); if( herm2(0,0) != 1 || herm2(0,1) != -4 || herm2(0,2) != 7 || herm2(1,0) != -4 || herm2(1,1) != 2 || herm2(1,2) != 0 || herm2(2,0) != 7 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -4 7 )\n( -4 2 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the HermitianMatrix addition assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the addition assignment operators of the HermitianMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void SparseRealTest::testAddAssign() { //===================================================================================== // Row-major dense matrix addition assignment //===================================================================================== // Row-major/row-major dense matrix addition assignment (symmetric) { test_ = "Row-major/row-major HermitianMatrix dense matrix addition assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm += mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -6 || herm(0,2) != 13 || herm(1,0) != -6 || herm(1,1) != 5 || herm(1,2) != 0 || herm(2,0) != 13 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix addition assignment (symmetric) { test_ = "Row-major/column-major HermitianMatrix dense matrix addition assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm += mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -6 || herm(0,2) != 13 || herm(1,0) != -6 || herm(1,1) != 5 || herm(1,2) != 0 || herm(2,0) != 13 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major dense matrix addition assignment (non-symmetric) { test_ = "Row-major/row-major HermitianMatrix dense matrix addition assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix addition assignment (non-symmetric) { test_ = "Row-major/column-major HermitianMatrix dense matrix addition assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix addition assignment (HermitianMatrix) { test_ = "Row-major/row-major HermitianMatrix dense matrix addition assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::rowMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 += herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -6 || herm2(0,2) != 13 || herm2(1,0) != -6 || herm2(1,1) != 5 || herm2(1,2) != 0 || herm2(2,0) != 13 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix addition assignment (HermitianMatrix) { test_ = "Row-major/column-major HermitianMatrix dense matrix addition assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::columnMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 += herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -6 || herm2(0,2) != 13 || herm2(1,0) != -6 || herm2(1,1) != 5 || herm2(1,2) != 0 || herm2(2,0) != 13 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major sparse matrix addition assignment //===================================================================================== // Row-major/row-major sparse matrix addition assignment (symmetric) { test_ = "Row-major/row-major HermitianMatrix sparse matrix addition assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm += mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 8UL ); checkNonZeros( herm, 8UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 3UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -6 || herm(0,2) != 13 || herm(1,0) != -6 || herm(1,1) != 5 || herm(1,2) != 0 || herm(2,0) != 13 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix addition assignment (symmetric) { test_ = "Row-major/column-major HermitianMatrix sparse matrix addition assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm += mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 8UL ); checkNonZeros( herm, 8UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 3UL ); if( herm(0,0) != 1 || herm(0,1) != -6 || herm(0,2) != 13 || herm(1,0) != -6 || herm(1,1) != 5 || herm(1,2) != 0 || herm(2,0) != 13 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major sparse matrix addition assignment (non-symmetric) { test_ = "Row-major/row-major HermitianMatrix sparse matrix addition assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix addition assignment (non-symmetric) { test_ = "Row-major/column-major HermitianMatrix sparse matrix addition assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix addition assignment (HermitianMatrix) { test_ = "Row-major/row-major HermitianMatrix sparse matrix addition assignment (HermitianMatrix)"; HT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 += herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -6 || herm2(0,2) != 13 || herm2(1,0) != -6 || herm2(1,1) != 5 || herm2(1,2) != 0 || herm2(2,0) != 13 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix addition assignment (HermitianMatrix) { test_ = "Row-major/column-major HermitianMatrix sparse matrix addition assignment (HermitianMatrix)"; OHT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 += herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -6 || herm2(0,2) != 13 || herm2(1,0) != -6 || herm2(1,1) != 5 || herm2(1,2) != 0 || herm2(2,0) != 13 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix addition assignment //===================================================================================== // Column-major/row-major dense matrix addition assignment (symmetric) { test_ = "Column-major/row-major HermitianMatrix dense matrix addition assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm += mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -6 || herm(0,2) != 13 || herm(1,0) != -6 || herm(1,1) != 5 || herm(1,2) != 0 || herm(2,0) != 13 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix addition assignment (symmetric) { test_ = "Column-major/column-major HermitianMatrix dense matrix addition assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm += mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -6 || herm(0,2) != 13 || herm(1,0) != -6 || herm(1,1) != 5 || herm(1,2) != 0 || herm(2,0) != 13 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major dense matrix addition assignment (non-symmetric) { test_ = "Column-major/row-major HermitianMatrix dense matrix addition assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix addition assignment (non-symmetric) { test_ = "Column-major/column-major HermitianMatrix dense matrix addition assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix addition assignment (HermitianMatrix) { test_ = "Column-major/row-major HermitianMatrix dense matrix addition assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::rowMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 += herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -6 || herm2(0,2) != 13 || herm2(1,0) != -6 || herm2(1,1) != 5 || herm2(1,2) != 0 || herm2(2,0) != 13 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix addition assignment (HermitianMatrix) { test_ = "Column-major/column-major HermitianMatrix dense matrix addition assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::columnMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 += herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -6 || herm2(0,2) != 13 || herm2(1,0) != -6 || herm2(1,1) != 5 || herm2(1,2) != 0 || herm2(2,0) != 13 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major sparse matrix addition assignment //===================================================================================== // Column-major/row-major sparse matrix addition assignment (symmetric) { test_ = "Column-major/row-major HermitianMatrix sparse matrix addition assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm += mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 8UL ); checkNonZeros( herm, 8UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 3UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -6 || herm(0,2) != 13 || herm(1,0) != -6 || herm(1,1) != 5 || herm(1,2) != 0 || herm(2,0) != 13 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix addition assignment (symmetric) { test_ = "Column-major/column-major HermitianMatrix sparse matrix addition assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm += mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 8UL ); checkNonZeros( herm, 8UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 3UL ); if( herm(0,0) != 1 || herm(0,1) != -6 || herm(0,2) != 13 || herm(1,0) != -6 || herm(1,1) != 5 || herm(1,2) != 0 || herm(2,0) != 13 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major sparse matrix addition assignment (non-symmetric) { test_ = "Column-major/row-major HermitianMatrix sparse matrix addition assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix addition assignment (non-symmetric) { test_ = "Column-major/column-major HermitianMatrix sparse matrix addition assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix addition assignment (HermitianMatrix) { test_ = "Column-major/row-major HermitianMatrix sparse matrix addition assignment (HermitianMatrix)"; HT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 += herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -6 || herm2(0,2) != 13 || herm2(1,0) != -6 || herm2(1,1) != 5 || herm2(1,2) != 0 || herm2(2,0) != 13 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix addition assignment (HermitianMatrix) { test_ = "Column-major/column-major HermitianMatrix sparse matrix addition assignment (HermitianMatrix)"; OHT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 += herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -6 || herm2(0,2) != 13 || herm2(1,0) != -6 || herm2(1,1) != 5 || herm2(1,2) != 0 || herm2(2,0) != 13 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -6 13 )\n( -6 5 0 )\n( 13 0 3 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the HermitianMatrix subtraction assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the subtraction assignment operators of the HermitianMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void SparseRealTest::testSubAssign() { //===================================================================================== // Row-major dense matrix subtraction assignment //===================================================================================== // Row-major/row-major dense matrix subtraction assignment (symmetric) { test_ = "Row-major/row-major HermitianMatrix dense matrix subtraction assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm -= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -2 || herm(0,2) != 1 || herm(1,0) != -2 || herm(1,1) != -1 || herm(1,2) != 0 || herm(2,0) != 1 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix subtraction assignment (symmetric) { test_ = "Row-major/column-major HermitianMatrix dense matrix subtraction assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm -= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -2 || herm(0,2) != 1 || herm(1,0) != -2 || herm(1,1) != -1 || herm(1,2) != 0 || herm(2,0) != 1 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major dense matrix subtraction assignment (non-symmetric) { test_ = "Row-major/row-major HermitianMatrix dense matrix subtraction assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix subtraction assignment (non-symmetric) { test_ = "Row-major/column-major HermitianMatrix dense matrix subtraction assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix subtraction assignment (HermitianMatrix) { test_ = "Row-major/row-major HermitianMatrix dense matrix subtraction assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::rowMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 -= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -2 || herm2(0,2) != 1 || herm2(1,0) != -2 || herm2(1,1) != -1 || herm2(1,2) != 0 || herm2(2,0) != 1 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix subtraction assignment (HermitianMatrix) { test_ = "Row-major/column-major HermitianMatrix dense matrix subtraction assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::columnMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 -= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -2 || herm2(0,2) != 1 || herm2(1,0) != -2 || herm2(1,1) != -1 || herm2(1,2) != 0 || herm2(2,0) != 1 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major sparse matrix subtraction assignment //===================================================================================== // Row-major/row-major sparse matrix subtraction assignment (symmetric) { test_ = "Row-major/row-major HermitianMatrix sparse matrix subtraction assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm -= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 8UL ); checkNonZeros( herm, 8UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 3UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -2 || herm(0,2) != 1 || herm(1,0) != -2 || herm(1,1) != -1 || herm(1,2) != 0 || herm(2,0) != 1 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix subtraction assignment (symmetric) { test_ = "Row-major/column-major HermitianMatrix sparse matrix subtraction assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm -= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 8UL ); checkNonZeros( herm, 8UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 3UL ); if( herm(0,0) != 1 || herm(0,1) != -2 || herm(0,2) != 1 || herm(1,0) != -2 || herm(1,1) != -1 || herm(1,2) != 0 || herm(2,0) != 1 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major sparse matrix subtraction assignment (non-symmetric) { test_ = "Row-major/row-major HermitianMatrix sparse matrix subtraction assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix subtraction assignment (non-symmetric) { test_ = "Row-major/column-major HermitianMatrix sparse matrix subtraction assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix subtraction assignment (HermitianMatrix) { test_ = "Row-major/row-major HermitianMatrix sparse matrix subtraction assignment (HermitianMatrix)"; HT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 -= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -2 || herm2(0,2) != 1 || herm2(1,0) != -2 || herm2(1,1) != -1 || herm2(1,2) != 0 || herm2(2,0) != 1 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix subtraction assignment (HermitianMatrix) { test_ = "Row-major/column-major HermitianMatrix sparse matrix subtraction assignment (HermitianMatrix)"; OHT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 -= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -2 || herm2(0,2) != 1 || herm2(1,0) != -2 || herm2(1,1) != -1 || herm2(1,2) != 0 || herm2(2,0) != 1 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix subtraction assignment //===================================================================================== // Column-major/row-major dense matrix subtraction assignment (symmetric) { test_ = "Column-major/row-major HermitianMatrix dense matrix subtraction assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm -= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -2 || herm(0,2) != 1 || herm(1,0) != -2 || herm(1,1) != -1 || herm(1,2) != 0 || herm(2,0) != 1 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix subtraction assignment (symmetric) { test_ = "Column-major/column-major HermitianMatrix dense matrix subtraction assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm -= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -2 || herm(0,2) != 1 || herm(1,0) != -2 || herm(1,1) != -1 || herm(1,2) != 0 || herm(2,0) != 1 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major dense matrix subtraction assignment (non-symmetric) { test_ = "Column-major/row-major HermitianMatrix dense matrix subtraction assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix subtraction assignment (non-symmetric) { test_ = "Column-major/column-major HermitianMatrix dense matrix subtraction assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix subtraction assignment (HermitianMatrix) { test_ = "Column-major/row-major HermitianMatrix dense matrix subtraction assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::rowMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 -= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -2 || herm2(0,2) != 1 || herm2(1,0) != -2 || herm2(1,1) != -1 || herm2(1,2) != 0 || herm2(2,0) != 1 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix subtraction assignment (HermitianMatrix) { test_ = "Column-major/column-major HermitianMatrix dense matrix subtraction assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::columnMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 -= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -2 || herm2(0,2) != 1 || herm2(1,0) != -2 || herm2(1,1) != -1 || herm2(1,2) != 0 || herm2(2,0) != 1 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major sparse matrix subtraction assignment //===================================================================================== // Column-major/row-major sparse matrix subtraction assignment (symmetric) { test_ = "Column-major/row-major HermitianMatrix sparse matrix subtraction assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm -= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 8UL ); checkNonZeros( herm, 8UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 3UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 1 || herm(0,1) != -2 || herm(0,2) != 1 || herm(1,0) != -2 || herm(1,1) != -1 || herm(1,2) != 0 || herm(2,0) != 1 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix subtraction assignment (symmetric) { test_ = "Column-major/column-major HermitianMatrix sparse matrix subtraction assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 5UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm -= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 8UL ); checkNonZeros( herm, 8UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 3UL ); if( herm(0,0) != 1 || herm(0,1) != -2 || herm(0,2) != 1 || herm(1,0) != -2 || herm(1,1) != -1 || herm(1,2) != 0 || herm(2,0) != 1 || herm(2,1) != 0 || herm(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major sparse matrix subtraction assignment (non-symmetric) { test_ = "Column-major/row-major HermitianMatrix sparse matrix subtraction assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix subtraction assignment (non-symmetric) { test_ = "Column-major/column-major HermitianMatrix sparse matrix subtraction assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix subtraction assignment (HermitianMatrix) { test_ = "Column-major/row-major HermitianMatrix sparse matrix subtraction assignment (HermitianMatrix)"; HT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 -= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -2 || herm2(0,2) != 1 || herm2(1,0) != -2 || herm2(1,1) != -1 || herm2(1,2) != 0 || herm2(2,0) != 1 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix subtraction assignment (HermitianMatrix) { test_ = "Column-major/column-major HermitianMatrix sparse matrix subtraction assignment (HermitianMatrix)"; OHT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 -= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 1 || herm2(0,1) != -2 || herm2(0,2) != 1 || herm2(1,0) != -2 || herm2(1,1) != -1 || herm2(1,2) != 0 || herm2(2,0) != 1 || herm2(2,1) != 0 || herm2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 -2 1 )\n( -2 -1 0 )\n( 1 0 3 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the HermitianMatrix Schur product assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the Schur product assignment operators of the HermitianMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void SparseRealTest::testSchurAssign() { //===================================================================================== // Row-major dense matrix Schur product assignment //===================================================================================== // Row-major/row-major dense matrix Schur product assignment (symmetric) { test_ = "Row-major/row-major HermitianMatrix dense matrix Schur product assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm %= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 0 || herm(0,1) != 8 || herm(0,2) != 42 || herm(1,0) != 8 || herm(1,1) != 6 || herm(1,2) != 0 || herm(2,0) != 42 || herm(2,1) != 0 || herm(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix Schur product assignment (symmetric) { test_ = "Row-major/column-major HermitianMatrix dense matrix Schur product assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm %= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 0 || herm(0,1) != 8 || herm(0,2) != 42 || herm(1,0) != 8 || herm(1,1) != 6 || herm(1,2) != 0 || herm(2,0) != 42 || herm(2,1) != 0 || herm(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major dense matrix Schur product assignment (non-symmetric) { test_ = "Row-major/row-major HermitianMatrix dense matrix Schur product assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm %= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix Schur product assignment (non-symmetric) { test_ = "Row-major/column-major HermitianMatrix dense matrix Schur product assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm %= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix Schur product assignment (HermitianMatrix) { test_ = "Row-major/row-major HermitianMatrix dense matrix Schur product assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::rowMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 %= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 0 || herm2(0,1) != 8 || herm2(0,2) != 42 || herm2(1,0) != 8 || herm2(1,1) != 6 || herm2(1,2) != 0 || herm2(2,0) != 42 || herm2(2,1) != 0 || herm2(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix Schur product assignment (HermitianMatrix) { test_ = "Row-major/column-major HermitianMatrix dense matrix Schur product assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::columnMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 %= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 0 || herm2(0,1) != 8 || herm2(0,2) != 42 || herm2(1,0) != 8 || herm2(1,1) != 6 || herm2(1,2) != 0 || herm2(2,0) != 42 || herm2(2,1) != 0 || herm2(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major sparse matrix Schur product assignment //===================================================================================== // Row-major/row-major sparse matrix Schur product assignment (symmetric) { test_ = "Row-major/row-major HermitianMatrix sparse matrix Schur product assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm %= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 5UL ); checkNonZeros( herm, 5UL ); checkNonZeros( herm, 0UL, 2UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 1UL ); if( herm(0,0) != 0 || herm(0,1) != 8 || herm(0,2) != 42 || herm(1,0) != 8 || herm(1,1) != 6 || herm(1,2) != 0 || herm(2,0) != 42 || herm(2,1) != 0 || herm(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix Schur product assignment (symmetric) { test_ = "Row-major/column-major HermitianMatrix sparse matrix Schur product assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm %= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 5UL ); checkNonZeros( herm, 5UL ); checkNonZeros( herm, 0UL, 2UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 1UL ); if( herm(0,0) != 0 || herm(0,1) != 8 || herm(0,2) != 42 || herm(1,0) != 8 || herm(1,1) != 6 || herm(1,2) != 0 || herm(2,0) != 42 || herm(2,1) != 0 || herm(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major sparse matrix Schur product assignment (non-symmetric) { test_ = "Row-major/row-major HermitianMatrix sparse matrix Schur product assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm %= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix Schur product assignment (non-symmetric) { test_ = "Row-major/column-major HermitianMatrix sparse matrix Schur product assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm %= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix Schur product assignment (HermitianMatrix) { test_ = "Row-major/row-major HermitianMatrix sparse matrix Schur product assignment (HermitianMatrix)"; HT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 %= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 5UL ); checkNonZeros( herm2, 5UL ); checkNonZeros( herm2, 0UL, 2UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 1UL ); if( herm2(0,0) != 0 || herm2(0,1) != 8 || herm2(0,2) != 42 || herm2(1,0) != 8 || herm2(1,1) != 6 || herm2(1,2) != 0 || herm2(2,0) != 42 || herm2(2,1) != 0 || herm2(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix Schur product assignment (HermitianMatrix) { test_ = "Row-major/column-major HermitianMatrix sparse matrix Schur product assignment (HermitianMatrix)"; OHT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 %= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 5UL ); checkNonZeros( herm2, 5UL ); checkNonZeros( herm2, 0UL, 2UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 1UL ); if( herm2(0,0) != 0 || herm2(0,1) != 8 || herm2(0,2) != 42 || herm2(1,0) != 8 || herm2(1,1) != 6 || herm2(1,2) != 0 || herm2(2,0) != 42 || herm2(2,1) != 0 || herm2(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix Schur product assignment //===================================================================================== // Column-major/row-major dense matrix Schur product assignment (symmetric) { test_ = "Column-major/row-major HermitianMatrix dense matrix Schur product assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm %= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 0 || herm(0,1) != 8 || herm(0,2) != 42 || herm(1,0) != 8 || herm(1,1) != 6 || herm(1,2) != 0 || herm(2,0) != 42 || herm(2,1) != 0 || herm(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix Schur product assignment (symmetric) { test_ = "Column-major/column-major HermitianMatrix dense matrix Schur product assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm %= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 0 || herm(0,1) != 8 || herm(0,2) != 42 || herm(1,0) != 8 || herm(1,1) != 6 || herm(1,2) != 0 || herm(2,0) != 42 || herm(2,1) != 0 || herm(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major dense matrix Schur product assignment (non-symmetric) { test_ = "Column-major/row-major HermitianMatrix dense matrix Schur product assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm %= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix Schur product assignment (non-symmetric) { test_ = "Column-major/column-major HermitianMatrix dense matrix Schur product assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm %= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix Schur product assignment (HermitianMatrix) { test_ = "Column-major/row-major HermitianMatrix dense matrix Schur product assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::rowMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 %= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 0 || herm2(0,1) != 8 || herm2(0,2) != 42 || herm2(1,0) != 8 || herm2(1,1) != 6 || herm2(1,2) != 0 || herm2(2,0) != 42 || herm2(2,1) != 0 || herm2(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix Schur product assignment (HermitianMatrix) { test_ = "Column-major/column-major HermitianMatrix dense matrix Schur product assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::columnMajor> > herm1( 3UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 %= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 0 || herm2(0,1) != 8 || herm2(0,2) != 42 || herm2(1,0) != 8 || herm2(1,1) != 6 || herm2(1,2) != 0 || herm2(2,0) != 42 || herm2(2,1) != 0 || herm2(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major sparse matrix Schur product assignment //===================================================================================== // Column-major/row-major sparse matrix Schur product assignment (symmetric) { test_ = "Column-major/row-major HermitianMatrix sparse matrix Schur product assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm %= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 5UL ); checkNonZeros( herm, 5UL ); checkNonZeros( herm, 0UL, 2UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 1UL ); if( herm(0,0) != 0 || herm(0,1) != 8 || herm(0,2) != 42 || herm(1,0) != 8 || herm(1,1) != 6 || herm(1,2) != 0 || herm(2,0) != 42 || herm(2,1) != 0 || herm(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix Schur product assignment (symmetric) { test_ = "Column-major/column-major HermitianMatrix sparse matrix Schur product assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 6UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,0) = -2; mat(1,1) = 3; mat(2,0) = 6; mat.insert( 1UL, 2UL, 0 ); OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm %= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 5UL ); checkNonZeros( herm, 5UL ); checkNonZeros( herm, 0UL, 2UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 1UL ); if( herm(0,0) != 0 || herm(0,1) != 8 || herm(0,2) != 42 || herm(1,0) != 8 || herm(1,1) != 6 || herm(1,2) != 0 || herm(2,0) != 42 || herm(2,1) != 0 || herm(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major sparse matrix Schur product assignment (non-symmetric) { test_ = "Column-major/row-major HermitianMatrix sparse matrix Schur product assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm %= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix Schur product assignment (non-symmetric) { test_ = "Column-major/column-major HermitianMatrix sparse matrix Schur product assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm %= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix Schur product assignment (HermitianMatrix) { test_ = "Column-major/row-major HermitianMatrix sparse matrix Schur product assignment (HermitianMatrix)"; HT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 %= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 5UL ); checkNonZeros( herm2, 5UL ); checkNonZeros( herm2, 0UL, 2UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 1UL ); if( herm2(0,0) != 0 || herm2(0,1) != 8 || herm2(0,2) != 42 || herm2(1,0) != 8 || herm2(1,1) != 6 || herm2(1,2) != 0 || herm2(2,0) != 42 || herm2(2,1) != 0 || herm2(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix Schur product assignment (HermitianMatrix) { test_ = "Column-major/column-major HermitianMatrix sparse matrix Schur product assignment (HermitianMatrix)"; OHT herm1( 3UL, 5UL ); herm1(0,1) = -2; herm1(0,2) = 6; herm1(1,1) = 3; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 %= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 5UL ); checkNonZeros( herm2, 5UL ); checkNonZeros( herm2, 0UL, 2UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 1UL ); if( herm2(0,0) != 0 || herm2(0,1) != 8 || herm2(0,2) != 42 || herm2(1,0) != 8 || herm2(1,1) != 6 || herm2(1,2) != 0 || herm2(2,0) != 42 || herm2(2,1) != 0 || herm2(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Schur product assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 1 8 42 )\n( 8 6 0 )\n( 42 0 0 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the HermitianMatrix multiplication assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the multiplication assignment operators of the HermitianMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void SparseRealTest::testMultAssign() { //===================================================================================== // Row-major dense matrix multiplication assignment //===================================================================================== // Row-major/row-major dense matrix multiplication assignment (symmetric) { test_ = "Row-major/row-major HermitianMatrix dense matrix multiplication assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm *= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 2 || herm(0,1) != -8 || herm(0,2) != 14 || herm(1,0) != -8 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 14 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix multiplication assignment (symmetric) { test_ = "Row-major/column-major HermitianMatrix dense matrix multiplication assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm *= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 2 || herm(0,1) != -8 || herm(0,2) != 14 || herm(1,0) != -8 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 14 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major dense matrix multiplication assignment (non-symmetric) { test_ = "Row-major/row-major HermitianMatrix dense matrix multiplication assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix multiplication assignment (non-symmetric) { test_ = "Row-major/column-major HermitianMatrix dense matrix multiplication assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix multiplication assignment (HermitianMatrix) { test_ = "Row-major/row-major HermitianMatrix dense matrix multiplication assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::rowMajor> > herm1( 3UL ); herm1(0,0) = 2; herm1(1,1) = 2; herm1(2,2) = 2; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 *= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 2 || herm2(0,1) != -8 || herm2(0,2) != 14 || herm2(1,0) != -8 || herm2(1,1) != 4 || herm2(1,2) != 0 || herm2(2,0) != 14 || herm2(2,1) != 0 || herm2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix multiplication assignment (HermitianMatrix) { test_ = "Row-major/column-major HermitianMatrix dense matrix multiplication assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::columnMajor> > herm1( 3UL ); herm1(0,0) = 2; herm1(1,1) = 2; herm1(2,2) = 2; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 *= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 2 || herm2(0,1) != -8 || herm2(0,2) != 14 || herm2(1,0) != -8 || herm2(1,1) != 4 || herm2(1,2) != 0 || herm2(2,0) != 14 || herm2(2,1) != 0 || herm2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major sparse matrix multiplication assignment //===================================================================================== // Row-major/row-major sparse matrix multiplication assignment (symmetric) { test_ = "Row-major/row-major HermitianMatrix sparse matrix multiplication assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm *= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 2 || herm(0,1) != -8 || herm(0,2) != 14 || herm(1,0) != -8 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 14 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix multiplication assignment (symmetric) { test_ = "Row-major/column-major HermitianMatrix sparse matrix multiplication assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm *= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 2 || herm(0,1) != -8 || herm(0,2) != 14 || herm(1,0) != -8 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 14 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major sparse matrix multiplication assignment (non-symmetric) { test_ = "Row-major/row-major HermitianMatrix sparse matrix multiplication assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix multiplication assignment (non-symmetric) { test_ = "Row-major/column-major HermitianMatrix sparse matrix multiplication assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; HT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix multiplication assignment (HermitianMatrix) { test_ = "Row-major/row-major HermitianMatrix sparse matrix multiplication assignment (HermitianMatrix)"; HT herm1( 3UL, 3UL ); herm1(0,0) = 2; herm1(1,1) = 2; herm1(2,2) = 2; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 *= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 2 || herm2(0,1) != -8 || herm2(0,2) != 14 || herm2(1,0) != -8 || herm2(1,1) != 4 || herm2(1,2) != 0 || herm2(2,0) != 14 || herm2(2,1) != 0 || herm2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix multiplication assignment (HermitianMatrix) { test_ = "Row-major/column-major HermitianMatrix sparse matrix multiplication assignment (HermitianMatrix)"; OHT herm1( 3UL, 3UL ); herm1(0,0) = 2; herm1(1,1) = 2; herm1(2,2) = 2; HT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 *= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 2 || herm2(0,1) != -8 || herm2(0,2) != 14 || herm2(1,0) != -8 || herm2(1,1) != 4 || herm2(1,2) != 0 || herm2(2,0) != 14 || herm2(2,1) != 0 || herm2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix multiplication assignment //===================================================================================== // Column-major/row-major dense matrix multiplication assignment (symmetric) { test_ = "Column-major/row-major HermitianMatrix dense matrix multiplication assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm *= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 2 || herm(0,1) != -8 || herm(0,2) != 14 || herm(1,0) != -8 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 14 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix multiplication assignment (symmetric) { test_ = "Column-major/column-major HermitianMatrix dense matrix multiplication assignment (symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm *= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 2 || herm(0,1) != -8 || herm(0,2) != 14 || herm(1,0) != -8 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 14 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major dense matrix multiplication assignment (non-symmetric) { test_ = "Column-major/row-major HermitianMatrix dense matrix multiplication assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix multiplication assignment (non-symmetric) { test_ = "Column-major/column-major HermitianMatrix dense matrix multiplication assignment (non-symmetric)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix multiplication assignment (HermitianMatrix) { test_ = "Column-major/row-major HermitianMatrix dense matrix multiplication assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::rowMajor> > herm1( 3UL ); herm1(0,0) = 2; herm1(1,1) = 2; herm1(2,2) = 2; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 *= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 2 || herm2(0,1) != -8 || herm2(0,2) != 14 || herm2(1,0) != -8 || herm2(1,1) != 4 || herm2(1,2) != 0 || herm2(2,0) != 14 || herm2(2,1) != 0 || herm2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix multiplication assignment (HermitianMatrix) { test_ = "Column-major/column-major HermitianMatrix dense matrix multiplication assignment (HermitianMatrix)"; blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::columnMajor> > herm1( 3UL ); herm1(0,0) = 2; herm1(1,1) = 2; herm1(2,2) = 2; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 *= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 2 || herm2(0,1) != -8 || herm2(0,2) != 14 || herm2(1,0) != -8 || herm2(1,1) != 4 || herm2(1,2) != 0 || herm2(2,0) != 14 || herm2(2,1) != 0 || herm2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major sparse matrix multiplication assignment //===================================================================================== // Column-major/row-major sparse matrix multiplication assignment (symmetric) { test_ = "Column-major/row-major HermitianMatrix sparse matrix multiplication assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm *= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 2 || herm(0,1) != -8 || herm(0,2) != 14 || herm(1,0) != -8 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 14 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix multiplication assignment (symmetric) { test_ = "Column-major/column-major HermitianMatrix sparse matrix multiplication assignment (symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; herm *= mat; checkRows ( herm, 3UL ); checkColumns ( herm, 3UL ); checkCapacity( herm, 7UL ); checkNonZeros( herm, 7UL ); checkNonZeros( herm, 0UL, 3UL ); checkNonZeros( herm, 1UL, 2UL ); checkNonZeros( herm, 2UL, 2UL ); if( herm(0,0) != 2 || herm(0,1) != -8 || herm(0,2) != 14 || herm(1,0) != -8 || herm(1,1) != 4 || herm(1,2) != 0 || herm(2,0) != 14 || herm(2,1) != 0 || herm(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major sparse matrix multiplication assignment (non-symmetric) { test_ = "Column-major/row-major HermitianMatrix sparse matrix multiplication assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of non-symmetric row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix multiplication assignment (non-symmetric) { test_ = "Column-major/column-major HermitianMatrix sparse matrix multiplication assignment (non-symmetric)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,1) = -2; mat(0,2) = 6; mat(1,1) = 3; mat(2,0) = 6; OHT herm( 3UL ); herm(0,0) = 1; herm(0,1) = -4; herm(0,2) = 7; herm(1,1) = 2; herm(2,2) = 3; try { herm *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of non-symmetric column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << herm << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix multiplication assignment (HermitianMatrix) { test_ = "Column-major/row-major HermitianMatrix sparse matrix multiplication assignment (HermitianMatrix)"; HT herm1( 3UL, 3UL ); herm1(0,0) = 2; herm1(1,1) = 2; herm1(2,2) = 2; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 *= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 2 || herm2(0,1) != -8 || herm2(0,2) != 14 || herm2(1,0) != -8 || herm2(1,1) != 4 || herm2(1,2) != 0 || herm2(2,0) != 14 || herm2(2,1) != 0 || herm2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix multiplication assignment (HermitianMatrix) { test_ = "Column-major/column-major HermitianMatrix sparse matrix multiplication assignment (HermitianMatrix)"; OHT herm1( 3UL, 3UL ); herm1(0,0) = 2; herm1(1,1) = 2; herm1(2,2) = 2; OHT herm2( 3UL ); herm2(0,0) = 1; herm2(0,1) = -4; herm2(0,2) = 7; herm2(1,1) = 2; herm2(2,2) = 3; herm2 *= herm1; checkRows ( herm2, 3UL ); checkColumns ( herm2, 3UL ); checkCapacity( herm2, 7UL ); checkNonZeros( herm2, 7UL ); checkNonZeros( herm2, 0UL, 3UL ); checkNonZeros( herm2, 1UL, 2UL ); checkNonZeros( herm2, 2UL, 2UL ); if( herm2(0,0) != 2 || herm2(0,1) != -8 || herm2(0,2) != 14 || herm2(1,0) != -8 || herm2(1,1) != 4 || herm2(1,2) != 0 || herm2(2,0) != 14 || herm2(2,1) != 0 || herm2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << herm2 << "\n" << " Expected result:\n( 2 -8 14 )\n( -8 4 0 )\n( 14 0 6 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* } // namespace hermitianmatrix } // namespace mathtest } // namespace blazetest //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running HermitianMatrix sparse real test (part 1)..." << std::endl; try { RUN_HERMITIANMATRIX_SPARSEREAL_TEST; } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during HermitianMatrix sparse real test (part 1):\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
2f3870cec24adeee902f4c9118c0b7c2fb8e4604
93186c86b991d8effd36eb5c1125287e45c22535
/Pràctiques grosses/5-Gotham city (EDA)/Solucionador.h
c527eb0b4ff26f6866e79235729d3a3115d33d0a
[]
no_license
marccane/Projectes-CPP
0a6dc55acac8488a30ff424f243d736a5a7f8a1f
60e449df36c1df5546a9f6c3acd1d1349e0c05c5
refs/heads/master
2021-01-01T04:42:29.867496
2017-07-14T15:44:27
2017-07-14T15:44:27
97,229,943
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,070
h
//Marc Cané Salamià //u1939666 //Practica Algoritmica #ifndef SOLUCIONADOR_H #define SOLUCIONADOR_H #include "Solucio.h" #include "Candidat.h" /** \brief Conte les dades per determinar la millor solucio i per saber si aquesta s'ha trobat*/ class Solucionador { public: Solucionador(); /** @pre cert @post retorna si ha trobat o no la Solucio (i la guarda si l’ha trobada)*/ bool Solucionar(Solucio &inicial); /** @pre cert @post retorna si ha trobat o no la millor Solucio*/ bool SolucionarOptim(Solucio &actual); /** @pre cert @post retorna si ha trobat o no una solucio*/ bool SolucionarVorac(Solucio &); private: /** @pre no encertat ^ sol és parcial @post no encertat o encertat ^ sol és completa*/ void trobarUnaSolucio(Solucio &); /** @pre @pre no encertat ^ sol és parcial @post no encertat o encertat ^ sol és optima*/ void trobarMillor(Solucio &actual); bool encertat; Solucio optima; }; #endif // SOLUCIONADOR_H
[ "marc00077@hotmail.com" ]
marc00077@hotmail.com
a17b52910b2cf9fb1a672964ec4540702978a4a1
f1984d9f42b16adc2d51a915b3f008eac758df6e
/Renders/Resources/GlobalBuffers.h
05024cc22b207716863bcf8c68c216279101850c
[]
no_license
Hyeon59/GameMake
66e4d78e9bb7b26e2f6e06e9105f220693ac6c1f
ef728ddd957e9dc983a4aab0864e9905af92de11
refs/heads/master
2021-03-06T19:50:16.340784
2020-03-08T17:42:55
2020-03-08T17:42:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
752
h
#pragma once #include "stdafx.h" class WorldBuffer : public ShaderBuffer { public: WorldBuffer() : ShaderBuffer(&data, sizeof(Struct)) { D3DXMatrixIdentity(&data.world); } void SetWorld(D3DXMATRIX world) { D3DXMatrixTranspose(&data.world, &world); } struct Struct { D3DXMATRIX world; }; private: Struct data; }; class VPBuffer : public ShaderBuffer { public: VPBuffer() : ShaderBuffer(&data, sizeof(Struct)) { D3DXMatrixIdentity(&data.view); D3DXMatrixIdentity(&data.proj); } void SetView(D3DXMATRIX view) { D3DXMatrixTranspose(&data.view, &view); } void SetProj(D3DXMATRIX proj) { D3DXMatrixTranspose(&data.proj, &proj); } struct Struct { D3DXMATRIX view; D3DXMATRIX proj; }; private: Struct data; };
[ "58232553+juwonyoon@users.noreply.github.com" ]
58232553+juwonyoon@users.noreply.github.com
788baf008cc62ac9b98ab34586a7636fe9b6591e
4da7ed6fe70fca58c08dcd54f55e7c216361fb2d
/2/src/server/CommonSys.h
5687deb10c5be3a6c1e6814bbe29ca6755f89bb0
[]
no_license
ensq/dv1457
20a6e81c407d1fbb4000170cd4fa1186a6d26ab3
443a56286628fa273b3a27004ed8899306a41461
refs/heads/master
2022-09-08T17:47:19.344462
2014-06-04T07:17:55
2014-06-04T07:17:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
437
h
#ifndef COMMONSYS_H #define COMMONSYS_H #include <string> #include <cstring> #include <fstream> #include <strings.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <netinet/in.h> #include <signal.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/resource.h> #include <syslog.h> #include <unistd.h> #include <pthread.h> #include <vector> #endif // COMMONSYS_H
[ "CaterHatterPillar@gmail.com" ]
CaterHatterPillar@gmail.com
fcf7d6c23e820eb30f02c44b244e608b7a1756a3
d1cfcb975eb7c436151c86c03a055c789195a45f
/BGE/ObstacleAvoidanceScenario.cpp
f0dcd7a88ed62ffc5866f10e0dff46538baf9041
[]
no_license
sac1million/GE1
fae27bcac658dab584be6b8694b4f0642b18dcf2
b311c5850988c4576013dca5ff01e2d53d516133
refs/heads/master
2021-03-13T00:08:39.165780
2014-01-02T12:41:53
2014-01-02T12:41:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,340
cpp
#include "ObstacleAvoidanceScenario.h" #include "Params.h" #include "SteeringGame.h" #include "Content.h" #include "Sphere.h" using namespace BGE; using namespace std; struct ObstacleParam { public: glm::vec3 pos; float radius; ObstacleParam(glm::vec3 pos, float radius) { this->pos = pos; this->radius = radius; } }; ObstacleAvoidanceScenario::ObstacleAvoidanceScenario(void) { } ObstacleAvoidanceScenario::~ObstacleAvoidanceScenario(void) { } string ObstacleAvoidanceScenario::Description() { return "Obstacle Avoidance Scenario"; } void ObstacleAvoidanceScenario::Initialise() { Params::Load("default"); SteeringGame * game = (SteeringGame *) Game::Instance(); shared_ptr<GameComponent> leader = make_shared<GameComponent>(); leader->tag = "Steerable"; shared_ptr<SteeringController> leaderController = make_shared<SteeringController>(); leaderController->position = glm::vec3(10, 120, 20); leaderController->TurnOn(SteeringController::behaviour_type::arrive); leaderController->TurnOn(SteeringController::behaviour_type::obstacle_avoidance); leaderController->TurnOn(SteeringController::behaviour_type::separation); leaderController->TurnOn(SteeringController::behaviour_type::wall_avoidance); leaderController->targetPos = glm::vec3(0, 100, -550); this->leaderController = leaderController; leader->Attach(leaderController); leader->Attach(Content::LoadModel("viper", glm::rotate(glm::mat4(1), 180.0f, GameComponent::basisUp))); leader->scale = glm::vec3(2,2,2); game->Attach(leader); // Add some Obstacles vector<ObstacleParam> obsParams; obsParams.push_back(ObstacleParam(glm::vec3(0, 110, -10), 20)); obsParams.push_back(ObstacleParam(glm::vec3(10, 136, -80), 17)); obsParams.push_back(ObstacleParam(glm::vec3(-10, 115, -120), 10)); obsParams.push_back(ObstacleParam(glm::vec3(5, 90, -150), 12)); obsParams.push_back(ObstacleParam(glm::vec3(-2, 105, -200), 20)); obsParams.push_back(ObstacleParam(glm::vec3(-25, 120, -250), 10)); obsParams.push_back(ObstacleParam(glm::vec3(-25, 80, -250), 10)); obsParams.push_back(ObstacleParam(glm::vec3(-25, 80, -280), 14)); for (int i = 0 ; i < obsParams.size() ; i ++) { shared_ptr<Sphere> obstacle = make_shared<Sphere>(obsParams[i].radius); obstacle->tag = "Obstacle"; obstacle->position = obsParams[i].pos; game->Attach(obstacle); } // Now make a fleet int fleetSize = 5; float xOff = 6; float zOff = 6; for (int i = 2; i < fleetSize; i++) { for (int j = 0; j < i; j++) { float z = (i - 1) * +zOff; shared_ptr<GameComponent> fleet = make_shared<GameComponent>(); fleet->tag = "Steerable"; shared_ptr<SteeringController> fleetController = make_shared<SteeringController>(); fleetController->leader = leaderController; fleetController->offset = glm::vec3((xOff * (-i / 2.0f)) + (j * xOff), 0, z); fleetController->position = leaderController->position + fleetController->offset; fleetController->TurnOn(SteeringController::behaviour_type::offset_pursuit); fleetController->TurnOn(SteeringController::behaviour_type::separation); fleetController->TurnOn(SteeringController::behaviour_type::wall_avoidance); fleetController->TurnOn(SteeringController::behaviour_type::obstacle_avoidance); fleet->Attach(fleetController); fleet->scale = glm::vec3(2,2,2); fleet->Attach(Content::LoadModel("cobramk1", glm::rotate(glm::mat4(1), 180.0f, GameComponent::basisUp))); game->Attach(fleet); } } game->camFollower = make_shared<GameComponent>(); shared_ptr<SteeringController> camController = make_shared<SteeringController>(); camController->offset = glm::vec3(0,0,3); camController->tag = "Steerable"; camController->leader = leader; camController->position = glm::vec3(0, 115, fleetSize * zOff);; camController->offset = glm::vec3(0, 5, fleetSize * zOff); camController->TurnOffAll(); camController->TurnOn(SteeringController::behaviour_type::offset_pursuit); camController->TurnOn(SteeringController::behaviour_type::wall_avoidance); camController->TurnOn(SteeringController::behaviour_type::obstacle_avoidance); game->Attach(game->camFollower); game->camFollower->Attach(camController); game->camera->GetController()->position = camController->position; shared_ptr<Ground> ground = make_shared<Ground>(); game->Attach(ground); game->ground= ground; }
[ "tc-irl@hotmail.com" ]
tc-irl@hotmail.com
da9ab6c8d29f0f8b49db679164932431a1ebb692
c95436f2fdfa2463af636d887c4ee588a4f6a7bb
/project3/gtest/HashMapTests.cpp
a1c7346df2471f12410fc7e43c1c431c9013ff1c
[]
no_license
binhnn1/CSE-45C
0557cdd3874cb5b087fb1907a71567bf8f82863b
5856c90480f49d98a3c2262c8f626445864ffea8
refs/heads/master
2021-01-17T17:23:21.491219
2016-06-14T07:41:26
2016-06-14T07:41:26
60,870,746
0
11
null
null
null
null
UTF-8
C++
false
false
4,144
cpp
// HashMapTests.cpp // // ICS 45C Fall 2015 // Project #3: Maps and Legends // // Write unit tests for your HashMap class here. I've provided one test already, // though I've commented it out, because it won't compile until you've implemented // three things: the HashMap constructor, the HashMap destructor, and HashMap's // size() member function. #include <gtest/gtest.h> #include "HashMap.hpp" TEST(TestHashMap, sizeOfNewlyCreatedHashMapIsZero) { HashMap empty; ASSERT_EQ(0, empty.size()); } TEST(TestHashMap, sizeOfBucketOfNewlyCreatedHashMapIsTen) { HashMap h; ASSERT_EQ(10, h.bucketCount()); } TEST(TestHashMap, testCopy) { HashMap h1; h1.add("boo", "123"); h1.add("alex", "234"); h1.add("ben", "345"); HashMap h2 = h1; ASSERT_EQ(3, h2.size()); ASSERT_EQ(true, h2.contains("boo")); ASSERT_EQ(true, h2.contains("alex")); ASSERT_EQ(true, h2.contains("ben")); } TEST(TestHashMap, testAssignment) { HashMap h1, h2; h1.add("boo", "123"); h1.add("alex", "234"); h1.add("ben", "345"); h2 = h1; ASSERT_EQ(3, h2.size()); ASSERT_EQ(true, h2.contains("boo")); ASSERT_EQ(true, h2.contains("alex")); ASSERT_EQ(true, h2.contains("ben")); } TEST(TestHashMap, testAdd) { HashMap h; h.add("boo", "123"); ASSERT_EQ(true, h.contains("boo")); ASSERT_EQ("123", h.value("boo")); ASSERT_EQ(1, h.size()); } TEST(TestHashMap, testAddDuplicate) { HashMap h; h.add("boo", "123"); h.add("boo", "234"); ASSERT_EQ("123", h.value("boo")); } TEST(TestHashMap, testRemove) { HashMap h; h.add("boo", "123"); h.add("alex", "234"); h.add("ben", "345"); ASSERT_EQ(3, h.size()); h.remove("boo"); ASSERT_EQ(2, h.size()); ASSERT_EQ(false, h.contains("boo")); } TEST(TestHashMap, testRemoveNonexist) { HashMap h; h.add("boo", "123"); h.add("alex", "234"); h.add("ben", "345"); ASSERT_EQ(3, h.size()); h.remove("john"); ASSERT_EQ(3, h.size()); } TEST(TestHashMap, testRemoveDuplicate) { HashMap h; h.add("boo", "123"); h.add("alex", "234"); h.add("ben", "345"); ASSERT_EQ(3, h.size()); h.remove("boo"); ASSERT_EQ(2, h.size()); h.remove("boo"); ASSERT_EQ(2, h.size()); } TEST(TestHashMap, testContains) { HashMap h; h.add("boo", "123"); h.add("alex", "234"); h.add("ben", "345"); ASSERT_EQ(true, h.contains("boo")); ASSERT_EQ(true, h.contains("alex")); ASSERT_EQ(true, h.contains("ben")); } TEST(TestHashMap, testContainsOfNonExist) { HashMap h; ASSERT_EQ(false, h.contains("George")); } TEST(TestHashMap, testValue) { HashMap h; h.add("boo", "123"); ASSERT_EQ("123", h.value("boo")); } TEST(TestHashMap, testValueOfNonExist) { HashMap h; ASSERT_EQ("", h.value("alex")); } TEST(TestHashMap, testSize) { HashMap h; h.add("boo", "123"); ASSERT_EQ(1, h.size()); h.add("alex", "234"); ASSERT_EQ(2, h.size()); h.add("ben", "345"); ASSERT_EQ(3, h.size()); h.remove("ben"); ASSERT_EQ(2, h.size()); h.remove("ben"); ASSERT_EQ(2, h.size()); } TEST(TestHashMap, testBucketCount) { HashMap h; ASSERT_EQ(10, h.bucketCount()); h.add("boo", "123"); h.add("alex", "234"); h.add("ben", "345"); h.add("john", "123"); h.add("binh", "123"); h.add("george", "567"); h.add("mike", "789"); ASSERT_EQ(10, h.bucketCount()); h.add("lisa", "123"); ASSERT_EQ(21, h.bucketCount()); } TEST(TestHashMap, testLoadFactor) { HashMap h; ASSERT_EQ(0, h.loadFactor()); h.add("boo", "123"); ASSERT_EQ(0.1, h.loadFactor()); h.add("alex", "234"); ASSERT_EQ(0.2, h.loadFactor()); h.remove("boo"); ASSERT_EQ(0.1, h.loadFactor()); } TEST(TestHashMap, testReHash) { HashMap h; h.add("boo", "123"); h.add("alex", "234"); h.add("ben", "345"); h.add("john", "123"); h.add("binh", "123"); h.add("george", "567"); h.add("mike", "789"); ASSERT_EQ(0.7, h.loadFactor()); h.add("lynn", "098"); ASSERT_NE(0.8, h.loadFactor()); }
[ "binhnn1@uci.edu" ]
binhnn1@uci.edu
f9d2e4f05cc1d9bff2f5f905c68cdb07fcd83f04
f9b1d520ceb3a22096d7cd3ea8b486c1ab79bf9b
/myRedBlackTree.h
920bd9512b99dd0c3652ec787dfdbae176ddd5f1
[]
no_license
atkins126/DSA_CPP_Deng
846e1cccb04d53702dc66a8362f256b1f5c964b3
cd92481d0f1ba141fc621488c29b36220da69cd0
refs/heads/master
2022-01-25T13:43:11.354131
2019-05-07T14:40:36
2019-05-07T14:40:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,854
h
#ifndef DSA_CPP_DENG_MYREDBLACKTREE_H #define DSA_CPP_DENG_MYREDBLACKTREE_H #include "myBST.h" #define IsBlack(p) (!(p) || ((p)->color == RB_BLACK)) // 外部节点视作黑色 #define IsRed(p) (!IsBlack(p)) #define BlackHeightUpdated(x) (\ (stature((x).lChild) == stature((x).rChild)) && \ ((x).height == (IsRed(&x) ? stature((x).lChild) : stature((x).lChild) + 1)) \ ) // RedBlack 高度更新条件 using namespace std; template <typename T> class RedBlack : public BST<T> { public: void solveDoubleRed(BinNodePosi(T) x); // 双红修正 void solveDoubleBlack(BinNodePosi(T) x); // 双黑修正 int updateHeight(BinNodePosi(T) x); // 更新节点 x 的高度 BinNodePosi(T) insert(const T& e); // 插入(重写) bool remove(const T& e); // 删除(重写) }; /** * 更新红黑树节点(黑)高度 * 因统一定了 stature(NULL) = -1,故 height 比黑高度少一,好在不致影响到各种算法中的比较判断 */ template<typename T> int RedBlack<T>::updateHeight(BinNode<T> *x) { x->height = max(stature(x->lChild), stature(x->rChild)); // 孩子节点一般黑高度相同,除非出现双黑 return IsRed(x) ? x->height : x->height++; } template<typename T> BinNode<T> *RedBlack<T>::insert(const T &e) { BinNodePosi(T)& x = search(e); if(x) return x; x = new BinNode<T>(e, this->_hot, nullptr, nullptr, -1); // 留意 _hot,留意 -1 的使用 solveDoubleRed(x); return x; } template<typename T> void RedBlack<T>::solveDoubleRed(BinNode<T> *x) { if(IsRoot(*x)) { // 递归基,到达根节点则染成黑色,高度上升一层 this->_root->color = RB_BLACK; this->_root->height++; return; } BinNodePosi(T) p = x->parent; if(IsBlack(p)) return; BinNodePosi(T) g = p->parent; BinNodePosi(T) u = uncle(*x); if(IsBlack(u)) { if(IsLChild(*x) == IsLChild(*p)) { p->color = RB_BLACK; } else { // 父子不同侧时 x->color = RB_BLACK; } g->color = RB_RED; // 以上虽保证总共两次染色,但因增加了判断而得不偿失 // 可改进为:在旋转后将根置黑、孩子置红,虽需三次染色但效率更高 BinNodePosi(T) gg = g->parent; BinNodePosi(T) r = FromParentTo(*g) = rotateAt(x); // 旋转,然后让曾祖父连接上旋转后的子树的根节点 r->parent = gg; } else { // 叔叔为红时 // 无论父子同不同侧 p->color = RB_BLACK; p->height++; u->color = RB_BLACK; u->height++; if(!IsRoot(*g)) g->color = RB_RED; solveDoubleRed(g); } } template<typename T> bool RedBlack<T>::remove(const T &e) { BinNodePosi(T)& x = search(e); if(!x) return false; BinNodePosi(T) r = removeAtStatic(x, this->_hot); // r 为取代 x 者 if(--this->_size <= 0) return true; // assert: _hot某一孩子刚被切除,且被r所指节点(可能是NULL)接替。以下检查是否失衡,幵做必要调整 if(!this->_hot) { // 若被删除的节点为根节点,则将其置黑,更新其高度 this->_root->color = RB_BLACK; updateHeight(this->_root); return true; } // assert: 以下,原x(现r)必非根,_hot必非空 if(BlackHeightUpdated(*(this->_hot))) // 若所有祖先的黑高度依然平衡,则无需调整 return true; if(IsRed(r)) { // 若 r 为红,只需将其置黑,并更新其高度 r->color = RB_BLACK; r->height++; return true; } // assert: 以下,原x(现r)均为黑色 solveDoubleBlack(r); return true; } template<typename T> void RedBlack<T>::solveDoubleBlack(BinNode<T> *x) { // todo } #endif //DSA_CPP_DENG_MYREDBLACKTREE_H
[ "makertuwem@outlook.com" ]
makertuwem@outlook.com
4517841c4405d841265b1103c565f5826c20adbf
b268d3851ca046c80cc2e052d8b853f19b59d3fb
/GameEngine/include/qt/QtGui/qtransform.h
436b9eb93a2c3edb0b4e03d0edc5923540888e85
[]
no_license
windless1015/CppGameEngine3D
03419c01baafc2b941649954c1549f155b396172
a26d830b8cd795eb797a3284038a03786ac2dc64
refs/heads/master
2022-03-27T10:15:55.351490
2016-03-16T19:22:55
2016-03-16T19:22:55
473,269,117
1
0
null
2022-03-23T16:24:37
2022-03-23T16:24:36
null
UTF-8
C++
false
false
11,299
h
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QTRANSFORM_H #define QTRANSFORM_H #include <QtGui/qmatrix.h> #include <QtGui/qpainterpath.h> #include <QtGui/qpolygon.h> #include <QtGui/qregion.h> #include <QtGui/qwindowdefs.h> #include <QtCore/qline.h> #include <QtCore/qpoint.h> #include <QtCore/qrect.h> QT_BEGIN_NAMESPACE class QVariant; class Q_GUI_EXPORT QTransform { public: enum TransformationType { TxNone = 0x00, TxTranslate = 0x01, TxScale = 0x02, TxRotate = 0x04, TxShear = 0x08, TxProject = 0x10 }; inline explicit QTransform(Qt::Initialization) : affine(Qt::Uninitialized) {} QTransform(); QTransform(qreal h11, qreal h12, qreal h13, qreal h21, qreal h22, qreal h23, qreal h31, qreal h32, qreal h33 = 1.0); QTransform(qreal h11, qreal h12, qreal h21, qreal h22, qreal dx, qreal dy); explicit QTransform(const QMatrix &mtx); bool isAffine() const; bool isIdentity() const; bool isInvertible() const; bool isScaling() const; bool isRotating() const; bool isTranslating() const; TransformationType type() const; inline qreal determinant() const; qreal det() const; qreal m11() const; qreal m12() const; qreal m13() const; qreal m21() const; qreal m22() const; qreal m23() const; qreal m31() const; qreal m32() const; qreal m33() const; qreal dx() const; qreal dy() const; void setMatrix(qreal m11, qreal m12, qreal m13, qreal m21, qreal m22, qreal m23, qreal m31, qreal m32, qreal m33); QTransform inverted(bool *invertible = 0) const Q_REQUIRED_RESULT; QTransform adjoint() const Q_REQUIRED_RESULT; QTransform transposed() const Q_REQUIRED_RESULT; QTransform &translate(qreal dx, qreal dy); QTransform &scale(qreal sx, qreal sy); QTransform &shear(qreal sh, qreal sv); QTransform &rotate(qreal a, Qt::Axis axis = Qt::ZAxis); QTransform &rotateRadians(qreal a, Qt::Axis axis = Qt::ZAxis); static bool squareToQuad(const QPolygonF &square, QTransform &result); static bool quadToSquare(const QPolygonF &quad, QTransform &result); static bool quadToQuad(const QPolygonF &one, const QPolygonF &two, QTransform &result); bool operator==(const QTransform &) const; bool operator!=(const QTransform &) const; QTransform &operator*=(const QTransform &); QTransform operator*(const QTransform &o) const; QTransform &operator=(const QTransform &); operator QVariant() const; void reset(); QPoint map(const QPoint &p) const; QPointF map(const QPointF &p) const; QLine map(const QLine &l) const; QLineF map(const QLineF &l) const; QPolygonF map(const QPolygonF &a) const; QPolygon map(const QPolygon &a) const; QRegion map(const QRegion &r) const; QPainterPath map(const QPainterPath &p) const; QPolygon mapToPolygon(const QRect &r) const; QRect mapRect(const QRect &) const; QRectF mapRect(const QRectF &) const; void map(int x, int y, int *tx, int *ty) const; void map(qreal x, qreal y, qreal *tx, qreal *ty) const; const QMatrix &toAffine() const; QTransform &operator*=(qreal div); QTransform &operator/=(qreal div); QTransform &operator+=(qreal div); QTransform &operator-=(qreal div); static QTransform fromTranslate(qreal dx, qreal dy); static QTransform fromScale(qreal dx, qreal dy); private: inline QTransform(qreal h11, qreal h12, qreal h13, qreal h21, qreal h22, qreal h23, qreal h31, qreal h32, qreal h33, bool) : affine(h11, h12, h21, h22, h31, h32, true) , m_13(h13), m_23(h23), m_33(h33) , m_type(TxNone) , m_dirty(TxProject) , d(Q_NULLPTR) { } inline QTransform(bool) : affine(true) , m_13(0), m_23(0), m_33(1) , m_type(TxNone) , m_dirty(TxNone) , d(Q_NULLPTR) { } inline TransformationType inline_type() const; QMatrix affine; qreal m_13; qreal m_23; qreal m_33; mutable uint m_type : 5; mutable uint m_dirty : 5; class Private; Private *d; }; Q_DECLARE_TYPEINFO(QTransform, Q_MOVABLE_TYPE); /******* inlines *****/ inline QTransform::TransformationType QTransform::inline_type() const { if (m_dirty == TxNone) return static_cast<TransformationType>(m_type); return type(); } inline bool QTransform::isAffine() const { return inline_type() < TxProject; } inline bool QTransform::isIdentity() const { return inline_type() == TxNone; } inline bool QTransform::isInvertible() const { return !qFuzzyIsNull(determinant()); } inline bool QTransform::isScaling() const { return type() >= TxScale; } inline bool QTransform::isRotating() const { return inline_type() >= TxRotate; } inline bool QTransform::isTranslating() const { return inline_type() >= TxTranslate; } inline qreal QTransform::determinant() const { return affine._m11*(m_33*affine._m22-affine._dy*m_23) - affine._m21*(m_33*affine._m12-affine._dy*m_13)+affine._dx*(m_23*affine._m12-affine._m22*m_13); } inline qreal QTransform::det() const { return determinant(); } inline qreal QTransform::m11() const { return affine._m11; } inline qreal QTransform::m12() const { return affine._m12; } inline qreal QTransform::m13() const { return m_13; } inline qreal QTransform::m21() const { return affine._m21; } inline qreal QTransform::m22() const { return affine._m22; } inline qreal QTransform::m23() const { return m_23; } inline qreal QTransform::m31() const { return affine._dx; } inline qreal QTransform::m32() const { return affine._dy; } inline qreal QTransform::m33() const { return m_33; } inline qreal QTransform::dx() const { return affine._dx; } inline qreal QTransform::dy() const { return affine._dy; } inline QTransform &QTransform::operator*=(qreal num) { if (num == 1.) return *this; affine._m11 *= num; affine._m12 *= num; m_13 *= num; affine._m21 *= num; affine._m22 *= num; m_23 *= num; affine._dx *= num; affine._dy *= num; m_33 *= num; if (m_dirty < TxScale) m_dirty = TxScale; return *this; } inline QTransform &QTransform::operator/=(qreal div) { if (div == 0) return *this; div = 1/div; return operator*=(div); } inline QTransform &QTransform::operator+=(qreal num) { if (num == 0) return *this; affine._m11 += num; affine._m12 += num; m_13 += num; affine._m21 += num; affine._m22 += num; m_23 += num; affine._dx += num; affine._dy += num; m_33 += num; m_dirty = TxProject; return *this; } inline QTransform &QTransform::operator-=(qreal num) { if (num == 0) return *this; affine._m11 -= num; affine._m12 -= num; m_13 -= num; affine._m21 -= num; affine._m22 -= num; m_23 -= num; affine._dx -= num; affine._dy -= num; m_33 -= num; m_dirty = TxProject; return *this; } inline bool qFuzzyCompare(const QTransform& t1, const QTransform& t2) { return qFuzzyCompare(t1.m11(), t2.m11()) && qFuzzyCompare(t1.m12(), t2.m12()) && qFuzzyCompare(t1.m13(), t2.m13()) && qFuzzyCompare(t1.m21(), t2.m21()) && qFuzzyCompare(t1.m22(), t2.m22()) && qFuzzyCompare(t1.m23(), t2.m23()) && qFuzzyCompare(t1.m31(), t2.m31()) && qFuzzyCompare(t1.m32(), t2.m32()) && qFuzzyCompare(t1.m33(), t2.m33()); } /****** stream functions *******************/ #ifndef QT_NO_DATASTREAM Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QTransform &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QTransform &); #endif #ifndef QT_NO_DEBUG_STREAM Q_GUI_EXPORT QDebug operator<<(QDebug, const QTransform &); #endif /****** end stream functions *******************/ // mathematical semantics inline QPoint operator*(const QPoint &p, const QTransform &m) { return m.map(p); } inline QPointF operator*(const QPointF &p, const QTransform &m) { return m.map(p); } inline QLineF operator*(const QLineF &l, const QTransform &m) { return m.map(l); } inline QLine operator*(const QLine &l, const QTransform &m) { return m.map(l); } inline QPolygon operator *(const QPolygon &a, const QTransform &m) { return m.map(a); } inline QPolygonF operator *(const QPolygonF &a, const QTransform &m) { return m.map(a); } inline QRegion operator *(const QRegion &r, const QTransform &m) { return m.map(r); } inline QPainterPath operator *(const QPainterPath &p, const QTransform &m) { return m.map(p); } inline QTransform operator *(const QTransform &a, qreal n) { QTransform t(a); t *= n; return t; } inline QTransform operator /(const QTransform &a, qreal n) { QTransform t(a); t /= n; return t; } inline QTransform operator +(const QTransform &a, qreal n) { QTransform t(a); t += n; return t; } inline QTransform operator -(const QTransform &a, qreal n) { QTransform t(a); t -= n; return t; } QT_END_NAMESPACE #endif // QTRANSFORM_H
[ "benwolverine2019@gmail.com" ]
benwolverine2019@gmail.com
032631b2e0a057a4c9a4e9a877968ba9710b055e
6b6e240ec74db2e9dec35b7fbe3c756c3dbc6340
/Pig Latin/Source.cpp
8a69b1081f21d9866c6199b12cdd4af0c81da07f
[]
no_license
Thestouges/Pig-Latin
c37116a6837b31363187346e515da07d517af7e5
197a4d05c8172d41f3297cd5165332a04e4deef5
refs/heads/master
2021-01-17T20:00:03.358706
2016-07-15T08:40:42
2016-07-15T08:40:42
63,406,077
0
0
null
null
null
null
UTF-8
C++
false
false
324
cpp
#include <iostream> #include <string> using namespace std; void main(){ string input, result = ""; cout<<"Enter word to be converted to pig latin: "; cin>>input; for(int i = 1; i < input.length(); i++){ result += input[i]; } result = result + "-" +input[0] + "ay"; cout<<"Word in pig latin: "<<result<<endl; }
[ "thestouges@gmail.com" ]
thestouges@gmail.com
94d876433d968b73337e0ae9ae49f4bf6ee50f69
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/rsync/gumtree/rsync_old_hunk_712.cpp
06f0000b99c689ae2f3a8504f53488c7ede77c69
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,897
cpp
if (flist->count < 2) return; if (hlink_list) free(hlink_list); if (!(hlink_list = new_array(struct file_struct, flist->count))) out_of_memory("init_hard_links"); for (i = 0; i < flist->count; i++) memcpy(&hlink_list[i], flist->files[i], sizeof(hlink_list[0])); qsort(hlink_list, flist->count, sizeof(hlink_list[0]), (int (*)()) hlink_compare); hlink_count = flist->count; #endif } /* check if a file should be skipped because it is the same as an earlier hard link */ int check_hard_link(struct file_struct *file) { #if SUPPORT_HARD_LINKS int low = 0, high = hlink_count - 1; int ret = 0; if (!hlink_list || !S_ISREG(file->mode)) return 0; while (low != high) { int mid = (low + high) / 2; ret = hlink_compare(&hlink_list[mid], file); if (ret == 0) { low = mid; break; } if (ret > 0) high = mid; else low = mid + 1; } /* XXX: To me this looks kind of dodgy -- why do we use [low] * here and [low-1] below? -- mbp */ if (hlink_compare(&hlink_list[low], file) != 0) return 0; if (low > 0 && S_ISREG(hlink_list[low - 1].mode) && file->dev == hlink_list[low - 1].dev && file->inode == hlink_list[low - 1].inode) { if (verbose >= 2) { rprintf(FINFO, "check_hard_link: \"%s\" is a hard link to file %d, \"%s\"\n", f_name(file), low-1, f_name(&hlink_list[low-1])); } return 1; } #endif return 0; } #if SUPPORT_HARD_LINKS static void hard_link_one(int i) { STRUCT_STAT st1, st2; if (link_stat(f_name(&hlink_list[i - 1]), &st1) != 0) return; if (link_stat(f_name(&hlink_list[i]), &st2) != 0) { if (do_link (f_name(&hlink_list[i - 1]), f_name(&hlink_list[i])) != 0) { if (verbose > 0) rprintf(FINFO, "link %s => %s : %s\n", f_name(&hlink_list[i]), f_name(&hlink_list[i - 1]), strerror(errno)); return; } } else { if (st2.st_dev == st1.st_dev && st2.st_ino == st1.st_ino) return; if (robust_unlink(f_name(&hlink_list[i])) != 0 || do_link(f_name(&hlink_list[i - 1]), f_name(&hlink_list[i])) != 0) { if (verbose > 0) rprintf(FINFO, "link %s => %s : %s\n", f_name(&hlink_list[i]), f_name(&hlink_list[i - 1]), strerror(errno)); return; } } if (verbose > 0) rprintf(FINFO, "%s => %s\n", f_name(&hlink_list[i]), f_name(&hlink_list[i - 1])); } #endif /** * Create any hard links in the global hlink_list. They were put * there by running init_hard_links on the filelist. **/ void do_hard_links(void) { #if SUPPORT_HARD_LINKS int i; if (!hlink_list) return; for (i = 1; i < hlink_count; i++) { if (S_ISREG(hlink_list[i].mode) && S_ISREG(hlink_list[i - 1].mode) && hlink_list[i].basename && hlink_list[i - 1].basename && hlink_list[i].dev == hlink_list[i - 1].dev && hlink_list[i].inode == hlink_list[i - 1].inode) { hard_link_one(i); } } #endif }
[ "993273596@qq.com" ]
993273596@qq.com
b7914c2446680196eb955839ed0e86126bf3a539
42d981b9ac42ad12577865115228b3744aad6e6b
/bachelors/year2/semestre1/HomeTasks/5/List.h
675d371e82cbfe983f9224b3efa371b0b8e45f06
[]
no_license
Witalia008/university_courses
bcd7683ac3abbfb8f5474c0d114ed01cbc15eab6
8bdfb3b5f8ce44680dde530e4eabc28141013bd0
refs/heads/main
2023-04-11T11:16:59.444067
2021-04-01T01:31:02
2021-04-01T01:31:02
350,045,497
0
0
null
null
null
null
UTF-8
C++
false
false
1,705
h
#pragma once #include <ostream> class List { protected: class Node { friend class List; protected: int data; Node *next; public: Node() : data(0), next(nullptr) {} Node(int d) : data(d), next(nullptr) {} Node(int d, Node *nxt) : data(d), next(nxt) {} ~Node() {} }; Node *head, *tail; int sz; public: class iterator { friend class List; private: Node *pos; public: iterator() {}; iterator(Node*a) : pos(a) {} iterator(iterator&a) : pos(a.pos) {} int operator*() { return pos->data; } iterator operator++() { iterator res = *this; if (pos->next) pos = pos->next; return res; } iterator operator++(int) { if (pos->next) pos = pos->next; return *this; } bool operator==(iterator b) { return this->pos == b.pos; } bool operator!=(iterator b) { return !(*this == b); } }; List(); List(const List&); ~List(); int size() { return sz; } void push_back(int data); void pop_back(); void push_front(int data); void pop_front(); void emplace_back(iterator); void emplace_front(iterator); void insert_before(iterator, iterator); void insert_after(iterator, iterator); iterator remove(iterator); int front() throw(); int back() throw(); iterator begin(); iterator end(); iterator last(); }; std::ostream& operator<<(std::ostream& out, List &l);
[ "kojvitalij@gmail.com" ]
kojvitalij@gmail.com
48f22385d737f008dcde14e3f1567508e2b284a2
4aca6e0da325098e72791349bea4dad0d79d3674
/Engine/Source/Engine/TerrainRenderer.h
8dcae63d1ff12e02ba7d7a3a4b427cb7d31ca269
[]
no_license
stenzek/YGameEngine
9e1d42cc01cba1ea40030776df401ec4ed2bc4cb
833e0dceee8f7d87c311624776344dde4ffa1c83
refs/heads/master
2021-08-23T10:10:20.598809
2015-11-05T15:19:37
2015-11-05T15:19:37
110,406,401
3
1
null
null
null
null
UTF-8
C++
false
false
2,535
h
#pragma once #include "Engine/Common.h" #include "Engine/TerrainSection.h" #include "Renderer/RenderProxy.h" class TerrainSectionRendererData; class TerrainSectionRenderProxy; class TerrainRenderer { friend class TerrainManager; public: TerrainRenderer(TERRAIN_RENDERER_TYPE type, const TerrainParameters *pParameters, const TerrainLayerList *pLayerList); virtual ~TerrainRenderer(); // accessors const TERRAIN_RENDERER_TYPE GetType() const { return m_type; } const TerrainParameters *GetTerrainParameters() const { return &m_parameters; } const TerrainLayerList *GetLayerList() const { return m_pLayerList; } // create a render proxy for a section virtual TerrainSectionRenderProxy *CreateSectionRenderProxy(uint32 entityId, const TerrainSection *pSection) = 0; // gpu resources virtual bool CreateGPUResources() = 0; virtual void ReleaseGPUResources() = 0; ////////////////////////////////////////////////////////////////////////// // create renderer static TerrainRenderer *CreateTerrainRenderer(const TerrainParameters *pParameters, const TerrainLayerList *pLayerList); protected: // vars TERRAIN_RENDERER_TYPE m_type; TerrainParameters m_parameters; const TerrainLayerList *m_pLayerList; }; class TerrainSectionRenderProxy : public RenderProxy { public: TerrainSectionRenderProxy(uint32 entityId, const TerrainSection *pSection); virtual ~TerrainSectionRenderProxy(); // section access const TerrainSection *GetSection() const { return m_pSection; } const int32 GetSectionX() const { return m_sectionX; } const int32 GetSectionY() const { return m_sectionY; } // when a layer is added to a section virtual void OnLayersModified() = 0; // when a height value is modified virtual void OnPointHeightModified(uint32 x, uint32 y) = 0; // when a layer weight is modified virtual void OnPointLayersModified(uint32 x, uint32 y) = 0; // we implement the raycasting and intersections in the base class, they are common between all renderer types virtual bool RayCast(const Ray &ray, float3 &contactNormal, float3 &contactPoint, bool exitAtFirstIntersection) const override; virtual uint32 GetIntersectingTriangles(const AABox &searchBox, IntersectingTriangleArray &intersectingTriangles) const override; protected: const TerrainSection *m_pSection; int32 m_sectionX, m_sectionY; }; // keep section in memory //bool IsSectionInVisibleRange(int32 sectionX, int32 sectionY) const;
[ "me" ]
me
334ad0ad4ebdabdaff4d9c16196869ca30cdf080
28cd54d1979c57d3ffdad6d4e75d0a4fe5ce7dbc
/src/StratumServer.cc
f84ea79216dcd3d70eb3e686860f51d390989a9d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
zhao9jack/btcpool
295440f167ceb39a7565e94a7559c1843dbff628
e5923956708a39fefac677569d60815ccccf5ed2
refs/heads/master
2021-01-21T19:35:22.914431
2016-09-06T03:10:27
2016-09-06T03:10:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,561
cc
/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "StratumServer.h" #include "Common.h" #include "Kafka.h" #include "MySQLConnection.h" #include "Utils.h" #include "utilities_js.hpp" //////////////////////////////// SessionIDManager ////////////////////////////// SessionIDManager::SessionIDManager(const uint8_t serverId) : serverId_(serverId), count_(0), allocIdx_(0) { sessionIds_.reset(); } bool SessionIDManager::ifFull() { ScopeLock sl(lock_); return _ifFull(); } bool SessionIDManager::_ifFull() { if (count_ >= (int32_t)(MAX_SESSION_INDEX_SERVER + 1)) { return true; } return false; } bool SessionIDManager::allocSessionId(uint32_t *sessionID) { ScopeLock sl(lock_); if (_ifFull()) return false; // find an empty bit while (sessionIds_.test(allocIdx_) == true) { allocIdx_++; if (allocIdx_ > MAX_SESSION_INDEX_SERVER) { allocIdx_ = 0; } } // set to true sessionIds_.set(allocIdx_, true); count_++; *sessionID = (((uint32_t)serverId_ << 24) | allocIdx_); return true; } void SessionIDManager::freeSessionId(uint32_t sessionId) { ScopeLock sl(lock_); const uint32_t idx = (sessionId & 0x00FFFFFFu); sessionIds_.set(idx, false); count_--; } ////////////////////////////////// JobRepository /////////////////////////////// JobRepository::JobRepository(const char *kafkaBrokers, Server *server): running_(true), kafkaConsumer_(kafkaBrokers, KAFKA_TOPIC_STRATUM_JOB, 0/*patition*/), server_(server), kMaxJobsLifeTime_(300), kMiningNotifyInterval_(30), // TODO: make as config arg lastJobSendTime_(0) { assert(kMiningNotifyInterval_ < kMaxJobsLifeTime_); } JobRepository::~JobRepository() { if (threadConsume_.joinable()) threadConsume_.join(); } shared_ptr<StratumJobEx> JobRepository::getStratumJobEx(const uint64_t jobId) { ScopeLock sl(lock_); auto itr = exJobs_.find(jobId); if (itr != exJobs_.end()) { return itr->second; } return nullptr; } shared_ptr<StratumJobEx> JobRepository::getLatestStratumJobEx() { ScopeLock sl(lock_); if (exJobs_.size()) { return exJobs_.rbegin()->second; } LOG(WARNING) << "getLatestStratumJobEx fail"; return nullptr; } void JobRepository::stop() { if (!running_) { return; } running_ = false; LOG(INFO) << "stop job repository"; } bool JobRepository::setupThreadConsume() { const int32_t kConsumeLatestN = 1; // we need to consume the latest one map<string, string> consumerOptions; consumerOptions["fetch.wait.max.ms"] = "10"; if (kafkaConsumer_.setup(RD_KAFKA_OFFSET_TAIL(kConsumeLatestN), &consumerOptions) == false) { LOG(INFO) << "setup consumer fail"; return false; } if (!kafkaConsumer_.checkAlive()) { LOG(ERROR) << "kafka brokers is not alive"; return false; } threadConsume_ = thread(&JobRepository::runThreadConsume, this); return true; } void JobRepository::runThreadConsume() { LOG(INFO) << "start job repository consume thread"; const int32_t kTimeoutMs = 1000; while (running_) { rd_kafka_message_t *rkmessage; rkmessage = kafkaConsumer_.consumer(kTimeoutMs); // timeout, most of time it's not nullptr and set an error: // rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF if (rkmessage == nullptr) { continue; } // consume stratum job consumeStratumJob(rkmessage); rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ // check if we need to send mining notify checkAndSendMiningNotify(); tryCleanExpiredJobs(); } LOG(INFO) << "stop job repository consume thread"; } void JobRepository::consumeStratumJob(rd_kafka_message_t *rkmessage) { // check error if (rkmessage->err) { if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF) { // Reached the end of the topic+partition queue on the broker. // Not really an error. // LOG(INFO) << "consumer reached end of " << rd_kafka_topic_name(rkmessage->rkt) // << "[" << rkmessage->partition << "] " // << " message queue at offset " << rkmessage->offset; // acturlly return; } LOG(ERROR) << "consume error for topic " << rd_kafka_topic_name(rkmessage->rkt) << "[" << rkmessage->partition << "] offset " << rkmessage->offset << ": " << rd_kafka_message_errstr(rkmessage); if (rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION || rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC) { LOG(FATAL) << "consume fatal"; } return; } StratumJob *sjob = new StratumJob(); bool res = sjob->unserializeFromJson((const char *)rkmessage->payload, rkmessage->len); if (res == false) { LOG(ERROR) << "unserialize stratum job fail"; delete sjob; return; } // make sure the job is not expired. if (jobId2Time(sjob->jobId_) + 60 < time(nullptr)) { LOG(ERROR) << "too large delay from kafka to receive topic 'StratumJob'"; delete sjob; return; } // here you could use Map.find() without lock, it's sure // that everyone is using this Map readonly now if (exJobs_.find(sjob->jobId_) != exJobs_.end()) { LOG(ERROR) << "jobId already existed"; delete sjob; return; } bool isClean = false; if (latestPrevBlockHash_ != sjob->prevHash_) { isClean = true; latestPrevBlockHash_ = sjob->prevHash_; LOG(INFO) << "received new height statum job, height: " << sjob->height_ << ", prevhash: " << sjob->prevHash_.ToString(); } shared_ptr<StratumJobEx> exJob = std::make_shared<StratumJobEx>(sjob, isClean); { ScopeLock sl(lock_); if (isClean) { // mark all jobs as stale, should do this before insert new job for (auto it : exJobs_) { it.second->markStale(); } } // insert new job exJobs_[sjob->jobId_] = exJob; } // if job has clean flag, call server to send job if (isClean) { sendMiningNotify(exJob); return; } // if last job is an empty block job(clean=true), we need to send a // new non-empty job as quick as possible. if (isClean == false && exJobs_.size() >= 2) { auto itr = exJobs_.rbegin(); shared_ptr<StratumJobEx> exJob1 = itr->second; itr++; shared_ptr<StratumJobEx> exJob2 = itr->second; if (exJob2->isClean_ == true && exJob2->sjob_->merkleBranch_.size() == 0 && exJob1->sjob_->merkleBranch_.size() != 0) { sendMiningNotify(exJob); } } } void JobRepository::markAllJobsAsStale() { ScopeLock sl(lock_); for (auto it : exJobs_) { it.second->markStale(); } } void JobRepository::checkAndSendMiningNotify() { // last job is 'expried', send a new one if (exJobs_.size() && lastJobSendTime_ + kMiningNotifyInterval_ <= time(nullptr)) { shared_ptr<StratumJobEx> exJob = exJobs_.rbegin()->second; sendMiningNotify(exJob); } } void JobRepository::sendMiningNotify(shared_ptr<StratumJobEx> exJob) { static uint64_t lastJobId = 0; if (lastJobId == exJob->sjob_->jobId_) { LOG(ERROR) << "no new jobId, ignore to send mining notify"; return; } // send job to all clients server_->sendMiningNotifyToAll(exJob); lastJobSendTime_ = time(nullptr); lastJobId = exJob->sjob_->jobId_; } void JobRepository::tryCleanExpiredJobs() { ScopeLock sl(lock_); const uint32_t nowTs = (uint32_t)time(nullptr); while (exJobs_.size()) { // Maps (and sets) are sorted, so the first element is the smallest, // and the last element is the largest. auto itr = exJobs_.begin(); const time_t jobTime = (time_t)(itr->first >> 32); if (nowTs < jobTime + kMaxJobsLifeTime_) { break; // not expired } // remove expired job exJobs_.erase(itr); LOG(INFO) << "remove expired stratum job, id: " << itr->first << ", time: " << date("%F %T", jobTime); } } //////////////////////////////////// UserInfo ///////////////////////////////// UserInfo::UserInfo(const string &apiUrl, const MysqlConnectInfo &dbInfo): running_(true), apiUrl_(apiUrl), lastMaxUserId_(0), db_(dbInfo) { pthread_rwlock_init(&rwlock_, nullptr); } UserInfo::~UserInfo() { stop(); if (threadUpdate_.joinable()) threadUpdate_.join(); if (threadInsertWorkerName_.joinable()) threadInsertWorkerName_.join(); pthread_rwlock_destroy(&rwlock_); } void UserInfo::stop() { if (!running_) return; running_ = false; } int32_t UserInfo::getUserId(const string userName) { pthread_rwlock_rdlock(&rwlock_); auto itr = nameIds_.find(userName); pthread_rwlock_unlock(&rwlock_); if (itr != nameIds_.end()) { return itr->second; } return 0; // not found } int32_t UserInfo::incrementalUpdateUsers() { // // WARNING: The API is incremental update, we use `?last_id=` to make sure // always get the new data. Make sure you have use `last_id` in API. // const string url = Strings::Format("%s?last_id=%d", apiUrl_.c_str(), lastMaxUserId_); string resp; if (!httpGET(url.c_str(), resp, 10000/* timeout ms */)) { LOG(ERROR) << "http get request user list fail, url: " << url; return -1; } JsonNode r; if (!JsonNode::parse(resp.c_str(), resp.c_str() + resp.length(), r)) { LOG(ERROR) << "decode json fail, json: " << resp; return -1; } if (r["data"].type() == Utilities::JS::type::Undefined) { LOG(ERROR) << "invalid data, should key->value, type: " << (int)r["data"].type(); return -1; } auto vUser = r["data"].children(); if (vUser->size() == 0) { return 0; } pthread_rwlock_wrlock(&rwlock_); for (const auto &itr : *vUser) { const string userName(itr.key_start(), itr.key_end() - itr.key_start()); const int32_t userId = itr.int32(); if (userId > lastMaxUserId_) { lastMaxUserId_ = userId; } nameIds_.insert(std::make_pair(userName, userId)); } pthread_rwlock_unlock(&rwlock_); return vUser->size(); } void UserInfo::runThreadUpdate() { const time_t updateInterval = 10; // seconds time_t lastUpdateTime = time(nullptr); while (running_) { if (lastUpdateTime + updateInterval > time(nullptr)) { usleep(500000); // 500ms continue; } int32_t res = incrementalUpdateUsers(); lastUpdateTime = time(nullptr); if (res > 0) LOG(INFO) << "update users count: " << res; } } bool UserInfo::setupThreads() { // check db available if (!db_.ping()) { LOG(ERROR) << "connect db failure"; return false; } // // get all user list, incremental update model. // // We use `offset` in incrementalUpdateUsers(), will keep update uitl no more // new users. Most of http API have timeout limit, so can't return lots of // data in one request. // while (1) { int32_t res = incrementalUpdateUsers(); if (res == 0) break; if (res == -1) { LOG(ERROR) << "update user list failure"; return false; } LOG(INFO) << "update users count: " << res; } threadUpdate_ = thread(&UserInfo::runThreadUpdate, this); threadInsertWorkerName_ = thread(&UserInfo::runThreadInsertWorkerName, this); return true; } void UserInfo::addWorker(const int32_t userId, const int64_t workerId, const string &workerName, const string &minerAgent) { ScopeLock sl(workerNameLock_); // insert to Q workerNameQ_.push_back(WorkerName()); workerNameQ_.rbegin()->userId_ = userId; workerNameQ_.rbegin()->workerId_ = workerId; // worker name snprintf(workerNameQ_.rbegin()->workerName_, sizeof(workerNameQ_.rbegin()->workerName_), "%s", workerName.c_str()); // miner agent snprintf(workerNameQ_.rbegin()->minerAgent_, sizeof(workerNameQ_.rbegin()->minerAgent_), "%s", minerAgent.c_str()); } void UserInfo::runThreadInsertWorkerName() { while (running_) { if (insertWorkerName() > 0) { continue; } sleep(1); } } int32_t UserInfo::insertWorkerName() { std::deque<WorkerName>::iterator itr = workerNameQ_.end(); { ScopeLock sl(workerNameLock_); if (workerNameQ_.size() == 0) return 0; itr = workerNameQ_.begin(); } if (itr == workerNameQ_.end()) return 0; string sql; char **row = nullptr; MySQLResult res; const string nowStr = date("%F %T"); // find the miner sql = Strings::Format("SELECT `group_id`,`worker_name` FROM `mining_workers` " " WHERE `puid`=%d AND `worker_id`= %" PRId64"", itr->userId_, itr->workerId_); db_.query(sql, res); if (res.numRows() != 0 && (row = res.nextRow()) != nullptr) { const int32_t groupId = atoi(row[0]); // group Id == 0: means the miner's status is 'deleted' // we need to move from 'deleted' group to 'default' group. sql = Strings::Format("UPDATE `mining_workers` SET `group_id`=%d, " " `worker_name`=\"%s\", `miner_agent`=\"%s\", " " `updated_at`=\"%s\" " " WHERE `puid`=%d AND `worker_id`= %" PRId64"", groupId == 0 ? itr->userId_ * -1 : groupId, itr->workerName_, itr->minerAgent_, nowStr.c_str(), itr->userId_, itr->workerId_); db_.execute(sql); } else { // we have to use 'ON DUPLICATE KEY UPDATE', because 'statshttpd' may insert // items to table.mining_workers between we 'select' and 'insert' gap. // 'statshttpd' will always set an empty 'worker_name'. sql = Strings::Format("INSERT INTO `mining_workers`(`puid`,`worker_id`," " `group_id`,`worker_name`,`miner_agent`," " `created_at`,`updated_at`) " " VALUES(%d,%" PRId64",%d,\"%s\",\"%s\",\"%s\",\"%s\")" " ON DUPLICATE KEY UPDATE " " `worker_name`= \"%s\",`miner_agent`=\"%s\",`updated_at`=\"%s\" ", itr->userId_, itr->workerId_, itr->userId_ * -1, // default group id itr->workerName_, itr->minerAgent_, nowStr.c_str(), nowStr.c_str(), itr->workerName_, itr->minerAgent_, nowStr.c_str()); if (db_.execute(sql) == false) { LOG(ERROR) << "insert worker name failure"; return 0; } } { ScopeLock sl(workerNameLock_); workerNameQ_.pop_front(); } return 1; } ////////////////////////////////// StratumJobEx //////////////////////////////// StratumJobEx::StratumJobEx(StratumJob *sjob, bool isClean): state_(0), isClean_(isClean), sjob_(sjob) { assert(sjob != nullptr); makeMiningNotifyStr(); } StratumJobEx::~StratumJobEx() { if (sjob_) { delete sjob_; sjob_ = nullptr; } } void StratumJobEx::makeMiningNotifyStr() { string merkleBranchStr; { // '"'+ 64 + '"' + ',' = 67 bytes merkleBranchStr.reserve(sjob_->merkleBranch_.size() * 67); for (size_t i = 0; i < sjob_->merkleBranch_.size(); i++) { // // do NOT use GetHex() or uint256.ToString(), need to dump the memory // string merklStr; Bin2Hex(sjob_->merkleBranch_[i].begin(), 32, merklStr); merkleBranchStr.append("\"" + merklStr + "\","); } if (merkleBranchStr.length()) { merkleBranchStr.resize(merkleBranchStr.length() - 1); // remove last ',' } } // we don't put jobId here, session will fill with the shortJobId miningNotify1_ = "{\"id\":null,\"method\":\"mining.notify\",\"params\":[\""; miningNotify2_ = Strings::Format("\",\"%s\",\"%s\",\"%s\"" ",[%s]" ",\"%08x\",\"%08x\",\"%08x\",%s" "]}\n", sjob_->prevHashBeStr_.c_str(), sjob_->coinbase1_.c_str(), sjob_->coinbase2_.c_str(), merkleBranchStr.c_str(), sjob_->nVersion_, sjob_->nBits_, sjob_->nTime_, isClean_ ? "true" : "false"); } void StratumJobEx::markStale() { // 0: MINING, 1: STALE state_ = 1; } bool StratumJobEx::isStale() { // 0: MINING, 1: STALE return (state_ == 1); } void StratumJobEx::generateCoinbaseTx(std::vector<char> *coinbaseBin, const uint32_t extraNonce1, const string &extraNonce2Hex) { string coinbaseHex; const string extraNonceStr = Strings::Format("%08x%s", extraNonce1, extraNonce2Hex.c_str()); coinbaseHex.append(sjob_->coinbase1_); coinbaseHex.append(extraNonceStr); coinbaseHex.append(sjob_->coinbase2_); Hex2Bin((const char *)coinbaseHex.c_str(), *coinbaseBin); } void StratumJobEx::generateBlockHeader(CBlockHeader *header, std::vector<char> *coinbaseBin, const uint32_t extraNonce1, const string &extraNonce2Hex, const vector<uint256> &merkleBranch, const uint256 &hashPrevBlock, const uint32_t nBits, const int32_t nVersion, const uint32_t nTime, const uint32_t nonce) { generateCoinbaseTx(coinbaseBin, extraNonce1, extraNonce2Hex); header->hashPrevBlock = hashPrevBlock; header->nVersion = nVersion; header->nBits = nBits; header->nTime = nTime; header->nNonce = nonce; // hashMerkleRoot Hash(coinbaseBin->begin(), coinbaseBin->end(), header->hashMerkleRoot); for (const uint256 & step : merkleBranch) { header->hashMerkleRoot = Hash(header->hashMerkleRoot.begin(), header->hashMerkleRoot.end(), step.begin(), step.end()); } } ////////////////////////////////// StratumServer /////////////////////////////// StratumServer::StratumServer(const char *ip, const unsigned short port, const char *kafkaBrokers, const string &userAPIUrl, const MysqlConnectInfo &poolDBInfo, const uint8_t serverId, bool isEnableSimulator, bool isSubmitInvalidBlock) :running_(true), ip_(ip), port_(port), serverId_(serverId), kafkaBrokers_(kafkaBrokers), userAPIUrl_(userAPIUrl), poolDBInfo_(poolDBInfo), isEnableSimulator_(isEnableSimulator), isSubmitInvalidBlock_(isSubmitInvalidBlock) { } StratumServer::~StratumServer() { } bool StratumServer::init() { if (!server_.setup(ip_.c_str(), port_, kafkaBrokers_.c_str(), userAPIUrl_, poolDBInfo_, serverId_, isEnableSimulator_, isSubmitInvalidBlock_)) { LOG(ERROR) << "fail to setup server"; return false; } return true; } void StratumServer::stop() { if (!running_) { return; } running_ = false; server_.stop(); LOG(INFO) << "stop stratum server"; } void StratumServer::run() { server_.run(); } ///////////////////////////////////// Server /////////////////////////////////// Server::Server(): base_(nullptr), signal_event_(nullptr), listener_(nullptr), kafkaProducerShareLog_(nullptr), kafkaProducerSolvedShare_(nullptr), isEnableSimulator_(false), isSubmitInvalidBlock_(false), kShareAvgSeconds_(10), // TODO: read from cfg jobRepository_(nullptr), userInfo_(nullptr), sessionIDManager_(nullptr) { } Server::~Server() { if (signal_event_ != nullptr) { event_free(signal_event_); } if (listener_ != nullptr) { evconnlistener_free(listener_); } if (base_ != nullptr) { event_base_free(base_); } if (kafkaProducerShareLog_ != nullptr) { delete kafkaProducerShareLog_; } if (kafkaProducerSolvedShare_ != nullptr) { delete kafkaProducerSolvedShare_; } if (jobRepository_ != nullptr) { delete jobRepository_; } if (userInfo_ != nullptr) { delete userInfo_; } if (sessionIDManager_ != nullptr) { delete sessionIDManager_; } } bool Server::setup(const char *ip, const unsigned short port, const char *kafkaBrokers, const string &userAPIUrl, const MysqlConnectInfo &dbInfo, const uint8_t serverId, bool isEnableSimulator, bool isSubmitInvalidBlock) { if (isEnableSimulator) { isEnableSimulator_ = true; LOG(WARNING) << "Simulator is enabled, all share will be accepted"; } if (isSubmitInvalidBlock) { isSubmitInvalidBlock_ = true; LOG(WARNING) << "submit invalid block is enabled, all block will be submited"; } kafkaProducerSolvedShare_ = new KafkaProducer(kafkaBrokers, KAFKA_TOPIC_SOLVED_SHARE, RD_KAFKA_PARTITION_UA); kafkaProducerShareLog_ = new KafkaProducer(kafkaBrokers, KAFKA_TOPIC_SHARE_LOG, RD_KAFKA_PARTITION_UA); // job repository jobRepository_ = new JobRepository(kafkaBrokers, this); if (!jobRepository_->setupThreadConsume()) { return false; } // user info userInfo_ = new UserInfo(userAPIUrl, dbInfo); if (!userInfo_->setupThreads()) { return false; } sessionIDManager_ = new SessionIDManager(serverId); // kafkaProducerShareLog_ { map<string, string> options; // we could delay 'sharelog' in producer // 10000000 * sizeof(Share) ~= 480 MB options["queue.buffering.max.messages"] = "10000000"; // send every second options["queue.buffering.max.ms"] = "1000"; // 10000 * sizeof(Share) ~= 480 KB options["batch.num.messages"] = "10000"; if (!kafkaProducerShareLog_->setup(&options)) { LOG(ERROR) << "kafka kafkaProducerShareLog_ setup failure"; return false; } if (!kafkaProducerShareLog_->checkAlive()) { LOG(ERROR) << "kafka kafkaProducerShareLog_ is NOT alive"; return false; } } // kafkaProducerSolvedShare_ { map<string, string> options; // set to 1 (0 is an illegal value here), deliver msg as soon as possible. options["queue.buffering.max.ms"] = "1"; if (!kafkaProducerSolvedShare_->setup(&options)) { LOG(ERROR) << "kafka kafkaProducerSolvedShare_ setup failure"; return false; } if (!kafkaProducerSolvedShare_->checkAlive()) { LOG(ERROR) << "kafka kafkaProducerSolvedShare_ is NOT alive"; return false; } } base_ = event_base_new(); if(!base_) { LOG(ERROR) << "server: cannot create base"; return false; } memset(&sin_, 0, sizeof(sin_)); sin_.sin_family = AF_INET; sin_.sin_port = htons(port); sin_.sin_addr.s_addr = htonl(INADDR_ANY); if (ip && inet_pton(AF_INET, ip, &sin_.sin_addr) == 0) { LOG(ERROR) << "invalid ip: " << ip; return false; } listener_ = evconnlistener_new_bind(base_, Server::listenerCallback, (void*)this, LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1, (struct sockaddr*)&sin_, sizeof(sin_)); if(!listener_) { LOG(ERROR) << "cannot create listener: " << ip << ":" << port; return false; } return true; } void Server::run() { if(base_ != NULL) { // event_base_loop(base_, EVLOOP_NONBLOCK); event_base_dispatch(base_); } } void Server::stop() { LOG(INFO) << "stop tcp server event loop"; event_base_loopexit(base_, NULL); jobRepository_->stop(); userInfo_->stop(); } void Server::sendMiningNotifyToAll(shared_ptr<StratumJobEx> exJobPtr) { // // http://www.sgi.com/tech/stl/Map.html // // Map has the important property that inserting a new element into a map // does not invalidate iterators that point to existing elements. Erasing // an element from a map also does not invalidate any iterators, except, // of course, for iterators that actually point to the element that is // being erased. // std::map<evutil_socket_t, StratumSession *>::iterator itr = connections_.begin(); while (itr != connections_.end()) { StratumSession *conn = itr->second; // alias if (conn->isDead()) { sessionIDManager_->freeSessionId(conn->getSessionId()); delete conn; itr = connections_.erase(itr); } else { conn->sendMiningNotify(exJobPtr); ++itr; } } } void Server::addConnection(evutil_socket_t fd, StratumSession *connection) { connections_.insert(std::pair<evutil_socket_t, StratumSession *>(fd, connection)); } void Server::removeConnection(evutil_socket_t fd) { auto itr = connections_.find(fd); if (itr == connections_.end()) { return; } // mark to delete itr->second->markAsDead(); } void Server::listenerCallback(struct evconnlistener* listener, evutil_socket_t fd, struct sockaddr *saddr, int socklen, void* data) { Server *server = static_cast<Server *>(data); struct event_base *base = (struct event_base*)server->base_; struct bufferevent *bev; uint32_t sessionID = 0u; // can't alloc session Id if (server->sessionIDManager_->allocSessionId(&sessionID) == false) { close(fd); return; } bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE); if(bev == nullptr) { LOG(ERROR) << "error constructing bufferevent!"; server->stop(); return; } // create stratum session StratumSession* conn = new StratumSession(fd, bev, server, saddr, server->kShareAvgSeconds_, sessionID); // set callback functions bufferevent_setcb(bev, Server::readCallback, nullptr, Server::eventCallback, (void*)conn); // By default, a newly created bufferevent has writing enabled. bufferevent_enable(bev, EV_READ|EV_WRITE); server->addConnection(fd, conn); } void Server::readCallback(struct bufferevent* bev, void *connection) { StratumSession *conn = static_cast<StratumSession *>(connection); conn->readBuf(bufferevent_get_input(bev)); } void Server::eventCallback(struct bufferevent* bev, short events, void *connection) { StratumSession *conn = static_cast<StratumSession *>(connection); Server *server = static_cast<Server *>(conn->server_); // should not be 'BEV_EVENT_CONNECTED' assert((events & BEV_EVENT_CONNECTED) != BEV_EVENT_CONNECTED); if (events & BEV_EVENT_EOF) { LOG(INFO) << "socket closed"; } else if (events & BEV_EVENT_ERROR) { LOG(INFO) << "got an error on the socket: " << evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()); } else if (events & BEV_EVENT_TIMEOUT) { LOG(INFO) << "socket read/write timeout, events: " << events; } else { LOG(ERROR) << "unhandled socket events: " << events; } server->removeConnection(conn->fd_); } int Server::checkShare(const Share &share, const uint32 extraNonce1, const string &extraNonce2Hex, const uint32_t nTime, const uint32_t nonce, const uint256 &jobTarget, const string &workFullName) { shared_ptr<StratumJobEx> exJobPtr = jobRepository_->getStratumJobEx(share.jobId_); if (exJobPtr == nullptr) { return StratumError::JOB_NOT_FOUND; } StratumJob *sjob = exJobPtr->sjob_; if (exJobPtr->isStale()) { return StratumError::JOB_NOT_FOUND; } if (nTime <= sjob->minTime_) { return StratumError::TIME_TOO_OLD; } if (nTime > sjob->nTime_ + 600) { return StratumError::TIME_TOO_NEW; } CBlockHeader header; std::vector<char> coinbaseBin; exJobPtr->generateBlockHeader(&header, &coinbaseBin, extraNonce1, extraNonce2Hex, sjob->merkleBranch_, sjob->prevHash_, sjob->nBits_, sjob->nVersion_, nTime, nonce); uint256 blkHash = header.GetHash(); // // found new block // if (isSubmitInvalidBlock_ == true || blkHash <= sjob->networkTarget_) { // // build found block // FoundBlock foundBlock; foundBlock.jobId_ = share.jobId_; foundBlock.workerId_ = share.workerHashId_; foundBlock.userId_ = share.userId_; foundBlock.height_ = sjob->height_; memcpy(foundBlock.header80_, (const uint8_t *)&header, sizeof(CBlockHeader)); snprintf(foundBlock.workerFullName_, sizeof(foundBlock.workerFullName_), "%s", workFullName.c_str()); // send sendSolvedShare2Kafka(&foundBlock, coinbaseBin); jobRepository_->markAllJobsAsStale(); LOG(INFO) << ">>>> found a new block: " << blkHash.ToString() << ", jobId: " << share.jobId_ << ", userId: " << share.userId_ << ", by: " << workFullName << " <<<<"; } // print out high diff share, 2^10 = 1024 if ((blkHash >> 10) <= sjob->networkTarget_) { LOG(INFO) << "high diff share, blkhash: " << blkHash.ToString() << ", diff: " << TargetToBdiff(blkHash) << ", networkDiff: " << TargetToBdiff(sjob->networkTarget_) << ", by: " << workFullName; } // check share diff if (isEnableSimulator_ == false && blkHash > jobTarget) { return StratumError::LOW_DIFFICULTY; } DLOG(INFO) << "blkHash: " << blkHash.ToString() << ", jobTarget: " << jobTarget.ToString() << ", networkTarget: " << sjob->networkTarget_.ToString(); // reach here means an valid share return StratumError::NO_ERROR; } void Server::sendShare2Kafka(const uint8_t *data, size_t len) { ScopeLock sl(producerShareLogLock_); kafkaProducerShareLog_->produce(data, len); } void Server::sendSolvedShare2Kafka(const FoundBlock *foundBlock, const std::vector<char> &coinbaseBin) { ScopeLock sl(producerSolvedShareLock_); // // solved share message: FoundBlock + coinbase_Tx // string buf; buf.resize(sizeof(FoundBlock) + coinbaseBin.size()); uint8_t *p = (uint8_t *)buf.data(); // FoundBlock memcpy(p, (const uint8_t *)foundBlock, sizeof(FoundBlock)); p += sizeof(FoundBlock); // coinbase TX memcpy(p, coinbaseBin.data(), coinbaseBin.size()); kafkaProducerSolvedShare_->produce(buf.data(), buf.size()); }
[ "zhibiao.pan@bitmain.com" ]
zhibiao.pan@bitmain.com
0282733ed5e76a2be3170aa1ec5c7ed715f9558a
8c8a276be1940eeb076de55813132a91f6e57cd2
/chap4_tools/_4_5.cpp
ffbaed75383dc207f84993853bc1c2849fd57442
[]
no_license
ve2102388688/myBoost
3808dabed5e4193d31db566e93ceba0ab8f2b5ac
b48eafb6693c7364cc23f2550e36680d09c18a0a
refs/heads/master
2023-06-24T19:40:16.813370
2021-07-17T15:13:10
2021-07-17T15:13:10
313,614,844
0
0
null
null
null
null
UTF-8
C++
false
false
230
cpp
#include <iostream> #include <cassert> #include <boost/logic/tribool.hpp> BOOST_TRIBOOL_THIRD_STATE(unknow); int main(int argc, char *argv[]) { boost::tribool tb(); boost::tribool tb2(unknow); assert(unknow(tb2)); }
[ "13666226583@163.com" ]
13666226583@163.com
cf75ae1bb5a57afdd6f310c9915fd81e2d6ae663
19907e496cfaf4d59030ff06a90dc7b14db939fc
/POC/oracle_dapp/node_modules/wrtc/third_party/webrtc/include/chromium/src/chrome/renderer/media/cast_transport_sender_ipc.h
2903d3169b1675c6b8d7c64a77a7d003a6df9da2
[ "BSD-2-Clause" ]
permissive
ATMatrix/demo
c10734441f21e24b89054842871a31fec19158e4
e71a3421c75ccdeac14eafba38f31cf92d0b2354
refs/heads/master
2020-12-02T20:53:29.214857
2017-08-28T05:49:35
2017-08-28T05:49:35
96,223,899
8
4
null
2017-08-28T05:49:36
2017-07-04T13:59:26
JavaScript
UTF-8
C++
false
false
3,823
h
// 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. #ifndef CHROME_RENDERER_MEDIA_CAST_TRANSPORT_SENDER_IPC_H_ #define CHROME_RENDERER_MEDIA_CAST_TRANSPORT_SENDER_IPC_H_ #include <stdint.h> #include <map> #include "base/macros.h" #include "base/thread_task_runner_handle.h" #include "ipc/ipc_channel_proxy.h" #include "media/cast/logging/logging_defines.h" #include "media/cast/net/cast_transport_sender.h" // This implementation of the CastTransportSender interface // communicates with the browser process over IPC and relays // all calls to/from the transport sender to the browser process. // The primary reason for this arrangement is to give the // renderer less direct control over the UDP sockets. class CastTransportSenderIPC : public media::cast::CastTransportSender { public: CastTransportSenderIPC( const net::IPEndPoint& local_end_point, const net::IPEndPoint& remote_end_point, scoped_ptr<base::DictionaryValue> options, const media::cast::PacketReceiverCallback& packet_callback, const media::cast::CastTransportStatusCallback& status_cb, const media::cast::BulkRawEventsCallback& raw_events_cb); ~CastTransportSenderIPC() override; // media::cast::CastTransportSender implementation. void InitializeAudio( const media::cast::CastTransportRtpConfig& config, const media::cast::RtcpCastMessageCallback& cast_message_cb, const media::cast::RtcpRttCallback& rtt_cb) override; void InitializeVideo( const media::cast::CastTransportRtpConfig& config, const media::cast::RtcpCastMessageCallback& cast_message_cb, const media::cast::RtcpRttCallback& rtt_cb) override; void InsertFrame(uint32_t ssrc, const media::cast::EncodedFrame& frame) override; void SendSenderReport( uint32_t ssrc, base::TimeTicks current_time, media::cast::RtpTimeTicks current_time_as_rtp_timestamp) override; void CancelSendingFrames(uint32_t ssrc, const std::vector<uint32_t>& frame_ids) override; void ResendFrameForKickstart(uint32_t ssrc, uint32_t frame_id) override; void AddValidSsrc(uint32_t ssrc) override; void SendRtcpFromRtpReceiver( uint32_t ssrc, uint32_t sender_ssrc, const media::cast::RtcpTimeData& time_data, const media::cast::RtcpCastMessage* cast_message, base::TimeDelta target_delay, const media::cast::ReceiverRtcpEventSubscriber::RtcpEvents* rtcp_events, const media::cast::RtpReceiverStatistics* rtp_receiver_statistics) override; void SetOptions(const base::DictionaryValue& options) final {} void OnNotifyStatusChange( media::cast::CastTransportStatus status); void OnRawEvents(const std::vector<media::cast::PacketEvent>& packet_events, const std::vector<media::cast::FrameEvent>& frame_events); void OnRtt(uint32_t ssrc, base::TimeDelta rtt); void OnRtcpCastMessage(uint32_t ssrc, const media::cast::RtcpCastMessage& cast_message); void OnReceivedPacket(const media::cast::Packet& packet); private: struct ClientCallbacks { ClientCallbacks(); ~ClientCallbacks(); media::cast::RtcpCastMessageCallback cast_message_cb; media::cast::RtcpRttCallback rtt_cb; }; void Send(IPC::Message* message); int32_t channel_id_; media::cast::PacketReceiverCallback packet_callback_; media::cast::CastTransportStatusCallback status_callback_; media::cast::BulkRawEventsCallback raw_events_callback_; typedef std::map<uint32_t, ClientCallbacks> ClientMap; ClientMap clients_; DISALLOW_COPY_AND_ASSIGN(CastTransportSenderIPC); }; #endif // CHROME_RENDERER_MEDIA_CAST_TRANSPORT_SENDER_IPC_H_
[ "steven.jun.liu@qq.com" ]
steven.jun.liu@qq.com
2fa12e139a3acbc10ab23d10c6da8cc7ed7ffdc1
b0bff4d9dec709f49704dcafa00fa70e79580e11
/projects/Phantom/phantom/CustomAllocator.hxx.cpp
c60e01acd0f126842ee7791572b6b5487d009e17
[ "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
lineCode/phantom-1
521470af834ef69437b109d47c5d089ee2c6c481
09bdc3f712aaea3e72259428ed05a3ed7f0bb2c0
refs/heads/master
2023-01-06T22:54:47.100740
2020-03-08T22:57:14
2020-03-08T22:57:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
30
cpp
#include "CustomAllocator.hxx"
[ "vivien.millet@gmail.com" ]
vivien.millet@gmail.com
03c9ed71221254d3e26455ad7e11b308983c7bee
1b6226dc80681a444190c61c9d06836d321380a1
/Source/Improved Camera/skse64/skse64/skse64/NiMaterial.h
fbfafbae5d0b197a250b8e682a211141806a645e
[]
no_license
clayne/improved-camera
bc5443dd40e7a7d562b4fb54bc493b92a7274a80
200ded1c45016518d5007c36350aa64f01c01bc0
refs/heads/main
2023-03-02T21:51:41.020299
2021-02-01T13:54:08
2021-02-01T13:54:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,055
h
// UDP: TODO #pragma once #include "skse64/NiTextures.h" #include "skse64/GameTypes.h" MAKE_NI_POINTER(BSTextureSet); MAKE_NI_POINTER(NiTexture); // 30 class BSShaderMaterial { public: virtual ~BSShaderMaterial(); virtual BSShaderMaterial * Create(void); virtual void Copy(BSShaderMaterial * source); // Must be same type virtual bool Unk_03(void * unk1); virtual SInt32 Unk_04(void * unk1); virtual void * Unk_05(void); virtual UInt32 GetShaderType(void); virtual UInt32 Unk_07(void); // Always seems to be 2 enum { kShaderType_Default = 0, kShaderType_EnvironmentMap, kShaderType_GlowMap, kShaderType_Parallax, kShaderType_FaceGen, kShaderType_FaceGenRGBTint, kShaderType_HairTint, kShaderType_ParallaxOcc, kShaderType_MultiTexLand, kShaderType_LODLand, kShaderType_Unknown1, kShaderType_MultilayerParallax, kShaderType_TreeAnim, kShaderType_Unknown2, kShaderType_MultiIndexTriShapeSnow, kShaderType_LODObjectsHD, kShaderType_Eye, kShaderType_Cloud, kShaderType_LODLandNoise, kShaderType_MultiTexLandLODBlend }; UInt32 unk04; // 08 BSIntrusiveRefCounted? UInt32 unk08; // 0C inited to 0 UInt32 unk10; // 10 inited to 0 UInt32 unk14; // 14 inited to 0 UInt32 unk18; // 18 inited to 0 float unk1C; // 1C inited to 1.0 float unk20; // 20 inited to 1.0 float unk24; // 24 inited to 1.0 float unk28; // 28 inited to 1.0 UInt32 unk2C; // 2C inited to -1 flags? }; // 30 class BSShaderMaterialBase : public BSShaderMaterial { public: virtual ~BSShaderMaterialBase(); virtual void SetTexture(UInt32 index, BSTextureSet * texture, SInt32 unk1); virtual void ReleaseTextures(void); // ReleaseRefs virtual void Unk_0A(UInt8 unk1, UInt8 unk2, UInt8 unk3, UInt8 unk4, UInt8 unk5, UInt32 unk6, UInt32 unk7); // AddRefs virtual void Unk_0B(void * unk1, UInt32 unk2); virtual void * Unk_0C(void * unk1); virtual void * Unk_0D(void * unk1); }; class BSEffectShaderMaterial : public BSShaderMaterialBase { public: virtual ~BSEffectShaderMaterial(); float falloffStartAngle; // 30 float falloffStopAngle; // 34 float falloffStartOpacity; // 38 float falloffStopOpacity; // 3C NiColorA emissiveColor; // 40 NiSourceTexture * unk50; // 50 NiSourceTexture * unk54; // 54 float softFalloffDepth; // 58 float emissiveMultiple; // 5C BSFixedString sourceTexture; // 60 BSFixedString greyscaleTexture; // 64 }; // A0 class BSLightingShaderMaterial : public BSShaderMaterialBase { public: virtual ~BSLightingShaderMaterial(); float unk30; // 30 float unk34; // 34 float unk38; // 38 float unk3C; // 3C float unk40; // 40 float unk44; // 44 NiTexture * texture1; // 48 SInt32 unk50; // 50 UInt32 unk54; // 54 NiTexture * texture2; // 58 NiTexture * texture3; // 60 NiTexture * texture4; // 68 UInt32 unk70; // 70 UInt32 unk74; // 74 BSTextureSetPtr textureSet; // 78 float alpha; // 80 float unk58; // 84 float glossiness; // 88 float specularStrength; // 8C float lightingEffect1; // 90 float lightingEffect2; // 94 UInt64 unk98; // 98 void SetTextureSet(BSTextureSet * textureSet); MEMBER_FN_PREFIX(BSLightingShaderMaterial); DEFINE_MEMBER_FN(CopyFrom, void, 0x012E6310, BSLightingShaderMaterial * other); }; STATIC_ASSERT(sizeof(BSLightingShaderMaterial) == 0xA0); class BSLightingShaderMaterialFacegen : public BSLightingShaderMaterial { public: virtual ~BSLightingShaderMaterialFacegen(); NiTexturePtr renderedTexture; // A0 inited to 0 NiTexturePtr unkA8; // A8 inited to 0 NiTexturePtr unkB0; // B0 inited to 0 }; class BSLightingShaderMaterialFacegenTint : public BSLightingShaderMaterial { public: virtual ~BSLightingShaderMaterialFacegenTint(); NiColor tintColor; // A0 }; class BSLightingShaderMaterialHairTint : public BSLightingShaderMaterial { public: virtual ~BSLightingShaderMaterialHairTint(); NiColor tintColor; // A0 }; typedef BSShaderMaterialBase * (* _CreateShaderMaterial)(UInt32 shaderType); extern RelocAddr<_CreateShaderMaterial> CreateShaderMaterial;
[ "ciathyza@ciathyza.com" ]
ciathyza@ciathyza.com
b5d55a79e48d11183a79cf5bfab36b42d2864c73
227b269b8a21f63d6bd95f5c0ce46ad239fd12e2
/stdafx.h
8d17bfb2d8b47f3dfc6471b39a47f17409570f01
[]
no_license
RENxi00/finalpopol
f350b92c98267f5eb5feb86f9a59a574b015bcac
5b9bfb1507cdc97e82d8af0f7e2a0a9c73eeedd0
refs/heads/master
2021-01-02T20:12:03.817128
2020-02-11T14:42:37
2020-02-11T14:42:37
239,781,053
0
0
null
null
null
null
UTF-8
C++
false
false
2,025
h
#pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // 거의 사용되지 않는 내용을 Windows 헤더에서 제외합니다. // Windows 헤더 파일 #include <windows.h> // C 런타임 헤더 파일입니다. #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include <iostream> using namespace std; #include "commonMacroFunction.h" #include "randomFunction.h" #include "keyManager.h" #include "utils.h" #include "imageManager.h" #include "timeManager.h" #include "effectManager.h" #include "txtData.h" #include "soundManager.h" #include "sceneManager.h" #include "keyAniManager.h" #include "iniDataManager.h" #include "cameraManager.h" #include<unordered_map> #include <math.h> using namespace SEVENTEEN_UTIL; //========================================= // ## 19.10.30 ## - 디파인문 - //========================================= #define WINNAME (LPCTSTR)(TEXT("SevenTeen Class")) #define WINSTARTX 50 #define WINSTARTY 50 #define WINSIZEX 1000 #define WINSIZEY 800 #define WINSTYLE WS_CAPTION | WS_SYSMENU #define RND randomFunction::getSingleton() #define KEYMANAGER keyManager::getSingleton() #define IMAGEMANAGER imageManager::getSingleton() #define TIMEMANAGER timeManager::getSingleton() #define EFFECTMANAGER effectManager::getSingleton() #define TXTDATA txtData::getSingleton() #define SOUNDMANAGER soundManager::getSingleton() #define SCENEMANAGER sceneManager::getSingleton() #define KEYANIMANAGER keyAniManager::getSingleton() #define INIDATAMANAGER iniDataManager::getSingleton() #define CAMERAMANAGER cameraManager::getSingleton() #define SAFE_DELETE(p) {if(p) {delete(p); (p)=NULL;}} #define SAFE_RELEASE(p) {if(p) {(p)->release(); (p) = NULL;}} #define SAFE_DELETE_ARRAY(p) {if(p) { delete[](p); (p) = NULL;}} //========================================== // ## 19.10.31 ## Extern //========================================== extern HINSTANCE _hInstance; extern HWND _hWnd; extern POINT _ptMouse; extern BOOL _leftButtonDown;
[ "renxio3o@gmail.com" ]
renxio3o@gmail.com
7cbb06cb595c6cfb7cfc7061cec2560a1556b1fe
224600a273de419ecd61137481c178c59b9ee406
/cpp/fast-modular-exponentiation/main.cpp
3b601efb4ecad752095fdea21348ef50e784b8f6
[]
no_license
Kartikei-12/algorithm
e2ace4e2803ff846fff866a9b9e8a22ba7cb41f2
672e5c430b133560ee87dd0546cbbc489b4fbca5
refs/heads/master
2020-03-23T19:55:02.240790
2018-08-24T03:48:41
2018-08-24T03:48:41
142,009,882
5
0
null
null
null
null
UTF-8
C++
false
false
170
cpp
#include<iostream> #include"modular-expoent.h" int main() { int a=5, b=3, m=2; std::cout<<"Result of (5^3)%2 = "<<my_namespace::mod_Exp(a, b, m); return 0; }
[ "kartikeimittal@gmail.com" ]
kartikeimittal@gmail.com
10e970a5a9ba3705554ee14453c3cb2ed78acb7c
40e4aae535c2edb73e81b12e32ae80af5ff0d6c7
/ocrmodule.h
07949672cdd2468125a3c890a942d2ca4679d5d3
[]
no_license
piotr-tanski/OCRApplication
92fbc4967ca3f8dd75f7d9c45ce4449b20414fba
47286777c906f5075d5160d7697c30ba58dff96d
refs/heads/master
2021-06-13T17:25:00.640977
2017-04-07T22:54:21
2017-04-07T22:54:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,214
h
#ifndef LEPTONICA_OCRMODULE_H #define LEPTONICA_OCRMODULE_H #include "iocr.h" #include <string> #include <memory> #include <tesseract/baseapi.h> struct Pix; // Forward declaration class LeptonicaOCRModule : public IOCR { public: explicit LeptonicaOCRModule(const std::string& lang); LeptonicaOCRModule(const LeptonicaOCRModule& oth); LeptonicaOCRModule(LeptonicaOCRModule&& oth) = default; LeptonicaOCRModule& operator=(const LeptonicaOCRModule& oth); LeptonicaOCRModule& operator=(LeptonicaOCRModule&& oth) = default; ~LeptonicaOCRModule() override; void changeLanguage(const std::string& lang) override; const std::string processImage(const std::string& filepath, const Config* config) const override; private: std::string m_language; std::unique_ptr<tesseract::TessBaseAPI> m_ocrApi; void initOcrApi(const std::string& lang); void deinitOcrApi(); Pix* preprocessImage(Pix* originalImage, const Config* config) const; }; constexpr char ConfigTileSize[] = "TileSize"; constexpr char ConfigForegroundThreshold[] = "FgThreshold"; constexpr char ConfigBackgroundThreshold[] = "BgThreshold"; constexpr char ConfigKernel[] = "Kernel"; #endif // OCRMODULE_H
[ "tanski.piotr@gmail.com" ]
tanski.piotr@gmail.com
c5f582f32cd2ae75385795b6ddf3e888732e31e4
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_old_hunk_1402.cpp
c1a945f38e2c96189298885f717e1f1657278362
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,206
cpp
SHORTPAIR(hostlen), SHORTPAIR(hostlen), SHORTPAIR(hostoff), 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0); /* size is now 64 */ size=64; ntlmbuf[62]=ntlmbuf[63]=0; memcpy(&ntlmbuf[size], domain, domlen); size += domlen; memcpy(&ntlmbuf[size], user, userlen); size += userlen; /* we append the binary hashes to the end of the blob */ if(size < ((int)sizeof(ntlmbuf) - 0x18)) { memcpy(&ntlmbuf[size], lmresp, 0x18); size += 0x18; } #ifdef USE_NTRESPONSES if(size < ((int)sizeof(ntlmbuf) - 0x18)) { memcpy(&ntlmbuf[size], ntresp, 0x18); size += 0x18; } #endif ntlmbuf[56] = (unsigned char)(size & 0xff); ntlmbuf[57] = (unsigned char)(size >> 8); /* convert the binary blob into base64 */ size = Curl_base64_encode((char *)ntlmbuf, size, &base64); if(size >0 ) { Curl_safefree(*allocuserpwd); *allocuserpwd = aprintf("%sAuthorization: NTLM %s\r\n", proxy?"Proxy-":"", base64); free(base64); } else
[ "993273596@qq.com" ]
993273596@qq.com
257459b23aa9b74a5ef1916a1753e6067e566892
31d184a4811aa5d79296703f7ffdf1666018aaab
/timing/main.cpp
3906dec5130576860cd40e6b597e05b94dd74108
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
skyformat99/ygg
3881e9809ba06311ddf012f5dbd1deda73e5ccfb
7bda9e887f7e5dfda0c8dc346db7608674557f2f
refs/heads/master
2021-01-01T04:43:13.292218
2017-07-13T10:52:54
2017-07-13T10:52:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
76
cpp
#include "benchmarker.hpp" int main() { Benchmarker b; b.run_all(); }
[ "lukas.barth@kit.edu" ]
lukas.barth@kit.edu
84f8a9dd2f07d51d88da50a7849cde73736d4aa2
b9c61c27a363ac866ac2d9d6a085e7e2db29f5db
/src/Utils/Python/ElementTypesPython.cpp
d94d51cdbc5f8ee2a83abbd4f8bfffd8dfb6e3b5
[ "BSD-3-Clause" ]
permissive
ehermes/utilities
e2d6eb8221e0a992701cc42bd719cb9f4d12e372
052452fcc3a4f7cc81740086d837c5d03652c030
refs/heads/master
2020-06-04T10:20:30.232921
2019-06-12T12:36:36
2019-06-12T12:36:36
191,976,830
0
0
BSD-3-Clause
2019-06-14T16:44:19
2019-06-14T16:44:19
null
UTF-8
C++
false
false
4,625
cpp
/** * @file * @copyright This code is licensed under the 3-clause BSD license.\n * Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n * See LICENSE.txt for details. */ #include <Utils/Geometry/ElementInfo.h> #include <Utils/Geometry/ElementTypes.h> #include <pybind11/pybind11.h> using namespace Scine::Utils; void init_element_type(pybind11::module& m) { pybind11::enum_<ElementType> element_type(m, "ElementType", pybind11::arithmetic(), "Element type enum"); element_type.value("none", ElementType::none) .value("H", ElementType::H) .value("He", ElementType::He) .value("Li", ElementType::Li) .value("Be", ElementType::Be) .value("B", ElementType::B) .value("C", ElementType::C) .value("N", ElementType::N) .value("O", ElementType::O) .value("F", ElementType::F) .value("Ne", ElementType::Ne) .value("Na", ElementType::Na) .value("Mg", ElementType::Mg) .value("Al", ElementType::Al) .value("Si", ElementType::Si) .value("P", ElementType::P) .value("S", ElementType::S) .value("Cl", ElementType::Cl) .value("Ar", ElementType::Ar) .value("K", ElementType::K) .value("Ca", ElementType::Ca) .value("Sc", ElementType::Sc) .value("Ti", ElementType::Ti) .value("V", ElementType::V) .value("Cr", ElementType::Cr) .value("Mn", ElementType::Mn) .value("Fe", ElementType::Fe) .value("Co", ElementType::Co) .value("Ni", ElementType::Ni) .value("Cu", ElementType::Cu) .value("Zn", ElementType::Zn) .value("Ga", ElementType::Ga) .value("Ge", ElementType::Ge) .value("As", ElementType::As) .value("Se", ElementType::Se) .value("Br", ElementType::Br) .value("Kr", ElementType::Kr) .value("Rb", ElementType::Rb) .value("Sr", ElementType::Sr) .value("Y", ElementType::Y) .value("Zr", ElementType::Zr) .value("Nb", ElementType::Nb) .value("Mo", ElementType::Mo) .value("Tc", ElementType::Tc) .value("Ru", ElementType::Ru) .value("Rh", ElementType::Rh) .value("Pd", ElementType::Pd) .value("Ag", ElementType::Ag) .value("Cd", ElementType::Cd) .value("In", ElementType::In) .value("Sn", ElementType::Sn) .value("Sb", ElementType::Sb) .value("Te", ElementType::Te) .value("I", ElementType::I) .value("Xe", ElementType::Xe) .value("Cs", ElementType::Cs) .value("Ba", ElementType::Ba) .value("La", ElementType::La) .value("Ce", ElementType::Ce) .value("Pr", ElementType::Pr) .value("Nd", ElementType::Nd) .value("Pm", ElementType::Pm) .value("Sm", ElementType::Sm) .value("Eu", ElementType::Eu) .value("Gd", ElementType::Gd) .value("Tb", ElementType::Tb) .value("Dy", ElementType::Dy) .value("Ho", ElementType::Ho) .value("Er", ElementType::Er) .value("Tm", ElementType::Tm) .value("Yb", ElementType::Yb) .value("Lu", ElementType::Lu) .value("Hf", ElementType::Hf) .value("Ta", ElementType::Ta) .value("W", ElementType::W) .value("Re", ElementType::Re) .value("Os", ElementType::Os) .value("Ir", ElementType::Ir) .value("Pt", ElementType::Pt) .value("Au", ElementType::Au) .value("Hg", ElementType::Hg) .value("Tl", ElementType::Tl) .value("Pb", ElementType::Pb) .value("Bi", ElementType::Bi) .value("Po", ElementType::Po) .value("At", ElementType::At) .value("Rn", ElementType::Rn) .value("Fr", ElementType::Fr) .value("Ra", ElementType::Ra) .value("Ac", ElementType::Ac) .value("Th", ElementType::Th) .value("Pa", ElementType::Pa) .value("U", ElementType::U) .value("Np", ElementType::Np) .value("Pu", ElementType::Pu) .value("Am", ElementType::Am) .value("Cm", ElementType::Cm) .value("Bk", ElementType::Bk) .value("Cf", ElementType::Cf) .value("Es", ElementType::Es) .value("Fm", ElementType::Fm) .value("Md", ElementType::Md) .value("No", ElementType::No) .value("Lr", ElementType::Lr) .value("Rf", ElementType::Rf) .value("Db", ElementType::Db) .value("Sg", ElementType::Sg) .value("Bh", ElementType::Bh) .value("Hs", ElementType::Hs) .value("Mt", ElementType::Mt) .value("Ds", ElementType::Ds) .value("Rg", ElementType::Rg) .value("Cn", ElementType::Cn); element_type.def("__str__", &ElementInfo::symbol); }
[ "scine@phys.chem.ethz.ch" ]
scine@phys.chem.ethz.ch