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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
59788c8fa6e93468ed3b18709f8765dd687a4c39
|
b923729dabc6ea385a6dfad97dd41d4b6c7c401b
|
/Date.h
|
0ae453d804d2f483f29ed41980d9bdc2fb0c47f4
|
[] |
no_license
|
fcshah/StoreManagmentSystem
|
3afa477f20668c82a584526bc2240dd74eb30cfc
|
bbdc4b7d05320b026d75a47fdb15d691477f21e5
|
refs/heads/master
| 2021-04-28T16:20:46.037366
| 2018-02-19T03:01:57
| 2018-02-19T03:01:57
| 122,012,672
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 967
|
h
|
Date.h
|
#ifndef SICT_DATE_H
#define SICT_DATE_H
#include <iostream>
namespace sict {
#define NO_ERROR 0
#define CIN_FAILED 1
#define YEAR_ERROR 2
#define MON_ERROR 3
#define DAY_ERROR 4
const int min_year = 2000;
const int max_year = 2030;
class Date {
int mdays(int, int)const;
void errCode(int errorCode);
private:
int value()const;
int m_Year;
int m_Month;
int m_Day;
int error_state;
public:
Date();
Date(int year, int month, int day);
bool operator==(const Date&) const;
bool operator!=(const Date&) const;
bool operator<(const Date&) const;
bool operator>(const Date&) const;
bool operator<=(const Date&) const;
bool operator>=(const Date&) const;
int errCode() const;
bool bad() const;
std::istream& read(std::istream&);
std::ostream& write(std::ostream&) const;
};
std::ostream& operator<<(std::ostream&, const Date&);
std::istream& operator>>(std::istream&, Date& );
}
#endif
|
ffa89cae57ec7d269f156350eb8861ddd5b84464
|
0f8eb14b579ae48dd1a7b3cd7e806172f5512baa
|
/Data_Structures/LCA_ST.cpp
|
c0c9b0cfdcc99dcd2b8ec4086732e14ac601ba46
|
[] |
no_license
|
Kanchii/CP_Algorithms
|
7d6901228f719fa5d05f118597b8329f7680c047
|
c525640638e1d79133f63e78021d9a83f2698ee8
|
refs/heads/master
| 2020-03-29T10:01:02.083825
| 2019-02-23T22:28:33
| 2019-02-23T22:28:33
| 149,785,736
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,234
|
cpp
|
LCA_ST.cpp
|
#include <bits/stdc++.h>
using namespace std;
vector<int> tour, height;
int vis[20];
int entrada[20];
void preTour(vector<vector<int> > &adj, int u, int nivel){
vis[u] = 1;
tour.push_back(u);
entrada[u] = tour.size() - 1;
height.push_back(nivel);
for(int v : adj[u]){
if(!vis[v]){
preTour(adj, v, nivel + 1);
tour.push_back(u);
height.push_back(nivel);
}
}
}
int st[20][10];
void preST(vector<vector<int> > &adj){
for(int i = 0; i < tour.size(); i++){
st[i][0] = entrada[tour[i]];
}
for(int j = 1; j <= 8; j++){
for(int i = 0; i + (1 << j) <= tour.size(); i++){
int u = height[st[i][j - 1]];
int v = height[st[i + (1 << (j - 1))][j - 1]];
if(u < v){
st[i][j] = st[i][j - 1];
} else {
st[i][j] = st[i + (1 << (j - 1))][j - 1];
}
}
}
}
int query(int l, int r){
if(l > r){
swap(l, r);
}
int diff = r - l + 1;
int first = 0;
int res;
for(int j = 8; j >= 0; j--){
if(diff & (1 << j)){
if(!first){
first = 1;
res = st[l][j];
l += (1 << j);
} else {
int u = st[l][j];
if(height[u] < height[res]){
res = u;
}
l += (1 << j);
}
}
}
return tour[res];
}
int main(int argc, char const *argv[]) {
vector<vector<int> > adj(8);
adj[1].push_back(2);
adj[2].push_back(1);
adj[1].push_back(3);
adj[3].push_back(1);
adj[1].push_back(4);
adj[4].push_back(1);
adj[2].push_back(5);
adj[5].push_back(2);
adj[2].push_back(6);
adj[6].push_back(2);
adj[4].push_back(7);
adj[7].push_back(4);
preTour(adj, 1, 1);
preST(adj);
cout << query(entrada[5], entrada[6]) << endl; // Saida = 2
cout << query(entrada[2], entrada[3]) << endl; // Saida = 1
cout << query(entrada[3], entrada[3]) << endl; // Saida = 3
cout << query(entrada[4], entrada[7]) << endl; // Saida = 4
cout << query(entrada[7], entrada[1]) << endl; // Saida = 1
return 0;
}
|
3620023b8f756bdd7105ec4963211e0325fbc1d5
|
802cdda4b7fcd4ebf2da5c924c7b9ec8f3774dc6
|
/untitled/score.cpp
|
2ad98d9ef027a6e6310fe5b9bde91f39f4c1f442
|
[] |
no_license
|
bradgearon/untitled
|
09e44eb0745e28bdf24d931d496131d7bfbc2996
|
08c6c45985b6b5e5b47e5dc95398d85488077106
|
refs/heads/master
| 2022-10-18T13:10:39.898080
| 2022-10-12T05:18:01
| 2022-10-12T05:18:01
| 75,348,547
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,718
|
cpp
|
score.cpp
|
#include "score.h"
using namespace untitled;
Score::Score(Level *level) : QObject() {
qDebug() << "creating score";
this->level = level;
}
QString Score::getName() const { return name; }
void Score::setName(const QString &value) { name = value; }
double Score::getRank() const { return rank; }
void Score::setRank(double value) { rank = value; }
double Score::getWeight() const { return weight; }
void Score::setWeight(double value) { weight = value; }
double Score::getRead() const { return read; }
void Score::setRead(double read) {
auto previous = this->read;
qDebug() << "read: " << read << " previous: " << previous;
if (read > previous) {
this->read = read;
onReadChanged(read, previous);
}
}
double Score::getNextDifference() const { return nextDifference; }
void Score::setNextDifference(double value) { nextDifference = value; }
void Score::onReadChanged(double read, double previous) {
double readTotal = level->getReadTotal();
auto count = level->getScores().size();
auto percentComplete = readTotal / count;
auto subtractFromWeight = read * getNextDifference();
auto addToWeight = read * percentComplete;
qDebug() << " " << read << " " << percentComplete << " " << addToWeight << " "
<< subtractFromWeight << " " << readTotal << " a "
<< getNextDifference();
setWeight(getRank() + addToWeight - subtractFromWeight);
qDebug() << "weight for element " << getName() << " now " << getWeight()
<< " in rank " << getRank() << " read " << readTotal
<< " percent complete: " << percentComplete;
if (read > previous) {
qDebug() << "read: " << read << " previous: " << previous;
emit readChanged(read);
}
}
|
d5a45ad740866ef7c606807451d61e41d1f4f2e6
|
297497957c531d81ba286bc91253fbbb78b4d8be
|
/third_party/libwebrtc/modules/utility/maybe_worker_thread.h
|
d1addace97203e3a56d89aece62ae40c77d4d332
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
marco-c/gecko-dev-comments-removed
|
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
|
61942784fb157763e65608e5a29b3729b0aa66fa
|
refs/heads/master
| 2023-08-09T18:55:25.895853
| 2023-08-01T00:40:39
| 2023-08-01T00:40:39
| 211,297,481
| 0
| 0
|
NOASSERTION
| 2019-09-29T01:27:49
| 2019-09-27T10:44:24
|
C++
|
UTF-8
|
C++
| false
| false
| 1,292
|
h
|
maybe_worker_thread.h
|
#ifndef MODULES_UTILITY_MAYBE_WORKER_THREAD_H_
#define MODULES_UTILITY_MAYBE_WORKER_THREAD_H_
#include <memory>
#include "absl/strings/string_view.h"
#include "api/field_trials_view.h"
#include "api/sequence_checker.h"
#include "api/task_queue/pending_task_safety_flag.h"
#include "api/task_queue/task_queue_base.h"
#include "api/task_queue/task_queue_factory.h"
#include "rtc_base/thread_annotations.h"
namespace webrtc {
class RTC_LOCKABLE MaybeWorkerThread {
public:
MaybeWorkerThread(const FieldTrialsView& field_trials,
absl::string_view task_queue_name,
TaskQueueFactory* factory);
~MaybeWorkerThread();
void RunOrPost(absl::AnyInvocable<void() &&> task);
void RunSynchronous(absl::AnyInvocable<void() &&> task);
TaskQueueBase* TaskQueueForDelayedTasks() const;
TaskQueueBase* TaskQueueForPost() const;
absl::AnyInvocable<void() &&> MaybeSafeTask(
rtc::scoped_refptr<PendingTaskSafetyFlag> flag,
absl::AnyInvocable<void() &&> task);
bool IsCurrent() const;
private:
SequenceChecker sequence_checker_;
std::unique_ptr<TaskQueueBase, TaskQueueDeleter> owned_task_queue_;
TaskQueueBase* const worker_thread_;
};
}
#endif
|
1fd134779c3dcbb351d4585b3fb20751d03e1c1c
|
5d62cc9de5169b6877da9e532961caf0c4279750
|
/Sources/Tools/DatabasePreprocessor/preprocessor.cpp
|
7dbf98bc197a8dcedae89b704d24a96194053c97
|
[
"MIT"
] |
permissive
|
jacket-code/diecast
|
55a69004e28cf654d3eabc7720e63445a8a1ff09
|
0b28c08b35071d6d04a5cd36c53fb0f58f3e1f90
|
refs/heads/master
| 2021-01-15T08:40:50.558625
| 2014-02-17T13:53:59
| 2014-02-17T13:53:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,760
|
cpp
|
preprocessor.cpp
|
#include "precomp.h"
#include "preprocessor.h"
std::string Preprocessor::process(const std::string &text)
{
Preprocessor processor(text);
return processor.output;
}
Preprocessor::Preprocessor(const std::string &text)
: text(text)
{
size_t line_start = 0;
while (true)
{
size_t line_end = text.find('\n', line_start);
if (line_end == std::string::npos)
line_end = text.length();
else
line_end++;
std::string line = text.substr(line_start, line_end - line_start);
preprocess_line(line);
output += line;
if (line_end == text.length())
break;
line_start = line_end;
}
}
void Preprocessor::preprocess_line(std::string &line)
{
size_t first_char_pos = line.find_first_not_of(" \t\r\n");
if (first_char_pos == std::string::npos)
return;
if (line[first_char_pos] == '#')
{
parse_preprocessor_directive(line.substr(first_char_pos));
line.clear();
}
else
{
replace_defines(line);
}
}
void Preprocessor::parse_preprocessor_directive(const std::string &line)
{
if (line.substr(0, 7) == "#define")
{
std::string identifier, value;
size_t identifier_start = line.find_first_not_of(" \t\r\n", 7);
if (identifier_start == std::string::npos)
return;
size_t identifier_end = line.find_first_of(" \t\r\n", identifier_start);
if (identifier_end == std::string::npos)
{
identifier = line.substr(identifier_start);
identifier_end = line.length();
}
else
{
identifier = line.substr(identifier_start, identifier_end - identifier_start);
}
size_t value_start = line.find_first_not_of(" \t\r\n", identifier_end);
if (value_start != std::string::npos)
{
size_t value_end = line.find_first_of(" \t\r\n", value_start);
if (value_end == std::string::npos)
value_end = line.length();
value = line.substr(value_start, value_end - value_start);
}
defines[identifier] = value;
}
}
void Preprocessor::replace_defines(std::string &line)
{
bool found_identifier = false;
size_t identifier_start = 0;
for (size_t i = 0; i < line.length(); )
{
if (!found_identifier)
{
if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') || line[i] == '_')
{
identifier_start = i;
found_identifier = true;
}
}
else if (found_identifier)
{
if (!(line[i] >= 'a' && line[i] <= 'z') && !(line[i] >= 'A' && line[i] <= 'Z') && !(line[i] >= '0' && line[i] <= '9') && line[i] != '_')
{
found_identifier = false;
std::string identifier = line.substr(identifier_start, i - identifier_start);
auto it = defines.find(identifier);
if (it != defines.end())
{
line = line.substr(0, identifier_start) + it->second + line.substr(i);
i = identifier_start + it->second.length();
continue;
}
}
}
i++;
}
}
|
30768fb043030105d59ed547bcc7e2e2d70459fa
|
5b4c2679a0da0c5e2aa206af7c257b0cda209c94
|
/C++/Vjudge/CodeForces/Watchmen.cpp
|
e9e8d67cd071a8dde8ac10c53f281b9ea5384466
|
[] |
no_license
|
mast1ren/mPracCodes
|
59b563ff77ff289587db0c58c52e2a17e8f97cf0
|
af621fe5e37783685badb5b29ecb9e5a6d78aefd
|
refs/heads/master
| 2023-01-08T01:39:09.301554
| 2020-11-06T05:02:52
| 2020-11-06T05:02:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 837
|
cpp
|
Watchmen.cpp
|
/*
当两点x或y相同时 计算的距离相同
但是要注意去除x和y同时相同的情况
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long int count = 0;
map<int, int> x; //记录相同x的
map<int, int> y; //记录相同y的
map<pair<int, int>, int> s; //记录xy同时相同的
int n;
cin >> n;
while (n--)
{
int a, b;
cin >> a >> b;
count += x[a] + y[b] - s[make_pair(a, b)]; //减去xy同时相同的情况
x[a]++;
y[b]++;
s[make_pair(a, b)]++;
}
cout << count << endl;
system("pause");
return 0;
}
//这个算法太nb了 膜了
// 为何递加可以算出多少对
// 以x举例
// x[i]初值为0
// 如有n个i
// 递加结果未 n*(n-1)/2
// 这个结果与 C(^2)(n)相同
|
c8d6a378269227ac8ce751a96d3cb595bb5a34ee
|
cffc214f1409565e6c2d35c74e45ab4206907228
|
/mysql_protocol/packet/BinaryPacket.cpp
|
3d294277fdf8404fda1bace7c67f03816aea3255
|
[
"MIT"
] |
permissive
|
zhukovaskychina/XSQL
|
eb07adbb243d0a552af64287a7d95f23502792fc
|
f91db06bf86f7f6ad321722c3aea11f83d34dba1
|
refs/heads/main
| 2023-01-09T11:11:00.869732
| 2020-10-23T10:02:52
| 2020-10-23T10:02:52
| 306,588,415
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 722
|
cpp
|
BinaryPacket.cpp
|
//
// Created by zhukovasky on 2020/9/17.
//
#include <muduo/net/TcpConnection.h>
#include "BinaryPacket.h"
namespace MyProtocol{
int BinaryPacket::calPacketSize() {
return 0;
}
std::string BinaryPacket::getPacketInfo() {
return std::__cxx11::string("MySQL Binary Packet");
}
const std::vector<char> &BinaryPacket::getData() const {
return data;
}
void BinaryPacket::setData(const std::vector<char> &data) {
BinaryPacket::data = data;
}
void BinaryPacket::write(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer &buffer) {
}
muduo::net::Buffer &BinaryPacket::writeBuf(muduo::net::Buffer &buffer) {
return buffer;
}
}
|
d8cd434be4b7c9140e45067cb56dd7718c7617c0
|
bafd731d3666b834e0b2bed3d8762bb74e098af0
|
/Кнопка-меню/main.cpp
|
d18e020e11ed1131f83b75b4cf1061c8a9bee89f
|
[] |
no_license
|
mikaevnikita/cpp
|
e2375f03f665186079b3178e620cc3c0c11933c7
|
58b4ba6dc6f90ae173479191c95ec782313c689a
|
refs/heads/master
| 2021-09-02T02:28:24.954142
| 2017-12-29T18:49:45
| 2017-12-29T18:49:45
| 115,746,352
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 509
|
cpp
|
main.cpp
|
#include <QWidget>
#include <QPushButton>
#include <QApplication>
#include <QMenu>
using namespace Qt;
int main(int argc, char** argv){
QApplication app(argc,argv);
QWidget window;
QPushButton* pb = new QPushButton("Menu",&window);
QPixmap pix(":/prefix1/rock");
pb->setIcon(pix);
QMenu* menu = new QMenu(pb);
menu->addAction("Item1");
menu->addAction("Item2");
menu->addAction("Quit",&app,SLOT(quit()));
pb->setMenu(menu);
window.show();
return app.exec();
}
|
a8ffa19e48ab78012b292069a53da3dbec608842
|
1c2531d44c9c00ff27d36ce67bb4554beab0622f
|
/problems/101-200/p136.cpp
|
ddbdce37becd6b204afe4b2765c96e51f1b59bb1
|
[] |
no_license
|
zpf0917/euler
|
c68207094331b41af381de2e08c0990acf9b0f90
|
6f21ef83668370caaf7e8262d9de7fd0efa933e1
|
refs/heads/master
| 2020-08-29T07:20:36.306580
| 2019-07-13T23:18:07
| 2019-07-13T23:20:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 691
|
cpp
|
p136.cpp
|
#include "lib/utility.hh"
constexpr int N = 50000000;
int sol_count[N];
void count_solutions() {
for (long x = 0; x < 2 * N; x++) {
for (long a = x / 5 + 1; a <= x / 2; a++) {
long n = (5*a - x) * (x - a);
if (n >= N) {
break;
}
long y = x - a;
long z = y - a;
if (n < N && x > 2 * a && x*x - y*y - z*z == n) {
sol_count[n]++;
}
}
}
}
int main(void) {
start_time();
count_solutions();
int count = 0;
for (int n = 0; n < N; n++) {
count += sol_count[n] == 1;
}
printf("Solution: %d\n", count);
end_time();
}
|
91338dd540a253492c6b7177c0cb13e47e4cc76e
|
a8c2faf5a0076d254b9cfecb86c56c1b9a75e7e7
|
/src/frameworkHistogramProducer.cc
|
54927d6214dc2cc3827cae44bfebde885c306e65
|
[] |
no_license
|
neilSchroeder/cms-lce-framework
|
085c0935f79607ed8e0dd92cbd8402afbbd3ab71
|
aae32ec6b46d11ade065b6a15bf772cc32385167
|
refs/heads/master
| 2020-04-16T05:26:25.912860
| 2019-08-19T15:22:24
| 2019-08-19T15:22:24
| 165,305,022
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 47,901
|
cc
|
frameworkHistogramProducer.cc
|
#ifndef utilityhistograms
#define utilityhistograms
/*
*
*
*
* This is where the functions used to produce the plots for the systematic
* uncertainty on the photon energy scale are defined.
*
*
*/
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <TH1.h>
#include <TH2.h>
#include <TFile.h>
#include <TTree.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TGaxis.h>
#include <TLegend.h>
#include <TCollection.h>
#include <TKey.h>
#include <TPave.h>
#include <TLatex.h>
#include <TPaletteAxis.h>
#include <TStyle.h>
#include <TTree.h>
#include "../interface/frameworkHistogramProducer.h"
//#define DEBUG
//#define ETA_VETO
//#define EVENT_INFO
//#define ALT_R9
//#define ALT_ETA
//#define DOITWRONG
extern std::string DIRECTORY_NAME;
/// Produce FNUF Histograms only analyzes two files at a time
void myHistogramProducer::produce_FNUF_Histograms( std::string ele_file, std::string pho_file, std::string outputFileName, std::string outputDirectoryName){
TH1F * distEta_ele = new TH1F("distEta_ele", "", 200, -2.5, 2.5);
TH1F * distEta_pho = new TH1F("distEta_pho", "", 200, -2.5, 2.5);
std::string ret = "";
std::cout << "[INFO] Electron File: " << ele_file << "\n[INFO] Photon File: " << pho_file << std::endl;
//declare some constants
#ifdef ALT_R9
int numR9bins = 6;
double r9Bins[7] = {0, 0.8, 0.9, 0.92, 0.94, 0.96, 1.00};
#else
int numR9bins = 5;
double r9Bins[6] = {0, 0.8, 0.9, 0.92, 0.96, 1.00};
#endif
#ifdef ALT_ETA
int numEtaBins = 9;
double etaBins [10] = {0, 0.3, 0.7, 1.1, 1.4442, 1.57, 1.8, 2.1, 2.4, 2.5};
#else
int numEtaBins = 8;
double etaBins [9] = {0, 0.3, 0.7, 1.1, 1.4442, 1.57, 1.8, 2.1, 2.5};
#endif
int apdBins = 100;
double apdMin = 0;
double apdMax = 1;
//make the histograms
//note: plotting using this code has been temporarily disabled
//declare std::vectors for an iterative TH1 creation method
std::vector< std::vector<TH1F*> > Histogramse_0;
std::vector< std::vector<TH1F*> > Histogramsg_0;
std::vector< std::vector<TH1F*> > Histogramse_1;
std::vector< std::vector<TH1F*> > Histogramsg_1;
std::vector< std::vector<TH1F*> > Histogramse_2;
std::vector< std::vector<TH1F*> > Histogramsg_2;
std::vector< std::vector<TH1F*> > Histogramse_3;
std::vector< std::vector<TH1F*> > Histogramsg_3;
std::vector< std::vector<TH1F*> > Histogramse_4;
std::vector< std::vector<TH1F*> > Histogramsg_4;
#ifdef ALT_R9
std::vector< std::vector<TH1F*> > Histogramse_5;
std::vector< std::vector<TH1F*> > Histogramsg_5;
#endif
char titleLow [50];
char titleHigh [50];
char tagLow [50];
char tagHigh [50];
std::vector<TH1F*> Histse_0;
std::vector<TH1F*> Histsg_0;
std::vector<TH1F*> Histse_1;
std::vector<TH1F*> Histsg_1;
std::vector<TH1F*> Histse_2;
std::vector<TH1F*> Histsg_2;
std::vector<TH1F*> Histse_3;
std::vector<TH1F*> Histsg_3;
std::vector<TH1F*> Histse_4;
std::vector<TH1F*> Histsg_4;
#ifdef ALT_R9
std::vector<TH1F*> Histse_5;
std::vector<TH1F*> Histsg_5;
#endif
int count = 1;
int bins = 125600;
//create the necessary histograms
for(int iii = 0; iii < numEtaBins; iii++){
double etaMax = etaBins[iii+1];
double etaMin = etaBins[iii];
double apd = 1;
for(int jjj = 0; jjj < 100; jjj++){
if( jjj > 0 ) apd -= 0.01;
sprintf( titleLow, "e R9_0, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( titleHigh, "g R9_0, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( tagLow, "e_0_%i_%i_%i", iii, iii+1, jjj);
sprintf( tagHigh, "g_0_%i_%i_%i", iii, iii+1, jjj);
TH1F * eHist_0 = new TH1F( tagLow, titleLow, bins, 0, 5);
TH1F * gHist_0 = new TH1F( tagHigh, titleHigh, bins, 0, 5);
sprintf( titleLow, "e R9_1, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( titleHigh, "g R9_1, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( tagLow, "e_1_%i_%i_%i", iii, iii+1, jjj);
sprintf( tagHigh, "g_1_%i_%i_%i", iii, iii+1, jjj);
TH1F * eHist_1 = new TH1F( tagLow, titleLow, bins, 0, 5);
TH1F * gHist_1 = new TH1F( tagHigh, titleHigh, bins, 0, 5);
sprintf( titleLow, "e R9_2, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( titleHigh, "g R9_2, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( tagLow, "e_2_%i_%i_%i", iii, iii+1, jjj);
sprintf( tagHigh, "g_2_%i_%i_%i", iii, iii+1, jjj);
TH1F * eHist_2 = new TH1F( tagLow, titleLow, bins, 0, 5);
TH1F * gHist_2 = new TH1F( tagHigh, titleHigh, bins, 0, 5);
sprintf( titleLow, "e R9_3, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( titleHigh, "g R9_3, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( tagLow, "e_3_%i_%i_%i", iii, iii+1, jjj);
sprintf( tagHigh, "g_3_%i_%i_%i", iii, iii+1, jjj);
TH1F * eHist_3 = new TH1F( tagLow, titleLow, bins, 0, 5);
TH1F * gHist_3 = new TH1F( tagHigh, titleHigh, bins, 0, 5);
sprintf( titleLow, "e R9_4, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( titleHigh, "g R9_4, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( tagLow, "e_4_%i_%i_%i", iii, iii+1, jjj);
sprintf( tagHigh, "g_4_%i_%i_%i", iii, iii+1, jjj);
TH1F * eHist_4 = new TH1F( tagLow, titleLow, bins, 0, 5);
TH1F * gHist_4 = new TH1F( tagHigh, titleHigh, bins, 0, 5);
#ifdef ALT_R9
sprintf( titleLow, "e R9_5, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( titleHigh, "g R9_5, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( tagLow, "e_5_%i_%i_%i", iii, iii+1, jjj);
sprintf( tagHigh, "g_5_%i_%i_%i", iii, iii+1, jjj);
TH1F * eHist_5 = new TH1F( tagLow, titleLow, bins, 0, 5);
TH1F * gHist_5 = new TH1F( tagHigh, titleHigh, bins, 0, 5);
#endif
Histse_0.push_back(eHist_0);
Histsg_0.push_back(gHist_0);
Histse_1.push_back(eHist_1);
Histsg_1.push_back(gHist_1);
Histse_2.push_back(eHist_2);
Histsg_2.push_back(gHist_2);
Histse_3.push_back(eHist_3);
Histsg_3.push_back(gHist_3);
Histse_4.push_back(eHist_4);
Histsg_4.push_back(gHist_4);
#ifdef ALT_R9
Histse_5.push_back(eHist_5);
Histsg_5.push_back(gHist_5);
#endif
if(iii != 4) count++;
}//end for jjj
Histogramse_0.push_back(Histse_0);
Histogramsg_0.push_back(Histsg_0);
Histogramse_1.push_back(Histse_1);
Histogramsg_1.push_back(Histsg_1);
Histogramse_2.push_back(Histse_2);
Histogramsg_2.push_back(Histsg_2);
Histogramse_3.push_back(Histse_3);
Histogramsg_3.push_back(Histsg_3);
Histogramse_4.push_back(Histse_4);
Histogramsg_4.push_back(Histsg_4);
#ifdef ALT_R9
Histogramse_5.push_back(Histse_5);
Histogramsg_5.push_back(Histsg_5);
#endif
Histse_0.clear();
Histsg_0.clear();
Histse_1.clear();
Histsg_1.clear();
Histse_2.clear();
Histsg_2.clear();
Histse_3.clear();
Histsg_3.clear();
Histse_4.clear();
Histsg_4.clear();
#ifdef ALT_R9
Histse_5.clear();
Histsg_5.clear();
#endif
}//end for iii
//tree members
float R9 [2];
float full5x5_R9 [2];
float energyR [2];
float eta [2];
float etaSC [2];
float phi [2];
float energyG [2];
float etaS [2];
float phiS [2];
float rawSuperClusterEnergy [2];
float def_nomiRecHitSum [2];
double apd_lce_RecHitSums1 [100];
double apd_lce_RecHitSums2 [100];
double linearEnergies1 [8];
double linearEnergies2 [8];
float dr [2];
float seedCrystalRatio [2];
int showerMaxBin [2];
float supClustCrystals [2];
Long64_t run, event, lum;
//File stuffs
std::ifstream in;
in.open( ele_file.c_str() );
std::string rootFile;
bool noVeto = true;
// by my own convention this loop will be the electron loop
while( in >> rootFile){
if(TFile::Open(rootFile.c_str(), "READ")){
TFile * myFile = TFile::Open(rootFile.c_str());
if(!(myFile->IsZombie())){
TIter next(myFile->GetListOfKeys());
TKey *key;
while( (key = (TKey*)next()) ){
std::string ntuples = "ntuples";
if(rootFile.find("High") != std::string::npos) ntuples = "ntuplesHigh";
if(rootFile.find("Low") != std::string::npos) ntuples = "ntuplesLow";
if( ntuples.compare(key->GetName()) == 0 ){
std::string folder = "ntuples/data";
if(rootFile.find("High") != std::string::npos) folder = "ntuplesHigh/data";
if(rootFile.find("Low") != std::string::npos) folder = "ntuplesLow/data";
TTree * thisTTree = (TTree*)myFile->Get(folder.c_str());
thisTTree->SetBranchAddress("RECO_Energy", energyR);
thisTTree->SetBranchAddress("Super_Cluster_Raw_Energy", rawSuperClusterEnergy);
thisTTree->SetBranchAddress("Rechit_Energy_Sum_1", def_nomiRecHitSum);
thisTTree->SetBranchAddress("apd_lce_RecHitSums1", apd_lce_RecHitSums1);
thisTTree->SetBranchAddress("apd_lce_RecHitSums2", apd_lce_RecHitSums2);
thisTTree->SetBranchAddress("Gen_Energy", energyG);
thisTTree->SetBranchAddress("R9", R9);
thisTTree->SetBranchAddress("Full_5x5_R9", full5x5_R9);
thisTTree->SetBranchAddress("Reco_Eta", eta);
thisTTree->SetBranchAddress("Super_Cluster_Eta", etaSC);
thisTTree->SetBranchAddress("Gen_Eta", etaS);
thisTTree->SetBranchAddress("Reco_Phi", phi);
thisTTree->SetBranchAddress("Gen_Phi", phiS);
thisTTree->SetBranchAddress("dR", dr);
//thisTTree->SetBranchAddress("Super_Cluster_Crystals", supClustCrystals);
//thisTTree->SetBranchAddress("Shower_Max_Bin", showerMaxBin);
thisTTree->SetBranchAddress("run", &run);
thisTTree->SetBranchAddress("event", &event);
thisTTree->SetBranchAddress("lum", &lum);
/////////////////////////////////////////////////////////////////////////////////////////////
//this part of the code fills the histograms
for(Long64_t treeIndex = 0; treeIndex < thisTTree->GetEntries(); treeIndex++){
thisTTree->GetEntry(treeIndex);
#ifdef DEBUG
std::cout << etaSC[0] << " " << eta[0] << std::endl;
std::cout << etaSC[1] << " " << eta[1] << std::endl;
std::cout << full5x5_R9[0] << " " << R9[0] << std::endl;
std::cout << full5x5_R9[1] << " " << R9[1] << std::endl;
#endif
if(etaSC[0] == -999 && eta[0] != -999) etaSC[0] = eta[0];
if(etaSC[1] == -999 && eta[1] != -999) etaSC[1] = eta[1];
if(full5x5_R9[0] == -999 && R9[0] != -999) full5x5_R9[0] = R9[0];
if(full5x5_R9[1] == -999 && R9[1] != -999) full5x5_R9[1] = R9[1];
#ifdef DEBUG
std::cout << etaSC[0] << " " << eta[0] << std::endl;
std::cout << etaSC[1] << " " << eta[1] << std::endl;
#endif
//determine which eta bin the first electron falls into
#ifdef DOITWRONG
int etaIndex1 = fabs(etaSC[0])/(2.5/(double)numEtaBins);
int etaIndex2 = fabs(etaSC[1])/(2.5/(double)numEtaBins);
#else
int etaIndex1 = -1;
int etaIndex2 = -1;
#endif
#ifdef DOITWRONG
for(int i = 0; i < numEtaBins-1; i++){
#else
for(int i = 0; i < numEtaBins; i++){
#endif
if( fabs(etaSC[0]) > etaBins[i] && fabs(etaSC[0]) < etaBins[i+1]){
etaIndex1 = i;
}
if( fabs(etaSC[1]) > etaBins[i] && fabs(etaSC[1]) < etaBins[i+1]){
etaIndex2 = i;
}
}
//the following if statement is just a catch for particles
// with an eta more than 2.5
#ifdef DOITWRONG
if(etaIndex1 < numEtaBins && etaIndex2 < numEtaBins){
#else
if(etaIndex1 != -1){
#endif
distEta_ele->Fill(etaSC[0]);
noVeto = true;
#ifdef ETA_VETO
if(fabs(etaSC[0]) < 0.024) noVeto = false;
if(fabs(etaSC[0]) > 0.432 && fabs(etaSC[0]) < 0.456) noVeto = false;
if(fabs(etaSC[0]) > 0.768 && fabs(etaSC[0]) < 0.816) noVeto = false;
if(fabs(etaSC[0]) > 1.128 && fabs(etaSC[0]) < 1.152) noVeto = false;
#endif
if(noVeto){
//make 2D plots for R9 bins:::
if(full5x5_R9[0] > r9Bins[0] && full5x5_R9[0] < r9Bins[1]){
for(int i = 0; i < 100; i++){
Histogramse_0[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
if(full5x5_R9[0] > r9Bins[1] && full5x5_R9[0] < r9Bins[2]){
for(int i = 0; i < 100; i++){
Histogramse_1[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
if(full5x5_R9[0] > r9Bins[2] && full5x5_R9[0] < r9Bins[3]){
for(int i = 0; i < 100; i++){
Histogramse_2[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
if(full5x5_R9[0] > r9Bins[3] && full5x5_R9[0] < r9Bins[4]){
for(int i = 0; i < 100; i++){
Histogramse_3[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
if(full5x5_R9[0] > r9Bins[4] && full5x5_R9[0] < r9Bins[5]){
for(int i = 0; i < 100; i++){
Histogramse_4[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
#ifdef ALT_R9
if(full5x5_R9[0] > r9Bins[5] && full5x5_R9[0] < r9Bins[6]){
for(int i = 0; i < 100; i++){
Histogramse_5[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
#endif
}
}
#ifdef DOITWRONG
if(etaIndex1 < numEtaBins && etaIndex2 < numEtaBins){
#else
if(etaIndex2 != -1){
#endif
distEta_ele->Fill(etaSC[1]);
#ifdef ETA_VETO
noVeto = true;
if(fabs(etaSC[1]) < 0.024 ) noVeto = false;
if(fabs(etaSC[1]) > 0.432 && fabs(etaSC[1]) < 0.456) noVeto = false;
if(fabs(etaSC[1]) > 0.768 && fabs(etaSC[1]) < 0.816) noVeto = false;
if(fabs(etaSC[1]) > 1.128 && fabs(etaSC[1]) < 1.152) noVeto = false;
#endif
if(noVeto){
if(full5x5_R9[1] > r9Bins[0] && full5x5_R9[1] < r9Bins[1]){
for(int i = 0; i < 100; i++){
Histogramse_0[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
if(full5x5_R9[1] > r9Bins[1] && full5x5_R9[1] < r9Bins[2]){
for(int i = 0; i < 100; i++){
Histogramse_1[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
if(full5x5_R9[1] > r9Bins[2] && full5x5_R9[1] < r9Bins[3]){
for(int i = 0; i < 100; i++){
Histogramse_2[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
if(full5x5_R9[1] > r9Bins[3] && full5x5_R9[1] < r9Bins[4]){
for(int i = 0; i < 100; i++){
Histogramse_3[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
if(full5x5_R9[1] > r9Bins[4] && full5x5_R9[1] < r9Bins[5]){
for(int i = 0; i < 100; i++){
Histogramse_4[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
#ifdef ALT_R9
if(full5x5_R9[1] > r9Bins[5] && full5x5_R9[1] < r9Bins[6]){
for(int i = 0; i < 100; i++){
Histogramse_5[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
#endif
}
}
}//end for tree index
}// end if found key named ntuples
else{
std::cout << "[ERROR] Did not find directory 'ntuples' for file " << rootFile << std::endl;
std::cout << "[ERROR-RECOVER] ... continuing without this file." << std::endl;
}
}//end while keys
}//end if not zombie
else{
std::cout << "[ERROR] The file " << ele_file << " did not open properly" << std::endl;
std::cout << "[ERROR-RECOVER] ... continuing without this file." << std::endl;
}
myFile->Close();
}//end if file opens
else{
std::cout << "[ERROR] the file " << rootFile << " did not open or does not exist" << std::endl;
std::cout << "[ERROR-RECOVER] ... continuing without this file." << std::endl;
}
}//end while files in
in.close();
in.open( pho_file.c_str() );
// this loop will be the photon loop
while( in >> rootFile){
if(TFile::Open(rootFile.c_str(), "READ")){
TFile * myFile = TFile::Open(rootFile.c_str());
if(!(myFile->IsZombie())){
TIter next(myFile->GetListOfKeys());
TKey *key;
while( (key = (TKey*)next()) ){
std::string ntuples = "ntuples";
if(rootFile.find("High") != std::string::npos) ntuples = "ntuplesHigh";
if(rootFile.find("Low") != std::string::npos) ntuples = "ntuplesLow";
if( ntuples.compare(key->GetName()) == 0 ){
std::string folder = "ntuples/data";
if(ntuples.find("High") != std::string::npos) folder = "ntuplesHigh/data";
if(ntuples.find("Low") != std::string::npos) folder = "ntuplesLow/data";
TTree * thisTTree = (TTree*)myFile->Get(folder.c_str());
thisTTree->SetBranchAddress("RECO_Energy", energyR);
thisTTree->SetBranchAddress("Super_Cluster_Raw_Energy", rawSuperClusterEnergy);
thisTTree->SetBranchAddress("Rechit_Energy_Sum_1", def_nomiRecHitSum);
thisTTree->SetBranchAddress("apd_lce_RecHitSums1", apd_lce_RecHitSums1);
thisTTree->SetBranchAddress("apd_lce_RecHitSums2", apd_lce_RecHitSums2);
thisTTree->SetBranchAddress("Gen_Energy", energyG);
thisTTree->SetBranchAddress("R9", R9);
thisTTree->SetBranchAddress("Full_5x5_R9", full5x5_R9);
thisTTree->SetBranchAddress("Reco_Eta", eta);
thisTTree->SetBranchAddress("Super_Cluster_Eta", etaSC);
thisTTree->SetBranchAddress("Gen_Eta", etaS);
thisTTree->SetBranchAddress("Reco_Phi", phi);
thisTTree->SetBranchAddress("Gen_Phi", phiS);
thisTTree->SetBranchAddress("dR", dr);
//thisTTree->SetBranchAddress("Super_Cluster_Crystals", supClustCrystals);
//thisTTree->SetBranchAddress("Shower_Max_Bin", showerMaxBin);
thisTTree->SetBranchAddress("run", &run);
thisTTree->SetBranchAddress("event", &event);
thisTTree->SetBranchAddress("lum", &lum);
for(Long64_t treeIndex = 0; treeIndex < thisTTree->GetEntries(); treeIndex++){
thisTTree->GetEntry(treeIndex);
#ifdef DOITWRONG
int etaIndex1 = fabs(etaSC[0])/(2.5/(double)numEtaBins);
int etaIndex2 = fabs(etaSC[1])/(2.5/(double)numEtaBins);
#else
int etaIndex1 = -1;
int etaIndex2 = -1;
#endif
#ifdef DOITWRONG
for(int i = 0; i < numEtaBins-1; i++){
#else
for(int i = 0; i < numEtaBins; i++){
#endif
if( fabs(etaSC[0]) > etaBins[i] && fabs(etaSC[0]) < etaBins[i+1]){
etaIndex1 = i;
}
if( fabs(etaSC[1]) > etaBins[i] && fabs(etaSC[1]) < etaBins[i+1]){
etaIndex2 = i;
}
}
#ifdef DOITWRONG
if(etaIndex1 < numEtaBins && etaIndex2 < numEtaBins){
#else
if(etaIndex1 != -1){
#endif
distEta_pho->Fill(etaSC[0]);
#ifdef ETA_VETO
noVeto = true;
if(fabs(etaSC[0]) < 0.024) noVeto = false;
if(fabs(etaSC[0]) > 0.432 && fabs(etaSC[0]) < 0.456) noVeto = false;
if(fabs(etaSC[0]) > 0.768 && fabs(etaSC[0]) < 0.816) noVeto = false;
if(fabs(etaSC[0]) > 1.128 && fabs(etaSC[0]) < 1.152) noVeto = false;
#endif
if(noVeto){
//make 2D plots for R9 bins:::
if(full5x5_R9[0] > r9Bins[0] && full5x5_R9[0] < r9Bins[1]){
for(int i = 0; i < 100; i++){
Histogramsg_0[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
if(full5x5_R9[0] > r9Bins[1] && full5x5_R9[0] < r9Bins[2]){
for(int i = 0; i < 100; i++){
Histogramsg_1[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
if(full5x5_R9[0] > r9Bins[2] && full5x5_R9[0] < r9Bins[3]){
for(int i = 0; i < 100; i++){
Histogramsg_2[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
if(full5x5_R9[0] > r9Bins[3] && full5x5_R9[0] < r9Bins[4]){
for(int i = 0; i < 100; i++){
Histogramsg_3[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
if(full5x5_R9[0] > r9Bins[4] && full5x5_R9[0] < r9Bins[5]){
for(int i = 0; i < 100; i++){
Histogramsg_4[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
#ifdef ALT_R9
if(full5x5_R9[0] > r9Bins[5] && full5x5_R9[0] < r9Bins[6]){
for(int i = 0; i < 100; i++){
Histogramsg_5[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
#endif
}//end if veto
}
#ifdef DOITWRONG
if(etaIndex1 < numEtaBins && etaIndex2 < numEtaBins){
#else
if(etaIndex2 != -1){
#endif
distEta_pho->Fill(etaSC[1]);
#ifdef ETA_VETO
noVeto = true;
if(fabs(etaSC[1]) < 0.024) noVeto = false;
if(fabs(etaSC[1]) > 0.432 && fabs(etaSC[1]) < 0.456) noVeto = false;
if(fabs(etaSC[1]) > 0.768 && fabs(etaSC[1]) < 0.816) noVeto = false;
if(fabs(etaSC[1]) > 1.128 && fabs(etaSC[1]) < 1.152) noVeto = false;
#endif
if(noVeto){
if(full5x5_R9[1] > r9Bins[0] && full5x5_R9[1] < r9Bins[1]){
for(int i = 0; i < 100; i++){
Histogramsg_0[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
if(full5x5_R9[1] > r9Bins[1] && full5x5_R9[1] < r9Bins[2]){
for(int i = 0; i < 100; i++){
Histogramsg_1[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
if(full5x5_R9[1] > r9Bins[2] && full5x5_R9[1] < r9Bins[3]){
for(int i = 0; i < 100; i++){
Histogramsg_2[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
if(full5x5_R9[1] > r9Bins[3] && full5x5_R9[1] < r9Bins[4]){
for(int i = 0; i < 100; i++){
Histogramsg_3[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
if(full5x5_R9[1] > r9Bins[4] && full5x5_R9[1] < r9Bins[5]){
for(int i = 0; i < 100; i++){
Histogramsg_4[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
#ifdef ALT_R9
if(full5x5_R9[1] > r9Bins[5] && full5x5_R9[1] < r9Bins[6]){
for(int i = 0; i < 100; i++){
Histogramsg_5[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
#endif
}
}
}//end for tree index
}//end if key == ntuples
else{
std::cout << "[ERROR] Did not find directory 'ntuples' for file " << rootFile << std::endl;
std::cout << "[ERROR-RECOVER] ... continuing without this file." << std::endl;
}
}//end while keys
}//end if is zombie
else{
std::cout << "[ERROR] The file " << pho_file << " did not open correctly" << std::endl;
std::cout << "[ERROR-RECOVER] ... continuing without this file." << std::endl;
}
myFile->Close();
}
else{
std::cout << "[ERROR] The file " << pho_file << " did not open or does not exist" << std::endl;
std::cout << "[ERROR-RECOVER] ... continuing without this file." << std::endl;
}
}//end while files in
in.close();
// manage output directory
//
DIRECTORY_NAME = outputDirectoryName;
std::cout << "[EXECUTE] source ./clean_up_directories.sh "+DIRECTORY_NAME << std::endl;
system(std::string("source ./clean_up_directories.sh "+DIRECTORY_NAME).c_str());
//////////////////////////////////////////////////////
std::string fileOut = DIRECTORY_NAME+outputFileName;
if(fileOut.find(".root") == std::string::npos) fileOut = fileOut+".root";
std::cout<< "[INFO] files successfully analyzed... " << std::endl;
std::cout<< "[INFO] begin writing to file `"<< fileOut << "' ..." << std::endl;
//////////////////////////////////////////////////////
TFile * out = new TFile(fileOut.c_str(), "RECREATE");
out->cd();
for(int i = 0; i < numEtaBins; i++){
for(int j = 0; j < apdBins; j++){
Histogramse_0[i][j]->Write();
Histogramse_1[i][j]->Write();
Histogramse_2[i][j]->Write();
Histogramse_3[i][j]->Write();
Histogramse_4[i][j]->Write();
Histogramsg_0[i][j]->Write();
Histogramsg_1[i][j]->Write();
Histogramsg_2[i][j]->Write();
Histogramsg_3[i][j]->Write();
Histogramsg_4[i][j]->Write();
#ifdef ALT_R9
if(!Histogramse_5[i][j] || !Histogramsg_5[i][j]){
std::cout << "YOU DONE GOOFED" << i << " " << j<< std::endl;
}
Histogramse_5[i][j]->Write();
Histogramsg_5[i][j]->Write();
#endif
#ifdef EVENT_INFO
if(j == 0){
std::cout << "[EVENT INFO] there are " << Histogramse_0[i][j]->GetEntries() + Histogramse_1[i][j]->GetEntries() + Histogramse_2[i][j]->GetEntries() + Histogramse_3[i][j]->GetEntries() + Histogramse_4[i][j]->GetEntries() << " electrons in the bin eta = " << i << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramse_0[i][j]->GetEntries() << " electrons in the (r9, eta) bin (0, "<<i<<") " << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramse_1[i][j]->GetEntries() << " electrons in the (r9, eta) bin (1, "<<i<<") " << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramse_2[i][j]->GetEntries() << " electrons in the (r9, eta) bin (2, "<<i<<") " << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramse_3[i][j]->GetEntries() << " electrons in the (r9, eta) bin (3, "<<i<<") " << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramse_4[i][j]->GetEntries() << " electrons in the (r9, eta) bin (4, "<<i<<") " << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramsg_0[i][j]->GetEntries() + Histogramsg_1[i][j]->GetEntries() + Histogramsg_2[i][j]->GetEntries() + Histogramsg_3[i][j]->GetEntries() + Histogramsg_4[i][j]->GetEntries() << " photons in the bin eta = " << i << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramsg_0[i][j]->GetEntries() << " photons in the (r9, eta) bin (0, "<<i<<") " << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramsg_1[i][j]->GetEntries() << " photons in the (r9, eta) bin (1, "<<i<<") " << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramsg_2[i][j]->GetEntries() << " photons in the (r9, eta) bin (2, "<<i<<") " << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramsg_3[i][j]->GetEntries() << " photons in the (r9, eta) bin (3, "<<i<<") " << std::endl;
std::cout << "[EVENT INFO] there are " << Histogramsg_4[i][j]->GetEntries() << " photons in the (r9, eta) bin (4, "<<i<<") " << std::endl;
}
#endif
}
}
distEta_ele->Write();
distEta_pho->Write();
out->Close();
for(int i = 0; i < numEtaBins; i++){
for(int j = 0; j < apdBins; j++){
delete Histogramse_0[i][j];
delete Histogramse_1[i][j];
delete Histogramse_2[i][j];
delete Histogramse_3[i][j];
delete Histogramse_4[i][j];
delete Histogramsg_0[i][j];
delete Histogramsg_1[i][j];
delete Histogramsg_2[i][j];
delete Histogramsg_3[i][j];
delete Histogramsg_4[i][j];
#ifdef ALT_R9
delete Histogramse_5[i][j];
delete Histogramsg_5[i][j];
#endif
}
}
delete distEta_ele;
delete distEta_pho;
std::cout << "[STATUS] finished writing to file... " << std::endl;
return;
};
void myHistogramProducer::produce_PION_Histograms( std::string ele_file, std::string pi_file, std::string outputFileName, std::string outputDirectoryName){
std::string ret = "";
std::cout << "You are working with Pions" << std::endl;
std::cout << "Electron File: " << ele_file << "\nPhoton File: " << pi_file << std::endl;
//declare some constants
int numEtaBins = 8;
double etaBins [9] = {0, 0.3, 0.7, 1.1, 1.4442, 1.57, 1.8, 2.1, 2.5};
int apdBins = 100;
double apdMin = 0;
double apdMax = 1;
//make the histograms
//note: plotting using this code has been temporarily disabled
//declare std::vectors for an iterative TH1 creation method
std::vector< std::vector<TH1F*> > Histogramse_0;
std::vector< std::vector<TH1F*> > Histogramsg_0;
char titleLow [50];
char titleHigh [50];
char tagLow [50];
char tagHigh [50];
std::vector<TH1F*> Histse_0;
std::vector<TH1F*> Histsg_0;
int count = 1;
int bins = 125600;
//create the necessary histograms
for(int iii = 0; iii < numEtaBins; iii++){
double etaMax = ((double)iii+1)*(2.5/(double)numEtaBins);
double etaMin = (double)iii * 2.5/(double)numEtaBins;
double apd = 1;
for(int jjj = 0; jjj < 100; jjj++){
if( jjj > 0 ) apd -= 0.01;
sprintf( titleLow, "e R9_0, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( titleHigh, "g R9_0, %lf < |#eta| < %lf, APD/PN = %lf", etaMin, etaMax, apd);
sprintf( tagLow, "e_0_%i_%i_%i", iii, iii+1, jjj);
sprintf( tagHigh, "g_0_%i_%i_%i", iii, iii+1, jjj);
TH1F * eHist_0 = new TH1F( tagLow, titleLow, bins, 0, 5);
TH1F * gHist_0 = new TH1F( tagHigh, titleHigh, bins, 0, 5);
Histse_0.push_back(eHist_0);
Histsg_0.push_back(gHist_0);
if(iii != 4) count++;
}//end for jjj
Histogramse_0.push_back(Histse_0);
Histogramsg_0.push_back(Histsg_0);
Histse_0.clear();
Histsg_0.clear();
}//end for iii
//tree members
float R9 [2];
float full5x5_R9 [2];
float energyR [2];
float eta [2];
float etaSC [2];
float phi [2];
float energyG [2];
float etaS [2];
float phiS [2];
float rawSuperClusterEnergy [2];
float def_nomiRecHitSum [2];
double apd_lce_RecHitSums1 [100];
double apd_lce_RecHitSums2 [100];
double linearEnergies1 [8];
double linearEnergies2 [8];
float dr [2];
float seedCrystalRatio [2];
int showerMaxBin [2];
float supClustCrystals [2];
Long64_t run, event, lum;
//File stuffs
std::ifstream in;
in.open( ele_file.c_str() );
std::string rootFile;
bool noVeto = true;
// by my own convention this loop will be the electron loop
while( in >> rootFile){
TFile * myFile = TFile::Open(rootFile.c_str());
if(!(myFile->IsZombie())){
TIter next(myFile->GetListOfKeys());
TKey *key;
while( (key = (TKey*)next()) ){
std::string ntuples = "ntuples";
if(rootFile.find("High") != std::string::npos) ntuples = "ntuplesHigh";
if(rootFile.find("Low") != std::string::npos) ntuples = "ntuplesLow";
if( ntuples.compare(key->GetName()) == 0 ){
std::string folder = "ntuples/data";
if(rootFile.find("High") != std::string::npos) folder = "ntuplesHigh/data";
if(rootFile.find("Low") != std::string::npos) folder = "ntuplesLow/data";
TTree * thisTTree = (TTree*)myFile->Get(folder.c_str());
thisTTree->SetBranchAddress("RECO_Energy", energyR);
thisTTree->SetBranchAddress("Super_Cluster_Raw_Energy", rawSuperClusterEnergy);
thisTTree->SetBranchAddress("Rechit_Energy_Sum_1", def_nomiRecHitSum);
thisTTree->SetBranchAddress("apd_lce_RecHitSums1", apd_lce_RecHitSums1);
thisTTree->SetBranchAddress("apd_lce_RecHitSums2", apd_lce_RecHitSums2);
thisTTree->SetBranchAddress("Gen_Energy", energyG);
thisTTree->SetBranchAddress("R9", R9);
thisTTree->SetBranchAddress("Full_5x5_R9", full5x5_R9);
thisTTree->SetBranchAddress("Reco_Eta", eta);
thisTTree->SetBranchAddress("Super_Cluster_Eta", etaSC);
thisTTree->SetBranchAddress("Reco_Phi", phi);
thisTTree->SetBranchAddress("Gen_Phi", phiS);
thisTTree->SetBranchAddress("dR", dr);
thisTTree->SetBranchAddress("run", &run);
thisTTree->SetBranchAddress("event", &event);
thisTTree->SetBranchAddress("lum", &lum);
/////////////////////////////////////////////////////////////////////////////////////////////
//this part of the code fills the histograms
for(Long64_t treeIndex = 0; treeIndex < thisTTree->GetEntries(); treeIndex++){
thisTTree->GetEntry(treeIndex);
if( dr[0] != 999 && dr[1] != 999){
//determine which eta bin the first electron falls into
int etaIndex1 = fabs(etaSC[0])/(2.5/(double)numEtaBins);
int etaIndex2 = fabs(etaSC[1])/(2.5/(double)numEtaBins);;
for(int i = 0; i < numEtaBins - 1 ; i++){
if( fabs(etaSC[0]) > etaBins[i] && fabs(etaSC[0]) < etaBins[i+1]){
etaIndex1 = i;
}
if( fabs(etaSC[1]) > etaBins[i] && fabs(etaSC[1]) < etaBins[i+1]){
etaIndex2 = i;
}
}
if( etaIndex1 < numEtaBins && full5x5_R9[0] > 0.94){
//make 2D plots for R9 bins:::
for(int i = 0; i < 100; i++){
Histogramse_0[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
if( etaIndex2 < numEtaBins && full5x5_R9[1] > 0.94){
for(int i = 0; i < 100; i++){
Histogramse_0[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}
}//end if both particles are reconstructed
}//end for tree index
}// end if found key named ntuples
else{
std::cout << "Did not find directory 'ntuples' for file " << rootFile << std::endl;
std::cout << "... continuing without this file." << std::endl;
}
}//end while keys
}//end if not zombie
else{
std::cout << "The file " << ele_file << " did not open properly" << std::endl;
std::cout << "... continuing without this file." << std::endl;
}
myFile->Close();
}//end while files in
in.close();
in.open( pi_file.c_str() );
// this loop will be the photon loop
while( in >> rootFile){
TFile * myFile = TFile::Open(rootFile.c_str());
if(!(myFile->IsZombie())){
TIter next(myFile->GetListOfKeys());
TKey *key;
while( (key = (TKey*)next()) ){
std::string ntuples = "ntuples";
if(rootFile.find("High") != std::string::npos) ntuples = "ntuplesHigh";
if(rootFile.find("Low") != std::string::npos) ntuples = "ntuplesLow";
if( ntuples.compare(key->GetName()) == 0 ){
std::string folder = "ntuples/data";
if(ntuples.find("High") != std::string::npos) folder = "ntuplesHigh/data";
if(ntuples.find("Low") != std::string::npos) folder = "ntuplesLow/data";
TTree * thisTTree = (TTree*)myFile->Get(folder.c_str());
thisTTree->SetBranchAddress("RECO_Energy", energyR);
thisTTree->SetBranchAddress("Super_Cluster_Raw_Energy", rawSuperClusterEnergy);
thisTTree->SetBranchAddress("Rechit_Energy_Sum_1", def_nomiRecHitSum);
thisTTree->SetBranchAddress("apd_lce_RecHitSums1", apd_lce_RecHitSums1);
thisTTree->SetBranchAddress("apd_lce_RecHitSums2", apd_lce_RecHitSums2);
thisTTree->SetBranchAddress("Gen_Energy", energyG);
thisTTree->SetBranchAddress("R9", R9);
thisTTree->SetBranchAddress("Full_5x5_R9", full5x5_R9);
thisTTree->SetBranchAddress("Reco_Eta", eta);
thisTTree->SetBranchAddress("Reco_Phi", phi);
thisTTree->SetBranchAddress("Gen_Phi", phiS);
thisTTree->SetBranchAddress("dR", dr);
thisTTree->SetBranchAddress("run", &run);
thisTTree->SetBranchAddress("event", &event);
thisTTree->SetBranchAddress("lum", &lum);
for(Long64_t treeIndex = 0; treeIndex < thisTTree->GetEntries(); treeIndex++){
thisTTree->GetEntry(treeIndex);
int etaIndex1 = fabs(eta[0])/(2.5/(double)numEtaBins);
int etaIndex2 = fabs(eta[1])/(2.5/(double)numEtaBins);
for(int i = 0; i < numEtaBins - 1 ; i++){
if( fabs(eta[0]) > etaBins[i] && fabs(eta[0]) < etaBins[i+1]){
etaIndex1 = i;
}
if( fabs(eta[1]) > etaBins[i] && fabs(eta[1]) < etaBins[i+1]){
etaIndex2 = i;
}
}
if(etaIndex1 < numEtaBins){
for(int i = 0; i < 100; i++){
Histogramsg_0[etaIndex1][i]->Fill(apd_lce_RecHitSums1[i]/def_nomiRecHitSum[0]);
}//end for apd bins
}
if(etaIndex2 < numEtaBins){
for(int i = 0; i < 100; i++){
Histogramsg_0[etaIndex2][i]->Fill(apd_lce_RecHitSums2[i]/def_nomiRecHitSum[1]);
}//end for apd bins
}//end if the particles are inside 2.5
}//end for tree index
}//end if key == ntuples
else{
std::cout << "Did not find directory 'ntuples' for file " << rootFile << std::endl;
std::cout << "... continuing without this file." << std::endl;
}
}//end while keys
}//end if is zombie
else{
std::cout << "The file " << pi_file << " did not open correctly" << std::endl;
std::cout << "... continuing without this file." << std::endl;
}
myFile->Close();
}//end while files in
in.close();
// manage output directory
//
DIRECTORY_NAME = outputDirectoryName;
system(std::string("source ./clean_up_directories.sh "+DIRECTORY_NAME).c_str());
std::cout << "source ./clean_up_directories.sh "+DIRECTORY_NAME << std::endl;
//////////////////////////////////////////////////////
std::string fileOut = DIRECTORY_NAME+outputFileName;
if(fileOut.find(".root") == std::string::npos) fileOut = fileOut+".root";
std::cout<< "files successfully analyzed... " << std::endl;
std::cout<< "begin writing to file `"<< fileOut << "' ..." << std::endl;
//////////////////////////////////////////////////////
TFile * out = new TFile(fileOut.c_str(), "RECREATE");
out->cd();
for(int i = 0; i < numEtaBins; i++){
for(int j = 0; j < apdBins; j++){
Histogramse_0[i][j]->Write();
Histogramsg_0[i][j]->Write();
}
}
out->Close();
for(int i = 0; i < numEtaBins; i++){
for(int j = 0; j < apdBins; j++){
delete Histogramse_0[i][j];
delete Histogramsg_0[i][j];
}
}
std::cout << "finished writing to file... " << std::endl;
return;
};
#endif
|
cb09ab68461cf3a5cf290ec81421f804a8c7377e
|
827322dc42ecca85d416c28ac458e28b6a4d6215
|
/examples/defaultPipeline.cpp
|
badcf0a0121168e26905b117a7a7c78091ad3475
|
[
"MIT"
] |
permissive
|
jimmiebergmann/Flare
|
182be70f8d1fb1fff62490c5139ea0161631fa27
|
68898053543b99da91d0914427e4ccc5076ae4e2
|
refs/heads/master
| 2020-04-06T20:52:13.429715
| 2019-01-15T00:36:45
| 2019-01-15T00:36:45
| 157,785,786
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,316
|
cpp
|
defaultPipeline.cpp
|
/*
* MIT License
*
* Copyright(c) 2018 Jimmie Bergmann
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files(the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions :
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <iostream>
#include "flare/flare.hpp"
#include <chrono>
int main(int argc, char ** argv)
{
/*Flare::Window window({ 800, 600 }, "Flare - Default pipeline example.");
Flare::RendererSettings settings;
settings.setWindow(&window);
std::unique_ptr<Flare::Renderer> renderer = std::make_unique<Flare::VulkanRenderer>(settings);
//Flare::Scene scene;
//scene.load("sponza.obj");
window.show();
while (window.update())
{
renderer->render();
}*/
Flare::Material mat;
/*std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < 10000; i++)
{*/
auto & out = mat.createOutputNode<Flare::Vector4f>(1.0f);
out = (mat.createVec4Node<float>(1.0f, 2.0f, 3.0f, 4.0f) * mat.createVec4Node<float>(5.0f, 6.0f, 7.0f, 8.0f)) /** mat.createScalarNode<float>(10.0f)*/;
auto & node = out.getInput().getConnection()->getNode();
auto nod2 = reinterpret_cast<Flare::MaterialMultVec4Vec4Node<float>*>(&node);
auto & out2 = mat.createOutputNode<Flare::Vector4i32>(1.0f) = mat.createVec4Node<int32_t>(11, 22, 33, 44);
/* }
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
std::cout << "It took me " << time_span.count() << " seconds.";
*/
//mat.debugPrint();
std::cout << std::endl << "-------------------------------------------" << std::endl << std::endl;
std::string glslSource = "";
mat.generateGlsl(glslSource);
std::cout << glslSource << std::endl;
//vec4->getInputX()->disconnect(a);
// auto output = material.createOutputNode("output");
/*output =*/ //Flare::Material::Vec3("name", 1.0f, 0.0f, 0.0f) * (Flare::Material::Texture2D("texture") = Flare::Material::Texture2DCoords("texture_coord"));
/*output =*/ //(material.createTexture2DNode("texture") = material.createTexture2DCoordsNode("texture_coord")) * material.createVec4Node("name", 1.0f, 0.0f, 0.0f, 1.0f);
return EXIT_SUCCESS;
}
|
f2e1862a36e0676412b302e87b8a78b5a2bbb0a0
|
a4b57e075d0b20186822bc4d565cf70b6b50bbe1
|
/Source/Night/Input.h
|
d7b23a23726fab0db862c2ceabdc8ef080ff2334
|
[] |
no_license
|
thanik/NightSimpleMaze
|
47dd3d99c928c7783abf3e0256a6d8e5633be5ff
|
9374062188cc49a682e75159eaeeebc9205da6eb
|
refs/heads/master
| 2022-12-06T13:34:07.839919
| 2020-09-03T11:35:30
| 2020-09-03T11:35:30
| 292,545,858
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 666
|
h
|
Input.h
|
#pragma once
struct InputCommands
{
bool forward;
bool back;
bool right;
bool left;
bool rotRight;
bool rotLeft;
bool rotUp;
bool rotDown;
bool cameraSwitch;
DirectX::SimpleMath::Vector3 mouseDelta;
};
class Input
{
public:
Input();
~Input();
void Initialise(HWND window);
void Update();
bool Quit();
InputCommands getGameInput();
void SetMouseMode(DirectX::Mouse::Mode mode);
private:
bool m_quitApp;
std::unique_ptr<DirectX::Keyboard> m_keyboard;
std::unique_ptr<DirectX::Mouse> m_mouse;
DirectX::Keyboard::KeyboardStateTracker m_KeyboardTracker;
DirectX::Mouse::ButtonStateTracker m_MouseTracker;
InputCommands m_GameInput;
};
|
66a7b8ca877b8942071e606fefa7e6dadd2bdd3d
|
632a1c0b67c496c05e1146ade894c78e202c047c
|
/SXR/SDK/sxrsdk/src/main/jni/vulkan/vk_cubemap_image.h
|
d3635680984778a8949127c147debccfb3a5f196
|
[
"Apache-2.0"
] |
permissive
|
sxrsdk/sxrsdk
|
a14b9b780f5b66fe66439957cff872c39c500176
|
a0b94e61201213ef68e33c5ec3de4e14da61ea45
|
refs/heads/master
| 2020-03-31T14:35:37.345354
| 2020-02-28T18:44:34
| 2020-02-28T18:44:34
| 152,301,610
| 17
| 19
|
Apache-2.0
| 2020-02-28T18:43:54
| 2018-10-09T18:31:52
|
C++
|
UTF-8
|
C++
| false
| false
| 1,634
|
h
|
vk_cubemap_image.h
|
/* Copyright 2015 Samsung Electronics Co., LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FRAMEWORK_VK_CUBEMAP_IMAGE_H
#define FRAMEWORK_VK_CUBEMAP_IMAGE_H
#include <vector>
#include "objects/textures/cubemap_image.h"
#include "vulkan_headers.h"
#include "vulkan/vulkan_image.h"
namespace sxr {
class VkCubemapImage : public vkImageBase, public CubemapImage
{
public:
explicit VkCubemapImage(int format);
virtual ~VkCubemapImage() {}
virtual int getId() { return 1; }
virtual void texParamsChanged(const TextureParameters&) { }
virtual bool isReady()
{
return checkForUpdate(true);
}
protected:
virtual void update(int texid);
private:
VkCubemapImage(const VkCubemapImage&) = delete;
VkCubemapImage(VkCubemapImage&&) = delete;
VkCubemapImage& operator=(const VkCubemapImage&) = delete;
VkCubemapImage& operator=(VkCubemapImage&&) = delete;
void updateFromBitmap(int texid);
void updateFromMemory(int texid);
};
}
#endif //FRAMEWORK_VK_CUBEMAP_IMAGE_H
|
0da1c115d1b8de1067a5d2f0795631c695761fb3
|
f5f5a0b8a4726f4f97abbf49c4a9abc44d900da9
|
/Codeforces/yet-another-dividing-into-teams.cpp
|
6fa20ad60a52a49a28a448c89b9135c209f13650
|
[] |
no_license
|
tapixhx/CPP
|
c96b87019000057096c2d33f5a2366c496cb6ed3
|
7271870738c75ef92c3fdb7aa019e78fbe1b5bfc
|
refs/heads/main
| 2023-08-22T09:44:28.956406
| 2021-09-15T17:37:24
| 2021-09-15T17:37:24
| 334,462,809
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,093
|
cpp
|
yet-another-dividing-into-teams.cpp
|
//#include <bits/stdc++.h>
//
//#define ll long long int
//#define mod 1000000007
//#define pi 3.141592653589793238
//#define lcm(a,b) (a/(__gcd(a,b)))*b
//#define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout<<fixed;cout.precision(10);
//
//using namespace std;
//
//int main() {
// FASTIO
// int q;
// cin >> q;
// while(q--) {
// int n, flag=0;
// cin >> n;
// vector<int> a(n);
// for(int i=0; i<n; i++)
// cin >> a[i];
// if(n==1)
// cout << 1 << "\n";
// else {
// for(int i=0; i<n-1; i++) {
// for(int j=i+1; j<n; j++) {
// if(abs(a[i]-a[j]) == 1) {
// flag=1;
// break;
// }
// }
// if(flag == 1)
// break;
// }
// if(flag == 1)
// cout << 2 << "\n";
// else
// cout << 1 << "\n";
// }
// }
// return 0;
//}
|
db1a44bfb577b4b135c712736766d24fc055ed45
|
75996c1510676b11af64db7f0eda7e11bc145058
|
/old/src/Roidar.cpp
|
8b8f87821286d939888e253249b5fb02a2e8ac56
|
[
"MIT"
] |
permissive
|
codygriffin/roidrage
|
be76a358d4124c76f2b744973320402c9d4f33b6
|
724d66d95f8705f207d50a0cb9a03675eceb1da2
|
refs/heads/master
| 2021-01-01T20:00:09.473456
| 2014-09-20T06:07:47
| 2014-09-20T06:07:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,443
|
cpp
|
Roidar.cpp
|
//------------------------------------------------------------------------------
//
// Copyright (C) 2013 Cody Griffin (cody.m.griffin@gmail.com)
//
//------------------------------------------------------------------------------
#include "Roidar.h"
#include "RoidRage.h"
#include "OrthoCamera.h"
#include "Program.h"
#include "VertexBufferObject.h"
#include "Systems.h"
#include "Params.h"
//------------------------------------------------------------------------------
using namespace roidrage;
//------------------------------------------------------------------------------
Roidar::Roidar()
{
getRenderPass().pProgram = pRoidRage->pOverlayProgram.get();
getRenderPass().pVbo.push_back(pRoidRage->pOverlayVbo.get());
}
//------------------------------------------------------------------------------
void
Roidar::preRender(OrthoCamera* pCam)
{
getRenderPass().color = glm::vec4(0.5f, 0.5f, 0.2f, 0.2f);
getRenderPass().pProgram->use();
getRenderPass().projectionMatrix = glm::ortho(
-(float)pRoidRage->width/2,
(float)pRoidRage->width/2,
(float)pRoidRage->height/2,
-(float)pRoidRage->height/2,
-1.0f, 1.0f);
getRenderPass().pProgram->uniform ("mModel", getRenderPass().modelMatrix);
getRenderPass().pProgram->uniform ("mOrtho", getRenderPass().projectionMatrix);
getRenderPass().pProgram->uniform ("vColor", getRenderPass().color);
getRenderPass().pProgram->attribute("vPosition", *getRenderPass().pVbo[0], 2, 0, 0);
}
//------------------------------------------------------------------------------
void Roidar::onRender(OrthoCamera* pCam) {
for (int i = 0; i < 12; i++) {
getRenderPass().modelMatrix = glm::scale(
glm::rotate(
glm::translate(
glm::mat4(),
glm::vec3(0.0f, 0.0f, 0.0f)
),
30.0f * -i,
glm::vec3(0.0f, 0.0f, 1.0f)
),
glm::vec3(pRoidRage->radar[i], pRoidRage->radar[i], 1.0f)
);
getRenderPass().pProgram->uniform ("mModel", getRenderPass().modelMatrix);
getRenderPass().pProgram->execute (0, 6);
}
};
//------------------------------------------------------------------------------
|
41b8f9c73f66540b19f034e75b099fc7f2b501d5
|
a827ee72645ffb355e52a0521a1ffe09ec75729e
|
/reg.h
|
001f6af9cef82f1b9096130b92e67b9b9fb51544
|
[] |
no_license
|
lutyyy/2017CMP
|
6f200f3cc85abe95f58a25adbce0b7729d17eb18
|
5abbf8d2623eaace940ef1a4d6d003a2887f51da
|
refs/heads/master
| 2021-06-17T00:53:01.998864
| 2017-06-04T09:39:51
| 2017-06-04T09:39:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 314
|
h
|
reg.h
|
#ifndef __REG_H__
#define __REG_H__
#include <iostream>
using namespace std ;
// register file
class Register{
protected:
int reg[32] ;
int pc, Hi, Lo;
ostream *os ;
// reference of sp
int &sp() ;
public:
// constructor
Register( ostream *os ) ;
// dump regs
void dump( int cycle ) ;
} ;
#endif
|
16cb5a70b62eb4ec575b73b31b74fed15443acae
|
3ac761e3aaf17aa7f3e2b8652662601e0096fb26
|
/LodeRunner/cEnemy.cpp
|
a5415de33b4837717774d78d5e1f3c07c058a5de
|
[] |
no_license
|
MichaelRussel/WaitressinDistress
|
e87808c896cd6886824856cc229f28e9c40748bd
|
fdfb7f8278d6de3f3c66b4d24bff09df88940587
|
refs/heads/master
| 2020-08-11T00:56:28.416214
| 2019-10-11T14:25:14
| 2019-10-11T14:25:14
| 214,457,092
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 389
|
cpp
|
cEnemy.cpp
|
#include "cEnemy.h"
cEnemy::cEnemy()
{
}
cEnemy::~cEnemy()
{
}
void cEnemy::Render()
{
}
void cEnemy::Init()
{
}
void cEnemy::Update(float tpf = 0.0333)
{
}
void cEnemy::ReadKeyboard(unsigned char key, int x, int y, bool press)
{
}
void cEnemy::ReadSpecialKeyboard(unsigned char key, int x, int y, bool press)
{
}
void cEnemy::ReadMouse(int button, int state, int x, int y)
{
}
|
6cd475b87fd01bddc38e04b9962d9d3d39519c6d
|
004270fb4ba9c46541723981af0304d323c28493
|
/Matemática ++/Pintar um tanque.cpp
|
853e2e3fe45ce2c865504033e94a3828443de0b3
|
[] |
no_license
|
enieber/Tools-student
|
ea7c203cd11a58db13561d1e58fa3e5cde68dedb
|
41e6c18564a2bdd5962c2b215c348b0b6d3f352d
|
refs/heads/master
| 2021-01-15T18:08:59.885036
| 2015-07-05T00:51:43
| 2015-07-05T00:51:43
| 38,544,641
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 516
|
cpp
|
Pintar um tanque.cpp
|
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
float nc,nq,area,litro;
float a,r,base;
cout<<"Digite o do raio:";
cin>>r;
cout<<"Digite a altura do tanque:";
cin>>a;
area=(3.14*(r*r))+(2*3.14*r*a);
litro=area/3;
nq=litro/5;
nc=nq*50.00;
cout<<"O custo da Pintura eh "<<nc<<"\n e a quantidade de latas de tintas eh "<<nq;
system("PAUSE>>null");
return EXIT_SUCCESS;
}
|
5e052d87ae7eb884762c83dbecb9ff14511a1227
|
dc568b92ce7a5ec226191f3a14893798e1303359
|
/XWCWallet/control/qrcodedialog.h
|
609ad6536bcd4edccb42f9f435530e82199e6971
|
[
"MIT"
] |
permissive
|
Whitecoin-XWC/Whitecoin-qt
|
38ca7959045306a09d56f03b0637138363774e44
|
7794a0057b63d004dd74ce68dba1a13e4b768502
|
refs/heads/develop
| 2022-12-07T11:58:51.733154
| 2022-11-22T05:53:42
| 2022-11-22T05:53:42
| 202,651,142
| 4
| 2
| null | 2021-07-07T14:10:23
| 2019-08-16T03:21:59
|
C++
|
UTF-8
|
C++
| false
| false
| 339
|
h
|
qrcodedialog.h
|
#ifndef QRCODEDIALOG_H
#define QRCODEDIALOG_H
#include <QDialog>
namespace Ui {
class QRCodeDialog;
}
class QRCodeDialog : public QDialog
{
Q_OBJECT
public:
explicit QRCodeDialog( QString address, QWidget *parent = 0);
~QRCodeDialog();
private:
Ui::QRCodeDialog *ui;
};
#endif // QRCODEDIALOG_H
|
010e6b0ca0ad53b8d55679943061172a0063cd03
|
f85b50ac273f1dfc92a99f429bec36505424588a
|
/Leetcode414.cpp
|
a58943e368b60f35a990e0590f3d6d8faf23bab2
|
[] |
no_license
|
THWANG-design/LEETCODE
|
decdae24188e6ec2fba991b9ae0a9906b7680b4b
|
cd762d3c3f08aa71ebc2f33a67ac3f6bcdcbb79f
|
refs/heads/master
| 2023-03-11T19:08:55.437277
| 2021-03-02T02:03:12
| 2021-03-02T02:03:12
| 343,290,092
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 723
|
cpp
|
Leetcode414.cpp
|
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution
{
public:
int thirdmax(vector<int>& nums)
{
int i, j;
for (i = 0; i < (nums.size() - 1); i++)
{
for (j = i + 1; j < nums.size(); j++)
{
if (nums[j] == nums[i])
nums[j] = INT_MAX;
}
}
nums.erase(remove(nums.begin(), nums.end(), INT_MAX), nums.end());
sort(nums.begin(), nums.end(), greater<int>());
if (nums.size() < 3)
return nums[0];
else return nums[2];
}
};
int main()
{
int i;
vector<int>example;
int arrary[] = { 1, 2};
for (i = 0; i < sizeof(arrary) / sizeof(int); i++)
example.push_back(arrary[i]);
Solution solution;
cout << solution.thirdmax(example) << endl;
return 0;
}
|
ed83573ae5dac57d8f9ba23d2b21b5396564ef8c
|
8da14e3c844502b0e896116547c7a805ec7448a2
|
/compress/client/client.h
|
38a36d3866af78f9e97ba9860bee23abf6157793
|
[] |
no_license
|
odindsp/old_dspads
|
a9bf7acdf10bd305176cc64f6170de717bfc2b1a
|
769bc93e9b2ce38587fc4c8095f76f0667e90776
|
refs/heads/master
| 2021-09-15T11:23:15.974170
| 2018-03-09T10:28:53
| 2018-03-09T10:28:53
| 124,525,754
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 711
|
h
|
client.h
|
#ifndef _CLIENT_H_
#define _CLIENT_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>
#include <dirent.h>
#include <libgen.h>
#include <string>
#include <vector>
#include <iostream>
#include <map>
#include "zlib.h"
#include "../common/common.h"
#include "../common/writelog.h"
#include "../common/confoperation.h"
using namespace std;
#define GZ_UNSENT 0
#define GZ_GZ 1
#define GZ_SENDING 2
#define GZ_INTERRUPT 3
#define GZ_SENT 4
#endif
|
dff30d96a4ca817087bf144b00bdcf8021cf07ea
|
5dffd8553b8c907b5e7a0904f8e772b931c15861
|
/solved/2383_Lunch_time.cpp
|
54054689fdcea20e6fd3d99d21492ae12dc9ab9f
|
[] |
no_license
|
Kyejoon-Lee/SWEA
|
36ae59ab486b8048815cbb07066820b53981c4da
|
2415cab2237d41ca939764b48b8782761d9586f1
|
refs/heads/master
| 2020-05-26T09:45:00.429162
| 2019-06-17T08:49:53
| 2019-06-17T08:49:53
| 188,192,410
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,990
|
cpp
|
2383_Lunch_time.cpp
|
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<list>
#include<cmath>
#include<algorithm>
using namespace std;
list<int>s1;
list<int>s2;
int room[11][11];
int people[11][2];
int stair[2][3];
int mini = 0;
int n, p, s;
int boom(list<int> q, int len) {
int time;
q.sort();
if (q.size() == 0) {
time = 0;
}
else if (q.size() <= 3) {
time = q.back() + len;
}
else {
int arrival;
int end;
list<int>endtime;
for (int i = 0; i < 3; i++) {
arrival = q.front();
q.pop_front();
endtime.push_back(arrival + len);
}
int size = (int)q.size();
for (int i = 0; i < size; i++) {
arrival = q.front();
q.pop_front();
end = endtime.front();
endtime.pop_front();
if (arrival < end) {
endtime.push_back(end + len);
}
else {
endtime.push_back(arrival + len);
}
}
time = endtime.back();
}
return time;
}
void dfs(int num, int select) {
if (select == 0) {
int dist = abs(people[num][0] - stair[0][0]) + abs(people[num][1] - stair[0][1]) + 1;
s1.push_back(dist);
}
else if (select == 1) {
int dist = abs(people[num][0] - stair[1][0]) + abs(people[num][1] - stair[1][1]) + 1;
s2.push_back(dist);
}
if (num == p - 1) {
int st1 = boom(s1, stair[0][2]);
int st2 = boom(s2, stair[1][2]);
mini = mini < max(st1, st2) ? mini : max(st1, st2);
return;
}
dfs(num + 1, 0);
s1.pop_back();
dfs(num + 1, 1);
s2.pop_back();
}
int main() {
int i, j, num, set;
scanf("%d", &set);
for (num = 1; num <= set; num++) {
scanf("%d", &n);
p = 0;
s = 0;
s1.clear();
s2.clear();
mini = 999999;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &room[i][j]);
if (room[i][j] == 1) {
people[p][0] = j;
people[p++][1] = i;
}
else if (room[i][j] >= 2) {
stair[s][0] = j;
stair[s][1] = i;
stair[s++][2] = room[i][j];
}
}
}
dfs(0, 0);
s1.pop_back();
dfs(0, 1);
s2.pop_back();
printf("#%d %d\n", num, mini);
}
return 0;
}
|
740e14c0faf1655556b4427ee8c82a1cbc837be5
|
313cdc3bd63a9d7f1a358758315f75bfe697720e
|
/Circuits/make-mand.cpp
|
190697ea1502f8ac89d8e2a31a3345a36d27d574
|
[
"BSD-2-Clause"
] |
permissive
|
KULeuven-COSIC/SCALE-MAMBA
|
1abf9151940b77e7d8919443fa5ca5cbb137b638
|
c111516e3ebc1efd12a2bd47dd2122b160e13d1e
|
refs/heads/master
| 2022-08-20T07:15:37.749282
| 2022-03-30T06:57:03
| 2022-03-30T06:57:03
| 131,836,493
| 241
| 102
|
NOASSERTION
| 2023-09-06T08:24:55
| 2018-05-02T10:40:57
|
Verilog
|
UTF-8
|
C++
| false
| false
| 1,135
|
cpp
|
make-mand.cpp
|
/*
Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom.
Copyright (c) 2021, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium.
All rights reserved
*/
#include "GC/SimplifyCircuit.h"
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, const char *argv[])
{
if (argc != 2)
{
cout << "Call using\n\tmake-mad.x file\nto convert \n\tBristol/file.txt\nto include MADD gates\n";
exit(1);
}
string input_file_name= argv[1], output_file_name= argv[1];
input_file_name= "Bristol/" + input_file_name + ".txt";
output_file_name= "MAND-Circuits/" + output_file_name + ".txt";
cout << "Input : " << input_file_name << endl;
cout << "Output : " << output_file_name << endl;
Circuit C;
ifstream inpf(input_file_name.c_str());
if (inpf.fail())
{
throw file_error(input_file_name);
}
inpf >> C;
inpf.close();
C.merge_AND_gates();
ofstream outf(output_file_name.c_str());
outf << C << endl;
outf.close();
cout << "All done" << endl;
}
|
14782a9a04d8f66f68de1dbb85ec4afb472e6171
|
9a57a696f1f64636efc9bac5f6c4e6efbf667635
|
/actor/sensors/coordinate/types.hpp
|
d12737e216490fad7a35f21b6cf67802e83b2492
|
[] |
no_license
|
Constant1355/knit
|
0684244960269b1c476c0578c109a41d29763ae0
|
deb095cfec5fb2a5330c31f3e0dbb14a7ed6ef99
|
refs/heads/master
| 2023-08-13T21:28:25.130833
| 2021-09-13T16:10:13
| 2021-09-13T16:10:13
| 398,517,174
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,020
|
hpp
|
types.hpp
|
#pragma once
#if __INTELLISENSE__
#undef __ARM_NEON
#undef __ARM_NEON__
#endif
#include <iostream>
#include <vector>
#include <memory>
#include <Eigen/Dense>
#include "../../source/stm32/spi.hpp"
namespace knit
{
namespace actor
{
namespace sensor
{
namespace coordinate
{
using source::stm32::SPIMessagePtr;
struct IMUData
{
double timestamp;
float temperature;
Eigen::Vector3f acc; //m/s2
Eigen::Vector3f gyro; //rad/s
uint32_t count_inter;
uint32_t count_task;
};
using IMUDataPtr = std::shared_ptr<IMUData>;
struct MagnetData
{
double timestamp;
Eigen::Vector3f value; //uT
};
using MagnetDataPtr = std::shared_ptr<MagnetData>;
}
}
}
}
|
1409119b150bcd6f2b7138ed7dc4e15571cbef70
|
551f53b107dc566529e9e551171712e907447528
|
/src/brdfviz/embree/rtccommonshader.cpp
|
6d1a2d12721fe3997f050757fd2f33abb6641fb1
|
[] |
no_license
|
SacrificeGhuleh/brdf_visualizer_cpp
|
e1049f85820b3d1f782424349dea9a8e2eadbd7a
|
dfa723b11c9b2c266abce8879ccbd0d2653656e8
|
refs/heads/master
| 2023-07-07T11:58:14.254087
| 2021-04-29T16:52:33
| 2021-04-29T16:52:33
| 286,674,581
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 29,171
|
cpp
|
rtccommonshader.cpp
|
/*
* This is a personal academic project. Dear PVS-Studio, please check it.
* PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
*/
#include <pch.h>
#include "rtccommonshader.h"
#include "mathscene.h"
#include "sphere.h"
#include "rtcamera.h"
#include "rtlight.h"
#include "gl/material.h"
#include "common/utils/math.h"
#include "common/utils/rng.h"
glm::vec4 RTCCommonShader::traceRay(const RTCRayHitIor &rayHit, int depth) {
if (rayHit.hit.geomID == RTC_INVALID_GEOMETRY_ID) {
return getBackgroundColor(rayHit);
}
glm::vec3 resultColor(0, 0, 0);
if (depth <= 0) {
//return from recursion, alpha 0 because division by alpha
return glm::vec4(resultColor, 0.0f);
}
glm::vec3 normal;
// and texture coordinates
glm::vec2 tex_coord;
//Acquire material from hit object
std::shared_ptr<Material> material = nullptr;
if (rayHit.hit.geomID == RTC_COMPUTE_GEOMETRY_ID) {
resultColor = glm::vec3(1.f, 0.f, 0.5f);
normal = mathScene_->getNormal(rayHit);
material = mathScene_->getMaterial(rayHit);
//return glm::vec4(normal, 1);
} else if (rayHit.hit.geomID != RTC_INVALID_GEOMETRY_ID) {
RTCGeometry geometry = rtcGetGeometry(rtcScene_, rayHit.hit.geomID);
// get interpolated normal
normal = glm::normalize(getNormal(geometry, rayHit));
// and texture coordinates
tex_coord = getTexCoords(geometry, rayHit);
//Acquire material from hit object
material = *static_cast<std::shared_ptr<Material> *>(rtcGetGeometryUserData(geometry));
} else {
spdlog::error("[RTC COMMON SHADER] Invalid geometry hit");
return glm::vec4(0, 1, 1, 1);
}
/*
* Common for all shaders
* */
const glm::vec3 origin(rayHit.ray.org_x, rayHit.ray.org_y, rayHit.ray.org_z);
// const glm::vec3 direction(rayHit.ray.dir_x, rayHit.ray.dir_y, rayHit.ray.dir_z);
const glm::vec3 direction = glm::normalize(glm::vec3(rayHit.ray.dir_x, rayHit.ray.dir_y, rayHit.ray.dir_z));
const glm::vec3 worldPos = origin + direction * rayHit.ray.tfar;
const glm::vec3 directionToCamera = -direction;
const glm::vec3 lightPos = light_->getPosition();
const glm::vec3 lightDir = glm::normalize(light_->getPosition() - worldPos);
glm::vec3 shaderNormal = normal;
float dotNormalCamera = glm::dot(shaderNormal, directionToCamera);
//Flip normal if invalid
// if (correctNormals_) {
// if (dotNormalCamera < 0) {
// shaderNormal *= -1.f;
// dotNormalCamera *= -1.f;
// dotNormalCamera = glm::dot(shaderNormal, directionToCamera);
// }
// assert(dotNormalCamera >= 0);
// }
/*
* End of common for all shaders
* */
// const RTCShadingType selectedShader = (useShader == RTCShadingType::None) ? material->shadingType : useShader;
const RTCShadingType selectedShader = useShader;
switch (selectedShader) {
case RTCShadingType::Glass: {
resultColor = traceMaterial<RTCShadingType::Glass>(rayHit, material, tex_coord, origin, direction, worldPos,
directionToCamera, lightPos, lightDir, shaderNormal,
dotNormalCamera, depth);
break;
}
case RTCShadingType::Mirror: {
resultColor = traceMaterial<RTCShadingType::Mirror>(rayHit, material, tex_coord, origin, direction, worldPos,
directionToCamera, lightPos, lightDir, shaderNormal,
dotNormalCamera, depth);
break;
}
case RTCShadingType::PathTracing: {
resultColor = traceMaterial<RTCShadingType::PathTracing>(rayHit, material, tex_coord, origin, direction, worldPos,
directionToCamera, lightPos, lightDir, shaderNormal,
dotNormalCamera, depth);
break;
}
case RTCShadingType::Normals: {
resultColor = traceMaterial<RTCShadingType::Normals>(rayHit, material, tex_coord, origin, direction, worldPos,
directionToCamera, lightPos, lightDir, shaderNormal,
dotNormalCamera, depth);
break;
};
case RTCShadingType::TexCoords: {
resultColor = traceMaterial<RTCShadingType::TexCoords>(rayHit, material, tex_coord, origin, direction, worldPos,
directionToCamera, lightPos, lightDir, shaderNormal,
dotNormalCamera, depth);
break;
};
default:
case RTCShadingType::None: {
resultColor = traceMaterial<RTCShadingType::None>(rayHit, material, tex_coord, origin, direction, worldPos,
directionToCamera, lightPos, lightDir, shaderNormal,
dotNormalCamera, depth);
break;
};
}
return glm::vec4(resultColor, 1.0f);
}
template<RTCShadingType T>
glm::vec4 RTCCommonShader::traceMaterial(const RTCRayHitIor &rayHit,
const std::shared_ptr<Material> &material,
const glm::vec2 &tex_coord,
const glm::vec3 &origin,
const glm::vec3 &direction,
const glm::vec3 &worldPos,
const glm::vec3 &directionToCamera,
const glm::vec3 &lightPos,
const glm::vec3 &lightDir,
const glm::vec3 &shaderNormal,
const float dotNormalCamera,
const int depth) {
spdlog::error("[RTC COMMON SHADER] Warning, no material");
return glm::vec4(1, 0, 1, 1);
}
float
RTCCommonShader::getPhongBRDF(const glm::vec3 &toLight, const glm::vec3 &toCamera, const glm::vec3 &normal, const std::shared_ptr<BRDFShader> &brdfShaderPtr) {
using Phong = BRDFShader::PhongUniformLocationsPack;
glm::vec3 reflectVector = reflect(-toLight, normal);
float specVal = std::pow(std::max(dot(toCamera, reflectVector), 0.0f), brdfShaderPtr->getBrdfUniformLocations().Phong::shininess.getData());
return specVal;
}
float RTCCommonShader::getBlinnPhongBRDF(const glm::vec3 &toLight, const glm::vec3 &toCamera, const glm::vec3 &normal,
const std::shared_ptr<BRDFShader> &brdfShaderPtr) {
using Phong = BRDFShader::PhongUniformLocationsPack;
glm::vec3 halfVector = normalize(toLight + toCamera);
float specVal = std::pow(std::max(glm::dot(normal, halfVector), 0.0f), brdfShaderPtr->getBrdfUniformLocations().Phong::shininess.getData());
return specVal;
}
float RTCCommonShader::beckmannDistribution(float roughness, float normDotHalf) {
float roughness2 = roughness * roughness;
float normDotHalf2 = normDotHalf * normDotHalf;
float normDotHalf4 = normDotHalf2 * normDotHalf2;
return std::exp((normDotHalf2 - 1) / (roughness2 * normDotHalf2)) / (roughness2 * normDotHalf2);
}
// https://en.wikipedia.org/wiki/Schlick%27s_approximation
float RTCCommonShader::schlick(float r0, float cosTheta) {
return r0 + (1.f - r0) * std::pow(1.f - cosTheta, 5.f);
}
float RTCCommonShader::geometricAttenuation(const glm::vec3 &toLight, const glm::vec3 &toCamera, const glm::vec3 &normal) {
glm::vec3 halfVector = normalize(toLight + toCamera);
float normDotHalf = dot(normal, halfVector);
float toCamDotHalf = dot(toCamera, halfVector);
float normDotToCamera = dot(normal, toCamera);
float normDotToLight = dot(normal, toLight);
float res1 = (2.f * normDotHalf * normDotToCamera) / toCamDotHalf;
float res2 = (2.f * normDotHalf * normDotToLight) / toCamDotHalf;
float res = std::min(1.f, std::min(res1, res2));
return res;
}
float RTCCommonShader::getTorranceSparrowBRDF(const glm::vec3 &toLight, const glm::vec3 &toCamera, const glm::vec3 &normal,
const std::shared_ptr<BRDFShader> &brdfShaderPtr) {
using TorranceSparrow = BRDFShader::TorranceSparrowUniformLocationsPack;
glm::vec3 halfVector = normalize(toLight + toCamera);
float normDotHalf = dot(normal, halfVector);
float toCamDotHalf = dot(toCamera, halfVector);
float normDotToLight = dot(normal, toLight);
float normDotToCamera = dot(normal, toLight);
float D = beckmannDistribution(brdfShaderPtr->getBrdfUniformLocations().TorranceSparrow::roughness.getData(), normDotHalf);
float F = schlick(brdfShaderPtr->getBrdfUniformLocations().TorranceSparrow::f0.getData(), toCamDotHalf);
float G = geometricAttenuation(toLight, toCamera, normal);
// float specVal = D * F * G;
float specVal = (F / M_PI) * (D / normDotToLight) * (G / normDotToCamera);
return specVal;
}
float RTCCommonShader::getCookTorranceBRDF(const glm::vec3 &toLight, const glm::vec3 &toCamera, const glm::vec3 &normal,
const std::shared_ptr<BRDFShader> &brdfShaderPtr) {
using CookTorrance = BRDFShader::TorranceSparrowUniformLocationsPack; // Cook Torrance and Torrance Sparrow share parameters
glm::vec3 halfVector = normalize(toLight + toCamera);
float normDotHalf = dot(normal, halfVector);
float toCamDotHalf = dot(toCamera, halfVector);
float normDotToLight = dot(normal, toLight);
float normDotToCamera = dot(normal, toLight);
float D = beckmannDistribution(brdfShaderPtr->getBrdfUniformLocations().CookTorrance::roughness.getData(), normDotHalf);
float F = schlick(brdfShaderPtr->getBrdfUniformLocations().CookTorrance::f0.getData(), toCamDotHalf);
float G = geometricAttenuation(toLight, toCamera, normal);
// float specVal = D * F * G;
float specVal = /*kd / M_PI*/ +(/*ks **/ D * F * G) / (4 * M_PI * normDotToLight);
return specVal;
}
float RTCCommonShader::getBRDF(const glm::vec3 &toLight, const glm::vec3 &toCamera, const glm::vec3 &normal) {
if (auto brdfShaderPtr = brdfShader.lock()) {
switch (brdfShaderPtr->currentBrdfIdx) {
case BRDFShader::BRDF::Phong:return getPhongBRDF(toLight, toCamera, normal, brdfShaderPtr);
case BRDFShader::BRDF::BlinnPhong:return getBlinnPhongBRDF(toLight, toCamera, normal, brdfShaderPtr);
case BRDFShader::BRDF::PhongPhysCorrect:return getPhysicallyCorrectPhongBRDF(toLight, toCamera, normal, brdfShaderPtr);
case BRDFShader::BRDF::Lambert:return getLambertBRDF(toLight, toCamera, normal, brdfShaderPtr);
case BRDFShader::BRDF::TorranceSparrow:return getTorranceSparrowBRDF(toLight, toCamera, normal, brdfShaderPtr);
case BRDFShader::BRDF::CookTorrance:return getCookTorranceBRDF(toLight, toCamera, normal, brdfShaderPtr);
case BRDFShader::BRDF::OrenNayar:return getOrenNayarBRDF(toLight, toCamera, normal, brdfShaderPtr);
default: {
spdlog::warn("[COMMON SHADER] invalid BRDF selected");
return 0;
}
}
} else {
spdlog::warn("[COMMON SHADER] cannot cock brdf shader");
return 0;
}
}
float RTCCommonShader::getLambertBRDF(const glm::vec3 &toLight, const glm::vec3 &toCamera, const glm::vec3 &normal,
const std::shared_ptr<BRDFShader> &brdfShaderPtr) {
using Lambert = BRDFShader::LambertUniformLocationsPack;
return brdfShaderPtr->getBrdfUniformLocations().Lambert::reflectance.getData() / M_PI;
}
float RTCCommonShader::getOrenNayarBRDF(const glm::vec3 &toLight, const glm::vec3 &toCamera, const glm::vec3 &normal,
const std::shared_ptr<BRDFShader> &brdfShaderPtr) {
using OrenNayar = BRDFShader::OrenNayarUniformLocationsPack;
float toCamDotNormal = dot(toCamera, normal);
float toLightDotNormal = dot(toLight, normal);
float rough2 =
brdfShaderPtr->getBrdfUniformLocations().OrenNayar::roughness.getData() * brdfShaderPtr->getBrdfUniformLocations().OrenNayar::roughness.getData();
float cosPhiri = dot(normalize(toCamera - normal * toCamDotNormal), normalize(toLight - normal * toLightDotNormal));
float thetaI = acos(toLightDotNormal);
float thetaO = acos(toCamDotNormal);
float alpha = std::max(thetaI, thetaO);
float beta = std::min(thetaI, thetaO);
float C1 = 1. - 0.5 * (rough2 / (rough2 + 0.33));
float C2;
if (cosPhiri >= 0) {
C2 = 0.45 * (rough2 / (rough2 + 0.09)) * sin(alpha);
} else {
C2 = 0.45 * (rough2 / (rough2 + 0.09)) * (sin(alpha) - pow(((2 * beta) / M_PI), 3));
}
float C3 = 0.125 * (rough2 / (rough2 + 0.09)) * ((4 * alpha * beta) / M_PI2);
float L1r = (brdfShaderPtr->getBrdfUniformLocations().OrenNayar::reflectance.getData() / M_PI) *
(C1 + cosPhiri * C2 * tan(beta) + (1. - abs(cosPhiri)) * C3 * tan((alpha + beta) / 2.));
float L2r = 0.17 * ((brdfShaderPtr->getBrdfUniformLocations().OrenNayar::reflectance.getData() *
brdfShaderPtr->getBrdfUniformLocations().OrenNayar::reflectance.getData()) / M_PI) * (rough2 / (rough2 + 0.09)) *
pow(((4 * alpha * beta) / M_PI2), 2);
return L1r + L2r;
}
float RTCCommonShader::getMirrorBRDF(const glm::vec3 &toLight, const glm::vec3 &toCamera, const glm::vec3 &normal,
const std::shared_ptr<BRDFShader> &brdfShaderPtr) {
glm::vec3 reflectVector = glm::reflect(-toCamera, normal);
if (toLight == toCamera)
return std::numeric_limits<float>::infinity();
else
return 0;
}
float RTCCommonShader::getPhysicallyCorrectPhongBRDF(const glm::vec3 &toLight, const glm::vec3 &toCamera, const glm::vec3 &normal,
const std::shared_ptr<BRDFShader> &brdfShaderPtr) {
using Phong = BRDFShader::PhongUniformLocationsPack;
glm::vec3 reflectVector = glm::reflect(-toLight, normal);
float specVal = std::pow(std::max(glm::dot(toCamera, reflectVector), 0.0f), brdfShaderPtr->getBrdfUniformLocations().Phong::shininess.getData());
// return (u_phongDiffuse / M_PI) + (((u_phongSpecular * (u_phongShininess + 2)) / M_2PI) * pow(max(dot(toCamera, reflectVector), 0.0), u_phongShininess));
return (brdfShaderPtr->getBrdfUniformLocations().Phong::diffuse.getData() / M_PI) +
(((brdfShaderPtr->getBrdfUniformLocations().Phong::specular.getData() * (brdfShaderPtr->getBrdfUniformLocations().Phong::shininess.getData() + 2)) /
M_2PI) * specVal);
}
template<>
glm::vec4 RTCCommonShader::traceMaterial<RTCShadingType::None>(const RTCRayHitIor &rayHit,
const std::shared_ptr<Material> &material,
const glm::vec2 &tex_coord,
const glm::vec3 &origin,
const glm::vec3 &direction,
const glm::vec3 &worldPos,
const glm::vec3 &directionToCamera,
const glm::vec3 &lightPos,
const glm::vec3 &lightDir,
const glm::vec3 &shaderNormal,
const float dotNormalCamera,
const int depth) {
return glm::vec4(colorToGlm(material->diffuse_), 1);
// return glm::vec4(1.f, 0.f, 0.f, 1.f);
}
template<>
glm::vec4 RTCCommonShader::traceMaterial<RTCShadingType::Glass>(const RTCRayHitIor &rayHit,
const std::shared_ptr<Material> &material,
const glm::vec2 &tex_coord,
const glm::vec3 &origin,
const glm::vec3 &direction,
const glm::vec3 &worldPos,
const glm::vec3 &directionToCamera,
const glm::vec3 &lightPos,
const glm::vec3 &lightDir,
const glm::vec3 &shaderNormal,
const float dotNormalCamera,
const int depth) {
float materialIor;
// if (useShader == RTCShadingType::Glass) {
// materialIor = ior;
// } else {
assert(material->ior >= 0);
materialIor = material->ior;
// }
if (depth <= 0) {
return getBackgroundColor(rayHit);
}
glm::vec4 reflected(0.f, 0.f, 0.f, 1.f);
glm::vec4 refracted(0.f, 0.f, 0.f, 1.f);
//n1 = ray ior
//n2 = material ior
//if n1 != vzduch than n2 = air
float n1 = rayHit.ior;
float n2 = materialIor;
if (n1 != IOR_AIR) {
n2 = IOR_AIR;
}
assert(n1 >= 0);
assert(n2 >= 0);
//0.64 1.54
const float n1overn2 = (n1 / n2);
//cos1
float Q1 = dotNormalCamera;
assert(Q1 >= 0);
const glm::vec3 reflectDir = glm::normalize(
(2.f * (directionToCamera * shaderNormal)) * shaderNormal - directionToCamera);
RTCRayHitIor reflectedRayHit = generateRay(worldPos, reflectDir, tNear_);
reflectedRayHit.ior = n2;
const float tmp = 1.f - sqr(n1overn2) * (1.f - sqr(Q1));
if (tmp < 0.f) {
return traceRay(reflectedRayHit, depth - 1);
}
//cos2
const float Q2 = sqrtf(tmp);
const glm::vec3 refractedDir = glm::normalize(
(n1overn2 * direction) + ((n1overn2 * Q1 - Q2) * shaderNormal));
// Fresnel
const float R = RTCShader::fresnel(n1, n2, Q1, Q2);
const float coefReflect = R;
const float coefRefract = 1.f - R;
RTCRayHitIor refractedRayHit = generateRay(worldPos, refractedDir, tNear_);
refractedRayHit.ior = n2;
reflected = traceRay(reflectedRayHit, depth - 1);
refracted = traceRay(refractedRayHit, depth - 1);
assert(coefReflect >= 0.f);
assert(coefReflect <= 1.f);
assert(coefRefract >= 0.f);
assert(coefRefract <= 1.f);
//C = [Crefl*R + Crefr*(1-R)] * TbeerLambert
//TbeerLambert = {1,1,1} for air
//TbeerLambert = {e^-Mr*l,e^-Mg*l,e^-Mb*l} for air, l = delka paprsku, M = absorpce materialu
glm::vec3 TBeerLambert;
if (rayHit.ior == IOR_AIR) {
TBeerLambert = {1.f, 1.f, 1.f};
} else {
const float l = rayHit.ray.tfar;
const glm::vec3 M = {10, 0.5, 10};
// const glm::vec3 M = material->absorption;
TBeerLambert = {
expf(-M.r * l),
expf(-M.g * l),
expf(-M.b * l)
};
}
const glm::vec3 finalReflect = coefReflect * glm::vec3(reflected.x, reflected.y, reflected.z);
const glm::vec3 finalRefract = coefRefract * glm::vec3(refracted.x, refracted.y, refracted.z);
return glm::vec4((finalReflect + finalRefract) * TBeerLambert, 1);
// return coefReflect * reflected + coefRefract * refracted * glm::vec4(TBeerLambert, 1.f);
}
template<>
glm::vec4 RTCCommonShader::traceMaterial<RTCShadingType::Mirror>(const RTCRayHitIor &rayHit,
const std::shared_ptr<Material> &material,
const glm::vec2 &tex_coord,
const glm::vec3 &origin,
const glm::vec3 &direction,
const glm::vec3 &worldPos,
const glm::vec3 &directionToCamera,
const glm::vec3 &lightPos,
const glm::vec3 &lightDir,
const glm::vec3 &shaderNormal,
const float dotNormalCamera,
const int depth) {
if (rayHit.hit.geomID == RTC_COMPUTE_GEOMETRY_ID) {
(void) 0; // my breakpint
}
//I - N * dot(N, I) * 2
glm::vec3 reflectDir = glm::reflect(direction, shaderNormal);
glm::vec4 reflected(0.f, 0.f, 0.f, 1.f);
RTCRayHitIor reflectedRayHit = generateRay(worldPos, reflectDir, tNear_);
reflected = traceRay(reflectedRayHit, depth - 1);
return reflected;
}
glm::vec4 RTCCommonShader::sampleBRDF(const glm::vec3 &direction,
const glm::vec3 &shaderNormal,
const glm::vec3 &directionToCamera,
const glm::vec3 &worldPos,
const int depth,
float &pdf) {
const glm::vec3 reflectDir = glm::reflect(direction, shaderNormal);
const glm::vec3 omegaI = pathTracerHelper->getTracesCount() == 0 ? reflectDir : sampler_->sample(shaderNormal, reflectDir, pdf);
const float brdf = getBRDF(omegaI, directionToCamera, shaderNormal);
const RTCRayHitIor rayHitNew = generateRay(worldPos, omegaI);
//
const glm::vec4 li = traceRay(rayHitNew, depth - 1);
glm::vec3 finalColor = li * brdf * glm::dot(shaderNormal, omegaI);
return glm::vec4(finalColor.x, finalColor.y, finalColor.z, 1);
}
glm::vec4 RTCCommonShader::sampleLight(const glm::vec3 &direction,
const glm::vec3 &shaderNormal,
const glm::vec3 &directionToCamera,
const glm::vec3 &worldPos,
const int depth,
float &pdf) {
const glm::vec3 reflectDir = glm::reflect(direction, shaderNormal);
glm::vec3 omegaI = reflectDir;
if (!pathTracerHelper->getTracesCount() == 0)
sphericalMap_->sample(pdf, omegaI);
const float brdf = getBRDF(omegaI, directionToCamera, shaderNormal);
const RTCRayHitIor rayHitNew = generateRay(worldPos, omegaI);
//
const glm::vec4 li = traceRay(rayHitNew, depth - 1);
glm::vec3 finalColor = li * brdf * glm::dot(shaderNormal, omegaI);
return glm::vec4(finalColor.x, finalColor.y, finalColor.z, 1);
}
template<>
glm::vec4 RTCCommonShader::traceMaterial<RTCShadingType::PathTracing>(const RTCRayHitIor &rayHit,
const std::shared_ptr<Material> &material,
const glm::vec2 &tex_coord,
const glm::vec3 &origin,
const glm::vec3 &direction,
const glm::vec3 &worldPos,
const glm::vec3 &directionToCamera,
const glm::vec3 &lightPos,
const glm::vec3 &lightDir,
const glm::vec3 &shaderNormal,
const float dotNormalCamera,
const int depth) {
// return glm::vec4(material->diffuse_.data[0], material->diffuse_.data[1], material->diffuse_.data[2], 1);
const int currentRecursion = recursionDepth_ - depth;
// Russian roulette
float rho = /*(material == nullptr) ?*/ 0.95 /*: (
(std::max<float>(material->diffuse_.data[0], std::max<float>(material->diffuse_.data[1], material->diffuse_.data[2]))) * 0.95f)*/;
if (rho <= rng()) {
return glm::vec4(0, 0, 0, 0);
}
if (brdfShader.lock()->currentBrdfIdx == BRDFShader::BRDF::Mirror) {
return traceMaterial<RTCShadingType::Mirror>(rayHit, material, tex_coord, origin, direction, worldPos,
directionToCamera, lightPos, lightDir, shaderNormal,
dotNormalCamera, depth);
}
const glm::vec3 emmision =
(material == nullptr) ? glm::vec3(0, 0, 0) : glm::vec3{material->emission_.data[0], material->emission_.data[1], material->emission_.data[2]};
float pdf = 1;
const glm::vec3 reflectDir = glm::reflect(direction, shaderNormal);
/*const*/ glm::vec3 omegaI = pathTracerHelper->getTracesCount() == 0 ? reflectDir : sampler_->sample(shaderNormal, reflectDir, pdf);
// if (pdf <= 0) {
// return glm::vec4(0, 0, 0, 0);
// }
switch (samplingType_) {
case Sampling::BRDF: {
const glm::vec4 brdfSample = sampleBRDF(direction, shaderNormal, directionToCamera, worldPos, depth, pdf);
return brdfSample;
}
case Sampling::Lights: {
const glm::vec4 lightSample = sampleLight(direction, shaderNormal, directionToCamera, worldPos, depth, pdf);
return lightSample;
}
case Sampling::MIS: {
const glm::vec4 brdfSample = sampleBRDF(direction, shaderNormal, directionToCamera, worldPos, depth, pdf);
const glm::vec4 lightSample = sampleLight(direction, shaderNormal, directionToCamera, worldPos, depth, pdf);
return brdfSample + lightSample;
}
}
throw std::runtime_error("Invalid sampling type");
// const glm::vec3 lightSample = sphericalMap_->sample(pdf, omegaI);
// const float brdf = getBRDF(omegaI, directionToCamera, shaderNormal);
// const RTCRayHitIor rayHitNew = generateRay(worldPos, omegaI);
////
// const glm::vec4 li = traceRay(rayHitNew, depth - 1);
// glm::vec3 finalColor = li * brdf * glm::dot(shaderNormal, omegaI);
// return glm::vec4(finalColor.x, finalColor.y, finalColor.z, 1);
}
template<>
glm::vec4 RTCCommonShader::traceMaterial<RTCShadingType::Normals>(const RTCRayHitIor &rayHit,
const std::shared_ptr<Material> &material,
const glm::vec2 &tex_coord,
const glm::vec3 &origin,
const glm::vec3 &direction,
const glm::vec3 &worldPos,
const glm::vec3 &directionToCamera,
const glm::vec3 &lightPos,
const glm::vec3 &lightDir,
const glm::vec3 &shaderNormal,
const float dotNormalCamera,
const int depth) {
//Debug dot normal
// return glm::vec4(glm::vec3(dotNormalCamera), 1.0f);
return glm::vec4((shaderNormal.x + 1.f) / 2.f,
(shaderNormal.y + 1.f) / 2.f,
(shaderNormal.z + 1.f) / 2.f,
1.0f);
}
template<>
glm::vec4 RTCCommonShader::traceMaterial<RTCShadingType::TexCoords>(const RTCRayHitIor &rayHit,
const std::shared_ptr<Material> &material,
const glm::vec2 &tex_coord,
const glm::vec3 &origin,
const glm::vec3 &direction,
const glm::vec3 &worldPos,
const glm::vec3 &directionToCamera,
const glm::vec3 &lightPos,
const glm::vec3 &lightDir,
const glm::vec3 &shaderNormal,
const float dotNormalCamera,
const int depth) {
return glm::vec4(tex_coord.x, tex_coord.y, 1.0, 1.0f);
}
|
7a3098a86da2f33cf5aa219f846e83f972b397b4
|
cf4dd4da38c52495c4e692c522714e5cd100e1f3
|
/oop2_week06.cpp
|
b9d9e0b70971127418014b2b2b37b2bce7aa270e
|
[] |
no_license
|
bong-too/oop2-1
|
8e66121b4bf430eb193894d845e14f3d1b3e7383
|
6f4631e1a1a23638911f21f8cf0e5a5659cf2883
|
refs/heads/main
| 2023-02-12T03:44:16.658073
| 2021-01-12T15:16:58
| 2021-01-12T15:16:58
| null | 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 3,633
|
cpp
|
oop2_week06.cpp
|
//#include <iostream>
//#include "ex1.h"
//using namespace std;
//int main() {
// int r;
// r = Plus(3, 7);
// return 0;
//}
//#pragma warning(disable:4996)
//#include <iostream>
//#include <cstring>
//#include <string>
//using namespace std;
//int main() {
// char cstyle[3];
// string cppstyle;
//
// //cin >> cstyle;
// //cin >> cppstyle;
// cin.getline(cstyle, 3);
// cin.clear();
// getline(cin, cppstyle);
//
// cout << cstyle << endl;
// cout << cppstyle << endl;
// return 0;
//}
//#pragma warning(disable:4996)
//#include <iostream>
//#include <cstring>
//using namespace std;
//int main() {
// string cppstyle = "Hell!";
// char* cstyle = new char[cppstyle.size() + 1];
//
// strcpy(cstyle, cppstyle.c_str());
//
// cstyle[0] = 'Y';
//
// cout << cstyle << endl;
// cout << cppstyle << endl;
//
// delete[] cstyle;
// cstyle = NULL;
// return 0;
//}
//#pragma warning(disable:4996)
//#include <iostream>
//#include <cstring>
//using namespace std;
//int main() {
// string cppstyle = "Hell!";
// const char* cstyle = NULL;
//
// cstyle = cppstyle.c_str();
//
// cout << cstyle << endl;
// cout << cppstyle << endl;
// return 0;
//}
//#pragma warning(disable:4996)
//#include <iostream>
//#include <cstring>
//using namespace std;
//int main() {
// char cstyle[] = "Hi~";
// string cppstyle;
//
// cppstyle = cstyle;
// cppstyle[0] = 'A';
// cout << cstyle << endl;
// cout << cppstyle << endl;
// return 0;
//}
// find, substr
//#include <iostream>
//using namespace std;
//int main() {
// string str = "Hi, Inha Univ.";
// cout << str.find("Univ.") << endl;
// string capture = str.substr(4, 4);
// cout << capture << endl;
//
// return 0;
//}
// C++ Style
//#include <iostream>
//using namespace std;
//int main() {
// string str1 = "Inha";
// string str2 = "Inha";
//
// if (str1 == str2) {
// cout << "같다" << endl;
// cout << typeid((str1 == str2)).name() << endl;
// }
// else {
// cout << "다르다" << endl;
// cout << (str1 == str2) << endl;
// }
//
// //str1 = str1 + str2;
// //cout << str1 << endl;
// //cout << str2 << endl;
//
// return 0;
//}
// Old Style (C Style)
//#pragma warning(disable:4996)
//#include <iostream>
//#include <cstring>
//using namespace std;
//int main() {
// char str1[10] = "Inha";
// char str2[] = "Inha";
//
// if (strcmp(str1, str2) == 0)
// cout << "같다" << endl;
// else {
// cout << "다르다" << endl;
// cout << strcmp(str1, str2) << endl;
// } // ascii str1 < str2 -1 리턴, str1 > str2 1 리턴
//
// //strcat(str1, str2);
// //cout << str1 << endl;
// //cout << str2 << endl;
//
// return 0;
//}
// C++ Style
//#include <iostream>
//using namespace std;
//int main() {
// string src = "Inha Univ";
// string dest;
//
// cout << src.size() << endl;
//
// dest = src;
//
// cout << src << endl;
// cout << dest << endl;
//
// return 0;
//}
// Old Style (C Style)
//#pragma warning(disable:4996)
//#include <iostream>
//#include <cstring>
//using namespace std;
//int main() {
// char src[] = "Inha Univ";
// int len = strlen(src);
// cout << len << endl;
//
// char* dest = new char[len + 1];
// strcpy(dest, src);
//
// cout << src << endl;
// cout << dest << endl;
//
// delete[] dest;
// dest = NULL;
//
// return 0;
//}
//#include <iostream>
//using namespace std;
//char* ReverseString(const char* src, int len){
// char* rev = new char[len + 1];
// for (auto i = 0; i < len; ++i)
// rev[i] = src[len - i - 1];
// rev[len] = NULL;
// return rev;
//}
//int main(){
// char orig[] = "Inha";
// char* copy = ReverseString(orig, 4);
// cout << orig << "\n";
// cout << copy << "\n";
// delete[] copy;
// copy = NULL;
// return 0;
//}
|
dbebbc5563e9597409804b15785f343689828450
|
3963d4f07de199407b893600b6bd48b9887ee8f8
|
/STUDY/MidTerm/PowerCpp/03/03_EX1.cpp
|
e69f6ee3e69a1bbc9ae5428c9857de51373e865d
|
[] |
no_license
|
james-sungjae-lee/2018_CPP
|
6f9fc15d183293f1c04a67071d4f24f15c483331
|
a277045f07be1350f2c914dbebfc5f24d6f2e6dd
|
refs/heads/master
| 2022-09-22T23:41:45.030906
| 2018-06-10T01:22:20
| 2018-06-10T01:22:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 194
|
cpp
|
03_EX1.cpp
|
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int age;
std::cin >> age;
int count = 0;
if (age >= 20 && age <= 65) {
count ++;
}
return 0;
}
|
b539e1aa10cdcce5c6414dcf9005e152a5d98c9e
|
765c82de19e89f7a467d004d529c739a3e038319
|
/FlowCube/src/Wall.h
|
6c8d84f3e8726c5305e882700c78827498124c5b
|
[] |
no_license
|
ryo0306/February-Screening-panel
|
712df4130153530b85a97f5704c5e6a9d3d1bffe
|
44f38b25cf3d9f103be736d031785ccecbfedffa
|
refs/heads/master
| 2021-01-10T03:54:22.463140
| 2016-03-05T08:08:00
| 2016-03-05T08:08:00
| 47,526,173
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 215
|
h
|
Wall.h
|
#pragma once
#include "Object.h"
class Wall : public Object
{
public:
Wall(){}
Wall(Vec2f pos_);
virtual void SetUp();
virtual void Update();
virtual void Draw();
protected:
Color color;
};
|
f15cdce396eaa3aaab2b42aaf666bce3f3270c9b
|
d1146d790bf3a7b24a67eab70f290134a07feb7a
|
/test/util/fuchsia_capability_util.cc
|
bbe8643e71027f05500ac84917de0049cf8621c8
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
google/gvisor
|
42ce9c6820612f06a74a20926c909edb2e61c539
|
c2a7efe6a23072acfde99147bd8e81130500bff3
|
refs/heads/master
| 2023-09-01T15:51:42.207968
| 2023-08-30T20:52:24
| 2023-08-30T20:56:03
| 131,212,638
| 14,223
| 1,390
|
Apache-2.0
| 2023-09-14T21:53:34
| 2018-04-26T21:28:49
|
Go
|
UTF-8
|
C++
| false
| false
| 2,064
|
cc
|
fuchsia_capability_util.cc
|
// Copyright 2021 The gVisor Authors.
//
// 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.
#ifdef __Fuchsia__
#include <netinet/if_ether.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "test/util/socket_util.h"
namespace gvisor {
namespace testing {
// On Linux, access to raw IP and packet socket is controlled by a single
// capability (CAP_NET_RAW). However on Fuchsia, access to raw IP and packet
// sockets are controlled by separate capabilities/protocols.
namespace {
PosixErrorOr<bool> HaveSocketCapability(int domain, int type, int protocol) {
// Fuchsia does not have a platform supported way to check the protocols made
// available to a sandbox. As a workaround, simply try to create the specified
// socket and assume no access if we get a no permissions error.
auto s = Socket(domain, type, protocol);
if (s.ok()) {
return true;
}
if (s.error().errno_value() == EPERM) {
return false;
}
return s.error();
}
} // namespace
PosixErrorOr<bool> HaveRawIPSocketCapability() {
static PosixErrorOr<bool> result(false);
static std::once_flag once;
std::call_once(once, [&]() {
result = HaveSocketCapability(AF_INET, SOCK_RAW, IPPROTO_UDP);
});
return result;
}
PosixErrorOr<bool> HavePacketSocketCapability() {
static PosixErrorOr<bool> result(false);
static std::once_flag once;
std::call_once(once, [&]() {
result = HaveSocketCapability(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
});
return result;
}
} // namespace testing
} // namespace gvisor
#endif // __Fuchsia__
|
8bb11a9662b153d63d9a58346105ef66ebc0be38
|
9fed22fc93b92648559f040ecdc68f03825f1bca
|
/src/ibool.cpp
|
7067e966c340b0403e5b552c3d75d8877c3a17cc
|
[
"ISC"
] |
permissive
|
rkojedzinszky/libjson-
|
ea4ab2568acdd4726162b8aa4c08228c4ff098b8
|
bb57fc0c9712586b7ece74649d9ecc353061cedd
|
refs/heads/master
| 2021-11-09T04:31:32.543315
| 2016-04-28T09:43:11
| 2016-04-28T09:43:11
| 32,326,698
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 871
|
cpp
|
ibool.cpp
|
#include <iostream>
#include <iomanip>
#include <json/ibool.hpp>
namespace JSON
{
IValue::Type IBool::type() const
{
return JSON_BOOL;
}
IBool* IBool::clone() const
{
return new IBool(value);
}
bool IBool::getBool() const
{
return value;
}
bool IBool::asBool() const
{
return value;
}
int IBool::asInt() const
{
return value ? 1 : 0;
}
unsigned IBool::asUInt() const
{
return value ? 1 : 0;
}
long long IBool::asLong() const
{
return value ? 1 : 0;
}
unsigned long long IBool::asULong() const
{
return value ? 1 : 0;
}
std::string IBool::asString() const
{
return value ? "true" : "false";
}
bool IBool::operator==(const IValue& r) const
{
return value == r.getBool();
}
void IBool::toStream(std::ostream& o) const
{
o << std::boolalpha << value;
}
void IBool::fromStream(std::istream& i)
{
i >> std::boolalpha >> value;
}
}; // namespace JSON
|
cd5da29d10473d9364671f1003a53dbfdb8ef50c
|
90e66232f6d02811acf1d9123dd1b7b5d19ed35a
|
/perket.cpp
|
e8018a663e97e039e1f9cffa027332aae62063c2
|
[] |
no_license
|
lukevand/kattis-submissions
|
8396fb2dbc4d5550c47eae7525bf9482d5155955
|
fc61a5117e507ef283241dec1dd3caa242df8934
|
refs/heads/master
| 2021-07-12T16:42:43.582376
| 2020-03-13T05:57:51
| 2021-05-27T19:40:12
| 246,996,282
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 931
|
cpp
|
perket.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> ii;
#define debugp(X) for(auto const& CCC:X) std::cerr<<CCC<<' '; cerr<<'\n'
#define debug(XXX) cerr << #XXX << ": " << XXX << '\n'
int main()
{
cin.sync_with_stdio(false);
int N;
ii ing[10];
int t1, t2;
scanf("%d", &N);
int limit = 1<<N;
for (int i=0; i<N;i++) {
scanf("%d %d", &t1, &t2);
ing[i] = ii(t1, t2);
}
/* if (N == 1) { */
/* printf("%d\n", abs(ing[0].first-ing[0].second)); */
/* return 0; */
/* } */
int min_combi = INT_MAX;
int sm, pd;
for (int i=1; i<limit; i++) {
pd = 1; sm = 0;
for (int j = 0; j<N; j++) {
if (i & (1 << j)) {
pd *= ing[j].first;
sm += ing[j].second;
}
}
min_combi = min(min_combi, abs(pd - sm));
}
printf("%d\n", min_combi);
return 0;
}
|
0bb326255550ac27b0ab12ba981bbdd1805b0fd5
|
c84bfd27a561a232c318ed1ce8c6f980067d3458
|
/AssetManager2/AssetManager2/television.h
|
01aaf5bd176a8851486ac9b092ed62eff59412a4
|
[] |
no_license
|
yaoReadingCode/VS2015project
|
2c2130edb6613d5d1b9657087220f74f92d7080d
|
235ac68ca25b8e999bef151a811f982ed07affc3
|
refs/heads/master
| 2022-04-04T05:59:40.134755
| 2018-05-11T11:32:00
| 2018-05-11T11:32:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 476
|
h
|
television.h
|
#ifndef TELEVISION_H
#define TELEVISION_H
#include<string>
#include"asset.h"
#include"custodian.h"
class Television : public Asset {
public:
Television(const std::string &id, const std::string &brand, const std::string &model,
const double purchasePrice, const Date &purchaseDate, const std::string &serial,
const std::string &location);
const std::string &location() const;
private:
std::string _location;
};
#endif // !TELEVISION_H
|
e677799cf3ce4b66fcbecb7ddcb5e41a4c9d35c7
|
f6bdab6c60adebe0d8b19779a6fa4e5071c4a318
|
/SLDLoop/CApp_OnEvent.cpp
|
944ba381c0b3a011e70e44c1167bb9efb2cfc08f
|
[] |
no_license
|
robertpfeiffer/Afterlife-Empire-Opensource
|
c16af55f1ab91ec29f8db1c4159743c4e3d8bedb
|
343c734d490b88301abe03b674f976aa00e25738
|
refs/heads/master
| 2020-05-07T22:06:46.205640
| 2015-08-17T19:31:20
| 2015-08-17T19:31:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,830
|
cpp
|
CApp_OnEvent.cpp
|
//==============================================================================
#include "CApp.h"
#include "GameLogic.h"
#include "Camera.h"
//==============================================================================
void CApp::OnEvent(SDL_Event* Event) {
CEvent::OnEvent(Event);
}
void CApp::OnResize(int w, int h)
{
if (!goFullScreen){
//SDL_SetVideoMode(w, h, 32, SDL_OPENGL | SDL_RESIZABLE | SDL_DOUBLEBUF);
}
GameLogic::setWindow(w, h);
screenWidth = w;
screenHeight = h;
}
void CApp::OnMButtonUp(int mX, int mY){
//GameLogic::mouseInput(MOUSE_STATE_UP, getPosInView(mX, mY), MOUSE_C);
}
void CApp::OnMouseWheel(bool Up, bool Down){
if (Up){
Camera::changeZoom(1.0);
}
if (Down){
Camera::changeZoom(-1.0);
}
}
cpVect CApp::getPosInView(int mX, int mY){
double amountX;
double amountY;
mY = screenHeight - mY;
if (GameLogic::width > GameLogic::height){
double width = screenWidth;
double height = screenHeight;
double xPos = (double)mX;
double yPos = (double)mY;
xPos -= width / 2.0;
yPos -= height / 2.0;
amountX = xPos / (width / 2.0);
amountY = yPos / (width / 2.0);
amountX *= 100;
amountY *= 100;
}
else {
double width = screenWidth;
double height = screenHeight;
double xPos = (double)mX;
double yPos = (double)mY;
xPos -= width / 2.0;
yPos -= height / 2.0;
amountX = xPos / (height / 2.0);
amountY = yPos / (height / 2.0);
amountX *= 100;
amountY *= 100;
}
//printf("%f, %f - %i, %i \n", amountX, amountY, mX, mY);
return cpv(amountX, amountY);
}
void CApp::OnLButtonDown(int mX, int mY) {
GameLogic::mouseInput(MOUSE_STATE_TOUCH, getPosInView(mX, mY), MOUSE_L);
}
void CApp::OnLButtonUp(int mX, int mY){
GameLogic::mouseInput(MOUSE_STATE_UP, getPosInView(mX, mY), MOUSE_L);
}
void CApp::OnRButtonDown(int mX, int mY) {
GameLogic::mouseInput(MOUSE_STATE_TOUCH, getPosInView(mX, mY), MOUSE_R);
}
void CApp::OnRButtonUp(int mX, int mY){
GameLogic::mouseInput(MOUSE_STATE_UP, getPosInView(mX, mY), MOUSE_R);
}
void CApp::OnKeyUp(SDL_Keycode sym){
GameLogic::keyInput(KEY_UP, sym);
}
void CApp::OnKeyDown(SDL_Keycode sym){
GameLogic::keyInput(KEY_DOWN, sym);
}
void CApp::OnMouseMove(int mX, int mY, int relX, int relY, bool Left,bool Right,bool Middle){
if (Left){
GameLogic::mouseInput(MOUSE_STATE_DRAG, getPosInView(mX, mY), MOUSE_L);
}
else if (Right){
GameLogic::mouseInput(MOUSE_STATE_DRAG, getPosInView(mX, mY), MOUSE_R);
}
else {
GameLogic::mouseInput(MOUSE_STATE_HOVER, getPosInView(mX, mY), MOUSE_L);
}
}
void CApp::OnExit() {
Running = false;
}
|
314cf5011d073c77d973701d9b712abb1946fb4f
|
32c2b550a15aeb900330ba9694c0a53c7a96a1fa
|
/course7/homeworks/kushagra/hw2/ls_hw2.cpp
|
b7bdb0d51b82bfb3515080b5ea914bce3a392781
|
[] |
no_license
|
5l1v3r1/c-excercises
|
42d396d60e347d0753e4b32414e8f222801bae9d
|
f217b7c404e0ce53dae625f3dc54709e4af24dc2
|
refs/heads/master
| 2021-05-25T18:02:10.522666
| 2018-04-26T15:46:46
| 2018-04-26T15:46:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,800
|
cpp
|
ls_hw2.cpp
|
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <string>
#include <iostream>
namespace po = boost::program_options;
namespace fs = boost::filesystem;
//For directory display without details
void print_dir_contents(const fs::path& full_path) {
std::cout << full_path.generic_string() << fs::path::preferred_separator << std::endl;
for (fs::directory_entry& x : fs::directory_iterator(full_path)) {
if (fs::is_regular_file(x.path())) {
std::cout << " " << x.path().filename().string() << std::endl;
} else {
std::cout << " " << x.path().filename().generic_string() << fs::path::preferred_separator
<< std::endl;
}
}
}
//Function overloading. For recursive directory display without details
void print_dir_contents(const fs::path& display_path, std::string& spaces) {
if (fs::is_regular_file(display_path)) {
std::cout << spaces << display_path.filename().generic_string() << std::endl;
}
else {
std::cout << spaces << display_path.filename().generic_string() <<
fs::path::preferred_separator << std::endl;
spaces += " ";
for (fs::directory_entry& x : fs::directory_iterator(display_path)) {
print_dir_contents(x.path(), spaces);
}
}
}
/*
Calculate the size of the files in the directory. If recursive is set to true, the total size of all files in the
directory and its subdirectories. If set to false, only the size of the files in the directory is calculated and
returned.
*/
int get_dir_size(const fs::path& dir_path, bool recursive=false) {
int dir_size = 0;
if(recursive) {
for (fs::directory_entry& x : fs::recursive_directory_iterator(dir_path)) {
if (fs::is_regular_file(x)) {
dir_size += fs::file_size(x);
}
}
} else {
for (fs::directory_entry& x : fs::directory_iterator(dir_path)) {
if (fs::is_regular_file(x)) {
dir_size += fs::file_size(x);
}
}
}
return dir_size;
}
/*Display the directory contents, along with the sizes. The size of the directory is calculated by the sum of all
the sizes of immediate descendant files in the directory
*/
void print_detailed_dir_contents(const fs::path& display_path) {
int file_size = 0;
int dir_size = get_dir_size(display_path);
std::cout << std::to_string(dir_size) << " " << display_path.filename().generic_string()
<< fs::path::preferred_separator << std::endl;
for (fs::directory_entry& x : fs::directory_iterator(display_path)) {
if (fs::is_regular_file(x.path())) {
file_size = fs::file_size(x.path());
std::cout << " " << std::to_string(file_size) << " " << x.path().filename().string() << std::endl;
}
else {
dir_size = get_dir_size(x.path());
std::cout << " " << std::to_string(dir_size) << " " << x.path().filename().generic_string()
<< fs::path::preferred_separator << std::endl;
}
}
}
/*Display the directory contents, along with the sizes. The size of the directory is calculated by the sum of all
the sizes of descendant files in the directory, as well as its subdirectories.
*/
void print_detailed_dir_contents(const fs::path& display_path, std::string& spaces) {
int dir_size = 0;
int file_size = 0;
if (fs::is_regular_file(display_path)) {
file_size = fs::file_size(display_path);
std::cout << spaces << std::to_string(file_size) << " " << display_path.filename().string() << std::endl;
}
else {
dir_size = get_dir_size(display_path, true);
std::cout << spaces << std::to_string(dir_size) << " " << display_path.filename().generic_string()
<< fs::path::preferred_separator << std::endl;
spaces += " ";
for (fs::directory_entry& x : fs::directory_iterator(display_path)) {
print_detailed_dir_contents(x.path(), spaces);
}
}
}
int main(int argc, char** argv)
{
std::string path_name = ".";
bool details = false, recursive = false;
po::options_description desc("Display contents of a directory.");
desc.add_options()
("help,h", "Display help text")
("path_name,p", po::value<std::string>()->default_value("."), "Path to display")
("long,l", po::bool_switch()->default_value(false)->implicit_value(true),
"Display full details")
("tee,t", po::bool_switch()->default_value(false)->implicit_value(true),
"Recursively display directory contents");
po::positional_options_description posOption;
posOption.add("path_name", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(posOption).run(), vm);
po::notify(vm);
if(vm.count("path_name")) {
path_name = vm["path_name"].as<std::string>();
if (path_name.back() == '/') {
path_name.erase(path_name.length()-1);
}
}
if(vm.count("long")) {
details = vm["long"].as<bool>();
}
if(vm.count("tee")) {
recursive = vm["tee"].as<bool>();
}
if(vm.count("help")) {
std::cout << desc << std::endl;
return 0;
}
fs::path full_path(path_name);
if (fs::exists(full_path)) {
if (fs::is_regular_file(full_path)) {
if(details) {
std::cout << fs::file_size(full_path) << " ";
}
std::cout << full_path.generic_string() << std::endl;
}
else {
std::string spaces = "";
if (details) {
if (recursive) {
print_detailed_dir_contents(full_path, spaces);
} else {
print_detailed_dir_contents(full_path);
}
} else {
if (recursive) {
print_dir_contents(full_path, spaces);
} else {
print_dir_contents(full_path);
}
}
}
}
}
|
2db7bff15baf42b631ecfba1b3087928df97dc17
|
4c6012967dd302ce78664f785869cf6da369ddef
|
/388_permutation-sequence/permutation-sequence.cpp
|
402f56d7fe1d35beb5000f4bb8e7c6f1805bdb80
|
[] |
no_license
|
heiyanbin/lintcode
|
24b6627847d462b6b0be06ac418b1a9059a02f57
|
752d10ba02430b4344965f3a3a183173600fd205
|
refs/heads/master
| 2021-01-12T07:48:38.716502
| 2016-12-21T06:25:25
| 2016-12-21T06:25:25
| 77,023,323
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,043
|
cpp
|
permutation-sequence.cpp
|
/*
@Copyright:LintCode
@Author: heiyanbin
@Problem: http://www.lintcode.com/problem/permutation-sequence
@Language: C++
@Datetime: 15-05-18 09:31
*/
class Solution {
public:
/**
* @param n: n
* @param k: the kth permutation
* @return: return the k-th permutation
*/
string getPermutation(int n, int k) {
if (n == 0) return "";
string res;
vector<bool> used(n);
int fac = 1;
for (int i = 2; i <= n; i++)
fac *= i;
k --;
for (int i = 0; i < n; i++) {
int f = fac / (n - i);
int index = k / f;
for (int j = 0, count = 0; j < n; j++) {
if (!used[j]) {
if (count == index) {
res.push_back(j + '1');
used[j] = true;
break;
}
count++;
}
}
k %= f;
fac = f;
}
return res;
}
};
|
32a82857accd596d54ba5eada0405877e0604f9c
|
038df27dfb74a68f7b2fef2f63e5cc6bfe720962
|
/examples/0024.locale/lconv_storage.cc
|
2633ffd2fde71bc8401ae808926e9a0593cc4ddf
|
[
"MIT"
] |
permissive
|
klmr/fast_io
|
6226db934bbda0b78ae1fac80d20c635106db2c1
|
1393ef01b82dffa87f3008ec0898431865870a1f
|
refs/heads/master
| 2022-07-28T12:34:10.173427
| 2020-05-25T11:25:38
| 2020-05-25T11:25:38
| 266,780,867
| 2
| 0
|
NOASSERTION
| 2020-05-25T13:03:19
| 2020-05-25T13:03:19
| null |
UTF-8
|
C++
| false
| false
| 381
|
cc
|
lconv_storage.cc
|
#include"../../include/fast_io.h"
#include"../../include/fast_io_locale.h"
int main()
{
fast_io::c_locale loc(fast_io::c_locale_category::all);
fast_io::c_lconv_storage stg(loc);
for(auto const& e : stg.grouping())
println(static_cast<int>(e));
// println("grouping:",stg.grouping(),
// "\nnegative_sign:",stg.negative_sign(),
// "\ncurrency sign:",stg.currency_symbol());
}
|
b331af305945de7473c882e82f4730e4122da025
|
80c12a189796bdf46ac469e6d19c0c0441abfe38
|
/src/OptimizationRunSelector.h
|
592c82ddeec2d656f6a9e20a295d430ec0609ec8
|
[
"BSL-1.0"
] |
permissive
|
snow-abstraction/contentless_gui
|
5e7f29ddb6f25b0bf6409727547d52cbcba8b9e2
|
65b08f19526f34a3e9ea229c3a96a665c1f515d7
|
refs/heads/master
| 2021-03-12T20:04:45.167824
| 2014-08-31T13:28:00
| 2014-08-31T13:28:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 776
|
h
|
OptimizationRunSelector.h
|
// Copyright Douglas W. Potter 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)'
#ifndef OPTIMIZATION_RUN_SELECTOR_H_
#define OPTIMIZATION_RUN_SELECTOR_H_
#include <string>
#include <vector>
#include "common_defs.h"
namespace ShapePackingGui {
class OptimizationRunSelector {
public:
void set_run_path_and_update(const std::string& path);
UpdateProblemDefSignal get_update_problem_def_signal();
UpdateSolutionDrawingsSignal get_update_solution_drawings_signal();
private:
UpdateProblemDefSignal update_problem_def_signal;
UpdateSolutionDrawingsSignal update_sol_drawings_signal;
};
}
#endif /* RUN_SELECTOR_H_ */
|
87a45d6940d6a622910c919f51614a422c1b44ad
|
b4858e9cb8086c6a3a26df531fb7ff6505dbfeff
|
/HW5/fs/src/node_visitor.h
|
f6fcd67b7027977f73db5f6f886f399b8ab50fcb
|
[] |
no_license
|
xtc841113/Design-Pattern
|
7047beeddb6959f8ba557137dd321310a0e670da
|
b23f38989697a5054147511994ad4fa850e14239
|
refs/heads/master
| 2022-12-01T07:18:49.084687
| 2020-07-31T14:40:50
| 2020-07-31T14:40:50
| 284,057,917
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 257
|
h
|
node_visitor.h
|
#ifndef NODE_VISITOR_H
#define NODE_VISITOR_H
#include <string>
class Folder;
class File;
class NodeVisitor{
public:
virtual void visitFolder(Folder *folder) = 0;
virtual void visitFile(File *file) = 0;
virtual std::string findResult(){};
};
#endif
|
0cb69363711fcace31b9fecac31c038697257e6f
|
d1e4718197ba3bddd13d6f6958e1d5a492b51af5
|
/afc/call_tcc.cpp
|
88a3587999a288483ea4221cb6fefabdf752c81d
|
[] |
no_license
|
reisoftware/ap2d
|
1f398664fdc4f8cab9479df18cd2a745f904cdff
|
e09732655ef66e13e98b8f3b008c91dac541e1f5
|
refs/heads/master
| 2022-01-22T05:36:56.295845
| 2022-01-04T05:31:57
| 2022-01-04T05:31:57
| 162,372,004
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,664
|
cpp
|
call_tcc.cpp
|
#include "StdAfx.h"
#include "call_tcc.h"
#include "tcc.h"
#include "dir.h"
#include <cassert>
namespace afc{
static void exit(LPCTSTR msg)
{
::MessageBox(NULL, msg, "tcc", MB_OK);
}
void call_code(PF_ADD_SYMBOL pf_symbol, LPCTSTR func_code, LPCTSTR func_name)
{
assert(pf_symbol);
try{
afc::Tcc t;
t.create(afc::dir::exe_path().c_str());
pf_symbol(t);
t.add_code(func_code);
t.relocate();
typedef void(*PF)();
PF pf = (PF)t.get_symbol(func_name);
pf();
}catch(afc::Tcc::Error err){
exit(err.msg_);
}
}
void call_code(PF_ADD_SYMBOL pf_symbol, LPCTSTR func_code, LPCTSTR func_name, void * param1)
{
assert(pf_symbol);
try{
afc::Tcc t;
t.create(afc::dir::exe_path().c_str());
pf_symbol(t);
t.add_code(func_code);
t.relocate();
typedef void(*PF)(void *);
PF pf = (PF)t.get_symbol(func_name);
pf(param1);
}catch(afc::Tcc::Error err){
exit(err.msg_);
}
}
void call_code(PF_ADD_SYMBOL pf_symbol, LPCTSTR func_code, LPCTSTR func_name, void * param1, void * param2)
{
assert(pf_symbol);
try{
afc::Tcc t;
t.create(afc::dir::exe_path().c_str());
pf_symbol(t);
t.add_code(func_code);
t.relocate();
typedef void(*PF)(void *, void *);
PF pf = (PF)t.get_symbol(func_name);
pf(param1, param2);
}catch(afc::Tcc::Error err){
exit(err.msg_);
}
}
void call_script(PF_ADD_SYMBOL pf_symbol, LPCTSTR file, LPCTSTR func_name)
{
assert(pf_symbol);
try{
afc::Tcc t;
t.create(afc::dir::exe_path().c_str());
pf_symbol(t);
t.add_file(file);
t.relocate();
typedef void(*PF)();
PF pf = (PF)t.get_symbol(func_name);
pf();
}catch(afc::Tcc::Error err){
exit(err.msg_);
}
}
void call_script(PF_ADD_SYMBOL pf_symbol, LPCTSTR file, LPCTSTR func_name, void * param1)
{
assert(pf_symbol);
try{
afc::Tcc t;
t.create(afc::dir::exe_path().c_str());
pf_symbol(t);
t.add_file(file);
t.relocate();
typedef void(*PF)(void *);
PF pf = (PF)t.get_symbol(func_name);
pf(param1);
}catch(afc::Tcc::Error err){
exit(err.msg_);
}
}
void call_script(PF_ADD_SYMBOL pf_symbol, LPCTSTR file, LPCTSTR func_name, void * param1, void * param2)
{
assert(pf_symbol);
try{
afc::Tcc t;
t.create(afc::dir::exe_path().c_str());
pf_symbol(t);
t.add_file(file);
t.relocate();
typedef void(*PF)(void *, void *);
PF pf = (PF)t.get_symbol(func_name);
pf(param1, param2);
}catch(afc::Tcc::Error err){
exit(err.msg_);
}
}
}//namespace
|
bb6d81491d08b2cd1fd9dde9a5ef75dd2b57bcc1
|
a23b2110aa8eea65b9e435e4fd5ca1bbfac9fed7
|
/A. Reconnaissance.cpp
|
796c8a239e700a28ba725a7acc299ab1d68955de
|
[] |
no_license
|
sbswarna/CodeForces
|
abfd92738255557590e8a82b305876d6a48113f0
|
29a9099446be51201b0bd0d6402ccc8fe77056d7
|
refs/heads/main
| 2023-08-28T18:31:03.851047
| 2021-09-29T02:48:16
| 2021-09-29T02:48:16
| 348,233,677
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 500
|
cpp
|
A. Reconnaissance.cpp
|
#include<bits/stdc++.h>
using namespace std;
long long n,d,a[1005];
void F()
{
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
freopen("output.in", "w", stdout);
#endif
}
int main(int argc, char const *argv[])
{
F();
cin>>n>>d;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
long long cnt=0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[j]-a[i]<=d)
cnt+=2;
else
break;
}
}
cout<<cnt<<endl;
return 0;
}
|
7e1ebcea280ad42fc505e01c63363835bafa3836
|
eac2309ca19f70ada801ae291378cfd430f5657b
|
/List/Q2/2-2.cpp
|
60d243a34f6c7f139a2bd81187024b9adf4c10ec
|
[] |
no_license
|
Alcatraz1337/Projects-New
|
d3480132e154fa8180dd705695df384bccd1628f
|
760abbc8b4186ddd33517038f62e6316e8e3437f
|
refs/heads/master
| 2023-03-09T06:23:48.498788
| 2021-03-01T05:24:13
| 2021-03-01T05:24:13
| 169,055,505
| 3
| 0
| null | 2019-02-05T10:55:31
| 2019-02-04T09:35:23
|
C++
|
UTF-8
|
C++
| false
| false
| 270
|
cpp
|
2-2.cpp
|
template <class T>
void ArrayList<T> :: deleteSpec(T x){
int i = 0;
for (i; i < curLen; i++){
if(ArrayList[i] == x){
for (int j = i; j < curLen - 1; j++)
ArrayList[j] = ArrayList[j + 1];
curLen--;
}
}
}
|
2df0e3d0c609d7ddcac215665abcd898e448290a
|
8f435fd95c7942d1dc49358a99a31b5076789fb9
|
/PI/openmp/original/FVLib/include/FVRecons1D.h
|
cf410d1697a4060c9dd488a793365d97eef1aee5
|
[] |
no_license
|
Surtr04/PI-CPD
|
5926f299689a4ba89b841e09193b3a7879437b88
|
48e02f749b4d1a8a205a5f23d9300a8be68edd66
|
refs/heads/master
| 2021-01-18T20:29:40.985365
| 2013-07-31T19:06:25
| 2013-07-31T19:06:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,544
|
h
|
FVRecons1D.h
|
// ------ FVRecons1D.h ------
// S. CLAIN 2011/10
#ifndef _FVRECONS1D
#define _FVRECONS1D
#include "FVMesh1D.h"
#include "FVStencil.h"
#include "FVVect.h"
#include "FVDenseM.h"
#include "FVPoint1D.h"
#include "FVGaussPoint.h"
#include "FVLib_config.h"
#include "FVTools.h"
class FVRecons1D
{
private:
FVPoint1D<double> _ref_point;
FVVect<double> *_Vertex1DVect,*_Cell1DVect;
FVVect<double> *_coef,*_M;
FVStencil * _ptr_s;
FVDenseM<double> *_A,*_Q,*_Adag;
double _evalMean(void *ptr,size_t type,size_t alpha);
double _ref_val;
size_t _degree,_Ncoef,_reconstruction_type;
public:
FVRecons1D()
{
//cout<<"using the FVRecons2D default constructor"<<endl; fflush(NULL);
_ptr_s=NULL;
_Vertex1DVect=NULL;
_Cell1DVect=NULL;
_A=new FVDenseM<double>;
_Q=new FVDenseM<double>;
_coef= new FVVect<double>;
_M=new FVVect<double>;
_Adag=new FVDenseM<double>;
_ref_point=0.; _ref_val=0;_degree=0;_Ncoef=0;_reconstruction_type= REC_NULL;
}
FVRecons1D(FVStencil *ptr_s)
{
//cout<<"using the FVRecons1D constructor with stencil"<<endl; fflush(NULL);
_ptr_s=ptr_s;
_A=new FVDenseM<double>;
_Q=new FVDenseM<double>;
_coef= new FVVect<double>;
_M=new FVVect<double>;
_Adag=new FVDenseM<double>;
_ref_point=0;_degree=0;_Ncoef=0;_reconstruction_type= REC_NULL;
if(ptr_s->getReferenceType()==FVVERTEX1D)
_ref_point=((FVVertex1D *)(_ptr_s->getReferenceGeometry()))->coord;
if(ptr_s->getReferenceType()==FVCELL1D)
_ref_point=((FVCell1D *)(_ptr_s->getReferenceGeometry()))->centroid;
}
FVRecons1D(FVStencil *ptr_s, size_t degree)
{
//cout<<"using the FVRecons2D constructor with stencil and degress"<<endl; fflush(NULL);
_degree=degree;
_Ncoef=_degree;
_ptr_s=ptr_s;
_A=new FVDenseM<double>;
_Q=new FVDenseM<double>;
_coef= new FVVect<double>;
_M=new FVVect<double>;
_Adag=new FVDenseM<double>;
_ref_point=0;
_reconstruction_type= REC_NULL;
if(ptr_s->getReferenceType()==FVVERTEX1D)
_ref_point=((FVVertex1D *)(_ptr_s->getReferenceGeometry()))->coord;
if(ptr_s->getReferenceType()==FVCELL1D)
_ref_point=((FVCell1D *)(_ptr_s->getReferenceGeometry()))->centroid;
}
// destructor
~FVRecons1D(){if(_A) delete(_A); if(_Q) delete(_Q);if(_coef) delete(_coef);if(_M) delete(_M);if(_Adag) delete(_Adag);}
FVRecons1D(const FVRecons1D & rec); // copy constructor
FVRecons1D & operator =(const FVRecons1D &rec) // assigment operator
{
//cout<<"using the FVRecons1D assigment operator "<<endl; fflush(NULL);
_ptr_s=rec._ptr_s;
_Vertex1DVect=rec._Vertex1DVect;
_Cell1DVect=rec._Cell1DVect;
_ref_point=rec._ref_point;
_ref_val=rec._ref_val;
_degree=rec._degree;
_Ncoef=rec._Ncoef;
_reconstruction_type=rec._reconstruction_type;
//
_A->resize(rec._A->nb_rows,rec._A->nb_cols);
(*_A)=(*rec._A);
_Adag->resize(rec._Adag->nb_rows,rec._Adag->nb_cols);
(*_Adag)=(*rec._Adag);
_Q->resize(rec._Q->nb_rows,rec._Q->nb_cols);
(*_Q)=(*rec._Q);
_coef->resize(rec._coef->size());
(*_coef)=(*rec._coef);
_M->resize(rec._M->size());
(*_M)=(*rec._M);
return *this;
}
// setStencil
void setStencil(FVStencil &st){ FVRecons1D::setStencil(&st); }
void setStencil(FVStencil *ptr_s)
{
_ptr_s=ptr_s;
_ref_point=0;_degree=0;_Ncoef=0;
if(_ptr_s->getReferenceType()==FVVERTEX1D)
_ref_point=((FVVertex1D *)(_ptr_s->getReferenceGeometry()))->coord;
if(_ptr_s->getReferenceType()==FVCELL1D)
_ref_point=((FVCell1D *)(_ptr_s->getReferenceGeometry()))->centroid;
}
void setStencil(FVStencil &st, size_t degree){ FVRecons1D::setStencil(&st,degree); }
void setStencil(FVStencil *ptr_s, size_t degree)
{
_ptr_s=ptr_s;
_ref_point=0;
_degree=degree;
_Ncoef=_degree;
if(_ptr_s->getReferenceType()==FVVERTEX1D) _ref_point=((FVVertex1D *)(_ptr_s->getReferenceGeometry()))->coord;
if(_ptr_s->getReferenceType()==FVCELL1D) _ref_point=((FVCell1D *)(_ptr_s->getReferenceGeometry()))->centroid;
}
FVStencil *getStencil() {return(_ptr_s);}
//others
void setPolynomialDegree(size_t degree){_degree=degree;_Ncoef=_degree;}
size_t getPolynomialDegree(){return(_degree); }
void setReferencePoint(double x){_ref_point.x=x;}
void setReferencePoint(FVPoint1D<double> P){_ref_point=P;}
void setVectorVertex1D( FVVect<double> & u){_Vertex1DVect=&u;}
void setVectorCell1D( FVVect<double> & u){_Cell1DVect=&u;}
void setReconstructionType(size_t rec_type){_reconstruction_type=rec_type;}
size_t getReconstructionType(){return _reconstruction_type;}
void doConservativeMatrix();
void computeConservativeCoef();
void doNonConservativeMatrix();
void computeNonConservativeCoef();
void doMatrix()
{
if(_reconstruction_type==REC_NULL) {cout<<"error construction type not defined"<<endl;exit(0);}
if(_reconstruction_type==REC_NON_CONSERVATIVE) FVRecons1D::doNonConservativeMatrix();
if(_reconstruction_type==REC_CONSERVATIVE) FVRecons1D::doConservativeMatrix();
}
void computeCoef()
{
if(_reconstruction_type==REC_NULL) {cout<<"error construction type not defined"<<endl;exit(0);}
if(_reconstruction_type==REC_NON_CONSERVATIVE) FVRecons1D::computeNonConservativeCoef();
if(_reconstruction_type==REC_CONSERVATIVE) FVRecons1D::computeConservativeCoef();
}
double ConditioningNumber();
void resetCoef(){if (_coef->size()!=_Ncoef) _coef->resize(_Ncoef);(*_coef)=0.;_ref_val=0.;}
double getValue(FVPoint1D<double> P, size_t degree);
double getValue(FVPoint1D<double> P){return(FVRecons1D::getValue(P,_degree));}
FVPoint1D<double> getDerivative(FVPoint1D<double> P, size_t degree);
FVPoint1D<double> getDerivative(FVPoint1D<double> P){return(FVRecons1D::getDerivative(P,_degree));}
FVPoint1D<FVPoint1D<double> >getHessian(FVPoint1D<double> P, size_t degree);
FVPoint1D<FVPoint1D<double> >getHessian(FVPoint1D<double> P){return(FVRecons1D::getHessian(P,_degree));}
void clean()
{
_A->resize(0);
_Adag->resize(0);
_Q->resize(0);
_coef->resize(0);
_M->resize(0);
_ptr_s=NULL;
_Vertex1DVect=NULL;
_Cell1DVect=NULL;
_ref_point=0.; _ref_val=0;_degree=0;_Ncoef=0;
_reconstruction_type= REC_NULL;
}
void show();
};
FVPoint1D<size_t> alpha1D(size_t k);
#endif // define _FVRECONS1D
|
b8172da9ae56bf1eecf61fb58a0c34e220116b40
|
63a5f2fbc1443b1a289f282c8a55ed5dc9d1c75c
|
/PiBot/src/gpio.cpp
|
0eb7ff1d528a7b820441e32f42476820c6e930b7
|
[] |
no_license
|
mslawicz/PiBot
|
03fd802e187465838ffb971753ca9d08e8dc7f60
|
c41a03f57b1474be2bb33c505cc896296af8d16b
|
refs/heads/master
| 2020-04-15T00:11:52.225682
| 2019-05-15T18:52:20
| 2019-05-15T18:52:20
| 164,231,945
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 716
|
cpp
|
gpio.cpp
|
/*
* gpio.cpp
*
* Created on: 5 sty 2019
* Author: Marcin
*/
#include "logger.h"
#include "gpio.h"
#include "program.h"
#include <stdlib.h>
void GPIO::initialize(void)
{
if(gpioInitialise() < 0)
{
Program::getInstance().terminate(GPIO_INITIALIZATION_ERROR);
}
}
void GPIO::terminate(void)
{
gpioTerminate();
}
GPIO::GPIO(GpioPin gpioNumber, unsigned mode, unsigned pull)
: gpio_number(gpioNumber)
{
auto result = gpioSetMode(gpioNumber, mode);
if(result == PI_BAD_GPIO)
{
Program::getInstance().terminate(BAD_GPIO_NUMBER);
}
if(result == PI_BAD_MODE)
{
Program::getInstance().terminate(BAD_GPIO_MODE);
}
gpioSetPullUpDown(gpioNumber, pull);
}
|
0f1e6f94d64604212090b00da53225dcbc134a82
|
b568504c7774e3b093067b2831fabb45e9925c55
|
/Radar Station/nodeList.cpp
|
21f3c402bb8e89c3ede270d7706748ef8f597041
|
[] |
no_license
|
Barttmr/Data-Structures
|
bc9ad0a0c85c1e1c0148f0f08c04177283f8afb5
|
b6b21fb1cbd0f89b968f6ba08a0a4443cf233c29
|
refs/heads/master
| 2022-11-12T16:26:23.173798
| 2020-06-26T14:07:16
| 2020-06-26T14:07:16
| 275,149,497
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 139
|
cpp
|
nodeList.cpp
|
#include "nodeList.h"
nodeList::nodeList()
{
sn = *new Session();
next = NULL;
previous = NULL;
}
nodeList::~nodeList()
{
}
|
40e6153eb6947f39e7b8fa54dc829736f34cddb8
|
8b29c9ee950b6d2b35c93cdb904706da5de2a2fc
|
/lab2/test/lab2_skeleton/DynamicStack.hpp
|
27dbb4c2d98d9620eceb54fcf480f70208d0f67f
|
[] |
no_license
|
adijunnarkar/AdiRepo
|
65ebe1b2cc067d3a0a5a9af4ee269dc88a475fb1
|
e2e36b4acea776f4bcd2c74c8920fbe987a7f237
|
refs/heads/master
| 2016-09-06T18:30:07.375449
| 2016-01-20T02:30:04
| 2016-01-20T02:30:04
| 26,737,108
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,535
|
hpp
|
DynamicStack.hpp
|
/*
* DynamicStack implements a stack using a dynamically resizable array.
* Default size of the array is 16.
*/
#ifndef DYNAMIC_STACK_HPP
#define DYNAMIC_STACK_HPP
class DynamicStack
{
friend class DynamicStackTest;
public:
// Can be seen outside as DynamicStack::StackItem
typedef int StackItem;
// Used as an indicator of empty stack.
static const StackItem EMPTY_STACK;
// Default constructor used to initialise the dynamic stack array.
// Default size is 16.
DynamicStack();
// Constructor used to initialise the dynamic stack array with the argument
// 'size' identifying the stack size.
// If size is 0, use an initial size of 16.
DynamicStack(unsigned int size);
// Destructor. It deallocates the memory space allocated for the stack.
~DynamicStack();
// Takes as an argument a StackItem value. If the stack is not full, the value
// is pushed onto the stack. Otherwise, the size limit of the stack is doubled
// and the item is pushed onto the resized stack.
void push(StackItem value);
// Removes and returns the top item from the stack, if it is not empty. If the
// number of items remaining in the stack after popping is less than or equal
// to 1/4 of the size limit of the array, then the array is halved unless the
// new size would be less than the initial size. If the stack is empty before
// the pop, the EMPTY_STACK constant is returned.
StackItem pop();
// Returns true if the stack is empty and false otherwise.
bool empty() const;
// Returns the number of items in the stack.
int size() const;
// Same as pop() function except that the top item is returned and is not
// removed from the stack.
StackItem peek() const;
// Prints the stack items sequentially ordered from the top to the bottom of
// the stack.
void print() const;
private:
// Override copy constructor and assignment operator in private so we can't
// use them.
DynamicStack(const DynamicStack& other) {}
DynamicStack operator=(const DynamicStack& other) {}
private:
// (Dynamic) array of stack items.
StackItem* items_;
// Maximum number of elements allowed in the stack.
int capacity_;
// Current number of elements in the stack.
int size_;
// Initial size of the array (i.e. the size in the constructor). This is used
// in pop() to determine if we should decrease the size.
int init_size_;
};
#endif
|
8add145f30bae8e0b833e3e4c7b20c532853d7f9
|
e3541ccbe0208b4680c0bb7065dd1a4827c6b443
|
/object.hpp
|
6b858bfa4565c3ceafae49dc8828e9f1a5237a34
|
[] |
no_license
|
henrikhasell/zombie
|
e665f9b45eb80b72b3c79ee103af9f51aa851a65
|
72b46860077aed55d4a382d6c12c93a8a6d3a183
|
refs/heads/master
| 2021-07-24T16:02:31.146162
| 2020-04-20T10:10:07
| 2020-04-20T10:10:07
| 151,676,302
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 525
|
hpp
|
object.hpp
|
#ifndef OBJECT_HPP
#define OBJECT_HPP
#include <Box2D/Box2D.h>
#include <iostream>
class Game;
class PhysicsObject
{
public:
PhysicsObject(Game *game, b2Body *body);
virtual ~PhysicsObject() = default;
virtual void onBeginContact(b2Body *other) = 0;
virtual void onEndContact(b2Body *other) = 0;
virtual void damage(float amount) { std::cout << "Damaging " << this << " by " << amount << std::endl; }
void remove();
protected:
Game *game;
b2Body *body;
private:
bool deleted;
};
#endif
|
a112814ff00f5cc4e683d205df1a687fa26f0e88
|
fcff7a2f81d8256363d5a1c37cffc5f6ad040132
|
/洛谷/简单DP/P1757.cpp
|
77ec8e768e306d07827802b704d3f5c7b91c3df7
|
[] |
no_license
|
HttoHu/cpp_acm_practice
|
d5401b09bce2d1774061ab385080e637ba95c568
|
c75106ea06aed7b4a39a54f4b1800b6066d9e3a4
|
refs/heads/master
| 2021-06-29T22:14:23.388608
| 2021-02-10T09:18:27
| 2021-02-10T09:18:27
| 218,294,314
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 741
|
cpp
|
P1757.cpp
|
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int M, N;
struct Bag
{
int w, v, team;
bool operator<(const Bag &b) const
{
return team < b.team;
}
} bags[1005];
int dp[1005][1005];
int main()
{
cin >> M >> N;
for (int i = 1; i <= N; i++)
cin >> bags[i].w >> bags[i].v >> bags[i].team;
sort(bags+1, bags + N+1);
for (int i = 1; i <= N; i++)
{
int k = bags[i].team;
for (int j = M; j >= 0; j--)
{
if (j < bags[i].w)
dp[j][k] = max(dp[j][k], dp[j][k - 1]);
else
dp[j][k] = max(dp[j][k], dp[j - bags[i].w][k - 1]+bags[i].v);
}
}
std::cout<<dp[M][bags[N].team];
}
|
a943a563ffe743e6c5c551172d522525b63b04a4
|
7032972f5ebbaf8ecb60da0a95bf16ea3e592633
|
/Barrage/bcg/inc/BCGPShellBreadcrumb.h
|
6980e4f1ccf57ff0205117e81aa507648a6f7c92
|
[
"Apache-2.0"
] |
permissive
|
luocheng610/Douyu_BarrageAssistant
|
817086abd75c58bfa68228697fa7aa786325ed82
|
b2ce4f49cc76e7c95b1383ecb1b5e37452b8da04
|
refs/heads/master
| 2021-01-22T11:32:06.879143
| 2019-12-15T03:40:46
| 2019-12-15T03:40:46
| 92,707,125
| 7
| 7
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,343
|
h
|
BCGPShellBreadcrumb.h
|
#if !defined(__BCGPSHELLBREADCRUMB_H)
#define __BCGPSHELLBREADCRUMB_H
//*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of BCGControlBar Library Professional Edition
// Copyright (C) 1998-2014 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "BCGPBreadcrumb.h"
class CBCGPShellList;
#ifndef BCGP_EXCLUDE_SHELL
class BCGCBPRODLLEXPORT CBCGPShellBreadcrumb : public CBCGPBreadcrumb
{
DECLARE_DYNAMIC(CBCGPShellBreadcrumb)
public:
CBCGPShellBreadcrumb();
virtual BOOL Create(const RECT& rect, CWnd* pParentWnd, UINT nID,
DWORD dwStyle = WS_CHILD | WS_TABSTOP | WS_VISIBLE | WS_BORDER |
BCCS_WANTRETURN | BCCS_EXTERNALBORDER | BCCS_INPLACEEDIT,
DWORD dwStyleEx = 0)
{
return CBCGPBreadcrumb::Create(rect, pParentWnd, nID, dwStyle, dwStyleEx);
}
void SetRelatedShellList(CBCGPShellList* pShellListControl);
CBCGPShellList* GetRelatedShellList () const
{ return m_pRelatedShellList; }
// Flags are same as in IShellFolder::EnumObjects
void SetShellFlags (DWORD dwFlags);
DWORD GetShellFlags () const
{
return m_dwShellFlags;
}
virtual CString GetItemPath (HBREADCRUMBITEM hItem, TCHAR delimiter = '\\') const;
virtual BOOL SelectPath(const CString& itemPath, TCHAR delimiter = '\\');
BOOL SelectShellItem (LPCITEMIDLIST lpidl);
protected:
DECLARE_MESSAGE_MAP();
afx_msg void DeleteItem (LPDELETEITEMSTRUCT pDeleteItem);
virtual void OnInitRoot ();
virtual void OnSelectionChanged (HBREADCRUMBITEM hSelectedItem);
virtual void GetItemChildrenDynamic (HBREADCRUMBITEM hParentItem);
static void ShellObjectToItemInfo (BREADCRUMBITEMINFO* pItemInfo, LPITEMIDLIST pidlCurrent, LPSHELLFOLDER pParentFolder, LPITEMIDLIST pidlParent);
virtual CEdit* CreateInplaceEdit(CWnd* pParent, const CRect& rect, UINT uiControlID);
private:
CBCGPShellList* m_pRelatedShellList;
DWORD m_dwShellFlags; // SHCONTF_* flags
};
#endif
#endif // __BCGPSHELLBREADCRUMB_H
|
7991fa6d6bbf4266a9446f06879bd2acec1792ef
|
cfac294ff3a871eede8949204b73a30dcb19a46d
|
/src/morphology/reference_dilate.cpp
|
4e33517bf915919f750cb78b5763233aaa3be943
|
[] |
no_license
|
unipv-ce18/aca-proj11
|
c1e6ac37fe51b0e776f22eb67d6641fff3976e40
|
a9055969ec95b59e601662561f7f4fe62475e33e
|
refs/heads/master
| 2021-07-15T09:30:48.434657
| 2020-06-07T09:46:39
| 2020-06-07T09:46:39
| 164,446,891
| 0
| 0
| null | 2020-06-07T09:46:40
| 2019-01-07T14:46:56
|
C++
|
UTF-8
|
C++
| false
| false
| 1,161
|
cpp
|
reference_dilate.cpp
|
#include "reference.h"
#include "StrEl.h"
#include <opencv2/core/core.hpp>
cv::Mat morph::dilate(const cv::Mat &image, const StrEl &strEl, const int nThreads) {
assert(image.type() == CV_8UC1);
cv::Size imSize = image.size();
cv::Mat output(imSize, CV_8UC1);
#pragma omp parallel for num_threads(nThreads) collapse(2) default(none) shared(image, imSize, strEl, output)
for (int y = 0; y < imSize.height; ++y) {
for (int x = 0; x < imSize.width; ++x) {
int val = 0;
for (int j = strEl.yMin(); j <= strEl.yMax(); ++j) {
for (int i = strEl.xMin(); i <= strEl.xMax(); ++i) {
int u = x + i;
int v = y + j;
if (v < 0 || v >= imSize.height) continue;
if (u < 0 || u >= imSize.width) continue;
if (!strEl.isSet(j, i)) continue;
int m = image.at<uint8_t>(v, u) + strEl.at(j, i);
if (m > val) val = m;
}
}
output.at<uint8_t>(y, x) = static_cast<uint8_t>(val < 0xFF ? val : 0xFF);
}
}
return output;
}
|
8e584fe714a7a9c51dc6bfb448ab3d38f3e5925b
|
1351f48d45c2c05e322c29c5f68da0d4590888c1
|
/uva2/CUET SELECT/11040.cpp
|
6d4578447e6cb9ed71e183e0561e41c888fec1c4
|
[] |
no_license
|
laziestcoder/Problem-Solvings
|
cd2db049c3f6d1c79dfc9fba9250f4e1d8c7b588
|
df487904876c748ad87a72a25d2bcee892a4d443
|
refs/heads/master
| 2023-08-19T09:55:32.144858
| 2021-10-21T20:32:21
| 2021-10-21T20:32:21
| 114,477,726
| 9
| 2
| null | 2021-06-22T15:46:43
| 2017-12-16T17:18:43
|
Python
|
UTF-8
|
C++
| false
| false
| 1,182
|
cpp
|
11040.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main ()
{
freopen("in.txt","r",stdin);
int t,i,j,k,a[10][10]={0},s;
cin >>t;
for(k=1; k<=t; k++)
{
for(i=1; i<=9; i+=2)
{
for(j=1; j<=i; j+=2)
cin>>a[i][j];
}
for(i=2; i<=9; i++)
{
for(j=1; j<i;j++)
{
if(i%2==0)
{
if(a[i-1][j]==(a[i][j]+a[i][j+1]))
continue;
else
{
s=a[i-1][j]/2;
if(a[i-1][j]%2!=0)
{
a[i][j]=s;
a[i][j+1]=s+1;
}
else
{
a[i][j]=s;
a[i][j+1]=s;
}
}
}
else
{
}
}
}
for(i=1; i<=9; i++)
{
for(j=1; j<=i;j++)
cout<<a[i][j]<<" " ;
cout <<"\n";
}
}
return 0;
}
|
d227e07a74b8e5052d7524435c2a8f350ae3ba8b
|
5bf7c4e5b61cf082311501a910121d8e0f941373
|
/matrix multiplication.cpp
|
e9f8d259e9c6c3280f116465c8c2688c86e9dce6
|
[] |
no_license
|
Abir-Naha/Simple-C-programs
|
5a3daf6ca802e918ac0dba34c40f5bf4aba29f21
|
ac0043d6c3eb79b0b281e08918133c9a84e311ac
|
refs/heads/main
| 2023-03-01T21:55:34.045273
| 2021-02-10T17:04:54
| 2021-02-10T17:04:54
| 337,763,410
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,840
|
cpp
|
matrix multiplication.cpp
|
// Given two matrics A and B with their respective order our task is to multiply those matrics and produce C=AB
#include<stdio.h>
#include<conio.h>
main()
{
int a1,a2,b1,b2; //matrix A is of order a1xa2 and B is of order b1xb2
printf("\n Enter the order of the first matrix A: \n"); //taking user defined values of order of A
printf("\n rows in A: ");
scanf("%d", &a1);
printf("\n columns in A: ");
scanf("%d", &a2);
printf("\n Enter the order of the second matrix B: \n"); //taking user defined values of order of B
printf("\n rows in B: ");
scanf("%d", &b1);
printf("\n columns in B: ");
scanf("%d", &b2);
float A[a1][a2], B[b1][b2], C[a1][b2]; //we are multiplying matrix A with matrix B and the resultant matrix is C
if(a2!=b1)
printf("\nMatrix Multiplication not possible!! "); //to multiply A with B, number of coulmns in A must be equal to numbers of rows in B
else
{
printf("\n Enter the elements of matrix A rowwise : \n"); //taking values into matrix A
for(int i=0; i<a1; i++)
{
for(int j=0; j<a2; j++)
{
printf("\n A[%d][%d] : ",i+1,j+1);
scanf("%f",&A[i][j]);
}
}
printf("\n Enter the elements of matrix B rowwise : \n"); //taking values into matrix B
for(int i=0; i<b1; i++)
{
for(int j=0; j<b2; j++)
{
printf("\n B[%d][%d] : ",i+1,j+1);
scanf("%f",&B[i][j]);
}
}
printf("\n The resultant product matrix C=AB is of order %d X %d and C looks like: \n\n",a1,b2); //calculating product of A with B
for(int i=0; i<a1; i++)
{
for(int j=0; j<b2; j++)
{
C[i][j] = 0;
for(int k=0; k<a2; k++)
C[i][j]+= A[i][k] * B[k][j];
printf("\t %.1f",C[i][j]);
}
printf("\n");
}
}
getch();
}
|
5b661592b34253820a50227e28221fc9db9a6bfa
|
9d5619eb306c24ce3cfe2b0fb54d17c54f04bc6a
|
/p55/source/std/ming.cpp
|
806dd0547b65da0edba9ada61dc5521c138fd733
|
[] |
no_license
|
cjsoft/lnoi
|
829da39bd06be7fb7c841c4bff0c6a7b3e6b72f6
|
d7ef6f5346db8ba96f1ca446d68bcb51452a12d3
|
refs/heads/master
| 2020-12-30T23:34:35.387799
| 2016-04-22T00:05:04
| 2016-04-22T00:05:04
| 55,044,245
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,748
|
cpp
|
ming.cpp
|
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
using namespace std;
const int BUF_SIZE = 30;
char buf[BUF_SIZE], *buf_s = buf, *buf_t = buf + 1;
#define PTR_NEXT() \
{ \
buf_s ++; \
if (buf_s == buf_t) \
{ \
buf_s = buf; \
buf_t = buf + fread(buf, 1, BUF_SIZE, stdin); \
} \
}
#define readint(_n_) \
{ \
while (*buf_s != '-' && !isdigit(*buf_s)) \
PTR_NEXT(); \
bool register _nega_ = false; \
if (*buf_s == '-') \
{ \
_nega_ = true; \
PTR_NEXT(); \
} \
int register _x_ = 0; \
while (isdigit(*buf_s)) \
{ \
_x_ = _x_ * 10 + *buf_s - '0'; \
PTR_NEXT(); \
} \
if (_nega_) \
_x_ = -_x_; \
(_n_) = (_x_); \
}
const int maxn=100010;
const int maxp=maxn*40;
int n,m,num,depth[2][maxn],f[2][maxn],l[maxn],r[maxn],en,wmt,root[maxn];
struct edge
{
int e;
edge *nextnext;
}*v[maxn],ed[maxn];
void add_edge(int s,int e)
{
en++;
ed[en].nextnext=v[s];v[s]=ed+en;v[s]->e=e;
}
void dfs(int o,int p)
{
num++;
if (o) l[p]=num;
for (edge *e=v[p];e;e=e->nextnext)
{
depth[o][e->e]=depth[o][p]+1;
dfs(o,e->e);
}
if (o) r[p]=num;
}
struct node
{
int l,r,col;
node()
{
l=r=col=0;
}
}z[maxp];
int newnode(int p)
{
wmt++;
z[wmt].l=z[p].l;
z[wmt].r=z[p].r;
z[wmt].col=z[p].col;
return wmt;
}
int modify(int p,int l,int r,int nowl,int nowr,int c)
{
int pp=newnode(p);
if (nowl<=l && r<=nowr)
{
z[pp].col=c;
return pp;
}
int m=(l+r)>>1;
if (nowl<=m) z[pp].l=modify(z[p].l,l,m,nowl,nowr,c);
if (m<nowr) z[pp].r=modify(z[p].r,m+1,r,nowl,nowr,c);
return pp;
}
int query(int p,int l,int r,int xp)
{
if (!p) return 0;
int m=(l+r)>>1;
int ans=z[p].col;
int res;
if (xp<=m) res=query(z[p].l,l,m,xp);
else res=query(z[p].r,m+1,r,xp);
if (ans>res) return ans;
else return res;
}
int main()
{
readint(n);
readint(m);
for (int a=2;a<=n;a++)
{
readint(f[0][a]);
}
for (int a=2;a<=n;a++)
{
readint(f[1][a]);
add_edge(f[1][a],a);
}
depth[1][1]=1;
num=0;
dfs(1,1);
en=0;
memset(v,0,sizeof(v));
for (int a=2;a<=n;a++)
add_edge(f[0][a],a);
depth[0][1]=1;
dfs(0,1);
wmt=0;
for (int a=1;a<=n;a++)
root[a]=modify(root[f[0][a]],1,n,l[a],r[a],a);
for (int a=1,ans=0;a<=m;a++)
{
int p1,p2;
readint(p1);
readint(p2);
p1=(p1+ans)%n+1;
p2=(p2+ans)%n+1;
ans=query(root[p1],1,n,l[p2]);
printf("%d %d %d\n",ans,depth[0][p1]-depth[0][ans]+1,depth[1][p2]-depth[1][ans]+1);
}
return 0;
}
|
1b202da9c924ad62aa3118257a1c331566e3f1a7
|
93091cffa5a9d77abbae0f2b3ee6437eba958c79
|
/dataline/setX.cc
|
ea8db082b73a3732f74cb1849291f9c0e50f6f89
|
[] |
no_license
|
paolotof/eyeTrackingProcessing
|
c75138ca3a3d04cb8766a0cf5ac7988f46da27a7
|
f21143b0d7a05238df702c90c75cfc82444d2885
|
refs/heads/master
| 2020-12-24T14:10:39.774104
| 2018-03-13T10:01:08
| 2018-03-13T10:01:08
| 28,056,028
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 125
|
cc
|
setX.cc
|
/* this is a template to create other stuff */
#include "dataline.ih"
void Dataline::setX(double xpos)
{
d_xpos = xpos;
}
|
06abef3476fa7311384d5fbe51cf063b508e4169
|
f3facba9b8fc4e0c34ebb723f70556063488696f
|
/src/Velocity/velocityvolumeconversion.cc
|
28f1131da2dd58acbfc89a4feaf0f54cec49c7c6
|
[] |
no_license
|
annequeentina/OpendTect
|
9af07b099d8e738cf0bfefbd4f4c77fb8db9d370
|
b728451cb04b8a3f3ec0355c5317ef4ebf62cb3f
|
refs/heads/master
| 2021-01-02T08:59:20.285242
| 2017-08-02T11:52:16
| 2017-08-02T11:52:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,794
|
cc
|
velocityvolumeconversion.cc
|
/*+
________________________________________________________________________
(C) dGB Beheer B.V.; (LICENSE) http://opendtect.org/OpendTect_license.txt
Author: K. Tingdahl
Date: Dec 2009
________________________________________________________________________
-*/
#include "velocityvolumeconversion.h"
#include "binidvalset.h"
#include "ioobj.h"
#include "ioobjtags.h"
#include "seisprovider.h"
#include "seisselectionimpl.h"
#include "seistrc.h"
#include "seistrctr.h"
#include "seiswrite.h"
#include "seispacketinfo.h"
#include "sorting.h"
#include "uistrings.h"
#include "varlenarray.h"
#include "velocitycalc.h"
namespace Vel
{
const char* VolumeConverter::sKeyInput() { return sKey::Input(); }
const char* VolumeConverter::sKeyOutput() { return sKey::Output(); }
VolumeConverter::VolumeConverter( const IOObj& input, const IOObj& output,
const TrcKeySampling& ranges,
const VelocityDesc& desc )
: tks_( ranges )
, veloutpdesc_( desc )
, input_( input.clone() )
, output_( output.clone() )
, provider_( 0 )
, writer_( 0 )
, sequentialwriter_(0)
{
uiRetVal uirv;
provider_ = Seis::Provider::create( input_->key(), &uirv );
if ( !provider_ )
{ errmsg_ = uirv; return; }
totalnr_ = provider_->totalNr();
provider_->setSelData( new Seis::RangeSelData(tks_) );
}
VolumeConverter::~VolumeConverter()
{
delete input_;
delete output_;
delete writer_;
delete sequentialwriter_;
delete provider_;
}
bool VolumeConverter::doFinish( bool res )
{
deleteAndZeroPtr( provider_ );
if ( !sequentialwriter_->finishWrite() )
res = false;
deleteAndZeroPtr( sequentialwriter_ );
deleteAndZeroPtr( writer_ );
return res;
}
bool VolumeConverter::doPrepare( int nrthreads )
{
if ( !errmsg_.getFullString().isEmpty() )
return false;
if ( !input_ || !output_ )
{
errmsg_ = tr("Either input or output cannot be found");
return false;
}
delete writer_;
writer_ = 0;
if ( !GetVelocityTag( *input_, velinpdesc_ ) )
{
errmsg_ = tr("Cannot read velocity information on input.");
return false;
}
if ( !SetVelocityTag( *output_, veloutpdesc_ ) )
{
errmsg_ = tr("Cannot write velocity information on output");
return false;
}
if ( ( velinpdesc_.type_ != VelocityDesc::Interval &&
velinpdesc_.type_ != VelocityDesc::RMS &&
velinpdesc_.type_ != VelocityDesc::Avg ) ||
( veloutpdesc_.type_ != VelocityDesc::Interval &&
veloutpdesc_.type_ != VelocityDesc::RMS &&
veloutpdesc_.type_ != VelocityDesc::Avg ) ||
velinpdesc_.type_ == veloutpdesc_.type_ )
{
errmsg_ = tr("Input/output velocities are not interval, RMS, or Avg "
"or are identical.");
return false;
}
//Check input Vel
if ( !provider_ )
{
uiRetVal uirv;
provider_ = Seis::Provider::create( input_->key(), &uirv );
if ( !provider_ )
{ errmsg_ = uirv; return false; }
provider_->setSelData( new Seis::RangeSelData(tks_) );
}
writer_ = new SeisTrcWriter( output_ );
sequentialwriter_ = new SeisSequentialWriter( writer_ );
return true;
}
bool VolumeConverter::doWork( od_int64, od_int64, int threadidx )
{
char res = 1;
SeisTrc trc;
lock_.lock();
res = getNewTrace( trc, threadidx );
lock_.unLock();
ArrPtrMan<float> owndata = 0;
SeisTrcValueSeries inputvs( trc, 0 );
const float* inputptr = inputvs.arr();
if ( !inputptr )
{
owndata = new float[trc.size()];
inputptr = owndata.ptr();
}
while ( res==1 )
{
if ( !shouldContinue() )
return false;
if ( owndata )
{
for ( int idx=0; idx<trc.size(); idx++ )
owndata[idx] = inputvs.value( idx );
}
SeisTrc* outputtrc = new SeisTrc( trc );
float* outptr = (float*) outputtrc->data().getComponent( 0 )->data();
const SamplingData<double>& sd = trc.info().sampling_;
TypeSet<float> timesamps;
const float sampstep = trc.info().sampling_.step;
for ( int idx=0; idx<trc.size(); idx++ )
timesamps += trc.startPos() + idx * sampstep;
float* interptr = 0;
if ( velinpdesc_.type_ != VelocityDesc::Interval )
{
if ( veloutpdesc_ != VelocityDesc::Interval )
{
mTryAlloc(interptr,float[trc.size()]);
if ( !interptr )
{
errmsg_ = tr("Not enough memory");
delete outputtrc;
outputtrc = 0;
return false;
}
}
if ( velinpdesc_.type_ == VelocityDesc::Avg )
{
if ( !computeVint( inputptr, timesamps[0], timesamps.arr(),
trc.size(), interptr ? interptr : outptr ) )
{
delete outputtrc;
outputtrc = 0;
}
}
else
{
if ( !computeDix( inputptr, sd, trc.size(),
interptr ? interptr :outptr ) )
{
delete outputtrc;
outputtrc = 0;
}
}
}
if ( veloutpdesc_.type_ == VelocityDesc::Avg )
{
if ( !computeVavg( interptr ? interptr : inputptr, timesamps[0],\
timesamps.arr(), trc.size(), outptr ) )
{
delete outputtrc;
outputtrc = 0;
}
}
else if ( veloutpdesc_.type_ == VelocityDesc::RMS )
{
if ( !computeVrms( interptr ? interptr : inputptr, sd, trc.size(),
outptr ) )
{
delete outputtrc;
outputtrc = 0;
}
}
delete [] interptr;
//Process trace
sequentialwriter_->submitTrace( outputtrc, true );
addToNrDone( 1 );
Threads::MutexLocker lock( lock_ );
res = getNewTrace( trc, threadidx );
}
return res==0;
}
char VolumeConverter::getNewTrace( SeisTrc& trc, int threadidx )
{
if ( !provider_ )
return 0;
const uiRetVal uirv = provider_->getNext( trc );
if ( !uirv.isOK() )
{
if ( isFinished(uirv) )
return 0;
errmsg_ = uirv;
return -1;
}
sequentialwriter_->announceTrace( trc.info().binID() );
delete provider_;
provider_ = 0;
return 1;
}
} // namespace Vel
|
68bef380d3a126c1b3b2ed1e2c300241c2468016
|
9209a62997622a50e1520048381ac6651b32030a
|
/hprof/test/types/test_objects_array.h
|
f7e9fa4ec33795cc2edc3d73b537dbce6648a370
|
[
"Apache-2.0"
] |
permissive
|
pvoid/android-hprof-browser
|
c88529591e97c10c98a10ad90a6f8b9107ce1288
|
548d5429becde0bbb746ecf71f505dd1b70d8547
|
refs/heads/master
| 2021-09-25T17:03:36.456763
| 2017-11-23T09:27:02
| 2017-11-23T09:27:02
| 103,631,792
| 1
| 0
|
Apache-2.0
| 2018-10-24T11:15:19
| 2017-09-15T08:09:52
|
C++
|
UTF-8
|
C++
| false
| false
| 4,560
|
h
|
test_objects_array.h
|
///
/// Copyright 2017 Dmitry "PVOID" Petukhov
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
#pragma once
#include <gtest/gtest.h>
#include "types/objects_array.h"
using namespace hprof;
TEST(objects_array_info_impl_t, When_CreateWithClassIdc0c1af_Expect_ClassIdReturnsc0c1af) {
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 0, 0);
ASSERT_EQ(0xc0c1af, instance->class_id());
}
TEST(objects_array_info_impl_t, When_CreateWithLength10_Expect_LenhthReturnsc10) {
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 10, 0);
ASSERT_EQ(10, instance->length());
}
TEST(objects_array_info_impl_t, When_EmptyArray_Expect_BeginEqualsEns) {
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 0, 0);
ASSERT_EQ(std::end(*instance), std::begin(*instance));
}
TEST(objects_array_info_impl_t, When_NotEmpty_Expect_BeginAlwaysEquals) {
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 2, 0);
ASSERT_EQ(std::begin(*instance), std::begin(*instance));
}
TEST(objects_array_info_impl_t, When_NotEmpty_Expect_EndAlwaysEquals) {
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 2, 0);
ASSERT_EQ(std::end(*instance), std::end(*instance));
}
TEST(objects_array_info_impl_t, When_NotEmpty_Expect_BeginIsNotEqualEnd) {
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 2, 0);
ASSERT_NE(std::begin(*instance), std::end(*instance));
}
TEST(objects_array_info_impl_t, When_NotEmpty_Expect_IterateOverData) {
u_int8_t data[] = { 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x20 };
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 2, sizeof(data));
std::memcpy(instance->data(), data, sizeof(data));
auto it = std::begin(*instance);
ASSERT_NE(std::end(*instance), it);
ASSERT_EQ(0x0F, *it);
ASSERT_NE(std::end(*instance), ++it);
ASSERT_EQ(0x20, *(it.operator->()));
ASSERT_EQ(std::end(*instance), ++it);
}
TEST(objects_array_info_impl_t, When_AccessByValidIndex_Expect_ValidIterator) {
u_int8_t data[] = { 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x20 };
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 2, sizeof(data));
std::memcpy(instance->data(), data, sizeof(data));
auto item = (*instance)[1];
ASSERT_NE(std::end(*instance), item);
ASSERT_EQ(0x20, *item);
}
TEST(objects_array_info_impl_t, When_AccessByInvalidIndex_Expect_EndIterator) {
u_int8_t data[] = { 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x20 };
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 2, sizeof(data));
std::memcpy(instance->data(), data, sizeof(data));
auto item = (*instance)[10];
ASSERT_EQ(std::end(*instance), item);
}
TEST(objects_array_info_impl_t, When_HasLinkToClass_Expect_HasLinksReturnsTypeInstance) {
u_int8_t data[] = { 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x20 };
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 2, sizeof(data));
std::memcpy(instance->data(), data, sizeof(data));
ASSERT_EQ(link_t::TYPE_INSTANCE, instance->has_link_to(0xc0c1af));
}
TEST(objects_array_info_impl_t, When_HasLinkToObject_Expect_HasLinksReturnsTypeOwnership) {
u_int8_t data[] = { 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x20 };
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0xc0c1af, 2, sizeof(data));
std::memcpy(instance->data(), data, sizeof(data));
ASSERT_EQ(link_t::TYPE_OWNERSHIP, instance->has_link_to(0x20));
}
TEST(objects_array_info_impl_t, When_HasLinkToClassAndObject_Expect_HasLinksReturnsTypeOwnershipAndInstance) {
u_int8_t data[] = { 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x20 };
auto instance = objects_array_info_impl_t::create(4, 0xc0f060, 0x20, 2, sizeof(data));
std::memcpy(instance->data(), data, sizeof(data));
ASSERT_EQ(link_t::TYPE_OWNERSHIP | link_t::TYPE_INSTANCE, instance->has_link_to(0x20));
}
|
a06d536a91d0ea66c4a0446aec561ceecc2cb529
|
0c0af780e498f93c700b06f649b864d3e75fd56f
|
/src/Once.cpp
|
0a65141663c00c8c824323d4665c5e392548f9e2
|
[] |
no_license
|
wlaub/vcv
|
fdb338b69fcfd33c1a1f011837b6bb831864254f
|
9d52e49ba0a92a51b733218e02202549b7fb4bf2
|
refs/heads/main
| 2022-12-22T19:35:36.824217
| 2022-12-18T21:54:59
| 2022-12-18T21:54:59
| 117,328,087
| 10
| 4
| null | 2022-02-06T17:54:06
| 2018-01-13T08:41:12
|
C++
|
UTF-8
|
C++
| false
| false
| 12,160
|
cpp
|
Once.cpp
|
#include "TechTechTechnologies.hpp"
#include "PngModule.hpp"
#include <numeric>
#define N 6
struct GateState {
int pending = 0;
int value = 0;
json_t* to_json()
{
json_t* result = json_object();
json_object_set_new(result, "pending", json_integer(pending));
json_object_set_new(result, "value", json_integer(value));
return result;
}
void from_json(json_t* rootJ)
{
if(rootJ == 0) return;
json_t* temp;
temp = json_object_get(rootJ, "pending");
if(temp) pending = json_integer_value(temp);
temp = json_object_get(rootJ, "value");
if(temp) value = json_integer_value(temp);
}
};
struct ButtonMode{
enum Mode {
TOGGLE_MODE,
TRIGGER_MODE,
PASS_MODE,
PASS_TRIGGER_MODE,
MODES_LEN,
};
int mode = TOGGLE_MODE;
json_t* to_json()
{
return json_integer(mode);
}
void from_json(json_t* rootJ)
{
if(rootJ) mode = json_integer_value(rootJ);
}
};
struct EdgeMode{
enum Mode {
RISING_MODE,
FALLING_MODE,
BOTH_MODE,
MODES_LEN,
};
int mode = RISING_MODE;
json_t* to_json()
{
return json_integer(mode);
}
void from_json(json_t* rootJ)
{
if(rootJ) mode = json_integer_value(rootJ);
}
};
struct Once : PngModule {
enum ParamId {
ENABLE_PARAM,
BUTTON_PARAM,
PARAMS_LEN = BUTTON_PARAM+N
};
enum InputId {
CLK_INPUT,
INPUTS_LEN
};
enum OutputId {
GATE_OUTPUT,
OUTPUTS_LEN = GATE_OUTPUT+N
};
enum LightId {
ENABLE_LIGHT,
BUTTON_LIGHT = ENABLE_LIGHT+3,
LIGHTS_LEN = BUTTON_LIGHT+N*3
};
dsp::SchmittTrigger clk_trigger, nclk_trigger, en_trigger;
dsp::PulseGenerator clk_pulse, vis_pulse;
dsp::SchmittTrigger butt_trigger[N];
struct GateState states[N];
int enabled = 1;
float blink_counter = 0;
int blink = 0;
struct ButtonMode button_mode;
struct EdgeMode edge_mode;
Once() {
config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN);
configButton(ENABLE_PARAM, "Enable");
for(int i = 0; i < N; ++i)
{
configOutput(GATE_OUTPUT+i, "Gate");
configButton(BUTTON_PARAM+i, "Activate");
}
configInput(CLK_INPUT, "Clock");
}
void set_light(int index, float r, float g, float b)
{
lights[index].setBrightness(r);
lights[index+1].setBrightness(g);
lights[index+2].setBrightness(b);
}
void process(const ProcessArgs& args) override {
float deltaTime = args.sampleTime;
/*
blink_counter += deltaTime;
if(blink_counter > 0.5)
{
blink_counter -= 0.5;
blink = 1-blink;
}
*/
/* Handle button presses */
for(int i = 0; i < N; ++i)
{
if(butt_trigger[i].process(params[BUTTON_PARAM+i].getValue()))
{
++states[i].pending;
states[i].pending %= 2;
}
}
if(en_trigger.process(params[ENABLE_PARAM].getValue()))
{
enabled = 1 - enabled;
}
/* Handle clock edges */
float clk_value = inputs[CLK_INPUT].getVoltage();
int clk = clk_value > 0.5? 1:0;
int rclk = clk_trigger.process(clk_value);
int fclk = nclk_trigger.process(!clk_trigger.state);
int clk_trigger_value = 0;
if(edge_mode.mode != EdgeMode::FALLING_MODE)
{
clk_trigger_value |= rclk;
}
if(edge_mode.mode != EdgeMode::RISING_MODE)
{
clk_trigger_value |= fclk;
}
if(clk_trigger_value && enabled)
{
vis_pulse.trigger(0.1);
clk_pulse.trigger();
for(int i = 0; i < N; ++i)
{
if(states[i].pending == 1)
{
states[i].pending = 0;
states[i].value = 1 - states[i].value;
}
}
}
int clk_pulse_value = clk_pulse.process(args.sampleTime);
int vis_pulse_value = vis_pulse.process(args.sampleTime);
for(int i = 0; i < N; ++i)
{
float out_val = 0;
if(button_mode.mode == ButtonMode::TRIGGER_MODE)
{
if(states[i].value)
{
out_val = clk_pulse_value;
}
if(clk_pulse_value == 0)
{
states[i].value = 0;
}
}
else if(button_mode.mode == ButtonMode::PASS_TRIGGER_MODE)
{
if(states[i].value)
{
out_val = clk_pulse_value;
}
}
else if(button_mode.mode == ButtonMode::PASS_MODE)
{
if(states[i].value)
{
out_val = clk;
}
}
else
{
out_val = states[i].value;
}
outputs[GATE_OUTPUT+i].setVoltage(out_val*5);
}
/* Handle lights */
if(enabled)
{
if(button_mode.mode == ButtonMode::TOGGLE_MODE)
{
set_light(ENABLE_LIGHT, clk,1,clk);
}
else if(button_mode.mode == ButtonMode::TRIGGER_MODE)
{
set_light(ENABLE_LIGHT, vis_pulse_value, 1, vis_pulse_value);
}
else if(button_mode.mode == ButtonMode::PASS_MODE)
{
set_light(ENABLE_LIGHT, clk, clk, 1);
}
else if(button_mode.mode == ButtonMode::PASS_TRIGGER_MODE)
{
set_light(ENABLE_LIGHT, vis_pulse_value, vis_pulse_value, 1);
}
}
else
{
set_light(ENABLE_LIGHT, 0,0,0);
}
for(int i = 0; i < N; ++i)
{
int idx = BUTTON_LIGHT+3*i;
if(states[i].pending == 1)
{
if(states[i].value == 0)
{
set_light(idx, 0, 1, 0);
}
else
{
set_light(idx, 0, 0, 1);
}
}
else
{
if(states[i].value == 1)
{
set_light(idx, 1, 1, 1);
}
else
{
set_light(idx, 0, 0, 0);
}
}
}
}
json_t* dataToJson() override {
json_t* rootJ = json_object();
load_panel(rootJ);
json_object_set_new(rootJ, "enabled", json_integer(enabled));
json_t* array = json_array();
json_object_set_new(rootJ, "states", array);
for(int i = 0; i < N; ++i)
{
json_array_append(array, states[i].to_json());
}
json_object_set_new(rootJ, "button_mode", button_mode.to_json());
json_object_set_new(rootJ, "edge_mode", edge_mode.to_json());
return rootJ;
}
void dataFromJson(json_t* rootJ) override {
save_panel(rootJ);
json_t* temp;
temp = json_object_get(rootJ, "enabled");
if(temp) enabled = json_integer_value(temp);
json_t* array = json_object_get(rootJ, "states");
if(array)
{
for(int i = 0; i < N; ++i)
{
temp = json_array_get(array, i);
states[i].from_json(temp);
}
}
button_mode.from_json(json_object_get(rootJ, "button_mode"));
edge_mode.from_json(json_object_get(rootJ, "edge_mode"));
}
};
#define GRIDX(x) 15.24*(x-0.5)
#define GRIDY(y) 15.24*(y)+3.28
#define GRID(x,y) GRIDX(x), GRIDY(y)
struct OnceWidget : PngModuleWidget {
void button_mode_menu(Menu* menu, Once* module)
{
menu->addChild(createMenuLabel("Button Mode"));
struct ModeItem : MenuItem {
Once* module;
int mode;
void onAction(const event::Action& e) override {
module->button_mode.mode = mode;
}
};
std::string mode_names[ButtonMode::MODES_LEN];
mode_names[ButtonMode::TOGGLE_MODE] = "Toggle Gate";
mode_names[ButtonMode::TRIGGER_MODE] = "Pulse";
mode_names[ButtonMode::PASS_MODE] = "Pass Clock";
mode_names[ButtonMode::PASS_TRIGGER_MODE] = "Pulse on Clock";
int mode_sequence[ButtonMode::MODES_LEN] = {ButtonMode::TOGGLE_MODE, ButtonMode::TRIGGER_MODE, ButtonMode::PASS_MODE, ButtonMode::PASS_TRIGGER_MODE};
for(int i = 0; i < ButtonMode::MODES_LEN; ++i)
{
int idx = mode_sequence[i];
ModeItem* item = createMenuItem<ModeItem>(mode_names[idx]);
item->module = module;
item->mode = idx;
item->rightText = CHECKMARK(module->button_mode.mode == idx);
menu->addChild(item);
}
}
void edge_mode_menu(Menu* menu, Once* module)
{
menu->addChild(createMenuLabel("Clock Mode"));
struct ModeItem : MenuItem {
Once* module;
int mode;
void onAction(const event::Action& e) override {
module->edge_mode.mode = mode;
}
};
std::string mode_names[EdgeMode::MODES_LEN];
mode_names[EdgeMode::RISING_MODE] = "Rising Edge";
mode_names[EdgeMode::FALLING_MODE] = "Falling Edge";
mode_names[EdgeMode::BOTH_MODE] = "Both Edges";
int mode_sequence[EdgeMode::MODES_LEN] = {EdgeMode::RISING_MODE, EdgeMode::FALLING_MODE, EdgeMode::BOTH_MODE};
for(int i = 0; i < EdgeMode::MODES_LEN; ++i)
{
int idx = mode_sequence[i];
ModeItem* item = createMenuItem<ModeItem>(mode_names[idx]);
item->module = module;
item->mode = idx;
item->rightText = CHECKMARK(module->edge_mode.mode == idx);
menu->addChild(item);
}
}
void appendContextMenu(Menu* menu) override {
Once* module = dynamic_cast<Once*>(this->module);
menu->addChild(new MenuEntry);
panel_select_menu(menu, module);
button_mode_menu(menu, module);
edge_mode_menu(menu, module);
}
OnceWidget(Once* module) {
setModule(module);
init_panels("Once");
addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
for(int i = 0; i < N; ++i)
{
addParam(createParamCentered<LEDBezel>(
mm2px(Vec(GRID(1, i+2))), module, Once::BUTTON_PARAM+i));
addChild(createLightCentered<LEDBezelLight<RedGreenBlueLight>>(
mm2px(Vec(GRID(1, i+2))), module, Once::BUTTON_LIGHT+3*i));
addOutput(createOutputCentered<PJ301MPort>(
mm2px(Vec(GRID(2, i+2))), module, Once::GATE_OUTPUT+i));
}
addInput(createInputCentered<PJ301MPort>(
mm2px(Vec(GRID(1,1))), module, Once::CLK_INPUT));
addParam(createParamCentered<LEDBezel>(
mm2px(Vec(GRID(2, 1))), module, Once::ENABLE_PARAM));
addChild(createLightCentered<LEDBezelLight<RedGreenBlueLight>>(
mm2px(Vec(GRID(2, 1))), module, Once::ENABLE_LIGHT));
}
};
Model* modelOnce = createModel<Once, OnceWidget>("Once");
|
5d2e05c5bc20a926fb77ef97564d92c21793a01d
|
e382c5268e7056012f637170229638a2f327b54f
|
/Strings/SearchSubstring.cpp
|
ea198a0778888733554a470dbf43e15d630d5b01
|
[] |
no_license
|
ParthPan7/Data-Structures-And-Algorithms---Problem-Solving
|
9847947499d4cd9a97dfb260821e395b54d4a207
|
dd520ae482b9772051a063cff48c041cc6a65042
|
refs/heads/main
| 2023-06-01T17:11:46.179839
| 2021-06-24T02:55:40
| 2021-06-24T02:55:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 772
|
cpp
|
SearchSubstring.cpp
|
/*
strstr - locate a substring ( needle ) in a string ( haystack ).
reference - https://www.interviewbit.com/problems/implement-strstr/
*/
int strStr(const string A, const string B)
{
int start = -1;
for (int i=0; i<A.length(); ++i)
{
if (A[i] == B[0])
{
start = i;
int bCounter = 0;
int aCounter = i;
while ( B[bCounter]!='\0' && A[aCounter] == B[bCounter] )
{
if ( aCounter > A.length() ) { return -1; }
aCounter++; bCounter++;
}
if (bCounter == B.size())
{
return start;
}
else
{
start = -1;
}
}
}
return start;
}
|
1ec6ed4df78e71c5cb7cf47c9b4b90536d4a1010
|
6d1e4e47266e1d6b818cbc3e19c42407fa9c6644
|
/SuffixArray3.cpp
|
be696d497a96a456599c374a78a33e26da0a358e
|
[] |
no_license
|
ishan16696/APS_assignment2
|
27e9188c6fc740ffe4c1ce1de7f096f36a67c8d7
|
c4ee62b8ff72e657471ce455cdcb315ecfceee51
|
refs/heads/master
| 2020-04-01T00:34:15.849875
| 2019-09-12T19:36:48
| 2019-09-12T19:36:48
| 152,702,672
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,575
|
cpp
|
SuffixArray3.cpp
|
#include<bits/stdc++.h>
using namespace std;
//******************************************************* Suffix Array ************************************************************************
struct node{
int index;
int curRank;
int nextRank;
};
bool comp(node r,node f){ // comparator function used for sorting
if(r.curRank==f.curRank){
if(r.nextRank <f.nextRank){
return true;
}
else
return false;
}
if(r.curRank < f.curRank)
return true;
else
return false;
}
int *calcSuffixArr(string s,int n){
transform(s.begin(), s.end(), s.begin(), ::tolower); // convering it into the lowerCase()
int len=s.length();
char input[len+1];
strcpy(input,s.c_str());// converting string to char array in the disguise of copy
node suffix[n];
//all suffixes have to be sorted according to first 2 characters.
for(int i=0;i<n;i++)
{
suffix[i].index=i;
suffix[i].curRank=input[i]-'a';
suffix[i].nextRank=((i+1)<n )? (input[i+1]-'a'): -1 ;
}
sort(suffix,suffix+n,comp); // O(nlogn)
int pointer[n]; //This array is needed to get the index in suffixes[] from original index
for(int k=4;k<2*n;k=k*2)
{
int rank = 0;
int prev_rank = suffix[0].curRank;
suffix[0].curRank = rank;
pointer[suffix[0].index] = 0;
// this is for Current Rank
for(int i=1;i<n;i++)
{
if(suffix[i].curRank==prev_rank && suffix[i].nextRank==suffix[i-1].nextRank)
{
prev_rank=suffix[i].curRank;
suffix[i].curRank=rank; // same rank
}
else
{
// if differ by prev rank then increment the rank
prev_rank = suffix[i].curRank;
rank++; // increment the rank
suffix[i].curRank=rank;
}
pointer[suffix[i].index] = i;
}
// this is for nextRank
for(int i=0;i<n;i++)
{
//to fill the next rank
int next_Index=suffix[i].index+k/2;
suffix[i].nextRank=(next_Index< n) ? suffix[pointer[next_Index]].curRank : -1;
}
sort(suffix,suffix+n,comp);
}
int *sufxArray = new int[n];
for (int i = 0; i < n; i++)
sufxArray[i] = suffix[i].index;
// Return the suffix array
return sufxArray;
}
//*************************************************************** Making if LCP(longest common prefix)*************************************
//=============================================================== using Kasai's algorothm ===================================================
int * longestCommonPrefix(string s,int n){
int *sufArray = calcSuffixArr(s,n);
int *result =new int[n];
int *invSuf=new int[n];
for(int i=0;i<n;i++){
invSuf[sufArray[i]]=i; // taking the inverse of
}
int k=0;
// result[invSuf[0]]=k;
for(int i=0;i<n;i++){
int j;// to hold the index for next substring which are next to subtring of i=0;
//base condition (applies on last element)
if(invSuf[i]==n-1){
k=0;
continue;
}
j=sufArray[invSuf[i]+1];// index of next subtring of sufArray(i.e sorted substring)
while(j+k < n && j+k < n&& s[i+k]==s[j+k])
k++;
result[invSuf[i]]=k;
if(k>0)
k--;// doubt
}
return result;
}
//*********************************************************************************************************************************************
//rotate to get lcp of suffix i to i-1 ; not from i to i+1;
int *rotate(int *lcp,int n){
std::vector<int> v;
for(int i=0;i<n;i++)
v.push_back(lcp[i]);
for(int i=1;i<v.size();i++){
lcp[i]=v[i-1];
}
lcp[0]=0;
return lcp;
}
//*************************************************************** Driver() function *************************************************************
int main()
{
string s;
cin >> s;// input string
string rev=s;
int len=s.size(); // original string length
int len_of_palindrome=0;
int position=0;
reverse(rev.begin(),rev.end()); // reverse the string
s=s+"#"+rev;
int *sufArray=calcSuffixArr(s,s.size()); // suffix array
int *lcp = longestCommonPrefix(s,s.size()); // lcp
/*for (int i = 0; i < s.size(); i++)
cout << lcp[i] << " "; */
cout <<endl;
/*for (int i = 0; i < s.size(); i++)
cout << sufArray[i] << " ";
cout << "after rotation" <<endl;*/
lcp=rotate(lcp,s.size());
/* cout << endl;
for (int i = 0; i < s.size(); i++)
cout << lcp[i] << " "; */
for(int i=1;i<s.size();i++)
{
if((lcp[i]>len_of_palindrome))
{
if((sufArray[i-1] < len && sufArray[i]>len ) || (sufArray[i]<len && sufArray[i-1]>len))
{
len_of_palindrome=lcp[i];
position=sufArray[i];
//cout<<len_of_palindrome<<" "<<position<<endl;
}
}
}
cout << "Longest palindromic subtring : " << s.substr(position,len_of_palindrome) << endl;
return 0;
}
|
ca2f0da5123df4e3248a66945851c57164c66f1d
|
4e0035299719bc4607eb26d4d1213fe921757336
|
/software/host/utility.hpp
|
1fe9659ca70a769f744721bea72ca872af0dc9ea
|
[] |
no_license
|
zjjzby/HPEC2021
|
d34136070c838a17c85414ccb1e6ff185a9cdcff
|
21f320f8e1207b850e35e9c54d006d164b78039f
|
refs/heads/main
| 2023-08-29T08:22:59.471344
| 2021-11-10T18:12:39
| 2021-11-10T18:12:39
| 402,191,162
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,961
|
hpp
|
utility.hpp
|
#define CL_HPP_CL_1_2_DEFAULT_BUILD
#define CL_HPP_TARGET_OPENCL_VERSION 120
#define CL_HPP_MINIMUM_OPENCL_VERSION 120
#define CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY 1
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
#ifndef UTILITY_DEF
#define UTILITY_DEF
#include <vector>
#include <vector>
#include <iostream>
#include <typeinfo>
#include <cstdio>
#include <tuple>
#include <algorithm>
#include <sys/resource.h>
#include <sys/time.h>
#include <string>
#include "./mmio.hpp"
using namespace std;
template<typename T>
bool compare(const std::tuple<int,
int,
T,
int> &lhs,
const std::tuple<int,
int,
T,
int> &rhs)
{
int a = std::get<0>(lhs);
int b = std::get<0>(rhs);
int c = std::get<1>(lhs);
int d = std::get<1>(rhs);
if( a==b ) return c < d;
else return a < b;
}
template<typename T>
void customSort( std::vector<int>& row_indices,
std::vector<int>& col_indices,
std::vector<T>& values )
{
int nvals = row_indices.size();
std::vector<std::tuple<int,
int,
T,
int> > my_tuple;
for(int i=0;i<nvals;++i){
my_tuple.push_back(std::make_tuple( row_indices[i], col_indices[i],
values[i], i));
}
std::sort( my_tuple.begin(), my_tuple.end(), compare<T> );
std::vector<int> v1 = row_indices;
std::vector<int> v2 = col_indices;
std::vector<T> v3 = values;
for(int i=0;i<nvals;++i){
int index= std::get<3>(my_tuple[i]);
row_indices[i] = v1[index];
col_indices[i] = v2[index];
values[i] = v3[index];
}
}
template<typename T, typename mtxT>
void readTuples( std::vector<int>& row_indices,
std::vector<int>& col_indices,
std::vector<T>& values,
const int nvals,
FILE* f)
{
int row_ind, col_ind;
T value;
mtxT raw_value;
char type_str[3];
type_str[0] = '%';
if( typeid(mtxT)==typeid(int) )
type_str[1] = 'd';
else if( typeid(mtxT)==typeid(float) )
type_str[1] = 'f';
// Currently checks if there are fewer rows than promised
// Could add check for edges in diagonal of adjacency matrix
for( int i=0; i<nvals; i++ ) {
if( fscanf(f, "%d", &row_ind)==EOF ) {
std::cout << "Error: not enough rows in mtx file.\n";
return;
} else {
int u = fscanf(f, "%d", &col_ind);
// Convert 1-based indexing MTX to 0-based indexing C++
row_indices.push_back(row_ind-1);
col_indices.push_back(col_ind-1);
u = fscanf(f, type_str, &raw_value);
value = (T) raw_value;
values.push_back(value);
//std::cout << value << std::endl;
//std::cout << "The first row is " << row_ind-1 << " " << col_ind-1
//<< std::endl;
// Finds max csr row.
/*int csr_max = 0;
int csr_current = 0;
int csr_row = 0;
int csr_first = 0;
if( i!=0 ) {
if( col_ind-1==0 ) csr_first++;
if( col_ind-1==col_indices[i-1] )
csr_current++;
else {
csr_current++;
if( csr_current > csr_max ) {
csr_max = csr_current;
csr_current = 0;
//csr_row = row_indices[i-1];
} else
csr_current = 0;
}
}*/
}}
//std::cout << "The biggest row was " << csr_row << " with " << csr_max <<
//" elements.\n";
//std::cout << "The first row has " << csr_first << " elements.\n";
}
template<typename T>
void readTuples( std::vector<int>& row_indices,
std::vector<int>& col_indices,
std::vector<T>& values,
const int nvals,
FILE* f)
{
int row_ind, col_ind;
T value = (T) 1.0;
// Currently checks if there are fewer rows than promised
// Could add check for edges in diagonal of adjacency matrix
for( int i=0; i<nvals; i++ ) {
if( fscanf(f, "%d", &row_ind)==EOF ) {
std::cout << "Error: not enough rows in mtx file.\n";
return;
} else {
int u = fscanf(f, "%d", &col_ind);
// Convert 1-based indexing MTX to 0-based indexing C++
row_indices.push_back(row_ind-1);
col_indices.push_back(col_ind-1);
values.push_back(value);
// Finds max csr row.
/*int csr_max = 0;
int csr_current = 0;
int csr_row = 0;
int csr_first = 0;
if( i!=0 ) {
if( col_ind-1==0 ) csr_first++;
if( col_ind-1==col_indices[i-1] )
csr_current++;
else {
csr_current++;
if( csr_current > csr_max ) {
csr_max = csr_current;
csr_current = 0;
csr_row = row_indices[i-1];
} else
csr_current = 0;
}
}*/
}}
//std::cout << "The biggest row was " << csr_row << " with " << csr_max <<
//" elements.\n";
//std::cout << "The first row has " << csr_first << " elements.\n";
}
template<typename T>
void makeSymmetric( std::vector<int>& row_indices,
std::vector<int>& col_indices,
std::vector<T>& values,
int& nvals,
bool remove_self_loops=true ) {
//std::cout << nvals << std::endl;
for( int i=0; i<nvals; i++ ) {
if( col_indices[i] != row_indices[i] ) {
row_indices.push_back( col_indices[i] );
col_indices.push_back( row_indices[i] );
values.push_back( values[i] );
}
}
nvals = row_indices.size();
//std::cout << nvals << std::endl;
// Sort
customSort<T>( row_indices, col_indices, values );
int curr = col_indices[0];
int last;
int curr_row = row_indices[0];
int last_row;
for( int i=0; i<nvals; i++ ) {
last = curr;
last_row = curr_row;
curr = col_indices[i];
curr_row = row_indices[i];
// Self-loops (TODO: make self-loops contingent on whether we
// are doing graph algorithm or matrix multiplication)
if( remove_self_loops && curr_row == curr )
col_indices[i] = -1;
// Duplicates
// if( curr == last && curr_row == last_row ) {
if ( i>0 && curr==last && curr_row==last_row ) {
//printf("Curr: %d, Last: %d, Curr_row: %d, Last_row: %d\n", curr, last,
// curr_row, last_row );
col_indices[i] = -1;
}}
int shift = 0;
// Remove self-loops and duplicates marked -1.
int back = 0;
for( int i=0; i+shift<nvals; i++ ) {
if(col_indices[i] == -1) {
for( ; back<=nvals; shift++ ) {
back = i+shift;
if( col_indices[back] != -1 ) {
col_indices[i] = col_indices[back];
row_indices[i] = row_indices[back];
col_indices[back] = -1;
break;
}}}}
nvals = nvals-shift;
row_indices.resize(nvals);
col_indices.resize(nvals);
//std::cout << nvals << std::endl;
values.resize(nvals);
}
template<typename T>
int readMtx( const char *fname,
std::vector<int>& row_indices,
std::vector<int>& col_indices,
std::vector<T>& values,
int& nrows,
int& ncols,
int& nvals)
// const bool DEBUG )
{
int ret_code;
MM_typecode matcode;
FILE *f;
if ((f = fopen(fname, "r")) == NULL) {
printf( "File %s not found", fname );
exit(1);
}
// Read MTX banner
if (mm_read_banner(f, &matcode) != 0) {
printf("Could not process Matrix Market banner.\n");
exit(1);
}
// Read MTX Size
if ((ret_code = mm_read_mtx_crd_size(f, &nrows, &ncols, &nvals)) !=0)
exit(1);
if (mm_is_integer(matcode))
readTuples<T, int>( row_indices, col_indices, values, nvals, f );
else if (mm_is_real(matcode))
readTuples<T, float>( row_indices, col_indices, values, nvals, f );
else if (mm_is_pattern(matcode))
readTuples<T>( row_indices, col_indices, values, nvals, f );
// If graph is symmetric, replicate it out in memory
if( mm_is_symmetric(matcode) )
// If user wants to treat MTX as a directed graph
//if( undirected )
makeSymmetric<T>( row_indices, col_indices, values, nvals);
customSort<T>( row_indices, col_indices, values );
// if( DEBUG ) mm_write_banner(stdout, matcode);
// if( DEBUG ) mm_write_mtx_crd_size(stdout, nrows, ncols, nvals);
return ret_code; //TODO: parse ret_code
}
template<typename T>
void printArray( const char* str, const T *array, int length=40 )
{
if( length>40 ) length=40;
std::cout << str << ":\n";
for( int i=0;i<length;i++ )
std::cout << "[" << i << "]:" << array[i] << " ";
std::cout << "\n";
}
template<typename T>
void printArray( const char* str, std::vector<T>& array, int length=40 )
{
if( length>40 ) length=40;
std::cout << str << ":\n";
for( int i=0;i<length;i++ )
std::cout << "[" << i << "]:" << array[i] << " ";
std::cout << "\n";
}
#endif
|
4b264b0a2fadb4934e4884d328a05e9a3fa9dc66
|
25011917acb3e3724af8991b5a755c7a332bdef9
|
/RubeGoldbergMachine.cpp
|
436216ddab4ef2ee0d361b01611df20de77ee9cf
|
[
"Apache-2.0"
] |
permissive
|
prason3106/RUBEGOLDBERGMACHINE
|
dffba39fee3533389642891280feae1a248c4004
|
c05ce96a17bd4a557052134aad7f5abe6657d3ed
|
refs/heads/main
| 2023-05-01T10:17:05.958208
| 2021-05-30T23:09:20
| 2021-05-30T23:09:20
| 372,331,912
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,187
|
cpp
|
RubeGoldbergMachine.cpp
|
#include <bits/stdc++.h>
#include <queue>
#include <fstream>
#include <stack>
#include <string.h>
using namespace std;
class Node // Node to represent the data in the ADTs
{
public:
string firstName; // first Name of person
string lastName; // last Name of person
int age; // age
string dob; // date of birth
Node *next; // pointer to next Node
Node *left;
Node *right;
};
void display(Node *temp)
{
cout << "[+]First Name - " << temp->firstName << endl;
cout << "[+]Last Name - " << temp->lastName << endl;
cout << "[+]Date Of Birth - " << temp->dob << endl
<< endl;
}
class LinkedList
{
// ADT - Interface
// Main Operations
// prepend(value)
// append(value)
// pop()
// popFirst()
//head()
//tail()
// remove(Node)
// remove(nodeData)
// remove(nodePosition)
private:
Node *head;
int size = 0;
public:
LinkedList()
{
head = NULL;
}
void changeHead(Node *val)
{
head = val;
}
void setData(string fst, string lst, int a, string db, Node *newNode)
{
// This saves the data into the node
newNode->firstName = fst;
newNode->lastName = lst;
newNode->age = a;
newNode->dob = db;
}
void firstNode(string fst, string lst, int a, string db)
{
// This creates the first node
Node *newNode = new Node();
setData(fst, lst, a, db, newNode);
newNode->next = head;
head = newNode;
}
void prepend(string fst, string lst, int a, string db)
{
size++;
if (head == NULL)
{
firstNode(fst, lst, a, db);
return;
}
else
{
Node *newNode = new Node();
setData(fst, lst, a, db, newNode);
newNode->next = head;
head = newNode;
}
}
void append(string fst, string lst, int a, string db)
{
size++;
if (head == NULL)
{
firstNode(fst, lst, a, db);
return;
}
else
{
Node *newNode = new Node();
setData(fst, lst, a, db, newNode);
Node *ptr = head;
while (ptr->next != NULL)
{
ptr = ptr->next;
}
newNode->next = ptr->next;
ptr->next = newNode;
}
}
Node *pop()
{
size--;
if (head == NULL)
{
cout << "[-]Empty List!!" << endl;
return NULL;
}
else
{
Node *ptr = head, *prev = head;
while (ptr->next != NULL)
{
prev = ptr;
ptr = ptr->next;
}
Node *temp = ptr;
prev->next = ptr->next;
//delete ptr;
return temp;
}
}
Node *popFirst()
{
size--;
if (head == NULL)
{
return NULL;
}
else
{
Node *temp = head;
head = head->next;
return temp;
}
}
int sizeVal()
{
return size;
}
Node *headVal()
{
return head;
}
};
class Stack
{
private:
LinkedList ll;
int size = 0;
public:
Stack()
{
}
void push(string fst, string lst, int a, string db)
{
ll.prepend(fst, lst, a, db);
size++;
}
void push(Node *node)
{
ll.prepend(node->firstName, node->lastName, node->age, node->dob);
delete node;
size++;
}
Node *pop()
{
Node *temp = ll.popFirst();
--size;
return temp;
}
int sizeVal()
{
return size;
}
Node *headVal()
{
return ll.headVal();
}
};
class Queue
{
private:
LinkedList ll;
int size = 0;
public:
Queue() {}
void enqueue(string fst, string lst, int a, string dob)
{
ll.prepend(fst, lst, a, dob);
size++;
}
void enqueue(Node *node)
{
ll.prepend(node->firstName, node->lastName, node->age, node->dob);
delete node;
size++;
}
Node *dequeue()
{
Node *temp = ll.pop();
return temp;
size--;
}
int sizeVal()
{
return size;
}
Node *headVal()
{
return ll.headVal();
}
void disp()
{
Node *h = ll.headVal();
cout << h->dob;
}
};
class BinaryTree
{
public:
// New Node creation
Node *newNode(string fst, string lst, int a, string db)
{
Node *node = new Node();
node->firstName = fst;
node->lastName = lst;
node->age = a;
node->dob = db;
node->left = NULL;
node->right = NULL;
return (node);
}
void traversePreOrder(Node *temp)
{
if (temp != NULL)
{
display(temp);
traversePreOrder(temp->left);
traversePreOrder(temp->right);
}
}
void traverseInOrder(Node *temp)
{
if (temp != NULL)
{
traverseInOrder(temp->left);
display(temp);
traverseInOrder(temp->right);
}
}
void traversePostOrder(Node *temp)
{
if (temp != NULL)
{
traversePostOrder(temp->left);
traversePostOrder(temp->right);
display(temp);
}
}
Node *InsertNode(Node *root, string fst, string lst, int a, string db)
{
if (root == NULL)
{
root = newNode(fst, lst, a, db);
return root;
}
else
{
queue<Node *> q;
q.push(root);
while (!q.empty())
{
Node *tmp = q.front();
q.pop();
if (tmp->left != NULL)
q.push(tmp->left);
else
{
tmp->left = newNode(fst, lst, a, db);
return root;
}
if (tmp->right != NULL)
q.push(tmp->right);
else
{
tmp->right = newNode(fst, lst, a, db);
return root;
}
}
}
}
};
struct Node *getTail(struct Node *cur)
{
while (cur != NULL && cur->next != NULL)
cur = cur->next;
return cur;
}
// Partitions the list taking the last element as the pivot
struct Node *partition(struct Node *head, struct Node *end,
struct Node **newHead, struct Node **newEnd)
{
struct Node *pivot = end;
struct Node *prev = NULL, *cur = head, *tail = pivot;
// During partition, both the head and end of the list might change
// which is updated in the newHead and newEnd variables
while (cur != pivot)
{
if (cur->firstName < pivot->firstName)
{
// First node that has a value less than the pivot - becomes
// the new head
if ((*newHead) == NULL)
(*newHead) = cur;
prev = cur;
cur = cur->next;
}
else // If cur node is greater than pivot
{
// Move cur node to next of tail, and change tail
if (prev)
prev->next = cur->next;
struct Node *tmp = cur->next;
cur->next = NULL;
tail->next = cur;
tail = cur;
cur = tmp;
}
}
// If the pivot data is the smallest element in the current list,
// pivot becomes the head
if ((*newHead) == NULL)
(*newHead) = pivot;
// Update newEnd to the current last node
(*newEnd) = tail;
// Return the pivot node
return pivot;
}
//here the sorting happens exclusive of the end node
struct Node *quickSortRecur(struct Node *head, struct Node *end)
{
// base condition
if (!head || head == end)
return head;
Node *newHead = NULL, *newEnd = NULL;
// Partition the list, newHead and newEnd will be updated
// by the partition function
struct Node *pivot = partition(head, end, &newHead, &newEnd);
// If pivot is the smallest element - no need to recur for
// the left part.
if (newHead != pivot)
{
// Set the node before the pivot node as NULL
struct Node *tmp = newHead;
while (tmp->next != pivot)
tmp = tmp->next;
tmp->next = NULL;
// Recur for the list before pivot
newHead = quickSortRecur(newHead, tmp);
// Change next of last node of the left half to pivot
tmp = getTail(newHead);
tmp->next = pivot;
}
// Recur for the list after the pivot element
pivot->next = quickSortRecur(pivot->next, newEnd);
return newHead;
}
// The main function for quick sort. This is a wrapper over recursive
// function quickSortRecur()
void quickSort(struct Node **headRef)
{
(*headRef) = quickSortRecur(*headRef, getTail(*headRef));
return;
}
int main()
{
// Setting up a queue
Queue q;
// Reading input from the text file
// Reads one line at a time and divides the line
// with respect to comma and space
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
ifstream fin;
fin.open("test.txt");
string line;
while (fin)
{
getline(fin, line);
string delimiter = ", ";
size_t pos = 0;
string token;
string arr[4];
int i = 0;
while ((pos = line.find(delimiter)) != string::npos)
{
token = line.substr(0, pos);
arr[i] = token;
line.erase(0, pos + delimiter.length());
++i;
}
arr[3] = line;
arr[2] = arr[1];
istringstream ss(arr[0]);
string word;
i = 0;
while (ss >> word)
{
arr[i] = word;
i++;
}
stringstream num(arr[2]);
int x = 0;
num >> x;
q.enqueue(arr[0], arr[1], x, arr[3]);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
}
// Step 1
Queue qB;
int s = q.sizeVal() - 1;
while (s != 0)
{
Node *temp = q.dequeue();
display(temp);
qB.enqueue(temp);
--s;
}
// Wait for user input
system("pause");
// Step 2
Stack st;
s = qB.sizeVal();
while (s != 0)
{
Node *tmp = qB.dequeue();
st.push(tmp);
--s;
}
Queue qC;
s = st.sizeVal();
while (s != 0)
{
Node *tmp = st.pop();
qC.enqueue(tmp);
s--;
}
Queue qD;
s = qC.sizeVal();
while (s != 0)
{
Node *tmp = qC.dequeue();
display(tmp);
qD.enqueue(tmp);
--s;
}
system("pause");
// Step - 3
BinaryTree bt;
Node *root = NULL;
s = qD.sizeVal();
while (s != 0)
{
Node *tmp = qD.dequeue();
root = bt.InsertNode(root, tmp->firstName, tmp->lastName, tmp->age, tmp->dob);
--s;
}
cout << root->age;
bt.traversePreOrder(root);
system("pause");
bt.traversePostOrder(root);
system("pause");
// Transferring the data from the binary tree
// linked list using in order traversal
LinkedList lt;
stack<Node *> stac;
Node *curr = root;
while (curr != NULL || stac.empty() == false)
{
while (curr != NULL)
{
stac.push(curr);
curr = curr->left;
}
curr = stac.top();
stac.pop();
lt.append(curr->firstName, curr->lastName, curr->age, curr->dob);
curr = curr->right;
}
Node *hd = lt.headVal();
while (hd != NULL)
{
display(hd);
hd = hd->next;
}
system("pause");
// Step - 4
Node *a = lt.headVal();
quickSort(&a);
Node *hdt = a;
while (hdt != NULL)
{
display(hdt);
hdt = hdt->next;
}
system("pause");
string f, l, d;
int ag;
cout << "[+] Enter another name, age and date of birth\n";
cin >> f >> l >> ag >> d;
lt.changeHead(a);
lt.append(f, l, ag, d);
a = lt.headVal();
quickSort(&a);
lt.changeHead(a);
hdt = a;
while (hdt != NULL)
{
display(hdt);
hdt = hdt->next;
}
system("pause");
cout << "Bye Bye!!";
return 0;
}
|
3626875df297dcfb192551c83e9ef61dfb1776db
|
157fd7fe5e541c8ef7559b212078eb7a6dbf51c6
|
/TRiAS/TRiAS V2.07/TRiAS01/DIO_INIT.CXX
|
25e08aa73e5f0f9988efe747ba7263dc765373f4
|
[] |
no_license
|
15831944/TRiAS
|
d2bab6fd129a86fc2f06f2103d8bcd08237c49af
|
840946b85dcefb34efc219446240e21f51d2c60d
|
refs/heads/master
| 2020-09-05T05:56:39.624150
| 2012-11-11T02:24:49
| 2012-11-11T02:24:49
| null | 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 6,274
|
cxx
|
DIO_INIT.CXX
|
/* Datenbank - I/O Funktionen unterste Ebene */
/* Initialisierung der Datenbank I/O-Arbeit */
/* File: DIO_INIT.C last update: 15. Februar 1990 */
#include "trias01p.hxx"
#define NOCOPYRIGHT
#include <dbversio.h>
/* globale Datendefinitionen fuer DIO */
short max_open_files = MAXFILES; /* maximale Anzahl eröffneter Files */
short cnt_open_files = 0; /* aktuelle Anzahl eröffneter Files */
short no_of_pages = DEFPAGES; /* Anzahl der Pages in der Pagetabelle */
short dynamic = DEFPAGES; /* Anzahl der dynamisch verwalteten Pages */
short least_recent = 0; /* Zähler fuer dynamisches Pageswopping */
short working_file = NONE; /* für Operationen mit default_file */
PAGE_ENTRY *pages = NULL; /* Pageverzeichnisse */
PGZERO *pgzero = NULL; /* Nullpagetabelle */
PAGE_ENTRY **page_table = NULL; /* Pagetabelle */
unsigned short ActPageSize = 0; /* aktuelle Pagegröße */
#ifdef BACKUP
short backup_flag = NONE;
PAGE_ENTRY *backup_page = NULL;
#endif // BACKUP
#ifdef PAGEHASH
HASH_LIST FAR **hash_table = NULL; /* Hashtabelle */
short hashsize = HASHSIZE; /* Größe der Hashtabelle */
#else // PAGEHASH
short hashsize;
#endif // PAGEHASH
#ifdef MULTI_DB
short last_db = 0; /* zuletzt angesprochene DB (fdbopen) */
#endif // MULTI_DB
extern "C" REC_ENTRY *FUNCTYPE EXPORT01 RecordTable (HPROJECT hPr, short iIndex)
{
if (iIndex >= 0 && iIndex < size_rt)
return record_table + iIndex;
return record_table;
}
// Test auf Übereinstimmung des CopyrightStrings ist Fatal bei Fehler
extern FLAG g_fCopyrightFlag;
int FUNCTYPE dio_init (DBASE *pDB)
{
register short i;
register PAGE_ENTRY *pe_p;
#ifdef BACKUP
/* Eigene Page fuer Backup anfordern */
if (backup_page == NULL && (pDB ? pDB -> db_bflag >= 0 : backup_flag)) {
TX_TRY(backup_page = (PAGE_ENTRY *)new char [sizeof (PAGE_ENTRY) + MAXPAGESIZE -1]);
if (backup_page == NULL)
return (db_error (S_NOMEMORY, DIO_INIT));
}
#endif // BACKUP
unsigned short uiPageSize = (pDB != NULL) ? pDB -> db_pagesize : PageSize;
#ifdef MULTI_DB
/* wenn nicht erste DB und Pages richtig in der Größe --> return */
if (page_table != NULL && ActPageSize >= uiPageSize)
return (db_status = S_OKAY);
#endif // MULTI_DB
// Anlegen der Pageverwaltungsstrukturen
if (page_table == NULL) {
TX_TRY(page_table = new PAGE_ENTRY * [no_of_pages]);
if (!page_table)
return (dberr (S_NOMEMORY, DIO_INIT));
memset (page_table, '\0', sizeof(PAGE_ENTRY *) * no_of_pages);
}
#ifdef PAGEHASH
hashsize = prim (no_of_pages);
TX_TRY(hash_table = new HASH_LIST *[hashsize]);
if (!hash_table) return (dberr (S_NOMEMORY, DIO_INIT));
for (i = 0; i < hashsize; ++i)
hash_table[i] = NULL;
#endif // PAGEHASH
// Initialisieren der angelegten Strukturen
last_db = 0;
if (pDB) pDB -> db_work = NONE;
else working_file = NONE;
pe_p = pages;
for (i = 0; i < no_of_pages; ++i) {
if (NULL == page_table[i]) {
// Speicher neu enfordern
TX_TRY(pe_p = (PAGE_ENTRY *)new char [sizeof(PAGE_ENTRY) + uiPageSize -1]);
if (pe_p == NULL)
return (db_error (S_NOMEMORY, DIO_INIT));
// Pages initialisieren
pe_p->file = -1;
pe_p->pageno = 0;
pe_p->recently_used = FALSE;
pe_p->modified = FALSE;
#ifdef PAGEHASH
pe_p->hash = NONE;
#endif
#ifdef MULTI_DB
pe_p->dbase = NULL;
#endif
pe_p -> pg_pagesize = uiPageSize;
} else {
// Pages vergrößern
PAGE_ENTRY *pPE = NULL;
TX_TRY(pPE = (PAGE_ENTRY *)new char [sizeof(PAGE_ENTRY) + uiPageSize -1]);
if (pPE == NULL) return (db_error (S_NOMEMORY, DIO_INIT));
memcpy (pPE, page_table[i], page_table[i] -> pg_pagesize);
delete [] (char *)page_table[i];
pe_p = pPE;
}
page_table[i] = pe_p;
}
least_recent = 0;
dynamic = no_of_pages;
ActPageSize = uiPageSize;
return (db_status = S_OKAY);
}
// Initialisieren der Page 0 Tabellen -----------------------------------------
int FUNCTYPE dio_pzinit (void)
{
register short i;
register int desc;
register FILE_ENTRY *ft_p;
BYTE version[COPYRIGHT_LEN];
TX_TRY(pgzero = new PGZERO [size_ft]);
if (!pgzero) return (dberr (S_NOMEMORY, DIO_PZINIT));
for (i = 0; i < size_ft; ++i) {
if ((ft_p = &file_table[i])->ft_access == O_NOACC)
continue;
if (file_open (ft_p) != S_OKAY)
return (db_status);
// auf Anfang positionieren
lseek (desc = ft_p->ft_desc, 0L, 0);
// Version überprüfen
#ifdef MSWIND
_lread (desc, (LPSTR)version, COPYRIGHT_LEN);
#else
read (desc, version, COPYRIGHT_LEN);
#endif
if (g_fCopyrightFlag &&
(mycrypt (version, COPYRIGHT_LEN) & 0xffff) != COPYRIGHT_CRC)
{
return (dberr (S_VERSION, DIO_PZINIT));
}
/* einlesen der Page 0 */
#ifdef MSWIND
if (_lread (desc, (LPSTR)&(pgzero[i]), sizeof(PGZERO)) < 0)
#else
if (read (desc, &(pgzero[i]), sizeof (PGZERO)) < 0)
#endif
return (dberr (S_NOREAD, DIO_PZINIT));
file_close (ft_p);
}
return (db_status = S_OKAY);
}
// Version für CompoundFiles --------------------------------------------------
#if defined(MSWIND)
short FUNCTYPE InitPageZeroTable (DBASE *pDB)
{
BYTE cbVersion[COPYRIGHT_LEN];
TX_TRY(pDB -> db_pztab = new PGZERO [pDB -> db_sft]);
if (!pDB -> db_pztab) return db_error (S_NOMEMORY, DIO_PZINIT);
for (short i = 0; i < pDB -> db_sft; ++i) {
FILE_ENTRY *ft_p = &pDB -> db_ftab[i];
if (ft_p -> ft_access == O_NOACC)
continue;
// auf Anfang positionieren
LPSTREAM pIStream = ft_p -> ft_pIStream;
LARGE_INTEGER li;
LISet32 (li, 0);
pIStream -> Seek (li, STREAM_SEEK_SET, NULL);
// Version überprüfen
pIStream -> Read (cbVersion, COPYRIGHT_LEN, NULL);
if (g_fCopyrightFlag &&
(mycrypt (cbVersion, COPYRIGHT_LEN) & 0xffff) != COPYRIGHT_CRC)
{
return db_error (S_VERSION, DIO_PZINIT);
}
// Einlesen der Page 0
HRESULT hr = pIStream -> Read (&pDB -> db_pztab[i], sizeof(PGZERO), NULL);
if (FAILED(hr)) return db_error (S_NOREAD, DIO_PZINIT);
}
return (db_status = S_OKAY);
}
#endif
|
21f36a89b9b02a193e586563e8dfa041e3a0ca86
|
15dea4de84765fd04efb0367247e94657e76515b
|
/source/3rdparty/won/crypt/cryptoFiles/eprecomp.h
|
9d018b3e26418daa9eb58d1717b2da9ac2766cc2
|
[] |
no_license
|
dppereyra/darkreign2
|
4893a628a89642121d230e6e02aa353636566be8
|
85c83fdbb4b4e32aa5f816ebfcaf286b5457a11d
|
refs/heads/master
| 2020-12-30T13:22:17.657084
| 2017-01-30T21:20:28
| 2017-01-30T21:20:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,269
|
h
|
eprecomp.h
|
#ifndef CRYPTOPP_EPRECOMP_H
#define CRYPTOPP_EPRECOMP_H
#include "integer.h"
#include <vector>
NAMESPACE_BEGIN(CryptoPP)
// Please do not directly use the following class. It should be
// considered a private class for the library. The following
// classes are public and use ExponentiationPrecomputation internally.
//
// ModExpPrecomputation;
// EcPrecomputation<EC2N>;
// EcPrecomputation<ECP>;
template <class T> class ExponentiationPrecomputation
{
public:
typedef T Group;
typedef typename Group::Element Element;
class CryptoPair
{
public:
Integer first;
Element second;
CryptoPair()
: first(Integer()), second(Element()) { }
CryptoPair(const Integer& f, const Element& s)
: first(f), second(s) { }
CryptoPair(const CryptoPair& pr)
: first(pr.first), second(pr.second) { }
bool operator==(const CryptoPair& cp) const
{ return (first == cp.first && second == cp.second); }
bool operator!=(const CryptoPair& cp) const
{ return !(*this == cp); }
bool operator<(const CryptoPair& cp) const
{ return (first < cp.first || !(cp.first < first) && second < cp.second); }
bool operator>(const CryptoPair& cp) const
{ return (cp < *this); }
bool operator<=(const CryptoPair& cp) const
{ return (!(cp < *this)); }
bool operator>=(const CryptoPair& cp) const
{ return (!(*this < cp)); }
};
ExponentiationPrecomputation(const Group &group) : group(group) {}
ExponentiationPrecomputation(const Group &group, const Element &base, unsigned int maxExpBits, unsigned int storage)
: group(group), storage(storage), g(storage) {Precompute(base, maxExpBits);}
ExponentiationPrecomputation(const Group &group, const ExponentiationPrecomputation &pc)
: group(group), storage(pc.storage), exponentBase(pc.exponentBase), g(pc.g) {}
void Precompute(const Element &base, unsigned int maxExpBits);
Element Exponentiate(const Integer &exponent) const;
Element CascadeExponentiate(const Integer &exponent, const ExponentiationPrecomputation<Group> &pc2, const Integer &exponent2) const;
const Group &group;
unsigned int storage; // number of precalculated bases
Integer exponentBase; // what base to represent the exponent in
std::vector<Element> g; // precalculated bases
};
NAMESPACE_END
#endif
|
4ec81a38fb65b53d9fd4d2ff8f34f81d9ac6e8c1
|
e961eed45a3278ad28f4dbb93e73acadc4711db8
|
/Atcoder Beginner Contest 126/Dice_and_coin.cpp
|
c814597f80ac102df0aa79b895f30828fb93d9e0
|
[
"MIT"
] |
permissive
|
Razdeep/AtCoder-Contests
|
3c60bf162ea44457d9d94588913ac968b172e16a
|
852eb3e05420b47f5d81a5fe561047e9dd4cef3a
|
refs/heads/master
| 2021-08-10T15:24:24.390419
| 2020-04-19T13:29:23
| 2020-04-19T13:29:23
| 160,945,196
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 573
|
cpp
|
Dice_and_coin.cpp
|
// https://atcoder.jp/contests/abc126/tasks/abc126_c
#include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
using namespace std;
typedef long long ll;
int main()
{
double n, k;
cin >> n >> k;
double answer = 0.0;
for (int i = 1; i <= n; i++)
{
double this_prob = 1.0 / n;
int this_score = i;
while (this_score < k)
{
this_score *= 2;
this_prob /= 2;
}
answer += this_prob;
}
cout << setprecision(12) << answer << endl;
// printf("%.12f\n", answer);
return 0;
}
|
85fb745d78121cdf468a733285925cb2bb66c90f
|
f44fc7e2b4b54bc68b9425b6eb38b6d83e8e873a
|
/StorageSpace.cpp
|
bd4c2f11aa2084ba41ba5e26026d22b89f30a362
|
[] |
no_license
|
adambacke/LagerhanteringsSystem
|
3bb562f0ceb2f76d8b3195d387c3440e18e89b88
|
4f5c7d05dd584e74c3a358148d8fc0a2f071fbf5
|
refs/heads/master
| 2021-09-11T21:05:33.985569
| 2018-01-08T10:32:04
| 2018-01-08T10:32:04
| 112,081,620
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,426
|
cpp
|
StorageSpace.cpp
|
#include "StorageSpace.h"
StorageSpace::StorageSpace()
{
this->IdNr = -1;
this->Capacity = -1;
this->NrOfItems = 0;
}
StorageSpace::StorageSpace(int Capacity, int IdNr, int NrOfItems)
{
this->Capacity = Capacity;
this->IdNr = IdNr;
this->NrOfItems = NrOfItems;
}
StorageSpace::StorageSpace(int IdNr)
{
this->IdNr = IdNr;
this->Capacity = 0;
}
StorageSpace::~StorageSpace()
{
//Tom just nu.
}
void StorageSpace::clearPlace()
{
this->IdNr = -1;
this->Capacity = -1;
}
QString StorageSpace::toString() const
{
QString retVal;
QString intConverter;
retVal += "Serie Nr: " + intConverter.setNum(IdNr) + "\n";
retVal += "Kapacitet: " + intConverter.setNum(Capacity) + "\n";
retVal += "Saldo: " + intConverter.setNum(NrOfItems) + "\n";
return retVal;
}
int StorageSpace::getIdNr()
{
return this->IdNr;
}
void StorageSpace::setCapacity(int Capacity)
{
this->Capacity=Capacity;
}
void StorageSpace::setIdNr(int IdNr)
{
this->IdNr = IdNr;
}
void StorageSpace::setNrOfItems(int NrOfItems)
{
this->NrOfItems = this->NrOfItems + NrOfItems;
}
int StorageSpace::getNrOfItems()
{
return this->NrOfItems;
}
int StorageSpace::getCapacity()
{
return this->Capacity;
}
bool StorageSpace::operator ==(StorageSpace other)
{
bool retVal = false;
if(this->IdNr == other.IdNr)
{
retVal = true;
}
return retVal;
}
|
c651c2f1c7f95d0ab34e82731ae767dd792c37d9
|
4f7f8d405160e45ab27fa7b5692f6762045c6a67
|
/HMK/src/Shader.cpp
|
04badfdd7cfccc0f16661d8a2bbc3fb77e33a56e
|
[] |
no_license
|
hmkum/HMKEngine
|
2e6758bc53d68bcbc87303d03f63e566b05cec7e
|
3166a4fa02847ae66c27f33e6cf631aa80e8e992
|
refs/heads/master
| 2021-01-18T02:32:22.292055
| 2015-11-05T19:05:27
| 2015-11-05T19:05:27
| 45,062,053
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 989
|
cpp
|
Shader.cpp
|
#include "Shader.h"
#include <iostream>
using namespace hmk;
Shader::Shader()
: shader_id_(0)
{ }
Shader::~Shader()
{
}
bool Shader::initialize(ShaderType shader_type, std::string shaderName)
{
std::ifstream file(SHADER_PATH + shaderName);
if(file.is_open())
{
std::string shaderCode;
std::string line;
while(std::getline(file, line))
{
shaderCode += line + "\n";
}
const GLchar *sCode = shaderCode.c_str();
shader_id_ = glCreateShader((unsigned int)shader_type);
glShaderSource(shader_id_, 1, &sCode, nullptr);
glCompileShader(shader_id_);
GLint success;
glGetShaderiv(shader_id_, GL_COMPILE_STATUS, &success);
if(!success)
{
GLchar log[512];
glGetShaderInfoLog(shader_id_, 512, nullptr, log);
std::cerr << "Shader(" << shaderName << "): " << log << std::endl;
return false;
}
return true;
}
else
{
return false;
}
}
|
f3b622ad314021de048035587bcd82051565fdb4
|
5519367afb178f45fd11d4412c81ed986ac16eb6
|
/src/lib/formats/apollo_dsk.h
|
2ea2026a239fb6be16374367b4d5115f5da44a2f
|
[] |
no_license
|
Heribertosgp/mame
|
ab1b4fb207e054e5b52a4f2ac61f955a62681f3f
|
7523b96daa6bfbc77005aab1a9f24829f2b4a971
|
refs/heads/master
| 2020-04-01T21:25:32.372860
| 2015-05-09T16:50:21
| 2015-05-09T16:50:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 597
|
h
|
apollo_dsk.h
|
// license:???
// copyright-holders:???
/*********************************************************************
formats/apollo_dsk.h
apollo format
*********************************************************************/
#ifndef APOLLO_DSK_H_
#define APOLLO_DSK_H_
#include "upd765_dsk.h"
class apollo_format : public upd765_format {
public:
apollo_format();
virtual const char *name() const;
virtual const char *description() const;
virtual const char *extensions() const;
private:
static const format formats[];
};
extern const floppy_format_type FLOPPY_APOLLO_FORMAT;
#endif
|
103e07cc240a83ded9ad2cf8a65466a7e2e40878
|
fb94f8cbb7e62facf1f85ba2ea180b47c441437a
|
/TsuPod.cpp
|
a2df8a52ac8d0719294402b0573c8ec8f391c7b8
|
[] |
no_license
|
RajarsiGit/chegg
|
508d89ceff032418b890f4dd9f3a9befe4bebcd3
|
2e5ba3bbfa7bda421d7488156fe66f69cf3a7720
|
refs/heads/master
| 2021-05-23T18:48:44.605687
| 2020-04-18T06:10:54
| 2020-04-18T06:10:54
| 253,423,898
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,207
|
cpp
|
TsuPod.cpp
|
#include <bits/stdc++.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include "Song.cpp"
#include "TsuPod.h"
#define SIZE 256
using namespace std;
TsuPod::TsuPod(int size){
if(size <= SIZE){
TsuPod::size = size;
TsuPod::list = (Song*) calloc(99999, sizeof(Song*));
TsuPod::count = 0;
}
else
cout << "Too large!" << endl;
}
void TsuPod::addSong(Song s){
if((TsuPod::getTotalMemory() + s.getSize()) <= TsuPod::size){
TsuPod::list[count++] = s;
cout << "Song added!" << endl;
}
else
cout << "Memory too less!" << endl;
}
void TsuPod::removeSong(Song s){
int i;
for(i=0;i<TsuPod::count;i++){
if(TsuPod::list[i] == s){
for(int j=i;j<(TsuPod::count-1);j++){
TsuPod::list[j] = TsuPod::list[j+1];
}
TsuPod::count--;
break;
}
}
if(i == TsuPod::count){
cout << "Song not found!" << endl;
}
else{
cout << "Song deleted!" << endl;
}
}
void TsuPod::shuffle(){
unsigned seed = 0;
std::shuffle(TsuPod::list, (TsuPod::list + TsuPod::count), default_random_engine(seed));
cout << "List shuffled" << endl;
}
void TsuPod::clearSongList(){
for(int i=0;i<TsuPod::count;i++){
TsuPod::list[i].setTitle("");
TsuPod::list[i].setArtist("");
TsuPod::list[i].setSize(0);
}
TsuPod::count = 0;
cout << "List cleared" << endl;
}
void TsuPod::showSongList(){
cout << "Title\tArtist\tSize" << endl;
for(int i=0;i<TsuPod::count;i++){
cout << TsuPod::list[i].getTitle() << "\t" << TsuPod::list[i].getArtist() << "\t" << TsuPod::list[i].getSize() << endl;
}
}
void TsuPod::sortSongList(){
cout << "Title\tArtist\tSize" << endl;
for (int i=0;i<TsuPod::count-1;i++)
for (int j=0;j<TsuPod::count-i-1;j++)
if (TsuPod::list[j] > TsuPod::list[j+1])
swap(&TsuPod::list[j], &TsuPod::list[j+1]);
cout << "List sorted" << endl;
}
int TsuPod::getTotalMemory(){
int total=0;
for(int i=0;i<TsuPod::count;i++){
total += TsuPod::list[i].getSize();
}
return total;
}
int TsuPod::getRemainingMemory(){
return TsuPod::size - TsuPod::getTotalMemory();
}
void TsuPod::swap(Song *xp, Song *yp)
{
Song temp = *xp;
*xp = *yp;
*yp = temp;
}
|
44ebc3d9dd71abe4ecf85bce3e9b36d0f957a7fa
|
54f352a242a8ad6ff5516703e91da61e08d9a9e6
|
/Source Codes/AtCoder/abc020/B/3417421.cpp
|
7fa04a155c29880442c31c1e8c050d6cc539a583
|
[] |
no_license
|
Kawser-nerd/CLCDSA
|
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
|
aee32551795763b54acb26856ab239370cac4e75
|
refs/heads/master
| 2022-02-09T11:08:56.588303
| 2022-01-26T18:53:40
| 2022-01-26T18:53:40
| 211,783,197
| 23
| 9
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 291
|
cpp
|
3417421.cpp
|
#include<iostream>
#include<stdlib.h>
using namespace std;
int main(void){
cin.tie(0);
ios::sync_with_stdio(false);
int a, b, num;
cin >> a >> b;
char c[7];
sprintf(c, "%d%d", a, b);
num = atoi(c);
cout << num * 2 << "\n";
return 0;
}
|
9195ec544781513afe19eef7d2dd1bd3bb610b5b
|
be6902683fb9405369a9135472c99ddffd7f3ee2
|
/cpp/test/test.cpp
|
204006f31a477765bcf564e30ba3559bd4cc5f32
|
[
"MIT"
] |
permissive
|
tomcattiger1230/traj_gen
|
3032f2f50b9b7477e33415d474abfb8ab58f0ace
|
d01882c17d8e979860fb1f09defa968a86adb494
|
refs/heads/master
| 2022-12-27T06:25:16.408488
| 2020-09-11T11:59:21
| 2020-09-11T11:59:21
| 278,294,127
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,260
|
cpp
|
test.cpp
|
#include <traj_gen2/TrajGen.hpp>
#include <iostream>
#include <chrono>
using namespace trajgen;
using namespace Eigen;
using Type = double ;
int main(){
// 1. Prameter setting
// common
const int dim = 3;
trajgen::time_knots<Type> ts{0,2,4,7};
trajgen::Vector<Type,3> objWeights(0,1,1);
// polyTrajGen
uint poly_order = 8, max_conti = 4;
trajgen::PolyParam pp(poly_order,max_conti,ALGORITHM::END_DERIVATIVE); // or ALGORITHM::POLY_COEFF
// optimTrajGen
Type pntDensity = 5;
// 2. Pin
// 2.1 FixPin
FixPin<Type,dim> x1(0.0f,0,Vector<Type,dim>(0,0,0));
FixPin<Type,dim> x2(2.0f,0,Vector<Type,dim>(2,-1,2));
FixPin<Type,dim> x3(4.0f,0,Vector<Type,dim>(5,3,4));
FixPin<Type,dim> x4(7.0f,0,Vector<Type,dim>(7,-5,5));
FixPin<Type,dim> xdot0(0.0f,1,Vector<Type,dim>(0,0,0));
FixPin<Type,dim> xddot0(0.0f,2,Vector<Type,dim>(0,0,0));
// 2.2 LoosePin
LoosePin<Type,dim> passCube(3.0f,0,Vector<Type,dim>(3,-3,1),Vector<Type,dim>(4.2,-2,2));
std::vector<Pin<Type,dim>*> pinSet{&x1,&x2,&x3,&x4,&xdot0,&xddot0,&passCube}; // to prevent downcasting slicing, vector of pointers
// Let's test the two trajGen class
TrajGen<Type,dim>** pTrajGenSet = new TrajGen<Type,dim>*[1]; //2
pTrajGenSet[0] = new PolyTrajGen<Type,dim>(ts,pp);
pTrajGenSet[1] = new OptimTrajGen<Type,dim>(ts,pntDensity);
bool verbose = false;
bool isSolved = false;
string TrajGenClass[2] = {"PolyTraj","OptimTraj"};
Type t_eval = 3; d_order d_eval = 1;
for (uint i = 0 ; i <2 ; i++) {
auto begin = std::chrono::steady_clock::now();
pTrajGenSet[i]->setDerivativeObj(objWeights);
pTrajGenSet[i]->addPinSet(pinSet);
isSolved = pTrajGenSet[i]->solve(verbose);
printf("For %s, The evaluated value for (t=%.2f, d=%d) : ",TrajGenClass[i].c_str(),t_eval,d_eval);
if (isSolved)
cout << pTrajGenSet[i]->eval(t_eval,d_eval).transpose() << endl;
else
cout << "Failed. " << endl;
auto end= std::chrono::steady_clock::now();
std::cout << "Total time : " <<
std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()*1e-3 << "[ms]" << std::endl;
}
return 0;
}
|
4d3f44ac06eb46124410a76f7db43d36332f14b2
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/buildtools/third_party/libc++/trunk/test/std/utilities/expected/expected.void/assign/assign.move.pass.cpp
|
3954cda51c346ad5279e844112862314bac1de40
|
[
"BSD-3-Clause",
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C++
| false
| false
| 4,893
|
cpp
|
assign.move.pass.cpp
|
//===----------------------------------------------------------------------===//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
// Older Clangs do not support the C++20 feature to constrain destructors
// XFAIL: apple-clang-14
// constexpr expected& operator=(expected&& rhs) noexcept(see below);
//
// Effects:
// - If this->has_value() && rhs.has_value() is true, no effects.
// - Otherwise, if this->has_value() is true, equivalent to:
// construct_at(addressof(unex), std::move(rhs.unex));
// has_val = false;
// - Otherwise, if rhs.has_value() is true, destroys unex and sets has_val to true.
// - Otherwise, equivalent to unex = std::move(rhs.error()).
//
// Returns: *this.
//
// Remarks: The exception specification is equivalent to is_nothrow_move_constructible_v<E> && is_nothrow_move_assignable_v<E>.
//
// This operator is defined as deleted unless is_move_constructible_v<E> is true and is_move_assignable_v<E> is true.
#include <cassert>
#include <concepts>
#include <expected>
#include <type_traits>
#include <utility>
#include "../../types.h"
#include "test_macros.h"
struct NotMoveConstructible {
NotMoveConstructible(NotMoveConstructible&&) = delete;
NotMoveConstructible& operator=(NotMoveConstructible&&) = default;
};
struct NotMoveAssignable {
NotMoveAssignable(NotMoveAssignable&&) = default;
NotMoveAssignable& operator=(NotMoveAssignable&&) = delete;
};
// Test constraints
static_assert(std::is_move_assignable_v<std::expected<void, int>>);
// !is_move_assignable_v<E>
static_assert(!std::is_move_assignable_v<std::expected<void, NotMoveAssignable>>);
// !is_move_constructible_v<E>
static_assert(!std::is_move_assignable_v<std::expected<void, NotMoveConstructible>>);
// Test noexcept
struct MoveCtorMayThrow {
MoveCtorMayThrow(MoveCtorMayThrow&&) noexcept(false) {}
MoveCtorMayThrow& operator=(MoveCtorMayThrow&&) noexcept = default;
};
struct MoveAssignMayThrow {
MoveAssignMayThrow(MoveAssignMayThrow&&) noexcept = default;
MoveAssignMayThrow& operator=(MoveAssignMayThrow&&) noexcept(false) { return *this; }
};
// Test noexcept
static_assert(std::is_nothrow_move_assignable_v<std::expected<void, int>>);
// !is_nothrow_move_assignable_v<E>
static_assert(!std::is_nothrow_move_assignable_v<std::expected<void, MoveAssignMayThrow>>);
// !is_nothrow_move_constructible_v<E>
static_assert(!std::is_nothrow_move_assignable_v<std::expected<void, MoveCtorMayThrow>>);
constexpr bool test() {
// If this->has_value() && rhs.has_value() is true, no effects.
{
std::expected<void, int> e1;
std::expected<void, int> e2;
decltype(auto) x = (e1 = std::move(e2));
static_assert(std::same_as<decltype(x), std::expected<void, int>&>);
assert(&x == &e1);
assert(e1.has_value());
}
// Otherwise, if this->has_value() is true, equivalent to:
// construct_at(addressof(unex), std::move(rhs.unex));
// has_val = false;
{
Traced::state state{};
std::expected<void, Traced> e1;
std::expected<void, Traced> e2(std::unexpect, state, 5);
decltype(auto) x = (e1 = std::move(e2));
static_assert(std::same_as<decltype(x), std::expected<void, Traced>&>);
assert(&x == &e1);
assert(!e1.has_value());
assert(e1.error().data_ == 5);
assert(state.moveCtorCalled);
}
// Otherwise, if rhs.has_value() is true, destroys unex and sets has_val to true.
{
Traced::state state{};
std::expected<void, Traced> e1(std::unexpect, state, 5);
std::expected<void, Traced> e2;
decltype(auto) x = (e1 = std::move(e2));
static_assert(std::same_as<decltype(x), std::expected<void, Traced>&>);
assert(&x == &e1);
assert(e1.has_value());
assert(state.dtorCalled);
}
// Otherwise, equivalent to unex = rhs.error().
{
Traced::state state{};
std::expected<void, Traced> e1(std::unexpect, state, 5);
std::expected<void, Traced> e2(std::unexpect, state, 10);
decltype(auto) x = (e1 = std::move(e2));
static_assert(std::same_as<decltype(x), std::expected<void, Traced>&>);
assert(&x == &e1);
assert(!e1.has_value());
assert(e1.error().data_ == 10);
assert(state.moveAssignCalled);
}
return true;
}
void testException() {
#ifndef TEST_HAS_NO_EXCEPTIONS
std::expected<void, ThrowOnMoveConstruct> e1(std::in_place);
std::expected<void, ThrowOnMoveConstruct> e2(std::unexpect);
try {
e1 = std::move(e2);
assert(false);
} catch (Except) {
assert(e1.has_value());
}
#endif // TEST_HAS_NO_EXCEPTIONS
}
int main(int, char**) {
test();
static_assert(test());
testException();
return 0;
}
|
14882f3b04878065252db12b371ba97aeea33697
|
2bac215c4601f5ea7ccd83f7308cdb09de635190
|
/Lab/lab3/hnu_lab_template/Code/mind.cpp
|
378d865d433b73d52a9fb74a16e5094f2706761d
|
[] |
no_license
|
DelinQu/IntroductionToTheTheoryOfComputation
|
2f064e2c0f9f0f556a2aa114b565b928b009b84b
|
9b21e502a57d6051941f9b63065f6c2cc73b817a
|
refs/heads/master
| 2023-04-23T05:40:24.093942
| 2021-05-15T14:53:17
| 2021-05-15T14:53:17
| 343,593,320
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,551
|
cpp
|
mind.cpp
|
main():
while(t--)
{
Input(DFA); // 输入DFA
DFS(); // 搜索状态图
for(int i = 0; i < cnt; i++) // 任何包含接受状态的节点都是接受状态
if(ans[i]&f)
ac[i] = 1, sum++;
for(int i = 0; i < cnt; i++) // 调整序号
change[ans[i]] = i;
OutPut(DFA); // 输出DFA
}
DFS(int p):
while(p)
{
int x = p&(-p); // 选择p的一个状态,我们才用与上p的补运算可以取出最后一个为1的位
int y = indexOfBinary(x); // 状态x的下标位置
lsum = travel(lsum, transTable0[y]); // 经过0到达的子集合
rsum = travel(rsum, transTable1[y]); // 经过1到达的子集合
p ^= x; // 迭代,p =p^x 剔除已经搜索的状态x,也就是最后一位
}
lft[cnt] = lsum; // 将DFA中的状态:δ(qcnt,0)保存
rgt[cnt] = rsum; // 将DFA中的状态:δ(qcnt,1)保存
cnt++; // 指针移动到下一个DFA状态
if(!visit[lsum]) // 如果lsum还没有被访问,则要迭代访问lsum
visit[lsum] = 1, DFS(lsum);
if(!visit[rsum]) // 同上
visit[rsum] = 1, DFS(rsum);
|
d90e7d26112e1f53f75ba3cbe8cc8ca49787f529
|
c3ed9fc86ec0596333a631ebd84fe8baf3e034d7
|
/oj-Project/oJ_log.hpp
|
10b5d1b41a4861420152b5e515ffd6f78b0859a2
|
[] |
no_license
|
Kaniso-Vok/Linux-code
|
5f9784968c5d49c9d4e75daf92663f79250243a9
|
1f563707d3b4622e4d20f9cb866c55b8e7764697
|
refs/heads/master
| 2021-07-07T19:55:46.567851
| 2020-12-19T07:32:06
| 2020-12-19T07:32:06
| 215,523,765
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,453
|
hpp
|
oJ_log.hpp
|
#pragma once
#include <iostream>
#include <cstdio>
#include <sys/time.h>
#include <string>
#include <string.h>
using namespace std;
//log服务也是在控制台输出
//输出格式:
//[时间 日志等级 文件:行号] 具体的日志信息
class LogTime{
public:
//获取时间戳
static int64_t GetTimeStamp(){
struct timeval tval;
gettimeofday(&tval,NULL);
return tval.tv_sec;
}
//获取格式为年-月-日 时:分:秒 的时间
static void GetTimeStamp(string* timestamp){
time_t systime;
time(&systime);
tm* st=localtime(&systime);
char buf[30]={'\0'};
snprintf(buf,sizeof(buf)-1,"%04d-%02d-%02d %02d:%02d:%02d",st->tm_year+1900,st->tm_mon+1,st->tm_mday,st->tm_hour,st->tm_min,st->tm_sec);
timestamp->assign(buf,strlen(buf));
}
};
//日志等级:INFO WARNING ERROR FATAL DEBUG
const char* level[]={
"INFO",
"WARNING",
"ERROR",
"FATAL",
"DEBUG"
};
enum LogLevel{
INFO=0,
WARNING,
ERROR,
FATAL,
DEBUG
};
inline std::ostream& Log(LogLevel lev,const char* file,int line,const string& logmsg){
string level_info=level[lev];
string timestamp;
LogTime::GetTimeStamp(×tamp);
//[时间 日志等级 文件:行号] 具体的日志信息
cout<<"["<<timestamp<<" "<<level_info<<" "<<file<<" "<<":"<<line<<"]"<<logmsg;
return std::cout;
}
#define LOG(lev,msg) Log(lev,__FILE__,__LINE__,msg)
|
601e81446a4e8649aa743a65d66adb4d98f0eed6
|
2307b57c64225ac62622349273b9298f8c6878a0
|
/gui/entity/cattlebuyscreen.cpp
|
50618b1363b886478ce82c8604edb67a558195b6
|
[
"MIT"
] |
permissive
|
MaceGabriel/GiroDeGado
|
8f417413bc3922204b52872103264189aa6bceda
|
0ea4ed5d048159fc714673dfef2828370e873f84
|
refs/heads/main
| 2023-08-09T01:17:49.990376
| 2021-08-27T21:56:01
| 2021-08-27T21:56:01
| 391,169,305
| 1
| 0
|
MIT
| 2021-08-25T01:05:45
| 2021-07-30T19:22:43
|
HTML
|
UTF-8
|
C++
| false
| false
| 2,073
|
cpp
|
cattlebuyscreen.cpp
|
#include "cattlebuyscreen.h"
#include "ui_cattlebuyscreen.h"
CattleBuyScreen::CattleBuyScreen(QWidget *parent, QWidget* backScreen, QWidget* loginScreen, Farm* f, std::string current_user) :
QDialog(parent),
ui_(new Ui::CattleBuyScreen)
{
setFixedSize(900, 600);
farm_ = f;
back_screen_ = backScreen;
login_screen_ = loginScreen;
current_user_ = current_user;
ui_->setupUi(this);
int earring = farm_->getLastEarringAvailable();
QString earring_str = QString::number(earring);
ui_->labelCattleEarring->setText("#" + earring_str);
}
CattleBuyScreen::~CattleBuyScreen()
{
delete ui_;
}
void CattleBuyScreen::on_backButton_clicked()
{
back_screen_->show();
this->close();
}
void CattleBuyScreen::on_registerButton_clicked()
{
int earring = farm_->getLastEarringAvailable();
QString breed = ui_->inputBreed->text();
std::string breed_2 = breed.toLocal8Bit().constData();
QString dateA = ui_->inputDateA->text();
std::string dateA_2 = dateA.toLocal8Bit().constData();
QString dateB = ui_->inputDateB->text();
std::string dateB_2 = dateB.toLocal8Bit().constData();
QString price = ui_->inputPrice->text();
double price_2 = price.toDouble();
QString weight = ui_->inputWeight->text();
double weight_2 = weight.toDouble();
if(price != "" && price_2 != 0){
Farm* f = getFarm();
f->createCattle(earring, breed_2, dateA_2, dateB_2, 0, 0, weight_2, price_2);
int number = farm_->getLastNumberAvailable();
f->createTransaction(number, price_2, "Compra de Gado", dateA_2, earring);
back_screen_->show();
this->close();
}
else{
if(breed_2 == "")
ui_->inputBreed->setText("A DEFINIR");
if(dateA_2 == "")
ui_->inputDateA->setText("A DEFINIR");
if(dateB_2 == "")
ui_->inputDateB->setText("A DEFINIR");
if(weight == "" || weight == "0")
ui_->inputWeight->setText("0.0");
}
}
Farm* CattleBuyScreen::getFarm()
{
return farm_;
}
|
6cce963e55ff321511971b2822527e3e8016e3e6
|
2588ad590b4df910fa5477ee84101b56dba69144
|
/List/List/DList.hpp
|
7e22f1f234660b844b89d9032c23d56b617b4f57
|
[] |
no_license
|
Mr-Jason-Sam/Algorithms
|
e6829cf55addb7a01c425f8f8c732dce1082901c
|
6f015cc63407cda1aae310aefd3b705fcc00a361
|
refs/heads/master
| 2021-01-19T10:53:22.400040
| 2019-05-23T17:06:42
| 2019-05-23T17:06:42
| 87,910,106
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 901
|
hpp
|
DList.hpp
|
//
// DList.hpp
// List
//
// Created by Jason_Sam on 21/03/2017.
// Copyright © 2017 Jason_Sam. All rights reserved.
//
#ifndef DList_hpp
#define DList_hpp
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct DListElem_{
void *data;
struct DListElem_ *prev;
struct DListElem_ *next;
}DListElem;
typedef struct DList_{
int size;
void (*destroy)(void *data);
DListElem *head;
DListElem *tail;
}DList;
DList* dlist_init(DList *list, void (*destroy)(void *data));
void dlist_destroy(DList *list);
int dlist_ins_next(DList *list, DListElem *element, const void *data);
int dlist_ins_prev(DList *list, DListElem *element, const void *data);
int dlist_remove(DList *list, DListElem *element, void **data);
int dlist_create(DList *list, const int num);
void dlist_display(DList *list, DListElem *element);
#endif /* DList_hpp */
|
8bb32721f771528630695eaf52ba9de13e16d742
|
9c3e44162c99df65ec71717e8c3c43a2593fe383
|
/tests/ChronoTest.cpp
|
34c003ff8c9102761b37387f5ca5893f3e5d8992
|
[
"MIT"
] |
permissive
|
SlavaMelanko/PocoHttpWebServer
|
b30dff2e7637ae7969a9aa752df07648449f5daf
|
17a90e0b489a94701cccf000a40728986b0b4832
|
refs/heads/master
| 2022-01-08T08:49:56.646239
| 2018-06-12T19:56:49
| 2018-06-12T19:56:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 346
|
cpp
|
ChronoTest.cpp
|
#include <regex>
#include <catch/catch.hpp>
#include <utils/Chrono.h>
TEST_CASE("Chrono: Check SORTABLE_FORMAT")
{
const auto now = utils::chrono::GetCurrentDateTime();
// 2018-01-01 00:00:01
std::regex pattern{ "\\d{4}[-]\\d{2}[-]\\d{2} \\d{2}[:]\\d{2}[:]\\d{2}" };
std::smatch match;
REQUIRE(std::regex_search(now, match, pattern));
}
|
e171fcc970faa58376057eecced7ab19d711d1ba
|
bebd8676e42fc0491be54e4c3e4407d528f0f036
|
/src/main/resources/Arduino/sketch_oct09a.ino
|
437895f219bf1833834ee9691f0502e047b58757
|
[] |
no_license
|
Bridge-Tech/ChallengePluSoft
|
d78953cda34692c84972614a2bae6f7b1615a08e
|
15dbd1fd7a59c7b85cb950ab045aecd4c34b806f
|
refs/heads/main
| 2023-08-25T00:03:27.492964
| 2021-10-24T22:49:35
| 2021-10-24T22:49:35
| 408,661,237
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 749
|
ino
|
sketch_oct09a.ino
|
#include <VarSpeedServo.h> // inclusão da bibliotecaa
VarSpeedServo servo;
void setup() {
Serial.begin(9600);
servo.attach(9);
}
char option;
void loop() {
/*
delay 1000 - speed 50
delay 700 - speed 100
delay 400 - speed 255
*/
if( Serial.available() > 0 ){
option = Serial.read();
}
Serial.print(option);
switch (option) {
case '1':
ServoMotor(1000,50);
break;
case '2':
ServoMotor(700,100);
break;
case '3':
ServoMotor(400,255);
break;
default:
servo.write(0);
break;
}
}
void ServoMotor(int delayServo ,int speedServo){
servo.slowmove(0, speedServo);
delay (delayServo);
servo.slowmove(95, speedServo);
delay (delayServo);
}
|
ffb68b729898aec41caf686e5992052987fbcc5b
|
feccd744d3cce74a928448ce0b2211fa70e09844
|
/src/appreq_serv_thread.cpp
|
f2b99d09a444a2d24b4e85b29ac62c48b18de73c
|
[
"MIT"
] |
permissive
|
original-work/wacc
|
3c3ad0944689c7fde2c59b33756a9a9b37b12711
|
3e70acf4346e2b64a118b67a4483a62273f12b05
|
refs/heads/master
| 2021-09-06T21:50:14.453456
| 2016-08-19T11:38:25
| 2016-08-19T11:38:25
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 14,579
|
cpp
|
appreq_serv_thread.cpp
|
/*
* =====================================================================================
*
* Filename: appreq_serv_thread.cpp
*
* Description:
*
* Version: 1.0
* Created: 2015/3/9 10:31:31
* Revision: none
* Compiler: gcc
*
* Author: wangxx
* Organization: lj
*
* =====================================================================================
* ============================== CHANGE REPORT HISTORY ================================
* | VERSION | UPDATE DATE | UPDATED BY | DESCRIPTION OF CHANGE |*
* =========================== END OF CHANGE REPORT HISTORY ============================
*/
#include "appreq_serv_thread.h"
#include "usracc_config.h"
#include "common_logger.h"
#include "tid_generator.h"
#include <sys/time.h>
#include <time.h>
#include "tools.h"
/*
*--------------------------------------------------------------------------------------
* Class: AppReqServThread
* Method: AppReqServThread
* Description: constructor
*--------------------------------------------------------------------------------------
*/
AppReqServThread::AppReqServThread() : CMaxEvents(1000)
{
} /* ----- end of method AppReqServThread::AppReqServThread(constructor) ----- */
AppReqServThread::~AppReqServThread()
{
} /* ----- end of method AppReqServThread::~AppReqServThread() ----- */
int AppReqServThread::open(void *args)
{
collection_server_.open();
if (start() == -1)
{
return -1;
}
return 0;
} /* ----- end of method AppReqServThread::open ----- */
int AppReqServThread::svc()
{
efd_ = epoll_create(CMaxEvents);
if (efd_ == -1)
{
return -1;
}
event_.data.fd = collection_server_.sockfd();
event_.events = EPOLLIN;
int res = epoll_ctl(efd_, EPOLL_CTL_ADD, collection_server_.sockfd(), &event_);
if (res == -1)
{
return -1;
}
events_ = (struct epoll_event*)calloc(CMaxEvents, sizeof(struct epoll_event));
for (;;) {
if(test_cancel_thread()==1) {
close_all_connection();
free(events_);
close(efd_);
all_stopped_ = true;
break;
}
if (loop_process()<0) {
continue;
}
}
return 0;
} /* ----- end of method AppReqServThread::svc ----- */
int AppReqServThread::init(InfoMemMgr *info_mem, MsgList *app_queue, MsgList *logic_queue)
{
/* 获取服务端监听端口*/
collection_server_.port(UsrAccConfig::instance().app_serv_port());
events_ = NULL;
all_stopped_ = false;
info_mgr_ = info_mem;
app_req_queue_ = app_queue;
logic_resp_queue_ = logic_queue;
current_connection_count_ = 0;
connection_count_limits_ = UsrAccConfig::instance().app_max_connection_count();
TidGenerator::instance().init();
return 0;
} /* ----- end of method AppReqServThread::init ----- */
int AppReqServThread::stop()
{
cancel_thread();
while(!all_stopped_) {
usleep(1);
}
return 0;
} /* ----- end of method AppReqServThread::stop ----- */
int AppReqServThread::my_check_epoll()
{
int nfds = epoll_wait(efd_, events_, CMaxEvents, 0);
return nfds;
} /* ----- end of method AppReqServThread::my_check_epoll ----- */
int AppReqServThread::loop_process()
{
//CommonLogger::instance().log_info("Enter into AppReqServThread loop_process");
deal_logic_resp_queue();
/* 监听连接*/
int n = my_check_epoll();
struct timeval start, end;
gettimeofday(&start, NULL);
for (int i=0; i < n; ++i)
{
/*检查是否为listen监听FD,是则执行accept建立连接,并生成连接FD */
if (events_[i].data.fd == collection_server_.sockfd())
{
// deal new connection
CommonLogger::instance().log_info("AppReqServThread: Recv new connection from APP");
CommonLogger::instance().log_info("AppReqServThread: sockfd:%d",collection_server_.sockfd());
if (deal_new_connection()<0)
{
return -1;
}
}
/* 不是listen监听FD,此连接已经建立,可以接收消息并处理 */
else if (events_[i].events & EPOLLIN)
{
// handle request
CommonLogger::instance().log_info("AppReqServThread: Recv request msg from App, fd:%d",events_[i].data.fd );
mihao_fd_= events_[i].data.fd;
handle_request(events_[i].data.fd);
}
}
gettimeofday(&end, NULL);
if (n > 0)
{
unsigned int cost = (end.tv_sec - start.tv_sec)*1000000 + (end.tv_usec - start.tv_usec);
CommonLogger::instance().log_info("AppReqServThread: client num %u, connections %u, cost %u, cost per %f", n, client_list_.size(), cost, ((float)cost)/n);
}
else
{
usleep(5);
}
return 0;
} /* ----- end of method AppReqServThread::loop_process ----- */
int AppReqServThread::handle_request(int fd)
{
BaseCollectionHandler *handler = collection_handler(fd);
if (handler != NULL)
{
if (handler->handle_recv() < 0)
{
close_connection(fd);
}
}
return 0;
} /* ----- end of method AppReqServThread::handle_request ----- */
int AppReqServThread::deal_new_connection()
{
if (current_connection_count_ >= connection_count_limits_ &&
connection_count_limits_ > 0) {
CommonLogger::instance().log_error("connection limited, cur %u, max %u",
current_connection_count_,
connection_count_limits_);
return 0;
}
BaseCollectionHandler* handler = collection_server_.deal_accept();
if (handler!=NULL) {
do {
event_.data.fd = handler->sockfd();
event_.events = EPOLLIN;
CommonLogger::instance().log_info("deal_new_connection: new sockfd:%d",handler->sockfd());
int res = epoll_ctl(efd_, EPOLL_CTL_ADD, handler->sockfd(), &event_);
if (res == -1)
{
close(handler->sockfd());
delete handler;
return -1;
}
map<int,BaseCollectionHandler*>::iterator it = client_list_.find(handler->sockfd());
if (it != client_list_.end())
{
close(it->first);
delete it->second;
client_list_.erase(handler->sockfd());
}
//pair<map<int,BaseCollectionHandler*>::iterator,bool> ret;
//ret = client_list_.insert(map<int,BaseCollectionHandler*>::value_type(handler->sockfd(), handler));
client_list_.insert(map<int,BaseCollectionHandler*>::value_type(handler->sockfd(), handler));
/*
if (ret.second == false)
{
CommonLogger::instance().log_debug("clients fd %d, %d",handler->sockfd(), client_list_.size());
return -1;
}
*/
if (connection_count_limits_>0) {
++current_connection_count_;
}
AppReqHandler *h = (AppReqHandler*)handler;
h->info_mgr(info_mgr_);
h->app_req_queue(app_req_queue_);
h->client_list(&client_list_);
handler = collection_server_.deal_accept();
} while (handler != NULL);
return 0;
}
return -1;
} /* ----- end of method AppReqServThread::deal_new_connection ----- */
int AppReqServThread::deal_logic_resp_queue()
{
char *pmsg = NULL;
unsigned int len;
char send_buf[600]= {0};
int sendlen;
//memset(send_buf,0,sizeof(send_buf));
//CommonLogger::instance().log_info("Enter into AppReqServThread deal_logic_resp_queue process");
if (logic_resp_queue_->get_front_record(pmsg, len))
{
RespMsg *resp = (RespMsg*)pmsg;
MTMsg *mt = (MTMsg*)resp->msg;
ActiveUser *user = NULL;
NIF_MSG_UNIT2 *unit = NULL;
AckMsg *ack = NULL;
MTMsg *data = NULL;
string msisdn;
//CommonLogger::instance().log_debug("deal_logic_resp_queue### %u", resp->msg_type);
switch (resp->msg_type)
{
case 4: // MT
memset(send_buf,0,sizeof(send_buf));
CommonLogger::instance().log_info("deal_logic_resp_queue: Deal MT msg, len=%d",len);
CommonLogger::instance().log_info("deal_logic_resp_queue: cd %s, tid %d", mt->cd,mt->tid);
memset(bcd_buf_,0,sizeof(bcd_buf_));
StrToBCD(mt->cd, bcd_buf_, sizeof(bcd_buf_));
user = (ActiveUser*)info_mgr_->active_usr_table_.find_num((char*)bcd_buf_, strlen(mt->cd));
if (user != NULL)
{
CommonLogger::instance().log_info("deal_logic_resp_queue: sms len=%d",mt->content_len);
unit = (NIF_MSG_UNIT2*)send_buf;
unit->head = htonl(0x1a2b3c4d);
unit->invoke = htonl(SMS_PUSH);
unit->dialog = htonl(BEGIN);
unit->length = htonl(sizeof(MTMsg));
data = (MTMsg*)(send_buf + sizeof(NIF_MSG_UNIT2) - sizeof(unsigned char*));
data->seq = mt->seq;
data->tid = htonl(mt->tid);
memcpy(data->cd, mt->cg, strlen(mt->cd));
memcpy(data->cg, mt->cg, strlen(mt->cg));
data->sms_code=mt->sms_code;
data->content_len=htonl(mt->content_len);
memcpy(data->sms_content, mt->sms_content, mt->content_len);
if (strcmp(user->msisdn,mt->cd))
{
CommonLogger::instance().log_error("deal_logic_resp_queue: Check App number fail, App=%s",user->msisdn);
}
sendlen = send_data(user->fd, send_buf, sizeof(NIF_MSG_UNIT2)-sizeof(unsigned char*)+sizeof(MTMsg));
if (sendlen != sizeof(NIF_MSG_UNIT2)-sizeof(unsigned char*)+sizeof(MTMsg))
{
CommonLogger::instance().log_info("deal_logic_resp_queue: send MT msg to %s FAIL!!! send length:%d", user->msisdn,len);
}
CommonLogger::instance().log_info("deal_logic_resp_queue: send MT msg to %s, Socket:%d, len:%d, sms_code is %u, seq is %u, tid is %u, cd is %s, cg is %s",
user->msisdn,user->fd,mt->content_len,data->sms_code,data->seq,data->tid,data->cd,data->cg);
tools::print_hex((unsigned char*)mt->sms_content,256);
}
else
CommonLogger::instance().log_info("deal_logic_resp_queue: Call find_num fail, user maybe not exist");
break;
case 5: //PING ACK
memset(send_buf,0,sizeof(send_buf));
ack = (AckMsg*)resp->msg;
CommonLogger::instance().log_info("deal_logic_resp_queue: PING ACK");
unit = (NIF_MSG_UNIT2*)send_buf;
unit->head = htonl(0x1a2b3c4d);
unit->dialog = htonl(END);
unit->invoke = htonl(ack->msg_type);
sendlen = send_data(mihao_fd_, send_buf, sizeof(NIF_MSG_UNIT2)-sizeof(unsigned char*)+sizeof(unsigned int));
if (sendlen != sizeof(NIF_MSG_UNIT2)-sizeof(unsigned char*)+sizeof(unsigned int))
{
CommonLogger::instance().log_error("deal_logic_resp_queue: send PING msg to %s FAIL!!!", mt->cd);
}
CommonLogger::instance().log_info("deal_logic_resp_queue: send PING msg to APP");
break;
case 8: // ACK
memset(send_buf,0,sizeof(send_buf));
ack = (AckMsg*)resp->msg;
msisdn = info_mgr_->find_msisdn_by_tid(ack->tid);
CommonLogger::instance().log_info("deal_logic_resp_queue: Deal ACK msg, tid=%u", ack->tid);
CommonLogger::instance().log_info("deal_logic_resp_queue: num %s, result %u", msisdn.c_str(), ack->result);
CommonLogger::instance().log_info("[%s %d] deal_logic_resp_queue: msg_type 0x%08x", __FILE__,__LINE__,ack->msg_type);
if (msisdn != "")
{
memset(bcd_buf_,0,sizeof(bcd_buf_));
StrToBCD(msisdn.c_str(), bcd_buf_, sizeof(bcd_buf_));
user = (ActiveUser*)info_mgr_->active_usr_table_.find_num((char*)bcd_buf_, msisdn.length());
if (user != NULL)
{
unit = (NIF_MSG_UNIT2*)send_buf;
unit->head = htonl(0x1a2b3c4d);
unit->dialog = htonl(END);
unit->invoke = htonl(ack->msg_type);
unit->length = htonl(sizeof(unsigned int));
*((unsigned int*)(send_buf + sizeof(NIF_MSG_UNIT2) - sizeof(unsigned char*))) = htonl(ack->result);
sendlen = send_data(user->fd, send_buf, sizeof(NIF_MSG_UNIT2)-sizeof(unsigned char*)+sizeof(unsigned int));
if (sendlen != sizeof(NIF_MSG_UNIT2)-sizeof(unsigned char*)+sizeof(unsigned int))
{
CommonLogger::instance().log_error("deal_logic_resp_queue: send ACK msg to %s FAIL!!!", mt->cd);
}
CommonLogger::instance().log_info("deal_logic_resp_queue: send ACK msg to APP");
}
else
CommonLogger::instance().log_info("deal_logic_resp_queue: Call find_num fail");
info_mgr_->remove_tid_msisdn(ack->tid);
}
else{
CommonLogger::instance().log_info("deal_logic_resp_queue: tid %u not found",ack->tid);
}
break;
default:
break;
}
CommonLogger::instance().log_error("\r\n\r\n\r\n");
logic_resp_queue_->advance_ridx();
}
else
{
usleep(1);
}
return 0;
} /* ----- end of method AppReqServThread::deal_logic_resp_queue ----- */
int AppReqServThread::send_data(int fd, char *buf, unsigned int send_size)
{
unsigned int need_send_length = send_size;
int sended_length=0;
while (need_send_length>0) {
int ret = send(fd,buf+sended_length,need_send_length,0);
CommonLogger::instance().log_info("AppReqServThread: send_data send %u Bytes", ret);
if (ret<0) {
if(errno == EINTR){
} else if(errno == EAGAIN) {
break;
} else {
return -1;
}
}else if(ret == 0){
return -1;
}
sended_length+=ret;
need_send_length-=ret;
}
return sended_length;
} /* ----- end of method AppReqServThread::send_data ----- */
BaseCollectionHandler* AppReqServThread::collection_handler(int fd)
{
map<int,BaseCollectionHandler*>::iterator iter = client_list_.find(fd);
if (iter!=client_list_.end()) {
return iter->second;
}
return NULL;
} /* ----- end of method AppReqServThread::collection_handler ----- */
int AppReqServThread::close_connection(int fd)
{
BaseCollectionHandler *handler = collection_handler(fd);
if (handler != NULL)
{
epoll_ctl(efd_, EPOLL_CTL_DEL, fd, NULL);
close(fd);
delete handler;
client_list_.erase(fd);
if (connection_count_limits_>0) {
--current_connection_count_;
}
}
return 0;
} /* ----- end of method AppReqServThread::close_connection ----- */
int AppReqServThread::close_all_connection() {
std::map<int,BaseCollectionHandler*>::iterator iter = client_list_.begin();
while (iter!=client_list_.end()) {
epoll_ctl(efd_, EPOLL_CTL_DEL, iter->first, NULL);
close(iter->first);
delete iter->second;
client_list_.erase(iter++);
if (connection_count_limits_>0) {
--current_connection_count_;
}
}
return 0;
}
bool AppReqServThread::StrToBCD(const char *Src,unsigned char *Des,int iDesLen)
{
if (NULL == Src)
{
return false;
}
if (NULL == Des)
{
return false;
}
if (0 == iDesLen)
{
return false;
}
int iSrcLen = strlen(Src);
if(iSrcLen==0)
{
memset(Des,0xFF,8);
return true;
}
if (iSrcLen > iDesLen * 2)
{
return false;
}
unsigned char chTemp = 0;
int i;
for (i = 0; i < iSrcLen; i++)
{
if (i % 2 == 0)
{
chTemp = (Src[i]-'0'); // << 4) & 0xF0;
}
else
{
chTemp = chTemp | (((Src[i]-'0')<<4) & 0xF0);
Des[i / 2] = chTemp;
}
}
if (i % 2 != 0)
{
Des[i / 2] = (chTemp|0xf0);
}
return true;
}
|
cc300940d6284d3a8851469c9f76525a613bdd9b
|
9b0d3472465e542aa440435989e2489e47dad269
|
/src/stdev.cpp
|
b15f4dc917160a8cefd75c5088e6acf88bcd6e6a
|
[] |
no_license
|
9prady9/arrayfire-benchmarks
|
1ef9df82a0ec752cdb1ac61cf22396003722a248
|
33a002ff42346c344654e9baf575ba2a3eec818d
|
refs/heads/master
| 2021-07-21T19:59:00.531861
| 2021-03-29T04:51:27
| 2021-03-29T04:51:27
| 148,154,099
| 0
| 0
| null | 2018-09-10T12:46:53
| 2018-09-10T12:46:53
| null |
UTF-8
|
C++
| false
| false
| 969
|
cpp
|
stdev.cpp
|
#include <arrayfire_benchmark.h>
#include <arrayfire.h>
#include <vector>
using af::array;
using af::randu;
using af::deviceGC;
using af::deviceMemInfo;
using std::vector;
using af::sum;
void stdevBench(benchmark::State& state, af_dtype type) {
af::dim4 aDim(state.range(0), state.range(1), state.range(2), state.range(3));
array a = randu(aDim, type);
unsigned stdevDim = state.range(4);
{ stdev(a, stdevDim); }
af::sync();
for(auto _ : state) {
stdev(a, stdevDim);
af::sync();
}
}
int main(int argc, char** argv) {
vector<af_dtype> types = {f32, f64};
benchmark::Initialize(&argc, argv);
af::benchmark::RegisterBenchmark("stdev", types, stdevBench)
->Ranges({{8, 1<<10}, {8, 1<<8}, {8, 1<<6}, {8, 1<<2}, {0, 3}})
->ArgNames({"dim0", "dim1", "dim2", "dim3", "stdevDim"})
->Unit(benchmark::kMicrosecond);
af::benchmark::AFReporter r;
benchmark::RunSpecifiedBenchmarks(&r);
}
|
60d9ef6f5e500fef7ce23e7f822e1c27c2f28257
|
10ab574d579d85a261efe0509bd38bdee7c3c529
|
/MONOPOLY.CPP
|
6ea7e8323a3af0e8a27780656427c3ee91738200
|
[
"MIT"
] |
permissive
|
choptastic/monopoly_cli
|
b6a63214540d50440e647994f7113c1e5608b71e
|
67e605b7d4323c7f85215232cbe2d6dfd8bc7d97
|
refs/heads/master
| 2020-04-06T04:40:21.182643
| 2016-09-15T19:03:20
| 2016-09-15T19:03:20
| 68,322,699
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,490
|
cpp
|
MONOPOLY.CPP
|
#include <stdlib.h>
#include <fstream.h>
#include <iomanip.h>
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <malloc.h>
const int MAXPLAYERS=8;
const int NO=0;
const int YES=1;
const int BANK=200;
const int FREEPARKING=100;
const int UNOWNED=300;
const char* SAVEFILE="monopoly.sav";
char* chance[16];
char* commchest[16];
char* properties[40];
int houses[40];
int prices[40];
int rent[40][6];
int owned[40];
int fund[MAXPLAYERS];
int position[MAXPLAYERS];
int exist[MAXPLAYERS];
int freefund=0;
void setup();
void loadinfo();
void save();
void load();
void help();
int upgradable(int prop);
int isprop(int prop);
int getrent(int prop);
int ismonopoly(int prop);
int thesame(int x, int y, int z);
void advance(int player, int spaces);
void goback(int player,int spaces);
void move(int player, int position, int passgo);
void transfer(int from, int to, int amt);
void changehouses(int prop, int amt);
void propinfo(int prop);
void funds();
void positioninfo(int player);
void createplayer(int player);
void destroy(int player);
void jail(int player);
void buy(int player, int prop, int amt);
void transferprop(int from, int to, int prop);
void restart();
void mortgagetoggle(int prop);
void listprops(int player);
void listunowned();
int interpretcommand(char line[], char &comm, int &arg1, int &arg2, int &arg3);
void main()
{
randomize();
loadinfo();
setup();
textcolor(7);
textbackground(0);
clrscr();
char comm;
int arg1,arg2,arg3,error;
char commandline[30];
//cin.getline(commandline,30);
cout << "Whoa! Productions' Monopoly assistant, v0.2\n";
while(comm!='Q')
{
cout << "Command: ";
cin.getline(commandline,30);
error=interpretcommand(commandline,comm,arg1,arg2,arg3);
if(error==-1 && comm!='Q')
cout << "Invalid Syntax\n";
else
{
switch(comm)
{
case('W'): listprops(arg1);
break;
case('U'): listunowned();
break;
case('O'): mortgagetoggle(arg1);
break;
case('L'): load();
break;
case('A'): advance(arg1, arg2);
break;
case('G'): goback(arg1, arg2);
break;
case('M'): move(arg1,arg2,YES);
break;
case('T'): transfer(arg1,arg2,arg3);
break;
case('B'): buy(arg1,arg2,arg3);
break;
case('J'): jail(arg1);
break;
case('R'): transferprop(arg1,arg2,arg3);
break;
case('H'): changehouses(arg1,arg2);
break;
case('I'): propinfo(arg1);
break;
case('F'): funds();
break;
case('K'): cout << "Free Parking: $" << freefund << endl;
break;
case('P'): positioninfo(arg1);
break;
case('C'): createplayer(arg1);
break;
case('D'): destroy(arg1);
break;
case('?'): help();
break;
case('Q'): cout << "Thank you for choosing Whoa! Productions\n";
break;
case('S'): restart();
break;
default: cout << "Invalid command\n";
}
}
save();
}
}
int isprop(int prop)
{
switch(prop)
{
case(0):
case(2):
case(4):
case(7):
case(10):
case(17):
case(20):
case(22):
case(30):
case(33):
case(36):
case(38): return NO;
default : return YES;
}
}
int upgradable( int prop)
{
switch(prop)
{
case(1):
case(3):
case(6):
case(8):
case(9):
case(11):
case(13):
case(14):
case(16):
case(18):
case(19):
case(21):
case(23):
case(24):
case(26):
case(27):
case(29):
case(31):
case(32):
case(34):
case(37):
case(39): return YES;
default: return NO;
}
}
void jail(int player)
{
if(!exist[player])
cout << "Player Nonexistant\n";
else
move(player,10,NO);
}
void buy(int player, int prop, int amt)
{
if(!exist[player])
cout << "Player Nonexistant\n";
else if(!isprop(prop))
cout << "Not a Property\n";
else if(owned[prop]!=UNOWNED)
cout << "Property already owned\n";
else if(fund[player]-amt<0)
cout << "Insufficient funds\n";
else
{
owned[prop]=player;
transfer(player,BANK,amt);
}
}
void help()
{
cout << "L = load" << endl
<< "C [player] = create" << endl
<< "D [player] = destroy" << endl
<< "A [player] [spaces] = advance" << endl
<< "M [player] [space] = move" << endl
<< "G [player] [spaces] = go back" << endl
<< "J [player] = Jail" << endl
<< "B [player] [property] [amount] = Buy" << endl
<< "R [from] [to] [property] = Transfer property" << endl
<< "H [property] [numhouses] = change amount of houses on [property] to [amount]" << endl
<< "O [property] = toggle mortgage" << endl
<< "T [from] [to] [amount] = Transfer funds" << endl
<< "I [space] = space info" << endl
<< "P [player] = space info of square [player] is on" << endl
<< "W [player] = list all properties [player] owns" << endl
<< "U = List all unowned properties" << endl
<< "F = Funds of all players" << endl
<< "K = Free Parking Fund" << endl
<< "200 = Bank (only in transfers)" << endl
<< "? = This help screen" << endl;
}
void transferprop(int from, int to, int prop)
{
if(!isprop(prop))
cout << "Not a property\n";
else if(owned[prop]!=from)
cout << "Property not owned by player " << from << endl;
else if(houses[prop]!=0)
cout << "Cannot sell a property that is developed\n";
else if(!exist[from] || !exist[to])
cout << "Player nonexistant\n";
else
owned[prop]=to;
}
int thesame(int x,int y,int z)
{
return (x==y && x==z);
}
int getrent(int prop)
{
int loop,num=0;
switch(prop)
{
case(5):
case(15):
case(25):
case(35): num=25;
for(loop=5;loop<=35;loop+=10)
if(owned[prop]==owned[loop] && prop!=loop && owned[loop]!=UNOWNED)
num*=2;
return num;
case(28):
case(12): gotoxy(wherex()-1,wherey());
cout << "amount thrown times $";
if(owned[12]==owned[28])
return 10;
else
return 4;
default: if(houses[prop]==0)
{
if(ismonopoly(prop))
return rent[prop][0]*2;
else
return rent[prop][0];
}
else
return rent[prop][houses[prop]];
}
}
int ismonopoly(int prop)
{
int num=0;
switch(prop)
{
case(1):
case(3): if(owned[1]==owned[3]) num=1;
break;
case(6):
case(8):
case(9): if(thesame(owned[6],owned[8],owned[9])) num=1;
break;
case(11):
case(13):
case(14):if(thesame(owned[11],owned[13],owned[14])) num=1;
break;
case(16):
case(18):
case(19):if(thesame(owned[16],owned[18],owned[19])) num=1;
break;
case(21):
case(23):
case(24):if(thesame(owned[21],owned[23],owned[24])) num=1;
break;
case(26):
case(27):
case(29):if(thesame(owned[26],owned[27],owned[29])) num=1;
break;
case(31):
case(32):
case(34):if(thesame(owned[31],owned[32],owned[34])) num=1;
break;
case(37):
case(39):if(owned[37]==owned[39]) num=1;
break;
}
return num;
}
void listprops(int player)
{
for(int loop=0;loop<40;loop++)
if(owned[loop]==player && isprop(loop))
cout << "Space " << loop << ": " << properties[loop] << endl;
}
void listunowned()
{
listprops(UNOWNED);
}
void mortgagetoggle(int prop)
{
if(owned[prop]==UNOWNED)
cout << "Property Unowned\n";
else if(houses[prop]>0)
cout << "Cannot mortgage properties that are developed\n";
else
{
if(houses[prop]==0)
{
fund[owned[prop]]+=(prices[prop]/2);
cout << "Mortgaged " << properties[prop] << endl;
houses[prop]=-1;
}
else
{
if(fund[owned[prop]]-(prices[prop]/2)<0)
cout << "Insufficient Funds\n";
else
{
fund[owned[prop]]-=(prices[prop]/2);
cout << "Unmortgaged " << properties[prop] << endl;
houses[prop]=0;
}
}
}
}
void advance(int player, int spaces)
{
if(!exist[player])
cout << "Player nonexistant\n";
else if(spaces<2 || spaces>12)
cout << "Invalid number of Spaces\n";
else
{
position[player]+=spaces;
if(position[player]>39)
{
transfer(BANK,player,200);
position[player]-=40;
cout << "Passed GO, player " << player << " credited $200\n";
}
positioninfo(player);
switch(position[player])
{
case(7):
case(22):
case(36): cout << chance[random(16)] << endl;
break;
case(2):
case(17):
case(33): cout << commchest[random(16)] << endl;
break;
case(30): move(player,10,NO);
break;
case(20): cout << "Player " << player << " credited $" << freefund << endl;
transfer(FREEPARKING,player,freefund);
break;
}
}
}
void goback(int player, int spaces)
{
if(!exist[player])
cout << "Nonexistant Player";
else
{
position[player]-=spaces;
if(position[player]<0)
position[player]+=40;
positioninfo(player);
}
}
void move(int player, int pos, int passgo)
{
if(!exist[player])
cout << "Player nonexistant\n";
else
{
if(passgo==YES && pos<position[player])
{
cout << "Passed GO, player " << player << " credited $200\n";
transfer(BANK,player,200);
}
position[player]=pos;
propinfo(pos);
}
}
void transfer(int from, int to, int amt)
{
if(!exist[from] || !exist[to])
cout << "Player nonexistant\n";
else
{
if(from==BANK)
fund[to]+=amt;
else if(to==BANK)
{
if(fund[from]-amt<0)
cout << "Insufficient funds\n";
else
fund[from]-=amt;
}
else if(from==FREEPARKING)
{
fund[to]+=freefund;
freefund=0;
}
else if(to==FREEPARKING)
{
if(fund[from]-amt<0)
cout << "Innsufficient funds\n";
else
{
fund[from]-=amt;
freefund+=amt;
}
}
else
{
if(fund[from]-amt<0)
cout << "Insufficient funds\n";
else
{
fund[to]+=amt;
fund[from]-=amt;
}
}
}
}
void changehouses(int prop, int amt)
{
if(!upgradable(prop))
cout << "Property Not Upgradable\n";
else if(owned[prop]==UNOWNED)
cout << "Property Unowned\n";
else if(!ismonopoly(prop))
cout << "Not a monopoly\n";
else
{
int perhouse=((prop/10)+1)*50;
if((amt-houses[prop])*perhouse>fund[owned[prop]])
cout << "Insufficient funds\n";
else if(amt>5 || amt <0)
cout << "Houses must be between 0 and 5\n";
else
{
if(amt<houses[prop])
perhouse/=2;
fund[owned[prop]]-=((amt-houses[prop])*perhouse);
houses[prop]=amt;
propinfo(prop);
}
}
}
void propinfo(int prop)
{
cout << "Property index: " << prop << endl
<< "Property Name: " << properties[prop] << endl;
if(isprop(prop))
{
if(owned[prop]==UNOWNED)
cout << "Unowned. . . it costs $" << prices[prop] << endl;
else
cout << "Owned by player " << owned[prop] << endl;
}
if(isprop(prop) && owned[prop]!=UNOWNED)
{
if(houses[prop]==-1)
cout << "Mortgaged\n";
else
{
if(upgradable(prop))
cout << "Number of houses (5 for hotel): " << houses[prop] << endl;
cout << "Rent Price: $";
cout << getrent(prop) << endl;
}
}
}
void funds()
{
for(int loop=0;loop<MAXPLAYERS;loop++)
if(exist[loop])
cout << "Player " << loop << " funds: $" << fund[loop] << endl;
}
void positioninfo(int player)
{
if(!exist[player])
cout << "Player nonexistant\n";
else
propinfo(position[player]);
}
void createplayer(int player)
{
if(exist[player])
cout << "Player " << player << " already exists\n";
else
{
exist[player]=1;
fund[player]=1500;
}
}
void destroy(int player)
{
if(!exist[player])
cout << "Player " << player << " already nonexistant\n";
else
{
exist[player]=0;
fund[player]=0;
for(int loop=0;loop<40;loop++)
if(owned[loop]==player)
owned[loop]=UNOWNED;
}
}
void restart()
{
char choice;
cout << "Are you sure you want to restart the current game (Y/N)\n";
do{
choice=toupper(getch());
}while(choice!='Y' && choice!='N');
if(choice=='Y')
setup();
else
cout << "Restart Cancelled\n";
}
void save()
{
ofstream out(SAVEFILE);
for(int loop=0;loop<40;loop++)
out << houses[loop] << endl
<< owned[loop] << endl;
for(loop=0;loop<MAXPLAYERS;loop++)
{
out<< fund[loop] << endl
<< position[loop] << endl
<< exist[loop] << endl;
}
out << freefund << endl;
out.close();
}
void load()
{
char choice;
cout << "Are you sure you want to load and end current game? (Y/N)\n";
do{
choice=toupper(getch());
}while(choice!='Y' && choice!='N');
if(choice=='Y')
{
ifstream in(SAVEFILE);
for(int loop=0;loop<40;loop++)
in >> houses[loop] >> owned[loop];
for(loop=0;loop<MAXPLAYERS;loop++)
in >> fund[loop] >> position[loop] >> exist[loop];
in >> freefund;
in.close();
}
else
cout << "Load Cancelled\n";
}
void setup()
{
for(int loop=0;loop<MAXPLAYERS;loop++)
{
exist[loop]=0;
fund[loop]=0;
position[loop]=0;
}
for(loop=0;loop<40;loop++)
{
houses[loop]=0;
owned[loop]=UNOWNED;
}
}
void loadinfo()
{
int temp;
for(int loop=0;loop<16;loop++)
{
chance[loop]=(char*)malloc(150);
commchest[loop]=(char*)malloc(150);
}
for(loop=0;loop<40;loop++)
properties[loop]=(char*)malloc(35);
ifstream ichance,icomm,iprops,iprice,irent;
ichance.open("chance.txt");
icomm.open("chest.txt");
iprops.open("squares.txt");
iprice.open("price.txt");
irent.open("rent.txt");
for(loop=0;loop<16;loop++)
{
ichance.getline(chance[loop],150);
icomm.getline(commchest[loop],150);
}
for(loop=0;loop<40;loop++)
iprops.getline(properties[loop],30);
for(loop=0;loop<22;loop++)
{
irent >> temp;
for(int i=0;i<6;i++)
irent >> rent[temp][i];
iprice >> temp;
iprice >> prices[temp];
}
for(loop=5;loop<40;loop+=10)
prices[loop]=200;
prices[12]=150;
prices[28]=150;
ichance.close();
icomm.close();
iprops.close();
irent.close();
iprice.close();
}
int interpretcommand(char line[], char &comm, int &arg1, int &arg2, int &arg3)
{
int loc=0,startloc,endloc,loop;
char a1[6],a2[6],a3[6];
for(loop=0;loop<6;loop++)
a1[loop]=a2[loop]=a3[loop]='\0';
for(loop=0;loop<50;loop++)
line[loop]=toupper(line[loop]);
loc=0;
while(line[loc]==' ')
loc++;
if((line[loc]>='A' && line[loc]<='Z') || line[loc]=='?')
{
comm=line[loc];
loc++;
}
else
return -1;
if(line[loc]!=' ' && line[loc]!='\n' && line[loc]!='\0')
return -1;
while(line[loc]==' ')
loc++;
if(line[loc]!='\n' && line[loc]!='\0')
{
startloc=loc;
while(line[loc]>='0' && line[loc]<='9')
loc++;
endloc=loc;
for(loop=0;loop<endloc-startloc;loop++)
a1[loop]=line[loop+startloc];
}
while(line[loc]==' ')
loc++;
if(line[loc]!='\n' && line[loc]!='\0')
{
startloc=loc;
while(line[loc]>='0' && line[loc]<='9')
loc++;
endloc=loc;
for(loop=0;loop<endloc-startloc;loop++)
a2[loop]=line[loop+startloc];
}
while(line[loc]==' ')
loc++;
if(line[loc]!='\n' && line[loc]!='\0')
{
startloc=loc;
while(line[loc]>='0' && line[loc]<='9')
loc++;
endloc=loc;
for(loop=0;loop<endloc-startloc;loop++)
a3[loop]=line[loop+startloc];
}
arg1=atoi(a1);
arg2=atoi(a2);
arg3=atoi(a3);
return 1;
}
|
ff57604437e3f80dedd92341c73f8764f4a0a235
|
076ba173f5b518977d30f4336c63b177a5a7f66d
|
/cases/spherical_surfers/param/init/objects/surfer__us_1o0__surftimeconst_9o0__reorientationtime_2o5/pos/group/_member/passive/choice.h
|
3fed9359a5cd44654efe1ed2dae1458f881651fb
|
[
"MIT"
] |
permissive
|
C0PEP0D/sheld0n
|
a661b27ffee7b087731f0a3e9f92c2ee26d7d560
|
a1b9a065cfaa2e3faf5a749f14201a84baa41ce9
|
refs/heads/master
| 2023-04-28T20:53:27.684636
| 2023-04-18T21:20:00
| 2023-04-18T21:20:00
| 421,041,396
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 874
|
h
|
choice.h
|
#ifndef C0P_PARAM_INIT_OBJECTS_SURFER__US_1O0__SURFTIMECONST_9O0__REORIENTATIONTIME_2O5_POS_GROUP_MEMBER_PASSIVE_CHOICE_H
#define C0P_PARAM_INIT_OBJECTS_SURFER__US_1O0__SURFTIMECONST_9O0__REORIENTATIONTIME_2O5_POS_GROUP_MEMBER_PASSIVE_CHOICE_H
#pragma once
// THIS FILE SHOULD NOT BE EDITED DIRECTLY BY THE USERS.
// THIS FILE WILL BE AUTOMATICALLY EDITED WHEN THE
// CHOOSE COMMAND IS USED
// choose your init
#include "param/init/objects/surfer__us_1o0__surftimeconst_9o0__reorientationtime_2o5/pos/group/_member/passive/position/choice.h"
namespace c0p {
template<typename TypeSurferUs1O0Surftimeconst9O0Reorientationtime2O5Step>
using InitSurferUs1O0Surftimeconst9O0Reorientationtime2O5PosGroupMemberPassive = InitSurferUs1O0Surftimeconst9O0Reorientationtime2O5PosGroupMemberPassivePosition<TypeSurferUs1O0Surftimeconst9O0Reorientationtime2O5Step>;
}
#endif
|
4f8fdbc3ad0daf8ed4709f22b1a3118911d40811
|
4ca0c84fb7af16b8470ab9ff408edd6d00c94f77
|
/Codeo/0xcf - Mirando al horizonte/0xcf.cpp
|
a0a0e0ec9ee956433d3af02ec5681fcb6322b6c3
|
[] |
no_license
|
svanegas/programming_solutions
|
87305a09dd2a2ea0c05b2e2fb703d5cd2b142fc0
|
32e5f6c566910e165effeb79ec34a8886edfccff
|
refs/heads/master
| 2020-12-23T16:03:33.848189
| 2020-10-10T18:59:58
| 2020-10-10T18:59:58
| 12,229,967
| 8
| 10
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 751
|
cpp
|
0xcf.cpp
|
#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
typedef long long ll;
const int MAXN = 500005;
int n, c, arr[MAXN];
stack<int> s, ans;
void
clear_stack(stack<int> &st) {
while (!st.empty()) st.pop();
}
int
main() {
scanf("%d", &c);
for (int z = 1; z <= c; ++z) {
clear_stack(s); clear_stack(ans);
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &arr[i]);
for (int i = n - 1; i >= 0; --i) {
while (!s.empty() && s.top() <= arr[i]) s.pop();
if (s.empty()) ans.push(-1);
else ans.push(s.top());
s.push(arr[i]);
}
printf("Case #%d:", z);
for (int i = 0; i < n; ++i) {
printf(" %d", ans.top());
ans.pop();
}
puts("");
}
return 0;
}
|
4b3958a0b3d8853a91f7aea2dc849a70cf44a1ae
|
a2ec36843fa96579cadc24e3bef03e65d23e3771
|
/leetcode/leetcode-november-challenge/3543.cpp
|
607d22dd3bb647172d90266d864becacc3cee25d
|
[] |
no_license
|
maniSHarma7575/Code_Mystery
|
01b72c83c8159acd7db36b815e8b6c37afbc811c
|
2c27fa37b7486877c63518984f583a9960631d15
|
refs/heads/master
| 2023-01-21T01:30:00.757993
| 2020-11-30T10:52:27
| 2020-11-30T10:52:27
| 262,289,318
| 3
| 0
| null | 2020-11-30T10:52:28
| 2020-05-08T10:04:36
|
C++
|
UTF-8
|
C++
| false
| false
| 300
|
cpp
|
3543.cpp
|
class Solution(object):
def smallestRepunitDivByK(self, K):
if K%10 not in {1,3,7,9}:
return -1
num=1
length=1
while True:
if num%K==0:
return length
length=length+1
num=num*10+1
|
1b9cdfb8ec230054869ef6cc8dfc3a242042bb1a
|
9ea624a093561c87e47b822008e35d40a136a953
|
/src/OpcUaClient/Client/ClientApplication.cpp
|
f6bdb5c528830b8d976a27a4f8d1e0914889a0f5
|
[
"Apache-2.0"
] |
permissive
|
ASNeG/OpcUaStack
|
399828371ed4c128360c710dcd831b41f192f27d
|
e7c365f006be878dcb588a83af9a0dde49bf2b5a
|
refs/heads/master
| 2023-08-30T16:12:24.823685
| 2022-06-27T21:35:44
| 2022-06-27T21:35:44
| 149,216,768
| 141
| 41
|
Apache-2.0
| 2023-08-22T09:10:17
| 2018-09-18T02:25:58
|
C++
|
UTF-8
|
C++
| false
| false
| 6,321
|
cpp
|
ClientApplication.cpp
|
/*
Copyright 2016-2017 Kai Huebl (kai@huebl-sgh.de)
Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser
Datei nur in Übereinstimmung mit der Lizenz erlaubt.
Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0.
Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart,
erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE
GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend.
Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen
im Rahmen der Lizenz finden Sie in der Lizenz.
Autor: Kai Huebl (kai@huebl-sgh.de)
*/
#include "OpcUaClient/Client/ClientApplication.h"
#include "OpcUaClient/ClientCommand/CommandParser.h"
#include "OpcUaClient/ClientService/ClientServiceExecute.h"
// commands
#include "OpcUaClient/ClientCommand/CommandConnect.h"
#include "OpcUaClient/ClientCommand/CommandDisconnect.h"
#include "OpcUaClient/ClientCommand/CommandRead.h"
#include "OpcUaClient/ClientCommand/CommandReadH.h"
#include "OpcUaClient/ClientCommand/CommandWrite.h"
#include "OpcUaClient/ClientCommand/CommandWriteH.h"
#include "OpcUaClient/ClientCommand/CommandDelay.h"
#include "OpcUaClient/ClientCommand/CommandNodeSetServer.h"
#include "OpcUaClient/ClientCommand/CommandNodeSetFilter.h"
#include "OpcUaClient/ClientCommand/CommandBrowse.h"
#include "OpcUaClient/ClientCommand/CommandFunction.h"
#include "OpcUaClient/ClientCommand/CommandBrowsePathToNodeId.h"
#include "OpcUaClient/ClientCommand/CommandGetEndpoint.h"
#include "OpcUaClient/ClientCommand/CommandFindServer.h"
#include "OpcUaClient/ClientCommand/CommandRegisterServer.h"
// services
#include "OpcUaClient/ClientService/ClientServiceConnect.h"
#include "OpcUaClient/ClientService/ClientServiceDisconnect.h"
#include "OpcUaClient/ClientService/ClientServiceRead.h"
#include "OpcUaClient/ClientService/ClientServiceReadH.h"
#include "OpcUaClient/ClientService/ClientServiceWrite.h"
#include "OpcUaClient/ClientService/ClientServiceWriteH.h"
#include "OpcUaClient/ClientService/ClientServiceDelay.h"
#include "OpcUaClient/ClientService/ClientServiceNodeSetServer.h"
#include "OpcUaClient/ClientService/ClientServiceNodeSetFilter.h"
#include "OpcUaClient/ClientService/ClientServiceBrowse.h"
#include "OpcUaClient/ClientService/ClientServiceFunction.h"
#include "OpcUaClient/ClientService/ClientServiceBrowsePathToNodeId.h"
#include "OpcUaClient/ClientService/ClientServiceGetEndpoint.h"
#include "OpcUaClient/ClientService/ClientServiceFindServer.h"
#include "OpcUaClient/ClientService/ClientServiceRegisterServer.h"
namespace OpcUaClient
{
ClientApplication::ClientApplication(void)
: core_()
{
core_.init();
}
ClientApplication::~ClientApplication(void)
{
core_.cleanup();
}
int
ClientApplication::run(uint32_t argc, char** argv)
{
// register command in command factory
CommandParser::addCommand("CONNECT", constructSPtr<CommandConnect>());
CommandParser::addCommand("DISCONNECT", constructSPtr<CommandDisconnect>());
CommandParser::addCommand("READ", constructSPtr<CommandRead>());
CommandParser::addCommand("WRITE", constructSPtr<CommandWrite>());
CommandParser::addCommand("READH", constructSPtr<CommandReadH>());
CommandParser::addCommand("WRITEH", constructSPtr<CommandWriteH>());
CommandParser::addCommand("DELAY", constructSPtr<CommandDelay>());
CommandParser::addCommand("NODESETSERVER", constructSPtr<CommandNodeSetServer>());
CommandParser::addCommand("NODESETFILTER", constructSPtr<CommandNodeSetFilter>());
CommandParser::addCommand("BROWSE", constructSPtr<CommandBrowse>());
CommandParser::addCommand("FUNCTION", constructSPtr<CommandFunction>());
CommandParser::addCommand("BROWSEPATHTONODEID", constructSPtr<CommandBrowsePathToNodeId>());
CommandParser::addCommand("GETENDPOINT", constructSPtr<CommandGetEndpoint>());
CommandParser::addCommand("FINDSERVER", constructSPtr<CommandFindServer>());
CommandParser::addCommand("REGISTERSERVER", constructSPtr<CommandRegisterServer>());
// register service in service factory
ClientServiceExecute::addClientService(CommandBase::Cmd_Connect, constructSPtr<ClientServiceConnect>());
ClientServiceExecute::addClientService(CommandBase::Cmd_Disconnect, constructSPtr<ClientServiceDisconnect>());
ClientServiceExecute::addClientService(CommandBase::Cmd_Read, constructSPtr<ClientServiceRead>());
ClientServiceExecute::addClientService(CommandBase::Cmd_ReadH, constructSPtr<ClientServiceReadH>());
ClientServiceExecute::addClientService(CommandBase::Cmd_Write, constructSPtr<ClientServiceWrite>());
ClientServiceExecute::addClientService(CommandBase::Cmd_WriteH, constructSPtr<ClientServiceWriteH>());
ClientServiceExecute::addClientService(CommandBase::Cmd_Delay, constructSPtr<ClientServiceDelay>());
ClientServiceExecute::addClientService(CommandBase::Cmd_NodeSetServer, constructSPtr<ClientServiceNodeSetServer>());
ClientServiceExecute::addClientService(CommandBase::Cmd_NodeSetFilter, constructSPtr<ClientServiceNodeSetFilter>());
ClientServiceExecute::addClientService(CommandBase::Cmd_Browse, constructSPtr<ClientServiceBrowse>());
ClientServiceExecute::addClientService(CommandBase::Cmd_Function, constructSPtr<ClientServiceFunction>());
ClientServiceExecute::addClientService(CommandBase::Cmd_BrowsePathToNodeId, constructSPtr<ClientServiceBrowsePathToNodeId>());
ClientServiceExecute::addClientService(CommandBase::Cmd_GetEndpoint, constructSPtr<ClientServiceGetEndpoint>());
ClientServiceExecute::addClientService(CommandBase::Cmd_FindServer, constructSPtr<ClientServiceFindServer>());
ClientServiceExecute::addClientService(CommandBase::Cmd_RegisterServer, constructSPtr<ClientServiceRegisterServer>());
// parse command line
CommandParser commandParser;
CommandBase::Vec commandBaseVec;
if (!commandParser.parse(argc, argv, commandBaseVec)) {
std::cerr << commandParser.errorString() << std::endl;
return -1;
}
// execute commands from command line line
ClientServiceExecute clientServiceExecute;
if (!clientServiceExecute.run(commandBaseVec)) {
std::cerr << clientServiceExecute.errorString() << std::endl;
return -1;
}
std::cout << "OK" << std::endl;
return 0;
}
}
|
89eadf1b71fbf10ee165b7dc7c91cc84d3898fe8
|
ca86a7775a8e4a2f7b3ee831454939062a1a2900
|
/cpp/RaspWrapCredential.cpp
|
b4b209cf2b78fdf04c02d4548d64fedb62021159
|
[] |
no_license
|
iboukris/RaspWrap
|
c84d5949dccdce937d501130139b0cc613b4de34
|
258bc8f042e1ddb137fdce1396513fdd29ced61a
|
refs/heads/master
| 2023-02-26T10:17:25.261893
| 2021-01-31T14:19:49
| 2021-02-06T19:29:01
| 334,674,734
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,372
|
cpp
|
RaspWrapCredential.cpp
|
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
#ifndef WIN32_NO_STATUS
#include <ntstatus.h>
#define WIN32_NO_STATUS
#endif
#include <unknwn.h>
#include <new>
#include "RaspWrapCredential.h"
#include "RaspWrapCredentialEvents.h"
#include "guid.h"
RaspWrapCredential::RaspWrapCredential():
_cRef(1), _bUseSSOChecked(false)
{
DllAddRef();
log("RaspWrapCredential::RaspWrapCredential(): this(%p)\n", this);
_pWrappedCredential = NULL;
_pWrappedCredentialEvents = NULL;
_pCredProvCredentialEvents = NULL;
_dwWrappedDescriptorCount = 0;
}
RaspWrapCredential::~RaspWrapCredential()
{
log("RaspWrapCredential::~RaspWrapCredential(): this(%p)\n", this);
_CleanupEvents();
if (_pWrappedCredential)
{
_pWrappedCredential->Release();
}
DllRelease();
}
// Initializes one credential with the field information passed in. We also keep track
// of our wrapped credential and how many fields it has.
HRESULT RaspWrapCredential::Initialize(
__in IConnectableCredentialProviderCredential *pWrappedCredential,
__in DWORD dwWrappedDescriptorCount)
{
HRESULT hr = S_OK;
log("RaspWrapCredential::Initialize(): this(%p)\n", this);
// Grab the credential we're wrapping for future reference.
if (_pWrappedCredential != NULL)
{
_pWrappedCredential->Release();
}
_pWrappedCredential = pWrappedCredential;
_pWrappedCredential->AddRef();
_dwWrappedDescriptorCount = dwWrappedDescriptorCount;
log("RaspWrapCredential::Initialize(): this(%p): dwWrappedDescriptorCount=%d\n",
this, dwWrappedDescriptorCount);
return hr;
}
// LogonUI calls this in order to give us a callback in case we need to notify it of
// anything. We'll also provide it to the wrapped credential.
HRESULT RaspWrapCredential::Advise(
__in ICredentialProviderCredentialEvents* pcpce
)
{
HRESULT hr = S_OK;
log("RaspWrapCredential::Advise(): this(%p)\n", this);
_CleanupEvents();
// We keep a strong reference on the real ICredentialProviderCredentialEvents
// to ensure that the weak reference held by the RaspWrapCredentialEvents is valid.
_pCredProvCredentialEvents = pcpce;
_pCredProvCredentialEvents->AddRef();
_pWrappedCredentialEvents = new (std::nothrow) RaspWrapCredentialEvents();
if (_pWrappedCredentialEvents != NULL)
{
_pWrappedCredentialEvents->Initialize(this, pcpce, _dwWrappedDescriptorCount);
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->Advise(_pWrappedCredentialEvents);
}
}
else
{
hr = E_OUTOFMEMORY;
}
return hr;
}
// LogonUI calls this to tell us to release the callback.
// We'll also provide it to the wrapped credential.
HRESULT RaspWrapCredential::UnAdvise()
{
HRESULT hr = S_OK;
log("RaspWrapCredential::UnAdvise(): this(%p)\n", this);
if (_pWrappedCredential != NULL)
{
_pWrappedCredential->UnAdvise();
}
_CleanupEvents();
return hr;
}
// LogonUI calls this function when our tile is selected (zoomed)
// If you simply want fields to show/hide based on the selected state,
// there's no need to do anything here - you can set that up in the
// field definitions. In fact, we're just going to hand it off to the
// wrapped credential in case it wants to do something.
HRESULT RaspWrapCredential::SetSelected(__out BOOL* pbAutoLogon)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::SetSelected(): this(%p)\n", this);
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->SetSelected(pbAutoLogon);
}
return hr;
}
// Similarly to SetSelected, LogonUI calls this when your tile was selected
// and now no longer is. We'll let the wrapped credential do anything it needs.
HRESULT RaspWrapCredential::SetDeselected()
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::SetDeselected(): this(%p)\n", this);
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->SetDeselected();
}
return hr;
}
// Get info for a particular field of a tile. Called by logonUI to get information to
// display the tile. We'll check to see if it's for us or the wrapped credential, and then
// handle or route it as appropriate.
HRESULT RaspWrapCredential::GetFieldState(
__in DWORD dwFieldID,
__out CREDENTIAL_PROVIDER_FIELD_STATE* pcpfs,
__out CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE* pcpfis
)
{
HRESULT hr = E_UNEXPECTED;
if (pcpfs == NULL || pcpfis == NULL)
{
return hr;
}
log("RaspWrapCredential::GetFieldState(): this(%p): dwFieldID=%d \n", this, dwFieldID);
if (dwFieldID == _dwWrappedDescriptorCount)
{
*pcpfs = CPFS_DISPLAY_IN_SELECTED_TILE;
*pcpfis = CPFIS_NONE;
return S_OK;
}
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->GetFieldState(dwFieldID, pcpfs, pcpfis);
if (SUCCEEDED(hr)) {
log("RaspWrapCredential::GetFieldState(): this(%p): dwFieldID=%d *pcpfs=%d\n", this, dwFieldID, *pcpfs);
}
}
return hr;
}
// Sets ppwsz to the string value of the field at the index dwFieldID. We'll check to see if
// it's for us or the wrapped credential, and then handle or route it as appropriate.
HRESULT RaspWrapCredential::GetStringValue(
__in DWORD dwFieldID,
__deref_out PWSTR* ppwsz
)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::GetStringValue(): this(%p): dwFieldID=%d\n", this, dwFieldID);
if (dwFieldID == _dwWrappedDescriptorCount)
{
hr = SHStrDupW(L"Use SSO", ppwsz);
}
else if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->GetStringValue(dwFieldID, ppwsz);
if (SUCCEEDED(hr))
{
log("RaspWrapCredential::GetStringValue(): %S\n", *ppwsz ? *ppwsz : L"null");
}
}
return hr;
}
// Returns the number of items to be included in the combobox (pcItems), as well as the
// currently selected item (pdwSelectedItem). We'll check to see if it's for us or the
// wrapped credential, and then handle or route it as appropriate.
HRESULT RaspWrapCredential::GetComboBoxValueCount(
__in DWORD dwFieldID,
__out DWORD* pcItems,
__out_range(<,*pcItems) DWORD* pdwSelectedItem
)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::GetComboBoxValueCount(): this(%p): dwFieldID=%d\n", this, dwFieldID);
if (dwFieldID == _dwWrappedDescriptorCount)
{
return hr;
}
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->GetComboBoxValueCount(dwFieldID, pcItems, pdwSelectedItem);
}
return hr;
}
// Called iteratively to fill the combobox with the string (ppwszItem) at index dwItem.
// We'll check to see if it's for us or the wrapped credential, and then handle or route
// it as appropriate.
HRESULT RaspWrapCredential::GetComboBoxValueAt(
__in DWORD dwFieldID,
__in DWORD dwItem,
__deref_out PWSTR* ppwszItem
)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::GetComboBoxValueAt(): this(%p): dwFieldID=%d\n", this, dwFieldID);
if (dwFieldID == _dwWrappedDescriptorCount)
{
return hr;
}
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->GetComboBoxValueAt(dwFieldID, dwItem, ppwszItem);
}
return hr;
}
// Called when the user changes the selected item in the combobox. We'll check to see if
// it's for us or the wrapped credential, and then handle or route it as appropriate.
HRESULT RaspWrapCredential::SetComboBoxSelectedValue(
__in DWORD dwFieldID,
__in DWORD dwSelectedItem
)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::SetComboBoxSelectedValue(): this(%p): dwFieldID=%d\n", this, dwFieldID);
if (dwFieldID == _dwWrappedDescriptorCount)
{
return hr;
}
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->SetComboBoxSelectedValue(dwFieldID, dwSelectedItem);
}
return hr;
}
// The following methods are for logonUI to get the values of various UI elements and
// then communicate to the credential about what the user did in that field. Even though
// we don't offer these field types ourselves, we need to pass along the request to the
// wrapped credential.
HRESULT RaspWrapCredential::GetBitmapValue(
__in DWORD dwFieldID,
__out HBITMAP* phbmp
)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::GetBitmapValue(): this(%p): dwFieldID=%d\n", this, dwFieldID);
if (dwFieldID == _dwWrappedDescriptorCount)
{
return hr;
}
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->GetBitmapValue(dwFieldID, phbmp);
}
return hr;
}
HRESULT RaspWrapCredential::GetSubmitButtonValue(
__in DWORD dwFieldID,
__out DWORD* pdwAdjacentTo
)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::GetSubmitButtonValue(): this(%p): dwFieldID=%d\n", this, dwFieldID);
if (dwFieldID == _dwWrappedDescriptorCount)
{
return hr;
}
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->GetSubmitButtonValue(dwFieldID, pdwAdjacentTo);
}
return hr;
}
HRESULT RaspWrapCredential::SetStringValue(
__in DWORD dwFieldID,
__in PCWSTR pwz
)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::SetStringValue(): this(%p): dwFieldID=%d\n", this, dwFieldID);
log("RaspWrapCredential::SetStringValue(): %S\n", pwz ? pwz : L"null");
if (dwFieldID == _dwWrappedDescriptorCount)
{
return hr;
}
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->SetStringValue(dwFieldID, pwz);
}
return hr;
}
HRESULT RaspWrapCredential::GetCheckboxValue(
__in DWORD dwFieldID,
__out BOOL* pbChecked,
__deref_out PWSTR* ppwszLabel
)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::GetCheckboxValue(): this(%p): dwFieldID=%d\n", this, dwFieldID);
if (dwFieldID == _dwWrappedDescriptorCount)
{
*pbChecked = _bUseSSOChecked;
hr = SHStrDupW(L"Use SSO", ppwszLabel); // caller should free
}
else if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->GetCheckboxValue(dwFieldID, pbChecked, ppwszLabel);
}
return hr;
}
HRESULT RaspWrapCredential::SetCheckboxValue(
__in DWORD dwFieldID,
__in BOOL bChecked
)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::SetCheckboxValue(): this(%p): dwFieldID=%d\n", this, dwFieldID);
if (dwFieldID == _dwWrappedDescriptorCount)
{
_bUseSSOChecked = bChecked;
return S_OK;
}
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->SetCheckboxValue(dwFieldID, bChecked);
}
return hr;
}
HRESULT RaspWrapCredential::CommandLinkClicked(__in DWORD dwFieldID)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::CommandLinkClicked(): this(%p): dwFieldID=%d\n", this, dwFieldID);
if (dwFieldID == _dwWrappedDescriptorCount)
{
return hr;
}
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->CommandLinkClicked(dwFieldID);
}
return hr;
}
//
// Collect the username and password into a serialized credential for the correct usage scenario
// (logon/unlock is what's demonstrated in this sample). LogonUI then passes these credentials
// back to the system to log on.
//
HRESULT RaspWrapCredential::GetSerialization(
__out CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE* pcpgsr,
__out CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* pcpcs,
__deref_out_opt PWSTR* ppwszOptionalStatusText,
__out CREDENTIAL_PROVIDER_STATUS_ICON* pcpsiOptionalStatusIcon
)
{
HRESULT hr = E_UNEXPECTED;
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->GetSerialization(pcpgsr, pcpcs, ppwszOptionalStatusText, pcpsiOptionalStatusIcon);
}
if (!_bUseSSOChecked)
{
*pcpgsr = CPGSR_NO_CREDENTIAL_FINISHED;
}
log("RaspWrapCredential::GetSerialization(): this(%p)\n", this);
return hr;
}
/* IConnectableCredentialProviderCredential */
HRESULT RaspWrapCredential::Connect(IQueryContinueWithStatus* pqcws)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::Connect(): this(%p)\n", this);
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->Connect(pqcws);
}
log("RaspWrapCredential::Connect(): this(%p) returned\n", this);
return hr;
}
HRESULT RaspWrapCredential::Disconnect()
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::Disconnect(): this(%p)\n", this);
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->Disconnect();
}
log("RaspWrapCredential::Disconnect(): this(%p) returned\n", this);
return hr;
}
// ReportResult is completely optional. However, we will hand it off to the wrapped
// credential in case they want to handle it.
HRESULT RaspWrapCredential::ReportResult(
__in NTSTATUS ntsStatus,
__in NTSTATUS ntsSubstatus,
__deref_out_opt PWSTR* ppwszOptionalStatusText,
__out CREDENTIAL_PROVIDER_STATUS_ICON* pcpsiOptionalStatusIcon
)
{
HRESULT hr = E_UNEXPECTED;
log("RaspWrapCredential::ReportResult(): this(%p)\n", this);
if (_pWrappedCredential != NULL)
{
hr = _pWrappedCredential->ReportResult(ntsStatus, ntsSubstatus, ppwszOptionalStatusText, pcpsiOptionalStatusIcon);
}
return hr;
}
void RaspWrapCredential::_CleanupEvents()
{
// Call Uninitialize before releasing our reference on the real
// ICredentialProviderCredentialEvents to avoid having an
// invalid reference.
if (_pWrappedCredentialEvents != NULL)
{
_pWrappedCredentialEvents->Uninitialize();
_pWrappedCredentialEvents->Release();
_pWrappedCredentialEvents = NULL;
}
if (_pCredProvCredentialEvents != NULL)
{
_pCredProvCredentialEvents->Release();
_pCredProvCredentialEvents = NULL;
}
}
|
1487faa085a70ce396f3d66072ffbb090bd2288c
|
2c4f360dc9bbfd5892e29341245e3374125d6b60
|
/AircraftDynamicsTestFramework/TestFrameworkFMS.cpp
|
70387cbfc39f1031f8a09c3d539ef245d756fb4e
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
mitre/FMACM
|
d5549ed4b0e26e72d8186afc77a57e4f3833d864
|
a9fb00aef7561d2cb35af1163b44dda55a48c85f
|
refs/heads/master
| 2023-09-03T01:13:05.401619
| 2023-08-16T20:48:59
| 2023-08-16T20:48:59
| 35,225,860
| 11
| 4
|
Apache-2.0
| 2018-06-27T18:07:04
| 2015-05-07T14:49:02
|
C++
|
UTF-8
|
C++
| false
| false
| 7,881
|
cpp
|
TestFrameworkFMS.cpp
|
// ****************************************************************************
// NOTICE
//
// This work was produced for the U.S. Government under Contract 693KA8-22-C-00001
// and is subject to Federal Aviation Administration Acquisition Management System
// Clause 3.5-13, Rights In Data-General, Alt. III and Alt. IV (Oct. 1996).
//
// The contents of this document reflect the views of the author and The MITRE
// Corporation and do not necessarily reflect the views of the Federal Aviation
// Administration (FAA) or the Department of Transportation (DOT). Neither the FAA
// nor the DOT makes any warranty or guarantee, expressed or implied, concerning
// the content or accuracy of these views.
//
// For further information, please contact The MITRE Corporation, Contracts Management
// Office, 7515 Colshire Drive, McLean, VA 22102-7539, (703) 983-6000.
//
// 2022 The MITRE Corporation. All Rights Reserved.
// ****************************************************************************
#include <public/CoreUtils.h>
#include <public/AlongPathDistanceCalculator.h>
#include "framework/TestFrameworkFMS.h"
#include "math/CustomMath.h"
#include "public/AircraftCalculations.h"
Units::DegreesAngle TestFrameworkFMS::MAX_BANK_ANGLE(25.0);
TestFrameworkFMS::TestFrameworkFMS()
: m_decrementing_distance_calculator(),
m_number_of_waypoints(),
m_psi(),
m_waypoint_altitude(),
m_waypoint_x(),
m_waypoint_y(),
m_mode(),
m_delta_track(),
m_turn_radius(),
m_range_start_turn(),
m_previous_range_to_next_waypoint(),
m_range_to_next_waypoint(),
m_track(),
m_length(),
m_next_waypoint_ix(),
m_nominal_ias_at_waypoint(),
m_mach_at_waypoint(),
m_constraints() {}
TestFrameworkFMS::~TestFrameworkFMS() = default;
void TestFrameworkFMS::Initialize(const std::vector<HorizontalPath> &horizontal_path) {
m_decrementing_distance_calculator =
AlongPathDistanceCalculator(horizontal_path, TrajectoryIndexProgressionDirection::DECREMENTING);
int i;
for (i = 1; i < m_number_of_waypoints; i++) {
double dx = m_waypoint_x[i] - m_waypoint_x[i - 1];
double dy = m_waypoint_y[i] - m_waypoint_y[i - 1];
auto heading = static_cast<double>(atan3(dx, dy));
m_track[i] = heading;
m_psi[i] = static_cast<double>(atan2(dy, dx));
m_length[i] = sqrt(dx * dx + dy * dy);
}
for (i = m_number_of_waypoints; i < 127; i++) {
m_track[i] = -999.9;
m_psi[i] = -999.9;
m_length[i] = -999.0;
}
m_next_waypoint_ix = 1;
m_mode = TRACKING;
m_range_to_next_waypoint = 1.0e+10;
m_previous_range_to_next_waypoint = 1.0e+10;
}
void TestFrameworkFMS::Update(const aaesim::open_source::AircraftState &state,
const std::vector<PrecalcWaypoint> &precalc_waypoints,
const std::vector<HorizontalPath> &horizontal_trajectory) {
double xWp = m_waypoint_x[m_next_waypoint_ix];
double yWp = m_waypoint_y[m_next_waypoint_ix];
double dx = xWp - state.m_x;
double dy = yWp - state.m_y;
m_previous_range_to_next_waypoint = m_range_to_next_waypoint;
m_range_to_next_waypoint = sqrt(dx * dx + dy * dy);
if (m_mode == TRACKING) {
if (m_range_to_next_waypoint > m_previous_range_to_next_waypoint && m_range_to_next_waypoint < 4000.0) {
m_next_waypoint_ix++;
if (m_next_waypoint_ix > m_number_of_waypoints - 1) {
return;
}
xWp = m_waypoint_x[m_next_waypoint_ix];
yWp = m_waypoint_y[m_next_waypoint_ix];
dx = xWp - state.m_x;
dy = yWp - state.m_y;
m_previous_range_to_next_waypoint = 1.0e+10;
m_range_to_next_waypoint = sqrt(dx * dx + dy * dy);
}
if (m_next_waypoint_ix >= m_number_of_waypoints - 1) {
m_delta_track = 0.;
} else {
m_delta_track = m_track[m_next_waypoint_ix + 1] - m_track[m_next_waypoint_ix];
}
double bank_angle_rad = CoreUtils::LimitOnInterval(m_delta_track, Units::RadiansAngle(-MAX_BANK_ANGLE).value(),
Units::RadiansAngle(MAX_BANK_ANGLE).value());
if (bank_angle_rad != 0.00) {
double gs = Units::FeetPerSecondSpeed(state.GetGroundSpeed()).value();
m_turn_radius = gs * gs / (GRAVITY_METERS_PER_SECOND / FEET_TO_METERS * tan(bank_angle_rad));
m_range_start_turn = fabs(m_turn_radius * tan(0.5 * m_delta_track));
} else {
m_turn_radius = 1.0e+10;
m_range_start_turn = 0.00;
}
if (m_range_to_next_waypoint <= (m_range_start_turn)) {
m_mode = TURNING;
m_next_waypoint_ix++;
if (m_next_waypoint_ix > m_number_of_waypoints - 1) {
return;
}
xWp = m_waypoint_x[m_next_waypoint_ix];
yWp = m_waypoint_y[m_next_waypoint_ix];
dx = xWp - state.m_x;
dy = yWp - state.m_y;
m_previous_range_to_next_waypoint = 1.0e+10;
m_range_to_next_waypoint = sqrt(dx * dx + dy * dy);
}
}
double desired_course = m_track[m_next_waypoint_ix];
// sin and cos swapped to account for heading instead of angle
double cross_track_error = -1.0 * (-dy * sin(desired_course) + dx * cos(desired_course));
double gs = Units::FeetPerSecondSpeed(state.GetGroundSpeed()).value();
double xdot = gs * sin(state.GetHeadingCcwFromEastRadians()) * cos(state.m_gamma);
double ydot = gs * cos(state.GetHeadingCcwFromEastRadians()) * cos(state.m_gamma);
double course = atan3(xdot, ydot);
double track_error = course - desired_course;
if (track_error > M_PI) {
while (track_error > M_PI) {
track_error = track_error - 2.0 * M_PI;
}
}
if (track_error < -M_PI) {
while (track_error < -M_PI) {
track_error = track_error + 2.0 * M_PI;
}
}
if (m_mode == TURNING) {
double DeltaGroundTrack = -1.0 * track_error;
if (cross_track_error < 0.00 && DeltaGroundTrack < 10.00 * DEGREES_TO_RADIAN) {
m_mode = TRACKING;
}
if (cross_track_error > 0.00 && DeltaGroundTrack > 10.00 * DEGREES_TO_RADIAN) {
m_mode = TRACKING;
}
if (fabs(cross_track_error) < 1000.0 && fabs(track_error) < 5.0 * DEGREES_TO_RADIAN) {
m_mode = TRACKING;
}
}
Units::MetersLength current_distance_to_go;
m_decrementing_distance_calculator.CalculateAlongPathDistanceFromPosition(
Units::FeetLength(state.m_x), Units::FeetLength(state.m_y), current_distance_to_go);
for (auto ix = 0; (ix < precalc_waypoints.size()); ix++) {
if (current_distance_to_go <= precalc_waypoints[ix].m_precalc_constraints.constraint_along_path_distance) {
this->m_next_waypoint_ix = m_number_of_waypoints - ix - 1;
break;
}
}
}
void TestFrameworkFMS::CopyWaypointsFromIntent(const AircraftIntent &intent_in) {
m_number_of_waypoints = intent_in.GetNumberOfWaypoints();
const AircraftIntent::RouteData &fms(intent_in.GetRouteData());
for (int j = 0; j < m_number_of_waypoints; j++) {
m_waypoint_x[j] = Units::FeetLength(fms.m_x[j]).value();
m_waypoint_y[j] = Units::FeetLength(fms.m_y[j]).value();
// m_waypoint_altitude[j] = Units::FeetLength(fms.m_nominal_altitude[j]).value();
// m_nominal_ias_at_waypoint[j] = fms.m_nominal_ias[j].value();
// m_mach_at_waypoint[j] = fms.m_mach[j];
// m_constraints[j].constraint_altHi = fms.m_high_altitude_constraint[j];
// m_constraints[j].constraint_altLow = fms.m_low_altitude_constraint[j];
// m_constraints[j].constraint_speedHi = fms.m_high_speed_constraint[j];
// m_constraints[j].constraint_speedLow = fms.m_low_speed_constraint[j];
}
}
bool TestFrameworkFMS::IsFinished() { return m_decrementing_distance_calculator.IsPassedEndOfRoute(); }
|
72334a8268459abb554c75cde065edc4286f3cca
|
592afcde25075a84292151c41a958be810c2b82d
|
/tests/unit/stat_mgr_test.cxx
|
c607ad6453c5643c377f37552a9fda48121e0ea4
|
[
"Apache-2.0",
"Zlib",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
eBay/NuRaft
|
2c854935cd377695bbb9cc6e049e7d8ece2fe829
|
e44a81d3f4d7c2993d659cbd655be023e523ffc7
|
refs/heads/master
| 2023-08-30T16:07:32.282662
| 2023-08-27T06:07:23
| 2023-08-27T06:07:23
| 199,921,433
| 888
| 199
|
Apache-2.0
| 2023-09-11T09:18:54
| 2019-07-31T20:05:08
|
C++
|
UTF-8
|
C++
| false
| false
| 2,720
|
cxx
|
stat_mgr_test.cxx
|
/************************************************************************
Copyright 2017-2019 eBay Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://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 "nuraft.hxx"
#include "stat_mgr.hxx"
#include "test_common.h"
#include <cstring>
#include <random>
#include <string>
using namespace nuraft;
namespace stat_mgr_test {
int stat_mgr_basic_test() {
stat_elem& counter = *stat_mgr::get_instance()->create_stat
(stat_elem::COUNTER, "counter");
stat_elem& gauge = *stat_mgr::get_instance()->create_stat
(stat_elem::GAUGE, "gauge");
stat_elem& histogram = *stat_mgr::get_instance()->create_stat
(stat_elem::HISTOGRAM, "histogram");
size_t exp_sum = 0;
size_t NUM = 1000;
for (size_t ii=0; ii<NUM; ++ii) {
counter++;
gauge += ii;
exp_sum += ii;
histogram += ii;
}
CHK_EQ(NUM, raft_server::get_stat_counter("counter"));
CHK_EQ(NUM, raft_server::get_stat_gauge("counter"));
CHK_EQ(exp_sum, raft_server::get_stat_counter("gauge"));
CHK_EQ(exp_sum, raft_server::get_stat_gauge("gauge"));
std::map<double, uint64_t> hist_dump;
raft_server::get_stat_histogram("histogram", hist_dump);
size_t hist_sum = 0;
for (auto& entry: hist_dump) {
TestSuite::_msg("%.1f %zu\n", entry.first, entry.second);
hist_sum += entry.second;
}
CHK_EQ(NUM, hist_sum);
raft_server::reset_stat("counter");
CHK_EQ(0, raft_server::get_stat_counter("counter"));
raft_server::reset_all_stats();
CHK_EQ(0, raft_server::get_stat_gauge("gauge"));
hist_dump.clear();
hist_sum = 0;
raft_server::get_stat_histogram("histogram", hist_dump);
for (auto& entry: hist_dump) {
TestSuite::_msg("%.1f %zu\n", entry.first, entry.second);
hist_sum += entry.second;
}
CHK_EQ(0, hist_sum);
return 0;
}
} // namespace stat_mgr_test;
using namespace stat_mgr_test;
int main(int argc, char** argv) {
TestSuite ts(argc, argv);
ts.options.printTestMessage = false;
#ifdef ENABLE_RAFT_STATS
ts.doTest( "stat mgr basic test",
stat_mgr_basic_test );
#endif
return 0;
}
|
fbd337fb7a6830f2e97740f40cc5082745ade959
|
cdda8a72c5db92fb0e1eb2d8c82a7db7520135d0
|
/lib/eventloop/EventLoop1.h
|
8f24af33cb35dd6daf93be680c10770f9e8139e7
|
[] |
no_license
|
DAN-AND-DNA/bfproxy
|
84a9193adcfafb7a1fb7c9c913b100c2f2a0a83e
|
d1b7315edaeca552fa89a6f96697c29663b55e33
|
refs/heads/master
| 2020-05-03T08:42:09.973192
| 2019-05-05T09:18:36
| 2019-05-05T09:18:36
| 178,533,403
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 690
|
h
|
EventLoop1.h
|
#pragma once
#include <common/utils.hpp>
#include <map>
#include <sys/epoll.h>
namespace dan { namespace eventloop {
class AnEvent1;
class EventLoop1 : common::NonCopyable
{
public:
EventLoop1() noexcept;
~EventLoop1() noexcept;
int Update(AnEvent1* pstNewEvent) noexcept;
void Wait() noexcept;
void Stop() {m_bStart = false;}
int GetEpollFd(){return m_iEpollFd;}
private:
void Fire(int iFired) noexcept;
private:
int m_iEpollFd;
std::map<int, AnEvent1*> m_stAllEvents; // fd : event
std::vector<struct ::epoll_event> m_stFiredEvents;
bool m_bStart;
};
}}
|
ca198d22fc66fcdc95a08b5b6d665c79997b9ef6
|
b8a359d40f3fb53799c3e367a570524f352aebe0
|
/modules/lidarlib/segmentation/groundseg/ground_filter.cpp
|
797c31a7cba73242de9c3ede688c46a8f0eca011
|
[] |
no_license
|
zbdj1992/LidarAlgorithm
|
51a2d040c627e617ed836d06d1fa7f055e886df9
|
43b931b32a4d8c7f40ff891730e4b93f139e69be
|
refs/heads/master
| 2022-11-18T03:48:40.563495
| 2020-07-16T02:16:32
| 2020-07-16T02:16:32
| 279,800,024
| 4
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,278
|
cpp
|
ground_filter.cpp
|
/**
* ground_filter.cpp
* Author: zhubin
* Created on: 2020-07-02
* Copyright (c) iRotran. All Rights Reserved
*/
#include "ground_filter.h"
#include <pcl/ModelCoefficients.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/filters/extract_indices.h>
namespace lidar_algorithm {
namespace points_process {
bool GroundFilter::init()
{
return true;
}
bool GroundFilter::groundseg(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr cloud,
pcl::PointIndices::Ptr groundp_indices)
{
groundp_indices->indices.clear();
if (!cloud->empty()) {
sac_seg(cloud,groundp_indices);
}
return true;
}
bool GroundFilter::sac_seg(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr cloud,
pcl::PointIndices::Ptr groundp_indices)
{
pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients);
pcl::SACSegmentation<pcl::PointXYZI> seg;
seg.setOptimizeCoefficients (true);
seg.setModelType (pcl::SACMODEL_PLANE);
seg.setMethodType (pcl::SAC_RANSAC);
seg.setDistanceThreshold (0.15);
seg.setMaxIterations(100);
seg.setProbability(0.95);
seg.setInputCloud (cloud);
seg.segment (*groundp_indices, *coefficients);
return true;
}
}//namespace points_process
}//namespace lidar_algorithm
|
d6b9ac7b1bf2044d93f950367b5453a45703a7ac
|
407f30aece41a66005fbe6fd151e3c6f1720c041
|
/include/DOM/BlackoutDOMNode.hpp
|
e14824a363d937ef74865b748a06d04d83747133
|
[
"MIT"
] |
permissive
|
Sage-of-Mirrors/Booldozer
|
b172a52f036e20d425862c50d8d12704cc993373
|
2a466d4a33399fecf7556a75de15030fe2e07d22
|
refs/heads/main
| 2023-08-21T14:30:29.998265
| 2022-08-08T04:13:14
| 2022-08-08T04:13:14
| 376,416,571
| 18
| 1
|
MIT
| 2021-09-11T22:35:15
| 2021-06-13T01:58:27
|
C++
|
UTF-8
|
C++
| false
| false
| 729
|
hpp
|
BlackoutDOMNode.hpp
|
#pragma once
#include "EntityDOMNode.hpp"
class LBlackoutDOMNode : public LEntityDOMNode
{
bool bIsActiveDuringBlackout;
public:
typedef LEntityDOMNode Super;
LBlackoutDOMNode(std::string name, bool isBlackoutEntity);
bool IsActiveDuringBlackout() { return bIsActiveDuringBlackout; }
static bool FilterBlackoutEntities(std::shared_ptr<LBlackoutDOMNode> node, bool isBlackoutOnly)
{
return node->bIsActiveDuringBlackout == isBlackoutOnly;
}
/*=== Type operations ===*/
// Returns whether this node is of the given type, or derives from a node of that type.
virtual bool IsNodeType(EDOMNodeType type) const override
{
if (type == EDOMNodeType::Blackout)
return true;
return Super::IsNodeType(type);
}
};
|
a758a05b20013c4cb1165dbd942d07d33246b2ef
|
1972b018572ff69a63431094f323ca656d3677e8
|
/baseboard.cpp
|
b5697431930727a6ef44fa2053504e48550be889
|
[
"JSON"
] |
permissive
|
yax571/sysinv
|
7e4f286d91aa60d61c893731542e002e5f1934d8
|
985460bd958fbc38972342fba9f687dd1c0827c7
|
refs/heads/master
| 2020-06-18T23:40:22.577634
| 2015-10-16T07:36:19
| 2015-10-16T07:36:19
| null | 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 5,192
|
cpp
|
baseboard.cpp
|
#include "stdafx.h"
#include "sysinv.h"
#include "smbios.h"
#include "baseboard.h"
// 7.3.1 Baseboard — feature flags
static LPCTSTR BOARD_FEATURES[] = {
_T("Hosting board"), // Bit 0
_T("Requires daughter board"), // Bit 1
_T("Removable"), // Bit 2
_T("Replaceable"), // Bit 3
_T("Hot swappable") // Bit 4
};
// 7.3.2 Baseboard — Board Type
static LPCTSTR BOARD_TYPE[] = {
_T("Invalid"), // 0x00 Invalid
_T("Unknown"), // 0x01 Unknown
_T("Other"), // 0x02 Other
_T("Server Blade"), // 0x03 Server Blade
_T("Connectivity Switch"), // 0x04 Connectivity Switch
_T("System Management Module"), // 0x05 System Management Module
_T("Processor Module"), // 0x06 Processor Module
_T("I/O Module"), // 0x07 I / O Module
_T("Memory Module"), // 0x08 Memory Module
_T("Daughter board"), // 0x09 Daughter board
_T("Motherboard"), // 0x0A Motherboard
_T("Processor/Memory Module"), // 0x0B Processor / Memory Module
_T("Processor/IO Module"), // 0x0C Processor / IO Module
_T("Interconnect board") // 0x0D Interconnect board
};
// Baseboard Table Type 2
PNODE EnumBaseboards()
{
PNODE baseBoardsNode = node_alloc(_T("Baseboards"), NFLG_TABLE);
PNODE node = NULL;
PNODE slotsNode = NULL;
PNODE portsNode = NULL;
PRAW_SMBIOS_DATA smbios = GetSmbiosData();
PSMBIOS_STRUCT_HEADER header = NULL;
DWORD childCount = 0;
PSMBIOS_STRUCT_HEADER childHeader = NULL;
WORD childHandle = 0;
LPTSTR unicode = NULL;
DWORD i = 0;
while (NULL != (header = GetNextStructureOfType(header, SMB_TABLE_BASEBOARD))) {
node = node_append_new(baseBoardsNode, _T("BaseBoard"), NFLG_TABLE_ROW);
// 0x04 Manufacturer
if (header->Length < 0x05) goto get_children;
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x04));
node_att_set(node, _T("Manufacturer"), unicode, 0);
LocalFree(unicode);
// 0x05 Product
if (header->Length < 0x06) goto get_children;
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x05));
node_att_set(node, _T("Product"), unicode, 0);
LocalFree(unicode);
// 0x06 Version String
if (header->Length < 0x07) goto get_children;
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x06));
node_att_set(node, _T("Version"), unicode, 0);
LocalFree(unicode);
// 0x07 Serial Number
if (header->Length < 0x08) goto get_children;
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x07));
node_att_set(node, _T("SerialNumber"), unicode, 0);
LocalFree(unicode);
// 0x08 Asset Tag
if (header->Length < 0x09) goto get_children;
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x08));
node_att_set(node, _T("AssetTag"), unicode, 0);
LocalFree(unicode);
// 0x09 Feature flags
if (header->Length < 0x0A) goto get_children;
unicode = NULL;
for (i = 0; i < ARRAYSIZE(BOARD_FEATURES); i++) {
if (CHECK_BIT(BYTE_AT_OFFSET(header, 0x09), i)) {
AppendMultiString(&unicode, BOARD_FEATURES[i]);
}
}
node_att_set_multi(node, _T("Features"), unicode, 0);
LocalFree(unicode);
// 0x0A Location in Chassis
if (header->Length < 0x0B) goto get_children;
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x0A));
node_att_set(node, _T("Location"), unicode, 0);
LocalFree(unicode);
// 0x0D Board Type
if (header->Length < 0x0E) goto get_children;
node_att_set(node, _T("Type"), SAFE_INDEX(BOARD_TYPE, BYTE_AT_OFFSET(header, 0x0D)), 0);
// Append Children
childCount = header->Length < 0x0F ? 0 : BYTE_AT_OFFSET(header, 0x0E);
get_children:
slotsNode = node_append_new(node, _T("Slots"), NFLG_TABLE);
portsNode = node_append_new(node, _T("Ports"), NFLG_TABLE);
if (0 == childCount) {
// Assume everything is a child if 0x0E is 0
// Ports (Type 8)
while (NULL != (childHeader = GetNextStructureOfType(childHeader, SMB_TABLE_PORTS))) {
node_append_child(portsNode, GetPortDetail(smbios, childHeader));
}
// Slots (Type 9)
while (NULL != (childHeader = GetNextStructureOfType(childHeader, SMB_TABLE_SLOTS))) {
node_append_child(slotsNode, GetSlotDetail(smbios, childHeader));
}
}
else {
// Enumerate explicitely linked children
for (i = 0; i < childCount; i++) {
// Prevent overflow
if (header->Length < (0x0F +(i * sizeof(WORD))))
break;
// Fetch child by handle
childHandle = WORD_AT_OFFSET(header, 0x0F + (i * sizeof(WORD)));
childHeader = GetStructureByHandle(childHandle);
if (NULL == childHeader) {
SetError(ERR_CRIT, 0, _T("Failed to get SMBIOS table with handle 0x%X which was specified as a child of Baseboard 0x%X"), childHandle, header->Handle);
continue;
}
else {
// Add node according to type
switch (childHeader->Type) {
case SMB_TABLE_PORTS:
node_append_child(portsNode, GetPortDetail(smbios, childHeader));
break;
case SMB_TABLE_SLOTS:
node_append_child(slotsNode, GetSlotDetail(smbios, childHeader));
break;
}
}
}
}
}
return baseBoardsNode;
}
|
28934864cc59783fbb59cec055d37c112bbdf2d2
|
e36128cfc5a6ef0cef1da54e536c99250fc6fd43
|
/Libs/src/YXC_Sys/Utils/YXC_OMemoryStream.cpp
|
981fb62de1614f51ee3c591b450332364831c84c
|
[] |
no_license
|
yuanqs86/native
|
f53cb48bae133976c89189e1ea879ab6854a9004
|
0a46999537260620b683296d53140e1873442514
|
refs/heads/master
| 2021-08-31T14:50:41.572622
| 2017-12-21T19:20:10
| 2017-12-21T19:20:10
| 114,990,467
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,022
|
cpp
|
YXC_OMemoryStream.cpp
|
#include <YXC_Sys/YXC_OMemoryStream.hpp>
#define MIN_WRITE_MEM (1 << 12) // 4K
namespace YXCLib
{
OMemoryStream::OMemoryStream(byte* buf_ptr, size_t buf_len)
: MemoryStream(buf_ptr, buf_len), _manage_mem(0)
{
}
OMemoryStream::OMemoryStream(size_t buf_len) : MemoryStream(NULL, 0), _manage_mem(1)
{
buf_len = (buf_len < MIN_WRITE_MEM) ? MIN_WRITE_MEM : buf_len;
this->_buf_ptr = NULL;
this->_def_buf_len = buf_len;
}
OMemoryStream::~OMemoryStream()
{
if (this->_manage_mem && this->_buf_ptr)
{
delete [] this->_buf_ptr;
}
}
void OMemoryStream::_PromiseMemory(size_t mem_size)
{
try
{
if (this->_buf_len < mem_size)
{
byte* new_ptr = NULL;
if (this->_buf_ptr == NULL)
{
mem_size = YXCLib::TMax(mem_size, this->_def_buf_len);
new_ptr = new byte[mem_size];
}
else
{
mem_size = 3 * mem_size;
new_ptr = new byte[mem_size];
memcpy(new_ptr, this->_buf_ptr, this->_buf_len);
delete [] this->_buf_ptr;
}
this->_buf_ptr = new_ptr;
this->_buf_len = mem_size;
}
}
catch (std::bad_alloc& e)
{
throw StreamException(e.what());
}
}
void OMemoryStream::_CheckValidRange(size_t cur_off, size_t need_len, size_t max_len, const char* member)
{
if (this->_manage_mem)
{
this->_PromiseMemory(cur_off + need_len);
}
else
{
this->MemoryStream::_CheckValidRange(cur_off, need_len, max_len, member);
}
}
OMemoryStream& OMemoryStream::Write(const void* buf, size_t len, const char* member)
{
this->_CheckValidRange(this->_off, len, this->_buf_len, member);
return this->WriteUnchecked(buf, len);
}
OMemoryStream& OMemoryStream::WriteString(const std::string &str, const char* member)
{
return this->Write(str.c_str(), str.size(), member);
}
OMemoryStream& OMemoryStream::WriteString(const char* str, size_t len, const char* member)
{
this->Write(&len, sizeof(size_t), member);
this->Write((const void*)str, len * sizeof(char), member);
return *this;
}
OMemoryStream& OMemoryStream::WriteString(const std::wstring &wstr, const char* member)
{
return this->Write(wstr.c_str(), wstr.size(), member);
}
OMemoryStream& OMemoryStream::WriteString(const wchar_t* wstr, size_t len, const char* member)
{
this->Write(&len, sizeof(size_t), member);
this->Write((const void*)wstr, len * sizeof(wchar_t), member);
return *this;
}
OMemoryStream& OMemoryStream::WriteUnchecked(const void *buf, size_t len) throw()
{
memcpy(this->_buf_ptr + this->_off, buf, len);
this->_off += len;
return *this;
}
OMemoryStream& OMemoryStream::WriteUnchecked(const std::string& str) throw()
{
size_t len = str.length();
this->WriteUnchecked(&len, sizeof(size_t));
this->WriteUnchecked(str.c_str(), sizeof(wchar_t));
return *this;
}
OMemoryStream& OMemoryStream::WriteUnchecked(const std::wstring& str) throw()
{
size_t len = str.length();
this->WriteUnchecked(&len, sizeof(size_t));
this->WriteUnchecked(str.c_str(), len * sizeof(wchar_t));
return *this;
}
}
|
05c32f037693a8c56c93f6c98b9a7ea6bbdf00f5
|
051f23a83a9a66cffbfb7e9bd2a82310f8757bf6
|
/src/filter.h
|
6e1b5e7a9d260c1b51e3e3e4dbb0a4f134e71a30
|
[] |
no_license
|
JanKuiken/rp3synth
|
1912bd5b74fcd742da2d8a84a3c9bb11f37d0b62
|
3741a09ed9ca10663b78533556658c660a971b06
|
refs/heads/master
| 2021-07-24T06:26:52.184986
| 2021-06-30T16:58:16
| 2021-06-30T16:58:16
| 171,031,855
| 0
| 0
| null | 2019-03-16T16:05:06
| 2019-02-16T17:35:51
|
C++
|
UTF-8
|
C++
| false
| false
| 508
|
h
|
filter.h
|
#ifndef FILTER_H
#define FILTER_H
#include <string>
enum FilterType { lowpass,
highpass
};
class Filter
{
public:
Filter(int in_rate);
void Start(double in_frequency, std::string in_type, double in_sensitifity);
double Next(double in_x);
private:
FilterType StringToFilterType(std::string in_type);
int rate;
FilterType filtertype;
double sensitifity;
double prev_x;
double prev_y;
double a_0, a_1, b_1;
};
#endif // FILTER_H
|
3a6e9d526367cd5fdabebdd7fb4d7a88fe3501cc
|
a06368ebe626e2373b3905ed7961fa2517c57ab2
|
/Week 2 Program 26.cpp
|
6f3e9b59537c650b67eb530f5d4aa1b0b1b1d254
|
[] |
no_license
|
gutty333/Practice-1
|
85fe2d171ea29fa329e953d5449bf9e7eb559bfa
|
ca88ceefe34e64a35f6ed6ad3a021a7b5a6117b7
|
refs/heads/master
| 2021-01-10T10:58:07.655402
| 2016-10-25T04:46:38
| 2016-10-25T04:46:38
| 46,999,755
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,363
|
cpp
|
Week 2 Program 26.cpp
|
/***********************************************
Box office
A theater only keeps a percentage of revenue from ticket sales, the rest goes to the distributor
Write a program that finds the profit of the theater
1. Ask the user for the name of the movie
2. How many adult and child tickets were sold
3. An adult is $6 and a child ticket is $3
4. Display a report similar to this
Movie Name: "Wheels of Fury"
Adult Tickets Sold: 382
Child Tickets Sold: 127
Gross Box Office: $2673.00
Amount Paid: $2138.00
Net Box Office: $534.60
5. Assume that the theater only keeps 20 percent of the total profit
Important!!!!!
**************************************************/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
const double adultPrice = 6, childPrice = 3, percent = .2;
string movie;
int adultTicket, childTicket;
double adultTotal, childTotal, total, theater, distributor;
cout << "What is the name of the movie? ";
getline(cin, movie);
cout << "How many adult tickets were sold? ";
cin >> adultTicket;
cout << "How many child tickets were sold? ";
cin >> childTicket;
adultTotal = adultTicket * adultPrice;
childTotal = childTicket*childPrice;
total = adultTotal + childTotal;
theater = total * percent;
distributor = total - theater;
// reminder that setw is not how many spaces you want to set
// Rather setw is how long a value will be, if the value is less than the setw than it will convert to space
// For example setw(5) << 22 = " 22"
// It turns into 3 spaces and the value of 22
// This is similar to padding
// Also note that by default things will print right align
// If you change the alignments, sometimes you need to reverse it back to align right
cout << left << setw(35) << "Movie Name:" << "\"" << movie << "\"" << endl;
cout << left << setw(35) << "Adult Tickets Sold:" << adultTicket << endl;
cout << left << setw(35) << "Child Tickets Sold:" << childTicket << endl;
cout << left << setw(35) << "Gross Box Office Profit:" << fixed << setprecision(2) << "$" << right << setw(10) << total << endl;
cout << left << setw(33) << "Gross Box Office Profit:" << "- " << "$" << right << setw(10) << distributor << endl;
cout << left << setw(35) << "Net Box Office Profit:" << "$" << right << setw(10) << theater << endl;
return 0;
}
|
5ac343c3846b579cb9ba60f474122bdd86e2b6da
|
2933025b55b34ccf0242de29c41c71a119bfb819
|
/1. Placements/3. Bitwise Algorithm/22. Finding a number.cpp
|
77fcae2b58712234ce082b1c981c713fc45e810f
|
[] |
no_license
|
rohitshakya/CodeBucket
|
460050cf3cb5ae29eac0b92fb15ddc7a5a9d9d80
|
5c3632d5860873c74cce850eb33bd89fdd77ce0a
|
refs/heads/master
| 2022-01-25T09:55:58.151327
| 2022-01-11T06:55:05
| 2022-01-11T06:55:05
| 253,870,196
| 2
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 206
|
cpp
|
22. Finding a number.cpp
|
class Solution {
public:
char findTheDifference(string s, string t) {
int res=0;
for(int i=0;i<s.length();i++)
res^=s[i];
for(int j=0;j<t.length();j++)
res^=t[j];
return char(res);
}
};
|
1d2286d15ff4deaf4ac0e50a349ede74066d7bc1
|
0e4de7b8dc768e39c051a006e18bfcf90008d502
|
/DKApps/SDL2Rml2/RmlFile.h
|
314fc3364740cf96cb2649b1c855ea54b6c131e8
|
[] |
no_license
|
aquawicket/DKTestApps
|
a35e2f391e80f53e2d431a05904882e97d7d9d00
|
813ceb3504569ce0f672d7fab465adbc5ed3009c
|
refs/heads/master
| 2023-03-05T13:29:08.102269
| 2022-06-02T14:51:55
| 2022-06-02T14:51:55
| 83,649,975
| 1
| 0
| null | 2022-06-02T14:51:56
| 2017-03-02T07:48:46
|
C++
|
UTF-8
|
C++
| false
| false
| 1,475
|
h
|
RmlFile.h
|
#pragma once
#ifndef RmlFile_H
#define RmlFile_H
#include <RmlUi/Core.h>
#include "RmlUtility.h"
#include <filesystem>
class RmlFile : public Rml::FileInterface
{
public:
RmlFile(const Rml::String& assets);
static RmlFile* Get();
static bool ChDir(const Rml::String& path);
static bool pathExists(const Rml::String path);
static bool MakeDir(const Rml::String path);
static bool PathExists(const Rml::String path);
static bool GetFilename(const Rml::String path, Rml::String& filename);
static bool VerifyPath(Rml::String& path);
static bool FileToString(const Rml::String file, Rml::String& str);
static bool GetDirectoryContents(const Rml::String& path, Rml::StringList& contents);
static bool IsDirectory(const Rml::String& path);
static bool GetExtention(const Rml::String& path, Rml::String& ext);
static bool GetExeName(Rml::String& path);
static bool GetExePath(Rml::String& path);
static bool GetModifiedTime(const Rml::String& file, Rml::String& time);
static bool RemoveExtention(Rml::String& file);
//bool FileInterface(const Rml::String& root);
virtual Rml::FileHandle Open(const Rml::String& path);
virtual void Close(Rml::FileHandle file);
virtual size_t Read(void* buffer, size_t size, Rml::FileHandle file);
virtual bool Seek(Rml::FileHandle file, long offset, int origin);
virtual size_t Tell(Rml::FileHandle file);
bool PathExists(const Rml::String& path);
Rml::String _assets;
static RmlFile* instance;
};
#endif //RmlFile_H
|
9a154a2cbb97af5faa2a8ee7be8988c457240f5a
|
c5e26167d000f9d52db0a1491c7995d0714f8714
|
/白马湖OJ/1602.cpp
|
68c7ac926a756c352fd79f06a4a56bed23ccdff3
|
[] |
no_license
|
memset0/OI-Code
|
48d0970685a62912409d75e1183080ec0c243e21
|
237e66d21520651a87764c385345e250f73b245c
|
refs/heads/master
| 2020-03-24T21:23:04.692539
| 2019-01-05T12:38:28
| 2019-01-05T12:38:28
| 143,029,281
| 18
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 804
|
cpp
|
1602.cpp
|
#include <iostream>
#include <cstdio>
using namespace std;
int a[10015], b[10015], k[10015], w[10015];
void output(int, char, int[]);
int main()
{
int n, m;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
scanf("%d", &m);
for (int i = 1; i <= n; i++)
{
scanf("%d", &b[i]);
k[i] = -1;
for (int j = 1; j <= n; j++)
{
if (a[j] == b[i]) k[i] = j;
}
}
for (int i = 1; i <= n; i++)
{
if (k[i] == -1)
{
w[i] = -1;
continue;
}
else
{w[i] = 1;
for (int j = 1; j < i; j++)
{
if (k[j] < k[i])
{
if (w[j] + 1 > w[i]) w[i] = w[j] + 1;
}
}
}
}
int max = w[1];
for (int i = 1; i <= n; i++)
{
if (w[i] > max) max = w[i];
}
cout << max;
return 0;
}
void output(int k, char c, int s[])
{
for (int i = 1; i <= k; i++)
}
|
f3c0cd2c4f6bfa5f68f4f49ee33fd70ecfc8a7b1
|
23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f
|
/AtlInternals2e/Chapter 05/MathServiceNoAttr/MathServiceNoAttr.cpp
|
9b57eaadf54fa2d8baa2b1511f81568c1948c99a
|
[] |
no_license
|
IgorYunusov/Mega-collection-cpp-1
|
c7c09e3c76395bcbf95a304db6462a315db921ba
|
42d07f16a379a8093b6ddc15675bf777eb10d480
|
refs/heads/master
| 2020-03-24T10:20:15.783034
| 2018-06-12T13:19:05
| 2018-06-12T13:19:05
| 142,653,486
| 3
| 1
| null | 2018-07-28T06:36:35
| 2018-07-28T06:36:35
| null |
UTF-8
|
C++
| false
| false
| 681
|
cpp
|
MathServiceNoAttr.cpp
|
// MathServiceNoAttr.cpp : Implementation of WinMain
#include "stdafx.h"
#include "resource.h"
#include "MathServiceNoAttr.h"
#include <stdio.h>
class CMathServiceNoAttrModule : public CAtlServiceModuleT< CMathServiceNoAttrModule, IDS_SERVICENAME >
{
public :
DECLARE_LIBID(LIBID_MathServiceNoAttrLib)
DECLARE_REGISTRY_APPID_RESOURCEID(IDR_MATHSERVICENOATTR, "{2D1CEBC5-3664-4FDA-A565-4FFC3875963A}")
};
CMathServiceNoAttrModule _AtlModule;
//
extern "C" int WINAPI _tWinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/,
LPTSTR /*lpCmdLine*/, int nShowCmd)
{
return _AtlModule.WinMain(nShowCmd);
}
|
0c5c57c3ac5186c1f470879222de947eddf2e468
|
594de70e1ce7b82e1caf7152e3e64ecdb2c54ed0
|
/src/library/textures.h
|
15e10dfa97045b60d3de954962a0718e40a951e7
|
[
"BSD-2-Clause"
] |
permissive
|
yeahren/RSXGL
|
d91762bf96bdcdf6a273595f6fc4ad7aa47c1c04
|
86f7470be2d10d5a3590851687cbe6c79b414bf5
|
refs/heads/master
| 2021-01-18T11:20:55.568029
| 2011-09-21T09:14:38
| 2011-09-21T09:14:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,074
|
h
|
textures.h
|
//-*-C++-*-
// RSXGL - Graphics library for the PS3 GPU.
//
// Copyright (c) 2011 Alexander Betts (alex.betts@gmail.com)
//
// textures.h - Private constants, types and functions related to texture maps.
#ifndef rsxgl_textures_H
#define rsxgl_textures_H
#include "gl_constants.h"
#include "rsxgl_limits.h"
#include "gl_object.h"
#include "arena.h"
#include "program.h"
#include <boost/integer/static_log2.hpp>
// These numbers correspond to what the RSX hardware expects. They are different from the numbers
// associated with the same enum's for the depth test, so they can't be shared with that.
enum rsxgl_texture_compare_funcs {
RSXGL_TEXTURE_COMPARE_NEVER = 0,
RSXGL_TEXTURE_COMPARE_GREATER = 1,
RSXGL_TEXTURE_COMPARE_EQUAL = 2,
RSXGL_TEXTURE_COMPARE_GEQUAL = 3,
RSXGL_TEXTURE_COMPARE_LESS = 4,
RSXGL_TEXTURE_COMPARE_NOTEQUAL = 5,
RSXGL_TEXTURE_COMPARE_LEQUAL = 6,
RSXGL_TEXTURE_COMPARE_ALWAYS = 7
};
enum rsxgl_sampler_wrap_modes {
RSXGL_REPEAT = 0,
RSXGL_CLAMP_TO_EDGE = 1,
RSXGL_MIRRORED_REPEAT = 2
};
enum rsxgl_sampler_filter_modes {
RSXGL_NEAREST = 0,
RSXGL_LINEAR = 1,
RSXGL_NEAREST_MIPMAP_NEAREST = 2,
RSXGL_LINEAR_MIPMAP_NEAREST = 3,
RSXGL_NEAREST_MIPMAP_LINEAR = 4,
RSXGL_LINEAR_MIPMAP_LINEAR = 5
};
struct sampler_t {
typedef bindable_gl_object< sampler_t, RSXGL_MAX_SAMPLERS, RSXGL_MAX_COMBINED_TEXTURE_IMAGE_UNITS > gl_object_type;
typedef typename gl_object_type::name_type name_type;
typedef typename gl_object_type::storage_type storage_type;
typedef typename gl_object_type::binding_bitfield_type binding_bitfield_type;
typedef typename gl_object_type::binding_type binding_type;
static storage_type & storage();
binding_bitfield_type binding_bitfield;
uint16_t wrap_s:2, wrap_t:2, wrap_r:2,
filter_min:3, filter_mag:3,
compare_mode:1, compare_func:4;
float lodBias, minLod, maxLod;
sampler_t();
void destroy() {}
};
enum rsxgl_texture_formats {
RSXGL_TEX_FORMAT_B8 = 0,
RSXGL_TEX_FORMAT_A1R5G5B5 = 1,
RSXGL_TEX_FORMAT_A4R4G4B4 = 2,
RSXGL_TEX_FORMAT_R5G6B5 = 3,
RSXGL_TEX_FORMAT_A8R8G8B8 = 4,
RSXGL_TEX_FORMAT_COMPRESSED_DXT1 = 5,
RSXGL_TEX_FORMAT_COMPRESSED_DXT23 = 6,
RSXGL_TEX_FORMAT_COMPRESSED_DXT45 = 7,
RSXGL_TEX_FORMAT_G8B8 = 8,
RSXGL_TEX_FORMAT_R6G5B5 = 9,
RSXGL_TEX_FORMAT_DEPTH24_D8 = 10,
RSXGL_TEX_FORMAT_DEPTH24_D8_FLOAT = 11,
RSXGL_TEX_FORMAT_DEPTH16 = 12,
RSXGL_TEX_FORMAT_DEPTH16_FLOAT = 13,
RSXGL_TEX_FORMAT_X16 = 14,
RSXGL_TEX_FORMAT_Y16_X16 = 15,
RSXGL_TEX_FORMAT_R5G5B5A1 = 16,
RSXGL_TEX_FORMAT_COMPRESSED_HILO8 = 17,
RSXGL_TEX_FORMAT_COMPRESSED_HILO_S8 = 18,
RSXGL_TEX_FORMAT_W16_Z16_Y16_X16_FLOAT = 19,
RSXGL_TEX_FORMAT_W32_Z32_Y32_X32_FLOAT = 20,
RSXGL_TEX_FORMAT_X32_FLOAT = 21,
RSXGL_TEX_FORMAT_D1R5G5B5 = 22,
RSXGL_TEX_FORMAT_D8R8G8B8 = 23,
RSXGL_TEX_FORMAT_Y16_X16_FLOAT = 24,
RSXGL_TEX_FORMAT_COMPRESSED_B8R8_G8R8 = 25,
RSXGL_TEX_FORMAT_COMPRESSED_R8B8_R8G8 = 26,
RSXGL_TEX_FORMAT_INVALID = 31,
RSXGL_TEX_FORMAT_SZ = 0,
RSXGL_TEX_FORMAT_LN = 0x20,
RSXGL_TEX_FORMAT_NR = 0,
RSXGL_TEX_FORMAT_UN = 0x40
};
enum rsxgl_texture_remap_outputs {
RSXGL_TEXTURE_REMAP_ZERO = 0,
RSXGL_TEXTURE_REMAP_ONE = 1,
RSXGL_TEXTURE_REMAP_REMAP = 2,
// Unused by the RSX, but used internally:
RSXGL_TEXTURE_REMAP_IGNORE = 3
};
enum rsxgl_texture_remap_inputs {
RSXGL_TEXTURE_REMAP_FROM_A = 0,
RSXGL_TEXTURE_REMAP_FROM_B = 1,
RSXGL_TEXTURE_REMAP_FROM_G = 2,
RSXGL_TEXTURE_REMAP_FROM_R = 3
};
struct texture_t {
typedef bindable_gl_object< texture_t, RSXGL_MAX_TEXTURES, RSXGL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 1 > gl_object_type;
typedef typename gl_object_type::name_type name_type;
typedef typename gl_object_type::storage_type storage_type;
typedef typename gl_object_type::binding_bitfield_type binding_bitfield_type;
typedef typename gl_object_type::binding_type binding_type;
typedef object_binding_type< buffer_t, RSXGL_MAX_COMBINED_TEXTURE_IMAGE_UNITS > buffer_binding_type;
static storage_type & storage();
binding_bitfield_type binding_bitfield;
uint32_t deleted:1, timestamp:31;
texture_t();
void destroy();
static const boost::static_log2_argument_type max_levels = boost::static_log2< RSXGL_MAX_TEXTURE_SIZE >::value + 1;
typedef boost::uint_value_t< max_levels - 1 >::least level_size_type;
typedef boost::uint_value_t< RSXGL_MAX_TEXTURE_SIZE - 1 >::least dimension_size_type;
// --- Cold:
struct level_t {
uint8_t invalid_contents:1, internalformat:5, dims:2;
dimension_size_type size[3];
void * data;
memory_t memory;
memory_arena_t::name_type arena;
level_t();
~level_t();
} levels[max_levels];
uint16_t invalid_storage:1,valid:1,immutable:1,internalformat:5, cube:1, rect:1, max_level:4, dims:2;
// --- Hot:
uint32_t format;
dimension_size_type size[3], pad;
uint32_t pitch;
uint32_t remap;
memory_t memory;
memory_arena_t::name_type arena;
sampler_t sampler;
};
struct rsxgl_context_t;
void rsxgl_textures_validate(rsxgl_context_t *,program_t &,const uint32_t);
#endif
|
112483a6ad1525371f0b97b1421a781dd5bbeedf
|
5138837a0034d705693f86debb3c4d069e09d48c
|
/HW2B/solution/read_recursively.cpp
|
1af4070c4b8fc1071a44deeef78cbd937d45993d
|
[] |
no_license
|
mv123453715/CCU_2019_Object-oriented_Programming
|
f45bc68e929bb2fa6570086a50ca382ad553bba1
|
5e538db26a2aa0d2640e969f1eba5576100764ac
|
refs/heads/master
| 2022-11-11T19:20:54.194984
| 2020-07-01T03:33:33
| 2020-07-01T03:33:33
| 276,267,301
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,320
|
cpp
|
read_recursively.cpp
|
#include "refs.h"
#include <bits/stdc++.h>
using namespace std;
//read_recursively
int read_recursively (fstream& file, RingNode*& current,RingNode*& head,int &size){
char c;
if ( !file.eof() ){
file.get(c);
//if c is \0 file.close() and current->next = head ,so we can get RingNode
if ( c == '\0' ){
file.close();
current->next = head;
current = head;
return size;
}//if
//if c is not \0 and current == NULL,current value is c and pointer current store to head;
//recursively call create RingNode
else if ( current == NULL ){
current = new RingNode();
current ->value= c;
head = current;
size++;
read_recursively (file, current,head,size);
}//else if
//if c is not \0 and current != NULL,create new RingNode()
//recursively call create RingNode
else {
RingNode* ptr1 = new RingNode();
ptr1->value = c;
current->next = ptr1;
current = current->next;
size++;
read_recursively (file, current,head,size);
return size;
}//else
}//if
}//read_recursively
|
86656c8e560cb9baea85482cded5f86bca7ad766
|
d5fdeaa6900f7bfc3aa7d3048fb803bb43b400a5
|
/GCLDProject2/.svn/pristine/db/db1d353e2d6c5674d06cdf579077e4acb3ec86a5.svn-base
|
82a2fa39ac8731d9f01f54d40a4ac02eca20a630
|
[] |
no_license
|
liu-jack/cxx_sth
|
52e1f0b190fe23fb16890cadd9efa15de59e70d0
|
986a0782d88405af83ae68ef124ff8cf19ada765
|
refs/heads/master
| 2020-05-07T13:53:03.555884
| 2017-11-17T02:26:55
| 2017-11-17T02:26:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 665
|
db1d353e2d6c5674d06cdf579077e4acb3ec86a5.svn-base
|
#include "Activity.pb.h"
#include "PlayerData.h"
#include "utility/MsgTool.h"
#include "data/ZhengWuTable.h"
#include "data/DbProxyDataMgr.h"
#include "boost/typeof/typeof.hpp"
bool PlayerData::save_zheng_wu()
{
m_ZhengWuTable.SaveMod();
return true;
}
void PlayerData::WritePlayerZhengWu(pb::GxDB_GovAffairsInfo& msg)
{
if(m_ZhengWuTable)
{
m_ZhengWuTable->SaveTo(msg);
}
}
Msg_Realize(SG2D_ZHENGWU_UPDATE, GxDB_GovAffairsInfo)
{
if(m_ZhengWuTable)
{
m_ZhengWuTable->LoadFrom(msg);
SetIsDirty(DIRTY_ZHENG_WU);
}
else
{
ZhengWuTable cell;
cell.player_id = GetPlayerId();
cell.LoadFrom(msg);
m_ZhengWuTable.SetAndAddToCache(&cell);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.