blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
69023b9f0e39a8f55f0eed1f53aa2333879bcd81
|
8a08cac7c5a5aeee935143cfec0723f5e0d2f11a
|
/01.项目源码/ColorMail客户端/EasyMail/addfriend.cpp
|
b2cb63a144194c36d4fae92f03f92027ab598db8
|
[] |
no_license
|
woyaonidsh/easymail
|
94dc83a78a6a4046aa76ea6ea489c16d46820da0
|
39cd68a4e2496d07ee8240cc47235efc780954e3
|
refs/heads/main
| 2023-06-30T20:21:16.665761
| 2021-08-03T13:31:11
| 2021-08-03T13:31:11
| 392,251,501
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,608
|
cpp
|
addfriend.cpp
|
#include "addfriend.h"
#include "ui_addfriend.h"
#include <QJsonArray>
#include <QJsonDocument>
addfriend::addfriend(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::addfriend)
{
QString ID = "";
QString n_name = "";
ui->setupUi(this);
ui->label_notice->setText(NULL); //初始通知消息为空
this->setWindowTitle("AddPeople");
showtime(); //显示时间
}
addfriend::~addfriend()
{
ui->label_notice->clear();
delete tcpClient;
delete ui;
}
void addfriend::timerUpdate(void) //更新时间
{
QDateTime time = QDateTime::currentDateTime();
QString timestr = time.toString("yyyy-MM-dd hh:mm:ss dddd");
currentTimeLabel->setText(timestr);
}
void addfriend::showtime(void)
{
currentTimeLabel = new QLabel;
ui->statusbar->addWidget(currentTimeLabel);
QTimer *timer = new QTimer(this);
timer->start(1000);
connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdate()));
}
void addfriend::on_pushButton_clicked()
{
tcpClient = new QTcpSocket(this);
tcpClient->abort();
tcpClient->connectToHost("192.168.43.188", 6666); //连接服务器
QString ID = ui->lineEdit->text();
QString n_name = ui->lineEdit_2->text();
if( ID==NULL )
{
ui->label_notice->setText("无效操作");
return;
}
QJsonArray add_array;
add_array.append(2);
add_array.append(name);
add_array.append(ID);
add_array.append(n_name);
QJsonDocument add_doc;
add_doc.setArray(add_array);
QByteArray add_byte = add_doc.toJson(QJsonDocument::Compact);
tcpClient->write(add_byte);
connect(tcpClient, SIGNAL(readyRead()), this, SLOT(add_GetTorF()));
}
void addfriend::add_GetTorF()
{
QByteArray add_qba = tcpClient->readAll();
QJsonParseError json_error;
QJsonDocument add_getdoc(QJsonDocument::fromJson(add_qba, &json_error));
if(json_error.error != QJsonParseError::NoError)
{
return;
}
QJsonArray ar_add = add_getdoc.array();
int add_flag = ar_add[0].toInt();
if(add_flag == 0)//添加成功之后显示
{
ui->label_notice->setText("添加成功!");
QString userID = ui->lineEdit->text();
QString username = ui->lineEdit_2->text();
emit successaddfriend(userID , username); //向email发送用户信息
}
else if(add_flag == 1)//添加不成功显示
{
ui->label_notice->setText("已添加该用户!");
}
else
{
ui->label_notice->setText("用户不存在!");
}
}
void addfriend::receivename(QString data) //接受用户名
{
name = data;
}
|
a67a88f212d702cc0085f9355c717e9b23c683ec
|
e9ae978ec137a107ec0535b943807e8a35b15d3f
|
/petr_and_calendar.cpp
|
a894e9ba23a9ddcd87ee4002680656400e99a800
|
[] |
no_license
|
jeremylao/solved_coding_challenges
|
83db66b6f6d414f29510013690fa8ba3fee36db2
|
49706e9e0ff2e3b73fe0f4ce0ed4e1745b888a0c
|
refs/heads/master
| 2021-01-11T20:24:18.719662
| 2017-03-04T14:07:56
| 2017-03-04T14:07:56
| 79,110,352
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 879
|
cpp
|
petr_and_calendar.cpp
|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int input_month, input_day;
int output;
cin >> input_month;
cin >> input_day;
if(input_month == 1 || input_month == 3 || input_month ==5 || input_month == 7|| input_month ==8 || input_month ==10 || input_month == 12){
if(input_day<=5){
output = 5;
}
else {
output = 6;
}
}
else if(input_month == 4 || input_month == 6 || input_month == 9 || input_month == 11){
if(input_day <= 6){
output = 5;
}
else{
output = 6;
}
}
else{
if(input_day >1){
output = 5;
}
else{
output = 4;
}
}
cout << output <<endl;
return 0;
}
// 5 6 7
// 8 9 10 11 12 13 14
// 15 16 17 18 19 20 21
// 22 23 24 25 26 27 28
// 29 30 31 32 33 34 35
|
f00b2f5ddccc2949f1d10322d4a8e226bdf8ec1a
|
0508304aeb1d50db67a090eecb7436b13f06583d
|
/nemo/headers/private/print/libprint/Halftone.h
|
f5837cb4eb27966e6c0cd39b2ad95a3ebaf82b86
|
[] |
no_license
|
BackupTheBerlios/nemo
|
229a7c64901162cf8359f7ddb3a7dd4d05763196
|
1511021681e9efd91e394191bb00313f0112c628
|
refs/heads/master
| 2016-08-03T16:33:46.947041
| 2004-04-28T01:51:58
| 2004-04-28T01:51:58
| 40,045,282
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,055
|
h
|
Halftone.h
|
/*
* HalftoneEngine.h
* Copyright 1999-2000 Y.Takagi. All Rights Reserved.
*/
#ifndef __HALFTONE_H
#define __HALFTONE_H
#include <GraphicsDefs.h>
struct CACHE_FOR_CMAP8 {
uint density;
bool hit;
};
class Halftone;
typedef int (Halftone::*PFN_dither)(uchar *dst, const uchar *src, int x, int y, int width);
typedef uint (*PFN_gray)(rgb_color c);
class Halftone {
public:
enum DITHERTYPE {
TYPE1,
TYPE2,
TYPE3
};
Halftone(color_space cs, double gamma = 1.4, DITHERTYPE dither_type = TYPE3);
~Halftone();
int dither(uchar *dst, const uchar *src, int x, int y, int width);
int getPixelDepth() const;
const rgb_color *getPalette() const;
const uchar *getPattern() const;
void setPattern(const uchar *pattern);
PFN_gray getGrayFunction() const;
void setGrayFunction(PFN_gray gray);
protected:
void createGammaTable(double gamma);
void initElements(int x, int y, uchar *elements);
int ditherGRAY1(uchar *dst, const uchar *src, int x, int y, int width);
int ditherGRAY8(uchar *dst, const uchar *src, int x, int y, int width);
int ditherCMAP8(uchar *dst, const uchar *src, int x, int y, int width);
int ditherRGB32(uchar *dst, const uchar *src, int x, int y, int width);
Halftone(const Halftone &);
Halftone &operator = (const Halftone &);
private:
PFN_dither __dither;
PFN_gray __gray;
int __pixel_depth;
const rgb_color *__palette;
const uchar *__pattern;
uint __gamma_table[256];
CACHE_FOR_CMAP8 __cache_table[256];
};
inline int Halftone::getPixelDepth() const
{
return __pixel_depth;
}
inline const rgb_color *Halftone::getPalette() const
{
return __palette;
}
inline const uchar * Halftone::getPattern() const
{
return __pattern;
}
inline void Halftone::setPattern(const uchar *pattern)
{
__pattern = pattern;
}
inline PFN_gray Halftone::getGrayFunction() const
{
return __gray;
}
inline void Halftone::setGrayFunction(PFN_gray gray)
{
__gray = gray;
}
#endif /* __HALFTONE_H */
|
678bdef7ff9b4eebcd561abc92b706016ea453d5
|
11dea9abaa6bb074ab652845f8fadb15a724a61a
|
/server/src/Main.cpp
|
8900267dd3fe3c8db130eab517149e8d7b82bef2
|
[] |
no_license
|
elvisdukaj/Triangulum-III
|
984dd640a8b032d44a98aec3ed14cf5df1387c85
|
1b171afbcb2821597f833da3810993eaee2f621d
|
refs/heads/master
| 2021-06-19T12:47:30.887167
| 2017-07-08T20:33:15
| 2017-07-08T20:33:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 218
|
cpp
|
Main.cpp
|
#include "triangulum/Game.h"
int main(int argc, char* argv[])
{
triangulum::Game g;
std::cout << "Triangulum III server (v. " << g.m_version << ") started" << std::endl;
g.init();
g.run();
return 0;
}
|
a9c99ad914666f355f361a2585a2c5b6e0c39f10
|
24c21816659a07f9b380ee1937ed908ea04eed00
|
/simulator/calculate.h
|
96a19427559464a00f702f95dac3e6d9c6cd5547
|
[] |
no_license
|
yj490732088/simulator_vpx_qt
|
2032038f2bd93e69b823fb4be0b4632651680c44
|
3801fb13fcd5f9e42628e3157f3c6692fd0e8f59
|
refs/heads/master
| 2021-05-31T11:19:31.068145
| 2016-04-21T11:07:29
| 2016-04-21T11:07:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 129
|
h
|
calculate.h
|
#ifndef CALCULATE_H
#define CALCULATE_H
class calculate
{
public:
calculate();
~calculate();
};
#endif // CALCULATE_H
|
1ebe0a0f1bd8041ff8102109560477d0d889c465
|
c44928026e7f9a3b4a694ab96936bfb2de53daae
|
/Graph.h
|
df0624d78c36fd485d8ec499f41e48b1c8dc7e98
|
[] |
no_license
|
bdkamenov/DSA_Project_Graph_Store
|
85894f7985d502f9ecdc88d4c094a521e4c3d3b8
|
e0be3bbb015912fa578f8c1b6917c4470d2addc8
|
refs/heads/master
| 2021-01-24T00:43:43.714600
| 2018-02-24T20:48:57
| 2018-02-24T20:48:57
| 122,777,605
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,841
|
h
|
Graph.h
|
#ifndef GRAPH_H
#define GRAPH_H
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <vector>
#include <queue>
#include <string>
#include <climits>
#include <functional>
struct algorithms_node_info
{
std::string parent;
int distance;
bool visited;
};
class Graph
{
enum Error
{
NODE_EXIST,
NODE_DOESNT_EXIST,
EDGE_EXIST,
EDGE_DOESNT_EXIST,
PATH_DOESNT_EXIST
};
struct Edge
{
std::string id;
int weigth;
Edge(const std::string& id = "", int weigth = 1) :id(id), weigth(weigth) {}
bool operator>(const Edge& rhs) const
{
return weigth > rhs.weigth;
}
friend std::ostream& operator<<(std::ostream& out, const Edge& elem)
{
out << "( " << elem.id << " " << elem.weigth << " )";
return out;
}
friend std::istream& operator>>(std::istream& in, Edge& elem)
{
char br;
in >> br;
in >> elem.id;
in >> elem.weigth >> br;
return in;
}
};
public:
Graph(bool = true);
void addNode(const std::string&);
void addEdge(const std::string&, const std::string&, int = 1);
void removeNode(const std::string&);
void removeEdge(const std::string&, const std::string&);
void print(std::ostream&) const;
void save(std::ofstream&) const;
void load(std::ifstream&);
/// A L G O R I T H M S
void BFS(const std::string&, const std::string&);
void dijkstra(const std::string&, const std::string&);
private:
void logError(const Error, std::ostream& = std::cerr) const;
void addEdge_h(const std::string&, const std::string&, int);
void removeEdge_h(const std::string&, const std::string&);
const char* NO_PARENT = "?";
const int MY_INFINITY = INT_MAX;
private:
std::unordered_map<std::string, std::vector<Edge>> graph;
bool isDirected;
};
#endif // !GRAPH_H
|
425edf3671e423c811ab2f36a1129ff93d0c54ad
|
6583f95ad8b6d0ca0ba5bff7663e957a07dba367
|
/include/ds18b20/commands/copy_scratchpad.hpp
|
85ad3c7f4f9bb16bfd0e5d924ee5c0511d1bbba6
|
[
"MIT"
] |
permissive
|
ricardocosme/ds18b20
|
54e11d0af6b334bd215fe707a95128834a88b152
|
c8b400da2625706e6592e858635dace86a64df90
|
refs/heads/master
| 2023-04-04T13:15:42.777691
| 2021-04-06T22:40:08
| 2021-04-06T22:40:08
| 304,535,274
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 259
|
hpp
|
copy_scratchpad.hpp
|
#pragma once
#include "ds18b20/onewire/write.hpp"
namespace ds18b20 { namespace commands {
template<bool InternalPullup, typename Pin>
inline void copy_scratchpad(Pin pin) noexcept {
onewire::write<InternalPullup>(pin, 0x48 /*Copy Scratchpad*/);
}
}}
|
6558f96c7abec909c956ccb8e2b08931c61dcf13
|
9401eaffc1830a2e239d6b9aee1e36a9e7470f03
|
/CodeBase/Generic/BaseObjects/SubSystems/Auto/Team271_Auto.hpp
|
b0be262c232d36dabce61ae1fe37a975f94bcb69
|
[] |
no_license
|
Team271/2019Season
|
f552f92f830ce04ec7ec432ea79a75e82a08b2e1
|
acaad0ba0520da9e0e463c9e06ee3df456519957
|
refs/heads/master
| 2020-12-04T10:41:04.246017
| 2020-01-04T08:37:38
| 2020-01-04T08:37:38
| 231,732,146
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,974
|
hpp
|
Team271_Auto.hpp
|
/*
* FRC Team 271's 2019 Comp Season Code
* Copyright (C) 2019 FRC Team 271
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef TEAM271_AUTO_H_
#define TEAM271_AUTO_H_
#if defined(T271_AUTO_ENABLE)
#define AUTO_MAX_MODES ( 10 )
void Team271_Auto0( void );
void Team271_Auto1( void );
void Team271_Auto2( void );
void Team271_Auto3( void );
void Team271_Auto4( void );
void Team271_Auto5( void );
void Team271_Auto6( void );
void Team271_Auto7( void );
void Team271_Auto8( void );
void Team271_Auto9( void );
void Team271_Auto10( void );
/*
*
* Shared Network Data
*
*/
typedef struct
{
uint8_t Mode_ = 0;
uint8_t Delay_ = 0;
}Team271AutoData;
class Team271Auto : public Team271Base
{
public:
Team271AutoData SharedAutoData_;
private:
Team271AutoMode _AutoModes[AUTO_MAX_MODES];
public:
Team271Auto( void );
/*
*
* Robot
*
*/
void RobotInit( const bool argIsParent = false ) override;
/*
*
* Autonomous
*
*/
void AutonomousInit( const bool argIsParent = false ) override;
void AutonomousPeriodic( const bool argIsParent = false ) override;
/*
*
* Auto
*
*/
void CreateAuto( void );
Team271AutoMode* GetAutoMode( const uint32_t argAutoMode );
uint32_t IsLeft( void ) const;
};
#endif
#endif /* TEAM271_AUTO_H_ */
|
ac2297e4f822544d0f22b04660b8f7329f88f34f
|
ad5b72656f0da99443003984c1e646cb6b3e67ea
|
/src/tests/functional/plugin/myriad/shared_tests_instances/behavior/ov_plugin/caching_tests.cpp
|
4b49dc9f6ac2bfe463fb78b9d220b2a8ca59253a
|
[
"Apache-2.0"
] |
permissive
|
novakale/openvino
|
9dfc89f2bc7ee0c9b4d899b4086d262f9205c4ae
|
544c1acd2be086c35e9f84a7b4359439515a0892
|
refs/heads/master
| 2022-12-31T08:04:48.124183
| 2022-12-16T09:05:34
| 2022-12-16T09:05:34
| 569,671,261
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,162
|
cpp
|
caching_tests.cpp
|
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "behavior/ov_plugin/caching_tests.hpp"
using namespace ov::test::behavior;
namespace {
static const std::vector<ngraph::element::Type> nightly_precisionsMyriad = {
ngraph::element::f32,
ngraph::element::f16,
ngraph::element::i32,
ngraph::element::i8,
ngraph::element::u8,
};
static const std::vector<ngraph::element::Type> smoke_precisionsMyriad = {
ngraph::element::f32,
};
static const std::vector<std::size_t> batchSizesMyriad = {
1, 2
};
static std::vector<ovModelWithName> smoke_functions() {
auto funcs = CompileModelCacheTestBase::getStandardFunctions();
if (funcs.size() > 1) {
funcs.erase(funcs.begin() + 1, funcs.end());
}
return funcs;
}
INSTANTIATE_TEST_SUITE_P(smoke_CachingSupportCase_Myriad, CompileModelCacheTestBase,
::testing::Combine(
::testing::ValuesIn(smoke_functions()),
::testing::ValuesIn(smoke_precisionsMyriad),
::testing::ValuesIn(batchSizesMyriad),
::testing::Values(CommonTestUtils::DEVICE_MYRIAD),
::testing::Values(ov::AnyMap{})),
CompileModelCacheTestBase::getTestCaseName);
INSTANTIATE_TEST_SUITE_P(nightly_CachingSupportCase_Myriad, CompileModelCacheTestBase,
::testing::Combine(
::testing::ValuesIn(CompileModelCacheTestBase::getStandardFunctions()),
::testing::ValuesIn(nightly_precisionsMyriad),
::testing::ValuesIn(batchSizesMyriad),
::testing::Values(CommonTestUtils::DEVICE_MYRIAD),
::testing::Values(ov::AnyMap{})),
CompileModelCacheTestBase::getTestCaseName);
} // namespace
|
db033f788d9eefa4e64a4c82697380593193fc8c
|
a13e7993275058dceae188f2101ad0750501b704
|
/2021/937. Reorder Data in Log Files.cpp
|
e140f291c224a33749a09132a852f919aef1c12b
|
[] |
no_license
|
yangjufo/LeetCode
|
f8cf8d76e5f1e78cbc053707af8bf4df7a5d1940
|
15a4ab7ce0b92b0a774ddae0841a57974450eb79
|
refs/heads/master
| 2023-09-01T01:52:49.036101
| 2023-08-31T00:23:19
| 2023-08-31T00:23:19
| 126,698,393
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,325
|
cpp
|
937. Reorder Data in Log Files.cpp
|
class Solution {
public:
vector<string> reorderLogFiles(vector<string>& logs) {
vector<string> ans(logs.size(), "");
int start = 0;
int end = logs.size() - 1;
for (int i = logs.size() - 1; i >= 0; i--) {
if (isDigitLog(logs[i])) {
ans[end] = logs[i];
end--;
} else {
ans[start] = logs[i];
start++;
}
}
sort(ans.begin(), ans.begin() + start, [](string& left, string& right) {
bool ans = false;
int i = 0, j = 0;
while (left[i] != ' ') i++;
while (right[j] != ' ') j++;
while (i < left.length() && j < right.length()) {
if (left[i] != right[j]) {
ans = left[i] < right[j];
break;
}
i++;
j++;
}
if (i == left.length() || j == right.length())
ans = left.length() < right.length();
return ans;
});
return ans;
}
bool isDigitLog(string& log) {
int i = 0;
while (log[i] != ' ') {
i++;
}
return log[i + 1] >= '0' && log[i + 1] <= '9';
}
};
|
88bd58c5b1e157481bb62a25e1b338f719e03bb4
|
ec915bf2f3fc0f9b05ff7e9f7b13d39fce78c7be
|
/helper_tests.cc
|
a7c7cc46a236ddaa9472b76597b987fc64b8d2bc
|
[] |
no_license
|
cmstas/SSAnalysis
|
ed85d6ecd2ccc9c191482bf53a586c41ee1c8941
|
658798ad51b8ca508ed38e23c6116178580ce9f2
|
refs/heads/master
| 2020-04-04T07:28:51.773617
| 2018-02-21T00:42:07
| 2018-02-21T00:42:07
| 30,431,428
| 1
| 0
| null | 2016-06-15T17:16:28
| 2015-02-06T20:24:36
|
C++
|
UTF-8
|
C++
| false
| false
| 69,976
|
cc
|
helper_tests.cc
|
#include "helper_tests.h"
#include "looper.h"
#include "TFile.h"
#include "./CORE/CMS3.h"
#include "./CORE/SSSelections.h"
#include "./tools.h"
using namespace tas;
void tests::runQCDtest(looper* loop, float& weight_, vector<Lep>& fobs, vector<Lep>& goodleps, int& njets, float& met) {
if (fobs.size()>1) return;
if (fobs[0].pt()<ptCutHigh) return;
loop->makeFillHisto1D<TH1F,int>("njets","njets",20,0,20,njets,weight_);
for (unsigned int ipu=0;ipu<puInfo_bunchCrossing().size();ipu++)
if (puInfo_bunchCrossing()[ipu]==0)
loop->makeFillHisto1D<TH1F,float>("npu_true","npu_true",20,0,100,puInfo_trueNumInteractions()[ipu],weight_);
if (njets==0) return;
float evtmt = mt(fobs[0].pt(),met,deltaPhi(fobs[0].p4().phi(),evt_pfmetPhi()));
float genmt = mt(fobs[0].pt(),gen_met(),deltaPhi(fobs[0].p4().phi(),gen_metPhi()));
float tkmet = trackerMET(0.2).met;
float minmet = std::min(tkmet,met);
loop->makeFillHisto1D<TH1F,float>("fo_pt","fo_pt",20,0,100,fobs[0].pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("fo_eta","fo_eta",10,-2.5,2.5,fobs[0].eta(),weight_);
loop->makeFillHisto1D<TH1F,float>("evt_met","evt_met",10,0,100,met,weight_);
loop->makeFillHisto1D<TH1F,float>("evt_tkmet","evt_tkmet",10,0,100,tkmet,weight_);
loop->makeFillHisto1D<TH1F,float>("evt_minmet","evt_minmet",10,0,100,minmet,weight_);
loop->makeFillHisto1D<TH1F,float>("evt_mt","evt_mt",20,0,200,evtmt,weight_);
loop->makeFillHisto2D<TH2F,float>("evt_mt_vs_met","evt_mt_vs_met",10,0,100,met,20,0,200,evtmt,weight_);
loop->makeFillHisto2D<TH2F,float>("evt_mt_vs_pt", "evt_mt_vs_pt",20,0,100,fobs[0].pt(),20,0,200,evtmt,weight_);
loop->makeFillHisto1D<TH1F,float>("gen_met","gen_met",10,0,100,gen_met(),weight_);
loop->makeFillHisto1D<TH1F,float>("gen_mt","gen_mt",20,0,200,genmt,weight_);
loop->makeFillHisto2D<TH2F,float>("gen_mt_vs_met","gen_mt_vs_met",10,0,100,gen_met(),20,0,200,genmt,weight_);
if (met<20 && evtmt<20) loop->makeFillHisto1D<TH1F,int>("pass_metmt","pass_metmt",2,0,2,1,weight_);
else loop->makeFillHisto1D<TH1F,int>("pass_metmt","pass_metmt",2,0,2,0,weight_);
if (minmet<20 && evtmt<20) loop->makeFillHisto1D<TH1F,int>("pass_minmetmt","pass_minmetmt",2,0,2,1,weight_);
else loop->makeFillHisto1D<TH1F,int>("pass_minmetmt","pass_minmetmt",2,0,2,0,weight_);
if (gen_met()<20 && genmt<20) loop->makeFillHisto1D<TH1F,int>("pass_gen_metmt","pass_gen_metmt",2,0,2,1,weight_);
else loop->makeFillHisto1D<TH1F,int>("pass_gen_metmt","pass_gen_metmt",2,0,2,0,weight_);
//compute fake rate
//reco level selection
if (met<20. && evtmt<20.) {
for (unsigned int fo=0;fo<fobs.size();++fo) {
//if (isFromW(fobs[fo])) continue;//fixme
//if (!isFromB(fobs[fo])) continue;//fixme
int pdgid = abs(fobs[fo].pdgId());
//denominator
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_den":"fr_el_den"),(pdgid==13?"fr_mu_den":"fr_el_den"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),weight_);
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_den_now":"fr_el_den_now"),(pdgid==13?"fr_mu_den_now":"fr_el_den_now"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),1.);
//numerator
for (unsigned int gl=0;gl<goodleps.size();++gl) {
if (abs(goodleps[gl].pdgId())==pdgid && goodleps[gl].idx()==fobs[fo].idx()) {
//cout << "goodleps.size()=" << goodleps.size() << endl;
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_num":"fr_el_num"),(pdgid==13?"fr_mu_num":"fr_el_num"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),weight_);
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_num_now":"fr_el_num_now"),(pdgid==13?"fr_mu_num_now":"fr_el_num_now"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),1.);
//std::cout << "scale1fb=" << evt_scale1fb() << endl;
break;
}
}
}
}
//reco level selection (minmet)
if (minmet<20. && evtmt<20.) {
for (unsigned int fo=0;fo<fobs.size();++fo) {
//if (isFromW(fobs[fo])) continue;//fixme
//if (!isFromB(fobs[fo])) continue;//fixme
int pdgid = abs(fobs[fo].pdgId());
//denominator
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_den_min":"fr_el_den_min"),(pdgid==13?"fr_mu_den_min":"fr_el_den_min"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),weight_);
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_den_min_now":"fr_el_den_min_now"),(pdgid==13?"fr_mu_den_min_now":"fr_el_den_min_now"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),1.);
//numerator
for (unsigned int gl=0;gl<goodleps.size();++gl) {
if (abs(goodleps[gl].pdgId())==pdgid && goodleps[gl].idx()==fobs[fo].idx()) {
//cout << "goodleps.size()=" << goodleps.size() << endl;
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_num_min":"fr_el_num_min"),(pdgid==13?"fr_mu_num_min":"fr_el_num_min"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),weight_);
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_num_min_now":"fr_el_num_min_now"),(pdgid==13?"fr_mu_num_min_now":"fr_el_num_min_now"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),1.);
//std::cout << "scale1fb=" << evt_scale1fb() << endl;
break;
}
}
}
}
//gen level selection
if (gen_met()<20. && genmt<20.) {
for (unsigned int fo=0;fo<fobs.size();++fo) {
//if (isFromW(fobs[fo])) continue;//fixme
//if (!isFromB(fobs[fo])) continue;//fixme
int pdgid = abs(fobs[fo].pdgId());
//denominator
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_den_gen":"fr_el_den_gen"),(pdgid==13?"fr_mu_den_gen":"fr_el_den_gen"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),weight_);
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_den_gen_now":"fr_el_den_gen_now"),(pdgid==13?"fr_mu_den_gen_now":"fr_el_den_gen_now"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),1.);
//numerator
for (unsigned int gl=0;gl<goodleps.size();++gl) {
if (abs(goodleps[gl].pdgId())==pdgid && goodleps[gl].idx()==fobs[fo].idx()) {
//cout << "goodleps.size()=" << goodleps.size() << endl;
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_num_gen":"fr_el_num_gen"),(pdgid==13?"fr_mu_num_gen":"fr_el_num_gen"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),weight_);
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_num_gen_now":"fr_el_num_gen_now"),(pdgid==13?"fr_mu_num_gen_now":"fr_el_num_gen_now"),
10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),1.);
//std::cout << "scale1fb=" << evt_scale1fb() << endl;
break;
}
}
}
}
}
void tests::runDYtest(looper* loop, float& weight_, vector<Lep>& vetoleps_noiso, vector<Lep>& fobs, vector<Lep>& goodleps, int& njets, float& met, float& ht) {
//check lepton selection efficiency
for (unsigned int gp=0;gp<genps_id().size();++gp) {
int pdgid = abs(genps_id()[gp]);
if (pdgid!=13 && pdgid!=11) continue;
if (genps_id_mother()[gp]!=23 && abs(genps_id_mother()[gp])!=24) continue;
if (genps_status()[gp]!=1) continue;//is this needed?
if (fabs(genps_p4()[gp].eta())>2.4) continue;
if (genps_p4()[gp].pt()<5) continue;
if (pdgid==11 && genps_p4()[gp].pt()<10) continue;
//denominator
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ef_mu_den":"ef_el_den"),(pdgid==13?"ef_mu_den":"ef_el_den"),5,0.,100.,genps_p4()[gp].pt(),3,0.,3.0,fabs(genps_p4()[gp].eta()),weight_);
if (fabs(genps_p4()[gp].eta())<1.0) {
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ef_ht_mu_den":"ef_ht_el_den"),(pdgid==13?"ef_ht_mu_den":"ef_ht_el_den"),5,0.,200.,genps_p4()[gp].pt(),6,0.,1200,ht,weight_);
}
//numerator
for (unsigned int gl=0;gl<goodleps.size();++gl) {
if (abs(goodleps[gl].pdgId())==pdgid && deltaR(goodleps[gl].p4(),genps_p4()[gp])<0.1) {
//cout << "goodleps.size()=" << goodleps.size() << endl;
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ef_mu_num":"ef_el_num"),(pdgid==13?"ef_mu_num":"ef_el_num"),5,0.,100.,genps_p4()[gp].pt(),3,0.,3.0,fabs(genps_p4()[gp].eta()),weight_);
if (fabs(genps_p4()[gp].eta())<1.0) {
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ef_ht_mu_num":"ef_ht_el_num"),(pdgid==13?"ef_ht_mu_num":"ef_ht_el_num"),5,0.,200.,genps_p4()[gp].pt(),6,0.,1200,ht,weight_);
}
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ptrel_vs_iso_mu":"ptrel_vs_iso_el"),(pdgid==13?"ptrel_vs_iso_mu":"ptrel_vs_iso_el"),10,0.,1.,goodleps[gl].relIso03(),
15,0.,30,getPtRel(goodleps[gl].pdgId(), goodleps[gl].idx(), true, ssWhichCorr),weight_);
//charge flip
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"flip_mu_den":"flip_el_den"),(pdgid==13?"flip_mu_den":"flip_el_den"),5,0.,100.,genps_p4()[gp].pt(),3,0.,3.0,fabs(genps_p4()[gp].eta()),weight_);
if (goodleps[gl].pdgId()==-genps_id()[gp]) loop->makeFillHisto2D<TH2F,float>((pdgid==13?"flip_mu_num":"flip_el_num"),(pdgid==13?"flip_mu_num":"flip_el_num"),5,0.,100.,genps_p4()[gp].pt(),3,0.,3.0,fabs(genps_p4()[gp].eta()),weight_);
break;
}
}
//numerator for fobs
for (unsigned int fo=0;fo<fobs.size();++fo) {
if (abs(fobs[fo].pdgId())==pdgid && deltaR(fobs[fo].p4(),genps_p4()[gp])<0.1) {
//cout << "fobs.size()=" << fobs.size() << endl;
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ef_mu_num_fo":"ef_el_num_fo"),(pdgid==13?"ef_mu_num_fo":"ef_el_num_fo"),5,0.,100.,genps_p4()[gp].pt(),3,0.,3.0,fabs(genps_p4()[gp].eta()),weight_);
if (fabs(genps_p4()[gp].eta())<1.0) {
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ef_ht_mu_num_fo":"ef_ht_el_num_fo"),(pdgid==13?"ef_ht_mu_num_fo":"ef_ht_el_num_fo"),5,0.,200.,genps_p4()[gp].pt(),6,0.,1200,ht,weight_);
}
break;
}
}
//numerator for tight id and fobs isolation
for (unsigned int fo=0;fo<fobs.size();++fo) {
if (abs(fobs[fo].pdgId())==pdgid && deltaR(fobs[fo].p4(),genps_p4()[gp])<0.1) {
//cout << "fobs.size()=" << fobs.size() << endl;
if (isGoodLeptonNoIso(fobs[fo].pdgId(),fobs[fo].idx())==0) continue;
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ef_mu_num_foiso":"ef_el_num_foiso"),(pdgid==13?"ef_mu_num_foiso":"ef_el_num_foiso"),5,0.,100.,genps_p4()[gp].pt(),3,0.,3.0,fabs(genps_p4()[gp].eta()),weight_);
if (fabs(genps_p4()[gp].eta())<1.0) {
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ef_ht_mu_num_foiso":"ef_ht_el_num_foiso"),(pdgid==13?"ef_ht_mu_num_foiso":"ef_ht_el_num_foiso"),5,0.,200.,genps_p4()[gp].pt(),6,0.,1200,ht,weight_);
}
break;
}
}
//numerator for vetoleps_noiso
for (unsigned int vlnoiso=0;vlnoiso<vetoleps_noiso.size();++vlnoiso) {
if (abs(vetoleps_noiso[vlnoiso].pdgId())==pdgid && deltaR(vetoleps_noiso[vlnoiso].p4(),genps_p4()[gp])<0.1) {
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ef_mu_num_vlnoiso":"ef_el_num_vlnoiso"),(pdgid==13?"ef_mu_num_vlnoiso":"ef_el_num_vlnoiso"),5,0.,100.,genps_p4()[gp].pt(),3,0.,3.0,fabs(genps_p4()[gp].eta()),weight_);
if (fabs(genps_p4()[gp].eta())<1.0) {
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"ef_ht_mu_num_vlnoiso":"ef_ht_el_num_vlnoiso"),(pdgid==13?"ef_ht_mu_num_vlnoiso":"ef_ht_el_num_vlnoiso"),5,0.,200.,genps_p4()[gp].pt(),6,0.,1200,ht,weight_);
}
if (isGoodLepton(vetoleps_noiso[vlnoiso].pdgId(),vetoleps_noiso[vlnoiso].idx())==0) {
plotLeptonIdVariables( loop, weight_, "vetoFailTight", vetoleps_noiso[vlnoiso].pdgId(), vetoleps_noiso[vlnoiso].idx());
if (isLooseIsolatedLepton(vetoleps_noiso[vlnoiso].pdgId(),vetoleps_noiso[vlnoiso].idx())) plotLeptonIdVariables( loop, weight_, "lisovetoFailTight", vetoleps_noiso[vlnoiso].pdgId(), vetoleps_noiso[vlnoiso].idx());
if (isIsolatedLepton(vetoleps_noiso[vlnoiso].pdgId(),vetoleps_noiso[vlnoiso].idx())) plotLeptonIdVariables( loop, weight_, "isovetoFailTight", vetoleps_noiso[vlnoiso].pdgId(), vetoleps_noiso[vlnoiso].idx());
}
break;
}
}
if (pdgid==11){
for (unsigned int elidx=0;elidx<els_p4().size();++elidx) {
if (deltaR(els_p4()[elidx],genps_p4()[gp])>0.1) continue;
if (fabs(els_etaSC().at(elidx)) <= 1.479) {
loop->makeFillHisto1D<TH1F,float>("el_fo_sietaieta_barrel","el_fo_sietaieta_barrel",50,0.,0.025,els_sigmaIEtaIEta_full5x5().at(elidx),weight_);
}
}
}
}
}
void tests::runWZtest(looper* loop, float& weight_, vector<Lep>& vetoleps, vector<Lep>& fobs, vector<Lep>& goodleps, int& njets, float& met) {
weight_=1.;//fixme
loop->makeFillHisto1D<TH1F,float>("vetoleps_size","vetoleps_size",10,-0.5,9.5,vetoleps.size(),weight_);
loop->makeFillHisto1D<TH1F,float>("goodleps_size","goodleps_size",10,-0.5,9.5,goodleps.size(),weight_);
if (goodleps.size()==2) {
loop->makeFillHisto1D<TH1F,float>("vetoleps_size_g2","vetoleps_size_g2",10,-0.5,9.5,vetoleps.size(),weight_);
if (goodleps[0].charge()!=goodleps[1].charge()) return;
loop->makeFillHisto1D<TH1F,float>("vetoleps_size_g2ss","vetoleps_size_g2ss",10,-0.5,9.5,vetoleps.size(),weight_);
bool noZmass = true;
for (unsigned int gl=0;gl<goodleps.size();++gl) {
for (unsigned int vl=0;vl<vetoleps.size();++vl) {
if ( fabs(ROOT::Math::VectorUtil::DeltaR(goodleps[gl].p4(),vetoleps[vl].p4()))<0.001 ) continue;
if ( goodleps[gl].pdgId()!=-vetoleps[vl].pdgId() ) continue;
float mll = (goodleps[gl].p4()+vetoleps[vl].p4()).mass();
if (fabs(mll-91.2)<15) {
noZmass = false;
break;
}
}
}
if (vetoleps.size()>2) loop->makeFillHisto1D<TH1F,float>("noZmass_v3g2ss","noZmass_v3g2ss",2,0,2,noZmass,weight_);
if (vetoleps.size()==2 || noZmass) {
loop->makeFillHisto1D<TH1F,float>("fobs_size_noZv3g2ss","fobs_size_noZv3g2ss",10,-0.5,9.5,fobs.size(),weight_);
if (fobs.size()>2) return;
cout << "new gps" << endl;
float mz = -999.;
float mw = -999.;
float maxAbsEta = -1;
float minPt = 999999.;
vector<unsigned int> gpidv;
for (unsigned int gp=0;gp<genps_id().size();++gp) {
int pdgid = abs(genps_id()[gp]);
if (pdgid==23) {
//cout << "Z status=" << genps_status()[gp] << " mother=" << genps_id_mother()[gp] << endl;
if (genps_status()[gp]==22) mz = genps_p4()[gp].mass();
}
if (pdgid==24) {
//cout << "W status=" << genps_status()[gp] << " mother=" << genps_id_mother()[gp] << endl;
if (genps_status()[gp]==22) mw = genps_p4()[gp].mass();
}
if (pdgid!=13 && pdgid!=11 && pdgid!=15) continue;
if (pdgid==11) cout << "electron status=" << genps_status()[gp] << " mother=" << genps_id_mother()[gp] << " pt=" << genps_p4()[gp].pt() << endl;
if (pdgid==13) cout << "muon status=" << genps_status()[gp] << " mother=" << genps_id_mother()[gp] << " pt=" << genps_p4()[gp].pt() << endl;
if (pdgid==15) cout << "tau status=" << genps_status()[gp] << " mother=" << genps_id_mother()[gp] << " pt=" << genps_p4()[gp].pt() << endl;
if (genps_id_mother()[gp]!=23 && abs(genps_id_mother()[gp])!=24) continue;
if (pdgid==11 && genps_status()[gp]!=1) continue;//is this needed?
if (pdgid==13 && genps_status()[gp]!=1) continue;//is this needed?
if (pdgid==15 && genps_status()[gp]!=2) continue;//is this needed?
gpidv.push_back(gp);
if (fabs(genps_p4()[gp].eta())>maxAbsEta) maxAbsEta=fabs(genps_p4()[gp].eta());
if (genps_p4()[gp].pt()<minPt) minPt=genps_p4()[gp].pt();
}
if (gpidv.size()==1) {
//cout << "size1" << endl;
for (unsigned int gp=0;gp<genps_id().size();++gp) {
int pdgid = abs(genps_id()[gp]);
//cout << "id=" << genps_id()[gp] << " status=" << genps_status()[gp] << " mother=" << genps_id_mother()[gp] << " pt=" << genps_p4()[gp].pt() << endl;
if (genps_status()[gp]!=1 && genps_status()[gp]!=2) continue;
if (abs(genps_id_mother()[gp])>=24) continue;//Ws are ok (size=1), don't want other resonances, but somehow Z leptons don't have mother id=23
if ((pdgid==11 && genps_status()[gp]==1) || (pdgid==13 && genps_status()[gp]==1) || (pdgid==15 && genps_status()[gp]==2)) gpidv.push_back(gp);
}
}
if (gpidv.size()>3) {
cout << "size>3 is " << gpidv.size() << endl;
for (unsigned int gp=0;gp<gpidv.size() && gpidv.size()>3;++gp) {
cout << "id=" << genps_id()[gpidv[gp]] << " status=" << genps_status()[gpidv[gp]] << " mother=" << genps_id_mother()[gpidv[gp]] << " pt=" << genps_p4()[gpidv[gp]].pt() << endl;
if (abs(genps_id()[gpidv[gp]])==15) {//extra leps can be duplicates from tau decays
gpidv.erase(gpidv.begin()+gp);
cout << "erased position=" << gp << " new size=" << gpidv.size() << endl;
gp--;
}
}
}
if (gpidv.size()>3) {
cout << "sorting size>3 is " << gpidv.size() << endl;
//sort by pt and erase exceeding items
std::sort(gpidv.begin(),gpidv.end(),ptsort);
gpidv.erase(gpidv.begin()+3,gpidv.end());
for (unsigned int gp=0;gp<gpidv.size();++gp) {
cout << "id=" << genps_id()[gpidv[gp]] << " status=" << genps_status()[gpidv[gp]]
<< " mother=" << genps_id_mother()[gpidv[gp]] << " pt=" << genps_p4()[gpidv[gp]].pt() << endl;
}
}
if (gpidv.size()!=3) {
cout << "anomalous size=" << gpidv.size() << endl;
for (unsigned int gp=0;gp<gpidv.size();++gp) {
cout << "sel id=" << genps_id()[gpidv[gp]] << " status=" << genps_status()[gpidv[gp]] << " mother=" << genps_id_mother()[gpidv[gp]] << " pt=" << genps_p4()[gpidv[gp]].pt() << endl;
}
for (unsigned int gp=0;gp<genps_id().size();++gp) {
cout << "gps id=" << genps_id()[gp] << " status=" << genps_status()[gp] << " mother=" << genps_id_mother()[gp] << " pt=" << genps_p4()[gp].pt() << endl;
}
}
int glepfromZ = -1;
for (unsigned int gl=0;gl<goodleps.size();++gl) {
//easy to check that it is not from W
if (isFromW(goodleps[gl].pdgId(),goodleps[gl].idx())==0 ||goodleps[gl].mc_motherid()==23) {
glepfromZ=gl;
break;
}
}
loop->makeFillHisto1D<TH1F,float>("gps_size_g2f2","gps_size_g2f2",10,-0.5,9.5,gpidv.size(),weight_);
loop->makeFillHisto1D<TH1F,float>("mz_g2f2","mz_g2f2",100,0.,200,mz,weight_);
loop->makeFillHisto1D<TH1F,float>("mw_g2f2","mw_g2f2",100,0.,200,mw,weight_);
if (gpidv.size()==3) {
loop->makeFillHisto1D<TH1F,float>("maxAbsEta_g2f2s3","maxAbsEta_g2f2s3",100,0.,5.0,maxAbsEta,weight_);
if (maxAbsEta<2.4) loop->makeFillHisto1D<TH1F,float>("minPt_g2f2s3eta24","minPt_g2f2s3eta24",100,0.,200.0,minPt,weight_);
else return;
//match goodleps and vetoleps with genps
cout << "check duplicates" << endl;
int unmatches = 0;
for (unsigned int gp=0;gp<gpidv.size();++gp) {
unsigned int gpid = gpidv[gp];
int pdgid = abs(genps_id()[gpid]);
/*
cout << "sel id=" << genps_id()[gpid] << " status=" << genps_status()[gpid]
<< " mother=" << genps_id_mother()[gpid] << " pt=" << genps_p4()[gpid].pt() << endl;
*/
bool glmatch = false;
for (unsigned int gl=0;gl<goodleps.size();++gl) {
if (goodleps[gl].mc3idx()==int(gpid) ||
fabs(ROOT::Math::VectorUtil::DeltaR(goodleps[gl].mc_p4(),genps_p4()[gpid]))<0.1 ||
fabs(ROOT::Math::VectorUtil::DeltaR(goodleps[gl].p4(),genps_p4()[gpid]))<0.1) {
cout << "match lep and gp, pt=" << goodleps[gl].mc_p4().pt() << " " << genps_p4()[gpid].pt() << endl;
glmatch = true;
}
}
if (glmatch==0) {
unmatches++;
int pfidx = -1;
float mindpt = 0.2;
for (unsigned int pfi=0; pfi<pfcands_p4().size(); ++pfi){
if ( pfcands_charge()[pfi]==0 ) continue;
float dR = fabs(ROOT::Math::VectorUtil::DeltaR(pfcands_p4()[pfi],genps_p4()[gpid]));
float dpt = fabs((pfcands_p4()[pfi].pt()-genps_p4()[gpid].pt())/genps_p4()[gpid].pt());
if ( dR<0.1 && dpt<mindpt ) {
pfidx=pfi;
mindpt=dpt;
//break;
}
}
loop->makeFillHisto1D<TH1F,float>("pdgId_noGL","pdgId_noGL",20,0.,20,pdgid,weight_);
loop->makeFillHisto1D<TH1F,float>("momId_noGL","momId_noGL",30,0.,30,abs(genps_id_mother()[gpid]),weight_);
if (pdgid==15) continue;
if (pfidx>=0) {
loop->makeFillHisto1D<TH1F,float>("deltapt_pfmatch","deltapt_pfmatch",100,-1.,1,(pfcands_p4()[pfidx].pt()-genps_p4()[gpid].pt())/genps_p4()[gpid].pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("pfid_pfmatch","pfid_pfmatch",250,0,250,abs(pfcands_particleId()[pfidx]),weight_);
} else {
if (pdgid==11) loop->makeFillHisto2D<TH2F,float>("pteta_el_noPFnoGLeta24","pteta_el_noPFnoGLeta24",5,0.,50.0,genps_p4()[gpid].pt(),5,0.,2.5,fabs(genps_p4()[gpid].eta()),weight_);
if (pdgid==13) loop->makeFillHisto2D<TH2F,float>("pteta_mu_noPFnoGLeta24","pteta_mu_noPFnoGLeta24",5,0.,50.0,genps_p4()[gpid].pt(),5,0.,2.5,fabs(genps_p4()[gpid].eta()),weight_);
}
if (pdgid==11) {
loop->makeFillHisto1D<TH1F,float>("eta_el_noGL","eta_el_noGL",100,0.,5.0,fabs(genps_p4()[gpid].eta()),weight_);
if (fabs(genps_p4()[gpid].eta())<2.4) {
loop->makeFillHisto1D<TH1F,float>("pt_el_noGLeta24","pt_el_noGLeta24",100,0.,200.0,genps_p4()[gpid].pt(),weight_);
if (pfidx>=0&&glepfromZ>=0) {
//loop->makeFillHisto1D<TH1F,float>("mll_elpf_noGLeta24","mll_elpf_noGLeta24",40,0.,200.0,(goodleps[glepfromZ].p4()+pfcands_p4()[pfidx]).mass(),weight_);
float mass0 = (goodleps[0].p4()+pfcands_p4()[pfidx]).mass();
float mass1 = (goodleps[1].p4()+pfcands_p4()[pfidx]).mass();
loop->makeFillHisto1D<TH1F,float>("mll_elpf_noGLeta24","mll_elpf_noGLeta24",40,0.,200.0,(fabs(mass0-91.2)<fabs(mass1-91.2)?mass0:mass1),weight_);
loop->makeFillHisto1D<TH1F,float>("mz_elpf_noGLeta24","mz_elpf_noGLeta24",40,0.,200.0,mz,weight_);
}
}
}
if (pdgid==13) {
loop->makeFillHisto1D<TH1F,float>("eta_mu_noGL","eta_mu_noGL",100,0.,5.0,fabs(genps_p4()[gpid].eta()),weight_);
if (fabs(genps_p4()[gpid].eta())<2.4) {
loop->makeFillHisto1D<TH1F,float>("pt_mu_noGLeta24","pt_mu_noGLeta24",100,0.,200.0,genps_p4()[gpid].pt(),weight_);
if (pfidx>=0&&glepfromZ>=0) {
//loop->makeFillHisto1D<TH1F,float>("mll_mupf_noGLeta24","mll_mupf_noGLeta24",40,0.,200.0,(goodleps[glepfromZ].p4()+pfcands_p4()[pfidx]).mass(),weight_);
float mass0 = (goodleps[0].p4()+pfcands_p4()[pfidx]).mass();
float mass1 = (goodleps[1].p4()+pfcands_p4()[pfidx]).mass();
loop->makeFillHisto1D<TH1F,float>("mll_mupf_noGLeta24","mll_mupf_noGLeta24",40,0.,200.0,(fabs(mass0-91.2)<fabs(mass1-91.2)?mass0:mass1),weight_);
loop->makeFillHisto1D<TH1F,float>("mz_mupf_noGLeta24","mz_mupf_noGLeta24",40,0.,200.0,mz,weight_);
}
}
}
}
}
if (unmatches>1) {
cout << "duplcates, unmatches=" << unmatches << endl;
for (unsigned int gl=0;gl<goodleps.size();++gl) {
cout << "good lep pt=" << goodleps[gl].pt() << " eta=" << goodleps[gl].eta() << " phi=" << goodleps[gl].p4().phi() << " mcpt=" << goodleps[gl].mc_p4().pt() << endl;
}
for (unsigned int gp=0;gp<gpidv.size();++gp) {
cout << "id=" << genps_id()[gpidv[gp]] << " status=" << genps_status()[gpidv[gp]] << " mother=" << genps_id_mother()[gpidv[gp]]
<< " pt=" << genps_p4()[gpidv[gp]].pt() << " eta=" << genps_p4()[gpidv[gp]].eta() << " phi=" << genps_p4()[gpidv[gp]].phi() << endl;
}
//return -1;
}
}
}
}
}
void tests::fakeStudy(looper* loop, float& weight_, DilepHyp& hyp, TString& ll, TString& lt) {
bool isLeadPrompt = 0;
bool isTrailPrompt = 0;
int leadType = -1;
int trailType = -1;
if ( !isFromW(hyp.traiLep().pdgId(),hyp.traiLep().idx()) ) {
//check fakes (mother not W)
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_mc","hyp_ss_faketrail_"+lt+"_mc",11001,-5500.5,5500.5,hyp.traiLep().mc_id(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_mc_mother","hyp_ss_faketrail_"+lt+"_mc_mother",11001,-5500.5,5500.5,hyp.traiLep().mc_motherid(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_mc3","hyp_ss_faketrail_"+lt+"_mc3",11001,-5500.5,5500.5,hyp.traiLep().mc3_id(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_mc3_mother","hyp_ss_faketrail_"+lt+"_mc3_mother",11001,-5500.5,5500.5,hyp.traiLep().mc3_motherid(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_faketrail_"+lt+"_relIso03","hyp_ss_faketrail_"+lt+"_relIso03",100,0.,1.,hyp.traiLep().relIso03(),weight_);
if (isFromB(hyp.traiLep().pdgId(),hyp.traiLep().idx()) ) trailType=FakeB;
else if (isFromC(hyp.traiLep().pdgId(),hyp.traiLep().idx()) ) trailType=FakeC;
else if (isFromLight(hyp.traiLep().pdgId(),hyp.traiLep().idx())) trailType=FakeLightTrue;
else if (isFromLightFake(hyp.traiLep().pdgId(),hyp.traiLep().idx())) trailType=FakeLightFake;
else if (hyp.traiLep().mc_id()==22 && hyp.traiLep().mc_p4().pt()>hyp.traiLep().pt()/2.) {
trailType=FakeHiPtGamma;
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_hiptgamma_mc","hyp_ss_faketrail_"+lt+"_hiptgamma_mc",11001,-5500.5,5500.5,hyp.traiLep().mc_id(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_hiptgamma_mc_mother","hyp_ss_faketrail_"+lt+"_hiptgamma_mc_mother",11001,-5500.5,5500.5,hyp.traiLep().mc_motherid(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_hiptgamma_mc3","hyp_ss_faketrail_"+lt+"_hiptgamma_mc3",11001,-5500.5,5500.5,hyp.traiLep().mc3_id(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_hiptgamma_mc3_mother","hyp_ss_faketrail_"+lt+"_hiptgamma_mc3_mother",11001,-5500.5,5500.5,hyp.traiLep().mc3_motherid(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_faketrail_"+lt+"_hiptgamma_pt","hyp_ss_faketrail_"+lt+"_hiptgamma_pt",50,0,100,hyp.traiLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_faketrail_"+lt+"_hiptgamma_ptmc","hyp_ss_faketrail_"+lt+"_hiptgamma_ptmc",50,0,100,hyp.traiLep().mc_p4().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_faketrail_"+lt+"_hiptgamma_deltaptoverpt","hyp_ss_faketrail_"+lt+"_hiptgamma_deltaptoverpt",100,-0.5,0.5,(hyp.traiLep().pt()-hyp.traiLep().mc_p4().pt())/hyp.traiLep().mc_p4().pt(),weight_);
} else {
trailType=FakeUnknown;
if (hyp.traiLep().mc_id()==22 && hyp.traiLep().mc_p4().pt()<1.) {
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_category","hyp_ss_faketrail_"+lt+"_category",End,0,End,FakeLowPtGamma,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_hilowgamma_mc","hyp_ss_faketrail_"+lt+"_hilowgamma_mc",11001,-5500.5,5500.5,hyp.traiLep().mc_id(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_hilowgamma_mc_mother","hyp_ss_faketrail_"+lt+"_hilowgamma_mc_mother",11001,-5500.5,5500.5,hyp.traiLep().mc_motherid(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_hilowgamma_mc3","hyp_ss_faketrail_"+lt+"_hilowgamma_mc3",11001,-5500.5,5500.5,hyp.traiLep().mc3_id(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_hilowgamma_mc3_mother","hyp_ss_faketrail_"+lt+"_hilowgamma_mc3_mother",11001,-5500.5,5500.5,hyp.traiLep().mc3_motherid(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_faketrail_"+lt+"_category_hilowgamma_pt","hyp_ss_faketrail_"+lt+"_category_hilowgamma_pt",50,0,100,hyp.traiLep().pt(),weight_);
} else if (hyp.traiLep().mc_id()==-9999 && hyp.traiLep().mc_motherid()==-9999 && hyp.traiLep().mc3_id()==-9999 && hyp.traiLep().mc3_motherid()==-9999) {
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_category","hyp_ss_faketrail_"+lt+"_category",End,0,End,All9999,weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_faketrail_"+lt+"_category_all9999_pt","hyp_ss_faketrail_"+lt+"_category_all9999_pt",50,0,100,hyp.traiLep().pt(),weight_);
}
else {
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_category","hyp_ss_faketrail_"+lt+"_category",End,0,End,Other,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_other_mc","hyp_ss_faketrail_"+lt+"_other_mc",11001,-5500.5,5500.5,hyp.traiLep().mc_id(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_other_mc_mother","hyp_ss_faketrail_"+lt+"_other_mc_mother",11001,-5500.5,5500.5,hyp.traiLep().mc_motherid(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_other_mc3","hyp_ss_faketrail_"+lt+"_other_mc3",11001,-5500.5,5500.5,hyp.traiLep().mc3_id(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_faketrail_"+lt+"_other_mc3_mother","hyp_ss_faketrail_"+lt+"_other_mc3_mother",11001,-5500.5,5500.5,hyp.traiLep().mc3_motherid(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_faketrail_"+lt+"_category_other_pt","hyp_ss_faketrail_"+lt+"_category_other_pt",50,0,100,hyp.traiLep().pt(),weight_);
/*
cout << "UNKNOWN FAKE LEPTON " << lt << endl;
cout << "trai lep id=" << hyp.traiLep().pdgId() << " p4=" << hyp.traiLep().p4()
<< " mcid=" << hyp.traiLep().mc_id() << " mcp4=" << hyp.traiLep().mc_p4() << " mother_id=" << hyp.traiLep().mc_motherid()
<< " mc3idx=" << hyp.traiLep().mc3idx() << " mc3_id=" << hyp.traiLep().mc3_id()
<< " mc3_motheridx=" << hyp.traiLep().mc3_motheridx() << " mc3_mother_id=" << hyp.traiLep().mc3_motherid()
<< " genps_id_mother()[hyp.traiLep().mc3_motheridx()]=" << genps_id_mother()[hyp.traiLep().mc3_motheridx()]
<< endl;
*/
}
}
} else {
isTrailPrompt = 1;
if ( hyp.traiLep().pdgId()==hyp.traiLep().mc_id() ) trailType=Prompt;
else if ( abs(hyp.traiLep().pdgId())==abs(hyp.traiLep().mc_id()) ) trailType=PromptWS;
else if ( abs(hyp.traiLep().pdgId())==11 ? abs(hyp.traiLep().mc_id())==13 : abs(hyp.traiLep().mc_id())==11 ) trailType=PromptWF;
else if ( hyp.traiLep().mc_id()==22) trailType=PromptFSR;
else cout << "UNKNOWN PROMPT LEPTON " << lt << endl;
}
if ( !isFromW(hyp.leadLep().pdgId(),hyp.leadLep().idx()) ) {
loop->makeFillHisto1D<TH1F,int>("hyp_ss_fakelead_"+ll+"_mc","hyp_ss_fakelead_"+ll+"_mc",11001,-5500.5,5500.5,hyp.leadLep().mc_id(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_fakelead_"+ll+"_mc_mother","hyp_ss_fakelead_"+ll+"_mc_mother",11001,-5500.5,5500.5,hyp.leadLep().mc_motherid(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_fakelead_"+ll+"_mc3","hyp_ss_fakelead_"+ll+"_mc3",11001,-5500.5,5500.5,hyp.leadLep().mc3_id(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_fakelead_"+ll+"_mc3_mother","hyp_ss_fakelead_"+ll+"_mc3_mother",11001,-5500.5,5500.5,hyp.leadLep().mc3_motherid(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_fakelead_"+lt+"_relIso03","hyp_ss_fakelead_"+lt+"_relIso03",100,0.,1.,hyp.leadLep().relIso03(),weight_);
if (isFromB(hyp.leadLep().pdgId(),hyp.leadLep().idx()) ) leadType=FakeB;
else if (isFromC(hyp.leadLep().pdgId(),hyp.leadLep().idx()) ) leadType=FakeC;
else if (isFromLight(hyp.leadLep().pdgId(),hyp.leadLep().idx())) leadType=FakeLightTrue;
else if (isFromLightFake(hyp.leadLep().pdgId(),hyp.leadLep().idx())) leadType=FakeLightFake;
else if (hyp.leadLep().mc_id()==22 && hyp.leadLep().mc_p4().pt()>hyp.leadLep().pt()/2.) leadType=FakeHiPtGamma;
else {
leadType=FakeUnknown;
if (hyp.leadLep().mc_id()==22 && hyp.leadLep().mc_p4().pt()<1.)
loop->makeFillHisto1D<TH1F,int>("hyp_ss_fakelead_"+ll+"_category","hyp_ss_fakelead_"+ll+"_category",End,0,End,FakeLowPtGamma,weight_);
else if (hyp.leadLep().mc_id()==-9999 && hyp.leadLep().mc_motherid()==-9999 && hyp.leadLep().mc3_id()==-9999 && hyp.leadLep().mc3_motherid()==-9999)
loop->makeFillHisto1D<TH1F,int>("hyp_ss_fakelead_"+ll+"_category","hyp_ss_fakelead_"+ll+"_category",End,0,End,All9999,weight_);
else {
loop->makeFillHisto1D<TH1F,int>("hyp_ss_fakelead_"+ll+"_category","hyp_ss_fakelead_"+ll+"_category",End,0,End,Other,weight_);
/*
cout << "UNKNOWN FAKE LEPTON " << ll << endl;
cout << "lead lep id=" << hyp.leadLep().pdgId() << " p4=" << hyp.leadLep().p4()
<< " mcid=" << hyp.leadLep().mc_id() << " mcp4=" << hyp.leadLep().mc_p4() << " mother_id=" << hyp.leadLep().mc_motherid()
<< " mc3idx=" << hyp.leadLep().mc3idx() << " mc3_id=" << hyp.leadLep().mc3_id()
<< " mc3_motheridx=" << hyp.leadLep().mc3_motheridx() << " mc3_mother_id=" << hyp.leadLep().mc3_motherid()
<< " genps_id_mother()[hyp.leadLep().mc3_motheridx()]=" << genps_id_mother()[hyp.leadLep().mc3_motheridx()]
<< endl;
*/
}
}
} else {
isLeadPrompt = 1;
if ( hyp.leadLep().pdgId()==hyp.leadLep().mc_id() ) leadType=Prompt;
else if ( abs(hyp.leadLep().pdgId())==abs(hyp.leadLep().mc_id()) ) leadType=PromptWS;
else if ( abs(hyp.leadLep().pdgId())==11 ? abs(hyp.leadLep().mc_id())==13 : abs(hyp.leadLep().mc_id())==11 ) leadType=PromptWF;
else if ( hyp.leadLep().mc_id()==22) leadType=PromptFSR;
else cout << "UNKNOWN PROMPT LEPTON " << ll << endl;
}
if (trailType>-1) loop->makeFillHisto1D<TH1F,int>("hyp_ss_trail_"+lt+"_category","hyp_ss_trail_"+lt+"_category",End,0,End,trailType,weight_);
if (leadType>-1 ) loop->makeFillHisto1D<TH1F,int>("hyp_ss_lead_"+ll+"_category","hyp_ss_lead_"+ll+"_category",End,0,End,leadType,weight_);
if (abs(hyp.traiLep().pdgId())==13 && hyp.traiLep().pt()>10 && trailType>-1) loop->makeFillHisto1D<TH1F,int>("hyp_ss_trail_"+lt+"_ptGt10_category","hyp_ss_trail_"+lt+"_ptGt10_category",End,0,End,trailType,weight_);
else if (abs(hyp.traiLep().pdgId())==13 && hyp.traiLep().pt()<10 && trailType>-1) loop->makeFillHisto1D<TH1F,int>("hyp_ss_trail_"+lt+"_ptLt10_category","hyp_ss_trail_"+lt+"_ptLt10_category",End,0,End,trailType,weight_);
int prompttype = -1;
if (isLeadPrompt && isTrailPrompt) prompttype=0;
if (isLeadPrompt && !isTrailPrompt) prompttype=1;
if (!isLeadPrompt && isTrailPrompt) prompttype=2;
if (!isLeadPrompt && !isTrailPrompt) prompttype=3;
loop->makeFillHisto1D<TH1F,int>("hyp_prompttype","hyp_prompttype",5,0,5,prompttype,weight_);
if (trailType==PromptWS) loop->makeFillHisto1D<TH1F,int>("hyp_fliptype","hyp_fliptype",3,0,3,1,weight_);
else if (leadType==PromptWS) loop->makeFillHisto1D<TH1F,int>("hyp_fliptype","hyp_fliptype",3,0,3,2,weight_);
else loop->makeFillHisto1D<TH1F,int>("hyp_fliptype","hyp_fliptype",3,0,3,0,weight_);
if (hyp.leadLep().mc_id()*hyp.traiLep().mc_id()<0) loop->makeFillHisto1D<TH1F,int>("hyp_ismcss","hyp_ismcss",3,0,3,0,weight_);
else loop->makeFillHisto1D<TH1F,int>("hyp_ismcss","hyp_ismcss",3,0,3,1,weight_);
if (isLeadPrompt && isTrailPrompt) {
int leadprompttype = -1;
if (leadType==0 && trailType==0) {
leadprompttype=0;
//cout << "UNEXPECTED DOUBLE PROMPT" << endl;
} else if (leadType==1 || trailType==1) leadprompttype=1;
else if (leadType==2 || trailType==2) leadprompttype=1;
else leadprompttype=3;
loop->makeFillHisto1D<TH1F,int>("hyp_leadprompttype","hyp_leadprompttype",5,0,5,leadprompttype,weight_);
}
}
void tests::testLepIdFailMode( looper* loop, float& weight_, std::vector<Lep>& fobs ) {
bool debug = false;
for (unsigned int gp=0;gp<genps_id().size();++gp) {
int pdgid = abs(genps_id()[gp]);
if (pdgid!=13 && pdgid!=11) continue;
if (genps_id_mother()[gp]!=23 && abs(genps_id_mother()[gp])!=24) continue;
if (genps_status()[gp]!=1) continue;//is this needed?
if (fabs(genps_p4()[gp].eta())>2.4) continue;
if (genps_p4()[gp].pt()<5) continue;
if (pdgid==11 && genps_p4()[gp].pt()<10) continue;
if (debug) cout << "gen lep id=" << genps_id()[gp] << " eta=" << genps_p4()[gp].eta() << " pt=" << genps_p4()[gp].pt() << endl;
if (pdgid==11) {
for (unsigned int elidx=0;elidx<els_p4().size();++elidx) {
if (fabs(ROOT::Math::VectorUtil::DeltaR(els_p4()[elidx],genps_p4()[gp]))>0.1) continue;
if (debug) cout << "el pt=" << els_p4()[elidx].pt() << " eta=" << els_p4()[elidx].eta() << " q=" << els_charge()[elidx] << " iso=" << eleRelIso03(elidx, SS)<< endl;
int failmode = 0;
if (isFakableElectron(elidx)==0) failmode = tests::isElectronFO_debug(elidx);
if (threeChargeAgree(elidx)==0) {
failmode = 10;
bool wrongGsf = (genps_charge()[gp]!=els_charge()[elidx]);
bool wrongTrk = (genps_charge()[gp]!=els_trk_charge()[elidx]);
bool wrongScl = (genps_charge()[gp]!=els_sccharge()[elidx]);
loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode","el_fo_q3fail_mode",7,0,7,0,weight_);
if (wrongGsf) loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode","el_fo_q3fail_mode",7,0,7,1,weight_);
else loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode","el_fo_q3fail_mode",7,0,7,2,weight_);
if (wrongTrk) loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode","el_fo_q3fail_mode",7,0,7,3,weight_);
else loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode","el_fo_q3fail_mode",7,0,7,4,weight_);
if (wrongScl) loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode","el_fo_q3fail_mode",7,0,7,5,weight_);
else loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode","el_fo_q3fail_mode",7,0,7,6,weight_);
if (fabs(els_etaSC().at(elidx)) <= 1.479){
loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_barrel","el_fo_q3fail_mode_barrel",7,0,7,0,weight_);
if (wrongGsf) loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_barrel","el_fo_q3fail_mode_barrel",7,0,7,1,weight_);
else loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_barrel","el_fo_q3fail_mode_barrel",7,0,7,2,weight_);
if (wrongTrk) loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_barrel","el_fo_q3fail_mode_barrel",7,0,7,3,weight_);
else loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_barrel","el_fo_q3fail_mode_barrel",7,0,7,4,weight_);
if (wrongScl) loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_barrel","el_fo_q3fail_mode_barrel",7,0,7,5,weight_);
else loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_barrel","el_fo_q3fail_mode_barrel",7,0,7,6,weight_);
} else {
loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_endcap","el_fo_q3fail_mode_endcap",7,0,7,0,weight_);
if (wrongGsf) loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_endcap","el_fo_q3fail_mode_endcap",7,0,7,1,weight_);
else loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_endcap","el_fo_q3fail_mode_endcap",7,0,7,2,weight_);
if (wrongTrk) loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_endcap","el_fo_q3fail_mode_endcap",7,0,7,3,weight_);
else loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_endcap","el_fo_q3fail_mode_endcap",7,0,7,4,weight_);
if (wrongScl) loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_endcap","el_fo_q3fail_mode_endcap",7,0,7,5,weight_);
else loop->makeFillHisto1D<TH1F,int>("el_fo_q3fail_mode_endcap","el_fo_q3fail_mode_endcap",7,0,7,6,weight_);
}
}
if (fabs(els_etaSC().at(elidx)) <= 1.479)
loop->makeFillHisto1D<TH1F,float>("el_fo_fail_sietaieta_barrel","el_fo_fail_sietaieta_barrel",25,0.,0.025,els_sigmaIEtaIEta_full5x5().at(elidx),weight_);
else
loop->makeFillHisto1D<TH1F,float>("el_fo_fail_sietaieta_endcap","el_fo_fail_sietaieta_endcap",25,0.,0.050,els_sigmaIEtaIEta_full5x5().at(elidx),weight_);
if (fabs(els_p4().at(elidx).eta())>2.4) failmode = 11;
if (els_p4().at(elidx).pt()<10.) failmode = 12;
if (isFakableElectron(elidx)==0) {
loop->makeFillHisto1D<TH1F,int>("el_fo_fail_mode","el_fo_fail_mode",15,0,15,failmode,weight_);
if (fabs(els_etaSC().at(elidx)) <= 1.479) loop->makeFillHisto1D<TH1F,int>("el_fo_fail_mode_barrel","el_fo_fail_mode_barrel",15,0,15,failmode,weight_);
else loop->makeFillHisto1D<TH1F,int>("el_fo_fail_mode_endcap","el_fo_fail_mode_endcap",15,0,15,failmode,weight_);
continue;
}
if (debug) cout << "pass FO selection" << endl;
}
}
}
if (debug) {
for (unsigned int fo=0;fo<fobs.size();++fo) {
cout<< "fo lep id=" << fobs[fo].pdgId() << " eta=" << fobs[fo].eta() << " pt=" << fobs[fo].pt() << " relIso=" << fobs[fo].relIso03()<< endl;
}
}
}
int tests::isElectronFO_debug(unsigned int elIdx){//fixme
if(fabs(els_etaSC().at(elIdx)) <= 1.479){
if(fabs(els_dEtaIn().at(elIdx)) >= 0.004) return 1;
if(fabs(els_dPhiIn().at(elIdx)) >= 0.06) return 2;
if(els_sigmaIEtaIEta_full5x5().at(elIdx) >= 0.01) return 3;
if(els_hOverE().at(elIdx) >= 0.12) return 4;
if(fabs(els_dxyPV().at(elIdx)) >= 0.05) return 5; //is this wrt the correct PV?
if(fabs(els_dzPV().at(elIdx)) >= 0.1) return 5; //is this wrt the correct PV?
if( fabs( (1.0/els_ecalEnergy().at(elIdx)) - (els_eOverPIn().at(elIdx)/els_ecalEnergy().at(elIdx)) ) >= 0.05) return 6; // |1/E - 1/p|
if( eleRelIso03(elIdx, SS) >= 0.5 ) return 7;
if( els_conv_vtx_flag().at(elIdx) ) return 8;
if( els_exp_innerlayers().at(elIdx) > 0) return 9;
return 0;
} else if((fabs(els_etaSC().at(elIdx)) > 1.479) && (fabs(els_etaSC().at(elIdx)) < 2.5)){
if(fabs(els_dEtaIn().at(elIdx)) >= 0.007) return 1;
if(fabs(els_dPhiIn().at(elIdx)) >= 0.03) return 2;
if(els_sigmaIEtaIEta_full5x5().at(elIdx) >= 0.03) return 3;
if(els_hOverE().at(elIdx) >= 0.1) return 4;
if(fabs(els_dxyPV().at(elIdx)) >= 0.05) return 5; //is this wrt the correct PV?
if(fabs(els_dzPV().at(elIdx)) >= 0.1) return 5; //is this wrt the correct PV?
if( fabs( (1.0/els_ecalEnergy().at(elIdx)) - (els_eOverPIn().at(elIdx)/els_ecalEnergy().at(elIdx)) ) >= 0.05) return 6; // |1/E - 1/p|
if( eleRelIso03(elIdx, SS) >= 0.5 ) return 7;
if( els_conv_vtx_flag().at(elIdx) ) return 8;
if( els_exp_innerlayers().at(elIdx) > 0) return 9;
return 0;
} else return -1;
}
void tests::computeFakeRateAndClosure( looper* loop, float& weight_, std::vector<Lep>& fobs, std::vector<Lep>& goodleps, TFile* fr_file ) {
for (unsigned int fo=0;fo<fobs.size();++fo) {
if (isFromW(fobs[fo].pdgId(),fobs[fo].idx())) continue;
int pdgid = abs(fobs[fo].pdgId());
//denominator
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_den":"fr_el_den"),(pdgid==13?"fr_mu_den":"fr_el_den"),10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),weight_);
//numerator
bool isNumerator = false;
for (unsigned int gl=0;gl<goodleps.size();++gl) {
if (abs(goodleps[gl].pdgId())==pdgid && goodleps[gl].idx()==fobs[fo].idx()) {
//cout << "goodleps.size()=" << goodleps.size() << endl;
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_num":"fr_el_num"),(pdgid==13?"fr_mu_num":"fr_el_num"),10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),weight_);
isNumerator = true;
break;
}
}
if (!isNumerator && fr_file) {
TH2F* fr_h = (TH2F*) fr_file->Get((pdgid==13?"fr_mu_gen":"fr_el_gen"));
float maxPt=fr_h->GetXaxis()->GetBinUpEdge(fr_h->GetXaxis()->GetNbins())-0.01;
float maxEta=fr_h->GetYaxis()->GetBinUpEdge(fr_h->GetYaxis()->GetNbins())-0.01;
float pt = fobs[fo].pt();
float eta = fabs(fobs[fo].eta());
if (pt>maxPt) pt=maxPt;
if (eta>maxEta) eta=maxEta;
float fr = fr_h->GetBinContent(fr_h->FindBin(pt,eta));
//float fre = fr_h->GetBinError(fr_h->FindBin(pt,eta));
float frW = fr/(1.-fr);
//std::cout << "fake rate=" << fr << " +/- " << fre << std::endl;
loop->makeFillHisto2D<TH2F,float>((pdgid==13?"fr_mu_close":"fr_el_close"),(pdgid==13?"fr_mu_close":"fr_el_close"),10,0.,50.,fobs[fo].pt(),5,0.,2.5,fabs(fobs[fo].eta()),weight_*frW);
}
}
}
void tests::testPtRel( looper* loop, float& weight_, DilepHyp& hyp, std::vector<Jet>& lepjets, TString& ll, TString& lt ) {
bool debug = false;
//make sure all cuts pass except isolation
if (isGoodLeptonNoIso(hyp.traiLep().pdgId(), hyp.traiLep().idx())) {
if (isFromW(hyp.traiLep().pdgId(),hyp.traiLep().idx())) {
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWtrail_"+lt+"_relIso03","hyp_ss_foFromWtrail_"+lt+"_relIso03",20,0.,2.,hyp.traiLep().relIso03(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWtrail_"+lt+"_iso03","hyp_ss_foFromWtrail_"+lt+"_iso03",10,0.,20.,hyp.traiLep().relIso03()*hyp.traiLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWtrail_"+lt+"_pt","hyp_ss_foFromWtrail_"+lt+"_pt",10,0.,200.,hyp.traiLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWtrail_"+lt+"_dxyPV","hyp_ss_foFromWtrail_"+lt+"_dxyPV",100,0,0.1,fabs(hyp.traiLep().dxyPV()),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWtrail_"+lt+"_dzPV","hyp_ss_foFromWtrail_"+lt+"_dzPV",100,0,0.5,fabs(hyp.traiLep().dzPV()),weight_);
} else {
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFaketrail_"+lt+"_relIso03","hyp_ss_foFaketrail_"+lt+"_relIso03",20,0.,2.,hyp.traiLep().relIso03(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFaketrail_"+lt+"_iso03","hyp_ss_foFaketrail_"+lt+"_iso03",10,0.,20.,hyp.traiLep().relIso03()*hyp.traiLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFaketrail_"+lt+"_pt","hyp_ss_foFaketrail_"+lt+"_pt",10,0.,200.,hyp.traiLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFaketrail_"+lt+"_dxyPV","hyp_ss_foFaketrail_"+lt+"_dxyPV",100,0,0.1,fabs(hyp.traiLep().dxyPV()),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFaketrail_"+lt+"_dzPV","hyp_ss_foFaketrail_"+lt+"_dzPV",100,0,0.5,fabs(hyp.traiLep().dzPV()),weight_);
}
}
//make sure all cuts pass except isolation
if (isGoodLeptonNoIso(hyp.leadLep().pdgId(), hyp.leadLep().idx())) {
if (isFromW(hyp.leadLep().pdgId(),hyp.leadLep().idx())) {
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_"+ll+"_relIso03","hyp_ss_foFromWlead_"+ll+"_relIso03",20,0.,2.,hyp.leadLep().relIso03(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_"+ll+"_iso03","hyp_ss_foFromWlead_"+ll+"_iso03",10,0.,20.,hyp.leadLep().relIso03()*hyp.leadLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_"+ll+"_pt","hyp_ss_foFromWlead_"+ll+"_pt",10,0.,200.,hyp.leadLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_"+lt+"_dxyPV","hyp_ss_foFromWlead_"+lt+"_dxyPV",100,0,0.1,fabs(hyp.leadLep().dxyPV()),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_"+lt+"_dzPV","hyp_ss_foFromWlead_"+lt+"_dzPV",100,0,0.5,fabs(hyp.leadLep().dzPV()),weight_);
if (isGoodLepton(hyp.leadLep().pdgId(), hyp.leadLep().idx())==0) {
if (ll=="mu") {
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_fail_"+ll+"_relIso03","hyp_ss_foFromWlead_fail_"+ll+"_relIso03",20,0.,2.,hyp.leadLep().relIso03(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_fail_"+ll+"_miniRelIso","hyp_ss_foFromWlead_fail_"+ll+"_miniRelIso",20,0.,1., muMiniRelIsoCMS3_EA(hyp.leadLep().idx(), ssEAversion),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_fail_"+ll+"_relIso02","hyp_ss_foFromWlead_fail_"+ll+"_relIso02",20,0.,1., muRelIsoCustomCone(hyp.leadLep().idx(),0.2,true,false),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_fail_"+ll+"_relIso02DB","hyp_ss_foFromWlead_fail_"+ll+"_relIso02DB",20,0.,1., muRelIsoCustomCone(hyp.leadLep().idx(),0.2,true,true),weight_);
} else {
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_fail_"+ll+"_relIso03","hyp_ss_foFromWlead_fail_"+ll+"_relIso03",20,0.,2.,hyp.leadLep().relIso03(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_fail_"+ll+"_miniRelIso","hyp_ss_foFromWlead_fail_"+ll+"_miniRelIso",20,0.,1., elMiniRelIsoCMS3_EA(hyp.leadLep().idx(), ssEAversion),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_fail_"+ll+"_relIso02","hyp_ss_foFromWlead_fail_"+ll+"_relIso02",20,0.,1., elRelIsoCustomCone(hyp.leadLep().idx(),0.2,true,false),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_fail_"+ll+"_relIso02DB","hyp_ss_foFromWlead_fail_"+ll+"_relIso02DB",20,0.,1., elRelIsoCustomCone(hyp.leadLep().idx(),0.2,true,true),weight_);
}
float ptrel = getPtRel(hyp.leadLep().pdgId(), hyp.leadLep().idx(), false, ssWhichCorr);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_"+ll+"_ptrel","hyp_ss_foFromWlead_"+ll+"_ptrel",10,0.,20.,ptrel,weight_);
float ptrelsub = getPtRel(hyp.leadLep().pdgId(), hyp.leadLep().idx(), true, ssWhichCorr);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_"+ll+"_ptrelsub","hyp_ss_foFromWlead_"+ll+"_ptrelsub",10,0.,20.,ptrelsub,weight_);
if (ptrelsub>14)
loop->makeFillHisto2D<TH2F,float>("hyp_ss_foFromWlead_"+ll+"_ptrel14_eta_vs_pt","hyp_ss_foFromWlead_"+ll+"_ptrel14_eta_vs_pt",10,0,100,hyp.leadLep().pt(),3,0,3,hyp.leadLep().eta(),weight_);
//test min dR between leptons and jets
int lepjetidx = -1;
if (debug) cout << "prompt non iso lepton with lepjets.size()=" << lepjets.size() << endl;
float mindr = 0.7;
int nlepjets_per_lep = 0;
for (unsigned int j=0;j<lepjets.size();++j) {
float dr = deltaR(lepjets[j].p4(),hyp.leadLep().p4());
if (debug) cout << "dr=" << dr << endl;
if (dr<0.7) nlepjets_per_lep++;
if (dr<mindr) {
mindr = dr;
lepjetidx = j;
}
}
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_"+ll+"_mindr","hyp_ss_foFromWlead_"+ll+"_mindr",20,0.,1.,mindr,weight_);
loop->makeFillHisto2D<TH2F,float>("hyp_ss_foFromWlead_"+ll+"_ptrel_vs_mindr","hyp_ss_foFromWlead_"+ll+"_ptrel_vs_mindr",10,0.,1.,mindr,10,0.,20.,ptrel,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_foFromWlead_"+ll+"_nlepjets","hyp_ss_foFromWlead_"+ll+"_nlepjets",10,0,10,nlepjets_per_lep,weight_);
loop->makeFillHisto2D<TH2F,float>("hyp_ss_foFromWlead_"+ll+"_mindr_vs_nlepjets","hyp_ss_foFromWlead_"+ll+"_mindr_vs_nlepjets",10,0,10,nlepjets_per_lep,10,0,1,mindr,weight_);
if (lepjetidx>=0) {
if (mindr<0.1) loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_"+ll+"_dPtMinDr01","hyp_ss_foFromWlead_"+ll+"_dPtMinDr01",20,-1.,1.,(lepjets[lepjetidx].pt()-hyp.leadLep().pt())/hyp.leadLep().pt(),weight_);
if (ll=="mu") loop->makeFillHisto2D<TH2F,float>("hyp_ss_foFromWlead_"+ll+"_ptrel_vs_lepfrac","hyp_ss_foFromWlead_"+ll+"_ptrel_vs_lepfrac",10,0.,1.,pfjets_muonE()[lepjets[lepjetidx].idx()]/(lepjets[lepjetidx].p4().E()*pfjets_undoJEC()[lepjets[lepjetidx].idx()]),10,0.,20.,ptrel,weight_);
else loop->makeFillHisto2D<TH2F,float>("hyp_ss_foFromWlead_"+ll+"_ptrel_vs_lepfrac","hyp_ss_foFromWlead_"+ll+"_ptrel_vs_lepfrac",10,0.,1.,pfjets_electronE()[lepjets[lepjetidx].idx()]/(lepjets[lepjetidx].p4().E()*pfjets_undoJEC()[lepjets[lepjetidx].idx()]),10,0.,20.,ptrel,weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFromWlead_"+ll+"_sinA","hyp_ss_foFromWlead_"+ll+"_sinA",10,0.,1.,ptrel/hyp.leadLep().pt(),weight_);
}
}
} else {
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_"+ll+"_relIso03","hyp_ss_foFakelead_"+ll+"_relIso03",20,0.,2.,hyp.leadLep().relIso03(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_"+ll+"_iso03","hyp_ss_foFakelead_"+ll+"_iso03",10,0.,20.,hyp.leadLep().relIso03()*hyp.leadLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_"+ll+"_pt","hyp_ss_foFakelead_"+ll+"_pt",10,0.,200.,hyp.leadLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_"+lt+"_dxyPV","hyp_ss_foFakelead_"+lt+"_dxyPV",100,0,0.1,fabs(hyp.leadLep().dxyPV()),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_"+lt+"_dzPV","hyp_ss_foFakelead_"+lt+"_dzPV",100,0,0.5,fabs(hyp.leadLep().dzPV()),weight_);
if (isGoodLepton(hyp.leadLep().pdgId(), hyp.leadLep().idx())==0) {
if (ll=="mu") {
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_fail_"+ll+"_relIso03","hyp_ss_foFakelead_fail_"+ll+"_relIso03",20,0.,2.,hyp.leadLep().relIso03(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_fail_"+ll+"_miniRelIso","hyp_ss_foFakelead_fail_"+ll+"_miniRelIso",20,0.,1., muMiniRelIsoCMS3_EA(hyp.leadLep().idx(), ssEAversion),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_fail_"+ll+"_relIso02","hyp_ss_foFakelead_fail_"+ll+"_relIso02",20,0.,1., muRelIsoCustomCone(hyp.leadLep().idx(),0.2,true,false),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_fail_"+ll+"_relIso02DB","hyp_ss_foFakelead_fail_"+ll+"_relIso02DB",20,0.,1., muRelIsoCustomCone(hyp.leadLep().idx(),0.2,true,true),weight_);
} else {
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_fail_"+ll+"_relIso03","hyp_ss_foFakelead_fail_"+ll+"_relIso03",20,0.,2.,hyp.leadLep().relIso03(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_fail_"+ll+"_miniRelIso","hyp_ss_foFakelead_fail_"+ll+"_miniRelIso",20,0.,1., elMiniRelIsoCMS3_EA(hyp.leadLep().idx(), ssEAversion),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_fail_"+ll+"_relIso02","hyp_ss_foFakelead_fail_"+ll+"_relIso02",20,0.,1., elRelIsoCustomCone(hyp.leadLep().idx(),0.2,true,false),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_fail_"+ll+"_relIso02DB","hyp_ss_foFakelead_fail_"+ll+"_relIso02DB",20,0.,1., elRelIsoCustomCone(hyp.leadLep().idx(),0.2,true,true),weight_);
}
float ptrel = getPtRel(hyp.leadLep().pdgId(), hyp.leadLep().idx(), false, ssWhichCorr);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_"+ll+"_ptrel","hyp_ss_foFakelead_"+ll+"_ptrel",10,0.,20.,ptrel,weight_);
float ptrelsub = getPtRel(hyp.leadLep().pdgId(), hyp.leadLep().idx(), true, ssWhichCorr);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_"+ll+"_ptrelsub","hyp_ss_foFakelead_"+ll+"_ptrelsub",10,0.,20.,ptrelsub,weight_);
if (ptrelsub>14)
loop->makeFillHisto2D<TH2F,float>("hyp_ss_foFakelead_"+ll+"_ptrel14_eta_vs_pt","hyp_ss_foFakelead_"+ll+"_ptrel14_eta_vs_pt",10,0,100,hyp.leadLep().pt(),3,0,3,hyp.leadLep().eta(),weight_);
//test min dR between leptons and jets
int lepjetidx = -1;
if (debug) cout << "prompt non iso lepton with lepjets.size()=" << lepjets.size() << endl;
float mindr = 0.7;
int nlepjets_per_lep = 0;
for (unsigned int j=0;j<lepjets.size();++j) {
float dr = deltaR(lepjets[j].p4(),hyp.leadLep().p4());
if (debug) cout << "dr=" << dr << endl;
if (dr<0.7) nlepjets_per_lep++;
if (dr<mindr) {
mindr = dr;
lepjetidx = j;
}
}
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_"+ll+"_mindr","hyp_ss_foFakelead_"+ll+"_mindr",20,0.,1.,mindr,weight_);
loop->makeFillHisto2D<TH2F,float>("hyp_ss_foFakelead_"+ll+"_ptrel_vs_mindr","hyp_ss_foFakelead_"+ll+"_ptrel_vs_mindr",10,0.,1.,mindr,10,0.,20.,ptrel,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_ss_foFakelead_"+ll+"_nlepjets","hyp_ss_foFakelead_"+ll+"_nlepjets",10,0,10,nlepjets_per_lep,weight_);
loop->makeFillHisto2D<TH2F,float>("hyp_ss_foFakelead_"+ll+"_mindr_vs_nlepjets","hyp_ss_foFakelead_"+ll+"_mindr_vs_nlepjets",10,0,10,nlepjets_per_lep,10,0,1,mindr,weight_);
if (lepjetidx>=0) {
if (mindr<0.1) loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_"+ll+"_dPtMinDr01","hyp_ss_foFakelead_"+ll+"_dPtMinDr01",20,-1.,1.,(lepjets[lepjetidx].pt()-hyp.leadLep().pt())/hyp.leadLep().pt(),weight_);
if (ll=="mu") loop->makeFillHisto2D<TH2F,float>("hyp_ss_foFakelead_"+ll+"_ptrel_vs_lepfrac","hyp_ss_foFakelead_"+ll+"_ptrel_vs_lepfrac",10,0.,1.,pfjets_muonE()[lepjets[lepjetidx].idx()]/(lepjets[lepjetidx].p4().E()*pfjets_undoJEC()[lepjets[lepjetidx].idx()]),10,0.,20.,ptrel,weight_);
else loop->makeFillHisto2D<TH2F,float>("hyp_ss_foFakelead_"+ll+"_ptrel_vs_lepfrac","hyp_ss_foFakelead_"+ll+"_ptrel_vs_lepfrac",10,0.,1.,pfjets_electronE()[lepjets[lepjetidx].idx()]/(lepjets[lepjetidx].p4().E()*pfjets_undoJEC()[lepjets[lepjetidx].idx()]),10,0.,20.,ptrel,weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_ss_foFakelead_"+ll+"_sinA","hyp_ss_foFakelead_"+ll+"_sinA",10,0.,1.,ptrel/hyp.leadLep().pt(),weight_);
}
}
}
}
}
void tests::testLeptonIdVariables( looper* loop, float& weight_, DilepHyp& hyp, TString& ll, TString& lt ) {
plotLeptonIdVariables( loop, weight_, "hyp_ss_alltrail_", hyp.traiLep().pdgId(), hyp.traiLep().idx());
plotLeptonIdVariables( loop, weight_, "hyp_ss_alllead_", hyp.leadLep().pdgId(), hyp.leadLep().idx());
}
void tests::plotLeptonIdVariables( looper* loop, float& weight_, TString prefix, int pdgId, unsigned int idx) {
if (abs(pdgId)==11) {
unsigned int elIdx = idx;
TString ebee = "EB";
if (fabs(els_etaSC().at(elIdx)) > 1.479) ebee = "EE";
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_pt",prefix+"_el_"+ebee+"_pt",20,0,100,els_p4().at(elIdx).pt(),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_eta",prefix+"_el_"+ebee+"_eta",20,-3,3,els_p4().at(elIdx).eta(),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_dEtaIn",prefix+"_el_"+ebee+"_dEtaIn",20,0,0.02,fabs(els_dEtaIn().at(elIdx)),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_dPhiIn",prefix+"_el_"+ebee+"_dPhiIn",20,0,0.1,fabs(els_dPhiIn().at(elIdx)),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_sIEtaIEta",prefix+"_el_"+ebee+"_sIEtaIEta",20,0,0.05,els_sigmaIEtaIEta_full5x5().at(elIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_hOverE",prefix+"_el_"+ebee+"_hOverE",20,0,0.2,els_hOverE().at(elIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_EoP",prefix+"_el_"+ebee+"_EoP",100,0,0.1,fabs( (1.0/els_ecalEnergy().at(elIdx)) - (els_eOverPIn().at(elIdx)/els_ecalEnergy().at(elIdx)) ),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_convflag",prefix+"_el_"+ebee+"_convflag",3,0,3,els_conv_vtx_flag().at(elIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_expinlay",prefix+"_el_"+ebee+"_expinlay",5,0,5,els_exp_innerlayers().at(elIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_3Qagree",prefix+"_el_"+ebee+"_3Qagree",3,0,3,els_isGsfCtfScPixChargeConsistent().at(elIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_relIso03",prefix+"_el_"+ebee+"_relIso03",20,0,1.,eleRelIso03(elIdx, SS),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_sip3d",prefix+"_el_"+ebee+"_sip3d",20,0,10,fabs(els_ip3d().at(elIdx))/els_ip3derr().at(elIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_dxyPV",prefix+"_el_"+ebee+"_dxyPV",100,0,0.1,fabs(els_dxyPV().at(elIdx)),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_el_"+ebee+"_dzPV",prefix+"_el_"+ebee+"_dzPV",100,0,0.5,fabs(els_dzPV().at(elIdx)),weight_);
} else {
unsigned int muIdx = idx;
bool isGlobal = true;
bool isTracker = true;
if (((mus_type().at(muIdx)) & (1<<1)) == 0) isGlobal = false;
if (((mus_type().at(muIdx)) & (1<<2)) == 0) isTracker = false;
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_pt",prefix+"_mu_pt",20,0,100,mus_p4().at(muIdx).pt(),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_eta",prefix+"_mu_eta",20,-3,3,mus_p4().at(muIdx).eta(),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_isPf",prefix+"_mu_isPf",2,0,2,mus_pid_PFMuon().at(muIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_isGl",prefix+"_mu_isGl",2,0,2,isGlobal,weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_isTk",prefix+"_mu_isTk",2,0,2,isTracker,weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_chi2",prefix+"_mu_chi2",100,0,20,mus_gfit_chi2().at(muIdx)/mus_gfit_ndof().at(muIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_vStaH",prefix+"_mu_vStaH",20,0,20,mus_gfit_validSTAHits().at(muIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_nMatchSt",prefix+"_mu_nMatchSt",20,0,20,mus_numberOfMatchedStations().at(muIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_vPixH",prefix+"_mu_vPixH",10,0,10,mus_validPixelHits().at(muIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_nLay",prefix+"_mu_nLay",20,0,20,mus_nlayers().at(muIdx),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_relIso03",prefix+"_mu_relIso03",20,0,1.,muRelIso03(muIdx, SS),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_dxyPV",prefix+"_mu_dxyPV",100,0,0.1,fabs(mus_dxyPV().at(muIdx)),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_dzPV",prefix+"_mu_dzPV",100,0,0.5,fabs(mus_dzPV().at(muIdx)),weight_);
loop->makeFillHisto1D<TH1F,float>(prefix+"_mu_sip3d",prefix+"_mu_sip3d",20,0,10,fabs(mus_ip3d().at(muIdx))/mus_ip3derr().at(muIdx),weight_);
}
}
void tests::testBtag( looper* loop, float& weight_, std::vector<Jet>& alljets ) {
int genbjets = 0;
int genbjets_pt20 = 0;
int genbjets_pt25 = 0;
int genbjets_pt30 = 0;
int genbjets_pt35 = 0;
int genbjets_pt40 = 0;
vector<Jet> jetsbmatch;
for (unsigned int j=0;j<alljets.size();++j) {
Jet jet = alljets[j];
if (abs(jet.mc3_id())==5) {
genbjets++;
jetsbmatch.push_back(jet);
if (jet.pt()>20) {
genbjets_pt20++;
if (jet.pt()>25) genbjets_pt25++;
if (jet.pt()>30) genbjets_pt30++;
if (jet.pt()>35) genbjets_pt35++;
if (jet.pt()>40) genbjets_pt40++;
loop->makeFillHisto1D<TH1F,float>("hyp_hihi_genbjets_csv","hyp_hihi_genbjets_csv",50,0,1.,jet.csv(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_hihi_genbjets_tche","hyp_hihi_genbjets_tche",50,-5.,5.,tas::getbtagvalue("pfTrackCountingHighEffBJetTags",jet.idx()),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_hihi_genbjets_tchp","hyp_hihi_genbjets_tchp",50,-5.,5.,tas::getbtagvalue("pfTrackCountingHighPurBJetTags",jet.idx()),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_hihi_genbjets_jbp","hyp_hihi_genbjets_jbp" ,50,0,10. ,tas::getbtagvalue("pfJetBProbabilityBJetTags",jet.idx()) ,weight_);
}
} else {
if (jet.pt()>20) {
loop->makeFillHisto1D<TH1F,float>("hyp_hihi_gennobjets_csv","hyp_hihi_gennobjets_csv",50,0,1.,jet.csv(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_hihi_gennobjets_tche","hyp_hihi_gennobjets_tche",50,-5.,5.,tas::getbtagvalue("pfTrackCountingHighEffBJetTags",jet.idx()),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_hihi_gennobjets_tchp","hyp_hihi_gennobjets_tchp",50,-5.,5.,tas::getbtagvalue("pfTrackCountingHighPurBJetTags",jet.idx()),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_hihi_gennobjets_jbp","hyp_hihi_gennobjets_jbp" ,50,0,10. ,tas::getbtagvalue("pfJetBProbabilityBJetTags",jet.idx()) ,weight_);
/*
OBJ: TNamed pfjets_combinedSecondaryVertexBJetTag floats_pfJetMaker_pfjetscombinedSecondaryVertexBJetTag_CMS2.obj : 0 at: 0x7fb6f3a4bf20
OBJ: TNamed pfjets_jetBProbabilityBJetTag floats_pfJetMaker_pfjetsjetBProbabilityBJetTag_CMS2.obj : 0 at: 0x7fb6f3a4c540
OBJ: TNamed pfjets_jetProbabilityBJetTag floats_pfJetMaker_pfjetsjetProbabilityBJetTag_CMS2.obj : 0 at: 0x7fb6f3a4c600
OBJ: TNamed pfjets_simpleSecondaryVertexHighEffBJetTag floats_pfJetMaker_pfjetssimpleSecondaryVertexHighEffBJetTag_CMS2.obj : 0 at: 0x7fb6f3a4ca80
OBJ: TNamed pfjets_trackCountingHighEffBJetTag floats_pfJetMaker_pfjetstrackCountingHighEffBJetTag_CMS2.obj : 0 at: 0x7fb6f3a4cc40
OBJ: TNamed pfjets_trackCountingHighPurBJetTag floats_pfJetMaker_pfjetstrackCountingHighPurBJetTag_CMS2.obj : 0 at: 0x7fb6f3a4cd10
*/
}
}
}
loop->makeFillHisto1D<TH1F,int>("hyp_hihi_genbjets","hyp_hihi_genbjets",8,0,8,genbjets,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_hihi_genbjets_pt20","hyp_hihi_genbjets_pt20",8,0,8,genbjets_pt20,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_hihi_genbjets_pt25","hyp_hihi_genbjets_pt25",8,0,8,genbjets_pt25,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_hihi_genbjets_pt30","hyp_hihi_genbjets_pt30",8,0,8,genbjets_pt30,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_hihi_genbjets_pt35","hyp_hihi_genbjets_pt35",8,0,8,genbjets_pt35,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_hihi_genbjets_pt40","hyp_hihi_genbjets_pt40",8,0,8,genbjets_pt40,weight_);
std::sort(jetsbmatch.begin(),jetsbmatch.end(),jetptsort);
if (jetsbmatch.size()>0) loop->makeFillHisto1D<TH1F,float>("hyp_hihi_genbjets_pt0","hyp_hihi_genbjets_pt0",40,0,200,jetsbmatch[0].pt(),weight_);
if (jetsbmatch.size()>1) loop->makeFillHisto1D<TH1F,float>("hyp_hihi_genbjets_pt1","hyp_hihi_genbjets_pt1",40,0,200,jetsbmatch[1].pt(),weight_);
if (jetsbmatch.size()>2) loop->makeFillHisto1D<TH1F,float>("hyp_hihi_genbjets_pt2","hyp_hihi_genbjets_pt2",40,0,200,jetsbmatch[2].pt(),weight_);
//now check the performance as a function of the btagging algo & discriminator
}
void tests::makeSRplots( looper* loop, float& weight_, TString label, int& br, int& sr, DilepHyp& hyp,
float& ht, float& met, float& mtmin, int& type, std::vector<Lep>& goodleps, std::vector<Lep>& fobs,
std::vector<Lep>& vetoleps, std::vector<Jet>& jets, std::vector<Jet>& alljets, std::vector<Jet>& btags,
TString& ll, TString& lt ) {
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_br","hyp_"+label+"_br",40,0,40,br,weight_);
//if ( isFromWZ(hyp.traiLep()) && isFromWZ(hyp.leadLep()) ) {
// loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_br_fromWZ","hyp_"+label+"_br_fromWZ",40,0,40,br,weight_);
//}
if (sr>0) {
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_sr","hyp_"+label+"_sr",40,0,40,br,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_sr","hyp_"+label+"_sr",40,0,40,sr,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_excl_sr","hyp_"+label+"_excl_sr",40,0,40,sr,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_excl_sr_mt100","hyp_"+label+"_excl_sr_mt100",40*2,0,40*2,sr+40*(mtmin>100),weight_);
int srt1 = signalRegion(jets.size(), btags.size(), met, ht, 5, 11, 11, 200, 600); //looks like we assumed pt == high, so gonna do the same for id. -AG
int srt2 = signalRegion(jets.size(), btags.size(), met, ht, 6, 11, 11, 250, 800);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_excl_srt1","hyp_"+label+"_excl_srt1",40,0,40,srt1,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_excl_srt2","hyp_"+label+"_excl_srt2",40,0,40,srt2,weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_excl_srt1_mt100","hyp_"+label+"_excl_srt1_mt100",40*2,0,40*2,srt1+40*(mtmin>100),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_excl_srt2_mt100","hyp_"+label+"_excl_srt2_mt100",40*2,0,40*2,srt2+40*(mtmin>100),weight_);
//if ( isFromWZ(hyp.traiLep()) && isFromWZ(hyp.leadLep()) ) {
// loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_sr_fromWZ","hyp_"+label+"_sr_fromWZ",40,0,40,br,weight_);
// loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_sr_fromWZ","hyp_"+label+"_sr_fromWZ",40,0,40,sr,weight_);
//}
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_charge","hyp_"+label+"_charge",7,-3.5,3.5,hyp.charge(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_njets","hyp_"+label+"_njets",8,0,8,jets.size(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_nbtag","hyp_"+label+"_nbtag",8,0,8,btags.size(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_ht","hyp_"+label+"_ht",30,80,1580,ht,weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_met","hyp_"+label+"_met",20,0,500,met,weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_mll","hyp_"+label+"_mll",100,0,1000,hyp.p4().mass(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_ptll","hyp_"+label+"_ptll",100,0,1000,hyp.p4().pt(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_type","hyp_"+label+"_type",5,0,5,type,weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_ptlead","hyp_"+label+"_ptlead",40,0,200,hyp.leadLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_pttrai","hyp_"+label+"_pttrai",40,0,200,hyp.traiLep().pt(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_etalead","hyp_"+label+"_etalead",10,0,2.5,fabs(hyp.leadLep().eta()),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_etatrai","hyp_"+label+"_etatrai",10,0,2.5,fabs(hyp.traiLep().eta()),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_mtmin","hyp_"+label+"_mtmin",15,0,300,mtmin,weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_ngleps","hyp_"+label+"_ngleps",10,0,10,goodleps.size(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_nfobs","hyp_"+label+"_nfobs",10,0,10,fobs.size(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_nvetos","hyp_"+label+"_nvetos",10,0,10,vetoleps.size(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_trail_"+lt+"_relIso03","hyp_"+label+"_trail_"+lt+"_relIso03",100,0.,1.,hyp.traiLep().relIso03(),weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_lead_"+ll+"_relIso03","hyp_"+label+"_lead_"+ll+"_relIso03",100,0.,1.,hyp.leadLep().relIso03(),weight_);
loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_leadjetpt","hyp_"+label+"_leadjetpt",50,0,1000,jets[0].pt(),weight_);
if (btags.size()>0) loop->makeFillHisto1D<TH1F,int>("hyp_"+label+"_leadbtagpt","hyp_"+label+"_leadbtagpt",50,0,1000,btags[0].pt(),weight_);
//float ld = computeLD(hyp, alljets, met, mtmin);
//loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_ld","hyp_"+label+"_ld",30,0,3.0,ld,weight_);
//loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_ld5bins","hyp_"+label+"_ld5bins",5,0,1.6,ld,weight_);
//loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_ld10bins","hyp_"+label+"_ld10bins",10,0,1.6,ld,weight_);
//loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_excl_srld","hyp_"+label+"_excl_srld",30*4,0,3.0*4,std::min(ld,float(3.0))+3.0*btags.size(),weight_);
//loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_excl_srld5bins","hyp_"+label+"_excl_srld5bins",5*4,0,1.6*4.,std::min(ld,float(1.6))+1.6*btags.size(),weight_);
//loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_excl_srld10bins","hyp_"+label+"_excl_srld10bins",10*4,0,1.6*4.,std::min(ld,float(1.6))+1.6*btags.size(),weight_);
//ptrel
float ptRelLead = getPtRel(hyp.leadLep().pdgId(), hyp.leadLep().idx(), true, ssWhichCorr);
float ptRelTrai = getPtRel(hyp.traiLep().pdgId(), hyp.traiLep().idx(), true, ssWhichCorr);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_ptRellead","hyp_"+label+"_ptRellead",10,0,20,ptRelLead,weight_);
loop->makeFillHisto1D<TH1F,float>("hyp_"+label+"_ptReltrai","hyp_"+label+"_ptReltrai",10,0,20,ptRelTrai,weight_);
loop->makeFillHisto2D<TH2F,float>("hyp_"+label+"_ptRellead_vs_iso_"+ll,"hyp_"+label+"_ptRellead_vs_iso_"+ll,10,0.,1.,hyp.leadLep().relIso03(), 15,0.,30,ptRelLead,weight_);
loop->makeFillHisto2D<TH2F,float>("hyp_"+label+"_ptReltrai_vs_iso_"+lt,"hyp_"+label+"_ptReltrai_vs_iso_"+lt,10,0.,1.,hyp.traiLep().relIso03(), 15,0.,30,ptRelTrai,weight_);
}
}
|
d9a52fae4c02fcc1989e2d81ba7d93be30760b03
|
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
|
/third_party/WebKit/Source/core/paint/BlockFlowPainter.cpp
|
32e93aaf53ccd58dc224a5b6e1a9aa2877189c7d
|
[
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] |
permissive
|
wzyy2/chromium-browser
|
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
|
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
|
refs/heads/master
| 2022-11-23T20:25:08.120045
| 2018-01-16T06:41:26
| 2018-01-16T06:41:26
| 117,618,467
| 3
| 2
|
BSD-3-Clause
| 2022-11-20T22:03:57
| 2018-01-16T02:09:10
| null |
UTF-8
|
C++
| false
| false
| 3,141
|
cpp
|
BlockFlowPainter.cpp
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/paint/BlockFlowPainter.h"
#include "core/layout/FloatingObjects.h"
#include "core/layout/LayoutBlockFlow.h"
#include "core/paint/BlockPainter.h"
#include "core/paint/LineBoxListPainter.h"
#include "core/paint/ObjectPainter.h"
#include "core/paint/PaintInfo.h"
namespace blink {
void BlockFlowPainter::PaintContents(const PaintInfo& paint_info,
const LayoutPoint& paint_offset) {
// Avoid painting descendants of the root element when stylesheets haven't
// loaded. This eliminates FOUC. It's ok not to draw, because later on, when
// all the stylesheets do load, styleResolverMayHaveChanged() on Document will
// trigger a full paint invalidation.
if (layout_block_flow_.GetDocument().DidLayoutWithPendingStylesheets() &&
!layout_block_flow_.IsLayoutView())
return;
if (!layout_block_flow_.ChildrenInline()) {
BlockPainter(layout_block_flow_).PaintContents(paint_info, paint_offset);
return;
}
if (ShouldPaintDescendantOutlines(paint_info.phase))
ObjectPainter(layout_block_flow_)
.PaintInlineChildrenOutlines(paint_info, paint_offset);
else
LineBoxListPainter(layout_block_flow_.LineBoxes())
.Paint(layout_block_flow_, paint_info, paint_offset);
}
void BlockFlowPainter::PaintFloats(const PaintInfo& paint_info,
const LayoutPoint& paint_offset) {
if (!layout_block_flow_.GetFloatingObjects())
return;
DCHECK(paint_info.phase == kPaintPhaseFloat ||
paint_info.phase == kPaintPhaseSelection ||
paint_info.phase == kPaintPhaseTextClip);
PaintInfo float_paint_info(paint_info);
if (paint_info.phase == kPaintPhaseFloat)
float_paint_info.phase = kPaintPhaseForeground;
for (const auto& floating_object :
layout_block_flow_.GetFloatingObjects()->Set()) {
if (!floating_object->ShouldPaint())
continue;
const LayoutBox* floating_layout_object =
floating_object->GetLayoutObject();
// TODO(wangxianzhu): Should this be a DCHECK?
if (floating_layout_object->HasSelfPaintingLayer())
continue;
// FIXME: LayoutPoint version of xPositionForFloatIncludingMargin would make
// this much cleaner.
LayoutPoint child_point =
layout_block_flow_.FlipFloatForWritingModeForChild(
*floating_object,
LayoutPoint(paint_offset.X() +
layout_block_flow_.XPositionForFloatIncludingMargin(
*floating_object) -
floating_layout_object->Location().X(),
paint_offset.Y() +
layout_block_flow_.YPositionForFloatIncludingMargin(
*floating_object) -
floating_layout_object->Location().Y()));
ObjectPainter(*floating_layout_object)
.PaintAllPhasesAtomically(float_paint_info, child_point);
}
}
} // namespace blink
|
bbefd06f93ea970b18d5712d04e272840214848d
|
78b313d5604fa4f6e34ae114f36e11f7d20f3b75
|
/OLA1/Project1/Roster.cpp
|
086e481ffaa24d2df809bf0372f1b0c472372271
|
[] |
no_license
|
MartysRepos/CSCI3110
|
f85bca648ffb1940b8e20fdf4af8e0d3085ecc7c
|
f75ca501aa8d649d046eae8b9280821d3c9b2d33
|
refs/heads/master
| 2021-01-11T18:12:36.444339
| 2017-01-20T02:15:09
| 2017-01-20T02:15:09
| 79,516,039
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,276
|
cpp
|
Roster.cpp
|
////Author: Martavious Dorsey
////Project: OLA1
////Due date: September 7, 2016
////Description: The Roster.cpp file is where the methods from Roster.h files are being implemented
#include <iostream>
#include <string>
#include <fstream>
#include "Roster.h"
using namespace std;
//Creates an empty roster before the file is being read in
Roster::Roster(std::string cName) {
m_studentNum = 0;
m_courseName = cName;
}
//This function reads the student information from the file
void Roster::readStudentRecord(std::string info) {
ifstream myIn;
string topLine;
myIn.open(info);
getline(myIn, topLine);
int count = 0;
string Id;
int num;
myIn >> Id;
while (myIn) {
m_students[m_studentNum].setID(Id);
myIn >> num;
m_students[m_studentNum].changeScore(Student::ScoreType::CLA, num);
myIn >> num;
m_students[m_studentNum].changeScore(Student::ScoreType::OLA, num);
myIn >> num;
m_students[m_studentNum].changeScore(Student::ScoreType::QUIZ, num);
myIn >> num;
m_students[m_studentNum].changeScore(Student::ScoreType::HOMEWORK, num);
myIn >> num;
m_students[m_studentNum].changeScore(Student::ScoreType::EXAM, num);
myIn >> num;
m_students[m_studentNum].changeScore(Student::ScoreType::BONUS, num);
m_studentNum++;
myIn >> Id;
}
}
//This function finds a particular ID from the file and
//prints all the different scores associated with that student
void Roster::findID(std::string cNumber){
for (int i = 0; i < m_studentNum; i++){
//compares the ID enter the from the user to the ID thats inside the file
if (cNumber == m_students[i].getID()){
//If found the student ID along with the scores of that student is printed
m_students[i].printIndividualStudentInfo();
return;
}
}
cout << "not found";
return;
}
//This function prints out all the student information that is contained in the file
void Roster::printAllStudentInfo(){
//The for loop keeps up with all the student information
//read from the file and stores it
for (int j = 0; j < m_studentNum; j++){
//once the for loop gets done storing them,
//then this line below prints all information stored in that array
m_students[j].printIndividualStudentInfo();
}
}
|
f19af7f22d4abd99f250cce7fa6d2768ebb99a43
|
03e9fcc01ab5bf150f88f19798c00ce3026aa495
|
/host.cpp
|
48cd7c1181a1c25628a9de3cec24c2974bfa8c26
|
[] |
no_license
|
jtforrestal/3d3Project2
|
44dd638b8dd995a47b87608ec343459cd89c6706
|
7f9fa9b0aefce2b6639979c38b7b8ccd7f6d61fb
|
refs/heads/master
| 2021-11-03T08:31:41.856255
| 2019-04-06T22:12:14
| 2019-04-06T22:12:14
| 177,126,141
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,593
|
cpp
|
host.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <assert.h>
#include <string>
#include <fstream>
#include <iostream>
#include <limits.h>
#include <chrono>
#include <future>
#include <sstream>
#include <iterator>
#include <map>
#define MAXBUFLEN 2048
#define DESTPEER "10001" // hardcoded for now...
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main (int argc, char* argv[]){
// -----------------------------------------------------------
// IMPORTANT NODE VARIABLES
// -----------------------------------------------------------
char *nodename = argv[1]; // NAME OF NODE
char *nodeport = "10010"; // PORT OF NODE
// -----------------------------------------------------------
// SET UP LISTENING SOCKET
// -----------------------------------------------------------
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
ssize_t numbytes;
struct sockaddr_storage their_addr;
char buf[MAXBUFLEN];
socklen_t addr_len;
char s[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, nodeport, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("listener: socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("listener: bind");
continue;
}
// allow others to reuse the address
int yes = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
perror("setsockopt");
return 1;
}
break;
}
if (p == NULL) {
fprintf(stderr, "listener: failed to bind socket\n");
return 2;
}
// *** NOT SURE ABOUT FREEING ADDRINFO HERE...
freeaddrinfo(servinfo);
// -----------------------------------------------------------
// PING NEIGHBOURS WITH CURRENT TABLE:
// -----------------------------------------------------------
if ((rv = getaddrinfo("localhost", DESTPEER, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket(unused?) -> get address
for(p = servinfo; p != NULL; p = p->ai_next) {
if (socket(p->ai_family, p->ai_socktype,
p->ai_protocol) == -1) {
perror("talker: socket");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "talker: failed to create socket\n");
return 2;
}
std::string msg = "Type:DATA\nSrc_Node:H\nF,0\nHello World!\n";
msg = msg +"Z,";
std::cout << msg << endl;
if ((numbytes = sendto(sockfd, msg.c_str(), msg.length(), 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
return 0;
}
|
b98d4271ea1320650954e59b2d0da004abebe384
|
5d952b15bb37e8a25f80b853b5a859569b7438a3
|
/yhgui/Component.cpp
|
20fe4bb874eb5f6a6b2d5d7d33449cbdcdf70801
|
[] |
no_license
|
trarck/yhgui
|
097a73c8c73b865beee95a81f95ae7ab2fc527fd
|
7a76ac984dfc6b23632574d9a4adfc0620158533
|
refs/heads/master
| 2021-01-13T07:38:21.359453
| 2013-12-26T12:29:44
| 2013-12-26T12:29:44
| 15,388,969
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,943
|
cpp
|
Component.cpp
|
#include "Component.h"
#include "event/UIEventNames.h"
NS_CC_YHGUI_BEGIN
Component::Component()
:m_name("")
,m_enabled(true)
,m_touchInside(false)
,m_touchPriority(0)
,m_needBubbles(true)
{
}
Component::~Component()
{
}
//void Component::onEnter()
//{
// if(m_enabled){
// this->registerWithTouchDispatcher();
// }
// CCNode::onEnter();
//}
//
//void Component::onExit()
//{
// if (m_enabled) {
// this->unregisterWithTouchDispatcher();
// }
// CCNode::onExit();
//}
/**
* 消除注册的事件
*/
void Component::cleanup()
{
UIEventListenerManager::sharedUIEventListenerManager()->removeEventListener(this);
CCNode::cleanup();
}
void Component::setEnabled(bool enabled)
{
if (m_enabled!=enabled) {
m_enabled = enabled;
// if (m_bRunning) {
// if (m_enabled) {
// this->registerWithTouchDispatcher();
// }else{
// this->unregisterWithTouchDispatcher();
// }
// }
}
}
void Component::setTouchPriority(int touchPriority)
{
m_touchPriority = touchPriority;
CCDirector::sharedDirector()->getTouchDispatcher()->setPriority(touchPriority, this);
}
void Component::registerWithTouchDispatcher(void)
{
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,m_touchPriority, true);
}
void Component::unregisterWithTouchDispatcher(void)
{
CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}
bool Component::isTouchInside(CCTouch* touch)
{
CCPoint touchLocation = touch->getLocation(); // Get the touch position
touchLocation = this->getParent()->convertToNodeSpace(touchLocation);
CCRect bBox=boundingBox();
return bBox.containsPoint(touchLocation);
}
/**
* 点是否在物体内
*/
bool Component::isPointInside(const CCPoint& point)
{
CCPoint localPoint=this->convertToNodeSpace(point);
CCSize contentSize=this->getContentSize();
return localPoint.x>=0 && localPoint.x<=contentSize.width && localPoint.y>=0 &&localPoint.y<=contentSize.height;
}
bool Component::hasVisibleParents()
{
CCNode* pParent = this->getParent();
for( CCNode *c = pParent; c != NULL; c = c->getParent() )
{
if( !c->isVisible() )
{
return false;
}
}
return true;
}
bool Component::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
// if (!isTouchInside(pTouch) || !isEnabled() || !isVisible() || !hasVisibleParents() )
// {
// return false;
// }
m_touchInside=true;
//touch enter
this->trigger(kEventNameTouchMoveEnter,NULL,m_needBubbles);
//touch down
this->trigger(kEventNameTouchDown,NULL,m_needBubbles);
return true;
}
void Component::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
//如果touch begin不返回true,则不会进入touch move里。所以这里已经是pressed
bool isTouchMoveInside = isTouchInside(pTouch);
if (isTouchMoveInside) {
//如果已经在里面则不触发move enter。
if (!m_touchInside) {
m_touchInside=true;
//按钮事件,不需要冒泡
this->trigger(kEventNameTouchMoveEnter,NULL,m_needBubbles);
}
}else if(m_touchInside){
m_touchInside=false;
//touch exit
this->trigger(kEventNameTouchMoveExit,NULL,m_needBubbles);
}
//touch move
this->trigger(kEventNameTouchMove, CCBool::create(isTouchMoveInside),m_needBubbles);
}
void Component::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
if (isTouchInside(pTouch)) {
//touch up inside
this->trigger(kEventNameTouchUpInside,NULL,m_needBubbles);
}else{
//touch up outside
this->trigger(kEventNameTouchUpOutside,NULL,m_needBubbles);
}
}
void Component::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent)
{
}
NS_CC_YHGUI_END
|
dcc7b2bddd320d1e99bcbca81e5783709007b390
|
7b27b844bb2ab3c46162fe1005608cebbe9f657b
|
/syx/syx/SyxInterface.h
|
c7445d45b3e8015d45483df2d9165e5cd15b1126
|
[] |
no_license
|
tristanschneider/syx
|
af36254469e7f77a134431a0a7d2601c83d4d580
|
95d9573339fe11a886ab6ca8060455357de4fdf0
|
refs/heads/main
| 2023-08-31T21:36:36.724283
| 2023-08-28T06:52:47
| 2023-08-28T06:52:47
| 97,346,704
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,593
|
h
|
SyxInterface.h
|
#pragma once
namespace Syx {
struct Vec3;
struct SyxOptions {
enum SIMD {
PositionIntegration = 1 << 0,
VelocityIntegration = 1 << 1,
SupportPoints = 1 << 2,
Transforms = 1 << 3,
ConstraintSolve = 1 << 4,
GJK = 1 << 5,
EPA = 1 << 6
};
enum Debug {
DrawModels = 1 << 0,
DrawPersonalBBs = 1 << 1,
DrawCollidingPairs = 1 << 2,
DrawGJK = 1 << 3,
DrawEPA = 1 << 4,
DrawNewContact = 1 << 5,
DrawManifolds = 1 << 6,
DisableCollision = 1 << 7,
DrawBroadphase = 1 << 8,
DrawIslands = 1 << 9,
DrawSleeping = 1 << 10,
DrawJoints = 1 << 11,
DrawCenterOfMass = 1 << 11,
};
int mSimdFlags = 0;
int mDebugFlags = 0;
int mTest = 0;
};
namespace Interface {
SyxOptions getOptions(void);
void setColor(float r, float g, float b);
void drawLine(const Vec3& start, const Vec3& end);
void drawVector(const Vec3& start, const Vec3& direction);
void drawSphere(const Vec3& center, float radius, const Vec3& right, const Vec3& up);
// Size is whole size, not half size
void drawCube(const Vec3& center, const Vec3& size, const Vec3& right, const Vec3& up);
// Simple representation of a point, like a cross where size is the length from one side to the other
void drawPoint(const Vec3& point, float size);
// 16 byte aligned
void* allocAligned(size_t size);
void freeAligned(void* p);
void* allocUnaligned(size_t size);
void freeUnaligned(void* p);
void log(const std::string& message);
}
}
|
af1460be5e2f960c8a062d31a6cb478a6e175476
|
5650f832143151664e978aabcaed4fc9098a26bb
|
/win/WIN_Window.h
|
2da83b7d3fb2b07bb58bb6bf993b6d152e3f019c
|
[] |
no_license
|
amyharris3/paint
|
ac6ff346c392464c038b2869b2e2d290613d0fe2
|
4b36dddda46e20f105d0439953865a52f243fb0e
|
refs/heads/master
| 2020-12-15T13:16:35.832045
| 2020-02-14T10:57:51
| 2020-02-14T10:57:51
| 235,114,101
| 0
| 0
| null | 2020-02-13T14:19:21
| 2020-01-20T13:59:53
|
C
|
UTF-8
|
C++
| false
| false
| 806
|
h
|
WIN_Window.h
|
#pragma once
#include "GFX_Rectangle.h"
#include "WIN_Container.h"
#include "WIN_FreeLayout.h"
//struct SDL_Window;
//struct SDL_Renderer;
//struct SDL_Surface;
namespace win
{
class Layout;
class FreeLayout;
class TableLayout;
class Window : public Container
{
public:
Window() = delete;
virtual ~Window() = default;
Window(const gfx::Rectangle& rect, const char* name);
Window(const gfx::Rectangle& rect, const char* name, std::shared_ptr<Layout> layout);
Window(Window const& that) = delete;
Window(Window && that) = delete;
Window & operator=(Window const& that) = delete;
Window& operator=(Window && that) = delete;
void draw(win::SDLRenderer* renderer) override;
private:
gfx::Rectangle rect_;
void updateAndRerender(win::SDLRenderer* renderer) override;
};
}
|
952cae21a8e896393c435da58d32b8734e768643
|
518892dbb2c4c57a26a21d123340f772787fe8bc
|
/重定义函数/Circle.h
|
bc040ac0e3c0e3eca6ab5dbf777cdacb28893c1b
|
[] |
no_license
|
forlqy/study
|
d5ba2cc7677ac1bc65134d077a27f93364a8a009
|
a31976c054a525a168d8db9cd833a12645f64964
|
refs/heads/master
| 2023-08-23T02:55:35.025706
| 2021-09-19T11:01:35
| 2021-09-19T11:01:35
| 397,440,754
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 365
|
h
|
Circle.h
|
#pragma once
#include "Shape.h"
class Circle : public Shape{//类的声明与实现分离只涉及到函数,不涉及到类的数据成员
public:
Circle();
Circle(double radius_);
Circle(double radius_, Color color_, bool filled_);
double getArea();
double getRadius() const;
void setRadius(double radius);
string toString();
private:
double radius;
};
|
5bf88bde3e764c6359e4d5cbeb7dc7a522ccdccf
|
93becb0e207e95d75dbb05c92c08c07402bcc492
|
/yosupo/point_set_range_composite.cpp
|
5aae8c960787201c1400474793f0174d7edf2d77
|
[] |
no_license
|
veqcc/atcoder
|
2c5f12e12704ca8eace9e2e1ec46a354f1ec71ed
|
cc3b30a818ba2f90c4d29c74b4d2231e8bca1903
|
refs/heads/master
| 2023-04-14T21:39:29.705256
| 2023-04-10T02:31:49
| 2023-04-10T02:31:49
| 136,691,016
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,997
|
cpp
|
point_set_range_composite.cpp
|
#include <functional>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <vector>
#include <random>
#include <bitset>
#include <queue>
#include <cmath>
#include <stack>
#include <set>
#include <map>
typedef long long ll;
using namespace std;
const ll MOD = 998244353;
template <typename T>
class SegmentTree {
using F = function<T(T, T)>;
int n;
F f;
T t;
vector <T> dat;
public:
SegmentTree(F f, T t) : f(f), t(t) {}
void init(int n_) {
n = 1;
while (n < n_) n <<= 1;
dat.assign(n << 1, t);
}
void build(const vector <T> &v) {
auto n_ = (int)v.size();
init(n_);
for (int i = 0; i < n_; i++) dat[n + i] = v[i];
for (int i = n - 1; i > 0; i--) dat[i] = f(dat[(i << 1) | 0], dat[(i << 1) | 1]);
}
void set_val(int k, T x) {
dat[k += n] = x;
while (k >>= 1) dat[k] = f(dat[(k << 1) | 0], dat[(k << 1) | 1]);
}
T query(int a, int b) {
T vl = t, vr = t;
for (int l = a + n, r = b + n; l < r; l >>= 1, r >>= 1) {
if (l & 1) vl = f(vl, dat[l++]);
if (r & 1) vr = f(dat[--r], vr);
}
return f(vl, vr);
}
};
typedef pair <ll, ll> P;
int main() {
cin.sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, q;
cin >> n >> q;
auto f = [](P a, P b) {
ll x = a.first * b.first % MOD;
ll y = (b.first * a.second + b.second) % MOD;
return P(x, y);
};
SegmentTree<P> seg(f, P(1, 0));
vector <P> vec(n);
for (int i = 0; i < n; i++) {
ll a, b;
cin >> a >> b;
vec[i] = P(a, b);
}
seg.build(vec);
while (q--) {
ll t, x, y, z;
cin >> t >> x >> y >> z;
if (t == 0) {
seg.set_val(x, P(y, z));
} else {
P p = seg.query(x, y);
cout << (p.first * z + p.second) % MOD << endl;
}
}
return 0;
}
|
a23d533d0021ccb13c891fa714030f11b41711b3
|
afee2250a162d9258f4a6eb49375290346d24557
|
/plugins/trisoup_gl/src/AbstractTriMeshDataSource.h
|
43bff0223d5c1c5985c84007ac3e84c52ea2243a
|
[
"BSD-3-Clause"
] |
permissive
|
sellendk/megamol
|
bbaa4ce9b1e78980017df25968559b86ff6e8684
|
03748a31064b06186ae2a14e34313b776c60b80f
|
refs/heads/master
| 2023-01-11T06:22:23.320033
| 2022-12-07T15:35:31
| 2022-12-07T15:35:31
| 208,452,969
| 0
| 0
|
BSD-3-Clause
| 2021-07-13T11:49:32
| 2019-09-14T14:36:44
|
C++
|
UTF-8
|
C++
| false
| false
| 2,595
|
h
|
AbstractTriMeshDataSource.h
|
/*
* AbstractTriMeshDataSource.h
*
* Copyright (C) 2010 by Sebastian Grottel
* Copyright (C) 2010 by VISUS (Universitaet Stuttgart)
* Alle Rechte vorbehalten.
*/
#ifndef MMTRISOUPPLG_ABSTRACTTRIMESHDATASOURCE_H_INCLUDED
#define MMTRISOUPPLG_ABSTRACTTRIMESHDATASOURCE_H_INCLUDED
#if (defined(_MSC_VER) && (_MSC_VER > 1000))
#pragma once
#endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */
#include "geometry_calls/LinesDataCall.h"
#include "geometry_calls_gl/CallTriMeshDataGL.h"
#include "mmcore/CalleeSlot.h"
#include "mmcore/Module.h"
#include "mmcore/param/ParamSlot.h"
#include "vislib/Array.h"
#include "vislib/String.h"
#include "vislib/math/Cuboid.h"
namespace megamol {
namespace trisoup_gl {
/**
* Abstract base class for tri-mesh data source classes
*/
class AbstractTriMeshDataSource : public core::Module {
public:
/** Ctor */
AbstractTriMeshDataSource(void);
/** Dtor */
virtual ~AbstractTriMeshDataSource(void);
protected:
/** Alias for mesh class */
typedef megamol::geocalls_gl::CallTriMeshDataGL::Mesh Mesh;
/** Alias for material class */
typedef megamol::geocalls_gl::CallTriMeshDataGL::Material Material;
/** Alias for lines class */
typedef megamol::geocalls::LinesDataCall::Lines Lines;
/**
* Implementation of 'Create'.
*
* @return 'true' on success, 'false' otherwise.
*/
virtual bool create(void);
/**
* Gets the data from the source.
*
* @param caller The calling call.
*
* @return 'true' on success, 'false' on failure.
*/
virtual bool getDataCallback(core::Call& caller);
/**
* Gets the data from the source.
*
* @param caller The calling call.
*
* @return 'true' on success, 'false' on failure.
*/
virtual bool getExtentCallback(core::Call& caller);
/**
* Implementation of 'Release'.
*/
virtual void release(void);
/** Ensures that the data is loaded */
virtual void assertData(void) = 0;
/** The objects */
vislib::Array<Mesh> objs;
/** The materials */
vislib::Array<Material> mats;
/** The lines */
std::vector<Lines> lines;
/** The bounding box */
vislib::math::Cuboid<float> bbox;
/** The data update hash */
SIZE_T datahash;
private:
/** The slot for requesting data */
core::CalleeSlot getDataSlot;
/** The slot for requesting lines data */
core::CalleeSlot getLinesDataSlot;
};
} // namespace trisoup_gl
} /* end namespace megamol */
#endif /* MMTRISOUPPLG_ABSTRACTTRIMESHDATASOURCE_H_INCLUDED */
|
e413c5b4d168925cdf4c3ddd2e04760a84c6212e
|
6d088ec295b33db11e378212d42d40d5a190c54c
|
/contrib/brl/bbas/bsta/pro/Templates/brdb_value_t+bsta_random_wrapper_sptr-.cxx
|
b8de632c432fa3400ab5ea730f80f894479d4094
|
[] |
no_license
|
vxl/vxl
|
29dffd5011f21a67e14c1bcbd5388fdbbc101b29
|
594ebed3d5fb6d0930d5758630113e044fee00bc
|
refs/heads/master
| 2023-08-31T03:56:24.286486
| 2023-08-29T17:53:12
| 2023-08-29T17:53:12
| 9,819,799
| 224
| 126
| null | 2023-09-14T15:52:32
| 2013-05-02T18:32:27
|
C++
|
UTF-8
|
C++
| false
| false
| 185
|
cxx
|
brdb_value_t+bsta_random_wrapper_sptr-.cxx
|
#include <brdb/brdb_value.hxx>
#include <bsta/bsta_random_wrapper.h>
#include <vbl/io/vbl_io_smart_ptr.h>
BRDB_VALUE_INSTANTIATE(bsta_random_wrapper_sptr, "bsta_random_wrapper_sptr");
|
75d02a76abc0465c3b13534f063edc164f5d92ed
|
dd656493066344e70123776c2cc31dd13f31c1d8
|
/MITK/Modules/MitkExt/Testing/mitkCompareImageSliceTestHelper.h
|
d2209c2effa5af5e7792434ccc1d481057e3c24a
|
[] |
no_license
|
david-guerrero/MITK
|
e9832b830cbcdd94030d2969aaed45da841ffc8c
|
e5fbc9993f7a7032fc936f29bc59ca296b4945ce
|
refs/heads/master
| 2020-04-24T19:08:37.405353
| 2011-11-13T22:25:21
| 2011-11-13T22:25:21
| 2,372,730
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,766
|
h
|
mitkCompareImageSliceTestHelper.h
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef mitkCompareImageSliceTestHelperhincluded
#define mitkCompareImageSliceTestHelperhincluded
#include "mitkImageCast.h"
#include "mitkImageAccessByItk.h"
#include <itkImageSliceConstIteratorWithIndex.h>
#include <itkImageRegionConstIterator.h>
// copied from mitk/Core/Algorithms/mitkOverwriteSliceImageFilter.cpp
// basically copied from mitk/Core/Algorithms/mitkImageAccessByItk.h
#define myMITKOverwriteSliceImageFilterAccessByItk(mitkImage, itkImageTypeFunction, pixeltype, dimension, itkimage2) \
if ( typeId == typeid(pixeltype) ) \
{ \
typedef itk::Image<pixeltype, dimension> ImageType; \
typedef mitk::ImageToItk<ImageType> ImageToItkType; \
itk::SmartPointer<ImageToItkType> imagetoitk = ImageToItkType::New(); \
imagetoitk->SetInput(mitkImage); \
imagetoitk->Update(); \
itkImageTypeFunction(imagetoitk->GetOutput(), itkimage2); \
}
#define myMITKOverwriteSliceImageFilterAccessAllTypesByItk(mitkImage, itkImageTypeFunction, dimension, itkimage2) \
{ \
myMITKOverwriteSliceImageFilterAccessByItk(mitkImage, itkImageTypeFunction, double, dimension, itkimage2) else \
myMITKOverwriteSliceImageFilterAccessByItk(mitkImage, itkImageTypeFunction, float, dimension, itkimage2) else \
myMITKOverwriteSliceImageFilterAccessByItk(mitkImage, itkImageTypeFunction, int, dimension, itkimage2) else \
myMITKOverwriteSliceImageFilterAccessByItk(mitkImage, itkImageTypeFunction, unsigned int, dimension, itkimage2) else \
myMITKOverwriteSliceImageFilterAccessByItk(mitkImage, itkImageTypeFunction, short, dimension, itkimage2) else \
myMITKOverwriteSliceImageFilterAccessByItk(mitkImage, itkImageTypeFunction, unsigned short, dimension, itkimage2) else \
myMITKOverwriteSliceImageFilterAccessByItk(mitkImage, itkImageTypeFunction, char, dimension, itkimage2) else \
myMITKOverwriteSliceImageFilterAccessByItk(mitkImage, itkImageTypeFunction, unsigned char, dimension, itkimage2) \
}
class CompareImageSliceTestHelper
{
private:
/* variables to be used by CompareSlice only */
static unsigned int m_Dimension0;
static unsigned int m_Dimension1;
static unsigned int m_SliceDimension;
static unsigned int m_SliceIndex;
static bool m_ComparisonResult;
static mitk::Image* m_SliceImage;
public:
template<typename TPixel1, unsigned int VImageDimension1, typename TPixel2, unsigned int VImageDimension2>
static void ItkImageCompare( itk::Image<TPixel1,VImageDimension1>* inputImage, itk::Image<TPixel2,VImageDimension2>* outputImage )
{
m_ComparisonResult = false;
typedef itk::Image<TPixel1, VImageDimension1> SliceImageType;
typedef itk::Image<TPixel2, VImageDimension2> VolumeImageType;
typedef itk::ImageSliceConstIteratorWithIndex< VolumeImageType > OutputSliceIteratorType;
typedef itk::ImageRegionConstIterator< SliceImageType > InputSliceIteratorType;
typename VolumeImageType::RegionType sliceInVolumeRegion;
sliceInVolumeRegion = outputImage->GetLargestPossibleRegion();
sliceInVolumeRegion.SetSize( m_SliceDimension, 1 ); // just one slice
sliceInVolumeRegion.SetIndex( m_SliceDimension, m_SliceIndex ); // exactly this slice, please
OutputSliceIteratorType outputIterator( outputImage, sliceInVolumeRegion );
outputIterator.SetFirstDirection(m_Dimension0);
outputIterator.SetSecondDirection(m_Dimension1);
InputSliceIteratorType inputIterator( inputImage, inputImage->GetLargestPossibleRegion() );
// iterate over output slice (and over input slice simultaneously)
outputIterator.GoToBegin();
inputIterator.GoToBegin();
while ( !outputIterator.IsAtEnd() )
{
while ( !outputIterator.IsAtEndOfSlice() )
{
while ( !outputIterator.IsAtEndOfLine() )
{
m_ComparisonResult = outputIterator.Get() == (TPixel2) inputIterator.Get();
if (!m_ComparisonResult) return; // return on first mismatch
++outputIterator;
++inputIterator;
}
outputIterator.NextLine();
}
outputIterator.NextSlice();
}
}
template<typename TPixel, unsigned int VImageDimension>
static void ItkImageSwitch( itk::Image<TPixel,VImageDimension>* itkImage )
{
const std::type_info& typeId=*(m_SliceImage->GetPixelType().GetTypeId());
//myMITKOverwriteSliceImageFilterAccessAllTypesByItk( m_SliceImage, ItkImageCompare, 2, itkImage );
AccessFixedDimensionByItk_1(m_SliceImage, ItkImageCompare, 2, itkImage)
}
static bool CompareSlice( mitk::Image* image, unsigned int sliceDimension, unsigned int sliceIndex, mitk::Image* slice )
{
if ( !image || ! slice ) return false;
switch (sliceDimension)
{
default:
case 2:
m_Dimension0 = 0;
m_Dimension1 = 1;
break;
case 1:
m_Dimension0 = 0;
m_Dimension1 = 2;
break;
case 0:
m_Dimension0 = 1;
m_Dimension1 = 2;
break;
}
if ( slice->GetDimension() != 2 || image->GetDimension() != 3 ||
slice->GetDimension(0) != image->GetDimension(m_Dimension0) ||
slice->GetDimension(1) != image->GetDimension(m_Dimension1) )
{
std::cerr << "Slice and image dimensions differ. Sorry, cannot work like this." << std::endl;
return false;
}
// this will do a long long if/else to find out both pixel typesA
m_SliceImage = slice;
m_SliceIndex = sliceIndex;
m_SliceDimension = sliceDimension;
m_ComparisonResult = false;
AccessFixedDimensionByItk( image, ItkImageSwitch, 3 );
return m_ComparisonResult;
}
}; // end class
#endif
|
4438a47658332971b5feb03db178267c3bef295e
|
0e4e677eec557eacba7ff8e0c2d56dcb8c601afb
|
/src/libhttpserver/multipart_response_stream.h
|
d2cdf2e2dfad3d97c80312e40a5994709c95f454
|
[
"MIT"
] |
permissive
|
RipcordSoftware/libhttpserver
|
a2d0db50c4ed4cc5826ba8856660ad6fde00bc23
|
87e8f67298763dacb1a4c13e3887532f688e5feb
|
refs/heads/master
| 2021-03-12T20:25:12.835298
| 2018-10-10T23:21:55
| 2018-10-10T23:21:55
| 31,376,981
| 25
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,162
|
h
|
multipart_response_stream.h
|
#ifndef RS_LIBHTTPSERVER_MULTIPART_RESPONSE_STREAM_H
#define RS_LIBHTTPSERVER_MULTIPART_RESPONSE_STREAM_H
#include "stream.h"
#include "response_headers.h"
namespace rs {
namespace httpserver {
class MultipartResponseStream final : public Stream {
public:
MultipartResponseStream(Stream& stream);
MultipartResponseStream(const MultipartResponseStream&) = delete;
virtual void Flush() override;
virtual int Read(Stream::byte* buffer, int offset, int count, bool peek = false) override;
virtual int Write(const Stream::byte* buffer, int offset, int count) override;
virtual long getPosition() override;
virtual long getLength() override;
void EmitPart(const char* contentType, const char* filename = nullptr, std::int64_t contentLength = -1);
unsigned getPartCount() { return partCount_; }
static const char* boundary;
private:
static const char* boundaryStart;
static const char* boundaryEnd;
static const unsigned boundaryEndLength;
Stream& stream_;
unsigned partCount_{0};
};
}}
#endif /* RS_LIBHTTPSERVER_MULTIPART_RESPONSE_STREAM_H */
|
8890897be3554b25e3ac4b86118d065a125b6d1f
|
2e0ffa41d68347285aeeea7b29039ef04cc7489a
|
/GWSystem1.0/ShowImgIntoFrame.cpp
|
113360b378b8b00dc1cae836dab14f211e2e14f3
|
[] |
no_license
|
AutumnCake/GWsystem_GIT
|
9b824a6e460b2c782259beb1e354d92687d89f38
|
da4aabaf6db804cc8424b9cf504c1e4519979156
|
refs/heads/master
| 2020-07-21T19:44:48.190713
| 2019-09-23T02:49:45
| 2019-09-23T02:49:45
| 206,958,800
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,025
|
cpp
|
ShowImgIntoFrame.cpp
|
// ShowImgIntoFrame.cpp : 实现文件
//
#include "stdafx.h"
#include "GWSystem1.0.h"
#include "ShowImgIntoFrame.h"
#include "afxdialogex.h"
// CShowImgIntoFrame 对话框
IMPLEMENT_DYNAMIC(CShowImgIntoFrame, CDialogEx)
CShowImgIntoFrame::CShowImgIntoFrame(CWnd* pParent /*=NULL*/)
: CDialogEx(CShowImgIntoFrame::IDD, pParent)
{
//将图片显示框ID存入数组
FrameName.push_back(IDC_FIGUREFRAME1);
FrameName.push_back(IDC_FIGUREFRAME2);
FrameName.push_back(IDC_FIGUREFRAME3);
FrameName.push_back(IDC_FIGUREFRAME4);
FrameName.push_back(IDC_FIGUREFRAME5);
FrameName.push_back(IDC_FIGUREFRAME6);
FrameName.push_back(IDC_FIGUREFRAME7);
FrameName.push_back(IDC_FIGUREFRAME8);
FrameName.push_back(IDC_FIGUREFRAME9);
FrameName.push_back(IDC_FIGUREFRAME10);
FrameName.push_back(IDC_FIGUREFRAME11);
FrameName.push_back(IDC_FIGUREFRAME12);
FrameName.push_back(IDC_FIGUREFRAME13);
FrameName.push_back(IDC_FIGUREFRAME14);
FrameName.push_back(IDC_FIGUREFRAME15);
}
CShowImgIntoFrame::~CShowImgIntoFrame()
{
}
void CShowImgIntoFrame::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
//图片显示框绑定变量
DDX_Control(pDX, IDC_FIGUREFRAME1, m_frame1);
DDX_Control(pDX, IDC_FIGUREFRAME2, m_frame2);
DDX_Control(pDX, IDC_FIGUREFRAME3, m_frame3);
DDX_Control(pDX, IDC_FIGUREFRAME4, m_frame4);
DDX_Control(pDX, IDC_FIGUREFRAME5, m_frame5);
DDX_Control(pDX, IDC_FIGUREFRAME6, m_frame6);
DDX_Control(pDX, IDC_FIGUREFRAME7, m_frame7);
DDX_Control(pDX, IDC_FIGUREFRAME8, m_frame8);
DDX_Control(pDX, IDC_FIGUREFRAME9, m_frame9);
DDX_Control(pDX, IDC_FIGUREFRAME10, m_frame10);
DDX_Control(pDX, IDC_FIGUREFRAME11, m_frame11);
DDX_Control(pDX, IDC_FIGUREFRAME12, m_frame12);
DDX_Control(pDX, IDC_FIGUREFRAME13, m_frame13);
DDX_Control(pDX, IDC_FIGUREFRAME14, m_frame14);
DDX_Control(pDX, IDC_FIGUREFRAME15, m_frame15);
}
BEGIN_MESSAGE_MAP(CShowImgIntoFrame, CDialogEx)
END_MESSAGE_MAP()
// CShowImgIntoFrame 消息处理程序
BOOL CShowImgIntoFrame::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: 在此添加额外的初始化
//获得15个图片显示框对应的区域,转换为client坐标,并存入数组
GetDlgItem(IDC_FIGUREFRAME1)->GetWindowRect(&rect1); ScreenToClient(&rect1); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME2)->GetWindowRect(&rect2); ScreenToClient(&rect2); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME3)->GetWindowRect(&rect3); ScreenToClient(&rect3); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME4)->GetWindowRect(&rect4); ScreenToClient(&rect4); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME5)->GetWindowRect(&rect5); ScreenToClient(&rect5); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME6)->GetWindowRect(&rect6); ScreenToClient(&rect6); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME7)->GetWindowRect(&rect7); ScreenToClient(&rect7); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME8)->GetWindowRect(&rect8); ScreenToClient(&rect8); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME9)->GetWindowRect(&rect9); ScreenToClient(&rect9); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME10)->GetWindowRect(&rect10); ScreenToClient(&rect10); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME11)->GetWindowRect(&rect11); ScreenToClient(&rect11); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME12)->GetWindowRect(&rect12); ScreenToClient(&rect12); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME13)->GetWindowRect(&rect13); ScreenToClient(&rect13); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME14)->GetWindowRect(&rect14); ScreenToClient(&rect14); rect.push_back(rect1);
GetDlgItem(IDC_FIGUREFRAME15)->GetWindowRect(&rect15); ScreenToClient(&rect15); rect.push_back(rect1);
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
// 查找文件夹里的所有图片路径
void CShowImgIntoFrame::FindAllImgFilePath()
{
char* fileName = nullptr;
int find_pic = 0;//的图片的序列号
vector <string>().swap(imgNames);
}
|
a865cb314c2628bfa919bb07adaf2ce2582f9e8d
|
93aa54535beca6865818e04a50659ca35fd0fa7c
|
/include/mgpcl/Singleton.h
|
4bbd5da1bda8b3bb92aef0c92bcd3f9525aec953
|
[
"MIT"
] |
permissive
|
montoyo/mgpcl
|
cef9e9f401340cdcbd3bd6a812d748b5bc174ad2
|
8e65d01e483124936de3650154e0e7e9586d27c0
|
refs/heads/master
| 2021-01-21T15:00:35.612965
| 2020-02-05T13:37:00
| 2020-02-05T13:37:00
| 95,368,396
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,315
|
h
|
Singleton.h
|
/* Copyright (C) 2017 BARBOTIN Nicolas
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
namespace m
{
template<class T> class Singleton
{
public:
static T &instance()
{
return *m_ptr;
}
static T &create()
{
if(m_ptr == nullptr)
m_ptr = new T;
return *m_ptr;
}
static void destroy()
{
if(m_ptr != nullptr) {
delete m_ptr;
m_ptr = nullptr;
}
}
private:
static T *m_ptr;
};
template<class T> T *Singleton<T>::m_ptr = nullptr;
//If you reaaallllyy need a real singleton, here
//it is; but I won't be held responsible for the
//lack of performance in your program.
template<class T> class RSingleton
{
public:
static T &instance()
{
if(m_ptr == nullptr)
m_ptr = new T;
return *m_ptr;
}
static void destroy()
{
if(m_ptr != nullptr) {
delete m_ptr;
m_ptr = nullptr;
}
}
private:
static T *m_ptr;
};
template<class T> T *RSingleton<T>::m_ptr = nullptr;
}
|
6dc3764b6532f56a97d7828ca62d74ad4c42e5fe
|
a804855bf0062ca58cfc9cce679efa0a30cfafb4
|
/TEST2 v2/TEST2/stoken.cpp
|
b79ee2b5b5b3f1a4d7326487e535d65f31f88885
|
[] |
no_license
|
Secret-Asian-Man/cs8
|
2cfde5ee215df411647ae10a595048d7e3a1de85
|
607cb5276295082064ac1f5d5958039c3e4f47c6
|
refs/heads/master
| 2016-08-12T12:58:26.939064
| 2015-12-18T11:08:29
| 2015-12-18T11:08:29
| 44,903,049
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,561
|
cpp
|
stoken.cpp
|
#include "stoken.h"
#include <iostream>
using namespace std;
sToken::sToken()
{
}
sToken::sToken(string src)
{
SOURCE=src;
anchor = 0;
done = false;
}
void sToken::operator =(string src)
{
SOURCE = src;
anchor = 0;
done = false;
}
void sToken::identify()
{
char first;
first = SOURCE.at(anchor);
if(alphabet.find(first)>=0)
{
tokenType = 1;
SET = alphabet;
}
else if(digits.find(first)>=0)
{
tokenType = 2;
SET = digits;
}
else if(spaces.find(first)>=0)
{
tokenType = 3;
SET = spaces;
}
else if(specials.find(first)>=0)
{
tokenType = 4;
SET = specials;
}
else
{
tokenType = 5;
specials+=first;
SET = specials;
}
}
void sToken::showStatus()
{
cout <<"\""<<STOKEN<<"\""<<endl;
}
void sToken::Zorg()
{
using namespace std;
int pos;
if(done == true)
{
cout << "..." << endl;
return;
}
else
{
pos=SOURCE.find_first_not_of(SET,anchor);
if(pos==-1)
{
STOKEN = SOURCE.substr(anchor, SOURCE.length()-anchor);
done = true;
}
else
{
done = false;
STOKEN = SOURCE.substr(anchor, pos-anchor);
anchor = pos;
}
}
}
void sToken::reset()
{
anchor = 0;
}
void sToken::initializeBlanks()
{
char* blanks;
blanks = new char[5];
blanks[0]=' ';
blanks[1]='\n';
blanks[2]='t';
blanks[3]='\0';
spaces = blanks;
}
bool sToken::progress()
{
return done;
}
|
a776b15703719f1e1514aa6c9ad6ea73bd36b77c
|
027ad99a3fa9231dd96dd610fdbebd26f9fd02db
|
/Projects/mo_graphics/Common_FBComponent_UpdateProps.h
|
a8461650fc92e86b269cbb1faf176f8b310cf2fd
|
[
"BSD-3-Clause"
] |
permissive
|
droidoid/MoPlugs
|
ee5b6162a3a504d43d8a62ab221cfe72317afe25
|
fce52e6469408e32e94af8ac8a303840bc956e53
|
refs/heads/master
| 2020-12-19T04:26:07.530778
| 2019-08-07T22:05:07
| 2019-08-07T22:05:07
| 235,619,955
| 1
| 0
|
BSD-3-Clause
| 2020-01-22T16:54:13
| 2020-01-22T16:54:12
| null |
UTF-8
|
C++
| false
| false
| 1,399
|
h
|
Common_FBComponent_UpdateProps.h
|
#pragma once
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// file: Common_FBComponent_UpdateProps.h
//
// Author Sergey Solokhin (Neill3d)
//
// GitHub page - https://github.com/Neill3d/MoPlugs
// Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE
//
///////////////////////////////////////////////////////////////////////////////////////////////////
//--- SDK include
#include <fbsdk/fbsdk.h>
class CFBComponentUpdateProps
{
public:
// ! a constructor
CFBComponentUpdateProps();
virtual ~CFBComponentUpdateProps()
{}
public:
FBPropertyBool RealTimeUpdate;
FBPropertyBool UpdateOnTimeSliderChange;
FBPropertyBool UpdateWhenSelected;
FBPropertyInt UpdateSkipFrames;
FBPropertyAction UpdateAction;
virtual void ResetUpdateValues();
void FBCreateUpdateProps(FBComponent *pParent, fbExternalGetSetHandler UpdateActionSet);
bool ProcessUpdateConditions( const bool offlineRender,
FBTime &localTime,
const unsigned int frameId );
bool HasUpdateFlag() const
{
return mUpdateFlag;
}
void SetUpdateFlag(bool flag) {
mUpdateFlag = flag;
}
void ResetUpdateFlag() {
mUpdateFlag = false;
}
protected:
FBComponent *mUpdateComponent;
bool mUpdateFlag;
FBTime mLastLocalTime;
unsigned int mLastFrameId;
void OnSetUpdateAction();
};
|
ff3b09782c140a605df958fce811a9ee65607f2b
|
4bf2ee10c6594f70c32feb3bcb50eec186daa9cf
|
/solutions/1085/1085.cpp11.cpp
|
3508ee8da86e45e3f83c62b4c46c787bfdf77878
|
[] |
no_license
|
jwvg0425/boj
|
7674928dc012ba3c404cef3a76aa753828e09761
|
4b7e7389cbe55270bd0dab546d6e84817477b0f1
|
refs/heads/master
| 2020-07-14T02:37:36.658675
| 2017-07-13T06:11:44
| 2017-07-13T06:11:44
| 94,295,654
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 182
|
cpp
|
1085.cpp11.cpp
|
#include <stdio.h>
#include <memory.h>
#include <algorithm>
int main()
{
int x, y, w, h;
scanf("%d %d %d %d", &x, &y, &w, &h);
printf("%d", std::min({ x, y, w - x, h - y }));
}
|
d63ecfaa31b25b9862250105224e6054669478c6
|
463d81a0c9ce92f1717050118329d268b170056d
|
/mikehsu-TestDarwin.c++
|
ebf6025b8aeb8490b782f78d8fd429b22a011221
|
[] |
no_license
|
cs371p-spring-2013/cs371p-darwin-tests
|
786a10244649ee4379754b1bb942aa346e310576
|
b7b15e7faf130c9518c6d9b7aec62759fce3ef49
|
refs/heads/master
| 2020-03-30T08:40:51.008175
| 2013-04-07T00:19:30
| 2013-04-07T00:19:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 36,703
|
mikehsu-TestDarwin.c++
|
// --------
// includes
// --------
#include <iostream> // cout, endl
#include <sstream> // istringtstream, ostringstream
#include <string> // ==
#include <vector> //vector
#include "cppunit/extensions/HelperMacros.h" // CPPUNIT_TEST, CPPUNIT_TEST_SUITE, CPPUNIT_TEST_SUITE_END
#include "cppunit/TestFixture.h" // TestFixture
#include "cppunit/TextTestRunner.h" // TextTestRunner
#define private public
#define protected public
#define class struct
#include "Darwin.h"
// -----------
// TestDarwin
// -----------
struct TestDarwin : CppUnit::TestFixture {
// test creature default constructor
void test_creature_default_creature_1 (){
Creature x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "C");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_creature_default_creature_2 (){
Creature x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "C");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_creature_default_creature_3 (){
Creature x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "C");
CPPUNIT_ASSERT(x.toRead == true);
}
//test creature int constructor
void test_creature_int_constuctors_1 (){
Creature x(0);
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "C");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_creature_int_constuctors_2 (){
Creature x(1);
CPPUNIT_ASSERT(x.direction == 1);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "C");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_creature_int_constuctors_3 (){
Creature x(2);
CPPUNIT_ASSERT(x.direction == 2);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "C");
CPPUNIT_ASSERT(x.toRead == true);
}
// test creature reset
void test_creature_reset_1 (){
Creature x(2);
x.toRead = false;
CPPUNIT_ASSERT(x.toRead == false);
x.reset();
CPPUNIT_ASSERT(x.toRead == true);
}
void test_creature_reset_2 (){
Creature x(1);
x.toRead = false;
CPPUNIT_ASSERT(x.toRead == false);
x.reset();
CPPUNIT_ASSERT(x.toRead == true);
}
void test_creature_reset_3 (){
Creature x(3);
x.toRead = false;
CPPUNIT_ASSERT(x.toRead == false);
x.reset();
CPPUNIT_ASSERT(x.toRead == true);
}
// test creature getName
void test_creature_getName_1 (){
Creature x(3);
CPPUNIT_ASSERT(x.name == "C");
CPPUNIT_ASSERT(x.getName() == "C");
}
void test_creature_getName_2 (){
Creature x(0);
CPPUNIT_ASSERT(x.name == "C");
CPPUNIT_ASSERT(x.getName() == "C");
}
void test_creature_getName_3 (){
Creature x(1);
CPPUNIT_ASSERT(x.name == "C");
CPPUNIT_ASSERT(x.getName() == "C");
}
// test creature getDirection
void test_creature_getDirection_1(){
Creature x(2);
CPPUNIT_ASSERT(x.direction == 2);
CPPUNIT_ASSERT(x.getDirection()== 2);
}
void test_creature_getDirection_2(){
Creature x(0);
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.getDirection()== 0);
}
void test_creature_getDirection_3(){
Creature x(3);
CPPUNIT_ASSERT(x.direction == 3);
CPPUNIT_ASSERT(x.getDirection()== 3);
}
// test creature setD
void test_creature_setD_1(){
Creature x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.getDirection() == 0);
x.setD(3);
CPPUNIT_ASSERT(x.direction == 3);
CPPUNIT_ASSERT(x.getDirection()== 3);
}
void test_creature_setD_2(){
Creature x(2);
CPPUNIT_ASSERT(x.direction == 2);
CPPUNIT_ASSERT(x.getDirection() == 2);
x.setD(1);
CPPUNIT_ASSERT(x.direction == 1);
CPPUNIT_ASSERT(x.getDirection()== 1);
}
void test_creature_setD_3(){
Creature x(1);
CPPUNIT_ASSERT(x.direction == 1);
CPPUNIT_ASSERT(x.getDirection() == 1);
x.setD(0);
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.getDirection()== 0);
}
// test creature virtual action
void test_creature_virtual_action_1(){
Creature a;
Creature b;
Creature c;
Creature* x = &a;
Creature* y = &b;
bool bo = true;
CPPUNIT_ASSERT(c.action(x,y,true,bo) == false);
}
void test_creature_virtual_action_2(){
Creature a;
Creature b;
Creature c;
Creature* x = &a;
Creature* y = &b;
bool bo = false;
CPPUNIT_ASSERT(c.action(x,y,false,bo) == false);
}
void test_creature_virtual_action_3(){
Creature a;
Creature b;
Creature c;
Creature* x = &a;
Creature* y = &b;
bool bo = false;
CPPUNIT_ASSERT(c.action(x,y,true,bo) == false);
}
// test creature left
void test_creature_left_1(){
Creature x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.getDirection() == 0);
x.left();
CPPUNIT_ASSERT(x.direction == 3);
CPPUNIT_ASSERT(x.getDirection() == 3);
}
void test_creature_left_2(){
Creature x(2);
CPPUNIT_ASSERT(x.direction == 2);
CPPUNIT_ASSERT(x.getDirection() == 2);
x.left();
CPPUNIT_ASSERT(x.direction == 1);
CPPUNIT_ASSERT(x.getDirection() == 1);
}
void test_creature_left_3(){
Creature x(1);
CPPUNIT_ASSERT(x.direction == 1);
CPPUNIT_ASSERT(x.getDirection() == 1);
x.left();
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.getDirection() == 0);
}
// test creature right
void test_creature_right_1(){
Creature x(3);
CPPUNIT_ASSERT(x.direction == 3);
CPPUNIT_ASSERT(x.getDirection() == 3);
x.right();
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.getDirection() == 0);
}
void test_creature_right_2(){
Creature x(2);
CPPUNIT_ASSERT(x.direction == 2);
CPPUNIT_ASSERT(x.getDirection() == 2);
x.right();
CPPUNIT_ASSERT(x.direction == 3);
CPPUNIT_ASSERT(x.getDirection() == 3);
}
void test_creature_right_3(){
Creature x(1);
CPPUNIT_ASSERT(x.direction == 1);
CPPUNIT_ASSERT(x.getDirection() == 1);
x.right();
CPPUNIT_ASSERT(x.direction == 2);
CPPUNIT_ASSERT(x.getDirection() == 2);
}
// test creature hop
void test_creature_hop_1 (){
Game<3,3,1,1> g;
ostringstream before, beforeHop, dummy, afterHop;
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ...\n1 ...\n2 ...\n\n");
Hopper h = 1;
g.put(h,2,2);
g.printGrid(beforeHop);
CPPUNIT_ASSERT(beforeHop.str() == "0 ...\n1 ...\n2 ..h\n\n");
g.run(dummy);
g.printGrid(afterHop);
CPPUNIT_ASSERT(afterHop.str() == "0 ...\n1 ..h\n2 ...\n\n");
}
void test_creature_hop_2 (){
Game<5,5,1,1> g;
ostringstream before, beforeHop, dummy, afterHop;
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 .....\n1 .....\n2 .....\n3 .....\n4 .....\n\n");
Hopper h = 2;
g.put(h,4,2);
// g.printGrid(cout);
g.printGrid(beforeHop);
CPPUNIT_ASSERT(beforeHop.str() == "0 .....\n1 .....\n2 .....\n3 .....\n4 ..h..\n\n");
g.run(dummy);
g.printGrid(afterHop);
CPPUNIT_ASSERT(afterHop.str() == "0 .....\n1 .....\n2 .....\n3 .....\n4 ...h.\n\n");
}
void test_creature_hop_3 (){
Game<2,2,1,1> g;
ostringstream before, beforeHop, dummy, afterHop;
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ..\n1 ..\n\n");
Hopper h = 0;
g.put(h,1,1);
g.printGrid(beforeHop);
CPPUNIT_ASSERT(beforeHop.str() == "0 ..\n1 .h\n\n");
g.run(dummy);
g.printGrid(afterHop);
CPPUNIT_ASSERT(afterHop.str() == "0 ..\n1 h.\n\n");
}
//test creature isEnemy
void test_creature_isEnemy_1 (){
Game<2,2,1,1> g;
ostringstream before, beforeHop, dummy, afterHop;
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ..\n1 ..\n\n");
Creature* x;
Creature* y;
Food f1 = 0;
Rover r2 = 1;
x = &f1;
y = &r2;
g.put(f1,0,1);
g.put(r2,1,1);
g.printGrid(beforeHop);
// g.printGrid(cout);
CPPUNIT_ASSERT(beforeHop.str() == "0 .f\n1 .r\n\n");
g.run(dummy);
CPPUNIT_ASSERT(r2.isEnemy(x, y) == true);
g.printGrid(afterHop);
// g.printGrid(cout);
CPPUNIT_ASSERT(afterHop.str() == "0 .r\n1 .r\n\n");
}
void test_creature_isEnemy_2 (){
Game<3,3,1,1> g;
ostringstream before, beforeHop, dummy, afterHop;
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ...\n1 ...\n2 ...\n\n");
Creature* x;
Creature* y;
Trap t1 = 0;
Rover r2 = 1;
x = &t1;
y = &r2;
g.put(t1,2,2);
g.put(r2,1,1);
g.printGrid(beforeHop);
CPPUNIT_ASSERT(beforeHop.str() == "0 ...\n1 .r.\n2 ..t\n\n");
g.run(dummy);
CPPUNIT_ASSERT(r2.isEnemy(x, y) == true);
g.printGrid(afterHop);
CPPUNIT_ASSERT(afterHop.str() == "0 .r.\n1 ...\n2 ..t\n\n");
}
void test_creature_isEnemy_3 (){
Game<4,4,1,1> g;
ostringstream before, beforeHop, dummy, afterHop;
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ....\n1 ....\n2 ....\n3 ....\n\n");
Creature* x;
Creature* y;
Creature* z;
Food f1 = 0;
Rover r2 = 1;
x = &f1;
y = &r2;
z = NULL;
g.put(f1,0,1);
g.put(r2,1,1);
g.printGrid(beforeHop);
CPPUNIT_ASSERT(beforeHop.str() == "0 .f..\n1 .r..\n2 ....\n3 ....\n\n");
g.run(dummy);
CPPUNIT_ASSERT(r2.isEnemy(x, y) == true);
CPPUNIT_ASSERT(r2.isEnemy(x, z) == false);
g.printGrid(afterHop);
CPPUNIT_ASSERT(afterHop.str() == "0 .r..\n1 .r..\n2 ....\n3 ....\n\n");
}
// test creature isEmpty
void test_creature_isEmpty_1 (){
Game<4,4,1,1> g;
ostringstream before, beforeHop, dummy, afterHop;
g.printGrid(before);
// g.printGrid(cout);
CPPUNIT_ASSERT(before.str() == "0 ....\n1 ....\n2 ....\n3 ....\n\n");
Creature* x;
Creature* y;
Creature* z;
Food f1 = 0;
Rover r2 = 1;
Hopper h1 = 2;
x = &f1;
y = &r2;
z = &h1;
g.put(f1,0,1);
g.put(r2,1,1);
g.put(h1,2,2);
g.printGrid(beforeHop);
// g.printGrid(cout);
CPPUNIT_ASSERT(beforeHop.str() == "0 .f..\n1 .r..\n2 ..h.\n3 ....\n\n");
g.run(dummy);
CPPUNIT_ASSERT(r2.isEmpty(x, y) == false);
y = NULL;
CPPUNIT_ASSERT(h1.isEmpty(z, y) == true);
g.printGrid(afterHop);
// g.printGrid(cout);
CPPUNIT_ASSERT(afterHop.str() == "0 .r..\n1 .r..\n2 ...h\n3 ....\n\n");
}
void test_creature_isEmpty_2 (){
Creature* x;
Creature* y;
Creature* z;
Food f1 = 0;
Rover r2 = 1;
Hopper h1 = 2;
x = &f1;
y = &r2;
z = &h1;
CPPUNIT_ASSERT(r2.isEmpty(x, y) == false);
z = NULL;
CPPUNIT_ASSERT(h1.isEmpty(x, z) == true);
x = NULL;
CPPUNIT_ASSERT(f1.isEmpty(z, x) == true);
}
void test_creature_isEmpty_3 (){
Creature* x;
Creature* y;
Creature* z;
Food f1 = 0;
Rover r2 = 1;
Hopper h1 = 2;
x = &f1;
y = &r2;
z = &h1;
CPPUNIT_ASSERT(r2.isEmpty(x, y) == false);
z = NULL;
CPPUNIT_ASSERT(h1.isEmpty(x, z) == true);
x = NULL;
CPPUNIT_ASSERT(f1.isEmpty(z, x) == true);
y = NULL;
x = &r2;
CPPUNIT_ASSERT(f1.isEmpty(y, x) == false);
}
// test food default constructor
void test_food_default_constructor_1 (){
Food x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "f");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_food_default_constructor_2 (){
Food x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "f");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_food_default_constructor_3 (){
Food x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "f");
CPPUNIT_ASSERT(x.toRead == true);
}
// test food int constructor
void test_food_int_constructor_1 (){
Food x(2);
CPPUNIT_ASSERT(x.direction == 2);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "f");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_food_int_constructor_2 (){
Food x(3);
CPPUNIT_ASSERT(x.direction == 3);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "f");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_food_int_constructor_3 (){
Food x = 1;
CPPUNIT_ASSERT(x.direction == 1);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "f");
CPPUNIT_ASSERT(x.toRead == true);
}
//test food getName
void test_food_getName_1 (){
Food x = 1;
CPPUNIT_ASSERT(x.getName() == "f");
}
void test_food_getName_2 (){
Food x = 2;
CPPUNIT_ASSERT(x.getName() == "f");
}
void test_food_getName_3 (){
Food x = 3;
CPPUNIT_ASSERT(x.getName() == "f");
}
// test food action
void test_food_action_1 (){
Game<2,2,1,1> g;
Food x = 2;
Food y = 3;
g.put(x,1,1);
g.put(y,1,0);
ostringstream u;
g.run(u);
CPPUNIT_ASSERT(x.getDirection() == 1);
CPPUNIT_ASSERT(y.getDirection() == 2);
}
void test_food_action_2 (){
Game<2,2,1,1> g;
Food x = 0;
Food y = 1;
g.put(x,1,1);
g.put(y,1,0);
ostringstream u;
g.run(u);
CPPUNIT_ASSERT(x.getDirection() == 3);
CPPUNIT_ASSERT(y.getDirection() == 0);
}
void test_food_action_3 (){
Game<2,2,1,1> g;
Food x = 1;
Food y = 2;
g.put(x,1,1);
g.put(y,1,0);
ostringstream u;
g.run(u);
CPPUNIT_ASSERT(x.getDirection() == 0);
CPPUNIT_ASSERT(y.getDirection() == 1);
}
// hopper food default constructor
void test_hopper_default_constructor_1 (){
Hopper x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "h");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_hopper_default_constructor_2 (){
Hopper x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "h");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_hopper_default_constructor_3 (){
Hopper x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "h");
CPPUNIT_ASSERT(x.toRead == true);
}
// test food int constructor
void test_hopper_int_constructor_1 (){
Hopper x(2);
CPPUNIT_ASSERT(x.direction == 2);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "h");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_hopper_int_constructor_2 (){
Hopper x(3);
CPPUNIT_ASSERT(x.direction == 3);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "h");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_hopper_int_constructor_3 (){
Hopper x = 1;
CPPUNIT_ASSERT(x.direction == 1);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "h");
CPPUNIT_ASSERT(x.toRead == true);
}
//test food getName
void test_hopper_getName_1 (){
Hopper x;
CPPUNIT_ASSERT(x.getName() == "h");
}
void test_hopper_getName_2 (){
Hopper x = 2;
CPPUNIT_ASSERT(x.getName() == "h");
}
void test_hopper_getName_3 (){
Hopper x(3);
CPPUNIT_ASSERT(x.getName() == "h");
}
// test hopper action
void test_hopper_action_1 (){
Game<2,2,1,1> g;
Hopper x = 3;
Hopper y = 3;
g.put(x,1,1);
g.put(y,1,0);
ostringstream before, after,u;
// g.printGrid(cout);
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ..\n1 hh\n\n");
g.run(u);
g.printGrid(after);
CPPUNIT_ASSERT(after.str() == "0 ..\n1 hh\n\n");
}
void test_hopper_action_2 (){
Game<3,3,1,1> g;
Hopper x = 3;
Hopper y = 3;
g.put(x,1,1);
g.put(y,1,0);
ostringstream before, after,u;
// g.printGrid(cout);
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ...\n1 hh.\n2 ...\n\n");
g.run(u);
g.printGrid(after);
CPPUNIT_ASSERT(after.str() == "0 ...\n1 ...\n2 hh.\n\n");
}
void test_hopper_action_3 (){
Game<2,2,1,1> g;
Hopper x = 0;
Hopper y = 0;
g.put(x,1,1);
g.put(y,0,1);
ostringstream before, after,u;
// g.printGrid(cout);
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 .h\n1 .h\n\n");
g.run(u);
g.printGrid(after);
CPPUNIT_ASSERT(after.str() == "0 h.\n1 h.\n\n");
}
// test rover default constructor
void test_rover_default_constructor_1 (){
Rover x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "r");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_rover_default_constructor_2 (){
Rover x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "r");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_rover_default_constructor_3 (){
Rover x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "r");
CPPUNIT_ASSERT(x.toRead == true);
}
// test rover int constructor
void test_rover_int_constructor_1 (){
Rover x(2);
CPPUNIT_ASSERT(x.direction == 2);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "r");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_rover_int_constructor_2 (){
Rover x(3);
CPPUNIT_ASSERT(x.direction == 3);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "r");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_rover_int_constructor_3 (){
Rover x = 1;
CPPUNIT_ASSERT(x.direction == 1);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "r");
CPPUNIT_ASSERT(x.toRead == true);
}
//test food getName
void test_rover_getName_1 (){
Rover x;
CPPUNIT_ASSERT(x.getName() == "r");
}
void test_rover_getName_2 (){
Rover x = 2;
CPPUNIT_ASSERT(x.getName() == "r");
}
void test_rover_getName_3 (){
Rover x(3);
CPPUNIT_ASSERT(x.getName() == "r");
}
// test rover action
void test_rover_action_1 (){
Game<2,2,1,1> g;
Rover x = 3;
Rover y = 3;
g.put(x,1,1);
g.put(y,1,0);
ostringstream before, after,u;
// g.printGrid(cout);
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ..\n1 rr\n\n");
g.run(u);
// g.printGrid(cout);
g.printGrid(after);
CPPUNIT_ASSERT(after.str() == "0 ..\n1 rr\n\n");
}
void test_rover_action_2 (){
Game<2,2,1,1> g;
Rover x = 1;
Rover y = 1;
Food a = 0;
Food b = 3;
g.put(x,1,1);
g.put(y,1,0);
g.put(a,0,0);
g.put(b,0,1);
ostringstream before, after,u;
// g.printGrid(cout);
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ff\n1 rr\n\n");
g.run(u);
g.printGrid(after);
CPPUNIT_ASSERT(after.str() == "0 rr\n1 rr\n\n");
}
void test_rover_action_3 (){
Game<2,2,1,1> g;
Rover a = 1;
Rover b = 1;
g.put(a,1,1);
g.put(b,1,0);
ostringstream before, after,u;
// g.printGrid(cout);
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ..\n1 rr\n\n");
g.run(u);
g.printGrid(after);
CPPUNIT_ASSERT(after.str() == "0 rr\n1 ..\n\n");
}
// test Trap default constructor
void test_trap_default_constructor_1 (){
Trap x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "t");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_trap_default_constructor_2 (){
Trap x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "t");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_trap_default_constructor_3 (){
Trap x;
CPPUNIT_ASSERT(x.direction == 0);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "t");
CPPUNIT_ASSERT(x.toRead == true);
}
// test rover int constructor
void test_trap_int_constructor_1 (){
Trap x(2);
CPPUNIT_ASSERT(x.direction == 2);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "t");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_trap_int_constructor_2 (){
Trap x(3);
CPPUNIT_ASSERT(x.direction == 3);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "t");
CPPUNIT_ASSERT(x.toRead == true);
}
void test_trap_int_constructor_3 (){
Trap x = 1;
CPPUNIT_ASSERT(x.direction == 1);
CPPUNIT_ASSERT(x.program_counter == 0);
CPPUNIT_ASSERT(x.name == "t");
CPPUNIT_ASSERT(x.toRead == true);
}
//test trap getName
void test_trap_getName_1 (){
Rover x;
CPPUNIT_ASSERT(x.getName() == "r");
}
void test_trap_getName_2 (){
Rover x = 2;
CPPUNIT_ASSERT(x.getName() == "r");
}
void test_trap_getName_3 (){
Rover x(3);
CPPUNIT_ASSERT(x.getName() == "r");
}
// test trap action
void test_trap_action_1 (){
Game<2,2,1,1> g;
Trap x = 3;
Trap y = 3;
g.put(x,1,1);
g.put(y,1,0);
ostringstream before, after,u;
// g.printGrid(cout);
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ..\n1 tt\n\n");
g.run(u);
g.printGrid(after);
CPPUNIT_ASSERT(after.str() == "0 ..\n1 tt\n\n");
}
void test_trap_action_2 (){
Game<2,2,1,1> g;
Trap x = 3;
Trap y = 3;
g.put(x,1,1);
g.put(y,1,0);
ostringstream before, after,u;
// g.printGrid(cout);
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ..\n1 tt\n\n");
g.run(u);
g.printGrid(after);
CPPUNIT_ASSERT(after.str() == "0 ..\n1 tt\n\n");
}
void test_trap_action_3 (){
Game<2,2,1,1> g;
Trap x = 3;
Trap y = 3;
g.put(x,1,1);
g.put(y,1,0);
ostringstream before, after,u;
// g.printGrid(cout);
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ..\n1 tt\n\n");
g.run(u);
g.printGrid(after);
CPPUNIT_ASSERT(after.str() == "0 ..\n1 tt\n\n");
}
// test Game default constructor
void test_game_default_1 (){
Game<2,2,1,1> g;
CPPUNIT_ASSERT(g._Height == 2);
CPPUNIT_ASSERT(g._Width == 2);
CPPUNIT_ASSERT(g.turn == 0);
CPPUNIT_ASSERT(g.Food_index == 0);
CPPUNIT_ASSERT(g.Hopper_index == 0);
CPPUNIT_ASSERT(g.Rover_index == 0);
CPPUNIT_ASSERT(g.Trap_index == 0);
CPPUNIT_ASSERT(g.Best_index == 0);
CPPUNIT_ASSERT(g._grid[0][0] == NULL);
CPPUNIT_ASSERT(g.isMoved[0][0] == false);
}
void test_game_default_2 (){
Game<5,5,1,1> g;
CPPUNIT_ASSERT(g._Height == 5);
CPPUNIT_ASSERT(g._Width == 5);
CPPUNIT_ASSERT(g.turn == 0);
CPPUNIT_ASSERT(g.Food_index == 0);
CPPUNIT_ASSERT(g.Hopper_index == 0);
CPPUNIT_ASSERT(g.Rover_index == 0);
CPPUNIT_ASSERT(g.Trap_index == 0);
CPPUNIT_ASSERT(g.Best_index == 0);
CPPUNIT_ASSERT(g._grid[0][0] == NULL);
CPPUNIT_ASSERT(g.isMoved[0][0] == false);
}
void test_game_default_3 (){
Game<4,4,1,1> g;
CPPUNIT_ASSERT(g._Height == 4);
CPPUNIT_ASSERT(g._Width == 4);
CPPUNIT_ASSERT(g.turn == 0);
CPPUNIT_ASSERT(g.Food_index == 0);
CPPUNIT_ASSERT(g.Hopper_index == 0);
CPPUNIT_ASSERT(g.Rover_index == 0);
CPPUNIT_ASSERT(g.Trap_index == 0);
CPPUNIT_ASSERT(g.Best_index == 0);
CPPUNIT_ASSERT(g._grid[0][0] == NULL);
CPPUNIT_ASSERT(g.isMoved[0][0] == false);
}
// test game put
void test_game_put_1 (){
Game<4,4,1,1> g;
Food a = 1;
Trap b = 1;
Rover c = 1;
Hopper d = 1;
g.put(a,1,1);
g.put(b,2,1);
g.put(c,3,1);
g.put(d,4,1);
CPPUNIT_ASSERT(g._grid[1][1] == &a);
CPPUNIT_ASSERT(g._grid[2][1] == &b);
CPPUNIT_ASSERT(g._grid[3][1] == &c);
CPPUNIT_ASSERT(g._grid[4][1] == &d);
}
void test_game_put_2 (){
Game<4,4,1,1> g;
Food a = 1;
Trap b = 1;
Rover c = 1;
Hopper d = 1;
Food f;
Trap j;
Hopper h;
g.put(a,1,1);
g.put(b,2,1);
g.put(c,3,1);
g.put(d,4,1);
g.put(f,2,2);
g.put(j,3,3);
g.put(h,3,2);
CPPUNIT_ASSERT(g._grid[1][1] == &a);
CPPUNIT_ASSERT(g._grid[2][1] == &b);
CPPUNIT_ASSERT(g._grid[3][1] == &c);
CPPUNIT_ASSERT(g._grid[4][1] == &d);
CPPUNIT_ASSERT(g._grid[2][2] == &f);
CPPUNIT_ASSERT(g._grid[3][3] == &j);
CPPUNIT_ASSERT(g._grid[3][2] == &h);
}
void test_game_put_3 (){
Game<4,4,1,1> g;
Food a = 1;
Trap b = 1;
Rover c = 1;
Hopper d = 1;
g.put(a,1,1);
g.put(b,2,1);
g.put(c,3,1);
g.put(d,0,1);
ostringstream before, after,u;
g.printGrid(before);
// g.printGrid(cout);
CPPUNIT_ASSERT(before.str() == "0 .h..\n1 .f..\n2 .t..\n3 .r..\n\n");
CPPUNIT_ASSERT(g._grid[1][1] == &a);
CPPUNIT_ASSERT(g._grid[2][1] == &b);
CPPUNIT_ASSERT(g._grid[3][1] == &c);
CPPUNIT_ASSERT(g._grid[0][1] == &d);
}
void test_run_put_1 (){
Game<3,3,1,1> g;
ostringstream before, beforeHop, dummy, afterHop;
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ...\n1 ...\n2 ...\n\n");
Trap t1 = 0;
Rover r1 = 1;
Trap t2 = 2;
Trap t3 = 3;
Trap t4 = 3;
Trap t5 = 2;
Rover r2 = 1;
Rover r3 = 1;
Rover r4 = 0;
g.put(t1,2,2);
g.put(r2,1,1);
g.put(r1,0,0);
g.put(t2,0,1);
g.put(r3,0,2);
g.put(t3,1,2);
g.put(t4,2,0);
g.put(r4,2,1);
g.put(t5,1,0);
g.printGrid(beforeHop);
// g.printGrid(cout);
CPPUNIT_ASSERT(beforeHop.str() == "0 rtr\n1 trt\n2 trt\n\n");
g.run(dummy);
// g.printGrid(cout);
g.printGrid(afterHop);
CPPUNIT_ASSERT(afterHop.str() == "0 rtt\n1 ttt\n2 rtt\n\n");
}
void test_run_put_2 (){
Game<3,3,1,1> g;
ostringstream before, beforeHop, dummy, afterHop;
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ...\n1 ...\n2 ...\n\n");
Trap t1 = 0;
Rover r1 = 1;
Trap t2 = 2;
Trap t3 = 3;
Trap t4 = 3;
Trap t5 = 2;
Rover r2 = 1;
Rover r3 = 1;
Rover r4 = 0;
g.put(t1,2,2);
g.put(r2,1,1);
g.put(r1,0,0);
g.put(t2,0,1);
g.put(r3,0,2);
g.put(t3,1,2);
g.put(t4,2,0);
g.put(r4,2,1);
g.put(t5,1,0);
g.printGrid(beforeHop);
// g.printGrid(cout);
CPPUNIT_ASSERT(beforeHop.str() == "0 rtr\n1 trt\n2 trt\n\n");
g.run(dummy);
// g.printGrid(cout);
g.printGrid(afterHop);
CPPUNIT_ASSERT(afterHop.str() == "0 rtt\n1 ttt\n2 rtt\n\n");
}
void test_run_put_3 (){
Game<3,3,1,1> g;
ostringstream before, beforeHop, dummy, afterHop;
g.printGrid(before);
CPPUNIT_ASSERT(before.str() == "0 ...\n1 ...\n2 ...\n\n");
Trap t1 = 0;
Rover r1 = 1;
Trap t2 = 2;
Trap t3 = 3;
Trap t4 = 3;
Trap t5 = 2;
Rover r2 = 1;
Rover r3 = 1;
Rover r4 = 0;
g.put(t1,2,2);
g.put(r2,1,1);
g.put(r1,0,0);
g.put(t2,0,1);
g.put(r3,0,2);
g.put(t3,1,2);
g.put(t4,2,0);
g.put(r4,2,1);
g.put(t5,1,0);
g.printGrid(beforeHop);
// g.printGrid(cout);
CPPUNIT_ASSERT(beforeHop.str() == "0 rtr\n1 trt\n2 trt\n\n");
g.run(dummy);
// g.printGrid(cout);
g.printGrid(afterHop);
CPPUNIT_ASSERT(afterHop.str() == "0 rtt\n1 ttt\n2 rtt\n\n");
}
// -----
// suite
// -----
CPPUNIT_TEST_SUITE(TestDarwin);
// test creature default constructor
CPPUNIT_TEST(test_creature_default_creature_1);
CPPUNIT_TEST(test_creature_default_creature_2);
CPPUNIT_TEST(test_creature_default_creature_3);
// test creature int constructor
CPPUNIT_TEST(test_creature_int_constuctors_1);
CPPUNIT_TEST(test_creature_int_constuctors_2);
CPPUNIT_TEST(test_creature_int_constuctors_3);
// test creature reset
CPPUNIT_TEST(test_creature_reset_1);
CPPUNIT_TEST(test_creature_reset_2);
CPPUNIT_TEST(test_creature_reset_3);
// test creature getName
CPPUNIT_TEST(test_creature_getName_1);
CPPUNIT_TEST(test_creature_getName_2);
CPPUNIT_TEST(test_creature_getName_3);
//test creature getDirection
CPPUNIT_TEST(test_creature_getDirection_1);
CPPUNIT_TEST(test_creature_getDirection_2);
CPPUNIT_TEST(test_creature_getDirection_3);
// test creature setD
CPPUNIT_TEST(test_creature_setD_1);
CPPUNIT_TEST(test_creature_setD_2);
CPPUNIT_TEST(test_creature_setD_3);
// test creature virtual action
CPPUNIT_TEST(test_creature_virtual_action_1);
CPPUNIT_TEST(test_creature_virtual_action_1);
CPPUNIT_TEST(test_creature_virtual_action_1);
// test creature turn left
CPPUNIT_TEST(test_creature_left_1);
CPPUNIT_TEST(test_creature_left_2);
CPPUNIT_TEST(test_creature_left_3);
// test creature turn right
CPPUNIT_TEST(test_creature_right_1);
CPPUNIT_TEST(test_creature_right_2);
CPPUNIT_TEST(test_creature_right_3);
// test creature hop
CPPUNIT_TEST(test_creature_hop_1);
CPPUNIT_TEST(test_creature_hop_2);
CPPUNIT_TEST(test_creature_hop_3);
// test creature isEnemy
CPPUNIT_TEST(test_creature_isEnemy_1);
CPPUNIT_TEST(test_creature_isEnemy_2);
CPPUNIT_TEST(test_creature_isEnemy_3);
// test creature isEmpty
CPPUNIT_TEST(test_creature_isEmpty_1);
CPPUNIT_TEST(test_creature_isEmpty_2);
CPPUNIT_TEST(test_creature_isEmpty_3);
// test food default constructor
CPPUNIT_TEST(test_food_default_constructor_1);
CPPUNIT_TEST(test_food_default_constructor_2);
CPPUNIT_TEST(test_food_default_constructor_3);
//test food int constructor
CPPUNIT_TEST(test_food_int_constructor_1);
CPPUNIT_TEST(test_food_int_constructor_2);
CPPUNIT_TEST(test_food_int_constructor_3);
//test food getName
CPPUNIT_TEST(test_food_getName_1);
CPPUNIT_TEST(test_food_getName_2);
CPPUNIT_TEST(test_food_getName_3);
// test food action
CPPUNIT_TEST(test_food_action_1);
CPPUNIT_TEST(test_food_action_2);
CPPUNIT_TEST(test_food_action_3);
//test hopper default constructor
CPPUNIT_TEST(test_hopper_default_constructor_1);
CPPUNIT_TEST(test_hopper_default_constructor_2);
CPPUNIT_TEST(test_hopper_default_constructor_3);
// test hopper int constructor
CPPUNIT_TEST(test_hopper_int_constructor_1);
CPPUNIT_TEST(test_hopper_int_constructor_2);
CPPUNIT_TEST(test_hopper_int_constructor_3);
//test hopper getName
CPPUNIT_TEST(test_hopper_getName_1);
CPPUNIT_TEST(test_hopper_getName_2);
CPPUNIT_TEST(test_hopper_getName_3);
//test hopper action
CPPUNIT_TEST(test_hopper_action_1);
CPPUNIT_TEST(test_hopper_action_2);
CPPUNIT_TEST(test_hopper_action_3);
//test rover default constructor
CPPUNIT_TEST(test_rover_default_constructor_1);
CPPUNIT_TEST(test_rover_default_constructor_2);
CPPUNIT_TEST(test_rover_default_constructor_3);
// test rover int constructor
CPPUNIT_TEST(test_rover_int_constructor_1);
CPPUNIT_TEST(test_rover_int_constructor_2);
CPPUNIT_TEST(test_rover_int_constructor_3);
//test rover getName
CPPUNIT_TEST(test_rover_getName_1);
CPPUNIT_TEST(test_rover_getName_2);
CPPUNIT_TEST(test_rover_getName_3);
//test rover action
CPPUNIT_TEST(test_rover_action_1);
CPPUNIT_TEST(test_rover_action_2);
CPPUNIT_TEST(test_rover_action_3);
//test trap default constructor
CPPUNIT_TEST(test_trap_default_constructor_1);
CPPUNIT_TEST(test_trap_default_constructor_2);
CPPUNIT_TEST(test_trap_default_constructor_3);
// test trap int constructor
CPPUNIT_TEST(test_trap_int_constructor_1);
CPPUNIT_TEST(test_trap_int_constructor_2);
CPPUNIT_TEST(test_trap_int_constructor_3);
//test trap getName
CPPUNIT_TEST(test_trap_getName_1);
CPPUNIT_TEST(test_trap_getName_2);
CPPUNIT_TEST(test_trap_getName_3);
//test trap action
CPPUNIT_TEST(test_trap_action_1);
CPPUNIT_TEST(test_trap_action_2);
CPPUNIT_TEST(test_trap_action_3);
// test game default constructor
CPPUNIT_TEST(test_game_default_1);
CPPUNIT_TEST(test_game_default_2);
CPPUNIT_TEST(test_game_default_3);
// test game put
CPPUNIT_TEST(test_game_put_1);
CPPUNIT_TEST(test_game_put_2);
CPPUNIT_TEST(test_game_put_3);
//test game run
CPPUNIT_TEST(test_run_put_1);
CPPUNIT_TEST(test_run_put_2);
CPPUNIT_TEST(test_run_put_3);
// //test_infect_helper
// CPPUNIT_TEST(test_infect_helper_1);
// CPPUNIT_TEST(test_infect_helper_2);
// CPPUNIT_TEST(test_infect_helper_3);
// // test action inst
// CPPUNIT_TEST(test_action_inst_1);
// CPPUNIT_TEST(test_action_inst_2);
// CPPUNIT_TEST(test_action_inst_3);
// // if empty
// CPPUNIT_TEST(test_empty_1);
// CPPUNIT_TEST(test_empty_2);
// CPPUNIT_TEST(test_empty_3);
// // test if wall
// CPPUNIT_TEST(test_if_wall_1);
// CPPUNIT_TEST(test_if_wall_2);
// CPPUNIT_TEST(test_if_wall_3);
// // test if random
// CPPUNIT_TEST(test_if_random_1);
// CPPUNIT_TEST(test_if_random_2);
// CPPUNIT_TEST(test_if_random_3);
// // test if enemy
// CPPUNIT_TEST(test_if_enemy_1);
// CPPUNIT_TEST(test_if_enemy_2);
// CPPUNIT_TEST(test_if_enemy_3);
// // test go
// CPPUNIT_TEST(test_go_1);
// CPPUNIT_TEST(test_go_2);
// CPPUNIT_TEST(test_go_3);
// // test run game
// CPPUNIT_TEST(test_run_game_1);
// CPPUNIT_TEST(test_run_game_2);
// CPPUNIT_TEST(test_run_game_3);
// CPPUNIT_TEST(test_run_game_4);
CPPUNIT_TEST_SUITE_END();};
// ----
// main
// ----
int main () {
using namespace std;
ios_base::sync_with_stdio(false); // turn off synchronization with C I/O
cout << "TestDarwin.c++" << endl;
CppUnit::TextTestRunner tr;
tr.addTest(TestDarwin::suite());
tr.run();
cout << "Done." << endl;
return 0;}
|
|
a8ba20030d484f36f67b6cf4d351faa16d56ae60
|
590eb4cc4d0fe83d9740ce478f857ca3a98e7dae
|
/OGDF/include/ogdf/internal/planarity/BoyerMyrvoldInit.h
|
51fa7b30468eccf215d019e4c1f232030b63536e
|
[
"LGPL-2.1-or-later",
"GPL-3.0-only",
"GPL-1.0-or-later",
"EPL-1.0",
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-generic-exception",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
cerebis/MetaCarvel
|
d0ca77645e9a964e349144974a05e17fa48c6e99
|
a047290e88769773d43e0a9f877a88c2a8df89d5
|
refs/heads/master
| 2020-12-05T05:40:19.460644
| 2020-01-06T05:38:34
| 2020-01-06T05:38:34
| 232,023,146
| 0
| 0
|
MIT
| 2020-01-06T04:22:00
| 2020-01-06T04:21:59
| null |
UTF-8
|
C++
| false
| false
| 4,714
|
h
|
BoyerMyrvoldInit.h
|
/** \file
* \brief Declaration of the classes BoyerMyrvoldInit and BucketLowPoint
*
* \author Jens Schmidt
*
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.txt in the root directory of the OGDF installation for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* \see http://www.gnu.org/copyleft/gpl.html
***************************************************************/
#ifdef _MSC_VER
#pragma once
#endif
#ifndef OGDF_BOYER_MYRVOLD_INIT_H
#define OGDF_BOYER_MYRVOLD_INIT_H
#include <random>
#include <limits>
#include <ogdf/internal/planarity/BoyerMyrvoldPlanar.h>
#include <ogdf/basic/List.h>
namespace ogdf {
//! This class is used in the Boyer-Myrvold planarity test for preprocessing purposes.
/**
* Among these is the computation of lowpoints, highestSubtreeDFIs,
* separatedDFSChildList and of course building the DFS-tree.
*/
class BoyerMyrvoldInit {
public:
//! Constructor, the parameter BoyerMyrvoldPlanar is needed
BoyerMyrvoldInit(BoyerMyrvoldPlanar* pBM);
//! Destructor
~BoyerMyrvoldInit() { }
//! Creates the DFSTree
void computeDFS();
//! Computes lowpoint, highestSubtreeDFI and links virtual to nonvirtual vertices
void computeLowPoints();
//! Computes the list of separated DFS children for all nodes
void computeDFSChildLists();
// avoid automatic creation of assignment operator
//! Assignment operator is undefined!
BoyerMyrvoldInit &operator=(const BoyerMyrvoldInit &);
private:
//! The input graph
Graph& m_g;
//! Some parameters... see BoyerMyrvold.h for further instructions
const int& m_embeddingGrade;
const double& m_randomness;
const EdgeArray<int> *m_edgeCosts;
std::minstd_rand m_rand;
//! Link to non-virtual vertex of a virtual Vertex.
/** A virtual vertex has negative DFI of the DFS-Child of related non-virtual Vertex
*/
NodeArray<node>& m_realVertex;
//! The one and only DFI-Array
NodeArray<int>& m_dfi;
//! Returns appropriate node from given DFI
Array<node>& m_nodeFromDFI;
//! Links to opposite adjacency entries on external face in clockwise resp. ccw order
/** m_link[0]=CCW, m_link[1]=CW
*/
NodeArray<adjEntry> (&m_link)[2];
//! The adjEntry which goes from DFS-parent to current vertex
NodeArray<adjEntry>& m_adjParent;
//! The DFI of the least ancestor node over all backedges
/** If no backedge exists, the least ancestor is the DFI of that node itself
*/
NodeArray<int>& m_leastAncestor;
//! Contains the type of each \a edge
/** @param 0 = EDGE_UNDEFINED
* @param 1 = EDGE_SELFLOOP
* @param 2 = EDGE_BACK
* @param 3 = EDGE_DFS
* @param 4 = EDGE_DFS_PARALLEL
* @param 5 = EDGE_BACK_DELETED
*/
EdgeArray<int>& m_edgeType;
//! The lowpoint of each \a node
NodeArray<int>& m_lowPoint;
//! The highest DFI in a subtree with \a node as root
NodeArray<int>& m_highestSubtreeDFI;
//! A list to all separated DFS-children of \a node
/** The list is sorted by lowpoint values (in linear time)
*/
NodeArray<ListPure<node> >& m_separatedDFSChildList;
//! Pointer to \a node contained in the DFSChildList of his parent, if exists.
/** If node isn't in list or list doesn't exist, the pointer is set to nullptr.
*/
NodeArray<ListIterator<node> >& m_pNodeInParent;
//! Creates and links a virtual vertex of the node belonging to \a father
void createVirtualVertex(const adjEntry father);
};
//! BucketFunction for lowPoint buckets
/** Parameter lowPoint may not be deleted til destruction of this class.
*/
class BucketLowPoint : public BucketFunc<node> {
public:
BucketLowPoint(const NodeArray<int>& lowPoint) :m_pLow(&lowPoint) { }
//! This function has to be derived from BucketFunc, it gets the buckets from lowPoint-Array
int getBucket(const node& v) {
return (*m_pLow)[v];
}
private:
//! Stored to be able to get the buckets
const NodeArray<int>* m_pLow;
};
}
#endif
|
bf1fcd449abe198ef8b024488e48d894bb06e3d1
|
aa4f0d4d62eda5b49e884f59837319527edc8bef
|
/shape_recognition/matlab_fcn.cpp
|
aa2188cb21a6a9d3d63b2ddbdda3f0cc971b4686
|
[] |
no_license
|
gxfgithub/shape_recognition
|
a92e6cd2e27cb9ea83a971b0145c26d02a3ad983
|
229da0c8a3b7d7c4272e4832a81bd00bd1b1c004
|
refs/heads/master
| 2021-06-12T18:18:11.237806
| 2017-03-23T04:49:18
| 2017-03-23T04:49:18
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,151
|
cpp
|
matlab_fcn.cpp
|
#include "matlab_fcn.h"
String fullfile(String a, String b) {
String c(a + "\\" + b);
return c;
}
clock_t ticTime;
void tic() {
ticTime = clock();
}
float toc() {
clock_t tocTime = clock();
return (float)(tocTime - ticTime) / CLOCKS_PER_SEC;
}
//只读取某给定路径下的当前文件夹名
void getJustCurrentDir(string path, vector<string>& files)
{
//文件句柄
long long hFile = 0;
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
files.push_back(fileinfo.name);
//files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
}
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
//只读取某给定路径下的当前文件名:
void getJustCurrentFile(string path, vector<string>& files)
{
//文件句柄
long long hFile = 0;
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
;
}
else
{
files.push_back(fileinfo.name);
//files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
//只读取某给定路径下的所有文件名(即包含当前目录及子目录的文件):
void getFilesAll(string path, vector<string>& files)
{
//文件句柄
long long hFile = 0;
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
//files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
getFilesAll(p.assign(path).append("\\").append(fileinfo.name), files);
}
}
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
//读取某给定路径下所有文件夹与文件名称,并带完整路径
void getAllFiles(string path, vector<string>& files)
{
//文件句柄
long long hFile = 0;
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
getFilesAll(p.assign(path).append("\\").append(fileinfo.name), files);
}
}
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
ImageDataStore::ImageDataStore(String location) {
getJustCurrentDir(location, categories);
const unsigned int categoriesNum = categories.size();
for (unsigned int i = 0; i < categoriesNum; i++) {
string folderDir = fullfile(location, categories[i]);
vector<string> imDir;
getAllFiles(folderDir, imDir);
//拼接files向量和imDir向量
files.insert(files.end(), imDir.begin(), imDir.end());
//向labels添加标签
labels.reserve(labels.size() + imDir.size());
const unsigned long imDirNum = imDir.size();
for (unsigned long j = 0; j < imDirNum; j++) {
labels.push_back(i);
}
}
}
Mat ImageDataStore::readImage(unsigned long i, int flags) {
Mat im = imread(files[i], flags);
return im;
}
vector<unsigned int> vec2ind(Mat x) {
vector<unsigned int> index;
index.reserve(x.rows);
const unsigned long rowNum = x.rows;
for (unsigned long i = 0; i < rowNum; i++) {
unsigned int indexMax=0;
float max = x.at<float>(i, 0);
for (unsigned int j = 1; j < x.cols; j++) {
if (x.at<float>(i, j) > max) {
max = x.at<float>(i, j);
indexMax = j;
}
}
index.push_back(indexMax);
}
return index;
}
|
0f26c3c5611b1face7a12438ffff8c5c17c23f07
|
e6652252222ce9e4ff0664e539bf450bc9799c50
|
/d0706/7.6/source/SN-wsw4/name.cpp
|
76585a2f090e8c7d633072111d5babb34467a072
|
[] |
no_license
|
cjsoft/inasdfz
|
db0cea1cf19cf6b753353eda38d62f1b783b8f76
|
3690e76404b9189e4dd52de3770d59716c81a4df
|
refs/heads/master
| 2021-01-17T23:13:51.000569
| 2016-07-12T07:21:19
| 2016-07-12T07:21:19
| 62,596,117
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 839
|
cpp
|
name.cpp
|
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstring>
#define maxn 100010
using namespace std;
int read(){
char c=getchar();
int y=0,tim=1;
while(c>'9'||c<'0'){
if(c=='-')tim=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
y=y*10+c-'0';
c=getchar();
}
return tim*y;
}
int n,m,vi[maxn][2]={0};
int xi[maxn]={0};
void work1(){
long long int ans=0;
int i,l,r,t;
for(i=1;i<=n;i++)vi[i][0]=read();
for(i=1;i<=n;i++)vi[i][1]=read();
m=read();
while(m--){
l=read();r=read();t=read();
for(i=l;i<=r;i++)
if(vi[i][xi[i]]<=t)xi[i]^=1;
}
for(i=1;i<=n;i++)ans+=vi[i][xi[i]];
cout<<ans<<endl;
}
int main(){
freopen("name.in","r",stdin);
freopen("name.out","w",stdout);
int i,x,y;
n=read();
work1();
return 0;
}
|
4eb4a2a47da1636aaafcc4d0fa6149aebe50ded0
|
f0749ffea2a953a324a26906b7dc3bd95ac06e60
|
/Core/Color/RGBTraits.cc
|
d25e8b5e54a555da4bc1bafe380cddb581da98cd
|
[
"MIT"
] |
permissive
|
jeffamstutz/rfManta
|
36970d20ef79907db250da83ec1e672943c199fe
|
77b3f8688f09719a9027a02777832bb734fc8431
|
refs/heads/master
| 2021-01-10T08:57:37.803549
| 2015-03-13T12:47:47
| 2015-03-13T12:47:47
| 48,449,383
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 239
|
cc
|
RGBTraits.cc
|
#include <Core/Color/RGBTraits.h>
#include <Core/Color/ColorSpace.h>
using namespace Manta;
using namespace std;
template<>
bool MantaRTTI<ColorSpace<RGBTraits> >::force_initialize = MantaRTTI<ColorSpace<RGBTraits> >::registerClass();
|
3abc0dd1ff838a9de61124919cdc201cd24a7b28
|
c191edd05a993c4248459219e9f17fc933626435
|
/MusicStructure.h
|
8068fe5cbb91694fe1b7899f2f479af6bfb606ec
|
[] |
no_license
|
prithviKantanAAU/GaitSoni-PostThesis
|
d49c701c50fc7e538771c5247b6d53ce4422ff5c
|
7f24bcb98b690473e2528e7aeaa855ea11fb4a29
|
refs/heads/master
| 2023-02-09T21:47:35.259905
| 2021-01-07T23:10:06
| 2021-01-07T23:10:06
| 285,592,406
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,610
|
h
|
MusicStructure.h
|
#pragma once
class MusicStructure
{
public:
MusicStructure();
~MusicStructure();
int numTrackMuteCombinations = 6;
int melodicMeasuresPerFile = 24;
int numSongStructures = 5;
short trackMuteConfigurations[11][8] =
{
{0, 0, 0, 0, 0, 0, 0, 0}, // All // 10 //M
{0, 0, 0, 0, 0, 0, 0, 0}, // All // 10 //M
{0, 0, 0, 0, 0, 0, 0, 0}, // All // 10 //M
{0, 0, 0, 0, 0, 0, 0, 0}, // All // 10 //M
{0, 0, 0, 0, 0, 0, 0, 0}, // All // 10 //M
{0, 0, 0, 0, 0, 0, 0, 0}, // All // 10 //M
{0, 0, 0, 0, 0, 0, 0, 0}, // All // 10 //M
{0, 0, 0, 0, 0, 0, 0, 0}, // All // 10 //M
{0, 0, 0, 0, 0, 0, 0, 0}, // All // 10 //M
{0, 0, 0, 0, 0, 0, 0, 0}, // All // 10 //M
{0, 0, 0, 0, 0, 0, 0, 0} // All // 10 //M
};
short muteStructuresPerc_L1[5] = { 0, 1, 2, 3, 4};
short muteStructuresPerc_L2[4] = { 5, 6, 7, 8 };
short muteStructuresPerc_L3 = 9;
short muteStructuresPerc_L4 = 10;
short songPatterns[5][24]
{
{4, 5, 0, 1, 6, 7, 8, 8, 9, 9, 10, 10, 2, 2, 3, 3, 8, 8, 8, 8, 9, 9, 10, 10},
{0, 0, 1, 1, 5, 5, 7, 7, 8, 9, 10, 10, 1, 2, 3, 3, 6, 7, 8, 4, 9, 9, 10, 10},
{1, 1, 2, 3, 4, 4, 6, 7, 8, 8, 9, 9, 9, 9, 10, 10, 0, 1, 7, 7, 8, 9, 10, 10},
{2, 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 10, 10, 1, 1, 2, 3, 5, 9, 10, 10},
{0, 1, 7, 8, 3, 3, 9, 10, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9, 9, 4, 10, 10, 10, 10}
};
short arpMode[24] =
{
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0
};
int level_Perc[24] =
{ 0, 0, 1, 1,
1, 1, 1, 1,
2, 2, 2, 2,
2, 2, 3, 3,
3, 3, 3, 3,
3, 3, 3, 3
};
int mute_Kick[24] =
{ 1, 1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
int mute_Snare[24] =
{ 1, 1,
1, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
int mute_HH[24] =
{ 1, 1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
int mute_Chords[24] =
{ 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
};
int mute_Riff[24] =
{ 1, 1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
int mute_Melody[24] =
{ 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
int mute_ChordStabs[24] =
{ 1, 1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
};
|
20ac92451c05ae826ce9860e29a8ee39ddfe118d
|
b04636f31f716c21a6c0d77bc49b876bc496fff7
|
/Codeforces/1234/a.cpp
|
6ce6abb74a348dd014e4657e5ee54b8ce73a2e97
|
[] |
no_license
|
khanhvu207/competitiveprogramming
|
736b15d46a24b93829f47e5a7dbcf461f4c30e9e
|
ae104488ec605a3d197740a270058401bc9c83df
|
refs/heads/master
| 2021-12-01T00:52:43.729734
| 2021-11-23T23:29:31
| 2021-11-23T23:29:31
| 158,355,181
| 19
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 496
|
cpp
|
a.cpp
|
#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long
using namespace std;
void solve(){
int n;
cin>>n;
vector<int> a(n);
for(int& x:a) cin>>x;
ll sum=accumulate(a.begin(),a.end(),0);
ll res=(sum+n-1)/n;
cout<<res<<'\n';
}
int main() {
#ifdef kvutxdy
freopen("C:/Users/khanh/OneDrive/RoadtoPurple/Code/Codeforces/input.in", "r", stdin);
#endif
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t;
cin>>t;
while(t--) solve();
}
|
e804edcaeaffd8c364afa480229fa9f99f648ec7
|
120f701ee4439524534294fac5401c97bbe4d28f
|
/main.cpp
|
36585aaef0a72ecd1a9b2961b68ec4d10a684200
|
[] |
no_license
|
alessadge/Examen120172-AlessandroGrimaldi
|
1dae1a7bf60ff443e270c501bcc2fe51af347e7b
|
37cc7d5109e972569e97c65d1147e599d6ca81c7
|
refs/heads/master
| 2021-01-21T15:18:20.491476
| 2017-05-19T23:46:00
| 2017-05-19T23:46:00
| 91,836,332
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,523
|
cpp
|
main.cpp
|
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include "Obras.h"
#include "Literatura.h"
#include "Esculturas.h"
#include "Disenos.h"
#include "Pinturas.h"
#include <stdlib.h>
using namespace std;
string hexadecimal(vector<Obras>);
int main(){
char opcion;
char opcion2;
vector<string> arreglo;
vector<Obras> Museo;
vector<Obras> Transferir;
string nombre, ID="", autor, artista;
int fechaIngresada;
while(opcion!='f'){
cout<<endl<<"MENU:"<<endl
<<"a. Agregar"<<endl
<<"b. Eliminar"<<endl
<<"c. Transferir Museo"<<endl
<<"d. Reportes"<<endl
<<"e. Buscar autor"<<endl
<<"f. Salir"<<endl;
cin>>opcion;
if(opcion=='a'||opcion=='A'){
cout<<endl<<"Agregar: "<<endl
<<"a. Literatura"<<endl
<<"b. Esculturas"<<endl
<<"c. Pintura"<<endl
<<"d. Diseno"<<endl;
cin>>opcion2;
if(opcion2=='a'||opcion2=='A'){
string genero, epoca;
cout<<"Ingrese un nombre: "<<endl;
cin>>nombre;
cout<<"Ingrese un autor: "<<endl;
cin>>autor;
cout<<"Ingrese un artista: "<<endl;
cin>>artista;
cout<<"Ingrese fecha: "<<endl;
cin>>fechaIngresada;
cout<<"Ingrese el genero: "<<endl;
cin>>genero;
cout<<"Ingrese la epoca: "<<endl;
cin>>epoca;
ID=hexadecimal(Museo);
Museo.push_back(Literatura(genero, epoca,nombre, ID, autor, artista,fechaIngresada));
//Museo[0].setID(ID);
cout<<"Se agrego exitosamente! "<<endl;
}
if(opcion2=='b'||opcion2=='B'){
string material;
double peso;
cout<<"Ingrese un nombre: "<<endl;
cin>>nombre;
cout<<"Ingrese un autor: "<<endl;
cin>>autor;
cout<<"Ingrese un artista: "<<endl;
cin>>artista;
cout<<"Ingrese fecha: "<<endl;
cin>>fechaIngresada;
cout<<"Ingrese el material: "<<endl;
cin>>material;
cout<<"Ingrese el peso: "<<endl;
cin>>peso;
ID=hexadecimal(Museo);
Museo.push_back( Esculturas(peso,material,nombre,ID,autor,artista,fechaIngresada));
cout<<"Se agrego exitosamente! "<<endl;
}
if(opcion2=='c'||opcion2=='C'){
string tecnica, material;
cout<<"Ingrese un nombre: "<<endl;
cin>>nombre;
cout<<"Ingrese un autor: "<<endl;
cin>>autor;
cout<<"Ingrese un artista: "<<endl;
cin>>artista;
cout<<"Ingrese fecha: "<<endl;
cin>>fechaIngresada;
cout<<"Ingrese el material: "<<endl;
cin>>material;
cout<<"Ingrese la tecnica: "<<endl;
cin>>tecnica;
ID=hexadecimal(Museo);
Museo.push_back(Pinturas(tecnica,material,nombre,ID,autor,artista,fechaIngresada));
cout<<"Se agrego exitosamente!"<<endl;
}
if(opcion2=='d'||opcion2=='D'){
string terreno;
cout<<"Ingrese un nombre: "<<endl;
cin>>nombre;
cout<<"Ingrese un autor: "<<endl;
cin>>autor;
cout<<"Ingrese un artista: "<<endl;
cin>>artista;
cout<<"Ingrese fecha: "<<endl;
cin>>fechaIngresada;
cout<<"Ingrese el terreno: "<<endl;
cin>>terreno;
ID=hexadecimal(Museo);
Museo.push_back(Disenos(terreno,nombre, ID, autor,artista, fechaIngresada));
cout<<"Se agrego exitosamente!"<<endl;
}//fin D
}
if(opcion=='b'||opcion=='B'){
int pos;
cout<<"Cual posicion quiere eliminar? "<<endl;
cin>>pos;
Museo.erase(Museo.begin()+pos);
cout<<"Se elimino exitosamente"<<endl;
}//fin if b
if(opcion=='c'||opcion=='C'){
int pos;
cout<<"Cual posicion quiere transferir? "<<endl;
cin>>pos;
Transferir.push_back(Museo[pos]);
Museo.erase(Museo.begin()+pos);
}//fin if c
if(opcion=='d'||opcion=='D'){
cout<<"Museos: "<<endl;
for(int i=0; i<Museo.size();i++){
cout<<i<<".) "<<Museo[i].getNombre()<<" "<<Museo[i].getID()<<" "<<Museo[i].getAutor()<<" "<<Museo[i].getArtista()<<endl;
}
cout<<"Transferidos: "<<endl;
for(int i=0; i<Transferir.size();i++){
cout<<i<<".) "<<Transferir[i].getNombre()<<" "<<Transferir[i].getID()<<" "<<Transferir[i].getAutor()<<" "<<Transferir[i].getArtista()<<endl;
}
}//fin if d
if(opcion=='e'||opcion=='E'){
string autor;
cout<<"Ingrese el nombre del autor"<<endl;
cin>>autor;
for(int i = 0; i<Museo.size();i++){
if(autor==Museo[i].getAutor()){
cout<<Museo[i].getNombre()<<endl;
}
}
}//fin if e
}
return 0;
}
string hexadecimal(vector<Obras> arreglo){
vector<string> pauta;
string acum;
int random;
int contador=0;
pauta.push_back("1");
pauta.push_back("2");
pauta.push_back("3");
pauta.push_back("4");
pauta.push_back("5");
pauta.push_back("6");
pauta.push_back("7");
pauta.push_back("8");
pauta.push_back("9");
pauta.push_back("A");
pauta.push_back("B");
pauta.push_back("C");
pauta.push_back("D");
pauta.push_back("E");
pauta.push_back("F");
while(contador==0){
for(int f = 0; f < 6; f++){
random = rand()%15;
acum=acum+ pauta[random];
}
contador=1;
for(int i = 0; i < arreglo.size();i++){
if(acum==arreglo[i].getID()){
contador=1;
}
cout<<acum<<endl;
}
}
return acum;
}
|
e89f97e94e072e16326f8e4fe48445397fd7c9ba
|
eac6cf47d690e9ed35f2b07cc77f5c5ca772dc8c
|
/core/base/geometry/Geometry.h
|
1d6b057c6ca6f2a5134763f30dc4f832fef848ae
|
[
"BSD-3-Clause"
] |
permissive
|
JonasLukasczyk/ttk
|
e0c782cffc13379444615f5e7fe2d0fb4a4ffd22
|
34f6c6b8f113ab7edae8be8c527f60639833e869
|
refs/heads/stable
| 2023-01-22T08:34:32.219078
| 2020-01-29T15:04:01
| 2020-01-29T15:04:01
| 152,736,705
| 1
| 0
|
NOASSERTION
| 2018-10-12T10:48:23
| 2018-10-12T10:48:23
| null |
UTF-8
|
C++
| false
| false
| 12,479
|
h
|
Geometry.h
|
/// \ingroup base
/// \class ttk::Geometry
/// \author Julien Tierny <julien.tierny@lip6.fr>
/// \date February 2016.
///
/// \brief Minimalist class that handles simple geometric computations
/// (operations on std::vectors, barycentric coordinates, etc.).
///
#ifndef _GEOMETRY_H
#define _GEOMETRY_H
#include <Debug.h>
namespace ttk {
namespace Geometry {
/// Compute the angle between two std::vectors
/// \param vA0 xyz coordinates of vA's origin
/// \param vA1 xyz coordinates of vA's destination
/// \param vB0 xyz coordinates of vB's origin
/// \param vB1 xyz coordinates of vB's destination
template <typename T>
T angle(const T *vA0, const T *vA1, const T *vB0, const T *vB1);
/// Check if two 3D std::vectors vA and vB are colinear.
/// \param vA0 xyz coordinates of vA's origin
/// \param vA1 xyz coordinates of vA's destination
/// \param vB0 xyz coordinates of vB's origin
/// \param vB1 xyz coordinates of vB's destination
/// \param coefficients Optional output std::vector of colinearity
/// coefficients.
/// \returns Returns true if the std::vectors are colinear, false
/// otherwise.
template <typename T>
bool areVectorsColinear(const T *vA0,
const T *vA1,
const T *vB0,
const T *vB1,
std::vector<T> *coefficients = NULL,
const T *tolerance = NULL);
/// Compute the barycentric coordinates of point \p p with regard to the
/// edge defined by the 3D points \p p0 and \p p1.
/// \param p0 xyz coordinates of the first vertex of the edge
/// \param p1 xyz coordinates of the second vertex of the edge
/// \param p xyz coordinates of the queried point
/// \param baryCentrics Output barycentric coordinates (all in [0, 1] if
/// \p p belongs to the edge).
/// \param dimension Optional parameter that specifies the dimension of
/// the point set (by default 3).
/// \return Returns 0 upon success, negative values otherwise.
template <typename T>
int computeBarycentricCoordinates(const T *p0,
const T *p1,
const T *p,
std::vector<T> &baryCentrics,
const int &dimension = 3);
/// Compute the barycentric coordinates of point \p xyz with regard to
/// the edge defined by the points \p xy0 and \p xy1.
/// \param x0 x coordinate of the first vertex of the edge
/// \param y0 y coordinate of the first vertex of the edge
/// \param x1 x coordinate of the second vertex of the edge
/// \param y1 y coordinate of the second vertex of the edge
/// \param x x coordinate of the queried point
/// \param y y coordinate of the queried point
/// \param baryCentrics Output barycentric coordinates (all in [0, 1] if
/// \p p belongs to the edge).
/// \return Returns 0 upon success, negative values otherwise.
template <typename T>
int computeBarycentricCoordinates(const T &x0,
const T &y0,
const T &x1,
const T &y1,
const T &x,
const T &y,
std::vector<T> &baryCentrics);
/// Compute the barycentric coordinates of point \p p with regard to the
/// triangle defined by the 3D points \p p0, \p p1, and \p p2.
/// \param p0 xyz coordinates of the first vertex of the triangle
/// \param p1 xyz coordinates of the second vertex of the triangle
/// \param p2 xyz coordinates of the third vertex of the triangle
/// \param p xyz coordinates of the queried point
/// \param baryCentrics Output barycentric coordinates (all in [0, 1] if
/// \p p belongs to the triangle).
/// \return Returns 0 upon success, negative values otherwise.
template <typename T>
int computeBarycentricCoordinates(const T *p0,
const T *p1,
const T *p2,
const T *p,
std::vector<T> &baryCentrics);
/// Compute the intersection between two 2D segments AB and CD.
/// \param xA x coordinate of the first vertex of the first segment (AB)
/// \param yA y coordinate of the first vertex of the first segment (AB)
/// \param xB x coordinate of the second vertex of the first segment (AB)
/// \param yB y coordinate of the second vertex of the first segment (AB)
/// \param xC x coordinate of the first vertex of the second segment (CD)
/// \param yC y coordinate of the first vertex of the second segment (CD)
/// \param xD x coordinate of the second vertex of the second segment (CD)
/// \param yD y coordinate of the second vertex of the second segment (CD)
/// \param x x coordinate of the output intersection (if any).
/// \param y y coordinate of the output intersection (if any).
/// \return Returns true if the segments intersect (false otherwise).
template <typename T>
bool computeSegmentIntersection(const T &xA,
const T &yA,
const T &xB,
const T &yB,
const T &xC,
const T &yC,
const T &xD,
const T &yD,
T &x,
T &y);
/// Compute the angles of a triangle
/// \param p0 xyz coordinates of the first vertex of the triangle
/// \param p1 xyz coordinates of the second vertex of the triangle
/// \param p2 xyz coordinates of the third vertex of the triangle
/// \param angles Angles (p0p1, p1p2) (p1p2, p2p0) (p2p0, p0p1)
template <typename T>
int computeTriangleAngles(const T *p0,
const T *p1,
const T *p2,
std::vector<T> &angles);
/// Compute the area of a 3D triangle.
/// \param p0 xyz coordinates of the first vertex of the triangle
/// \param p1 xyz coordinates of the second vertex of the triangle
/// \param p2 xyz coordinates of the third vertex of the triangle
/// \param area Output area.
/// \return Returns 0 upon success, negative values otherwise.
template <typename T>
int computeTriangleArea(const T *p0, const T *p1, const T *p2, T &area);
/// Compute the cross product of two 3D std::vectors
/// \param vA0 xyz coordinates of vA's origin
/// \param vA1 xyz coordinates of vA's destination
/// \param vB0 xyz coordinates of vB's origin
/// \param vB1 xyz coordinates of vB's destination
/// \param crossProduct Output cross product.
/// \return Returns 0 upon success, negative values otherwise.
template <typename T>
int crossProduct(const T *vA0,
const T *vA1,
const T *vB0,
const T *vB1,
std::vector<T> &crossProduct);
/// Compute the cross product of two 3D std::vectors
/// \param vA xyz coordinates of vA std::vector
/// \param vB xyz coordinates of vB std::vector
/// \param crossProduct Output cross product.
/// \return Returns 0 upon success, negative values otherwise.
template <typename T>
int crossProduct(const T *vA, const T *vB, T *crossProduct);
/// Compute the Euclidean distance between two points
/// \param p0 xyz coordinates of the first input point.
/// \param p1 xyz coordinates of the second input point.
/// \param dimension Optional parameter that specifies the dimension of
/// the point set (by default 3).
template <typename T>
T distance(const T *p0, const T *p1, const int &dimension = 3);
/// Compute the dot product of two 3D std::vectors
/// \param vA0 xyz coordinates of vA's origin
/// \param vA1 xyz coordinates of vA's destination
/// \param vB0 xyz coordinates of vB's origin
/// \param vB1 xyz coordinates of vB's destination
/// \return Returns Output dot product
template <typename T>
T dotProduct(const T *vA0, const T *vA1, const T *vB0, const T *vB1);
/// Compute the dot product of two 3D std::vectors
/// \param vA0 xyz coordinates of vA std::vector
/// \param vB0 xyz coordinates of vB std::vector
/// \return Returns Output dot product
template <typename T>
T dotProduct(const T *vA, const T *vB);
/// Compute the bounding box of a point set.
/// \param points Vector of points. Each entry is a std::vector whose size
/// is
/// equal to the dimension of the space embedding the points.
/// \param bBox Output bounding box. The number of entries in this
/// std::vector
/// is equal to the dimension of the space embedding the points.
/// \return Returns 0 upon success, negative values otherwise.
template <typename T>
int getBoundingBox(const std::vector<std::vector<float>> &points,
std::vector<std::pair<T, T>> &bBox);
/// Check if the point \p p is inside the triangle (\p p0, \p p1, \p p2).
/// \param p0 xyz coordinates of the first vertex of the triangle
/// \param p1 xyz coordinates of the second vertex of the triangle
/// \param p2 xyz coordinates of the third vertex of the triangle
/// \param p xyz coordinates of the queried point
/// \return Returns true if \p p is in the triangle, false otherwise.
template <typename T>
bool isPointInTriangle(const T *p0, const T *p1, const T *p2, const T *p);
/// Check if a 2D point \p xy lies on a 2D segment \p AB.
/// \param x x coordinate of the input point.
/// \param y y coordinate of the input point.
/// \param xA x coordinate of the first vertex of the segment [AB]
/// \param yA y coordinate of the first vertex of the segment [AB]
/// \param xB x coordinate of the second vertex of the segment [AB]
/// \param yB y coordinate of the second vertex of the segment [AB]
/// \return Returns true if the point lies on the segment, false
/// otherwise.
template <typename T>
bool isPointOnSegment(const T &x,
const T &y,
const T &xA,
const T &yA,
const T &xB,
const T &yB);
/// Check if a point \p p lies on a segment \p AB.
/// \param p xyz coordinates of the input point.
/// \param pA xyz coordinates of the first vertex of the segment [AB]
/// \param pB xyz coordinate of the second vertex of the segment [AB]
/// \param dimension Optional parameter that specifies the dimension of
/// the point set (by default 3).
/// \return Returns true if the point lies on the segment, false
/// otherwise.
template <typename T>
bool isPointOnSegment(const T *p,
const T *pA,
const T *pB,
const int &dimension = 3);
/// Check if all the edges of a triangle are colinear.
/// \param p0 xyz coordinates of the first vertex of the triangle.
/// \param p1 xyz coordinates of the second vertex of the triangle.
/// \param p2 xyz coordinates of the third vertex of the triangle.
/// \return Returns true if all the edges are colinear (false otherwise).
template <typename T>
bool isTriangleColinear(const T *p0,
const T *p1,
const T *p2,
const T *tolerance = NULL);
/// Compute the magnitude of a 3D std::vector \p v.
/// \param v xyz coordinates of the input std::vector.
/// \return Returns the magnitude upon success, negative values otherwise.
template <typename T>
T magnitude(const T *v);
/// Compute the magnitude of a 3D std::vector.
/// \param o xyz coordinates of the std::vector's origin
/// \param d xyz coordinates of the std::vector's destination
template <typename T>
T magnitude(const T *o, const T *d);
} // namespace Geometry
} // namespace ttk
#endif
|
a7bb71766090539f3c911476370d1ddaf329f01b
|
c3f70154e766cffa78a997e858ba9929d9364087
|
/groundupdb/include/extensions/extquery.h
|
18c50441ea7be2936e8faef571260493b225bc40
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
adamfowleruk/groundupdb
|
a66ca1919170032c431e225960a80c26a1aae157
|
2864f599fd31bdd705555633dc16986482218ec5
|
refs/heads/stem
| 2023-02-02T15:32:47.318583
| 2023-01-29T19:45:17
| 2023-01-29T19:45:17
| 273,469,105
| 101
| 22
|
Apache-2.0
| 2023-01-29T19:45:19
| 2020-06-19T10:41:25
|
C++
|
UTF-8
|
C++
| false
| false
| 1,080
|
h
|
extquery.h
|
/*
See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Adam Fowler licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#ifndef EXTQUERY_H
#define EXTQUERY_H
#include "../query.h"
namespace groundupdbext {
using namespace groundupdb;
class DefaultQueryResult: public IQueryResult {
public:
DefaultQueryResult();
DefaultQueryResult(KeySet&& recordKeys);
DefaultQueryResult(Set&& recordKeys);
virtual ~DefaultQueryResult() = default;
const KeySet& recordKeys();
private:
KeySet m_recordKeys;
};
}
#endif // EXTQUERY_H
|
8b349bc876c4a9021d0d5e889373c7a396010727
|
34143cd84540d99cef21fd5edd468c7cd40ac335
|
/POJ/2375.cc
|
dd5680c3f78e1f351d900dc99cf28df0eeb5ef27
|
[] |
no_license
|
osak/Contest
|
0094f87c674d24ebfc0d764fca284493ab90df99
|
22c9edb994b6506b1a4f65b53a6046145a6cce41
|
refs/heads/master
| 2023-03-06T02:23:53.795410
| 2023-02-26T11:32:11
| 2023-02-26T11:32:11
| 5,219,104
| 8
| 9
| null | 2015-02-09T06:09:14
| 2012-07-29T01:16:42
|
C++
|
UTF-8
|
C++
| false
| false
| 4,819
|
cc
|
2375.cc
|
//Name: Cow Ski Area
//Level: 3
//Category: グラフ,Graph,強連結成分分解
//Note: TLE厳しい
/**
* 全体を強連結なグラフにする問題。
*
* このグラフを強連結成分分解したDAG上で考えると、
* 始点と終点の間で適当に辺を張ってやれば、全体を行き来することができるようになる。
*
* このとき、全体が巡回するように辺を張ることで、条件を満たす。
* このために必要な辺の本数は、始点の合計数と終点の合計数のうち、多い方の
* 数と等しい。
* これが最小であることは自明である。
*
* POJではTLEが厳しいので、強連結成分分解のトポロジカルソートを再帰で実装すると
* TLEしてしまう。
* したがって、自分でスタックを作り、再帰をシミュレーションしてやる必要がある。
*
* オーダーはO(WL)。
*/
#ifndef ONLINE_JUDGE
#define _GLIBCXX_DEBUG
#endif
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <stack>
using namespace std;
#define FOREACH(it,c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it)
#define TIMES(i,n) for(int (i) = 0; (i) < (n); ++(i))
const int MAX = 500*500;
int graph[MAX][5];
int graph_n[MAX];
int rev_graph[MAX][5];
int rev_graph_n[MAX];
int field[500][500];
const int DR[] = {0, -1, 0, 1};
const int DC[] = {1, 0, -1, 0};
bool visited[MAX];
int labels[MAX];
bool is_head[MAX], is_tail[MAX];
stack<pair<int,int> > stk;
inline bool in_range(int a, int x, int b) {
return a <= x && x < b;
}
// Number the nodes by post-order
void dfs1(int pos, vector<int> &ord) {
stk.push(make_pair(pos, 1));
stk.push(make_pair(pos, 0));
visited[pos] = true;
while(!stk.empty()) {
const int cur = stk.top().first;
const int phase = stk.top().second;
stk.pop();
if(phase == 1) {
ord.push_back(cur);
} else {
visited[cur] = true;
const int N = graph_n[cur];
for(int i = 0; i < N; ++i) {
if(!visited[graph[cur][i]]) {
stk.push(make_pair(graph[cur][i], 1));
stk.push(make_pair(graph[cur][i], 0));
visited[graph[cur][i]] = true;
}
}
}
}
}
// Label connected nodes
void dfs2(int pos, int l) {
stk.push(make_pair(pos, 0));
visited[pos] = true;
labels[pos] = l;
while(!stk.empty()) {
const int cur = stk.top().first;
stk.pop();
const int N = rev_graph_n[cur];
for(int i = 0; i < N; ++i) {
if(!visited[rev_graph[cur][i]]) {
visited[rev_graph[cur][i]] = true;
labels[rev_graph[cur][i]] = l;
stk.push(make_pair(rev_graph[cur][i], 0));
}
}
}
}
int scc(int N) {
vector<int> ord;
fill_n(visited, N, false);
for(int i = 0; i < N; ++i) {
if(!visited[i]) dfs1(i, ord);
}
reverse(ord.begin(), ord.end());
fill_n(visited, N, false);
int l = 0;
for(int i = 0; i < N; ++i) {
if(!visited[ord[i]]) dfs2(ord[i], l++);
}
return l;
}
bool solve() {
int W, L;
if(scanf("%d %d", &W, &L) == EOF) return false;
TIMES(r, L) {
TIMES(c, W) {
scanf(" %d", &field[r][c]);
graph_n[r*W+c] = 0;
rev_graph_n[r*W+c] = 0;
}
}
TIMES(r, L) {
TIMES(c, W) {
const int id = r*W+c;
TIMES(dir, 4) {
const int nr = r + DR[dir];
const int nc = c + DC[dir];
if(!in_range(0, nr, L) || !in_range(0, nc, W)) continue;
const int nid = nr*W+nc;
if(field[r][c] >= field[nr][nc]) {
graph[id][graph_n[id]++] = nid;
}
if(field[r][c] <= field[nr][nc]) {
rev_graph[id][rev_graph_n[id]++] = nid;
}
}
}
}
const int LN = scc(W*L);
if(LN == 1) {
puts("0");
return true;
}
fill_n(is_head, MAX, true);
fill_n(is_tail, MAX, true);
for(int i = 0; i < W*L; ++i) {
const int N = graph_n[i];
const int li = labels[i];
for(int j = 0; j < N; ++j) {
const int lj = labels[graph[i][j]];
if(lj != li) {
is_head[lj] = false;
is_tail[li] = false;
}
}
}
int heads = 0, tails = 0;
for(int i = 0; i < LN; ++i) {
if(is_head[i]) ++heads;
else if(is_tail[i]) ++tails;
}
//printf("%d %d\n", heads, tails);
printf("%d\n", max(heads, tails));
return true;
}
int main() {
while(solve()) ;
return 0;
}
|
edcefc282c5c093d0574da632ffa2c0c2b9b7ab8
|
8fbc0a30921bee6ec0161b9e263fb3cef2a3c0a4
|
/codewars/brainfuck-translator.cpp
|
ead8abe2c21ff23382046d27594ea4e6062a064c
|
[
"WTFPL"
] |
permissive
|
swwind/code
|
57d0d02c166d1c64469e0361fc14355d866079a8
|
c240122a236e375e43bcf145d67af5a3a8299298
|
refs/heads/master
| 2023-06-17T15:25:07.412105
| 2023-05-29T11:21:31
| 2023-05-29T11:21:31
| 93,724,691
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,863
|
cpp
|
brainfuck-translator.cpp
|
#include <iostream>
#include <string> // std::string
#include <cstring>
int type[100020];
int num[100020];
int top, dep;
#define ERROR "Error!"
#define indent__(x) std::string((x) * 2, ' ')
std::string brainfuck_to_c(std::string source_code) {
memset(type, 0, sizeof type);
memset(num, 0, sizeof num);
top = dep = 0;
const char *st = source_code.c_str();
int len = source_code.length();
for (int i = 0; i < len; i++) {
if (top && type[top] < 3 && !num[top]) top --;
if (st[i] == '+' || st[i] == '-') {
if (type[top] == 1) {
num[top] += st[i] == '+' ? 1 : -1;
} else {
type[++ top] = 1;
num[top] = st[i] == '+' ? 1 : -1;
}
} else if (st[i] == '>' || st[i] == '<') {
if (type[top] == 2) {
num[top] += st[i] == '>' ? 1 : -1;
} else {
type[++ top] = 2;
num[top] = st[i] == '>' ? 1 : -1;
}
} else {
type[++ top] = 3;
if (st[i] == ',')
num[top] = 1;
else if (st[i] == '.')
num[top] = 2;
else if (st[i] == '[')
num[top] = 3;
else if (st[i] == ']') {
if (top > 1 && type[top - 1] == 3 && num[top - 1] == 3) // last is '['
top -= 2;
else
num[top] = 4;
} else top --;
}
}
std::string res = "";
for (int i = 1; i <= top; i++) {
if (type[i] == 1) {
if (!num[i])
continue;
res += indent__(dep);
if (num[i] < 0)
res += "*p -= " + std::to_string(-num[i]) + ";";
else
res += "*p += " + std::to_string(num[i]) + ";";
} else if (type[i] == 2) {
if (!num[i])
continue;
res += indent__(dep);
if (num[i] < 0)
res += "p -= " + std::to_string(-num[i]) + ";";
else
res += "p += " + std::to_string(num[i]) + ";";
} else if (type[i] == 3) {
if (num[i] == 1) {
res += indent__(dep) + "*p = getchar();";
} else if (num[i] == 2) {
res += indent__(dep) + "putchar(*p);";
} else if (num[i] == 3) {
res += indent__(dep) + "if (*p) do {";
dep ++;
} else if (num[i] == 4) {
if (!dep)
return ERROR;
res += indent__(-- dep) + "} while (*p);";
}
}
res += '\n';
}
if (dep) return ERROR;
return res;
}
void DoTest(std::string a, std::string res) {
a = brainfuck_to_c(a);
if (a == res) puts("Passed");
else {
puts("Faild");
printf("Your output:<<");
std::cout << a;
puts(">>");
printf("Answer:<<");
std::cout << res;
puts(">>");
}
}
int main(int argc, char const *argv[]) {
DoTest("++++", "*p += 4;\n");
DoTest("----", "*p -= 4;\n");
DoTest(">>>>", "p += 4;\n");
DoTest("<<<<", "p -= 4;\n");
DoTest(".", "putchar(*p);\n");
DoTest(",", "*p = getchar();\n");
DoTest("[[[]]", "Error!");
DoTest("[][]", "");
DoTest("[.]", "if (*p) do {\n putchar(*p);\n} while (*p);\n");
DoTest("++<<[]>>++", "*p += 4;\n");
DoTest("++5++", "*p += 4;\n");
std::string str;
std::cin >> str;
std::cout << brainfuck_to_c(str);
return 0;
}
|
e354ee4e400ddbbb10ee75968641e62514fb4cba
|
73903e30de4a163cc48a1ce574e94623fb215a22
|
/cpp/acm/poj-3664.cpp
|
a69721b9e4452eab46e42515f2ea3b3dcd2f09c6
|
[] |
no_license
|
fuxiang90/code-fuxiang90
|
3d60972214f30b909222339d4373190e84ef8afc
|
a6258a82f992faa3d4c20f240dace033bede1375
|
refs/heads/master
| 2020-04-05T22:41:25.927586
| 2014-05-02T02:04:49
| 2014-05-02T02:04:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,368
|
cpp
|
poj-3664.cpp
|
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAX = 50010;
int n, k;
struct node
{
int a;
int b;
int num;
}cow[MAX];
int cmpa(node p, node q)//先按a从大到小排序,若a相等则按b从大到小排序
{
if(p.a == q.a && p.b == q.b) return 0;
if (p.a == q.a) return p.b > q.b ?1:-1;;
return p.a > q.a?1:-1;
}
//s 和e 表示能访问的最大 最小下标
int Partition(struct node * data ,int s ,int e )
{
if(s == e) return s;
int p = s;
int l = s + 1;
int r = e;
while(l <= r){
while(l <= e && cmpa(data[l] ,data[p]) < 0){
l ++;
}
while(r > s && cmpa (data[r] , data[p] )>=0 ){
r --;
}
if(l < r)
swap(data[l] ,data[r]);
}
swap(data[r] ,data[p]);
return r;
}
//int * getMaxK(int *data,int s ,int e,int k);
struct node * getMaxK(struct node *data,int s ,int e,int k)
{
if(e -s + 1 <= k ){
return data;
}
int p = Partition(data,s,e);
if(e - p + 1 > k ){
return getMaxK(data,p+1,e,k);
}else if ( e- p + 1 == k){
struct node *new_data = (struct node *)malloc(sizeof(struct node )*k);
for(int i = 0 ; i < k ; i ++ ){
new_data[i] = data[p+i];
}
return new_data;
}else {
int k2 = e-p+1;
struct node *new_data = (struct node *)malloc(sizeof(struct node )*k);
for(int i = 0 ; i < k2 ; i ++ ){
new_data[i] = data[p+i];
}
struct node * data2 = getMaxK(data,s,p-1, k-k2);
for(int i = 0 ; i < k -k2 ; i ++){
new_data[k2 + i] = data2[i];
}
free(data2);
data2 = NULL;
return new_data;
}
}
int cmpb(node p, node q)//先按b从大到小排序,若b相等则按a从大到小排序
{
if (p.b == q.b) return p.a > q.a;
return p.b > q.b;
}
int main()
{
//freopen("in","r",stdin);
int i;
while (scanf("%d%d", &n, &k) != EOF)
{
for (i = 0; i < n; ++i)
{
scanf("%d%d", &cow[i].a, &cow[i].b);
cow[i].num = i + 1;//牛的标号
}
struct node * data = getMaxK(cow, 0,n-1 ,k);//前n个牛排序
sort(data, data + k, cmpb);//前k个牛排序
printf("%d\n", data[0].num);
}
return 0;
}
|
7a9ffa72accd2a74aadfc41b21c4701a276747f3
|
6642ad5b6e88524b47dc5d2fbd744e7c7c1ae642
|
/src/applications/helper/gasper/gasper-participant-helper.cpp
|
d847eb8dc1ee20be4af5379397a254c7466f9fa3
|
[] |
no_license
|
Failips/SimPoS
|
e6dcbc890d1eef43d4faac3ca79c417104fddaf8
|
8b45d4388aa392737ac279e0e73d0ee190eeaa13
|
refs/heads/main
| 2023-04-19T20:15:51.600488
| 2021-05-10T16:22:44
| 2021-05-10T16:22:44
| 333,158,910
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,172
|
cpp
|
gasper-participant-helper.cpp
|
/**
* This file contains the definitions of the functions declared in gasper-participant-helper.h
*/
#include "gasper-participant-helper.h"
#include "ns3/string.h"
#include "ns3/inet-socket-address.h"
#include "ns3/names.h"
#include "ns3/uinteger.h"
#include "ns3/gasper-participant.h"
#include "ns3/log.h"
#include "ns3/double.h"
#include <algorithm>
#include "../../libsodium/include/sodium.h"
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("GasperParticipantHelper");
GasperParticipantHelper::GasperParticipantHelper (std::string protocol, Address address, std::vector<Ipv4Address> peers, int noMiners,
std::map<Ipv4Address, double> &peersDownloadSpeeds, std::map<Ipv4Address,
double> &peersUploadSpeeds, nodeInternetSpeeds &internetSpeeds, nodeStatistics *stats) :
BitcoinNodeHelper (), m_minerType (NORMAL_MINER), m_blockBroadcastType (STANDARD)
{
m_factory.SetTypeId ("ns3::GasperParticipant");
commonConstructor(protocol, address, peers, peersDownloadSpeeds, peersUploadSpeeds, internetSpeeds, stats);
m_noMiners = noMiners;
std::random_device rd; // obtain a random number from hardware
m_generator.seed(rd()); // seed the generator
randombytes_buf(m_genesisVrfSeed, sizeof m_genesisVrfSeed);
}
Ptr<Application>
GasperParticipantHelper::InstallPriv (Ptr<Node> node) //FIX ME
{
switch (m_minerType)
{
case NORMAL_MINER:
{
Ptr<GasperParticipant> app = m_factory.Create<GasperParticipant> ();
app->SetPeersAddresses(m_peersAddresses);
app->SetPeersDownloadSpeeds(m_peersDownloadSpeeds);
app->SetPeersUploadSpeeds(m_peersUploadSpeeds);
app->SetNodeInternetSpeeds(m_internetSpeeds);
app->SetNodeStats(m_nodeStats);
app->SetBlockBroadcastType(m_blockBroadcastType);
app->SetProtocolType(m_protocolType);
app->SetHelper(this);
app->SetAllPrint(m_allPrint);
app->SetEpochSize(m_epochSize);
app->SetGenesisVrfSeed(m_genesisVrfSeed);
app->SetVrfThresholdBP(m_vrfThresholdBP);
app->SetVrfThreshold(m_vrfThreshold);
app->SetIntervalBP(m_intervalBP);
app->SetIntervalAttest(m_intervalAttest);
node->AddApplication (app);
return app;
}
}
}
enum MinerType
GasperParticipantHelper::GetMinerType(void)
{
return m_minerType;
}
void
GasperParticipantHelper::SetMinerType(enum MinerType m)
{
m_minerType = m;
switch (m)
{
case NORMAL_MINER:
{
m_factory.SetTypeId ("ns3::GasperParticipant");
SetFactoryAttributes();
break;
}
}
}
void
GasperParticipantHelper::SetBlockBroadcastType (enum BlockBroadcastType m)
{
m_blockBroadcastType = m;
}
void
GasperParticipantHelper::SetAllPrint(bool allPrint)
{
m_allPrint = allPrint;
}
void
GasperParticipantHelper::SetEpochSize(int epochSize)
{
m_epochSize = epochSize;
}
void
GasperParticipantHelper::SetVrfThresholdBP(unsigned char *threshold) {
memcpy(m_vrfThresholdBP, threshold, sizeof m_vrfThresholdBP);
}
void
GasperParticipantHelper::SetVrfThreshold(unsigned char *threshold) {
memcpy(m_vrfThreshold, threshold, sizeof m_vrfThreshold);
}
void
GasperParticipantHelper::SetIntervalBP(double interval) {
m_intervalBP = interval;
}
void
GasperParticipantHelper::SetIntervalAttest(double interval) {
m_intervalAttest = interval;
}
void
GasperParticipantHelper::SetFactoryAttributes (void)
{
m_factory.Set ("Protocol", StringValue (m_protocol));
m_factory.Set ("Local", AddressValue (m_address));
}
} // namespace ns3
|
a1d629dd407b8afe0823a12f9c75b82da8ce65f5
|
88881f70bbb9ff42970796a8ec89c82e666d55bc
|
/CodeChefLongApril20/HLD.cpp
|
33f6fbc55f7bfd5f1edb7d256dc280cbd0290d8e
|
[] |
no_license
|
uhini0201/CodeChefChallenges
|
e7f7c5e7e036ca3cf84ea04d23931b79819371a3
|
21d270675a7fb10cbc929ffddccdb5f960e1c073
|
refs/heads/master
| 2023-02-01T09:00:33.105552
| 2020-12-14T10:19:07
| 2020-12-14T10:19:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,651
|
cpp
|
HLD.cpp
|
// Problem Link : https://www.codechef.com/APRIL20B/problems/FCTRE
// Answer For Subtask #1
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
#define whatis(x) cerr << #x << " is : " << x <<endl;
#define IOS ios_base::sync_with_stdio(false),cin.tie(NULL);
#define N 100005
#define MAXA 1000001
#define MOD 1000000007
typedef long long ll;
vector< vector<ll> > adj;
ll MAX;
ll chainId;
ll pos;
ll segTree[N * 4];
ll chain[N];
ll chainHead[N];
ll position[N];
ll subTreeSize[N];
ll parent[N][16];
ll level[N];
ll arr[N];
ll spf[MAXA];
void sieve(){
spf[1] = 1;
for (ll i=2; i<MAXA; i++)
spf[i] = i;
for (ll i=4; i<MAXA; i+=2)
spf[i] = 2;
for (ll i=3; i*i<MAXA; i++){
if (spf[i] == i){
for (ll j=i*i; j<MAXA; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
vector<ll> getFactorization(ll x){
vector<ll> ret;
while (x != 1){
ret.push_back(spf[x]);
x = x / spf[x];
}
return ret;
}
ll countFactors(unordered_map<ll,ll> m){
ll count = 1;
for(auto x : m){
count = ((count % MOD) * ((x.second+1) % MOD)) % MOD;
}
return count;
}
unordered_map<ll,ll> findFactors(ll n){
unordered_map<ll,ll> ans;
vector<ll> factors = getFactorization(n);
for(ll i=0; i<factors.size(); i++){
ans[factors[i]] = ((ans[factors[i]] % MOD) + (1 % MOD)) % MOD;
}
return ans;
}
void swap(ll& u,ll& v){
ll temp;
temp = u;
u = v;
v = temp;
}
void HLD(ll v, ll par, vector< unordered_map<ll,ll> >& baseArr, vector< unordered_map<ll,ll> >& primeFactors) {
ll heavyChild = -1, heavySize = 0;
chain[v] = chainId;
position[v] = pos++;
for(ll p : adj[v]) {
if(p != par) {
if(subTreeSize[p] > heavySize) {
heavySize = subTreeSize[p];
heavyChild = p;
}
}
}
baseArr[pos] = primeFactors[v];
if(heavyChild!=-1) {
HLD(heavyChild, v, baseArr, primeFactors);
}
for(ll p : adj[v]) {
if(p != par && p != heavyChild) {
chainId++;
chainHead[chainId] = p;
HLD(p, v, baseArr, primeFactors);
}
}
}
ll LCA(ll u,ll v){
if(level[u] > level[v])
swap(u,v);
ll diff = level[v] - level[u];
for(ll i=MAX; i>=0; --i){
if((diff & (1<<i)) != 0) {
v = parent[v][i];
}
}
if(u == v)
return u;
for(ll i=MAX;i>=0;--i) {
if(parent[u][i] != parent[v][i]) {
u = parent[u][i];
v = parent[v][i];
}
}
return parent[u][0];
}
void dfs(ll v, ll par, ll l, vector< unordered_map<ll,ll> >& primeFactors) {
parent[v][0] = par;
for(ll i=1;i<=MAX;++i) {
if(parent[v][i-1]!=0) {
parent[v][i] = parent[parent[v][i-1]][i-1];
}
}
subTreeSize[v] += 1;
level[v] = l;
for(ll p : adj[v]) {
if(p!=par) {
dfs(p, v, l+1, primeFactors);
subTreeSize[v]+=subTreeSize[p];
}
}
}
unordered_map<ll,ll> merge(unordered_map<ll,ll> a, unordered_map<ll,ll> b){
unordered_map<ll,ll> x ;
for(auto it : a){
x[it.first] = ((x[it.first] % MOD) + (it.second % MOD)) % MOD;
}
for(auto it : b){
x[it.first] = ((x[it.first] % MOD) + (it.second % MOD)) % MOD;
}
return x;
}
unordered_map<ll, ll> query(ll treein,ll low,ll high,ll l,ll r, vector< unordered_map<ll,ll> >& tree){
if(l<=low && high<=r)
return tree[treein];
unordered_map<ll,ll> m;
if(low>r || high<l)
return m;
ll mid = (low+high)>>1;
unordered_map<ll,ll> m1 = query(2*treein,low,mid,l,r,tree);
unordered_map<ll,ll> m2 = query(2*treein+1,mid+1,high,l,r,tree);
unordered_map<ll,ll> m3 = merge(m1,m2);
return m3;
}
unordered_map<ll, ll> query(ll l,ll r, ll n, vector< unordered_map<ll,ll> >& tree){
unordered_map<ll,ll> m;
if(l>r) {
return m;
}
return query(1,0,n-1,l,r,tree);
}
unordered_map<ll,ll> queryUp(ll from, ll to, ll n, vector< unordered_map<ll,ll> >& tree){
ll curr = from;
unordered_map<ll,ll> ans;
while(chain[curr] != chain[to]) {
ans = merge(ans, query(position[chainHead[chain[curr]]], position[curr], n, tree));
curr = parent[chainHead[chain[curr]]][0];
}
ans = merge(ans, query(position[to], position[curr], n, tree));
return ans;
}
void build(ll treein,ll low,ll high, vector< unordered_map<ll,ll> >& tree, vector< unordered_map<ll,ll> >& baseArr){
if(low==high){
tree[treein] = baseArr[low+1];
}
else{
ll mid = (low+high)/2;
build(2*treein,low,mid, tree, baseArr);
build(2*treein+1,mid+1,high, tree, baseArr);
auto x = merge(tree[2*treein],tree[2*treein+1]);
tree[treein] = x;
}
}
int main(){
IOS;
ll t;
cin >> t;
sieve();
while(t--){
vector< unordered_map<ll,ll> > primeFactors(N);
vector< unordered_map<ll,ll> > baseArr(N);
vector< unordered_map<ll,ll> > tree(N*6);
ll n;
cin >> n;
ll u, v;
vector< vector<ll> > a(n+1);
adj = a;
memset(arr,0,sizeof(arr));
for(ll i=0; i<n-1; i++){
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for(ll i=1; i<=n; i++){
cin >> arr[i];
primeFactors[i] = findFactors(arr[i]);
}
MAX = log(n)/log(2);
chainId = 0;
pos = 0;
memset(segTree,0,sizeof(segTree));
memset(chain,0,sizeof(chain));
memset(chainHead,0,sizeof(chainHead));
memset(position,0,sizeof(position));
memset(subTreeSize,0,sizeof(subTreeSize));
memset(subTreeSize,0,sizeof(subTreeSize));
memset(parent,0,sizeof(parent));
memset(level,0,sizeof(level));
dfs(1,0,0,primeFactors);
chainHead[0] = 1;
HLD(1,0,baseArr,primeFactors);
build(1,0, n-1,tree, baseArr);
ll q;
cin >> q;
while(q--){
ll l,r;
cin >> l >> r;
ll lca = LCA(l,r);
unordered_map<ll,ll> m1 = queryUp(l,lca,n,tree);
unordered_map<ll,ll> m2 = queryUp(r,lca,n,tree);
unordered_map<ll,ll> m3 = merge(m1,m2);
unordered_map<ll,ll> lc = primeFactors[lca];
for(auto x : lc){
m3[x.first] -= x.second;
}
cout << countFactors(m3) << endl;
}
}
return 0;
}
|
636fe2bd4e7021c3c6b0298d7d1613d0d0ef9314
|
c7c73566784a7896100e993606e1bd8fdd0ea94e
|
/pandatool/src/flt/fltLightSourceDefinition.h
|
e96d275254329b5526edbbf20cc1b2c3a582efea
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
panda3d/panda3d
|
c3f94df2206ff7cfe4a3b370777a56fb11a07926
|
160ba090a5e80068f61f34fc3d6f49dbb6ad52c5
|
refs/heads/master
| 2023-08-21T13:23:16.904756
| 2021-04-11T22:55:33
| 2023-08-06T06:09:32
| 13,212,165
| 4,417
| 1,072
|
NOASSERTION
| 2023-09-09T19:26:14
| 2013-09-30T10:20:25
|
C++
|
UTF-8
|
C++
| false
| false
| 1,999
|
h
|
fltLightSourceDefinition.h
|
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file fltLightSourceDefinition.h
* @author drose
* @date 2000-08-26
*/
#ifndef FLTLIGHTSOURCEDEFINITION_H
#define FLTLIGHTSOURCEDEFINITION_H
#include "pandatoolbase.h"
#include "fltRecord.h"
#include "luse.h"
/**
* Represents a single entry in the light source palette. This completely
* defines the color, etc. of a single light source, which may be referenced
* later by a FltLightSource bead in the hierarchy.
*/
class FltLightSourceDefinition : public FltRecord {
public:
FltLightSourceDefinition(FltHeader *header);
enum LightType {
LT_infinite = 0,
LT_local = 1,
LT_spot = 2
};
int _light_index;
std::string _light_name;
LColor _ambient;
LColor _diffuse;
LColor _specular;
LightType _light_type;
PN_stdfloat _exponential_dropoff;
PN_stdfloat _cutoff_angle; // in degrees
// yaw and pitch only for modeling lights, which are positioned at the
// eyepoint.
PN_stdfloat _yaw;
PN_stdfloat _pitch;
PN_stdfloat _constant_coefficient;
PN_stdfloat _linear_coefficient;
PN_stdfloat _quadratic_coefficient;
bool _modeling_light;
protected:
virtual bool extract_record(FltRecordReader &reader);
virtual bool build_record(FltRecordWriter &writer) const;
public:
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
FltRecord::init_type();
register_type(_type_handle, "FltLightSourceDefinition",
FltRecord::get_class_type());
}
private:
static TypeHandle _type_handle;
friend class FltHeader;
};
#endif
|
ae5d505aa06277f5fb3bcd9d399a5629141ee5cd
|
bce8a7a8ad903aba8b5bdb1d47936b4f90cd5769
|
/src/sky_plugin_curl.cc
|
b35004b80413c7f0718a9ba58d65f9683fb3cb9c
|
[
"Apache-2.0"
] |
permissive
|
bostin/SkyAPM-php-sdk
|
298cad6ce9008fb2a098c3bb5a4203781e252d6d
|
ddcfe4d1d97c8c360a7f9352ac6c14a8881bc57c
|
refs/heads/master
| 2022-03-09T13:01:38.544387
| 2022-03-03T16:24:11
| 2022-03-03T16:24:11
| 197,617,608
| 4
| 0
|
Apache-2.0
| 2019-11-08T06:55:11
| 2019-07-18T15:57:46
|
C
|
UTF-8
|
C++
| false
| false
| 8,967
|
cc
|
sky_plugin_curl.cc
|
/*
* Copyright 2021 SkyAPM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include "sky_plugin_curl.h"
#include "php_skywalking.h"
#include "segment.h"
#include "sky_utils.h"
void (*orig_curl_exec)(INTERNAL_FUNCTION_PARAMETERS) = nullptr;
void (*orig_curl_setopt)(INTERNAL_FUNCTION_PARAMETERS) = nullptr;
void (*orig_curl_setopt_array)(INTERNAL_FUNCTION_PARAMETERS) = nullptr;
void (*orig_curl_close)(INTERNAL_FUNCTION_PARAMETERS) = nullptr;
void sky_curl_setopt_handler(INTERNAL_FUNCTION_PARAMETERS) {
auto *segment = sky_get_segment(execute_data, -1);
if (segment == nullptr || segment->skip()) {
orig_curl_setopt(INTERNAL_FUNCTION_PARAM_PASSTHRU);
return;
}
zval *zid, *zvalue;
zend_long options;
#if PHP_VERSION_ID >= 80000
ZEND_PARSE_PARAMETERS_START(3, 3)
Z_PARAM_OBJECT_OF_CLASS(zid, curl_ce)
Z_PARAM_LONG(options)
Z_PARAM_ZVAL(zvalue)
ZEND_PARSE_PARAMETERS_END();
zend_ulong cid = Z_OBJ_HANDLE_P(zid);
#else
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rlz", &zid, &options, &zvalue) == FAILURE) {
return;
}
zend_ulong cid = Z_RES_HANDLE_P(zid);
#endif
if (SKY_CURLOPT_HTTPHEADER == options) {
zval *header = ZEND_CALL_ARG(execute_data, 2);
header->value.lval = CURLOPT_HTTPHEADER;
} else if (CURLOPT_HTTPHEADER == options && Z_TYPE_P(zvalue) == IS_ARRAY) {
zval dup_header;
ZVAL_DUP(&dup_header, zvalue);
add_index_zval(&SKYWALKING_G(curl_header), cid, &dup_header);
}
orig_curl_setopt(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
void sky_curl_setopt_array_handler(INTERNAL_FUNCTION_PARAMETERS) {
auto *segment = sky_get_segment(execute_data, -1);
if (segment == nullptr || segment->skip()) {
orig_curl_setopt_array(INTERNAL_FUNCTION_PARAM_PASSTHRU);
return;
}
zval *zid, *arr;
#if PHP_VERSION_ID >= 80000
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_OBJECT_OF_CLASS(zid, curl_ce)
Z_PARAM_ARRAY(arr)
ZEND_PARSE_PARAMETERS_END();
zend_ulong cid = Z_OBJ_HANDLE_P(zid);
#else
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_RESOURCE(zid)
Z_PARAM_ARRAY(arr)
ZEND_PARSE_PARAMETERS_END();
zend_ulong cid = Z_RES_HANDLE_P(zid);
#endif
zval *http_header = zend_hash_index_find(Z_ARRVAL_P(arr), CURLOPT_HTTPHEADER);
if (http_header != nullptr) {
zval copy_header;
ZVAL_DUP(©_header, http_header);
add_index_zval(&SKYWALKING_G(curl_header), cid, ©_header);
}
orig_curl_setopt_array(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
void sky_curl_exec_handler(INTERNAL_FUNCTION_PARAMETERS) {
auto *segment = sky_get_segment(execute_data, -1);
if (segment == nullptr || segment->skip()) {
orig_curl_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU);
return;
}
zval *zid;
#if PHP_VERSION_ID >= 80000
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(zid, curl_ce)
ZEND_PARSE_PARAMETERS_END();
zend_ulong cid = Z_OBJ_HANDLE_P(zid);
#else
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) {
return;
}
zend_ulong cid = Z_RES_HANDLE_P(zid);
#endif
int is_record = 0;
zval func;
zval args[1];
zval url_info;
ZVAL_COPY(&args[0], zid);
ZVAL_STRING(&func, "curl_getinfo");
call_user_function(CG(function_table), nullptr, &func, &url_info, 1, args);
zval_dtor(&func);
zval_dtor(&args[0]);
// check
php_url *url_parse = nullptr;
zval *z_url = zend_hash_str_find(Z_ARRVAL(url_info), ZEND_STRL("url"));
char *url_str = Z_STRVAL_P(z_url);
if (strlen(url_str) > 0 && (starts_with("http://", url_str) || starts_with("https://", url_str))) {
url_parse = php_url_parse(url_str);
if (url_parse != nullptr && url_parse->scheme != nullptr && url_parse->host != nullptr) {
is_record = 1;
}
}
// set header
Span *span;
int is_emalloc = 0;
zval *option;
option = zend_hash_index_find(Z_ARRVAL_P(&SKYWALKING_G(curl_header)), cid);
if (is_record) {
if (option == nullptr) {
option = (zval *) emalloc(sizeof(zval));
bzero(option, sizeof(zval));
array_init(option);
is_emalloc = 1;
}
// for php7.3.0+
#if PHP_VERSION_ID >= 70300
char *php_url_scheme = ZSTR_VAL(url_parse->scheme);
char *php_url_host = ZSTR_VAL(url_parse->host);
char *php_url_path = url_parse->path != nullptr ? ZSTR_VAL(url_parse->path) : nullptr;
#else
char *php_url_scheme = url_parse->scheme;
char *php_url_host = url_parse->host;
char *php_url_path = url_parse->path;
#endif
int peer_port;
if (url_parse->port) {
peer_port = url_parse->port;
} else {
if (strcasecmp("http", php_url_scheme) == 0) {
peer_port = 80;
} else {
peer_port = 443;
}
}
span = segment->createSpan(SkySpanType::Exit, SkySpanLayer::Http, 8002);
span->setPeer(std::string(php_url_host) + ":" + std::to_string(peer_port));
span->setOperationName(php_url_path == nullptr ? "/" : php_url_path);
span->addTag("url", url_str);
std::string sw_header = segment->createHeader(span);
add_next_index_string(option, ("sw8: " + sw_header).c_str());
zval argv[3];
zval ret;
ZVAL_STRING(&func, "curl_setopt");
ZVAL_COPY(&argv[0], zid);
ZVAL_LONG(&argv[1], SKY_CURLOPT_HTTPHEADER);
ZVAL_COPY(&argv[2], option);
call_user_function(CG(function_table), nullptr, &func, &ret, 3, argv);
zval_dtor(&func);
zval_dtor(&ret);
zval_dtor(&argv[0]);
zval_dtor(&argv[1]);
zval_dtor(&argv[2]);
if (is_emalloc) {
zval_ptr_dtor(option);
efree(option);
}
}
orig_curl_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU);
// record
if (is_record == 1) {
// get response
zval url_response;
ZVAL_COPY(&args[0], zid);
ZVAL_STRING(&func, "curl_getinfo");
call_user_function(CG(function_table), nullptr, &func, &url_response, 1, args);
zval_dtor(&func);
zval_dtor(&args[0]);
zval *response_http_code;
response_http_code = zend_hash_str_find(Z_ARRVAL(url_response), ZEND_STRL("http_code"));
span->addTag("status_code", std::to_string(Z_LVAL_P(response_http_code)));
if (Z_LVAL_P(response_http_code) == 0) {
// get errors
zval curl_error;
ZVAL_COPY(&args[0], zid);
ZVAL_STRING(&func, "curl_error");
call_user_function(CG(function_table), nullptr, &func, &curl_error, 1, args);
span->addLog("CURL_ERROR", Z_STRVAL(curl_error));
span->setIsError(true);
zval_dtor(&func);
zval_dtor(&args[0]);
zval_dtor(&curl_error);
} else if (Z_LVAL_P(response_http_code) >= 400) {
if (SKYWALKING_G(curl_response_enable) && Z_TYPE_P(return_value) == IS_STRING) {
span->addTag("http.response", Z_STRVAL_P(return_value));
}
span->setIsError(true);
} else {
span->setIsError(false);
}
zval_dtor(&url_response);
span->setEndTIme();
}
zval_dtor(&url_info);
if (url_parse != nullptr) {
php_url_free(url_parse);
}
}
void sky_curl_close_handler(INTERNAL_FUNCTION_PARAMETERS) {
auto *segment = sky_get_segment(execute_data, -1);
if (segment == nullptr || segment->skip()) {
orig_curl_close(INTERNAL_FUNCTION_PARAM_PASSTHRU);
return;
}
zval *zid;
#if PHP_VERSION_ID >= 80000
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(zid, curl_ce)
ZEND_PARSE_PARAMETERS_END();
zend_ulong cid = Z_OBJ_HANDLE_P(zid);
#else
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) {
return;
}
zend_ulong cid = Z_RES_HANDLE_P(zid);
#endif
zval *http_header = zend_hash_index_find(Z_ARRVAL_P(&SKYWALKING_G(curl_header)), cid);
if (http_header != nullptr) {
zend_hash_index_del(Z_ARRVAL_P(&SKYWALKING_G(curl_header)), cid);
}
orig_curl_close(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
|
28a9c07905e2a42b9bb33322f452b04b4424317f
|
38f5b7ef3ce514a970db6b404f5635628867a999
|
/OItemWeaponBow.cpp
|
339865db0bf2393c0f1f909f8095dd5bcf13d2b5
|
[] |
no_license
|
Shinyj/Crypt-of-the-NecroDancer
|
3465ff02ec131253d7e5941d508ba1845fe2f415
|
8760a7b9adc9b0f9aca258e12f5e7d73d067ebaa
|
refs/heads/master
| 2020-03-30T08:25:21.481320
| 2018-10-01T00:01:55
| 2018-10-01T00:01:55
| 151,013,897
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,135
|
cpp
|
OItemWeaponBow.cpp
|
#include "stdafx.h"
#include "OItemWeaponBow.h"
#include "OPlayer1.h"
OItemWeaponBow::OItemWeaponBow()
{
}
OItemWeaponBow::~OItemWeaponBow()
{
}
HRESULT OItemWeaponBow::Init(string key, int pos, ITEMKIND kind)
{
ItemBase::Init(key,pos,kind);
infoImage = IMAGEMANAGER->FindImage("hint_rangedattack");
effectU = IMAGEMANAGER->FindImage("swipe_arrow_U");
effectD = IMAGEMANAGER->FindImage("swipe_arrow_D");
effectL = IMAGEMANAGER->FindImage("swipe_arrow_L");
effectR = IMAGEMANAGER->FindImage("swipe_arrow_R");
direction = 5;
posX = -1;
posY = 0;
effectX = 0;
effectY = 0;
effectCount = 0;
isEffectAnim = false;
attribute = 1;
range = 0;
return S_OK;
}
void OItemWeaponBow::Release()
{
ItemBase::Release();
}
void OItemWeaponBow::Update()
{
ItemBase::Update();
if (isEffectAnim)
EffectAnim();
}
void OItemWeaponBow::Render()
{
ItemBase::Render();
if (isEffectAnim)
EffectRender();
}
void OItemWeaponBow::ShowInfo()
{
infoImage->Render(GetMemDC(), x + 26 - 46, y - 18 );
}
bool OItemWeaponBow::UseIt(int pos, int dir)
{
GameObject * obj[3];
//GameObject * player;
posX = OBJECTMANAGER->GetPlayer()->GetX();
posY = OBJECTMANAGER->GetPlayer()->GetY();
posY -= 10;
switch (dir)
{
case 8:
obj[0] = OBJECTMANAGER->GetIsThereObj(pos);
obj[1] = OBJECTMANAGER->GetIsThereObj(pos - 50);
obj[2] = OBJECTMANAGER->GetIsThereObj(pos - 100);
posY -= 52;
break;
case 2:
obj[0] = OBJECTMANAGER->GetIsThereObj(pos);
obj[1] = OBJECTMANAGER->GetIsThereObj(pos + 50);
obj[2] = OBJECTMANAGER->GetIsThereObj(pos + 100);
posY += 52;
break;
case 4:
obj[0] = OBJECTMANAGER->GetIsThereObj(pos);
obj[1] = OBJECTMANAGER->GetIsThereObj(pos - 1 );
obj[2] = OBJECTMANAGER->GetIsThereObj(pos - 2 );
posX -= 52;
break;
case 6:
obj[0] = OBJECTMANAGER->GetIsThereObj(pos);
obj[1] = OBJECTMANAGER->GetIsThereObj(pos + 1);
obj[2] = OBJECTMANAGER->GetIsThereObj(pos + 2);
posX += 52;
break;
}
bool existObj = false;
range = 0;
for (int i = 0; i < 3; i++)
{
range++;
if (obj[i] != NULL && obj[i]->GetObjKind() == OBJ_MONSTER)
{
direction = dir;
effectX = 0;
effectY = 0;
//posX = obj[1]->GetX();
//posY = obj[1]->GetY();
obj[i]->Defence(attribute);
isEffectAnim = true;
existObj = true;
break;
}
}
return existObj;
}
void OItemWeaponBow::EffectAnim()
{
effectCount++;
if (effectCount % 1 == 0)
{
effectCount = 0;
effectX++;
effectY++;
if (effectX == 6 || effectY == 6)
isEffectAnim = false;
}
}
void OItemWeaponBow::EffectRender()
{
switch (direction)
{
case 8:
for (int i = 0; i < range; i++)
{
effectU->FrameRender(GetMemDC(), posX + 10, posY - i * 52, 0, 6 - effectY -i);
}
break;
case 2:
for (int i = 0; i < range; i++)
{
effectD->FrameRender(GetMemDC(), posX + 10, posY + i * 52, 0, 6 - effectY-i);
}
break;
case 4:
for (int i = 0; i < range; i++)
{
effectL->FrameRender( GetMemDC(), posX - i * 52, posY, 6 - effectX -i , 0);
}
break;
case 6:
for (int i = 0; i < range; i++)
{
effectR->FrameRender(GetMemDC(), posX + i * 52, posY, effectX - i, 0);
}
break;
}
}
|
497a337f117113017a93704dfa30b284c6dff922
|
44cf55a4c2eed8da013236ee312673f7e1e4566e
|
/ideas/procpp/mixin_handler/Scheduler.h
|
59482f4cd20059466733a74141d9bb43b2b80512
|
[] |
no_license
|
wangxx2026/universe
|
fe0709a0b2dd289815a481cad98a28b3a43b5f5f
|
d10dd5517e53d196da6a38c1530384093a9812db
|
refs/heads/master
| 2020-03-21T17:45:12.260873
| 2018-03-08T02:51:00
| 2018-03-08T02:51:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,063
|
h
|
Scheduler.h
|
#pragma once
#include <functional>
#include <time.h>
#include <vector>
#include <sys/timerfd.h>
#include "EventManager.h"
using namespace std;
class IScheduler
{
public:
using CB = function<void(void)>;
virtual int schedule_once(CB cb, float sec) = 0;
virtual int schedule(CB cb, float sec, float interval) = 0;
virtual int schedule_once(CB cb, const struct timespec ts) = 0;
virtual int schedule(CB cb, struct itimerspec ts) = 0;
virtual void unschedule(int timer_fd) = 0;
};
class Scheduler : public IScheduler, public EventManager
{
public:
using CB = IScheduler::CB;
virtual int schedule_once(CB cb, float sec) override;
virtual int schedule(CB cb, float sec, float interval) override;
virtual int schedule_once(CB cb, const struct timespec ts) override;
virtual int schedule(CB cb, struct itimerspec its) override;
virtual void unschedule(int timer_fd) override;
private:
virtual int _create_timerfd(const struct itimerspec its);
vector<CB> _update_cbs;
vector<CB> _once_cbs;
};
|
420fdf82400fd48ea1aea76600219b486dc55dba
|
d1dbbfca0e2a2a465cacb27db2aaa32733291c10
|
/McCluskey.h
|
4db00e7ba28e845d0910a52dc6eb5e5ad8e456e4
|
[] |
no_license
|
aa89227-zz/K-map-based-logic-minimization
|
4bac9c910b736a112992acefeed28679810a9b90
|
366852620660c46aef13fa877368f51493c59167
|
refs/heads/main
| 2022-12-29T09:34:34.653953
| 2020-10-20T05:47:28
| 2020-10-20T05:47:28
| null | 0
| 0
| null | null | null | null |
BIG5
|
C++
| false
| false
| 9,299
|
h
|
McCluskey.h
|
#ifndef MCCLUSKEY_H
#define MCCLUSKEY_H
#include <vector>
#include <iostream>
#include <set>
#include "BinaryCode.h"
#include <iomanip>
#include <fstream>
using namespace std;
class McCluskey
{
public:
McCluskey(vector<int>);
struct implicant
{
bool isPrime = true; //prime: true
int oneNum = 0;
set< int > n; //implicant with any size; m(1,5,7,10)
vector< int > s; //example: 2001 -> -001
};
using implicantlist = vector< implicant >;
void outputMin(int);
void output();
private:
int bits;
vector< int > m; //min term
vector< int > d; //don't care
//push with boolean code
void push(implicantlist&, int, vector< bool >);
vector< implicantlist > fullImplicantList; //full implicant list ;
vector< binarycode::binarycodeType > bCode;
implicantlist prime; //prime implicant
int min = 99999;
//recursive find prime implicant
void findPrime(int);
//compare two implicant and combine them (push to implicantList)
bool compare(int, int, int);
vector< set< int > > minPossibleList; //list all possible combanition
void doPetrick();
vector<vector<bool>> Index;
void findPossible(vector<bool>, vector<vector<int>>&, int, int, set<int>);
void outputProcess(vector< vector< int > >&);
};
McCluskey::McCluskey(vector<int> sop)
{
bits = 0;
for ( size_t s = sop.size(); s != 1; s /= 2 )++bits;
binarycode tempB(bits);
bCode = tempB.getCode();
fullImplicantList.resize(1);
for ( int i = 0; i < sop.size(); ++i ) //set m
if ( sop[i] == 1 ) {
m.push_back(i);
push(fullImplicantList[0], i, bCode[i]);
}
for ( int i = 0; i < sop.size(); ++i ) //set d
if ( sop[i] == 2 ) {
d.push_back(i);
push(fullImplicantList[0], i, bCode[i]);
}
findPrime(1);
doPetrick();
}
void McCluskey::findPrime(int index)
{
if ( index + 1 >= bits || fullImplicantList[index - 1].size() == 0 ) { //all finished, push prime
for ( int i = 0; i < fullImplicantList.size(); ++i ) {
for ( int j = 0; j < fullImplicantList[i].size(); ++j ) {
if ( fullImplicantList[i][j].isPrime )
prime.push_back(fullImplicantList[i][j]);
}
}
return;
}
fullImplicantList.resize(fullImplicantList.size() + 1);
for ( int i = 0; i < fullImplicantList[index - 1].size(); ++i ) {
for ( int j = 0; j < fullImplicantList[index - 1].size(); ++j ) {
if ( fullImplicantList[index - 1][i].oneNum < fullImplicantList[index - 1][j].oneNum )
if ( compare(index, i, j) )
fullImplicantList[index - 1][i].isPrime = fullImplicantList[index - 1][j].isPrime = false;
}
}
findPrime(index + 1);
}
bool McCluskey::compare(int index, int first, int second)
{
int bit = -1; //bit of different
for ( int i = 0; i < bits; ++i ) {
if ( fullImplicantList[index - 1][first].s[i] != fullImplicantList[index - 1][second].s[i] ) {
if ( bit == -1 )
bit = i;
else
return false;
}
}
fullImplicantList[index].push_back(fullImplicantList[index - 1][first]);
fullImplicantList[index].back().isPrime = true;
fullImplicantList[index].back().oneNum -= fullImplicantList[index - 1][first].s[bit] ? 1 : 0;
fullImplicantList[index].back().s[bit] = 2;
fullImplicantList[index].back().n.insert(fullImplicantList[index - 1][second].n.begin(),
fullImplicantList[index - 1][second].n.end());
for ( int i = 0; i < fullImplicantList[index].size() - 1; ++i )
if ( fullImplicantList[index][i].n == fullImplicantList[index].back().n ) {
fullImplicantList[index].pop_back();
break;
}
return true;
}
void McCluskey::doPetrick()
{
vector<vector<int>> table;
table.resize(m.size());
for ( int i = 0; i < prime.size(); ++i ) { //create table https://en.wikipedia.org/wiki/Petrick%27s_method
for ( set<int>::iterator it = prime[i].n.begin(); it != prime[i].n.end(); ++it ) {
for ( int j = 0; j < m.size(); ++j )
if ( m[j] == *it ) {
table[j].push_back(i);
break;
}
}
}
Index.resize(prime.size());
set<int> temp;
for ( int i = 0; i < table.size(); ++i ) { //把所有一定會用到的row放入temp
if ( table[i].size() == 1 ) {
temp.insert(table[i][0]);
}
}
bool isDelete;
for ( vector<vector<int>>::iterator it = table.begin(); it != table.end(); ) { //將擁有一定會用到row的選項刪掉
isDelete = false;
for ( vector<int>::iterator it2 = (*it).begin(); it2 != (*it).end(); ++it2) {
if ( temp.find(*it2) != temp.end() ) {
it = table.erase(it);
isDelete = true;
break;
}
}
if ( !isDelete )
++it;
}
vector<bool> enableIndex(table.size(), false);
for ( int i = 0; i < Index.size(); ++i )
Index[i].resize(table.size());
for ( int i = 0; i < table.size(); ++i ) {
for ( int j = 0; j < table[i].size(); ++j ) {
Index[table[i][j]][i] = true;
}
}
if ( table.size() > 0 )
for ( int j = 0; j < table[0].size(); ++j )
findPossible(enableIndex, table, 0, j, temp);
else
minPossibleList.push_back(temp);
outputProcess(table);
}
void McCluskey::findPossible(vector<bool> enableIndex, vector<vector<int>>& table, int ti, int tj, set<int> temp)
{
temp.insert(table[ti][tj]);
if ( min <= temp.size() )
return;
if ( ti + 1 != table.size() ) {
for ( int i = ti; i < enableIndex.size(); ++i ) {
if ( !enableIndex[i] )
enableIndex[i] = Index[table[ti][tj]][i];
}
while ( ti + 1 < enableIndex.size() )
if ( enableIndex[ti + 1] )
++ti;
else
break;
if ( ti + 1 != table.size() ) {
for ( int j = 0; j < table[ti + 1].size(); ++j )
findPossible(enableIndex, table, ti + 1, j, temp);
}
}
if ( ti + 1 == table.size() ) {
if ( min <= temp.size() )
return;
else if ( min > temp.size() ) {
min = temp.size();
minPossibleList.clear();
}
bool isIn = false;
for ( int i = 0; i < minPossibleList.size(); ++i )
if (minPossibleList[i] == temp ) {
isIn = true;
break;
}
if ( !isIn ) {
minPossibleList.push_back(temp);
/*
cout << temp.size() << " : ";
for ( set<int>::iterator it = temp.begin(); it != temp.end(); ++it )
cout << *it << " ";
cout << endl;
*/
}
return;
}
}
void McCluskey::output()
{
/*
for ( int i = 0; i < minPossibleList.size(); ++i ) {
cout << endl << "(" << i + 1 << ")" << endl;
for ( set< int >::iterator it = minPossibleList[i].begin(); it != minPossibleList[i].end(); ++it ) {
for ( int j = bits - 1; j >= 0; --j )
cout << prime[*it].s[j];
cout << endl;
}
}
*/
for ( set< int >::iterator it = minPossibleList[0].begin(); it != minPossibleList[0].end(); ++it ) {
for ( int j = bits - 1; j >= 0; --j )
cout << prime[*it].s[j];
cout << endl;
}
}
void McCluskey::outputMin(int i)
{
ofstream outFile("output", ios::app);
vector< vector<int> > result;
vector<int> buffer;
buffer.resize(bits);
outFile << '#' << i + 1 << endl;
for ( set< int >::iterator it = minPossibleList[0].begin(); it != minPossibleList[0].end(); ++it ) {
for ( int j = bits - 1; j >= 0; --j ) {
outFile << prime[*it].s[j];
}
outFile << endl;
}
}
void McCluskey::push(implicantlist& list, int N, vector<bool> S)
{
int back = list.size();
list.resize(back + 1);
list[back].n.insert(N);
for ( int i = 0; i < S.size(); ++i ) {
if ( S[i] ) {
list[back].s.push_back(1);
++(list[back].oneNum);
}
else
list[back].s.push_back(0);
}
}
void McCluskey::outputProcess(vector< vector< int > >& table)
{
//https://en.wikipedia.org/wiki/Quine%E2%80%93McCluskey_algorithm
//step 1
cout << "step 1 :";
int i = 0;
for ( vector<implicantlist>::iterator it1 = fullImplicantList.begin(); it1 != fullImplicantList.end(); ++it1 ) {
cout << endl << setw(4) << "<1>" << setw(3 + pow(2, i) * 3) << "m" << setw(10) << "implicant";
for ( implicantlist::iterator it2 = (*it1).begin(); it2 != (*it1).end(); ++it2 ) {
cout << endl << setw(4) << (*it2).oneNum << " ";
for ( set<int>::iterator it3 = (*it2).n.begin(); it3 != (*it2).n.end(); ++it3 )
cout << setw(3) << *it3 ;
cout << setw(6);
for ( vector<int >::iterator it4 = (*it2).s.begin(); it4 != (*it2).s.end(); ++it4 ) {
if ( *it4 == 2 )
cout << "-";
else
cout << *it4;
}
if ( (*it2).isPrime )
cout << "*";
}
++i;
cout << endl;
}
// step 2
cout << endl << "step 2 :" << endl;
for ( int i = 0; i < m.size(); ++i )
cout << setw(3) << m[i];
for ( int i = 0; i < prime.size(); ++i ) {
cout << endl;
for ( int j = 0; j < m.size(); ++j ) {
if ( prime[i].n.find(m[j]) != prime[i].n.end() )
cout << " *";
else
cout << " ";
}
}
cout << endl;
cout << endl << "table : ";
for ( int i = 0; i < table.size(); ++i ) {
cout << endl << "(" << i << ")";
for ( int j = 0; j < table[i].size(); ++j ) {
cout << table[i][j] << " ";
}
}
cout << endl;
cout << endl << "find possible combinations :" << endl;
for ( int i = 0; i < minPossibleList.size(); ++i ) {
for ( set<int>::iterator it = minPossibleList[i].begin(); it != minPossibleList[i].end(); ++it )
cout << *it << " ";
cout << endl;
}
cout << endl;
}
#endif // !MCCLUSKEY_H
|
bfa22206780ff73c3efac6b2f9c79515bd44f35e
|
79e13c2a952ba68b7fcee5ef5b34d9a8c41030f1
|
/Codeforces/Playing With Dice.cpp
|
312070e3c7f78b3190093c6023a97270fe4162ef
|
[] |
no_license
|
Shahin15-1573/mycode-arena
|
924a571a58eba07bc6455e9aeb02f7186e5b527d
|
05b615b80e90d76d05e761f6517ce3053458a44c
|
refs/heads/master
| 2020-02-26T13:18:13.304157
| 2015-11-27T20:08:19
| 2015-11-27T20:08:19
| 47,061,299
| 1
| 0
| null | 2015-11-29T11:43:12
| 2015-11-29T11:43:12
| null |
UTF-8
|
C++
| false
| false
| 989
|
cpp
|
Playing With Dice.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <algorithm>
using namespace std;
#define l long int
#define LL long long int
#define ULL unsigned long long
#define MAX 9999
int main(){
int a, b, way, fast, secnd, tmp, cnt, i, j, ans;
while (scanf ("%d%d", &a, &b) == 2){
//way = abs (a-b);
way = fast = secnd = 0;
for (i = 1; i <= 6; i++){
if (abs (i-a) < abs (i-b)) way++;
else if (abs (i-a) > abs (i-b)) secnd++;
else fast++;
}
printf ("%d %d %d\n", way, fast, secnd);
}
return 0;
}
/*int main(){
int a, b, way, fast, secnd, tmp, cnt, i, j, ans;
while (scanf ("%d%d", &a, &b) == 2){
way = abs (a-b);
fast = secnd = 0;
for (i = 1; i <= 6; i++){
if (abs (i-a) > abs (i-b)) secnd++;
else fast++;
}
printf ("%d %d %d\n", way, fast, secnd);
}
return 0;
}*/
|
98f2a4a24f9288394f7695c3fde4df76dfd77029
|
86113fa41cf26d5c6a5fa4e51f581ec5ef77b1ed
|
/Coursework2/Sphere/Particle.h
|
3c72907168ab5acd5d4ffd9d4cf8036e49faabca
|
[] |
no_license
|
SamiJones/Collision-Detection
|
b3120b9bd8843bc1b18a295752153ede05822a26
|
00e04efcfd05b386fe17772b54df92e4ab854dee
|
refs/heads/master
| 2021-03-19T16:44:05.155539
| 2018-01-17T20:42:37
| 2018-01-17T20:42:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,378
|
h
|
Particle.h
|
#pragma once
#include "CoreMath.h"
class Particle
{
private:
Vector2 position;
Vector2 velocity;
Vector2 acceleration;
Vector2 forceAccum;
float inverseMass;
float radius;
public:
Particle();
// calculates the next position of the particle.
// Duration denotes the time interval
//since the last update
void integrate(float duration);
// Sets the position of the particle by component
void setPosition(const float x, const float y);
// Gets the position of the particle.
Vector2 getPosition();
// Sets the velocity of the particle by component.
void setVelocity(const float x, const float y);
void setVelocity(const Vector2& velocity);
// Gets the velocity of the particle.
Vector2 getVelocity();
//Sets the radius of the particle.
void setRadius(const float r);
// Gets the radius of the particle
float getRadius();
// Sets the acceleration of the particle.
void setAcceleration(const Vector2 &acceleration);
void setAcceleration(const float x, const float y);
//Gets the acceleration of the particle.
Vector2 getAcceleration(void);
void setDamping(const float damping);
float getDamping();
void setMass(const float mass);
float getMass() const;
void setInverseMass(const float inverseMass);
float getInverseMass() const;
bool hasFiniteMass() const;
void clearAccumulator();
void addForce(const Vector2 &force);
};
|
6bc2c9c05fa38d677ea81795f7884fe660be793e
|
1a1a4c9cbae2ab5e4de408f81cd6ef959993dc64
|
/INFO450MULTIPLY/INFO450MULTIPLY.cpp
|
680531ce847aedf85dce3cca65756eaf3a6858c2
|
[] |
no_license
|
NoeBrow/INFO450MULTIPLY
|
f01a0c195486b0e0e49cd26cdf0380430a30a9bd
|
7052646e86199a295727d5845ed04a13383f6194
|
refs/heads/master
| 2020-04-10T14:16:33.554586
| 2016-09-13T00:20:59
| 2016-09-13T00:20:59
| 68,053,998
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 473
|
cpp
|
INFO450MULTIPLY.cpp
|
// INFO450Multiply.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
cout << "Multiplcation table: " << endl;
cout << "\t1\t2\t3\t4\t5\t6\t7\t8\t9\t" << endl;
for (int x = 1; x < 10; x++)
{
cout << x << '\t';
for (int y = 1; y < 10; y++)
{
cout << y * x << '\t';
}
cout << endl;
}
printf("Press anykey to continue...");
_getch();
return 0;
}
|
0326d3c5213913b370a747bbee382d951a1ffd3a
|
2d17040d5f8e7eac41e9d1ef90b5cbab22e52bbf
|
/include/graphics/scenegraph/modelloader/floormodelloader.hpp
|
6ace9fc6331536b4abcf421d1e5c9af83b71e086
|
[] |
no_license
|
ne0ndrag0n/Concordia
|
5818a09af5919288b3ebbca21f7f2fcef1a4f52a
|
98a0444509f9b0110a3e57cc9f4d535fd4585037
|
refs/heads/master
| 2021-06-17T17:20:22.976001
| 2019-07-27T20:41:47
| 2019-07-27T20:41:47
| 34,757,048
| 8
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,190
|
hpp
|
floormodelloader.hpp
|
#ifndef BB_FLOOR_MODEL_LOADER
#define BB_FLOOR_MODEL_LOADER
#include "graphics/scenegraph/modelloader/proceduralmodelloader.hpp"
#include "graphics/scenegraph/mesh/texturedvertex.hpp"
#include "graphics/scenegraph/mesh/meshdefinition.hpp"
#include "models/infrastructure.hpp"
#include "exceptions/genexc.hpp"
#include <glm/glm.hpp>
#include <memory>
#include <vector>
#include <array>
namespace BlueBear {
namespace Models {
class FloorTile;
}
namespace Scripting {
class Tile;
}
namespace Graphics {
namespace Utilities{ class ShaderManager; }
class Shader;
namespace SceneGraph {
class Model;
namespace ModelLoader {
class FloorModelLoader : public ProceduralModelLoader {
std::shared_ptr< Shader > shader;
const std::vector< Models::Infrastructure::FloorLevel >& levels;
sf::Image generateTexture( const Models::Infrastructure::FloorLevel& currentLevel );
public:
FloorModelLoader( const std::vector< Models::Infrastructure::FloorLevel >& levels, Utilities::ShaderManager& shaderManager );
virtual std::shared_ptr< Model > get();
};
}
}
}
}
#endif
|
4344e85e529d5b6264ce4985c82ebd9d87430a94
|
b4f3090140bd1310655e005361ce0594d1638be5
|
/SplashState.cpp
|
47441ccf7d1645d35e4470a2e969979148a1524c
|
[
"MIT"
] |
permissive
|
Adilyaa/Flappy_bird_cpp
|
5421713bd5e9ce97d35f34c89f96dfbc52f814be
|
cc8303278f8ca6f84204ff42b9ed6fcd7dc04358
|
refs/heads/master
| 2020-03-08T23:43:42.499582
| 2018-04-06T21:24:07
| 2018-04-06T21:40:39
| 128,471,305
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,371
|
cpp
|
SplashState.cpp
|
#include <sstream>
#include "SplashState.hpp"
#include "MainMenuState.hpp"
#include "DEFINITIONS.hpp"
#include <iostream>
namespace Sonar
{
SplashState::SplashState( GameDataRef data) : _data( data )
{
}
void SplashState::Init( )
{
_data->assets.LoadTexture( "Splash State Background", SPLASH_SCENE_BACKGROUND_FILEPATH );
_background.setTexture( this->_data->assets.GetTexture( "Splash State Background" ) );
}
void SplashState::HandleInput( )
{
sf::Event event;
while ( _data->window.pollEvent( event ) )
{
// std::cout << "ok";
// fflush(0);
if ( sf::Event::Closed == event.type )
{
// std::cout << "closed";
// fflush(0);
_data->window.close( );
}
}
}
void SplashState::Update(float dt)
{
if ( _clock.getElapsedTime( ).asSeconds( ) > SPLASH_STATE_SHOW_TIME)
{
_data->machine.AddState( StateRef( new MainMenuState( _data )), true );
}
}
void SplashState::Draw( float dt )
{
// std::cout << dt << std::endl;
_data->window.clear( );
_data->window.draw( _background );
_data->window.display( );
}
}
|
b33535902b6952a8e5fab59ad89d060c1d1d5fc7
|
154d29faa77b3cb97470cb1e0871c40d29c4bb9f
|
/propeller debug/P2 Graphical Debug Terminal.h
|
ec1a297c181344a59744be1d68aecb7ec65d91fa
|
[
"MIT"
] |
permissive
|
glgorman/rubidium
|
ac7b521ce820774c39a3900a6dbb8f6db99bd60e
|
7ae1cec2666225e8d5962bd94f01fb93504426b7
|
refs/heads/master
| 2023-07-11T18:17:47.940829
| 2023-06-28T23:48:56
| 2023-06-28T23:48:56
| 130,815,478
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 937
|
h
|
P2 Graphical Debug Terminal.h
|
// P2 Graphical Debug Terminal.h : main header file for the P2 Graphical Debug Terminal application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
#include "messages.h"
#include "compatibility.h"
#include "debugdisplayunit.h"
#include "propserial.h"
class CComThread;
class CTerminalThread;
class CDebugTerminalApp: public CWinApp
{
protected:
void StartTerminalThread ();
void StopTerminalThread ();
void StartComThread ();
void StopComThread ();
public:
CTerminalThread *m_pTerminalThread;
CComThread *m_pComThread;
public:
CDebugTerminalApp();
virtual BOOL InitInstance();
virtual int ExitInstance();
DECLARE_MESSAGE_MAP()
afx_msg void OnAppAbout();
afx_msg void OnToolsDetectHardware();
afx_msg void OnToolsDisplaycputypes();
afx_msg void OnToolsDetectcomports();
};
|
325012e9eb4e85b83c4d20f29c22b49b36cefc82
|
3c6c9373298fca5549d4a753bf7ed3a336d5209d
|
/src/stiffness_ellipsoid/src/ellipsoid_visualization.cpp
|
2223ffe36c37dbfe57d7980d602b1ca8e8948c02
|
[] |
no_license
|
JLSchol/omni_marco_gazebo
|
70077a4648b186bd09510e29f35664bd28f13fd0
|
050cb6dad674a5ff05b0cd5713d989d0d9bf05ee
|
refs/heads/master
| 2023-01-30T16:13:07.620255
| 2019-12-06T15:39:30
| 2019-12-06T15:39:30
| 211,870,305
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,929
|
cpp
|
ellipsoid_visualization.cpp
|
#include "stiffness_ellipsoid/ellipsoid_visualization.h"
EllipsoidVisualization::EllipsoidVisualization():
nh_("~")
{
ROS_INFO_STREAM("----------------------------------");
getParameters();
initializeSubscribers();
initializePublishers();
}
void EllipsoidVisualization::getParameters()
{
// pub/sub names
nh_.param<std::string>("input_topic_name", stiffness_topic_name_, "/stiffness_command");
nh_.param<std::string>("output_topic_name", marker_topic_name_, "/ellipsoid_visualization");
// TF frame names
nh_.param<std::string>("base_frame_name", base_frame_name_, "base_footprint");
nh_.param<std::string>("ee_frame_name", ee_frame_name_, "wrist_ft_tool_link");
// rosparam server from other launch file
// std::string stiffness_min_path, stiffness_max_path, lambda_min_path, lambda_max_path, lambda_max_path;
if (nh_.hasParam("/stiffness_learning/stiffness_min") &&
nh_.hasParam("/stiffness_learning/stiffness_max") &&
nh_.hasParam("/stiffness_learning/lambda_min") &&
nh_.hasParam("/stiffness_learning/lambda_max"))
{
nh_.getParam("/stiffness_learning/stiffness_min", stiffness_min_);
nh_.getParam("/stiffness_learning/stiffness_max", stiffness_max_);
nh_.getParam("/stiffness_learning/lambda_min", lambda_min_);
nh_.getParam("/stiffness_learning/lambda_max", lambda_max_);
}
else
{
ROS_INFO_STREAM("PARAMETERS NOT FOUND");
}
// if (nh_.getParam("relative_name", relative_name))
// {
// }
// Default value version
// nh_.param<float>("stiffness_min", stiffness_min_, 1);
// nh_.param<float>("stiffness_max", stiffness_max_, 1);
// nh_.param<float>("lambda_min", lambda_min_, 1);
// nh_.param<float>("lambda_max", lambda_max_, 1);
// nh_.param<float>("window_length", window_length_, 1);
// nh_.param<std::string>("default_param", default_param, "default_value");
}
void EllipsoidVisualization::initializeSubscribers()
{
stiffness_sub_ = nh_.subscribe(stiffness_topic_name_, 1, &EllipsoidVisualization::CB_getStiffnessArray, this);
}
void EllipsoidVisualization::initializePublishers()
{
marker_pub_ = nh_.advertise<visualization_msgs::Marker>(marker_topic_name_,1);
marker_pub_arrow_ = nh_.advertise<visualization_msgs::Marker>("arrow_vizualisation",1);
}
void EllipsoidVisualization::CB_getStiffnessArray(const std_msgs::Float32MultiArray& stiffness_array_msgs)
{
stiffness_MultiArray_ = stiffness_array_msgs; // als cb klaar msgs weg?!?! o.O
// ROS_INFO_STREAM(stiffness_MultiArray_);
}
Eigen::Matrix3f EllipsoidVisualization::getStiffnessMatrix()
{
// ROS_INFO_STREAM(stiffness_MultiArray_);
float dstride0 = stiffness_MultiArray_.layout.dim[0].stride; //9 just total elements
float dstride1 = stiffness_MultiArray_.layout.dim[1].stride; //3
float h = stiffness_MultiArray_.layout.dim[0].size;
float w = stiffness_MultiArray_.layout.dim[1].size;
// ROS_INFO_STREAM("h"<< h);
Eigen::Matrix3f stiffness_matrix = Eigen::Matrix3f::Zero();
for(int i=0; i<h; ++i){
for(int j=0; j<w; ++j){
// multiarray(i,j,k) = data[data_offset + dim[1]stride*i + dim[2]stride*j + k]
stiffness_matrix(i,j) = stiffness_MultiArray_.data[dstride1*i+j];
// ROS_INFO_STREAM("multiarr: "<<stiffness_MultiArray_.data[dstride1*i+j]);
// ROS_INFO_STREAM("stiffnessmat: "<<stiffness_matrix(i,j));
}
}
// ROS_INFO_STREAM(stiffness_matrix);
return stiffness_matrix;
}
std::pair<Eigen::Matrix3f, Eigen::Vector3f> EllipsoidVisualization::computeEigenValuesAndVectors(Eigen::Matrix3f stiffness)
{
Eigen::Vector3f eigen_values = Eigen::Vector3f::Identity();
Eigen::Matrix3f eigen_vectors = Eigen::Matrix3f::Zero();
// Compute eigen values and eigen vectors.
Eigen::EigenSolver<Eigen::Matrix3f> eigensolver(stiffness);
if (eigensolver.info() == Eigen::Success)
{
eigen_values = eigensolver.eigenvalues().real();
eigen_vectors = eigensolver.eigenvectors().real();
}
else
{
ROS_WARN_THROTTLE(1, "Failed to compute eigen vectors/values. Is the stiffness matrix correct?");
}
return std::make_pair(eigen_vectors, eigen_values);
}
tf2::Quaternion EllipsoidVisualization::computeRotation(std::pair<Eigen::Matrix3f, Eigen::Vector3f>& vector_value_pair)
{
Eigen::Vector3f V1,V2,V3;
tf2::Quaternion my_quaternion, ee_2_base_quat,relative_quat;
Eigen::Matrix3f eigen_vectors = vector_value_pair.first;//.transpose();
// ROS_INFO_STREAM("EIGENVECTORS IN compute rotation: \n"<<eigen_vectors);
// ROS_INFO_STREAM("Kmatrix: \n "<< K_matrix);;
// Eigen::Vector3f eigen_values = vector_value_pair.second;
// Eigen::Matrix3f k_diag;
// k_diag.setIdentity();
// for(int i=0; i<3;++i){
// k_diag(i,i) = eigen_values(i);
// }
// Eigen::Matrix3f K_matrix = eigen_vectors * k_diag * eigen_vectors.transpose();
// ROS_INFO_STREAM("Kmatrix: \n "<< K_matrix);
ee_2_base_quat[0] = -0.5;
ee_2_base_quat[1] = 0.5;
ee_2_base_quat[2] = 0.5;
ee_2_base_quat[3] = -0.5; // invert quaternion
// base_2_ee_quat[3] = -1*base_2_ee_quat.w(); // invert quaternion
tf2::Matrix3x3 matrixclass;
// V1(0) =eigen_vectors(0,0);
// V1(1) =eigen_vectors(1,0);
// V1(2) =eigen_vectors(2,0);
// V1.normalize();
// V2(0)=eigen_vectors(0,1);
// V2(1)=eigen_vectors(1,1);
// V2(2)=eigen_vectors(2,1);
// V2.normalize();
// V3(0)=eigen_vectors(0,2);
// V3(1)=eigen_vectors(1,2);
// V3(2)=eigen_vectors(2,2);
// V3.normalize();
matrixclass.setValue(eigen_vectors(0,0), eigen_vectors(0,1), eigen_vectors(0,2),
eigen_vectors(1,0), eigen_vectors(1,1), eigen_vectors(1,2),
eigen_vectors(2,0), eigen_vectors(2,1), eigen_vectors(2,2));
// matrixclass.setValue(V1(0), V2(0), V3(0),
// V1(1), V2(1), V3(1),
// V1(2), V2(2), V3(2));
matrixclass.getRotation(my_quaternion);
relative_quat = my_quaternion*ee_2_base_quat;
// my_quaternion[3] = -1*my_quaternion.w();
double yaw,pitch,roll;
matrixclass.getEulerYPR(yaw,pitch,roll);
yaw = yaw*(180/3.141);
pitch = pitch*(180/3.141);
roll = roll*(180/3.141);
ROS_INFO_STREAM("\n yaw:"<<yaw << " pitch:"<<pitch
<< " roll:"<<roll );
my_quaternion.normalize(); //fout!!
ROS_INFO_STREAM("quaternionen in computeRotation\n "<< "x:" <<my_quaternion[0] << " y:"
<< my_quaternion[0] << " z:"<< my_quaternion[0] << " w:"<< my_quaternion[0]);
return my_quaternion;
// return relative_quat;
}
Eigen::Vector3f EllipsoidVisualization::computeScale(std::pair<Eigen::Matrix3f, Eigen::Vector3f>& vector_value_pair)
{
Eigen::Vector3f eigen_values = vector_value_pair.second;
Eigen::Vector3f scalings = Eigen::Vector3f::Identity();
for(int i=0; i<scalings.size(); ++i)
{
float k = eigen_values(i);
float lambda;
if(k>=stiffness_max_){
lambda = lambda_min_;
}
else if(k > stiffness_min_ && k < stiffness_max_){
lambda = lambda_min_ - (lambda_min_ - lambda_max_)/(stiffness_min_ - stiffness_max_) * (k - stiffness_max_);
}
else if(k<=stiffness_min_){
lambda = lambda_max_;
}
else{
ROS_INFO_STREAM("Er is iets mis gegaan");
}
scalings(i) = lambda;
}
return scalings;
}
void EllipsoidVisualization::run()
{
if(stiffness_MultiArray_.data.empty()){
return; // no data, no muney
}
getTF();
Eigen::Matrix3f stiffness_matrix = getStiffnessMatrix();
// ROS_INFO_STREAM(stiffness_matrix);
std::pair<Eigen::Matrix3f, Eigen::Vector3f> stiffness_eigenVectors_and_values = computeEigenValuesAndVectors(stiffness_matrix);
// ROS_INFO_STREAM("vector: \n" << stiffness_eigenVectors_and_values.first);
// ROS_INFO_STREAM("values: \n" << stiffness_eigenVectors_and_values.second);
// Eigen::EigenSolver<Eigen::Matrix3f> eigensolver(stiffness_matrix);
// Eigen::Vector3f eigen_values = eigensolver.eigenvalues().real();
// Eigen::Matrix3f eigen_vectors = eigensolver.eigenvectors().real();
// // ROS_INFO_STREAM("K_matrix: "<< "\n" << K_matrix);
// ROS_INFO_STREAM("vector: \n" << eigen_vectors);
// ROS_INFO_STREAM("values: \n" << eigen_values);
// ROS_INFO_STREAM("EIGENVECTORS IN RUN: \n"<<stiffness_eigenVectors_and_values.first);
// tf2::Quaternion rotation = computeRotation(stiffness_eigenVectors_and_values);
// tf2::Quaternion omni_2_base_quat;
// tf2::Matrix3x3 omni_2_base_trans;
// omni_2_base_trans.setValue( 0, -1, 0,
// 0, 0, -1,
// -1, 0, 0);
// omni_2_base_trans.getRotation(omni_2_base_quat);
// rotation = omni_2_base_quat*rotation;
// ROS_INFO_STREAM("quaternionen in run\n qx:"<<rotation[0] << " qy:"<<rotation[1]
// << " qz:"<<rotation[2] << " qw:"<<rotation[3]);
// Eigen::Vector3f scales = computeScale(stiffness_eigenVectors_and_values);
// ROS_INFO_STREAM("Scaling: "<< scales);
setEllipsoidMsg(stiffness_eigenVectors_and_values);
// Eigen::Matrix3f matrix_of_eigen_vectors= stiffness_eigenVectors_and_values.first
Eigen::Vector3f scales = computeScale(stiffness_eigenVectors_and_values);
for(int i = 0; i<3; ++i){
visualization_msgs::Marker arrow_i = setArrowMsg(stiffness_eigenVectors_and_values.first,
scales,i);
marker_pub_arrow_.publish(arrow_i);
}
marker_pub_.publish(ellipsoid_);
ROS_INFO_STREAM("---------------------------------------------------------------------");
}
void EllipsoidVisualization::setEllipsoidMsg(std::pair<Eigen::Matrix3f, Eigen::Vector3f>& stiffness_eigenVectors_and_values)
{
tf2::Quaternion rotation = computeRotation(stiffness_eigenVectors_and_values);
Eigen::Vector3f scales = computeScale(stiffness_eigenVectors_and_values);
// scales(2)= 2*scales(2);
// Set the frame ID and timestamp. See the TF tutorials for information on these.
ellipsoid_.header.frame_id = base_frame_name_; // verancer nog
ellipsoid_.header.stamp = ros::Time::now();
// Set the namespace and id for this marker. This serves to create a unique ID
// Any marker sent with the same namespace and id will overwrite the old one
ellipsoid_.ns = "ellipsoid"; // TODO: make variable
ellipsoid_.id = 0;
// Set the marker type. Initially this is CUBE, and cycles between that and SPHERE, ARROW, and CYLINDER
ellipsoid_.type = visualization_msgs::Marker::SPHERE;
// Set the marker action. Options are ADD, DELETE, and DELETEALL
ellipsoid_.action = visualization_msgs::Marker::ADD;
// Set the pose of the marker. This is a full 6DOF pose relative to the frame/time specified in the header
ellipsoid_.pose.position.x = base_to_ee_.getOrigin().x();//1;
ellipsoid_.pose.position.y = base_to_ee_.getOrigin().y();//1;
ellipsoid_.pose.position.z = base_to_ee_.getOrigin().z();//1;
// marker_.pose.position = base_to_marker_.getOrigin();
ROS_INFO_STREAM("quaternionen ixn setEllipsoidMsgs\n qx:"<<rotation[0] << " qy:"<<rotation[1]
<< " qz:"<<rotation[2] << " qw:"<<rotation[3]);
ROS_INFO_STREAM("With scale IN setEllipsoidMsg: \n" <<scales);
ellipsoid_.scale.x = 3*scales(0);
ellipsoid_.scale.y = 3*scales(1);
ellipsoid_.scale.z = 3*scales(2);
ROS_INFO_STREAM("EIGENVECTORS IN setEllipsoidMsg \n" << stiffness_eigenVectors_and_values.first);
ellipsoid_.pose.orientation.x = rotation.x();//0.0076248;//rotation.x();//rotation.x();//base_to_ee_.getRotation().x();
ellipsoid_.pose.orientation.y = rotation.y();//-0.0871531;//rotation.y();//rotation.y();//base_to_ee_.getRotation().y();
ellipsoid_.pose.orientation.z = rotation.z();//0;//rotation.z();//rotation.z();//base_to_ee_.getRotation().z();
ellipsoid_.pose.orientation.w = rotation.w();//0.9961657;//rotation.w();//rotation.w();//base_to_ee_.getRotation().w();
// marker_.pose.orientation = base_to_ee_.getRotation();
// Set the scale of the marker -- 1x1x1 here means 1m on a side
// ROS_INFO_STREAM("With scale IN setEllipsoidMsg: \n"<<1<<") scale:"<<scales(0));
// ROS_INFO_STREAM("With scale IN setEllipsoidMsg: \n"<<2<<") scale:"<<scales(1));
// ROS_INFO_STREAM("With scale IN setEllipsoidMsg: \n"<<3<<") scale:"<<scales(2));
// Set the color -- be sure to set alpha to something non-zero!
ellipsoid_.color.r = 1.0f;
ellipsoid_.color.g = 0.3f;
ellipsoid_.color.b = 1.0f;
ellipsoid_.color.a = 0.3;
ellipsoid_.lifetime = ros::Duration();
}
visualization_msgs::Marker EllipsoidVisualization::setArrowMsg(Eigen::Matrix3f M, Eigen::Vector3f& scales, int vector_i)
{
visualization_msgs::Marker arrow;
// get vector wrt base?
Eigen::Vector3f V;
V(0) = M(0,vector_i);
V(1) = M(1,vector_i);
V(2) = M(2,vector_i);
ROS_INFO_STREAM("EIGENVECTORS IN ARROW: \n"<<V);
ROS_INFO_STREAM("With scale IN ARROW: \n"<<vector_i+1<<") scale:"<<scales(vector_i));
V = 1.5*V*scales(vector_i); //scale it
// if (vector_i == 2){
// V = 2*V;
// }
// Set the frame ID and timestamp. See the TF tutorials for information on these.
arrow.header.frame_id = base_frame_name_; // verancer nog
arrow.header.stamp = ros::Time::now();
// Set the namespace and id for this marker. This serves to create a unique ID
// Any marker sent with the same namespace and id will overwrite the old one
arrow.ns = "arrow"; // TODO: make variable
arrow.id = vector_i+1; // std::to_string(vector_i+1)
// Set the marker type. Initially this is CUBE, and cycles between that and SPHERE, ARROW, and CYLINDER
arrow.type = visualization_msgs::Marker::ARROW;
// Set the marker action. Options are ADD, DELETE, and DELETEALL
arrow.action = visualization_msgs::Marker::ADD;
// use [start end] vector
geometry_msgs::Point start,end;
start.x = base_to_ee_.getOrigin().x();
start.y = base_to_ee_.getOrigin().y();
start.z = base_to_ee_.getOrigin().z();
end.x = base_to_ee_.getOrigin().x()+ V(0);
end.y = base_to_ee_.getOrigin().y()+ V(1);
end.z = base_to_ee_.getOrigin().z()+ V(2);
arrow.points.push_back(start);
arrow.points.push_back(end);
// Set the scale of the marker -- 1x1x1 here means 1m on a side
arrow.scale.x = 0.01; //shaft diameter
arrow.scale.y = 0.03; // head diameter
arrow.scale.z = 0.01; // head length
// Set the color -- be sure to set alpha to something non-zero!
float color[3] = {0,0,0};
switch (vector_i)
{
case 0:
color[0] = 255; //red
break;
case 1:
color[1] = 255; //bleu
break;
case 2:
color[2] = 255; //green
break;
}
arrow.color.r = color[0];
arrow.color.g = color[1];
arrow.color.b = color[2];
arrow.color.a = 1;
arrow.lifetime = ros::Duration();
return arrow;
}
void EllipsoidVisualization::getTF()
{
if (TF_listener_.waitForTransform(ee_frame_name_, base_frame_name_, ros::Time(0), ros::Duration(0.25)))
{
TF_listener_.lookupTransform(base_frame_name_, ee_frame_name_,ros::Time(0), base_to_ee_);
}
}
int main( int argc, char** argv )
{
ros::init(argc, argv, "stiffness_ellipsoid");
EllipsoidVisualization node;
while (ros::ok())
{
ros::Rate loop_rate(30);
node.run();
ros::spinOnce();
loop_rate.sleep();
}
}
|
1f4c85f22238b390d86a2ab814639fa1d386d789
|
5c7f0c4b112b0e2d37a53b42717d743fc861df72
|
/CreatAllParameter - 副本/CreatAllParameter/BullMarkBearMark.cpp
|
6b1d612568e1de37a776a95b9589c7b757ceb7d2
|
[] |
no_license
|
136397089/Windows_Projects
|
7f8aaf4875880842deba45a91f92b496f43fcad0
|
8f4a5fd325e1b22df6a5649a4f64b4f4105eabdd
|
refs/heads/master
| 2022-02-15T08:41:29.268455
| 2019-08-24T03:36:16
| 2019-08-24T03:36:16
| 162,861,429
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,387
|
cpp
|
BullMarkBearMark.cpp
|
#include "stdafx.h"
#include "BullMarkBearMark.h"
#include "glog/logging.h"
CBullMarkBearMark::CBullMarkBearMark()
{
}
CBullMarkBearMark::~CBullMarkBearMark()
{
}
#define BULLMARKET 10
MarketTypeList CBullMarkBearMark::GetMarketTypes(const VStockData& pricedata, const vector<string>& day)
{
MarketTypeList templist;
templist.clear();
if (pricedata.size() != day.size())
return templist;
if (pricedata.size() == 0)
return templist;
StockDataType fristData = pricedata[0];
StockDataType FrontData = pricedata[0];
string FrontDay = day[0];
MarketTypeIndex tempmarkindex;
bool fristIndexFound = false;
bool findBull = true;
for (unsigned int i = 0; i < pricedata.size();i++)
{
//判断第一个市场特征
if ((pricedata[i] - FrontData) * 100 / FrontData >= BULLMARKET && (!fristIndexFound))
{
fristIndexFound = true;
findBull = true;
FrontData = pricedata[i];
FrontDay = day[i];
tempmarkindex._markettype = BullMarket;
tempmarkindex._day.SetDay(day[i]);
tempmarkindex._mdata = pricedata[i];
tempmarkindex._relativeDate.SetDay(day[0]);
tempmarkindex._relativeData = FrontData;
templist.push_back(tempmarkindex);
continue;
}
else if ((pricedata[i] - FrontData) * 100 / FrontData <= -BULLMARKET && (!fristIndexFound))
{
fristIndexFound = true;
findBull = false;
FrontData = pricedata[i];
FrontDay = day[i];
tempmarkindex._markettype = BearMarket;
tempmarkindex._day.SetDay(day[i]);
tempmarkindex._mdata = pricedata[i];
tempmarkindex._relativeDate.SetDay(day[0]);
tempmarkindex._relativeData = FrontData;
templist.push_back(tempmarkindex);
continue;
}
//判断后面的市场特征
if (fristIndexFound)
{
if (!findBull && (pricedata[i] - FrontData) * 100 >= BULLMARKET * FrontData){// 找牛市点
tempmarkindex._markettype = BullMarket;
tempmarkindex._day.SetDay(day[i]);
tempmarkindex._mdata = pricedata[i];
tempmarkindex._relativeDate.SetDay(FrontDay);
tempmarkindex._relativeData = FrontData;
templist.push_back(tempmarkindex);
findBull = true;
FrontData = pricedata[i];
}
if (!findBull && pricedata[i] < FrontData){
FrontData = pricedata[i];
FrontDay = day[i];
}
if (findBull && (pricedata[i] - FrontData) * 100 <= -BULLMARKET *FrontData){//找熊市场点
tempmarkindex._markettype = BearMarket;
tempmarkindex._day.SetDay(day[i]);
tempmarkindex._mdata = pricedata[i];
tempmarkindex._relativeDate.SetDay(FrontDay);
tempmarkindex._relativeData = FrontData;
templist.push_back(tempmarkindex);
findBull = false;
FrontData = pricedata[i];
}
if (findBull && pricedata[i] > FrontData){
FrontData = pricedata[i];
FrontDay = day[i];
}
}
}
#ifdef _MYDEBUG
LOG(INFO) << "MarketData";
for (unsigned int i = 1; i < templist.size();i++)
{
LOG(INFO) << "FrontData:" << int(templist[i]._inputdata) << " \t"
<< "FrontDay:" << templist[i]._day.GetDay() << " \t"
<< "RelativeData:" << int(templist[i]._relativeData) << " \t"
<< "RelativeDay:" << templist[i]._relativeDate.GetDay() << " \t"
<< "MaxChangeRage:" << (templist[i]._relativeData - templist[i - 1]._relativeData) * 100 / templist[i - 1]._relativeData
<< endl;
}
#endif
return templist;
}
|
0bd9622d18e6717f8ff04c2ca5edf4cfc486f940
|
78e5db3cb0f586d5571854754d72e7866093e8ad
|
/training/Elephant/main.cpp
|
0f77a9eafde85449ad488787c1ff0759168e5fa7
|
[] |
no_license
|
Vietdung113/Cp-Algorithm
|
347f38df3e0cd0d2763ba591fc77e405dfdd7280
|
24c79ebf69f331cba27783e1a9522cb6c88b0edd
|
refs/heads/main
| 2023-05-24T12:25:10.388062
| 2023-05-17T13:23:48
| 2023-05-17T13:23:48
| 331,326,065
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,147
|
cpp
|
main.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define DOWN 0
#define UP 1
long long s[2][301][301];
bool visited[2][301][301];
int T;
int N;
long long calc(int a,int b,int k){
if(a+b == 0) return 1;
if(visited[k][a][b]) return s[k][a][b];
visited[k][a][b] = true;
if(k){
for(int i =1; i<=b; i++){
s[k][a][b] += calc(a+i-1,b-i,1-k) ;
if(s[k][a][b] >= 1000000007){
s[k][a][b] -= 1000000007;
}
}
}else
{
for(int i=1;i<=a;i++){
s[k][a][b]+=calc(i-1,a+b-i,1-k);
if(s[k][a][b] >= 1000000007){
s[k][a][b] -= 1000000007;
}
}
}
return s[k][a][b];
}
int main(){
cin >> T;
for(int t=1;t<=T;t++){
cin >> N;
long long anws = 0;
memset(visited,false, sizeof visited);
memset(s, 0, sizeof s);
for(int i=1;i<=N;i++){
anws += (calc(i-1,N-i,DOWN) + calc(i-1,N-i,UP)) % 1000000007;
if(anws>= 1000000007){
anws -= 1000000007;
}
}
cout << "#" << t << " " << anws<<endl;;
}
}
|
5bcd289297956a48387b5b803f7a3f5ab91304c5
|
47ec47a5bb53e6a12bac91e97741e48ae460881d
|
/Computer Programming Year - II/An II OOP Labs/ATM Homework/ATM Homework/Bank.h
|
5f9f5784773288da1a5c9c0b12e7a59ed7fd72f3
|
[] |
no_license
|
zVoxty/University
|
ad97f3bc1ba7e850cad3725098b610e037eceb99
|
8d9822631a3c8c13506d528ab6a3cbf660a511d3
|
refs/heads/master
| 2020-12-29T02:42:53.186222
| 2018-05-17T05:52:44
| 2018-05-17T05:52:44
| 53,352,966
| 0
| 1
| null | 2016-05-31T09:19:08
| 2016-03-07T19:33:00
|
HTML
|
UTF-8
|
C++
| false
| false
| 510
|
h
|
Bank.h
|
#pragma once
#include <string>
using namespace std;
class Bank
{
public:
Bank();
~Bank();
//Getters
int getMoney();
string getCardNumber();
string getCardPIN();
string getFirstName();
string getLastName();
//Setters
void setMoney(int money);
void setFirstName(string firstName);
void setLastName(string lastName);
void setCardNumber(string cardNumber);
void setCardPIN(string cardPIN);
private:
int _money;
string _cardNumber;
string _cardPIN;
string _firstName;
string _lastName;
};
|
ff4b6f2f43859918ecc90fc19eb1fc04c7f6674b
|
5260e67aa57535dea1c807e3de993a64fb2d1bb9
|
/test/main.cpp
|
9bc0c54b0a4117d41a3a8f45b85eb5af047f1272
|
[] |
no_license
|
glandu2/librzu
|
bcbc7fde1f4cc48154da1e6ce4a8ad6a46df7bb7
|
46305cd935e3f887a8e160b8ffe58928c02520a8
|
refs/heads/master
| 2021-01-10T11:29:39.913740
| 2020-08-26T21:27:10
| 2020-08-26T21:27:10
| 36,559,923
| 6
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 196
|
cpp
|
main.cpp
|
#include "RunTests.h"
#include "gtest/gtest.h"
static void initConfigs() {}
int main(int argc, char** argv) {
TestRunner testRunner(argc, argv, &initConfigs);
return testRunner.runTests();
}
|
8abd0ed690ccfe14d7b9aa3d96030b682a416c20
|
e78f80f028b1fba0a09652a4bb6dd4a14283e96f
|
/Cpp_version/ALI_two_stream_approx_cpp/dydx.cpp
|
31bf642d83618d41e332958f532c9bb10f1f775e
|
[] |
no_license
|
taylerquist/Python_RT
|
40790a0e7183c4a42a0d736e65a1d53049483c08
|
30f767f634cb5a3e29c96d1b91622d9a5949f237
|
refs/heads/master
| 2021-07-11T19:23:22.045762
| 2020-07-17T19:48:48
| 2020-07-17T19:48:48
| 162,329,469
| 0
| 1
| null | 2019-01-09T20:14:41
| 2018-12-18T18:24:07
|
Jupyter Notebook
|
UTF-8
|
C++
| false
| false
| 2,064
|
cpp
|
dydx.cpp
|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cmath>
double dydx(double x, double f, double rho, double avg_I)
{
/*
* Units of each input/output
* f: This is the current value of QHII, dimensionless
* rho: #/cm^3
* avg_I: (erg)(cm^-2)(s^-1)(Hz^-1)(rad^-2)
*/
double c_HII = 3.; // Clumping fraction for the IGM at z=3, T=20,000K
double alpha_B; // Recombination coefficient, cm**3/s
double sigma_nu; // Photoionization cross-section of H ions
double Y_p = 0.24; // Fraction of Helium
double X_p = 1. - Y_p; // Fraction of Hydrogen
double n_h_avg; // Hydrogen number density in each cell
double n_dot_ion; // Ionizing photon rate
double t_rec_inv; // Recombination time
double pi = 3.14159265358979323846; // Value of pi
double c_light = 3.*pow(10.,10.); // Speed of light in cm/s
double eps_ion = pow(10.,25.25); // Ionizing photon production efficiency Hz/erg
double lmfp;
double dQp, dQn;
double answer;
// Set the constants needed for (t_rec)**(-1)
alpha_B = 2.6*pow(10.,-13.);
alpha_B = 2.6e-13;
sigma_nu = 7.91e-18;
//sigma_nu = 7.91*pow(10.,-18.);
n_h_avg = rho*X_p;
// * avg_I: (erg)(cm^-2)(s^-1)(Hz^-1)(rad^-2)
//n_dot_ion = avg_I*(4*pi)*c_HII*n_h_avg*sigma_nu*eps_ion;
// * n_dot_ion: (cm^-3)(s^-1)
/*if(f<1)
{
lmfp = 1./(c_HII*(1-f)*n_h_avg*sigma_nu);
}else{
lmfp = 1.0e24;
}*/
lmfp = 1./(c_HII*(1-f)*n_h_avg*sigma_nu);
if(lmfp>1.0e24)
lmfp = 1.0e24;
//lmfp =
lmfp = 2.782235e+22;
n_dot_ion = avg_I*(4*pi)*eps_ion/lmfp;
//n_dot_ion = (4*pi/c)*avg_I*eps_ion; //# density of ionizing photons
t_rec_inv = c_HII*alpha_B*(1. + (Y_p/(4.*X_p)))*n_h_avg;
// Return the spatially dependent solution
dQp = n_dot_ion/n_h_avg;
dQn = f*t_rec_inv;
answer = dQp - dQn;
//printf("t %e avg_I %e n_dot_ion %e lmfp %e n_h_ave %e f %e t_rec_inv %e dQ %e %e answer %e\n",x,avg_I,n_dot_ion,lmfp,n_h_avg,f,t_rec_inv,dQp,dQn,answer);
return answer;
}
|
d766564ae75a69ea0a9fd270d48d6bdc8e822446
|
451749dfb5f78e53766526406f3c9f89b5e0c90f
|
/src/indexed_force_tri_3D.cpp
|
8a87f8223a7bd4e17c0b9b6802b9bc0b0c8187c2
|
[] |
no_license
|
joelfl/tri_tracker
|
7daed16ae85e3b9f617d85875e788fb92b8960af
|
bf809e3c45884dc5b9b300bf3e1284c621544857
|
refs/heads/master
| 2021-06-25T09:01:07.608883
| 2014-09-05T15:51:17
| 2014-09-05T15:51:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,525
|
cpp
|
indexed_force_tri_3D.cpp
|
/******************************************************************************
** Program : indexed_force_tri_3D.cpp
** Author : Neil Massey
** Date : 11/06/13
** Purpose : class to hold 3D triangle information with reference to points in
** the point cloud and reference to indices in the original grid
******************************************************************************/
#include "indexed_force_tri_3D.h"
#include "bin_file_utils.h"
/*****************************************************************************/
indexed_force_tri_3D::indexed_force_tri_3D(void) : force_tri_3D()
{
}
/*****************************************************************************/
indexed_force_tri_3D::indexed_force_tri_3D(point_cloud* pPC, int ip0, int ip1, int ip2, LABEL i_label)
:force_tri_3D(pPC, ip0, ip1, ip2), label(i_label)
{
}
/*****************************************************************************/
indexed_force_tri_3D::indexed_force_tri_3D(const force_tri_3D& rhs)
:force_tri_3D(rhs)
{
}
/*****************************************************************************/
void indexed_force_tri_3D::add_index(int ii, int ij, vector_3D cart_coord)
{
// add a grid index to this triangle
grid_index gdx;
gdx.i = ii;
gdx.j = ij;
gdx.cart_coord = cart_coord;
grid_indices.push_back(gdx);
}
/*****************************************************************************/
void indexed_force_tri_3D::set_label(LABEL i_label)
{
label = i_label;
}
/*****************************************************************************/
LABEL indexed_force_tri_3D::get_label(void)
{
return label;
}
/*****************************************************************************/
int indexed_force_tri_3D::get_number_of_indices(void)
{
return grid_indices.size();
}
/*****************************************************************************/
const std::list<grid_index>* indexed_force_tri_3D::get_grid_indices(void) const
{
return &grid_indices;
}
/*****************************************************************************/
void indexed_force_tri_3D::add_adjacency(LABEL label, ADJACENCY type)
{
adjacency[type].push_back(label);
}
/*****************************************************************************/
const LABEL_STORE* indexed_force_tri_3D::get_adjacent_labels(ADJACENCY type) const
{
return &(adjacency[type]);
}
/*****************************************************************************/
int indexed_force_tri_3D::get_ds_index(void)
{
return ds_index;
}
/*****************************************************************************/
void indexed_force_tri_3D::set_ds_index(int ti)
{
ds_index = ti;
}
/*****************************************************************************/
void indexed_force_tri_3D::save(std::ofstream& out)
{
// write the label string
write_label(out, label);
// write the point cloud indices for each vertex
for (int t=0; t<3; t++)
write_int(out, p[t]);
// write the target index
write_int(out, ds_index);
// write the index list - first the length
write_int(out, grid_indices.size());
// now write all the indices
for (std::list<grid_index>::iterator it=grid_indices.begin();
it!=grid_indices.end(); it++)
{
write_int(out, it->i);
write_int(out, it->j);
write_vector(out, it->cart_coord);
}
// write the point and edge adjacency list
for (int a=0; a<2; a++)
{
write_int(out, adjacency[a].size());
for (LABEL_STORE::iterator it=adjacency[a].begin();
it!= adjacency[a].end(); it++)
write_label(out, *it);
}
}
/*****************************************************************************/
void indexed_force_tri_3D::load(std::ifstream& in, point_cloud* pPC)
{
// read the label in and set it
LABEL label = read_label(in);
set_label(label);
if (in.eof())
return;
// set the point cloud
ppoint_cloud_instance = pPC;
// read the point cloud indices for each vertex
for (int t=0; t<3; t++)
p[t] = read_int(in);
// calculate the centroid
calculate_centroid();
// read the target index
ds_index = read_int(in);
// read the length of index list in
int n_idx = read_int(in);
for (int i=0; i<n_idx; i++)
{
grid_index gr_idx;
gr_idx.i = read_int(in);
gr_idx.j = read_int(in);
gr_idx.cart_coord = read_vector(in);
grid_indices.push_back(gr_idx);
}
// read the point and adjacency list
for (int a=0; a<2; a++)
{
// get the size first
int s = read_int(in);
for (int i=0; i<s; i++)
adjacency[a].push_back(read_label(in));
}
}
|
157ca88465aee7cccd3b1c27acc69c922d1fc4c9
|
a61e42d6ad1928547a06e1c2330d3da143f1b153
|
/Week8/CMP105App/Level.cpp
|
317660fd3c473362b44c0761e837568103f8c2c3
|
[] |
no_license
|
StuartMorrison/CMP105_W8
|
305edc61fe863b40f46dc13e79c5fc080bd6cc07
|
bd92741d013d842571e03744954a74d97d5a777d
|
refs/heads/master
| 2021-02-15T05:29:58.152417
| 2020-03-04T12:54:31
| 2020-03-04T12:54:31
| 244,866,988
| 0
| 0
| null | 2020-03-04T10:06:08
| 2020-03-04T10:06:08
| null |
UTF-8
|
C++
| false
| false
| 2,810
|
cpp
|
Level.cpp
|
#include "Level.h"
Level::Level(sf::RenderWindow* hwnd, Input* in)
{
window = hwnd;
input = in;
// initialise game objects
/*
ball1Text.loadFromFile("gfx/Beach_Ball.png");
ball1.setTexture(&ball1Text);
ball1.setSize(sf::Vector2f(100, 100));
ball1.setPosition(100, 100);
ball2.setTexture(&ball1Text);
ball2.setSize(sf::Vector2f(100, 100));
ball2.setPosition(800, 100);
ball1.setWindu(window);
ball2.setWindu(window);
square1.setSize(sf::Vector2f(50, 50));
square1.setCollisionBox(sf::FloatRect(0, 0, 50, 50));
square1.setPosition(100, 300);
square1.setVelocity(100, 0);
square1.setFillColor(sf::Color::Green);
square2.setSize(sf::Vector2f(50, 50));
square2.setCollisionBox(sf::FloatRect(0, 0, 50, 50));
square2.setPosition(800, 300);
square2.setVelocity(-100, 0);
square2.setFillColor(sf::Color::Blue);
square1.setWindu(window);
square2.setWindu(window);
*/
leftPaddle.setSize(sf::Vector2f(50, 200));
leftPaddle.setCollisionBox(sf::FloatRect(0, 0, 50, 200));
leftPaddle.setPosition(100, 275);
leftPaddle.setFillColor(sf::Color::Red);
leftPaddle.setWindu(window);
leftPaddle.setInput(input);
rightPaddle.setSize(sf::Vector2f(50, 200));
rightPaddle.setCollisionBox(sf::FloatRect(0, 0, 50, 200));
rightPaddle.setPosition(1100, 275);
rightPaddle.setFillColor(sf::Color::Red);
rightPaddle.setWindu(window);
rightPaddle.setInput(input);
pong.setSize(sf::Vector2f(20, 20));
pong.setCollisionBox(sf::FloatRect(0, 0, 20, 20));
pong.setPosition(600, 275);
pong.setFillColor(sf::Color::White);
pong.setWindu(window);
}
Level::~Level()
{
}
// handle user input
void Level::handleInput(float dt)
{
leftPaddle.handleInput(dt);
rightPaddle.handleInput(dt);
}
// Update game objects
void Level::update(float dt)
{
/*ball1.update(dt);
ball2.update(dt);
square1.update(dt);
square2.update(dt);
if (Collision::checkBoundingCircle(&ball1, &ball2))
{
ball1.collisionResponse(NULL);
ball2.collisionResponse(NULL);
}
if (Collision::checkBoundingBox(&square1, &square2))
{
square1.collisionResponse(NULL);
square2.collisionResponse(NULL);
}*/
pong.update(dt);
if (Collision::checkBoundingBox(&leftPaddle, &pong))
{
pong.collisionResponse(NULL);
}
if (Collision::checkBoundingBox(&pong, &rightPaddle))
{
pong.collisionResponse(NULL);
}
}
// Render level
void Level::render()
{
beginDraw();
/*window->draw(ball1);
window->draw(ball2);
window->draw(square1);
window->draw(square2);*/
window->draw(leftPaddle);
window->draw(rightPaddle);
window->draw(pong);
endDraw();
}
// Begins rendering to the back buffer. Background colour set to light blue.
void Level::beginDraw()
{
window->clear(sf::Color(100, 149, 237));
}
// Ends rendering to the back buffer, and swaps buffer to the screen.
void Level::endDraw()
{
window->display();
}
|
87a223312031d9a6a3879ceab78de594df27f38b
|
8bb2296029fd8e05130f1a83168f2ab36a768c2b
|
/p10683.cpp
|
f16ff226a05baf0aeddcacb79c98a97cbf695ceb
|
[] |
no_license
|
djohn833/UVA
|
866de3773da0774be08d0635ca70b5f53daaca02
|
b5e8a633c9042c0d37e3f405ec036e40b295be59
|
refs/heads/master
| 2016-09-05T23:13:12.566349
| 2015-02-17T01:32:38
| 2015-02-17T01:32:38
| 11,392,466
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 663
|
cpp
|
p10683.cpp
|
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
string t;
int h, m, s, c;
int
digits(int i, int n)
{
return atoi(t.substr(i, n).c_str());
}
int
main()
{
long long time;
while (cin >> t) {
h = digits(0, 1);
m = digits(1, 2);
s = digits(3, 2);
c = digits(5, 2);
time = h;
time = time * 60 + m;
time = time * 60 + s;
time = time * 60 + c;
cout << "foo " << time << endl;
stringstream out;
out << (time * 10000000) / (24*60*60*100);
cout << out.str().substr(0, 7).c_str() << endl;
}
return 0;
}
|
d1632554680880853d8a6c267a7c22cd09c13469
|
d96417411dfc6536b1ecc6d56fe1fc895eeaf96d
|
/varsayilan.cpp
|
de1e9099f5210524ddaace776166515b7a16507a
|
[] |
no_license
|
kadertarlan/c_plus_plus
|
4423ea8331cc520176bfd3e7bed84277612ae378
|
4f52e3b8ae12af16c10d0cc32f70def0e992d786
|
refs/heads/master
| 2021-01-20T10:41:29.991641
| 2014-02-15T14:10:50
| 2014-02-15T14:10:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 360
|
cpp
|
varsayilan.cpp
|
#include <iostream>
using namespace std;
double kare(double uzunluk, double genislik=0){
if(!genislik) genislik=uzunluk;
return uzunluk * genislik;}
//double kare(double uzunluk){
// return uzunluk* uzunluk;}
int main(){
cout << "10* 5.8 in alanı:" ;
cout << kare(10.0,5.8) << endl;
cout << "10*10 un alanı:" ;
cout << kare(10) << endl;
}
|
d61bfd1e2ded744e4533fac239d75ebf96b94a76
|
594d4a72ec745747e8266a569144928b93258324
|
/src/particle.hpp
|
6c0e8ada1399e9074043d5ffd0e624cdc537aa09
|
[
"MIT"
] |
permissive
|
mistakia/wpaFloor
|
3f227b0fc9fa93aa4b78c40f1fae7fe4fb0c187d
|
823d97782c5b22f809e19080770535d40cc6e927
|
refs/heads/master
| 2023-04-07T14:30:22.889590
| 2023-04-01T01:44:36
| 2023-04-01T01:44:36
| 181,741,221
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 913
|
hpp
|
particle.hpp
|
//
// particle.hpp
// wpaFloor
//
// Created by mistakia on 15/04/2019.
//
#ifndef particle_hpp
#define particle_hpp
#include <stdio.h>
#pragma once
#include "ofMain.h"
#include "ofxOpenCv.h"
#include "ofxColorGradient.h"
class Particle{
public:
Particle(ofParameterGroup & particleParameters);
void setAttractPoints( vector <ofPoint> * attract );
void reset(int peerId);
void update();
void updateContours(ofxCvContourFinder & contourFinder, int offsetX, int offsetY);
void updatePeers(vector <Particle> & allPeers);
void findPeer(vector <Particle> & allPeers);
void draw(vector <Particle> & allPeers);
ofParameterGroup parameters;
ofPoint pos;
ofPoint vel;
ofPoint frc;
int id;
float drag;
float uniqueVal;
ofColor color;
float scale;
vector <ofPoint> * attractPoints;
vector <int> peerIds;
};
#endif /* particle_hpp */
|
4d58736c9143f506ea0d3846bd4e1583a8fb2b91
|
fe455903738d1699afdb68a9153361536663e7df
|
/ArduinoDriver_ASCOM_RESPONSE.ino
|
a773bc42b37bffbaf977e76cd1ea4d1dac8552e4
|
[
"MIT"
] |
permissive
|
sdrexler11791/Arduino_Ascom_Project
|
d6ff58f941e6c161b51360ed3921b9ac47c1578e
|
59c4eb6cb865a0ddbbe081ef7c81dccea3707c37
|
refs/heads/master
| 2021-09-15T20:23:32.961994
| 2018-06-10T11:11:54
| 2018-06-10T11:11:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,145
|
ino
|
ArduinoDriver_ASCOM_RESPONSE.ino
|
// Include Libraries
#include "Arduino.h"
// Pin Definitions
#define STEPPER1_PIN_STEP 3
#define STEPPER1_PIN_DIR 2
#define STEPPER2_PIN_STEP 5
#define STEPPER2_PIN_DIR 4
// Fixed track rate
// 1 sidereal day = 86'164'000 ms
// 1 day = 1 big wheel turn = 144 small screw turns (in RA)
// 1 screw turn = 598'361 ms
// 1 screw turn = 1 motor turn = 200 steps * 8 (microstepping)
// 1 motor step = 374 ms
int stepDelay = 374; // delay in ms for one step
int dur; // duration
boolean isPulseGuiding = false;
// Setup the essentials for your circuit to work. It runs first every time your circuit is powered with electricity.
void setup()
{
// assign pin modes
pinMode(STEPPER1_PIN_DIR, OUTPUT);
pinMode(STEPPER1_PIN_STEP, OUTPUT);
pinMode(STEPPER2_PIN_DIR, OUTPUT);
pinMode(STEPPER2_PIN_STEP, OUTPUT);
// no power to pins
digitalWrite(STEPPER1_PIN_STEP, LOW);
digitalWrite(STEPPER2_PIN_STEP, LOW);
// initialize serial connection:
Serial.begin(57600);
Serial.flush();
// wait for serial port to connect. Needed for native USB
while (!Serial) ;
Serial.println("Connection successful.");
}
void loop()
{
/* SerialEvent occurs whenever a new data comes in the hardware serial RX. The pulses are put out in the form of <direction#duration[in ms]#>. ( ex: "E#400#" ) */
if(Serial.available()>0)
{
String driver_cmd;
driver_cmd = Serial.readStringUntil('#');
if(driver_cmd == "I") // Pulseguiding info
{
if(isPulseGuiding)
{
Serial.println("TRUE#");
}
else
{
Serial.println("FALSE#");
}
}
// move motor 1 step north
if(driver_cmd == "N") {
driver_cmd = "";
driver_cmd = Serial.readStringUntil('#');
dur = driver_cmd.toInt();
Move(0, dur);
isPulseGuiding = true;
}
// move motor 1 step south
if(driver_cmd == "S") {
driver_cmd = "";
driver_cmd = Serial.readStringUntil('#');
dur = driver_cmd.toInt();
Move(1, dur);
isPulseGuiding = true;
}
// move motor 1 step west
if(driver_cmd == "W") {
driver_cmd = "";
driver_cmd = Serial.readStringUntil('#');
dur = driver_cmd.toInt();
Move(2, dur);
isPulseGuiding = true;
}
// move motor 1 step east
if(driver_cmd == "E") {
driver_cmd = "";
driver_cmd = Serial.readStringUntil('#');
dur = driver_cmd.toInt();
Move(3, dur);
isPulseGuiding = true;
}
// stop motors
if(driver_cmd == "H") {
driver_cmd = "";
Move(4, 0);
isPulseGuiding = false;
}
}
}
void Move(int dir, int duration)
{
if(duration < 374) // for test to get at least one step for each pulse, delete this for actual tracking
{
duration = 374;
}
int steps = duration/stepDelay;
if(dir == 0) // North
{
digitalWrite(STEPPER1_PIN_DIR, LOW);
for ( int i=0; i<(steps); i++)
{
digitalWrite(STEPPER1_PIN_STEP, HIGH);
delay(stepDelay);
digitalWrite(STEPPER1_PIN_STEP, LOW);
}
}
else if(dir == 1) // South
{
digitalWrite(STEPPER1_PIN_DIR, HIGH);
for ( int i=0; i<(steps); i++)
{
digitalWrite(STEPPER1_PIN_STEP, HIGH);
delay(stepDelay);
digitalWrite(STEPPER1_PIN_STEP, LOW);
}
}
else if(dir == 2) // West
{
digitalWrite(STEPPER2_PIN_DIR, LOW);
for ( int i=0; i<steps; i++)
{
digitalWrite(STEPPER2_PIN_STEP, HIGH);
delay(stepDelay);
digitalWrite(STEPPER2_PIN_STEP, LOW);
}
}
else if(dir == 3) // East
{
digitalWrite(STEPPER2_PIN_DIR, LOW);
for ( int i=0; i<steps; i++)
{
digitalWrite(STEPPER2_PIN_STEP, HIGH);
delay(stepDelay);
digitalWrite(STEPPER2_PIN_STEP, LOW);
}
}
else if(dir == 4) // STOP
{
digitalWrite(STEPPER1_PIN_STEP, LOW);
digitalWrite(STEPPER2_PIN_STEP, LOW);
}
}
|
c1741902835c2d7273dee75ff70fd85d21184cc3
|
9bb4a516a6571abf76a3ea313c20186f6107dfa1
|
/main.cpp
|
ad02c58df5e3c811ef52039f38b4521187d590a2
|
[] |
no_license
|
aawee0/openCV_img_reg
|
da59a2ff2d6b30f268d2eda7c3a7abc659e08b0b
|
9c75ac48cd1ad257a5ab6b20680b8354c9e9d440
|
refs/heads/master
| 2020-04-05T17:40:52.004018
| 2015-09-23T04:50:18
| 2015-09-23T04:50:18
| 42,975,465
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 30,033
|
cpp
|
main.cpp
|
#include <opencv\cv.h>
#include <opencv\highgui.h>
#include <vector>
#include <dlib/optimization.h>
#include <math.h>
#define OPT 1
#define SMP 0
#define THRESH 160
#define THR1 0.5
using namespace cv;
using namespace std;
using namespace dlib;
typedef matrix<double,0,1> column_vector;
IplImage* imgSrc;
IplImage* imgTrg;
IplImage* imgWpd;
IplImage* imgSrcCp;
IplImage* imgTrgCp;
IplImage* imgWpdCp;
int counter;
int *pts;
int num_pts;
class warp
{
public:
warp(int cps);
~warp(void);
std::vector<double> Eval(double u, double v);
void warpImg(IplImage* img1, IplImage* imgRes);
double warpedSSD(IplImage* img1, IplImage* imgRes, double x, double y, int r);
double warpedSSDfull(IplImage* img1, IplImage* imgRes);
void simpOpt(IplImage* imgS, IplImage* imgT, int rad);
int simpOptSg(IplImage* imgS, IplImage* imgT, int rad);
void drawCpt(IplImage* img1);
int m;
int n;
double *cps_x;
double *cps_y;
double *dsp_x;
double *dsp_y;
double *localSSD;
bool *checked;
};
warp *wp;
warp::warp(int cps)
{
/*
string warp_func0 = "warping function9.wrf"; // WARP ZERO
FILE *fp0 = fopen(warp_func0.c_str(), "r");
char buffer0[100];
fscanf(fp0, "%s", buffer0);
fscanf(fp0, "%d%d", &m, &n); */
// 11 , 20
n=cps;
m=cps;
double betw = 1 / ((double) cps-2.0);
//printf(" %d ", betw);
cps_x = NULL;
if( cps_x )
free( cps_x );
cps_x = (double *)malloc((n+1)*(m+1)*sizeof(double));
memset(cps_x,0,sizeof(cps_x));
cps_y = NULL;
if( cps_y )
free( cps_y );
cps_y = (double *)malloc((n+1)*(m+1)*sizeof(double));
memset(cps_y,0,sizeof(cps_y));
dsp_x = NULL;
if( dsp_x )
free( dsp_x );
dsp_x = (double *)malloc((n+1)*(m+1)*sizeof(double));
memset(dsp_x,0,sizeof(dsp_x));
dsp_y = NULL;
if (dsp_y)
free(dsp_y);
dsp_y = (double *)malloc((n + 1)*(m + 1)*sizeof(double));
memset(dsp_y, 0, sizeof(dsp_y));
localSSD = NULL;
if (localSSD)
free(localSSD);
localSSD = (double *)malloc((n + 1)*(m + 1)*sizeof(double));
memset(localSSD, 0, sizeof(localSSD));
checked = NULL;
if (checked)
free(checked);
checked = (bool *)malloc((n + 1)*(m + 1)*sizeof(bool));
memset(checked, 0, sizeof(checked));
double inc_x = -betw;
for (int i=0; i<=n; i++) {
double inc_y = -betw; //-0.111;
for (int j=0; j<=m; j++) {
//double x,y;
//fscanf(fp0, "%lf%lf", &x, &y);
//cps_x[i*(m+1) + j]=x;
//cps_y[i*(m+1) + j]=y;
cps_x[i*(m+1) + j]=inc_x;
cps_y[i*(m+1) + j]=inc_y;
dsp_x[i*(m+1) + j]=0.0;
dsp_y[i*(m + 1) + j]=0.0;
localSSD[i*(m + 1) + j] = -1.0;
checked[i*(m + 1) + j] = false;
inc_y+=betw; //0.111;
}
inc_x+=betw; //0.111;
}
//fclose(fp0);
/*
for (int i=0; i<=n; i++) {
for (int j=0; j<=m; j++) {
printf(" %f %f \n", cps_x[i*(m+1) + j], cps_y[i*(m+1) + j]);
}
}
*/
}
warp::~warp(void)
{
delete[] cps_x;
delete[] cps_y;
}
void warp::warpImg(IplImage* img1, IplImage* imgRes) {
int width = img1->width;
int height = img1->height;
int step = img1->widthStep;
//printf (" { %d %d }", width, step);
// making the image black
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
CvScalar s;
s.val[0]=0.0;
s.val[1]=255.0;
s.val[2]=0.0;
cvSet2D(imgRes,i,j,s);
/*
imgRes->imageData[3*(i*width + j)]=0;
imgRes->imageData[3*(i*width + j)+1]=(char) 255;
imgRes->imageData[3*(i*width + j)+2]=0;*/
}
}
// warping img1 onto imgRes
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
double y = i/((double) height);
double x = j/((double) width);
std::vector<double> pt(2);
pt=Eval(x, y);
double x1=pt[0];
double y1=pt[1];
if (x <= 0.0) x1 = 0.0;
if (x >= 1.0) x1 = 1.0;
if (y <= 0.0) y1 = 0.0;
if (y >= 1.0) y1 = 1.0;
int y_pix = (int) (y1*height);
int x_pix = (int) (x1*width);
if (x1 < 0.0) x_pix = 0;
if (x1 > 1.0) {
//if (x<0.8)printf(" { %f %d %d } " , x, i,j);
x_pix = width-1;
}
if (y1 < 0.0) y_pix = 0;
if (y1 > 1.0) y_pix = height-1;
//if (j-x_pix>100 || j-x_pix<-100) printf(" ( %f %f ) ", x, pt[0]);
//if (j<10) printf(" %d ", x_pix);
imgRes->imageData[3*(y_pix*width + x_pix)]=img1->imageData[3*(i*width + j)];
imgRes->imageData[3*(y_pix*width + x_pix)+1]=img1->imageData[3*(i*width + j)+1];
imgRes->imageData[3*(y_pix*width + x_pix)+2]=img1->imageData[3*(i*width + j)+2];
//if ((int) imgRes->imageData[3*(y_pix*width + x_pix)]<0) printf(" %d ", (int) imgRes->imageData[3*(y_pix*width + x_pix)]);
}
}
// interpolate
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
CvScalar curpix = cvGet2D( imgRes, i, j);
//if (i==180 && j==305) printf(" [ %f %f %f ] ", curpix.val[0], curpix.val[1], curpix.val[2]);
if (curpix.val[0]==0 && curpix.val[1]==255.0 && curpix.val[2]==0) {
// if the pixel is empty - do the interpolation
CvScalar icol;
icol.val[0]=0.0;
icol.val[1]=0.0;
icol.val[2]=0.0;
int cnt = 0; // number of nonzero neighbouring pixels
int inc = 1; // sort of radius
//printf (" %d %d ", i, j);
while (cnt==0) {
for (int n=i-1-inc; n<=i+1+inc; n++) {
if (n<height && n>=0) {
for (int m=j-1-inc; m<=j+1+inc; m++) {
if (m<width && m>=0) {
//
CvScalar pixel = cvGet2D( imgRes, n, m);
if (!(pixel.val[0]==0 && pixel.val[1]==255 && pixel.val[2]==0)) {
icol.val[0]+=pixel.val[0];
icol.val[1]+=pixel.val[1];
icol.val[2]+=pixel.val[2];
cnt++;
}
//
}
}
}
}
inc++;
}
icol.val[0]/=cnt;
icol.val[1]/=cnt;
icol.val[2]/=cnt;
cvSet2D(imgRes,i,j,icol);
//if (red>=230 || blue>=230 || green>=230) printf(" ( %d %d ) ", i, j);
}
}
}
}
double warp::warpedSSD(IplImage* img1, IplImage* imgRes, double x, double y, int r) {
int width = img1->width;
int height = img1->height;
int step = img1->widthStep;
//printf (" { %d %d }", width, step);
int pix_x = (int) (x * width);
int pix_y = (int) (y * height);
double ssd_sum = 0.0;
/*
for (int j=pix_x-r; j<pix_x+r; j++) {
if (j>=0 && j<width) {
for (int i=pix_y+r; i<pix_y+r; i++) { // i<=j
if (i>=0 && i<height) {
CvScalar s;
s.val[0]=0.0;
s.val[1]=255.0;
s.val[2]=0.0;
cvSet2D(imgRes,i,j,s);
}
}
}
}
*/
double cnter = 0.0;
// warping img1 onto imgRes
for (int i=0; i<height; i++) {
for (int j = 0; j < width; j++) {
if (j<(pix_x + 4 * r) && j>(pix_x - 4 * r) && i<(pix_y + 4 * r) && i>(pix_y - 4 * r)) {
double y0 = i / ((double)height);
double x0 = j / ((double)width);
std::vector<double> pt(2);
pt = Eval(x0, y0);
double x1 = pt[0];
double y1 = pt[1];
if (x0 <= 0.0) x1 = 0.0;
if (x0 >= 1.0) x1 = 1.0;
if (y0 <= 0.0) y1 = 0.0;
if (y0 >= 1.0) y1 = 1.0;
int y_pix = (int)(y1*height);
int x_pix = (int)(x1*width);
if (x1 < 0.0) x_pix = 0;
if (x1 > 1.0) {
//if (x<0.8)printf(" { %f %d %d } " , x, i,j);
x_pix = width - 1;
}
if (y1 < 0.0) y_pix = 0;
if (y1 > 1.0) y_pix = height - 1;
//if (j-x_pix>100 || j-x_pix<-100) printf(" ( %f %f ) ", x, pt[0]);
//if (j<10) printf(" %d ", x_pix);
if (x_pix<(pix_x + 2 * r) && x_pix>(pix_x - 2 * r) && y_pix<(pix_y + 2 * r) && y_pix>(pix_y - 2 * r)) {
double diff = img1->imageData[3 * (i*width + j)] - imgRes->imageData[3 * (y_pix*width + x_pix)];
ssd_sum += diff*diff;
cnter++;
//printf(" %d %d %d %d \n", x_pix, pix_x, y_pix, pix_y);
}
}
//if ((int) imgRes->imageData[3*(y_pix*width + x_pix)]<0) printf(" %d ", (int) imgRes->imageData[3*(y_pix*width + x_pix)]);
}
}
ssd_sum /= cnter;
/*
for (int j=pix_x-r; j<pix_x+r; j++) {
if (j>=0 && j<width) {
for (int i=pix_y+r; i<pix_y+r; i++) { // i<=j
if (i>=0 && i<height) {
CvScalar pixS=cvGet2D( imgRes, i, j);
CvScalar pixT=cvGet2D( imgTrg, i, j);
double diff0 = (pixS.val[0] - pixT.val[0]);
double diff1 = (pixS.val[1] - pixT.val[1]);
double diff2 = (pixS.val[2] - pixT.val[2]);
if (!(pixS.val[0]==0.0 && pixS.val[1]==255.0 && pixS.val[2]==0.0)) ssd_sum += ( diff0*diff0 + diff1*diff1 + diff2*diff2 ) / 9.0;
}
}
}
}*/
return ssd_sum;
}
double warp::warpedSSDfull(IplImage* img1, IplImage* imgRes) {
int width = img1->width;
int height = img1->height;
int step = img1->widthStep;
//printf (" { %d %d }", width, step);
double ssd_sum = 0.0;
double cnter = 0.0;
// warping img1 onto imgRes
for (int i = 0; i<height; i++) {
for (int j = 0; j < width; j++) {
double y0 = i / ((double)height);
double x0 = j / ((double)width);
std::vector<double> pt(2);
pt = Eval(x0, y0);
double x1 = pt[0];
double y1 = pt[1];
if (x0 <= 0.0) x1 = 0.0;
if (x0 >= 1.0) x1 = 1.0;
if (y0 <= 0.0) y1 = 0.0;
if (y0 >= 1.0) y1 = 1.0;
int y_pix = (int)(y1*height);
int x_pix = (int)(x1*width);
if (x1 < 0.0) x_pix = 0;
if (x1 > 1.0) {
//if (x<0.8)printf(" { %f %d %d } " , x, i,j);
x_pix = width - 1;
}
if (y1 < 0.0) y_pix = 0;
if (y1 > 1.0) y_pix = height - 1;
//if (j-x_pix>100 || j-x_pix<-100) printf(" ( %f %f ) ", x, pt[0]);
//if (j<10) printf(" %d ", x_pix);
if ( x_pix<width && x_pix>=0 && y_pix<height && y_pix>=0 ) {
double diff = img1->imageData[3 * (i*width + j)] - imgRes->imageData[3 * (y_pix*width + x_pix)];
ssd_sum += diff*diff;
cnter++;
//printf(" %d %d %d %d \n", x_pix, pix_x, y_pix, pix_y);
}
}
}
ssd_sum /= cnter;
return ssd_sum;
}
void get_ucbs_basis(double t, double *basis)
{
double tt = t * t;
double ttt = tt * t;
basis[0] = (1.0 - 3 * t + 3 * tt - ttt) / 6.0;
basis[1] = (3 * ttt - 6 * tt + 4) / 6.0;
basis[2] = (-3 * ttt + 3 * tt + 3 * t + 1) / 6.0;
basis[3] = ttt / 6.0;
}
double ssd(IplImage* imgS, IplImage* imgT) {
int width = imgS->width;
int height = imgS->height;
double ssd_sum = 0.0;
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
CvScalar pixS = cvGet2D( imgS, i, j);
CvScalar pixT = cvGet2D( imgT, i, j);
double diff0 = (pixS.val[0] - pixT.val[0]);
double diff1 = (pixS.val[1] - pixT.val[1]);
double diff2 = (pixS.val[2] - pixT.val[2]);
ssd_sum += ( diff0*diff0 + diff1*diff1 + diff2*diff2 ) / 9.0;
}
}
return ssd_sum;
}
double ssd_dir(IplImage* imgS, IplImage* imgT, double x, double y, int r, int dir) {
int width = imgS->width;
int height = imgS->height;
int pix_x = (int) (x * width);
int pix_y = (int) (y * height);
double ssd_sum = 0.0;
for (int j=0; j<r; j++) {
for (int i=0; i<r; i++) { // i<=j
CvScalar pixS;
CvScalar pixT;
if (dir==1) { // to the right
pixS = cvGet2D( imgS, pix_y+i, pix_x+j);
pixT = cvGet2D( imgT, pix_y+i, pix_x+j);
}
else if (dir==2) { // to the left
pixS = cvGet2D( imgS, pix_y+i, pix_x-j);
pixT = cvGet2D( imgT, pix_y+i, pix_x-j);
}
else if (dir==3) { // upwards
pixS = cvGet2D( imgS, pix_y+j, pix_x+i);
pixT = cvGet2D( imgT, pix_y+j, pix_x+i);
}
else if (dir==4) { // downwards
pixS = cvGet2D( imgS, pix_y-j, pix_x+i);
pixT = cvGet2D( imgT, pix_y-j, pix_x+i);
}
double diff0 = (pixS.val[0] - pixT.val[0]);
double diff1 = (pixS.val[1] - pixT.val[1]);
double diff2 = (pixS.val[2] - pixT.val[2]);
ssd_sum += ( diff0*diff0 + diff1*diff1 + diff2*diff2 ) / 9.0;
if (i!=0) {
if (dir==1) { // to the right
pixS = cvGet2D( imgS, pix_y-i, pix_x+j);
pixT = cvGet2D( imgT, pix_y-i, pix_x+j);
}
else if (dir==2) { // to the left
pixS = cvGet2D( imgS, pix_y-i, pix_x-j);
pixT = cvGet2D( imgT, pix_y-i, pix_x-j);
}
else if (dir==3) { // upwards
pixS = cvGet2D( imgS, pix_y+j, pix_x-i);
pixT = cvGet2D( imgT, pix_y+j, pix_x-i);
}
else if (dir==4) { // downwards
pixS = cvGet2D( imgS, pix_y-j, pix_x-i);
pixT = cvGet2D( imgT, pix_y-j, pix_x-i);
}
diff0 = (pixS.val[0] - pixT.val[0]);
diff1 = (pixS.val[1] - pixT.val[1]);
diff2 = (pixS.val[2] - pixT.val[2]);
ssd_sum += ( diff0*diff0 + diff1*diff1 + diff2*diff2 ) / 9.0;
}
}
}
return ssd_sum;
}
double ssd_nb(double x, double y, int r) {
int width = imgWpd->width;
int height = imgWpd->height;
int pix_x = (int) (x * width);
int pix_y = (int) (y * height);
double ssd_sum = 0.0;
for (int j=pix_x-r; j<pix_x+r; j++) {
if (j>=0 && j<width) {
for (int i=pix_y+r; i<pix_y+r; i++) { // i<=j
if (i>=0 && i<height) {
CvScalar pixS=cvGet2D( imgWpd, i, j);
CvScalar pixT=cvGet2D( imgTrg, i, j);
double diff0 = (pixS.val[0] - pixT.val[0]);
double diff1 = (pixS.val[1] - pixT.val[1]);
double diff2 = (pixS.val[2] - pixT.val[2]);
ssd_sum += ( diff0*diff0 + diff1*diff1 + diff2*diff2 ) / 9.0;
}
}
}
}
return ssd_sum;
}
void warp::simpOpt(IplImage* imgS, IplImage* imgT, int rad) {
int width = imgS->width;
int height = imgS->height;
double nb_x = rad/((double) width);
double nb_y = rad/((double) height);
for (int i=0; i<=n; i++) {
for (int j=0; j<=m; j++) {
double x = cps_x[i*(m+1) + j];
double y = cps_y[i*(m+1) + j];
if ((x+nb_x)<1.0 && (x-nb_x)>=0 && (y+nb_y)<1.0 && (y-nb_y)>=0) {
double delta1_x = ssd_dir(imgS, imgT, x, y, rad, 1);
double delta2_x = ssd_dir(imgS, imgT, x, y, rad, 2);
double delta1_y = ssd_dir(imgS, imgT, x, y, rad, 3);
double delta2_y = ssd_dir(imgS, imgT, x, y, rad, 4);
double max = ( 255.0 * 255.0 * 4.0 * rad * rad ) / 6.0;
double delta_x = 0;
if ((delta1_x + delta2_x)!=0 && SMP==1) delta_x = (delta1_x - delta2_x)/(delta1_x + delta2_x);
else delta_x = (delta1_x - delta2_x)/max;
double delta_y = 0;
if ((delta1_y + delta2_y)!=0 && SMP==1) delta_y = (delta1_y - delta2_y)/(delta1_y + delta2_y);
else delta_y = (delta1_y - delta2_y)/max;
dsp_x[i*(m+1) + j] = nb_x*delta_x;
//printf("\n%d %d x SSD: %f %f \n ", i, j, nb_x, delta_x);
dsp_y[i*(m+1) + j] = nb_y*delta_y;
//printf("\n%d %d y SSD: %f %f \n", i, j, nb_y, delta_y);
if ((i*(m+1) + j)==50 || (i*(m+1) + j)==100 ) {
printf(" %f %f %f %f \n", delta1_x, delta2_x, delta1_y, delta2_y);
}
//i=n;
//j=m;
}
// endif
}
}
// smoothness filter
for (int i=0; i<=n; i++) {
for (int j=0; j<=m; j++) {
double avg_x = 0.0;
double avg_y = 0.0;
int cnt = 0;
int nb = 1;
// average value
for (int p=i-nb; p<=i+nb; p++) {
for (int q=j-nb; q<=j+nb; q++) {
if (!(p==0 && q==0) && (p>0) && (q>0) && (p<n) && (q<m)) {
avg_x += dsp_x[p*(m+1) + q];
avg_y += dsp_y[p*(m+1) + q];
cnt++;
}
}
}
if (cnt!=0) {
avg_x/= ((double) cnt);
avg_y/= ((double) cnt);
}
if (abs(dsp_x[i*(m+1) + j]) > 0.005 && SMP==0) cps_x[i*(m+1) + j] += (2*dsp_x[i*(m+1) + j]);
else cps_x[i*(m+1) + j] += (dsp_x[i*(m+1) + j] + avg_x)/2.0;
if (abs(dsp_y[i*(m+1) + j]) > 0.005 && SMP==0) cps_y[i*(m+1) + j] += (2*dsp_y[i*(m+1) + j]);
else cps_y[i*(m+1) + j] += (dsp_y[i*(m+1) + j] + avg_y)/2.0;
//cps_x[i*(m+1) + j] += dsp_x[i*(m+1) + j];
//cps_y[i*(m+1) + j] += dsp_y[i*(m+1) + j];
}
}
}
int warp::simpOptSg(IplImage* imgS, IplImage* imgT, int rad) {
int width = imgS->width;
int height = imgS->height;
double nb_x = rad/((double) width);
double nb_y = rad/((double) height);
double max_dsp = 0;
int max_cp;
for (int i=0; i<=n; i++) {
for (int j=0; j<=m; j++) {
double x = cps_x[i*(m+1) + j];
double y = cps_y[i*(m+1) + j];
if ((x + nb_x)<1.0 && (x - nb_x) >= 0 && (y + nb_y)<1.0 && (y - nb_y) >= 0 && (x > 0.01) && (x < 0.99) && (y > 0.01) && (y < 0.99)) {
double delta1_x = ssd_dir(imgS, imgT, x, y, rad, 1);
double delta2_x = ssd_dir(imgS, imgT, x, y, rad, 2);
double delta1_y = ssd_dir(imgS, imgT, x, y, rad, 3);
double delta2_y = ssd_dir(imgS, imgT, x, y, rad, 4);
double max = ( 255.0 * 255.0 * 4.0 * rad * rad ) / 6.0;
double delta_x = 0;
if ((delta1_x + delta2_x)!=0 && SMP==1) delta_x = (delta1_x - delta2_x)/(delta1_x + delta2_x);
else delta_x = (delta1_x - delta2_x)/max;
double delta_y = 0;
if ((delta1_y + delta2_y)!=0 && SMP==1) delta_y = (delta1_y - delta2_y)/(delta1_y + delta2_y);
else delta_y = (delta1_y - delta2_y)/max;
dsp_x[i*(m+1) + j] = nb_x*delta_x;
//printf("\n%d %d x SSD: %f %f \n ", i, j, nb_x, delta_x);
dsp_y[i*(m+1) + j] = nb_y*delta_y;
//printf("\n%d %d y SSD: %f %f \n", i, j, nb_y, delta_y);
if ((dsp_x[i*(m + 1) + j] + dsp_y[i*(m + 1) + j]) > max_dsp && !checked[i*(m + 1) + j] ) {
max_dsp = (dsp_x[i*(m+1) + j] + dsp_y[i*(m+1) + j]);
max_cp = i*(m + 1) + j;
}
if ((i*(m+1) + j)==50 || (i*(m+1) + j)==100 ) {
//printf(" %f %f %f %f \n", delta1_x, delta2_x, delta1_y, delta2_y);
}
//i=n;
//j=m;
}
// endif
}
}
for (int i=0; i< (m+1)*(n+1); i++) {
if ( (dsp_x[i] + dsp_y[i]) > THR1 * max_dsp) {
printf(" !! %d !! ", i);
cps_x[i] += dsp_x[i];
cps_y[i] += dsp_y[i];
}
}
/*
// smoothness filter
for (int i=0; i<=n; i++) {
for (int j=0; j<=m; j++) {
double avg_x = 0.0;
double avg_y = 0.0;
int cnt = 0;
int nb = 1;
// average value
for (int p=i-nb; p<=i+nb; p++) {
for (int q=j-nb; q<=j+nb; q++) {
if (!(p==0 && q==0) && (p>0) && (q>0) && (p<n) && (q<m)) {
avg_x += dsp_x[p*(m+1) + q];
avg_y += dsp_y[p*(m+1) + q];
cnt++;
}
}
}
if (cnt!=0) {
avg_x/= ((double) cnt);
avg_y/= ((double) cnt);
}
if (abs(dsp_x[i*(m+1) + j]) > 0.005 && SMP==0) cps_x[i*(m+1) + j] += (2*dsp_x[i*(m+1) + j]);
else cps_x[i*(m+1) + j] += (dsp_x[i*(m+1) + j] + avg_x)/2.0;
if (abs(dsp_y[i*(m+1) + j]) > 0.005 && SMP==0) cps_y[i*(m+1) + j] += (2*dsp_y[i*(m+1) + j]);
else cps_y[i*(m+1) + j] += (dsp_y[i*(m+1) + j] + avg_y)/2.0;
//cps_x[i*(m+1) + j] += dsp_x[i*(m+1) + j];
//cps_y[i*(m+1) + j] += dsp_y[i*(m+1) + j];
}
}
*/
return max_cp;
}
void warp::drawCpt(IplImage* img1){
int width = img1->width;
int height = img1->height;
for (int i=0; i<=n; i++) {
for (int j=0; j<=m; j++) {
int x = (int) (width * cps_x[i*(m+1) + j]);
int y = (int)(height * cps_y[i*(m + 1) + j]);
CvScalar pix;
pix.val[0]=0;
pix.val[1]=0;
pix.val[2]=255;
bool isIn = false;
for (int k = 0; k < num_pts; k++) {
if (pts[k] == (i*(m + 1) + j)) isIn = true;
}
if (isIn) {
pix.val[1] = 255;
pix.val[2] = 0;
}
//if (i==2 && j==5) {
/*
if ((i*(m + 1) + j) == 50 || (i*(m + 1) + j) == 38) {
//printf(" { %f %f } ", cps_x[i*(m+1) + j], cps_y[i*(m+1) + j]);
pix.val[1]=255;
}
*/
if (x>=0 && y>=0 && x<width && y<height) cvSet2D(img1,y,x,pix);
}
}
/*
CvScalar pix;
pix.val[0] = 0;
pix.val[1] = 255;
pix.val[2] = 0;
cvSet2D(img1, 0, 0, pix);
*/
}
std::vector<double> warp::Eval(double u, double v)
{
/* double v;
va_list ap;
va_start(ap, u);
v = va_arg(ap, double);
va_end(ap); */
// get local parameter values for u and v
double uu = u * (m - 2);
double vv = v * (n - 2);
int k = (int)uu;
int l = (int)vv; // P(k,l) is the left bottum control points.
uu = uu - k;
vv = vv - l; // get the local parameter of u and v.
if (k == m - 2) // special case for u is 1.0.
{
k = m - 3;
uu = 1.0;
}
if (l == n - 2) // special case for v is 1.0.
{
l = n - 3;
vv = 1.0;
}
static double basis_u[4], basis_v[4];
get_ucbs_basis(uu, basis_u);
get_ucbs_basis(vv, basis_v);
std::vector<double> pt(2);
pt[0]=0;
pt[1]=0;
for (int i = 0; i < 4; ++i)
{
int idx = (k + i) * (n + 1) + l;
pt[0] += basis_u[i] * (cps_x[idx] * basis_v[0] + cps_x[idx + 1] * basis_v[1] + cps_x[idx + 2] * basis_v[2] + cps_x[idx + 3] * basis_v[3]);
pt[1] += basis_u[i] * (cps_y[idx] * basis_v[0] + cps_y[idx + 1] * basis_v[1] + cps_y[idx + 2] * basis_v[2] + cps_y[idx + 3] * basis_v[3]);
}
return pt;
}
class test_function
{
public:
test_function ()
{
}
double operator() ( const column_vector& arg) const
{
counter++;
printf("%d ", counter);
//warp *wp = new warp(11);
double midX = 0;
double midY = 0;
double midDspX = 0;
double midDspY = 0;
for (int i = 0; i<num_pts; i++) {
wp->cps_x[pts[i]] = arg(2 * i);
wp->cps_y[pts[i]] = arg(2 * i + 1);
midX += arg(2 * i);
midY += arg(2 * i + 1);
midDspX += wp->cps_x[pts[i]] - wp->dsp_x[pts[i]];
midDspY += wp->cps_y[pts[i]] - wp->dsp_y[pts[i]];
printf(" %d %f %f \n", pts[i], wp->cps_x[pts[i]], wp->cps_y[pts[i]]);
}
midX /= (double)num_pts;
midY /= (double)num_pts;
midDspX /= (double)num_pts;
midDspY /= (double)num_pts;
//wp->warpImg(imgSrc, imgWpd);
double diff = wp->warpedSSD(imgSrcCp, imgTrgCp, midX, midY, ((int)(0.22*imgSrc->width)));
/*
for (int i=0; i<num_pts; i++) {
diff+=wp->warpedSSD(imgSrcCp, imgWpdCp, wp->cps_x[pts[i]], wp->cps_y[pts[i]], ((int) (0.06*imgSrcCp->width)));
printf(" %f %f %f \n", wp->cps_x[pts[i]], wp->cps_y[pts[i]], diff);
//cvCopy(imgSrc, imgWpd);
}
*/
double smoo = 0;
double diffX = 0;
double diffY = 0;
for (int i = 0; i<num_pts; i++) {
diffX = midDspX - (wp->cps_x[pts[i]] - wp->dsp_x[pts[i]]);
diffY = midDspY - (wp->cps_y[pts[i]] - wp->dsp_y[pts[i]]);
smoo += sqrt(diffX*diffX + diffY*diffY);
}
printf(" %f %f \n \n", diff, smoo);
/*
wp->warpImg(imgSrcCp, imgWpdCp);
wp->drawCpt(imgWpdCp);
cvShowImage("Source", imgWpdCp);
cvWaitKey(0);
int a;
*/
//scanf(" %d ", &a);
return diff+300*smoo;
}
};
int main () {
counter=0;
/*
warp *wp = new warp(11);
wp->cps_x[50]-=0.05;
wp->cps_y[50]+=0.05;
*/
if (SMP==1) {
imgSrc = cvLoadImage( "src2.jpg" );
imgTrg = cvLoadImage( "trg2.jpg" );
}
else {
imgSrc = cvLoadImage( "src.jpg" );
imgTrg = cvLoadImage( "trg.jpg" );
}
int width = imgSrc->width;
int height = imgSrc->height;
/*
cvNamedWindow( "1", CV_WINDOW_NORMAL );
cvShowImage("1", imgSrc);
cvNamedWindow( "2", CV_WINDOW_NORMAL );
cvShowImage("2", imgTrg);
*/
imgWpd = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
//wp->drawCpt(imgWpd); // draw control points
// stroka, stolbec:
// cvSet2D(imgWpd,50,1,col);
//wp->warpImg(imgSrc, imgWpd);
cvCopy(imgSrc, imgWpd);
cvNamedWindow( "Source", CV_WINDOW_NORMAL );
cvResizeWindow("Source", width, height);
cvShowImage("Source", imgWpd);
// smallen
imgSrcCp = cvCreateImage(cvSize(width / 5, height / 5), IPL_DEPTH_8U, 3);
imgWpdCp = cvCreateImage(cvSize(width / 5, height / 5), IPL_DEPTH_8U, 3);
imgTrgCp = cvCreateImage(cvSize(width / 5, height / 5), IPL_DEPTH_8U, 3);
/*
imgSrcCp = cvCreateImage(cvSize(width , height ), IPL_DEPTH_8U, 3);
imgWpdCp = cvCreateImage(cvSize(width , height ), IPL_DEPTH_8U, 3);
imgTrgCp = cvCreateImage(cvSize(width , height ), IPL_DEPTH_8U, 3);
*/
cvResize(imgSrc, imgSrcCp);
cvCopy(imgSrcCp, imgWpdCp);
cvResize(imgTrg, imgTrgCp);
cvNamedWindow("Trg", CV_WINDOW_NORMAL);
cvResizeWindow("Trg", width, height);
cvShowImage("Trg", imgTrgCp);
width /= 5;
height /= 5;
if (OPT==1) {
int cps = 11;
int rad = 0.06*width;
//int num_pts = (cps + 1) * (cps + 1);
wp = new warp(cps);
bool inclNb = true; // include or not to include the neighbours
double globalSSD = wp->warpedSSDfull(imgSrcCp, imgTrgCp); // ssd(imgSrcCp, imgTrgCp);
printf("\n SSD: %f \n", globalSSD);
test_function Func;
for (int num = 0; num < 1; num++) {
double tregion = 0.05;
int cnt_stop = 0;
if (num == 1) {
width *= 5;
height *= 5;
rad *= 5;
imgSrcCp = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
imgWpdCp = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
imgTrgCp = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
cvCopy(imgSrc, imgSrcCp);
cvCopy(imgSrc, imgWpdCp);
cvCopy(imgTrg, imgTrgCp);
}
while (cnt_stop<3) {
int max_cp = wp->simpOptSg(imgWpdCp, imgTrgCp, rad);
double max_dsp = (wp->dsp_x[max_cp] + wp->dsp_y[max_cp]);
/*
for (int i = 0; i< (wp->m + 1)*(wp->n + 1); i++) {
if ((wp->dsp_x[i] + wp->dsp_y[i]) > THR1 * max_dsp) num_pts++;
}
*/
if (!inclNb) {
num_pts = 1; // just one point
max_cp = 88;
}
else {
num_pts = 0; // point with neighbourhood
double diff_lim = 0.12 * 0.12;
for (int i = 0; i < (wp->m + 1)*(wp->n + 1); i++) {
double diffx = (wp->cps_x[i] - wp->cps_x[max_cp]);
double diffy = (wp->cps_y[i] - wp->cps_y[max_cp]);
double diff = diffx*diffx + diffy*diffy;
if (diff < diff_lim) num_pts++;
}
}
column_vector starting_point(2 * num_pts); // vector for BOBYQA
column_vector low_point(2 * num_pts);
column_vector hgh_point(2 * num_pts);
pts = NULL; // indexes of points
if (pts) free(pts);
pts = (int *)malloc(num_pts*sizeof(int));
memset(pts, 0, sizeof(pts));
// filling
num_pts = 0;
if (!inclNb) { // just one point
pts[num_pts] = max_cp;
starting_point(2 * num_pts) = wp->cps_x[max_cp];
low_point(2 * num_pts) = wp->cps_x[max_cp] - 0.055;
hgh_point(2 * num_pts) = wp->cps_x[max_cp] + 0.055;
starting_point(2 * num_pts + 1) = wp->cps_y[max_cp];
low_point(2 * num_pts + 1) = wp->cps_y[max_cp] - 0.055;
hgh_point(2 * num_pts + 1) = wp->cps_y[max_cp] + 0.055;
num_pts++;
}
else {
double diff_lim = 0.12 * 0.12;
for (int i = 0; i < (wp->m + 1)*(wp->n + 1); i++) {
double diffx = (wp->cps_x[i] - wp->cps_x[max_cp]);
double diffy = (wp->cps_y[i] - wp->cps_y[max_cp]);
double diff = diffx*diffx + diffy*diffy;
if (diff < diff_lim) {
pts[num_pts] = i;
starting_point(2 * num_pts) = wp->cps_x[i];
low_point(2 * num_pts) = wp->cps_x[i] - 0.055;
hgh_point(2 * num_pts) = wp->cps_x[i] + 0.055;
starting_point(2 * num_pts + 1) = wp->cps_y[i];
low_point(2 * num_pts + 1) = wp->cps_y[i] - 0.055;
hgh_point(2 * num_pts + 1) = wp->cps_y[i] + 0.055;
num_pts++;
}
}
}
/*
for (int i = 0; i< (wp->m + 1)*(wp->n + 1); i++) {
if ((wp->dsp_x[i] + wp->dsp_y[i]) > THR1 * max_dsp) {
pts[num_pts] = i;
starting_point(2 * num_pts) = wp->cps_x[i];
low_point(2 * num_pts) = wp->cps_x[i] - 0.07;
hgh_point(2 * num_pts) = wp->cps_x[i] + 0.07;
starting_point(2 * num_pts + 1) = wp->cps_y[i];
low_point(2 * num_pts + 1) = wp->cps_y[i] - 0.07;
hgh_point(2 * num_pts + 1) = wp->cps_y[i] + 0.07;
num_pts++;
}
} */
printf("Inputs: \n");
for (int i = 0; i < num_pts; i++) {
printf("%f %f \n", starting_point(2 * i), starting_point(2 * i + 1));
}
for (int i = 0; i < num_pts; i++) { // backup points
wp->dsp_x[pts[i]] = wp->cps_x[pts[i]];
wp->dsp_y[pts[i]] = wp->cps_y[pts[i]];
}
find_min_bobyqa(test_function(),
starting_point,
// (2 * num_pts + 1)*(2 * num_pts + 2) / 2, //377 number of interpolation points
(2 *num_pts + 1)*(2 *num_pts + 2) / 2,
low_point,
hgh_point,
tregion,// initial trust region radius
0.00001, // stopping trust region radius 1e-6
10000 // max number of objective function evaluations
);
/*
uniform_matrix<double>(2 * num_pts, 1, 0), // lower bound constraint
uniform_matrix<double>(2 * num_pts, 1, 1), // upper bound constraint
*/
printf("Results: \n");
for (int i = 0; i < num_pts; i++) {
printf("%f %f \n", starting_point(2 * i), starting_point(2 * i + 1));
}
for (int i = 0; i < num_pts; i++) {
wp->cps_x[pts[i]] = starting_point(2 * i);
wp->cps_y[pts[i]] = starting_point(2 * i + 1);
}
wp->warpImg(imgSrcCp, imgWpdCp);
wp->drawCpt(imgWpdCp);
cvShowImage("Source", imgWpdCp);
double ssdNew = wp->warpedSSDfull(imgSrcCp, imgTrgCp);
double locSSD = Func(starting_point);
if ( (wp->localSSD[max_cp] != -1) && (locSSD < wp->localSSD[max_cp]) ) {
wp->localSSD[max_cp] = locSSD;
}
else {
wp->checked[max_cp] = true;
}
printf("\n SSD: new %f , old %f \n", ssdNew, globalSSD);
if (ssdNew > 1.02 * globalSSD) {
printf("backup: \n");
for (int i = 0; i < num_pts; i++) {
wp->cps_x[pts[i]] = wp->dsp_x[pts[i]];
wp->cps_y[pts[i]] = wp->dsp_y[pts[i]];
printf("%f %f \n", wp->cps_x[pts[i]], wp->cps_y[pts[i]]);
//cvCopy(imgSrcCp, imgWpdCp);
}
cnt_stop++;
//inclNb = true;
}
else {
globalSSD = ssdNew;
//tregion = 0.0001;
//inclNb = false;
}
//cvWaitKey(0);
}
}
}
else {
int rad = 30;
int cps = 11;
double ssd_val = ssd(imgSrc, imgTrg);
while (rad > 2) {
wp = new warp(cps);
wp->simpOptSg(imgWpd, imgTrg, rad);
printf(" %f %f ", wp->dsp_x[100], wp->dsp_y[100]);
printf(" %f %f \n", wp->dsp_x[50], wp->dsp_y[50]);
wp->warpImg(imgSrc, imgWpd);
if (ssd(imgWpd, imgTrg)>ssd_val) {
//cps*=2;
//rad/=2;
}
ssd_val = ssd(imgWpd, imgTrg);
cvCopy(imgWpd, imgSrc);
printf("\n SSD: %f \n", ssd_val);
wp->drawCpt(imgWpd);
cvShowImage("Source", imgWpd);
cvWaitKey(0);
}
}
printf("\n SSD: %f \n", ssd(imgWpd, imgTrg));
//wp->drawCpt(imgWpd);
//wp2->drawCpt(imgSrc);
//printf("SSD: %f %f \n", ssd_dir(imgSrc, imgTrg, 0.104067, 0.396732, 30, 1), ssd_dir(imgSrc, imgTrg, 0.104067, 0.396732, 30, 2));
//printf("SSD: %f %f \n", ssd_dir(imgSrc, imgTrg, 0.104067, 0.396732, 30, 3), ssd_dir(imgSrc, imgTrg, 0.104067, 0.396732, 30, 4));
// cycle on SSD's till minimizing
wp->warpImg(imgSrc, imgWpd);
wp->drawCpt(imgWpd);
//cvShowImage("Source", imgSrc);
cvShowImage("Source", imgWpd);
cvResizeWindow("Source", width, height);
cvWaitKey(0);
cvDestroyWindow( "Example1" );
//cvReleaseImage( &img );
//cvReleaseImage( &imgWpd );
//int a;
//scanf(" %d ", &a);
return 0;
}
|
5977119a8e8e0969d5ddda07e5d6f2ec1fd1b58b
|
2b554aa96a9846e13d9bd44ffd49f6afff1bef0b
|
/zerojudge/c628 皮皮的邀約/c628 皮皮的邀約(NA 20%).cpp
|
29814da0f9cdca25a9fe68e8abe04d6b23299f6a
|
[] |
no_license
|
mmi366127/Online_Judge
|
193d0377686ebc7178d73f3fa57f9810bf8427bf
|
b9bd97b17a792f8b871b181c672201c07488f778
|
refs/heads/master
| 2021-07-09T19:55:34.466588
| 2020-09-27T06:09:12
| 2020-09-27T06:09:12
| 191,015,108
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,715
|
cpp
|
c628 皮皮的邀約(NA 20%).cpp
|
#includebitsstdc++.h
#define ls(x) (x1)
#define rs(x) ((x1)1)
#define maxn 200007
using namespace std;
struct seg{
vectorint ST;
seg(int _sz) ST(_sz2) {}
void build(int x,int L,int R,int a[]){
if(L==R){
ST[x] = a[L];
return;
}
int mid = (L+R)1;
build(ls(x),L,mid,a);
build(rs(x),mid+1,R,a);
ST[x] = max(ST[ls(x)],ST[rs(x)]);
}
int query(int x,int L,int R,int l,int r){
if(rLRl)
return 0;
else if(l=L&&R=r)
return ST[x];
int mid = (L+R)1;
return max(query(ls(x),L,mid,l,r),query(rs(x),mid+1,R,l,r));
}
};
mapint,int cnt[2];
void add(int n){
if(cnt[1].find(n)!=cnt[1].end()){
cnt[0][n] = cnt[1][n]+1;
cnt[1].erase(n);
} else {
if(cnt[0].find(n)==cnt[0].end()){
cnt[1][n] = 1;
} else {
cnt[1][n] = cnt[0][n]+1;
cnt[0].erase(n);
}
}
}
void kill(int n){
if(cnt[0].find(n)!=cnt[0].end()){
cnt[1][n] = cnt[0][n]-1;
cnt[0].erase(n);
} else {
if(cnt[1][n]1){
cnt[0][n] = cnt[1][n]-1;
}
cnt[1].erase(n);
}
}
struct qu{
int l,r,id,block;
};
bool cmp(qu a,qu b){
return a.block==b.block a.rb.r a.blockb.block;
}
vectorqu Q;
int a[maxn];
int main(){
int n,q,o,l,r,i;
scanf(%d%d%d,&n,&q,&o);
if(o){
int ans = 0;
seg SG(n);
for(int i=1;i=n;i++){
scanf(%d,a+i);
}
SG.build(1,1,n,a);
for(int i=1;i=q;i++){
scanf(%d%d,&l,&r);
l = (l+ans)%n +1;
r = (r+ans)%n +1;
if(lr)
swap(l,r);
printf(%d %dn,l,r);
ans = SG.query(1,1,n,l,r);
printf(%dn,ans);
}
} else {
int k = sqrt(n)+1;
for(i=1;i=n;i++){
scanf(%d,a+i);
}
for(i=1;i=q;i++){
scanf(%d%d,&l,&r);
Q.push_back({l,r,i,lk});
}
int ans[q+1];
sort(Q.begin(),Q.end(),cmp);
cnt[0].clear();
cnt[1].clear();
l = 1; r = 1;
add(a[1]);
for(int i=0;iQ.size();i++){
while(lQ[i].l) kill(a[l++]);
while(lQ[i].l) add(a[--l]);
while(rQ[i].r) add(a[++r]);
while(rQ[i].r) kill(a[r--]);
if(cnt[1].size())
ans[Q[i].id] = prev(cnt[1].end())-first;
else
ans[Q[i].id] = 0;
}
for(i=1;i=q;i++)
printf(%dn,ans[i]);
}
return 0;
}
|
f70509966fd5f5342a86556395d15d997dc84b63
|
802f0c1dd855693f709da4024b50d6d4938c13ff
|
/test/ocp_qp/test_qpsolvers.cpp
|
639299859f6d66edff8539ea6f03db8aa18b2582
|
[
"BSD-2-Clause"
] |
permissive
|
acados/acados
|
9cd480da3462725506f06199838e3cdae007d0c8
|
64166a37859108ab74ce6bf7408501f9bd4a89da
|
refs/heads/master
| 2023-08-16T13:03:44.298740
| 2023-08-15T13:07:48
| 2023-08-15T13:07:48
| 55,497,573
| 558
| 213
|
NOASSERTION
| 2023-09-01T09:01:33
| 2016-04-05T10:06:48
|
C
|
UTF-8
|
C++
| false
| false
| 8,025
|
cpp
|
test_qpsolvers.cpp
|
/*
* Copyright (c) The acados authors.
*
* This file is part of acados.
*
* The 2-Clause 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.
*
* 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.;
*/
#include <iostream>
#include <string>
#include <vector>
#include "catch/include/catch.hpp"
//#include "test/test_utils/eigen.h"
#include "acados_c/ocp_qp_interface.h"
extern "C" {
ocp_qp_xcond_solver_dims *create_ocp_qp_dims_mass_spring(ocp_qp_xcond_solver_config *config, int N, int nx_, int nu_, int nb_, int ng_, int ngN);
ocp_qp_in *create_ocp_qp_in_mass_spring(ocp_qp_dims *dims);
}
using std::vector;
ocp_qp_solver_t hashit(std::string const &inString)
{
if (inString == "SPARSE_HPIPM") return PARTIAL_CONDENSING_HPIPM;
if (inString == "DENSE_HPIPM") return FULL_CONDENSING_HPIPM;
#ifdef ACADOS_WITH_HPMPC
if (inString == "SPARSE_HPMPC") return PARTIAL_CONDENSING_HPMPC;
#endif
#ifdef ACADOS_WITH_QPOASES
if (inString == "DENSE_QPOASES") return FULL_CONDENSING_QPOASES;
#endif
#ifdef ACADOS_WITH_DAQP
if (inString == "DENSE_DAQP") return FULL_CONDENSING_DAQP;
#endif
#ifdef ACADOS_WITH_QPDUNES
if (inString == "SPARSE_QPDUNES") return PARTIAL_CONDENSING_QPDUNES;
#endif
#ifdef ACADOS_WITH_OOQP
if (inString == "DENSE_OOQP") return FULL_CONDENSING_OOQP;
if (inString == "SPARSE_OOQP") return PARTIAL_CONDENSING_OOQP;
#endif
#ifdef ACADOS_WITH_OSQP
if (inString == "SPARSE_OSQP") return PARTIAL_CONDENSING_OSQP;
#endif
#ifdef ACADOS_WITH_QORE
if (inString == "DENSE_QORE") return FULL_CONDENSING_QORE;
#endif
return (ocp_qp_solver_t) -1;
}
double solver_tolerance(std::string const &inString)
{
if (inString == "SPARSE_HPIPM") return 1e-8;
if (inString == "SPARSE_HPMPC") return 1e-5;
// if (inString == "SPARSE_QPDUNES") return 1e-8;
if (inString == "DENSE_HPIPM") return 1e-8;
if (inString == "DENSE_QPOASES") return 1e-10;
if (inString == "DENSE_DAQP") return 1e-10;
if (inString == "DENSE_QORE") return 1e-10;
if (inString == "SPARSE_OOQP") return 1e-5;
if (inString == "DENSE_OOQP") return 1e-5;
if (inString == "SPARSE_OSQP") return 1e-8;
return -1;
}
void set_N2(std::string const &inString, ocp_qp_xcond_solver_config *config, void *opts, int N2, int N)
{
bool option_found = false;
if ( inString=="SPARSE_HPIPM" | inString=="SPARSE_HPMPC" | inString == "SPARSE_OOQP" | inString == "SPARSE_OSQP" )
{
config->opts_set(config, opts, "cond_N", &N2);
}
if (inString == "SPARSE_QPDUNES")
{
config->opts_set(config, opts, "cond_N", &N2);
}
}
TEST_CASE("mass spring example", "[QP solvers]")
{
vector<std::string> solvers = {"DENSE_HPIPM",
"SPARSE_HPIPM"
#ifdef ACADOS_WITH_HPMPC
,
"SPARSE_HPMPC"
#endif
#ifdef ACADOS_WITH_QPOASES
,
"DENSE_QPOASES"
#endif
#ifdef ACADOS_WITH_DAQP
,
"DENSE_DAQP"
#endif
// #ifdef ACADOS_WITH_QPDUNES
// ,"SPARSE_QPDUNES"
// #endif
#ifdef ACADOS_WITH_OOQP
,
"DENSE_OOQP",
"SPARSE_OOQP"
#endif
#ifdef ACADOS_WITH_OSQP
,
"SPARSE_OSQP"
#endif
#ifdef ACADOS_WITH_QORE
,
"DENSE_QORE"
#endif
};
/************************************************
* set up dimensions
************************************************/
int nx_ = 8; // number of states (it has to be even for the mass-spring system test problem)
int nu_ = 3; // number of inputs (controllers) ( 1 <= nu_ <= nx_/2 )
int N = 15; // horizon length
int nb_ = 11; // number of box constrained inputs and states
int ng_ = 0; // number of general constraints
int ngN = 0; // number of general constraints at last stage
double N2_values[] = {15, 5, 3}; // horizon of partially condensed QP for sparse solvers
ocp_qp_xcond_solver_dims *qp_dims;
ocp_qp_in *qp_in;
ocp_qp_out *qp_out;
ocp_qp_solver_plan_t plan;
ocp_qp_xcond_solver_config *config;
ocp_qp_solver *qp_solver;
void *opts;
int acados_return;
double res[4];
double max_res;
double tol;
int N2_length; // 3 for sparse solvers, 1 for dense solvers
std::size_t sparse_solver;
for (std::string solver : solvers)
{
SECTION(solver)
{
plan.qp_solver = hashit(solver); // convert string to enum
sparse_solver = !solver.find("SPARSE");
tol = solver_tolerance(solver);
config = ocp_qp_xcond_solver_config_create(plan);
qp_dims = create_ocp_qp_dims_mass_spring(config, N, nx_, nu_, nb_, ng_, ngN);
qp_in = create_ocp_qp_in_mass_spring(qp_dims->orig_dims);
qp_out = ocp_qp_out_create(qp_dims->orig_dims);
opts = ocp_qp_xcond_solver_opts_create(config, qp_dims);
if (sparse_solver)
{
N2_length = 3;
#ifdef ACADOS_WITH_HPMPC
if (plan.qp_solver == PARTIAL_CONDENSING_HPMPC)
N2_length = 1; // TODO(dimitris): fix this
#endif
}
else
{
N2_length = 1;
}
for (int ii = 0; ii < N2_length; ii++)
{
SECTION("N2 = " + std::to_string((int) N2_values[ii]))
{
set_N2(solver, config, opts, N2_values[ii], N);
qp_solver = ocp_qp_create(config, qp_dims, opts);
acados_return = ocp_qp_solve(qp_solver, qp_in, qp_out);
REQUIRE(acados_return == 0);
ocp_qp_inf_norm_residuals(qp_dims->orig_dims, qp_in, qp_out, res);
max_res = 0.0;
for (int ii = 0; ii < 4; ii++)
{
max_res = (res[ii] > max_res) ? res[ii] : max_res;
}
std::cout << "\n---> residuals of " << solver << " (N2 = " << N2_values[ii]
<< ")\n";
printf("\ninf norm res: %e, %e, %e, %e\n", res[0], res[1], res[2], res[3]);
REQUIRE(max_res <= tol);
free(qp_solver);
}
}
free(qp_out);
free(qp_in);
free(qp_dims);
free(opts);
free(config);
} // END_FOR_N2
} // END_FOR_SOLVERS
} // END_TEST_CASE
|
6424fa218cebbc11aaa12af8159043085576241d
|
e5c23bbbfcfc17ae04b4abf006caa02180d8ca63
|
/Posts/Code/发帖小工具/Posts.h
|
50dbfa83ac6e4ff41968a52ca2dcaa34bf38d7f9
|
[] |
no_license
|
jiftle/Posts
|
1e9b1e69fde6e71e4c3c0eadfd6c67aea674199e
|
3affe8e80e1d37644aa3f3ba4998ab63591921a0
|
refs/heads/master
| 2020-04-11T17:33:44.420672
| 2015-02-18T09:33:46
| 2015-02-18T09:33:46
| 161,965,838
| 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 1,492
|
h
|
Posts.h
|
// Posts.h : main header file for the POSTS application
//
#if !defined(AFX_POSTS_H__50A0BFB9_187D_4CDE_B1D5_961DEAC3B1EF__INCLUDED_)
#define AFX_POSTS_H__50A0BFB9_187D_4CDE_B1D5_961DEAC3B1EF__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CPostsApp:
// See Posts.cpp for the implementation of this class
//
typedef struct{
UINT nCTRL_ID;
UINT fsModifiers;
UINT vk;
UINT hotkeyID;
}HOTKEY;
class CPostsApp : public CWinApp
{
public:
CPostsApp();
CString strAd1;
CString strAd2;
CString strAd3;
CString strAd4;
CString strAd5;
CString strAd6;
HOTKEY CurHotKey; //ÈȼüÉèÖÃ
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPostsApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CPostsApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_POSTS_H__50A0BFB9_187D_4CDE_B1D5_961DEAC3B1EF__INCLUDED_)
|
38c3fac11c381297bfa7c702678db4171b377bb5
|
4832149691f7cbcc30bbd3c2ac9abd5980344707
|
/C++ Solutions/Array & String/LC022_GenerateParentheses.cpp
|
dc84ce09f242c7104774fa2fe2b52b3707095189
|
[] |
no_license
|
kapil8882001/Coding-Practice-1
|
4149dc3151517e8a4b5d9bed507a58c309b79ad2
|
f0679e543628bf093419e574dffad1a0a36dca2c
|
refs/heads/master
| 2022-02-18T14:47:15.402707
| 2019-09-24T07:18:21
| 2019-09-24T07:18:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 765
|
cpp
|
LC022_GenerateParentheses.cpp
|
//Leetcode: Generate Parentheses
/*
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
*/
class Solution {
public:
vector<string> ans;
vector<string> generateParenthesis(int n) {
helper("", n, 0);
return ans;
}
void helper(string s, int leftParen, int right_need){
if(leftParen == 0 && right_need == 0){
ans.push_back(s);
return;
}
if(leftParen > 0){
helper(s + "(", leftParen - 1, right_need + 1);
}
if(right_need > 0){
helper(s + ")", leftParen, right_need - 1);
}
}
};
|
5c2802746264d697818ad5379dc3730e673e6dda
|
9b17f84f716812f68490bbf685e0fb585dc2c2f9
|
/gloox/addon/qsv.h
|
7b745ab94d72a82810e97d880458e8bc35196397
|
[] |
no_license
|
SiteView/eccmeteor
|
5f2e81dbf373290cf3b21c3df061c34843f807d1
|
12439345a9d50395c52d879b8777a31d042475a7
|
refs/heads/master
| 2020-05-30T12:15:18.035344
| 2013-11-29T09:02:07
| 2013-12-02T02:38:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 869
|
h
|
qsv.h
|
#include <string>
#include <map>
#include <list>
#include <vector>
using std::string;
using std::vector;
using std::map;
typedef std::map<string,string> StrMap;
typedef std::vector< StrMap > ForestVector;
typedef std::map< string, StrMap > ForestMap;
bool qt_GetForestData (ForestVector & fvec, StrMap & inwhat, std::string & estr);
bool qt_GetUnivData (ForestMap & fmap, StrMap & inwhat, std::string & estr);
bool qt_SubmitUnivData (ForestMap & fmap, StrMap & inwhat, std::string & estr);
string GB2312ToUTF8(string intext);
string UTF8ToGB2312(string intext);
string GetValue(const ForestMap & fmap, string section, string key, bool & isok );
string GetValue(const StrMap & smap, string section, string key, bool & isok );
std::string testGetMonitorTemplet();
std::string testGetTreeData();
std::string testSubmitGroup();
std::string getSVstr();
|
0c199360f6b9abeec21e848301fad9ced720f82b
|
c26267aae7dc1cac467010e73fa7893aa581c1f0
|
/Prácticas/Practica4/src/4_DemoMatriz2D_1.cpp
|
5ee9ec8b1a08ab130374da10a5e61218d316200c
|
[
"MIT"
] |
permissive
|
josepadial/MP
|
18dab956aa02509a986cc8895009f90f904cb4b2
|
d7bb62943cb84b0e8ccb5336498328f536e001ee
|
refs/heads/master
| 2021-05-23T13:21:54.583254
| 2020-04-05T23:17:21
| 2020-04-05T23:17:21
| 253,308,099
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,840
|
cpp
|
4_DemoMatriz2D_1.cpp
|
/*
Nombre: Jose Antonio Padial Molina
DNI: 77391553A
Curso: 2016/2017
Grupo: 2ºB
Fecha: 28/03/2017
*/
#include "Matriz2D_1.h"
int main(){
int fil, col;
int fil_ini, fil_fin;
int col_ini, col_fin;
int fil_eli, col_eli;
time_t t;
srand((int) time(&t));
cout << "Introduzca el numero de filas: " << endl;
cin >> fil;
cout << "Introduzca el numero de columnas: " << endl;
cin >> col;
Matriz2D_1 matriz(fil,col);
Matriz2D_1 matriz2(fil,col);
ReservarMatrizIndefinida(matriz);
cout << "Matriz indefinida" << endl;
Imprimir(matriz);
LiberarMatriz(matriz);
ReservarMatrizEntrada(matriz);
cout << "Matriz de entradas" << endl;
Imprimir(matriz);
LiberarMatriz(matriz);
ReservarMatrizAleatorio(matriz);
cout << "Matriz aleatoria" << endl;
Imprimir(matriz);
matriz2 = CopiarMatriz(matriz);
cout << "Matriz copiada" << endl;
Imprimir(matriz2);
cout << "Introduzca la fila de inicio: " << endl;
cin >> fil_ini;
cout << "Introduzca la fila de fin: " << endl;
cin >> fil_fin;
cout << "Introduzca la columna de inicio: " << endl;
cin >> col_ini;
cout << "Introduzca la columna de fin: " << endl;
cin >> col_fin;
matriz2 = SubMatriz(matriz, fil_ini, fil_fin, col_ini, col_fin);
cout << "Submatriz" << endl;
Imprimir(matriz2);
cout << "Introduzca la fila a eliminar: " << endl;
cin >> fil_eli;
matriz2 = EliminarFila(matriz, fil_eli);
cout << "Fila eliminada" << endl;
Imprimir(matriz2);
cout << "Introduzca la columna a eliminar: " << endl;
cin >> col_eli;
matriz2 = EliminarColumna(matriz, col_eli);
cout << "Columna eliminada" << endl;
Imprimir(matriz2);
matriz2 = Traspuesta(matriz);
cout << "Matriz traspuesta" << endl;
Imprimir(matriz2);
matriz2 = CambiarFilas(matriz);
cout << "Matriz Cambiada" << endl;
Imprimir(matriz2);
LiberarMatriz(matriz);
LiberarMatriz(matriz2);
return 0;
}
|
c1fef71bf45562da4462f98def344c5b54d15e76
|
fa889d051a1b3c4d861fb06b10aa5b2e21f97123
|
/kbe/res/client/sdk_templates/ue4/Source/KBEnginePlugins/Private/MessageReader.cpp
|
9ee68440c47f0c2e322da4b313fc2d364d6b1c76
|
[
"MIT",
"LGPL-3.0-only"
] |
permissive
|
BuddhistDeveloper/HeroLegendServer
|
bcaa837e3bbd6544ce0cf8920fd54a1a324d95c8
|
8bf77679595a2c49c6f381c961e6c52d31a88245
|
refs/heads/master
| 2022-12-08T00:32:45.623725
| 2018-01-15T02:01:44
| 2018-01-15T02:01:44
| 117,069,431
| 1
| 1
|
MIT
| 2022-11-19T15:58:30
| 2018-01-11T08:05:32
|
Python
|
UTF-8
|
C++
| false
| false
| 3,685
|
cpp
|
MessageReader.cpp
|
#include "MessageReader.h"
#include "KBDebug.h"
MessageReader::MessageReader():
msgid_(0),
msglen_(0),
expectSize_(2),
state_(READ_STATE_MSGID),
pMemoryStream_(new MemoryStream())
{
}
MessageReader::~MessageReader()
{
KBE_SAFE_RELEASE(pMemoryStream_);
}
void MessageReader::process(const uint8* datas, MessageLengthEx offset, MessageLengthEx length)
{
MessageLengthEx totallen = offset;
while (length > 0 && expectSize_ > 0)
{
if (state_ == READ_STATE_MSGID)
{
if (length >= expectSize_)
{
memcpy(pMemoryStream_->data() + pMemoryStream_->wpos(), datas + totallen, expectSize_);
totallen += expectSize_;
pMemoryStream_->wpos(pMemoryStream_->wpos() + expectSize_);
length -= expectSize_;
(*pMemoryStream_) >> msgid_;
pMemoryStream_->clear(false);
Message* pMsg = Messages::getSingleton().findClientMessage(msgid_);
if (pMsg == NULL)
{
SCREEN_ERROR_MSG("MessageReader::process(): not found Message(%d)!", msgid_);
break;
}
if (pMsg->msglen == -1)
{
state_ = READ_STATE_MSGLEN;
expectSize_ = 2;
}
else if (pMsg->msglen == 0)
{
// 如果是0个参数的消息,那么没有后续内容可读了,处理本条消息并且直接跳到下一条消息
pMsg->handle(*pMemoryStream_);
state_ = READ_STATE_MSGID;
expectSize_ = 2;
}
else
{
expectSize_ = (MessageLengthEx)pMsg->msglen;
state_ = READ_STATE_BODY;
}
}
else
{
memcpy(pMemoryStream_->data() + pMemoryStream_->wpos(), datas + totallen, length);
pMemoryStream_->wpos(pMemoryStream_->wpos() + length);
expectSize_ -= length;
break;
}
}
else if (state_ == READ_STATE_MSGLEN)
{
if (length >= expectSize_)
{
memcpy(pMemoryStream_->data() + pMemoryStream_->wpos(), datas + totallen, expectSize_);
totallen += expectSize_;
pMemoryStream_->wpos(pMemoryStream_->wpos() + expectSize_);
length -= expectSize_;
(*pMemoryStream_) >> msglen_;
pMemoryStream_->clear(false);
// 长度扩展
if (msglen_ >= 65535)
{
state_ = READ_STATE_MSGLEN_EX;
expectSize_ = 4;
}
else
{
state_ = READ_STATE_BODY;
expectSize_ = msglen_;
}
}
else
{
memcpy(pMemoryStream_->data() + pMemoryStream_->wpos(), datas + totallen, length);
pMemoryStream_->wpos(pMemoryStream_->wpos() + length);
expectSize_ -= length;
break;
}
}
else if (state_ == READ_STATE_MSGLEN_EX)
{
if (length >= expectSize_)
{
memcpy(pMemoryStream_->data() + pMemoryStream_->wpos(), datas + totallen, expectSize_);
totallen += expectSize_;
pMemoryStream_->wpos(pMemoryStream_->wpos() + expectSize_);
length -= expectSize_;
(*pMemoryStream_) >> expectSize_;
pMemoryStream_->clear(false);
state_ = READ_STATE_BODY;
}
else
{
memcpy(pMemoryStream_->data() + pMemoryStream_->wpos(), datas + totallen, length);
pMemoryStream_->wpos(pMemoryStream_->wpos() + length);
expectSize_ -= length;
break;
}
}
else if (state_ == READ_STATE_BODY)
{
if (length >= expectSize_)
{
pMemoryStream_->append(datas, totallen, expectSize_);
totallen += expectSize_;
length -= expectSize_;
Message* pMsg = Messages::getSingleton().findClientMessage(msgid_);
if (pMsg == NULL)
{
SCREEN_ERROR_MSG("MessageReader::process(): not found Message(%d)!", msgid_);
break;
}
pMsg->handle(*pMemoryStream_);
pMemoryStream_->clear(false);
state_ = READ_STATE_MSGID;
expectSize_ = 2;
}
else
{
pMemoryStream_->append(datas, totallen, length);
expectSize_ -= length;
break;
}
}
}
}
|
7fd389e5a06b5c4b7ef511ec50978eb54d6e9997
|
3f75df57ae155e3eaada2885b12b78a63bbc43a1
|
/source/Geometry/tbeam/src/EncoderTBscecal01.cc
|
352b925b5e872a16f13a18043118ca07239d54e0
|
[] |
no_license
|
nkxuyin/mokka-cepc
|
52bb13455b6fc5961de678ad7cb695f754e49a47
|
61ce9f792a4cb8883f0d1cd1391884444b372dc0
|
refs/heads/master
| 2021-01-20T10:42:00.982704
| 2015-02-11T12:59:43
| 2015-02-11T12:59:43
| 24,243,983
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,456
|
cc
|
EncoderTBscecal01.cc
|
#include "Control.hh"
#include "EncoderTBscecal01.hh"
#include "CalHit.hh"
#include <assert.h>
#define K_Protoshift 0 // K = 8 bits
#define J_Protoshift 8 // J = 8 bits
#define I_Protoshift 16 // I = 8 bits
#define K_ProtoMask (unsigned int) 0x000000FF
#define J_ProtoMask (unsigned int) 0x0000FF00
#define I_ProtoMask (unsigned int) 0x00FF0000
// Refer to EncorderTB at .../Geometry/CGA/src(include)/EncoderTB.cc(hh)
EncoderTBscecal01::EncoderTBscecal01(void):VEncoder(false) {
idString="K:8,J:8,I:8";
}
cell_ids EncoderTBscecal01::encode(G4int, G4int, G4int, G4int J, G4int K,
G4int) {
//assert((I<256) && (I>=0));
assert((J<256) && (J>=0));
assert((K<256) && (K>=0));
cell_ids index;
index.id0 = (( (J << J_Protoshift) & J_ProtoMask ) |
( (K << K_Protoshift) & K_ProtoMask )
);
//120228. Strip no also from the first digit. --> using K_Protoshift, K_ProtoMask
index.id1 = (
( (J << K_Protoshift) & K_ProtoMask )
);
return index;
}
CalHit* EncoderTBscecal01::decode(cell_ids index) {
G4int J, K;
G4int cellID0 = index.id0;
G4int cellID1 = index.id1;
K= ( ( (unsigned int) cellID0 & K_ProtoMask ) >> K_Protoshift);
J= ( ( (unsigned int) cellID1 & K_ProtoMask ) >> K_Protoshift);
return new CalHit(0, 0, 0, J, K, 0, 0, 0, 0, 0, 0, 0, 0, 0, index);
}
|
af1ae52b8509d857ad379a8dd7f17d839d62db04
|
b84750a9c52170335dafbf6722e3f3dcef48e604
|
/src/Music.cpp
|
3cdf131d702175183b10a873e0659c060e593013
|
[
"MIT"
] |
permissive
|
Daivuk/onut
|
092605d61921aa00e38140ac1b48ae6bdfb9057e
|
a257a644db6fdfeed9a6e28a37c7d20682c8b7b8
|
refs/heads/master
| 2023-08-27T23:10:55.607302
| 2023-08-15T20:59:35
| 2023-08-15T21:00:28
| 27,346,843
| 53
| 9
|
MIT
| 2021-01-08T15:24:59
| 2014-11-30T19:15:13
|
C
|
UTF-8
|
C++
| false
| false
| 497
|
cpp
|
Music.cpp
|
// Onut
#include <onut/ContentManager.h>
#include <onut/Music.h>
namespace onut
{
Music::Music()
{
}
Music::~Music()
{
}
}
OMusicRef OGetMusic(const std::string& name)
{
return oContentManager->getResourceAs<OMusic>(name);
}
void OPlayMusic(const std::string& name, bool loop)
{
auto pMusic = OGetMusic(name);
if (pMusic) pMusic->play(loop);
}
void OStopMusic(const std::string& name)
{
auto pMusic = OGetMusic(name);
if (pMusic) pMusic->stop();
}
|
f1dd5bd770233bdc771887df8ff85f32142021d3
|
d3b7136c8f233b864ef18faff03259cad5cbd5f8
|
/example/rfSender/rfSender.ino
|
3e91a17f71e5f504ceab7430ccb8c586d141eb5c
|
[] |
no_license
|
vaginessa/esp8266_rfSniffer
|
4a44d2ad56149b10d4269c6392bb5eb622c58f80
|
f24831f344e810ceaa2fab356a1309cf7237c553
|
refs/heads/master
| 2020-04-17T09:23:31.547137
| 2018-04-05T04:37:06
| 2018-04-05T04:37:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,057
|
ino
|
rfSender.ino
|
/*
Example for different sending methods
https://github.com/sui77/rc-switch/
*/
#include <RCSwitch.h>
#include <RfProcl.h>
#include <RfDevices.h>
#define WEMOS_PIN_D0 16u // D0
#define WEMOS_PIN_D1 5u // D1
#define WEMOS_PIN_D2 4u // D2
#define WEMOS_PIN_D3 0u // D3
#define WEMOS_PIN_D4 2u // D4
#define WEMOS_PIN_D5 14u // D5
#define WEMOS_PIN_D6 12u // D6
#define WEMOS_PIN_D7 13u // D7
#define WEMOS_PIN_D8 15u // D8
#define TX_PIN WEMOS_PIN_D4
RCSwitch mySwitch = RCSwitch();
static msg_t myMessage_s;
static void printMsg();
void setup() {
Serial.begin(115200);
// Transmitter is connected to Arduino Pin #10
mySwitch.enableTransmit(TX_PIN);
// initialize message
RfProcl::InitializeMessage(&myMessage_s);
Serial.println("sender initialized");
Serial.print("msg after init:");
Serial.println(RfProcl::GetRawData(&myMessage_s));
// Optional set protocol (default is 1, will work for most outlets)
// mySwitch.setProtocol(2);
// Optional set pulse length.
// mySwitch.setPulseLength(320);
// Optional set number of transmission repetitions.
// mySwitch.setRepeatTransmit(15);
}
void loop()
{
Serial.println("send start of loop pattern:");
mySwitch.send(1111, 32);
delay(1000);
// send all message with 1
RfProcl::InitializeMessage(&myMessage_s);
RfProcl::SetFromNodeId(&myMessage_s, FROM_NODE_ID_03);
RfProcl::SetToNodeId(&myMessage_s, TO_NODE_ID_03);
RfProcl::SetMsgTypeId(&myMessage_s, MSG_ID_03);
RfProcl::SetMsgData(&myMessage_s, 0xffff);
RfProcl::CalculateChkSum(&myMessage_s);
mySwitch.send(RfProcl::GetRawData(&myMessage_s), 32);
printMsg();
delay(1000);
// send all message with all 0
RfProcl::InitializeMessage(&myMessage_s);
RfProcl::SetFromNodeId(&myMessage_s, FROM_NODE_ID_00);
RfProcl::SetToNodeId(&myMessage_s, TO_NODE_ID_00);
RfProcl::SetMsgTypeId(&myMessage_s, MSG_ID_00);
RfProcl::SetMsgData(&myMessage_s, 0x0000);
RfProcl::CalculateChkSum(&myMessage_s);
mySwitch.send(RfProcl::GetRawData(&myMessage_s), 32);
printMsg();
delay(1000);
Serial.println("send end of loop pattern");
mySwitch.send(4444, 32);
delay(3000);
}
void printMsg()
{
Serial.print("+++ Header: ");
Serial.print(myMessage_s.header_u8);
Serial.print(", Data: ");
Serial.print(myMessage_s.data_u16);
Serial.print(", CheckSum: ");
Serial.println(myMessage_s.chkSum_u8);
Serial.print(">>> FromNode: ");
Serial.print(RfProcl::GetFromNodeId(&myMessage_s));
Serial.print(" -> ToNode: ");
Serial.print(RfProcl::GetToNodeId(&myMessage_s));
Serial.print(" [");
Serial.print(RfProcl::GetMsgTypeId(&myMessage_s));
Serial.print("] ");
Serial.print("Payload: ");
Serial.print(RfProcl::GetMsgData(&myMessage_s));
Serial.print(" V: ");
Serial.println(RfProcl::VerifyMessage(&myMessage_s));
}
|
9aa917c5a2ec9f4f6a4d91becb42e70d037d7d05
|
bd86855370d1225a69945061f84f5f55002c844b
|
/src/inc/agent/TaskWorker.h
|
c83150e751f12e7f29b5617f77c57277b9e0cb91
|
[
"Apache-2.0"
] |
permissive
|
wangguitao/intelligent-protector
|
6675b2740d618586e4c42059299811fba7db1b6b
|
f521e23db3f57f30f5e1dc05f5ec95d392440474
|
refs/heads/master
| 2022-04-01T01:58:31.491728
| 2018-02-01T14:26:53
| 2018-02-01T14:26:53
| 119,827,684
| 5
| 3
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,815
|
h
|
TaskWorker.h
|
/*******************************************************************************
* Copyright @ Huawei Technologies Co., Ltd. 2017-2018. All rights reserved.
********************************************************************************/
#ifndef _AGENT_TASK_WORKER_H_
#define _AGENT_TASK_WORKER_H_
#include "pluginfx/IPlugin.h"
#include "pluginfx/PluginCfgParse.h"
#include "pluginfx/PluginManager.h"
#include "plugins/ServicePlugin.h"
#include "common/Types.h"
#include "common/Thread.h"
#include "agent/Communication.h"
enum WORK_STATUS
{
IDLE = 0,
RUNNING = 1
};
class CTaskWorker
{
private:
thread_lock_t m_tPlgLock;
thread_lock_t m_tReqLock;
thread_id_t m_threadId;
mp_bool m_bClosed;
vector<message_pair_t> m_vecReqQueue;
mp_uint64 m_SCN;
const mp_char* m_plgName;
const mp_char* m_plgVersion;
CPluginCfgParse* m_plgCfgParse;
CPluginManager* m_plgMgr;
volatile mp_bool m_bProcReq;
volatile mp_bool m_bNeedExit; //线程退出标识
volatile mp_int32 m_iThreadStatus; //接收线程状态
public:
CTaskWorker();
virtual ~CTaskWorker();
virtual mp_int32 ReqProc();
mp_bool NeedExit();
mp_void SetThreadStatus(mp_int32 iThreadStatus);
mp_bool GetThreadProcReqStatus();
mp_int32 PopRequest(message_pair_t& msg);
mp_void PushRequest(message_pair_t& msg);
mp_int32 Init(CPluginCfgParse* pPlgCfgParse, CPluginManager* pPlgMgr);
mp_void Exit();
mp_bool CanUnloadPlugin(mp_uint64 newSCN, const char* plgName);
private:
CServicePlugin* GetPlugin(mp_char* pszService);
mp_void SetPlugin(CServicePlugin* pPlug);
#ifdef WIN32
static DWORD WINAPI WorkProc(void* pThis);
#else
static void* WorkProc(void* pThis);
#endif
};
#endif //_AGENT_TASK_WORKER_H_
|
2796c9fde512cdb3a5d6ae7119ff5538b13675af
|
fcb2003b548494a0ce6a0f7bcac36aecab83bf20
|
/finddErrors/finddErrors/findError.cpp
|
0277b1b37e4af1fc114800844ba360193ec4389d
|
[] |
no_license
|
anderfernandes/ITSE2421
|
c594fb66a1546607984d385859d82b487ec5c9ee
|
369920fddbebebdb4cf557ef4af7e4e18ea569b9
|
refs/heads/master
| 2016-09-06T11:51:32.321491
| 2015-05-15T12:38:28
| 2015-05-15T12:38:50
| 15,922,213
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 669
|
cpp
|
findError.cpp
|
// findErrors.cpp
// This program has several syntax and logic errors.
#include <iostream>
using namespace std;
int main()
{
// Changed "doubl" in line below to "double". (Anderson Fernandes)
double length = 0, // Length of a room in feet
width = 0, // Width of a room in feet
area = 0; // Area of the room in sq. ft.
// Get the room dimensions
cout << "Enter room length (in feet): ";
cin >> length;
cout << "Enter room width (in feet): ";
cin >> width;
// Compute and display the area
area = length * width;
cout << "The area of the room is " << area << " square feet. " << endl;
return 0;
}
|
32c2054c7dcf5ff967d913b2d1ae21fed3164974
|
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
|
/app/src/main/cpp/dir521/dir522/dir572/dir2774/dir2803/file2876.cpp
|
a2bf40ab9c6cea2b82163e8f586103eb48a51c6a
|
[] |
no_license
|
tgeng/HugeProject
|
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
|
4488d3b765e8827636ce5e878baacdf388710ef2
|
refs/heads/master
| 2022-08-21T16:58:54.161627
| 2020-05-28T01:54:03
| 2020-05-28T01:54:03
| 267,468,475
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 111
|
cpp
|
file2876.cpp
|
#ifndef file2876
#error "macro file2876 must be defined"
#endif
static const char* file2876String = "file2876";
|
632ec12ac4139a2d1f7f996001eb5126bae42135
|
1dbf007249acad6038d2aaa1751cbde7e7842c53
|
/gaussdb/include/huaweicloud/gaussdb/v3/model/Resource.h
|
b0524cacef7d2d6d8d210dc8b31e474973d67887
|
[] |
permissive
|
huaweicloud/huaweicloud-sdk-cpp-v3
|
24fc8d93c922598376bdb7d009e12378dff5dd20
|
71674f4afbb0cd5950f880ec516cfabcde71afe4
|
refs/heads/master
| 2023-08-04T19:37:47.187698
| 2023-08-03T08:25:43
| 2023-08-03T08:25:43
| 324,328,641
| 11
| 10
|
Apache-2.0
| 2021-06-24T07:25:26
| 2020-12-25T09:11:43
|
C++
|
UTF-8
|
C++
| false
| false
| 1,727
|
h
|
Resource.h
|
#ifndef HUAWEICLOUD_SDK_GAUSSDB_V3_MODEL_Resource_H_
#define HUAWEICLOUD_SDK_GAUSSDB_V3_MODEL_Resource_H_
#include <huaweicloud/gaussdb/v3/GaussDBExport.h>
#include <huaweicloud/core/utils/ModelBase.h>
#include <huaweicloud/core/http/HttpResponse.h>
#include <string>
namespace HuaweiCloud {
namespace Sdk {
namespace Gaussdb {
namespace V3 {
namespace Model {
using namespace HuaweiCloud::Sdk::Core::Utils;
using namespace HuaweiCloud::Sdk::Core::Http;
/// <summary>
///
/// </summary>
class HUAWEICLOUD_GAUSSDB_V3_EXPORT Resource
: public ModelBase
{
public:
Resource();
virtual ~Resource();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
bool fromJson(const web::json::value& json) override;
/////////////////////////////////////////////
/// Resource members
/// <summary>
/// 指定类型的配额。 - instance: 表示实例的配额
/// </summary>
std::string getType() const;
bool typeIsSet() const;
void unsettype();
void setType(const std::string& value);
/// <summary>
/// 已创建的资源个数。
/// </summary>
int32_t getUsed() const;
bool usedIsSet() const;
void unsetused();
void setUsed(int32_t value);
/// <summary>
/// 资源最大的配额数。
/// </summary>
int32_t getQuota() const;
bool quotaIsSet() const;
void unsetquota();
void setQuota(int32_t value);
protected:
std::string type_;
bool typeIsSet_;
int32_t used_;
bool usedIsSet_;
int32_t quota_;
bool quotaIsSet_;
};
}
}
}
}
}
#endif // HUAWEICLOUD_SDK_GAUSSDB_V3_MODEL_Resource_H_
|
05a42054e16e4eb660750e9f95c27ae91d45cb33
|
0e6853db844833b61d0ce60fa6fdf11ee499e791
|
/src/Territory.cpp
|
1d2685f2a04c5ddff0a091bbf216ca6138b2270d
|
[] |
no_license
|
Schtekt/RiskGame
|
cbecf781193337816d22f1e07d1da4c5383d9105
|
8ab2cfd3b1d583942124290a4935753bce633144
|
refs/heads/master
| 2021-05-20T03:01:24.854604
| 2020-06-15T15:37:04
| 2020-06-15T15:37:04
| 252,157,607
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,056
|
cpp
|
Territory.cpp
|
#include "Territory.h"
#include "Player.h"
Territory::Territory(const std::string& name): m_owner(nullptr), m_troopCountToken(nullptr)
{
m_name = name;
m_armyCount = 0;
}
void Territory::AddNeighbour(Territory* area)
{
m_neighbours.push_back(area);
}
void Territory::SetArmyCount(unsigned int count)
{
m_armyCount = count;
if(m_troopCountToken)
m_troopCountToken->Txt.setString(std::to_string(m_armyCount));
}
void Territory::AddTroopCountToken(TroopCount* tc)
{
m_troopCountToken = tc;
}
void Territory::SetOwner(Player* player)
{
m_owner = player;
}
TroopCount* Territory::GetTroopCountToken()
{
return m_troopCountToken;
}
std::string Territory::GetName() const
{
return m_name;
}
unsigned int Territory::GetArmyCount() const
{
return m_armyCount;
}
unsigned int Territory::NrOfNeighbours() const
{
return m_neighbours.size();
}
Territory* Territory::GetNeighbour(int index) const
{
return m_neighbours[index];
}
Player* Territory::GetOwner() const
{
return m_owner;
}
|
90c5bc7bae143480d1dac8d708132bdd573ef184
|
80f270c68e853c9f7a885b4744a21ad4c93e05cc
|
/UglyUnsorted/Summer/cpp/petunin.cpp
|
c2c1598e6f221d00ff8e81672c6f690c008ce790
|
[] |
no_license
|
chankhavu/CancerDetection
|
bc0453cad614ea82596808ab4c68d770cc2255d3
|
ee2cf082929f33f2096033b153606045abfa6e68
|
refs/heads/master
| 2020-12-07T02:39:09.970163
| 2017-06-28T10:25:26
| 2017-06-28T10:25:26
| 95,491,385
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,566
|
cpp
|
petunin.cpp
|
#include <iostream>
#include <iomanip>
#include <queue>
#include <string>
#include <algorithm>
#include <Magick++.h>
#include <tuple>
#include <assert.h>
#include <cstdlib>
typedef struct {
double r, g, b;
} point3d;
inline double dist2(point3d a, point3d b){
return (a.r-b.r)*(a.r-b.r) + (a.g-b.g)*(a.g-b.g) + (a.b-b.b)*(a.b-b.b);
}
class mapped_image {
private:
int height;
int width;
point3d **pixels;
public:
mapped_image(const std::string& image_name){
Magick::Image image(image_name);
Magick::PixelPacket* pixel_cache = image.getPixels(0, 0, image.columns(), image.rows());
this->width = image.columns(), this->height = image.rows();
pixels = new point3d* [height];
for (int i=0; i<height; i++)
pixels[i] = new point3d [width];
for (int i=0; i<height; i++)
for (int j=0; j<width; j++){
Magick::Color c = *(pixel_cache + i*width + j);
pixels[i][j] = {
(double)c.redQuantum(), (double)c.greenQuantum(), (double)c.blueQuantum() };
}
}
~mapped_image(){
for (int i=0; i<height; i++)
delete[] pixels[i];
delete[] pixels;
}
int get_height(){ return height; }
int get_width(){ return width; }
point3d operator() (int column, int row){
return pixels[row][column];
}
};
class screen_row {
protected:
int size;
int left, right;
int column;
int row;
mapped_image& image;
point3d d0, d1;
double distance = -1.;
public:
std::tuple<point3d, point3d, double> get_diameter(){
return std::make_tuple(d0, d1, distance);
}
screen_row(mapped_image& map, int c, int r, int rad): image(map), column(c), row(r){
right = std::min(rad+1, image.get_width()-c);
left = std::max(-rad, 0-c);
size = right - left;
}
int width(){ return size; }
point3d operator[] (int index){
// std::cerr << column + left << " " << column + left + size<< std::endl;;
return image(column + left + index, row);
}
friend void try_update_diameter(screen_row& row, screen_row& new_row){
for (int i=0; i<row.width(); i++)
for (int j=0; j<new_row.width(); j++){
point3d a = row[i], b = new_row[j];
if (a.r > b.r)
std::swap(a, b);
double new_dist = dist2(a, b);
if (new_dist > row.distance)
row.d0 = a, row.d1 = b, row.distance = new_dist;
}
return;
}
};
typedef struct {
point3d f;
point3d s;
} zip;
class kernel {
protected:
mapped_image& image;
std::list<screen_row> screen;
int column, row, radius;
point3d d0, d1;
double diameter;
public:
kernel(mapped_image& img, int rad, int c, int r):
image(img), radius(rad)
{
this->move_to(c, r);
for (auto it0 = screen.begin(); it0 != screen.end(); it0++)
for (auto it1 = it0; it1 != screen.end(); it1++)
try_update_diameter(*it1, *it0);
diameter = 1.0;
for (auto it = screen.begin(); it != screen.end(); it++){
auto t = (*it).get_diameter();
if (std::get<2>(t) > this->diameter)
this->d0 = std::get<0>(t), this->d1 = std::get<1>(t), diameter = std::get<2>(t);
}
}
void move_to(int c, int r) {
if (!screen.empty())
screen.clear();
this->column = c, this->row = r;
for (int i=std::max(-radius, 0-row); i<std::min(radius+1, image.get_height()-row); i++)
screen.push_front(screen_row(image, column, row+i, radius));
}
void move_down() {
diameter = -1.;
screen.pop_back();
row++;
if (row + radius >= image.get_height()) {
for (auto it = screen.begin(); it != screen.end(); it++){
auto t = (*it).get_diameter();
if (std::get<2>(t) > this->diameter)
this->d0 = std::get<0>(t), this->d1 = std::get<1>(t), diameter = std::get<2>(t);
}
return;
}
screen.push_front(screen_row(image, column, row+radius-1, radius));
screen_row& new_row = screen.front();
for (auto it = screen.begin(); it != screen.end(); it++){
try_update_diameter(*it, new_row);
auto t = (*it).get_diameter();
if (std::get<2>(t) > this->diameter)
this->d0 = std::get<0>(t), this->d1 = std::get<1>(t), diameter = std::get<2>(t);
}
}
std::tuple<point3d, point3d, double> get_diameter(){
return std::make_tuple(d0, d1, diameter);
}
std::vector<zip> to_zipped(){
std::vector<zip> v;
for (auto it = screen.begin(); it != screen.end(); it++)
for (int i=0; i<(*it).width(); i++)
v.push_back({ (*it)[i], (*it)[i] });
return v;
}
};
void affine_move(std::vector<zip>& v, point3d u){
for (int i=0; i<v.size(); i++)
v[i].f = { v[i].f.r + u.r, v[i].f.g + u.g, v[i].f.b + u.b };
}
void affine_rotationxy(std::vector<zip>& v, double xy_angle){
for (int i=0; i<v.size(); i++){
double r = v[i].f.r * cos(xy_angle) - v[i].f.g * sin(xy_angle);
double g = v[i].f.r * sin(xy_angle) + v[i].f.g * cos(xy_angle);
v[i].f = {r, g, v[i].f.b};
}
}
void affine_rotationxz(std::vector<zip>& v, double xz_angle){
for (int i=0; i<v.size(); i++){
double r = v[i].f.r * cos(xz_angle) - v[i].f.b * sin(xz_angle);
double b = v[i].f.r * sin(xz_angle) + v[i].f.b * cos(xz_angle);
v[i].f = {r, v[i].f.g, b};
}
}
void affine_scale(std::vector<zip>& v){
double maxr = std::max_element(v.begin(), v.end(), [](zip a, zip b){return a.f.r<b.f.r;})->f.r;
double minr = std::min_element(v.begin(), v.end(), [](zip a, zip b){return a.f.r<b.f.r;})->f.r;
double maxg = std::max_element(v.begin(), v.end(), [](zip a, zip b){return a.f.g<b.f.g;})->f.g;
double ming = std::min_element(v.begin(), v.end(), [](zip a, zip b){return a.f.g<b.f.g;})->f.g;
double maxb = std::max_element(v.begin(), v.end(), [](zip a, zip b){return a.f.b<b.f.b;})->f.b;
double minb = std::min_element(v.begin(), v.end(), [](zip a, zip b){return a.f.b<b.f.b;})->f.b;
point3d u;
if (minr < 0.)
affine_move(v, u = {-minr, 0, 0}), maxr -= minr;
if (ming < 0.)
affine_move(v, u = {0, -ming, 0}), maxg -= ming;
if (minb < 0.)
affine_move(v, u = {0, 0, -minb}), maxb -= minb;
for (int i=0; i<v.size(); i++){
v[i].f.r /= maxr;
v[i].f.g /= maxg;
v[i].f.b /= maxb;
}
maxr = std::max_element(v.begin(), v.end(), [](zip a, zip b){return a.f.r<b.f.r;})->f.r;
minr = std::min_element(v.begin(), v.end(), [](zip a, zip b){return a.f.r<b.f.r;})->f.r;
maxg = std::max_element(v.begin(), v.end(), [](zip a, zip b){return a.f.g<b.f.g;})->f.g;
ming = std::min_element(v.begin(), v.end(), [](zip a, zip b){return a.f.g<b.f.g;})->f.g;
maxb = std::max_element(v.begin(), v.end(), [](zip a, zip b){return a.f.b<b.f.b;})->f.b;
minb = std::min_element(v.begin(), v.end(), [](zip a, zip b){return a.f.b<b.f.b;})->f.b;
// std::cerr << minr << " " << ming << " " << minb << std::endl;
assert(minr >= -0.001 && ming >= -0.001 && minb >= -0.001);
assert(maxr <= 1.001 && maxg <= 1.001 && maxb <= 1.001);
}
void petunin_order(std::vector<zip>& v, point3d d0, point3d d1){
std::cerr << std::fixed << std::setprecision(6) ;
point3d u = { -d0.r, -d0.g, -d0.b };
affine_move(v, u);
point3d d = { d1.r - d0.r, d1.g - d0.g, d1.b - d0.b };
double xy_angle = -atan2(d.g, d.r);
affine_rotationxy(v, xy_angle);
double tr = d.r * cos(xy_angle) - d.g * sin(xy_angle);
double tg = d.r * sin(xy_angle) + d.g * cos(xy_angle);
d = { tr, tg, d.b };
double xz_angle = -atan2(d.b, d.r);
affine_rotationxz(v, xz_angle);
// tr = d.r * cos(xz_angle) - d.b * sin(xz_angle);
// double tb = d.r * sin(xz_angle) + d.b * cos(xz_angle);
// d = { tr, d.g, tb };
// std::cerr << d1.r << " " << d1.g << " " << d1.b << " " << xy_angle << " " << xz_angle << std::endl;
// assert(abs(d.g) < 0.0001 && abs(d.b) < 0.0001);
affine_scale(v);
point3d m = {0.5, 0.5, 0.5};
/*
double maxr = std::max_element(v.begin(), v.end(), [](zip a, zip b){return a.f.r<b.f.r;})->f.r;
double minr = std::min_element(v.begin(), v.end(), [](zip a, zip b){return a.f.r<b.f.r;})->f.r;
double maxg = std::max_element(v.begin(), v.end(), [](zip a, zip b){return a.f.g<b.f.g;})->f.g;
double ming = std::min_element(v.begin(), v.end(), [](zip a, zip b){return a.f.g<b.f.g;})->f.g;
double maxb = std::max_element(v.begin(), v.end(), [](zip a, zip b){return a.f.b<b.f.b;})->f.b;
double minb = std::max_element(v.begin(), v.end(), [](zip a, zip b){return a.f.b<b.f.b;})->f.b;
point3d m = { (maxr+minr)/2., (maxg+ming)/2., (maxb+minb)/2. };
*/
std::sort(v.begin(), v.end(), [&](zip a, zip b){return dist2(a.f, m) < dist2(b.f, m);});
}
Magick::Image petunin_filter(mapped_image& image, int radius){
Magick::Image filtered_image(Magick::Geometry(image.get_width(), image.get_height()), "white");
int column = 0, row = 0;
kernel petunin_kernel(image, radius, column, 0);
while (column < image.get_width()){
while (row < image.get_height()){
// std::cerr << row << std::endl;
point3d d0, d1;
auto t = petunin_kernel.get_diameter();
d0 = std::get<0>(t), d1 = std::get<1>(t);
// std::cerr << std::setprecision(6) << std::fixed << std::get<2>(t) << std::endl;
std::vector<zip> v = petunin_kernel.to_zipped();
petunin_order(v, d0, d1);
point3d mid = v[0].s;
int r = mid.r, g = mid.g, b = mid.b;
filtered_image.pixelColor(column, row, Magick::Color(r, g, b));
petunin_kernel.move_down();
row++;
}
row = 0;
column++;
petunin_kernel.move_to(column, row);
}
return filtered_image;
}
int main(int argc, char* argv[]){
#ifdef IMG_DEBUG
mapped_image image("a.bmp");
Magick::Image filtered_image = petunin_filter(image, 7);
filtered_image.magick("PNG");
filtered_image.write("filtered_a");
#endif
if (argc != 4)
return 0;
int kernel_size = std::atoi(argv[3]);
mapped_image image(argv[1]);
Magick::Image filtered_image = petunin_filter(image, kernel_size);
filtered_image.magick("PNG");
filtered_image.write(argv[2]);
return 0;
}
|
e055328f579355e450f6999cbf8beb250d9d312e
|
1e49fa19e10c5e3a610960d6017196ebaac9b552
|
/cheats/menu.cpp
|
801c4fbe28237727e20141d483eb34cd120ddfd3
|
[
"Unlicense"
] |
permissive
|
Aholicknight/Legendware-V3
|
6504a28892eb29e941b67ac9e3feb906fba87e5f
|
de63ad96fe233f81c5952c327469239de223f08c
|
refs/heads/main
| 2023-01-13T19:28:56.868371
| 2020-11-19T13:31:37
| 2020-11-19T13:31:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 91,308
|
cpp
|
menu.cpp
|
#include <ShlObj_core.h>
#include "menu.h"
#include "../ImGui/code_editor.h"
#include "../constchars.h"
#include "../cheats/misc/logs.h"
#define ALPHA (ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaBar| ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_Float)
#define NOALPHA (ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_Float)
// TODO: crypt_str check for all strings
std::vector <std::string> files;
std::vector <std::string> scripts;
int selected_script = 0;
static bool menu_setupped = false;
IDirect3DTexture9* all_skins[36];
std::string get_wep(int id, int custom_index = -1, bool knife = true)
{
if (custom_index > -1)
{
if (knife)
{
switch (custom_index)
{
case 0: return "weapon_knife";
case 1: return "weapon_bayonet";
case 2: return "weapon_knife_css";
case 3: return "weapon_knife_skeleton";
case 4: return "weapon_knife_outdoor";
case 5: return "weapon_knife_cord";
case 6: return "weapon_knife_canis";
case 7: return "weapon_knife_flip";
case 8: return "weapon_knife_gut";
case 9: return "weapon_knife_karambit";
case 10: return "weapon_knife_m9_bayonet";
case 11: return "weapon_knife_tactical";
case 12: return "weapon_knife_falchion";
case 13: return "weapon_knife_survival_bowie";
case 14: return "weapon_knife_butterfly";
case 15: return "weapon_knife_push";
case 16: return "weapon_knife_ursus";
case 17: return "weapon_knife_gypsy_jackknife";
case 18: return "weapon_knife_stiletto";
case 19: return "weapon_knife_widowmaker";
}
}
else
{
switch (custom_index)
{
case 0: return "ct_gloves";
case 1: return "studded_bloodhound_gloves";
case 2: return "t_gloves";
case 3: return "ct_gloves";
case 4: return "sporty_gloves";
case 5: return "slick_gloves";
case 6: return "leather_handwraps";
case 7: return "motorcycle_gloves";
case 8: return "specialist_gloves";
case 9: return "studded_hydra_gloves";
}
}
}
else
{
switch (id)
{
case 0: return "knife";
case 1: return "gloves";
case 2: return "weapon_ak47";
case 3: return "weapon_aug";
case 4: return "weapon_awp";
case 5: return "weapon_cz75a";
case 6: return "weapon_deagle";
case 7: return "weapon_elite";
case 8: return "weapon_famas";
case 9: return "weapon_fiveseven";
case 10: return "weapon_g3sg1";
case 11: return "weapon_galilar";
case 12: return "weapon_glock";
case 13: return "weapon_m249";
case 14: return "weapon_m4a1_silencer";
case 15: return "weapon_m4a1";
case 16: return "weapon_mac10";
case 17: return "weapon_mag7";
case 18: return "weapon_mp5sd";
case 19: return "weapon_mp7";
case 20: return "weapon_mp9";
case 21: return "weapon_negev";
case 22: return "weapon_nova";
case 23: return "weapon_hkp2000";
case 24: return "weapon_p250";
case 25: return "weapon_p90";
case 26: return "weapon_bizon";
case 27: return "weapon_revolver";
case 28: return "weapon_sawedoff";
case 29: return "weapon_scar20";
case 30: return "weapon_ssg08";
case 31: return "weapon_sg556";
case 32: return "weapon_tec9";
case 33: return "weapon_ump45";
case 34: return "weapon_usp_silencer";
case 35: return "weapon_xm1014";
default: return "unknown";
}
}
}
IDirect3DTexture9* get_skin_preview(const char* weapon_name, std::string skin_name, IDirect3DDevice9* device)
{
IDirect3DTexture9* skin_image = nullptr;
if (!skin_image)
{
std::string vpk_path;
if (strcmp(weapon_name, "unknown") && strcmp(weapon_name, "knife") && strcmp(weapon_name, "gloves"))
{
if (skin_name == "" || skin_name == "default")
vpk_path = "resource/flash/econ/weapons/base_weapons/" + std::string(weapon_name) + ".png";
else
vpk_path = "resource/flash/econ/default_generated/" + std::string(weapon_name) + "_" + std::string(skin_name) + "_light_large.png";
}
else
{
if (!strcmp(weapon_name, "knife"))
vpk_path = "resource/flash/econ/weapons/base_weapons/weapon_knife.png";
else if (!strcmp(weapon_name, "gloves"))
vpk_path = "resource/flash/econ/weapons/base_weapons/ct_gloves.png";
else if (!strcmp(weapon_name, "unknown"))
vpk_path = "resource/flash/econ/weapons/base_weapons/weapon_snowball.png";
}
const auto handle = m_basefilesys()->Open(vpk_path.c_str(), "r", "GAME");
if (handle)
{
int file_len = m_basefilesys()->Size(handle);
char* image = new char[file_len];
m_basefilesys()->Read(image, file_len, handle);
m_basefilesys()->Close(handle);
D3DXCreateTextureFromFileInMemory(device, image, file_len, &skin_image);
delete[] image;
}
}
if (skin_image != nullptr)
return skin_image;
else if (!skin_image)
{
std::string vpk_path;
if (strstr(weapon_name, "bloodhound") != NULL || strstr(weapon_name, "hydra") != NULL)
vpk_path = "resource/flash/econ/weapons/base_weapons/ct_gloves.png";
else
vpk_path = "resource/flash/econ/weapons/base_weapons/" + std::string(weapon_name) + ".png";
const auto handle = m_basefilesys()->Open(vpk_path.c_str(), "r", "GAME");
if (handle)
{
int file_len = m_basefilesys()->Size(handle);
char* image = new char[file_len];
m_basefilesys()->Read(image, file_len, handle);
m_basefilesys()->Close(handle);
D3DXCreateTextureFromFileInMemory(device, image, file_len, &skin_image);
delete[] image;
}
}
return skin_image;
}
// setup some styles and colors, window size and bg alpha
// dpi setup
void c_menu::menu_setup(ImGuiStyle &style)
{
ImGui::StyleColorsClassic(); // colors setup
ImGui::SetNextWindowSize(ImVec2(width, height), ImGuiCond_Once); // window pos setup
ImGui::SetNextWindowBgAlpha(min(style.Alpha, 0.94f)); // window bg alpha setup
styles.WindowPadding = style.WindowPadding;
styles.WindowRounding = style.WindowRounding;
styles.WindowMinSize = style.WindowMinSize;
styles.ChildRounding = style.ChildRounding;
styles.PopupRounding = style.PopupRounding;
styles.FramePadding = style.FramePadding;
styles.FrameRounding = style.FrameRounding;
styles.ItemSpacing = style.ItemSpacing;
styles.ItemInnerSpacing = style.ItemInnerSpacing;
styles.TouchExtraPadding = style.TouchExtraPadding;
styles.IndentSpacing = style.IndentSpacing;
styles.ColumnsMinSpacing = style.ColumnsMinSpacing;
styles.ScrollbarSize = style.ScrollbarSize;
styles.ScrollbarRounding = style.ScrollbarRounding;
styles.GrabMinSize = style.GrabMinSize;
styles.GrabRounding = style.GrabRounding;
styles.TabRounding = style.TabRounding;
styles.TabMinWidthForUnselectedCloseButton = style.TabMinWidthForUnselectedCloseButton;
styles.DisplayWindowPadding = style.DisplayWindowPadding;
styles.DisplaySafeAreaPadding = style.DisplaySafeAreaPadding;
styles.MouseCursorScale = style.MouseCursorScale;
// setup skins preview
for (auto i = 0; i < g_cfg.skins.skinChanger.size(); i++)
{
if (all_skins[i] == nullptr)
all_skins[i] = get_skin_preview(get_wep(i, (i == 0 || i == 1) ? g_cfg.skins.skinChanger.at(i).definition_override_vector_index : -1, i == 0).c_str(), g_cfg.skins.skinChanger.at(i).skin_name, device);
}
dpi_scale = max(1, ImGui::GetIO().DisplaySize.y / 1080);
update_dpi = true;
menu_setupped = true; // we dont want to setup menu again
}
// resize current style sizes
void c_menu::dpi_resize(float scale_factor, ImGuiStyle &style)
{
style.WindowPadding = (styles.WindowPadding * scale_factor);
style.WindowRounding = (styles.WindowRounding * scale_factor);
style.WindowMinSize = (styles.WindowMinSize * scale_factor);
style.ChildRounding = (styles.ChildRounding * scale_factor);
style.PopupRounding = (styles.PopupRounding * scale_factor);
style.FramePadding = (styles.FramePadding * scale_factor);
style.FrameRounding = (styles.FrameRounding * scale_factor);
style.ItemSpacing = (styles.ItemSpacing * scale_factor);
style.ItemInnerSpacing = (styles.ItemInnerSpacing * scale_factor);
style.TouchExtraPadding = (styles.TouchExtraPadding * scale_factor);
style.IndentSpacing = (styles.IndentSpacing * scale_factor);
style.ColumnsMinSpacing = (styles.ColumnsMinSpacing * scale_factor);
style.ScrollbarSize = (styles.ScrollbarSize * scale_factor);
style.ScrollbarRounding = (styles.ScrollbarRounding * scale_factor);
style.GrabMinSize = (styles.GrabMinSize * scale_factor);
style.GrabRounding = (styles.GrabRounding * scale_factor);
style.TabRounding = (styles.TabRounding * scale_factor);
if (styles.TabMinWidthForUnselectedCloseButton != FLT_MAX)
style.TabMinWidthForUnselectedCloseButton = (styles.TabMinWidthForUnselectedCloseButton * scale_factor);
style.DisplayWindowPadding = (styles.DisplayWindowPadding * scale_factor);
style.DisplaySafeAreaPadding = (styles.DisplaySafeAreaPadding * scale_factor);
style.MouseCursorScale = (styles.MouseCursorScale * scale_factor);
}
std::string get_config_dir()
{
std::string folder;
static TCHAR path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, 0x001a, NULL, NULL, path)))
folder = std::string(path) + crypt_str("\\Legendware\\Configs\\");
CreateDirectory(folder.c_str(), NULL);
return folder;
}
void load_config()
{
if (cfg_manager->files.empty())
return;
cfg_manager->load(cfg_manager->files.at(g_cfg.selected_config), false);
c_lua::get().unload_all_scripts();
for (auto& script : g_cfg.scripts.scripts)
c_lua::get().load_script(c_lua::get().get_script_id(script));
scripts = c_lua::get().scripts;
if (selected_script >= scripts.size())
selected_script = scripts.size() - 1;
for (auto& current : scripts)
{
if (current.size() >= 5 && current.at(current.size() - 1) == 'c')
current.erase(current.size() - 5, 5);
else if (current.size() >= 4)
current.erase(current.size() - 4, 4);
}
g_cfg.scripts.scripts.clear();
cfg_manager->load(cfg_manager->files.at(g_cfg.selected_config), true);
cfg_manager->config_files();
eventlogs::get().add(crypt_str("Loaded ") + files.at(g_cfg.selected_config) + crypt_str(" config"), false);
}
void save_config()
{
if (cfg_manager->files.empty())
return;
g_cfg.scripts.scripts.clear();
for (auto i = 0; i < c_lua::get().scripts.size(); ++i)
{
auto script = c_lua::get().scripts.at(i);
if (c_lua::get().loaded.at(i))
g_cfg.scripts.scripts.emplace_back(script);
}
cfg_manager->save(cfg_manager->files.at(g_cfg.selected_config));
cfg_manager->config_files();
eventlogs::get().add(crypt_str("Saved ") + files.at(g_cfg.selected_config) + crypt_str(" config"), false);
}
void remove_config()
{
if (cfg_manager->files.empty())
return;
eventlogs::get().add(crypt_str("Removed ") + files.at(g_cfg.selected_config) + crypt_str(" config"), false);
cfg_manager->remove(cfg_manager->files.at(g_cfg.selected_config));
cfg_manager->config_files();
files = cfg_manager->files;
if (g_cfg.selected_config >= files.size())
g_cfg.selected_config = files.size() - 1;
for (auto& current : files)
if (current.size() > 2)
current.erase(current.size() - 3, 3);
}
void add_config()
{
auto empty = true;
for (auto current : g_cfg.new_config_name)
{
if (current != ' ')
{
empty = false;
break;
}
}
if (empty)
g_cfg.new_config_name = crypt_str("config");
eventlogs::get().add(crypt_str("Added ") + g_cfg.new_config_name + crypt_str(" config"), false);
if (g_cfg.new_config_name.find(crypt_str(".lw")) == std::string::npos)
g_cfg.new_config_name += crypt_str(".lw");
cfg_manager->save(g_cfg.new_config_name);
cfg_manager->config_files();
g_cfg.selected_config = cfg_manager->files.size() - 1;
files = cfg_manager->files;
for (auto& current : files)
if (current.size() > 2)
current.erase(current.size() - 3, 3);
}
__forceinline void padding(float x, float y)
{
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + x * c_menu::get().dpi_scale);
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + y * c_menu::get().dpi_scale);
}
// title of content child
void child_title(const char* label)
{
ImGui::PushFont(c_menu::get().futura_large);
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.f, 1.f, 1.f, 1.f));
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (12 * c_menu::get().dpi_scale));
ImGui::Text(label);
ImGui::PopStyleColor();
ImGui::PopFont();
}
void draw_combo(const char* name, int& variable, const char* labels[], int count)
{
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 6 * c_menu::get().dpi_scale);
ImGui::Text(name);
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 5 * c_menu::get().dpi_scale);
ImGui::Combo(std::string("##COMBO__" + std::string(name)).c_str(), &variable, labels, count);
}
void draw_multicombo(const char* name, std::vector<int>& variable, const char* labels[], int count, std::string &preview )
{
padding(-3, -6);
ImGui::Text((" " + (std::string)name).c_str());
padding(0, -5);
std::string hashname = "##" + std::string(name); // we dont want to render name of combo
for (auto i = 0, j = 0; i < count; i++)
{
if (variable[i])
{
if (j)
preview += crypt_str(", ") + (std::string)labels[i];
else
preview = labels[i];
j++;
}
}
if (ImGui::BeginCombo(crypt_str(hashname.c_str()), preview.c_str())) // draw start
{
ImGui::Spacing();
ImGui::BeginGroup();
{
for (auto i = 0; i < count; i++)
ImGui::Selectable(labels[i], (bool*)&variable[i], ImGuiSelectableFlags_DontClosePopups);
}
ImGui::EndGroup();
ImGui::Spacing();
ImGui::EndCombo();
}
preview = crypt_str("None"); // reset preview to use later
}
bool LabelClick(const char* label, bool* v, const char* unique_id)
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return false;
// The concatoff/on thingies were for my weapon config system so if we're going to make that, we still need this aids.
char Buf[64];
_snprintf(Buf, 62, crypt_str("%s"), label);
char getid[128];
sprintf_s(getid, 128, crypt_str("%s%s"), label, unique_id);
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(getid);
const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true);
const ImRect check_bb(window->DC.CursorPos, ImVec2(label_size.y + style.FramePadding.y * 2 + window->DC.CursorPos.x, window->DC.CursorPos.y + label_size.y + style.FramePadding.y * 2));
ImGui::ItemSize(check_bb, style.FramePadding.y);
ImRect total_bb = check_bb;
if (label_size.x > 0)
{
ImGui::SameLine(0, style.ItemInnerSpacing.x);
const ImRect text_bb(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), ImVec2(window->DC.CursorPos.x + label_size.x, window->DC.CursorPos.y + style.FramePadding.y + label_size.y));
ImGui::ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max));
}
if (!ImGui::ItemAdd(total_bb, id))
return false;
bool hovered, held;
bool pressed = ImGui::ButtonBehavior(total_bb, id, &hovered, &held);
if (pressed)
*v = !(*v);
if (*v)
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(126 / 255.f, 131 / 255.f, 219 / 255.f, 1.f));
if (label_size.x > 0.0f)
ImGui::RenderText(ImVec2(check_bb.GetTL().x + 12, check_bb.GetTL().y), Buf);
if (*v)
ImGui::PopStyleColor();
return pressed;
}
void draw_keybind(const char* label, key_bind* key_bind, const char* unique_id)
{
// reset bind if we re pressing esc
if (key_bind->key == KEY_ESCAPE)
key_bind->key = KEY_NONE;
auto clicked = false;
auto text = (std::string)m_inputsys()->ButtonCodeToString(key_bind->key);
if (key_bind->key <= KEY_NONE || key_bind->key >= KEY_MAX)
text = crypt_str("None");
// if we clicked on keybind
if (hooks::input_shouldListen && hooks::input_receivedKeyval == &key_bind->key)
{
clicked = true;
text = crypt_str("...");
}
auto textsize = ImGui::CalcTextSize(text.c_str()).x + 8 * c_menu::get().dpi_scale;
auto labelsize = ImGui::CalcTextSize(label);
ImGui::Text(label);
ImGui::SameLine();
ImGui::SetCursorPosX(ImGui::GetWindowSize().x - (ImGui::GetWindowSize().x - ImGui::CalcItemWidth()) - max(50 * c_menu::get().dpi_scale, textsize));
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 3 * c_menu::get().dpi_scale);
if (ImGui::KeybindButton(text.c_str(), unique_id, ImVec2(max(50 * c_menu::get().dpi_scale, textsize), 23 * c_menu::get().dpi_scale), clicked))
clicked = true;
if (clicked)
{
hooks::input_shouldListen = true;
hooks::input_receivedKeyval = &key_bind->key;
}
static auto hold = false, toggle = false;
switch (key_bind->mode)
{
case HOLD:
hold = true;
toggle = false;
break;
case TOGGLE:
toggle = true;
hold = false;
break;
}
if (ImGui::BeginPopup(unique_id))
{
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 6 * c_menu::get().dpi_scale);
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ((ImGui::GetCurrentWindow()->Size.x / 2) - (ImGui::CalcTextSize("Hold").x / 2)));
ImGui::SetCursorPosX(ImGui::GetCursorPosX() - 11);
if (LabelClick(crypt_str("Hold"), &hold, unique_id))
{
if (hold)
{
toggle = false;
key_bind->mode = HOLD;
}
else if (toggle)
{
hold = false;
key_bind->mode = TOGGLE;
}
else
{
toggle = false;
key_bind->mode = HOLD;
}
ImGui::CloseCurrentPopup();
}
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ((ImGui::GetCurrentWindow()->Size.x / 2) - (ImGui::CalcTextSize("Toggle").x / 2)));
ImGui::SetCursorPosX(ImGui::GetCursorPosX() - 11);
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 9 * c_menu::get().dpi_scale);
if (LabelClick(crypt_str("Toggle"), &toggle, unique_id))
{
if (toggle)
{
hold = false;
key_bind->mode = TOGGLE;
}
else if (hold)
{
toggle = false;
key_bind->mode = HOLD;
}
else
{
hold = false;
key_bind->mode = TOGGLE;
}
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
void draw_semitabs(const char* labels[], int count, int &tab, ImGuiStyle style)
{
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - (2 * c_menu::get().dpi_scale));
// center of main child
float offset = 343 * c_menu::get().dpi_scale;
// text size padding + frame padding
for (int i = 0; i < count; i++)
offset -= (ImGui::CalcTextSize(labels[i]).x) / 2 + style.FramePadding.x * 2;
// set new padding
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offset);
ImGui::BeginGroup();
for (int i = 0; i < count; i++)
{
// switch current tab
if (ImGui::ContentTab(labels[i], tab == i))
tab = i;
// continue drawing on same line
if (i + 1 != count)
{
ImGui::SameLine();
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + style.ItemSpacing.x);
}
}
ImGui::EndGroup();
}
__forceinline void tab_start()
{
ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX() + (20 * c_menu::get().dpi_scale), ImGui::GetCursorPosY() + (5 * c_menu::get().dpi_scale)));
}
__forceinline void tab_end()
{
ImGui::PopStyleVar();
ImGui::SetWindowFontScale(c_menu::get().dpi_scale);
}
// TODO: do it for every script
void lua_edit(std::string window_name)
{
const char* child_name = (window_name + window_name).c_str();
ImGui::SetNextWindowSize(ImVec2(700, 600), ImGuiCond_Once);
ImGui::Begin(window_name.c_str(), nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse);
ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 5.f);
static bool load = false;
static TextEditor editor;
if (!load)
{
auto lang = TextEditor::LanguageDefinition::Lua();
editor.SetLanguageDefinition(lang);
editor.SetReadOnly(false);
// TODO: get correct path to lua file (now it's Counter Strike../lua/..)
static const char* fileToEdit = "lua/kon_utils.lua";
{
std::ifstream t(fileToEdit);
if (t.good()) // does while exist?
{
std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
editor.SetText(str); // setup script content
}
}
load = true;
}
// dpi scale for font
// we dont need to resize it for full scale
ImGui::SetWindowFontScale(1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f));
// new size depending on dpi scale
ImGui::SetWindowSize(ImVec2(ImFloor(800 * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f))), ImFloor(700 * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f)))));
editor.Render(child_name, ImGui::GetWindowSize() - ImVec2(0, 66 * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f))));
// seperate code with buttons
ImGui::Separator();
// set cursor pos to right edge of window
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetWindowSize().x - (16.f * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f))) - (250.f * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f))));
ImGui::BeginGroup();
if (ImGui::CustomButton("Save", ("Save" + window_name).c_str(), ImVec2(125 * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f)), 0), true, c_menu::get().ico_bottom, "S"))
{
std::ofstream out;
// TODO: correct file path
out.open("lua/kon_utils.lua");
out << editor.GetText() << std::endl;
out.close();
}
ImGui::SameLine();
// TOOD: close button will close window (return in start of function)
if (ImGui::CustomButton("Close", ("Close" + window_name).c_str(), ImVec2(125 * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f)), 0)))
{
}
ImGui::EndGroup();
ImGui::PopStyleVar();
ImGui::End();
}
// SEMITABS FUNCTIONS
void c_menu::draw_tabs_ragebot()
{
const char* rage_sections[2] = { "General", "Weapon" };
draw_semitabs(rage_sections, 2, rage_section, ImGui::GetStyle());
}
void c_menu::draw_ragebot(int child)
{
if (!rage_section)
{
if (!child)
{
child_title("Ragebot");
tab_start();
ImGui::BeginChild("##RAGE1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Enable"), &g_cfg.ragebot.enable);
if (g_cfg.ragebot.enable)
g_cfg.legitbot.enabled = false;
ImGui::SliderInt(crypt_str("Field of view"), &g_cfg.ragebot.field_of_view, 1, 180);
ImGui::Checkbox(crypt_str("Silent aim"), &g_cfg.ragebot.silent_aim);
ImGui::Checkbox(crypt_str("Automatic wall"), &g_cfg.ragebot.autowall);
ImGui::Checkbox(crypt_str("Aimbot with zeus"), &g_cfg.ragebot.zeus_bot);
ImGui::Checkbox(crypt_str("Aimbot with knife"), &g_cfg.ragebot.knife_bot);
ImGui::Checkbox(crypt_str("Automatic fire"), &g_cfg.ragebot.autoshoot);
ImGui::Checkbox(crypt_str("Automatic scope"), &g_cfg.ragebot.autoscope);
ImGui::Checkbox(crypt_str("Pitch desync correction"), &g_cfg.ragebot.pitch_antiaim_correction);
ImGui::Spacing();
ImGui::Checkbox(crypt_str("Double tap"), &g_cfg.ragebot.double_tap);
if (g_cfg.ragebot.double_tap)
{
ImGui::SameLine();
draw_keybind("", &g_cfg.ragebot.double_tap_key, "##HOTKEY_DT");
ImGui::Checkbox(crypt_str("Slow teleport"), &g_cfg.ragebot.slow_teleport);
}
ImGui::Checkbox(crypt_str("Hide shots"), &g_cfg.antiaim.hide_shots);
if (g_cfg.antiaim.hide_shots)
{
ImGui::SameLine();
draw_keybind("", &g_cfg.antiaim.hide_shots_key, "##HOTKEY_HIDESHOTS");
}
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Anti-aim");
tab_start();
ImGui::BeginChild("##RAGE2_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
static auto type = 0;
ImGui::Checkbox(crypt_str("Enable"), &g_cfg.antiaim.enable);
draw_combo(crypt_str("Anti-aim type"), g_cfg.antiaim.antiaim_type, antiaim_type, ARRAYSIZE(antiaim_type));
if (g_cfg.antiaim.antiaim_type)
{
padding(0, 3);
draw_combo(crypt_str("Desync"), g_cfg.antiaim.desync, desync, ARRAYSIZE(desync));
if (g_cfg.antiaim.desync)
{
padding(0, 3);
draw_combo(crypt_str("LBY type"), g_cfg.antiaim.legit_lby_type, lby_type, ARRAYSIZE(lby_type));
if (g_cfg.antiaim.desync == 1)
{
draw_keybind("Invert desync", &g_cfg.antiaim.flip_desync, "##HOTKEY_INVERT_DESYNC");
}
}
}
else
{
draw_combo(crypt_str("Movement type"), type, movement_type, ARRAYSIZE(movement_type));
padding(0, 3);
draw_combo(crypt_str("Pitch"), g_cfg.antiaim.type[type].pitch, pitch, ARRAYSIZE(pitch));
padding(0, 3);
draw_combo(crypt_str("Yaw"), g_cfg.antiaim.type[type].yaw, yaw, ARRAYSIZE(yaw));
padding(0, 3);
draw_combo(crypt_str("Base angle"), g_cfg.antiaim.type[type].base_angle, baseangle, ARRAYSIZE(baseangle));
if (g_cfg.antiaim.type[type].yaw)
{
ImGui::SliderInt(g_cfg.antiaim.type[type].yaw == 1 ? crypt_str("Jitter range") : crypt_str("Spin range"), &g_cfg.antiaim.type[type].range, 1, 180);
if (g_cfg.antiaim.type[type].yaw == 2)
ImGui::SliderInt(crypt_str("Spin speed"), &g_cfg.antiaim.type[type].speed, 1, 15);
padding(0, 3);
}
draw_combo(crypt_str("Desync"), g_cfg.antiaim.type[type].desync, desync, ARRAYSIZE(desync));
if (g_cfg.antiaim.type[type].desync)
{
if (type == ANTIAIM_STAND)
{
padding(0, 3);
draw_combo(crypt_str("LBY type"), g_cfg.antiaim.lby_type, lby_type, ARRAYSIZE(lby_type));
}
if (type != ANTIAIM_STAND || !g_cfg.antiaim.lby_type)
{
ImGui::SliderInt(crypt_str("Desync range"), &g_cfg.antiaim.type[type].desync_range, 1, 100, "%.0f%%");
ImGui::SliderInt(crypt_str("Body lean"), &g_cfg.antiaim.type[type].body_lean, 0, 100);
ImGui::SliderInt(crypt_str("Inverted body lean"), &g_cfg.antiaim.type[type].inverted_body_lean, 0, 100);
}
if (g_cfg.antiaim.type[type].desync == 1)
{
draw_keybind("Invert desync", &g_cfg.antiaim.flip_desync, "##HOTKEY_INVERT_DESYNC");
}
}
draw_keybind("Manual back", &g_cfg.antiaim.manual_back, "##HOTKEY_INVERT_BACK");
draw_keybind("Manual left", &g_cfg.antiaim.manual_left, "##HOTKEY_INVERT_LEFT");
draw_keybind("Manual right", &g_cfg.antiaim.manual_right, "##HOTKEY_INVERT_RIGHT");
if (g_cfg.antiaim.manual_back.key > KEY_NONE && g_cfg.antiaim.manual_back.key < KEY_MAX || g_cfg.antiaim.manual_left.key > KEY_NONE && g_cfg.antiaim.manual_left.key < KEY_MAX || g_cfg.antiaim.manual_right.key > KEY_NONE && g_cfg.antiaim.manual_right.key < KEY_MAX)
{
ImGui::Checkbox(crypt_str("Manuals indicator"), &g_cfg.antiaim.flip_indicator);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##invc"), &g_cfg.antiaim.flip_indicator_color, ALPHA);
}
}
}
ImGui::EndChild();
tab_end();
}
}
else
{
static int rage_weapon = 0;
const char* rage_weapons[8] = { "R8 & Deagle", "Pistols", "SMGs", "Rifles", "Auto snipers", "Scout", "AWP", "Heavy" };
if (!child)
{
child_title("General");
tab_start();
ImGui::BeginChild("##RAGE1_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Spacing();
draw_combo(crypt_str("Current weapon"), rage_weapon, rage_weapons, ARRAYSIZE(rage_weapons));
ImGui::Spacing();
draw_combo(crypt_str("Target selection"), g_cfg.ragebot.weapon[rage_weapon].selection_type, selection, ARRAYSIZE(selection));
padding(0, 3);
draw_multicombo(crypt_str("Hitboxes"), g_cfg.ragebot.weapon[rage_weapon].hitscan, hitboxes, ARRAYSIZE(hitboxes), preview);
// TODO: Uncomment me
//ImGui::Checkbox(crypt_str("Enable max misses"), &g_cfg.ragebot.weapon[rage_weapon].max_misses);
//
//if (g_cfg.ragebot.weapon[rage_weapon].max_misses)
// ImGui::SliderInt("Max misses", &g_cfg.ragebot.weapon[rage_weapon].max_misses_amount, 0, 6);
//ImGui::Checkbox(crypt_str("Prefer safe points"), &g_cfg.ragebot.weapon[rage_weapon].prefer_safe_points);
//ImGui::Checkbox(crypt_str("Prefer body aim"), &g_cfg.ragebot.weapon[rage_weapon].prefer_body_aim);
//draw_keybind("Force safe points", &g_cfg.ragebot.safe_point_key, "##HOKEY_FORCE_SAFE_POINTS");
draw_keybind("Force body aim", &g_cfg.ragebot.baim_key, "##HOKEY_FORCE_BODY_AIM");
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Accuracy");
tab_start();
ImGui::BeginChild("##RAGE2_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
// TODO: проверь, чтобы все настройки тут были из обычного меню текущего
ImGui::Checkbox(crypt_str("Automatic stop"), &g_cfg.ragebot.weapon[rage_weapon].autostop);
if (g_cfg.ragebot.weapon[rage_weapon].autostop)
draw_multicombo("Modifiers", g_cfg.ragebot.weapon[rage_weapon].autostop_modifiers, autostop_modifiers, ARRAYSIZE(autostop_modifiers), preview);
ImGui::Checkbox(crypt_str("Hitchance"), &g_cfg.ragebot.weapon[rage_weapon].hitchance);
if (g_cfg.ragebot.weapon[rage_weapon].hitchance)
ImGui::SliderInt(crypt_str("Hitchance amount"), &g_cfg.ragebot.weapon[rage_weapon].hitchance_amount, 1, 100);
if (g_cfg.ragebot.double_tap && rage_weapon <= 4)
{
ImGui::Checkbox(crypt_str("Double tap hitchance"), &g_cfg.ragebot.weapon[rage_weapon].double_tap_hitchance);
if (g_cfg.ragebot.weapon[rage_weapon].double_tap_hitchance)
ImGui::SliderInt(crypt_str("Double tap hitchance amount"), &g_cfg.ragebot.weapon[rage_weapon].double_tap_hitchance_amount, 1, 100);
}
ImGui::SliderInt(crypt_str("Minimum visible damage"), &g_cfg.ragebot.weapon[rage_weapon].minimum_visible_damage, 1, 120);
if (g_cfg.ragebot.autowall)
ImGui::SliderInt(crypt_str("Minimum wall damage"), &g_cfg.ragebot.weapon[rage_weapon].minimum_damage, 1, 120);
draw_keybind("Damage override", &g_cfg.ragebot.weapon[rage_weapon].damage_override_key, "##HOTKEY__DAMAGE_OVERRIDE");
if (g_cfg.ragebot.weapon[rage_weapon].damage_override_key.key > KEY_NONE && g_cfg.ragebot.weapon[rage_weapon].damage_override_key.key < KEY_MAX)
ImGui::SliderInt(crypt_str("Minimum override damage"), &g_cfg.ragebot.weapon[rage_weapon].minimum_override_damage, 1, 120);
}
ImGui::EndChild();
tab_end();
}
}
}
/*
struct weapon_t
{
int awall_dmg;
float target_switch_delay;
} weapon[8];
*/
void c_menu::draw_tabs_legit()
{
const char* legit_sections[1] = { "General" };
draw_semitabs(legit_sections, 1, legit_section, ImGui::GetStyle());
}
void c_menu::draw_legit(int child)
{
static int legit_weapon = 0;
const char* legit_weapons[6] = { "Deagle", "Pistols", "Rifles", "SMGs", "Sniper", "Heavy" };
const char* hitbox_legit[3] = { "Nearest", "Head", "Body" };
if (!child)
{
child_title("Legitbot");
tab_start();
ImGui::BeginChild("##RAGE1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
padding(0, 6);
ImGui::Checkbox(crypt_str("Enabled"), &g_cfg.legitbot.enabled);
ImGui::SameLine();
draw_keybind(crypt_str(""), &g_cfg.legitbot.key, crypt_str("##HOTKEY_LGBT_KEY"));
if (g_cfg.legitbot.enabled)
g_cfg.ragebot.enable = false;
ImGui::Checkbox(crypt_str("Friendly fire"), &g_cfg.legitbot.friendly_fire);
ImGui::Checkbox(crypt_str("Auto pistols"), &g_cfg.legitbot.autopistol);
ImGui::Checkbox(crypt_str("Auto scope"), &g_cfg.legitbot.autoscope);
if (g_cfg.legitbot.autoscope)
ImGui::Checkbox(crypt_str("Unscope after shot"), &g_cfg.legitbot.unscope);
ImGui::Checkbox(crypt_str("Sniper in zoom only"), &g_cfg.legitbot.sniper_in_zoom_only);
ImGui::Checkbox(crypt_str("Scan in air"), &g_cfg.legitbot.do_if_local_in_air);
ImGui::Checkbox(crypt_str("Scan if flashed"), &g_cfg.legitbot.do_if_local_flashed);
ImGui::Checkbox(crypt_str("Scan in smoke"), &g_cfg.legitbot.do_if_enemy_in_smoke);
draw_keybind(crypt_str("Autofire key"), &g_cfg.legitbot.autofire_key, crypt_str("##HOTKEY_AUTOFIRE_LGBT_KEY"));
ImGui::SliderInt(crypt_str("Autofire delay"), &g_cfg.legitbot.autofire_delay, 0, 12, (!g_cfg.legitbot.autofire_delay ? "No" : (g_cfg.legitbot.autofire_delay == 1 ? "%dtick" : "%dticks")));
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Weapon settings");
tab_start();
ImGui::BeginChild("##RAGE1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Spacing();
draw_combo(crypt_str("Weapon preset"), legit_weapon, legit_weapons, ARRAYSIZE(legit_weapons));
ImGui::Spacing();
draw_combo(crypt_str("Hitbox"), g_cfg.legitbot.weapon[legit_weapon].priority, hitbox_legit, ARRAYSIZE(hitbox_legit));
ImGui::Checkbox(crypt_str("Auto stop"), &g_cfg.legitbot.weapon[legit_weapon].auto_stop);
draw_combo(crypt_str("Fov type"), g_cfg.legitbot.weapon[legit_weapon].fov_type, LegitFov, ARRAYSIZE(LegitFov));
ImGui::SliderFloat(crypt_str("Fov amount"), &g_cfg.legitbot.weapon[legit_weapon].fov, 0.f, 30.f, "%.2f");
ImGui::Spacing();
ImGui::SliderFloat(crypt_str("Silent fov"), &g_cfg.legitbot.weapon[legit_weapon].silent_fov, 0.f, 30.f, (!g_cfg.legitbot.weapon[legit_weapon].silent_fov ? "No" : "%.2f"));
ImGui::Spacing();
draw_combo(crypt_str("Smooth type"), g_cfg.legitbot.weapon[legit_weapon].smooth_type, LegitSmooth, ARRAYSIZE(LegitSmooth));
ImGui::SliderFloat(crypt_str("Smooth amount"), &g_cfg.legitbot.weapon[legit_weapon].smooth, 1.f, 12.f, "%.1f");
ImGui::Spacing();
draw_combo(crypt_str("RCS type"), g_cfg.legitbot.weapon[legit_weapon].rcs_type, RCSType, ARRAYSIZE(RCSType));
ImGui::SliderFloat(crypt_str("RCS amount"), &g_cfg.legitbot.weapon[legit_weapon].rcs, 0.f, 100.f, "%.0f%%", 1.f);
if (g_cfg.legitbot.weapon[legit_weapon].rcs > 0)
{
ImGui::SliderFloat(crypt_str("RCS Custom Fov"), &g_cfg.legitbot.weapon[legit_weapon].custom_rcs_fov, 0.f, 30.f, (!g_cfg.legitbot.weapon[legit_weapon].custom_rcs_fov ? "No" : "%.2f"));
ImGui::SliderFloat(crypt_str("RCS Custom Smooth"), &g_cfg.legitbot.weapon[legit_weapon].custom_rcs_smooth, 0.f, 12.f, (!g_cfg.legitbot.weapon[legit_weapon].custom_rcs_smooth ? "No" : "%.1f"));
}
ImGui::Spacing();
ImGui::SliderInt(crypt_str("Autowall damage"), &g_cfg.legitbot.weapon[legit_weapon].awall_dmg, 0, 100, (!g_cfg.legitbot.weapon[legit_weapon].awall_dmg ? "No" : "%d"));
ImGui::SliderInt(crypt_str("Autofire hitchance"), &g_cfg.legitbot.weapon[legit_weapon].autofire_hitchance, 0, 100, (!g_cfg.legitbot.weapon[legit_weapon].autofire_hitchance ? "No" : "%d"));
ImGui::SliderFloat(crypt_str("Target switch delay"), &g_cfg.legitbot.weapon[legit_weapon].target_switch_delay, 0.f, 1.f, "%.3fs");
}
ImGui::EndChild();
tab_end();
}
}
void c_menu::draw_tabs_visuals()
{
const char* visuals_sections[3] = { "General", "Viewmodel", "Skinchanger" };
draw_semitabs(visuals_sections, 3, visuals_section, ImGui::GetStyle());
}
void c_menu::draw_visuals(int child)
{
if (visuals_section != 2)
{
if (!child)
{
if (!visuals_section)
{
child_title("General");
tab_start();
ImGui::BeginChild("##VISUAL1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Enable"), &g_cfg.player.enable);
draw_multicombo("Indicators", g_cfg.esp.indicators, indicators, ARRAYSIZE(indicators), preview);
padding(0, 3);
draw_multicombo("Removals", g_cfg.esp.removals, removals, ARRAYSIZE(removals), preview);
if (g_cfg.esp.removals[REMOVALS_ZOOM])
ImGui::Checkbox(crypt_str("Fix zoom sensivity"), &g_cfg.esp.fix_zoom_sensivity);
ImGui::Checkbox(crypt_str("Grenade prediction"), &g_cfg.esp.grenade_prediction);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##grenpredcolor"), &g_cfg.esp.grenade_prediction_color, ALPHA);
if (g_cfg.esp.grenade_prediction)
{
ImGui::Checkbox(crypt_str("On click"), &g_cfg.esp.on_click);
ImGui::Text(crypt_str("Tracer color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##tracergrenpredcolor"), &g_cfg.esp.grenade_prediction_tracer_color, ALPHA);
}
ImGui::Checkbox(crypt_str("Grenade projectiles"), &g_cfg.esp.projectiles);
if (g_cfg.esp.projectiles)
draw_multicombo("Grenade ESP", g_cfg.esp.grenade_esp, proj_combo, ARRAYSIZE(proj_combo), preview);
if (g_cfg.esp.grenade_esp[GRENADE_ICON] || g_cfg.esp.grenade_esp[GRENADE_TEXT])
{
ImGui::Text(crypt_str("Color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##projectcolor"), &g_cfg.esp.projectiles_color, ALPHA);
}
if (g_cfg.esp.grenade_esp[GRENADE_BOX])
{
ImGui::Text(crypt_str("Box color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##grenade_box_color"), &g_cfg.esp.grenade_box_color, ALPHA);
}
if (g_cfg.esp.grenade_esp[GRENADE_GLOW])
{
ImGui::Text(crypt_str("Glow color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##grenade_glow_color"), &g_cfg.esp.grenade_glow_color, ALPHA);
}
ImGui::Checkbox(crypt_str("Fire timer"), &g_cfg.esp.molotov_timer);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##molotovcolor"), &g_cfg.esp.molotov_timer_color, ALPHA);
ImGui::Checkbox(crypt_str("Bomb indicator"), &g_cfg.esp.bomb_timer);
draw_multicombo("Weapon ESP", g_cfg.esp.weapon, weaponesp, ARRAYSIZE(weaponesp), preview);
if (g_cfg.esp.weapon[WEAPON_ICON] || g_cfg.esp.weapon[WEAPON_TEXT] || g_cfg.esp.weapon[WEAPON_DISTANCE])
{
ImGui::Text(crypt_str("Color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##weaponcolor"), &g_cfg.esp.weapon_color, ALPHA);
}
if (g_cfg.esp.weapon[WEAPON_BOX])
{
ImGui::Text(crypt_str("Box color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##weaponboxcolor"), &g_cfg.esp.box_color, ALPHA);
}
if (g_cfg.esp.weapon[WEAPON_GLOW])
{
ImGui::Text(crypt_str("Glow color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##weaponglowcolor"), &g_cfg.esp.weapon_glow_color, ALPHA);
}
if (g_cfg.esp.weapon[WEAPON_AMMO])
{
ImGui::Text(crypt_str("Ammo bar color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##weaponammocolor"), &g_cfg.esp.weapon_ammo_color, ALPHA);
}
ImGui::Checkbox(crypt_str("Client bullet impacts"), &g_cfg.esp.client_bullet_impacts);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##clientbulletimpacts"), &g_cfg.esp.client_bullet_impacts_color, ALPHA);
ImGui::Checkbox(crypt_str("Server bullet impacts"), &g_cfg.esp.server_bullet_impacts);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##serverbulletimpacts"), &g_cfg.esp.server_bullet_impacts_color, ALPHA);
ImGui::Checkbox(crypt_str("Local bullet tracers"), &g_cfg.esp.bullet_tracer);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##bulltracecolor"), &g_cfg.esp.bullet_tracer_color, ALPHA);
ImGui::Checkbox(crypt_str("Enemy bullet tracers"), &g_cfg.esp.enemy_bullet_tracer);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##enemybulltracecolor"), &g_cfg.esp.enemy_bullet_tracer_color, ALPHA);
ImGui::Checkbox(crypt_str("Hitmarker"), &g_cfg.esp.hitmarker);
ImGui::Checkbox(crypt_str("Damage marker"), &g_cfg.esp.damage_marker);
ImGui::Checkbox(crypt_str("Kill effect"), &g_cfg.esp.kill_effect);
if (g_cfg.esp.kill_effect)
ImGui::SliderFloat(crypt_str("Duration"), &g_cfg.esp.kill_effect_duration, 0.01f, 3.0f);
draw_keybind("Thirdperson", &g_cfg.misc.thirdperson_toggle, "##TPKEY__HOTKEY");
ImGui::Checkbox(crypt_str("Thirdperson when spectating"), &g_cfg.misc.thirdperson_when_spectating);
if (g_cfg.misc.thirdperson_toggle.key > KEY_NONE && g_cfg.misc.thirdperson_toggle.key < KEY_MAX)
ImGui::SliderInt(crypt_str("Thirdperson distance"), &g_cfg.misc.thirdperson_distance, 100, 300);
ImGui::SliderInt(crypt_str("Field of view"), &g_cfg.esp.fov, 0, 89);
ImGui::Checkbox(crypt_str("Taser range"), &g_cfg.esp.taser_range);
ImGui::Checkbox(crypt_str("Show spread"), &g_cfg.esp.show_spread);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##spredcolor"), &g_cfg.esp.show_spread_color, ALPHA);
ImGui::Checkbox(crypt_str("Penetration crosshair"), &g_cfg.esp.penetration_reticle);
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("General");
tab_start();
ImGui::BeginChild("##VISUAL2_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Rare animations"), &g_cfg.skins.rare_animations);
ImGui::SliderInt(crypt_str("Viewmodel field of view"), &g_cfg.esp.viewmodel_fov, 0, 89);
ImGui::SliderInt(crypt_str("Viewmodel X"), &g_cfg.esp.viewmodel_x, -50, 50);
ImGui::SliderInt(crypt_str("Viewmodel Y"), &g_cfg.esp.viewmodel_y, -50, 50);
ImGui::SliderInt(crypt_str("Viewmodel Z"), &g_cfg.esp.viewmodel_z, -50, 50);
ImGui::SliderInt(crypt_str("Viewmodel roll"), &g_cfg.esp.viewmodel_roll, -180, 180);
}
ImGui::EndChild();
tab_end();
}
}
else
{
if (!visuals_section)
{
child_title("World");
tab_start();
ImGui::BeginChild("##VISUAL1_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Full bright"), &g_cfg.esp.bright);
draw_combo("Skybox", g_cfg.esp.skybox, skybox, ARRAYSIZE(skybox));
ImGui::Text(crypt_str("Color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##skyboxcolor"), &g_cfg.esp.skybox_color, NOALPHA);
if (g_cfg.esp.skybox == 21)
{
static char sky_custom[64] = "\0";
if (!g_cfg.esp.custom_skybox.empty())
strcpy_s(sky_custom, sizeof(sky_custom), g_cfg.esp.custom_skybox.c_str());
ImGui::Text(crypt_str("Name"));
if (ImGui::InputText(crypt_str("##customsky"), sky_custom, sizeof(sky_custom)))
g_cfg.esp.custom_skybox = sky_custom;
}
ImGui::Checkbox(crypt_str("Night mode"), &g_cfg.esp.nightmode);
if (g_cfg.esp.nightmode)
{
ImGui::Text(crypt_str("World color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##worldcolor"), &g_cfg.esp.world_color, ALPHA);
ImGui::Text(crypt_str("Props color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##propscolor"), &g_cfg.esp.props_color, ALPHA);
}
ImGui::Checkbox(crypt_str("World modulation"), &g_cfg.esp.world_modulation);
if (g_cfg.esp.world_modulation)
{
ImGui::SliderFloat(crypt_str("Bloom"), &g_cfg.esp.bloom, 0.0f, 750.0f);
ImGui::SliderFloat(crypt_str("Exposure"), &g_cfg.esp.exposure, 0.0f, 2000.0f);
ImGui::SliderFloat(crypt_str("Ambient"), &g_cfg.esp.ambient, 0.0f, 1500.0f);
}
ImGui::Checkbox(crypt_str("Fog modulation"), &g_cfg.esp.fog);
if (g_cfg.esp.fog)
{
ImGui::SliderInt(crypt_str("Distance"), &g_cfg.esp.fog_distance, 0, 2500);
ImGui::SliderInt(crypt_str("Density"), &g_cfg.esp.fog_density, 0, 100);
ImGui::Text(crypt_str("Color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##fogcolor"), &g_cfg.esp.fog_color, NOALPHA);
}
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Chams");
tab_start();
ImGui::BeginChild("##VISUAL2_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Arms chams"), &g_cfg.esp.arms_chams);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##armscolor"), &g_cfg.esp.arms_chams_color, ALPHA);
draw_combo(crypt_str("Arms chams material"), g_cfg.esp.arms_chams_type, chamstype, ARRAYSIZE(chamstype));
if (g_cfg.esp.arms_chams_type != 6)
{
ImGui::Checkbox(crypt_str("Arms double material "), &g_cfg.esp.arms_double_material);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##armsdoublematerial"), &g_cfg.esp.arms_double_material_color, ALPHA);
}
ImGui::Checkbox(crypt_str("Arms animated material "), &g_cfg.esp.arms_animated_material);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##armsanimatedmaterial"), &g_cfg.esp.arms_animated_material_color, ALPHA);
ImGui::Spacing();
ImGui::Checkbox(crypt_str("Weapon chams"), &g_cfg.esp.weapon_chams);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##weaponchamscolors"), &g_cfg.esp.weapon_chams_color, ALPHA);
draw_combo(crypt_str("Weapon chams material"), g_cfg.esp.weapon_chams_type, chamstype, ARRAYSIZE(chamstype));
if (g_cfg.esp.weapon_chams_type != 6)
{
ImGui::Checkbox(crypt_str("Weapon double material "), &g_cfg.esp.weapon_double_material);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##weapondoublematerial"), &g_cfg.esp.weapon_double_material_color, ALPHA);
}
ImGui::Checkbox(crypt_str("Weapon animated material "), &g_cfg.esp.weapon_animated_material);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##weaponanimatedmaterial"), &g_cfg.esp.weapon_animated_material_color, ALPHA);
}
ImGui::EndChild();
tab_end();
}
}
}
else if (child == -1)
{
// hey stewen, what r u doing there? he, hm heee, DRUGS
static bool drugs = false;
// some animation logic(switch)
static bool active_animation = false;
static bool preview_reverse = false;
static float switch_alpha = 1.f;
static int next_id = -1;
if (active_animation)
{
if (preview_reverse)
{
if (switch_alpha == 1.f)
{
preview_reverse = false;
active_animation = false;
}
switch_alpha = math::clamp(switch_alpha + (4.f * ImGui::GetIO().DeltaTime), 0.01f, 1.f);
}
else
{
if (switch_alpha == 0.01f)
{
preview_reverse = true;
}
switch_alpha = math::clamp(switch_alpha - (4.f * ImGui::GetIO().DeltaTime), 0.01f, 1.f);
}
}
else
switch_alpha = math::clamp(switch_alpha + (4.f * ImGui::GetIO().DeltaTime), 0.0f, 1.f);
// TODO: delete g_cfg.skin.enable and auto force it to TRUE
g_cfg.skins.enable = true;
ImGui::BeginChild("##SKINCHANGER__TAB", ImVec2(686 * dpi_scale, child_height * dpi_scale)); // first functional child
{
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (1.f - preview_alpha) * public_alpha * switch_alpha);
child_title(current_profile == -1 ? "Skinchanger" : game_data::weapon_names[current_profile].name);
tab_start();
ImGui::BeginChild("##SKINCHANGER__CHILD", ImVec2(686 * dpi_scale, (child_height - 35)* dpi_scale));
{
// we need to count our items in 1 line
int same_line_counter = 0;
// if we didnt choose any weapon
if (current_profile == -1)
{
for (auto i = 0; i < g_cfg.skins.skinChanger.size(); i++)
{
// do we need update our preview for some reasons?
if (all_skins[i] == nullptr)
all_skins[i] = get_skin_preview(get_wep(i, (i == 0 || i == 1) ? g_cfg.skins.skinChanger.at(i).definition_override_vector_index : -1, i == 0).c_str(), g_cfg.skins.skinChanger.at(i).skin_name, device);
// we licked on weapon
if (ImGui::ImageButton(all_skins[i], ImVec2(107 * dpi_scale, 76 * dpi_scale)))
{
next_id = i;
active_animation = true;
}
// if our animation step is half from all - switch profile
if (active_animation && preview_reverse)
{
ImGui::SetScrollY(0);
current_profile = next_id;
}
if (same_line_counter < 4) { // continue push same-line
ImGui::SameLine();
same_line_counter++;
}
else { // we have maximum elements in 1 line
same_line_counter = 0;
}
}
}
else
{
// update skin preview bool
static bool need_update[36];
// we pressed "Save & Close" button
static bool leave;
// update if we have nullptr texture or if we push force update
if (all_skins[current_profile] == nullptr || need_update[current_profile])
{
all_skins[current_profile] = get_skin_preview(get_wep(current_profile, (current_profile == 0 || current_profile == 1) ? g_cfg.skins.skinChanger.at(current_profile).definition_override_vector_index : -1, current_profile == 0).c_str(), g_cfg.skins.skinChanger.at(current_profile).skin_name, device);
need_update[current_profile] = false;
}
// get settings for selected weapon
auto& selected_entry = g_cfg.skins.skinChanger[current_profile];
selected_entry.itemIdIndex = current_profile;
ImGui::BeginGroup();
ImGui::PushItemWidth(260 * dpi_scale);
// search input later
static char search_skins[64] = "";
static auto item_index = selected_entry.paint_kit_vector_index;
if (!current_profile)
{
ImGui::Text("Knife");
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 5 * c_menu::get().dpi_scale);
if (ImGui::Combo("##Knife_combo", &selected_entry.definition_override_vector_index, [](void* data, int idx, const char** out_text)
{
*out_text = game_data::knife_names[idx].name;
return true;
}, nullptr, IM_ARRAYSIZE(game_data::knife_names)))
need_update[current_profile] = true; // push force update
}
else if (current_profile == 1)
{
ImGui::Text("Gloves");
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 5 * c_menu::get().dpi_scale);
if (ImGui::Combo("##Glove_combo", &selected_entry.definition_override_vector_index, [](void* data, int idx, const char** out_text)
{
*out_text = game_data::glove_names[idx].name;
return true;
}, nullptr, IM_ARRAYSIZE(game_data::glove_names)))
{
item_index = 0; // set new generated paintkits element to 0;
need_update[current_profile] = true; // push force update
}
}
else
selected_entry.definition_override_vector_index = 0;
if (current_profile != 1)
{
ImGui::Text("Search");
if (ImGui::InputText("##search", search_skins, sizeof(search_skins)))
item_index = -1;
}
auto main_kits = current_profile == 1 ? SkinChanger::gloveKits : SkinChanger::skinKits;
auto display_index = 0;
SkinChanger::displayKits = main_kits;
// we dont need custom gloves
if (current_profile == 1)
{
for (auto i = 0; i < main_kits.size(); i++)
{
auto main_name = main_kits.at(i).name;
for (auto i = 0; i < main_name.size(); i++)
if (iswalpha((main_name.at(i))))
main_name.at(i) = towlower(main_name.at(i));
char search_name[64];
if (!strcmp(game_data::glove_names[selected_entry.definition_override_vector_index].name, "Hydra"))
strcpy_s(search_name, sizeof(search_name), "Bloodhound");
else
strcpy_s(search_name, sizeof(search_name), game_data::glove_names[selected_entry.definition_override_vector_index].name);
for (auto i = 0; i < sizeof(search_name); i++)
if (iswalpha(search_name[i]))
search_name[i] = towlower(search_name[i]);
if (main_name.find(search_name) != std::string::npos)
{
SkinChanger::displayKits.at(display_index) = main_kits.at(i);
display_index++;
}
}
SkinChanger::displayKits.erase(SkinChanger::displayKits.begin() + display_index, SkinChanger::displayKits.end());
}
else
{
// TODO: fix ru finding symbols ('Градиент' не будет найден по запросу 'градиент' etc)
if (strcmp(search_skins, "")) //-V526
{
for (auto i = 0; i < main_kits.size(); i++)
{
auto main_name = main_kits.at(i).name;
for (auto i = 0; i < main_name.size(); i++)
if (iswalpha(main_name.at(i)))
main_name.at(i) = towlower(main_name.at(i));
char search_name[64];
strcpy_s(search_name, sizeof(search_name), search_skins);
for (auto i = 0; i < sizeof(search_name); i++)
if (iswalpha(search_name[i]))
search_name[i] = towlower(search_name[i]);
if (main_name.find(search_name) != std::string::npos)
{
SkinChanger::displayKits.at(display_index) = main_kits.at(i);
display_index++;
}
}
SkinChanger::displayKits.erase(SkinChanger::displayKits.begin() + display_index, SkinChanger::displayKits.end());
}
else
item_index = selected_entry.paint_kit_vector_index;
}
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f);
if (!SkinChanger::displayKits.empty())
{
if (ImGui::ListBox("##PAINTKITS", &item_index, [](void* data, int idx, const char** out_text)
{
while (SkinChanger::displayKits.at(idx).name.find("С‘") != std::string::npos) //-V807
SkinChanger::displayKits.at(idx).name.replace(SkinChanger::displayKits.at(idx).name.find("С‘"), 2, "Рµ");
*out_text = SkinChanger::displayKits.at(idx).name.c_str();
return true;
}, nullptr, SkinChanger::displayKits.size(), SkinChanger::displayKits.size() > 9 ? 9 : SkinChanger::displayKits.size()) || !all_skins[current_profile])
{
g_ctx.globals.force_skin_update = true;
need_update[current_profile] = true;
auto i = 0;
while (i < main_kits.size())
{
if (main_kits.at(i).id == SkinChanger::displayKits.at(item_index).id)
{
selected_entry.paint_kit_vector_index = i;
break;
}
i++;
}
}
}
ImGui::PopStyleVar();
if (ImGui::InputInt("Seed", &selected_entry.seed, 1, 100))
g_ctx.globals.force_skin_update = true;
if (ImGui::InputInt("StatTrak", &selected_entry.stat_trak, 1, 15))
g_ctx.globals.force_skin_update = true;
if (ImGui::SliderFloat("Wear", &selected_entry.wear, 0.0f, 1.0f))
drugs = true;
else if (drugs)
{
g_ctx.globals.force_skin_update = true;
drugs = false;
}
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 6 * c_menu::get().dpi_scale);
ImGui::Text("Quality");
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 5 * c_menu::get().dpi_scale);
if (ImGui::Combo("##Quality_combo", &selected_entry.entity_quality_vector_index, [](void* data, int idx, const char** out_text)
{
*out_text = game_data::quality_names[idx].name;
return true;
}, nullptr, IM_ARRAYSIZE(game_data::quality_names)))
g_ctx.globals.force_skin_update = true;
if (current_profile != 1)
{
if (!g_cfg.skins.custom_name_tag[current_profile].empty())
strcpy_s(selected_entry.custom_name, sizeof(selected_entry.custom_name), g_cfg.skins.custom_name_tag[current_profile].c_str());
ImGui::Text("Name Tag");
if (ImGui::InputText("##nametag", selected_entry.custom_name, sizeof(selected_entry.custom_name)))
{
g_cfg.skins.custom_name_tag[current_profile] = selected_entry.custom_name;
g_ctx.globals.force_skin_update = true;
}
}
ImGui::PopItemWidth();
ImGui::EndGroup();
ImGui::SameLine();
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 286 * dpi_scale - 200 * dpi_scale);
ImGui::BeginGroup();
if (ImGui::ImageButton(all_skins[current_profile], ImVec2(190 * dpi_scale, 155 * dpi_scale)))
{
// maybe i will do smth later where, who knows :/
}
if (ImGui::CustomButton("Save & Close", "##SAVE__CLOSE__SKING", ImVec2(198 * dpi_scale, 26 * dpi_scale)))
{
// start animation
active_animation = true;
next_id = -1;
leave = true;
}
ImGui::EndGroup();
// update element
selected_entry.update();
// we need to reset profile in the end to prevent render images with massive's index == -1
if (leave && ((active_animation && preview_reverse) || !active_animation))
{
g_ctx.globals.force_skin_update = true;
ImGui::SetScrollY(0);
current_profile = next_id;
leave = false;
}
}
}
ImGui::EndChild();
tab_end();
}
ImGui::EndChild();
}
}
void c_menu::draw_tabs_players()
{
const char* players_sections[3] = { "Enemy", "Team", "Local" };
draw_semitabs(players_sections, 3, players_section, ImGui::GetStyle());
}
void c_menu::draw_players(int child)
{
auto player = players_section;
static std::vector <Player_list_data> players;
if (!g_cfg.player_list.refreshing)
{
players.clear();
for (auto player : g_cfg.player_list.players)
players.emplace_back(player);
}
static auto current_player = 0;
if (!child)
{
if (players_section < 3)
{
child_title("ESP");
tab_start();
ImGui::BeginChild("##ESP1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Enable"), &g_cfg.player.enable);
if (player == ENEMY)
{
ImGui::Checkbox(crypt_str("OOF arrows"), &g_cfg.player.arrows);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##arrowscolor"), &g_cfg.player.arrows_color, ALPHA);
if (g_cfg.player.arrows)
{
ImGui::SliderInt(crypt_str("Arrows distance"), &g_cfg.player.distance, 1, 100);
ImGui::SliderInt(crypt_str("Arrows size"), &g_cfg.player.size, 1, 100);
}
}
ImGui::Checkbox(crypt_str("Bounding box"), &g_cfg.player.type[player].box);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##boxcolor"), &g_cfg.player.type[player].box_color, ALPHA);
ImGui::Checkbox(crypt_str("Name"), &g_cfg.player.type[player].name);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##namecolor"), &g_cfg.player.type[player].name_color, ALPHA);
ImGui::Checkbox(crypt_str("Health bar"), &g_cfg.player.type[player].health);
ImGui::Checkbox(crypt_str("Health color"), &g_cfg.player.type[player].custom_health_color);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##healthcolor"), &g_cfg.player.type[player].health_color, ALPHA);
for (auto i = 0, j = 0; i < ARRAYSIZE(flags); i++)
{
if (g_cfg.player.type[player].flags[i])
{
if (j)
preview += crypt_str(", ") + (std::string)flags[i];
else
preview = flags[i];
j++;
}
}
draw_multicombo("Flags", g_cfg.player.type[player].flags, flags, ARRAYSIZE(flags), preview);
draw_multicombo("Weapon", g_cfg.player.type[player].weapon, weaponplayer, ARRAYSIZE(weaponplayer), preview);
if (g_cfg.player.type[player].weapon[WEAPON_ICON] || g_cfg.player.type[player].weapon[WEAPON_TEXT])
{
ImGui::Text(crypt_str("Color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##weapcolor"), &g_cfg.player.type[player].weapon_color, ALPHA);
}
ImGui::Checkbox(crypt_str("Skeleton"), &g_cfg.player.type[player].skeleton);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##skeletoncolor"), &g_cfg.player.type[player].skeleton_color, ALPHA);
ImGui::Checkbox(crypt_str("Ammo bar"), &g_cfg.player.type[player].ammo);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##ammocolor"), &g_cfg.player.type[player].ammobar_color, ALPHA);
ImGui::Checkbox(crypt_str("Footsteps"), &g_cfg.player.type[player].footsteps);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##footstepscolor"), &g_cfg.player.type[player].footsteps_color, ALPHA);
if (g_cfg.player.type[player].footsteps)
{
ImGui::SliderInt(crypt_str("Thickness"), &g_cfg.player.type[player].thickness, 1, 10);
ImGui::SliderInt(crypt_str("Radius"), &g_cfg.player.type[player].radius, 50, 500);
}
if (player == ENEMY || player == TEAM)
{
ImGui::Checkbox(crypt_str("Snap lines"), &g_cfg.player.type[player].snap_lines);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##snapcolor"), &g_cfg.player.type[player].snap_lines_color, ALPHA);
if (player == ENEMY)
{
if (g_cfg.ragebot.enable)
{
ImGui::Checkbox(crypt_str("Aimbot points"), &g_cfg.player.show_multi_points);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##showmultipointscolor"), &g_cfg.player.show_multi_points_color, ALPHA);
}
ImGui::Checkbox(crypt_str("Aimbot hitboxes"), &g_cfg.player.lag_hitbox);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##lagcompcolor"), &g_cfg.player.lag_hitbox_color, ALPHA);
}
}
else
{
draw_combo(crypt_str("Player model T"), g_cfg.player.player_model_t, player_model_t, ARRAYSIZE(player_model_t));
padding(0, 3);
draw_combo(crypt_str("Player model CT"), g_cfg.player.player_model_ct, player_model_ct, ARRAYSIZE(player_model_ct));
}
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Players");
tab_start();
ImGui::BeginChild("##ESP2_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
if (!players.empty())
{
std::vector <std::string> player_names;
for (auto player : players)
player_names.emplace_back(player.name);
ImGui::PushItemWidth(291 * dpi_scale);
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f);
ImGui::ListBoxConfigArray(crypt_str("##PLAYERLIST"), ¤t_player, player_names, 14);
ImGui::PopStyleVar();
ImGui::PopItemWidth();
}
}
ImGui::EndChild();
tab_end();
}
}
else
{
if (players_section > 2)
{
child_title("Settings");
tab_start();
ImGui::BeginChild("##ESP1_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
if (!players.empty())
{
if (current_player >= players.size())
current_player = players.size() - 1; //-V103
ImGui::Checkbox(crypt_str("White list"), &g_cfg.player_list.white_list[players.at(current_player).i]); //-V106 //-V807
if (!g_cfg.player_list.white_list[players.at(current_player).i]) //-V106
{
// TODO: arty pidoras uncomment
ImGui::Checkbox(crypt_str("High priority"), &g_cfg.player_list.high_priority[players.at(current_player).i]); //-V106
//ImGui::Checkbox(crypt_str("Force safe points"), &g_cfg.player_list.force_safe_points[players.at(current_player).i]); //-V106
ImGui::Checkbox(crypt_str("Force body aim"), &g_cfg.player_list.force_body_aim[players.at(current_player).i]); //-V106
//ImGui::Checkbox(crypt_str("Low delta"), &g_cfg.player_list.low_delta[players.at(current_player).i]); //-V106
}
}
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Model");
tab_start();
ImGui::BeginChild("##ESP2_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Spacing();
if (player == LOCAL)
draw_combo(crypt_str("Type"), g_cfg.player.local_chams_type, local_chams_type, ARRAYSIZE(local_chams_type));
if (player != LOCAL || !g_cfg.player.local_chams_type)
draw_multicombo("Chams", g_cfg.player.type[player].chams, g_cfg.player.type[player].chams[PLAYER_CHAMS_VISIBLE] ? chamsvisact : chamsvis, g_cfg.player.type[player].chams[PLAYER_CHAMS_VISIBLE] ? ARRAYSIZE(chamsvisact) : ARRAYSIZE(chamsvis), preview);
if (g_cfg.player.type[player].chams[PLAYER_CHAMS_VISIBLE] || player == LOCAL && g_cfg.player.local_chams_type)
{
if (player == LOCAL && g_cfg.player.local_chams_type)
{
ImGui::Checkbox(crypt_str("Enable desync chams"), &g_cfg.player.fake_chams_enable);
ImGui::Checkbox(crypt_str("Visualize lag"), &g_cfg.player.visualize_lag);
ImGui::Checkbox(crypt_str("Layered"), &g_cfg.player.layered);
draw_combo(crypt_str("Player chams material"), g_cfg.player.fake_chams_type, chamstype, ARRAYSIZE(chamstype));
ImGui::Text(crypt_str("Color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##fakechamscolor"), &g_cfg.player.fake_chams_color, ALPHA);
if (g_cfg.player.fake_chams_type != 6)
{
ImGui::Checkbox(crypt_str("Double material "), &g_cfg.player.fake_double_material);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##doublematerialcolor"), &g_cfg.player.fake_double_material_color, ALPHA);
}
ImGui::Checkbox(crypt_str("Animated material"), &g_cfg.player.fake_animated_material);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##animcolormat"), &g_cfg.player.fake_animated_material_color, ALPHA);
}
else
{
draw_combo(crypt_str("Player chams material"), g_cfg.player.type[player].chams_type, chamstype, ARRAYSIZE(chamstype));
if (g_cfg.player.type[player].chams[PLAYER_CHAMS_VISIBLE])
{
ImGui::Text(crypt_str("Visible "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##chamsvisible"), &g_cfg.player.type[player].chams_color, ALPHA);
}
if (g_cfg.player.type[player].chams[PLAYER_CHAMS_VISIBLE] && g_cfg.player.type[player].chams[PLAYER_CHAMS_INVISIBLE])
{
ImGui::Text(crypt_str("Invisible "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##chamsinvisible"), &g_cfg.player.type[player].xqz_color, ALPHA);
}
if (g_cfg.player.type[player].chams_type != 6)
{
ImGui::Checkbox(crypt_str("Double material "), &g_cfg.player.type[player].double_material);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##doublematerialcolor"), &g_cfg.player.type[player].double_material_color, ALPHA);
}
ImGui::Checkbox(crypt_str("Animated material"), &g_cfg.player.type[player].animated_material);
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##animcolormat"), &g_cfg.player.type[player].animated_material_color, ALPHA);
if (player == ENEMY)
{
ImGui::Checkbox(crypt_str("Backtrack chams"), &g_cfg.player.backtrack_chams);
if (g_cfg.player.backtrack_chams)
{
draw_combo(crypt_str("Backtrack chams material"), g_cfg.player.backtrack_chams_material, chamstype, ARRAYSIZE(chamstype));
ImGui::Text(crypt_str("Color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("##backtrackcolor"), &g_cfg.player.backtrack_chams_color, ALPHA);
}
}
}
}
if (player == ENEMY || player == TEAM)
{
ImGui::Checkbox(crypt_str("Ragdoll chams"), &g_cfg.player.type[player].ragdoll_chams);
if (g_cfg.player.type[player].ragdoll_chams)
{
draw_combo(crypt_str("Ragdoll chams material"), g_cfg.player.type[player].ragdoll_chams_material, chamstype, ARRAYSIZE(chamstype));
ImGui::Text(crypt_str("Color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("ragdollcolor"), &g_cfg.player.type[player].ragdoll_chams_color, ALPHA);
}
}
else if (!g_cfg.player.local_chams_type)
{
ImGui::Checkbox(crypt_str("Transparency in scope"), &g_cfg.player.transparency_in_scope);
if (g_cfg.player.transparency_in_scope)
ImGui::SliderFloat(crypt_str("Alpha"), &g_cfg.player.transparency_in_scope_amount, 0.0f, 1.0f);
}
ImGui::Spacing();
ImGui::Checkbox(crypt_str("Glow"), &g_cfg.player.type[player].glow);
if (g_cfg.player.type[player].glow)
{
draw_combo(crypt_str("Glow type"), g_cfg.player.type[player].glow_type, glowtype, ARRAYSIZE(glowtype));
ImGui::Text(crypt_str("Color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("glowcolor"), &g_cfg.player.type[player].glow_color, ALPHA);
}
}
ImGui::EndChild();
tab_end();
}
}
}
void c_menu::draw_tabs_misc()
{
const char* misc_sections[2] = { "Main", "Additives" };
draw_semitabs(misc_sections, 2, misc_section, ImGui::GetStyle());
}
void c_menu::draw_misc(int child)
{
if (!child)
{
if (!misc_section)
{
child_title("General");
tab_start();
ImGui::BeginChild("##MISC1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Anti-untrusted"), &g_cfg.misc.anti_untrusted);
ImGui::Checkbox(crypt_str("Rank reveal"), &g_cfg.misc.rank_reveal);
ImGui::Checkbox(crypt_str("Unlock inventory access"), &g_cfg.misc.inventory_access);
ImGui::Checkbox(crypt_str("Gravity ragdolls"), &g_cfg.misc.ragdolls);
ImGui::Checkbox(crypt_str("Preserve killfeed"), &g_cfg.esp.preserve_killfeed);
ImGui::Checkbox(crypt_str("Aspect ratio"), &g_cfg.misc.aspect_ratio);
if (g_cfg.misc.aspect_ratio)
{
padding(0, -5);
ImGui::SliderFloat(crypt_str("Amount"), &g_cfg.misc.aspect_ratio_amount, 1.0f, 2.0f);
}
ImGui::Checkbox(crypt_str("Fake lag"), &g_cfg.antiaim.fakelag);
if (g_cfg.antiaim.fakelag)
{
draw_combo(crypt_str("Fake lag type"), g_cfg.antiaim.fakelag_type, fakelags, ARRAYSIZE(fakelags));
ImGui::SliderInt(crypt_str("Limit"), &g_cfg.antiaim.fakelag_amount, 1, 16);
draw_multicombo("Fake lag triggers", g_cfg.antiaim.fakelag_enablers, lagstrigger, ARRAYSIZE(lagstrigger), preview);
auto enabled_fakelag_triggers = false;
for (auto i = 0; i < ARRAYSIZE(lagstrigger); i++)
if (g_cfg.antiaim.fakelag_enablers[i])
enabled_fakelag_triggers = true;
if (enabled_fakelag_triggers)
ImGui::SliderInt(crypt_str("Triggers limit"), &g_cfg.antiaim.triggers_fakelag_amount, 1, 16);
}
draw_keybind("Teleport Exploit", &g_cfg.misc.teleport_exploit, "##TP_HOTKEY");
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Information");
tab_start();
ImGui::BeginChild("##MISC1_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Watermark"), &g_cfg.menu.watermark);
ImGui::Checkbox(crypt_str("Spectators list"), &g_cfg.misc.spectators_list);
draw_combo(crypt_str("Hitsound"), g_cfg.esp.hitsound, sounds, ARRAYSIZE(sounds));
ImGui::Checkbox(crypt_str("Killsound"), &g_cfg.esp.killsound);
draw_multicombo(crypt_str("Logs"), g_cfg.misc.events_to_log, events, ARRAYSIZE(events), preview);
padding(0, 3);
draw_multicombo(crypt_str("Logs output"), g_cfg.misc.log_output, events_output, ARRAYSIZE(events_output), preview);
if (g_cfg.misc.events_to_log[EVENTLOG_HIT] || g_cfg.misc.events_to_log[EVENTLOG_ITEM_PURCHASES] || g_cfg.misc.events_to_log[EVENTLOG_BOMB])
{
ImGui::Text(crypt_str("Color "));
ImGui::SameLine();
ImGui::ColorEdit(crypt_str("logcolor"), &g_cfg.misc.log_color, ALPHA);
}
ImGui::Checkbox(crypt_str("Show CS:GO logs"), &g_cfg.misc.show_default_log);
}
ImGui::EndChild();
tab_end();
}
}
else
{
if (!misc_section)
{
child_title("Movement");
tab_start();
ImGui::BeginChild("##MISC2_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Automatic jump"), &g_cfg.misc.bunnyhop);
draw_combo(crypt_str("Automatic strafes"), g_cfg.misc.airstrafe, strafes, ARRAYSIZE(strafes));
ImGui::Checkbox(crypt_str("Crouch in air"), &g_cfg.misc.crouch_in_air);
ImGui::Checkbox(crypt_str("Fast stop"), &g_cfg.misc.fast_stop);
ImGui::Checkbox(crypt_str("Slide walk"), &g_cfg.misc.slidewalk);
ImGui::Checkbox(crypt_str("No duck cooldown"), &g_cfg.misc.noduck);
if (g_cfg.misc.noduck)
draw_keybind(crypt_str("Fakeduck"), &g_cfg.misc.fakeduck_key, crypt_str("##FAKEDUCK__HOTKEY"));
draw_keybind(crypt_str("Slowwalk"), &g_cfg.misc.slowwalk_key, crypt_str("##SLOWWALK__HOTKEY"));
draw_keybind(crypt_str("Auto peek"), &g_cfg.misc.automatic_peek, crypt_str("##AUTOPEEK__HOTKEY"));
draw_keybind(crypt_str("Edge jump"), &g_cfg.misc.edge_jump, crypt_str("##EDGEJUMP__HOTKEY"));
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Extra");
tab_start();
ImGui::BeginChild("##MISC2_SECOND", ImVec2(317 * dpi_scale, (child_height - 35)* dpi_scale));
{
ImGui::Checkbox(crypt_str("Anti-screenshot"), &g_cfg.misc.anti_screenshot);
ImGui::Checkbox(crypt_str("Clantag"), &g_cfg.misc.clantag_spammer);
ImGui::Checkbox(crypt_str("Chat spam"), &g_cfg.misc.chat);
ImGui::Checkbox(crypt_str("Enable buybot"), &g_cfg.misc.buybot_enable);
draw_combo(crypt_str("Snipers"), g_cfg.misc.buybot1, mainwep, ARRAYSIZE(mainwep));
padding(0, 3);
draw_combo(crypt_str("Pistols"), g_cfg.misc.buybot2, secwep, ARRAYSIZE(secwep));
padding(0, 3);
draw_multicombo("Other", g_cfg.misc.buybot3, grenades, ARRAYSIZE(grenades), preview);
#if !RELEASE
ImGui::Text("DPI Scale");
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 5 * dpi_scale);
if (ImGui::DragFloat("##DPIScale", &dpi_scale, 0.005f, 1.f, 1.8f, "%.2f"))
update_dpi = true;
#endif
}
ImGui::EndChild();
tab_end();
}
}
}
void c_menu::draw_settings(int child)
{
child_title("Configs");
tab_start();
ImGui::BeginChild("##CONFIGS__FIRST", ImVec2(686 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::BeginChild("##CONFIGS__FIRST_POSHELNAHUI", ImVec2(686 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::PushItemWidth(629 * c_menu::get().dpi_scale);
static auto should_update = true;
if (should_update)
{
should_update = false;
cfg_manager->config_files();
files = cfg_manager->files;
for (auto& current : files)
if (current.size() > 2)
current.erase(current.size() - 3, 3);
}
if (ImGui::CustomButton("Open configs folder", "##CONFIG__FOLDER", ImVec2(629 * dpi_scale, 26 * dpi_scale)))
{
std::string folder;
auto get_dir = [&folder]() -> void
{
static TCHAR path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, NULL, path)))
folder = std::string(path) + crypt_str("\\Legendware\\Configs\\");
CreateDirectory(folder.c_str(), NULL);
};
get_dir();
ShellExecute(NULL, crypt_str("open"), folder.c_str(), NULL, NULL, SW_SHOWNORMAL);
}
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f);
ImGui::ListBoxConfigArray(crypt_str("##CONFIGS"), &g_cfg.selected_config, files, 7);
ImGui::PopStyleVar();
if (ImGui::CustomButton("Refresh configs", "##CONFIG__REFRESH", ImVec2(629 * dpi_scale, 26 * dpi_scale)))
{
cfg_manager->config_files();
files = cfg_manager->files;
for (auto& current : files)
if (current.size() > 2)
current.erase(current.size() - 3, 3);
}
static char config_name[64] = "\0";
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f);
ImGui::InputText(crypt_str("##configname"), config_name, sizeof(config_name));
ImGui::PopStyleVar();
if (ImGui::CustomButton("Create config", "##CONFIG__CREATE", ImVec2(629 * dpi_scale, 26 * dpi_scale)))
{
g_cfg.new_config_name = config_name;
add_config();
}
/* SAVE BUTTON */
static bool next_save = false;
static bool prenext_save = false;
static bool clicked_sure = false;
static auto save_time = m_globals()->m_realtime;
static float save_alpha = 1.f;
save_alpha = math::clamp(save_alpha + (4.f * ImGui::GetIO().DeltaTime * (!prenext_save ? 1.f : -1.f)), 0.01f, 1.f);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, save_alpha * public_alpha * (1.f - preview_alpha));
if (!next_save)
{
clicked_sure = false;
if (prenext_save && save_alpha <= 0.01f)
next_save = true;
if (ImGui::CustomButton("Save config", "##CONFIG__SAVE", ImVec2(629 * dpi_scale, 26 * dpi_scale)))
{
save_time = m_globals()->m_realtime;
prenext_save = true;
}
}
else
{
if (prenext_save && save_alpha <= 0.01f)
{
prenext_save = false;
next_save = !clicked_sure;
}
if (ImGui::CustomButton("Are you sure?", "##AREYOUSURE__SAVE", ImVec2(629 * dpi_scale, 26 * dpi_scale)))
{
save_config();
prenext_save = true;
clicked_sure = true;
}
if (!clicked_sure && m_globals()->m_realtime > save_time + 3.f)
{
prenext_save = true;
clicked_sure = true;
}
}
ImGui::PopStyleVar();
/* */
if (ImGui::CustomButton("Load config", "##CONFIG__LOAD", ImVec2(629 * dpi_scale, 26 * dpi_scale)))
load_config();
/* DELETE BUTTON */
static bool next_delete = false;
static bool prenext_delete = false;
static bool clicked_sure_del = false;
static auto delete_time = m_globals()->m_realtime;
static float delete_alpha = 1.f;
delete_alpha = math::clamp(delete_alpha + (4.f * ImGui::GetIO().DeltaTime * (!prenext_delete ? 1.f : -1.f)), 0.01f, 1.f);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, delete_alpha * public_alpha * (1.f - preview_alpha));
if (!next_delete)
{
clicked_sure_del = false;
if (prenext_delete && delete_alpha <= 0.01f)
next_delete = true;
if (ImGui::CustomButton("Remove config", "##CONFIG__delete", ImVec2(629 * dpi_scale, 26 * dpi_scale)))
{
delete_time = m_globals()->m_realtime;
prenext_delete = true;
}
}
else
{
if (prenext_delete && delete_alpha <= 0.01f)
{
prenext_delete = false;
next_delete = !clicked_sure_del;
}
if (ImGui::CustomButton("Are you sure?", "##AREYOUSURE__delete", ImVec2(629 * dpi_scale, 26 * dpi_scale)))
{
remove_config();
prenext_delete = true;
clicked_sure_del = true;
}
if (!clicked_sure_del && m_globals()->m_realtime > delete_time + 3.f)
{
prenext_delete = true;
clicked_sure_del = true;
}
}
ImGui::PopStyleVar();
/* */
ImGui::PopItemWidth();
}
ImGui::EndChild();
ImGui::SetWindowFontScale(c_menu::get().dpi_scale);
}
ImGui::EndChild();
ImGui::PopStyleVar();
}
void c_menu::draw_lua(int child)
{
if (!child)
{
child_title("Scripts");
tab_start();
ImGui::BeginChild("##LUA_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::PushItemWidth(291 * c_menu::get().dpi_scale);
static auto should_update = true;
if (should_update)
{
should_update = false;
scripts = c_lua::get().scripts;
for (auto& current : scripts)
{
if (current.size() >= 5 && current.at(current.size() - 1) == 'c')
current.erase(current.size() - 5, 5);
else if (current.size() >= 4)
current.erase(current.size() - 4, 4);
}
}
if (ImGui::CustomButton("Open scripts folder", "##LUAS__FOLDER", ImVec2(291 * dpi_scale, 26 * dpi_scale)))
{
std::string folder;
auto get_dir = [&folder]() -> void
{
static TCHAR path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, NULL, path)))
folder = std::string(path) + crypt_str("\\Legendware\\Scripts\\");
CreateDirectory(folder.c_str(), NULL);
};
get_dir();
ShellExecute(NULL, crypt_str("open"), folder.c_str(), NULL, NULL, SW_SHOWNORMAL);
}
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f);
if (scripts.empty())
ImGui::ListBoxConfigArray(crypt_str("##LUAS"), &selected_script, scripts, 10);
else
{
auto backup_scripts = scripts;
for (auto& script : scripts)
{
auto script_id = c_lua::get().get_script_id(script + crypt_str(".lua"));
if (script_id == -1)
continue;
if (c_lua::get().loaded.at(script_id))
scripts.at(script_id) += crypt_str(" [loaded]");
}
ImGui::ListBoxConfigArray(crypt_str("##LUAS"), &selected_script, scripts, 10);
scripts = std::move(backup_scripts);
}
ImGui::PopStyleVar();
if (ImGui::CustomButton("Refresh scripts", "##LUA__REFRESH", ImVec2(291 * dpi_scale, 26 * dpi_scale)))
{
c_lua::get().refresh_scripts();
scripts = c_lua::get().scripts;
if (selected_script >= scripts.size())
selected_script = scripts.size() - 1; //-V103
for (auto& current : scripts)
{
if (current.size() >= 5 && current.at(current.size() - 1) == 'c')
current.erase(current.size() - 5, 5);
else if (current.size() >= 4)
current.erase(current.size() - 4, 4);
}
}
// TOOD: заставить кнопку работать
if (ImGui::CustomButton("Edit script", "##LUA__EDIT", ImVec2(291 * dpi_scale, 26 * dpi_scale)))
{
}
ImGui::PopItemWidth();
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Script elements");
tab_start();
ImGui::BeginChild("##LUA_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
}
ImGui::EndChild();
tab_end();
}
}
void c_menu::draw_radar(int child)
{
if (!child)
{
child_title("Hud radar");
tab_start();
ImGui::BeginChild("##RADAR_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Engine radar"), &g_cfg.misc.engine_radar);
ImGui::Checkbox(crypt_str("Disable rendering"), &g_cfg.misc.disable_radar_render); // TODO: cl_drawhud 0
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Custom radar");
tab_start();
ImGui::BeginChild("##RADAR_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
ImGui::Checkbox(crypt_str("Draw custom radar"), &g_cfg.misc.ingame_radar);
ImGui::Checkbox(crypt_str("Render local"), &g_cfg.radar.render_local);
ImGui::Checkbox(crypt_str("Render enemy"), &g_cfg.radar.render_enemy);
ImGui::Checkbox(crypt_str("Render team"), &g_cfg.radar.render_team);
ImGui::Checkbox(crypt_str("Show planted c4"), &g_cfg.radar.render_planted_c4);
ImGui::Checkbox(crypt_str("Show dropped c4"), &g_cfg.radar.render_dropped_c4);
ImGui::Checkbox(crypt_str("Show health"), &g_cfg.radar.render_health);
}
ImGui::EndChild();
tab_end();
}
}
void c_menu::draw_profile(int child)
{
auto player = players_section;
static std::vector <Player_list_data> players;
if (!g_cfg.player_list.refreshing)
{
players.clear();
for (auto player : g_cfg.player_list.players)
players.emplace_back(player);
}
static auto current_player = 0;
if (!child)
{
child_title("Players");
tab_start();
ImGui::BeginChild("##ESP2_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
if (!players.empty())
{
std::vector <std::string> player_names;
for (auto player : players)
player_names.emplace_back(player.name);
ImGui::PushItemWidth(291 * dpi_scale);
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f);
ImGui::ListBoxConfigArray(crypt_str("##PLAYERLIST"), ¤t_player, player_names, 14);
ImGui::PopStyleVar();
ImGui::PopItemWidth();
}
}
ImGui::EndChild();
tab_end();
}
else
{
child_title("Settings");
tab_start();
ImGui::BeginChild("##ESP1_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale));
{
if (!players.empty())
{
if (current_player >= players.size())
current_player = players.size() - 1; //-V103
ImGui::Checkbox(crypt_str("White list"), &g_cfg.player_list.white_list[players.at(current_player).i]); //-V106 //-V807
if (!g_cfg.player_list.white_list[players.at(current_player).i]) //-V106
{
// TODO: arty pidoras uncomment
ImGui::Checkbox(crypt_str("High priority"), &g_cfg.player_list.high_priority[players.at(current_player).i]); //-V106
//ImGui::Checkbox(crypt_str("Force safe points"), &g_cfg.player_list.force_safe_points[players.at(current_player).i]); //-V106
ImGui::Checkbox(crypt_str("Force body aim"), &g_cfg.player_list.force_body_aim[players.at(current_player).i]); //-V106
//ImGui::Checkbox(crypt_str("Low delta"), &g_cfg.player_list.low_delta[players.at(current_player).i]); //-V106
}
}
}
ImGui::EndChild();
tab_end();
}
}
void c_menu::draw(bool is_open) {
// animation related code
static float m_alpha = 0.0002f;
m_alpha = math::clamp(m_alpha + (3.f * ImGui::GetIO().DeltaTime * (is_open ? 1.f : -1.f)), 0.0001f, 1.f);
// set alpha in class to use later in widgets
public_alpha = m_alpha;
if (m_alpha == 0.0001f)
return;
// set new alpha
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, m_alpha);
// setup colors and some styles
if (!menu_setupped)
menu_setup(ImGui::GetStyle());
ImGui::PushStyleColor(ImGuiCol_ScrollbarGrab, ImVec4(ImGui::GetStyle().Colors[ImGuiCol_ScrollbarGrab].x, ImGui::GetStyle().Colors[ImGuiCol_ScrollbarGrab].y, ImGui::GetStyle().Colors[ImGuiCol_ScrollbarGrab].z, m_alpha));
// default menu size
const int x = 850, y = 560;
// last active tab to switch effect & reverse alpha & preview alpha
// IMPORTANT: DO TAB SWITCHING BY LAST_TAB!!!!!
static int last_tab = active_tab;
static bool preview_reverse = false;
// preview for multicombos
std::string preview = "None";
// lua editor (test)
// TODO: get name of script(not a path!!!!!)
lua_edit("kon_utils");
// start menu render
ImGui::Begin("lw3", nullptr, ImGuiWindowFlags_NoDecoration);
{
auto p = ImGui::GetWindowPos();
// main dpi update logic
// KEYWORD : DPI_FIND
if (update_dpi)
{
// prevent oversizing
dpi_scale = min(1.8f, max(dpi_scale, 1.f));
// font and window size setting
ImGui::SetWindowFontScale(dpi_scale);
ImGui::SetWindowSize(ImVec2(ImFloor(x * dpi_scale), ImFloor(y * dpi_scale)));
// styles resizing
dpi_resize(dpi_scale, ImGui::GetStyle());
// setup new window sizes
width = ImFloor(x * dpi_scale);
height = ImFloor(y * dpi_scale);
// end of dpi updating
update_dpi = false;
}
// set padding to draw { tabs , main functional area } / close group to draw last bottom child at x-0 pos
ImGui::SetCursorPos(ImVec2(10 * dpi_scale, 13 * dpi_scale));
ImGui::BeginGroup();
ImGui::BeginChild("##tabs_area", ImVec2(124 * dpi_scale, 509 * dpi_scale)); // there will be tabs
{ // KEYWORD : TABS_FIND
ImGui::PushFont(futura);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(8.f * dpi_scale, 12.f * dpi_scale));
// some extra pdding
ImGui::Spacing();
// we need some more checks to prevent over-switching tabs
if (ImGui::MainTab("Ragebot", ico_menu, "R", active_tab == 0, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 0;
if (ImGui::MainTab("Legit", ico_menu, "L", active_tab == 1, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 1;
if (ImGui::MainTab("Visuals", ico_menu, "V", active_tab == 2, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 2;
if (ImGui::MainTab("Players", ico_menu, "P", active_tab == 3, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 3;
if (ImGui::MainTab("Misc", ico_menu, "M", active_tab == 4, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 4;
if (ImGui::MainTab("Settings", ico_menu, "S", active_tab == 5, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 5;
// seperate our main-func tabs with additional tabs
ImGui::Spacing();
ImGui::Spacing();
if (ImGui::MainTab("Player list", ico_bottom, "P", active_tab == 8, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 8;
if (ImGui::MainTab("Radar", ico_bottom, "R", active_tab == 7, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 7;
if (ImGui::MainTab("Lua", ico_bottom, "L", active_tab == 6, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 6;
ImGui::PopStyleVar();
ImGui::PopFont();
}
ImGui::EndChild();
ImGui::SameLine();
// vertical separator after tabs
ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorPos() + p + ImVec2(3 * dpi_scale, 0), ImGui::GetCursorPos() + p + ImVec2(4 * dpi_scale, 479 * dpi_scale), ImGui::ColorConvertFloat4ToU32(ImVec4(66 / 255.f, 68 / 255.f, 125 / 255.f, m_alpha * 0.3f)));
/* \\ let's set alpha of rect when we will switch tab // */
// ̶c̶h̶e̶c̶k̶ ̶E̶n̶d̶C̶h̶i̶l̶d̶()̶ ̶f̶o̶r̶ ̶m̶o̶r̶e̶ ̶i̶n̶f̶o̶r̶m̶a̶t̶i̶o̶n
if (last_tab != active_tab || (last_tab == active_tab && preview_reverse))
{
if (!preview_reverse)
{
if (preview_alpha == 1.f)
preview_reverse = true;
preview_alpha = math::clamp(preview_alpha + (4.f * ImGui::GetIO().DeltaTime), 0.01f, 1.f);
}
else
{
last_tab = active_tab;
if (preview_alpha == 0.01f)
{
preview_reverse = false;
}
preview_alpha = math::clamp(preview_alpha - (4.f * ImGui::GetIO().DeltaTime), 0.01f, 1.f);
}
}
else
preview_alpha = math::clamp(preview_alpha - (4.f * ImGui::GetIO().DeltaTime), 0.0f, 1.f);
/* \\--------------------------------------------------------------// */
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (12 * dpi_scale));
ImGui::BeginChild("##content_area", ImVec2(686 * dpi_scale, 479 * dpi_scale)); // there wiil be main cheat functional
{ // KEYWORD : FUNC_FIND
ImGui::PushFont(futura);
if (last_tab > 4)
child_height = 471;
else
child_height = 435;
// push alpha-channel adjustment
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (1.f - preview_alpha) * m_alpha);
// semitabs rendering
switch (last_tab % 9)
{
case 0: draw_tabs_ragebot(); break;
case 1: draw_tabs_legit(); break;
case 2: draw_tabs_visuals(); break;
case 3: draw_tabs_players(); break;
case 4: draw_tabs_misc(); break;
default: break;
}
ImGui::PopStyleVar();
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (6 * dpi_scale) + ((dpi_scale - 1.f) * 8.f));
ImGui::BeginGroup(); // groupping two childs to prevent multipadding
{
ImGui::PushFont(futura_small);
if (last_tab == 2 && visuals_section == 2)
{
draw_visuals(-1);
}
else if (last_tab == 5)
{
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (1.f - preview_alpha)* m_alpha);
draw_settings(0);
}
else
{
ImGui::BeginChild("##content_first", ImVec2(339 * dpi_scale, child_height * dpi_scale)); // first functional child
{
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (1.f - preview_alpha) * m_alpha);
switch (last_tab % 9)
{
case 0: draw_ragebot(0); break;
case 1: draw_legit(0); break;
case 2: draw_visuals(0); break;
case 3: draw_players(0); break;
case 4: draw_misc(0); break;
case 6: draw_lua(0); break;
case 7: draw_radar(0); break;
case 8: draw_profile(0); break;
default: break;
}
}
ImGui::EndChild();
ImGui::SameLine();
ImGui::BeginChild("##content_second", ImVec2(339 * dpi_scale, child_height * dpi_scale)); // second functional child
{
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (1.f - preview_alpha) * m_alpha);
switch (last_tab % 9)
{
case 0: draw_ragebot(1); break;
case 1: draw_legit(1); break;
case 2: draw_visuals(1); break;
case 3: draw_players(1); break;
case 4: draw_misc(1); break;
case 6: draw_lua(1); break;
case 7: draw_radar(1); break;
case 8: draw_profile(1); break;
default: break;
}
}
ImGui::EndChild();
}
ImGui::PopFont();
};
ImGui::EndGroup();
ImGui::PopFont();
}
ImGui::EndChild();
ImGui::EndGroup();
/* ------ BOTTOM ------ */
// Fill bottom
ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorPos() + p, ImGui::GetCursorPos() + p + ImVec2(850 * dpi_scale, ((dpi_scale >= 1.04f && dpi_scale <= 1.07f) ? 2 : 0) + (29 * dpi_scale + (9.45f * (dpi_scale - 1.f)))), ImGui::ColorConvertFloat4ToU32(ImVec4(66 / 255.f, 68 / 255.f, 125 / 255.f, m_alpha)), 7.f * dpi_scale, ImDrawCornerFlags_Bot);
ImGui::PushFont(gotham);
ImGui::SetCursorPos(ImGui::GetCursorPos() + ImVec2(850 * dpi_scale - ImGui::CalcTextSize("legendawre.pw v3").x - (11 * dpi_scale), (16 * dpi_scale) - (ImGui::CalcTextSize("legendawre.pw v3").y / 2)));
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.f, 1.f, 1.f, 1.f));
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, m_alpha);
ImGui::Text("legendware.pw v3");
ImGui::PopStyleVar();
ImGui::PopStyleColor();
ImGui::PopFont();
}
ImGui::End();
ImGui::PopStyleColor();
ImGui::PopStyleVar();
}
|
ff85956820babb37600b0f78862b6c88d564ddd0
|
70fe255d0a301952a023be5e1c1fefd062d1e804
|
/剑指Offer注解/21.cpp
|
ba042e35c8804389f23db97535e0b3df6cc0d39f
|
[
"MIT"
] |
permissive
|
LauZyHou/Algorithm-To-Practice
|
524d4318032467a975cf548d0c824098d63cca59
|
66c047fe68409c73a077eae561cf82b081cf8e45
|
refs/heads/master
| 2021-06-18T01:48:43.378355
| 2021-01-27T14:44:14
| 2021-01-27T14:44:14
| 147,997,740
| 8
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,606
|
cpp
|
21.cpp
|
#include<bits/stdc++.h>
using namespace std;
void Reorder(int *pData, unsigned int length, bool (*func)(int));
bool isEven(int n);
//输入要做操作的数组,数组的长度
void ReorderOddEven_2(int *pData, unsigned int length) {
Reorder(pData, length, isEven);//在这里传入要用于判断的函数
//当条件改变时,只要再写一个函数,然后在这里改变传进去的函数即可
}
//输入要做操作的数组,数组的长度,用于判断的函数指针(一个int参数,返回值是bool)
void Reorder(int *pData, unsigned int length, bool (*func)(int)) {
//输入非空校验
if(pData == nullptr || length == 0)
return;
int *pBegin = pData;//左侧指针从第一个元素开始
int *pEnd = pData + length - 1;//右侧指针从最后一个元素开始
//只要两指针尚未相遇
while(pBegin < pEnd) {
//向右移动pBegin,直到函数对其计算为false
while(pBegin < pEnd && !func(*pBegin))
pBegin ++;
//向左移动pEnd,直到函数对其计算为true
while(pBegin < pEnd && func(*pEnd))
pEnd --;
//再次检查它们没有相遇过
if(pBegin < pEnd) {
//交换它们所指向的两个元素的值
int temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
}
}
}
//解耦出的判断奇偶的函数
bool isEven(int n) {
//和1相与为0即为偶数,该函数当输入偶数时返回true
return (n & 1) == 0;
}
int main() {
int numbers[] = {1, 2, 3, 4, 5, 6, 7};
int length=sizeof(numbers)/sizeof(int);
ReorderOddEven_2(numbers,length);
for(int i=0;i<length;i++)
cout<<numbers[i]<<"\t";
return 0;
}
|
e74af3e927fdcbd21cedd723d0bc375641d8cb8c
|
a85d397a09ad060c3eefcaf977013423cef3f846
|
/Sheet2/source/CenterlineExtraction.cpp
|
411d5c70ee8d6d5a7f5a5d72897503f220a14163
|
[] |
no_license
|
skillii/MedBildA
|
4c5bcf6ae163919a43d7e71503e3087aa3ec2920
|
bea887178d7f465a96e2d724c945eded5e62c732
|
refs/heads/master
| 2020-12-24T15:58:28.896043
| 2012-06-25T18:49:53
| 2012-06-25T18:49:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,414
|
cpp
|
CenterlineExtraction.cpp
|
/*
* CenterlineExtraction.cpp
*
* Created on: Jun 20, 2012
* Author: tom
*/
#include "CenterlineExtraction.h"
#include "TubeDetection.h"
#include "Numericshelper.h"
#include <cmath>
const float CenterlineExtraction::threshold_low = 0.04f;
const float CenterlineExtraction::threshold_high = 0.15f;
const int CenterlineExtraction::skippixels = 3;
int CenterlineExtraction::readSavedFiles()
{
bool success = volumeHandler.readVolume("EV/0.mhd", true);
if (!success)
{
std::cout << "Error reading input volume EV/0.mhd!" << std::endl;
return EXIT_FAILURE;
}
// get the image from the volume handler class
this->eigenvector[0] = volumeHandler.getHostMem();
volumeHandler.getOrigMinMaxValues(min_vals_eigenvector[0], max_vals_eigenvector[0]);
success = volumeHandler.readVolume("EV/1.mhd", true);
if (!success)
{
std::cout << "Error reading input volume EV/1.mhd!" << std::endl;
return EXIT_FAILURE;
}
// get the image from the volume handler class
this->eigenvector[1] = volumeHandler.getHostMem();
volumeHandler.getOrigMinMaxValues(min_vals_eigenvector[1], max_vals_eigenvector[1]);
success = volumeHandler.readVolume("EV/2.mhd", true);
if (!success)
{
std::cout << "Error reading input volume EV/2.mhd!" << std::endl;
return EXIT_FAILURE;
}
// get the image from the volume handler class
this->eigenvector[2] = volumeHandler.getHostMem();
volumeHandler.getOrigMinMaxValues(min_vals_eigenvector[2], max_vals_eigenvector[2]);
success = volumeHandler.readVolume("medialness/max.mhd", true);
if (!success)
{
std::cout << "Error reading input volume medialness/max.mhd!" << std::endl;
return EXIT_FAILURE;
}
// get the image from the volume handler class
this->maxMedialnessOverScales = volumeHandler.getHostMem();
volumeHandler.getOrigMinMaxValues(this->min_val_maxMedialness, this->max_val_maxMedialness);
return EXIT_SUCCESS;
}
void printVector(itk::Vector<float, 3> v)
{
std::cout << v[0] << " " << v[1] << " " << v[2] << std::endl;
}
void CenterlineExtraction::performReconnection()
{
FloatImageType::IndexType index;
itk::Vector<float, 3> v;
std::cout << "starting reconnection: " << std::endl;
DuplicatorType::Pointer duplicator = DuplicatorType::New();
duplicator->SetInputImage(maxMedialnessOverScales);
duplicator->Update();
centerlineImage = duplicator->GetOutput();
SetAllPixels(centerlineImage, 0.0f);
while(!reconnectionQueue.empty())
{
index = reconnectionQueue.front();
reconnectionQueue.pop();
v[0] = this->eigenvector[0]->GetPixel(index);
v[1] = this->eigenvector[1]->GetPixel(index);
v[2] = this->eigenvector[2]->GetPixel(index);
//printVector(v);
performReconnection(index, v);
//performReconnection(index, -v);
}
std::cout << "finished reconnection: " << std::endl;
}
void CenterlineExtraction::performReconnection(FloatImageType::IndexType index, itk::Vector<float, 3> direction)
{
int x,y,z;
unsigned int x_size;
unsigned int y_size;
unsigned int z_size;
float pixelvalue;
float initialvalue;
int pathlength = 0;
static int total_pathlength = 0;
static int count = 0;
direction.Normalize();
itk::Vector<float, 3> pos;
x_size = maxMedialnessOverScales->GetLargestPossibleRegion().GetSize(0);
y_size = maxMedialnessOverScales->GetLargestPossibleRegion().GetSize(1);
z_size = maxMedialnessOverScales->GetLargestPossibleRegion().GetSize(2);
initialvalue = maxMedialnessOverScales->GetPixel(index);
//initialvalue = 1.0f;
centerlineImage->SetPixel(index, initialvalue);
//centerlineImage->SetPixel(index, initialvalue);
pos[0] = index[0];
pos[1] = index[1];
pos[2] = index[2];
int skipped_positions = 0;
std::queue<FloatImageType::IndexType> skipped_queue;
itk::Vector<float, 3> old_direction = direction;
FloatImageType::IndexType nearestNeighbour = index;
while(1)
{
direction[0] = this->eigenvector[0]->GetPixel(nearestNeighbour);
direction[1] = this->eigenvector[1]->GetPixel(nearestNeighbour);
direction[2] = this->eigenvector[2]->GetPixel(nearestNeighbour);
direction.Normalize();
if(abs(direction * old_direction) > cos(90))
{
if(direction * old_direction < 0)
direction = -direction;
}
else
direction = old_direction;
pos = pos + direction;
old_direction = direction;
x = static_cast<unsigned>(floor(pos[0]));
y = static_cast<unsigned>(floor(pos[1]));
z = static_cast<unsigned>(floor(pos[2]));
//boundary check:
if(x < 0 || x >= (int)x_size || y < 0 || y >= (int)y_size || z < 0 || z >= (int)z_size)
break;
nearestNeighbour[0] = x; nearestNeighbour[1] = y; nearestNeighbour[2] = z;
pixelvalue = maxMedialnessOverScales->GetPixel(nearestNeighbour);
//pixelvalue = NumericsHelper::trilinearInterp(maxMedialnessOverScales, pos[0], pos[1], pos[2]);
if(pixelvalue > threshold_low)
{
if(initialvalue > centerlineImage->GetPixel(nearestNeighbour))
centerlineImage->SetPixel(nearestNeighbour, initialvalue);
pathlength++;
while(skipped_queue.size() != 0)
{
std::cout << "skipping(pathlength=" << pathlength++ << ")" << std::endl;
centerlineImage->SetPixel(skipped_queue.front(), initialvalue);
skipped_queue.pop();
}
skipped_positions = 0;
}
else
{
/*itk::Vector<float, 3> neighbourdir;
if(getMaxNeighbour(nearestNeighbour, neighbourdir) > threshold_low)
{
if(neighbourdir*direction > -0.5) //don't go back!
{
centerlineImage->SetPixel(nearestNeighbour, 1);
pos = pos + neighbourdir;
direction = neighbourdir;
std::cout << "----------------------------" << std::endl;
std::cout << "----------------------------" << std::endl;
std::cout << "----------------------------" << std::endl;
std::cout << "----------------------------" << std::endl;
pathlength++;
continue;
}
}*/
skipped_positions++;
if(skipped_positions > skippixels)
break;
else
skipped_queue.push(nearestNeighbour);
}
}
total_pathlength += pathlength;
count++;
std::cout << "total length of reconnection: " << pathlength << std::endl;
std::cout << "mean pathlength: " << static_cast<float>(total_pathlength) / count << std::endl;
}
float CenterlineExtraction::getMaxNeighbour(FloatImageType::IndexType index, itk::Vector<float, 3> &direction)
{
float value;
int x,y,z;
FloatImageType::IndexType ind;
FloatImageType::IndexType maxInd;
float max = 0;
for(x = -1; x <= 1; x++)
{
for(y = -1; y <= 1; y++)
{
for(z = -1; z <= 1; z++)
{
if(x == 0 && y == 0 && z == 0)
continue;
ind[0] = index[0] + x;
ind[1] = index[1] + y;
ind[2] = index[2] + z;
value = maxMedialnessOverScales->GetPixel(ind);
if(value >= max)
{
max = value;
maxInd = ind;
}
}
}
}
direction[0] = maxInd[0] - ind[0];
direction[1] = maxInd[1] - ind[1];
direction[2] = maxInd[2] - ind[2];
return max;
}
void CenterlineExtraction::SetAllPixels(FloatImageType::Pointer img, float value)
{
unsigned int x, y, z;
unsigned int x_size;
unsigned int y_size;
unsigned int z_size;
FloatImageType::IndexType index;
x_size = img->GetLargestPossibleRegion().GetSize(0);
y_size = img->GetLargestPossibleRegion().GetSize(1);
z_size = img->GetLargestPossibleRegion().GetSize(2);
for(x = 0; x < x_size; x++)
{
index[0] = x;
for(y = 0; y < y_size; y++)
{
index[1] = y;
for(z = 0; z < z_size; z++)
{
index[2] = z;
img->SetPixel(index, value);
}
}
}
}
void CenterlineExtraction::performNonMaximaSurpression()
{
unsigned x,y,z;
int i;
int isMax;
unsigned int x_size;
unsigned int y_size;
unsigned int z_size;
FloatImageType::IndexType index;
std::cout << "Starting non-Maxima supression" << std::endl;
x_size = maxMedialnessOverScales->GetLargestPossibleRegion().GetSize(0);
y_size = maxMedialnessOverScales->GetLargestPossibleRegion().GetSize(1);
z_size = maxMedialnessOverScales->GetLargestPossibleRegion().GetSize(2);
float current_medialness_value;
float neighbor_medialness_value;
itk::Vector<float, 3> v;
itk::Vector<float, 3> v_i[2];
float alpha_step = 2*M_PI/TubeDetection::alpha_steps;
float alpha = 0;
for(x = 0; x < x_size; x++)
{
index[0] = x;
if(x % 10 == 0)
std::cout << "x " << x << std::endl;
for(y = 0; y < y_size; y++)
{
index[1] = y;
for(z = 0; z < z_size; z++)
{
index[2] = z;
current_medialness_value = maxMedialnessOverScales->GetPixel(index);
if(current_medialness_value < threshold_low)
{
maxMedialnessOverScales->SetPixel(index,0);
continue;
}
//Calculate other 2 eigenvector here and perform non-maxima surpression
v[0] = this->eigenvector[0]->GetPixel(index);
v[1] = this->eigenvector[1]->GetPixel(index);
v[2] = this->eigenvector[2]->GetPixel(index);
v.Normalize();
if(v[2] < 0.5)
{
v_i[0][0] = -v[1];
v_i[0][1] = v[0];
v_i[0][2] = 0;
v_i[0].Normalize();
}
else
{
v_i[0][0] = -v[2];
v_i[0][1] = 0;
v_i[0][2] = v[0];
v_i[0].Normalize();
}
v_i[1] = itk::CrossProduct(v,v_i[0]);
v_i[1].Normalize();
isMax = 1;
//Check out the neighborinos
for(i = 0; i < TubeDetection::alpha_steps; i++, alpha += alpha_step)
{
v = v_i[0]*cosf(alpha) + v_i[1]*sinf(alpha);
neighbor_medialness_value = NumericsHelper::trilinearInterp(maxMedialnessOverScales,
v[0] + x, v[1] + y, v[2] + z);
if(current_medialness_value < neighbor_medialness_value)
{
//Not a local maxima! Set value at index to 0
maxMedialnessOverScales->SetPixel(index,0);
isMax = 0;
break;
}
}
if(isMax && current_medialness_value > threshold_high)
reconnectionQueue.push(index);
}
}
}
}
|
a655e24905a3f47df0f8721c4566347a73b4246d
|
36c31b485a5906ab514c964491b8f001a70a67f5
|
/Codeforces/CF 1300 - 1399/CF1395/CF1395F.cpp
|
f85faf200d1b0f7735fca74bac89c48992e46129
|
[] |
no_license
|
SMiles02/CompetitiveProgramming
|
77926918d5512824900384639955b31b0d0a5841
|
035040538c7e2102a88a2e3587e1ca984a2d9568
|
refs/heads/master
| 2023-08-18T22:14:09.997704
| 2023-08-13T20:30:42
| 2023-08-13T20:30:42
| 277,504,801
| 25
| 5
| null | 2022-11-01T01:34:30
| 2020-07-06T09:54:44
|
C++
|
UTF-8
|
C++
| false
| false
| 1,046
|
cpp
|
CF1395F.cpp
|
#include <bits/stdc++.h>
#define ll long long
#define sz(x) (int)(x).size()
using namespace std;
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
int n,a1=5e5,a2=0,b1=5e5,b2=0,x,y,c=0,d=1e6,e=0,f=1e6;
cin>>n;
string s;
for (int i=0;i<n;++i)
{
cin>>s;
x=0;y=0;
for (auto c : s)
{
if (c=='B')
++x;
else
++y;
}
a1=min(x,a1);
a2=max(x,a2);
b1=min(y,b1);
b2=max(y,b2);
cout<<x<<" "<<y<<"\n";
}
for (int i=0;i<500001;++i)
{
if (max(abs(a1-i),abs(a2-i))<=d)
{
d=max(abs(a1-i),abs(a2-i));
c=i;
}
if (max(abs(b1-i),abs(b2-i))<=f)
{
f=max(abs(b1-i),abs(b2-i));
e=i;
}
}
cout<<c<<" "<<e<<"!!!\n";
cout<<max(max(abs(b1-e),abs(b2-e)),max(abs(a1-c),abs(a2-c)))<<"\n";
for (int i=0;i<e;++i)
cout<<"N";
for (int i=0;i<c;++i)
cout<<"B";
return 0;
}
|
5bc1719658b3f3f203a96e102fc319dc2c9441e4
|
7d03e3c7f7ab8c301290904bf0e44e09652d0d3d
|
/plugins/Type-length-value/Interface/core_interface.h
|
2fb76ddf2fef389af689e33c8725478d04247a93
|
[] |
no_license
|
mak733/Flashlight
|
1755917d62cd2b64d92780086445ed8efd073bda
|
3f41027eb0f77847588a4a72ae5321478ea6adbd
|
refs/heads/master
| 2021-10-27T09:37:01.059168
| 2021-10-13T09:15:51
| 2021-10-13T09:15:51
| 248,747,908
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 738
|
h
|
core_interface.h
|
#ifndef CORE_INTERFACE_H
#define CORE_INTERFACE_H
//Подумать над размещением этого интерфейса в иерархии плагинов.
//Следует разместить этот класс в папке plugins, и применять его к новым протоколам
#include <QtPlugin>
class CoreInterface {
public:
virtual ~CoreInterface() {}
virtual QVariant value(const QString &member,
const QByteArray &data) const = 0;
virtual QString name() const = 0;
virtual quint8 codogrammType() const = 0;
virtual quint8 protocol() const = 0;
};
Q_DECLARE_INTERFACE(CoreInterface, "CoreInterface")
#endif // CORE_INTERFACE_H
|
dfb739a8e50c8ffc820cea12750bccf4eb8f1852
|
9939aab9b0bd1dcf8f37d4ec315ded474076b322
|
/libs/core/datastructures/tests/performance/small_vector_benchmark.cpp
|
964a3aa75c0a64e69e31be8fc88881eeb40d9a50
|
[
"BSL-1.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
STEllAR-GROUP/hpx
|
1068d7c3c4a941c74d9c548d217fb82702053379
|
c435525b4631c5028a9cb085fc0d27012adaab8c
|
refs/heads/master
| 2023-08-30T00:46:26.910504
| 2023-08-29T14:59:39
| 2023-08-29T14:59:39
| 4,455,628
| 2,244
| 500
|
BSL-1.0
| 2023-09-14T13:54:12
| 2012-05-26T15:02:39
|
C++
|
UTF-8
|
C++
| false
| false
| 3,536
|
cpp
|
small_vector_benchmark.cpp
|
// Copyright (c) 2022 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#include <hpx/config.hpp>
#include <hpx/chrono.hpp>
#include <hpx/datastructures/detail/small_vector.hpp>
#include <hpx/functional.hpp>
#include <hpx/init.hpp>
#include <cstddef>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
template <typename Container>
std::uint64_t measure(std::size_t repeat, std::size_t size)
{
std::uint64_t start = hpx::chrono::high_resolution_clock::now();
for (std::size_t i = 0; i != repeat; ++i)
{
Container cont;
for (std::size_t i = 0; i != size; ++i)
{
cont.push_back(typename Container::value_type{});
}
}
return (hpx::chrono::high_resolution_clock::now() - start) / repeat;
}
template <typename T, std::size_t N>
void compare(std::size_t repeat, std::size_t size)
{
std::uint64_t time = measure<hpx::detail::small_vector<T, N>>(repeat, size);
std::cout << "-----Average-(hpx::small_vector<" << typeid(T).name() << ", "
<< N << ">)------ \n"
<< std::left << "Average execution time : " << std::right
<< std::setw(8) << time / 1e9 << "\n";
}
int hpx_main(hpx::program_options::variables_map& vm)
{
// pull values from cmd
std::size_t repeat = vm["test_count"].as<std::size_t>();
std::size_t size = vm["vector_size"].as<std::size_t>();
std::cout << std::left
<< "----------------Parameters---------------------\n"
<< std::left
<< "Vector size : " << std::right
<< std::setw(8) << size << "\n"
<< std::left
<< "Number of tests : " << std::right
<< std::setw(8) << repeat << "\n"
<< std::left
<< "Display time in : " << std::right
<< std::setw(8) << "Seconds\n"
<< std::flush;
compare<int, 1>(repeat, size);
compare<int, 2>(repeat, size);
compare<int, 4>(repeat, size);
compare<int, 8>(repeat, size);
compare<int, 16>(repeat, size);
compare<hpx::move_only_function<void()>, 1>(repeat, size);
compare<hpx::move_only_function<void()>, 2>(repeat, size);
compare<hpx::move_only_function<void()>, 4>(repeat, size);
compare<hpx::move_only_function<void()>, 8>(repeat, size);
compare<hpx::move_only_function<void()>, 16>(repeat, size);
return hpx::local::finalize();
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
//initialize program
std::vector<std::string> const cfg = {"hpx.os_threads=1"};
using namespace hpx::program_options;
options_description cmdline("usage: " HPX_APPLICATION_STRING " [options]");
// clang-format off
cmdline.add_options()
("vector_size", value<std::size_t>()->default_value(10),
"size of vector")
("test_count", value<std::size_t>()->default_value(100000),
"number of tests to be averaged")
;
// clang-format on
hpx::local::init_params init_args;
init_args.desc_cmdline = cmdline;
init_args.cfg = cfg;
return hpx::local::init(hpx_main, argc, argv, init_args);
}
|
cef0f57786746bc8c9be7b422a2d798b02462f1c
|
5fa9510a4c45f6abc7a09cdf909de2451058dcdb
|
/BlindCurated75-problem/DecodeWays#24.cpp
|
d488fff08f671b0c7f325ff6ff12bbc04127413e
|
[] |
no_license
|
eecheng87/LeetCode-top-prob
|
5f8a4186bc9f6932377d3495fb2b59c399c119b7
|
8e1e8a1479efcdf3be3362da408066402658a4eb
|
refs/heads/main
| 2023-05-29T08:24:41.920355
| 2021-06-08T02:02:18
| 2021-06-08T02:02:18
| 334,911,200
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 835
|
cpp
|
DecodeWays#24.cpp
|
class Solution {
public:
int numDecodings(string s) {
if(s.size() < 1 || s[0] == '0')return 0;
int dp[s.size() + 1];
// dp[i] means # of method compose length i string
dp[0] = 1;
dp[1] = s[0] == '0' ? 0 : 1;
for(int i = 2; i <= s.size(); i++){
int digit = s[i - 2] - '0';
digit = digit * 10 + s[i - 1] - '0';
if(digit == 0 || (s[i - 1] == '0' && digit > 26))
return 0;
else if(s[i - 1] == '0')
dp[i] = dp[i - 2];
else if((digit > 0 && digit < 10) || (digit > 26))
dp[i] = dp[i - 1];
else if(digit > 10 && digit < 27)
dp[i] = dp[i - 1] + dp[i - 2];
else
return 0;
}
return dp[s.size()];
}
};
|
c1bcfc65bbe9fde4aeb95a29b7a6fb112942d811
|
6b36d141c261a00dc15d792929f6fd602e204d2a
|
/BOJ/6137.cpp
|
add408ca546cd863eacd3af7d9fe509a3cee555b
|
[] |
no_license
|
quasar0204/Problem-Solving
|
82bb5f79fca9300df5cc2e366f942563c5cf1cd8
|
68b52f326c5c402d9e9beb10307b947c62741445
|
refs/heads/master
| 2023-05-14T06:47:26.741138
| 2021-06-06T14:31:46
| 2021-06-06T14:31:46
| 290,471,843
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,293
|
cpp
|
6137.cpp
|
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <map>
#include <set>
#include <deque>
#include <random>
using namespace std;
#define all(v) (v).begin(),(v).end()
using pii = pair<int, int>;
using lint = long long;
using pll = pair<lint, lint>;
const int MOD = 1e9 + 7, INF = 987654321;
const lint LMOD = 1e9 + 7;
const lint LINF = 987654321987654321;
const int dr[] = { -1, 0, 1, 0 };
const int dc[] = { 0, -1, 0, 1 };
const double PI = 3.14159265359;
const int mxn = 10000;
int tc, cnt;
int n;
vector<char> arr;
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//code start
cin >> n;
arr.resize(n);
for (int i = 0; i < n; i++)
cin >> arr[i];
int l = 0, r = n - 1;
while (cnt < n) {
bool left = false;
for (int i = 0; i + l < r; i++) {
if (arr[l + i] < arr[r - i]) {
left = true;
break;
}
else if (arr[r - i] < arr[l + i])
break;
}
if (left) {
cout << arr[l];
l++;
}
else {
cout << arr[r];
r--;
}
cnt++;
if (cnt != 0 && cnt % 80 == 0) cout << '\n';
}
//code end
return 0;
}
|
c6444a238d2b6e259b79f71566d6e8cb7d729dbe
|
228a0cec7ea2dd2bb7a95739167a93e2a856f67c
|
/robot1.0__pre_pwmboard_/robot1.0__pre_pwmboard_.ino
|
6c12bd18496dcda268221529347ce8448dad033b
|
[] |
no_license
|
sherwinner/roboto
|
c2fa5b09fa4e7269ee5f0f506c76a19bdaede57e
|
22df2bc4596aa96f7346658a0f704c9e3ca2ac62
|
refs/heads/master
| 2020-03-10T00:17:16.908081
| 2018-04-28T11:56:07
| 2018-04-28T11:56:07
| 129,078,075
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,887
|
ino
|
robot1.0__pre_pwmboard_.ino
|
//add servo library
#include <Servo.h>
//define our servos
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
Servo servo5;
Servo servo6;
//define our potentiometers
int pot1 = A1;
int pot2 = A2;
int pot3 = A3;
int pot4 = A4;
int pot5 = A5;
int pot6 = A6;
//variable to read the values from the analog pin (potentiometers)
int valPot1;
int valPot2;
int valPot3;
int valPot4;
int valPot5;
int valPot6;
void setup()
{
//attaches our servos on pins PWM 3-5-6-9 to the servos
servo1.attach(3);// base turn
servo1.write(-10); //define servo1 start position
servo2.attach(5);// base tilt
servo2.write(-10); //define servo2 start position
servo3.attach(6);//elbow bend
servo3.write(90); //define servo3 start position
servo4.attach(9);// wrist bend
servo4.write(70); //define servo4 start position
servo5.attach(10);// claw turn
servo5.write(70); //define servo4 start position
servo6.attach(11);// claw grab
servo6.write(70); //define servo4 start position
Serial.begin(9600);
}
void loop()
{
//reads the value of potentiometers (value between 0 and 1023)
valPot1 = analogRead(pot1);
valPot1 = map (valPot1, 0, 1023, 0, 260); //scale it to use it with the servo (value between 0 and 180)
servo1.write(valPot1); //set the servo position according to the scaled value
Serial.println(valPot1);
valPot2 = analogRead(pot2);
valPot2 = map (valPot2, 0, 1023, 150, 0);
servo2.write(valPot2);
Serial.println(valPot2);
valPot3 = analogRead(pot3);
valPot3 = map (valPot3, 0, 1023, 0, 180);
servo3.write(valPot3);
valPot4 = analogRead(pot4);
valPot4 = map (valPot4, 0, 1023, 0, 145);
servo4.write(valPot4);
valPot5 = analogRead(pot5);
valPot5 = map (valPot5, 0, 1023, 180, 0);
servo5.write(valPot5);
valPot6 = analogRead(pot6);
valPot6 = map (valPot6, 0, 1023, 25, 105);
servo6.write(valPot6);
}
|
ad989aeb5d968213026641331c4d28ad6aa1e02c
|
461473dbd2713ff19eed84e21b40438ef0512763
|
/include/delfem2/ls_block_sparse.cpp
|
e489c0e579a00ae198d9a49e47e61cde92acac96
|
[
"MIT"
] |
permissive
|
nobuyuki83/delfem2
|
7211c7eb3c59293c4bc92d285600d6404952dea8
|
104f3deb80e7501b3dd5eea0456d10c4e5095753
|
refs/heads/master
| 2022-11-13T21:46:13.926755
| 2022-11-06T06:38:04
| 2022-11-06T06:38:04
| 140,655,906
| 194
| 21
|
MIT
| 2022-11-06T06:38:06
| 2018-07-12T03:25:11
|
C++
|
UTF-8
|
C++
| false
| false
| 19,513
|
cpp
|
ls_block_sparse.cpp
|
/*
* Copyright (c) 2019 Nobuyuki Umetani
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "delfem2/ls_block_sparse.h"
#include <cassert>
#include <complex>
namespace delfem2::mats {
DFM2_INLINE double MatNorm_Assym(
const double *V0,
unsigned int n0,
unsigned int m0,
const double *V1) {
double s = 0.0;
for (unsigned int i = 0; i < n0; ++i) {
for (unsigned int j = 0; j < m0; ++j) {
double v0 = V0[i * m0 + j];
double v1 = V1[j * n0 + i];
s += (v0 - v1) * (v0 - v1);
}
}
return s;
}
DFM2_INLINE double MatNorm(
const double *V,
unsigned int n,
unsigned int m) {
double s = 0.0;
for (unsigned int i = 0; i < n; ++i) {
for (unsigned int j = 0; j < m; ++j) {
double v = V[i * m + j];
s += v * v;
}
}
return s;
}
DFM2_INLINE double MatNorm_Assym(
const double *V,
unsigned int n) {
double s = 0.0;
for (unsigned int i = 0; i < n; ++i) {
for (unsigned int j = 0; j < n; ++j) {
double v0 = V[i * n + j];
double v1 = V[j * n + i];
s += (v0 - v1) * (v0 - v1);
}
}
return s;
}
template<typename T>
void MatVec_MatSparseCRS_Blk11(
T *y,
T alpha,
unsigned nrowblk,
const T *vcrs,
const T *vdia,
const unsigned int *colind,
const unsigned int *rowptr,
const T *x) {
for (unsigned int iblk = 0; iblk < nrowblk; iblk++) {
const unsigned int colind0 = colind[iblk];
const unsigned int colind1 = colind[iblk + 1];
for (unsigned int icrs = colind0; icrs < colind1; icrs++) {
const unsigned int jblk0 = rowptr[icrs];
y[iblk] += alpha * vcrs[icrs] * x[jblk0];
}
y[iblk] += alpha * vdia[iblk] * x[iblk];
}
}
template<typename T>
void MatVec_MatSparseCRS_Blk22(
T *y,
T alpha,
unsigned nrowblk,
const T *vcrs,
const T *vdia,
const unsigned int *colind,
const unsigned int *rowptr,
const T *x) {
for (unsigned int iblk = 0; iblk < nrowblk; iblk++) {
const unsigned int icrs0 = colind[iblk];
const unsigned int icrs1 = colind[iblk + 1];
for (unsigned int icrs = icrs0; icrs < icrs1; icrs++) {
const unsigned int jblk0 = rowptr[icrs];
y[iblk * 2 + 0] += alpha * (vcrs[icrs * 4] * x[jblk0 * 2 + 0] + vcrs[icrs * 4 + 1] * x[jblk0 * 2 + 1]);
y[iblk * 2 + 1] += alpha * (vcrs[icrs * 4 + 2] * x[jblk0 * 2 + 0] + vcrs[icrs * 4 + 3] * x[jblk0 * 2 + 1]);
}
y[iblk * 2 + 0] += alpha * (vdia[iblk * 4 + 0] * x[iblk * 2 + 0] + vdia[iblk * 4 + 1] * x[iblk * 2 + 1]);
y[iblk * 2 + 1] += alpha * (vdia[iblk * 4 + 2] * x[iblk * 2 + 0] + vdia[iblk * 4 + 3] * x[iblk * 2 + 1]);
}
}
template<typename T>
void MatVec_MatSparseCRS_Blk33(
T *y,
T alpha,
unsigned nrowblk,
const T *vcrs,
const T *vdia,
const unsigned int *colind,
const unsigned int *rowptr,
const T *x) {
for (unsigned int iblk = 0; iblk < nrowblk; iblk++) {
const unsigned int icrs0 = colind[iblk];
const unsigned int icrs1 = colind[iblk + 1];
for (unsigned int icrs = icrs0; icrs < icrs1; icrs++) {
const unsigned int jblk0 = rowptr[icrs];
const unsigned int i0 = iblk * 3;
const unsigned int j0 = jblk0 * 3;
const unsigned int k0 = icrs * 9;
y[i0 + 0] += alpha * (vcrs[k0 + 0] * x[j0 + 0] + vcrs[k0 + 1] * x[j0 + 1] + vcrs[k0 + 2] * x[j0 + 2]);
y[i0 + 1] += alpha * (vcrs[k0 + 3] * x[j0 + 0] + vcrs[k0 + 4] * x[j0 + 1] + vcrs[k0 + 5] * x[j0 + 2]);
y[i0 + 2] += alpha * (vcrs[k0 + 6] * x[j0 + 0] + vcrs[k0 + 7] * x[j0 + 1] + vcrs[k0 + 8] * x[j0 + 2]);
}
{
const unsigned int i0 = iblk * 3;
const unsigned int k0 = iblk * 9;
y[i0 + 0] += alpha * (vdia[k0 + 0] * x[i0 + 0] + vdia[k0 + 1] * x[i0 + 1] + vdia[k0 + 2] * x[i0 + 2]);
y[i0 + 1] += alpha * (vdia[k0 + 3] * x[i0 + 0] + vdia[k0 + 4] * x[i0 + 1] + vdia[k0 + 5] * x[i0 + 2]);
y[i0 + 2] += alpha * (vdia[k0 + 6] * x[i0 + 0] + vdia[k0 + 7] * x[i0 + 1] + vdia[k0 + 8] * x[i0 + 2]);
}
}
}
template<typename T>
void MatVec_MatSparseCRS_Blk44(
T *y,
T alpha,
unsigned nrowblk,
const T *vcrs,
const T *vdia,
const unsigned int *colind,
const unsigned int *rowptr,
const T *x) {
for (unsigned int iblk = 0; iblk < nrowblk; iblk++) {
const unsigned int icrs0 = colind[iblk];
const unsigned int icrs1 = colind[iblk + 1];
for (unsigned int icrs = icrs0; icrs < icrs1; icrs++) {
const unsigned int jblk0 = rowptr[icrs];
const unsigned int i0 = iblk * 4;
const unsigned int j0 = jblk0 * 4;
const unsigned int k0 = icrs * 16;
y[i0 + 0] +=
alpha * (
vcrs[k0 + 0] * x[j0 + 0] +
vcrs[k0 + 1] * x[j0 + 1] +
vcrs[k0 + 2] * x[j0 + 2] +
vcrs[k0 + 3] * x[j0 + 3]);
y[i0 + 1] +=
alpha * (
vcrs[k0 + 4] * x[j0 + 0] +
vcrs[k0 + 5] * x[j0 + 1] +
vcrs[k0 + 6] * x[j0 + 2] +
vcrs[k0 + 7] * x[j0 + 3]);
y[i0 + 2] +=
alpha * (
vcrs[k0 + 8] * x[j0 + 0] +
vcrs[k0 + 9] * x[j0 + 1] +
vcrs[k0 + 10] * x[j0 + 2] +
vcrs[k0 + 11] * x[j0 + 3]);
y[i0 + 3] +=
alpha * (
vcrs[k0 + 12] * x[j0 + 0] +
vcrs[k0 + 13] * x[j0 + 1] +
vcrs[k0 + 14] * x[j0 + 2] +
vcrs[k0 + 15] * x[j0 + 3]);
}
{
const unsigned int i0 = iblk * 4;
const unsigned int k0 = iblk * 16;
y[i0 + 0] +=
alpha * (
vdia[k0 + 0] * x[i0 + 0] +
vdia[k0 + 1] * x[i0 + 1] +
vdia[k0 + 2] * x[i0 + 2] +
vdia[k0 + 3] * x[i0 + 3]);
y[i0 + 1] +=
alpha * (
vdia[k0 + 4] * x[i0 + 0] +
vdia[k0 + 5] * x[i0 + 1] +
vdia[k0 + 6] * x[i0 + 2] +
vdia[k0 + 7] * x[i0 + 3]);
y[i0 + 2] +=
alpha * (
vdia[k0 + 8] * x[i0 + 0] +
vdia[k0 + 9] * x[i0 + 1] +
vdia[k0 + 10] * x[i0 + 2] +
vdia[k0 + 11] * x[i0 + 3]);
y[i0 + 3] +=
alpha * (
vdia[k0 + 12] * x[i0 + 0] +
vdia[k0 + 13] * x[i0 + 1] +
vdia[k0 + 14] * x[i0 + 2] +
vdia[k0 + 15] * x[i0 + 3]);
}
}
}
}
// -------------------------------------------------------
// Calc Matrix Vector Product
// {y} = alpha*[A]{x} + beta*{y}
template<typename T>
void delfem2::CMatrixSparse<T>::MatVec(
T *y,
T alpha,
const T *x,
T beta) const {
const unsigned int ndofcol = nrowdim_ * nrowblk_;
for (unsigned int i = 0; i < ndofcol; ++i) { y[i] *= beta; }
// --------
if (nrowdim_ == 1 && ncoldim_ == 1) {
mats::MatVec_MatSparseCRS_Blk11(
y,
alpha, nrowblk_, val_crs_.data(), val_dia_.data(),
col_ind_.data(), row_ptr_.data(), x);
} else if (nrowdim_ == 2 && ncoldim_ == 2) {
mats::MatVec_MatSparseCRS_Blk22(
y,
alpha, nrowblk_, val_crs_.data(), val_dia_.data(),
col_ind_.data(), row_ptr_.data(), x);
} else if (nrowdim_ == 3 && ncoldim_ == 3) {
mats::MatVec_MatSparseCRS_Blk33(
y,
alpha, nrowblk_, val_crs_.data(), val_dia_.data(),
col_ind_.data(), row_ptr_.data(), x);
} else if (nrowdim_ == 4 && ncoldim_ == 4) {
mats::MatVec_MatSparseCRS_Blk44(
y,
alpha, nrowblk_, val_crs_.data(), val_dia_.data(),
col_ind_.data(), row_ptr_.data(), x);
} else {
const unsigned int blksize = nrowdim_ * ncoldim_;
const T *vcrs = val_crs_.data();
const T *vdia = val_dia_.data();
const unsigned int *colind = col_ind_.data();
const unsigned int *rowptr = row_ptr_.data();
//
for (unsigned int iblk = 0; iblk < nrowblk_; iblk++) {
const unsigned int colind0 = colind[iblk];
const unsigned int colind1 = colind[iblk + 1];
for (unsigned int icrs = colind0; icrs < colind1; icrs++) {
assert(icrs < row_ptr_.size());
const unsigned int jblk0 = rowptr[icrs];
assert(jblk0 < ncolblk_);
for (unsigned int idof = 0; idof < nrowdim_; idof++) {
for (unsigned int jdof = 0; jdof < ncoldim_; jdof++) {
y[iblk * nrowdim_ + idof] +=
alpha * vcrs[icrs * blksize + idof * ncoldim_ + jdof] * x[jblk0 * ncoldim_ + jdof];
}
}
}
for (unsigned int idof = 0; idof < nrowdim_; idof++) {
for (unsigned int jdof = 0; jdof < ncoldim_; jdof++) {
y[iblk * nrowdim_ + idof] +=
alpha * vdia[iblk * blksize + idof * ncoldim_ + jdof] * x[iblk * ncoldim_ + jdof];
}
}
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::MatVec(
float *y, float alpha, const float *x, float beta) const;
template void delfem2::CMatrixSparse<double>::MatVec(
double *y, double alpha, const double *x, double beta) const;
template void delfem2::CMatrixSparse<std::complex<double>>::MatVec(
std::complex<double> *y, std::complex<double> alpha,
const std::complex<double> *x, std::complex<double> beta) const;
#endif
// -------------------------------------------------------
/**
* @brief Calc Matrix Vector Product {y} = alpha*[A]{x} + beta*{y}
* the 1x1 sparse matrix is expanded as the len x len sparse matrix
*/
template<typename T>
void delfem2::CMatrixSparse<T>::MatVecDegenerate(
T *y,
unsigned int len,
T alpha,
const T *x,
T beta) const {
assert(nrowdim_ == 1 && ncoldim_ == 1);
const unsigned int ndofcol = len * nrowblk_;
for (unsigned int i = 0; i < ndofcol; ++i) { y[i] *= beta; }
const T *vcrs = val_crs_.data();
const T *vdia = val_dia_.data();
const unsigned int *colind = col_ind_.data();
const unsigned int *rowptr = row_ptr_.data();
for (unsigned int iblk = 0; iblk < nrowblk_; iblk++) {
const unsigned int colind0 = colind[iblk];
const unsigned int colind1 = colind[iblk + 1];
for (unsigned int icrs = colind0; icrs < colind1; icrs++) {
assert(icrs < row_ptr_.size());
const unsigned int jblk0 = rowptr[icrs];
assert(jblk0 < ncolblk_);
const T mval0 = alpha * vcrs[icrs];
for (unsigned int ilen = 0; ilen < len; ilen++) {
y[iblk * len + ilen] += mval0 * x[jblk0 * len + ilen];
}
}
{ // compute diagonal
const T mval0 = alpha * vdia[iblk];
for (unsigned int ilen = 0; ilen < len; ilen++) {
y[iblk * len + ilen] += mval0 * x[iblk * len + ilen];
}
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::MatVecDegenerate(
float *y,
unsigned int len,
float alpha,
const float *x,
float beta) const;
template void delfem2::CMatrixSparse<double>::MatVecDegenerate(
double *y,
unsigned int len,
double alpha,
const double *x,
double beta) const;
#endif
// -------------------------------------------------------
// Calc Matrix Vector Product
// {y} = alpha*[A]^T{x} + beta*{y}
template<typename T>
void delfem2::CMatrixSparse<T>::MatTVec(
T *y,
T alpha,
const T *x,
T beta) const {
const unsigned int ndofrow = ncoldim_ * ncolblk_;
for (unsigned int i = 0; i < ndofrow; ++i) { y[i] *= beta; }
const unsigned int blksize = nrowdim_ * ncoldim_;
{
const T *vcrs = val_crs_.data();
const T *vdia = val_dia_.data();
const unsigned int *colind = col_ind_.data();
const unsigned int *rowptr = row_ptr_.data();
//
for (unsigned int iblk = 0; iblk < nrowblk_; iblk++) {
const unsigned int colind0 = colind[iblk];
const unsigned int colind1 = colind[iblk + 1];
for (unsigned int icrs = colind0; icrs < colind1; icrs++) {
assert(icrs < row_ptr_.size());
const unsigned int jblk0 = rowptr[icrs];
assert(jblk0 < ncolblk_);
for (unsigned int idof = 0; idof < nrowdim_; idof++) {
for (unsigned int jdof = 0; jdof < ncoldim_; jdof++) {
y[jblk0 * ncoldim_ + jdof] +=
alpha * vcrs[icrs * blksize + idof * ncoldim_ + jdof] * x[iblk * nrowdim_ + idof];
}
}
}
for (unsigned int jdof = 0; jdof < ncoldim_; jdof++) {
for (unsigned int idof = 0; idof < nrowdim_; idof++) {
y[iblk * ncoldim_ + jdof] +=
alpha * vdia[iblk * blksize + idof * ncoldim_ + jdof] * x[iblk * nrowdim_ + idof];
}
}
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::MatTVec(
float *y, float alpha, const float *x, float beta) const;
template void delfem2::CMatrixSparse<double>::MatTVec(
double *y, double alpha, const double *x, double beta) const;
template void delfem2::CMatrixSparse<std::complex<double>>::MatTVec(
std::complex<double> *y, std::complex<double> alpha,
const std::complex<double> *x, std::complex<double> beta) const;
#endif
// -----------------------------------------------------------------
template<typename T>
void delfem2::CMatrixSparse<T>::SetFixedBC_Dia(
const int *bc_flag,
T val_dia) {
assert(!this->val_dia_.empty());
assert(this->ncolblk_ == this->nrowblk_);
assert(this->ncoldim_ == this->nrowdim_);
const int blksize = nrowdim_ * ncoldim_;
for (unsigned int iblk = 0; iblk < nrowblk_; iblk++) { // set diagonal
for (unsigned int ilen = 0; ilen < nrowdim_; ilen++) {
if (bc_flag[iblk * nrowdim_ + ilen] == 0) continue;
for (unsigned int jlen = 0; jlen < ncoldim_; jlen++) {
val_dia_[iblk * blksize + ilen * nrowdim_ + jlen] = 0.0;
val_dia_[iblk * blksize + jlen * nrowdim_ + ilen] = 0.0;
}
val_dia_[iblk * blksize + ilen * nrowdim_ + ilen] = val_dia;
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::SetFixedBC_Dia(
const int *bc_flag, float val_dia);
template void delfem2::CMatrixSparse<double>::SetFixedBC_Dia(
const int *bc_flag, double val_dia);
template void delfem2::CMatrixSparse<std::complex<double>>::SetFixedBC_Dia(
const int *bc_flag, std::complex<double> val_dia);
#endif
// --------------------------
template<typename T>
void delfem2::CMatrixSparse<T>::SetFixedBC_Row(
const int *bc_flag) {
assert(!this->val_dia_.empty());
assert(this->ncolblk_ == this->nrowblk_);
assert(this->ncoldim_ == this->nrowdim_);
const int blksize = nrowdim_ * ncoldim_;
for (unsigned int iblk = 0; iblk < nrowblk_; iblk++) { // set row
for (unsigned int icrs = col_ind_[iblk]; icrs < col_ind_[iblk + 1]; icrs++) {
for (unsigned int ilen = 0; ilen < nrowdim_; ilen++) {
if (bc_flag[iblk * nrowdim_ + ilen] == 0) continue;
for (unsigned int jlen = 0; jlen < ncoldim_; jlen++) {
val_crs_[icrs * blksize + ilen * nrowdim_ + jlen] = 0.0;
}
}
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::SetFixedBC_Row(
const int *bc_flag);
template void delfem2::CMatrixSparse<double>::SetFixedBC_Row(
const int *bc_flag);
template void delfem2::CMatrixSparse<std::complex<double>>::SetFixedBC_Row(
const int *bc_flag);
#endif
// ---------------------------
template<typename T>
void delfem2::CMatrixSparse<T>::SetFixedBC_Col(
const int *bc_flag) {
assert(!this->val_dia_.empty());
assert(this->ncolblk_ == this->nrowblk_);
assert(this->ncoldim_ == this->nrowdim_);
const int blksize = nrowdim_ * ncoldim_;
for (unsigned int icrs = 0; icrs < row_ptr_.size(); icrs++) { // set column
const int jblk1 = row_ptr_[icrs];
for (unsigned int jlen = 0; jlen < ncoldim_; jlen++) {
if (bc_flag[jblk1 * ncoldim_ + jlen] == 0) continue;
for (unsigned int ilen = 0; ilen < nrowdim_; ilen++) {
val_crs_[icrs * blksize + ilen * nrowdim_ + jlen] = 0.0;
}
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::SetFixedBC_Col(const int *bc_flag);
template void delfem2::CMatrixSparse<double>::SetFixedBC_Col(const int *bc_flag);
template void delfem2::CMatrixSparse<std::complex<double>>::SetFixedBC_Col(const int *bc_flag);
#endif
// -----------------------------------------------------------------
DFM2_INLINE void delfem2::MatSparse_ScaleBlk_LeftRight(
delfem2::CMatrixSparse<double> &mat,
const double *scale) {
assert(mat.ncolblk_ == mat.nrowblk_);
assert(mat.ncoldim_ == mat.nrowdim_);
const unsigned int nblk = mat.nrowblk_;
const unsigned int len = mat.nrowdim_;
const unsigned int blksize = len * len;
for (unsigned int ino = 0; ino < nblk; ++ino) {
for (unsigned int icrs0 = mat.col_ind_[ino]; icrs0 < mat.col_ind_[ino + 1]; ++icrs0) {
const unsigned int jno = mat.row_ptr_[icrs0];
const double s0 = scale[ino] * scale[jno];
for (unsigned int i = 0; i < blksize; ++i) { mat.val_crs_[icrs0 * blksize + i] *= s0; }
}
}
if (!mat.val_dia_.empty()) {
for (unsigned int ino = 0; ino < nblk; ++ino) {
double s0 = scale[ino] * scale[ino];
for (unsigned int i = 0; i < blksize; ++i) { mat.val_dia_[ino * blksize + i] *= s0; }
}
}
}
DFM2_INLINE void delfem2::MatSparse_ScaleBlkLen_LeftRight(
delfem2::CMatrixSparse<double> &mat,
const double *scale) {
assert(mat.ncolblk_ == mat.nrowblk_);
assert(mat.ncoldim_ == mat.nrowdim_);
const unsigned int nblk = mat.nrowblk_;
const unsigned int len = mat.nrowdim_;
const unsigned int blksize = len * len;
for (unsigned int ino = 0; ino < nblk; ++ino) {
for (unsigned int icrs0 = mat.col_ind_[ino]; icrs0 < mat.col_ind_[ino + 1]; ++icrs0) {
const unsigned int jno = mat.row_ptr_[icrs0];
for (unsigned int ilen = 0; ilen < len; ++ilen) {
for (unsigned int jlen = 0; jlen < len; ++jlen) {
mat.val_crs_[icrs0 * blksize + ilen * len + jlen] *=
scale[ino * len + ilen] * scale[jno * len + jlen];
}
}
}
}
if (!mat.val_dia_.empty()) {
for (unsigned int ino = 0; ino < nblk; ++ino) {
for (unsigned int ilen = 0; ilen < len; ++ilen) {
for (unsigned int jlen = 0; jlen < len; ++jlen) {
mat.val_dia_[ino * blksize + ilen * len + jlen] *=
scale[ino * len + ilen] * scale[ino * len + jlen];
}
}
}
}
}
DFM2_INLINE double delfem2::CheckSymmetry(
const delfem2::CMatrixSparse<double> &mat) {
assert(mat.ncolblk_ == mat.nrowblk_);
assert(mat.ncoldim_ == mat.nrowdim_);
const unsigned int blksize = mat.nrowdim_ * mat.ncoldim_;
const unsigned int nlen = mat.nrowdim_;
//
double sum = 0;
for (unsigned int ino = 0; ino < mat.nrowblk_; ++ino) {
for (unsigned int icrs0 = mat.col_ind_[ino]; icrs0 < mat.col_ind_[ino + 1]; ++icrs0) {
unsigned int jno = mat.row_ptr_[icrs0];
unsigned int icrs1 = mat.col_ind_[jno];
for (; icrs1 < mat.col_ind_[jno + 1]; ++icrs1) {
if (mat.row_ptr_[icrs1] == ino) { break; }
}
if (icrs1 == mat.col_ind_[jno + 1]) { // no counterpart
sum += mats::MatNorm(
mat.val_crs_.data() + blksize * icrs0, mat.nrowdim_, mat.ncoldim_);
} else {
sum += mats::MatNorm_Assym(
mat.val_crs_.data() + blksize * icrs0, mat.nrowdim_, mat.ncoldim_,
mat.val_crs_.data() + blksize * icrs1);
}
}
sum += mats::MatNorm_Assym(mat.val_dia_.data() + blksize * ino, nlen);
}
return sum;
}
|
c9621f624e35399cc2b8ca0c025b2c470afe9ff5
|
092921fd9604b676d5a62f955513029231e30f19
|
/signature_test/src/libCrypto/Schnorr.cpp
|
c32805eb115af832cdd6c949067cc18d5ce3a5ce
|
[] |
no_license
|
LogosNetwork/crypto-function-benchmark
|
375ffb77309a50dae13d307b9c822ede6068950b
|
0468833f7735046c6c0a5d45d3090a89177c3176
|
refs/heads/master
| 2020-05-02T08:19:09.397721
| 2019-03-26T17:55:59
| 2019-03-26T17:55:59
| 177,839,603
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 31,970
|
cpp
|
Schnorr.cpp
|
/**
* Copyright (c) 2018 Zilliqa
* This source code is being disclosed to you solely for the purpose of your participation in
* testing Zilliqa. You may view, compile and run the code for that purpose and pursuant to
* the protocols and algorithms that are programmed into, and intended by, the code. You may
* not do anything else with the code without express permission from Zilliqa Research Pte. Ltd.,
* including modifying or publishing the code (or any part of it), and developing or forming
* another public or private blockchain network. This source code is provided ‘as is’ and no
* warranties are given as to title or non-infringement, merchantability or fitness for purpose
* and, to the extent permitted by law, all liability for your use of the code is disclaimed.
* Some programs in this code are governed by the GNU General Public License v3.0 (available at
* https://www.gnu.org/licenses/gpl-3.0.en.html) (‘GPLv3’). The programs that are governed by
* GPLv3.0 are those programs that are located in the folders src/depends and tests/depends
* and which include a reference to GPLv3 in their program files.
*
* This file implements the Schnorr signature standard from
* https://www.bsi.bund.de/SharedDocs/Downloads/EN/BSI/Publications/TechGuidelines/TR03111/BSI-TR-03111_pdf.pdf?__blob=publicationFile&v=1
* Refer to Section 4.2.3, page 24.
**/
#include "Sha2.h"
#include <openssl/bn.h>
#include <openssl/ec.h>
#include <openssl/err.h>
#include <openssl/obj_mac.h>
#include <array>
#include "Schnorr.h"
//#include "libUtils/Logger.h"
using namespace std;
//std::mutex BIGNUMSerialize::m_mutexBIGNUM;
//std::mutex ECPOINTSerialize::m_mutexECPOINT;
Curve::Curve()
: m_group(EC_GROUP_new_by_curve_name(NID_secp256k1), EC_GROUP_clear_free)
, m_order(BN_new(), BN_clear_free)
{
if (m_order == nullptr)
{
LOG_GENERAL(WARNING, "Curve order setup failed");
// throw exception();
}
if (m_group == nullptr)
{
LOG_GENERAL(WARNING, "Curve group setup failed");
// throw exception();
}
// Get group order
if (!EC_GROUP_get_order(m_group.get(), m_order.get(), NULL))
{
LOG_GENERAL(WARNING, "Recover curve order failed");
// throw exception();
}
}
Curve::~Curve() {}
//shared_ptr<BIGNUM> BIGNUMSerialize::GetNumber(const vector<unsigned char>& src,
// unsigned int offset,
// unsigned int size)
//{
// assert(size > 0);
// lock_guard<mutex> g(m_mutexBIGNUM);
//
// if (offset + size <= src.size())
// {
// BIGNUM* ret = BN_bin2bn(src.data() + offset, size, NULL);
// if (ret != NULL)
// {
// return shared_ptr<BIGNUM>(ret, BN_clear_free);
// }
// }
// else
// {
// LOG_GENERAL(WARNING,
// "Unable to get BIGNUM of size "
// << size << " from stream with available size "
// << src.size() - offset);
// }
//
// return nullptr;
//}
//
//void BIGNUMSerialize::SetNumber(vector<unsigned char>& dst, unsigned int offset,
// unsigned int size, shared_ptr<BIGNUM> value)
//{
// assert(size > 0);
// lock_guard<mutex> g(m_mutexBIGNUM);
//
// const int actual_bn_size = BN_num_bytes(value.get());
//
// //if (actual_bn_size > 0)
// {
// if (actual_bn_size <= static_cast<int>(size))
// {
// const unsigned int length_available = dst.size() - offset;
//
// if (length_available < size)
// {
// dst.resize(dst.size() + size - length_available);
// }
//
// // Pad with zeroes as needed
// const unsigned int size_diff
// = size - static_cast<unsigned int>(actual_bn_size);
// fill(dst.begin() + offset, dst.begin() + offset + size_diff, 0x00);
//
// if (BN_bn2bin(value.get(), dst.data() + offset + size_diff)
// != actual_bn_size)
// {
// LOG_GENERAL(WARNING, "Unexpected serialized size");
// }
// }
// else
// {
// LOG_GENERAL(WARNING,
// "BIGNUM size ("
// << actual_bn_size
// << ") exceeds requested serialize size (" << size
// << ")");
// }
// }
// // else
// // {
// // LOG_MESSAGE("Error: Zero-sized BIGNUM");
// // }
//}
//shared_ptr<EC_POINT>
//ECPOINTSerialize::GetNumber(const vector<unsigned char>& src,
// unsigned int offset, unsigned int size)
//{
// shared_ptr<BIGNUM> bnvalue = BIGNUMSerialize::GetNumber(src, offset, size);
// lock_guard<mutex> g(m_mutexECPOINT);
//
// if (bnvalue != nullptr)
// {
// unique_ptr<BN_CTX, void (*)(BN_CTX*)> ctx(BN_CTX_new(), BN_CTX_free);
// if (ctx == nullptr)
// {
// LOG_GENERAL(WARNING, "Memory allocation failure");
// // throw exception();
// }
//
// EC_POINT* ret
// = EC_POINT_bn2point(Schnorr::GetInstance().GetCurve().m_group.get(),
// bnvalue.get(), NULL, ctx.get());
// if (ret != NULL)
// {
// return shared_ptr<EC_POINT>(ret, EC_POINT_clear_free);
// }
// }
// return nullptr;
//}
//
//void ECPOINTSerialize::SetNumber(vector<unsigned char>& dst,
// unsigned int offset, unsigned int size,
// shared_ptr<EC_POINT> value)
//{
// shared_ptr<BIGNUM> bnvalue;
// {
// std::lock_guard<mutex> g(m_mutexECPOINT);
//
// unique_ptr<BN_CTX, void (*)(BN_CTX*)> ctx(BN_CTX_new(), BN_CTX_free);
// if (ctx == nullptr)
// {
// LOG_GENERAL(WARNING, "Memory allocation failure");
// // throw exception();
// }
//
// bnvalue.reset(
// EC_POINT_point2bn(Schnorr::GetInstance().GetCurve().m_group.get(),
// value.get(), POINT_CONVERSION_COMPRESSED, NULL,
// ctx.get()),
// BN_clear_free);
// if (bnvalue == nullptr)
// {
// LOG_GENERAL(WARNING, "Memory allocation failure");
// // throw exception();
// }
// }
//
// BIGNUMSerialize::SetNumber(dst, offset, size, bnvalue);
//}
PrivKey::PrivKey()
: m_d(BN_new(), BN_clear_free)
, m_initialized(false)
{
// kpriv->d should be in [1,...,order-1]
// -1 means no constraint on the MSB of kpriv->d
// 0 means no constraint on the LSB of kpriv->d
if (m_d != nullptr)
{
const Curve& curve = Schnorr::GetInstance().GetCurve();
m_initialized = true;
do
{
if (!BN_rand(m_d.get(), BN_num_bits(curve.m_order.get()), -1, 0))
{
LOG_GENERAL(WARNING, "Private key generation failed");
m_initialized = false;
break;
}
} while (BN_is_zero(m_d.get()) || BN_is_one(m_d.get())
|| (BN_cmp(m_d.get(), curve.m_order.get()) != -1));
}
else
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
}
}
//PrivKey::PrivKey(const vector<unsigned char>& src, unsigned int offset)
//{
// if (Deserialize(src, offset) != 0)
// {
// LOG_GENERAL(WARNING, "We failed to init PrivKey.");
// }
//}
PrivKey::PrivKey(const PrivKey& src)
: m_d(BN_new(), BN_clear_free)
, m_initialized(false)
{
if (m_d != nullptr)
{
if (BN_copy(m_d.get(), src.m_d.get()) == NULL)
{
LOG_GENERAL(WARNING, "PrivKey copy failed");
}
else
{
m_initialized = true;
}
}
else
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
}
}
PrivKey::~PrivKey() {}
bool PrivKey::Initialized() const { return m_initialized; }
//unsigned int PrivKey::Serialize(vector<unsigned char>& dst,
// unsigned int offset) const
//{
// // LOG_MARKER();
//
// if (m_initialized)
// {
// BIGNUMSerialize::SetNumber(dst, offset, PRIV_KEY_SIZE, m_d);
// }
//
// return PRIV_KEY_SIZE;
//}
//
//int PrivKey::Deserialize(const vector<unsigned char>& src, unsigned int offset)
//{
// // LOG_MARKER();
//
// try
// {
// m_d = BIGNUMSerialize::GetNumber(src, offset, PRIV_KEY_SIZE);
// if (m_d == nullptr)
// {
// LOG_GENERAL(WARNING, "Deserialization failure");
// m_initialized = false;
// }
// else
// {
// m_initialized = true;
// }
// }
// catch (const std::exception& e)
// {
// LOG_GENERAL(WARNING,
// "Error with PrivKey::Deserialize." << ' ' << e.what());
// return -1;
// }
// return 0;
//}
PrivKey& PrivKey::operator=(const PrivKey& src)
{
m_initialized = (BN_copy(m_d.get(), src.m_d.get()) == m_d.get());
return *this;
}
bool PrivKey::operator==(const PrivKey& r) const
{
return (m_initialized && r.m_initialized
&& (BN_cmp(m_d.get(), r.m_d.get()) == 0));
}
PubKey::PubKey()
: m_P(EC_POINT_new(Schnorr::GetInstance().GetCurve().m_group.get()),
EC_POINT_clear_free)
, m_initialized(false)
{
if (m_P == nullptr)
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
}
}
PubKey::PubKey(const PrivKey& privkey)
: m_P(EC_POINT_new(Schnorr::GetInstance().GetCurve().m_group.get()),
EC_POINT_clear_free)
, m_initialized(false)
{
if (m_P == nullptr)
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
}
else if (!privkey.Initialized())
{
LOG_GENERAL(WARNING, "Private key is not initialized");
}
else
{
const Curve& curve = Schnorr::GetInstance().GetCurve();
if (BN_is_zero(privkey.m_d.get()) || BN_is_one(privkey.m_d.get())
|| (BN_cmp(privkey.m_d.get(), curve.m_order.get()) != -1))
{
LOG_GENERAL(WARNING,
"Input private key is weak. Public key "
"generation failed");
return;
}
if (EC_POINT_mul(curve.m_group.get(), m_P.get(), privkey.m_d.get(),
NULL, NULL, NULL)
== 0)
{
LOG_GENERAL(WARNING, "Public key generation failed");
return;
}
m_initialized = true;
}
}
//PubKey::PubKey(const vector<unsigned char>& src, unsigned int offset)
//{
// if (Deserialize(src, offset) != 0)
// {
// LOG_GENERAL(WARNING, "We failed to init PubKey.");
// }
//}
PubKey::PubKey(const PubKey& src)
: m_P(EC_POINT_new(Schnorr::GetInstance().GetCurve().m_group.get()),
EC_POINT_clear_free)
, m_initialized(false)
{
if (m_P == nullptr)
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
}
else if (src.m_P == nullptr)
{
LOG_GENERAL(WARNING, "src (ec point) is null in pub key construct.");
// throw exception();
}
else
{
if (EC_POINT_copy(m_P.get(), src.m_P.get()) != 1)
{
LOG_GENERAL(WARNING, "PubKey copy failed");
}
else
{
m_initialized = true;
}
}
}
PubKey::~PubKey() {}
bool PubKey::Initialized() const { return m_initialized; }
//unsigned int PubKey::Serialize(vector<unsigned char>& dst,
// unsigned int offset) const
//{
// if (m_initialized)
// {
// ECPOINTSerialize::SetNumber(dst, offset, PUB_KEY_SIZE, m_P);
// }
//
// return PUB_KEY_SIZE;
//}
//
//int PubKey::Deserialize(const vector<unsigned char>& src, unsigned int offset)
//{
// // LOG_MARKER();
//
// try
// {
// m_P = ECPOINTSerialize::GetNumber(src, offset, PUB_KEY_SIZE);
// if (m_P == nullptr)
// {
// LOG_GENERAL(WARNING, "Deserialization failure");
// m_initialized = false;
// }
// else
// {
// m_initialized = true;
// }
// }
// catch (const std::exception& e)
// {
// LOG_GENERAL(WARNING,
// "Error with PubKey::Deserialize." << ' ' << e.what());
// return -1;
// }
// return 0;
//}
PubKey& PubKey::operator=(const PubKey& src)
{
m_initialized = (EC_POINT_copy(m_P.get(), src.m_P.get()) == 1);
return *this;
}
bool PubKey::operator<(const PubKey& r) const
{
unique_ptr<BN_CTX, void (*)(BN_CTX*)> ctx(BN_CTX_new(), BN_CTX_free);
if (ctx == nullptr)
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
return false;
}
shared_ptr<BIGNUM> lhs_bnvalue(
EC_POINT_point2bn(Schnorr::GetInstance().GetCurve().m_group.get(),
m_P.get(), POINT_CONVERSION_COMPRESSED, NULL,
ctx.get()),
BN_clear_free);
shared_ptr<BIGNUM> rhs_bnvalue(
EC_POINT_point2bn(Schnorr::GetInstance().GetCurve().m_group.get(),
r.m_P.get(), POINT_CONVERSION_COMPRESSED, NULL,
ctx.get()),
BN_clear_free);
return (m_initialized && r.m_initialized
&& (BN_cmp(lhs_bnvalue.get(), rhs_bnvalue.get()) == -1));
}
bool PubKey::operator>(const PubKey& r) const
{
unique_ptr<BN_CTX, void (*)(BN_CTX*)> ctx(BN_CTX_new(), BN_CTX_free);
if (ctx == nullptr)
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
return false;
}
shared_ptr<BIGNUM> lhs_bnvalue(
EC_POINT_point2bn(Schnorr::GetInstance().GetCurve().m_group.get(),
m_P.get(), POINT_CONVERSION_COMPRESSED, NULL,
ctx.get()),
BN_clear_free);
shared_ptr<BIGNUM> rhs_bnvalue(
EC_POINT_point2bn(Schnorr::GetInstance().GetCurve().m_group.get(),
r.m_P.get(), POINT_CONVERSION_COMPRESSED, NULL,
ctx.get()),
BN_clear_free);
return (m_initialized && r.m_initialized
&& (BN_cmp(lhs_bnvalue.get(), rhs_bnvalue.get()) == 1));
}
bool PubKey::operator==(const PubKey& r) const
{
unique_ptr<BN_CTX, void (*)(BN_CTX*)> ctx(BN_CTX_new(), BN_CTX_free);
if (ctx == nullptr)
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
return false;
}
return (m_initialized && r.m_initialized
&& (EC_POINT_cmp(Schnorr::GetInstance().GetCurve().m_group.get(),
m_P.get(), r.m_P.get(), ctx.get())
== 0));
}
Signature::Signature()
: m_r(BN_new(), BN_clear_free)
, m_s(BN_new(), BN_clear_free)
, m_initialized(false)
{
if ((m_r == nullptr) || (m_s == nullptr))
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
}
m_initialized = true;
}
//Signature::Signature(const vector<unsigned char>& src, unsigned int offset)
//{
//
// if (Deserialize(src, offset) != 0)
// {
// LOG_GENERAL(WARNING, "We failed to init Signature.");
// }
//}
Signature::Signature(const Signature& src)
: m_r(BN_new(), BN_clear_free)
, m_s(BN_new(), BN_clear_free)
, m_initialized(false)
{
if ((m_r != nullptr) && (m_s != nullptr))
{
m_initialized = true;
if (BN_copy(m_r.get(), src.m_r.get()) == NULL)
{
LOG_GENERAL(WARNING, "Signature challenge copy failed");
m_initialized = false;
}
if (BN_copy(m_s.get(), src.m_s.get()) == NULL)
{
LOG_GENERAL(WARNING, "Signature response copy failed");
m_initialized = false;
}
}
else
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
}
}
Signature::~Signature() {}
bool Signature::Initialized() const { return m_initialized; }
//unsigned int Signature::Serialize(vector<unsigned char>& dst,
// unsigned int offset) const
//{
// // LOG_MARKER();
//
// if (m_initialized)
// {
// BIGNUMSerialize::SetNumber(dst, offset, SIGNATURE_CHALLENGE_SIZE, m_r);
// BIGNUMSerialize::SetNumber(dst, offset + SIGNATURE_CHALLENGE_SIZE,
// SIGNATURE_RESPONSE_SIZE, m_s);
// }
//
// return SIGNATURE_CHALLENGE_SIZE + SIGNATURE_RESPONSE_SIZE;
//}
//
//int Signature::Deserialize(const vector<unsigned char>& src,
// unsigned int offset)
//{
// // LOG_MARKER();
//
// try
// {
// m_r = BIGNUMSerialize::GetNumber(src, offset, SIGNATURE_CHALLENGE_SIZE);
// if (m_r == nullptr)
// {
// LOG_GENERAL(WARNING, "Deserialization failure");
// m_initialized = false;
// }
// else
// {
// m_s = BIGNUMSerialize::GetNumber(src,
// offset + SIGNATURE_CHALLENGE_SIZE,
// SIGNATURE_RESPONSE_SIZE);
// if (m_s == nullptr)
// {
// LOG_GENERAL(WARNING, "Deserialization failure");
// m_initialized = false;
// }
// else
// {
// m_initialized = true;
// }
// }
// }
// catch (const std::exception& e)
// {
// LOG_GENERAL(WARNING,
// "Error with Signature::Deserialize." << ' ' << e.what());
// return -1;
// }
// return 0;
//}
Signature& Signature::operator=(const Signature& src)
{
m_initialized = ((BN_copy(m_r.get(), src.m_r.get()) == m_r.get())
&& (BN_copy(m_s.get(), src.m_s.get()) == m_s.get()));
return *this;
}
bool Signature::operator==(const Signature& r) const
{
return (m_initialized && r.m_initialized
&& ((BN_cmp(m_r.get(), r.m_r.get()) == 0)
&& (BN_cmp(m_s.get(), r.m_s.get()) == 0)));
}
Schnorr::Schnorr() {}
Schnorr::~Schnorr() {}
Schnorr& Schnorr::GetInstance()
{
static Schnorr schnorr;
return schnorr;
}
const Curve& Schnorr::GetCurve() const { return m_curve; }
pair<PrivKey, PubKey> Schnorr::GenKeyPair()
{
// LOG_MARKER();
//lock_guard<mutex> g(m_mutexSchnorr);
PrivKey privkey;
PubKey pubkey(privkey);
return make_pair(PrivKey(privkey), PubKey(pubkey));
}
bool Schnorr::Sign(const vector<unsigned char>& message, const PrivKey& privkey,
const PubKey& pubkey, Signature& result)
{
return Sign(message, 0, message.size(), privkey, pubkey, result);
}
bool Schnorr::Sign(const vector<unsigned char>& message, unsigned int offset,
unsigned int size, const PrivKey& privkey,
const PubKey& pubkey, Signature& result)
{
// LOG_MARKER();
//lock_guard<mutex> g(m_mutexSchnorr);
// Initial checks
if (message.size() == 0)
{
LOG_GENERAL(WARNING, "Empty message");
return false;
}
if (message.size() < (offset + size))
{
LOG_GENERAL(WARNING, "Offset and size beyond message size");
return false;
}
if (!privkey.Initialized())
{
LOG_GENERAL(WARNING, "Private key not initialized");
return false;
}
if (!pubkey.Initialized())
{
LOG_GENERAL(WARNING, "Public key not initialized");
return false;
}
if (!result.Initialized())
{
LOG_GENERAL(WARNING, "Signature not initialized");
return false;
}
// Main signing procedure
// The algorithm takes the following steps:
// 1. Generate a random k from [1, ..., order-1]
// 2. Compute the commitment Q = kG, where G is the base point
// 3. Compute the challenge r = H(Q, kpub, m)
// 4. If r = 0 mod(order), goto 1
// 4. Compute s = k - r*kpriv mod(order)
// 5. If s = 0 goto 1.
// 5 Signature on m is (r, s)
vector<unsigned char> buf(PUBKEY_COMPRESSED_SIZE_BYTES);
SHA2<HASH_TYPE::HASH_VARIANT_256> sha2;
bool err = false; // detect error
int res = 1; // result to return
unique_ptr<BIGNUM, void (*)(BIGNUM*)> k(BN_new(), BN_clear_free);
unique_ptr<EC_POINT, void (*)(EC_POINT*)> Q(
EC_POINT_new(m_curve.m_group.get()), EC_POINT_clear_free);
unique_ptr<BN_CTX, void (*)(BN_CTX*)> ctx(BN_CTX_new(), BN_CTX_free);
if ((k != nullptr) && (ctx != nullptr) && (Q != nullptr))
{
do
{
err = false;
// 1. Generate a random k from [1, ..., order-1]
do
{
// -1 means no constraint on the MSB of k
// 0 means no constraint on the LSB of k
err = (BN_rand(k.get(), BN_num_bits(m_curve.m_order.get()), -1,
0)
== 0);
if (err)
{
LOG_GENERAL(WARNING, "Random generation failed");
return false;
}
} while ((BN_is_zero(k.get()))
|| (BN_cmp(k.get(), m_curve.m_order.get()) != -1));
// 2. Compute the commitment Q = kG, where G is the base point
err = (EC_POINT_mul(m_curve.m_group.get(), Q.get(), k.get(), NULL,
NULL, NULL)
== 0);
if (err)
{
LOG_GENERAL(WARNING, "Commit generation failed");
return false;
}
// 3. Compute the challenge r = H(Q, kpub, m)
// Convert the committment to octets first
err = (EC_POINT_point2oct(m_curve.m_group.get(), Q.get(),
POINT_CONVERSION_COMPRESSED, buf.data(),
PUBKEY_COMPRESSED_SIZE_BYTES, NULL)
!= PUBKEY_COMPRESSED_SIZE_BYTES);
if (err)
{
LOG_GENERAL(WARNING, "Commit octet conversion failed");
return false;
}
// Hash commitment
sha2.Update(buf);
// Clear buffer
fill(buf.begin(), buf.end(), 0x00);
// Convert the public key to octets
err = (EC_POINT_point2oct(m_curve.m_group.get(), pubkey.m_P.get(),
POINT_CONVERSION_COMPRESSED, buf.data(),
PUBKEY_COMPRESSED_SIZE_BYTES, NULL)
!= PUBKEY_COMPRESSED_SIZE_BYTES);
if (err)
{
LOG_GENERAL(WARNING, "Pubkey octet conversion failed");
return false;
}
// Hash public key
sha2.Update(buf);
// Hash message
sha2.Update(message, offset, size);
vector<unsigned char> digest = sha2.Finalize();
// Build the challenge
err = ((BN_bin2bn(digest.data(), digest.size(), result.m_r.get()))
== NULL);
if (err)
{
LOG_GENERAL(WARNING, "Digest to challenge failed");
return false;
}
err = (BN_nnmod(result.m_r.get(), result.m_r.get(),
m_curve.m_order.get(), NULL)
== 0);
if (err)
{
LOG_GENERAL(WARNING, "BIGNUM NNmod failed");
return false;
}
// 4. Compute s = k - r*krpiv
// 4.1 r*kpriv
err = (BN_mod_mul(result.m_s.get(), result.m_r.get(),
privkey.m_d.get(), m_curve.m_order.get(),
ctx.get())
== 0);
if (err)
{
LOG_GENERAL(WARNING, "Response mod mul failed");
return false;
}
// 4.2 k-r*kpriv
err = (BN_mod_sub(result.m_s.get(), k.get(), result.m_s.get(),
m_curve.m_order.get(), ctx.get())
== 0);
if (err)
{
LOG_GENERAL(WARNING, "BIGNUM mod sub failed");
return false;
}
// Clear buffer
fill(buf.begin(), buf.end(), 0x00);
if (!err)
{
res = (BN_is_zero(result.m_r.get()))
|| (BN_is_zero(result.m_s.get()));
}
sha2.Reset();
} while (res);
}
else
{
LOG_GENERAL(WARNING, "Memory allocation failure");
return false;
// throw exception();
}
return (res == 0);
}
bool Schnorr::Verify(const vector<unsigned char>& message,
const Signature& toverify, const PubKey& pubkey)
{
return Verify(message, 0, message.size(), toverify, pubkey);
}
bool Schnorr::Verify(const vector<unsigned char>& message, unsigned int offset,
unsigned int size, const Signature& toverify,
const PubKey& pubkey)
{
// LOG_MARKER();
//lock_guard<mutex> g(m_mutexSchnorr);
// Initial checks
if (message.size() == 0)
{
LOG_GENERAL(WARNING, "Empty message");
return false;
}
if (message.size() < (offset + size))
{
LOG_GENERAL(WARNING, "Offset and size beyond message size");
return false;
}
if (!pubkey.Initialized())
{
LOG_GENERAL(WARNING, "Public key not initialized");
return false;
}
if (!toverify.Initialized())
{
LOG_GENERAL(WARNING, "Signature not initialized");
return false;
}
try
{
// Main verification procedure
// The algorithm to check the signature (r, s) on a message m using a public key kpub is as follows
// 1. Check if r,s is in [1, ..., order-1]
// 2. Compute Q = sG + r*kpub
// 3. If Q = O (the neutral point), return 0;
// 4. r' = H(Q, kpub, m)
// 5. return r' == r
vector<unsigned char> buf(PUBKEY_COMPRESSED_SIZE_BYTES);
SHA2<HASH_TYPE::HASH_VARIANT_256> sha2;
bool err = false;
bool err2 = false;
// Regenerate the commitmment part of the signature
unique_ptr<BIGNUM, void (*)(BIGNUM*)> challenge_built(BN_new(),
BN_clear_free);
unique_ptr<EC_POINT, void (*)(EC_POINT*)> Q(
EC_POINT_new(m_curve.m_group.get()), EC_POINT_clear_free);
unique_ptr<BN_CTX, void (*)(BN_CTX*)> ctx(BN_CTX_new(), BN_CTX_free);
if ((challenge_built != nullptr) && (ctx != nullptr) && (Q != nullptr))
{
// 1. Check if r,s is in [1, ..., order-1]
err2 = (BN_is_zero(toverify.m_r.get())
|| (BN_cmp(toverify.m_r.get(), m_curve.m_order.get())
!= -1));
err = err || err2;
if (err2)
{
LOG_GENERAL(WARNING, "Challenge not in range");
return false;
}
err2 = (BN_is_zero(toverify.m_s.get())
|| (BN_cmp(toverify.m_s.get(), m_curve.m_order.get())
!= -1));
err = err || err2;
if (err2)
{
LOG_GENERAL(WARNING, "Response not in range");
return false;
}
// 2. Compute Q = sG + r*kpub
err2 = (EC_POINT_mul(m_curve.m_group.get(), Q.get(),
toverify.m_s.get(), pubkey.m_P.get(),
toverify.m_r.get(), ctx.get())
== 0);
err = err || err2;
if (err2)
{
LOG_GENERAL(WARNING, "Commit regenerate failed");
return false;
}
// 3. If Q = O (the neutral point), return 0;
err2 = (EC_POINT_is_at_infinity(m_curve.m_group.get(), Q.get()));
err = err || err2;
if (err2)
{
LOG_GENERAL(WARNING, "Commit at infinity");
return false;
}
// 4. r' = H(Q, kpub, m)
// 4.1 Convert the committment to octets first
err2 = (EC_POINT_point2oct(m_curve.m_group.get(), Q.get(),
POINT_CONVERSION_COMPRESSED, buf.data(),
PUBKEY_COMPRESSED_SIZE_BYTES, NULL)
!= PUBKEY_COMPRESSED_SIZE_BYTES);
err = err || err2;
if (err2)
{
LOG_GENERAL(WARNING, "Commit octet conversion failed");
return false;
}
// Hash commitment
sha2.Update(buf);
// Reset buf
fill(buf.begin(), buf.end(), 0x00);
// 4.2 Convert the public key to octets
err2 = (EC_POINT_point2oct(m_curve.m_group.get(), pubkey.m_P.get(),
POINT_CONVERSION_COMPRESSED, buf.data(),
PUBKEY_COMPRESSED_SIZE_BYTES, NULL)
!= PUBKEY_COMPRESSED_SIZE_BYTES);
err = err || err2;
if (err2)
{
LOG_GENERAL(WARNING, "Pubkey octet conversion failed");
return false;
}
// Hash public key
sha2.Update(buf);
// 4.3 Hash message
sha2.Update(message, offset, size);
vector<unsigned char> digest = sha2.Finalize();
// 5. return r' == r
err2 = (BN_bin2bn(digest.data(), digest.size(),
challenge_built.get())
== NULL);
err = err || err2;
if (err2)
{
LOG_GENERAL(WARNING, "Challenge bin2bn conversion failed");
return false;
}
err2 = (BN_nnmod(challenge_built.get(), challenge_built.get(),
m_curve.m_order.get(), NULL)
== 0);
err = err || err2;
if (err2)
{
LOG_GENERAL(WARNING, "Challenge rebuild mod failed");
return false;
}
sha2.Reset();
}
else
{
LOG_GENERAL(WARNING, "Memory allocation failure");
// throw exception();
return false;
}
return (!err)
&& (BN_cmp(challenge_built.get(), toverify.m_r.get()) == 0);
}
catch (const std::exception& e)
{
LOG_GENERAL(WARNING, "Error with Schnorr::Verify." << ' ' << e.what());
return false;
}
}
void Schnorr::PrintPoint(const EC_POINT* point)
{
LOG_MARKER();
//lock_guard<mutex> g(m_mutexSchnorr);
unique_ptr<BIGNUM, void (*)(BIGNUM*)> x(BN_new(), BN_clear_free);
unique_ptr<BIGNUM, void (*)(BIGNUM*)> y(BN_new(), BN_clear_free);
if ((x != nullptr) && (y != nullptr))
{
// Get affine coordinates for the point
if (EC_POINT_get_affine_coordinates_GFp(m_curve.m_group.get(), point,
x.get(), y.get(), NULL))
{
unique_ptr<char, void (*)(void*)> x_str(BN_bn2hex(x.get()), free);
unique_ptr<char, void (*)(void*)> y_str(BN_bn2hex(y.get()), free);
if ((x_str != nullptr) && (y_str != nullptr))
{
LOG_GENERAL(INFO, "x: " << x_str.get());
LOG_GENERAL(INFO, "y: " << y_str.get());
}
}
}
}
|
193904adcf7bfa79d4990a777337e2c7270a7144
|
b4472ed45d300d163625bffc83e32d5d100ef595
|
/TAIFATECH/ANDROID/scJNI/src/cidana_screencap_Capture.cpp
|
2420356ed722ac7c421eb8e9f0b29878212adea3
|
[] |
no_license
|
cswei0501/SCREENCAPTURE
|
da44b8aff35efb92e53ab9272cf7397d5592f0c5
|
6e0c52711ed0467732617e7b73bf6f403df62b79
|
refs/heads/master
| 2020-12-30T02:31:46.347637
| 2013-09-12T02:52:09
| 2013-09-12T02:52:09
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 33,140
|
cpp
|
cidana_screencap_Capture.cpp
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "capture_control.h"
#include "cidana_screencap_Capture.h"
using namespace android;
/*****************************************************
* Func: CWiMoControl
* Function: construction function
* Parameters: void
*****************************************************/
CWiMoControl::CWiMoControl(JNIEnv * env, jobject thiz, jint videoMode, jint audioMode, char* libPath)
{
pCAudio = NULL;
pCPUControl = NULL;
pCNetwork = NULL;
pCVideo = NULL;
pdl = NULL;
Start_II = NULL;
Stop_V = NULL;
pVideoBuff = NULL;
iVideoSize = 0;
pAudioBuff = NULL;
pVidSrcBuff1 = NULL;
pVidSrcBuff2 = NULL;
iVidSrcBuffSize1 = 0;
iVidSrcBuffSize2 = 0;
bSrcBuffFlag1 = BUFFERWRITE;
bSrcBuffFlag2 = BUFFERWRITE;
currUpdate = 0;
prevUpdate = currUpdate - 1;
bLock = false;
bLimitedFPS = false;
m_calledScreenshot = CALLEDSHOTOFF;
iUIrotate = ROTATION_0;
rotateFlag = iUIrotate - 1;
checkCPUUtilization_hnd = 0;
checkTimoutThread_hnd = 0;
LoopVideoThread_hnd = 0;
bQuitJNIFlag = false;
bConvertWH = false;
bJNIInit = false;
iDeviceModel = -1;
m_env = env;
m_thiz = thiz;
iAudioCapMethod = METHOD_AUDIO_ERROR;
iCaptureMethod = METHOD_VIDEO_ERROR;
iTvRotate = CURRENT_TV_ROTATE_0;
statusWiMo = WIMO_STATUS_FINISH;
iCallingBuffIndex = CALLINGENTRANCEFIRSTLY;
iCallingSrcIndex = CALLINGENTRANCEFIRSTLY;
iVidDataType = -1;
memset(pAppLibPath, 0, sizeof(pAppLibPath));
memcpy(pAppLibPath, libPath, strlen(libPath));
memset(&sTimeBomb, 0, sizeof(sTimeBomb));
sTimeBomb.tm_year = TIME_BOMB_YEAR - INTERNATIONAL_STD_YEAR;
sTimeBomb.tm_mon = TIME_BOMB_MONTH;
sTimeBomb.tm_mday = TIME_BOMB_DAY;
sTimeBomb.tm_hour = TIME_BOMB_HOUR;
sTimeBomb.tm_min = TIME_BOMB_MINUTE;
sTimeBomb.tm_sec = TIME_BOMB_SECOND;
sTimeBomb.tm_isdst = 0;
timeBomb = (DDword)mktime(&sTimeBomb);
if(videoMode == JNI_TS_STREAM_INTERFACE) // for wimo2.0
{
iCaptureMethod = METHOD_TS_STREAM_INTERFACE;
iAudioCapMethod = METHOD_TS_AUD_STREAM;
}
else
{
//check audio mode
#ifdef AudioSWCapture
iAudioCapMethod = METHOD_SW_ANDROID_AUD_SPEAKER;
#else
if(audioMode == JNI_AUD_DEFAULT)
iAudioCapMethod = METHOD_AUDIO_DEFAULT;
else if(audioMode == JNI_AUDIO_SPEAKER)
iAudioCapMethod = METHOD_SW_ANDROID_AUD_SPEAKER;
else if(audioMode == JNI_AUDIO_METHOD_LNV)
iAudioCapMethod = METHOD_LNV_AUD_MIXER;
else if(audioMode == JNI_AUDIO_METHOD_HS)
iAudioCapMethod = METHOD_HS_AUD_MIXER;
else if(audioMode == JNI_AUDIO_METHOD_ZTE)
iAudioCapMethod = METHOD_ZTE_AUD_MIXER;
else if(audioMode == JNI_AUDIO_METHOD_GAME)
iAudioCapMethod = METHOD_GAME_AUDIO;
else if(audioMode == JNI_AUDIO_METHOD_HAOLIAN)
iAudioCapMethod = METHOD_SW_ANDROID_AUD_SPEAKER;
#endif
//check video mode
if(videoMode == JNI_HW_VID_INTERFACE)
iCaptureMethod = METHOD_HW_VIDEO_INTERFACE;
else if(videoMode == JNI_SW_VID_FRAMEBUFFER)
iCaptureMethod = METHOD_FRAMEBUFFER_INTERFACE;
else if(videoMode == JNI_SW_VID_SCREENSHOT)
iCaptureMethod = METHOD_SCREENSHOT_INTERFACE;
else if(videoMode == JNI_LNV_VIDEO_INTERFACE)
iCaptureMethod = METHOD_LNV_HW_INTERFACE;
else if(videoMode == JNI_HS_VIDEO_INTERFACE)
iCaptureMethod = METHOD_HS_HW_INTERFACE;
else if(videoMode == JNI_ZTE_VIDEO_INTERFACE)
iCaptureMethod = METHOD_ZTE_HW_INTERFACE;
else if(videoMode == JNI_GAME_VIDEO_INTERFACE)
iCaptureMethod = METHOD_GAME_INTERFACE;
else if(videoMode == JNI_HAOLIAN_VIDEO_INTERFACE)
{
iCaptureMethod = METHOD_FRAMEBUFFER_INTERFACE;
bLimitedFPS = true;
}
else if(videoMode == JNI_XIAOMI2_VIDEO_INTERFACE)
{
iDeviceModel = DEVICE_XIAOMI2_41;
iCaptureMethod = METHOD_FRAMEBUFFER_INTERFACE;
if(audioMode == JNI_AUDIO_METHOD_HAOLIAN)
bLimitedFPS = true;
}
}
if(iCaptureMethod == METHOD_HW_VIDEO_INTERFACE || iCaptureMethod == METHOD_GAME_INTERFACE)
{
pVidSrcBuff1 = (Byte*)malloc(VIDEO_SRC_BUFFER_SIZE);
if(pVidSrcBuff1 == NULL)
{
LOGE("malloc pVidSrcBuff1 failed!\n");
}
pVidSrcBuff2 = (Byte*)malloc(VIDEO_SRC_BUFFER_SIZE);
if(pVidSrcBuff2 == NULL)
{
LOGE("malloc pVidSrcBuff2 failed!\n");
}
}
if(iCaptureMethod == METHOD_HS_HW_INTERFACE && iAudioCapMethod == METHOD_HS_AUD_MIXER)
{
pdl = dlopen("/system/lib/libavcap.so", RTLD_NOW);
if(pdl != NULL)
{
Start_II = (pF_INT_INT)dlsym(pdl, "start");
Stop_V = (pF_VOID)dlsym(pdl, "stop");
}
else
{
LOGE("dlopen HS libs failed!\n");
iAudioCapMethod = METHOD_AUDIO_ERROR;
iCaptureMethod = METHOD_VIDEO_ERROR;
}
}
LOGI("iCaptureMethod:%d, iAudioCapMethod:%d\n", iCaptureMethod,iAudioCapMethod);
JniInit(m_env, m_thiz);
}
/*****************************************************
* Func: ~CWiMoControl
* Function: deconstruction function
* Parameters: void
*****************************************************/
CWiMoControl::~CWiMoControl()
{
JniUnInit(m_env, m_thiz);
if(pdl)
dlclose(pdl);
if(pVidSrcBuff1)
{
free(pVidSrcBuff1);
pVidSrcBuff1 = NULL;
}
if(pVidSrcBuff2)
{
free(pVidSrcBuff2);
pVidSrcBuff2 = NULL;
}
}
/*****************************************************
* Func: JniInit
* Function: jni init parameters
* Parameters:
* env: environment variable
* thiz: object
*****************************************************/
int CWiMoControl::JniInit(JNIEnv * env, jobject thiz)
{
if(bJNIInit) return S_OK;
if(!env || !thiz)
{
LOGE("FAILED to get env && thiz\n");
return E_INVALIDARG;
}
//get java method
env->GetJavaVM(&jCallbackFun.jvm);
if(!jCallbackFun.jvm)
{
LOGE("FAILED to get JVM \n");
return E_FAILED;
}
jCallbackFun.env = env;
jCallbackFun.obj = env->NewGlobalRef(thiz);
jCallbackFun.cls = env->GetObjectClass(thiz);
jCallbackFun.cls = (jclass)env->NewGlobalRef(jCallbackFun.cls);
jCallbackFun.callbackFuns = env->GetMethodID(jCallbackFun.cls, "javaCallback", "(I)I");
bJNIInit = true;
return S_OK;
}
/*****************************************************
* Func: JniUnInit
* Function: Release Video SC
* Parameters:
* env: environment variable
* thiz: object
*****************************************************/
int CWiMoControl::JniUnInit(JNIEnv * env, jobject thiz)
{
if(!bJNIInit) return S_OK;
jCallbackFun.env = env;
jCallbackFun.env->DeleteGlobalRef(jCallbackFun.obj);
jCallbackFun.env->DeleteGlobalRef(jCallbackFun.cls);
memset(&jCallbackFun,0,sizeof(jCallbackFun));
bJNIInit = false;
return S_OK;
}
/*****************************************************
* Function: StartWiMo
* Parameters: void
*****************************************************/
int CWiMoControl::StartWiMo()
{
#if 0
if(iCaptureMethod != METHOD_LNV_HW_INTERFACE && iCaptureMethod != METHOD_HS_HW_INTERFACE)
{
if(timeBomb < GetTickCount()/NumOneThousand)
{
LOGE("time bomb, please update version to newest!\n");
goto INIT_FAILED_JUMP;
}
}
#endif
if(statusWiMo == WIMO_STATUS_INITING
|| statusWiMo == WIMO_STATUS_CONNECTING)
return S_OK;
#if OUTLOG
LOGI("connecting, please wait for a moment...\n");
#endif
statusWiMo = WIMO_STATUS_INITING;
if(Init() != S_OK)
{
LOGE("failed to Init()!\n");
goto INIT_FAILED_JUMP;
}
checkTimoutThread_hnd = CreateThreadHelper(CheckConnectTimeoutThread, (void*)this);
if(checkTimoutThread_hnd == 0)
{
LOGE("creat thread CheckConnectTimeoutThread failed!\n");
goto INIT_FAILED_JUMP;
}
return S_OK;
INIT_FAILED_JUMP:
statusWiMo = WIMO_STATUS_FINISH;
NotifyUIStop();
UnInit();
return E_FAILED;
}
/*****************************************************
* Function: StopWiMo
* Parameters: void
*****************************************************/
int CWiMoControl::StopWiMo()
{
if(statusWiMo == WIMO_STATUS_FINISH)
return S_OK;
statusWiMo = WIMO_STATUS_FINISH;
if(iCaptureMethod != METHOD_TS_STREAM_INTERFACE)
{
if(checkCPUUtilization_hnd)
{
pthread_join(checkCPUUtilization_hnd, NULL);
checkCPUUtilization_hnd = 0;
}
if(LoopVideoThread_hnd)
{
pthread_join(LoopVideoThread_hnd, NULL);
LoopVideoThread_hnd = 0;
}
}
if(checkTimoutThread_hnd)
{
pthread_join(checkTimoutThread_hnd, NULL);
checkTimoutThread_hnd = 0;
}
UnInit();
#if OUTLOG
LOGI("Disconnection!\n");
#endif
return S_OK;
}
/*****************************************************
* Function: SendVideoData
* Parameters:
* data: jpeg data
* vSizeHW: the size of jpeg data
* width: jpeg width
* height: jpeg height
*****************************************************/
int CWiMoControl::SendVideoData(int dataType, char* data, int vSize, int width, int height, int rotate)
{
//LOGI("video dataType:%d,data:%d, vSize:%d,width:%d,height:%d,rotate:%d\n",dataType,*data, vSize,width,height,rotate);
if(vSize == 0)
{
if(width !=0 && height !=0)
{
ALIGNED_WIDTH = SRC_WIDTH = width;// &~ 7;
ALIGNED_HEIGTH = SRC_HEIGHT = height;// &~ 7;
iVidDataType = dataType;
if(JNI_VIDEO_TYPE_ARGB8888 == dataType)
iVidDataType = VIDEO_TYPE_ARGB8888;
else if(JNI_VIDEO_TYPE_JPEG == dataType)
iVidDataType = VIDEO_TYPE_JPEG;
}
else
{
LOGE("data is null\n");
return E_FAILED;
}
}
bLock = true;
// iUIrotate = rotate;
if(JNI_VIDEO_TYPE_ARGB8888 == dataType)
iVidDataType = VIDEO_TYPE_ARGB8888;
else if(JNI_VIDEO_TYPE_JPEG == dataType)
iVidDataType = VIDEO_TYPE_JPEG;
if(VIDEO_TYPE_JPEG == iVidDataType &&
(iCallingBuffIndex == CALLINGBUFFER2 || iCallingBuffIndex == CALLINGENTRANCEFIRSTLY))
{
pVideoBuff = data;
iVideoSize = vSize;
iCallingBuffIndex = CALLINGBUFFER1;
}
else if(VIDEO_TYPE_ARGB8888 == iVidDataType)
{
if(iCallingSrcIndex == CALLINGENTRANCEFIRSTLY
||(bSrcBuffFlag1 == BUFFERWRITE && iCallingSrcIndex == CALLINGBUFFER1))
{
memcpy(pVidSrcBuff1, (Byte*)data, vSize);
iVidSrcBuffSize1 = vSize;
}
else if(bSrcBuffFlag2 == BUFFERWRITE && iCallingSrcIndex == CALLINGBUFFER2)
{
memcpy(pVidSrcBuff2, (Byte*)data, vSize);
iVidSrcBuffSize2 = vSize;
}
}
bLock = false;
return S_OK;
}
/*****************************************************
* Function: SendAudioData
* Parameters:
* data: audio data of pcm
* size: the size of audio data
*****************************************************/
int CWiMoControl::SendAudioData(int dataType, char* data, int size, int sampleRate, int bitRate, int channels)
{
//LOGI("audio dataType:%d,data:%d, size:%d,sampleRate:%d,bitRate:%d,channels:%d\n",dataType,*data, size,sampleRate,bitRate,channels);
if(data == NULL)
{
LOGE("data is null\n");
return E_FAILED;
}
if(pCAudio && JNI_AUDIO_TYPE_PCM == dataType)
{
pAudioBuff = (LIVEDATABUFFER*)pCAudio->GetSendAudioBuffer();
pAudioBuff->SendData(size, (unsigned char*)data);
}
return S_OK;
}
/*****************************************************
* Function: setSelectDevice
* Parameters:
* nTVRotate: set tv rotation
*****************************************************/
int CWiMoControl::SetTVRotate(int nTVRotate)
{
if(iTvRotate == nTVRotate)
return S_OK;
if(nTVRotate == JNI_CURRENT_TV_ROTATE_90R)
iTvRotate = CURRENT_TV_ROTATE_90R;
else if(nTVRotate == JNI_CURRENT_TV_ROTATE_90L)
iTvRotate = CURRENT_TV_ROTATE_90L;
else //default tv is not rotate
iTvRotate = CURRENT_TV_ROTATE_0;
LOGI("SetTVRotate: %d\n", iTvRotate);
return S_OK;
}
/*****************************************************
* Function: SetVideoRotate
* Parameters:
* nRotate: 0: no rotate;
* 1: rotate left 90
* 2: rotate 180
* 3: rotate right 90
*****************************************************/
int CWiMoControl::SetVideoRotate(int nRotate)
{
if(iUIrotate == nRotate)
return S_OK;
iUIrotate = nRotate;
// LOGI("rotate: %d\n", nRotate);
return S_OK;
}
/*****************************************************
* Function: CheckFB0
* Parameters: void
*****************************************************/
int CWiMoControl::CheckFB0()
{
if(iCaptureMethod == METHOD_TS_STREAM_INTERFACE)
return S_OK;
else if(iCaptureMethod == METHOD_FRAMEBUFFER_INTERFACE
|| iCaptureMethod == METHOD_SCREENSHOT_INTERFACE)
{
FILE* fb = fopen(FRAMEBUFERFB, "r");
if(fb == NULL)
return E_FAILED;
fclose(fb);
}
return S_OK;
}
/*****************************************************
* Function: NotifyScreenshotCalled
* Parameters: called, 0: don't call screen shot
* 1: call screen shot method
*****************************************************/
int CWiMoControl::NotifyScreenshotCalled(int called)
{
m_calledScreenshot = called;
return 0;
}
/*****************************************************
* Func: SetDeviceWidthHeight
* Function: set device width and height
* Parameters: width: device widht
* height: device height
*****************************************************/
void CWiMoControl::SetDeviceWidthHeight(int width, int height)
{
SRC_WIDTH = width;
SRC_HEIGHT = height;
}
/*****************************************************
* Func: SetAlignedWidthHeight
* Function: set widht and height aligned to 16
* Parameters: width: aligned widht
* height: aligned height
*****************************************************/
void CWiMoControl::SetAlignedWidthHeight(int width, int height)
{
ALIGNED_WIDTH = width;
ALIGNED_HEIGTH = height;
}
/*****************************************************
* Func: GetAudioMethod
* Function: get audio capture method
* Parameters: void
*****************************************************/
int CWiMoControl::GetAudioMethod()
{
return iAudioCapMethod;
}
/*****************************************************
* Func: GetVideoMethod
* Function: get video capture method
* Parameters: void
*****************************************************/
int CWiMoControl::GetVideoMethod()
{
return iCaptureMethod;
}
/*****************************************************
* Func: GetVideoMethod
* Function: get video capture method
* Parameters: void
*****************************************************/
void CWiMoControl::SetVideoMethod(int method)
{
iCaptureMethod = method;
}
/*****************************************************
* Func: GetVideoType
* Function: get video data type
* Parameters: void
*****************************************************/
int CWiMoControl::GetVideoType()
{
return iVidDataType;
}
/*****************************************************
* Func: GetVideoDataBuff
* Function: get video data buffer
* Parameters: size: valide data size
* return buffer address
*****************************************************/
char* CWiMoControl::GetVideoDataBuff(int *size)
{
char* buff = NULL;
if(VIDEO_TYPE_JPEG == iVidDataType)
{
if(iCallingBuffIndex == CALLINGBUFFER1)
{
*size = iVideoSize;
iVideoSize = 0;
buff = pVideoBuff;
}
}
else if(VIDEO_TYPE_ARGB8888 == iVidDataType && bLock == false)
{
prevUpdate = currUpdate;
if((iCallingSrcIndex == CALLINGBUFFER1 || iCallingSrcIndex == CALLINGENTRANCEFIRSTLY)
&& iVidSrcBuffSize1 != 0)
{
iCallingSrcIndex = CALLINGBUFFER2;
bSrcBuffFlag1 = BUFFERREAD;
bSrcBuffFlag2 = BUFFERWRITE;
buff = (char*)pVidSrcBuff1;
*size = iVidSrcBuffSize1;
iVidSrcBuffSize1 = 0;
currUpdate = 1;
}
else if(iCallingSrcIndex == CALLINGBUFFER2 && iVidSrcBuffSize2 != 0)
{
iCallingSrcIndex = CALLINGBUFFER1;
bSrcBuffFlag2 = BUFFERREAD;
bSrcBuffFlag1 = BUFFERWRITE;
buff = (char*)pVidSrcBuff2;
*size = iVidSrcBuffSize2;
iVidSrcBuffSize2 = 0;
currUpdate = 2;
}
if(prevUpdate == currUpdate)
return NULL;
}
return buff;
}
/*****************************************************
* Func: GetLimitedFPS
* Function: return limited video FPS whether or not
* Parameters: void
*****************************************************/
bool CWiMoControl::GetLimitedFPS(void)
{
return bLimitedFPS;
}
/*****************************************************
* Func: GetDeviceModel
* Function: return device mode
* Parameters: void
*****************************************************/
int CWiMoControl::GetDeviceModel(void)
{
return iDeviceModel;
}
/*****************************************************
* Func: Init
* Function: init serveral global parameters
* Parameters: void
*****************************************************/
int CWiMoControl::Init()
{
if(iCaptureMethod != METHOD_GAME_INTERFACE)
{
SRC_WIDTH = 0;
SRC_HEIGHT = 0;
ALIGNED_WIDTH = 0;
ALIGNED_HEIGTH = 0;
}
iCallingBuffIndex = CALLINGENTRANCEFIRSTLY;
iCallingSrcIndex = CALLINGENTRANCEFIRSTLY;
currUpdate = 0;
prevUpdate = currUpdate - 1;
if(iCaptureMethod == METHOD_VIDEO_ERROR)
return E_FAILED;
if(iCaptureMethod == METHOD_HS_HW_INTERFACE)
{
iHSHandle = -1;
if(Start_II && (iHSHandle = (*Start_II)(HS_ROTATE_0, HS_QFACOTR_10)) != 0)
return E_FAILED;
}
if((iAudioCapMethod == METHOD_AUDIO_DEFAULT
|| iAudioCapMethod == METHOD_SW_ANDROID_AUD_SPEAKER
|| iAudioCapMethod == METHOD_HS_AUD_MIXER
|| iAudioCapMethod == METHOD_LNV_AUD_MIXER
|| iAudioCapMethod == METHOD_ZTE_AUD_MIXER) && iCaptureMethod != METHOD_TS_STREAM_INTERFACE)
pCAudio = new CWiMoAudio(this);
if(iCaptureMethod != METHOD_TS_STREAM_INTERFACE && iCaptureMethod != METHOD_HW_VIDEO_INTERFACE)
{
if(iCaptureMethod == METHOD_FRAMEBUFFER_INTERFACE)
{
pCPUControl = new CCPUControl(this);
}
pCVideo = new CWiMoVideo(this, pAppLibPath);
}
pCNetwork = new CWiMoNetwork(this);
return S_OK;
}
/*****************************************************
* Func: AndroidUnInit
* Function: UnInit all global parameters
* Parameters: void
*****************************************************/
void CWiMoControl::UnInit()
{
if(pCNetwork)
{
delete pCNetwork;
pCNetwork = NULL;
}
if(iCaptureMethod != METHOD_TS_STREAM_INTERFACE && iCaptureMethod != METHOD_HW_VIDEO_INTERFACE)
{
if(pCVideo)
{
delete pCVideo;
pCVideo = NULL;
}
if(pCPUControl && (iCaptureMethod != METHOD_HS_HW_INTERFACE && iCaptureMethod != METHOD_LNV_HW_INTERFACE))
{
delete pCPUControl;
pCPUControl = NULL;
}
}
if((iAudioCapMethod == METHOD_AUDIO_DEFAULT
|| iAudioCapMethod == METHOD_SW_ANDROID_AUD_SPEAKER
|| iAudioCapMethod == METHOD_HS_AUD_MIXER
|| iAudioCapMethod == METHOD_LNV_AUD_MIXER) && iCaptureMethod != METHOD_TS_STREAM_INTERFACE)
{
if(pCAudio)
{
delete pCAudio;
pCAudio = NULL;
}
}
if(iCaptureMethod == METHOD_HS_HW_INTERFACE && iHSHandle == 0 && Stop_V)
{
iHSHandle = -1;
(*Stop_V)();
}
}
/*****************************************************
* Func: NotifyUIStop
* Function: notify UI to stop it
* Parameters: void
*****************************************************/
void CWiMoControl::NotifyUIStop()
{
if(pCNetwork !=NULL && pCNetwork->GetDisconnectReason() == DISCONNECT_KICKED)
{
LOGI("quit sdk, be kicked\n");
JniStatusChangedCallBack(CONNECTIONWIMOKICKED);
}
else if(pCNetwork !=NULL && pCNetwork->GetDisconnectReason() == DISCONNECT_TIMEOUT)
{
LOGI("quit sdk, the network is timeout\n");
JniStatusChangedCallBack(CONNECTIONWIMOTIMEOUT);
}
else
JniStatusChangedCallBack(CONNECTIONWIMOFAIL);
if(iCaptureMethod == METHOD_HS_HW_INTERFACE && iHSHandle == 0 && Stop_V)
{
iHSHandle = -1;
(*Stop_V)();
}
}
/*****************************************************
* Func: MainThread
* Function: start WiMo NONBLOCK loop
* Parameters: param: thread input parameter
*****************************************************/
void* CWiMoControl::CheckConnectTimeoutThread(void* param)
{
CWiMoControl* pthis = (CWiMoControl*)param;
DDword startTime = GetTickCount();
while(pthis->statusWiMo == WIMO_STATUS_INITING)
{
if(GetTickCount() - startTime < NumTimeOut)
{
usleep(LOOPWAITTIMES);
continue;
}
else
{
pthis->pCNetwork->SetDisconnectReason(DISCONNECT_TIMEOUT);
break;
}
}
//timeout or status changed.
if(pthis->statusWiMo == WIMO_STATUS_CONNECTING)
{
pthis->JniStatusChangedCallBack(CONNECTIONWIMOSUCCESS);
if(pthis->iCaptureMethod != METHOD_TS_STREAM_INTERFACE && pthis->iCaptureMethod != METHOD_HW_VIDEO_INTERFACE)
{
if(pthis->pCVideo != NULL
&& ((pthis->LoopVideoThread_hnd = CreateThreadHelper(pthis->pCVideo->LoopThread, (void*)pthis->pCVideo)) == 0)
)
{
LOGE("creat thread LoopVideoThread_hnd failed!\n");
return (void*)-1;
}
if(pthis->iCaptureMethod == METHOD_FRAMEBUFFER_INTERFACE && pthis->pCPUControl != NULL)
{
pthis->checkCPUUtilization_hnd = CreateThreadHelper(pthis->pCPUControl->LoopCheckCPUUtilization,(void*)pthis->pCPUControl);
if(pthis->checkCPUUtilization_hnd == 0)
{
LOGE("pCPUControl->CreateThreadHelper() failed!\n");
return (void*)-1;
}
}
}
}
else
{
pthis->statusWiMo = WIMO_STATUS_FINISH;
//pthis->NotifyUIStop();
pthis->UnInit();
}
return 0;
}
/*****************************************************
* Func: JniStatusChangedCallBack
* Function: Call back flag of the success or failure
* Parameters:
* connectionFlag: 0: failure
* 1: success
*****************************************************/
void CWiMoControl::JniStatusChangedCallBack(int connectionFlag)
{
bool isAttached = false;
int status = 0;
status = jCallbackFun.jvm->GetEnv((void **) &jCallbackFun.env, JNI_VERSION_1_4);
if(status< 0)
{
//LOGE("callback_handler: failed to get JNI environment, " "assuming native thread");
status = jCallbackFun.jvm->AttachCurrentThread(&jCallbackFun.env, NULL);
if(status< 0)
{
LOGE("callback_handler: failed to attach " "current thread");
return;
}
isAttached = true;
}
if(connectionFlag == CONNECTIONWIMOSUCCESS)
{
LOGI("Connect to WiMo SUCCESSFULLY!\n");
if(iCaptureMethod == METHOD_TS_STREAM_INTERFACE)
{
jclass objClass = jCallbackFun.env->GetObjectClass(jCallbackFun.obj);
//get ipAddress(long)
jfieldID ipAddress = jCallbackFun.env->GetFieldID(objClass, "ipAddr", "J");
long longFieldVal = jCallbackFun.env->GetLongField(jCallbackFun.obj, ipAddress);
//LOGI("ipAddress field value:%ld, valid ip:%ld",longFieldVal,pCNetwork->GetServerIpAddr());
jCallbackFun.env->SetLongField(jCallbackFun.obj,ipAddress, pCNetwork->GetServerIpAddr());
//get udpPort(int)
jfieldID port = jCallbackFun.env->GetFieldID(objClass, "udpPort", "I");
int intFieldVal = jCallbackFun.env->GetIntField(jCallbackFun.obj, port);
//LOGI("port field value:%d",intFieldVal);
jCallbackFun.env->SetIntField(jCallbackFun.obj,port, TSUDPPORT);
}
}
else
{
if(statusWiMo == WIMO_STATUS_FINISH)
{
bQuitJNIFlag = true;
LOGI("Connect WiMo FINSHED\n");
}
}
#if OUTLOG
LOGE("env: %p, obj: %p, callback: %p\n", jCallbackFun.env, jCallbackFun.obj, jCallbackFun.callbackFuns);
#endif
jCallbackFun.env->CallIntMethod(jCallbackFun.obj, jCallbackFun.callbackFuns,connectionFlag);
if (isAttached)
jCallbackFun.jvm->DetachCurrentThread();
}
// java中的jstring, 转化为c的一个字符数组
int Jstring2CStr(JNIEnv* env, jstring jstr, char* buff)
{
char* rtn = buff;
if(rtn == NULL)
return -1;
jclass clsstring = env->FindClass("java/lang/String");
jstring strencode = env->NewStringUTF("GB2312");
jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
jbyteArray barr = (jbyteArray)env->CallObjectMethod(jstr,mid,strencode); // String .getByte("GB2312");
jsize alen = env->GetArrayLength(barr);
jbyte* ba = env->GetByteArrayElements(barr,JNI_FALSE);
//LOGI("alen: %d\n", alen);
if(alen > 0)
{
memcpy(rtn,ba,alen);
rtn[alen]=0;
}
env->ReleaseByteArrayElements(barr,ba,0); //释放内存
return S_OK;
}
int jbyteArrayToChar(JNIEnv *env, jbyteArray bytes, jint size, char* buff)
{
char *rtn = buff;
if(rtn == NULL)
return -1;
jsize len = (jsize)size;
jbyte *arrayBody = env->GetByteArrayElements(bytes,0);
if(len > 0)
{
memcpy(rtn, arrayBody, len);
rtn[len]=0;
}
env->ReleaseByteArrayElements(bytes, arrayBody, 0);
return 0;
}
/*****************************************************
* Class: com_cmcc_wimo_WiMoCapture
* Method: jniInit
* Signature: (II)I
*****************************************************/
JNIEXPORT jint JNICALL Java_com_cmcc_wimo_WiMoCapture_jniInit
(JNIEnv *env, jobject thiz, jint videoMode, jint audioMode)
{
LOGI("%s \n",__FUNCTION__);
jclass objClass = env->GetObjectClass(thiz);
//取String libPath
jfieldID path = env->GetFieldID(objClass, "libPath", "Ljava/lang/String;");
//判断是否为NULL
if(!path) {
LOGE("libPath: failed to get field ID");
return NULL;
}
//获取此参数的值,基本类型的,赋值的话直接等于即可
jstring str = (jstring) env->GetObjectField(thiz, path);
char* libPath = new char[STRINGDATESIZE];
Jstring2CStr(env, str, libPath);
//LOGI("libPath: %s\n", libPath);
CWiMoControl * pcWiMo = new CWiMoControl(env,thiz,videoMode, audioMode, libPath);
delete libPath;
return (int)pcWiMo;
}
/*****************************************************
* Class: com_cmcc_wimo_WiMoCapture
* Method: jniUnInit
* Signature: ()I
*****************************************************/
JNIEXPORT jint JNICALL Java_com_cmcc_wimo_WiMoCapture_jniUnInit
(JNIEnv * env, jobject thiz)
{
LOGI("%s \n",__FUNCTION__);
jclass objClass = env->GetObjectClass(thiz);
//取int cValPointer
jfieldID j = env->GetFieldID(objClass, "cValPointer", "I");
if (j == 0)
{
LOGI("Faild to get the j field");
return E_FAILED;
}
int intFieldVal = env->GetIntField(thiz, j);
CWiMoControl* cWiMo = (CWiMoControl*)intFieldVal;
if(!cWiMo)
return E_FAILED;
delete cWiMo;
cWiMo = NULL;
return S_OK;
}
/*****************************************************
* Class: com_cmcc_wimo_WiMoCapture
* Method: startWiMo
* Signature: ()I
*****************************************************/
JNIEXPORT jint JNICALL Java_com_cmcc_wimo_WiMoCapture_startWiMo
(JNIEnv *env, jobject thiz)
{
LOGI("%s \n",__FUNCTION__);
jclass objClass = env->GetObjectClass(thiz);
//取int cValPointer
jfieldID j = env->GetFieldID(objClass, "cValPointer", "I");
if (j == 0)
{
LOGI("Faild to get the j field");
return E_FAILED;
}
int intFieldVal = env->GetIntField(thiz, j);
CWiMoControl* cWiMo = (CWiMoControl*)intFieldVal;
if(!cWiMo)
return E_FAILED;
return cWiMo->StartWiMo();
}
/*****************************************************
* Class: com_cmcc_wimo_WiMoCapture
* Method: stopWiMo
* Signature: ()I
*****************************************************/
JNIEXPORT jint JNICALL Java_com_cmcc_wimo_WiMoCapture_stopWiMo
(JNIEnv *env, jobject thiz)
{
LOGI("%s \n",__FUNCTION__);
jclass objClass = env->GetObjectClass(thiz);
//取int cValPointer
jfieldID j = env->GetFieldID(objClass, "cValPointer", "I");
if (j == 0)
{
LOGI("Faild to get the j field");
return E_FAILED;
}
int intFieldVal = env->GetIntField(thiz, j);
CWiMoControl* cWiMo = (CWiMoControl*)intFieldVal;
if(!cWiMo)
return E_FAILED;
return cWiMo->StopWiMo();
}
/*****************************************************
* Class: com_cmcc_wimo_WiMoCapture
* Method: sendVideoData
* Signature: (I[BIIII)I
*****************************************************/
JNIEXPORT jint JNICALL Java_com_cmcc_wimo_WiMoCapture_sendVideoData
(JNIEnv * env, jobject thiz, jint dataType, jbyteArray data, jint size, jint width, jint height, jint rotate)
{
//LOGI("%s \n",__FUNCTION__);
jclass objClass = env->GetObjectClass(thiz);
//取int cValPointer
jfieldID j = env->GetFieldID(objClass, "cValPointer", "I");
if (j == 0)
{
LOGI("Faild to get the j field");
return E_FAILED;
}
int intFieldVal = env->GetIntField(thiz, j);
CWiMoControl* cWiMo = (CWiMoControl*)intFieldVal;
if(!cWiMo)
return E_FAILED;
char *dataBuf = (char*)malloc(size+1);
if(jbyteArrayToChar(env, data, size, dataBuf) != 0)
{
LOGE("sendVideoData: malloc buffer failed!\n");
return E_FAILED;
}
/*
//byte[] abyte
jfieldID arrFieldId = env->GetFieldID(objClass, "abyte", "[B");
if (arrFieldId == 0)
{
LOGI("Faild to get the abyte field");
return 0;
}
jbyteArray jarr = (jbyteArray)env->GetObjectField(test_obj, arrFieldId);
jbyte *arr = env->GetByteArrayElements(jarr, 0);
LOGI("Reach here arr=%x",arr);
int len = (env)->GetArrayLength(jarr);
LOGI("Reach here len=%d",len );
for(int i=0;i<len;i++)
{
LOGI("TestClass's abyte field[%d] value:%d",i,arr[i]);
arr[i] += 1;
}
env->SetByteArrayRegion(jarr,0, len,arr);
(env)->SetObjectField(test_obj,arrFieldId,jarr);
arr = env->GetByteArrayElements(jarr, 0);
for(int i=0;i<len;i++)
{
LOGI("TestClass's abyte field[%d] value:%d",i,arr[i]);
}
(env)->ReleaseByteArrayElements(jarr, arr, 0 );
*/
cWiMo->SendVideoData(dataType, dataBuf, size, width, height, rotate);
if(dataBuf)
free(dataBuf);
return S_OK;
}
/*****************************************************
* Class: com_cmcc_wimo_WiMoCapture
* Method: sendAudioData
* Signature: (I[BIIII)I
*****************************************************/
JNIEXPORT jint JNICALL Java_com_cmcc_wimo_WiMoCapture_sendAudioData
(JNIEnv * env, jobject thiz, jint dataType, jbyteArray data, jint size, jint sampleRate, jint bitRate, jint channels)
{
//LOGI("%s \n",__FUNCTION__);
jclass objClass = env->GetObjectClass(thiz);
//取int cValPointer
jfieldID j = env->GetFieldID(objClass, "cValPointer", "I");
if (j == 0)
{
LOGI("Faild to get the j field");
return E_FAILED;
}
int intFieldVal = env->GetIntField(thiz, j);
CWiMoControl* cWiMo = (CWiMoControl*)intFieldVal;
if(!cWiMo)
return E_FAILED;
char *dataBuf = (char*)malloc(size+1);
if(jbyteArrayToChar(env, data, size, dataBuf) != 0)
{
LOGE("sendAudioData: malloc buffer failed!\n");
return E_FAILED;
}
cWiMo->SendAudioData(dataType, dataBuf, size, sampleRate, bitRate, channels);
if(dataBuf)
free(dataBuf);
return S_OK;
}
/*****************************************************
* Class: com_cmcc_wimo_WiMoCapture
* Method: setTVRotate
* Signature: (I)I
*****************************************************/
JNIEXPORT jint JNICALL Java_com_cmcc_wimo_WiMoCapture_setTVRotate
(JNIEnv * env, jobject thiz, jint nTVRotate)
{
LOGI("%s \n",__FUNCTION__);
jclass objClass = env->GetObjectClass(thiz);
//取int cValPointer
jfieldID j = env->GetFieldID(objClass, "cValPointer", "I");
if (j == 0)
{
LOGI("Faild to get the j field");
return E_FAILED;
}
int intFieldVal = env->GetIntField(thiz, j);
CWiMoControl* cWiMo = (CWiMoControl*)intFieldVal;
if(!cWiMo)
return E_FAILED;
return cWiMo->SetTVRotate(nTVRotate);
}
/*****************************************************
* Class: com_cmcc_wimo_WiMoCapture
* Method: setVideoRotate
* Signature: (I)I
*****************************************************/
JNIEXPORT jint JNICALL Java_com_cmcc_wimo_WiMoCapture_setVideoRotate
(JNIEnv * env, jobject thiz, jint rotate)
{
//LOGI("%s , rotate: %d\n",__FUNCTION__, rotate);
jclass objClass = env->GetObjectClass(thiz);
//取int cValPointer
jfieldID j = env->GetFieldID(objClass, "cValPointer", "I");
if (j == 0)
{
LOGI("Faild to get the j field");
return E_FAILED;
}
int intFieldVal = env->GetIntField(thiz, j);
CWiMoControl* cWiMo = (CWiMoControl*)intFieldVal;
if(!cWiMo)
return E_FAILED;
return cWiMo->SetVideoRotate(rotate);
}
/*****************************************************
* Class: com_cmcc_wimo_WiMoCapture
* Method: checkFb0
* Signature: ()I
*****************************************************/
JNIEXPORT jint JNICALL Java_com_cmcc_wimo_WiMoCapture_checkFb0
(JNIEnv * env, jobject thiz)
{
LOGI("%s \n",__FUNCTION__);
jclass objClass = env->GetObjectClass(thiz);
//取int cValPointer
jfieldID j = env->GetFieldID(objClass, "cValPointer", "I");
if (j == 0)
{
LOGI("Faild to get the j field");
return E_FAILED;
}
int intFieldVal = env->GetIntField(thiz, j);
CWiMoControl* cWiMo = (CWiMoControl*)intFieldVal;
if(!cWiMo)
return E_FAILED;
return cWiMo->CheckFB0();
}
/*****************************************************
* Class: com_cmcc_wimo_WiMoCapture
* Method: notifyScreenshotCalled
* Signature: ()I
*****************************************************/
JNIEXPORT jint JNICALL Java_com_cmcc_wimo_WiMoCapture_notifyScreenshotCalled
(JNIEnv * env, jobject thiz, jint shotCalled)
{
//LOGI("%s \n",__FUNCTION__);
jclass objClass = env->GetObjectClass(thiz);
//取int cValPointer
jfieldID j = env->GetFieldID(objClass, "cValPointer", "I");
if (j == 0)
{
LOGI("Faild to get the j field");
return E_FAILED;
}
int intFieldVal = env->GetIntField(thiz, j);
CWiMoControl* cWiMo = (CWiMoControl*)intFieldVal;
if(!cWiMo)
return E_FAILED;
return cWiMo->NotifyScreenshotCalled(shotCalled);
}
|
2a2daac8ce4218fa8b7a4dbcaca6e80009db90ca
|
1e01340dd92a17332c2aa25eb4dbc7e5bd869bd6
|
/Ld40/TheDestructor.h
|
6c20fcda6bb3c11e90a848baf2ebe02afdb76d3b
|
[] |
no_license
|
Harrimaga/LD40
|
d7d5f5aff74c78d690bbf0ace1dcf8889fce76d0
|
c574b68b5233fed3966fc6d9e4a92f7db6684089
|
refs/heads/master
| 2023-01-03T06:13:05.887386
| 2020-10-28T15:35:41
| 2020-10-28T15:35:41
| 308,053,961
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 515
|
h
|
TheDestructor.h
|
#pragma once
#include "Enemy.h"
#include "Globals.h"
#include "BigCircle.h"
#include "RandomRain.h"
#include "ThunderStorm.h"
class TheDestructor : public Enemy {
public:
TheDestructor(int x, int y, std::vector<Direction*> movement) :Enemy(Globals::sprites->at(2), x, y, movement)
{
attackAmount = -1;
attackTime = 90;
timer = attackTime;
spells->push_back(new BigCircle());
spells->push_back(new RandomRain());
spells->push_back(new ThunderStorm());
health = 300;
score = 15000;
};
protected:
};
|
fe7b895ecd60d2a49e3edc8937a4093a5d08c3cb
|
2cce15887362c58716aaec9eaa486363984bcf42
|
/chapter9/9.13.cpp
|
7fee9d895815ff0f9cd3bf27682eaf577f6fc5db
|
[] |
no_license
|
LiwenChii/cpp_practice
|
c0f2fc4ab1f44313023f4d69e62f0bf0b6835a5d
|
fa04723d764193280814509fcb6385e9e8336951
|
refs/heads/master
| 2020-03-30T10:17:37.952146
| 2016-02-25T14:58:29
| 2016-02-25T14:58:29
| 41,008,719
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 440
|
cpp
|
9.13.cpp
|
#include <iostream>
#include <list>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::list;
using std::vector;
int main()
{
list<int> lst(6, 6);
vector<int> ivec(6, 9);
vector<double> dvec(lst.begin(), lst.end());
for (auto d : dvec)
{
cout << d << " ";
}
cout << endl;
vector<double> dvec1(ivec.begin(), ivec.end());
for (auto d : dvec1)
{
cout << d << " ";
}
cout << endl;
return 0;
}
|
935144b1607ad2b8ae3696a59aa583021cd379e4
|
814710876d2287f746ad76b3383423a7762f740a
|
/1.7_for_and_massives/bowling.cpp
|
3189307ff56111cc1d3878672ab4ef4f9e8d92bf
|
[
"MIT"
] |
permissive
|
yoshi42/simple_but_important_algorythms
|
2e4a672fd6d202d2afe12c6a6d11462048048b4a
|
301b529cea13c121579901ddeffaa062a49f4caf
|
refs/heads/master
| 2021-07-18T02:08:47.853784
| 2017-10-27T07:43:34
| 2017-10-27T07:43:34
| 108,515,294
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 644
|
cpp
|
bowling.cpp
|
#include <iostream>
#include <vector>
using namespace std;
// Є ряд чисел:
int main()
{
int n = 0, k = 0, l = 0, r = 0 ;
cin >> n;
vector <int> a(n);
for (int i = 0; i < a.size(); i++)
{
a[i] = 1;
}
cin >> k;
for (int w = 0; w < k; w++)
{
cin >> l;
cin >> r;
for (int j = l-1; j < r; j++)
{
a[j] = 0;
}
}
// вивід
for (int q = 0; q < a.size(); q++)
{
if (a[q] == 1)
{
cout << "I";
}
else if (a[q] == 0)
{
cout << ".";
}
}
return 0;
}
|
fa176b5607d3d4ba767d4eae25c91a8ab915e3e3
|
b9606c302edeb76b52ab22bdccd596d9f7a94209
|
/modules/task_2/arisova_a_sleeping_barber/sleeping_barber.cpp
|
21c7120e072f452b9fb5e3543ff2b9496d737230
|
[] |
no_license
|
DrXlor/pp_2019_autumn
|
31f68a32f2fc334f4ce534161fb32c8cb70baf1c
|
e01960c714ad1e86d68cbf3be551741106dc908d
|
refs/heads/master
| 2020-09-20T11:56:11.773825
| 2019-11-26T09:00:15
| 2019-11-26T09:00:15
| 224,469,332
| 2
| 0
| null | 2019-11-27T16:11:27
| 2019-11-27T16:11:26
| null |
UTF-8
|
C++
| false
| false
| 3,055
|
cpp
|
sleeping_barber.cpp
|
// Copyright 2019 Arisova Anastasiia
#include <mpi.h>
#include <queue>
#include <ctime>
#include <algorithm>
#include "../../../modules/task_2/arisova_a_sleeping_barber/sleeping_barber.h"
enum message {start_haircut, end_haircut, want_haircut, empty_seat, no_seat};
void sleep(double t) {
double time = MPI_Wtime();
while (MPI_Wtime() - time < t) {
}
}
void haircut() {
sleep(0.01);
}
int Barber(int size_queue, int size) {
MPI_Status status;
std:: queue <int> reception;
int counter = 0; // the number of customers who cut the Barber
int cust_rank;
int flag;
int buff; // buffer for send letter
// work or sleep while there are a custimers
while (counter != (size-1)) {
// check probably customers
MPI_Iprobe(MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &flag, &status);
// add customer in reception
while (flag) {
MPI_Recv(&cust_rank, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
if ((static_cast<int>(reception.size()) != size_queue)) {
reception.push(cust_rank);
buff = empty_seat;
MPI_Send(&buff, 1, MPI_INT, cust_rank, 0, MPI_COMM_WORLD);
} else {
buff = no_seat;
MPI_Send(&buff, 1, MPI_INT, cust_rank, 0, MPI_COMM_WORLD);
}
// recheck probably customers
MPI_Iprobe(MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &flag, &status);
}
if (!reception.empty()) {
cust_rank = reception.front();
reception.pop();
buff = start_haircut;
MPI_Send(&buff, 1, MPI_INT, cust_rank, 0, MPI_COMM_WORLD);
haircut();
buff = end_haircut;
MPI_Send(&buff, 1, MPI_INT, cust_rank, 0, MPI_COMM_WORLD);
counter++;
}
}
return counter;
}
void Customer(int R) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Status status;
double temp = std::rand() / static_cast<double>(RAND_MAX);
sleep(temp);
int mess = -1;
while (mess != end_haircut) {
MPI_Send(&rank, 1, MPI_INT, R, 0, MPI_COMM_WORLD);
int flag;
MPI_Recv(&flag, 1, MPI_INT, R, 0, MPI_COMM_WORLD, &status);
if (flag == empty_seat) {
MPI_Recv(&flag, 1, MPI_INT, R, 0, MPI_COMM_WORLD, &status);
MPI_Recv(&mess, 1, MPI_INT, R, 0, MPI_COMM_WORLD, &status);
} else {
sleep(temp);
}
}
}
int BarberShop(int R, int size_queue) {
// R - rang process-barber
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int count_cust = 0;
if (size_queue == 0)
throw("Incorrect size of queue");
if (R >= size)
R = 0;
if (rank == R)
// This is process-barber
count_cust = Barber(size_queue, size);
else
// This is process-customer
Customer(R);
MPI_Bcast(&count_cust, 1, MPI_INT, R, MPI_COMM_WORLD);
return count_cust;
}
|
da4508d2bca6dd71d123585b74b9c3fe4288b4a4
|
3f8c02bb11ad4cc748b0b340c4a8246a0b8639f3
|
/inc/DoorSensor.h
|
922c27bc1a724cd30d7a4f292b851c4d495140aa
|
[] |
no_license
|
Kn-Jakub/SmartServer
|
a84a0ac24a72e5583d28b337c317d5bdfb71496b
|
0ee2f16db0a8561a4bf9a6c3f839360f7f2924d3
|
refs/heads/master
| 2021-06-22T08:45:49.173457
| 2019-06-04T09:58:55
| 2019-06-04T09:58:55
| 131,844,224
| 0
| 0
| null | 2018-08-25T12:07:26
| 2018-05-02T11:59:11
| null |
UTF-8
|
C++
| false
| false
| 1,080
|
h
|
DoorSensor.h
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: DoorSensor.h
* Author: Jakub Pekar
*
*/
#ifndef DOORSENSOR_H
#define DOORSENSOR_H
#include "MySQL.h"
#include "Condition.h"
#include "Socket.h"
#include "Thread.h"
#include "Modul.h"
#include "LightServer.h"
class DoorSensor : public Thread, Modul {
public:
DoorSensor(Socket* socketDescriptor,
std::string pName,
bool *pAlarmActive,
Condition *pAlarm,
Condition *paCondition,
MySQL *paConnectToState);
virtual void threadMain();
DoorSensor(const DoorSensor& orig) = delete;
virtual ~DoorSensor();
/**
* Function for get name of modul
* @return string of name
*/
std::string getName() const {
return name;
}
private:
MySQL *m_connectorToStateDB;
Condition *conIsDisconnect;
Condition *m_alarm;
bool *alarmActive;
};
#endif /* DOORSENSOR_H */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.