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
a964722a11fdcc75a514e008f1b31eea3c9e4541
9a7d75b0d32ca40ab26860983e769c13d45267f9
/include/win32/ListView.h
0284a40a7b56ed658f525dab5c7d7efd6d5e091b
[ "BSD-2-Clause" ]
permissive
jpd002/Play--Framework
4427b6709c819a4403f14dd41fd8f3131f5f8d48
2dadb6dfcbc855c08a6f0bdea90e0572ac4ee0b8
refs/heads/master
2023-08-31T11:40:41.713390
2023-08-27T00:35:45
2023-08-27T00:35:45
17,099,900
42
24
NOASSERTION
2022-05-19T12:48:40
2014-02-23T02:27:07
C++
UTF-8
C++
false
false
1,398
h
ListView.h
#pragma once #include "Window.h" #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x501 #endif #include <commctrl.h> namespace Framework { namespace Win32 { class CListView : public CWindow { public: CListView(HWND = 0); CListView(HWND, const RECT&, unsigned long = 0, unsigned long = WS_EX_CLIENTEDGE); virtual ~CListView(); CListView& operator =(CListView&&); int GetItemCount(); int FindItemData(unsigned long); void DeleteItem(unsigned int); bool DeleteColumn(unsigned int); void DeleteAllItems(); int InsertItem(const LVITEM&); void InsertColumn(unsigned int, const LVCOLUMN&); std::tstring GetItemText(unsigned int, unsigned int); void SetItemText(unsigned int, unsigned int, const TCHAR*); void SetItemState(unsigned int, unsigned int, unsigned int); unsigned long GetItemData(unsigned int); int GetSelection(); void SetSelection(int); void EnableGroupView(bool); int InsertGroup(const TCHAR*, unsigned int, unsigned int = -1); void RemoveAllGroups(); void SetColumnWidth(unsigned int, unsigned int); void SetExtendedListViewStyle(unsigned long); unsigned long GetExtendedListViewStyle(); void SetItemCount(int); void EnsureItemVisible(unsigned int, bool); HWND GetHeader(); }; } }
bb4327b3153f2961fffc258874da3ef478be056a
4078c657863b5ce577071f8b26627cbe7d9a9c69
/CDB/VisitsInfoView.h
8e0049dfe774bbcab656afa8d915f0de883b2968
[ "MIT" ]
permissive
polamagdygeo/ChurchDb
eff5fae99c12739975b8f6ec737771bfa6226ea0
41c593c12c51aab492c04c074af03f2fe1b2a8e7
refs/heads/master
2023-05-11T19:44:15.456072
2021-05-28T18:22:42
2021-05-28T18:22:42
280,492,384
0
0
null
null
null
null
UTF-8
C++
false
false
740
h
VisitsInfoView.h
#ifndef VISITSINFOVIEW_H #define VISITSINFOVIEW_H #include <QDialog> #include "VisitsRepo.h" #include "PersonRepo.h" namespace Ui { class VisitsInfoView; } class VisitsInfoView : public QDialog { Q_OBJECT public: explicit VisitsInfoView(int m_familyId,QWidget *parent = nullptr); ~VisitsInfoView(); private slots: void on_pushButton_mainWinReturn_3_clicked(); void on_pushButton_addVisit_clicked(); void updateSlot(); void on_pushButton_deleteVisit_clicked(); private: Ui::VisitsInfoView *ui; VisitsRepo *m_pVisitsRepo; PersonRepo *m_pPersonRepo; int m_familyId; QList<VisitModel> m_visitsList; void update(); }; #endif // VISITSINFOVIEW_H
c6d99d0e0fdaacc5fac8f9f8feb5b576a3c60bb4
222ccbf6f706edcb2e4469f796cf18b3297609e0
/src/run_crown/symbolic_memory.h
b78a0ed59f76a925a6be178da1c8050c997b5b7e
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Deeby/CROWN
333ec1c27cc5c1356d5a6c82ab9c4b16eff33d7e
e59b894fb64db0a6a8dc079e9069a976efeeac13
refs/heads/master
2020-04-12T00:56:13.858648
2018-12-14T13:15:28
2018-12-14T13:15:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,699
h
symbolic_memory.h
// This file is part of CROWN, which is distributed under the revised // BSD license. A copy of this license can be found in the file LICENSE. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE // for details. #ifndef BASE_SYMBOLIC_MEMORY_H__ #define BASE_SYMBOLIC_MEMORY_H__ #include <ext/hash_map> #include "base/basic_types.h" #include <z3.h> #include <ostream> using std::ostream; using std::string; using std::istream; namespace crown { class SymbolicExpr; class SymbolicMemory { friend class Logger; public: SymbolicMemory(); SymbolicMemory(const SymbolicMemory& m); ~SymbolicMemory(); SymbolicExpr* read(addr_t addr, Value_t val) const; bool Parse(istream &s); Z3_ast ConvertToSMT(Z3_context ctx, addr_t addr); // For debugging. void Dump() const; private: class MemElem { friend class Logger; public: MemElem(); MemElem(const MemElem& elem); MemElem(SymbolicExpr **slot); ~MemElem(); inline SymbolicExpr* read(addr_t addr, size_t n, Value_t val, const MemElem *next) const; void Dump(addr_t addr) const; bool Parse(istream &s); #if 1 static const size_t kMemElemCapacity = 32; static const size_t kOffsetMask = kMemElemCapacity - 1; static const size_t kAddrMask = ~kOffsetMask; #else static const size_t kMemElemCapacity = 4096; static const size_t kOffsetMask = kMemElemCapacity - 1; static const size_t kAddrMask = ~kOffsetMask; #endif private: SymbolicExpr* slots_[kMemElemCapacity]; }; __gnu_cxx::hash_map<addr_t, MemElem> mem_; }; } #endif // BASE_SYMBOLIC_MEMORY_H__
dbcbb965e09f14100ee5cfe6cb0ec755d21d5632
213c541abe41d53a31d69c0a35cec8543c23a83a
/remove_words_game_v3_source_byQT/check.cpp
b99c59bb558f4823f9db4cb51aa06e2b7e2db013
[]
no_license
666WXY666/WordGame
c88df5e28293f9778ead0903ca7263a0c1c10de8
ece15697004670cf99954b29e9b8d153fea87f1f
refs/heads/master
2022-11-21T23:54:12.964185
2020-07-15T02:55:24
2020-07-15T02:55:24
279,747,092
0
0
null
null
null
null
UTF-8
C++
false
false
13,070
cpp
check.cpp
#include "check.h" #include "ui_check.h" check::check(QWidget *parent) : QWidget(parent), ui(new Ui::check) { ui->setupUi(this); init_database(); init_UI(); connect_event(); } void check::init_database() { if(QSqlDatabase::contains("qt_sql_default_connection")) db2 = QSqlDatabase::database("qt_sql_default_connection"); else db2 = QSqlDatabase::addDatabase("QMYSQL","1"); db2.setHostName("127.0.0.1"); db2.setUserName("wxy"); db2.setPassword("123456"); db2.setDatabaseName("sys"); if(!db2.open()) { QMessageBox::warning(this,"打开数据库错误",db2.lastError().text()); return; } QSqlQuery query1(db2); query1.exec("create database if not exists word_game_v3 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;"); if(QSqlDatabase::contains("qt_sql_default_connection")) db = QSqlDatabase::database("qt_sql_default_connection"); else db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("127.0.0.1"); db.setUserName("wxy"); db.setPassword("123456"); db.setDatabaseName("word_game_v3"); if(!db.open()) { QMessageBox::warning(this,"打开数据库错误",db.lastError().text()); return; } QSqlQuery query; query.exec("drop table if exists check_user;"); query.exec("drop table if exists check_creater;"); query.exec("create table if not exists check_user(id int primary key auto_increment,username varchar(255),level int default 1,experience int default 0,passed_num int default 0);"); query.exec("create table if not exists check_creater(id int primary key auto_increment,username varchar(255),level int default 1,experience int default 0,create_num int default 0);"); } void check::init_UI() { //背景大小设置 setFixedSize(800,800); this->setAutoFillBackground(true); QPalette palette = this->palette(); palette.setBrush(QPalette::Background, QBrush(QPixmap("://resource/background3.jpg").scaled(800,800,Qt::IgnoreAspectRatio,Qt::SmoothTransformation))); this->setPalette(palette); //标题图标设置 this->setWindowTitle("单词消除游戏<查询信息>"); QIcon exe_iocn("://resource/logo.png"); this->setWindowIcon(exe_iocn); model=new QSqlTableModel(this); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setSortingEnabled(true); ui->type_comboBox->clear(); ui->type_comboBox->addItem("用户名"); ui->type_comboBox->addItem("等级"); ui->type_comboBox->addItem("经验"); if(type_flag==0) { ui->type_comboBox->addItem("已过关数"); model->setHeaderData(0,Qt::Horizontal,"用户名"); model->setHeaderData(1,Qt::Horizontal,"等级"); model->setHeaderData(2,Qt::Horizontal,"经验"); model->setHeaderData(3,Qt::Horizontal,"已过关数"); } else if(type_flag==1) { ui->type_comboBox->addItem("已出题数"); model->setHeaderData(0,Qt::Horizontal,"用户名"); model->setHeaderData(1,Qt::Horizontal,"等级"); model->setHeaderData(2,Qt::Horizontal,"经验"); model->setHeaderData(3,Qt::Horizontal,"已出题数"); } model->removeRows(0,model->rowCount()); ui->tableView->setModel(model); model->select(); } void check::connect_event() { connect(ui->back_pushButton,&QPushButton::clicked,this,&check::send_change_signal); } void check::showEvent(QShowEvent *) { //渐变出现 QPropertyAnimation *animation = new QPropertyAnimation(this, "windowOpacity"); animation->setDuration(200); animation->setStartValue(0); animation->setEndValue(1); animation->start(); connect(animation, &QPropertyAnimation::finished, this, &check::show); QSqlQuery query; query.exec("drop table if exists check_user;"); query.exec("drop table if exists check_creater;"); init_UI(); } void check::close_Widget() { QPropertyAnimation *animation = new QPropertyAnimation(this, "windowOpacity"); animation->setDuration(200); animation->setStartValue(1); animation->setEndValue(0); animation->start(); connect(animation, &QPropertyAnimation::finished, this, &check::close); } void check::send_change_signal() { emit change_widget_signal(); } check::~check() { delete ui; } QString check::string_to_type() { QString type=ui->type_comboBox->itemText(ui->type_comboBox->currentIndex()); if(type==QString("用户名")) { return QString("username"); } else if (type==QString("等级")) { return QString("level"); } else if (type==QString("经验")) { return QString("experience"); } else if (type==QString("已过关数")) { return QString("passed_num"); } else if (type==QString("已出题数")) { return QString("create_num"); } return type; } void check::on_check_pushButton_clicked() { QString type=string_to_type(); QString content=ui->content_lineEdit->text(); if(content.isEmpty()) { QMessageBox::warning(this,"搜索失败","搜索内容为空"); return; } else { QTcpSocket *tcpsocket=new QTcpSocket(this); QString ip=QString("127.0.0.1"); qint16 port=8888; tcpsocket->connectToHost(QHostAddress(ip),port); tcpsocket->write(QString("request check").toUtf8().data()); connect(tcpsocket,&QTcpSocket::readyRead,[=]() { QString info; QByteArray array=tcpsocket->readAll(); QString str(array); if(str==QString("request info")) { info=QString("%1,%2,%3").arg(type_flag).arg(type).arg(content); tcpsocket->write(info.toUtf8().data()); qDebug()<<info; } else if(str==QString("error")) { QMessageBox::warning(this,"查找失败","信息不存在"); qDebug()<<"error"; tcpsocket->disconnectFromHost(); tcpsocket->close(); } else { QSqlQuery query0; query0.exec("drop table if exists check_user;"); query0.exec("drop table if exists check_creater;"); query0.exec("create table if not exists check_user(id int primary key auto_increment,username varchar(255),level int default 1,experience int default 0,passed_num int default 0);"); query0.exec("create table if not exists check_creater(id int primary key auto_increment,username varchar(255),level int default 1,experience int default 0,create_num int default 0);"); QString username; int level; int experience; int num; qDebug()<<str; for (int i=0;!str.section(',',i,i).isEmpty();) { username=str.section(',',i,i); i++; level=str.section(',',i,i).toInt(); i++; experience=str.section(',',i,i).toInt(); i++; num=str.section(',',i,i).toInt(); i++; QSqlQuery query; QString sql; if(type_flag==0) { sql=QString("select * from check_user where username='%1';").arg(username); query.exec(sql); if (query.next()) { QSqlQuery query1; QString sql1=QString("update check_user set experience=%1 where username='%2';").arg(experience).arg(username); QString sql2=QString("update check_user set level=%1 where username='%2';").arg(level).arg(username); QString sql3=QString("update check_user set passed_num=%1 where username='%2';").arg(num).arg(username); query1.exec(sql1); query1.exec(sql2); query1.exec(sql3); } else { QString sql=QString("insert into check_user(username,level,experience,passed_num) value('%1',%2,%3,%4);").arg(username).arg(level).arg(experience).arg(num); query.exec(sql); } } else { sql=QString("select * from check_creater where username='%1';").arg(username); query.exec(sql); if (query.next()) { QSqlQuery query1; QString sql1=QString("update check_creater set experience=%1 where username='%2';").arg(experience).arg(username); QString sql2=QString("update check_creater set level=%1 where username='%2';").arg(level).arg(username); QString sql3=QString("update check_creater set create_num=%1 where username='%2';").arg(num).arg(username); query1.exec(sql1); query1.exec(sql2); query1.exec(sql3); } else { QString sql=QString("insert into check_creater(username,level,experience,create_num) value('%1',%2,%3,%4);").arg(username).arg(level).arg(experience).arg(num); query.exec(sql); } } } model=new QSqlTableModel(this); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setSortingEnabled(true); if(type_flag==0) { model->setTable("check_user"); model->removeColumn(0); model->setHeaderData(0,Qt::Horizontal,"用户名"); model->setHeaderData(1,Qt::Horizontal,"等级"); model->setHeaderData(2,Qt::Horizontal,"经验"); model->setHeaderData(3,Qt::Horizontal,"已过关数"); } else { model->setTable("check_creater"); model->removeColumn(0); model->setHeaderData(0,Qt::Horizontal,"用户名"); model->setHeaderData(1,Qt::Horizontal,"等级"); model->setHeaderData(2,Qt::Horizontal,"经验"); model->setHeaderData(3,Qt::Horizontal,"已出题数"); } ui->tableView->setModel(model); model->select(); tcpsocket->disconnectFromHost(); tcpsocket->close(); } }); } } void check::on_all_pushButton_clicked() { // model=new QSqlTableModel(this); // model->setTable("user"); // ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); // ui->tableView->setSortingEnabled(true); // if(type_flag==0) // { // ui->type_comboBox->clear(); // ui->type_comboBox->addItem("用户名"); // ui->type_comboBox->addItem("等级"); // ui->type_comboBox->addItem("经验"); // ui->type_comboBox->addItem("已过关数"); // model->setTable("user"); // model->removeColumn(0); // model->removeColumn(1); // model->setHeaderData(0,Qt::Horizontal,"用户名"); // model->setHeaderData(1,Qt::Horizontal,"等级"); // model->setHeaderData(2,Qt::Horizontal,"经验"); // model->setHeaderData(3,Qt::Horizontal,"已过关数"); // } // else if(type_flag==1) // { // ui->type_comboBox->clear(); // ui->type_comboBox->addItem("用户名"); // ui->type_comboBox->addItem("等级"); // ui->type_comboBox->addItem("经验"); // ui->type_comboBox->addItem("已出题数"); // model->setTable("creater"); // model->removeColumn(0); // model->removeColumn(1); // model->setHeaderData(0,Qt::Horizontal,"用户名"); // model->setHeaderData(1,Qt::Horizontal,"等级"); // model->setHeaderData(2,Qt::Horizontal,"经验"); // model->setHeaderData(3,Qt::Horizontal,"已出题数"); // } // ui->tableView->setModel(model); // model->select(); }
ed95308536ddf7939262c114797f768eb6ffff21
6f2851bb06ca514bdb2263611315a4119495d13f
/KursachTP/car.h
d70eb06e4f9d3541fe0da226b2107b7b69207245
[]
no_license
rorrq/KursachTP
f597150ddf92c703c9e63e4c28ad9324b54a8448
e8f2c7e9f069ecf1d21bd177ddcf7ff779581059
refs/heads/master
2022-10-07T16:30:49.661669
2020-06-11T15:28:03
2020-06-11T15:28:03
271,341,831
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,591
h
car.h
#pragma once #include <iostream> #include <fstream> #include "exceptions.h" class car { public: car(); car& operator=(const car& Obj); friend std::ostream& operator<<(std::ostream& os, const car& Obj); friend std::istream& operator>>(std::istream& is, car& Obj); friend std::ofstream& operator<<(std::ofstream& ofs, const car& Obj); friend std::ifstream& operator>>(std::ifstream& ifs, car& Obj); friend bool operator==(const car& Obj1, const car& Obj2); bool check(const std::string& model) const; friend void move(car& Obj1, car& Obj2); const std::string& get_model() const; const std::string& get_color() const; void set_model(const std::string model); bool is_pattern() const; private: std::string model; //Модель std::string color; //Цвет int year; //Год выпуска int airbags; //Кол-во подушек безопасности double capacity; //объем двигателя в литрах double power; //Мощность двигателя в кВТ double fuelTank; //Объем топливного бака в литрах double fuelCons; //Расход топлива на 100км bool rdrHeat; //Подогрев руля bool gearBox; //АКПП или МКПП bool ABS; //ABS bool EDS; //EDS bool sysNav; //Система навигации bool computer; //Бортовой компьютер bool seatHead; //Подогрев сидений bool roofRack; //Багажник на крышу double x; //Длина double y; //Ширина double z; //Высота };
edea6bb384b25180010f4aa50bd69007d75857f7
b264a0a7435a991c7803102d62fcc136b13c784c
/Calculator.cpp
b24b73c29b9253c6982e3982854a7ed52d453214
[]
no_license
Sammy2022/SammyJammy
ebbbb1e67901d4544b4df751fabbe972f1cedd6b
2bb9b216c703db4018483c94a4ee8e3f474477e4
refs/heads/main
2023-07-12T10:49:21.584003
2021-08-10T07:05:47
2021-08-10T07:05:47
393,329,469
0
0
null
null
null
null
UTF-8
C++
false
false
822
cpp
Calculator.cpp
// // main.cpp // Calculator // // Created by samarth kumar on 06/08/21. // /* Calculator using switch case*/ #include<iostream> using namespace std; int main() { char oper; float num1,num2; cout<<" Please Enter 2 Numbers:"<<endl; cin>>num1>>num2; cout<<"Enter an operation(+,-,*,/):"<<endl; cin>>oper; switch(oper) { case'+': cout<<num1<<"+"<<num2<<"="<<num1+num2; // ADDITION// break; case'-': cout<<num1<<"-"<<num2<<"="<<num1-num2; //SUBTACTION// break; case'*': cout<<num1<<"*"<<num2<<"="<<num1*num2; //MULTIPLY// break; case'/': cout<<num1<<"/"<<num2<<"="<<num1/num2; //DIVIDE// break; default: cout<<"Error!! You've Entered the wrong operand"<<endl; } return 0; }
683a5f92e386ac2379f463ef3eabeaf345663a59
f28782d02a8fa301be9e08496c7341762462bc2c
/DataStruct/栈与队列/buct1959全排列.cpp
355467f33da35dcac1dba234b8e0594291e52f9c
[]
no_license
BUCTdarkness/JiyiShen-s-Coding
4dcd265c9e65d6c7dee21d87bb76420f39ace3b2
9957c10e222f15686459e5a7c909404e7e7ff536
refs/heads/master
2016-09-06T16:50:31.586323
2015-03-22T01:44:56
2015-03-22T01:44:56
32,655,388
2
0
null
null
null
null
UTF-8
C++
false
false
642
cpp
buct1959全排列.cpp
#include<iostream> #include<algorithm> #include<string.h> using namespace std; char s[10],ans[10],pre[1000][10]; int vis[10]; int len,p; void dfs(int count) { if(count==len) { int flag=1; for(int k=0;k<p;k++) { if(strcmp(ans,pre[k])==0) { flag=0; break; } } if(flag) { cout<<ans<<endl; strcpy(pre[p],ans); p++; } return; } for(int i=0;i<len;i++) { if(!vis[i]) { vis[i]=1; ans[count]=s[i]; dfs(count+1); vis[i]=0; } } } int main() { while(gets(s)) { memset(vis,0,sizeof(vis)); memset(ans,'\0',sizeof(ans)); len=strlen(s); p=0; dfs(0); cout<<endl; } return 0; }
05c913eb9de94e769f651718d620857ac58a2dcb
d696095a5f8f8f14ee17f53a96dcf3b2a66b1c0c
/BFS_1697_v2.cpp
4997bacf512bbc3a0a14e32cb7f78e7d0f6dc8e2
[]
no_license
xhoneybee23/Algorithm-Master
bbba78b0759d9477c94cee51a69cb673f9c2e7ce
a9d20f0b91924f8850e272c61c1cc0d3e52f9972
refs/heads/master
2022-04-02T06:15:23.337257
2019-10-16T12:02:42
2019-10-16T12:02:42
91,090,329
0
0
null
null
null
null
UTF-8
C++
false
false
1,087
cpp
BFS_1697_v2.cpp
#include <iostream> #include <queue> using namespace std; int main() { int s, d; int dist[100001] = { 0 }; bool check[100001] = { false }; cin >> s >> d; queue <int> q; q.push(s); dist[s] = 0; check[s] = true; while (!q.empty()){ int x = q.front(); q.pop(); // 여기서 x값을 destination과 비교해서 바로 dist값을 출력하면 시간복잡도를 줄일 수 있다. // 굳이 모든 값에 대한 dist값을 계산하지 않고 원하는 값의 dist 값을 찾으면 끝내기 때문에 if (x == d) { cout << dist[x] << endl; break; } int s_1 = x + 1; if (s_1 >= 0 && s_1 <= 100000 && check[s_1] == false){ q.push(s_1); dist[s_1] = dist[x] + 1; check[s_1] = true; } int s_2 = x - 1; if (s_2 >= 0 && s_2 <= 100000 && check[s_2] == false){ q.push(s_2); dist[s_2] = dist[x] + 1; check[s_2] = true; } int s_3 = 2 * x; if (s_3 >= 0 && s_3 <= 100000 && check[s_3] == false){ q.push(s_3); dist[s_3] = dist[x] + 1; check[s_3] = true; } } return 0; }
e8636989aefc9cacc485aadd6eea9914b8d0592e
3be032c14c9b659ba4c1dfd599f8c85257688317
/dist/ios/src/_root.app18_ButtonEntry_Value_Property.cpp
d33b3390d311ee2c7452437f87eeaa45e1f925cb
[]
no_license
gncvalente/18app
5433674c6f86d204af81290aa61eef07bb897cf5
40968aa4e3e7c044ce14cd2488313dd5a45d9b1b
refs/heads/master
2021-07-21T01:43:39.091532
2017-10-31T12:44:48
2017-10-31T12:44:48
106,106,556
3
0
null
2017-10-07T15:02:43
2017-10-07T15:02:43
null
UTF-8
C++
false
false
4,379
cpp
_root.app18_ButtonEntry_Value_Property.cpp
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno. // WARNING: Changes might be lost if you edit this file directly. #include <_root.app18_ButtonEntry_Value_Property.h> #include <_root.ButtonEntry.h> #include <Uno.Bool.h> #include <Uno.UX.IPropertyListener.h> #include <Uno.UX.PropertyObject.h> #include <Uno.UX.Selector.h> static uType* TYPES[1]; namespace g{ // internal sealed class app18_ButtonEntry_Value_Property :446 // { static void app18_ButtonEntry_Value_Property_build(uType* type) { ::TYPES[0] = ::g::ButtonEntry_typeof(); type->SetBase(::g::Uno::UX::Property1_typeof()->MakeType(::g::Uno::String_typeof(), NULL)); type->SetFields(1, ::TYPES[0/*ButtonEntry*/], offsetof(app18_ButtonEntry_Value_Property, _obj), uFieldFlagsWeak); } ::g::Uno::UX::Property1_type* app18_ButtonEntry_Value_Property_typeof() { static uSStrong< ::g::Uno::UX::Property1_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::UX::Property1_typeof(); options.FieldCount = 2; options.ObjectSize = sizeof(app18_ButtonEntry_Value_Property); options.TypeSize = sizeof(::g::Uno::UX::Property1_type); type = (::g::Uno::UX::Property1_type*)uClassType::New("app18_ButtonEntry_Value_Property", options); type->fp_build_ = app18_ButtonEntry_Value_Property_build; type->fp_Get1 = (void(*)(::g::Uno::UX::Property1*, ::g::Uno::UX::PropertyObject*, uTRef))app18_ButtonEntry_Value_Property__Get1_fn; type->fp_get_Object = (void(*)(::g::Uno::UX::Property*, ::g::Uno::UX::PropertyObject**))app18_ButtonEntry_Value_Property__get_Object_fn; type->fp_Set1 = (void(*)(::g::Uno::UX::Property1*, ::g::Uno::UX::PropertyObject*, void*, uObject*))app18_ButtonEntry_Value_Property__Set1_fn; type->fp_get_SupportsOriginSetter = (void(*)(::g::Uno::UX::PropertyAccessor*, bool*))app18_ButtonEntry_Value_Property__get_SupportsOriginSetter_fn; return type; } // public app18_ButtonEntry_Value_Property(ButtonEntry obj, Uno.UX.Selector name) :449 void app18_ButtonEntry_Value_Property__ctor_3_fn(app18_ButtonEntry_Value_Property* __this, ::g::ButtonEntry* obj, ::g::Uno::UX::Selector* name) { __this->ctor_3(obj, *name); } // public override sealed string Get(Uno.UX.PropertyObject obj) :451 void app18_ButtonEntry_Value_Property__Get1_fn(app18_ButtonEntry_Value_Property* __this, ::g::Uno::UX::PropertyObject* obj, uString** __retval) { return *__retval = uPtr(uCast< ::g::ButtonEntry*>(obj, ::TYPES[0/*ButtonEntry*/]))->Value(), void(); } // public app18_ButtonEntry_Value_Property New(ButtonEntry obj, Uno.UX.Selector name) :449 void app18_ButtonEntry_Value_Property__New1_fn(::g::ButtonEntry* obj, ::g::Uno::UX::Selector* name, app18_ButtonEntry_Value_Property** __retval) { *__retval = app18_ButtonEntry_Value_Property::New1(obj, *name); } // public override sealed Uno.UX.PropertyObject get_Object() :450 void app18_ButtonEntry_Value_Property__get_Object_fn(app18_ButtonEntry_Value_Property* __this, ::g::Uno::UX::PropertyObject** __retval) { return *__retval = __this->_obj, void(); } // public override sealed void Set(Uno.UX.PropertyObject obj, string v, Uno.UX.IPropertyListener origin) :452 void app18_ButtonEntry_Value_Property__Set1_fn(app18_ButtonEntry_Value_Property* __this, ::g::Uno::UX::PropertyObject* obj, uString* v, uObject* origin) { uPtr(uCast< ::g::ButtonEntry*>(obj, ::TYPES[0/*ButtonEntry*/]))->SetValue(v, origin); } // public override sealed bool get_SupportsOriginSetter() :453 void app18_ButtonEntry_Value_Property__get_SupportsOriginSetter_fn(app18_ButtonEntry_Value_Property* __this, bool* __retval) { return *__retval = true, void(); } // public app18_ButtonEntry_Value_Property(ButtonEntry obj, Uno.UX.Selector name) [instance] :449 void app18_ButtonEntry_Value_Property::ctor_3(::g::ButtonEntry* obj, ::g::Uno::UX::Selector name) { ctor_2(name); _obj = obj; } // public app18_ButtonEntry_Value_Property New(ButtonEntry obj, Uno.UX.Selector name) [static] :449 app18_ButtonEntry_Value_Property* app18_ButtonEntry_Value_Property::New1(::g::ButtonEntry* obj, ::g::Uno::UX::Selector name) { app18_ButtonEntry_Value_Property* obj1 = (app18_ButtonEntry_Value_Property*)uNew(app18_ButtonEntry_Value_Property_typeof()); obj1->ctor_3(obj, name); return obj1; } // } } // ::g
5619455460e73f88735cdb0a2dff7ee88f901296
0fb375d004d1c98d4356acbeb0d5a6a9cc37b801
/demo/wpr_grab_control/include/wpr_grab_control/wpr_grab_control_node.h
0d1b485edb4298fa7678a4564f17e81d3fcf3a0c
[ "MIT" ]
permissive
yjz17377133/Team204
6675e7fc05fee0256420d86aff0d7f84ea4e7f7c
12a9679c6eb7bc6a52d5691586fce2672dfcbc44
refs/heads/master
2021-03-01T13:40:02.741331
2020-06-15T06:08:10
2020-06-15T06:08:10
245,790,185
1
0
MIT
2020-05-21T02:41:06
2020-03-08T09:59:28
null
UTF-8
C++
false
false
3,466
h
wpr_grab_control_node.h
// // Created by yspjack on 2020/5/25. // #ifndef SRC_WPR_GRAB_CONTROL_NODE_H #define SRC_WPR_GRAB_CONTROL_NODE_H namespace wpr_grab_control_node { /** \brief Bounding box */ struct BoxMarker { float xMax; float xMin; float yMax; float yMin; float zMax; float zMin; }; class JointControl { public: virtual void lift(double liftValue) = 0; virtual void gripper(double gripperValue) = 0; virtual double getLift() = 0; virtual double getGripper() = 0; }; class GrabControl { public: enum State { STEP_WAIT, STEP_FIND_PLANE, STEP_PLANE_DIST, STEP_FIND_OBJ, //STEP_FIND_PLAC: 寻找、检查放置位置情况 STEP_FIND_PLACE, STEP_OBJ_DIST, STEP_HAND_UP, STEP_FORWARD, STEP_GRAB, STEP_RELEASE, STEP_OBJ_UP, //STEP_OBJ_FREE: 此时机械臂已离开目标 STEP_OBJ_FREE, STEP_BACKWARD, STEP_DONE, STEP_EXCEPTION }; static float grabHorizontalOffset; static float grabLiftOffset; static float grabForwardOffset; static float grabGripperValue; private: State nStep; std::shared_ptr<JointControl> jointControl; ros::Publisher ctrl_pub; std_msgs::String ctrl_msg; ros::Publisher vel_pub; ros::Subscriber pose_diff_sub; geometry_msgs::Pose2D pose_diff; BoxMarker *boxLastObject; BoxMarker *boxPlane; float fObjGrabX; float fObjGrabY; float fObjGrabZ; float fMoveTargetX; float fMoveTargetY; float fPlaneDist; float fTargetPlaneDist; float fTargetGrabX; float fTargetGrabY; float fPlaneHeight; public: GrabControl(const std::shared_ptr<JointControl> &jointControl); void VelCmd(float inVx, float inVy, float inTz); //2、前后运动控制到平面的距离 bool stepPlaneDist(); //3、检测物品,挑选出准备抓取的目标物品 bool stepFindObject(); //3.5、确定物品释放位置 //当物品释放位置不合适or物品和桌子边缘的距离不合适时返回false, 进入异常状态 bool stepFindPlace(); //4、左右平移对准目标物品 bool stepObjectDist(); //5、抬起手臂 bool stepHandUp(); //6、前进靠近物品 bool stepForward(); //7、抓取物品 bool stepGrab(); //7.5、 松开机械臂 bool stepRelease(); //8、拿起物品 bool stepObjUp(); //8.5、放下物品,收回机械臂 bool stepObjFree(); //9、带着物品后退 //后退 bool stepBackward(); //左右平移对准桌子中心 bool stepPlaneAdjustY(); void reset(); State grab(BoxMarker *boxPlane, BoxMarker *boxLastObject); //此处 boxPlane为目标放置平面,boxLastObject为目标放置位置 State release(BoxMarker *boxPlane, BoxMarker *boxLastObject); void init(ros::NodeHandle &nh); void PoseDiffCallback(const geometry_msgs::Pose2D::ConstPtr &msg); State getState(); }; } #endif //SRC_WPR_GRAB_CONTROL_NODE_H
3550b29928eea23ea951ad1fea13ebfd6cc73353
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/14_12523_55.cpp
8fc708fb85e5184ae950f13a4186e902dc69ed39
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,311
cpp
14_12523_55.cpp
#include <iostream> #include <vector> #include <algorithm> #include <fstream> using namespace std; // main int main(){ ifstream cin; cin.open("magic_tric_test.txt"); ofstream cout; cout.open("magic_tric_sol.txt"); // store T & proceed int T; cin >> T; for (int t = 0; t < T; t++){ // store 1st int r1; cin >> r1; int a1[4][4]; for (int i = 0; i<4; i++){ for (int j = 0; j<4; j++){ cin >> a1[i][j]; } } // store 2nd int r2; cin >> r2; int a2[4][4]; for (int i = 0; i<4; i++){ for (int j = 0; j<4; j++){ cin >> a2[i][j]; } } // get their intersection vector<int> s1(4); for (int i = 0; i<4; i++){ s1[i] = a1[r1-1][i]; } sort(s1.begin(), s1.end()); vector<int> s2(4); for (int i = 0; i<4; i++){ s2[i] = a2[r2-1][i]; } sort(s2.begin(), s2.end()); vector<int> X; int i1=0, i2=0; while (i1<4 && i2<4){ if (s1[i1] < s2[i2]){ i1++; } else if (s1[i1] > s2[i2]){ i2++; } else { X.push_back(s1[i1]); i1++; i2++; } } // print the result cout << "Case #" << (t+1) << ": "; if (X.size()==1) cout << X[0] << endl; else if (X.size()>1) cout << "Bad magician!" << endl; else if (X.size()==0) cout << "Volunteer cheated!" << endl; } return 0; }
382e60ed8b7ecadd8bc5f9663f1b75183af70920
7c24f112542188b3ad8f7815859017038982d69b
/Bolyongas/Bolyongas_old.ino_
6c60b3af9109749c70cd7eb714050631f006ea93
[]
no_license
csatacsirke/Arduino
ede4acb0c9f668cffb809bb9b67cfa72e7da0e7f
d4b1a979630fd7464462407aadf7418507f0ce51
refs/heads/master
2021-01-10T13:19:52.892437
2016-02-11T13:48:18
2016-02-11T13:48:18
45,172,832
0
1
null
2016-02-11T13:48:18
2015-10-29T09:23:53
Java
UTF-8
C++
false
false
3,030
Bolyongas_old.ino_
/////////////////////////////////////// //#include <Bridge.h> //#include <HttpClient.h> //#include <ArduinoJson.h> #include <Servo.h> Servo fwservo; Servo stservo; Servo turret; //Digital pin 7 for reading in the pulse width from the MaxSonar device. //This variable is a constant because the pin will not change throughout execution of this code. //const int pwPin = 8; const int sonarSensors[] = {8, 9, 3}; #define FrontSensor 9 #define LeftSensor 3 #define RightSensor 8 #define TurretPin 5 //variables needed to store values long pulse, inches, cm; void InitWheels() { pinMode(TurretPin, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); turret.attach(TurretPin); fwservo.attach(11); stservo.attach(10); fwservo.write(90); stservo.write(90); turret.write(90); } void InitSonars() { pinMode(sonarSensors[0], INPUT); pinMode(sonarSensors[1], INPUT); pinMode(sonarSensors[2], INPUT); } int ReadSensor(int pin) { pulse = pulseIn(pin, HIGH); //147uS per inch inches = pulse/147; //change inches to centimetres return int(inches * 2.54); } void ReadAndPrintSensor(int pin) { //Used to read in the pulse that is being sent by the MaxSonar device. //Pulse Width representation with a scale factor of 147 uS per Inch. /* pulse = pulseIn(pin, HIGH); //147uS per inch inches = pulse/147; //change inches to centimetres cm = inches * 2.54; */ cm = ReadSensor(pin); Serial.print("pin: "); Serial.print(pin); Serial.print(" "); Serial.print(cm); Serial.print("cm"); Serial.println(); } //int irany = 90; void Stop() { fwservo.write(90); stservo.write(90); } // speed: pozitiv: elöre, negativ hatra min: kb -60 max +60 // direction: 0: egyenesen void Start(int speed, int direction) { //const int sebesseg = 0; fwservo.write(90 + speed); //unsigned long t = millis(); //int irany = 90 + int(sebesseg * sin( double(t) / 1000 / 5 * 2 * 3.14 )); int irany = 90 - direction; stservo.write(irany); } void TurnForMillis(int duration) { static unsigned long endTime = 0; static bool isTurning = false; unsigned long t = millis(); if ( isTurning ) { if( t >= endTime ) { Stop(); isTurning = false; } } else { endTime = t + duration; Start(0, 30); isTurning = true; } } long startupTime; void setup() { //This opens up a serial connection to shoot the results back to the PC console Serial.begin(9600); startupTime = millis(); InitWheels(); InitSonars(); srand(millis()); turret.write(91); } void loop() { if( millis() > startupTime + 30*1000) { delay(3000); turret.write(90); Stop(); Serial.write("megallt"); return; } Start(0, 30); delay( rand() % 1500 ); int distance = ReadSensor(FrontSensor); if( distance > 50 ) { Start(30, 0); } while(true) { int dist = ReadSensor(FrontSensor); if( dist < 50 ) { Stop(); break; } delay( 50 ); } delay(500); }
4a858703be46a35c4070dce5944e0e9289b851d7
2f095fea14e9dcc9a0c422d822c398afbaacfcc8
/binCon/MorseNode.h
2bbcc5cd9fdd06153a607d9762a96cd048538d1a
[]
no_license
jmanndev/morseCodeConverter
03c62253436792e768a16d81929952c08ca33ef2
eefd5244a2c29f416d690d30cfc615615e77889e
refs/heads/master
2020-07-02T03:58:22.964091
2016-11-21T06:43:20
2016-11-21T06:43:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
562
h
MorseNode.h
#include <string> #ifndef MORSENODE_H #define MORSENODE_H struct MorseNode { char letter; std::string morse; bool operator==(const MorseNode& inputNode) const { return (morse == inputNode.morse); } bool operator<(const MorseNode& inputNode) const { return (morse < inputNode.morse); } bool operator>(const MorseNode& inputNode) const { return (morse > inputNode.morse); } bool operator!=(const MorseNode& inputNode) const { return (morse != inputNode.morse); } }; #endif /* MORSENODE_H */
23b24f779e9116849b71acaa0b0450c89fc90a3c
fb1eceebfb75469bd30c8f3c3a44872613ddc8be
/Sources/Luogu P1006 传纸条.cc
860aa19c6bfa3b4d61146ebe506c065c09433b0c
[]
no_license
zeyugao/oi
50711c0fc3c3103b23c6781f44907b2b31252959
5452b4e7540cae656dd839132ef5807e48b52cf5
refs/heads/master
2021-08-10T15:48:28.545202
2021-07-03T00:45:51
2021-07-03T00:45:51
64,367,780
0
0
null
null
null
null
UTF-8
C++
false
false
1,294
cc
Luogu P1006 传纸条.cc
#include <string.h> #include <algorithm> #include <iostream> using namespace std; #define MAXNUM 10000 #define LEN 4 //Summary: // dp[step][x1][x2] = max( // dp[step-1][x1][x2],//两个都只往下走一格 // dp[step-1][x1-1][x2], // dp[step-1][x1][x2-1], // dp[step-1][x1-1][x2-1])+lover[x1][step-x1+2] + lover[x2][step-x2+2]; int main() { int m, n; cin >> m >> n; int lover[55][55] = { 0 }; for (int y = 1; y <= m; y++) { for (int x = 1; x <= n; x++) { cin >> lover[x][y]; } } // int dp[110][55][55] = { 0 }; for (int step = 1; step <= m + n - 2; step++) { for (int x1 = 1; x1 <= n; x1++) { for (int x2 = 1; x2 <= n; x2++) { //在开始或者终点的时候没有值 //开始:x1==x2 //终点:x1==n&&x2==n if ((x1 == n && x2 == n && step == m + n - 2) || (x1 != x2 && step + 1 >= x1 && step + 1 >= x2)) { int calc_tmp_1 = max(dp[step - 1][x1][x2], dp[step - 1][x1 - 1][x2 - 1]); int calc_tmp_2 = max(dp[step - 1][x1 - 1][x2], dp[step - 1][x1][x2 - 1]); dp[step][x1][x2] = max(calc_tmp_1, calc_tmp_2) + lover[x1][step - x1 + 2] + lover[x2][step - x2 + 2]; } } } } cout << dp[m + n - 2][n][n]; //system("pause"); return 0; }
1813abe1f5b15cf1b49aea339249cbab2f11c5fd
a7a0a438f9bc9c79f79c85a76cd9e49a31e871ea
/GameTemplate/Game/graphics/SkinModelEffect.h
95da3fe358a1793babd2c3157517dd879b01fc7f
[]
no_license
m-taku/sotuken
0e042cdadca5d960bdd48aeabdb3ea398c90fe87
472664bf8d3a4e22b1c8988d615d8e81fe6286c3
refs/heads/master
2022-04-16T01:25:42.834442
2020-03-27T07:10:42
2020-03-27T07:10:42
204,858,655
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,859
h
SkinModelEffect.h
#pragma once #include "graphics/Shader.h" #include "TextureManager.h" /*! *@brief モデルエフェクト。 */ class ModelEffect : public DirectX::IEffect { protected: std::wstring m_materialName; //!<マテリアル名。 Shader* m_pVSShader = nullptr; Shader* m_pPSShader = nullptr; Shader m_vsShader; Shader m_vsShaderNature; Shader m_vsShaderInstancingNature; Shader m_vsSkyShader; Shader m_vsShaderInstancing; Shader m_vsShaderShadow; Shader m_vsShaderInstancingShadow; Shader m_vsNatureShaderInstancingShadow; Shader m_vsNatureShaderShadow; Shader m_psShader; Shader m_psSkyShader; Shader m_psNatureShader; Shader m_psShaderShadow; Shader m_psNatureShaderShadow; bool isSkining; ID3D11ShaderResourceView* m_albedoTex = nullptr; bool isTextureManager = false; ID3D11ShaderResourceView* m_normalTex = nullptr; EnDrawMode m_drawMode = enNormal; public: ModelEffect() { m_psShader.Load("Assets/shader/model.fx", "PSMain", Shader::EnType::PS); m_psSkyShader.Load("Assets/shader/skycube.fx", "PSCubeMain", Shader::EnType::PS); m_psShaderShadow.Load("Assets/shader/shadowmap.fx", "PSMain", Shader::EnType::PS); m_psNatureShader.Load("Assets/shader/model.fx", "PSTreeMain", Shader::EnType::PS); m_psNatureShaderShadow.Load("Assets/shader/shadowmap.fx", "PSTreeMain", Shader::EnType::PS); m_pPSShader = &m_psShader; } virtual ~ModelEffect() { if (!isTextureManager) { if (m_albedoTex) { m_albedoTex->Release(); } } } void __cdecl Apply(ID3D11DeviceContext* deviceContext) override; void __cdecl GetVertexShaderBytecode(void const** pShaderByteCode, size_t* pByteCodeLength) override { *pShaderByteCode = m_vsShader.GetByteCode(); *pByteCodeLength = m_vsShader.GetByteCodeSize(); } void SetAlbedoTexture(ID3D11ShaderResourceView* tex,bool furag) { m_albedoTex = tex; isTextureManager = furag; } void SetNormalTexture(ID3D11ShaderResourceView* tex) { m_normalTex = tex; } void SetMatrialName(const wchar_t* matName) { m_materialName = matName; } bool EqualMaterialName(const wchar_t* name) const { return wcscmp(name, m_materialName.c_str()) == 0; } void SetDrawMode(EnDrawMode mode) { m_drawMode = mode; } }; /*! *@brief * スキンなしモデルエフェクト。 */ class NonSkinModelEffect : public ModelEffect { public: NonSkinModelEffect() { m_vsShader.Load("Assets/shader/model.fx", "VSMain", Shader::EnType::VS); m_vsSkyShader.Load("Assets/shader/skycube.fx", "VSMain", Shader::EnType::VS); m_vsShaderInstancing.Load("Assets/shader/model.fx", "VSMainInstancing", Shader::EnType::VS); m_vsShaderNature.Load("Assets/shader/model.fx", "VSTreeMain", Shader::EnType::VS); m_vsShaderInstancingNature.Load("Assets/shader/model.fx", "VSTreeMainInstancing", Shader::EnType::VS); m_vsShaderShadow.Load("Assets/shader/shadowmap.fx", "VSMain", Shader::EnType::VS); m_vsShaderInstancingShadow.Load("Assets/shader/shadowmap.fx", "VSMainInstancing", Shader::EnType::VS); m_vsNatureShaderInstancingShadow.Load("Assets/shader/shadowmap.fx", "VSTreeMainInstancing", Shader::EnType::VS);; m_vsNatureShaderShadow.Load("Assets/shader/shadowmap.fx", "VSTreeMain", Shader::EnType::VS); m_pVSShader = &m_vsShader; isSkining = false; } }; /*! *@brief * スキンモデルエフェクト。 */ class SkinModelEffect : public ModelEffect { public: SkinModelEffect() { /* wchar_t hoge[256]; GetCurrentDirectoryW(256, hoge);*/ m_vsShader.Load("Assets/shader/model.fx", "VSMainSkin", Shader::EnType::VS); m_vsSkyShader.Load("Assets/shader/skycube.fx", "VSMain", Shader::EnType::VS); m_vsShaderInstancing.Load("Assets/shader/model.fx", "VSMainSkinInstancing", Shader::EnType::VS); m_vsShaderShadow.Load("Assets/shader/shadowmap.fx", "VSMainSkin", Shader::EnType::VS); m_vsShaderInstancingShadow.Load("Assets/shader/shadowmap.fx", "VSMainSkinInstancing", Shader::EnType::VS); m_pVSShader = &m_vsShader; isSkining = true; } }; /*! *@brief * エフェクトファクトリ。 */ class SkinModelEffectFactory : public DirectX::EffectFactory { public: SkinModelEffectFactory(ID3D11Device* device) : EffectFactory(device) {} std::shared_ptr<DirectX::IEffect> __cdecl CreateEffect(const EffectInfo& info, ID3D11DeviceContext* deviceContext)override { std::shared_ptr<ModelEffect> effect; if (info.enableSkinning) { //スキニングあり。 effect = std::make_shared<SkinModelEffect>(); } else { //スキニングなし。 effect = std::make_shared<NonSkinModelEffect>(); } effect->SetMatrialName(info.name); if (info.diffuseTexture && *info.diffuseTexture) { wchar_t moveFilePath[256]; ID3D11ShaderResourceView* texSRV; auto ma = wcsstr(info.diffuseTexture, L"T_"); if (ma != NULL) { wchar_t name[256]; auto num = wcslen(ma); wcscpy(name, ma); name[num - 11] = NULL; swprintf_s(moveFilePath, L"Assets/sprite/T_%sBC.dds", &name[3]); texSRV = g_TextureManager.Load(moveFilePath); effect->SetAlbedoTexture(texSRV,true); swprintf_s(moveFilePath, L"Assets/sprite/T_%sN.dds", &name[3]); texSRV = g_TextureManager.Load(moveFilePath); effect->SetNormalTexture(texSRV); } else { DirectX::EffectFactory::CreateTexture(info.diffuseTexture, deviceContext, &texSRV); effect->SetAlbedoTexture(texSRV,false); DirectX::CreateDDSTextureFromFileEx( g_graphicsEngine->GetD3DDevice(), L"Assets/sprite/nomal.dds", 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, nullptr, &texSRV ); effect->SetNormalTexture(texSRV); } } return effect; } void __cdecl CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) override { return DirectX::EffectFactory::CreateTexture(name, deviceContext, textureView); } };
6834cff1a032f1ddc15010077e4dd27010db3c57
aab3ae5bb8ce591d29599f51f5fb4cd9c5b05f38
/SourceCode/Base/Math/Vector/Vec2D.cpp
cb3611e84d0c2e571cf8258400ef26e8cbf3fea7
[]
no_license
S-V/Lollipop
b720ef749e599deaf3fbf48b1e883338dcb573c3
eca4bfe6115437dc87f638af54a69de09956cbfb
refs/heads/master
2022-02-09T04:59:17.474909
2022-01-25T20:20:20
2022-01-25T20:20:20
43,964,835
11
1
null
null
null
null
UTF-8
C++
false
false
1,290
cpp
Vec2D.cpp
/* ============================================================================= File: Vec2D.cpp Desc:. ============================================================================= */ #include <Base_PCH.h> #pragma hdrstop #include <Base.h> #include <Base/Math/Math.h> mxNAMESPACE_BEGIN const Vec2D Vec2D::vec2_origin ( 0.0f, 0.0f ); const Vec2D Vec2D::vec2_unit ( 1.0f, 1.0f ); /* ============= Vec2D::ToChars ============= */ const char *Vec2D::ToChars( INT precision ) const { return String::FloatArrayToString( ToFloatPtr(), GetDimension(), precision ); } /* ============= Lerp Linearly inperpolates one vector to another. ============= */ void Vec2D::Lerp( const Vec2D &v1, const Vec2D &v2, const FLOAT l ) { if ( l <= 0.0f ) { (*this) = v1; } else if ( l >= 1.0f ) { (*this) = v2; } else { (*this) = v1 + l * ( v2 - v1 ); } } /* ============= Vec2D::Rotate ============= */ Vec2D & Vec2D::Rotate( FLOAT angle ) { FLOAT s, c; mxSinCos( angle, s, c ); FLOAT nx = c * x - s * y; FLOAT ny = s * x + c * y; this->x = nx; this->y = ny; return *this; } mxNAMESPACE_END //--------------------------------------------------------------// // End Of File. // //--------------------------------------------------------------//
bdf19315d89648c4f9a8e799f2fc9684f0e2a6ef
368056bea38d2870eff3d059fff7bae77a73f2da
/repo/Mix2dSP/Fields.cpp
52111c290a42dc90b7211ef898bb7de48e4914c1
[]
no_license
lzrdig/Mix2dSP
b6e03527bc4232ed79d055914e5552c98f0b276e
f8549685e11be7310b09246b75d1c87853d0b4d9
refs/heads/master
2021-01-13T08:50:21.828358
2018-08-11T20:30:00
2018-08-11T20:30:00
71,913,197
0
0
null
null
null
null
UTF-8
C++
false
false
6,042
cpp
Fields.cpp
//*************************************************************************** // // Class CFields // // List of member functions: // // * fSetField(int type, int num, float val) // // This function will set the array element 'num' for the variable // specified in the 'type' argument to a 'val' value of type float. // // // Example: pField->SetField(FREQ,5,0.79) will set the 5th array // element of the 'Freq' array to the value 0.79 // // // * dSetField(int type, int num, double val) // // Same as above, only for type double 'val' (only used by the // Noisefield array) // // // Example: pField->SetField(NOISEFIELD,jj,12.4) sets the jjth // element of the 'Noisefield' array to 12.4 // // // * dGetField(int type, int num) // // This function returns the value of the 'type' array for the // 'num' array element (only used by the Noisefield array) // // // Example: pField->dGetField(NOISEFIELD,m) returns the mth element // of the 'Noisefield' array // // // * fGetField(int type, int num) // // Same as above, only for type float 'val' // // // Example: pField->fGetField(TERMPUMP,kk) returns the kkth element // of the 'Termpump' array // // // (Note: for a complete list of the 'type' arguments, see 'Fields.h') // //*************************************************************************** // Pre-compiler instructions #include "StdAfx.h" #include "DecIncl.h" #include "Fields.h" #pragma warning(disable:4305) #pragma warning(disable:4100) extern "C" float *vector(long nl, long nh); extern "C" void free_vector(float *v, long nl, long nh); extern "C" double *dvector(long nl, long nh); extern "C" void free_dvector(double *v, long nl, long nh); //*************************************************************************** // Class constructor (initializes all arrays with zero elements) CFields::CFields(long gridtot, long xtot, long ytot, long ttot) { // Supergaussian coefficients pSgcoeff = vector(1,5); pSgcoeff[1] = 0.5; pSgcoeff[2] = 0.4431; pSgcoeff[3] = 0.4465; pSgcoeff[4] = 0.4532; pSgcoeff[5] = 0.4591; // 3d arrays maxnn = gridtot; // complex arrays pEField_s = vector(1,2*xtot*(ytot/2)*ttot); pEField_i = vector(1,2*xtot*(ytot/2)*ttot); pEField_p = vector(1,2*xtot*(ytot/2)*ttot); pPhase_s = vector(1,2*maxnn); pPhase_i = vector(1,2*maxnn); pPhase_p = vector(1,2*maxnn); // real arrays pPhaseTerm_s = vector(1,maxnn); pPhaseTerm_i = vector(1,maxnn); pPhaseTerm_p = vector(1,maxnn); // x arrays maxx = xtot; pXgrid = vector(1,maxx); // y arrays maxy = ytot; pYgrid = vector(1,maxy); // t arrays maxt = ttot; pTgrid = vector(1,maxt); // FFT arrays pFFTW = (fftw_complex *) malloc(xtot*ytot*ttot*sizeof(fftw_complex)); pFarFFT_x = (fftw_complex *) malloc(xtot*sizeof(fftw_complex)); pFarFFT_y = (fftw_complex *) malloc(ytot*sizeof(fftw_complex)); // Expansion factor for smoothing the spectra by 0 buffering XFactor = 4; pSpecFFT = (fftw_complex *) malloc(XFactor*ttot*sizeof(fftw_complex)); } //*************************************************************************** // Class destructor (deletes all of the arrays and sets them to zero) CFields::~CFields() { free_vector(pSgcoeff,1,5); // 3d fields free_vector(pEField_s,1,2*maxx*(maxy/2)*maxt); free_vector(pEField_i,1,2*maxx*(maxy/2)*maxt); free_vector(pEField_p,1,2*maxx*(maxy/2)*maxt); free_vector(pPhase_s,1,2*maxnn); free_vector(pPhase_i,1,2*maxnn); free_vector(pPhase_p,1,2*maxnn); free_vector(pPhaseTerm_s,1,maxnn); free_vector(pPhaseTerm_i,1,maxnn); free_vector(pPhaseTerm_p,1,maxnn); free_vector(pXgrid,1,maxx); free_vector(pYgrid,1,maxy); free_vector(pTgrid,1,maxt); free(pFFTW); free(pSpecFFT); free(pFarFFT_x); free(pFarFFT_y); } //********************************************************************** // Function fSetField void CFields::fSetField(int type, int num, float val) { switch(type) { case SGCOEFF: pSgcoeff[num] = val; break; case PHASETERM_S: pPhaseTerm_s[num] = val; break; case PHASETERM_I: pPhaseTerm_i[num] = val; break; case PHASETERM_P: pPhaseTerm_p[num] = val; break; case XGRID: pXgrid[num] = val; break; case YGRID: pYgrid[num] = val; break; case TGRID: pTgrid[num] = val; break; default: break; } } //********************************************************************** // Function fGetField float CFields::fGetField(int type, int num) { switch(type) { case SGCOEFF: return pSgcoeff[num]; break; case PHASETERM_S: return pPhaseTerm_s[num]; break; case PHASETERM_I: return pPhaseTerm_i[num]; break; case PHASETERM_P: return pPhaseTerm_p[num]; break; case XGRID: return pXgrid[num]; break; case YGRID: return pYgrid[num]; break; case TGRID: return pTgrid[num]; break; default: return 0.0; break; } } //********************************************************************** // Function dSetField void CFields::dSetField(int type, int num, double val) { /* switch(type) { case EFIELD_S: pEField_s[num] = val; break; case EFIELD_I: pEField_i[num] = val; break; case EFIELD_P: pEField_p[num] = val; break; case PHASE_S: pPhase_s[num] = val; break; case PHASE_I: pPhase_i[num] = val; break; case PHASE_P: pPhase_p[num] = val; break; default: break; } */ } //********************************************************************** // Function dGetField double CFields::dGetField(int type, int num) { /* switch(type) { case EFIELD_S: return pEField_s[num]; break; case EFIELD_I: return pEField_i[num]; break; case EFIELD_P: return pEField_p[num]; break; case PHASE_S: return pPhase_s[num]; break; case PHASE_I: return pPhase_i[num]; break; case PHASE_P: return pPhase_p[num]; break; default: return 0.0; break; } */ return 0.0; }
592edbe54700ce9a32031108983ce4ffd8c0569a
09e5cfe06e437989a2ccf2aeecb9c73eb998a36c
/modules/clipper/clipper/contrib/fffear.h
8bb32e08f7352d2d9e54ab792d674027af519baf
[ "LGPL-2.1-only", "BSD-3-Clause" ]
permissive
jorgediazjr/dials-dev20191018
b81b19653624cee39207b7cefb8dfcb2e99b79eb
77d66c719b5746f37af51ad593e2941ed6fbba17
refs/heads/master
2020-08-21T02:48:54.719532
2020-01-25T01:41:37
2020-01-25T01:41:37
216,089,955
0
1
BSD-3-Clause
2020-01-25T01:41:39
2019-10-18T19:03:17
Python
UTF-8
C++
false
false
6,210
h
fffear.h
/*! \file fffear.h Header file for sample fffear impelementation \ingroup g_fffear */ //C Copyright (C) 2000-2004 Kevin Cowtan and University of York //C Copyright (C) 2000-2005 Kevin Cowtan and University of York //L //L This library is free software and is distributed under the terms //L and conditions of version 2.1 of the GNU Lesser General Public //L Licence (LGPL) with the following additional clause: //L //L `You may also combine or link a "work that uses the Library" to //L produce a work containing portions of the Library, and distribute //L that work under terms of your choice, provided that you give //L prominent notice with each copy of the work that the specified //L version of the Library is used in it, and that you include or //L provide public access to the complete corresponding //L machine-readable source code for the Library including whatever //L changes were used in the work. (i.e. If you make changes to the //L Library you must distribute those, but you do not need to //L distribute source or object code to those portions of the work //L not covered by this licence.)' //L //L Note that this clause grants an additional right and does not impose //L any additional restriction, and so does not affect compatibility //L with the GNU General Public Licence (GPL). If you wish to negotiate //L other terms, please contact the maintainer. //L //L You can redistribute it and/or modify the library under the terms of //L the GNU Lesser General Public License as published by the Free Software //L Foundation; either version 2.1 of the License, or (at your option) any //L later version. //L //L This library is distributed in the hope that it will be useful, but //L WITHOUT ANY WARRANTY; without even the implied warranty of //L MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //L Lesser General Public License for more details. //L //L You should have received a copy of the CCP4 licence and/or GNU //L Lesser General Public License along with this library; if not, write //L to the CCP4 Secretary, Daresbury Laboratory, Warrington WA4 4AD, UK. //L The GNU Lesser General Public can also be obtained by writing to the //L Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, //L MA 02111-1307 USA #ifndef CLIPPER_FFFEAR #define CLIPPER_FFFEAR #include "function_object_bases.h" namespace clipper { //! Simple fffear implementation /*! \deprecated This is for testing purposes only, as it is very slow. The search target and weights are not handled generally in this implementation: The NXmaps are assumed to have a grid matching the map grid with the origin at the centre. */ class FFFear_slow_basic { public: //! constructor FFFear_slow_basic( const Xmap<float>& xmap ) : xmp( &xmap ) {} //! constructor: shorthand for constructor+operator FFFear_slow_basic( Xmap<float>& result, const NXmap<float>& srchval, const NXmap<float>& srchwgt, const Xmap<float>& xmap ) : xmp( &xmap ) { (*this)( result, srchval, srchwgt ); } bool operator() ( Xmap<float>& result, const NXmap<float>& srchval, const NXmap<float>& srchwgt ) const; private: const Xmap<float>* xmp; }; //! FFT-based fffear implementation /*! \deprecated This implementation is currently unoptimised, but much faster then the simple implementation. The search target and weights are not handled generally in this implementation: The NXmaps are assumed to have a grid matching the map grid with the origin at the centre. */ class FFFear_fft_basic { public: //! constructor FFFear_fft_basic( const Xmap<float>& xmap ) { init( xmap ); } //! constructor: shorthand for constructor+operator FFFear_fft_basic( Xmap<float>& result, const NXmap<float>& srchval, const NXmap<float>& srchwgt, const Xmap<float>& xmap ) { init( xmap ); (*this)( result, srchval, srchwgt ); } //! initialiser: initialise with the given target Xmap void init( const Xmap<float>& xmap ); bool operator() ( Xmap<float>& result, const NXmap<float>& srchval, const NXmap<float>& srchwgt ) const; private: ftype vol; FFTmap_p1 rho1; FFTmap_p1 rho2; }; //! FFT-based fffear implementation /*! \ingroup g_fffear This implementation is currently unoptimised, but much faster then the simple implementation. */ template<class T> class FFFear_slow : public FFFear_base<T> { public: //! constructor FFFear_slow( const Xmap<T>& xmap ) { init( xmap ); } //! constructor: shorthand for constructor+operator FFFear_slow( Xmap<T>& result, const NXmap<T>& srchval, const NXmap<T>& srchwgt, const Xmap<T>& xmap, const NX_operator& nxop ) { init( xmap ); (*this)( result, srchval, srchwgt, nxop ); } //! initialiser: initialise with the given target Xmap void init( const Xmap<T>& xmap ) { xmp = &xmap; } bool operator() ( Xmap<T>& result, const NXmap<T>& srchval, const NXmap<T>& srchwgt, const NX_operator& nxop ) const; bool operator() ( Xmap<T>& result, const NXmap<T>& srchval, const NXmap<T>& srchwgt ) const; //!< \deprecated private: const Xmap<T>* xmp; }; //! FFT-based fffear implementation /*! \ingroup g_fffear This implementation is currently unoptimised, but much faster then the simple implementation. */ template<class T> class FFFear_fft : public FFFear_base<T> { public: //! constructor FFFear_fft( const Xmap<T>& xmap ) { init( xmap ); } //! constructor: shorthand for constructor+operator FFFear_fft( Xmap<T>& result, const NXmap<T>& srchval, const NXmap<T>& srchwgt, const Xmap<T>& xmap, const NX_operator& nxop ) { init( xmap ); (*this)( result, srchval, srchwgt, nxop ); } //! initialiser: initialise with the given target Xmap void init( const Xmap<T>& xmap ); bool operator() ( Xmap<T>& result, const NXmap<T>& srchval, const NXmap<T>& srchwgt, const NX_operator& nxop ) const; bool operator() ( Xmap<T>& result, const NXmap<T>& srchval, const NXmap<T>& srchwgt ) const; //!< \deprecated private: ftype vol; FFTmap_p1 rho1; FFTmap_p1 rho2; }; } // namespace clipper #endif
6eb428bf84faacd10d5d91e6efd9f2ea491b37f8
828a10fe37b8736ad9677849c924aae260aace56
/rviz_robot_marker/include/rviz_robot_marker/RvizRobotMarkerPublisher.h
5c102c63ba85a76ed6f2b7d8a4ad2d60dc0ce83f
[]
no_license
squirrel-project/squirrel_motion_planner
c65db2a3290723071ba07ef1fff484aba4908732
7ec99ce10732455581b73b230f48e57a618c2094
refs/heads/indigo_dev
2021-05-23T05:59:20.961557
2018-03-19T09:50:41
2018-03-19T09:50:41
94,750,216
0
5
null
2018-03-19T09:50:42
2017-06-19T07:44:56
C++
UTF-8
C++
false
false
8,509
h
RvizRobotMarkerPublisher.h
#ifndef INCLUDE_RVIZROBOTMARKERPUBLISHER_H_ #define INCLUDE_RVIZROBOTMARKERPUBLISHER_H_ #include <sensor_msgs/JointState.h> #include <kdl/chainfksolverpos_recursive.hpp> #include <kdl/tree.hpp> #include <tf/tf.h> #include <urdf_model/model.h> #include <std_msgs/ColorRGBA.h> #include <visualization_msgs/MarkerArray.h> namespace rviz_robot_marker { /** * Class for publishing robot models as visualization markers for RViz. * This module does *not* use TF. */ class RvizRobotMarkerPublisher { public: /** * @brief Constructor. * @param markerTopic Topic name for the robot visualization marker publisher. */ RvizRobotMarkerPublisher(const std::string& markerTopic = "robot_markers_array"); /** * @brief Destructor. * * The destructor does *not* send visualization marker deletion messages to RViz. * Call clear() before deleting the instance if you would like to send deletion messages. */ virtual ~RvizRobotMarkerPublisher(); /** Mode defining precedence of color values */ enum ColorMode { REPLACE_MESH_COLOR, ///< Use color unless color is explicitly set in URDF definition (replaces mesh color) FORCE_COLOR, ///< Force given color (overrides mesh color and URDF color) BLEND ///< Blend given color and mesh/URDF color }; /** * @brief Updates an existing robot marker with a new pose. * The robot marker must exist (call addRobotFromDescription() or addRobotWithJointListener() first) * * @param id ID of the robot marker as returned by addRobotFromDescription() or addRobotWithJointListener() * @param baseTransform Transform from a fixed frame (e.g., the map frame) to the base link of the robot. * If the baseTransform.frame_id_ is set, the robot marker will be published in that frame. * If empty, the marker will be published in the base link frame of the robot instead. * @param jointStates New joint angles for the robot's pose. * @throws std::invalid_argument if robot ID is invalid or joint state name vector does not match position vector */ void setRobotPose(const size_t& id, const tf::StampedTransform& baseTransform, const sensor_msgs::JointStateConstPtr& jointStates); /** * @brief Adds a new robot marker from a URDF robot description on the parameter server. * @param param Name of the param from where to load the URDF robot description. * @return Internal ID of the marker for use within this class (this is *not* the ID of the visualization marker). * @throws std::invalid_argument if robot description parameter cannot be found or the URDF model cannot be parsed */ const size_t addRobotFromDescription(const std::string& param = "/robot_description"); /** * @brief Adds a new robot marker from a URDF robot description on the parameter server and attaches it to sensor_msgs::JointState topic subscriber. * @param topic The topic name for subscribing to sensor_msgs::JointState messages * @param param Name of the param from where to load the URDF robot description. * @return Internal ID of the marker for use within this class (this is *not* the ID of the visualization marker). * @throws std::invalid_argument if robot description parameter cannot be found or the URDF model cannot be parsed */ const size_t addRobotWithJointListener(const std::string& topic, const std::string& param = "/robot_description"); /** * @brief Deletes a robot marker. * This will also send a visualization marker deletion message to RViz. * @param id ID of the robot marker as returned by addRobotFromDescription() or addRobotWithJointListener() * @throws std::invalid_argument if robot ID is invalid */ void deleteRobot(const size_t& id); /** * @brief Deletes all robot markers. * This will also send visualization marker deletion messages to RViz. */ void clear(); /** * @brief Sets the color for the robot mesh. This also affects the lighting and transparency of textured meshes. * @param id ID of the robot marker as returned by addRobotFromDescription() or addRobotWithJointListener() * @param color The new color to use for the robot markers. * @param colorMode Color mode defining precedence of colors from mesh, URDF, and color given here * @throws std::invalid_argument if robot ID is invalid */ void setRobotColor(const size_t& id, const std_msgs::ColorRGBA& color, const ColorMode& colorMode = REPLACE_MESH_COLOR); /** * @brief Sets the name of the robot that will be shown in RViz. * @param id ID of the robot marker as returned by addRobotFromDescription() or addRobotWithJointListener() * @param name The new name of the robot. * @throws std::invalid_argument if robot ID is invalid */ void setRobotName(const size_t& id, const std::string& name); /** * @brief Shows the robot again after it has been hidden with hideRobot(). * @param id The robot to show. */ void showRobot(const size_t& id); /** * @brief Hides the robot temporarily by sending a deletion message to RViz and not publishing updates anymore. * Call showRobot() to show the robot again. * @param id The robot to hide. */ void hideRobot(const size_t& id); protected: ros::NodeHandle nh; ///< sibling node handle ros::Publisher markerPub; ///< visualization marker publisher /** @brief Internal structure representing a robot */ struct Robot { KDL::Tree kdlTree; ///< KDL tree generated from URDF model boost::shared_ptr<const urdf::ModelInterface> urdf; ///< Pointer to the URDF model size_t highestMarkerId; ///< Highest marker ID used for this robot std_msgs::ColorRGBA markerColor; ///< Base marker color (also affects textured meshes) ColorMode colorMode; ///< Color mode defining color precedence std::string markerNS; ///< Marker namespace that will be shown in RViz boost::shared_ptr<ros::Subscriber> jointSubscriber; ///< Joint subscriber added with addRobotWithJointListener(), may be NULL bool hide; ///< True if robot should be temporarily hidden, set by showRobot() and hideRobot() sensor_msgs::JointStateConstPtr jointStates; ///< Last known joint states tf::StampedTransform baseTransform; ///< Last known base transform }; typedef std::map<size_t, boost::shared_ptr<Robot> > Robots; ///< Type of the robots list Robots robots; ///< list of robots size_t highestRobotId; ///< highest ID assigned so far; typedef std::map<std::string, boost::shared_ptr<const urdf::ModelInterface> > UrdfModelMap; ///< Type of the urdfModels map. UrdfModelMap urdfModels; ///< cache for URDF models /** * @brief Generate a KDL model from the URDF model * @param model Pointer to the URDF model * @param robot Pointer the the Robot for filling its kdlTree member * @return true on success */ bool kdlModelFromURDF(const boost::shared_ptr<const urdf::ModelInterface>& model, boost::shared_ptr<Robot> robot); /** * @brief Propagates joint state updates through the KDL tree and stores the new link poses to a given TF buffer. * This is a recursive function. * @param jointStates The new joint state message containing new positions for all joints. * @param segment Current node to update (children will be updated recursively). * @param tf Internal TF transform buffer. */ bool computeChildTransforms(const sensor_msgs::JointStateConstPtr& jointStates, const KDL::SegmentMap::const_iterator& segment, tf::Transformer& tf) const; /** * @brief Callback function for subscriber listening to sensor_msgs::JointState messages. * @param id ID of the robot * @param jointStates Message. */ void jointStateCallback(const size_t& id, const sensor_msgs::JointStateConstPtr& jointStates); /** * @brief Internal method for adding a DELETE marker for the given robot. * @param robotIt Iterator pointing to a Robot. * @param markerArray Marker array where the marker should be appended. */ void addDeletionMsg(const Robots::iterator& robotIt, visualization_msgs::MarkerArray& markerArray) const; /** * @brief Publishes visualization markers for a robot. * @param robtoIt Iterator pointing to the robot. */ void publishVisualization(const Robots::iterator& robotIt) const; }; } /* namespace rviz_robot_marker */ #endif /* INCLUDE_RVIZROBOTMARKERPUBLISHER_H_ */
298f138ffa8b59e5eed55566ced15f371d350ff1
b26066401b2a4cb8d88f5b4b1b515bebb0c004f5
/include/rpc_client.hpp
9ad6d20fe957d8451ec771ff9ae59345fae31e03
[ "MIT" ]
permissive
sleepy-zeo/rest_rpc
4ee706be8cfd24fdc699d77b1e9accb53dc408d6
b3d1c6e4dd42145fe36153cb01c6522e16f50f60
refs/heads/master
2022-12-12T19:10:59.393310
2020-09-16T09:00:54
2020-09-16T09:00:54
289,219,788
0
0
null
null
null
null
UTF-8
C++
false
false
24,189
hpp
rpc_client.hpp
#ifndef REST_RPC_RPC_CLIENT_H #define REST_RPC_RPC_CLIENT_H #include <deque> #include <future> #include <iostream> #include <string> #include <utility> #include "client_util.hpp" #include "const_vars.h" #include "meta_util.hpp" #include "use_asio.hpp" using namespace rest_rpc::rpc_service; namespace rest_rpc { enum CallModel { future, callback }; const CallModel FUTURE = CallModel::future; const CallModel CALLBACK = CallModel::callback; const size_t DEFAULT_TIMEOUT = 5000; // ms class request_result { public: request_result() = default; explicit request_result(string_view data) : data_(data.data(), data.length()) { } template <class T = void> T as(); bool success() const { return !has_error(data_); } private: std::string data_; }; template <class T> T request_result::as() { if (has_error(data_)) { throw std::logic_error(get_error_msg(data_)); } return get_result<T>(data_); } template <> void request_result::as<void>() { if (has_error(data_)) { throw std::logic_error(get_error_msg(data_)); } } class rpc_client : private asio::noncopyable { public: rpc_client() : socket_(io_service_), work_(io_service_), deadline_(io_service_), body_(INIT_BUF_SIZE) { io_service_thread_ = std::make_shared<std::thread>([this] { io_service_.run(); }); } rpc_client(std::string host, unsigned short port) : socket_(io_service_) , work_(io_service_) , deadline_(io_service_) , host_(std::move(host)) , port_(port) , body_(INIT_BUF_SIZE) { io_service_thread_ = std::make_shared<std::thread>([this] { io_service_.run(); }); } ~rpc_client() { close(); stop(); } bool connect(size_t timeout = 3, bool is_ssl = false) { if (has_connected_) return true; assert(port_ != 0); if (is_ssl) { upgrade_to_ssl(); } async_connect(); return wait_conn(timeout); } bool connect(const std::string& host, unsigned short port, bool is_ssl = false, size_t timeout = 3) { if (port_ == 0) { host_ = host; port_ = port; } return connect(timeout, is_ssl); } void async_connect(const std::string& host, unsigned short port) { if (port_ == 0) { host_ = host; port_ = port; } async_connect(); } bool wait_conn(size_t timeout) { if (has_connected_) { return true; } has_wait_ = true; std::unique_lock<std::mutex> lock(conn_mtx_); conn_cond_.wait_for(lock, std::chrono::seconds(timeout), [this] { return has_connected_.load(); }); has_wait_ = false; return has_connected_; } void stop() { if (io_service_thread_ != nullptr) { io_service_.stop(); io_service_thread_->join(); io_service_thread_ = nullptr; } } void close(bool close_ssl = true) { boost::system::error_code ec; if (close_ssl) { #ifdef CINATRA_ENABLE_SSL if (ssl_stream_) { ssl_stream_->shutdown(ec); ssl_stream_ = nullptr; } #endif } if (!has_connected_) return; has_connected_ = false; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); socket_.close(ec); clear_cache(); } // sync call #if __cplusplus > 201402L template <size_t TIMEOUT, typename T = void, typename... Args> auto call(const std::string& rpc_name, Args&&... args) { std::future<request_result> future = async_call<FUTURE>(rpc_name, std::forward<Args>(args)...); auto status = future.wait_for(std::chrono::milliseconds(TIMEOUT)); if (status == std::future_status::timeout || status == std::future_status::deferred) { throw std::out_of_range("timeout or deferred"); } if constexpr (std::is_void_v<T>) { future.get().as(); } else { return future.get().as<T>(); } } template <typename T = void, typename... Args> auto call(const std::string& rpc_name, Args&&... args) { return call<DEFAULT_TIMEOUT, T>(rpc_name, std::forward<Args>(args)...); } #else // void类型的future template <size_t TIMEOUT = DEFAULT_TIMEOUT, typename T, typename... Args> typename std::enable_if<std::is_void<T>::value>::type call(const std::string& rpc_name, Args&&... args) { std::future<request_result> future = async_call<FUTURE>(rpc_name, std::forward<Args>(args)...); auto status = future.wait_for(std::chrono::milliseconds(TIMEOUT)); if (status == std::future_status::timeout || status == std::future_status::deferred) { throw std::out_of_range("timeout or deferred"); } future.get().as(); } // 非void类型的future template <size_t TIMEOUT = DEFAULT_TIMEOUT, typename T, typename... Args> typename std::enable_if<!std::is_void<T>::value, T>::type call(const std::string& rpc_name, Args&&... args) { std::future<request_result> future = async_call<FUTURE>(rpc_name, std::forward<Args>(args)...); auto status = future.wait_for(std::chrono::milliseconds(TIMEOUT)); if (status == std::future_status::timeout || status == std::future_status::deferred) { throw std::out_of_range("timeout or deferred"); } return future.get().as<T>(); } #endif template <CallModel model, size_t TIMEOUT = DEFAULT_TIMEOUT, typename... Args> typename std::enable_if<model == FUTURE, std::future<request_result>>::type async_call( const std::string& rpc_name, Args&&... args) { auto p = std::make_shared<std::promise<request_result>>(); std::future<request_result> future = p->get_future(); uint64_t fu_id = 0; { std::unique_lock<std::mutex> lock(callback_mutex_); fu_id_++; fu_id = fu_id_; future_map_.emplace(fu_id, std::move(p)); } msgpack_codec codec; auto ret = codec.pack_args(rpc_name, std::forward<Args>(args)...); write(fu_id, request_type::request, std::move(ret)); return future; } template <CallModel model, size_t TIMEOUT = DEFAULT_TIMEOUT, typename... Args> typename std::enable_if<model == CALLBACK>::type async_call( const std::string& rpc_name, std::function<void(boost::system::error_code, string_view)> cb, Args&&... args) { if (!has_connected_) { if (cb) cb(boost::asio::error::make_error_code(boost::asio::error::not_connected), "not connected"); return; } uint64_t cb_id = 0; { std::unique_lock<std::mutex> lock(callback_mutex_); callback_id_++; callback_id_ |= (uint64_t(1) << 63); cb_id = callback_id_; auto call = std::make_shared<call_t>(io_service_, std::move(cb), TIMEOUT); call->start_timer(); callback_map_.emplace(cb_id, call); } msgpack_codec codec; auto ret = codec.pack_args(rpc_name, std::forward<Args>(args)...); write(cb_id, request_type::request, std::move(ret)); } template <typename Func> void subscribe(std::string key, Func f) { auto it = subscribes_map_.find(key); if (it != subscribes_map_.end()) { assert("duplicated subscribe"); return; } subscribes_map_.emplace(key, std::move(f)); send_subscribe(key, ""); key_token_set_.emplace(std::move(key), ""); } template <typename Func> void subscribe(std::string key, std::string token, Func f) { auto composite_key = key + token; auto it = subscribes_map_.find(composite_key); if (it != subscribes_map_.end()) { assert("duplicated subscribe"); return; } subscribes_map_.emplace(std::move(composite_key), std::move(f)); send_subscribe(key, token); key_token_set_.emplace(std::move(key), std::move(token)); } template <typename T, size_t TIMEOUT = 3> void publish(std::string key, T&& t) { msgpack_codec codec; auto buf = codec.pack(std::forward<T>(t)); call<TIMEOUT>("publish", std::move(key), "", std::string(buf.data(), buf.size())); } template <typename T, size_t TIMEOUT = 3> void publish_by_token(std::string key, std::string token, T&& t) { msgpack_codec codec; auto buf = codec.pack(std::forward<T>(t)); call<TIMEOUT>("publish_by_token", std::move(key), std::move(token), std::string(buf.data(), buf.size())); } void enable_auto_reconnect(bool enable = true) { enable_reconnect_ = enable; } void enable_auto_heartbeat(bool enable = true) { if (enable) { reset_deadline_timer(5); } else { deadline_.cancel(); } } void update_addr(const std::string& host, unsigned short port) { host_ = host; port_ = port; } void set_error_callback(std::function<void(boost::system::error_code)> f) { error_callback_ = std::move(f); } uint64_t reqest_id() { return temp_req_id_; } bool has_connected() const { return has_connected_; } void set_connect_timeout(size_t milliseconds) { connect_timeout_ = milliseconds; } void set_reconnect_count(int reconnect_count) { reconnect_cnt_ = reconnect_count; } #ifdef CINATRA_ENABLE_SSL void set_ssl_context_callback(std::function<void(boost::asio::ssl::context&)> ssl_context_callback) { ssl_context_callback_ = std::move(ssl_context_callback); } #endif private: void async_connect() { assert(port_ != 0); auto addr = boost::asio::ip::address::from_string(host_); socket_.async_connect({addr, port_}, [this](const boost::system::error_code& ec) { if (has_connected_) { return; } if (ec) { std::cout << "connect failed, msg: " << ec.message() << std::endl; has_connected_ = false; if (reconnect_cnt_ <= 0) { return; } if (reconnect_cnt_ > 0) { reconnect_cnt_--; } async_reconnect(); } else { std::cout << "connected success" << std::endl; if (is_ssl()) { handshake(); return; } has_connected_ = true; read_head(); resend_subscribe(); if (has_wait_) conn_cond_.notify_one(); } }); } void async_reconnect() { reset_socket(); async_connect(); std::this_thread::sleep_for(std::chrono::milliseconds(connect_timeout_)); } void read_head() { async_read_head([this](const boost::system::error_code& ec, const size_t length) { if (!socket_.is_open()) { has_connected_ = false; return; } if (!ec) { auto* header = (rpc_header*)(head_); const uint32_t body_len = header->body_len; if (body_len > 0 && body_len < MAX_BUF_LEN) { if (body_.size() < body_len) { body_.resize(body_len); } read_body(header->req_id, header->req_type, body_len); return; } if (body_len == 0 || body_len > MAX_BUF_LEN) { close(); error_callback(asio::error::make_error_code(asio::error::message_size)); return; } } else { close(false); error_callback(ec); } }); } void read_body(std::uint64_t req_id, request_type req_type, size_t body_len) { async_read(body_len, [this, req_id, req_type, body_len](boost::system::error_code ec, std::size_t length) { if (!socket_.is_open()) { callback_request(req_id, asio::error::make_error_code(asio::error::connection_aborted), {}); return; } if (!ec) { if (req_type == request_type::request) { callback_request(req_id, ec, {body_.data(), body_len}); } else if (req_type == request_type::subscribe) { callback_subscribe(ec, {body_.data(), body_len}); } else { close(); error_callback(asio::error::make_error_code(asio::error::invalid_argument)); return; } read_head(); } else { has_connected_ = false; close(); error_callback(ec); } }); } void write(std::uint64_t req_id, request_type type, buffer_type&& message) { size_t size = message.size(); assert(size < MAX_BUF_LEN); client_message_type msg{req_id, type, {message.release(), size}}; std::unique_lock<std::mutex> lock(write_mtx_); write_queue_.emplace_back(msg); if (write_queue_.size() > 1) { return; } write(); } void write() { auto& msg = write_queue_[0]; write_size_ = (uint32_t)msg.content.length(); std::array<boost::asio::const_buffer, 4> write_buffers; write_buffers[0] = boost::asio::buffer(&write_size_, sizeof(int32_t)); write_buffers[1] = boost::asio::buffer(&msg.req_id, sizeof(uint64_t)); write_buffers[2] = boost::asio::buffer(&msg.req_type, sizeof(request_type)); write_buffers[3] = boost::asio::buffer((char*)msg.content.data(), write_size_); async_write(write_buffers, [this](const boost::system::error_code& ec, const size_t length) { if (ec) { has_connected_ = false; close(false); error_callback(ec); return; } std::unique_lock<std::mutex> lock(write_mtx_); if (write_queue_.empty()) { return; } ::free((char*)write_queue_.front().content.data()); write_queue_.pop_front(); if (!write_queue_.empty()) { // more messages to send this->write(); } }); } void send_subscribe(const std::string& key, const std::string& token) { msgpack_codec codec; auto ret = codec.pack_args(key, token); write(0, request_type::subscribe, std::move(ret)); } void resend_subscribe() { if (key_token_set_.empty()) return; for (auto& pair : key_token_set_) { send_subscribe(pair.first, pair.second); } } void callback_request(uint64_t req_id, const boost::system::error_code& ec, string_view data) { temp_req_id_ = req_id; auto cb_flag = req_id >> 63; if (cb_flag) { std::shared_ptr<call_t> cl = nullptr; { std::unique_lock<std::mutex> lock(callback_mutex_); cl = std::move(callback_map_[req_id]); } assert(cl); if (!cl->has_timeout()) { cl->cancel(); cl->callback(ec, data); } else { cl->callback(asio::error::make_error_code(asio::error::timed_out), {}); } std::unique_lock<std::mutex> lock(callback_mutex_); callback_map_.erase(req_id); } else { std::unique_lock<std::mutex> lock(callback_mutex_); auto& f = future_map_[req_id]; if (ec) { if (!f) { return; } } assert(f); f->set_value(request_result{data}); future_map_.erase(req_id); } } void callback_subscribe(const boost::system::error_code& ec, string_view result) { rpc_service::msgpack_codec codec; try { auto tp = codec.unpack<std::tuple<int, std::string, std::string>>(result.data(), result.size()); auto code = std::get<0>(tp); auto& key = std::get<1>(tp); auto& data = std::get<2>(tp); auto it = subscribes_map_.find(key); if (it == subscribes_map_.end()) { return; } it->second(data); } catch (const std::exception& /*ex*/) { error_callback(asio::error::make_error_code(asio::error::invalid_argument)); } } void reset_deadline_timer(size_t timeout) { deadline_.expires_from_now(std::chrono::seconds(timeout)); deadline_.async_wait([this, timeout](const boost::system::error_code& ec) { if (!ec) { if (has_connected_) { write(0, request_type::request, buffer_type(0)); } } reset_deadline_timer(timeout); }); } void clear_cache() { { std::unique_lock<std::mutex> lock(write_mtx_); while (!write_queue_.empty()) { ::free((char*)write_queue_.front().content.data()); write_queue_.pop_front(); } } { std::unique_lock<std::mutex> lock(callback_mutex_); callback_map_.clear(); future_map_.clear(); } } void reset_socket() { boost::system::error_code ignored_ec; socket_.close(ignored_ec); socket_ = decltype(socket_)(io_service_); if (!socket_.is_open()) { socket_.open(boost::asio::ip::tcp::v4()); } } void error_callback(const boost::system::error_code& ec) { if (error_callback_) { error_callback_(ec); } if (enable_reconnect_) { async_connect(); } } void set_default_error_cb() { error_callback_ = [this](boost::system::error_code) { async_connect(); }; } bool is_ssl() const { #ifdef CINATRA_ENABLE_SSL return ssl_stream_ != nullptr; #else return false; #endif } void handshake() { #ifdef CINATRA_ENABLE_SSL ssl_stream_->async_handshake( boost::asio::ssl::stream_base::client, [this](const boost::system::error_code& ec) { if (!ec) { has_connected_ = true; do_read(); resend_subscribe(); if (has_wait_) conn_cond_.notify_one(); } else { error_callback(ec); close(); } }); #endif } void upgrade_to_ssl() { #ifdef CINATRA_ENABLE_SSL if (ssl_stream_) return; boost::asio::ssl::context ssl_context(boost::asio::ssl::context::sslv23); ssl_context.set_default_verify_paths(); boost::system::error_code ec; ssl_context.set_options(boost::asio::ssl::context::default_workarounds, ec); if (ssl_context_callback_) { ssl_context_callback_(ssl_context); } ssl_stream_ = std::make_unique<boost::asio::ssl::stream<boost::asio::ip::tcp::socket&>>(socket_, ssl_context); // verify peer TODO #else assert(is_ssl()); // please add definition CINATRA_ENABLE_SSL, not allowed coming in this branch #endif } template <typename Handler> void async_read_head(Handler handler) { if (is_ssl()) { #ifdef CINATRA_ENABLE_SSL boost::asio::async_read(*ssl_stream_, boost::asio::buffer(head_, HEAD_LEN), std::move(handler)); #endif } else { boost::asio::async_read(socket_, boost::asio::buffer(head_, HEAD_LEN), std::move(handler)); } } template <typename Handler> void async_read(size_t size_to_read, Handler handler) { if (is_ssl()) { #ifdef CINATRA_ENABLE_SSL boost::asio::async_read(*ssl_stream_, boost::asio::buffer(body_.data(), size_to_read), std::move(handler)); #endif } else { boost::asio::async_read(socket_, boost::asio::buffer(body_.data(), size_to_read), std::move(handler)); } } template <typename BufferType, typename Handler> void async_write(const BufferType& buffers, Handler handler) { if (is_ssl()) { #ifdef CINATRA_ENABLE_SSL boost::asio::async_write(*ssl_stream_, buffers, std::move(handler)); #endif } else { boost::asio::async_write(socket_, buffers, std::move(handler)); } } class call_t : public std::enable_shared_from_this<call_t> { public: call_t(asio::io_service& ios, std::function<void(boost::system::error_code, string_view)> cb, size_t timeout) : timeout_timer_(ios), cb_(std::move(cb)), timeout_ms_(timeout) { } call_t(const call_t&) = delete; call_t operator=(const call_t&) = delete; void start_timer() { if (timeout_ms_ == 0) { return; } timeout_timer_.expires_from_now(std::chrono::milliseconds(timeout_ms_)); auto self = this->shared_from_this(); timeout_timer_.async_wait([this, self](boost::system::error_code ec) { if (ec) { return; } has_timeout_ = true; }); } void callback(boost::system::error_code ec, string_view data) { cb_(ec, data); } bool has_timeout() const { return has_timeout_; } void cancel() { if (timeout_ms_ == 0) { return; } boost::system::error_code ec; timeout_timer_.cancel(ec); } private: boost::asio::steady_timer timeout_timer_; size_t timeout_ms_; bool has_timeout_ = false; std::function<void(boost::system::error_code, string_view)> cb_; }; struct client_message_type { std::uint64_t req_id; request_type req_type; string_view content; }; boost::asio::io_service io_service_; asio::ip::tcp::socket socket_; #ifdef CINATRA_ENABLE_SSL std::unique_ptr<boost::asio::ssl::stream<boost::asio::ip::tcp::socket&>> ssl_stream_; std::function<void(boost::asio::ssl::context&)> ssl_context_callback_; #endif boost::asio::io_service::work work_; std::shared_ptr<std::thread> io_service_thread_ = nullptr; std::string host_; unsigned short port_ = 0; size_t connect_timeout_ = 1000; // s int reconnect_cnt_ = -1; std::atomic_bool has_connected_ = {false}; std::mutex conn_mtx_; std::condition_variable conn_cond_; bool has_wait_ = false; asio::steady_timer deadline_; std::deque<client_message_type> write_queue_; uint32_t write_size_ = 0; std::mutex write_mtx_; uint64_t fu_id_ = 0; std::function<void(boost::system::error_code)> error_callback_; bool enable_reconnect_ = false; std::unordered_map<std::uint64_t, std::shared_ptr<std::promise<request_result>>> future_map_; std::unordered_map<std::uint64_t, std::shared_ptr<call_t>> callback_map_; std::mutex callback_mutex_; uint64_t callback_id_ = 0; uint64_t temp_req_id_ = 0; char head_[HEAD_LEN] = {}; std::vector<char> body_; std::unordered_map<std::string, std::function<void(string_view)>> subscribes_map_; std::set<std::pair<std::string, std::string>> key_token_set_; }; } // namespace rest_rpc #endif
1f98f0a18992bac845bd0ceb849e830d819bfc6c
24d4eaf7a113c45e39d512cd35803fe5cbadb501
/ChatServer/Misc.cpp
f45b1cf72fff95660802604a1e9caac2421bd40a
[ "Apache-2.0" ]
permissive
kc345ws/ChatMFC
42d29e799e9bbf638e0bd39c8ba86859cc405c16
d568a3d36434ff18524dd635e6fa2615aeb5564e
refs/heads/master
2020-03-16T08:19:15.011355
2018-05-04T13:20:12
2018-05-04T13:20:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,822
cpp
Misc.cpp
#include "stdafx.h" #include "ChatServer.h" #include "ChatServerDlg.h" void CChatServerDlg::OnBnClickedOk() { PasswordBox->GetWindowTextW(Context.Password, 16); Context.ServerThread = AfxBeginThread(CChatServerContext::ServerFunc, &Context); } void CChatServerDlg::OnBnClickedButton2() { if (Context.ServerThread) { if (Context.ServerSocket && Context.ServerSocket != 3435973836 && ~Context.ServerSocket) closesocket(Context.ServerSocket); WSACancelBlockingCall(); Context.ServerThread = NULL; } } BOOL CChatServerContext::Log(WPARAM wParam, CChatClientContext *a) { return CChatServerDlg::Log(Window, wParam, a); } BOOL CChatServerContext::Log(WPARAM wParam, LPCWSTR a) { return CChatServerDlg::Log(Window, wParam, a); } BOOL CChatServerContext::Log(WPARAM wParam, LPCWSTR a, PCSTR v) { return CChatServerDlg::Log(Window, wParam, a, v); } BOOL CChatServerContext::Log(WPARAM wParam, LPCWSTR a, LPCWSTR v) { return CChatServerDlg::Log(Window, wParam, a, v); } BOOL CChatServerContext::Log(WPARAM wParam, LPCWSTR a, DWORD b) { return CChatServerDlg::Log(Window, wParam, a, b); } BOOL CChatServerContext::Log(WPARAM wParam, LPCWSTR str, sockaddr_in wtf) { return CChatServerDlg::Log(Window, wParam, str, wtf); } BOOL CChatClientContext::Log(WPARAM wParam, LPCWSTR a) { return CChatServerDlg::Log(Window, wParam, a); } BOOL CChatClientContext::Log(WPARAM wParam, LPCWSTR a, PCSTR v) { return CChatServerDlg::Log(Window, wParam, a, v); } BOOL CChatClientContext::Log(WPARAM wParam, LPCWSTR a, LPCWSTR v) { return CChatServerDlg::Log(Window, wParam, a, v); } BOOL CChatClientContext::Log(WPARAM wParam, LPCWSTR a, DWORD b) { return CChatServerDlg::Log(Window, wParam, a, b); } BOOL CChatClientContext::Log(WPARAM wParam, LPCWSTR str, sockaddr_in wtf) { return CChatServerDlg::Log(Window, wParam, str, wtf); }
c28635ab1d9074c7e2f1aee7c77f87af1574f16b
c56a11bf4a49ce315e5fead7563b792c4a1c5cf6
/SPN/unused/main.cpp
710105185a2bb8652b49eef6ca2e44635830d724
[]
no_license
podiumdesu/cryptography_design
d1c52ca46dec30316951f837b53bc7939e0a9b60
d134e172a5f1f69cb14a6d80d3477292bf14ed90
refs/heads/master
2021-10-10T23:04:07.295800
2019-01-18T17:04:23
2019-01-18T17:04:23
143,545,598
0
0
null
null
null
null
UTF-8
C++
false
false
6,378
cpp
main.cpp
#include <stdio.h> #include <stdlib.h> #include "spn_create.h" int max = 1310720; // 10M unsigned long long k1=0x123ab25df686c124; unsigned long long k2=0x973a5b6c7f7a654d; unsigned long long x1=0x0000000000000000; unsigned long long x2=0x0000000000000000; unsigned long long iv1=0x3a94d63f12345678; unsigned long long iv2=0x3a94d63f12345678; int main (void) { int choice; int op = 1; char filename[]="cipherdataOld"; unsigned long save_spn_x_encryption[100]; unsigned long save_spn_y_encryption[100]; unsigned long long save_spn_k_encryption[100]; unsigned long save_spn_x_decryption[100]; unsigned long save_spn_y_decryption[100]; unsigned long long save_spn_k_decryption[100]; int save_spn_num = 0; int save_spn_num_decryption = 0; // x = 0x3333fdfdffffdada; // printf("输入明文为:%lx", x); unsigned long long keyString = 0b00111010100101001101011000111111; unsigned long input_x, input_y; char change_key_choice; while(op) { // system("clear"); printf("\n"); printf(" 密码学课程设计 \n"); printf("-------------------------------------------------\n"); printf(" 1. SPN 加密明文 2. SPN 解密密文\n"); printf(" 3. SPN 线性分析 4. SPN 差分分析\n"); printf(" 5. 查看当前参数及历史记录 6. SPN 检测\n"); printf(" 0. 退出\n"); printf("-------------------------------------------------\n"); printf("请输入选择序号: "); scanf("%d", &op); switch (op) { case 1: printf("请输入明文 x :"); scanf("%lx", &input_x); save_spn_x_encryption[save_spn_num] = input_x; unsigned int y = spn_create(input_x, keyString); save_spn_y_encryption[save_spn_num] = y; save_spn_k_encryption[save_spn_num] = keyString; save_spn_num++; printf("加密得密文 y :%x\n", y); printf("请按回车键继续......\n"); getchar(); getchar(); break; case 2: printf("请输入密文 y :"); scanf("%lx", &input_y); save_spn_x_decryption[save_spn_num_decryption] = input_y; unsigned int new = spn_decode(input_y, keyString); save_spn_y_decryption[save_spn_num_decryption] = new; save_spn_k_decryption[save_spn_num_decryption] = keyString; save_spn_num_decryption++; printf("解密得明文 x :%x\n", new); printf("请按回车键继续......\n"); getchar(); getchar(); break; case 3: printf("正确密钥应为 %llx\n", keyString); printf("正在对密钥进行线性分析中.......\n"); spn_linear_analysis(keyString); printf("请按回车键继续......\n"); getchar(); getchar(); break; case 4: printf("正确密钥应为 %llx\n", keyString); printf("正在对密钥进行差分分析中.......\n"); spn_diff_analysis(keyString); printf("请按回车键继续......\n"); getchar(); getchar(); break; case 5: printf("当前SPN基本参数如下所示:\n"); printf("当前使用密钥为: %llx\n", keyString); printf("------- 历史加密记录 -------\n"); if (save_spn_num > 0) { printf("明文 密钥 密文\n"); for (int i = 0; i < save_spn_num; i++) { printf("%lx %llx %lx\n", save_spn_x_encryption[i], save_spn_k_encryption[i], save_spn_y_encryption[i]); } } else { printf("暂无...\n"); } printf("\n"); printf("------- 历史解密记录 -------\n"); if (save_spn_num_decryption > 0) { printf("密文 密钥 明文\n"); for (int j = 0; j < save_spn_num_decryption; j++) { printf("%lx %llx %lx\n", save_spn_x_decryption[j], save_spn_k_decryption[j], save_spn_y_decryption[j]); } } else { printf("暂无...\n"); } printf("\n\n修改密钥?[y/n] "); scanf(" %c", &change_key_choice); if (change_key_choice == 'y') { printf("请重新输入密钥(30位):"); scanf("%llx", &keyString); } else if (change_key_choice == 'n') { // printf("当前使用密钥为: %llx\n", keyString); } printf("请按回车键继续......\n"); getchar(); getchar(); break; case 6: unsigned long long * cipherdata; cipherdata = (unsigned long long *)malloc(sizeof(unsigned long long) * max); cipherdata[0] = spn_create(x1^iv1, k1); cipherdata[1] = spn_create(x2^iv2, k2); for (int k = 0; k < max / 2; k++) { cipherdata[k*2] = spn_create(cipherdata[k*2-1]^x1, k1); cipherdata[k*2+1] = spn_create(cipherdata[k*2]^x2, k2); } FILE *fp; fp = fopen(filename, "wb"); for (int k = 0; k < max; k++) { fwrite(&cipherdata[k], sizeof(unsigned long long), 1, fp); } fclose(fp); printf("随机检测所需要的密文生成成功!"); break; case 0: printf("\n欢迎下次使用本系统\n"); op = 0; break; } } return 0; } // keyString = 0b00111010100101001101011000111111; // keyString = 0b0011101001010010111011110101111000111101; // keyString = 0b00111010100101001101011000100111;
4e8fe08dbc9135c7ac21c8f9e45eaa023193d3ea
49bfb93d4775a43cd1d564c90f8de3b81fc4474c
/Labsheets/Lab_5 (Queue)/queue/queue_array.h
29ddd097ac9f08017a7eb7f5b4a22623953cbdbf
[]
no_license
tt-jaimon/Data-Structures
1532cc3f4ffdb88ac31c5b49e6781e6a4e4c19a6
aaacdb75878525962e3da14379c3c9e47ff2cd9a
refs/heads/master
2020-05-17T10:47:56.989844
2015-04-15T18:14:15
2015-04-15T18:14:15
27,226,505
0
0
null
null
null
null
UTF-8
C++
false
false
816
h
queue_array.h
#ifndef QUEUE_ARRAY_H #define QUEUE_ARRAY_H using namespace std; #include<iostream> class Queue_Array { static const size_t queue_size = 5; typedef size_t size_type; typedef int value_type; value_type data[queue_size]; size_type Queue_Size; int front_queue; int back_queue; public: Queue_Array() :front_queue(-1), back_queue(-1), Queue_Size(0){} bool empty() const{ return(Queue_Size == 0); } void push(const int& x); void pop(); size_type size() const{ return Queue_Size; } value_type& front(){ return data[front_queue];} const value_type& front() const { return data[front_queue]; } value_type& back() { return data[back_queue]; } const value_type& back() const{ return data[back_queue]; } friend ostream& operator<<(ostream& out, const Queue_Array& s); }; #endif
d29d1eda296c6e4ec7a8ca86d6377f63848e7e89
afe703e78726cac56ac084021cafe870eee7bdec
/core/utils/lz4compression.cpp
55a02fac8ff98298af7b5f45484c5d4c99ff7cdf
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unicode", "Unicode-DFS-2016", "BSD-3-Clause", "BSL-1.0", "BSD-2-Clause" ]
permissive
iresearch-toolkit/iresearch
061e0296cc0735c16f6ac9c69fbab1f21b77d92f
27444dbdc18289b676a9fd45388861d4d496628f
refs/heads/master
2023-08-16T23:58:24.239543
2023-08-16T19:20:58
2023-08-16T19:20:58
71,565,220
182
31
NOASSERTION
2023-09-14T16:23:43
2016-10-21T13:06:05
C++
UTF-8
C++
false
false
4,403
cpp
lz4compression.cpp
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2019 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov //////////////////////////////////////////////////////////////////////////////// #include "lz4compression.hpp" #include <lz4.h> #include "error/error.hpp" #include "shared.hpp" #include "utils/misc.hpp" #include "utils/type_limits.hpp" namespace irs { namespace { // can reuse stateless instances compression::lz4::lz4compressor kLZ4BasicCompressor; compression::lz4::lz4decompressor kLZ4BasicDecompressor; inline int acceleration(const compression::options::Hint hint) noexcept { static constexpr int FACTORS[]{0, 2, 0}; IRS_ASSERT(static_cast<size_t>(hint) < std::size(FACTORS)); return FACTORS[static_cast<size_t>(hint)]; } } // namespace static_assert(sizeof(char) == sizeof(byte_type)); namespace compression { void LZ4_streamDecode_deleter::operator()(void* p) noexcept { if (p != nullptr) { LZ4_freeStreamDecode(reinterpret_cast<LZ4_streamDecode_t*>(p)); } } void LZ4_stream_deleter::operator()(void* p) noexcept { if (p != nullptr) { LZ4_freeStream(reinterpret_cast<LZ4_stream_t*>(p)); } } lz4stream lz4_make_stream() { return lz4stream(LZ4_createStream()); } lz4stream_decode lz4_make_stream_decode() { return lz4stream_decode(LZ4_createStreamDecode()); } bytes_view lz4::lz4compressor::compress(byte_type* src, size_t size, bstring& out) { IRS_ASSERT(size <= static_cast<unsigned>( std::numeric_limits<int>::max())); // LZ4 API uses int const auto src_size = static_cast<int>(size); // Ensure we have enough space to store compressed data, // but preserve original size const uint32_t bound = LZ4_COMPRESSBOUND(src_size); out.resize(std::max(out.size(), size_t{bound})); const auto* src_data = reinterpret_cast<const char*>(src); auto* buf = reinterpret_cast<char*>(out.data()); const auto buf_size = static_cast<int>(out.size()); const auto lz4_size = LZ4_compress_fast(src_data, buf, src_size, buf_size, acceleration_); if (IRS_UNLIKELY(lz4_size < 0)) { throw index_error{"While compressing, error: LZ4 returned negative size"}; } return {reinterpret_cast<const byte_type*>(buf), static_cast<size_t>(lz4_size)}; } bytes_view lz4::lz4decompressor::decompress(const byte_type* src, size_t src_size, byte_type* dst, size_t dst_size) { IRS_ASSERT(src_size <= static_cast<unsigned>( std::numeric_limits<int>::max())); // LZ4 API uses int const auto lz4_size = LZ4_decompress_safe( reinterpret_cast<const char*>(src), reinterpret_cast<char*>(dst), static_cast<int>(src_size), // LZ4 API uses int static_cast<int>(std::min( dst_size, static_cast<size_t>( std::numeric_limits<int>::max()))) // LZ4 API uses int ); if (IRS_UNLIKELY(lz4_size < 0)) { return {}; // corrupted index } return bytes_view{dst, static_cast<size_t>(lz4_size)}; } compressor::ptr lz4::compressor(const options& opts) { const auto acceleration = irs::acceleration(opts.hint); if (0 == acceleration) { return memory::to_managed<lz4compressor>(kLZ4BasicCompressor); } return memory::make_managed<lz4compressor>(acceleration); } decompressor::ptr lz4::decompressor() { return memory::to_managed<lz4decompressor>(kLZ4BasicDecompressor); } void lz4::init() { // match registration below REGISTER_COMPRESSION(lz4, &lz4::compressor, &lz4::decompressor); } REGISTER_COMPRESSION(lz4, &lz4::compressor, &lz4::decompressor); } // namespace compression } // namespace irs
8ffabb1663d4adca47fd5fe55f7f9e642efb4aa9
e1aa89225cbf3b540db43c69bb161209dbb2ce90
/person.h
75fde9847642e1e12c7fbf6963995f4f9a102840
[]
no_license
chitalshangy/curriculum-design
32a20c1b7283ae94b5d8bbe71f4c88bb08f4a882
07fa03b92ee926359b090bec668687edbb01e20e
refs/heads/master
2021-06-26T07:42:13.363713
2020-12-07T13:56:10
2020-12-07T13:56:10
189,151,745
0
0
null
null
null
null
GB18030
C++
false
false
2,152
h
person.h
#include<iostream> #include<cstring> using namespace std; class person { public: person();//无参构造函数 void setname(string q1);//设置姓名 void setsex(string q2);//设置性别 void setpbnumber(string q3);//设置电话号码 void setaddress(string q4);//设置地址 void setpostal_code(string q5);//设置邮政编码 void setemail(string q6);//设置邮箱 void setQQnumber(string q7);//设置QQ号 void settype(string q8);//设置类别 string getname();//获取姓名 string getsex();//获取性别 string getpbnumber();//获取电话号码 string getaddress();//获取地址 string getpostal_code();//获取邮政编码 string getemail();//获取邮箱 string getQQnumber();//获取QQ号码 string gettype();//获取类别 void searchname(string rname);//查找姓名 void searchpbnumber(string rnumber);//查找电话号码 void searchaddress(string raddress);//查找地址 void searchtype(string rtype);//查找类别 void sortname();//根据姓名排序 void sortsex();//根据性别排序 void sortpostal_code();//根据邮政编码排序 void sorttype();//根据类别排序 void loadperson(string q1,string q2,string q3,string q4,string q5,string q6,string q7,string q8);//重新设置人员信息 person* searchxname(string xname);//根据姓名查找信息,后修改 person* searchxpbnumber(string xpbnumber);//根据电话号码查找信息,后修改 person* searchscname(string sname);//根据姓名查找信息,后删除 person* searchscname1(string sname);//辅助根据姓名查找信息,后删除 person* searchscpbnumber(string spbnumber);//根据电话号码查找信息,后删除 person* searchscpbnumber1(string spbnumber);//辅助根据电话号码查找信息,后删除 void pinout();//输出信息 person *next;//定义next指针,用于建立链表 ~person();//析构函数 private: //定义姓名、性别、电话号码、地址、邮政编码、邮箱、QQ号码、类别变量 string name,sex,pbnumber,address,postal_code,email,QQnumber,type; };
796d8b0219e9557c22ee21b32923226b5999df0b
b3e5b0bd78521e7cc02d45076305bfcdd6095462
/NAVS/userTools/usertools.h
7a4a28c0bfe8c356842281e17842ccb66273abfe
[]
no_license
rapcode005/QMLApp
4e3fc2681c10474a10c7ba1f1358fef1200ef6da
b764db47a22d66584a7b6933b9b512e07588c323
refs/heads/master
2022-12-28T06:31:23.388021
2020-10-12T09:27:25
2020-10-12T09:27:25
303,338,979
0
0
null
null
null
null
UTF-8
C++
false
false
1,481
h
usertools.h
#ifndef USERTOOLS_H #define USERTOOLS_H #include <QAbstractListModel> #include <QObject> #include <QJsonObject> #include "webServicesTools/webservicestools.h" #include "organizationModel.h" #include "installationTools/installationtools.h" class UserTools : public QObject { Q_OBJECT public: explicit UserTools(QObject *parent = nullptr); void checkOrganization(const QString &s_organizationDnsKey); void loginWindowsUsername(); int getLoginTypeID(const QJsonObject &user) const; void loadMeData(const QString &sessionKey); void loadOrganizationByID(const int organizationID, const QString &sessionKey); signals: void organizationDnsKeyStatusLoaded(const bool &organizationDnsKeyStatus); void organizationDataLoaded(OrganizationModel *organizationModel); void loginWindowsUsernameLoaded(const QJsonObject &result); void meDataLoaded(const QJsonObject jsonResult); void writeLogItem(const QString logVal); void organizationDNSKeyErrorLoaded(const QString &code); void organizationByIDErrorLoaded(const QString &code); void loginWindowsUsernameErrorLoaded(const QString &code); void loadMeDataErrorLoaded(const QString &code); void networkError(QNetworkReply::NetworkError code); public slots: void requestErrorOccurred(QNetworkReply::NetworkError code); private: QJsonObject jsonOrganization; WebServicesTools webServiceTools; InstallationTools installationTools; }; #endif // USERTOOLS_H
48e0be23e3a9214e813f584f89acbe82c880f5a4
0937a9f2a63692a058dded1eb80afd2ce2759e9f
/Line.h
245cb0602a9a6e51ee26e9d2dab0dfd2953742bb
[]
no_license
mejaseye9083/Individual_team
4318d458d92115de9679e7d85b6468e8a708b86e
49922689f7b38b576c9caa0d5950d0acb55a0074
refs/heads/master
2021-01-10T07:33:50.859837
2016-03-11T04:25:54
2016-03-11T04:25:54
51,127,622
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
996
h
Line.h
/*=========================================================================================== 概 略:描画関連の作成(カメラの向いてる向きのチェック等) 作成日:2015.08.31 更新日:2015.09.02 制作者:藤原順基 =============================================================================================*/ #pragma once //---------------インクルード----------------------- #include "Global.h" //--------------ラインクラスの定義------------------ class Line { public: //---------------------------------- //機能:描画処理(カラー無し) //引数:なし //戻値:成功or失敗 //---------------------------------- HRESULT Draw(D3DXVECTOR3 start, D3DXVECTOR3 end); //---------------------------------- //機能:描画処理(カラー付き) //引数:なし //戻値:成功or失敗 //---------------------------------- HRESULT Draw(D3DXVECTOR3 start, D3DXVECTOR3 end, DWORD color); };
89cb96c4c95799245f3aae9da5a304e3452401a2
925eca107f80e1b066a6dcc939b9a5758e5ac287
/7_09_1/7_09_1/7_09_6.cpp
1ec2ba5ec19061ab401125c9c9e3ad3df793f92c
[]
no_license
SeungWookJung/Cpp_Study
8f03cf23f28421ad478e5f8c913ea270dc8c97e1
66c39e5c57aca551e1b81fc72e2f3b2eb2c8dd12
refs/heads/master
2020-06-21T05:16:08.218304
2019-07-30T02:25:05
2019-07-30T02:25:05
197,353,226
0
0
null
null
null
null
UHC
C++
false
false
1,079
cpp
7_09_6.cpp
#include <iostream> using namespace std; typedef struct Person { int id; string name; int phone; }; int main() { int id = 0; int count = 0; int Default = 5; Person p; Person* person = new Person[Default]; int* dynamic_memory1 = new int[5]; int array_size = sizeof(*dynamic_memory1) / sizeof(int); while (1) { if (array_size > Default) { Default=Default + 5; int* dynamic_memory2 = new int[Default]; copy(dynamic_memory1[0], dynamic_memory1[5],*dynamic_memory2); delete[] dynamic_memory1; dynamic_memory1 = nullptr; dynamic_memory1 = dynamic_memory2; } cout << "id를 입력해 주세요" << endl; cin >> id; if (id == -1) { for (int i = 0; i= Default; i++) { cout << dynamic_memory1[i] << endl; } exit(1); } person[count].id = id; cout << "이름을 입력해 주세요" << endl; cin >> person[count].name; cout << "전화번호를 입력해 주세요" << endl; cin >> person[count].phone; count++; copy(person[0], person[Default], *dynamic_memory1); } return 0; }
4227a02a6a7ed3e38b822d7edd2780bfc79bc386
74ec995628b5dc433367d834890df040aae196e3
/src/kruto/sandbox/application.hpp
ed57a2052ce26427870233a3f42b009f2e43c622
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bagobor/kruto.js
4b9f6d5035bf0ec69d8de783a8f7663209055013
ac602b27b3b9c1a6212d4b0bb6b4e2b1f383f415
refs/heads/master
2021-01-16T19:54:23.776023
2013-01-11T17:16:23
2013-01-11T17:16:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
725
hpp
application.hpp
#ifndef KRAPPLICATION_HPP #define KRAPPLICATION_HPP namespace kruto { class Script; class Application { public: public: Application(const int pArgc, char **pArgv); ~Application(void); bool initialize(void); void uninitialize(void); int translateKey(const int pKey) const; void processEvents(void); int exec(void); void setTitle(const char *pTitle); const char *title(void) const; int argc(void) const; char **argv(void) const; const char *argv(const unsigned int pIndex); unsigned int width(void) const; unsigned int height(void) const; unsigned int ticks(void) const; void quit(void); private: int mArgc; char **mArgv; int mWidth; int mHeight; bool mRunning; Script *mScript; }; } #endif
c6aa4a5ab95a89e34d3540945bcf05697606114c
4e4b253d61b2502ae9c18c4587df8a4dac2b072b
/Program8_Task1.cpp
098c926190339a46bf3225a2d1bd6d440b6b90ab
[]
no_license
hardik20sharma/Classroom_Data_Structures_and_Algorithms
8674964832044460c9ab59e56d306ca84d429b0e
1635d7981e292684f71b38bed771c8282ae76863
refs/heads/master
2022-04-20T18:56:21.568000
2020-04-19T12:05:17
2020-04-19T12:05:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,693
cpp
Program8_Task1.cpp
// WAP to insert, display, delete elements in circular linked list #include<iostream> using namespace std; struct node { int info; node *next; } *start, *rear, *newptr, *ptr; node *create_new_node(int inf) { ptr = new node; ptr->info = inf; ptr->next = NULL; } void insert_node(node *n) { if(start == NULL) start = rear = n; else { rear->next = n; n->next = start; rear = n; } } void display_node(node *n) { if(start == NULL) cout << "UNDERFLOW ERROR !!\n"; else { while(n) { cout << n->info <<"->"; if(n->next == start) break; n = n->next; } cout << "END\n"; } } void delete_node(int inf) { bool cnd; if(start==NULL) { cout << "UNDERFLOW\n"; } else { node *store; ptr = start; while(ptr->info!=inf) { store = ptr; ptr = ptr->next; } store->next = ptr->next; delete ptr; } } int main() { int ch=0, info; flag1: cout << "------------------\n"; cout << "1. Insert Element\n"; cout << "2. Display Element\n"; cout << "3. Delete Element\n"; cout << "Enter your choice: "; cin >> ch; cout << "------------------\n"; switch(ch) { case 1: cout << "Enter the information: "; cin >> info; newptr = create_new_node(info); if(!newptr) { cout<<"Problem creating in node !"; exit(0); } insert_node(newptr); goto flag1; case 2: cout << "Displaying data...\n"; display_node(start); goto flag1; case 3: cout << "Enter the element to delete: "; cin >> info; delete_node(info); goto flag1; default: cout << "Wrong Input !!\n\n"; goto flag1; } }
642d4c42946fb956db96ecc4b6c95498c76670ee
971a269417a87b9755f2904836e462d1999b1333
/test-2/main.cpp
d89e798e7bdd013d6392d54a9a1e2906e419359d
[]
no_license
egon12/OFsketchToH264
f4ab4232724f22adf6a273165253530aab99a355
f86bc0edff4a6443646a713a564a19729dfaf02f
refs/heads/master
2020-04-23T18:38:39.279930
2019-02-15T16:58:27
2019-02-15T16:58:27
171,374,681
0
0
null
null
null
null
UTF-8
C++
false
false
426
cpp
main.cpp
#include <iostream> #include "../src/movie/RGBtoYCbCr.hpp" int main() { int w, h, c; w = h = 2; c = 3; unsigned char rgb_data[12] = {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}; auto converter = new RGBtoYCbCr(w, h, c); converter->setRGB(rgb_data); auto yuvImage = converter->yuvImage; for (int i=0; i<4; i++) { std::cout << (int) yuvImage[i] << ","; } std::cout << "\n"; }
614552938eb76a614f76cb111bb9ab7c070e44fc
6531a31eaa5d9c7f8720f2c7b2667e6ce96a75e5
/TMXTiledMapEx.h
80505201c17f520311a56ac7860a20459ea42543
[ "MIT" ]
permissive
DEAGS3000/cocos2dx-animated-tile-support
f3febbdd2359993101220e4d849af9ca327c0f9a
228c9e33217b050e5c96961629f148172caebaab
refs/heads/master
2020-08-31T02:04:59.006316
2019-11-18T12:10:55
2019-11-18T12:10:55
218,553,301
8
1
null
null
null
null
UTF-8
C++
false
false
1,727
h
TMXTiledMapEx.h
#pragma once #include "cocos2d.h" #include "TMXLayerEx.h" #include "TMXTilesetInfoEx.h" USING_NS_CC; namespace pm { class TMXLayerEx; class TMXLayerInfoEx; class TMXMapInfoEx : public TMXMapInfo { public: static TMXMapInfoEx * create(const std::string& tmxFile); /// Layers const Vector<TMXLayerInfoEx*>& getLayers() const; Vector<TMXLayerInfoEx*>& getLayers(); void setLayers(const Vector<TMXLayerInfoEx*>& layers); /// tilesets const Vector<TMXTilesetInfoEx*>& getTilesets() const; Vector<TMXTilesetInfoEx*>& getTilesets(); void setTilesets(const Vector<TMXTilesetInfoEx*>& tilesets); /** initializes a TMX format with a tmx file */ bool initWithTMXFileEx(const std::string& tmxFile); private: void startElement(void* /*ctx*/, const char *name, const char **atts) override; void endElement(void *ctx, const char *name) override; protected: /// Layers Vector<TMXLayerInfoEx*> _layers; /// tilesets Vector<TMXTilesetInfoEx*> _tilesets; }; class TMXTiledMapEx : public TMXTiledMap { public: static TMXTiledMapEx* create(const std::string& tmxFile); TMXTiledMapEx(); ~TMXTiledMapEx(); bool initWithTMXFileEx(const std::string& tmxFile); //void runTileAnimations(); void onEnter() override; void update(float dt) override; //Vector<Sprite*> animation_tiles_; protected: TMXTilesetInfoEx * tilesetForLayer(TMXLayerInfoEx *layerInfo, TMXMapInfoEx *mapInfo); TMXLayerEx * parseLayer(TMXLayerInfoEx *layerInfo, TMXMapInfoEx *mapInfo); void buildWithMapInfoEx(TMXMapInfoEx* mapInfo); }; }
b9f371b6a5d5aab25dabfd0a0f30c86a3df37ac4
1a380d6b5a6ed3984874b68ade18830056ff0b3b
/TREES/Trees 0/printing a tree in reverse order.cpp
71bf936cb49e6cdf4fc48f77ccfe6651a4c20831
[]
no_license
avinashgazula/Data-Structures
689149f6b05ce209dabe1c8445f56d8c3777828e
0aada83e7fe28bd01019290fb53773f725cdab9c
refs/heads/master
2020-03-25T06:48:20.168064
2018-08-04T13:47:37
2018-08-04T13:47:37
143,524,990
0
0
null
null
null
null
UTF-8
C++
false
false
1,181
cpp
printing a tree in reverse order.cpp
#include<iostream> using namespace std; struct stack{ int size; int top; int elements[50]; }; typedef struct bstnode{ int data; struct bstnode *lchild; struct bstnode *rchild; }* bstptr; void push(struct stack &s,int data) { if(s.top==s.size-1) { cout<<"Stack is full\n"; } else { s.top++; s.elements[s.top]=data; } } int pop(struct stack &s) { if(s.top==-1) { cout<<"Stack is empty\n"; } else return s.elements[s.top--]; } void insert(bstptr &h,int k) { if(h==NULL) { h=new bstnode; h->data=k; h->lchild=NULL; h->rchild=NULL; } else { if(k<h->data) { insert(h->lchild,k); } if(k>h->data) { insert(h->rchild,k); } } } void print(bstptr h,stack s) { if(h==NULL) { return; } else { push(s,h->data); print(h->lchild,s); print(h->rchild,s); } } int main(){ bstptr h; h=NULL; struct stack s; cout<<"Enter data or -1 to quit\n"; int n;int i=0; cin>>n; while(n!=-1) { insert(h,n); cout<<"Enter data or -1 to quit\n"; cin>>n; i++; } print(h,s); for(int j=0;j<i;j++) pop(s); }
7d38af7b5fb122bbbabd654af5c17e2424f4f59b
5b27c5a740e76c5c77c876b0ac2e009abe8cb120
/include/dframework/monitor/MonBase.h
944136a8a57d2ccfd3915dc01440f2590b0a3e44
[]
no_license
dframework/cpp-common
5a31ee667fa53a2e27c4ea362a4273889a860cb1
745d52e848db5261c9c3b2974999d085baffd1b2
refs/heads/master
2021-01-17T20:36:01.823663
2020-10-22T11:31:16
2020-10-22T11:31:16
59,715,298
1
0
null
null
null
null
UTF-8
C++
false
false
2,453
h
MonBase.h
#ifndef DFRAMEWORK_MONITOR_MONBASE_H #define DFRAMEWORK_MONITOR_MONBASE_H #include <dframework/base/Retval.h> #include <dframework/util/Array.h> #include <dframework/util/ArraySorted.h> #include <dframework/io/File.h> namespace dframework { class Monitor; class MonBase : public Object { public: static const char* SUBDIR; public: class info : public Object { private: int m_plus_count; public: uint64_t m_sec; sp<MonBase> m_last; sp<MonBase> m_total; ArraySorted<MonBase> m_aLists; public: info(); virtual ~info(); DFW_OPERATOR_EX_DECLARATION(info, m_sec); friend class Monitor; }; class group : public Object { public: sp<MonBase> m_base; Array<info> m_infos; public: group(); virtual ~group(); }; public: uint64_t m_sec; public: MonBase(uint64_t sec); virtual ~MonBase(); virtual sp<MonBase> create(uint64_t sec) = 0; virtual const char* source_path() = 0; virtual const char* savename() = 0; virtual const char* rawname() = 0; virtual sp<Retval> readData() = 0; virtual sp<MonBase> depth(int no, uint64_t sec , sp<MonBase>& old) = 0; virtual void plus(sp<MonBase>& old) = 0; virtual void avg(int count) = 0; virtual sp<Retval> draw(int num, sp<info>&, sp<MonBase>& , const char* path) = 0; virtual sp<MonBase> createBlank(uint64_t sec, sp<MonBase>& old)=0; virtual bool getRawString(String& out, sp<MonBase>& base); virtual sp<Retval> loadData(sp<MonBase>& out, String&); virtual sp<Retval> loadRawData(unsigned, sp<info>& , String&, int max_rows); virtual sp<Retval> saveRawData(int num, sp<info>&, sp<MonBase>& , const char* path); virtual sp<Retval> openTempFile(sp<File>& out , String& tempfile, String& orgFile , const char* path, const char* subdir , uint64_t subnm, const char* ext); virtual sp<Retval> replaceTempFile(String& sTemp, String& sOrg); DFW_OPERATOR_EX_DECLARATION(MonBase, m_sec); }; }; #endif /* DFRAMEWORK_MONITOR_MONBASE_H */
d557de267b4168d800c2ce0b4c99f5e50fbbec31
4986ae1665b0ab0eac85e13f6a883fa786bbe580
/data/heap.cc
33ff13ab6a8401d8351bf6117bb26599dec3f4f9
[]
no_license
finallyjustice/sample
ffcbfca8adf1bdd129baa8f819b53321e74d17f6
36ae225a82640951b74be85e1e9d42a213845fbd
refs/heads/master
2023-03-09T08:44:37.049755
2023-02-27T16:38:06
2023-02-27T16:38:06
14,458,335
4
1
null
null
null
null
UTF-8
C++
false
false
2,755
cc
heap.cc
#include <iostream> #include <cstdlib> using namespace std; template <typename T> class MaxHeap { private: T *data; int size; int capacity; private: int parent(int i); int left(int i); int right(int i); void max_heapify(int i); public: MaxHeap(int cap); void build_max_heap(T *a, int n); void insert(T val); T pop(); void print(); void print_layer(); void heapsort(T *a, int n); }; template <typename T> int MaxHeap<T>::parent(int i) { return (i+1)/2-1; } template <typename T> int MaxHeap<T>::left(int i) { return i*2+1; } template <typename T> int MaxHeap<T>::right(int i) { return i*2+2; } template <typename T> void MaxHeap<T>::max_heapify(int i) { if(size == 0) return; int largest; int lc = left(i); int rc = right(i); if(lc<size && data[i]<data[lc]) largest = lc; else largest = i; if(rc<size && data[largest]<data[rc]) largest = rc; if(largest != i) { int tmp = data[largest]; data[largest] = data[i]; data[i] = tmp; max_heapify(largest); } } template <typename T> MaxHeap<T>::MaxHeap(int cap) { size = 0; capacity = cap; data = (T *)malloc(sizeof(T)*capacity); } template <typename T> void MaxHeap<T>::build_max_heap(T *a, int n) { if(n > capacity) return; for(int i=0; i<n; i++) data[i] = a[i]; size = n; for(int i=n/2-1; i>=0; i--) max_heapify(i); } template <typename T> void MaxHeap<T>::insert(T val) { if(size >= capacity) { cout<<"Cannot insert the new value"<<endl; return; } int pos = size; data[pos] = val; while(pos>0 && data[pos]>data[parent(pos)]) { int tmp = data[pos]; data[pos] = data[parent(pos)]; data[parent(pos)] = tmp; pos = parent(pos); } size++; } template <typename T> T MaxHeap<T>::pop() { T ret = data[0]; data[0] = data[size-1]; size--; max_heapify(0); return ret; } template <typename T> void MaxHeap<T>::print() { for(int i=0; i<size; i++) cout<<data[i]<<" "; cout<<endl; } template <typename T> void MaxHeap<T>::print_layer() { int c = 0; int tot = 1; while(c < size) { for(int i=c; i<c+tot; i++) { if(i >= size) break; cout<<data[i]<<" "; } cout<<endl; c = c+tot; tot = tot*2; } } template <typename T> void MaxHeap<T>::heapsort(T *a, int n) { build_max_heap(a, n); for(int i=size-1; i>0; i--) { T tmp = data[0]; data[0] = data[i]; data[i] = tmp; size--; max_heapify(0); } size = n; } int main(int argc, char **argv) { MaxHeap<int> mh(100); /*mh.insert(16); mh.insert(14); mh.insert(10); mh.insert(8); mh.insert(7); mh.insert(9); mh.insert(3); mh.insert(2); mh.print(); mh.print_layer(); cout<<"# "<<mh.pop()<<endl; cout<<"# "<<mh.pop()<<endl;*/ int a[] = {5, 6, 3, 4, 1, 9, 7, 8, 2, 11}; mh.heapsort(a, 10); mh.print(); return 0; }
dc0ecb3f054457677f931d038e975e479c479894
973996e18022fc176ec68876bbceb5ae54aa9cac
/ICPC_Mirrors/Nitc_13.0/problems/problems/lengths/files/validate.cpp
968eda7517ea05e5cb99de00a0a73977ffb89624
[ "MIT" ]
permissive
Shahraaz/CP_P_S5
80bda6a39f197428bbe6952c6735fe9a17c01cb8
b068ad02d34338337e549d92a14e3b3d9e8df712
refs/heads/master
2021-08-16T11:09:59.341001
2021-06-22T05:14:10
2021-06-22T05:14:10
197,088,137
1
0
null
null
null
null
UTF-8
C++
false
false
223
cpp
validate.cpp
#include "testlib.h" using namespace std; int main(int argc, char** argv) { registerValidation(argc, argv); inf.readToken("[a-z]{1,200000}", "w"); inf.readEoln(); inf.readEof(); return 0; }
6f3196f19c7d2f3bf5bf4f97eca3ab3c18b50111
7e1e01498a2c9dc2c0c183463fd746ee73128e1f
/Battle City/Battle City/Block.cpp
3b6e42c0e84d8c4589690685fab6c5ccf5c54ef3
[]
no_license
parksch/SuChanPark
b91d3653eeb93fe81c6d1081bc48cb0af99658b6
fd214f322c6766add20bdd90c057b0d3f8662879
refs/heads/master
2023-04-27T20:38:57.667603
2021-05-17T02:18:24
2021-05-17T02:18:24
265,213,869
0
0
null
null
null
null
UTF-8
C++
false
false
9,025
cpp
Block.cpp
#include "Block.h" #include "GameScene.h" Block::Block() { } Block::~Block() { delete m_Block; } void Block::Init(int width, int height, int startX, int startY) { m_Block = NULL; m_BlockSize.cx = (width *0.8f) / 13.0f; m_BlockSize.cy = height / 13.0f; m_Pos.x = m_BlockSize.cx * startX; m_Pos.y = m_BlockSize.cy * startY; } void Block::BlockSet(int code) { string name; m_BlockCode = code; if (m_BlockCode < 10) { name = "block0" + to_string(code) + ".bmp"; } else if (m_BlockCode < 15) { name = "block" + to_string(code) + ".bmp"; } if (m_BlockCode < 15) { if (m_Block != NULL) { delete m_Block; } m_Block = new Animation(); m_Block->Push(ResourceManager::GetInstance()->GetBitmap(name)); } CollisionBoxSet(code); } void Block::Draw(HDC hdc) { if (m_BlockCode < 15) { m_Block->Draw(hdc, m_Pos.x, m_Pos.y, m_ImageSize, &m_DrawBox); DrawFocusRect(hdc, &m_CollisionBox); } } string Block::CollisionCheck(RECT *rect, string tag, int code) { if (IntersectRect(&RECT(), rect, &m_CollisionBox)) { if (tag == "Spawn") { return "Block"; } if (m_BlockCode == 5) { return "IceBlock"; } else if (m_BlockCode == 6) { return "Non"; } else if (m_BlockCode == 7) { if (tag == "Tank") { return "Block"; } } else if (m_BlockCode == 0 || m_BlockCode == 1 || m_BlockCode == 2 || m_BlockCode == 3 || m_BlockCode == 4) { if (tag == "PlayerProjectile" || tag == "EnemyProjectile") { switch ((MOVE_STATE)code) { case UP: if (m_BlockCode == 0 || m_BlockCode == 2 || m_BlockCode == 4) { m_ImageSize.cy = m_ImageSize.cy - m_BlockSize.cy / 4; m_CollisionBox.bottom = m_CollisionBox.bottom - m_BlockSize.cy / 4; m_DrawBox.bottom = m_DrawBox.bottom - m_Block->GetSize().cy / 4; } if (m_BlockCode == 1) { m_CollisionBox.bottom = m_CollisionBox.bottom - m_BlockSize.cy / 4; m_ImageSize.cy = m_CollisionBox.bottom - m_CollisionBox.top; m_DrawBox.bottom = m_DrawBox.bottom - m_Block->GetSize().cy * 0.75f; } if (m_BlockCode == 3) { m_ImageSize.cy = m_ImageSize.cy - m_BlockSize.cy / 4; m_CollisionBox.bottom = m_CollisionBox.bottom - m_BlockSize.cy / 4; m_DrawBox.bottom = m_DrawBox.bottom - m_Block->GetSize().cy / 4; if (m_ImageSize.cy < m_BlockSize.cy * 0.55f) { m_ImageSize.cy = 0; m_CollisionBox.bottom = 0; m_DrawBox.bottom = 0; } } if (m_ImageSize.cy < m_BlockSize.cy * 0.1f) { m_ImageSize.cy = 0; m_CollisionBox.bottom = 0; m_DrawBox.bottom = 0; } break; case DOWN: if (m_BlockCode == 0 || m_BlockCode == 2 || m_BlockCode == 4) { m_Pos.y = m_Pos.y + m_BlockSize.cy * 0.25f; m_ImageSize.cy = m_ImageSize.cy - m_BlockSize.cy / 4; m_CollisionBox.top = m_CollisionBox.top + m_BlockSize.cy / 4; m_DrawBox.top = m_DrawBox.top + m_Block->GetSize().cy / 4; m_DrawBox.bottom = m_DrawBox.bottom - m_Block->GetSize().cy / 4; } if (m_BlockCode == 1) { m_Pos.y = m_Pos.y + m_BlockSize.cy * 0.25f; m_CollisionBox.top = m_CollisionBox.top + m_BlockSize.cy / 4; m_ImageSize.cy = m_ImageSize.cy - m_BlockSize.cy / 4; m_DrawBox.top = m_DrawBox.top + m_Block->GetSize().cy / 4; m_DrawBox.bottom = m_DrawBox.bottom - m_Block->GetSize().cy / 4; if (m_ImageSize.cy < m_BlockSize.cy * 0.55f) { m_ImageSize.cy = 0; m_CollisionBox.bottom = 0; m_DrawBox.bottom = 0; } } if (m_BlockCode == 3) { m_Pos.y = m_Pos.y + m_BlockSize.cy * 0.75f; m_CollisionBox.top = m_CollisionBox.top + m_BlockSize.cy / 4; m_ImageSize.cy = m_ImageSize.cy - m_BlockSize.cy *0.75f; m_DrawBox.top = m_DrawBox.top + m_Block->GetSize().cy * 0.75f; m_DrawBox.bottom = m_DrawBox.bottom - m_Block->GetSize().cy *0.75f; } if (m_ImageSize.cy < m_BlockSize.cy * 0.1f) { m_ImageSize.cy = 0; m_CollisionBox.bottom = 0; m_DrawBox.bottom = 0; } break; case LEFT: if (m_BlockCode == 0 || m_BlockCode == 1 || m_BlockCode == 3) { m_CollisionBox.right = m_CollisionBox.right - m_BlockSize.cx * 0.25f; m_ImageSize.cx = m_ImageSize.cx - m_BlockSize.cx * 0.25f; m_DrawBox.right = m_DrawBox.right - m_Block->GetSize().cx * 0.25f; } if (m_BlockCode == 2) { m_CollisionBox.right = m_CollisionBox.right - m_BlockSize.cx * 0.25f; m_ImageSize.cx = m_ImageSize.cx - m_BlockSize.cx * 0.75f; m_DrawBox.right = m_DrawBox.right - m_Block->GetSize().cx * 0.75f; } if (m_BlockCode == 4) { m_CollisionBox.right = m_CollisionBox.right - m_BlockSize.cx * 0.25f; m_ImageSize.cx = m_ImageSize.cx - m_BlockSize.cx * 0.25f; m_DrawBox.right = m_DrawBox.right - m_Block->GetSize().cx * 0.25f; if (m_ImageSize.cx < m_BlockSize.cx * 0.55f) { m_ImageSize.cx = 0; m_CollisionBox.bottom = 0; m_DrawBox.bottom = 0; } } if (m_ImageSize.cx < m_BlockSize.cx * 0.2f) { m_ImageSize.cx = 0; m_CollisionBox.bottom = 0; m_DrawBox.bottom = 0; } break; case RIGHT: if (m_BlockCode == 0 || m_BlockCode == 1 || m_BlockCode == 3) { m_Pos.x = m_Pos.x + m_BlockSize.cx *0.25f; m_CollisionBox.left = m_CollisionBox.left + m_BlockSize.cx * 0.25f; m_ImageSize.cx = m_ImageSize.cx - m_BlockSize.cx * 0.25f; m_DrawBox.left = m_DrawBox.left + m_Block->GetSize().cx * 0.25f; m_DrawBox.right = m_DrawBox.right - m_Block->GetSize().cx * 0.25f; } if (m_BlockCode == 2) { m_Pos.x = m_Pos.x + m_BlockSize.cx *0.25f; m_CollisionBox.left = m_CollisionBox.left + m_BlockSize.cx * 0.25f; m_ImageSize.cx = m_ImageSize.cx - m_BlockSize.cx * 0.25f; m_DrawBox.left = m_DrawBox.left + m_Block->GetSize().cx * 0.25f; m_DrawBox.right = m_DrawBox.right - m_Block->GetSize().cx * 0.25f; if (m_ImageSize.cx < m_BlockSize.cx * 0.55f) { m_ImageSize.cx = 0; m_CollisionBox.bottom = 0; m_DrawBox.bottom = 0; } } if (m_BlockCode == 4) { m_Pos.x = m_Pos.x + m_BlockSize.cx *0.75f; m_CollisionBox.left = m_CollisionBox.left + m_BlockSize.cx * 0.25f; m_ImageSize.cx = m_ImageSize.cx - m_BlockSize.cx * 0.75f; m_DrawBox.left = m_DrawBox.left + m_Block->GetSize().cx * 0.75f; m_DrawBox.right = m_DrawBox.right - m_Block->GetSize().cx * 0.75f; } if (m_ImageSize.cx < m_BlockSize.cx * 0.2f) { m_ImageSize.cx = 0; m_CollisionBox.bottom = 0; m_DrawBox.bottom = 0; } break; default: break; } return "Block"; } else if (tag == "Tank") { return "Block"; } } else if (m_BlockCode == 8 || m_BlockCode == 9 || m_BlockCode == 10 || m_BlockCode == 11 || m_BlockCode == 12) { return "Block"; } else if (m_BlockCode == 13) { if (tag == "PlayerProjectile" || tag == "EnemyProjectile") { delete m_Block; m_Block = new Animation(); m_Block->Push(ResourceManager::GetInstance()->GetBitmap("block14.bmp"), m_BlockSize.cx, m_BlockSize.cy); GameScene *scene = (GameScene*)(SceneManager::GetInstance()->getCurScene()); scene->ChangeScore(FLAG); return "Block"; } else if (tag == "Tank") { return "Block"; } } } return "Non"; } void Block::CollisionBoxSet(int code) { m_CollisionBox.left = 0; m_CollisionBox.top = 0; m_CollisionBox.right = 0; m_CollisionBox.bottom = 0; m_ImageSize.cx = m_BlockSize.cx; m_ImageSize.cy = m_BlockSize.cy; if (code < 15) { m_DrawBox.left = 0; m_DrawBox.top = 0; m_DrawBox.right = m_Block->GetSize().cx; m_DrawBox.bottom = m_Block->GetSize().cy; } if (code == 0 || code == 5 || code == 7 || code == 8 || code == 13) { m_CollisionBox.left = m_Pos.x; m_CollisionBox.top = m_Pos.y; m_CollisionBox.right = m_Pos.x + m_BlockSize.cx; m_CollisionBox.bottom = m_Pos.y + m_BlockSize.cy; } else if (code == 1 || code == 9) { m_CollisionBox.left = m_Pos.x; m_CollisionBox.top = m_Pos.y; m_CollisionBox.right = m_Pos.x + m_ImageSize.cx; m_CollisionBox.bottom = m_Pos.y + m_ImageSize.cy / 2; } else if (code == 2 || code == 10) { m_CollisionBox.left = m_Pos.x; m_CollisionBox.top = m_Pos.y; m_CollisionBox.right = m_Pos.x + m_ImageSize.cx / 2; m_CollisionBox.bottom = m_Pos.y + m_ImageSize.cy; } else if (code == 3 || code == 11) { m_CollisionBox.left = m_Pos.x; m_CollisionBox.top = m_Pos.y + m_ImageSize.cy / 2; m_CollisionBox.right = m_Pos.x + m_ImageSize.cx; m_CollisionBox.bottom = m_Pos.y + m_ImageSize.cy; } else if (code == 4 || code == 12) { m_CollisionBox.left = m_Pos.x + m_ImageSize.cx / 2; m_CollisionBox.top = m_Pos.y; m_CollisionBox.right = m_Pos.x + m_ImageSize.cx; m_CollisionBox.bottom = m_Pos.y + m_ImageSize.cy; } CollisionManager::GetInstance()->RegisterObject(this); }
371a99d2a278284f7547de46e338418d27cd1cf0
b7b2ab4cc78f0fa7c012dbc4c2cff81636b0345a
/src/Menu/Button.cpp
e66250a05d3aa30fb23db5c42cc18ba86014f021
[]
no_license
Reterer/Ping-pong
550844fd79d9f1bf38b680809ff03aa34d40aa8d
6db2b07f131bdc6f6344babee8d7d6875880d410
refs/heads/master
2020-06-22T04:24:59.407225
2019-07-18T17:47:20
2019-07-18T17:47:20
197,632,272
0
0
null
null
null
null
UTF-8
C++
false
false
885
cpp
Button.cpp
#include "Button.h" Button::Button() { } void Button::init(int x, int y, int size_x, int size_y, sf::String str, sf::Font& font) { this->x = x; this->y = y; this->size_x = size_x; this->size_y = size_y; shape.setPosition(sf::Vector2f(x,y)); shape.setSize(sf::Vector2f(size_x,size_y)); shape.setFillColor(COLOR_MIDLE); text.setPosition(sf::Vector2f(x+10,y+15)); text.setCharacterSize(size_y/2); text.setFont(font); text.setString(str); } Button::~Button() { } void Button::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); target.draw(shape, states); target.draw(text, states); } bool Button::isMovedOn(sf::Vector2i mouse_position) { return x <= mouse_position.x && x+size_x >= mouse_position.x && y <= mouse_position.y && y+size_y >= mouse_position.y; }
58638dc4de1fd1cb26ddd7b3e6bb7ef7be943291
90f012884b86fa418bc68ab393eff629a17d3fc8
/src/abbros/src/qnode.cpp
9964b3f35344d8ff0cb5ac3109e96fbac7c8a16a
[]
no_license
RazThePsycho/ABB_IRB140_PACKAGES_ROS
6d4a21148a2454204b481f058d564ff9d0317563
39e1233a1fd32a92e955ef4ba898f469eaa3b72d
refs/heads/master
2023-03-16T07:06:00.024265
2017-03-14T20:06:23
2017-03-14T20:06:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,398
cpp
qnode.cpp
/** * @file /src/qnode.cpp * * @brief Ros communication central! * * @date February 2011 **/ /***************************************************************************** ** Includes *****************************************************************************/ #include <ros/ros.h> #include <ros/network.h> #include <string> #include <std_msgs/String.h> #include <sstream> #include "../include/abbros/qnode.hpp" #include "../include/abbros/main_window.hpp" #include <sensor_msgs/JointState.h> #include <tf/transform_broadcaster.h> #include "glob.h" /***************************************************************************** ** Namespaces *****************************************************************************/ namespace abbros { /***************************************************************************** ** Implementation *****************************************************************************/ QNode::QNode(int argc, char** argv ) : init_argc(argc), init_argv(argv) {} QNode::~QNode() { if(ros::isStarted()) { ros::shutdown(); // explicitly needed since we use ros::start(); ros::waitForShutdown(); } wait(); } bool QNode::init() { ros::init(init_argc,init_argv,"abbros"); if ( ! ros::master::check() ) { return false; } ros::start(); // explicitly needed since our nodehandle is going out of scope. ros::NodeHandle n; // QFile file("irb140.urdf"); XmlRpc::XmlRpcValue file ="irb140.urdf"; // Add your ros communications here. joint_pub = n.advertise<sensor_msgs::JointState>("joint_states", 1); n.setParam("robot_description", file); //broadcaster = n.advertise<geometry_msgs::Transform>("tf", 1); //extern tf::TransformBroadcaster broadcaster; //tf::TransformBroadcaster broadcaster; start(); return true; } bool QNode::init(const std::string &master_url, const std::string &host_url) { std::map<std::string,std::string> remappings; remappings["__master"] = master_url; remappings["__hostname"] = host_url; ros::init(remappings,"abbros"); if ( ! ros::master::check() ) { return false; } ros::start(); // explicitly needed since our nodehandle is going out of scope. ros::NodeHandle n; // Add your ros communications here. //chatter_publisher = n.advertise<std_msgs::String>("chatter", 1000); start(); return true; } void QNode::run() { ros::Rate loop_rate(10); //int count = 0; if(bandera == 1){ bandera = 0; } tf::TransformBroadcaster broadcaster; while ( ros::ok() ) { //std_msgs::String msg; //std::stringstream ss; //ss << count; //msg.data = ss.str(); //envío datos de articulaciónes joint_pub.publish(joint_state); double th1 = joint_state.position[0]; double th2 = joint_state.position[1]; double th3 = joint_state.position[2]; double th4 = joint_state.position[3]; double th5 = joint_state.position[4]; double th6 = joint_state.position[5]; /* //envío datos transformada de articulación joint_1 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, 0.0, 0.0, 1.0), tf::Vector3(0.0, 0.0, 0.0)), ros::Time::now(),"base", "base_link")); //envío datos transformada de articulación joint_1 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, 0.0, th1+(M_PI/2), 1.0), tf::Vector3(0.0, 0.0, 0.0)), ros::Time::now(),"base_link", "link_1")); //envío datos transformada de articulación joint_2 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(th2, 0.0, 0.0, 1.0), tf::Vector3(0.0, -0.273, 0.9)), ros::Time::now(),"link_1", "link_2")); //envío datos transformada de articulación joint_3 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(th3, 0.0, 0.0, 1.0), tf::Vector3(0.0, 0.0, 1.42)), ros::Time::now(),"link_2", "link_3")); //envío datos transformada de articulación joint_4 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, th4, 0.0, 1.0), tf::Vector3(0.0, -0.9, 0.0)), ros::Time::now(),"link_3", "link_4")); //envío datos transformada de articulación joint_5 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(th5, 0.0, 0.0, 1.0), tf::Vector3(0.0, -0.6, 0.0)), ros::Time::now(),"link_4", "link_5")); //envío datos transformada de articulación joint_6 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, th6, 0.0, 1.0), tf::Vector3(0.0, -0.2, 0.0)), ros::Time::now(),"link_5", "link_6")); //envío datos transformada de articulación base_link-base broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, 0.0, 0.0, 1.0), tf::Vector3(0.0, 0.0, 0.0)), ros::Time::now(),"base_link", "base")); //envío datos transformada de articulación link_6-tool broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, 0.0, 0.0, 1.0), tf::Vector3(0.0, 0.0, 0.0)), ros::Time::now(),"link_6", "tool0")); */ double factor = 0.9; //envío datos transformada de articulación joint_1 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, 0.0, 0.0, 1.0), tf::Vector3(0.0, 0.0, 0.0)), ros::Time::now(),"base", "base_link")); //envío datos transformada de articulación joint_1 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, 0.0, th1, 1.0), tf::Vector3(0.0, 0.0, 0.0)), ros::Time::now(),"base_link", "link_1")); //envío datos transformada de articulación joint_2 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, th2, 0.0, 1.0), tf::Vector3(0.273, 0.0, 1.42)), ros::Time::now(),"link_1", "link_2")); //envío datos transformada de articulación joint_3 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, th3, 0.0, 1.0), tf::Vector3(0.0, 0.0, 1.42)), ros::Time::now(),"link_2", "link_3")); //envío datos transformada de articulación joint_4 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(th4, 0.0, 0.0, 1.0), tf::Vector3(0.9, 0.0, 0.0)), ros::Time::now(),"link_3", "link_4")); //envío datos transformada de articulación joint_5 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, th5, 0.0, 1.0), tf::Vector3(0.6, 0.0, 0.0)), ros::Time::now(),"link_4", "link_5")); //envío datos transformada de articulación joint_6 broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(th6, 0.0, 0.0, 1.0), tf::Vector3(0.25, 0.0, 0.0)), ros::Time::now(),"link_5", "link_6")); //envío datos transformada de articulación base_link-base broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, 0.0, 0.0, 1.0), tf::Vector3(0.0, 0.0, 0.0)), ros::Time::now(),"base_link", "base")); //envío datos transformada de articulación link_6-tool broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.0, 0.0, 0.0, 1.0), tf::Vector3(0.0, 0.0, 0.0)), ros::Time::now(),"link_6", "tool0")); log(Info,std::string("Dato Enviado: ")); /* if(flag1 == 1) { joint_pub.publish(joint_state); // flag1 = 0; } */ ros::spinOnce(); loop_rate.sleep(); //++count; } std::cout << "Ros shutdown, proceeding to close the gui." << std::endl; Q_EMIT rosShutdown(); // used to signal the gui for a shutdown (useful to roslaunch) } void QNode::setvalue(QVector<double> i) { double factor = 0.65; joint_state.name.resize(6); joint_state.name[0] = "joint_1"; joint_state.name[1] = "joint_2"; joint_state.name[2] = "joint_3"; joint_state.name[3] = "joint_4"; joint_state.name[4] = "joint_5"; joint_state.name[5] = "joint_6"; joint_state.position.resize(6); joint_state.position[0] = i[0]*factor; joint_state.position[1] = i[1]*factor; joint_state.position[2] = i[2]*factor; joint_state.position[3] = i[3]*factor; joint_state.position[4] = i[4]*factor; joint_state.position[5] = i[5]*factor; joint_state.velocity.resize(6); joint_state.velocity[0] = 0.0; joint_state.velocity[1] = 0.0; joint_state.velocity[2] = 0.0; joint_state.velocity[3] = 0.0; joint_state.velocity[4] = 0.0; joint_state.velocity[5] = 0.0; joint_state.effort.resize(6); joint_state.effort[0] = 0.0; joint_state.effort[1] = 0.0; joint_state.effort[2] = 0.0; joint_state.effort[3] = 0.0; joint_state.effort[4] = 0.0; joint_state.effort[5] = 0.0; } void QNode::settf(int i, QVector<double> valores) { if(i == 1) { joint_1.resize(7); joint_1[0] = valores[0]; joint_1[1] = valores[1]; joint_1[2] = valores[2]; joint_1[3] = valores[3]; joint_1[4] = valores[4]; joint_1[5] = valores[5]; joint_1[6] = valores[6]; }else if(i == 2) { joint_2.resize(7); joint_2[0] = valores[0]; joint_2[1] = valores[1]; joint_2[2] = valores[2]; joint_2[3] = valores[3]; joint_2[4] = valores[4]; joint_2[5] = valores[5]; joint_2[6] = valores[6]; }else if(i == 3) { joint_3.resize(7); joint_3[0] = valores[0]; joint_3[1] = valores[1]; joint_3[2] = valores[2]; joint_3[3] = valores[3]; joint_3[4] = valores[4]; joint_3[5] = valores[5]; joint_3[6] = valores[6]; }else if(i == 4) { joint_4.resize(7); joint_4[0] = valores[0]; joint_4[1] = valores[1]; joint_4[2] = valores[2]; joint_4[3] = valores[3]; joint_4[4] = valores[4]; joint_4[5] = valores[5]; joint_4[6] = valores[6]; }else if(i == 5) { joint_5.resize(7); joint_5[0] = valores[0]; joint_5[1] = valores[1]; joint_5[2] = valores[2]; joint_5[3] = valores[3]; joint_5[4] = valores[4]; joint_5[5] = valores[5]; joint_5[6] = valores[6]; }else if(i == 6) { joint_6.resize(7); joint_6[0] = valores[0]; joint_6[1] = valores[1]; joint_6[2] = valores[2]; joint_6[3] = valores[3]; joint_6[4] = valores[4]; joint_6[5] = valores[5]; joint_6[6] = valores[6]; }else if(i == 7) { joint_6_tool0.resize(7); joint_6_tool0[0] = valores[0]; joint_6_tool0[1] = valores[1]; joint_6_tool0[2] = valores[2]; joint_6_tool0[3] = valores[3]; joint_6_tool0[4] = valores[4]; joint_6_tool0[5] = valores[5]; joint_6_tool0[6] = valores[6]; }else if(i == 8) { base_link_base.resize(7); base_link_base[0] = valores[0]; base_link_base[1] = valores[1]; base_link_base[2] = valores[2]; base_link_base[3] = valores[3]; base_link_base[4] = valores[4]; base_link_base[5] = valores[5]; base_link_base[6] = valores[6]; } } int QNode::getflag() { return flag1; } void QNode::setflag(int i) { flag1 = i; } void QNode::log( const LogLevel &level, const std::string &msg) { logging_model.insertRows(logging_model.rowCount(),1); std::stringstream logging_model_msg; switch ( level ) { case(Debug) : { ROS_DEBUG_STREAM(msg); logging_model_msg << "[DEBUG] [" << ros::Time::now() << "]: " << msg; break; } case(Info) : { ROS_INFO_STREAM(msg); //logging_model_msg << "[INFO] [" << ros::Time::now() << "]: " << msg; logging_model_msg << "[INFO] " << msg; break; } case(Warn) : { ROS_WARN_STREAM(msg); logging_model_msg << "[WARN] [" << ros::Time::now() << "]: " << msg; break; } case(Error) : { ROS_ERROR_STREAM(msg); logging_model_msg << "[ERROR] [" << ros::Time::now() << "]: " << msg; break; } case(Fatal) : { ROS_FATAL_STREAM(msg); logging_model_msg << "[FATAL] [" << ros::Time::now() << "]: " << msg; break; } } QVariant new_row(QString(logging_model_msg.str().c_str())); logging_model.setData(logging_model.index(logging_model.rowCount()-1),new_row); Q_EMIT loggingUpdated(); // used to readjust the scrollbar } } // namespace abbros
3f5ead27bc6826ff2cc350ff020530edc701d8c7
5b4e7bacdc6373fe7167bdbc3d98d1cc7e9f6c0d
/raytracer/Plane.h
73ac5f81680e0efa81defb4b470a05c9e81dec94
[]
no_license
AliShug/Raytracer
78989d4ba2db5d8361074515100c1d85d1001848
d61fe8ee57a5697d432e0e5f7502983d20135c0b
refs/heads/master
2020-12-25T13:08:03.444916
2015-05-22T23:40:10
2015-05-22T23:40:10
32,888,496
0
0
null
null
null
null
UTF-8
C++
false
false
234
h
Plane.h
#pragma once #include "SceneObj.h" class Plane : public SceneObj { public: Plane(glm::vec3 point = { 0, -0.8f, 0 }, glm::vec3 normal = { 0, 1, 0 }); ~Plane(); HitInfo Intersect(const Ray &ray); protected: glm::vec3 _p, _n; };
fd27ad64e84f1b244d9bce321d702eace5f0a302
18a4f8bd035da2a92dae23b06dbffba90c31354b
/drivers/laser/laser.hpp
218d6dd4cb378be1d364a0a2f301ef6cf1e3a63b
[ "MIT" ]
permissive
ArchiGithub/zynq-sdk
9d98247cfe758e3f5168e5973002ae98487c1497
9c95d033e4bde824c399478ac85b9ec9374f87bc
refs/heads/master
2021-01-23T23:35:11.390955
2016-06-23T21:14:55
2016-06-23T21:14:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,048
hpp
laser.hpp
/// Laser development kit driver /// /// (c) Koheron #ifndef __DRIVERS_LASER_HPP__ #define __DRIVERS_LASER_HPP__ #include <tuple> #include <drivers/lib/dev_mem.hpp> #include <drivers/addresses.hpp> #include <drivers/xadc/xadc.hpp> #include <drivers/gpio/gpio.hpp> #include <drivers/eeprom/eeprom.hpp> #include <thread> #include <chrono> // XADC channels #define LASER_POWER_CHANNEL 1 #define LASER_CURRENT_CHANNEL 8 # define LASER_ENABLE_PIN 5 // Laser enable on pin DIO7_P #define MAX_LASER_CURRENT 50.0 // mA #define GAIN_LT1789 (1+200/10) #define PWM_MAX_VOLTAGE 1.8 #define PWM_MAX_VALUE 1024 #define MILLIAMPS_TO_AMPS 0.001 constexpr float current_to_pwm = MILLIAMPS_TO_AMPS * PWM_MAX_VALUE * GAIN_LT1789 / PWM_MAX_VOLTAGE; constexpr float pwm_to_current = 1 / current_to_pwm; #define EEPROM_CURRENT_ADDR 0 #define TEST_EEPROM_ADDR 63 class Laser { public: Laser(Klib::DevMem& dvm_) : dvm(dvm_) , xadc(dvm_) , gpio(dvm_) , eeprom(dvm_) { config_map = dvm.AddMemoryMap(CONFIG_ADDR, CONFIG_RANGE); reset(); } ~Laser() {if (dvm.is_ok()) reset();} int Open() {return dvm.is_ok() ? 0 : -1;} void reset(); uint32_t get_laser_current() {return xadc.read(LASER_CURRENT_CHANNEL);} uint32_t get_laser_power() {return xadc.read(LASER_POWER_CHANNEL);} // TODO replace get_monitoring() with get_status() std::tuple<uint32_t, uint32_t> get_monitoring() { return std::make_tuple(get_laser_current(), get_laser_power()); } std::tuple<bool, float, float> get_status() { float current = (0.0001/21.) * float(get_laser_current()); float power = float(get_laser_power()); return std::make_tuple(laser_on, current, power); } void start_laser() {gpio.clear_bit(LASER_ENABLE_PIN, 2); laser_on = true;} void stop_laser() {gpio.set_bit(LASER_ENABLE_PIN, 2); laser_on = false;} void set_laser_current(float current); uint32_t pwm_from_current(float current) {return uint32_t(current * current_to_pwm);} float current_from_pwm(uint32_t pwm) {return pwm * pwm_to_current;} bool is_laser_present() { eeprom.write_enable(); std::this_thread::sleep_for(std::chrono::milliseconds(2)); eeprom.write(TEST_EEPROM_ADDR, 42); std::this_thread::sleep_for(std::chrono::milliseconds(2)); return eeprom.read(TEST_EEPROM_ADDR) == 42; } void save_config() { uint32_t current = dvm.read32(config_map, PWM3_OFF); eeprom.write(EEPROM_CURRENT_ADDR, current); } float load_config() { uint32_t pwm = eeprom.read(EEPROM_CURRENT_ADDR); dvm.write32(config_map, PWM3_OFF, pwm); return MILLIAMPS_TO_AMPS * current_from_pwm(pwm); } #pragma tcp-server is_failed bool IsFailed() const {return dvm.IsFailed();} private: Klib::DevMem& dvm; Klib::MemMapID config_map; // required for pwm Xadc xadc; Gpio gpio; Eeprom eeprom; bool laser_on; }; #endif // __DRIVERS_LASER_HPP__
31ce47cbacfb20463850beb60797f03137339506
7b20d9bc63db11417847977cd2bdd3866f5128b7
/Labwork4/Source.cpp
0085efd2b4a9bc4359f7effa342b8c26c1106bf7
[]
no_license
Evasionn/CENG351
e9c517dbd01c081d25ada698c6b2c1bab0684f58
67934f6575710324a66e56a552b4af451008d071
refs/heads/master
2021-01-22T03:01:37.204521
2016-12-25T22:16:08
2016-12-25T22:16:08
72,097,595
0
0
null
2016-10-27T19:47:36
2016-10-27T10:29:03
C++
UTF-8
C++
false
false
5,382
cpp
Source.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #define indexFile "index.txt" //Index file format is (INDEX ID) #define studentFile "student.txt" //Student file format is (INDEX ID NAME) typedef struct s { int ID; char name[32]; }Student; typedef struct { Student * list; int size; }StudentList; void checkTheFile(FILE *); StudentList createList(); Student createStudent(int, char *); void getList(StudentList *); void addStudent(StudentList * sList); int isExist(StudentList, int); void addToList(StudentList *, Student); void addToFile(StudentList); void copyTheList(StudentList*, StudentList*); void fillIndexList(int[], StudentList *); void updateIndexFile(StudentList*); void quickSort(StudentList *, int, int, int[]); int menu(); void searchStudent(StudentList *); int findIndex(int); int main() { StudentList sList = createList(); getList(&sList); int selection = -1; while(selection!=3) { selection = menu(); switch (selection) { case 1: addStudent(&sList); break; case 2: searchStudent(&sList); break; } } return 0; } void checkTheFile(FILE * theFile) { if (theFile == NULL) { printf("An error has been occured."); exit(0); } } int menu() { int selection; puts("1.) Add a new student"); puts("2.) Search a student by student ID"); puts("3.) Exit"); while (scanf("%d", &selection) != 1) { puts("1.) Add a new student"); puts("2.) Search a student by student ID"); puts("3.) Exit"); while (getchar() != '\n'); } return selection; } StudentList createList() { StudentList sList; sList.list = (Student *)malloc(sizeof(Student)); sList.size = 0; return sList; } Student createStudent(int ID, char* name) { Student newStudent; newStudent.ID = ID; strcpy(newStudent.name, name); return newStudent; } void getList(StudentList * sList) { FILE * theFile = fopen(studentFile, "r"); checkTheFile(theFile); Student tempStudent; int index; while (fscanf(theFile, "%d %d %s", &index, &tempStudent.ID, tempStudent.name) != EOF) { addToList(sList, tempStudent); } fclose(theFile); } int isExist(StudentList sList, int ID) { for (int i = 0; i < sList.size; i++) { if (sList.list[i].ID == ID) return 1; } return 0; } void addToList(StudentList * sList, Student newStudent) { sList->list = (Student *)realloc(sList->list, sizeof(Student)*(sList->size + 1)); sList->list[sList->size] = newStudent; sList->size++; } void addToFile(StudentList sList) { FILE * theFile = fopen(studentFile, "a+"); checkTheFile(theFile); fprintf(theFile, "%d %d %s\n", sList.size - 1, sList.list[sList.size - 1].ID, sList.list[sList.size - 1].name); fclose(theFile); } void copyTheList(StudentList* original, StudentList* copied) { Student temp; for (int i = 0; i < original->size; i++) { temp = original->list[i]; addToList(copied, temp); } } void fillIndexList(int arr[], StudentList * indexList) { FILE * theFile = fopen(studentFile, "r"); checkTheFile(theFile); int index; Student temp; for (int i = 0; i < indexList->size; i++) { fscanf(theFile, "%d %d %s", &index, &temp.ID, temp.name); arr[i] = index; } fclose(theFile); } void updateIndexFile(StudentList* indexList) { int * iList = (int*)malloc(sizeof(int)*indexList->size); fillIndexList(iList, indexList); quickSort(indexList, 0, indexList->size - 1, iList); FILE * theFile = fopen(indexFile, "w"); checkTheFile(theFile); for (int i = 0; i < indexList->size; i++) { fprintf(theFile, "%d %d\n", iList[i], indexList->list[i].ID); } fclose(theFile); free(iList); } void quickSort(StudentList *arr, int left, int right, int indexList[]) { int i = left; int j = right; int pivot = arr->list[(left + right) / 2].ID; Student temp; int tempIndex; while (i <= j) { while (arr->list[i].ID < pivot) i++; while (arr->list[j].ID > pivot) j--; if (i <= j) { temp = arr->list[i]; arr->list[i] = arr->list[j]; arr->list[j] = temp; tempIndex = indexList[i]; indexList[i] = indexList[j]; indexList[j] = tempIndex; i++; j--; } } if (left < j) quickSort(arr, left, j, indexList); if (i < right) quickSort(arr, i, right, indexList); } void addStudent(StudentList * sList) { int ID; char name[32]; printf("Enter Student ID: "); while (scanf("%d", &ID) != 1) { printf("Enter Student ID: "); while (getchar() != '\n'); } if (isExist(*sList, ID)) { puts("This student ID is already exist"); return; } printf("Enter Student Name: "); scanf("%s", name); Student newStudent; newStudent = createStudent(ID, name); addToList(sList, newStudent); addToFile(*sList); StudentList indexList = createList(); copyTheList(sList, &indexList); updateIndexFile(&indexList); free(indexList.list); } int findIndex(int ID) { int tempIndex; int tempID; int result = -1; FILE * theFile = fopen(indexFile, "r"); checkTheFile(theFile); while (fscanf(theFile, "%d %d", &tempIndex, &tempID) != EOF) { if (tempID == ID) result = tempIndex; } fclose(theFile); return result; } void searchStudent(StudentList * sList) { int ID; int index; printf("Enter a Student ID: "); while (scanf("%d", &ID) != 1) { printf("Enter a Student ID: "); while (getchar() != '\n'); } index = findIndex(ID); if (index == -1) puts("The student couldn't be found."); else printf("Student ID: %d\nStudent Name: %s\n", sList->list[index].ID, sList->list[index].name); }
9ec68c5dc7a7536695cbea4a15314a84bf7c944b
8f4faf47d46d87991329d6499a3eb9e2688301b7
/Sorting/Shellsort/main.cpp
556c005b92770c1fb2db20687c1638b086a8a8f7
[]
no_license
kirisanm/CppCollection
e65799b22bec40c971893b2add904a517d0e550d
baee9f2e70703eceb85180aeafeac1fc9296ffb5
refs/heads/master
2020-03-11T08:18:37.948341
2018-05-24T19:37:51
2018-05-24T19:37:51
129,880,512
2
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
main.cpp
// Coded & Developed by Kirisan Manivannan #include <iostream> void shell_sort(int[], int); void insertion_sort(int[], int, int); int main{ const int length = 100; int array[length]; shell_sort(array, length); char ch; cin >> ch; // Keep window open(); return 0; } void shell_sort(int arr[], int len){ int gap = len / 2; while(gap > 0){ insertion_sort(arr, len, gap); gap = gap / 2; } } void insertion_sort(int arr[], int len, int gap) { for (int i = gap; i < len; i++) { int j = i; while (j >= gap && arr[j] < arr[j - gap]) { swap(arr[j], arr[j - gap]); j= j-gap; } } }
b3a173820c25d4334e0b964ec528157e3bb8bd79
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5669245564223488_1/C++/urusant/main.cpp
e5ce77e9c683bcf4e52445165e958992c679b394
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
3,404
cpp
main.cpp
#include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <ctime> #include <cstdlib> #include <cstring> #include <string> #include <queue> #include <deque> #include <stack> #include <set> #include <map> #include <iterator> #include <cstdio> #include <list> using namespace std; #define rs resize #define sz(a) (int)(a).size() #define mp make_pair #define pb push_back #define ms(a, x) memset((a), (x), sizeof(a)) #define ass assign #define inf (int)1e9 #define pi 3.1415926535 #define reverse(a) reverse((a).begin(),(a).end()) #define sort(a) sort((a).begin(),(a).end()) #define sf scanf #define pf printf typedef long long ll; typedef vector <int> vi; typedef vector <vi> vvi; typedef vector <vvi> vvvi; typedef vector <vvvi> vvvvi; typedef vector <ll> vl; typedef vector <vl> vvl; typedef vector <vvl> vvvl; typedef pair <int, int> ii; typedef vector <ii> vii; typedef vector <vii> vvii; typedef set <int> si; typedef queue <int> qi; typedef vector <string> vs; typedef vector <bool> vb; typedef unsigned long long ull; typedef vector <vb> vvb; const ll M = 1e9 + 7; ll f(ll x) { if (x <= 1) return 1; return (f(x - 1) * x) % M; } void solve() { int n; cin >> n; vs a(n); for (int i = 0; i < n; ++i) cin >> a[i]; vi type(n); for (int i = 0; i < n; ++i) for (int j = 0; j < sz(a[i]); ++j) if (a[i][j] != a[i][0]) type[i] = 1; for (int i = 0; i < n; ++i) { if (type[i] == 0) continue; for (int j = 0; j < sz(a[i]); ++j) if (a[i][j] != a[i][0] && a[i][j] != a[i].back()) type[i] = 2; } bool u[26]; ms(u, 0); for (int i = 0; i < n; ++i) for (int j = 0; j < sz(a[i]); ++j) { if (a[i][j] != a[i][0] && a[i][j] != a[i].back()) { if (u[a[i][j] - 'a']) { cout << 0 << endl; return ; } else { char x = a[i][j]; u[x - 'a'] = 1; while (a[i][j] == x) j++; j--; } } } for (int i = 0; i < n; ++i) if (u[a[i][0] - 'a'] || u[a[i].back() - 'a']) { cout << 0 << endl; return ; } vs b(n, ""); for (int i = 0; i < n; ++i) if (type[i] == 0) b[i] += a[i][0]; else { b[i] += a[i][0]; b[i] += a[i].back(); } vvi g(26), g1(26); int c[26]; ms(c, 0); for (int i = 0; i < n; ++i) if (sz(b[i]) == 1) c[b[i][0] - 'a']++; else { g[b[i][0] - 'a'].pb(b[i][1] - 'a'); g1[b[i][1] - 'a'].pb(b[i][0] - 'a'); } ms(u, 0); ll ans = 0; for (int i = 0; i < 26; ++i) { if (sz(g1[i]) != 0) continue; int x = i, l = 1; u[x] = 1; while (1) { if (sz(g[x]) == 0) break; if (sz(g[x]) > 1 || u[g[x][0]]) { cout << 0 << endl; return ; } x = g[x][0]; u[x] = 1; l++; } ans++; } for (int i = 0; i < 26; ++i) if (!u[i] && (sz(g[i]) != 0 || sz(g1[i]) != 0)) { cout << 0 << endl; return ; } for (int i = 0; i < 26; ++i) if (c[i] == 0 && sz(g[i]) == 0 && sz(g1[i]) == 0) ans--; ans = f(ans); for (int i = 0; i < 26; ++i) ans = (ans * f(c[i])) % M; cout << ans << endl; return ; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t; cin >> t; for (int i = 0; i < t; ++i) { cout << "Case #" << i + 1 << ": "; solve(); } }
26b4dd2ff06ed7341ebae232dcc1f4e48a86ca32
4732e8b09bfef920f834ae4be32af1210278eee8
/2017 Data Structure/Project5/priorityQueue.cpp
c21ad615c4bda586b3a09f92a240f0b5c2a64947
[]
no_license
Justin1095/2017-Data-Structure
466a91383eb8f0fdeb82908ab18a337ae155f381
80ad8ad3720b86622822b486a3d9fd6d6da76676
refs/heads/master
2021-05-13T14:28:32.246914
2018-01-08T23:47:48
2018-01-08T23:47:48
116,741,616
0
0
null
null
null
null
UTF-8
C++
false
false
2,618
cpp
priorityQueue.cpp
//Justin Seda //CPSC 250 10am //jseda1@live.esu.edu //30 April 2017 //This program is a heap implementation of a priority queue ADT. //priorityQueue.cpp #include"priorityQueue.h" #include<iostream> #include<iomanip> using namespace std; //Constructor - Initializes size to NULL and data to new int[CAPACITY]. priorityQueue::priorityQueue() { data = new int[CAPACITY]; size = NULL; } //Destructor - deletes the data. priorityQueue::~priorityQueue() { delete data; } //getParent- finds the index of a node's parent node. int priorityQueue::getParent(int index) { return (index - 1) / 2; } //getLeftChild- finds the index of node's left child. int priorityQueue::getLeftChild(int index) { return (2 * index) + 1; } //getRightChild- finds the index of a node's right child. int priorityQueue::getRightChild(int index) { return (2 * index) + 2; } //swap- exchanges 2 given values. void priorityQueue::swap(int& item, int& item2) { int temp; temp = item; item = item2; item2 = temp; } //heapify - maintains the heap property. void priorityQueue::heapify(int index) { int min; int left = getLeftChild(index); int right = getRightChild(index); if (left < size && data[left] < data[index]) { min = left; } else { min = index; } if (right < size && data[right] < data[min]) { min = right; } if (min != index) { swap(data[index], data[min]); heapify(min); } } //printArray- displays the priority queue. void priorityQueue::printArray(int data[]) { for (int i = 0; i < size; i++) { cout << data[i] << ", "; } } //insert- inserts items into the priority queue. void priorityQueue::insert(int item) { size++; int index = size - 1; while (index > 0 && data[getParent(index)] > item) { data[index] = data[getParent(index)]; index = getParent(index); } data[index] = item; cout << endl << "After inserting " << item << " the Priority Queue is:" << endl; printArray(data); cout << endl; } //extractMin- removes the smallest value in the priority queue. int priorityQueue::extractMin() { int min = data[0]; data[0] = data[size - 1]; size--; heapify(0); cout << endl << "After extracting the minimum value Priority Queue has" << endl; printArray(data); cout << endl; return min; } //empty- checks if the size is empty. bool priorityQueue::empty() const { return size == NULL; } //min- finds the smallest value in the priority queue. int priorityQueue::min() const { return data[0]; }
585355ddcb9749796f44649ea358f994946fc51e
682dfc3e2ae0b49eafc52b7f9a079562e8bac7cf
/class/Division.cpp
ba2842e63ce9e826c7a6fbf8c0461ba2aa40f14a
[]
no_license
Snowdigit/Championnat
9adb87cd123a501f6fa909733608c18ec9301fcb
4e36cf7e197b801a837ed6e2d249fa3ad82a2a3e
refs/heads/main
2023-06-15T22:11:55.848449
2021-07-15T06:17:18
2021-07-15T06:17:18
386,325,283
0
0
null
null
null
null
ISO-8859-1
C++
false
false
14,905
cpp
Division.cpp
#include "Division.h" // Pour créer une division void Division::CreationDivision(){ sqlite3* db; sqlite3_stmt* stmt; int rc = sqlite3_open("mydb.db", &db); char* err; system ("cls"); cout << "Entrer le numero pour choisir championnat "<<endl; sqlite3_prepare_v2(db, "select * from Championnats ", -1, &stmt, 0); int id; const unsigned char* pays; while(sqlite3_step(stmt) != SQLITE_DONE){ id = sqlite3_column_int(stmt,0); pays = sqlite3_column_text(stmt,1); cout<<id<<"-"<<pays<<endl; } std::cin >> Division::idchampionnat; string cham; stringstream division; division << Division::idchampionnat; division>>cham; cout << "Entrer la division (ex : ligue1) : " ; std::cin >> Division::libelle; string r1 = "insert into divisions (libelle,idchampionnat) VALUES ('"+Division::libelle+"','"+cham+"');"; rc = sqlite3_exec(db, r1.c_str(), NULL, NULL, &err); if (rc != SQLITE_OK){ std::cout << "Erreur d'insertion" << err; } } // pour modifier une division void Division::ModificationDivision() { system ("cls"); cout << "Entrer le numero de la division a Modifier "<<endl; sqlite3* db; sqlite3_stmt* stmt; int rc = sqlite3_open("mydb.db", &db); char* err; sqlite3_prepare_v2(db, "select divisions.id, divisions.libelle, championnats.pays from divisions, championnats where divisions.idchampionnat = championnats.id ", -1, &stmt, 0); int id; const unsigned char* libelle; const unsigned char* pays; while(sqlite3_step(stmt) != SQLITE_DONE){ id = sqlite3_column_int(stmt,0); libelle = sqlite3_column_text(stmt,1); pays = sqlite3_column_text(stmt,2); cout<<id<<" - "<<libelle<<" - "<<pays<<endl; } std::cin >> Division::iddivision; string cham; stringstream division; division << Division::iddivision; division>>cham; system("cls"); bool test = 1; int id_valeur; while(test) { system ("cls"); cout<<"Choisissez le champ a modifier :"<<endl; cout<< "1.Nom de la division"<<endl; cout<< "2.Le Championnat"<<endl; int val1; cin>>val1; if(val1== 1) { system ("cls"); cout<<"Entrez la nouveau libelle de la division : (ex : Ligue1)"<<endl; string val; cin>>val; string query = "update divisions set libelle = '"+val+"'where id ='"+cham+"';"; rc = sqlite3_exec(db, query.c_str(), NULL, NULL, &err); if (rc != SQLITE_OK){ std::cout << "Erreur de modification " << err; } // pour afficher les nouvelles divisions d'un championnat lorsqu'une division est modifiée else { system ("cls"); cout << "Felicitations, voici la nouvelle liste de divisions dans le championnat "<<endl; sqlite3* db; sqlite3_stmt* stmt; int rc = sqlite3_open("mydb.db", &db); char* err; string q2 = "select divisions.id, divisions.libelle, championnats.pays from divisions, championnats where divisions.idchampionnat = championnats.id AND divisions.idchampionnat = '"+cham+"';"; sqlite3_prepare_v2(db, q2.c_str(), -1, &stmt, 0); int id; const unsigned char* libelle; const unsigned char* pays; while(sqlite3_step(stmt) != SQLITE_DONE){ id = sqlite3_column_int(stmt,0); libelle = sqlite3_column_text(stmt,1); pays = sqlite3_column_text(stmt,2); cout<<id<<" - "<<libelle<<" - "<<pays<<endl; } // Fin } test = 0; } else if(val1==2) { system ("cls"); cout << "Entrer le numero du championnat correspondant "<<endl; sqlite3* db; sqlite3_stmt* stmt; int rc = sqlite3_open("mydb.db", &db); char* err; sqlite3_prepare_v2(db, "select * from championnats ", -1, &stmt, 0); int id; const unsigned char* pays; while(sqlite3_step(stmt) != SQLITE_DONE){ id = sqlite3_column_int(stmt,0); pays = sqlite3_column_text(stmt,1); cout<<id<<"-"<<pays<<endl; } std::cin >> Division::idchampionnat; string newid; stringstream division; division << Division::idchampionnat; division>>newid; string query = "update divisions set idchampionnat = '"+newid+"'where id ='"+cham+"';"; rc = sqlite3_exec(db, query.c_str(), NULL, NULL, &err); if (rc != SQLITE_OK){ std::cout << "Erreur de modification " << err; } test = 0; } } } // Pour supprimer une division void Division::SuppressionDivision() { system ("cls"); cout << "Entrer le numero de la division a supprimer "<<endl; sqlite3* db; sqlite3_stmt* stmt; int rc = sqlite3_open("mydb.db", &db); char* err; sqlite3_prepare_v2(db, "select * from divisions ", -1, &stmt, 0); int id; const unsigned char* libelle; while(sqlite3_step(stmt) != SQLITE_DONE){ id = sqlite3_column_int(stmt,0); libelle = sqlite3_column_text(stmt,1); cout<<id<<"-"<<libelle<<endl; } std::cin >> Division::iddivision; string cham; stringstream division; division << Division::iddivision; division>>cham; string query = "delete from divisions where id ='"+cham+"';"; rc = sqlite3_exec(db, query.c_str(), NULL, NULL, &err); if (rc != SQLITE_OK){ std::cout << "Erreur de suppression " << err; } } //***************************** Classement ****************************** void Division::Classement(){ //Affichage des championnats sqlite3* db; sqlite3_stmt* stmt; int rc = sqlite3_open("mydb.db", &db); char* err; system ("cls"); cout << "Entrer le numero correspondant au championnat "<<endl; sqlite3_prepare_v2(db, "select * from championnats ", -1, &stmt, 0); int id1; const unsigned char* pays; while(sqlite3_step(stmt) != SQLITE_DONE){ id1 = sqlite3_column_int(stmt,0); pays = sqlite3_column_text(stmt,1); cout<<id1<<"-"<<pays<<endl; } std::cin >> Division::idchampionnat; //Récupération de l'id du championnat string cham; stringstream divis; divis << Division::idchampionnat; divis>>cham; //Affichage des divisions liées au championnat choisi system ("cls"); cout << "Entrer le numero correspondant a la division "<<endl; string r3 ="select divisions.id, divisions.libelle, championnats.pays from divisions, championnats where divisions.idchampionnat = championnats.id AND divisions.idchampionnat = '"+cham+"';"; sqlite3_prepare_v2(db, r3.c_str(), -1, &stmt, 0); int id2; const unsigned char* libelle; while(sqlite3_step(stmt) != SQLITE_DONE){ id2 = sqlite3_column_int(stmt,0); libelle = sqlite3_column_text(stmt,1); cout<<id2<<"-"<<libelle<<endl; } std::cin >> Division::iddivision; // Récupération de l'id de la division string div; stringstream division; division << Division::iddivision; division>>div; //Affichage des saisons system ("cls"); cout << "Entrer le numero correspondant a la saison "<<endl; string r7 ="select * from saisons ;"; sqlite3_prepare_v2(db, r7.c_str(), -1, &stmt, 0); int id6; const unsigned char* libelle6; while(sqlite3_step(stmt) != SQLITE_DONE){ id6 = sqlite3_column_int(stmt,0); libelle6 = sqlite3_column_text(stmt,1); cout<<id6<<"-"<<libelle6<<endl; } std::cin >> Division::idsaison; // Récupération de l'id de la division string saisid; stringstream intervertion6; intervertion6 << Division::idsaison; intervertion6>>saisid; string req4 ="SELECT Eq.nom,Eq.point,Eq.Gdif from (SELECT Z.nom,sum(Z.point) as point,sum(Z.Gdif) as Gdif from (select E1.nom,sum(matchs.point_1) as point,sum(matchs.goaldiff1) as Gdif from matchs, equipes E1,divisions WHERE matchs.equipe_1 = E1.id and matchs.iddiv = divisions.id and divisions.id ='"+div+"' AND matchs.idsais = '"+saisid+"' GROUP by E1.nom UNION select E2.nom,sum(matchs.point_2) as point,sum(matchs.goaldiff2) as Gdif from matchs, equipes E2,divisions WHERE matchs.equipe_2 = E2.id and matchs.iddiv = divisions.id and divisions.id ='"+div+"' AND matchs.idsais = '"+saisid+"' GROUP by E2.nom) As Z GROUP by Z.nom) AS Eq ORDER by Eq.point DESC,Eq.Gdif DESC;"; sqlite3_prepare_v2(db,req4.c_str() , -1, &stmt, 0); int point; int gdif; int pos = 0; const unsigned char* nomeq; system ("cls"); std::cout << termcolor::red; std::cout <<"^^^^^^^^^^ Le Classement ^^^^^^^^^^\n" << std::endl; std::cout << termcolor::reset; cout<<"position ----"<<" Equipes "<<"---- points ----"<<"Ecart de buts"<<endl; std::cout << termcolor::yellow; while(sqlite3_step(stmt) != SQLITE_DONE){ nomeq = sqlite3_column_text(stmt,0); point = sqlite3_column_int(stmt,1); gdif = sqlite3_column_int(stmt,2); std::cout <<"\n________________________________________________________________\n" << std::endl; cout<<++pos<<" ---- "<<nomeq<<" ---- "<<point<<" ---- "<<gdif<<endl; } std::cout << termcolor::reset; } //****************************Calendrier***********************// void Division::Calendrier(){ //Affichage des championnats sqlite3* db; sqlite3_stmt* stmt; int rc = sqlite3_open("mydb.db", &db); char* err; system ("cls"); cout << "Entrer le numero correspondant au championnat "<<endl; sqlite3_prepare_v2(db, "select * from championnats ", -1, &stmt, 0); int id1; const unsigned char* pays; while(sqlite3_step(stmt) != SQLITE_DONE){ id1 = sqlite3_column_int(stmt,0); pays = sqlite3_column_text(stmt,1); cout<<id1<<"-"<<pays<<endl; } std::cin >> Division::idchampionnat; //Récupération de l'id du championnat string cham; stringstream divis; divis << Division::idchampionnat; divis>>cham; //Affichage des divisions liées au championnat choisi system ("cls"); cout << "Entrer le numero correspondant a la division "<<endl; string r3 ="select divisions.id, divisions.libelle, championnats.pays from divisions, championnats where divisions.idchampionnat = championnats.id AND divisions.idchampionnat = '"+cham+"';"; sqlite3_prepare_v2(db, r3.c_str(), -1, &stmt, 0); int id2; const unsigned char* libelle; while(sqlite3_step(stmt) != SQLITE_DONE){ id2 = sqlite3_column_int(stmt,0); libelle = sqlite3_column_text(stmt,1); cout<<id2<<"-"<<libelle<<endl; } std::cin >> Division::iddivision; // Récupération de l'id de la division string div; stringstream division; division << Division::iddivision; division>>div; //Affichage des saisons system ("cls"); cout << "Entrer le numero correspondant a la saison "<<endl; string r7 ="select * from saisons ;"; sqlite3_prepare_v2(db, r7.c_str(), -1, &stmt, 0); int id6; const unsigned char* libelle6; while(sqlite3_step(stmt) != SQLITE_DONE){ id6 = sqlite3_column_int(stmt,0); libelle6 = sqlite3_column_text(stmt,1); cout<<id6<<"-"<<libelle6<<endl; } std::cin >> Division::idsaison; // Récupération de l'id de la division string saisid; stringstream intervertion6; intervertion6 << Division::idsaison; intervertion6>>saisid; // Affichage du Calendrier system ("cls"); std::cout << termcolor::yellow; cout<< "**************** Le calendrier *****************"<<endl; string req2 = "select matchs.id, matchs.date, matchs.journee, equipes.nom, equipes.nom, matchs.point_1, matchs.point_2, matchs.score_1, matchs.score_2 from matchs, equipes, divisions, saisons where saisons.id = matchs.idsais AND saisons.id ='"+saisid+"' AND matchs.iddiv= '"+div+"' AND matchs.iddiv = divisions.id AND (matchs.equipe_1= equipes.id OR matchs.equipe_2= equipes.id ) AND matchs.point_1= 0 AND matchs.point_2=0 ; " ; sqlite3_prepare_v2(db,req2.c_str(), -1, &stmt, 0); int id; int jrnee; int pt1; int pt2; int sc1; int sc2; const unsigned char* date; const unsigned char* eq1; const unsigned char* eq2; int saut=1; while(sqlite3_step(stmt) != SQLITE_DONE){ id = sqlite3_column_int(stmt,0); date = sqlite3_column_text(stmt,1); jrnee = sqlite3_column_int(stmt,2); eq1 = sqlite3_column_text(stmt,3); eq2 = sqlite3_column_text(stmt,4); pt1 = sqlite3_column_int(stmt,5); pt2 = sqlite3_column_int(stmt,6); sc1 = sqlite3_column_int(stmt,7); sc2 = sqlite3_column_int(stmt,8); if(saut%2 !=0) { cout<<id<<" "<<date<<" - journee "<<jrnee<<" "<<eq1; saut++; } else { cout<<" "<<"-"<<" "<<eq2<<endl; saut++; } } std::cout << termcolor::reset; } // ************************AFFICHAGE DIVISIONS******************************* void Division::AffichageDivision(){ //Affichage des championnats sqlite3* db; sqlite3_stmt* stmt; int rc = sqlite3_open("mydb.db", &db); char* err; system ("cls"); cout << "Entrer le numero correspondant au championnat "<<endl; sqlite3_prepare_v2(db, "select * from Championnats ", -1, &stmt, 0); int id1; const unsigned char* pays; while(sqlite3_step(stmt) != SQLITE_DONE){ id1 = sqlite3_column_int(stmt,0); pays = sqlite3_column_text(stmt,1); cout<<id1<<"-"<<pays<<endl; } std::cin >> Division::idchampionnat; //Récupération de l'id du championnat string cham; stringstream divis; divis << Division::idchampionnat; divis>>cham; string r4 ="select championnats.pays from divisions, championnats where divisions.idchampionnat = championnats.id AND divisions.idchampionnat = '"+cham+"';"; sqlite3_prepare_v2(db, r4.c_str(), -1, &stmt, 0); const unsigned char* pays2; // Affichage de l'en-tête if(sqlite3_step(stmt) != SQLITE_DONE) { system ("cls"); pays2 = sqlite3_column_text(stmt,0); cout << "\n** ** ** ** **La liste des divisions du championnat de "<<pays2<<"** ** ** ** **\n"<<endl; } //Affichage des divisions liées au championnat choisi string r3 ="select divisions.id, divisions.libelle, championnats.pays from divisions, championnats where divisions.idchampionnat = championnats.id AND divisions.idchampionnat = '"+cham+"';"; sqlite3_prepare_v2(db, r3.c_str(), -1, &stmt, 0); int id2; const unsigned char* libelle; while(sqlite3_step(stmt) != SQLITE_DONE){ id2 = sqlite3_column_int(stmt,0); libelle = sqlite3_column_text(stmt,1); cout<<id2<<"-"<<libelle<<endl; } }
d41890c321d526dbbe65af0cd3d82859a817a0cd
955790a1f28accff52f890211fdc2f5e4e58b3e1
/SRC/experimentalSignalFilter/ESFErrorSimUndershoot.cpp
479083881db36622fc89fd29895b21d3b91b93fd
[]
no_license
yangxlhit/OpenFresco
5e18da3c5440c8573688ecb5590c6dafe5bd3afa
c94e549e6907bff6cc7aff6d85c2fbf5f5d4c2c3
refs/heads/master
2023-08-28T02:11:41.646849
2021-10-24T21:14:38
2021-10-24T21:14:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,128
cpp
ESFErrorSimUndershoot.cpp
/* ****************************************************************** ** ** OpenFRESCO - Open Framework ** ** for Experimental Setup and Control ** ** ** ** ** ** Copyright (c) 2006, Yoshikazu Takahashi, Kyoto University ** ** All rights reserved. ** ** ** ** Licensed under the modified BSD License (the "License"); ** ** you may not use this file except in compliance with the License. ** ** You may obtain a copy of the License in main directory. ** ** 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. ** ** ** ** Developed by: ** ** Yoshikazu Takahashi (yos@catfish.dpri.kyoto-u.ac.jp) ** ** Andreas Schellenberg (andreas.schellenberg@gmx.net) ** ** Gregory L. Fenves (fenves@berkeley.edu) ** ** ** ** ****************************************************************** */ // Written: Yoshi // Created: 09/06 // Revision: A // // Purpose: This file contains the implementation of // ESFErrorSimUndershoot. #include "ESFErrorSimUndershoot.h" #include <elementAPI.h> #include <math.h> void* OPF_ESFErrorSimUndershoot() { // pointer to experimental control that will be returned ExperimentalSignalFilter* theFilter = 0; if (OPS_GetNumRemainingInputArgs() < 2) { opserr << "WARNING invalid number of arguments\n"; opserr << "Want: expSignalFilter ErrorSimUndershoot tag error\n"; return 0; } // filter tag int tag; int numdata = 1; if (OPS_GetIntInput(&numdata, &tag) != 0) { opserr << "WARNING invalid expSignalFilter ErrorSimUndershoot tag\n"; return 0; } // undershoot error double error; numdata = 1; if (OPS_GetDoubleInput(&numdata, &error) != 0) { opserr << "WARNING invalid undershoot error\n"; opserr << "expSignalFilter ErrorSimUndershoot " << tag << endln; return 0; } // parsing was successful, allocate the signal filter theFilter = new ESFErrorSimUndershoot(tag, error); if (theFilter == 0) { opserr << "WARNING could not create experimental signal filter " << "of type ESFErrorSimUndershoot\n"; return 0; } return theFilter; } ESFErrorSimUndershoot::ESFErrorSimUndershoot(int tag, double error) : ESFErrorSimulation(tag), undershoot(error), data(0.0), predata(0.0) { // does nothing } ESFErrorSimUndershoot::ESFErrorSimUndershoot(const ESFErrorSimUndershoot& esf) : ESFErrorSimulation(esf) { undershoot = esf.undershoot; data = esf.data; predata = esf.predata; } ESFErrorSimUndershoot::~ESFErrorSimUndershoot() { // does nothing } double ESFErrorSimUndershoot::filtering(double d) { data = d; if (d > predata) data -= undershoot; else if (d < predata) data += undershoot; if (fabs(d) < 1.0e-6) data += undershoot; predata = d; return data; } void ESFErrorSimUndershoot::update() { // does nothing } ExperimentalSignalFilter* ESFErrorSimUndershoot::getCopy() { return new ESFErrorSimUndershoot(*this); } void ESFErrorSimUndershoot::Print(OPS_Stream &s, int flag) { s << "Filter: " << this->getTag(); s << " type: ESFErrorSimUndershoot\n"; s << " undershoot error: " << undershoot << endln; }
9fe4e74ee1c5fb3ad3cd4ed20921b07dff03f6be
635824211a4c1b94badcbd6d23d94bcfb765694e
/src/sched/ze/ze_event_manager.hpp
68d7352d643fff94118a3207ed6dc0ee0b60f264
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
oneapi-src/oneCCL
3c62402dd644495938c36a85f1866510f2e8c92b
b4c31ba6b42b5bcc7228820e44d2d3f3d519fdc7
refs/heads/master
2023-08-25T20:30:14.485614
2023-07-19T19:42:04
2023-07-19T19:42:04
207,412,282
125
45
NOASSERTION
2023-07-25T13:18:50
2019-09-09T21:57:46
C++
UTF-8
C++
false
false
5,203
hpp
ze_event_manager.hpp
/* Copyright 2016-2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <list> #include <unordered_map> #include "common/api_wrapper/ze_api_wrapper.hpp" #include "sched/entry/ze/ze_primitives.hpp" class ccl_stream; namespace ccl { namespace ze { class event_pool { public: event_pool(ze_context_handle_t context); event_pool(ze_context_handle_t context, const ze_event_pool_desc_t& pool_desc); event_pool(ze_context_handle_t context, const ze_event_pool_desc_t& pool_desc, const ze_event_desc_t& event_desc); event_pool(const event_pool&) = delete; event_pool(event_pool&&) = default; event_pool& operator=(const event_pool&) = delete; event_pool& operator=(event_pool&&) = delete; virtual ~event_pool(); operator ze_event_pool_handle_t() const; ze_event_handle_t create_event(); ze_event_handle_t create_event(ze_event_desc_t& desc); size_t size() const; size_t capacity() const; void reset(); void clear(); private: static constexpr size_t worker_idx{}; const ze_context_handle_t context; const ze_event_pool_desc_t pool_desc; const ze_event_desc_t event_desc; ze_event_pool_handle_t pool{}; std::list<ze_event_handle_t> events; void create_pool(); }; class event_manager { public: event_manager(ze_context_handle_t context); event_manager(const ccl_stream* stream); event_manager(const event_manager&) = delete; event_manager(event_manager&&) = default; event_manager& operator=(const event_manager&) = delete; event_manager& operator=(event_manager&&) = default; virtual ~event_manager(); ze_event_handle_t create(ze_event_desc_t desc = get_default_event_desc()); std::vector<ze_event_handle_t> create(size_t count, ze_event_desc_t desc = get_default_event_desc()); void reset(); void clear(); static ze_event_desc_t get_default_event_desc(); static ze_event_pool_desc_t get_default_event_pool_desc(); protected: static constexpr size_t default_pool_size{ 50 }; ze_context_handle_t context{}; std::list<event_pool> pools; event_pool* add_pool(ze_event_pool_desc_t desc = get_default_event_pool_desc(), ze_event_desc_t event_desc = get_default_event_desc()); }; // allows to dynamically allocate events by managing multiple event pools // the basic idea is to have a list of event pools(depending on the number // of requested events). For each pool we keep track of slots with allocated // events and slots without them. // note: this is relatively similar to event_manager class above, except it // allows to release events one by one, but with additional overhead of status // tracking. Potentially these 2 classes could be merged into one, but keep // them separate for now for different use-cases. class dynamic_event_pool { public: dynamic_event_pool(const ccl_stream* stream); ~dynamic_event_pool(); dynamic_event_pool(const dynamic_event_pool&) = delete; dynamic_event_pool(dynamic_event_pool&&) = delete; dynamic_event_pool& operator=(const dynamic_event_pool&) = delete; dynamic_event_pool& operator=(dynamic_event_pool&&) = delete; ze_event_handle_t get_event(); void put_event(ze_event_handle_t event); private: struct event_pool_info { ze_event_pool_handle_t pool; // number of allocated events from the pool size_t num_alloc_events; // vector of flags(true - slot is occupied, false - slot is free) std::vector<bool> event_alloc_status; }; struct event_info { // position of the event's pool in the list std::list<event_pool_info>::iterator pool; // index inside the pool, necessary to track free/non-free status size_t pool_idx; }; bool find_free_slot(event_info& slot); ze_event_handle_t create_event(const event_info& slot); // TODO: make some parameters configurable // TODO: check if another value would be better, as this one is chosen quite arbitrary static constexpr size_t event_pool_size{ 50 }; static ze_event_pool_desc_t get_default_event_pool_desc(); static const ze_event_pool_desc_t common_pool_desc; static constexpr size_t worker_idx{}; ze_context_handle_t context; std::mutex lock; // map to keep allocation information for each event so we can properly track // free/non-free slots std::unordered_map<ze_event_handle_t, event_info> event_alloc_info; // list of all allocated event pools std::list<event_pool_info> event_pools; }; } // namespace ze } // namespace ccl
fb32c1afd570b1e0a7cc7b9f1dd15567b7abc643
f3f2fb683ab1877eace58541e6d292f36e11abf1
/KruskalMST.cpp
929fa635a126ae45ca8c16ad25413466a331b720
[]
no_license
prakritidave/graph-implementation
27d11cfc5db1f522e3c0ff6a02c09813f8cb1811
92660d4b749a2b12b17dfb21c0f6716c0eed4a0a
refs/heads/master
2021-01-01T16:41:39.533385
2017-07-21T19:14:02
2017-07-21T19:14:02
97,890,990
2
0
null
null
null
null
UTF-8
C++
false
false
2,479
cpp
KruskalMST.cpp
// KruskalMST.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <vector> #include <algorithm> using namespace std; struct setUnion{ vector<int>parent; vector<int>size; int n; //number of elements in set; }; class kruskal{ setUnion *s; vector< pair<int, pair<int, int> > >edges; int nedges; int nvertices; public: kruskal(int v, int e){ nedges=e; nvertices=v; s=new setUnion(); setUnionInit(); } void setUnionInit(){ for(int i=0; i<=nvertices; i++){ s->parent.push_back(i); s->size.push_back(1); } s->n=nvertices; } void addEdges(){ cout<<"\n enter all edges "; int x,y,wt; for(int i=0; i<nedges; i++){ cout<<"\n enter source and destination "; cin>>x; cin>>y; cout<<"\n enter edge cost "; cin>>wt; edges.push_back(make_pair(wt, make_pair(x,y))); } } void sortEdges(){ sort(edges.begin(),edges.end()); } void printEdges(){ cout<<"\n print graph \n"; vector< pair<int, pair<int,int> > >::iterator outer; for(outer = edges.begin(); outer!=edges.end(); outer++){ int wt= outer->first; int x=outer->second.first; int y=outer->second.second; cout<<"from "<<x<<" to "<<y<<" weight "<<wt; cout<<endl; } } int find(int x){ if(s->parent[x] == x)return x; s->parent[x]=find(s->parent[x]); return s->parent[x]; } bool sameComponent(int u, int v){ return (find(v) == find(u)); } void union_sets(int u, int v){ int r1,r2; r1=find(u); r2=find(v); if(r1 == r2)return; if(s->size[r1] >= s->size[r2]){ s->parent[r2]=r1; s->size[r1] += s->size[r2]; } else{ s->parent[r1]=r2; s->size[r2] += s->size[r1]; } } void kruskalMST(){ int mstwt=0; vector< pair<int, pair<int, int>> >::iterator outer; int wt,x,y; sortEdges(); cout<<"\n minimal spanning tree \n"; for(outer=edges.begin(); outer!=edges.end(); outer++){ wt=outer->first; x=outer->second.first; y=outer->second.second; if(!sameComponent(x, y)){ cout<<x<<" - "<<y<<endl; union_sets(x,y); mstwt+=wt; } } cout<<"\n minimal spanning tree weight "<<mstwt<<" "; } }; int _tmain(int argc, _TCHAR* argv[]) { int v,e; cout<<"\n enter the number of vertices "; cin>>v; cout<<"\n enter the number of edges "; cin>>e; kruskal *k = new kruskal(v,e); k->addEdges(); k->printEdges(); k->kruskalMST(); return 0; }
609d3a88cea19add971f734cde2f116b7540a579
ab5acae36b1a040030abc4835813a05c550d8811
/Radium/MouseTest.cpp
a07d51c7528dc03249fdc4a7a0b088897bc6f481
[ "MIT" ]
permissive
GameLabStudios/radium
1f6bbce6e2cba6949339fe76fe657245cbf05fe7
2b0fe0e3dd20a5e8d66396b18659ddc33d369151
refs/heads/master
2020-04-04T14:33:47.732415
2015-03-28T09:14:39
2015-03-28T09:14:39
19,444,756
0
0
null
null
null
null
UTF-8
C++
false
false
1,408
cpp
MouseTest.cpp
#include "MouseTest.hpp" #include <iostream> #include <string> #define _USE_MATH_DEFINES #include <math.h> MouseTest::MouseTest() { circle = CircleShape(20, 30); circle.setOrigin(20.f, 20.f); playerSpeed = 200.0f; } void MouseTest::onDraw(RenderTarget& target, RenderStates states) const { target.draw(circle, states); } void MouseTest::onUpdate(Time dt) { //Vector2f mousePos = Game::getInstance().getWorld().getMousePosition(); //float angle = atan2(mousePos.y - getPosition().y, mousePos.x - getPosition().x); //setRotation(((angle * 180) / M_PI) - 45.f); //direction of movement Vector2f direction = Vector2f(0.0f, 0.0f); //input if (Keyboard::isKeyPressed(Keyboard::A)) { direction.x -= 1.0f; } if (Keyboard::isKeyPressed(Keyboard::D)) { direction.x += 1.0f; } if (Keyboard::isKeyPressed(Keyboard::S)) { direction.y += 1.0f; } if (Keyboard::isKeyPressed(Keyboard::W)) { direction.y -= 1.0f; } //normalize the direction if (direction.x != 0.0f) { direction.x = direction.x / sqrt((direction.x*direction.x) + (direction.y*direction.y)); } if (direction.y != 0.0f) { direction.y = direction.y / sqrt((direction.x*direction.x) + (direction.y*direction.y)); } //move the player move(direction * playerSpeed * dt.asSeconds()); }
f32f84696e05d2b60b727740d89a9f4ae4214eef
db2d2b3e36d9c9411a3983ca4ba38613ee8eabcf
/src/App/Controller/CommandReportWindShift.h
295ef0a86e4a7cc2a69c1a17672b09e0eb73f164
[]
no_license
jrezzende/Airport
598036658a6777a70bbaf9c368e51c11c2207912
67d08b3e58cbe786895619f87dd8f768226a5c8b
refs/heads/master
2021-09-05T16:42:53.946208
2018-01-29T18:03:45
2018-01-29T18:03:45
115,729,500
0
0
null
null
null
null
UTF-8
C++
false
false
349
h
CommandReportWindShift.h
#pragma once #ifndef INCLUDED_COMMANDREPORTWINDSHIFT_H #define INCLUDED_COMMANDREPORTWINDSHIFT_H #include "Command.h" class UserI; class CommandReportWindShift : public Command { public: CommandReportWindShift() = default; ~CommandReportWindShift() = default; void exec(UserI& ui) override; }; #endif //INCLUDED_COMMANDREPORTWINDSHIFT_H
d9a817da5f2f14c1954a0299875cdf2ee8c45657
7fa0466c095842523cd3d58d1152557a6ea49acf
/mainwindow.h
f03bae358447256864bb5a65e3dd91cd0e2f3cfa
[]
no_license
CMon/qtPorts
0e0dc690aa91ee2627ea085ad8d3d5b6e039aa54
c43974cbe767935ee497a9af5ffd0c6b31faae78
refs/heads/master
2021-01-19T18:53:40.094791
2012-07-15T15:14:39
2012-07-15T15:14:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
503
h
mainwindow.h
#pragma once #include <QMainWindow> #include <QSet> class QTreeWidgetItem; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_twCategories_currentItemChanged(QTreeWidgetItem * current, QTreeWidgetItem *); void showCleaningTasks(); private: void initCategories(); private: Ui::MainWindow * ui_; private: QSet<QString> categories_; };
48c63540ded2f5fffe0289156e0118ea0bebb4c4
671b2830778c1efe5d918a1ebe25a53c894cbfe6
/cpp/CmdLinePrinter.cpp
3d4c7abe0ebe8a54e4eea9d7a4bdba1271727f51
[ "MIT" ]
permissive
YukihoAA/Simple-Cake-Collections
1680c0e343bc55ac5c741b3b9e85462798f84a65
59857181415a6850c884735d2e65d70b17729b95
refs/heads/master
2022-09-12T01:08:24.675671
2022-08-21T08:34:39
2022-08-21T08:34:39
128,611,479
0
0
null
null
null
null
UTF-8
C++
false
false
577
cpp
CmdLinePrinter.cpp
// CmdLinePrinter.cpp - by Yuki (yukiho5048@naver.com) // #include <stdio.h> #include <Windows.h> int main(int argc, char* argv[]) { HWND hWnd = GetConsoleWindow(); if (hWnd == NULL || ShowWindow(hWnd, SW_SHOW) == 0) { char CmdLine[MAX_PATH] = ""; for (int i = 1; i < argc; i++){ strcat_s(CmdLine, argv[i]); strcat_s(CmdLine, " "); } ShellExecuteA(NULL, "open", argv[0], CmdLine, NULL, SW_SHOW); return 0; } printf("Argument Count: %d\n", argc); for (int i = 0; i < argc; i++) printf("argv[%d]: %s\n", i, argv[i]); system("pause"); return 0; }
34f4026202b38819cf730b96c517d4d67aa1b71c
f61c7e32650a10e3b697cf4e1a1ccbb4c2e2570d
/include/sympack/Ordering.hpp
458e2687ae975ca7f7d41d376295bc7bda19eae7
[ "BSD-3-Clause-LBNL" ]
permissive
symPACK/symPACK
1446d84671550bc28d4867611df1a2d8cc7e25b7
2137ee661c8eb4c6fae4cf692c702f48d7dd0962
refs/heads/master
2023-09-04T01:29:39.613180
2023-08-27T21:26:06
2023-08-27T21:26:06
73,348,141
14
3
NOASSERTION
2023-09-07T20:43:56
2016-11-10T04:50:05
C++
UTF-8
C++
false
false
1,753
hpp
Ordering.hpp
/****************************************************************************** AMD, Copyright (c), 1996-2015, Timothy A. Davis, Patrick R. Amestoy, and Iain S. Duff. All Rights Reserved. Used in symPACK under the BSD 3-clause license. ******************************************************************************/ #ifndef _ORDERING_HPP_ #define _ORDERING_HPP_ #include <stdlib.h> #include "sympack/Environment.hpp" #include "sympack/DistSparseMatrixGraph.hpp" namespace symPACK{ class SparseMatrixGraph; class DistSparseMatrixGraph; class Ordering; #if RCMIDXSIZE==64 typedef int64_t RCMInt; #else typedef int32_t RCMInt; #endif #if MMDIDXSIZE==64 typedef int64_t MMDInt; #else typedef int32_t MMDInt; #endif #if AMDIDXSIZE==64 typedef int64_t AMDInt; #else typedef int32_t AMDInt; #endif class Ordering{ public: std::vector<Int> perm; std::vector<Int> invp; int NpOrdering; Ordering():NpOrdering(0){}; void RCM(const SparseMatrixGraph & g, MPI_Comm comm); void MMD(const SparseMatrixGraph & g, MPI_Comm comm); void AMD(const SparseMatrixGraph & g, MPI_Comm comm); void NDBOX(Int size, MPI_Comm comm); void NDGRID(Int size, MPI_Comm comm); #ifdef USE_PARMETIS void PARMETIS(const DistSparseMatrixGraph & g); #endif #ifdef USE_PTSCOTCH void PTSCOTCH(const DistSparseMatrixGraph & g); #endif #ifdef USE_METIS void METIS(const SparseMatrixGraph & g, MPI_Comm comm); #endif #ifdef USE_SCOTCH void SCOTCH(const SparseMatrixGraph & g, MPI_Comm comm); #endif void GetRelativeInvp(const std::vector<Int> & frominvp, std::vector<Int> & relinvp); void Compose(std::vector<Int> & invp2); }; } #endif // _ORDERING_HPP_
06a5a503dc0a924be0505b5a098b9b29555a28a6
320f29dc945abd753ffdbfc4ebfe1108c81d1dd7
/Basic/12hours24hours.cpp
aed64ea892b1ea8b23faeed1ef92e99535f526de
[]
no_license
JayThakkar17/DataStructuresAndAlgorithms
a41f375aa9791fe59c4442b0b87be92f5117276d
32feb8e3c0b356503f10a63b7590fa745d9124da
refs/heads/master
2023-02-09T02:00:41.842014
2021-01-04T05:27:46
2021-01-04T05:27:46
315,225,118
2
0
null
null
null
null
UTF-8
C++
false
false
1,831
cpp
12hours24hours.cpp
#include<iostream> #include<string.h> #include <iomanip> using namespace std; int main() { int hours, minutes, seconds, h1, m1, s1; char median[10]; cout << "Enter hours, minutes, seconds:"; cin >> hours; cin >> minutes; cin >> seconds; cout << "Enter median:"; cin >> median; cout << "Time in 12 hour format:" << setfill('0') << setw(2) << hours << ":" << setfill('0') << setw(2) << minutes << ":" << setfill('0') << setw(2) << seconds << median << endl; //setw()=sets the field width, //setfill()=set character as the streams fill character. if (strcmp(median, "pm") == 0) { //compare the strings "0" is for true "1" is for false. if (hours < 12) { h1 = hours + 12; m1 = minutes; s1 = seconds; cout << "Time in 24 hour format:" << h1 << ":" << setfill('0') << setw(2) << m1 << ":" << setfill('0') << setw(2) << s1 << median; } else if (hours = 12) { h1 = 12; m1 = minutes; s1 = seconds; cout << "Time in 24 hour format:" << h1 << ":" << setfill('0') << setw(2) << m1 << ":" << setfill('0') << setw(2) << s1 << median; } } else if (strcmp(median, "am") == 0) { if (hours < 12) { h1 = hours; m1 = minutes; s1 = seconds; cout << "Time in 24 hour format:" << setfill('0') << setw(2) << h1 << ":" << setfill('0') << setw(2) << m1 << ":" << setfill('0') << setw(2) << s1 << median; } else if (hours = 12) { m1 = minutes; s1 = seconds; cout << "Time in 24 hour format:" << "00" << ":" << setfill('0') << setw(2) << m1 << ":" << setfill('0') << setw(2) << s1 << median; } } else { printf("Wrong choice"); } }
028d037dd59b162fffb981ee944b3ee86f0b889e
276c472235c963c01160275830fb68a68bc78eed
/CJOJ/CJ1478.cpp
106d10604b93472a68632ab1c06dd8cfe7f3e010
[]
no_license
MicDZ/Code
057f5ef39e6b296d3d38897f20a7fae1edf37fa9
6665d48c742fd6e80f87b5ef23c030ec7f60fd2f
refs/heads/master
2022-12-07T20:33:49.153077
2022-11-28T03:49:35
2022-11-28T03:49:35
218,696,992
3
0
null
null
null
null
UTF-8
C++
false
false
999
cpp
CJ1478.cpp
////////////////////////////////////////////// // Author: MicDZ // Email: me@micdz.cn // Last modified: 2019-07-31 18:03 // Filename: CJ1478.cpp ////////////////////////////////////////////// #include<bits/stdc++.h> using namespace std; #define REP(i,e,s) for(register int i=e; i<=s; i++) #define DREP(i,e,s) for(register int i=e; i>=s; i--) #define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout) int read() { int x=0,f=1,ch=getchar(); while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } const int MAXN=100+10; int a[MAXN][MAXN]; int main() { int n=read(),m=read(); memset(a,1,sizeof(a)); REP(i,1,m) { int u=read(),v=read(),w=read(); a[u][v]=a[v][u]=w; } REP(k,1,n) REP(i,1,n) REP(j,1,n) a[i][j]=min(a[i][j],a[i][k]+a[k][j]); int ans=0; REP(i,2,n) ans=max(ans,a[1][i]); if(ans>=a[0][0]) puts("-1"); else printf("%d\n",ans); return 0; }
3a5af57cc471e136ce785b97d2c9b8f0e349c476
6bf5f3857bc3d1cf945ea377e3280bcfbbf6c600
/includes/debug.hpp
7a0db8bb4806b7f5fdf1ff944435d8fe54b70a5a
[]
no_license
burner/pimp
7ec25a2efc017664653ea5b03eadf5ab879cac63
c415386064b621546fe4fcfc187a4f6a3b2eb828
refs/heads/master
2020-05-21T00:43:12.222136
2013-04-05T13:03:25
2013-04-05T13:03:25
3,632,148
1
0
null
2012-10-15T11:26:22
2012-03-05T22:34:00
C++
UTF-8
C++
false
false
1,542
hpp
debug.hpp
#ifndef DEBUG #define DEBUG #include <QDebug> #include <iostream> #include "format.hpp" static const QString prettyPrintFileLineInfo(const QString& file, int line) { auto tmp = QString("%1:%2").arg(file, QString::number(line)); return tmp; } static const QString stripFileName(const char* file) { QString str(file); int pos = str.lastIndexOf('/'); str.remove(0,pos+1); return str; } #ifndef RELEASE #define LOG Log(__FILE__,__LINE__) #define WARN Log(__FILE__,__LINE__,true) #else #define LOG() ; #define WARN() ; #endif #define debug() qDebug()<<prettyPrintFileLineInfo(stripFileName(__FILE__),__LINE__)<<"]" #define warning() qWarning()<<prettyPrintFileLineInfo(stripFileName(__FILE__),__LINE__)<<"]" #define critical() qCritical()<<prettyPrintFileLineInfo(stripFileName(__FILE__),__LINE__)<<"]" #define fatal() qFatal()<<prettyPrintFileLineInfo(stripFileName(__FILE__),__LINE__)<<"]" static std::string shortenString(const std::string& str) { size_t idx = str.rfind('/'); if(idx == std::string::npos) { return str; } else { return str.substr(idx+1); } } struct Log { public: Log(const char* f, int l, bool w = false) { if(w) { std::cerr<<"WARN "; } std::cerr<<shortenString(f)<<':'<<l<<' '; debug()<<QString::fromStdString(shortenString(f))<<':'<<l<<' '; } void operator()() { std::cerr<<std::endl; } template<typename... Args> void operator()(std::string form, Args... args) { auto tmp = format(form, args...); std::cerr<<tmp<<std::endl; debug()<<QString::fromStdString(tmp); } }; #endif
b1927481489bee41479391dc968d3f0aeee26cdb
3fef56efe52dd97c4942d8b8021d69c28b8b4e1e
/Problemset/977A - Wrong Subtraction.cpp
1879274bf0c7ca8606f38275c96790036acce49e
[]
no_license
naiyer-abbas/Code-Forces
384850c939b4243499ffd446092ff69a3e3ea8b0
aca143949efe1583cdc9c8f71cb0e21b5d14fa1e
refs/heads/master
2023-05-07T00:53:17.811357
2021-05-26T17:48:37
2021-05-26T17:48:37
327,666,421
3
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
977A - Wrong Subtraction.cpp
#include<bits/stdc++.h> using namespace std; int main() { int n, k; cin>>n>>k; for(int i = 0; i<k; i++) { if(n%10) n--; else { n = n / 10; } } cout<<n; }
8c18da4714c3d49fc056d479a80820e2a372a321
19a012b6a66374235771a8c2baee19560e98f8d7
/UVa/v120/potentiometers.cpp
523afb23106fa101b153a9e6e4881044c69ce1cc
[]
no_license
juancate/CompetitivePrograming
735e992fd6ac9c264059604fb7a2f2dfce74d330
8cea3695fd0dec7122c94ab45b4517cb13232fb3
refs/heads/master
2021-01-25T10:06:47.576470
2018-12-19T01:11:41
2018-12-19T01:11:41
14,966,965
0
0
null
null
null
null
UTF-8
C++
false
false
1,933
cpp
potentiometers.cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <cctype> #include <cassert> #include <iostream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <stack> #include <queue> #include <deque> #include <list> #include <set> #include <map> #include <bitset> #include <algorithm> #include <numeric> #include <complex> #define D(x) cerr << #x << " = " << (x) << endl; #define REP(i,a,n) for(int i=(a); i<(int)(n); i++) #define FOREACH(it,v) for(__typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it) #define ALL(v) (v).begin(), (v).end() using namespace std; typedef long long int64; const int INF = (int)(1e9); const int64 INFLL = (int64)(1e18); const double EPS = 1e-13; #define LSOne(S) (S & (-S)) typedef vector<int> vi; void ft_create(vi& t, int n) { t.assign(n+1, 0); } int ft_rsq(const vi& t, int b) { int sum = 0; for(; b; b -= LSOne(b)) sum += t[b]; return sum; } int ft_rsq(const vi& t, int a, int b) { return ft_rsq(t, b) - (a == 1? 0 : ft_rsq(t, a-1)); } void ft_adjust(vi& t, int k, int v) { for(; k <= (int)t.size(); k += LSOne(k)) t[k] += v; } char buffer[10010]; int main() { int n, case_id = 1; while(sscanf(gets(buffer), "%d", &n)) { if(n == 0) break; vi ft; ft_create(ft, n); for(int i = 1; i <= n; i++) { int x; sscanf(gets(buffer), "%d", &x); ft_adjust(ft, i, x - ft_rsq(ft, i, i)); } if(case_id > 1) puts(""); printf("Case %d:\n", case_id++); while(gets(buffer)) { if(buffer[0] == 'E') break; char op; int i, j; sscanf(buffer, "%c%d%d", &op, &i, &j); if(op == 'S') ft_adjust(ft, i, j - ft_rsq(ft, i, i)); else { printf("%d\n", ft_rsq(ft, i, j)); } } } }
4027ed336efb85830cbef7e61568ad2219ce7014
8597e881cf20cf5f822f5b5a7c74d7862506cc50
/iss_sgp4_teme.cpp
46662e264d090e74d70ffb29e94b15e355572fb3
[ "MIT" ]
permissive
komasaru/iss_sgp4_teme
e7ea1cb894fb41fdae726282914fc028bd7ae54b
5474ab1acdc5076e12d90c1dcd2d259e36fbd18d
refs/heads/main
2023-05-30T23:30:31.473863
2021-06-13T01:33:32
2021-06-13T01:33:32
376,413,592
1
0
null
null
null
null
UTF-8
C++
false
false
3,356
cpp
iss_sgp4_teme.cpp
/*********************************************************** TLE から ISS の位置・速度を計算 : 但し、座標系は TEME(True Equator, Mean Equinox; 真赤道面平均春分点) : 指定 JST における BLH 座標の計算は iss_sgp4_blh DATE AUTHOR VERSION 2021.05.13 mk-mode.com 1.00 新規作成 Copyright(C) 2021 mk-mode.com All Rights Reserved. 引数 : UT1(世界時1) 書式:最大23桁の数字 (先頭から、西暦年(4), 月(2), 日(2), 時(2), 分(2), 秒(2), 1秒未満(9)(小数点以下9桁(ナノ秒)まで)) 無指定なら現在(システム日時)と判断。 ***********************************************************/ #include "sgp4.hpp" #include "time.hpp" #include "tle.hpp" #include <cstdlib> // for EXIT_XXXX #include <ctime> #include <iomanip> #include <iostream> #include <string> #include <vector> int main(int argc, char* argv[]) { namespace ns = iss_sgp4_teme; std::string tm_str; // time string unsigned int s_tm; // size of time string int s_nsec; // size of nsec string int ret; // return of functions struct tm t = {}; // for work struct timespec ut1; // UT1 std::vector<std::string> tle; // TLE ns::Satellite sat; // 衛星情報 ns::PvTeme teme; // 位置・速度 try { // 現在日時(UT1) 取得 if (argc > 1) { // コマンドライン引数より取得 tm_str = argv[1]; s_tm = tm_str.size(); if (s_tm > 23) { std::cout << "[ERROR] Over 23-digits!" << std::endl; return EXIT_FAILURE; } s_nsec = s_tm - 14; std::istringstream is(tm_str); is >> std::get_time(&t, "%Y%m%d%H%M%S"); ut1.tv_sec = mktime(&t); ut1.tv_nsec = 0; if (s_tm > 14) { ut1.tv_nsec = std::stod( tm_str.substr(14, s_nsec) + std::string(9 - s_nsec, '0')); } } else { // 現在日時の取得 ret = std::timespec_get(&ut1, TIME_UTC); if (ret != 1) { std::cout << "[ERROR] Could not get now time!" << std::endl; return EXIT_FAILURE; } } // TLE 読み込み, gravconst 取得 ns::Tle o_t(ut1); tle = o_t.get_tle(); // ISS 初期位置・速度の取得 ns::Sgp4 o_s(ut1, tle); sat = o_s.twoline2rv(); // 指定 UT1 の ISS 位置・速度の取得 teme = o_s.propagate(sat); // Calculation & display std::cout << "[" << ns::gen_time_str(ut1) << " UT1]" << std::endl; std::cout << "TLE:" << tle[0] << std::endl; std::cout << " " << tle[1] << std::endl; std::cout << std::fixed << std::setprecision(8); std::cout << "TEME POS:[" << std::setw(16) << teme.r.x << ", " << std::setw(16) << teme.r.y << ", " << std::setw(16) << teme.r.z << "]" << std::endl; std::cout << " VEL:[" << std::setw(16) << teme.v.x << ", " << std::setw(16) << teme.v.y << ", " << std::setw(16) << teme.v.z << "]" << std::endl; } catch (...) { std::cerr << "EXCEPTION!" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
93d03fe7a4dab98ecffac7cff5ba6e5f403f8b14
bc5acb0441096513b649c71c1fc582e32e889a32
/nsfwgl/Window.cpp
9a5b91751654169f88d86e0fcdeb48b8fd5408c1
[]
no_license
Aidonis/octo-capsicum
41d8bd062fb42db5f39d5f0b44d638034106b4fe
b492177a9002e867261329df071e3b8f6c7dda95
refs/heads/master
2021-01-13T00:45:44.696978
2015-12-11T21:21:53
2015-12-11T21:21:53
43,904,764
0
1
null
2015-11-07T01:10:31
2015-10-08T17:13:03
C
UTF-8
C++
false
false
2,659
cpp
Window.cpp
#include "nsfw.h" void APIENTRY oglErrorDefaultCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { // if 'GL_DEBUG_OUTPUT_SYNCHRONOUS' is enabled, you can place a // breakpoint here and the callstack should reflect the problem location! std::cerr << message << std::endl; } void nsfw::Window::init(unsigned width, unsigned height) { if (glfwInit() == false) { return; } glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true); window = glfwCreateWindow(width, height, "nsfwGL", nullptr, nullptr); this->width = width; this->height = height; if (window == nullptr) { glfwTerminate(); } glfwMakeContextCurrent(window); if (ogl_LoadFunctions() == ogl_LOAD_FAILED) { glfwDestroyWindow(window); glfwTerminate(); return; } #ifdef _DEBUG if (glDebugMessageCallback) { glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(oglErrorDefaultCallback, nullptr); GLuint unusedIDs = 0; glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, &unusedIDs, true); } else { std::cerr << "Failed to subscribe to glDebugMessageCallback." << std::endl; } #endif //TODO_D("Should create and set an active windowing context. ONLY GLFW! No GL!"); } void nsfw::Window::step() { lastElapsedTime = getTime(); glfwSwapBuffers(window); glfwPollEvents(); //TODO_D("GLFW poll events and swap buffers is all that should really be here! No GL!"); } void nsfw::Window::term() { glfwDestroyWindow(window); glfwTerminate(); } float nsfw::Window::getDeltaTime() { float delta = (getTime() - lastElapsedTime); if (delta > 5.f) { return 5.f; } else { return delta; } } float nsfw::Window::getTime() const { //Look into tick //TODO(); return glfwGetTime(); } bool nsfw::Window::getKey(unsigned k) const { //TODO(); if (glfwGetKey(window, k) == GLFW_PRESS) { return true; } else { return false; } } bool nsfw::Window::getShouldClose() const { if (glfwWindowShouldClose(window) || getKey(256)) { return true; } /*int i = 1; if (i == 1){ return true; }*/ //TODO(); return false; } unsigned nsfw::Window::getWidth() const { //TODO(); return width; } unsigned nsfw::Window::getHeight() const { //TODO(); return height; } glm::mat4 nsfw::Window::getTexelAdjustmentMatrix() const { TODO_D("Implemented, not tested."); glm::vec3 texelSize = 1.0f/glm::vec3(width,height,0); glm::vec3 halfTexel = texelSize * 0.5f; // bottom left // scale up to the appropriate size, then shift it to line up w/center of texels return glm::translate(halfTexel) * glm::scale(glm::vec3(1, 1, 1) - texelSize); }
9007c4ea26507c68386341d1fc30484418292232
1f87cb8eb878000afbdcd24543e87301f4cd2ae3
/src/apps/PSSM/Distances.cpp
8c138eb1a05378cfb0d4272b7fdb04b40e904ef8
[ "MIT" ]
permissive
pkrusche/seaweeds
03834f03394842e921a632d4563f67e280846058
6607c577f11509ae819584a7ef86fcb1f243ec45
refs/heads/master
2020-12-25T18:17:53.330615
2018-09-27T16:56:45
2018-09-27T16:56:45
32,395,782
1
0
null
2018-09-27T16:56:46
2015-03-17T13:44:14
C++
UTF-8
C++
false
false
4,875
cpp
Distances.cpp
/*************************************************************************** * Copyright (C) 2012 Peter Krusche, The University of Warwick * * pkrusche@gmail.com * ***************************************************************************/ #include "autoconfig.h" #include "PSSM_Tool.h" /************************************************************************/ /* PSSM Pairwise distance App */ /************************************************************************/ /** * Pairwise distance matrix class */ class Distances { private: int N; utilities::AVector<double> distances; public: Distances () { N = 0; } inline void resize (int _n) { N = _n; distances.resize( N * N ); for (int j = 0; j < N * N; ++j) { distances [j] = -1.0; } } inline double & operator() (int i, int j) { return distances[i*N + j]; } inline void normalize() { using namespace std; double mi = DBL_MAX, ma = 0; for (int j = 0; j < N * N; ++j) { mi = min (mi, distances[j]); ma = max (ma, distances[j]); } for (int j = 0; j < N * N; ++j) { distances[j] = (distances[j] - mi) / (ma - mi); } } inline void * data () { return distances.data; } inline size_t data_size() { return N*N * sizeof(double); } }; /** Parallel code for computing pairwise distances * * Uses g_pssms. * */ class PSSM_Distances : public bsp::Context { public: enum distance_t { DIST_KULLBACK_LEIBLER, DIST_HELLINGER, }; PSSM_Distances() { CONTEXT_SHARED_INIT(dt, distance_t); dt = DIST_KULLBACK_LEIBLER; N = (int) g_pssms.size(); data = new double [N*N]; i_have_the_result = false; } ~PSSM_Distances() { delete [] data; } /** Set the distance type, default: Kullback-Leibler */ void set_distance_type (distance_t _dt) { dt = _dt; } static bool result_ready() { return i_have_the_result; } static Distances & get_distances () { ASSERT(i_have_the_result); return dists; } protected: static double KD ( pssms::PSSM<4> const & a , pssms::PSSM<4> const & b ) { static pssms::Both_Strands_DNA_Min_KullbackLeibler_Distance d; return d(a, b); } static double HD ( pssms::PSSM<4> const & a , pssms::PSSM<4> const & b ) { static pssms::Both_Strands_DNA_Min_Hellinger_Distance d; return d(a, b); } boost::function2<double, pssms::PSSM<4> const &, pssms::PSSM<4> const & > distancefun; /** Context variables */ int P, N, p, n, my_start, my_end; double * data; distance_t dt; /** Result output */ static bool i_have_the_result; static Distances dists; void run () { using namespace std; BSP_SCOPE(PSSM_Distances); BSP_BEGIN(); switch (dt) { case DIST_HELLINGER: distancefun = &HD; break; default: distancefun = &KD; break; } P = bsp_nprocs(); p = bsp_pid(); n = ICD(N, P); my_start = n * p; my_end = n * (p+1) - 1; if (my_end >= N) { my_end = N-1; } bsp_push_reg(data, N*N*sizeof(double)); BSP_SYNC(); int l = 0; for (int j = my_start; j <= my_end; ++j) { for (int k = 0; k < N; ++k) { if (j == k) { data[l*N+k] = 0; } else { data[l*N+k] = distancefun(g_pssms[j], g_pssms[k]); } add_progress(1); } ++l; } if (bsp_pid() != 0 && my_start <= my_end) { bsp_hpput(0, data, data, my_start * N *sizeof(double), (my_end - my_start + 1) * N * sizeof(double)); } BSP_SYNC(); bsp_pop_reg(data); if ( bsp_pid() == 0 ) { i_have_the_result = true; dists.resize(N); memcpy(dists.data(), data, N * N * sizeof(double)); } BSP_END(); } }; /** static implementation */ bool PSSM_Distances::i_have_the_result; Distances PSSM_Distances::dists; /** run the app and output results on one node */ void PSSM_DistancesApp::run (boost::program_options::variables_map & vm) { using namespace std; int distancefun = vm["distancetype"].as<int>(); if (distancefun < 0 || distancefun > 1) { throw std::runtime_error( "Unknown distance function"); } bsp::Runner<PSSM_Distances> r; if (distancefun == 0) { r.set_distance_type(PSSM_Distances::DIST_HELLINGER); } else { r.set_distance_type(PSSM_Distances::DIST_KULLBACK_LEIBLER); } start_progress("Computing pairwise distances...", (int) ( g_pssms.size() * g_pssms.size() ) ); r.run(); end_progress(); /** only happens on one node */ if (r.result_ready()) { Distances & d(r.get_distances()); if (vm.count("normalize") > 0) { d.normalize(); } for (size_t i = 0; i < g_pssms.size(); ++i) { cout << g_pssms[i].get_name() << "\t" ; } cout << "X" << endl; for (size_t i = 0; i < g_pssms.size(); ++i) { cout << g_pssms[i].get_name() << "\t"; for (size_t j = 0; j < g_pssms.size(); ++j) { double distance = d ((int)i, (int)j); cout << distance << "\t"; } cout << endl; } } }
25e1e627c0562327ac6ee99fbe28fcfbe0b77951
1e29330fbf4d53cf5dfac6f0290f660647109da7
/yss/inc/drv/clock/drv_microchip_clock_type_A.h
032dd43e2fab0cb09fde5d88ad9e84ce29d5868a
[]
no_license
bluelife85/yss
2c9807bba61723a6fa578f80edadd9e8d6f9d1a9
1ada1bcc8579bf17e53d6f31525960703ef2f6b9
refs/heads/master
2023-01-16T02:12:26.099052
2020-11-26T01:18:43
2020-11-26T01:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,488
h
drv_microchip_clock_type_A.h
//////////////////////////////////////////////////////////////////////////////////////// // // 저작권 표기 License_ver_2.0 // 본 소스코드의 소유권은 yss Embedded Operating System 네이버 카페 관리자와 운영진에게 있습니다. // 운영진이 임의로 코드의 권한을 타인에게 양도할 수 없습니다. // 본 소스코드는 아래 사항에 동의할 경우에 사용 가능합니다. // 아래 사항에 대해 동의하지 않거나 이해하지 못했을 경우 사용을 금합니다. // 본 소스코드를 사용하였다면 아래 사항을 모두 동의하는 것으로 자동 간주 합니다. // 본 소스코드의 상업적 또는 비상업적 이용이 가능합니다. // 본 소스코드의 내용을 임의로 수정하여 재배포하는 행위를 금합니다. // 본 소스코드의 내용을 무단 전재하는 행위를 금합니다. // 본 소스코드의 사용으로 인해 발생하는 모든 사고에 대해서 어떤한 법적 책임을 지지 않습니다. // // Home Page : http://cafe.naver.com/yssoperatingsystem // Copyright 2020. yss Embedded Operating System all right reserved. // // 주담당자 : 아이구 (mymy49@nate.com) 2016.04.30 ~ 현재 // 부담당자 : - // //////////////////////////////////////////////////////////////////////////////////////// #ifndef YSS_DRV_CLOCK_MICROCHIP_TYPE_A__H_ #define YSS_DRV_CLOCK_MICROCHIP_TYPE_A__H_ #if defined (__SAML21E15A__) || defined (__SAML21E15B__) || defined (__SAML21E16A__) || defined (__SAML21E16B__) || \ defined (__SAML21E17A__) || defined (__SAML21E17B__) || defined (__SAML21E18B__) || defined (__SAML21G16A__) || \ defined (__SAML21G16B__) || defined (__SAML21G17A__) || defined (__SAML21G17B__) || defined (__SAML21G18A__) || \ defined (__SAML21G18B__) || defined (__SAML21J16A__) || defined (__SAML21J16B__) || defined (__SAML21J17A__) || \ defined (__SAML21J17B__) || defined (__SAML21J18A__) || defined (__SAML21J18B__) #include <yss/mcu.h> #include <config.h> #include "drv_microchip_clock_type_A_ec.h" //#include "drv_st_clock_type_A_define.h" //#include "drv_st_clock_type_A_config.h" namespace drv { /* class MainPll { public: bool enable(config::clock::Pll &config, bool en = true); unsigned long getFreq(void); }; class SaiPll { public: bool enable(config::clock::Saipll &config, bool en = true); }; */ class Peripheral { public: bool setPeripheralClock(unsigned char num, unsigned char gen, bool en, bool lock = false); #if defined(SERCOM0) void setSerCom0En(bool en); #endif #if defined(DMA1) void setDmaEn(bool en); void resetDma(void); #endif #if defined(GPIOA) void setGpioAEn(bool en); #endif #if defined(GPIOB) void setGpioBEn(bool en); #endif #if defined(GPIOC) void setGpioCEn(bool en); #endif #if defined(GPIOD) void setGpioDEn(bool en); #endif #if defined(GPIOE) void setGpioEEn(bool en); #endif #if defined(GPIOF) void setGpioFEn(bool en); #endif #if defined(GPIOG) void setGpioGEn(bool en); #endif #if defined(GPIOH) void setGpioHEn(bool en); #endif #if defined(GPIOI) void setGpioIEn(bool en); #endif #if defined(GPIOJ) void setGpioJEn(bool en); #endif #if defined(GPIOK) void setGpioKEn(bool en); #endif #if defined(TIM1) void setTimer1En(bool en); #endif #if defined(TIM2) void setTimer2En(bool en); #endif #if defined(TIM3) void setTimer3En(bool en); #endif #if defined(TIM4) void setTimer4En(bool en); #endif #if defined(TIM5) void setTimer5En(bool en); #endif #if defined(TIM6) void setTimer6En(bool en); #endif #if defined(TIM7) void setTimer7En(bool en); #endif #if defined(TIM8) void setTimer8En(bool en); #endif #if defined(TIM9) void setTimer9En(bool en); #endif #if defined(TIM10) void setTimer10En(bool en); #endif #if defined(TIM11) void setTimer11En(bool en); #endif #if defined(TIM12) void setTimer12En(bool en); #endif #if defined(TIM13) void setTimer13En(bool en); #endif #if defined(TIM14) void setTimer14En(bool en); #endif #if defined(LTDC) void setLtdcEn(bool en); #endif #if defined(I2C1) void setI2c1En(bool en); #endif #if defined(I2C2) void setI2c2En(bool en); #endif #if defined(I2C3) void setI2c3En(bool en); #endif #if defined(I2C4) void setI2c4En(bool en); #endif #if defined(FMC_Bank1) void setFmcEn(bool en); #endif #if defined(SYSCFG) void setSyscfgEn(bool en); #endif #if defined(QUADSPI) void setQuadspi(bool en); #endif #if defined(USB_OTG_FS) void setUsbdFsEn(bool en); #endif #if defined(USB_OTG_HS) void setUsbdHsEn(bool en); #endif #if defined(USART1) void setUart1En(bool en); #endif #if defined(USART2) void setUart2En(bool en); void resetUart2(void); #endif #if defined(USART3) void setUart3En(bool en); #endif #if defined(UART4) void setUart4En(bool en); #endif #if defined(UART5) void setUart5En(bool en); #endif #if defined(USART6) void setUart6En(bool en); #endif #if defined(UART7) void setUart7En(bool en); #endif #if defined(UART8) void setUart8En(bool en); #endif #if defined(DMA2D) void setDma2d(bool en); #endif #if defined(SDMMC1) void setSdmmc(bool en); #endif #if defined(CAN1) void setCan(bool en); #endif }; class Clock { public : bool enableHse(unsigned char hseMhz); bool enableLse(void); bool setGenericClock(unsigned char num, bool en, unsigned short div, unsigned char src); // MainPll pll; // SaiPll saipll; Peripheral peripheral; }; } extern drv::Clock clock; #endif #endif
bdb9ac9eb50a5684e36aa752ad8abd4079a5b2b0
1ccbb3d8cada7f5c4acf6b32f3396b95a91bb6ca
/SonicGame3Dv3/src/water/WaterRenderer.cpp
c2d30fc488d3aceeacd248f6267718747b54c4ce
[]
no_license
jo9182/Sonic3DGamev3
980a59ce07e3848b3e8e462b79fe871923eba7bb
4f40c27690f89be55701985855dde93be34b5ca8
refs/heads/master
2022-09-18T06:43:31.919326
2021-05-27T01:21:17
2021-05-27T01:21:17
308,197,647
0
0
null
2020-10-29T02:37:35
2020-10-29T02:37:34
null
UTF-8
C++
false
false
3,115
cpp
WaterRenderer.cpp
#include "waterrenderer.h" #include "../renderEngine/renderEngine.h" #include "watershader.h" #include "waterframebuffers.h" #include "watertile.h" #include <list> #include <vector> #include "../engineTester/main.h" #include "../toolbox/maths.h" #include "../toolbox/vector.h" #include "../toolbox/matrix.h" #include "../shadows/shadowmapmasterrenderer.h" const float WaterRenderer::WAVE_SPEED = 0.0002f; WaterRenderer::WaterRenderer(WaterShader* shader, Matrix4f* projectionMatrix, WaterFrameBuffers* fbos, ShadowMapMasterRenderer* shadowMapRenderer) { this->shader = shader; this->fbos = fbos; this->shadowMapRenderer = shadowMapRenderer; dudvTexture = Loader::loadTexture("res/Images/waterDUDV.png"); normalMap = Loader::loadTexture("res/Images/normalMap.png"); shader->start(); shader->connectTextureUnits(); shader->loadProjectionMatrix(projectionMatrix); shader->stop(); setUpVAO(); } void WaterRenderer::prepareRender(Camera* camera, Light* sun) { shader->start(); shader->loadViewMatrix(camera); if (Global::renderShadowsFar) { shader->loadToShadowSpaceMatrix(shadowMapRenderer->getToShadowMapSpaceMatrix()); } moveFactor += WAVE_SPEED; moveFactor = fmodf(moveFactor, 1); shader->loadMoveFactor(moveFactor); shader->loadLight(sun); glBindVertexArray(quad->getVaoID()); glEnableVertexAttribArray(0); glActiveTexture(GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, fbos->getReflectionTexture()); glActiveTexture(GL_TEXTURE1); glBindTexture (GL_TEXTURE_2D, fbos->getRefractionTexture()); glActiveTexture(GL_TEXTURE2); glBindTexture (GL_TEXTURE_2D, dudvTexture); glActiveTexture(GL_TEXTURE3); glBindTexture (GL_TEXTURE_2D, normalMap); glActiveTexture(GL_TEXTURE4); glBindTexture (GL_TEXTURE_2D, fbos->getRefractionDepthTexture()); glDepthMask(true); } void WaterRenderer::unbind() { glDisableVertexAttribArray(0); glBindVertexArray(0); shader->stop(); } void WaterRenderer::setUpVAO() { // Just x and z vectex positions here, y is set to 0 in v.shader std::vector<float> vertices; vertices.push_back(-1); vertices.push_back(-1); vertices.push_back(-1); vertices.push_back(1); vertices.push_back(1); vertices.push_back(-1); vertices.push_back(1); vertices.push_back(-1); vertices.push_back(-1); vertices.push_back(1); vertices.push_back(1); vertices.push_back(1); quad = new RawModel(Loader::loadToVAO(&vertices, 2)); INCR_NEW } void WaterRenderer::render(std::list<WaterTile*>* water, Camera* camera, Light* sun) { prepareRender(camera, sun); for (WaterTile* tile : (*water)) { Matrix4f modelMatrix; Vector3f tilePosition(tile->getX(), tile->getHeight(), tile->getZ()); createTransformationMatrix(&modelMatrix, &tilePosition, 0, 0, 0, 0, WaterTile::TILE_SIZE); shader->loadModelMatrix(&modelMatrix); glDrawArrays(GL_TRIANGLES, 0, quad->getVertexCount()); } unbind(); } void WaterRenderer::updateProjectionMatrix(Matrix4f* projectionMatrix) { shader->start(); shader->loadProjectionMatrix(projectionMatrix); shader->stop(); }
ece879d66c1b6329143ac0ef30d1cf22d250d8ce
e8282e3ae8aafa07b7f7261c639f206c4e97e0fc
/02 - SMA/Camp 1 OSN Kelas 11/Hari-13/E.cpp
bd0450adc479afa55dff8fe0182a92c059458e72
[]
no_license
irfansofyana/cp-codes
7cad844da49b901ccf678b75c31ed41e2fa9d645
9fa723129088f0e4832ecb7e012fe586b6d59e41
refs/heads/master
2023-04-04T00:48:36.334817
2021-04-12T03:07:06
2021-04-12T03:07:06
218,084,148
0
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
E.cpp
#include <bits/stdc++.h> using namespace std; long long n,i,j; long long A[50]; int main(){ cin.tie(0); A[1] = 2; A[2] = 2; for (i = 3 ; i<=45 ; i++) A[i] = A[i-1]+A[i-2]; cin >> n; cout << A[n] << endl; return 0; }
a9c5e5781800afbde4e3e62941617dbe499c689c
fafdf1e62cf622035ee82666ba6ae7108127d140
/kynapse7/include/kypathdata/blob/blobfileheader.h
4605636fc76f6a545aa648eb40556e28387076eb
[]
no_license
saerich/RaiderZ-Evolved-SDK
7f18942ddc6c566d47c3a6222c03fad7543738a4
b576e6757b6a781a656be7ba31eb0cf5e8a23391
refs/heads/master
2023-02-12T03:21:26.442348
2020-08-30T15:39:54
2020-08-30T15:39:54
281,213,173
1
2
null
null
null
null
UTF-8
C++
false
false
2,215
h
blobfileheader.h
/* * Copyright 2010 Autodesk, Inc. All rights reserved. * Use of this software is subject to the terms of the Autodesk license agreement provided at the time of installation or download, * or which otherwise accompanies this software in either electronic or hard copy form. */ /*! \file \ingroup kypathdata_blob */ // primary contact: GUAL - secondary contact: NOBODY #ifndef KyPathData_BlobFileHeader_H #define KyPathData_BlobFileHeader_H #include <kypathdata/blob/endianness.h> #include <kypathdata/generic/memory.h> namespace Kaim { /* BlobFileHeader is the header information that is stored in a file just before the Blob buffer. It allows to describe - the endianness - the blob type, version, size BlobFileHeader memory layout m_magicString (12) | m_endianness (4) | | m_blobType (24) | | | m_blobVersion UINT (4) | | | | m_blobSize UINT (4) | | | | | blob | | | | | | BlobFile0000 #### MyBlobType00000000000000 #### #### ###########... */ class BlobFileHeader { KY_DEFINE_NEW_DELETE_OPERATORS public: static const char* MagicString() { return "BlobFile"; } BlobFileHeader(); /* Sets the whole structure to zeros */ void Clear(); /* Copy memoryBuffer to this and fix the endianness if needed. Typically called when loading a Blob from a buffer or a file. */ KyResult InitFromBuffer(void* memoryBuffer, bool& isEndiannessSwap); /* Typically called when saving a Blob to a buffer or a file */ KyResult Init(KyUInt32 blobSize, const char* blobType, KyUInt32 blobVersion); /* GetEndianness() works even if the endianness of the structure is swapped */ Endianness::Type GetEndianness() const; /* Swap endianness in place. After SwapEndianness() is called, all subsequent calls to BlobFileHeader are invalid ! Swaps also m_endianness from little to big or big to little */ void SwapEndianness(); public: char m_magicString[12]; // BlobFile0000 KyUInt32 m_endianness; char m_blobType[24]; KyUInt32 m_blobVersion; KyUInt32 m_blobSize; }; } #endif
7e943094859c03ab40f0e9150894abe2d2dca565
a2206795a05877f83ac561e482e7b41772b22da8
/Source/PV/build/Wrapping/ClientServer/vtkPVServerManagerCoreCSInit.cxx
afc5f309c3c728582f9046bc66be3cb6ad02ee52
[]
no_license
supreethms1809/mpas-insitu
5578d465602feb4d6b239a22912c33918c7bb1c3
701644bcdae771e6878736cb6f49ccd2eb38b36e
refs/heads/master
2020-03-25T16:47:29.316814
2018-08-08T02:00:13
2018-08-08T02:00:13
143,947,446
0
0
null
null
null
null
UTF-8
C++
false
false
11,300
cxx
vtkPVServerManagerCoreCSInit.cxx
/* #undef PARAVIEW_USE_UNIFIED_BINDINGS */ /* #undef NO_PYTHON_BINDINGS_AVAILABLE */ #ifdef NO_PYTHON_BINDINGS_AVAILABLE #undef PARAVIEW_USE_UNIFIED_BINDINGS #endif #ifdef PARAVIEW_USE_UNIFIED_BINDINGS #include "vtkPython.h" #include "vtkPythonInterpreter.h" #endif #include "vtkClientServerInterpreter.h" #ifndef PARAVIEW_BUILD_SHARED_LIBS /* #undef PARAVIEW_BUILD_SHARED_LIBS */ #endif #if defined(PARAVIEW_BUILD_SHARED_LIBS) && defined(_WIN32) # define VTK_WRAP_CS_EXPORT __declspec(dllexport) #else # define VTK_WRAP_CS_EXPORT #endif #ifdef PARAVIEW_USE_UNIFIED_BINDINGS extern "C" void real_initvtkPVServerManagerCorePython(const char *modulename); void initvtkPVServerManagerCorePython() { static const char modulename[] = "vtkPVServerManagerCorePython"; real_initvtkPVServerManagerCorePython(modulename); } #endif extern void vtkLiveInsituLink_Init(vtkClientServerInterpreter* csi); extern void vtkSMArrayListDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMArrayRangeDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMArraySelectionDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMBooleanDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMBoundsDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMCollaborationManager_Init(vtkClientServerInterpreter* csi); extern void vtkSMCompositeTreeDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMCompoundProxyDefinitionLoader_Init(vtkClientServerInterpreter* csi); extern void vtkSMCompoundSourceProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMCompoundSourceProxyDefinitionBuilder_Init(vtkClientServerInterpreter* csi); extern void vtkSMCoreUtilities_Init(vtkClientServerInterpreter* csi); extern void vtkSMDataSourceProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMDataTypeDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMDeserializer_Init(vtkClientServerInterpreter* csi); extern void vtkSMDeserializerProtobuf_Init(vtkClientServerInterpreter* csi); extern void vtkSMDeserializerXMLCache_Init(vtkClientServerInterpreter* csi); extern void vtkSMDeserializerXML_Init(vtkClientServerInterpreter* csi); extern void vtkSMDimensionsDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMDocumentation_Init(vtkClientServerInterpreter* csi); extern void vtkSMDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMDomainIterator_Init(vtkClientServerInterpreter* csi); extern void vtkSMDoubleMapProperty_Init(vtkClientServerInterpreter* csi); extern void vtkSMDoubleMapPropertyIterator_Init(vtkClientServerInterpreter* csi); extern void vtkSMDoubleRangeDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMDoubleVectorProperty_Init(vtkClientServerInterpreter* csi); extern void vtkSMEnumerationDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMExtentDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMFieldDataDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMFileListDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMFixedTypeDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMGlobalPropertiesLinkUndoElement_Init(vtkClientServerInterpreter* csi); extern void vtkSMGlobalPropertiesProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMIdTypeVectorProperty_Init(vtkClientServerInterpreter* csi); extern void vtkSMInputArrayDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMInputProperty_Init(vtkClientServerInterpreter* csi); extern void vtkSMInsituStateLoader_Init(vtkClientServerInterpreter* csi); extern void vtkSMIntRangeDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMIntVectorProperty_Init(vtkClientServerInterpreter* csi); extern void vtkSMLink_Init(vtkClientServerInterpreter* csi); extern void vtkSMLiveInsituLinkProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMMapProperty_Init(vtkClientServerInterpreter* csi); extern void vtkSMNamedPropertyIterator_Init(vtkClientServerInterpreter* csi); extern void vtkSMNumberOfComponentsDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMObject_Init(vtkClientServerInterpreter* csi); extern void vtkSMOrderedPropertyIterator_Init(vtkClientServerInterpreter* csi); extern void vtkSMOutputPort_Init(vtkClientServerInterpreter* csi); extern void vtkSMParaViewPipelineController_Init(vtkClientServerInterpreter* csi); extern void vtkSMPWriterProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMPipelineState_Init(vtkClientServerInterpreter* csi); extern void vtkSMPluginLoaderProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMPluginManager_Init(vtkClientServerInterpreter* csi); extern void vtkSMProperty_Init(vtkClientServerInterpreter* csi); extern void vtkSMPropertyGroup_Init(vtkClientServerInterpreter* csi); extern void vtkSMPropertyIterator_Init(vtkClientServerInterpreter* csi); extern void vtkSMPropertyLink_Init(vtkClientServerInterpreter* csi); extern void vtkSMProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMProxyDefinitionManager_Init(vtkClientServerInterpreter* csi); extern void vtkSMProxyGroupDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMProxyIterator_Init(vtkClientServerInterpreter* csi); extern void vtkSMProxyLink_Init(vtkClientServerInterpreter* csi); extern void vtkSMProxyListDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMProxyLocator_Init(vtkClientServerInterpreter* csi); extern void vtkSMProxyManager_Init(vtkClientServerInterpreter* csi); extern void vtkSMProxyProperty_Init(vtkClientServerInterpreter* csi); extern void vtkSMProxySelectionModel_Init(vtkClientServerInterpreter* csi); extern void vtkSMReaderFactory_Init(vtkClientServerInterpreter* csi); extern void vtkSMRemoteObject_Init(vtkClientServerInterpreter* csi); extern void vtkSMRemoteObjectUpdateUndoElement_Init(vtkClientServerInterpreter* csi); extern void vtkSMServerStateLocator_Init(vtkClientServerInterpreter* csi); extern void vtkSMSessionClient_Init(vtkClientServerInterpreter* csi); extern void vtkSMSession_Init(vtkClientServerInterpreter* csi); extern void vtkSMSessionObject_Init(vtkClientServerInterpreter* csi); extern void vtkSMSessionProxyManager_Init(vtkClientServerInterpreter* csi); extern void vtkSMSettings_Init(vtkClientServerInterpreter* csi); extern void vtkSMSettingsProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMSILDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMSILModel_Init(vtkClientServerInterpreter* csi); extern void vtkSMSourceProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMStateLoader_Init(vtkClientServerInterpreter* csi); extern void vtkSMStateLocator_Init(vtkClientServerInterpreter* csi); extern void vtkSMStateVersionController_Init(vtkClientServerInterpreter* csi); extern void vtkSMStringListDomain_Init(vtkClientServerInterpreter* csi); extern void vtkSMStringVectorProperty_Init(vtkClientServerInterpreter* csi); extern void vtkSMUndoElement_Init(vtkClientServerInterpreter* csi); extern void vtkSMUndoStackBuilder_Init(vtkClientServerInterpreter* csi); extern void vtkSMUndoStack_Init(vtkClientServerInterpreter* csi); extern void vtkSMNullProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMTimeKeeper_Init(vtkClientServerInterpreter* csi); extern void vtkSMTimeKeeperProxy_Init(vtkClientServerInterpreter* csi); extern void vtkSMTrace_Init(vtkClientServerInterpreter* csi); extern void vtkSMVectorProperty_Init(vtkClientServerInterpreter* csi); extern void vtkSMWriterFactory_Init(vtkClientServerInterpreter* csi); extern void vtkSMWriterProxy_Init(vtkClientServerInterpreter* csi); extern "C" void VTK_WRAP_CS_EXPORT vtkPVServerManagerCoreCS_Initialize( vtkClientServerInterpreter *csi) { #ifdef PARAVIEW_USE_UNIFIED_BINDINGS if (!vtkPythonInterpreter::IsInitialized()) { vtkPythonInterpreter::Initialize(); } static bool initialized = false; if (!initialized) { initialized = true; PyImport_AppendInittab("vtkPVServerManagerCorePython", initvtkPVServerManagerCorePython); } csi->Load("vtkPVServerManagerCore"); #endif vtkLiveInsituLink_Init(csi); vtkSMArrayListDomain_Init(csi); vtkSMArrayRangeDomain_Init(csi); vtkSMArraySelectionDomain_Init(csi); vtkSMBooleanDomain_Init(csi); vtkSMBoundsDomain_Init(csi); vtkSMCollaborationManager_Init(csi); vtkSMCompositeTreeDomain_Init(csi); vtkSMCompoundProxyDefinitionLoader_Init(csi); vtkSMCompoundSourceProxy_Init(csi); vtkSMCompoundSourceProxyDefinitionBuilder_Init(csi); vtkSMCoreUtilities_Init(csi); vtkSMDataSourceProxy_Init(csi); vtkSMDataTypeDomain_Init(csi); vtkSMDeserializer_Init(csi); vtkSMDeserializerProtobuf_Init(csi); vtkSMDeserializerXMLCache_Init(csi); vtkSMDeserializerXML_Init(csi); vtkSMDimensionsDomain_Init(csi); vtkSMDocumentation_Init(csi); vtkSMDomain_Init(csi); vtkSMDomainIterator_Init(csi); vtkSMDoubleMapProperty_Init(csi); vtkSMDoubleMapPropertyIterator_Init(csi); vtkSMDoubleRangeDomain_Init(csi); vtkSMDoubleVectorProperty_Init(csi); vtkSMEnumerationDomain_Init(csi); vtkSMExtentDomain_Init(csi); vtkSMFieldDataDomain_Init(csi); vtkSMFileListDomain_Init(csi); vtkSMFixedTypeDomain_Init(csi); vtkSMGlobalPropertiesLinkUndoElement_Init(csi); vtkSMGlobalPropertiesProxy_Init(csi); vtkSMIdTypeVectorProperty_Init(csi); vtkSMInputArrayDomain_Init(csi); vtkSMInputProperty_Init(csi); vtkSMInsituStateLoader_Init(csi); vtkSMIntRangeDomain_Init(csi); vtkSMIntVectorProperty_Init(csi); vtkSMLink_Init(csi); vtkSMLiveInsituLinkProxy_Init(csi); vtkSMMapProperty_Init(csi); vtkSMNamedPropertyIterator_Init(csi); vtkSMNumberOfComponentsDomain_Init(csi); vtkSMObject_Init(csi); vtkSMOrderedPropertyIterator_Init(csi); vtkSMOutputPort_Init(csi); vtkSMParaViewPipelineController_Init(csi); vtkSMPWriterProxy_Init(csi); vtkSMPipelineState_Init(csi); vtkSMPluginLoaderProxy_Init(csi); vtkSMPluginManager_Init(csi); vtkSMProperty_Init(csi); vtkSMPropertyGroup_Init(csi); vtkSMPropertyIterator_Init(csi); vtkSMPropertyLink_Init(csi); vtkSMProxy_Init(csi); vtkSMProxyDefinitionManager_Init(csi); vtkSMProxyGroupDomain_Init(csi); vtkSMProxyIterator_Init(csi); vtkSMProxyLink_Init(csi); vtkSMProxyListDomain_Init(csi); vtkSMProxyLocator_Init(csi); vtkSMProxyManager_Init(csi); vtkSMProxyProperty_Init(csi); vtkSMProxySelectionModel_Init(csi); vtkSMReaderFactory_Init(csi); vtkSMRemoteObject_Init(csi); vtkSMRemoteObjectUpdateUndoElement_Init(csi); vtkSMServerStateLocator_Init(csi); vtkSMSessionClient_Init(csi); vtkSMSession_Init(csi); vtkSMSessionObject_Init(csi); vtkSMSessionProxyManager_Init(csi); vtkSMSettings_Init(csi); vtkSMSettingsProxy_Init(csi); vtkSMSILDomain_Init(csi); vtkSMSILModel_Init(csi); vtkSMSourceProxy_Init(csi); vtkSMStateLoader_Init(csi); vtkSMStateLocator_Init(csi); vtkSMStateVersionController_Init(csi); vtkSMStringListDomain_Init(csi); vtkSMStringVectorProperty_Init(csi); vtkSMUndoElement_Init(csi); vtkSMUndoStackBuilder_Init(csi); vtkSMUndoStack_Init(csi); vtkSMNullProxy_Init(csi); vtkSMTimeKeeper_Init(csi); vtkSMTimeKeeperProxy_Init(csi); vtkSMTrace_Init(csi); vtkSMVectorProperty_Init(csi); vtkSMWriterFactory_Init(csi); vtkSMWriterProxy_Init(csi); }
a6de5f381b9dd42929c9a70b8d87494c480ab547
e006941ba53095bae9e233aab360925db7f30f2d
/engine/modules/core/src/atomic.cpp
ffcf0d3c43f5ee0fb9146b6370a34af41d7ca04d
[]
no_license
billfreist/LightEngine
a23e840e30a0758264b68e5274c881c6f4e0c863
0f0d017075889cf5d518086edc0f3ed055bee53b
refs/heads/master
2021-01-12T04:53:45.265090
2020-04-06T04:34:55
2020-04-06T04:34:55
77,804,804
1
0
null
null
null
null
UTF-8
C++
false
false
77
cpp
atomic.cpp
/// /// LICENSE /// #include "pch.h" namespace lite { } // namespace lite
5d62f7045ff7ee84bcd27a38f8dac0f0956d1301
2558d081018b41203812933efe70365b71681987
/Searching/linearsearching.cpp
338fd8a0a8c2bea19c37ebe34920b3760c5fb7ab
[]
no_license
erwasim1/DSA
a166a2b662e1ba0ce64c3c84bc894cec0b5dbcef
c17ec591147142a467ffdc5d54028cdb3efaf1b0
refs/heads/master
2023-06-24T14:06:36.261310
2021-07-27T04:34:22
2021-07-27T04:34:22
389,848,274
0
0
null
null
null
null
UTF-8
C++
false
false
646
cpp
linearsearching.cpp
#include<iostream> using namespace std; void init(int arr[],int n){ for(int i=0;i<n;i++) cin>>arr[i]; } void display(int arr[],int n){ for(int i=0;i<n;i++) cout<<arr[i]<<" "; } int linearsrch(int arr[],int n,int k){ for(int i=0;i<n;i++){ if(arr[i]==k){ return i; } } return -1; } int main(){ int n; cout<<"enter the size of array :-> "; cin>>n; int arr[n]; cout<<endl; cout<<"enter the elements in array :-> "; init(arr,n); display(arr,n); cout<<"enter the element u want to search :-> "; int k; cin>>k; cout<<linearsrch(arr,n,k); return 0; }
73df22e480ebe64e6cfda5f15e10c1c11cf3ceae
bd7a1a70e83fa81acc152454494d822acb795ffd
/src/MarchingChunkManager.cpp
d6f9d386c3b10bdb0f0e47b37442574d335ab0e2
[]
no_license
JC-G/Mountains
828e69a4ab2a6b9ed5f125ddf06ec15d1dd13bed
b0d81eacac9352fadf606c8ec74b55d6c9885a84
refs/heads/master
2020-04-08T17:15:09.915382
2019-08-03T13:29:17
2019-08-03T13:29:17
159,558,928
4
0
null
null
null
null
UTF-8
C++
false
false
270
cpp
MarchingChunkManager.cpp
#include "MarchingChunkManager.h" namespace MarchingChunkManager { std::vector<MarchingChunk*> loadedChunks; GLuint VAO; bool genVAO() { glGenVertexArrays(1,&VAO); glBindVertexArray(VAO); return glIsVertexArray(VAO); } }
0ced73ed1fbbb502a14d88c3ea93ca653a740d22
d3718f4b2330e4f77168ab6a18a432cdd0dbbc4b
/MainForm.h
a10e64473fc5a7c3db544b5692c4a550c5873df0
[ "MIT" ]
permissive
BomjSoft/Duplicate-finder
0a81c164ccea8356c5aeeab0f477859ea0890bc4
d865efba226ec5c9b29904226eae09f818988957
refs/heads/main
2023-07-02T20:02:30.703070
2021-08-04T07:59:21
2021-08-04T07:59:21
392,598,346
0
0
null
null
null
null
UTF-8
C++
false
false
2,747
h
MainForm.h
//--------------------------------------------------------------------------- #pragma once //--------------------------------------------------------------------------- #include <set> #include "BCL.h" //--------------------------------------------------------------------------- #include "PerceptiveHash.h" #include "Texture.h" //--------------------------------------------------------------------------- #define MAX_DUPLICATE_DELTA 4 //--------------------------------------------------------------------------- struct SImageInfo { public: std::tstring name; LARGE_INTEGER size; BYTE hash[HASH_LEN]; DWORD SizeX; DWORD SizeY; DWORD group; bool deleted; bool operator<(const SImageInfo &Operand) const { return name < Operand.name; } }; //--------------------------------------------------------------------------- DWORD CaculateDist(const BYTE Value1[HASH_LEN], const BYTE Value2[HASH_LEN]); //--------------------------------------------------------------------------- class CMainForm : public bcl::CForm { private: bcl::CListBox listSelectedFiles; bcl::CButton buttonAddFile; bcl::CButton buttonAddFolder; bcl::CButton buttonRemove; bcl::CButton buttonModify; bcl::CButton buttonNext; bcl::CProgressBar progressScan; bcl::CProgressBar progressCalculate; bcl::CProgressBar progressCompare; bcl::CLabel imageListDescription; bcl::CLabel imageDescription; bcl::CLabel deleteListDescription; bcl::CListBox imageList; bcl::CCheckListBox deleteList; bcl::CButton buttonFinish; std::vector<SImageInfo> hashList; std::vector<std::vector<SImageInfo*> > groupList; bool display; bcl::CBitmap displayImage; void FormCreate(bcl::CObject *Sender); void FormResize(bcl::CObject *Sender); void FormPaint(bcl::CObject *Sender); void FormMouseDoubleClick(bcl::CObject *Sender, EMouseButton MouseButton, int X, int Y); void ChangeSelectedFiles(bcl::CObject *Sender); void AddFileClick(bcl::CObject *Sender); void AddFolderClick(bcl::CObject *Sender); void RemoveClick(bcl::CObject *Sender); void ModifyClick(bcl::CObject *Sender); void NextClick(bcl::CObject *Sender); void ImageChange(bcl::CObject *Sender); void DeleteCheck(bcl::CObject *Sender, int Item, bool Value); void DeleteChange(bcl::CObject *Sender); void FinishClick(bcl::CObject *Sender); static void SearchDuplicateFolder(std::tstring Folder, std::set<std::tstring> &List); public: CMainForm(); virtual ~CMainForm(); void SearchDuplicate(); void DeleteDuplicate(); }; //---------------------------------------------------------------------------
bec1baf0e89dd02e0420573186206397ef931054
0619320681cddf3169f62676c3ef76c3764f1676
/server-side/ws/soapStub.h
3475451d99e2d3e3d7c9cc8b6cdf187a40e8e2e0
[]
no_license
radtek/eHealthMonitoring
177a5b8892bf906b77760c0934c616600c80bce3
cbb23c1a4c04491b7d791803d265ab7dd75989d2
refs/heads/master
2020-06-21T22:29:28.870198
2018-07-04T22:11:18
2018-07-04T22:11:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,073
h
soapStub.h
/* soapStub.h Generated by gSOAP 2.8.67 for sensor.h gSOAP XML Web services tools Copyright (C) 2000-2018, Robert van Engelen, Genivia Inc. All Rights Reserved. The soapcpp2 tool and its generated software are released under the GPL. This program is released under the GPL with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. -------------------------------------------------------------------------------- A commercial use license is available from Genivia Inc., contact@genivia.com -------------------------------------------------------------------------------- */ #ifndef soapStub_H #define soapStub_H #include "stdsoap2.h" #if GSOAP_VERSION != 20867 # error "GSOAP VERSION 20867 MISMATCH IN GENERATED CODE VERSUS LIBRARY CODE: PLEASE REINSTALL PACKAGE" #endif /******************************************************************************\ * * * Types with Custom Serializers * * * \******************************************************************************/ /******************************************************************************\ * * * Classes, Structs and Unions * * * \******************************************************************************/ class ns__sensorData; /* sensor.h:9 */ struct ns__getSensorData; /* sensor.h:21 */ /* sensor.h:9 */ #ifndef SOAP_TYPE_ns__sensorData #define SOAP_TYPE_ns__sensorData (7) /* complex XSD type 'ns:sensorData': */ class SOAP_CMAC ns__sensorData { public: /// optional attribute 'temperature' of XSD type 'xsd:float' float temperature; ///< initialized with default value = 9999 /// optional attribute 'ecg' of XSD type 'xsd:float' float ecg; ///< initialized with default value = 9999 /// optional attribute 'pulse' of XSD type 'xsd:int' int pulse; ///< initialized with default value = 9999 /// optional attribute 'systolic' of XSD type 'xsd:int' int systolic; ///< initialized with default value = 9999 /// optional attribute 'diastolic' of XSD type 'xsd:int' int diastolic; ///< initialized with default value = 9999 public: /// Return unique type id SOAP_TYPE_ns__sensorData virtual long soap_type(void) const { return SOAP_TYPE_ns__sensorData; } /// (Re)set members to default values virtual void soap_default(struct soap*); /// Serialize object to prepare for SOAP 1.1/1.2 encoded output (or with SOAP_XML_GRAPH) by analyzing its (cyclic) structures virtual void soap_serialize(struct soap*) const; /// Output object in XML, compliant with SOAP 1.1 encoding style, return error code or SOAP_OK virtual int soap_put(struct soap*, const char *tag, const char *type) const; /// Output object in XML, with tag and optional id attribute and xsi:type, return error code or SOAP_OK virtual int soap_out(struct soap*, const char *tag, int id, const char *type) const; /// Get object from XML, compliant with SOAP 1.1 encoding style, return pointer to object or NULL on error virtual void *soap_get(struct soap*, const char *tag, const char *type); /// Get object from XML, with matching tag and type (NULL matches any tag and type), return pointer to object or NULL on error virtual void *soap_in(struct soap*, const char *tag, const char *type); /// Return a new object of type ns__sensorData, default initialized and not managed by a soap context virtual ns__sensorData *soap_alloc(void) const { return SOAP_NEW_UNMANAGED(ns__sensorData); } public: /// Constructor with initializations ns__sensorData() : temperature(9999), ecg(9999), pulse(9999), systolic(9999), diastolic(9999) { } virtual ~ns__sensorData() { } /// Friend allocator used by soap_new_ns__sensorData(struct soap*, int) friend SOAP_FMAC1 ns__sensorData * SOAP_FMAC2 soap_instantiate_ns__sensorData(struct soap*, int, const char*, const char*, size_t*); }; #endif /* sensor.h:21 */ #ifndef SOAP_TYPE_ns__getSensorData #define SOAP_TYPE_ns__getSensorData (11) /* complex XSD type 'ns:getSensorData': */ struct SOAP_CMAC ns__getSensorData { public: /** Return unique type id SOAP_TYPE_ns__getSensorData */ long soap_type() const { return SOAP_TYPE_ns__getSensorData; } /** Constructor with member initializations */ ns__getSensorData() { } /** Friend allocator */ friend SOAP_FMAC1 ns__getSensorData * SOAP_FMAC2 soap_instantiate_ns__getSensorData(struct soap*, int, const char*, const char*, size_t*); }; #endif /* sensor.h:22 */ #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Header #define SOAP_TYPE_SOAP_ENV__Header (12) /* SOAP_ENV__Header: */ struct SOAP_CMAC SOAP_ENV__Header { public: /** Return unique type id SOAP_TYPE_SOAP_ENV__Header */ long soap_type() const { return SOAP_TYPE_SOAP_ENV__Header; } /** Constructor with member initializations */ SOAP_ENV__Header() { } /** Friend allocator */ friend SOAP_FMAC1 SOAP_ENV__Header * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Header(struct soap*, int, const char*, const char*, size_t*); }; #endif #endif /* sensor.h:22 */ #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Code #define SOAP_TYPE_SOAP_ENV__Code (13) /* Type SOAP_ENV__Code is a recursive data type, (in)directly referencing itself through its (base or derived class) members */ /* SOAP_ENV__Code: */ struct SOAP_CMAC SOAP_ENV__Code { public: /** Optional element 'SOAP-ENV:Value' of XSD type 'xsd:QName' */ char *SOAP_ENV__Value; /** Optional element 'SOAP-ENV:Subcode' of XSD type 'SOAP-ENV:Code' */ struct SOAP_ENV__Code *SOAP_ENV__Subcode; public: /** Return unique type id SOAP_TYPE_SOAP_ENV__Code */ long soap_type() const { return SOAP_TYPE_SOAP_ENV__Code; } /** Constructor with member initializations */ SOAP_ENV__Code() : SOAP_ENV__Value(), SOAP_ENV__Subcode() { } /** Friend allocator */ friend SOAP_FMAC1 SOAP_ENV__Code * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Code(struct soap*, int, const char*, const char*, size_t*); }; #endif #endif /* sensor.h:22 */ #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Detail #define SOAP_TYPE_SOAP_ENV__Detail (15) /* SOAP_ENV__Detail: */ struct SOAP_CMAC SOAP_ENV__Detail { public: char *__any; /** Any type of element 'fault' assigned to fault with its SOAP_TYPE_T assigned to __type */ /** Do not create a cyclic data structure throught this member unless SOAP encoding or SOAP_XML_GRAPH are used for id-ref serialization */ int __type; void *fault; public: /** Return unique type id SOAP_TYPE_SOAP_ENV__Detail */ long soap_type() const { return SOAP_TYPE_SOAP_ENV__Detail; } /** Constructor with member initializations */ SOAP_ENV__Detail() : __any(), __type(), fault() { } /** Friend allocator */ friend SOAP_FMAC1 SOAP_ENV__Detail * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Detail(struct soap*, int, const char*, const char*, size_t*); }; #endif #endif /* sensor.h:22 */ #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Reason #define SOAP_TYPE_SOAP_ENV__Reason (18) /* SOAP_ENV__Reason: */ struct SOAP_CMAC SOAP_ENV__Reason { public: /** Optional element 'SOAP-ENV:Text' of XSD type 'xsd:string' */ char *SOAP_ENV__Text; public: /** Return unique type id SOAP_TYPE_SOAP_ENV__Reason */ long soap_type() const { return SOAP_TYPE_SOAP_ENV__Reason; } /** Constructor with member initializations */ SOAP_ENV__Reason() : SOAP_ENV__Text() { } /** Friend allocator */ friend SOAP_FMAC1 SOAP_ENV__Reason * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Reason(struct soap*, int, const char*, const char*, size_t*); }; #endif #endif /* sensor.h:22 */ #ifndef WITH_NOGLOBAL #ifndef SOAP_TYPE_SOAP_ENV__Fault #define SOAP_TYPE_SOAP_ENV__Fault (19) /* SOAP_ENV__Fault: */ struct SOAP_CMAC SOAP_ENV__Fault { public: /** Optional element 'faultcode' of XSD type 'xsd:QName' */ char *faultcode; /** Optional element 'faultstring' of XSD type 'xsd:string' */ char *faultstring; /** Optional element 'faultactor' of XSD type 'xsd:string' */ char *faultactor; /** Optional element 'detail' of XSD type 'SOAP-ENV:Detail' */ struct SOAP_ENV__Detail *detail; /** Optional element 'SOAP-ENV:Code' of XSD type 'SOAP-ENV:Code' */ struct SOAP_ENV__Code *SOAP_ENV__Code; /** Optional element 'SOAP-ENV:Reason' of XSD type 'SOAP-ENV:Reason' */ struct SOAP_ENV__Reason *SOAP_ENV__Reason; /** Optional element 'SOAP-ENV:Node' of XSD type 'xsd:string' */ char *SOAP_ENV__Node; /** Optional element 'SOAP-ENV:Role' of XSD type 'xsd:string' */ char *SOAP_ENV__Role; /** Optional element 'SOAP-ENV:Detail' of XSD type 'SOAP-ENV:Detail' */ struct SOAP_ENV__Detail *SOAP_ENV__Detail; public: /** Return unique type id SOAP_TYPE_SOAP_ENV__Fault */ long soap_type() const { return SOAP_TYPE_SOAP_ENV__Fault; } /** Constructor with member initializations */ SOAP_ENV__Fault() : faultcode(), faultstring(), faultactor(), detail(), SOAP_ENV__Code(), SOAP_ENV__Reason(), SOAP_ENV__Node(), SOAP_ENV__Role(), SOAP_ENV__Detail() { } /** Friend allocator */ friend SOAP_FMAC1 SOAP_ENV__Fault * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Fault(struct soap*, int, const char*, const char*, size_t*); }; #endif #endif /******************************************************************************\ * * * Typedefs * * * \******************************************************************************/ /* (built-in):0 */ #ifndef SOAP_TYPE__XML #define SOAP_TYPE__XML (5) typedef char *_XML; #endif /* (built-in):0 */ #ifndef SOAP_TYPE__QName #define SOAP_TYPE__QName (6) typedef char *_QName; #endif /******************************************************************************\ * * * Serializable Types * * * \******************************************************************************/ /* char has binding name 'byte' for type 'xsd:byte' */ #ifndef SOAP_TYPE_byte #define SOAP_TYPE_byte (3) #endif /* int has binding name 'int' for type 'xsd:int' */ #ifndef SOAP_TYPE_int #define SOAP_TYPE_int (1) #endif /* float has binding name 'float' for type 'xsd:float' */ #ifndef SOAP_TYPE_float #define SOAP_TYPE_float (8) #endif /* ns__sensorData has binding name 'ns__sensorData' for type 'ns:sensorData' */ #ifndef SOAP_TYPE_ns__sensorData #define SOAP_TYPE_ns__sensorData (7) #endif /* struct SOAP_ENV__Fault has binding name 'SOAP_ENV__Fault' for type '' */ #ifndef SOAP_TYPE_SOAP_ENV__Fault #define SOAP_TYPE_SOAP_ENV__Fault (19) #endif /* struct SOAP_ENV__Reason has binding name 'SOAP_ENV__Reason' for type '' */ #ifndef SOAP_TYPE_SOAP_ENV__Reason #define SOAP_TYPE_SOAP_ENV__Reason (18) #endif /* struct SOAP_ENV__Detail has binding name 'SOAP_ENV__Detail' for type '' */ #ifndef SOAP_TYPE_SOAP_ENV__Detail #define SOAP_TYPE_SOAP_ENV__Detail (15) #endif /* struct SOAP_ENV__Code has binding name 'SOAP_ENV__Code' for type '' */ #ifndef SOAP_TYPE_SOAP_ENV__Code #define SOAP_TYPE_SOAP_ENV__Code (13) #endif /* struct SOAP_ENV__Header has binding name 'SOAP_ENV__Header' for type '' */ #ifndef SOAP_TYPE_SOAP_ENV__Header #define SOAP_TYPE_SOAP_ENV__Header (12) #endif /* struct ns__getSensorData has binding name 'ns__getSensorData' for type 'ns:getSensorData' */ #ifndef SOAP_TYPE_ns__getSensorData #define SOAP_TYPE_ns__getSensorData (11) #endif /* struct SOAP_ENV__Reason * has binding name 'PointerToSOAP_ENV__Reason' for type '' */ #ifndef SOAP_TYPE_PointerToSOAP_ENV__Reason #define SOAP_TYPE_PointerToSOAP_ENV__Reason (21) #endif /* struct SOAP_ENV__Detail * has binding name 'PointerToSOAP_ENV__Detail' for type '' */ #ifndef SOAP_TYPE_PointerToSOAP_ENV__Detail #define SOAP_TYPE_PointerToSOAP_ENV__Detail (20) #endif /* struct SOAP_ENV__Code * has binding name 'PointerToSOAP_ENV__Code' for type '' */ #ifndef SOAP_TYPE_PointerToSOAP_ENV__Code #define SOAP_TYPE_PointerToSOAP_ENV__Code (14) #endif /* ns__sensorData * has binding name 'PointerTons__sensorData' for type 'ns:sensorData' */ #ifndef SOAP_TYPE_PointerTons__sensorData #define SOAP_TYPE_PointerTons__sensorData (9) #endif /* _QName has binding name '_QName' for type 'xsd:QName' */ #ifndef SOAP_TYPE__QName #define SOAP_TYPE__QName (6) #endif /* _XML has binding name '_XML' for type '' */ #ifndef SOAP_TYPE__XML #define SOAP_TYPE__XML (5) #endif /* char * has binding name 'string' for type 'xsd:string' */ #ifndef SOAP_TYPE_string #define SOAP_TYPE_string (4) #endif /******************************************************************************\ * * * Externals * * * \******************************************************************************/ #endif /* End of soapStub.h */
5c8e420eb3be37d898dd8dd1ebdb7f09f143924d
ae6c77d78818d1148ec068b64da357b4a56f5bf8
/fade away.ino
628dd384abc8d9710aa2844d609bc27f9f5855b2
[]
no_license
wenxiaoding/fade-away
e12e4b672c0422fccf04f4744405aaaf3832944d
73ea6eb40b67d65a14266b8291fef2a17dc76848
refs/heads/main
2023-02-07T05:15:33.851161
2020-12-29T04:35:48
2020-12-29T04:35:48
325,186,342
0
0
null
null
null
null
UTF-8
C++
false
false
2,259
ino
fade away.ino
#define ValueGap 405 //该数值可用砝码校准 long HX711_Buffer = 0; long Weight_Maopi = 0,Weight_Shiwu = 0; float Weight = 0; #define HX711_SCK A0 #define HX711_DT A1 int maxp=716; int p=0; void setup() { Init_Hx711(); //初始化HX711模块连接的IO设置 Serial.begin(115200); delay(1000); // Serial.print("Welcome to use!\n"); Get_Maopi(); } void loop() { Weight = Get_Weight(); //计算放在传感器上的重物重量 // Serial.print(Weight); //串口显示重量 // Serial.print(" g\n"); //显示单位 delay(100); //延时1s p=map(Weight ,0,1000,0,maxp); if(p<0) p=0; if(p>maxp) p=maxp; // Serial.println(String(p)+",0"); Serial.println(String(int(Weight))+",0"); } void Init_Hx711() { pinMode(HX711_SCK, OUTPUT); pinMode(HX711_DT, INPUT); } //**************************************************** //获取毛皮重量 //**************************************************** void Get_Maopi() { Weight_Maopi = HX711_Read(); } //**************************************************** //称重 //**************************************************** unsigned int Get_Weight() { HX711_Buffer = HX711_Read(); Weight_Shiwu = HX711_Buffer; Weight_Shiwu = Weight_Shiwu - Weight_Maopi; //获取实物的AD采样数值。 Weight_Shiwu = (int)((float)Weight_Shiwu/ValueGap+0.05); return Weight_Shiwu; } //**************************************************** //读取HX711 //**************************************************** unsigned long HX711_Read(void) //增益128 { unsigned long count; unsigned char i; bool Flag = 0; digitalWrite(HX711_DT, HIGH); delayMicroseconds(1); digitalWrite(HX711_SCK, LOW); delayMicroseconds(1); count=0; while(digitalRead(HX711_DT)); for(i=0;i<24;i++) { digitalWrite(HX711_SCK, HIGH); delayMicroseconds(1); count=count<<1; digitalWrite(HX711_SCK, LOW); delayMicroseconds(1); if(digitalRead(HX711_DT)) count++; } digitalWrite(HX711_SCK, HIGH); delayMicroseconds(1); digitalWrite(HX711_SCK, LOW); delayMicroseconds(1); count ^= 0x800000; return(count); }
bd518cbebb6004efcfd88c35427560fea069b9b5
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/core/scoring/methods/WaterSpecificEnergy.cc
51152c829bcbd26c962335cb4437e00d6c537912
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
4,404
cc
WaterSpecificEnergy.cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file core/scoring/methods/WaterSpecificEnergy.hh /// @brief Energetic considerations for explicit water molecules, // /// @author Joaquin Ambia, Jason K. Lai // Unit headers #include <core/scoring/methods/WaterSpecificEnergy.hh> #include <core/scoring/methods/WaterSpecificEnergyCreator.hh> // Package headers #include <core/scoring/methods/ContextIndependentOneBodyEnergy.hh> #include <core/scoring/ScoringManager.hh> #include <core/scoring/EnergyMap.hh> #include <core/scoring/Energies.hh> #include <core/scoring/EnergiesCacheableDataType.hh> #include <core/scoring/hbonds/HBEvalTuple.hh> #include <core/scoring/hbonds/HBondSet.hh> #include <core/scoring/hbonds/hbonds.hh> #include <core/scoring/hbonds/hbonds_geom.hh> #include <core/scoring/hbonds/HBondOptions.hh> // Project headers #include <core/conformation/Residue.hh> #include <core/pose/Pose.hh> #include <core/chemical/AtomType.hh> #include <utility/vector1.hh> #include <basic/datacache/BasicDataCache.hh> #include <basic/datacache/CacheableData.hh> // Options header #include <basic/options/option.hh> #include <basic/options/keys/hydrate.OptionKeys.gen.hh> #include <basic/options/keys/score.OptionKeys.gen.hh> namespace core { namespace scoring { namespace methods { /// @details This must return a fresh instance of the WaterSpecificEnergy class, /// never an instance already in use methods::EnergyMethodOP WaterSpecificEnergyCreator::create_energy_method( methods::EnergyMethodOptions const & ) const { return utility::pointer::make_shared< WaterSpecificEnergy >(); } ScoreTypes WaterSpecificEnergyCreator::score_types_for_method() const { ScoreTypes sts; sts.push_back( wat_desolv ); return sts; } /// ctor WaterSpecificEnergy::WaterSpecificEnergy() : parent( utility::pointer::make_shared< WaterSpecificEnergyCreator >() ) { using namespace basic::options; using namespace basic::options::OptionKeys::hydrate; using namespace basic::options::OptionKeys::score; // hydrate/SPaDES protocol wat_desolv_ = option[ water_desolvation ](); if ( !option[ water_desolvation ].user() ) { if ( option[ water_hybrid_sf ]() ) { wat_desolv_ = 4.8; } if ( option[ short_residence_time_mode ] ) { wat_desolv_ = wat_desolv_ / 2.0; } } } /// clone EnergyMethodOP WaterSpecificEnergy::clone() const { return utility::pointer::make_shared< WaterSpecificEnergy >( *this ); } ///////////////////////////////////////////////////////////////////////////// // methods for ContextIndependentOneBodyEnergies ///////////////////////////////////////////////////////////////////////////// /// void WaterSpecificEnergy::residue_energy( conformation::Residue const & rsd, pose::Pose const & pose, EnergyMap & emap ) const { // These terms are only meant to be used with water if ( rsd.name() != "TP3" ) return; // The term wat_desolv is the desolvation energy of a water, it is 0 if the molecules is in bulk water (away rotamers) // and it has a constant value if the molecule is near the protein // This might need to be revisited, for now we find away rotamers simply by their position, // We might actually want to check for neighbors if ( rsd.name() != "TP3" || rsd.xyz(1).x() > pose.residue(1).xyz(1).x() + 10000 ) emap[ wat_desolv ] = 0; else emap[ wat_desolv ] = wat_desolv_; } /// Real WaterSpecificEnergy::eval_dof_derivative( id::DOF_ID const &,// dof_id, id::TorsionID const &, // tor_id pose::Pose const &, // pose ScoreFunction const &, //sfxn EnergyMap const & // weights ) const { return 0.0; } /// @brief WaterSpecificEnergy is context independent; indicates that no /// context graphs are required void WaterSpecificEnergy::indicate_required_context_graphs( utility::vector1< bool > & ) const {} core::Size WaterSpecificEnergy::version() const { return 1; // Initial versioning } } // methods } // scoring } // core
8200908e2983fc5525ef82967df0ec464775c574
f62e37d6a8884960b8e315c61a924650d756df0d
/src/core/hw/gfxip/gfx9/gfx9PipelineChunkPs.cpp
2ef1e2efa50baec9038aa2b06097c1ccf9ff634b
[ "MIT" ]
permissive
ardacoskunses/pal
cd5f0dfd35912239c32e884005bd68b391bb96e0
ec4457f9b005dcb7a6178debc19b1df65da57280
refs/heads/master
2020-03-28T18:00:47.178244
2018-09-12T04:59:18
2018-09-12T05:06:04
148,844,552
0
0
MIT
2018-09-14T21:41:30
2018-09-14T21:41:30
null
UTF-8
C++
false
false
13,570
cpp
gfx9PipelineChunkPs.cpp
/* *********************************************************************************************************************** * * Copyright (c) 2015-2018 Advanced Micro Devices, Inc. All Rights Reserved. * * 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 "core/hw/gfxip/gfx9/gfx9CmdStream.h" #include "core/hw/gfxip/gfx9/gfx9CmdUtil.h" #include "core/hw/gfxip/gfx9/gfx9Device.h" #include "core/hw/gfxip/gfx9/gfx9PipelineChunkPs.h" #include "core/platform.h" #include "palPipeline.h" #include "palPipelineAbiProcessorImpl.h" using namespace Util; namespace Pal { namespace Gfx9 { // ===================================================================================================================== PipelineChunkPs::PipelineChunkPs( const Device& device) : m_device(device), m_pPsPerfDataInfo(nullptr) { memset(&m_pm4ImageSh, 0, sizeof(m_pm4ImageSh)); memset(&m_pm4ImageShDynamic, 0, sizeof(m_pm4ImageShDynamic)); memset(&m_pm4ImageContext, 0, sizeof(m_pm4ImageContext)); memset(&m_stageInfo, 0, sizeof(m_stageInfo)); m_stageInfo.stageId = Abi::HardwareStage::Ps; m_paScShaderControl.u32All = 0; } // ===================================================================================================================== // Initializes this pipeline chunk. void PipelineChunkPs::Init( const AbiProcessor& abiProcessor, const CodeObjectMetadata& metadata, const RegisterVector& registers, const PsParams& params) { const Gfx9PalSettings& settings = m_device.Settings(); m_pPsPerfDataInfo = params.pPsPerfDataInfo; uint16 lastPsInterpolator = mmSPI_PS_INPUT_CNTL_0; for (uint32 i = 0; i < MaxPsInputSemantics; ++i) { const uint16 offset = static_cast<uint16>(mmSPI_PS_INPUT_CNTL_0 + i); if (registers.HasEntry(offset, &m_pm4ImageContext.spiPsInputCntl[i].u32All)) { lastPsInterpolator = offset; } else { break; } } BuildPm4Headers(lastPsInterpolator); m_pm4ImageSh.spiShaderPgmRsrc1Ps.u32All = registers.At(mmSPI_SHADER_PGM_RSRC1_PS); m_pm4ImageSh.spiShaderPgmRsrc2Ps.u32All = registers.At(mmSPI_SHADER_PGM_RSRC2_PS); registers.HasEntry(mmSPI_SHADER_PGM_RSRC3_PS, &m_pm4ImageShDynamic.spiShaderPgmRsrc3Ps.u32All); // NOTE: The Pipeline ABI doesn't specify CU_GROUP_DISABLE for various shader stages, so it should be safe to // always use the setting PAL prefers. m_pm4ImageSh.spiShaderPgmRsrc1Ps.bits.CU_GROUP_DISABLE = (settings.psCuGroupEnabled ? 0 : 1); m_pm4ImageShDynamic.spiShaderPgmRsrc3Ps.bits.CU_EN = m_device.GetCuEnableMask(0, settings.psCuEnLimitMask); m_pm4ImageContext.dbShaderControl.u32All = registers.At(mmDB_SHADER_CONTROL); m_pm4ImageContext.paScAaConfig.reg_data = registers.At(mmPA_SC_AA_CONFIG); m_paScShaderControl.u32All = registers.At(mmPA_SC_SHADER_CONTROL); m_pm4ImageContext.spiBarycCntl.u32All = registers.At(mmSPI_BARYC_CNTL); m_pm4ImageContext.spiPsInputAddr.u32All = registers.At(mmSPI_PS_INPUT_ADDR); m_pm4ImageContext.spiPsInputEna.u32All = registers.At(mmSPI_PS_INPUT_ENA); m_pm4ImageContext.spiShaderColFormat.u32All = registers.At(mmSPI_SHADER_COL_FORMAT); m_pm4ImageContext.spiShaderZFormat.u32All = registers.At(mmSPI_SHADER_Z_FORMAT); m_pm4ImageContext.paScConservativeRastCntl.reg_data = registers.At(mmPA_SC_CONSERVATIVE_RASTERIZATION_CNTL); // Override the Pipeline ABI's reported COVERAGE_AA_MASK_ENABLE bit if the settings request it. if (settings.disableCoverageAaMask) { m_pm4ImageContext.paScConservativeRastCntl.reg_data &= ~PA_SC_CONSERVATIVE_RASTERIZATION_CNTL__COVERAGE_AA_MASK_ENABLE_MASK; } // Binner_cntl1: // 16 bits: Maximum amount of parameter storage allowed per batch. // - Legacy: param cache lines/2 (groups of 16 vert-attributes) (0 means 1 encoding) // - NGG: number of vert-attributes (0 means 1 encoding) // - NGG + PC: param cache lines/2 (groups of 16 vert-attributes) (0 means 1 encoding) // 16 bits: Max number of primitives in batch m_pm4ImageContext.paScBinnerCntl1.u32All = 0; m_pm4ImageContext.paScBinnerCntl1.bits.MAX_PRIM_PER_BATCH = settings.binningMaxPrimPerBatch - 1; if (params.isNgg) { // If we add support for off-chip parameter cache this code will need to be updated as well. PAL_ALERT(m_device.Parent()->ChipProperties().gfx9.primShaderInfo.parameterCacheSize != 0); m_pm4ImageContext.paScBinnerCntl1.bits.MAX_ALLOC_COUNT = settings.binningMaxAllocCountNggOnChip - 1; } else { m_pm4ImageContext.paScBinnerCntl1.bits.MAX_ALLOC_COUNT = settings.binningMaxAllocCountLegacy - 1; } // Compute the checksum here because we don't want it to include the GPU virtual addresses! params.pHasher->Update(m_pm4ImageContext); Abi::PipelineSymbolEntry symbol = { }; if (abiProcessor.HasPipelineSymbolEntry(Abi::PipelineSymbolType::PsMainEntry, &symbol)) { const gpusize programGpuVa = (symbol.value + params.codeGpuVirtAddr); PAL_ASSERT(programGpuVa == Pow2Align(programGpuVa, 256)); m_pm4ImageSh.spiShaderPgmLoPs.bits.MEM_BASE = Get256BAddrLo(programGpuVa); m_pm4ImageSh.spiShaderPgmHiPs.bits.MEM_BASE = Get256BAddrHi(programGpuVa); m_stageInfo.codeLength = static_cast<size_t>(symbol.size); } if (abiProcessor.HasPipelineSymbolEntry(Abi::PipelineSymbolType::PsShdrIntrlTblPtr, &symbol)) { const gpusize srdTableGpuVa = (symbol.value + params.dataGpuVirtAddr); m_pm4ImageSh.spiShaderUserDataLoPs.bits.DATA = LowPart(srdTableGpuVa); } if (abiProcessor.HasPipelineSymbolEntry(Abi::PipelineSymbolType::PsDisassembly, &symbol)) { m_stageInfo.disassemblyLength = static_cast<size_t>(symbol.size); } } // ===================================================================================================================== // Copies this pipeline chunk's sh commands into the specified command space. Returns the next unused DWORD in // pCmdSpace. uint32* PipelineChunkPs::WriteShCommands( CmdStream* pCmdStream, uint32* pCmdSpace, const DynamicStageInfo& vsStageInfo ) const { Pm4ImageShDynamic pm4ImageShDynamic = m_pm4ImageShDynamic; if (vsStageInfo.wavesPerSh > 0) { pm4ImageShDynamic.spiShaderPgmRsrc3Ps.bits.WAVE_LIMIT = vsStageInfo.wavesPerSh; } if (vsStageInfo.cuEnableMask != 0) { pm4ImageShDynamic.spiShaderPgmRsrc3Ps.bits.CU_EN &= vsStageInfo.cuEnableMask; } pCmdSpace = pCmdStream->WritePm4Image(m_pm4ImageSh.spaceNeeded, &m_pm4ImageSh, pCmdSpace); pCmdSpace = pCmdStream->WritePm4Image(pm4ImageShDynamic.spaceNeeded, &pm4ImageShDynamic, pCmdSpace); if (m_pPsPerfDataInfo->regOffset != UserDataNotMapped) { pCmdSpace = pCmdStream->WriteSetOneShReg<ShaderGraphics>(m_pPsPerfDataInfo->regOffset, m_pPsPerfDataInfo->gpuVirtAddr, pCmdSpace); } return pCmdSpace; } // ===================================================================================================================== // Copies this pipeline chunk's context commands into the specified command space. Returns the next unused DWORD in // pCmdSpace. uint32* PipelineChunkPs::WriteContextCommands( CmdStream* pCmdStream, uint32* pCmdSpace ) const { pCmdSpace = pCmdStream->WritePm4Image(m_pm4ImageContext.spaceNeeded, &m_pm4ImageContext, pCmdSpace); return pCmdSpace; } // ===================================================================================================================== // Assembles the PM4 headers for the commands in this pipeline chunk. void PipelineChunkPs::BuildPm4Headers( uint32 lastPsInterpolator) { const CmdUtil& cmdUtil = m_device.CmdUtil(); // Sets the following SH registers: SPI_SHADER_PGM_LO_PS, SPI_SHADER_PGM_HI_PS, // SPI_SHADER_PGM_RSRC1_PS, SPI_SHADER_PGM_RSRC2_PS. m_pm4ImageSh.spaceNeeded = cmdUtil.BuildSetSeqShRegs(mmSPI_SHADER_PGM_LO_PS, mmSPI_SHADER_PGM_RSRC2_PS, ShaderGraphics, &m_pm4ImageSh.hdrSpiShaderPgm); // Sets the following SH register: SPI_SHADER_USER_DATA_PS_1. m_pm4ImageSh.spaceNeeded += cmdUtil.BuildSetOneShReg(mmSPI_SHADER_USER_DATA_PS_0 + ConstBufTblStartReg, ShaderGraphics, &m_pm4ImageSh.hdrSpiShaderUserData); // Sets the following SH register: SPI_SHADER_PGM_RSRC3_PS. // We must use the SET_SH_REG_INDEX packet to support the real-time compute feature. m_pm4ImageShDynamic.spaceNeeded = cmdUtil.BuildSetOneShRegIndex(mmSPI_SHADER_PGM_RSRC3_PS, ShaderGraphics, index__pfp_set_sh_reg_index__apply_kmd_cu_and_mask, &m_pm4ImageShDynamic.hdrPgmRsrc3Ps); // Sets the following context register: // SPI_SHADER_Z_FORMAT, SPI_SHADER_COL_FORMAT. m_pm4ImageContext.spaceNeeded = cmdUtil.BuildSetSeqContextRegs(mmSPI_SHADER_Z_FORMAT, mmSPI_SHADER_COL_FORMAT, &m_pm4ImageContext.hdrSpiShaderFormat); // Sets the following context register: SPI_BARYC_CNTL. m_pm4ImageContext.spaceNeeded += cmdUtil.BuildSetOneContextReg(mmSPI_BARYC_CNTL, &m_pm4ImageContext.hdrSpiBarycCntl); // Sets the following context registers: SPI_PS_INPUT_ENA, SPI_PS_INPUT_ADDR. m_pm4ImageContext.spaceNeeded += cmdUtil.BuildSetSeqContextRegs(mmSPI_PS_INPUT_ENA, mmSPI_PS_INPUT_ADDR, &m_pm4ImageContext.hdrSpiPsInput); // Sets the following context register: DB_SHADER_CONTROL. m_pm4ImageContext.spaceNeeded += cmdUtil.BuildSetOneContextReg(mmDB_SHADER_CONTROL, &m_pm4ImageContext.hdrDbShaderControl); // Sets the following context register: PA_SC_BINNER_CNTL_1. m_pm4ImageContext.spaceNeeded += cmdUtil.BuildSetOneContextReg(mmPA_SC_BINNER_CNTL_1, &m_pm4ImageContext.hdrPaScBinnerCntl1); m_pm4ImageContext.spaceNeeded += cmdUtil.BuildContextRegRmw( mmPA_SC_AA_CONFIG, static_cast<uint32>(PA_SC_AA_CONFIG__COVERAGE_TO_SHADER_SELECT_MASK), 0, &m_pm4ImageContext.paScAaConfig); m_pm4ImageContext.spaceNeeded += cmdUtil.BuildContextRegRmw( mmPA_SC_CONSERVATIVE_RASTERIZATION_CNTL, static_cast<uint32>(PA_SC_CONSERVATIVE_RASTERIZATION_CNTL__COVERAGE_AA_MASK_ENABLE_MASK | PA_SC_CONSERVATIVE_RASTERIZATION_CNTL__UNDER_RAST_ENABLE_MASK), 0, // filled in by the "Init" function &m_pm4ImageContext.paScConservativeRastCntl); // Sets the following context registers: SPI_PS_INPUT_CNTL_0 - SPI_PS_INPUT_CNTL_X. m_pm4ImageContext.spaceNeeded += m_device.CmdUtil().BuildSetSeqContextRegs(mmSPI_PS_INPUT_CNTL_0, lastPsInterpolator, &m_pm4ImageContext.hdrSpiPsInputCntl); } // ===================================================================================================================== regPA_SC_SHADER_CONTROL PipelineChunkPs::PaScShaderControl( uint32 numIndices ) const { regPA_SC_SHADER_CONTROL paScShaderControl = m_paScShaderControl; return paScShaderControl; } } // Gfx9 } // Pal
2112d42cfd535a02d9c896fdd3c694f8cc1fceb4
a68c444d56d0bb6b5e0bb8ccbb76bfb081ba6b07
/CowNetControllerV4/us/cownet/lamps/simple/SimpleGreyscaleLampPattern.h
2aade3eaa6807b890c954965ef9ddc26ce9c0d48
[]
no_license
fitzpatricksrus/Pinduino
03040b99bdc27daecf6743a63a1a9a5d6f1b0a51
45bfdd5ca34163dc44ceb91380d36a7307c4f2df
refs/heads/master
2020-04-06T07:05:09.429566
2016-06-30T02:23:51
2016-06-30T02:23:51
24,709,921
2
0
null
null
null
null
UTF-8
C++
false
false
632
h
SimpleGreyscaleLampPattern.h
/* * SimpleGreyscaleLampPattern.h * * Created on: Jun 3, 2015 * Author: jfitzpatrick */ #ifndef SIMPLEGREYSCALELAMPPATTERN_H_ #define SIMPLEGREYSCALELAMPPATTERN_H_ #include <Arduino.h> namespace us_cownet_lamps_simple { class SimpleGreyscaleLampPattern { public: SimpleGreyscaleLampPattern(); virtual ~SimpleGreyscaleLampPattern(); virtual byte** getPattern(); virtual void setPattern(byte** pattern); virtual byte getLamp(int col, int row); virtual void setLamp(int col, int row, byte value); private: byte** pattern; }; } /* namespace us_cownet_lamps_simple */ #endif /* SIMPLEGREYSCALELAMPPATTERN_H_ */
e024053f61a8811304f43dea89617490cef36520
25f2e4653573fd51200b89e2feea4d9cab1a4c45
/CE_Summative.ino
768209f1778f613b205a49055603343bf417ab96
[]
no_license
HannahGuo/JustPlay
b7f9578359b1fcdbf4672ec15c94df87689fbabf
eb9583a754c6fd20f4d916cc452ba823f4266391
refs/heads/master
2020-03-20T10:13:33.351996
2018-06-24T00:46:54
2018-06-24T00:46:54
137,363,236
0
0
null
null
null
null
UTF-8
C++
false
false
8,176
ino
CE_Summative.ino
#include <TimeLib.h> // imports the time library for the milliseconds function #include <LiquidCrystal.h> // imports a library to control the LCD #include <pitches.h> // imports a library that has the notes for the buzzer #define buzzerID 0 // Signal port for buzzer #define scaler 1.0 // Scaler for note playing const int redButton = 2; // Corresponds with the button with a red signal wire const int yellowButton = 3; // Corresponds with the button with a yellow signal wire const int greenButton = 4; // Corresponds with the button with a green signal wire const int blueButton = 5; // Corresponds with the button with a blue signal wire const int whiteButton = 6; // Corresponds with the button with a white signal wire const int ledPort = 0; // Port for the LED // Defines the LCD const int rs = 7, en = 8, d4 = 9, d5 = 10, d6 = 11, d7 = 12; const LiquidCrystal lcd(rs, en, d4, d5, d6, d7); int score = 0; // Keeps count of score // Various Songs, stored as integer arrays. int marySong[] = {3, 2, 1, 2, 3, 3, 3, 2, 2, 2, 3, 5, 5, 3, 2, 1, 2, 3, 3, 3, 3, 2, 2, 3, 2, 1}; // mary had a little lamb int hotCrossSong[] = {3, 2, 1, 3, 2, 1, 3, 3, 3, 2, 2, 2, 3, 2, 1}; // hot cross buns int scale[] = {1, 2, 3, 4, 5, 5, 4, 3, 2, 1}; // scale int jingle[] = {3, 3, 3, 3, 3, 3, 3, 5, 1, 2, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 2, 2, 3, 2, 5}; // jingle bells int spider[] = {5, 1, 1, 1, 2, 3, 3, 3, 2, 3, 1, 3, 3, 4, 5, 5, 4, 3, 4, 5, 3, 1, 1, 2, 3, 3, 2, 1, 2, 3, 1, 5, 5, 1, 1, 1, 2, 3, 3, 3, 2, 1, 2, 3, 1}; // itsy bitsy spider // An array that saves the letter values of the notes const String noteValues[] = {"C", "D", "E", "F", "G"}; void setup() { // runs once when the Arduino starts up // Set each button as an input. Note that when these pins are read from, a LOW output means that the button was pressed, and a HIGH output means it wasn't. pinMode(redButton, INPUT_PULLUP); pinMode(yellowButton, INPUT_PULLUP); pinMode(greenButton, INPUT_PULLUP); pinMode(blueButton, INPUT_PULLUP); pinMode(whiteButton, INPUT_PULLUP); pinMode(ledPort, OUTPUT); // Set the LED port to an output digitalWrite(1, LOW); // Initially set the LED off (LOW) lcd.begin(16, 2); // Begin the LCD display } void loop() { // runs continuously in a loop mainInterface(); // Run the main interface } void playSong(int *song) { // this function plays the song passed in as a parameter bool correctPress = false; // set correctPress to false since the user hasn't hit the right button yet bool turn = false; // set turn to false since the user hasn't taken a turn yet for (int i = 0; i < sizeof(song) / sizeof(song[0]) ; i++) { // loop through the notes of the song lcd.setCursor(0, 0); // set the location of the cursor lcd.print("Note # :" + (String) (i + 1) + " - " + (String) noteValues[song[i] - 1] + " "); // shows the current note on the LCD double currentMill = millis(); // gets current time while (millis() - currentMill < 2000) { // this loop acts as a timer, since it will run until about 2 seconds has passed. if ((digitalRead(song[i] + 1) == LOW) and oneButtonPressed()) { // check if the user hit the correct button, and only one button was pressed at the time playNote(song[i]); // play the note on the buzzer digitalWrite(1, HIGH); // turn the LED on (HIGH) correctPress = true; // set correctPress to true break; // break out of this time loop } turn = true; // the user has take their turn, so set turn to true } if (turn) { // if the user took their turn lcd.setCursor(0, 1); // set the location of the cursor to the second row if (correctPress) { // if the user pressed the correct button score += 1; // add one to their score lcd.print("Correct! "); // print "Correct!" to the LCD correctPress = false; // reset correctPress to false } else { // otherwise, they didn't press the right button lcd.print("Incorrect!"); // print "Incorrect!" to the LCD digitalWrite(1, LOW); // turn the LED off } turn = false; // reset turn to false } } double currentMill = millis(); // get current time in milliseconds while (millis() - currentMill < 2000) { // this loop acts as a timer, since it will run until about 2 seconds has passed. lcd.print("Song Finished!"); // print that the song has finished to the LCD lcd.setCursor(0, 1); // set the position of the cursor to the second row lcd.print("Final Score: " + (String) score + "/" + (String) (sizeof(song) / sizeof(song[0]))); // show the final score on the LCD } lcd.setCursor(0, 0); // set the cursor to the first row lcd.print("Final Score: " + (String) score + "/" + (String) (sizeof(song) / sizeof(song[0]))); // show the final score on the LCD lcd.setCursor(0, 1); // set the cursor to the second row lcd.print("Awaiting restart."); // print "Awaiting restart." to the LCD while (true) { // runs until a button was pressed if (anyButtonPressed()) { // checks if a button was pressed score = 0; // resets score mainInterface(); //returns to main interface } } } void mainInterface() { // This function is the main interface of the program lcd.setCursor(0, 0); // Set the location of the cursor to the start of the first tow lcd.print("Select"); // Print select to the LCD if (oneButtonPressed()) { // Check if only one button was pressed // The following code plays a song based on the button pressed. if (digitalRead(redButton) == LOW) { // Check if the red wired button was pressed playSong(marySong); // plays Mary had a Little Lamb } else if (digitalRead(yellowButton) == LOW) { // Check if the yellow wired button was pressed playSong(hotCrossSong); // plays Hot Cross Buttons } else if (digitalRead(greenButton) == LOW) { // Check if the green wired button was pressed playSong(scale); // plays a simple scale } else if (digitalRead(blueButton) == LOW) { // Check if the blue wired button was pressed playSong(jingle); // plays Jingle Bells } else if (digitalRead(whiteButton) == LOW) { // Check if the white wired button was pressed playSong(spider); // plays the itsy bitsy spider } } } void playNote(int note) { // This function plays a note on a buzzer int noteID = 0; // holds the noteID that will be changed in the switch case float duration = 3000 / 6; // how long to play the note for switch (note) { // switch case that determines which note to play based on the note passed into the function. Each case assigns noteID to the appropriate note to be played case 1: // plays a low C noteID = NOTE_C4; break; case 2: // plays a low D noteID = NOTE_D4; break; case 3: // plays a low E noteID = NOTE_E4; break; case 4: // plays a low F noteID = NOTE_F4; break; case 5: // plays a low G noteID = NOTE_G4; break; } tone(buzzerID, noteID, duration); // play the note on the buzzer delay(duration * scaler); // add a delay so the note sounds proper } bool anyButtonPressed() { // This function checks if any button has been pressed. It returns a true/false boolean. return digitalRead(redButton) == LOW or digitalRead(yellowButton) == LOW or digitalRead(greenButton) == LOW or digitalRead(blueButton) == LOW or digitalRead(whiteButton) == LOW; } bool oneButtonPressed() { // This function makes sure only one button was pressed (uses XOR). It returns a true/false boolean. return digitalRead(redButton) == LOW ^ digitalRead(yellowButton) == LOW ^ digitalRead(greenButton) == LOW ^ digitalRead(blueButton) == LOW ^ digitalRead(whiteButton) == LOW; }
56957a309ffeec43bd9488c64edeb0759090202b
8c925d9e1aa4a299089bd2cfdf6aa4100e63dacb
/TP1/TDS/Medecin.h
ea9bb02769c48ebe43c6412b5fd4612db98a9abf
[]
no_license
loic294/TPs-INF1010
1934530aa59c91e08e89f6451f3458aa333d3faa
3895d9a21531616cda30e61e08ce3a04236da818
refs/heads/master
2021-03-24T10:27:00.389482
2017-02-19T18:53:56
2017-02-19T18:54:11
80,391,245
0
0
null
null
null
null
UTF-8
C++
false
false
883
h
Medecin.h
/******************************************** * Titre: Travail pratique #1 - Medecin.cpp * Date: 31 janvier 2017 * Auteur: Julien Bergeron (1829496) et Loic Bellemare-Alford (1846135) *******************************************/ #ifndef MEDECIN_H #define MEDECIN_H #include <string> #include "Specialiste.h" using namespace std; class Medecin { public: // Constructeurs par defaut et par parametre Medecin(); Medecin(string nom, int horaires, Specialiste* uneSpecialiste); //destructeur ~Medecin(); // Methodes d'acces string obtenirNom() const; int obtenirHoraires() const; Specialiste obtenirSpecialiste() const; // Methodes de modification void modifierNom(string nom); void modifierHoraires(int horaires); void modifierSpecialiste(Specialiste* specialite); private: // Variables privees string nom_; int horaires_; Specialiste* specialite_; }; #endif
555ab69df9059976e8c8253f112edf897f64dc96
574e5be8595ab272d5414e2f09dad27d75624d8e
/Assign3/Interval.h
c5c723d3c83236c14a257141dda8af01307a3259
[]
no_license
VolrathTheFallen/DVA222-Assign3
460e72df150d5dd3013d0000bc34dc9f7ee2f3a5
bb873279e41467b8748b836de3f859ee217c6775
refs/heads/master
2021-01-13T02:18:38.045620
2015-05-08T12:25:19
2015-05-08T12:25:19
35,118,247
0
0
null
null
null
null
UTF-8
C++
false
false
198
h
Interval.h
#ifndef INTERVAL_H #define INTERVAL_H class Interval { public: int from; int to; Interval(); Interval(int from, int to); static int CompareInterval(const void* l, const void* r); }; #endif
fcbbba1ae77cdad207950b25f611661d34ad094d
33f8a1164c44b4ade4a1ae9edca25a5d631b14dc
/Sprite.h
67580ba8052734999b7f1252e2ee2af42029df4d
[]
no_license
kuribohlv9/Skelly_Dungeon
fe2ef781c3e4169ef7300a3af1347ee7f18bf4a3
01d8d165a3d045b58b467a5e5c4594ba6c92a115
refs/heads/master
2020-04-30T09:03:41.956469
2015-02-07T15:29:12
2015-02-07T15:29:12
28,010,758
0
0
null
null
null
null
UTF-8
C++
false
false
321
h
Sprite.h
// Sprite.h #ifndef SPRITE_H_INCLUDED #define SPRITE_H_INCLUDED class Sprite { public: Sprite(SDL_Texture* texture); virtual ~Sprite(); SDL_Rect* GetRegion(); SDL_Texture* GetTexture(); virtual void Update(float deltatime); protected: SDL_Rect m_region; SDL_Texture* m_texture; }; #endif // SPRITE_H_INCLUDED
33cf74bcc90cb28f369771051e5d9818f2f1b445
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_old_hunk_670.cpp
a29ce1e0a7232a941220daccab69cdbc3fbe54d4
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
223
cpp
Kitware_CMake_old_hunk_670.cpp
if(res) return res; Curl_safefree(*allocuserpwd); *allocuserpwd = aprintf("%sAuthorization: %s\r\n", proxy ? "Proxy-" : "", conn->response_header);
6af434b2351c61e14a23e5d508def09271ad72fc
1684eccb401fb70871857b8fc547e3d2b8f99132
/libraries/YarpPlugins/CuiAbsolute/IPositionControl2RawImpl.cpp
54e56cfed297a7215e987959698cbf5e7d226014
[]
no_license
David-Estevez/yarp-devices
ae9b07d0b1b9e91abf6b472d8469d5c8cc127d3f
1632d72a7f6a2bf601dac52628226e4a1f319472
refs/heads/develop
2021-01-23T08:04:13.529029
2018-10-25T11:15:17
2018-10-25T11:15:17
86,474,242
0
0
null
2017-03-28T15:06:49
2017-03-28T15:06:48
null
UTF-8
C++
false
false
6,833
cpp
IPositionControl2RawImpl.cpp
// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- #include "CuiAbsolute.hpp" // ------------------ IPositionControlRaw Related ---------------------------------------- bool roboticslab::CuiAbsolute::getAxes(int *ax) { *ax = 1; return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::positionMoveRaw(int j, double ref) // encExposed = ref; { CD_INFO("(%d,%f)\n",j,ref); //-- Check index within range if ( j != 0 ) return false; CD_WARNING("Not implemented yet (CuiAbsolute).\n"); return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::positionMoveRaw(const double *refs) { CD_ERROR("Missing implementation\n"); return false; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::relativeMoveRaw(int j, double delta) { CD_INFO("(%d, %f)\n",j,delta); //-- Check index within range if ( j != 0 ) return false; CD_WARNING("Not implemented yet (CuiAbsolute).\n"); return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::relativeMoveRaw(const double *deltas) { CD_ERROR("Missing implementation\n"); return false; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::checkMotionDoneRaw(int j, bool *flag) { CD_INFO("(%d)\n",j); //-- Check index within range if ( j != 0 ) return false; *flag = true; return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::checkMotionDoneRaw(bool *flag) { CD_ERROR("Missing implementation\n"); return false; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::setRefSpeedRaw(int j, double sp) { CD_INFO("(%d, %f)\n",j,sp); //-- Check index within range if ( j != 0 ) return false; return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::setRefSpeedsRaw(const double *spds) { CD_ERROR("Missing implementation\n"); return false; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::setRefAccelerationRaw(int j, double acc) { CD_INFO("(%d, %f)\n",j,acc); //-- Check index within range if ( j != 0 ) return false; return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::setRefAccelerationsRaw(const double *accs) { CD_ERROR("Missing implementation\n"); return false; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::getRefSpeedRaw(int j, double *ref) { CD_INFO("(%d)\n",j); //-- Check index within range if ( j != 0 ) return false; *ref = 0; return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::getRefSpeedsRaw(double *spds) { CD_ERROR("Missing implementation\n"); return false; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::getRefAccelerationRaw(int j, double *acc) { CD_INFO("(%d)\n",j); //-- Check index within range if ( j != 0 ) return false; *acc = 0; return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::getRefAccelerationsRaw(double *accs) { CD_ERROR("Missing implementation\n"); return false; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::stopRaw(int j) { CD_INFO("(%d)\n",j); //-- Check index within range if ( j != 0 ) return false; return true; } bool roboticslab::CuiAbsolute::stopRaw() { CD_ERROR("Missing implementation\n"); return false; } // -------------------------- IPositionControl2Raw Related ---------------------------- bool roboticslab::CuiAbsolute::positionMoveRaw(const int n_joint, const int *joints, const double *refs) { CD_WARNING("Missing implementation\n"); return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::relativeMoveRaw(const int n_joint, const int *joints, const double *deltas) { CD_WARNING("Missing implementation\n"); return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::checkMotionDoneRaw(const int n_joint, const int *joints, bool *flags) { CD_WARNING("Missing implementation\n"); return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::setRefSpeedsRaw(const int n_joint, const int *joints, const double *spds) { CD_WARNING("Missing implementation\n"); return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::setRefAccelerationsRaw(const int n_joint, const int *joints, const double *accs) { CD_WARNING("Missing implementation\n"); return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::getRefSpeedsRaw(const int n_joint, const int *joints, double *spds) { CD_WARNING("Missing implementation\n"); return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::getRefAccelerationsRaw(const int n_joint, const int *joints, double *accs) { CD_WARNING("Missing implementation\n"); return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::stopRaw(const int n_joint, const int *joints) { CD_WARNING("Missing implementation\n"); return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::getTargetPositionRaw(const int joint, double *ref) { CD_INFO("\n"); *ref = targetPosition; return true; } // ----------------------------------------------------------------------------- bool roboticslab::CuiAbsolute::getTargetPositionsRaw(double *refs) { CD_WARNING("Missing implementation\n"); return true; } bool roboticslab::CuiAbsolute::getTargetPositionsRaw(const int n_joint, const int *joints, double *refs) { CD_WARNING("Missing implementation\n"); return true; }
5ce608878ae71cbcc6fbc363358805d9527f2330
b7056c4edc0ecb087fb6bc7a199d267e58df3f91
/AnnihilationCharacter/AnnihilationCharacter/generic/Latter.hpp
7c268815d157eb94b35ca870dc7777e3889470f1
[]
no_license
elipmoc/AnnihilationCharacter
e9e7276c9eb01b3c89d92a2e25cb861a936d1089
6fda4c8bb69f6bb3e89682018fb2f9603d92b6c4
refs/heads/master
2020-12-02T19:19:29.642985
2017-07-15T05:16:18
2017-07-15T05:16:18
96,323,975
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,811
hpp
Latter.hpp
#pragma once #include <string> #include "DrawObject.hpp" #include "generic\Utility.hpp" #include "DxLib.h" namespace generic{ //画面に文字を表示するオブジェクト class Letter :DrawObject { //フォントハンドル int fontHandle; //文字のカラー unsigned int color; //文字列の縦幅横幅 Vect rect; //表示する文字 std::string text; //文字拡大率 Vect scale; //中心点 Vect anchor; //角度 double angle; //透過度 int opacity=0; protected: //ゲッターセッター virtual const Vect GetScale() const{ return scale; } virtual void SetScale(const Vect& _scale) { scale = _scale; } virtual const std::string GetText()const { return text; } virtual void SetText(const std::string& _text) { text = _text; rect.x = dx::GetDrawStringWidth(text.c_str, text.length()); } virtual const double GetAngle()const { return angle; } virtual void SetAngle(const double _angle){ angle=_angle; } virtual const Vect GetAnchor()const { return anchor; } virtual void SetAnchor(const Vect& _anchor) { anchor = _anchor; } virtual const unsigned int GetColor()const { return color; } virtual void SetColor(const unsigned int _color){ color=_color; } public: //コンストラクタ Letter(const std::string& _text, unsigned int _color) { color = _color; SetText(_text); } Letter(const std::string& _text) { SetText(_text); } Letter() {} //描画処理 void Update()override { dx::SetDrawBlendMode(DX_BLENDMODE_ALPHA, opacity); dx::DrawRotaStringToHandle(GetPos().x, GetPos().y, scale.x, scale.y, anchor.x*rect.x, anchor.y * 16, generic::ToRad(angle), color,fontHandle, color, FALSE, text.c_str()); dx::SetDrawBlendMode(DX_BLENDGRAPHTYPE_NORMAL, 0); } }; }
8b9d4359ea50482332a13f6d4624708e18f3fc02
f7f09782d15ee7bdd14e637bd717dfb8327bc57c
/2014Train/VJ/17/A.cpp
a00a1bbe6425a6b231a9483194e63435b6c9609f
[]
no_license
whywhyzhang/ACM-ICPC-Code
14f3f6b0532c18da9694d7f70914a97e0983913f
d15bd475774ff104ebfe9504f8ea0acffdb5ddb0
refs/heads/master
2022-12-09T06:27:14.893967
2017-03-09T14:31:49
2017-03-09T14:31:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,016
cpp
A.cpp
#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <time.h> using namespace std; const int MaxL=500005; const int MaxC=26; int que[MaxL]; int first,last; struct AC_auto { int next[MaxL][MaxC],fail[MaxL],word[MaxL]; int root,Tp; int Newnode() { // for(int i=0;i<MaxC;++i) // next[Tp][i]=-1; memset(next[Tp],-1,sizeof(next[Tp])); word[Tp++]=0; return Tp-1; } void Init() { Tp=0; root=Newnode(); first=last=0; } void Insert(char s[]) { int p=root; for(int i=0;s[i];++i) { if(next[p][s[i]-'a']==-1) next[p][s[i]-'a']=Newnode(); p=next[p][s[i]-'a']; } ++word[p]; } void Build() { int p,temp; fail[root]=-1; que[last++]=root; while(last-first) { p=que[first++]; for(int i=0;i<MaxC;++i) if(next[p][i]!=-1) { if(p==root) fail[next[p][i]]=root; else { temp=fail[p]; while(temp!=-1) { if(next[temp][i]!=-1) { fail[next[p][i]]=next[temp][i]; break; } temp=fail[temp]; } if(temp==-1) fail[next[p][i]]=root; } que[last++]=next[p][i]; } } } int Query(char s[]) { int p=root,temp; int ret=0; for(int i=0;s[i];++i) { while(p!=root && next[p][s[i]-'a']==-1) p=fail[p]; if(next[p][s[i]-'a']!=-1) p=next[p][s[i]-'a']; else p=root; temp=p; while(temp!=rooti && word[temp]) { ret+=word[temp]; word[temp]=0; temp=fail[temp]; } } return ret; } }; AC_auto myAC; char s[1000006]; int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int T; scanf("%d",&T); while(T--) { int n; myAC.Init(); scanf("%d",&n); while(n--) { scanf("%s",s); myAC.Insert(s); } myAC.Build(); scanf("%s",s); printf("%d\n",myAC.Query(s)); } return 0; }
7c7d304f1839bd11273563492e93216639f188b2
7556139eba33cbbbf0e0262c69e9c8b56e08a399
/include/RED4ext/Scripting/Natives/Generated/CTextureArray.hpp
3b5868823fbcd8bd28a1298fd6ee1756cfbc5f0c
[ "MIT" ]
permissive
vandermerwewaj/RED4ext.SDK
3ef7563a1855e6206097fdf6c5b44ae1c1c2c20d
9dd544a221a39f27c8d38aa23a607b31aba1715a
refs/heads/master
2023-09-05T06:32:39.278419
2021-11-22T15:01:18
2021-11-22T15:01:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
848
hpp
CTextureArray.hpp
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/Scripting/Natives/Generated/ITexture.hpp> #include <RED4ext/Scripting/Natives/Generated/STextureGroupSetup.hpp> #include <RED4ext/Scripting/Natives/Generated/rend/RenderTextureResource.hpp> namespace RED4ext { struct IRenderResourceBlob; struct CTextureArray : ITexture { static constexpr const char* NAME = "CTextureArray"; static constexpr const char* ALIAS = NAME; uint8_t unk40[0x58 - 0x40]; // 40 STextureGroupSetup setup; // 58 Handle<IRenderResourceBlob> renderResourceBlob; // 68 uint8_t unk78[0x80 - 0x78]; // 78 rend::RenderTextureResource renderTextureResource; // 80 }; RED4EXT_ASSERT_SIZE(CTextureArray, 0x90); } // namespace RED4ext
11744f3e00595ec10e6b7af0a42b7ba01fb2eead
561dd3af726151ec2fa7f23680108883a265fd95
/OFProject 1/src/ofApp.cpp
d845122f10e3bd75caa7ff497c399cc76e080431
[]
no_license
jessica0427/Project-1
41f2e0b00b5a295b4ea9301ad2af87632e5206a6
3fcc297c0bddbd9e7a1be81218bd215c636c4d90
refs/heads/master
2022-06-18T02:54:05.064366
2020-05-08T23:17:09
2020-05-08T23:17:09
255,390,729
0
0
null
null
null
null
UTF-8
C++
false
false
3,641
cpp
ofApp.cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetFrameRate(60); ofSetBackgroundAuto(false); ofBackground(0, 0, 0); ofEnableBlendMode(OF_BLENDMODE_ALPHA); control = true; } //-------------------------------------------------------------- void ofApp::update(){ theta = PI / 2 + PI / 2 / 700 * pos.size(); //theta of raindrops, perpendicular = PI / 2 float speed = pos.size() / 15;; //a speed of raindrops for(int i = 0; i < pos.size(); i++) { //convert speed from vector to x, y ofVec2f vel; vel.x = ofGetHeight() / 2300.0f * (length[i] + speed) * cos(theta + noise[i]); vel.y = ofGetHeight() / 2300.0f * (length[i] + speed) * sin(theta + noise[i]); pos[i].x += vel.x; pos[i].y += vel.y; //if a raindrop reaches the bottom of window, it will return to the first position if(pos[i].y - length[i] * sin(theta + noise[i]) > ofGetHeight()){ pos[i].y = 0; pos[i].x -= vel.x * (ofGetHeight() / vel.y); } } } //-------------------------------------------------------------- void ofApp::draw(){ ofSetColor(0, 0, 0, 150); ofRectangle(0, 0, ofGetWidth(), ofGetHeight()); //fadeout ofSetColor(173, 216, 230); //color of letters and raindrops for(int i = 0; i < pos.size(); i++) { //coordinate of a raindrop float x1 = pos[i].x; float y1 = pos[i].y; float x2 = pos[i].x - length[i] * cos(theta + noise[i]); float y2 = pos[i].y - length[i] * sin(theta + noise[i]); ofSetLineWidth(length[i] / 30); //width of a raindrop ofDrawLine(x1, y1, x2, y2); //draw a raindrop } //log if(control == true){ string log; log = "raindrops num = " + ofToString(pos.size(), 0) + "\n"; log += "ofSetFrameRate = " + ofToString(ofGetFrameRate(), 4) + "\n"; log += "1:add 5 raindrops, 2:subtract 5 raindrops \n"; log += "c:clear raindrops num, f:fullScreen \n"; log += "press spacekey to change log on/off"; ofDrawBitmapString(log, 20, 20); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if(key == '1'){ //add 5 raindrops for(int i = 0; i < 5; i++){ //define first position ofVec2f p; float x = ofRandom(ofGetWidth() + ofGetHeight()); p.set(x, 0); pos.push_back(p); //define length float l = ofRandom(ofGetHeight() / 60, ofGetHeight() / 10); length.push_back(l); //define speed ofVec2f v; float vx = length[length.size() - 1] / 10 * cos(theta); float vy = length[length.size() - 1] / 10 * sin(theta); v.set(vx, vy); velocity.push_back(v); //define noise of slant float n; n = ofRandom(-PI/90, PI/90); noise.push_back(n); } } if(key == '2'){ //subtract 5 raindrops if(pos.size() > 0){ for(int i = 0; i < 5; i++){ pos.pop_back(); length.pop_back(); velocity.pop_back(); noise.pop_back(); } } } if(key == 'c'){ //clear raindrops pos.clear(); length.clear(); velocity.clear(); noise.clear(); } if(key == 'f'){ ofSetFullscreen(true); } if(key == ' '){ //state of log log control =! control; } }
e883c1d3025dcc4c704d42869e754063a21d2f87
8bb6d8ce77b9064da19fe3915a706904223f3f0a
/LeetCode/0452 - Minimum Number of Arrows to Burst Balloons.cpp
1e56e5e79f91ab98c2619a385bbc24e0c0375714
[]
no_license
wj32/Judge
8c92eb2c108839395bc902454030745b97ed7f29
d0bd7805c0d441c892c28a718470a378a38e7124
refs/heads/master
2023-08-16T19:16:59.475037
2023-08-02T03:46:12
2023-08-02T03:46:12
8,853,058
6
10
null
null
null
null
UTF-8
C++
false
false
494
cpp
0452 - Minimum Number of Arrows to Burst Balloons.cpp
class Solution { public: int findMinArrowShots(vector<pair<int, int>>& points) { sort(points.begin(), points.end()); long long end = numeric_limits<long long>::min(); int count = 0; for (const auto& p : points) { if (p.first <= end) { end = min(end, static_cast<long long>(p.second)); } else { count++; end = p.second; } } return count; } };
ed64618d307b8df329a6a8008e305bacaddc413b
1c390cd4fd3605046914767485b49a929198b470
/spoj/HK.cpp
8d78edd72900de87b8cf82d95db680b46aebe787
[]
no_license
wwwwodddd/Zukunft
f87fe736b53506f69ab18db674311dd60de04a43
03ffffee9a76e99f6e00bba6dbae91abc6994a34
refs/heads/master
2023-01-24T06:14:35.691292
2023-01-21T15:42:32
2023-01-21T15:42:32
163,685,977
7
8
null
null
null
null
UTF-8
C++
false
false
782
cpp
HK.cpp
#include <bits/stdc++.h> using namespace std; const int p = 1000000007; int t, n, m; int f[501][1001]; int main() { scanf("%d", &t); for (int tt = 0; tt < t; tt++) { scanf("%d%d", &n, &m); double z = 0; f[0][0] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j <= m; j++) { f[i + 1][j] = f[i][j] * 32LL % p; } long long x; scanf("%lld", &x); for (int j = 0; j < 32; j++) { if (x >> j & 1) { z += pow(2, j) * 31; } else { z += pow(2, j); } } for (int j = 0; j < 32; j++) { for (long long k = 0; k <= m - (x ^ (1LL << j)); k++) { long long nk = k + (x ^ (1LL << j)); f[i + 1][nk] = (f[i + 1][nk] + f[i][k]) % p; } } } printf("%d %.6f\n", f[n][m], z / 64); } return 0; }
e6ed258de5042532ab6c4bd2ccffef633820b2c6
bc31e7497ca3421a32afa3a55c65f9882a1ad452
/src/main.cpp
796239ace837a29f05f1b12c2279b9b0d0013295
[ "BSD-2-Clause" ]
permissive
a9650615/qtCanvas
d8ac582de999c74a6ba022d0b4d6e0ccd7878135
ad84a034cbca3abcc374208b6ee1c9687dccbc3f
refs/heads/master
2020-07-28T15:14:55.896518
2019-09-19T08:26:54
2019-09-19T08:26:54
209,448,700
0
0
null
null
null
null
UTF-8
C++
false
false
427
cpp
main.cpp
#include <QApplication> #include <QQmlApplicationEngine> #include <QtQml> #include <QtGui/QGuiApplication> #include "colorMarker.h" int main(int argc, char** argv) { QApplication app(argc, argv); // load custom c++ module qmlRegisterType<ColorMarker>("io.qt.colormarker", 1, 0, "ColorMarker"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
fb8f0f059ce2e86a60683c9693e360f40acd482c
303e592c312459bf9eb3ce231b1357c4de91124b
/pku/2601/2601.cpp
75e0b98437341c3796064e9f6f98887ae824d205
[]
no_license
kohyatoh/contests
866c60a1687f8a59d440da3356c6117f9596e8ce
b3dffeaf15564d57aec5c306f5f84bd448bc791f
refs/heads/master
2021-01-17T15:06:23.216232
2016-07-18T14:06:05
2016-07-18T14:06:05
2,369,261
0
1
null
null
null
null
UTF-8
C++
false
false
452
cpp
2601.cpp
#include <stdio.h> #define rep(i, n) for(int i=0; i<(int)(n); i++) int n; double x, a[5000], c[5000]; double calc(double a1) { a[1]=a1; rep(i, n) a[i+2]=2*a[i+1]-a[i]+2*c[i]; return a[n+1]; } int main() { scanf("%d%lf%lf", &n, a, &x); rep(i, n) scanf("%lf", c+i); double l=-1000, r=1000, m; while(r-l>1e-4) { m=(l+r)/2; if(calc(m)<x) l=m; else r=m; } printf("%.2f\n", l); return 0; }
f72a99b69b93e6059116cbede13070d931face3b
20f30902c29ede4a4aaa84eb4cd9cfb8d6ef8675
/src/BasicOpenGL/Buffer.cpp
788e11646212fe8d1cf096c2739646b94411198f
[]
no_license
Muroidea/SkeletalSkinning
6e3b825bf654921f80c1de5260100ebef38c6191
bc22ea3507cd276ce6f271d24df4720ea54db968
refs/heads/master
2023-03-12T16:41:56.693738
2021-03-02T10:34:18
2021-03-02T10:34:18
320,626,999
0
0
null
null
null
null
UTF-8
C++
false
false
1,419
cpp
Buffer.cpp
// // Created by Rafał on 28.11.2020. // #include "Buffer.h" Buffer::Buffer(unsigned int elementCount, size_t size, const void *data, GLenum bufferType, GLenum usage) : m_ElementCount(elementCount), m_ElementSize(size), m_BufferType(bufferType) { Init(data, usage); } Buffer::Buffer(size_t size, const void* data, GLenum bufferType, GLenum usage) : m_ElementCount(1), m_ElementSize(size), m_BufferType(bufferType) { Init(data, usage); } void Buffer::Init(const void* data, GLenum usage) { glGenBuffers(1, &m_ID); Bind(); glBufferData(m_BufferType, m_ElementCount * m_ElementSize, data, usage); Unbind(); } Buffer::~Buffer() { glDeleteBuffers(1, &m_ID); } void Buffer::Bind() const { glBindBuffer(m_BufferType, m_ID); } void Buffer::Unbind() const { glBindBuffer(m_BufferType, 0); } unsigned int Buffer::GetCount() const { return m_ElementCount; } void Buffer::UploadData(const void* data, unsigned int offsetCount, unsigned int elementCount) { Bind(); glBufferSubData(m_BufferType, offsetCount * m_ElementSize, elementCount * m_ElementSize, data); Unbind(); } void Buffer::UploadDataInBytes(const void* data, unsigned int offset, unsigned int size) { Bind(); glBufferSubData(m_BufferType, offset, size, data); Unbind(); } void Buffer::SetBufferBindingID(unsigned int binding) { glBindBufferBase(m_BufferType, binding, m_ID); }
71f076cd6eca93c7b07b7578e593ae7ce40fcab8
fc7457b8e150bb7585cd3726770f85da2c9bba13
/TP_POO/TP_POO/refugioPiratas.h
2ef53f6684f99cca0cfdf401dfa9df2c00207139
[]
no_license
cpo991/Kingdom_Game_C-Plus-Plus
ba1b32592b7f5e02aba09618742129f4e6b38645
c20fa976186c7d8ef750f3013c8540503990e7f1
refs/heads/main
2023-02-19T09:45:50.951133
2021-01-18T00:46:57
2021-01-18T00:46:57
312,855,424
0
0
null
null
null
null
UTF-8
C++
false
false
274
h
refugioPiratas.h
// // Created by Carolina Oliveira & Isabel Castro on 21/11/2020 // #ifndef TP_POO_REFUGIOPIRATAS_H #define TP_POO_REFUGIOPIRATAS_H #include "territorio.h" class refugioPiratas : public territorio { static int id; public: refugioPiratas(const string name); }; #endif
629f38e0d5602869136c0b1f36f22f518531f340
339e6cdb43fa4ac500a5f2e07026364340238160
/Circuits/Circuits/main.cpp
4ca8d60a01882bc1dcb6d725056850c437ce9e5e
[]
no_license
Ahmed-H300/cuircuit-solver
b26c2fee53fe0293614bf475b2a0c6cc65f92058
103f39b3556dacbace7cb9efa6c2feabab79b281
refs/heads/main
2023-06-16T00:46:10.418507
2021-07-04T19:19:56
2021-07-04T19:19:56
382,927,134
1
0
null
null
null
null
UTF-8
C++
false
false
68,304
cpp
main.cpp
#include<iostream> #include <cmath> #include<string> #include<fstream> #include<Eigen/Dense> #include<Eigen/Sparse> #include<complex> #include"vsrc.h" #include"Capacaitor.h" #include"Resistance.h" #include"Inductor.h" #include"isrc.h" #include"Branch.h" #include "Node.h" #include"Dependent_sources.h" #include"Current_C_Current.h" #include"Voltage_C_Voltage.h" using namespace std; using namespace Eigen; using namespace std::complex_literals; using namespace std; #include"Component.h" double W; int searcher(string x); void Save( Node**, Branch**, int, int ); #define n_max 10 Component* complist[n_max] = { NULL }; int comcount = 0; /////////////nodes&branches///////////// int nodecount = 0; int nonsimple_nodecount = 0; int simple_nodecount = 0; int branchcount = 0; int nodes_rannk[10] = { -1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; Node** Nodelist; Node** nonsimple_Nodelist; Node** simple_Nodelist; Branch** fullBranchlist; Branch** Branchlist; /////////////nodes&branches///////////// Isrc* simplification(Vsrc* a, complex<double> b, Node* N1, Node* N2) { complex<double> x = (a->getcomplex()) / b; double p = x.real() * x.real() + x.imag() * x.imag(); double mag = sqrt(p); double phase = atan(x.imag() / x.real()) * 180 / 3.14; Isrc* c = NULL; if(N2->getrank() == a->get_node2() || N1->getrank() == a->get_node1()) { c = new Isrc(a->get_name(), N1->getrank(), N2->getrank(), phase, mag); } else { c = new Isrc(a->get_name(), N2->getrank(), N1->getrank(), phase, mag); } Branchlist[branchcount] = new Branch(N1, N2); Branchlist[branchcount]->setcurentsource(c); branchcount++; return c; } MatrixXcd CalculateVoltNode(MatrixXcd G, MatrixXcd I); int main() { ifstream inputfile; inputfile.open("testcase2.txt"); if (!(inputfile.is_open())) { cout << "file is not opened , try again" << endl; return 0; } string name; while (!(inputfile.eof())) { int n1 = -1, n2 = -1; inputfile >> name; if (name == "w"|| name =="W") { double w; inputfile >> w; W = w; } else if (name == "vsrc" || name == "Vsrc" || name == "VSrc") { string Name; double phase, magintude; inputfile >> Name >> n1 >> n2 >> magintude >> phase; Vsrc* v1 = new Vsrc(Name, n1, n2, phase, magintude); complist[comcount++] = v1; } else if (name == "isrc" || name == "Isrc" || name == "ISrc") { string Name; double phase, magintude; inputfile >> Name >> n1 >> n2 >> magintude >> phase; Isrc* v1 = new Isrc(Name, n1, n2, phase, magintude); complist[comcount++] = v1; } else if (name == "vcvs" || name == "Vcvs" || name == "VCvs") { string Name; int n3, n4; string Name2; double val; inputfile >> Name >> n1 >> n2 >> n3 >> n4 >> val; Voltage_C_Voltage* v1 = new Voltage_C_Voltage(n1, n2, name, n3, n4, val); complist[comcount++] = v1; } else if (name == "cccs" || name == "Cccs" || name == "CCcs") { string Name; int n3, n4; string Name2; double val; inputfile >> Name >> n1 >> n2 >> n3 >> n4 >> Name2 >> val; Current_C_Current* cccs = new Current_C_Current(n1,n2,Name,n3,n4,Name2,val); complist[comcount++] = cccs; } else if (name == "res") { string Name; double val; inputfile >> Name >> n1 >> n2 >> val; Resistance* v1 = new Resistance(val, Name, n1, n2); complist[comcount++] = v1; } else if (name == "cap") { string Name; double val; inputfile >> Name >> n1 >> n2 >> val; Capacaitor* v1 = new Capacaitor(val, W, Name, n1, n2); complist[comcount++] = v1; } else if (name == "ind") { string Name; double val; inputfile >> Name >> n1 >> n2 >> val; Inductor* v1 = new Inductor(val, W, Name, n1, n2); complist[comcount++] = v1; } bool findN1 = false; bool findN2 = false; for (int i = 0; i < 10; i++) { if (n1 == nodes_rannk[i]) { findN1 = true; } if (n2 == nodes_rannk[i]) { findN2 = true; } } if (findN1 == false) { nodes_rannk[nodecount++] = n1; } if (findN2 == false) { nodes_rannk[nodecount++] = n2; } } inputfile.close(); Nodelist = new Node * [nodecount]; for (int i = 0; i < nodecount; i++) { Nodelist[i] = new Node(i); } for (int i = 0; i < comcount; i++) { int N1 = complist[i]->get_node1(); int N2 = complist[i]->get_node2(); int indexnode1, indexnode2; for (int j = 0; j < nodecount; j++) { if (Nodelist[j]->getrank() == N1) { indexnode1 = j; } else if (Nodelist[j]->getrank() == N2) { indexnode2 = j; } } Nodelist[indexnode1]->increment_connections(Nodelist[indexnode2]); Nodelist[indexnode2]->increment_connections(Nodelist[indexnode1]); } for (int j = 0; j < nodecount; j++) { if (!(Nodelist[j]->ifsimple())) { nonsimple_nodecount++; } } simple_nodecount = nodecount - nonsimple_nodecount; nonsimple_Nodelist = new Node * [nonsimple_nodecount]; simple_Nodelist = new Node * [simple_nodecount]; { int nonsimple = 0; int simple = 0; for (int i = 0; i < nodecount; i++) { if (Nodelist[i]->ifsimple()) { simple_Nodelist[simple++] = Nodelist[i]; } else { nonsimple_Nodelist[nonsimple++] = Nodelist[i]; } } } ////////////////////////////// creat branches ///////////////////////////////////// branchcount = comcount - simple_nodecount; Branchlist = new Branch * [comcount]; for (int i = 0; i < comcount; i++) { Branchlist[i] = NULL; } { int counter = 0; for (int i = 0; i < comcount; i++) { int N1 = complist[i]->get_node1(); int N2 = complist[i]->get_node2(); bool find = false; for (int j = 0; j < simple_nodecount; j++) { if (N1 == simple_Nodelist[j]->getrank() || N2 == simple_Nodelist[j]->getrank()) { find = true; } } if (find == false) { Vsrc* v1 = dynamic_cast <Vsrc*>(complist[i]); Isrc* i1 = dynamic_cast <Isrc*>(complist[i]); Current_C_Current* D_I = dynamic_cast<Current_C_Current*>(complist[i]); Resistance* r1 = dynamic_cast <Resistance*>(complist[i]); Capacaitor* c1 = dynamic_cast <Capacaitor*>(complist[i]); Inductor* in1 = dynamic_cast <Inductor*>(complist[i]); Branchlist[counter] = new Branch(Nodelist[N1], Nodelist[N2]); if (v1 != NULL) { Branchlist[counter]->setvolt(v1); } else if (i1 != NULL) { Branchlist[counter]->setcurentsource(i1); } else if (r1 != NULL) { Branchlist[counter]->setz(r1->get_Impedance()); } else if (c1 != NULL) { Branchlist[counter]->setz(c1->get_Impedance()); } else if (in1 != NULL) { Branchlist[counter]->setz(in1->get_Impedance()); } else if(D_I != NULL) { Branchlist[counter]->setDependentCsource(D_I); } counter++; } } ////////////////// circuts that has only one loop if (nonsimple_nodecount == 0) { Branchlist[counter] = new Branch(Nodelist[0], Nodelist[0]); for (int j = 0; j < comcount; j++) { Vsrc* v1 = dynamic_cast <Vsrc*>(complist[j]); Isrc* i1 = dynamic_cast <Isrc*>(complist[j]); Resistance* r1 = dynamic_cast <Resistance*>(complist[j]); Capacaitor* c1 = dynamic_cast <Capacaitor*>(complist[j]); Inductor* in1 = dynamic_cast <Inductor*>(complist[j]); if (v1 != NULL) { if (Branchlist[counter]->getvolt() != NULL) { int N1 = Branchlist[counter]->getvolt()->get_node1(); int N2 = Branchlist[counter]->getvolt()->get_node2(); int N3 = v1->get_node1(); Vsrc* sum_volt = new Vsrc("loop", N1, N2, Branchlist[counter]->getvolt()->getphase(), Branchlist[counter]->getvolt()->getmag()); complex <double> curently_volt = sum_volt->getcomplex(); int N4 = v1->get_node2(); if (N1 == N4 || N2 == N3) { curently_volt += v1->getcomplex(); } else if (N1 == N3 || N2 == N4) { curently_volt -= v1->getcomplex(); } else { if (N1 > N2) { for (int i = 1; i < nodecount; i++) { if ((N1 + i) == N4) { curently_volt += v1->getcomplex(); break; } else if ((N1 + i) == N3) { curently_volt -= v1->getcomplex(); break; } else if ((N2 - i) == N4) { curently_volt -= v1->getcomplex(); break; } else if ((N2 - i) == N3) { curently_volt += v1->getcomplex(); break; } } } else { for (int i = 1; i < nodecount; i++) { if ((N1 - i) == N4) { curently_volt += v1->getcomplex(); break; } else if ((N1 - i) == N3) { curently_volt -= v1->getcomplex(); break; } else if ((N2 + i) == N4) { curently_volt -= v1->getcomplex(); break; } else if ((N2 + i) == N3) { curently_volt += v1->getcomplex(); break; } } } } if (curently_volt == 0.0) { sum_volt->zerosetters(); } else { sum_volt->setcomplex(curently_volt); } Branchlist[counter]->setvolt(sum_volt); } else { Branchlist[counter]->setvolt(v1); } } else if (i1 != NULL) { Branchlist[counter]->setcurentsource(i1); } else if (r1 != NULL) { Branchlist[counter]->setz(r1->get_Impedance()); } else if (c1 != NULL) { Branchlist[counter]->setz(c1->get_Impedance()); } else if (in1 != NULL) { Branchlist[counter]->setz(in1->get_Impedance()); } } //Isrc* i22 = Branchlist[counter]->getcsource(); ////////// set current in the loop //////////// if (Branchlist[counter]->getcsource() != NULL) { Branchlist[counter]->setcurrent(Branchlist[counter]->getcsource()->getcomplex()); } else { if (Branchlist[counter]->getvolt()->getmag() == 0.0) { //Branchlist[counter]->getvolt()->setcomplex((0, 0)); Branchlist[counter]->setcurrent((0, 0)); } else { Branchlist[counter]->setcurrent((Branchlist[counter]->getvolt()->getcomplex()) * (Branchlist[counter]->get_Admittance())); } } /*cout << r1 << endl; cout <<v1<<endl; cout << Branchlist[counter]->getcurrent() << endl;*/ ////////// set voltage for every node //////////// Nodelist[0]->setvoltage((0, 0)); if (Branchlist[counter]->getcsource() != NULL) { Isrc* ic = Branchlist[counter]->getcsource(); int Nc1 = ic->get_node1(); int Nc2 = ic->get_node2(); if (Nc1 > Nc2) { for (int i = 1; i <= Nc2; i++) { complex<double> v = Nodelist[i - 1]->getvoltage(); Component* c_find = NULL; int pos_node = -1; int neg_node = -1; for (int j = 0; j < comcount; j++) { int N1 = complist[j]->get_node1(); int N2 = complist[j]->get_node2(); if ((N1 == Nodelist[i]->getrank() || N2 == Nodelist[i]->getrank()) && (N1 == Nodelist[i - 1]->getrank() || N2 == Nodelist[i - 1]->getrank())) { c_find = complist[j]; break; } } if (c_find != NULL) { pos_node = c_find->get_node1(); neg_node = c_find->get_node2(); Vsrc* v1 = dynamic_cast <Vsrc*>(c_find); Isrc* i1 = dynamic_cast <Isrc*>(c_find); Resistance* r1 = dynamic_cast <Resistance*>(c_find); Capacaitor* c1 = dynamic_cast <Capacaitor*>(c_find); Inductor* in1 = dynamic_cast <Inductor*>(c_find); if (v1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += v1->getcomplex(); } else { v -= v1->getcomplex(); } } else if (r1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += r1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= r1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } else if (c1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += c1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= c1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } else if (in1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += in1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= in1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } } Nodelist[i]->setvoltage(v); } for (int i = nodecount - 1; i >= Nc1; i--) { complex<double> v = (0, 0); Component* c_find = NULL; int pos_node = -1; int neg_node = -1; for (int j = 0; j < comcount; j++) { int N1 = complist[j]->get_node1(); int N2 = complist[j]->get_node2(); if ((N1 == Nodelist[i]->getrank() || N2 == Nodelist[i]->getrank()) && (N1 != Nodelist[i - 1]->getrank() && N2 != Nodelist[i - 1]->getrank())) { c_find = complist[j]; if (N1 != Nodelist[i]->getrank()) { v = Nodelist[N1]->getvoltage(); } else if (N2 != Nodelist[i]->getrank()) { v = Nodelist[N2]->getvoltage(); } break; } } if (c_find != NULL) { pos_node = c_find->get_node1(); neg_node = c_find->get_node2(); Vsrc* v1 = dynamic_cast <Vsrc*>(c_find); Resistance* r1 = dynamic_cast <Resistance*>(c_find); Capacaitor* c1 = dynamic_cast <Capacaitor*>(c_find); Inductor* in1 = dynamic_cast <Inductor*>(c_find); if (v1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += v1->getcomplex(); } else { v -= v1->getcomplex(); } } else if (r1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += r1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= r1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } else if (c1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += c1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= c1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } else if (in1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += in1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= in1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } } Nodelist[i]->setvoltage(v); } } else { for (int i = 1; i <= Nc1; i++) { complex<double> v = Nodelist[i - 1]->getvoltage(); Component* c_find = NULL; int pos_node = -1; int neg_node = -1; for (int j = 0; j < comcount; j++) { int N1 = complist[j]->get_node1(); int N2 = complist[j]->get_node2(); if ((N1 == Nodelist[i]->getrank() || N2 == Nodelist[i]->getrank()) && (N1 == Nodelist[i - 1]->getrank() || N2 == Nodelist[i - 1]->getrank())) { c_find = complist[j]; break; } } if (c_find != NULL) { pos_node = c_find->get_node1(); neg_node = c_find->get_node2(); Vsrc* v1 = dynamic_cast <Vsrc*>(c_find); Isrc* i1 = dynamic_cast <Isrc*>(c_find); Resistance* r1 = dynamic_cast <Resistance*>(c_find); Capacaitor* c1 = dynamic_cast <Capacaitor*>(c_find); Inductor* in1 = dynamic_cast <Inductor*>(c_find); if (v1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += v1->getcomplex(); } else { v -= v1->getcomplex(); } } else if (r1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += r1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= r1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } else if (c1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += c1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= c1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } else if (in1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += in1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= in1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } } Nodelist[i]->setvoltage(v); } for (int i = nodecount - 1; i >= Nc2; i--) { complex<double> v = (0, 0); Component* c_find = NULL; int pos_node = -1; int neg_node = -1; for (int j = 0; j < comcount; j++) { int N1 = complist[j]->get_node1(); int N2 = complist[j]->get_node2(); if ((N1 == Nodelist[i]->getrank() || N2 == Nodelist[i]->getrank()) && (N1 != Nodelist[i - 1]->getrank() && N2 != Nodelist[i - 1]->getrank())) { c_find = complist[j]; if (N1 != Nodelist[i]->getrank()) { v = Nodelist[N1]->getvoltage(); } else if (N2 != Nodelist[i]->getrank()) { v = Nodelist[N2]->getvoltage(); } break; } } if (c_find != NULL) { pos_node = c_find->get_node1(); neg_node = c_find->get_node2(); Vsrc* v1 = dynamic_cast <Vsrc*>(c_find); Resistance* r1 = dynamic_cast <Resistance*>(c_find); Capacaitor* c1 = dynamic_cast <Capacaitor*>(c_find); Inductor* in1 = dynamic_cast <Inductor*>(c_find); if (v1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += v1->getcomplex(); } else { v -= v1->getcomplex(); } } else if (r1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += r1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= r1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } else if (c1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += c1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= c1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } else if (in1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += in1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= in1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } } Nodelist[i]->setvoltage(v); } } } else { for (int i = 1; i < nodecount; i++) { complex<double> v = Nodelist[i - 1]->getvoltage(); Component* c_find = NULL; int pos_node = -1; int neg_node = -1; for (int j = 0; j < comcount; j++) { int N1 = complist[j]->get_node1(); int N2 = complist[j]->get_node2(); if ((N1 == Nodelist[i]->getrank() || N2 == Nodelist[i]->getrank()) && (N1 == Nodelist[i - 1]->getrank() || N2 == Nodelist[i - 1]->getrank())) { c_find = complist[j]; break; } } if (c_find != NULL) { pos_node = c_find->get_node1(); neg_node = c_find->get_node2(); Vsrc* v1 = dynamic_cast <Vsrc*>(c_find); Isrc* i1 = dynamic_cast <Isrc*>(c_find); Resistance* r1 = dynamic_cast <Resistance*>(c_find); Capacaitor* c1 = dynamic_cast <Capacaitor*>(c_find); Inductor* in1 = dynamic_cast <Inductor*>(c_find); if (v1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += v1->getcomplex(); } else { v -= v1->getcomplex(); } } else if (r1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += r1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= r1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } else if (c1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += c1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= c1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } else if (in1 != NULL) { if (pos_node == Nodelist[i]->getrank()) { v += in1->get_Impedance() * (Branchlist[counter]->getcurrent()); } else { v -= in1->get_Impedance() * (Branchlist[counter]->getcurrent()); } } } Nodelist[i]->setvoltage(v); } } counter++; //cout << Branchlist[counter]->getcurrent() << endl; for (int i = 0; i < nodecount; i++) { cout << "v"<<i <<"= "<< Nodelist[i]->getvoltage() << endl; } return 0; } ///////////////// end of ciruts that has one loop //////////////// for (int i = 0; i < simple_nodecount; i++) { Node** connection = simple_Nodelist[i]->getNodeconnections(); int N1 = connection[0]->getrank(); // the node that before the simplenode that we work on int N = simple_Nodelist[i]->getrank(); // the simplenode that we work on int N2 = connection[1]->getrank(); // the node that after the simplenode that we work on Branchlist[counter] = new Branch(Nodelist[N1], Nodelist[N2]); bool find = false; for (int j = 0; j < comcount; j++) { int N3 = complist[j]->get_node1(); int N4 = complist[j]->get_node2(); if ((N3 == N && N4 == N1) || (N3 == N1 && N4 == N) || (N3 == N && N4 == N2) || (N3 == N2 && N4 == N)) { find = true; } if (find == true) { Vsrc* v1 = dynamic_cast <Vsrc*>(complist[j]); Isrc* i1 = dynamic_cast <Isrc*>(complist[j]); Resistance* r1 = dynamic_cast <Resistance*>(complist[j]); Capacaitor* c1 = dynamic_cast <Capacaitor*>(complist[j]); Inductor* in1 = dynamic_cast <Inductor*>(complist[j]); if (v1 != NULL) { Branchlist[counter]->setvolt(v1); } else if (i1 != NULL) { Branchlist[counter]->setcurentsource(i1); } else if (r1 != NULL) { Branchlist[counter]->setz(r1->get_Impedance()); } else if (c1 != NULL) { Branchlist[counter]->setz(c1->get_Impedance()); } else if (in1 != NULL) { Branchlist[counter]->setz(in1->get_Impedance()); } } find = false; } // this code work when N2 is also a simple Node // then we should add the component between N2 and the next Node to the same btanch // and Repeat this step if the Node that next to N2 is alse asimple // and so , if all nodes is asimple Node we must make exactly one branch // this branch will take all the components for (int k = i; k < simple_nodecount; k++) { N2; bool find2 = false; for (int k1 = i; k1 < simple_nodecount; k1++) { if (N2 == simple_Nodelist[k1]->getrank()) { find2 = true; } } if (find2 == true) { i++; N = N2; connection = simple_Nodelist[i]->getNodeconnections(); N2 = connection[1]->getrank(); bool f = false; for (int k2 = 0; k2 < comcount; k2++) { int N3 = complist[k2]->get_node1(); int N4 = complist[k2]->get_node2(); if ((N3 == N && N4 == N2) || (N3 == N2 && N4 == N)) { f = true; } if (f == true) { Vsrc* v1 = dynamic_cast <Vsrc*>(complist[k2]); Isrc* i1 = dynamic_cast <Isrc*>(complist[k2]); Resistance* r1 = dynamic_cast <Resistance*>(complist[k2]); Capacaitor* c1 = dynamic_cast <Capacaitor*>(complist[k2]); Inductor* in1 = dynamic_cast <Inductor*>(complist[k2]); if (v1 != NULL) { Branchlist[counter]->setvolt(v1); } else if (i1 != NULL) { Branchlist[counter]->setcurentsource(i1); } else if (r1 != NULL) { Branchlist[counter]->setz(r1->get_Impedance()); } else if (c1 != NULL) { Branchlist[counter]->setz(c1->get_Impedance()); } else if (in1 != NULL) { Branchlist[counter]->setz(in1->get_Impedance()); } } } } else {} } counter++; } } /////////////////////////Convert Voltage Source to Current Source ////////////////////////////////////////////////////// complex<double> zero; zero.real(0); zero.imag(0); Isrc* c; for (int i = 0; i < branchcount; i++) { Branch* b1 = Branchlist[i]; if (Branchlist[i] != NULL) { if ((Branchlist[i]->getvolt() != NULL)) { if (Branchlist[i]->getcsource() == NULL && Branchlist[i]->getz() != zero && Branchlist[i]->getvolt()->getcomplex() != zero) { int n = searcher(Branchlist[i]->getvolt()->get_name()); c = simplification(Branchlist[i]->getvolt(), Branchlist[i]->getz(), Branchlist[i]->getnode1(), Branchlist[i]->getnode2()); complist[comcount++] = c; Branchlist[i]->getvolt()->zerosetters(); } } } } ////////////////////////////////////// Solving matrices of G & I & V //////////////////////////////////////////// int num_non_sim_nodes = nonsimple_nodecount; int num = num_non_sim_nodes - 1; int* arr; arr = new int[nonsimple_nodecount - 1]; for (int i = 1; i < nonsimple_nodecount; i++) { arr[i - 1] = nonsimple_Nodelist[i]->getrank(); } Eigen::MatrixXcd m(num, num); for (int i = 0; i < num; i++) { for (int j = 0; j < num; j++) { m(i, j).real(0); m(i, j).imag(0); } } Eigen::MatrixXcd I(num, 1); for (int i = 0; i < num; i++) { I(i, 0) = 0; } Current_C_Current* cccs = NULL; Voltage_C_Voltage* vsvc = NULL; for (int i = 0; i < comcount; i++) { cccs = dynamic_cast<Current_C_Current*>(complist[i]); vsvc = dynamic_cast<Voltage_C_Voltage*>(complist[i]); if (cccs != NULL) { break; } if(vsvc !=NULL) { break; } } if (cccs != NULL) { for (int j = 0; j < comcount; j++) { if (cccs->get_Noded1() == complist[j]->get_node1() && cccs->get_Noded2() == complist[j]->get_node2() || cccs->get_Noded2() == complist[j]->get_node1() && cccs->get_Noded1() == complist[j]->get_node2()) { Resistance* r1 = dynamic_cast <Resistance*>(complist[j]); Capacaitor* c1 = dynamic_cast <Capacaitor*>(complist[j]); Inductor* in1 = dynamic_cast <Inductor*>(complist[j]); if (r1 != NULL) { cccs->set_Impedance(r1->get_Impedance()); } else if (c1 != NULL) { cccs->set_Impedance(c1->get_Impedance()); } else if (in1 != NULL) { cccs->set_Impedance(in1->get_Impedance()); } } } } ////////////////////////////////////////// Check Current-Current Source //////////////////////////////////////////// if (cccs != NULL) { int check_specialcase; int indexx; int no_Equations = num; Node* node_reference = NULL; for (int i = 0; i < branchcount; i++) { if (Branchlist[i]->getvolt() != NULL && Branchlist[i]->getz() == (0.0 + 0.0i)) { if (Branchlist[i]->getnode1()->getrank() == arr[i] && Branchlist[i]->getnode2()->getrank() == 0) { no_Equations--; node_reference = Branchlist[i]->getnode1(); node_reference->setvoltage(Branchlist[i]->getvolt()->getcomplex()); check_specialcase = Branchlist[i]->getnode1()->getrank(); break; } else if (Branchlist[i]->getnode2()->getrank() == arr[i] && Branchlist[i]->getnode1()->getrank() == 0) { no_Equations--; node_reference = Branchlist[i]->getnode2(); node_reference->setvoltage(-Branchlist[i]->getvolt()->getcomplex()); check_specialcase = Branchlist[i]->getnode2()->getrank(); break; } } } ////////////////////////////// Check Voltage Source connected alone to ground ///////////////////////////////////// if (node_reference != NULL) { for (int k = 0; k < num; k++) { complex <double> Admittance_s(0, 0); for (int i = 0; i < branchcount; i++) { if ((Branchlist[i]->getnode1()->getrank() == arr[k]) || (Branchlist[i]->getnode2()->getrank() == arr[k])) { complex <double> r; r = Branchlist[i]->get_Admittance(); Admittance_s += r; } } m(k, k) = Admittance_s; } for (int v = 0; v < num; v++) { for (int k = v + 1; k < num; k++) { complex <double> Admittance_d(0, 0); for (int l = 0; l < branchcount; l++) { if (((Branchlist[l]->getnode1()->getrank() == arr[v]) || (Branchlist[l]->getnode2()->getrank() == arr[v])) && ((Branchlist[l]->getnode1()->getrank() == arr[k]) || (Branchlist[l]->getnode2()->getrank() == arr[k]))) { Admittance_d += Branchlist[l]->get_Admittance(); } } m(v, k) = -Admittance_d; m(k, v) = -Admittance_d; } } for (int i = 0; i < num; i++) { for (int k = 0; k < num; k++) { if (arr[i] == check_specialcase) { I(i, 0) = node_reference->getvoltage(); m(i, k) = 0; if(i == k) { m(i, i) = 1; } } } } int cccs_node1; double sign = 1; int index; if (cccs != NULL) { for (int i = 1; i < nonsimple_nodecount; i++) { if (cccs->get_node1() == nonsimple_Nodelist[i]->getrank()) { index = i; sign *= -1; } else if (cccs->get_node2() == nonsimple_Nodelist[i]->getrank()) { index = i; sign *= 1; } } for (int i = 1; i < nonsimple_nodecount; i++) { if (nonsimple_Nodelist[i]->getrank() == cccs->get_Noded1()) { m(index - 1, i - 1) += sign * cccs->get_Admittance() * cccs->get_cofficient(); } else if (nonsimple_Nodelist[i]->getrank() == cccs->get_Noded2()) { m(index - 1, i - 1) -= sign * cccs->get_Admittance() * cccs->get_cofficient(); } } } MatrixXcd V = CalculateVoltNode(m, I); // function calculate volt of each node for (int i = 1; i < nonsimple_nodecount; i++) { nonsimple_Nodelist[i]->setvoltage(V(i - 1, 0)); } for (int i = 0; i < branchcount; i++) { Branchlist[i]->Calculatecurrent(); } cout << m; cout << "..........................." << endl; cout << I << endl; cout << "..........................." << endl; cout << V << endl; cout << "..........................." << endl; Save(nonsimple_Nodelist, Branchlist, nonsimple_nodecount, branchcount); return 0; } else { for (int k = 0; k < num; k++) { complex <double> Admittance_s(0, 0); for (int i = 0; i < branchcount; i++) { if ((Branchlist[i]->getnode1()->getrank() == arr[k]) || (Branchlist[i]->getnode2()->getrank() == arr[k])) { complex <double> r; r = Branchlist[i]->get_Admittance(); Admittance_s += r; } } m(k, k) = Admittance_s; } for (int v = 0; v < num; v++) { for (int k = v + 1; k < num; k++) { complex <double> Admittance_d(0, 0); for (int l = 0; l < branchcount; l++) { if (((Branchlist[l]->getnode1()->getrank() == arr[v]) || (Branchlist[l]->getnode2()->getrank() == arr[v])) && ((Branchlist[l]->getnode1()->getrank() == arr[k]) || (Branchlist[l]->getnode2()->getrank() == arr[k]))) { Admittance_d += Branchlist[l]->get_Admittance(); } } m(v, k) = -Admittance_d; m(k, v) = -Admittance_d; } } for (int j = 0; j < num; j++) { for (int i = 0; i < comcount; i++) { Component* comp = complist[i]; Isrc* current = dynamic_cast<Isrc*>(comp); if (current != NULL) { if (current->get_node1() == arr[j]) { complex <double> curr = current->getcomplex(); I(j, 0) += curr; } if (current->get_node2() == arr[j]) { complex <double> curr = -current->getcomplex(); I(j, 0) += curr; } } } } int cccs_node1; double sign = 1; int index; if (cccs != NULL) { for (int i = 1; i < nonsimple_nodecount; i++) { if (cccs->get_node1() == nonsimple_Nodelist[i]->getrank()) { index = i; sign *= -1; } else if (cccs->get_node2() == nonsimple_Nodelist[i]->getrank()) { index = i; sign *= 1; } } for (int i = 1; i < nonsimple_nodecount; i++) { if (nonsimple_Nodelist[i]->getrank() == cccs->get_Noded1()) { m(index - 1, i - 1) += sign * cccs->get_Admittance() * cccs->get_cofficient(); } else if (nonsimple_Nodelist[i]->getrank() == cccs->get_Noded2()) { m(index - 1, i - 1) -= sign * cccs->get_Admittance() * cccs->get_cofficient(); } } } MatrixXcd V = CalculateVoltNode(m, I); // function calculate volt of each node for (int i = 1; i < nonsimple_nodecount; i++) { nonsimple_Nodelist[i]->setvoltage(V(i - 1, 0)); } for (int i = 0; i < branchcount; i++) { Branchlist[i]->Calculatecurrent(); } cout << "..........................." << endl; cout << m << endl; cout << "..........................." << endl; cout << I << endl; cout << "..........................." << endl; cout << V << endl; Save(nonsimple_Nodelist, Branchlist, nonsimple_nodecount, branchcount); return 0; } } ////////////////////////////////////////// check if Volt - Volt source //////////////////////////////////// else if (vsvc != NULL) { /////////////////// super node ////////////////////////////// bool R1 = false, R2 = false; int reference1, reference2; Vsrc* voltage_source = NULL; Vsrc* voltage_source2 = NULL; for (int i = 0; i < comcount; i++) { voltage_source = dynamic_cast<Vsrc*> (complist[i]); if (voltage_source != NULL) { for (int j = 0; j < num; j++) { if (voltage_source->get_node1() == arr[j]) { voltage_source2 = voltage_source; reference1 = j; R1 = true; } if (voltage_source->get_node2() == arr[j]) { reference2 = j; R2 = true; } } } } Voltage_C_Voltage* vv = vsvc; int pos_node = vv->get_node1(); int cof = vv->get_cofficient(); int neg_node = vv->get_node2(); int node_d_pos = vv->get_Noded1(); int node_d_neg = vv->get_Noded2(); int node_v_d; int node_vv_d; int node_s; if ((vv->get_node1() == voltage_source2->get_node1()) || (vv->get_node1() == voltage_source2->get_node2())) { node_s = vv->get_node1(); if (vv->get_node1() == voltage_source2->get_node1()) { node_v_d = voltage_source2->get_node2(); } else { node_v_d = voltage_source2->get_node1(); } node_vv_d = vv->get_node2(); } else if ((vv->get_node2() == voltage_source2->get_node1()) || (vv->get_node2() == voltage_source2->get_node2())) { node_s = vv->get_node2(); if (vv->get_node2() == voltage_source2->get_node1()) { node_v_d = voltage_source2->get_node2(); } else { node_v_d = voltage_source2->get_node1(); } node_vv_d = vv->get_node1(); } if ((R1 && R2) && (vsvc->get_node1() != 0 && vsvc->get_node2() != 0)) { for (int k = 0; k < num; k++) { for (int i = 0; i < nonsimple_nodecount; i++) { if (voltage_source2->get_node1() == nonsimple_Nodelist[i]->getrank()) { m(node_v_d - 1, reference1) = 1; } else if (voltage_source2->get_node2() == nonsimple_Nodelist[i]->getrank()) { m(node_v_d - 1, reference2) = -1; } else { m(node_v_d - 1, k) = 0; } } I(node_v_d - 1, 0) = voltage_source2->getcomplex(); }/////////////// m(node_vv_d - 1, node_d_pos - 1) = 0; m(node_vv_d - 1, node_d_neg - 1) = 0; m(node_vv_d - 1, pos_node - 1) = 0; m(node_vv_d - 1, neg_node - 1) = 0; m(node_vv_d - 1, pos_node - 1) = 1; m(node_vv_d - 1, neg_node - 1) = -1; m(node_vv_d - 1, node_d_pos - 1) += -cof; m(node_vv_d - 1, node_d_neg - 1) += cof; I(node_vv_d - 1, 0) = 0; I(node_vv_d - 1, 0) = 0; for (int k = 0; k < branchcount; k++) { if ((((Branchlist[k]->getnode1()->getrank() == node_vv_d) && (Branchlist[k]->getnode2()->getrank() == 0)) || ((Branchlist[k]->getnode1()->getrank() == 0) && (Branchlist[k]->getnode2()->getrank() == node_vv_d))) || (((Branchlist[k]->getnode1()->getrank() == node_v_d) && (Branchlist[k]->getnode2()->getrank() == 0)) || ((Branchlist[k]->getnode1()->getrank() == 0) && (Branchlist[k]->getnode2()->getrank() == node_v_d))) || (((Branchlist[k]->getnode1()->getrank() == node_s) && (Branchlist[k]->getnode2()->getrank() == 0)) || ((Branchlist[k]->getnode1()->getrank() == 0) && (Branchlist[k]->getnode2()->getrank() == node_s)))) { Isrc* currentsource = Branchlist[k]->getcsource(); if (currentsource != NULL) { I(node_s - 1, 0) += Branchlist[k]->getcsource()->getcomplex(); } } } complex <double> Admittance_d4(0, 0); for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == node_vv_d) && (Branchlist[k]->getnode2()->getrank() == 0)) || ((Branchlist[k]->getnode1()->getrank() == 0) && (Branchlist[k]->getnode2()->getrank() == node_vv_d))) { m(node_s - 1, node_vv_d - 1) += Branchlist[k]->get_Admittance(); } if (((Branchlist[k]->getnode1()->getrank() == node_v_d) && (Branchlist[k]->getnode2()->getrank() == 0)) || ((Branchlist[k]->getnode1()->getrank() == 0) && (Branchlist[k]->getnode2()->getrank() == node_v_d))) { m(node_s - 1, node_v_d - 1) += Branchlist[k]->get_Admittance(); } if (((Branchlist[k]->getnode1()->getrank() == node_s) && (Branchlist[k]->getnode2()->getrank() == 0)) || ((Branchlist[k]->getnode1()->getrank() == 0) && (Branchlist[k]->getnode2()->getrank() == node_s))) { m(node_s - 1, node_s - 1) += Branchlist[k]->get_Admittance(); } } MatrixXcd V = CalculateVoltNode(m, I); // function calculate volt of each node for (int i = 1; i < nonsimple_nodecount; i++) { nonsimple_Nodelist[i]->setvoltage(V(i - 1, 0)); } for (int i = 0; i < branchcount; i++) { Branchlist[i]->Calculatecurrent(); } cout << "..........................." << endl; cout << m << endl; cout << "..........................." << endl; cout << I << endl; cout << "..........................." << endl; cout << V << endl; Save(nonsimple_Nodelist, Branchlist, nonsimple_nodecount, branchcount); return 0; } ///////////////////super node /////////////////////////// int check_specialcase; int no_Equations = num; Node* node_reference = NULL; for (int i = 0; i < branchcount; i++) { if (Branchlist[i]->getvolt() != NULL && Branchlist[i]->getz() == (0.0 + 0.0i)) { if (Branchlist[i]->getnode1()->getrank() == arr[i] && Branchlist[i]->getnode2()->getrank() == 0) { no_Equations--; node_reference = Branchlist[i]->getnode1(); node_reference->setvoltage(Branchlist[i]->getvolt()->getcomplex()); check_specialcase = Branchlist[i]->getnode1()->getrank(); break; } else if (Branchlist[i]->getnode2()->getrank() == arr[i] && Branchlist[i]->getnode1()->getrank() ==0 ) { no_Equations--; node_reference = Branchlist[i]->getnode2(); node_reference->setvoltage(-Branchlist[i]->getvolt()->getcomplex()); check_specialcase = Branchlist[i]->getnode2()->getrank(); break; } } } /////////////////////////////////// check if voltage source connected to ground ///////////////////////////////// if (node_reference != NULL) { for (int k = 0; k < num; k++) { complex <double> Admittance_s(0, 0); for (int i = 0; i < branchcount; i++) { if ((Branchlist[i]->getnode1()->getrank() == arr[k]) || (Branchlist[i]->getnode2()->getrank() == arr[k])) { complex <double> r; r = Branchlist[i]->get_Admittance(); Admittance_s += r; } } m(k, k) = Admittance_s; } for (int v = 0; v < num; v++) { for (int k = v + 1; k < num; k++) { complex <double> Admittance_d(0, 0); for (int l = 0; l < branchcount; l++) { if (((Branchlist[l]->getnode1()->getrank() == arr[v]) || (Branchlist[l]->getnode2()->getrank() == arr[v])) && ((Branchlist[l]->getnode1()->getrank() == arr[k]) || (Branchlist[l]->getnode2()->getrank() == arr[k]))) { Admittance_d += Branchlist[l]->get_Admittance(); } } m(v, k) = -Admittance_d; m(k, v) = -Admittance_d; } } for (int i = 0; i < num; i++) { for (int k = 0; k < num; k++) { if (arr[i] == check_specialcase) { I(i, 0) = node_reference->getvoltage(); m(i, k) = 0; if (i == k) { m(i, i) = 1; } } } } for (int i = 0; i < comcount; i++) { Voltage_C_Voltage* vv = dynamic_cast<Voltage_C_Voltage*>(complist[i]); if (vv != NULL) { int pos_node = vv->get_node1(); if (pos_node == 0) { int cof = -vv->get_cofficient(); int node_d_pos = vv->get_Noded1(); int node_d_neg = vv->get_Noded2(); int node_neg = vv->get_node2(); for (int i = 0; i < num; i++) { m(node_neg - 1, i) = 0; } m(node_neg - 1, node_d_pos - 1) += cof; m(node_neg - 1, node_d_neg - 1) += -cof; m(node_neg - 1, node_neg - 1) += 1; } else if (vv->get_node2() == 0) { int cof = vv->get_cofficient(); int node_d_pos = vv->get_Noded1(); int node_d_neg = vv->get_Noded2(); int node_neg = vv->get_node2(); for (int i = 0; i < num; i++) { m(pos_node - 1, i) = 0; } m(pos_node - 1, node_d_pos - 1) += -cof; m(pos_node - 1, node_d_neg - 1) += cof; m(pos_node - 1, pos_node - 1) += 1; } else { int cof = vv->get_cofficient(); int neg_node = vv->get_node2(); int node_d_pos = vv->get_Noded1(); int node_d_neg = vv->get_Noded2(); m(pos_node - 1, node_d_pos - 1) = 0; m(pos_node - 1, node_d_neg - 1) = 0; m(pos_node - 1, pos_node - 1) = 0; m(pos_node - 1, neg_node - 1) = 0; m(pos_node - 1, pos_node - 1) = 1; m(pos_node - 1, neg_node - 1) = -1; m(pos_node - 1, node_d_pos - 1) += -cof; m(pos_node - 1, node_d_neg - 1) += cof; I(pos_node - 1, 0) = 0; I(neg_node - 1, 0) = 0; for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == pos_node) || (Branchlist[k]->getnode2()->getrank() == pos_node)) && ((Branchlist[k]->getnode1()->getrank() != neg_node) && (Branchlist[k]->getnode2()->getrank() != neg_node))) { Isrc* currentsource = Branchlist[k]->getcsource(); if (currentsource != NULL) { I(neg_node - 1, 0) += Branchlist[k]->getcsource()->getcomplex(); } } } for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == neg_node) || (Branchlist[k]->getnode2()->getrank() == neg_node)) && ((Branchlist[k]->getnode1()->getrank() != pos_node) && (Branchlist[k]->getnode2()->getrank() != pos_node))) { Isrc* currentsource = Branchlist[k]->getcsource(); if (currentsource != NULL) { I(neg_node - 1, 0) += Branchlist[k]->getcsource()->getcomplex(); } } } complex <double> Admittance_d(0, 0); for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == pos_node) || (Branchlist[k]->getnode2()->getrank() == pos_node)) && ((Branchlist[k]->getnode1()->getrank() != neg_node) && (Branchlist[k]->getnode2()->getrank() != neg_node))) { Admittance_d += Branchlist[k]->get_Admittance(); } } m(neg_node - 1, pos_node - 1) = Admittance_d; complex <double> Admittance_d2(0, 0); for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == neg_node) || (Branchlist[k]->getnode2()->getrank() == neg_node)) && ((Branchlist[k]->getnode1()->getrank() != pos_node) && (Branchlist[k]->getnode2()->getrank() != pos_node))) { Admittance_d2 += Branchlist[k]->get_Admittance(); } } m(neg_node - 1, neg_node - 1) = Admittance_d2; Admittance_d2 = 0.0 + 0.0i; complex <double> Admittance_d3(0, 0); for (int i = 0; i < num; i++) { if (i != neg_node - 1 && i != pos_node - 1) { for (int k = 0; k < branchcount; k++) { if (Branchlist[k]->getnode1()->getrank() == arr[i] && Branchlist[k]->getnode2()->getrank() == pos_node || Branchlist[k]->getnode2()->getrank() == arr[i] && Branchlist[k]->getnode1()->getrank() == pos_node) { Admittance_d2 += Branchlist[k]->get_Admittance(); } } for (int k = 0; k < branchcount; k++) { if (Branchlist[k]->getnode1()->getrank() == arr[i] && Branchlist[k]->getnode2()->getrank() == neg_node || Branchlist[k]->getnode2()->getrank() == arr[i] && Branchlist[k]->getnode1()->getrank() == neg_node) { Admittance_d3 += Branchlist[k]->get_Admittance(); } } m(neg_node - 1, i) = -Admittance_d2 - Admittance_d3; } } } } } MatrixXcd V = CalculateVoltNode(m, I); // function calculate volt of each node for (int i = 1; i < nonsimple_nodecount; i++) { nonsimple_Nodelist[i]->setvoltage(V(i - 1, 0)); } for (int i = 0; i < branchcount; i++) { Branchlist[i]->Calculatecurrent(); } cout << "..........................." << endl; cout << m << endl; cout << "..........................." << endl; cout << I << endl; cout << "..........................." << endl; cout << V << endl; Save(nonsimple_Nodelist, Branchlist, nonsimple_nodecount, branchcount); return 0; } else if (node_reference == NULL) { for (int i = 0; i < comcount; i++) { Voltage_C_Voltage* vv = dynamic_cast<Voltage_C_Voltage*>(complist[i]); if (vv != NULL) { // node that is not equal to zero int pos_node = vv->get_node1(); if (pos_node == 0) { int cof = -vv->get_cofficient(); int node_d_pos = vv->get_Noded1(); int node_d_neg = vv->get_Noded2(); int node_neg = vv->get_node2(); for (int i = 0; i < num; i++) { m(node_neg - 1, i) = 0; } m(node_neg - 1, node_d_pos - 1) += cof; m(node_neg - 1, node_d_neg - 1) += -cof; m(node_neg - 1, node_neg - 1) += 1; } else if (vv->get_node2() == 0) { int cof = vv->get_cofficient(); int node_d_pos = vv->get_Noded1(); int node_d_neg = vv->get_Noded2(); int node_neg = vv->get_node2(); for (int i = 0; i < num; i++) { m(pos_node - 1, i) = 0; } m(pos_node - 1, node_d_pos - 1) += -cof; m(pos_node - 1, node_d_neg - 1) += cof; m(pos_node - 1, pos_node - 1) += 1; } else { int cof = vv->get_cofficient(); int neg_node = vv->get_node2(); int node_d_pos = vv->get_Noded1(); int node_d_neg = vv->get_Noded2(); m(pos_node - 1, node_d_pos - 1) = 0; m(pos_node - 1, node_d_neg - 1) = 0; m(pos_node - 1, pos_node - 1) = 0; m(pos_node - 1, neg_node - 1) = 0; m(pos_node - 1, pos_node - 1) = 1; m(pos_node - 1, neg_node - 1) = -1; m(pos_node - 1, node_d_pos - 1) += -cof; m(pos_node - 1, node_d_neg - 1) += cof; I(pos_node - 1, 0) = 0; I(neg_node - 1, 0) = 0; for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == pos_node) || (Branchlist[k]->getnode2()->getrank() == pos_node)) && ((Branchlist[k]->getnode1()->getrank() != neg_node) && (Branchlist[k]->getnode2()->getrank() != neg_node))) { Isrc* currentsource = Branchlist[k]->getcsource(); if (currentsource != NULL) { I(neg_node - 1, 0) += Branchlist[k]->getcsource()->getcomplex(); } } } for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == neg_node) || (Branchlist[k]->getnode2()->getrank() == neg_node)) && ((Branchlist[k]->getnode1()->getrank() != pos_node) && (Branchlist[k]->getnode2()->getrank() != pos_node))) { Isrc* currentsource = Branchlist[k]->getcsource(); if (currentsource != NULL) { I(neg_node - 1, 0) += Branchlist[k]->getcsource()->getcomplex(); } } } complex <double> Admittance_d(0, 0); for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == pos_node) || (Branchlist[k]->getnode2()->getrank() == pos_node)) && ((Branchlist[k]->getnode1()->getrank() != neg_node) && (Branchlist[k]->getnode2()->getrank() != neg_node))) { Admittance_d += Branchlist[k]->get_Admittance(); } } m(neg_node - 1, pos_node - 1) = Admittance_d; complex <double> Admittance_d2(0, 0); for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == neg_node) || (Branchlist[k]->getnode2()->getrank() == neg_node)) && ((Branchlist[k]->getnode1()->getrank() != pos_node) && (Branchlist[k]->getnode2()->getrank() != pos_node))) { Admittance_d2 += Branchlist[k]->get_Admittance(); } } m(neg_node - 1, neg_node - 1) = Admittance_d2; Admittance_d2 = 0.0 + 0.0i; complex <double> Admittance_d3(0, 0); for (int i = 0; i < num; i++) { if (i != neg_node - 1 && i != pos_node - 1) { for (int k = 0; k < branchcount; k++) { if (Branchlist[k]->getnode1()->getrank() == arr[i] && Branchlist[k]->getnode2()->getrank() == pos_node || Branchlist[k]->getnode2()->getrank() == arr[i] && Branchlist[k]->getnode1()->getrank() == pos_node) { Admittance_d2 += Branchlist[k]->get_Admittance(); } } for (int k = 0; k < branchcount; k++) { if (Branchlist[k]->getnode1()->getrank() == arr[i] && Branchlist[k]->getnode2()->getrank() == neg_node || Branchlist[k]->getnode2()->getrank() == arr[i] && Branchlist[k]->getnode1()->getrank() == neg_node) { Admittance_d3 += Branchlist[k]->get_Admittance(); } } m(neg_node - 1, i) = -Admittance_d2 - Admittance_d3; } } } } } cout << "................" << endl; cout << m << endl; cout << "................" << endl; cout << I << endl; MatrixXcd V = CalculateVoltNode(m, I); // function calculate volt of each node for (int i = 1; i < nonsimple_nodecount; i++) { nonsimple_Nodelist[i]->setvoltage(V(i - 1, 0)); } for (int i = 0; i < branchcount; i++) { Branchlist[i]->Calculatecurrent(); } cout << "the volt at Each node " << endl; cout << V << endl; Save(nonsimple_Nodelist, Branchlist, nonsimple_nodecount, branchcount); return 0; } } else { /////////////////////////////////////////////// Voltage Source Connected to ground ////////////////////////////////////////// int check_specialcase; int no_Equations = num; Node* node_reference = NULL; for (int i = 0; i < branchcount; i++) { if (Branchlist[i]->getvolt() != NULL && Branchlist[i]->getz() == (0.0 + 0.0i)) { if (Branchlist[i]->getnode1()->getrank() == arr[i] && Branchlist[i]->getnode2()->getrank() == 0) { no_Equations--; node_reference = Branchlist[i]->getnode1(); node_reference->setvoltage(Branchlist[i]->getvolt()->getcomplex()); check_specialcase = Branchlist[i]->getnode1()->getrank(); break; } else if (Branchlist[i]->getnode2()->getrank() == arr[i] && Branchlist[i]->getnode1()->getrank() == 0) { no_Equations--; node_reference = Branchlist[i]->getnode2(); node_reference->setvoltage(-Branchlist[i]->getvolt()->getcomplex()); check_specialcase = Branchlist[i]->getnode2()->getrank(); break; } } } Eigen::MatrixXcd m1(no_Equations, no_Equations); for (int i = 0; i < no_Equations; i++) { for (int j = 0; j < no_Equations; j++) { m1(i, j).real(0); m1(i, j).imag(0); } } Eigen::MatrixXcd I1(no_Equations, 1); for (int i = 0; i < no_Equations; i++) { I1(i, 0) = 0; } complex<double>* admitt = new complex<double>[no_Equations]; for (int l = 0; l < no_Equations; l++) { admitt[l] = 0.0 + 0.0i; } if (node_reference != NULL) { int* arr2 = new int[no_Equations]; int k = 0; for (int i = 0; i < num; i++) { if (arr[i] != check_specialcase) { arr2[k] = arr[i]; k++; } } for (int i = 0; i < no_Equations; i++) { for (int k = 0; k < branchcount; k++) { if ((Branchlist[k]->getnode1()->getrank() == check_specialcase || Branchlist[k]->getnode2()->getrank() == check_specialcase) && (Branchlist[k]->getnode1()->getrank() == arr2[i] || Branchlist[k]->getnode2()->getrank() == arr2[i])) { admitt[i] += Branchlist[k]->get_Admittance(); } } } for (int i = 0; i < no_Equations; i++) { I1(i, 0) += node_reference->getvoltage() * admitt[i]; } for (int k = 0; k < no_Equations; k++) { complex <double> Admittance_s(0, 0); for (int i = 0; i < branchcount; i++) { if ((Branchlist[i]->getnode1()->getrank() == arr2[k]) || (Branchlist[i]->getnode2()->getrank() == arr2[k])) { complex <double> r; r = Branchlist[i]->get_Admittance(); Admittance_s += r; } } m1(k, k) = Admittance_s; } for (int v = 0; v < no_Equations; v++) { for (int k = v + 1; k < no_Equations; k++) { complex <double> Admittance_d(0, 0); for (int l = 0; l < branchcount; l++) { if (((Branchlist[l]->getnode1()->getrank() == arr2[v]) || (Branchlist[l]->getnode2()->getrank() == arr2[v])) && ((Branchlist[l]->getnode1()->getrank() == arr2[k]) || (Branchlist[l]->getnode2()->getrank() == arr2[k]))) { Admittance_d += Branchlist[l]->get_Admittance(); } } m1(v, k) = -Admittance_d; m1(k, v) = -Admittance_d; } } for (int j = 0; j < no_Equations; j++) { for (int i = 0; i < comcount; i++) { Component* comp = complist[i]; Isrc* current = dynamic_cast<Isrc*>(comp); if (current != NULL) { if (current->get_node1() == arr2[j]) { complex <double> curr = current->getcomplex(); I1(j, 0) += curr; } if (current->get_node2() == arr2[j]) { complex <double> curr = -current->getcomplex(); I1(j, 0) += curr; } } } } cout << "................" << endl; cout << m1 << endl; cout << "................" << endl; cout << I1 << endl; cout << "................" << endl; MatrixXcd V1 = CalculateVoltNode(m1, I1); // function calculate volt of each node k = 0; for (int i = 1; i < nonsimple_nodecount; i++) { if (nonsimple_Nodelist[i]->getrank() != check_specialcase) { nonsimple_Nodelist[i]->setvoltage(V1(k, 0)); k++; } } for (int i = 0; i < branchcount; i++) { Branchlist[i]->Calculatecurrent(); cout << "current " << i << " :" << Branchlist[i]->getcurrent(); } cout << "................" << endl; cout << V1; cout << "................" << endl; Save(nonsimple_Nodelist, Branchlist, nonsimple_nodecount, branchcount); return 0; } //////////////////////// Super Node independent Sources ///////////////////////////////////////////////////////// bool R1 = false, R2 = false; int reference1, reference2; Vsrc* voltage_source = NULL; Vsrc* voltage_source2 = NULL; for (int i = 0; i < comcount; i++) { voltage_source = dynamic_cast<Vsrc*> (complist[i]); if (voltage_source != NULL) { for (int j = 0; j < num; j++) { if (voltage_source->get_node1() == arr[j]) { voltage_source2 = voltage_source; reference1 = j; R1 = true; } if (voltage_source->get_node2() == arr[j]) { reference2 = j; R2 = true; } } } } if (R1 && R2) { for (int k = 0; k < num; k++) { for (int i = 0; i < nonsimple_nodecount; i++) { if (voltage_source2->get_node1() == nonsimple_Nodelist[i]->getrank()) { m(0, reference1) = 1; } else if (voltage_source2->get_node2() == nonsimple_Nodelist[i]->getrank()) { m(0, reference2) = -1; } else { m(0, k) = 0; } } I(0, 0) = voltage_source2->getcomplex(); }/////////////// cout << m << endl; complex <double> Admittance_d(0, 0); for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == arr[reference1]) || (Branchlist[k]->getnode2()->getrank() == arr[reference1])) && ((Branchlist[k]->getnode1()->getrank() != arr[reference2]) && (Branchlist[k]->getnode2()->getrank() != arr[reference2]))) { Admittance_d += Branchlist[k]->get_Admittance(); } } m(1, reference1) = Admittance_d; complex <double> Admittance_d2(0, 0); for (int k = 0; k < branchcount; k++) { if (((Branchlist[k]->getnode1()->getrank() == arr[reference2]) || (Branchlist[k]->getnode2()->getrank() == arr[reference2])) && ((Branchlist[k]->getnode1()->getrank() != arr[reference1]) && (Branchlist[k]->getnode2()->getrank() != arr[reference1]))) { Admittance_d2 += Branchlist[k]->get_Admittance(); } } m(1, reference2) = Admittance_d2; Admittance_d2 = 0.0 + 0.0i; complex <double> Admittance_d3(0, 0); for (int i = 0; i < num; i++) { if (i != reference1 && i != reference2) { for (int k = 0; k < branchcount; k++) { if (Branchlist[k]->getnode1()->getrank() == arr[i] && Branchlist[k]->getnode2()->getrank() == arr[reference1] || Branchlist[k]->getnode2()->getrank() == arr[i] && Branchlist[k]->getnode1()->getrank() == arr[reference1]) { Admittance_d2 += Branchlist[k]->get_Admittance(); } } for (int k = 0; k < branchcount; k++) { if (Branchlist[k]->getnode1()->getrank() == arr[i] && Branchlist[k]->getnode2()->getrank() == arr[reference2] || Branchlist[k]->getnode2()->getrank() == arr[i] && Branchlist[k]->getnode1()->getrank() == arr[reference2]) { Admittance_d3 += Branchlist[k]->get_Admittance(); } } m(1, i) = -Admittance_d2 - Admittance_d3; } } for (int i = 2; i < num; i++) { for (int j = 0; j < num; j++) { if (arr[j] == voltage_source->get_node2() || arr[j] == voltage_source->get_node1()) { } else { complex <double> Admittance_s(0, 0); for (int k = 0; k < branchcount; k++) { if ((Branchlist[i]->getnode1()->getrank() == arr[j]) || (Branchlist[i]->getnode2()->getrank() == arr[j])) { complex <double> r; r = Branchlist[i]->get_Admittance(); Admittance_s += r; if (Branchlist[i]->getnode1()->getrank() == arr[reference1] || Branchlist[i]->getnode2()->getrank() == arr[reference1]) { Admittance_d = 0.0 + 0.0i; Admittance_d = Branchlist[i]->get_Admittance(); } if (Branchlist[i]->getnode1()->getrank() == arr[reference2] || Branchlist[i]->getnode2()->getrank() == arr[reference2]) { Admittance_d2 = 0.0 + 0.0i; Admittance_d2 = Branchlist[i]->get_Admittance(); } } } m(i, j) = Admittance_s; m(i, reference1) = -Admittance_d; m(i, reference1) = -Admittance_d2; } } } ////////////////// Calculate Currents /////////////////////////////// for (int j = 1; j < num; j++) { for (int i = 0; i < comcount; i++) { Component* comp = complist[i]; Isrc* current = dynamic_cast<Isrc*>(comp); if (current != NULL) { if (true) { if (current->get_node1() == arr[j] || current->get_node2() == arr[j]) { complex <double> curr = current->getcomplex(); I(j, 0) += curr; } if (current->get_node2() == arr[j-1] || current->get_node1() == arr[j - 1]) { complex <double> curr = current->getcomplex(); I(j, 0) += curr; } } } } } cout << "................" << endl; cout << m << endl; cout << "................" << endl; cout << I << endl; cout << "................" << endl; ///////////////// calculate volts ///////////////////////////////// MatrixXcd V = CalculateVoltNode(m, I); // function calculate volt of each node for (int i = 1; i < nonsimple_nodecount; i++) { nonsimple_Nodelist[i]->setvoltage(V(i - 1, 0)); } for (int i = 0; i < branchcount; i++) { Branchlist[i]->Calculatecurrent(); } cout << V; Save(nonsimple_Nodelist, Branchlist, nonsimple_nodecount, branchcount); return 0; } //////////////////code dependent /////////////////////////////////////////////////// for (int k = 0; k < num; k++) { complex <double> Admittance_s(0, 0); for (int i = 0; i < branchcount; i++) { if ((Branchlist[i]->getnode1()->getrank() == arr[k]) || (Branchlist[i]->getnode2()->getrank() == arr[k])) { complex <double> r; r = Branchlist[i]->get_Admittance(); Admittance_s += r; } } m(k, k) = Admittance_s; } for (int v = 0; v < num; v++) { for (int k = v + 1; k < num; k++) { complex <double> Admittance_d(0, 0); for (int l = 0; l < branchcount; l++) { if (((Branchlist[l]->getnode1()->getrank() == arr[v]) || (Branchlist[l]->getnode2()->getrank() == arr[v])) && ((Branchlist[l]->getnode1()->getrank() == arr[k]) || (Branchlist[l]->getnode2()->getrank() == arr[k]))) { Admittance_d += Branchlist[l]->get_Admittance(); } } m(v, k) = -Admittance_d; m(k, v) = -Admittance_d; } } for (int j = 0; j < num; j++) { for (int i = 0; i < comcount; i++) { Component* comp = complist[i]; Isrc* current = dynamic_cast<Isrc*>(comp); if (current != NULL) { if (current->get_node1() == arr[j]) { complex <double> curr = current->getcomplex(); I(j, 0) += curr; } if (current->get_node2() == arr[j]) { complex <double> curr = -current->getcomplex(); I(j, 0) += curr; } } } } MatrixXcd V = CalculateVoltNode(m, I); // function calculate volt of each node for (int i = 1; i < nonsimple_nodecount; i++) { nonsimple_Nodelist[i]->setvoltage(V(i - 1, 0)); } for (int i = 0; i < branchcount; i++) { Branchlist[i]->Calculatecurrent(); } cout << "..........................." << endl; cout << "Matrix of admittance" << endl; cout << m << endl; cout << "..........................." << endl; cout << "Matrix of I" << endl; cout << I << endl; cout << "..........................." << endl; cout << "volt at nonsimplenode" << endl; cout << V << endl; ///////////////////////////////////////////// calculate the value of voltage on simple node /////////////////////////////////////////// for (int i = 0; i < simple_nodecount; i++) { for (int j = 0; j < nonsimple_nodecount; j++) { if (simple_Nodelist[i]->getvoltage() != 0.0) { for (int k = 0; k < branchcount; k++) { if ((Branchlist[k]->getnode1() == simple_Nodelist[i] || Branchlist[k]->getnode2() == simple_Nodelist[i]) && (Branchlist[k]->getnode1() == nonsimple_Nodelist[j] || Branchlist[k]->getnode2() == nonsimple_Nodelist[j])) { complex<double>x = Branchlist[k]->getcurrent() * Branchlist[k]->getz(); complex<double>c = 0.0; if (Branchlist[k]->getvolt() != NULL) { c = Branchlist[k]->getvolt()->getcomplex(); } complex<double>e = nonsimple_Nodelist[j]->getvoltage(); int N1 = Branchlist[k]->getnode1()->getrank(); int N2 = Branchlist[k]->getnode2()->getrank(); Component* comp2 = NULL; for (int i = 0; i < comcount; i++) { if (((complist[i]->get_node1() == N1) && (complist[i]->get_node2() == N2)) || ((complist[i]->get_node1() == N2) && (complist[i]->get_node2() == N1))) { comp2 = complist[i]; } } int pos_node = comp2->get_node1(); int neg_node = comp2->get_node2(); if (pos_node == simple_Nodelist[i]->getrank() && neg_node == nonsimple_Nodelist[j]->getrank()) { complex<double> cs = x + e + c; simple_Nodelist[i]->setvoltage(cs); } else if (neg_node == simple_Nodelist[i]->getrank() && pos_node == nonsimple_Nodelist[j]->getrank()) { complex<double> cs = e - x - c; simple_Nodelist[i]->setvoltage(cs); } break; } } } } } int zero_volt = 0; int non_zerovolt = 0; for (int i = 0; i < simple_nodecount; i++) { if (simple_Nodelist[i]->getvoltage() == 0.0) { zero_volt++; } else { non_zerovolt++; } } if (non_zerovolt != 0) { Node** zero_voltlist = new Node * [zero_volt]; Node** nonzero_voltlist = new Node * [non_zerovolt]; int i1 = 0; int i2 = 0; for (int i = 0; i < simple_nodecount; i++) { if (simple_Nodelist[i]->getvoltage() == 0.0) { zero_voltlist[i1] = simple_Nodelist[i]; i1++; } else { nonzero_voltlist[i2] = simple_Nodelist[i]; i2++; } } for (int i = 0; i < i1; i++) { for (int j = 0; j < i2; j++) { if (zero_voltlist[i]->getvoltage() != 0.0) { for (int k = 0; k < branchcount; k++) { if ((Branchlist[k]->getnode1() == zero_voltlist[i] || Branchlist[k]->getnode2() == zero_voltlist[i]) && (Branchlist[k]->getnode1() == nonzero_voltlist[j] || Branchlist[k]->getnode2() == nonzero_voltlist[j])) { complex<double>x = Branchlist[k]->getcurrent() * Branchlist[k]->getz(); complex<double>c = 0.0; if (Branchlist[k]->getvolt() != NULL) { c = Branchlist[k]->getvolt()->getcomplex(); } complex<double>e = nonzero_voltlist[j]->getvoltage(); int N1 = Branchlist[k]->getnode1()->getrank(); int N2 = Branchlist[k]->getnode2()->getrank(); Component* comp2 = NULL; for (int i = 0; i < comcount; i++) { if (((complist[i]->get_node1() == N1) && (complist[i]->get_node2() == N2)) || ((complist[i]->get_node1() == N2) && (complist[i]->get_node2() == N1))) { comp2 = complist[i]; } } int pos_node = comp2->get_node1(); int neg_node = comp2->get_node2(); if (pos_node == zero_voltlist[i]->getrank() && neg_node == nonzero_voltlist[j]->getrank()) { complex<double> cs = x + e + c; zero_voltlist[i]->setvoltage(cs); } else if (neg_node == zero_voltlist[i]->getrank() && pos_node == nonzero_voltlist[j]->getrank()) { complex<double> cs = e - x - c; zero_voltlist[i]->setvoltage(cs); } break; } } } } } } cout << "\nvoltage at simple nodes" << endl; for (int i = 0; i < simple_nodecount; i++) { cout<<simple_Nodelist[i]<<" "; } Save(nonsimple_Nodelist, Branchlist, nonsimple_nodecount, branchcount); return 0; } return 0; } MatrixXcd CalculateVoltNode(MatrixXcd G, MatrixXcd I) { MatrixXcd V; V = G.inverse() * I; return V; } int searcher(string x) { int c; Component* comp = NULL; for (int i = 0; i < comcount; i++) { string name = complist[i]->get_name(); if ((name.compare(x) == 0)) { comp = complist[i]; c = i; } } return c; } void Save(Node** list1, Branch** list2,int num1,int num2 ) { string name; cout << endl; cout << "enter the name of file (name .txt)" << endl; cin >> name; ofstream outputfile(name); outputfile << "the voltage at each node :" << endl; for (int i = 0; i < num1; i++) { outputfile << "v1" << " " << list1[i]->getvoltage() << endl;; } for (int i = 0; i < num2; i++) { int n1 =list2[i]->getnode1()->getrank(); int n2 = list2[i]->getnode2()->getrank(); outputfile << "I" << " " << n1 << " " << n2 << " " << list2[i]->getcurrent() << endl; } outputfile.close(); }
0fa6199574c9d9e083877b00483ac33ae6ac8302
332b6c8e272a0ac3c580dcf9c0a4afad2fd4f484
/jni/audio_fft_test/discrete_point_fft.h
985e4c8a83ec6f665324ead5c644e177fe286c83
[]
no_license
TellMeYourName/Ne10-sample-test
c52c473c894fc02a5c261ffb8710adf20277d7a7
a98e359cd5fa4b4c07668453749cf3fd18aa7247
refs/heads/master
2021-06-18T04:53:50.236967
2017-07-04T04:00:18
2017-07-04T04:00:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
842
h
discrete_point_fft.h
#ifndef _DISCRETE_POINT_FFT_H_ #define _DISCRETE_POINT_FFT_H_ #include "CommonTools.h" #include "./mayer_fft/fft_routine.h" class DisCretePointFFT { public: DisCretePointFFT(); virtual ~DisCretePointFFT(); void test(); private: /** 汉明窗 **/ float* m_hannwindow; int m_corrsize; void buildData(short* buffer, int size); /** 使用MayerFFT所定义的变量与生命周期方法 **/ FftRoutine* fftRoutine; float* m_ffttime; float* m_fftfreqre; float* m_fftfreqim; void mayerFFTInit(); void mayerFFTProcess(short* buffer, int size); void mayerFFTDestroy(); /** 使用DSPFFT所定义的变量与生命周期方法 **/ ne10_fft_r2c_cfg_float32_t cfg; // An FFT "configuration structure" void dspFFTInit(); void dspFFTProcess(short* buffer, int size); void dspFFTDestroy(); }; #endif //_DISCRETE_POINT_FFT_H_
5f9746693262e2dc1939ab658bc8194ef0104c95
3a200778c4f6bb7d4f4f2a3c8ee4e63757edaee1
/src/projector/ProjectorOpenGL.cpp
c9f7a5a6f313b1f3ab9861e32a840d84f2f41636
[]
no_license
arkbriar/slstudio
e2179cf5d2563c481d715644cedd2ef5eea36181
abe12bc909e81ea5e6bbba1c7d1f239a378fa7df
refs/heads/master
2021-01-17T22:04:44.631504
2017-05-14T13:46:09
2017-05-14T13:46:09
84,187,632
5
2
null
2017-03-07T10:43:14
2017-03-07T10:43:13
null
UTF-8
C++
false
false
7,656
cpp
ProjectorOpenGL.cpp
#include "ProjectorOpenGL.h" ProjectorOpenGL::ProjectorOpenGL(unsigned int _screenNum) { // Create the OpenGL context context = new OpenGLContext(_screenNum); // OpenGL setup context->makeContextCurrent(); glEnable(GL_TEXTURE_2D); glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); // Set up for 1:1 pixel mapping in the z=0 plane. Upper left corner is (0,0). glViewport(0, 0, context->getScreenResX(), context->getScreenResY()); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 1, 1, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Set up fragment shader GLenum err = glewInit(); if (err != GLEW_OK) std::cerr << "ProjectorOpenGL: Could not initialize GLEW!" << std::endl; // const GLchar *vertexShaderSource = // "void main(){\n" // " gl_Position = ftransform();\n" // "}"; // const GLchar *fragmentShaderSource = // "uniform sampler2D texture;\n" // "void main(void){\n" // " gl_FragColor = texture2D(texture, gl_TexCoord[0].st);\n" // "}"; // GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); // glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); // glCompileShader(vertexShader); // GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); // glCompileShader(fragmentShader); // GLint status; // glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); // if(status != GL_TRUE) // std::cerr << "ProjectorOpenGL: Could not compile vertex shader!" << std::endl; // glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status); // if(status != GL_TRUE) // std::cerr << "ProjectorOpenGL: Could not compile fragment shader!" << std::endl; // int len = 0; // glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &len); // char* log = new char[len]; // glGetShaderInfoLog(vertexShader, len, NULL, log); // std::cout << log << std::endl; // glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &len); // glGetShaderInfoLog(fragmentShader, len, NULL, log); // std::cout << log << std::endl; // shaderProgram = glCreateProgram(); // glAttachShader(shaderProgram, vertexShader); // glAttachShader(shaderProgram, fragmentShader); // glLinkProgram(shaderProgram); // glUseProgram(shaderProgram); context->flush(); } void ProjectorOpenGL::setPattern(unsigned int patternNumber, const unsigned char *tex, unsigned int texWidth, unsigned int texHeight) { context->makeContextCurrent(); if (patternNumber + 1 == frameBuffers.size() + 1) { GLuint frameBuffer; // Generate frame buffer object glGenFramebuffers(1, &frameBuffer); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer); frameBuffers.push_back(frameBuffer); // Generate render buffer object to store pixel data GLuint renderBuffer; glGenRenderbuffers(1, &renderBuffer); glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, context->getScreenResX(), context->getScreenResY()); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderBuffer); GLint status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) std::cout << "Error Framebuffer Complete" << std::endl; else std::cout << "Framebuffer Complete" << std::endl; } else if (patternNumber < frameBuffers.size()) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffers[patternNumber]); } else if (patternNumber + 1 > frameBuffers.size() + 1) { std::cerr << "ProjectorOpenGL: cannot set pattern " << patternNumber << " before setting " << frameBuffers.size() << " -- " << patternNumber - 1 << std::endl; return; } // Render pattern into buffer glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, tex); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_FALSE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); float texWidthf = (float)context->getScreenResX() / texWidth; float texHeightf = (float)context->getScreenResY() / texHeight; glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2i(0, 0); glTexCoord2f(texWidthf, 0); glVertex2i(1, 0); glTexCoord2f(texWidthf, texHeightf); glVertex2i(1, 1); glTexCoord2f(0, texHeightf); glVertex2i(0, 1); glEnd(); } void ProjectorOpenGL::displayPattern(unsigned int patternNumber) { if (patternNumber + 1 > frameBuffers.size()) { std::cerr << "ProjectorOpenGL: cannot display pattern " << patternNumber << "! Out of bounds." << std::endl; return; } context->makeContextCurrent(); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBuffers[patternNumber]); glBlitFramebuffer(0, 0, context->getScreenResX(), context->getScreenResY(), 0, 0, context->getScreenResX(), context->getScreenResY(), GL_COLOR_BUFFER_BIT, GL_NEAREST); // glClear(GL_COLOR_BUFFER_BIT); // glBindTexture(GL_TEXTURE_2D, textures[patternNumber].texName); // GLint locTex = glGetUniformLocation(shaderProgram, "texture"); // glUniform1i(locTex, 0); context->flush(); } void ProjectorOpenGL::displayTexture(const unsigned char *tex, unsigned int texWidth, unsigned int texHeight) { context->makeContextCurrent(); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, tex); // glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_FALSE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); float texWidthf = (float)context->getScreenResX() / texWidth; float texHeightf = (float)context->getScreenResY() / texHeight; glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2i(0, 0); glTexCoord2f(texWidthf, 0); glVertex2i(1, 0); glTexCoord2f(texWidthf, texHeightf); glVertex2i(1, 1); glTexCoord2f(0, texHeightf); glVertex2i(0, 1); glEnd(); context->flush(); } void ProjectorOpenGL::displayBlack() { context->makeContextCurrent(); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); context->flush(); } void ProjectorOpenGL::displayWhite() { context->makeContextCurrent(); glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); context->flush(); } void ProjectorOpenGL::getScreenRes(unsigned int *nx, unsigned int *ny) { *nx = context->getScreenResX(); *ny = context->getScreenResY(); } ProjectorOpenGL::~ProjectorOpenGL() { context->makeContextCurrent(); delete context; }
6dc5f4d70f2c6e02dc60e082050142eace9c2e12
c360bda7972554be8e9bb2cff42db68e4a2f1eb9
/simview_vs2015/params.cpp
98d663cbc9f53316e64974e3eaea412a45ab853a
[]
no_license
zhou-l/simview_vs2015
8c2caa5ee9c605b36a81d6bc7c0917543a18c942
726479c11dcc1f54afe3e6d27dabb6e8f963a01f
refs/heads/master
2021-08-30T05:14:52.491253
2017-12-16T05:00:38
2017-12-16T05:00:38
113,353,612
0
0
null
null
null
null
UTF-8
C++
false
false
1,523
cpp
params.cpp
#include "params.h" #include "SysTools.h" #include "MersenneTwister.h" using namespace std; Params::Params(): _meshKDtree(3) { VolBlockSize(32); ensStatNumOutliers(4); ensStatNumNeighbors(8); _randGen = new MTRand(); currentRun(0); // should set to the mean run string folder = "C:/MyData/Utah_heart_ischemia/201701_Conductivity/simRuns/dataset_test"; runFileFolder(folder); string meshFile = "C:\\MyData\\Utah_heart_ischemia\\201701_Conductivity\\mesh\\heartPts.csv"; meshFileName(meshFile); // Get number of runs vector<string> folderContent = SysTools::GetDirContents(folder, "*", "txt"); vector<string> runFileList; for (size_t i = 0; i < folderContent.size(); i++) { if (folderContent[i].find("run") != std::string::npos) runFileList.push_back(folderContent[i]); } setRunFileList(runFileList); numRuns(int(runFileList.size())); } Params::~Params() { _meshKDtree.clear(); SAFE_DELETE(_randGen); } const std::vector<std::vector<float> >& Params::pointData() const { return _pointData; } void Params::setPointData(const std::vector<std::vector<float> > &pointData) { _pointData = pointData; } const std::vector<Vertex>& Params::vertices() const { return _vertices; } void Params::setVertices(const std::vector<Vertex> &vertices) { _vertices = vertices; } const std::vector<std::vector<float> >& Params::ensembleData() const { return _ensembleData; } void Params::setEnsembleData(const std::vector<std::vector<float> > &val) { _ensembleData = val; }
d3f9eee15602998bac6d0e2d2630dfa1ed153d52
60a95653baf5feb6a61cb66efc198ddfd4ac9a1e
/src/gpurt.h
cf9220ddb9088b0da2e94e07e17fc6cdfd541cad
[]
no_license
TheNumbat/GPU-RT
9c066002c727729c592cde6177857bb16b90a083
2912c8335b52fa83d3d825563b93fc908aee70ea
refs/heads/main
2023-04-26T10:53:09.627720
2021-05-24T06:29:14
2021-05-24T06:29:14
358,044,311
20
0
null
null
null
null
UTF-8
C++
false
false
1,649
h
gpurt.h
#pragma once #include <SDL2/SDL.h> #include <platform/window.h> #include <lib/mathlib.h> #include <scene/scene.h> #include <vk/rt.h> #include <vk/effect.h> #include <vk/mesh.h> class GPURT { public: GPURT(Window& window, std::string scene_file); ~GPURT(); void loop(); private: void event(SDL_Event e); void render(); void apply_window_dim(Vec2 new_dim); void UIsidebar(); void load_scene(); void edit_material(Material& opt); void build_images(); void build_accel(); void build_frames(); void build_pipe(); void build_pass(); void build_rt(); void save_rt(); static inline const char* scene_file_types = "dae,obj,fbx,glb,gltf,3ds,blend,stl,ply"; static inline const char* image_file_types = "exr,hdr,hdri,jpg,jpeg,png,tga,bmp,psd,gif"; unsigned int selected_id = 0; enum class Camera_Control { none, orbit, move }; Camera_Control cam_mode = Camera_Control::none; Camera cam; Window& window; Scene scene; std::vector<VK::Drop<VK::Accel>> BLAS; std::vector<Mat4> BLAS_T; VK::Drop<VK::Accel> TLAS; VK::Drop<VK::Image> rt_target; VK::Drop<VK::ImageView> rt_target_view; struct Frame { VK::Drop<VK::Image> color, depth; VK::Drop<VK::ImageView> color_view, depth_view; VK::Drop<VK::Framebuffer> m_fb, ef_fb; }; bool use_rt = true; bool rebuild_tlas = true; bool rebuild_blas = true; std::array<Frame, VK::Manager::MAX_IN_FLIGHT> frames; VK::Drop<VK::Pass> mesh_pass, effect_pass; VK::MeshPipe mesh_pipe; VK::EffectPipe effect_pipe; VK::RTPipe rt_pipe; };
7cd373cb3b3b60db3ab8ec744db402e6c5fda989
34f2081361c2cdb28649db5c311b23ae45729867
/Codeforces/285b.cpp
1b3b6fe7a58259f9d293ee785163de79b0226481
[]
no_license
shashank21j/CompetitiveProgramming
bd7d1516bda0047162293f62e78a8f3134021454
5e905ad7f59f36541baaa669391eba667f291a45
refs/heads/master
2022-02-14T08:12:05.656586
2022-01-30T02:56:15
2022-01-30T02:56:15
14,283,517
4
1
null
null
null
null
UTF-8
C++
false
false
327
cpp
285b.cpp
#include <bits/stdc++.h> using namespace std; int main() { int n,s,t; cin>>n>>s>>t; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } int count = 0; for (int i=0;i<=n;i++) { if (s == t) { break; } s = Arr[s-1]; count++; } if (count == n+1) cout<<"-1"<<endl; else cout<<count<<endl; return 0; }
d30caa9225b16251357f0f7c4fe2c17c3a061af3
633bff0938643c0fd7b535e2b30e2eb57f5e87a7
/C++ Games/MyGame/Src/Scene/TextHighlighterComponent.cpp
2ba4ea0ee19c2861c1c80a519eea9f8393d2fa59
[]
no_license
PaulPopa/Games
98b7595861b42f7dd467f21bd751fe188cd5aac8
ed0f36333dcbaf1bf35a35217845249351ec9a7a
refs/heads/master
2021-01-10T16:03:45.241239
2018-05-31T09:27:51
2018-05-31T09:27:51
43,204,837
0
0
null
null
null
null
UTF-8
C++
false
false
2,207
cpp
TextHighlighterComponent.cpp
#include "TextHighlighterComponent.h" #include "App.h" #include "Helpers.h" #include "stdincl.h" #include "Input.h" #include "SpriteComponent.h" REGISTERIMPL(TextHighlighterComponent); TextHighlighterComponent::TextHighlighterComponent() : m_selected(false) { } TextHighlighterComponent::~TextHighlighterComponent() { } void TextHighlighterComponent::OnStart() { auto textComp = m_object->GetComponent<TextComponent>(); assert(textComp); auto color = textComp->GetColor(); m_highlightedColorMask.x = (float)Min((int)m_highlightedColorMask.x, color.r - (int)m_highlightedColorMask.x); m_highlightedColorMask.y = (float)Min((int)m_highlightedColorMask.y, color.g - (int)m_highlightedColorMask.y); m_highlightedColorMask.z = (float)Min((int)m_highlightedColorMask.z, color.b - (int)m_highlightedColorMask.z); } void TextHighlighterComponent::Update(float dtime) { } void TextHighlighterComponent::Select() { if (!m_selected) { auto textComp = m_object->GetComponent<TextComponent>(); assert(textComp); auto color = textComp->GetColor(); color.r += m_highlightedColorMask.x; color.g += m_highlightedColorMask.y; color.b += m_highlightedColorMask.z; textComp->SetColor(color); } } void TextHighlighterComponent::UnSelect() { if (m_selected) { auto textComp = m_object->GetComponent<TextComponent>(); assert(textComp); auto color = textComp->GetColor(); color.r -= m_highlightedColorMask.x; color.g -= m_highlightedColorMask.y; color.b -= m_highlightedColorMask.z; textComp->SetColor(color); } } void TextHighlighterComponent::CheckMouseCollision() { auto textComp = m_object->GetComponent<TextComponent>(); assert(textComp); Vector2f diff = g_input->GetMousePosition() - m_object->GetGlobalPos(); float alpha = -m_object->GetGlobalRotation() * (float)PI / 180.f; Vector2f rotatedDiff = Vector2f(diff.x * cos(alpha) - diff.y * sin(alpha), diff.x * sin(alpha) + diff.y * cos(alpha)); if (rotatedDiff.x >= 0 && rotatedDiff.y >= 0 && rotatedDiff.x <= textComp->GetSize().x && rotatedDiff.y <= textComp->GetSize().y) { Select(); } else { UnSelect(); } } void TextHighlighterComponent::ParseAttribute(const TiXmlAttribute* attribute) { }
c68057798c6fab3313673fce0a8e9ccbb707e86e
6b86a8e198ddcacef5efa25b7068aedb5b99a1e9
/engine/ui/components/LayoutPanel.cpp
05f9d4071968bbc21dc7dcb4bcb1bd7698c6c727
[]
no_license
mattiejas/Push-d-Out
82884859622b62dabf971e21915ef9315c13307f
564ea23218f95b6bbf12aea91df0d9a7a7cbff84
refs/heads/master
2023-03-15T01:33:34.778444
2018-11-06T12:35:33
2018-11-06T12:35:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,969
cpp
LayoutPanel.cpp
#include "LayoutPanel.h" #include <algorithm> namespace engine { namespace ui { void LayoutPanel::addComponent(const std::shared_ptr<Component>& component, LayoutAnchor anchor) { std::shared_ptr<WrappedComponent> wrappedComponent = std::make_shared<WrappedComponent>(component, anchor); m_components.insert(wrappedComponent); } DrawContext LayoutPanel::draw(DrawContext context) { DrawContext compositeContext{ context }; DrawContext childContext{ context }; childContext.availableSize = (context.availableSize / sumRelativeSize()).castTo<int>(); for (const auto& component : m_components) { common::Vector2D<int> childPosition = getChildPosition(context.renderer, *component.get(), childContext.availableSize, context.availableSize); childContext.pos = childPosition + context.pos; DrawContext updatedContext = component->draw(childContext); compositeContext.pos = common::Vector2D<int>::max(compositeContext.pos, updatedContext.pos); } return compositeContext; } common::Vector2D<int> LayoutPanel::calculateSize(const IRenderer& renderer, common::Vector2D<int> availableSize) const { common::Vector2D<int> requiredSize{ 0, 0 }; common::Vector2D<int> availableChildSize = (availableSize / sumRelativeSize()).castTo<int>(); for (const auto& component : m_components) { common::Vector2D<int> componentSize = component->getComponent()->calculateSize(renderer, availableChildSize); if (m_flowDirection == FlowDirection::Horizontal) { requiredSize.x += componentSize.x; requiredSize.y = std::max(requiredSize.y, componentSize.y); } else { requiredSize.y += componentSize.y; requiredSize.x = std::max(requiredSize.x, componentSize.x); } } return m_size.getSize(requiredSize, availableSize); } common::Vector2D<double> LayoutPanel::sumRelativeSize() const { common::Vector2D<int> minimumSize{ 1, 1 }; common::Vector2D<double> sum{ 1, 1 }; for (const auto& component : m_components) { sum += component->getComponent()->getSize().getRelativeRatio(); } if (m_flowDirection == FlowDirection::Vertical) { sum.x = 1; } else { sum.y = 1; } return common::Vector2D<double>::max(sum, minimumSize.castTo<double>()); } common::Vector2D<int> LayoutPanel::getChildPosition(const IRenderer& renderer, const WrappedComponent& component, common::Vector2D<int> availableSize, common::Vector2D<int> parentSize) const { common::Vector2D<int> position{ 0, 0 }; common::Vector2D<int> calculatedSize = component.getComponent()->calculateSize(renderer, availableSize); switch (component.getAnchor()) { case LayoutAnchor::Start: break; case LayoutAnchor::End: if (m_flowDirection == FlowDirection::Horizontal) { position.x = parentSize.x - calculatedSize.x; } else { position.y = parentSize.y - calculatedSize.y; } break; case LayoutAnchor::Center: if (m_flowDirection == FlowDirection::Horizontal) { position.x = (parentSize.x - calculatedSize.x) / 2; } else { position.y = (parentSize.y - calculatedSize.y) / 2; } break; } return position; } std::shared_ptr<Component> LayoutPanel::getNavigatableAt(size_t index) const { size_t currentTotal = 0; for (const auto& wrapper : m_components) { auto* panel = dynamic_cast<ComponentPanel*>(wrapper->getComponent().get()); if (panel != nullptr) { size_t childTotal = panel->countNavigatableChildren(); if (currentTotal + childTotal > index) { return panel->getNavigatableAt(index - currentTotal); } currentTotal += childTotal; } else if (wrapper->getComponent()->isNavigatable()) { currentTotal++; if (currentTotal > index) { return wrapper->getComponent(); } } } return nullptr; } size_t LayoutPanel::countNavigatableChildren() const { size_t total = 0; for (const auto& wrapper : m_components) { auto* panel = dynamic_cast<ComponentPanel*>(wrapper->getComponent().get()); if (panel != nullptr) { total += panel->countNavigatableChildren(); } else if (wrapper->getComponent()->isNavigatable()) { total++; } } return total; } } }