hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e1be2e761d7913fa6e1dde8363dc8c266fd60ba1
| 4,968
|
cpp
|
C++
|
Structures/Common/ResiduePropertiesAssignation.cpp
|
ElianeBriand/SMolDock
|
de0cb746ef995ae0eef0f812ebd61727311c332f
|
[
"Apache-2.0"
] | 1
|
2019-05-30T02:33:13.000Z
|
2019-05-30T02:33:13.000Z
|
Structures/Common/ResiduePropertiesAssignation.cpp
|
ElianeBriand/SMolDock
|
de0cb746ef995ae0eef0f812ebd61727311c332f
|
[
"Apache-2.0"
] | null | null | null |
Structures/Common/ResiduePropertiesAssignation.cpp
|
ElianeBriand/SMolDock
|
de0cb746ef995ae0eef0f812ebd61727311c332f
|
[
"Apache-2.0"
] | 3
|
2020-12-30T19:11:51.000Z
|
2021-06-25T02:45:49.000Z
|
/*
* Copyright (c) 2018 Eliane Briand
*
* This file is part of SmolDock.
*
* SmolDock 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.
*
* SmolDock 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 SmolDock. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include <boost/assert.hpp>
#include "ResiduePropertiesAssignation.h"
#include "Structures/Bond.h"
#include <boost/log/trivial.hpp>
#include "PDBResiduePropertiesTable.h"
namespace SmolDock {
void assignPropertiesForResidueAtom(AminoAcid &residue, PDBResidueVariantAssignationType assignation_type) {
std::map<AminoAcid::AAType, std::map<std::string, std::tuple<Atom::AtomVariant, double> > > *ResidueAtomPropertiesLookupTable;
if (assignation_type == PDBResidueVariantAssignationType::GeneralPurpose) {
ResidueAtomPropertiesLookupTable = &ResidueAtomPropertiesLookupTable_General;
} else {
ResidueAtomPropertiesLookupTable = &ResidueAtomPropertiesLookupTable_General;
}
AminoAcid::AAType type = residue.getType();
if (type == AminoAcid::AAType::unknown) {
BOOST_LOG_TRIVIAL(error)
<< "Encountered unknown residue type while assigning atom variant. Check PDB file. Undefined behaviour may occur.";
} else {
auto record_it = ResidueAtomPropertiesLookupTable->find(type);
if (record_it == std::end(*ResidueAtomPropertiesLookupTable)) {
// Not found
BOOST_LOG_TRIVIAL(error)
<< "Amino acid not found in ResidueAtomPropertiesLookupTable. Variant assignation not done for this amino acid.";
return;
}
for (auto &atom : residue.atoms) {
std::string complete_atom_name = atom->rawPDBAtomName;
auto nameTypeTuple_it = record_it->second.find(complete_atom_name);
if (nameTypeTuple_it != std::end(record_it->second)) {
// We have an association between complete atom name and AtomVariant
Atom::AtomVariant newVariant = atom->getAtomVariant() | std::get<0>(nameTypeTuple_it->second);
atom->setAtomVariant(newVariant);
atom->setCharge(std::get<1>(nameTypeTuple_it->second));
} else {
BOOST_LOG_TRIVIAL(error)
<< "Missing record for residue " << resTypeToString(type) << ", atom "
<< complete_atom_name;
}
}
}
}
void assignApolarCarbonFlag(std::vector<std::shared_ptr<Atom> > &atomVect) {
for (auto &atom: atomVect) {
if (atom->getAtomType() == Atom::AtomType::carbon) {
bool isLinkedToHeteroatom = false;
for (const auto &bond_weakptr: atom->bonds) {
std::shared_ptr<Bond> bond = bond_weakptr.lock();
if (bond == nullptr) {
BOOST_LOG_TRIVIAL(error)
<< "Encountered nullptr weak_ptr while traversing molecule. This is definitely a bug: please report.";
BOOST_LOG_TRIVIAL(error) << "Exiting unsucessfully...";
std::exit(6);
}
std::shared_ptr<Atom> endA = bond->getEndA();
std::shared_ptr<Atom> endB = bond->getEndB();
BOOST_ASSERT((endA.get() == atom.get()) !=
(endB.get() ==
atom.get())); // Check that the current atom is exactly one of the end (!= is logical XOR for bool)
std::shared_ptr<Atom> opposite_end;
if (endA.get() == atom.get())
// The current atom is EndA
opposite_end = endB;
else if (endB.get() == atom.get())
// The current atom is EndB
opposite_end = endA;
Atom::AtomType linked_atom_type = opposite_end->getAtomType();
if ((linked_atom_type != Atom::AtomType::carbon) &&
(linked_atom_type != Atom::AtomType::hydrogen)) {
isLinkedToHeteroatom = true;
}
}
if (!isLinkedToHeteroatom) {
atom->variant = atom->variant | Atom::AtomVariant::apolar;
}
}
}
}
}
| 41.057851
| 134
| 0.572464
|
ElianeBriand
|
e1c659c90126678fcb3d9e8d8d37f1bc0543684f
| 1,470
|
cpp
|
C++
|
AutopilotRemoteRFM69/src/main.cpp
|
chacal/arduino
|
6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd
|
[
"Apache-2.0"
] | 4
|
2016-12-10T13:20:52.000Z
|
2019-10-25T19:47:44.000Z
|
AutopilotRemoteRFM69/src/main.cpp
|
chacal/arduino
|
6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd
|
[
"Apache-2.0"
] | null | null | null |
AutopilotRemoteRFM69/src/main.cpp
|
chacal/arduino
|
6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd
|
[
"Apache-2.0"
] | 1
|
2019-05-03T17:31:38.000Z
|
2019-05-03T17:31:38.000Z
|
#include <SPI.h>
#include <RFM69.h>
#include "main.h"
#include "buttons.h"
#include <EEPROM.h>
#include <LowPower.h>
static RFM69 radio(RFM69_NSS_PIN, RF69_IRQ_PIN, true);
static Config config;
unsigned long wakeUpTime = 0;
void setup() {
Serial.begin(SERIAL_BAUD);
initializeConfig();
initializeRadio();
setupPinChangeInterrupts();
setupButtonCallbacks(&radio, &config);
goToSleep();
}
void loop() {
updateButtonStates();
if(hasMinAwakeTimeElapsed() && noButtonsPressed()) {
goToSleep();
}
}
bool hasMinAwakeTimeElapsed() { return millis() - wakeUpTime > MIN_AWAKE_TIME_MS; }
void goToSleep() {
if(DEBUG) {
Serial.println("Sleeping");
Serial.flush();
}
LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
wakeUpTime = millis();
}
void initializeRadio() {
radio.initialize(FREQUENCY, INSTANCE, NETWORKID);
radio.setHighPower();
radio.setPowerLevel(20);
radio.sleep();
}
void initializeConfig() {
EEPROM.get(CONFIG_EEPROM_ADDR, config);
if(FORCE_CONFIG_SAVE || (config.r1 == -1 && config.r2 == -1)) {
config.r1 = R1;
config.r2 = R2;
config.instance = INSTANCE;
Serial.println("Saving defaults to EEPROM...");
EEPROM.put(CONFIG_EEPROM_ADDR, config);
}
Serial.println("Used configuration:");
Serial.print("R1 = ");
Serial.println(config.r1);
Serial.print("R2 = ");
Serial.println(config.r2);
Serial.print("Instance = ");
Serial.println(config.instance);
Serial.flush();
}
| 21.304348
| 83
| 0.685034
|
chacal
|
e1c83b75307a304a12c5423e0937bf28442a35ab
| 2,307
|
cpp
|
C++
|
shared/src/APIFactory.cpp
|
ElitCoder/speedogift
|
44b8c2fe08a7f12c0b4286c766e7d7247b37b5de
|
[
"MIT"
] | null | null | null |
shared/src/APIFactory.cpp
|
ElitCoder/speedogift
|
44b8c2fe08a7f12c0b4286c766e7d7247b37b5de
|
[
"MIT"
] | 1
|
2019-09-04T20:28:11.000Z
|
2019-09-05T18:23:53.000Z
|
shared/src/APIFactory.cpp
|
ElitCoder/speedogift
|
44b8c2fe08a7f12c0b4286c766e7d7247b37b5de
|
[
"MIT"
] | null | null | null |
#include "APIFactory.h"
#include "API.h"
using namespace std;
using namespace ncnet;
static API create_api_wrapper(Packet &packet, APIHeader reply) {
API api;
api.set_packet(packet);
api.set_reply_header(reply);
return api;
}
static API create_generic(APIHeader header, APIHeader reply) {
Packet packet;
packet.add_byte(header);
return create_api_wrapper(packet, reply);
}
static API create_generic_reply(APIHeader header, APIStatusCode code) {
Packet packet;
packet.add_byte(header);
packet << code;
return create_api_wrapper(packet, API_HEADER_NONE);
}
API APIFactory::auth(const string &name) {
Packet packet;
packet.add_byte(API_HEADER_AUTH);
packet << API_VERSION;
packet << name;
return create_api_wrapper(packet, API_HEADER_AUTH_REPLY);
}
API APIFactory::auth_reply(APIStatusCode code) {
return create_generic_reply(API_HEADER_AUTH_REPLY, code);
}
API APIFactory::list() {
return create_generic(API_HEADER_LIST, API_HEADER_LIST_REPLY);
}
API APIFactory::list_reply(const vector<APIFactory::ListReply> &clients) {
Packet packet;
packet.add_byte(API_HEADER_LIST_REPLY);
packet << clients.size();
for (auto &client : clients) {
packet << client.version << client.name << client.active;
}
return create_api_wrapper(packet, API_HEADER_NONE);
}
API APIFactory::send(const string &from, const string &to, const vector<APIFactory::Send> &files) {
Packet packet;
packet.add_byte(API_HEADER_SEND);
packet << from << to;
packet << files.size();
for (auto &file : files) {
packet << file.path << file.size << file.hash;
}
return create_api_wrapper(packet, API_HEADER_SEND_REPLY);
}
API APIFactory::send_reply(const string &from, const string &to, APIStatusCode code) {
Packet packet;
packet.add_byte(API_HEADER_SEND_REPLY);
packet << from << to << code;
return create_api_wrapper(packet, API_HEADER_NONE);
}
API APIFactory::change_active(bool active) {
Packet packet;
packet.add_byte(API_HEADER_CHANGE_ACTIVE);
packet << active;
return create_api_wrapper(packet, API_HEADER_CHANGE_ACTIVE_REPLY);
}
API APIFactory::change_active_reply(APIStatusCode code) {
return create_generic_reply(API_HEADER_CHANGE_ACTIVE_REPLY, code);
}
| 28.8375
| 99
| 0.724317
|
ElitCoder
|
e1c88e91454157b20c0ed9cf68f4bc251e87a46b
| 3,253
|
hpp
|
C++
|
src/Entity.hpp
|
lonnort/thga
|
22cc8868ec8bf9cee195771f0a88bef4d1fa1013
|
[
"BSL-1.0"
] | 1
|
2022-02-14T12:32:23.000Z
|
2022-02-14T12:32:23.000Z
|
src/Entity.hpp
|
lonnort/thga
|
22cc8868ec8bf9cee195771f0a88bef4d1fa1013
|
[
"BSL-1.0"
] | 16
|
2022-02-04T14:26:25.000Z
|
2022-02-04T14:27:18.000Z
|
src/Entity.hpp
|
lonnort/thga
|
22cc8868ec8bf9cee195771f0a88bef4d1fa1013
|
[
"BSL-1.0"
] | null | null | null |
#pragma once
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics.hpp>
namespace Pacenstein {
/**
* The class describing what anything that can be interacted with has to contain.
*
* Entities are items like fruits and pellets, ghosts, and the player itself.
*/
class Entity {
public:
/**
* Constructor of the Entity class.
*
* \param px The x position of the entity.
* \param py The y position of the entity.
* \param dx The x direction of the entity.
* \param dy The y direction of the entity.
* \param sx The size in the x direction of the entity.
* \param sy The size in the y direction of the entity.
* \param ms The move speed of the entity. Default is 0.
*/
Entity(float px, float py, float dx, float dy, float sx, float sy, float ms = 0);
/**
* Constructor of the Entity class.
*
* \param pos The position of the entity as an sf::Vector2f.
* \param dir The direction of the entity as an sf::Vector2f.
* \param size The size of the entity as an sf::Vector2f.
* \param ms The move speed of the entity. Default is 0.
*/
Entity(sf::Vector2f pos, sf::Vector2f dir, sf::Vector2f size, float ms = 0);
/**
* Constructor of the Entity class.
*
* Initializes all the member variables with 0.
*/
Entity();
// Entity(const std::shared_ptr<Entity> entity);
/**
* Returns the position of the entity.
*
* \return The position of the entity as an sf::Vector2f.
*/
sf::Vector2f getPos();
/**
* Returns the direction of the entity.
*
* \return The direction of the entity as an sf::Vector2f.
*/
sf::Vector2f getDir();
/**
* Returns the x position of the entity.
*
* \deprecated Use `Pacenstein::Entity::getPos()` instead.
*
* \return A float of the x position.
*/
[[deprecated("Use Pacenstein::Entity::getPos() instead.")]]
float getPosX();
/**
* Returns the y position of the entity.
*
* \deprecated Use `Pacenstein::Entity::getPos()` instead.
*
* \return A float of the y position.
*/
[[deprecated("Use Pacenstein::Entity::getPos() instead.")]]
float getPosY();
/**
* Returns the x direction of the entity.
*
* \deprecated Use `Pacenstein::Entity::getDir()` instead.
*
* \return A float of the x direction.
*/
[[deprecated("Use Pacenstein::Entity::getDir() instead.")]]
float getDirX();
/**
* Returns the y direction of the entity.
*
* \deprecated Use `Pacenstein::Entity::getDir()` instead.
*
* \return A float of the y direction.
*/
[[deprecated("Use Pacenstein::Entity::getDir() instead.")]]
float getDirY();
protected:
// sf::RectangleShape bounding_box;
sf::Vector2f position, direction, size;
float moveSpeed;
};
}
| 30.688679
| 89
| 0.544728
|
lonnort
|
e1c9feb4340eeb61af4a42e02562263a8608fbfc
| 3,136
|
cpp
|
C++
|
src/GSvar/GeneInfoDBs.cpp
|
BeneKenobi/ngs-bits
|
cf849deb1c80e87b734d748f37f5878536277386
|
[
"MIT"
] | null | null | null |
src/GSvar/GeneInfoDBs.cpp
|
BeneKenobi/ngs-bits
|
cf849deb1c80e87b734d748f37f5878536277386
|
[
"MIT"
] | null | null | null |
src/GSvar/GeneInfoDBs.cpp
|
BeneKenobi/ngs-bits
|
cf849deb1c80e87b734d748f37f5878536277386
|
[
"MIT"
] | null | null | null |
#include "GeneInfoDBs.h"
#include "Exceptions.h"
#include "HttpHandler.h"
#include "Settings.h"
#include <QMessageBox>
#include <QApplication>
#include <QDesktopServices>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
void GeneInfoDBs::openUrl(QString db_name, QString gene_symbol)
{
foreach(const GeneDB& db, all())
{
if (db.name==db_name)
{
QString url = db.url;
if (url.contains("[gene_id_ncbi]"))
{
static HttpHandler http_handler(HttpRequestHandler::INI); //static to allow caching of credentials
try
{
HttpHeaders add_headers;
add_headers.insert("Accept", "application/json");
QByteArray reply = http_handler.get("https://rest.genenames.org/fetch/symbol/"+gene_symbol, add_headers);
QJsonDocument json = QJsonDocument::fromJson(reply);
QJsonArray docs = json.object().value("response").toObject().value("docs").toArray();
if (docs.count()!=1)
{
THROW(Exception, "Could not convert gene symbol to NCBI identifier: HGNC REST API returned " + QString::number(docs.count()) + " entries!");
}
QString ncbi_id = docs.at(0).toObject().value("entrez_id").toString();
url.replace("[gene_id_ncbi]", ncbi_id);
}
catch(Exception& e)
{
QMessageBox::warning(QApplication::activeWindow(), "Could not get NCBI gene identifier from HGNC", e.message());
return;
}
}
else
{
url.replace("[gene]", gene_symbol);
}
QDesktopServices::openUrl(QUrl(url));
return;
}
}
THROW(ProgrammingException, "Unknown gene DB '" + db_name + "' in GeneInfoDBs::openUrl!");
}
QList<GeneDB>& GeneInfoDBs::all()
{
static QList<GeneDB> dbs_;
if (dbs_.isEmpty())
{
dbs_ << GeneDB{"ClinGen", "https://search.clinicalgenome.org/kb/gene-dosage?search=[gene]", QIcon("://Icons/ClinGen.png"), false};
dbs_ << GeneDB{"ClinVar", "https://www.ncbi.nlm.nih.gov/clinvar/?term=[gene]%5Bgene%5D", QIcon("://Icons/ClinGen.png"), false};
dbs_ << GeneDB{"GeneCards", "https://www.genecards.org/cgi-bin/carddisp.pl?gene=[gene]", QIcon("://Icons/GeneCards.png"), false};
dbs_ << GeneDB{"GTEx", "https://www.gtexportal.org/home/gene/[gene]", QIcon("://Icons/GTEx.png"), false};
dbs_ << GeneDB{"gnomAD", "https://gnomad.broadinstitute.org/gene/[gene]?dataset=gnomad_r3", QIcon("://Icons/gnomAD.png"), false};
if (Settings::boolean("use_free_hgmd_version"))
{
dbs_ << GeneDB{"HGMD", "http://www.hgmd.cf.ac.uk/ac/gene.php?gene=[gene]", QIcon("://Icons/HGMD.png"), false}; //no HTTPS
}
else
{
dbs_ << GeneDB{"HGMD", "https://my.qiagendigitalinsights.com/bbp/view/hgmd/pro/gene.php?gene=[gene]", QIcon("://Icons/HGMD.png"), false};
}
dbs_ << GeneDB{"OMIM", "https://omim.org/search/?search=[gene]", QIcon("://Icons/OMIM.png"), false};
dbs_ << GeneDB{"SysID", "https://sysid.cmbi.umcn.nl/search?search=[gene]", QIcon("://Icons/SysID.png"), false};
dbs_ << GeneDB{"cBioPortal", "https://www.cbioportal.org/ln?q=[gene]:MUT", QIcon("://Icons/cbioportal.png"), true};
dbs_ << GeneDB{"CKB", "https://ckb.jax.org/gene/show?geneId=[gene_id_ncbi]", QIcon("://Icons/ckb.png"), true};
}
return dbs_;
}
| 37.783133
| 146
| 0.665816
|
BeneKenobi
|
e1ca9c375beb2f04ac707dbe1bf2945fd056f53c
| 3,409
|
cxx
|
C++
|
osprey/common/com/opcode.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
osprey/common/com/opcode.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
osprey/common/com/opcode.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
/**
*** Implementation of external functions from opcode.h.
**/
/** $Revision: 1.1.1.1 $
*** $Date: 2005/10/21 19:00:00 $
*** $Author: marcel $
*** $Source: /proj/osprey/CVS/open64/osprey1.0/common/com/opcode.cxx,v $
**/
#include "opcode.h"
#define opcode_C "opcode.c"
/**
*** Looks up the name of this operator in the table from opcode_gen.c
**/
const char *OPERATOR_name(OPERATOR opr)
{
Is_True(opr >= OPERATOR_FIRST && opr <= OPERATOR_LAST,
("Bad OPERATOR %d", opr));
return (const char *) OPERATOR_info[opr]._name;
}
/**
*** To make this lookup routine routine simple but efficient, we use a closed
*** hashing scheme.
**/
BOOL Operator_To_Opcode_Table_Inited = FALSE;
void Init_Operator_To_Opcode_Table(void)
{
Operator_To_Opcode_Table_Inited = TRUE;
}
/* ====================================================================
*
* OPCODE OPCODE_commutative_op(OPCODE opc)
*
* If opc is commutative, return the opcode for whatever operation
* gives equivalent results. If the operator isn't commutative, return 0.
*
* ====================================================================
*/
OPCODE OPCODE_commutative_op( OPCODE opc )
{
OPCODE rop = (OPCODE) 0;
OPERATOR opr = OPCODE_operator(opc);
TYPE_ID rtype = OPCODE_rtype(opc);
TYPE_ID desc = OPCODE_desc(opc);
switch (opr) {
/* These ops are commutative and don't need to be altered */
case OPR_ADD:
case OPR_MPY:
case OPR_MAX:
case OPR_MIN:
case OPR_BAND:
case OPR_BIOR:
case OPR_BNOR:
case OPR_BXOR:
case OPR_LAND:
case OPR_LIOR:
case OPR_EQ:
case OPR_NE:
rop = opc;
break;
/* these are treated specially */
case OPR_GT:
rop = OPCODE_make_op(OPR_LT, rtype, desc);
break;
case OPR_GE:
rop = OPCODE_make_op(OPR_LE, rtype, desc);
break;
case OPR_LT:
rop = OPCODE_make_op(OPR_GT, rtype, desc);
break;
case OPR_LE:
rop = OPCODE_make_op(OPR_GE, rtype, desc);
break;
/* Anything else is a null */
default:
break;
}
return (rop);
}
| 26.022901
| 77
| 0.662364
|
sharugupta
|
e1d052b5c1e9ae2078aa18e38c5f37d24f222a4c
| 8,255
|
cpp
|
C++
|
tools/lsvast/src/print_partition.cpp
|
vast-io/vast
|
6c9c787adc54079202dba85ea4a929004063f1ba
|
[
"BSD-3-Clause"
] | 63
|
2016-04-22T01:50:03.000Z
|
2019-07-31T15:50:36.000Z
|
tools/lsvast/src/print_partition.cpp
|
vast-io/vast
|
6c9c787adc54079202dba85ea4a929004063f1ba
|
[
"BSD-3-Clause"
] | 216
|
2017-01-24T16:25:43.000Z
|
2019-08-01T19:37:00.000Z
|
tools/lsvast/src/print_partition.cpp
|
vast-io/vast
|
6c9c787adc54079202dba85ea4a929004063f1ba
|
[
"BSD-3-Clause"
] | 28
|
2016-05-19T13:09:19.000Z
|
2019-04-12T15:11:42.000Z
|
// _ _____ __________
// | | / / _ | / __/_ __/ Visibility
// | |/ / __ |_\ \ / / Across
// |___/_/ |_/___/ /_/ Space and Time
//
// SPDX-FileCopyrightText: (c) 2020 The VAST Contributors
// SPDX-License-Identifier: BSD-3-Clause
#include <vast/as_bytes.hpp>
#include <vast/concept/printable/to_string.hpp>
#include <vast/concept/printable/vast/uuid.hpp>
#include <vast/detail/legacy_deserialize.hpp>
#include <vast/fbs/partition.hpp>
#include <vast/fbs/utils.hpp>
#include <vast/index/hash_index.hpp>
#include <vast/legacy_type.hpp>
#include <vast/qualified_record_field.hpp>
#include <vast/type.hpp>
#include <vast/value_index_factory.hpp>
#include <iostream>
#include "lsvast.hpp"
#include "util.hpp"
namespace lsvast {
template <size_t N>
void print_hash_index_(const vast::hash_index<N>& idx, indentation& indent,
const options& options) {
std::cout << indent << " - hash index bytes " << N << "\n";
std::cout << indent << " - " << idx.digests().size() << " digests:"
<< "\n";
indented_scope _(indent);
if (options.format.verbosity == output_verbosity::normal) {
const size_t bound = std::min<size_t>(idx.digests().size(), 3);
for (size_t i = 0; i < bound; ++i) {
std::cout << indent << idx.digests().at(i) << "\n";
}
if (bound < idx.digests().size())
std::cout << indent << "... (use -v to display remaining entries)\n";
} else {
for (const auto& digest : idx.digests()) {
std::cout << indent << digest << "\n";
}
}
}
void print_hash_index(const vast::value_index_ptr& ptr, indentation& indent,
const options& options) {
// TODO: This is probably a good use case for a macro.
if (auto idx = dynamic_cast<const vast::hash_index<1>*>(ptr.get())) {
print_hash_index_(*idx, indent, options);
} else if (auto idx = dynamic_cast<const vast::hash_index<1>*>(ptr.get())) {
print_hash_index_(*idx, indent, options);
} else if (auto idx = dynamic_cast<const vast::hash_index<2>*>(ptr.get())) {
print_hash_index_(*idx, indent, options);
} else if (auto idx = dynamic_cast<const vast::hash_index<3>*>(ptr.get())) {
print_hash_index_(*idx, indent, options);
} else if (auto idx = dynamic_cast<const vast::hash_index<4>*>(ptr.get())) {
print_hash_index_(*idx, indent, options);
} else if (auto idx = dynamic_cast<const vast::hash_index<5>*>(ptr.get())) {
print_hash_index_(*idx, indent, options);
} else if (auto idx = dynamic_cast<const vast::hash_index<6>*>(ptr.get())) {
print_hash_index_(*idx, indent, options);
} else if (auto idx = dynamic_cast<const vast::hash_index<7>*>(ptr.get())) {
print_hash_index_(*idx, indent, options);
} else if (auto idx = dynamic_cast<const vast::hash_index<8>*>(ptr.get())) {
print_hash_index_(*idx, indent, options);
} else {
std::cout << "more than 8 bytes digest :(\n";
}
}
void print_partition_legacy(
const vast::fbs::partition::LegacyPartition* partition, indentation& indent,
const options& options) {
if (!partition) {
std::cout << "(null)\n";
return;
}
std::cout << indent << "Partition\n";
indented_scope _(indent);
vast::uuid id;
if (partition->uuid())
if (auto error = unpack(*partition->uuid(), id))
std::cerr << indent << to_string(error);
std::cout << indent << "uuid: " << to_string(id) << "\n";
std::cout << indent << "offset: " << partition->offset() << "\n";
std::cout << indent << "events: " << partition->events() << "\n";
// Print contained event types.
std::cout << indent << "Event Types: \n";
if (auto type_ids_vector = partition->type_ids()) {
indented_scope _(indent);
for (auto type_ids : *type_ids_vector) {
auto name = type_ids->name()->c_str();
auto ids_bytes = type_ids->ids();
std::cout << indent << name << ": ";
vast::ids restored_ids;
vast::detail::legacy_deserializer bds(
vast::as_bytes(ids_bytes->data(), ids_bytes->size()));
if (!bds(restored_ids))
std::cout << " (deserialization error)";
else
std::cout << rank(restored_ids);
if (options.format.print_bytesizes)
std::cout << " (" << print_bytesize(ids_bytes->size(), options.format)
<< ")";
std::cout << "\n";
}
}
// Print catalog contents.
std::cout << indent << "Catalog\n";
if (auto partition_synopsis = partition->partition_synopsis()) {
indented_scope _(indent);
for (auto column_synopsis : *partition_synopsis->synopses()) {
vast::qualified_record_field fqf;
auto name = vast::fbs::deserialize_bytes(
column_synopsis->qualified_record_field(), fqf);
std::cout << indent << fqf.name() << ": ";
if (auto opaque = column_synopsis->opaque_synopsis()) {
std::cout << "opaque_synopsis";
if (options.format.print_bytesizes)
std::cout << " ("
<< print_bytesize(opaque->data()->size(), options.format)
<< ")";
} else if (auto bs = column_synopsis->bool_synopsis()) {
std::cout << "bool_synopis " << bs->any_true() << " "
<< bs->any_false();
} else if (auto ts = column_synopsis->time_synopsis()) {
std::cout << "time_synopsis " << ts->start() << "-" << ts->end();
} else {
std::cout << "(unknown)";
}
std::cout << '\n';
}
}
// Print column indices.
std::cout << indent << "Column Indices\n";
vast::legacy_record_type intermediate;
vast::fbs::deserialize_bytes(partition->combined_layout(), intermediate);
auto combined_layout
= caf::get<vast::record_type>(vast::type::from_legacy_type(intermediate));
if (auto indexes = partition->indexes()) {
if (indexes->size() != combined_layout.num_fields()) {
std::cout << indent << "!! wrong number of fields\n";
return;
}
const auto& expand_indexes = options.partition.expand_indexes;
indented_scope _(indent);
for (size_t i = 0; i < indexes->size(); ++i) {
auto field = combined_layout.field(i);
auto name = field.name;
const auto* index = indexes->Get(i);
if (!index) {
std::cout << indent << "(missing index field " << name << ")\n";
continue;
}
auto sz = index->index() && index->index()->data()
? index->index()->data()->size()
: 0;
std::cout << indent << name << ": " << fmt::to_string(field.type);
if (options.format.print_bytesizes)
std::cout << " (" << print_bytesize(sz, options.format) << ")";
std::cout << "\n";
bool expand
= std::find(expand_indexes.begin(), expand_indexes.end(), name)
!= expand_indexes.end();
if (expand && index->index()) {
vast::factory_traits<vast::value_index>::initialize();
vast::value_index_ptr state_ptr;
if (auto error
= vast::fbs::deserialize_bytes(index->index()->data(), state_ptr)) {
std::cout << "!! failed to deserialize index" << to_string(error)
<< std::endl;
continue;
}
const auto& type = state_ptr->type();
std::cout << indent << "- type: " << fmt::to_string(type) << std::endl;
std::cout << indent << "- options: " << to_string(state_ptr->options())
<< std::endl;
// Print even more detailed information for hash indices.
using namespace std::string_literals;
if (auto index = type.attribute("index"))
if (*index == "hash")
print_hash_index(state_ptr, indent, options);
}
}
}
}
void print_partition(const std::filesystem::path& path, indentation& indent,
const options& formatting) {
auto partition = read_flatbuffer_file<vast::fbs::Partition>(path);
if (!partition) {
std::cout << "(error reading partition file " << path.string() << ")\n";
return;
}
switch (partition->partition_type()) {
case vast::fbs::partition::Partition::legacy:
print_partition_legacy(partition->partition_as_legacy(), indent,
formatting);
break;
default:
std::cout << "(unknown partition version)\n";
}
}
} // namespace lsvast
| 39.309524
| 80
| 0.595397
|
vast-io
|
e1d3d5a24f7939d9486876160a68e8060488618c
| 660
|
cpp
|
C++
|
DirectX2D11/Framework/Buffer/ConstBuffer.cpp
|
GyumLee/DirectX2D11
|
7a92946241ad177c7efac5609e831bc7f0b06908
|
[
"Apache-2.0"
] | null | null | null |
DirectX2D11/Framework/Buffer/ConstBuffer.cpp
|
GyumLee/DirectX2D11
|
7a92946241ad177c7efac5609e831bc7f0b06908
|
[
"Apache-2.0"
] | null | null | null |
DirectX2D11/Framework/Buffer/ConstBuffer.cpp
|
GyumLee/DirectX2D11
|
7a92946241ad177c7efac5609e831bc7f0b06908
|
[
"Apache-2.0"
] | null | null | null |
#include "Framework.h"
ConstBuffer::ConstBuffer(void* data, UINT dataSize)
: data(data), dataSize(dataSize)
{
D3D11_BUFFER_DESC bd = {};
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = dataSize;
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
DEVICE->CreateBuffer(&bd, nullptr, &buffer);
}
ConstBuffer::~ConstBuffer()
{
buffer->Release();
}
void ConstBuffer::SetVS(UINT slot)
{
DC->UpdateSubresource(buffer, 0, nullptr, data, 0, 0);
DC->VSSetConstantBuffers(slot, 1, &buffer);
}
void ConstBuffer::SetPS(UINT slot)
{
DC->UpdateSubresource(buffer, 0, nullptr, data, 0, 0);
DC->PSSetConstantBuffers(slot, 1, &buffer);
}
| 22
| 58
| 0.684848
|
GyumLee
|
e1d69f1c8ee2d262aa8aeff39f5dfd8fff27bae8
| 15,745
|
hpp
|
C++
|
src/reflect_class.hpp
|
vantonyy/CPP-Reflection
|
165a6650dbb3247a1a520477c976a5e0f81a4ced
|
[
"MIT"
] | 4
|
2019-03-16T07:19:25.000Z
|
2021-02-09T21:16:25.000Z
|
src/reflect_class.hpp
|
vantonyy/CPP-Reflection
|
165a6650dbb3247a1a520477c976a5e0f81a4ced
|
[
"MIT"
] | null | null | null |
src/reflect_class.hpp
|
vantonyy/CPP-Reflection
|
165a6650dbb3247a1a520477c976a5e0f81a4ced
|
[
"MIT"
] | 1
|
2020-04-04T02:23:30.000Z
|
2020-04-04T02:23:30.000Z
|
/*
* Copyright (C) 2016 Vladimir Antonyan <antonyan_v@outlook.com>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*/
#ifndef REFLECTED_CLASS_HPP
#define REFLECTED_CLASS_HPP
#include "debug.hpp"
#include "utils.hpp"
#include <clang/AST/Decl.h>
#include <clang/AST/DeclCXX.h>
#include <clang/Basic/Specifiers.h>
#include <llvm/Support/raw_ostream.h>
#include <string>
#include <sstream>
#include <set>
// @class method_info
class method_info
{
public:
class signature_comparator
{
public:
bool operator ()(const method_info& i1, const method_info& i2) const
{
if (i1.get_params_count() == i2.get_params_count()) {
const std::string& k1 = i1.get_key();
const std::string& k2 = i2.get_key();
return i1.is_const() < i2.is_const() || k1.size() < k2.size() || k1 < k2;
}
return i1.get_params_count() < i2.get_params_count();
}
};
typedef clang::CXXMethodDecl method;
typedef std::set<std::string> method_names;
public:
explicit method_info(method* m)
: m_method(m)
, m_return_type(extract_return_type())
, m_param_types(exctrat_param_type_list())
, m_forward_arguments(extract_forward_arguments())
, m_signature(extract_signature())
{
}
static const std::string get_type_def()
{
static std::string def = "FuncPtrToClassMethod";
return def;
}
const std::string& get_signture() const
{
return m_signature;
}
const std::string& get_key() const
{
return m_signature;
}
const std::string& get_param_type_list() const
{
return m_param_types;
}
const std::string& get_forward_arguments() const
{
return m_forward_arguments;
}
const std::string& get_return_type() const
{
return m_return_type;
}
unsigned get_params_count() const
{
ASSERT(0 != m_method);
return m_method->getNumParams();
}
bool is_const() const
{
ASSERT(0 != m_method);
return m_method->isConst();
}
bool has_param() const
{
return 0 < get_params_count();
}
bool non_void_return_type() const
{
return m_return_type != "void";
}
private:
std::string extract_signature() const
{
ASSERT(0 != m_method);
std::string res = get_return_type() + " (Type::*" + get_type_def() + ")(";
method::param_const_iterator b = m_method->param_begin();
method::param_const_iterator e = m_method->param_end();
while ( b != e ) {
ASSERT(0 != *b);
res += (*b)->getType().getAsString();
if (++b != e) {
res += ", ";
}
}
res += is_const() ? ") const" : ")";
utils::replace(res, "_Bool", "bool");
return res;
}
std::string extract_return_type() const
{
ASSERT(0 != m_method);
std::string res = m_method->getReturnType().getAsString();
utils::replace(res, "_Bool", "bool");
return res;
}
std::string exctrat_param_type_list() const
{
ASSERT(0 != m_method);
std::string res;
method::param_const_iterator b = m_method->param_begin();
method::param_const_iterator e = m_method->param_end();
unsigned idx = 0;
while (b != e) {
res += (*b)->getType().getAsString() + " p" + std::to_string(++idx);
if (++b != e) {
res += ", ";
}
}
utils::replace(res, "_Bool", "bool");
return res;
}
std::string extract_forward_arguments() const
{
typedef std::vector<std::string> Strings;
Strings params;
utils::split(m_param_types, params, ", ");
std::string res;
Strings::const_iterator b = params.begin();
Strings::const_iterator e = params.end();
while( b != e ) {
std::string::const_reverse_iterator i = std::find(b->rbegin(), b->rend(), ' ');
ASSERT(i != b->rend());
const unsigned pos = b->rend() - i;
res += "std::forward<" + b->substr(0, pos - 1) + ">(" + b->substr(pos, b->size()) + ")";
if (++b != e) {
res += ", ";
}
}
return res;
}
//@TODO implement
//void keep_code_stile(std::string& str, unsigned count) const
//{
// if (0 == count) {
// return;
// }
// std::string::size_type pos = count;
// std::string tab = "\n\t\t\t\t";
// while (str.size() > pos && (pos = str.find(',', pos)) != std::string::npos) {
// str.insert(pos + 1, tab);
// pos += count - (tab.size() / 2 - 3) * (count / 10);
// tab += "\t";
// }
//}
private:
method* m_method;
std::string m_return_type;
std::string m_param_types;
std::string m_forward_arguments;
std::string m_signature;
}; // class method_info
//@class invoke_output
class invoke_output
{
private:
typedef method_info::method method;
typedef method_info::method_names method_names;
typedef std::map<method_info, method_names, method_info::signature_comparator> methods_map;
public:
invoke_output(clang::CXXRecordDecl::method_range r)
{
init(r);
}
public:
bool has_methods() const
{
return !m_methods_map.empty();
}
void get_methods(method_names& ns) const
{
for (auto i : m_methods_map) {
ns.insert(i.second.begin(), i.second.end());
}
}
void dump(clang::raw_ostream& out) const
{
for (auto i : m_methods_map) {
dump(out, i.first, i.second);
}
}
private:
void init(clang::CXXRecordDecl::method_range r)
{
for (clang::CXXRecordDecl::method_iterator i = r.begin(); i != r.end(); ++i) {
method* m = *i;
ASSERT(0 != m);
if (supported(m)) {
m_methods_map[method_info(m)].insert(m->getNameAsString());
}
}
}
bool supported(method* m) const
{
ASSERT(0 != m);
return !m->isStatic() && m->isUserProvided() && clang::Decl::Kind::CXXMethod == m->getKind() &&
m->getAccess() == clang::AccessSpecifier::AS_public && !m->isDefaulted() &&
!m->isCopyAssignmentOperator() && !m->isMoveAssignmentOperator();
}
void dump(clang::raw_ostream& out, const method_info& info, const method_names& names) const
{
ASSERT(!names.empty());
std::string const_qualifier = info.is_const() ? "const " : "";
out << "\tstatic " << info.get_return_type() << " invoke(" << const_qualifier << "Type & o, const char * n";
if (info.has_param()) {
out << ", " + info.get_param_type_list();
}
out << ") " << "\n\t{\n";
out << "\t\ttypedef " << info.get_signture() << ";\n";
out << "\t\ttypedef std::map<std::string, " << method_info::get_type_def() << "> funcMap;\n";
out << "\t\tstatic funcMap f_map;\n";
out << "\t\tif (f_map.empty()) {\n";
for (auto i : names) {
out << "\t\t\tf_map.insert(std::make_pair(\"" << i << "\", &Type::" << i << "));\n";
}
out << "\t\t}\n\t\tfuncMap::const_iterator found = f_map.find(n);\n";
out << "\t\tif(found == f_map.end()) {\n";
out << "\t\t\tthrow std::runtime_error(\"Function with name '\" + std::string(n) + \"' not found\");\n\t\t}\n";
out << "\t\t";
if (info.non_void_return_type()) {
out << "return ";
}
out << "(o.*found->second)(" << info.get_forward_arguments() << ");\n\t}\n\n";
}
private:
methods_map m_methods_map;
}; // class invoke_output
//@class reflected_class
class reflected_class
{
private:
typedef clang::CXXRecordDecl source_class;
public:
typedef std::shared_ptr<reflected_class> ptr;
typedef std::list<ptr> reflected_collection;
public:
reflected_class(source_class* d)
: m_source_class(d)
, m_methods(d->methods())
{
ASSERT(d->isClass());
ASSERT(d->hasDefinition());
}
std::string get_qualified_name() const
{
return m_source_class->getQualifiedNameAsString();
}
std::string get_name() const
{
return m_source_class->getNameAsString();
}
int get_num_bases() const
{
return m_source_class->getNumBases();
}
bool has_any_dependent_bases() const
{
return m_source_class->hasAnyDependentBases();
}
bool has_friends() const
{
return m_source_class->hasFriends();
}
bool has_user_declared_constructor() const
{
return m_source_class->hasUserDeclaredConstructor();
}
bool has_user_declared_copy_assignment() const
{
return m_source_class->hasUserDeclaredCopyAssignment();
}
bool has_user_declared_destructor() const
{
return m_source_class->hasUserDeclaredDestructor();
}
bool has_user_provided_default_constructor() const
{
return m_source_class->hasUserProvidedDefaultConstructor();
}
bool is_aggregate() const
{
return m_source_class->isAggregate();
}
bool is_derived_from(const std::string& base_name) const
{
static method_info::method_names names;
if (names.empty()) {
get_base_names(names);
}
return names.find("class " + base_name) != names.end();
}
bool is_template_decl() const
{
return m_source_class->isTemplateDecl();
}
bool is_polymorphic() const
{
return m_source_class->isPolymorphic();
}
int get_num_virtual_bases() const
{
return m_source_class->getNumVBases();
}
bool is_abstract() const
{
return m_source_class->isAbstract();
}
bool has_default_constructor() const
{
return m_source_class->hasDefaultConstructor();
}
void get_base_names(method_info::method_names& names) const
{
source_class::base_class_iterator b = m_source_class->bases_begin();
source_class::base_class_iterator e = m_source_class->bases_end();
for (; b != e; ++b) {
names.insert(b->getType().getAsString());
}
}
void dump(clang::raw_ostream& out) const
{
dump_begin_specalization(out);
dump_create(out);
dump_get_name(out);
dump_get_qualified_name(out);
dump_get_base_names(out);
dump_get_num_bases(out);
dump_get_num_virtual_bases(out);
dump_get_methods(out);
dump_has_default_constructor(out);
dump_has_any_dependent_bases(out);
dump_has_friends(out);
dump_has_user_declared_constructor(out);
dump_has_user_declared_copy_assignment(out);
dump_has_user_declared_destructor(out);
dump_has_user_provided_default_constructor(out);
dump_is_aggregate(out);
dump_is_derived_from(out);
dump_is_template_decl(out);
dump_is_abstract(out);
dump_is_polymorphic(out);
dump_invokes(out);
dump_end_specalization(out);
}
private:
void dump_begin_specalization(clang::raw_ostream& out) const
{
std::string name = get_qualified_name();
out << "// @class reflect<" << name << ">\n";
out << "template <>\nclass reflect<" << name << ">\n{\n";
out << "public:\n\ttypedef " << name << " Type;\n";
out << "\ttypedef std::set<std::string> names;\n\n";
out << "public:\n";
}
void dump_end_specalization(clang::raw_ostream& out) const
{
out << "\n}; // class reflect<" << get_name() << ">\n\n\n";
}
void dump_get_name(clang::raw_ostream& out) const
{
out << "\tstatic std::string get_name()\n\t{\n";
out << "\t\treturn \"" << get_name() << "\";\t\n\t}\n\n";
}
void dump_get_qualified_name(clang::raw_ostream& out) const
{
out << "\tstatic std::string get_qualified_name()\n\t{\n";
out << "\t\treturn \"" << get_qualified_name() << "\";\t\n\t}\n\n";
}
void dump_get_num_bases(clang::raw_ostream& out) const
{
out << "\tstatic int get_num_bases()\n\t{\n";
out << "\t\treturn " << get_num_bases() << ";\n\t}\n\n";
}
void dump_get_num_virtual_bases(clang::raw_ostream& out) const
{
out << "\tstatic int get_num_virtual_bases()\n\t{\n";
out << "\t\treturn " << get_num_virtual_bases() << ";\n\t}\n\n";
}
void dump_get_methods(clang::raw_ostream& out) const
{
out << "\tstatic void get_methods(names& ns)\n\t{\n";
method_info::method_names names;
m_methods.get_methods(names);
for (auto i : names ) {
out << "\t\tns.insert(\"" << i << "\");\n";
}
out << "\t}\n\n";
}
void dump_is_abstract(clang::raw_ostream& out) const
{
out << "\tstatic bool is_abstract()\n\t{\n";
out << "\t\treturn " << (is_abstract() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_is_polymorphic(clang::raw_ostream& out) const
{
out << "\tstatic bool is_polymorphic()\n\t{\n";
out << "\t\treturn " << (is_polymorphic() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_has_default_constructor(clang::raw_ostream& out) const
{
out << "\tstatic bool has_default_constructor()\n\t{\n";
out << "\t\treturn "<< (has_default_constructor() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_create(clang::raw_ostream& out) const
{
out << "\ttemplate<typename ...Args>\n";
out << "\tstatic Type create(const Args&...args)\n\t{\n";
out << "\t\treturn Type(std::forward<const Args&>(args)...);\n\t}\n\n";
}
void dump_get_base_names(clang::raw_ostream& out) const
{
out << "\tstatic void get_base_names(names& ns)\n\t{\n";
source_class::base_class_iterator b = m_source_class->bases_begin();
source_class::base_class_iterator e = m_source_class->bases_end();
if (b == e) {
out << "\t\t/// Has not base\n";
}
for (; b != e; ++b) {
out << "\t\tns.insert(\"" << b->getType().getAsString() << "\");\n";
}
out << "\t}\n\n";
}
void dump_has_any_dependent_bases(clang::raw_ostream& out) const
{
out << "\tstatic bool has_any_dependent_bases()\n\t{\n";
out << "\t\treturn " << (has_any_dependent_bases() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_has_friends(clang::raw_ostream& out) const
{
out << "\tstatic bool has_friends()\n\t{\n";
out << "\t\treturn " << (has_friends() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_has_user_declared_constructor(clang::raw_ostream& out) const
{
out << "\tstatic bool has_user_declared_constructor()\n\t{\n";
out << "\t\treturn " << (has_user_declared_constructor() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_has_user_declared_copy_assignment(clang::raw_ostream& out) const
{
out << "\tstatic bool has_user_declared_copy_assignment()\n\t{\n";
out << "\t\treturn " << (has_user_declared_copy_assignment() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_has_user_declared_destructor(clang::raw_ostream& out) const
{
out << "\tstatic bool has_user_declared_destructor()\n\t{\n";
out << "\t\treturn " << (has_user_declared_destructor() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_has_user_provided_default_constructor(clang::raw_ostream& out) const
{
out << "\tstatic bool has_user_provided_default_constructor()\n\t{\n";
out << "\t\treturn " << (has_user_provided_default_constructor() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_is_aggregate(clang::raw_ostream& out) const
{
out << "\tstatic bool is_aggregate()\n\t{\n";
out << "\t\treturn " << (is_aggregate() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_is_derived_from(clang::raw_ostream& out) const
{
out << "\tstatic bool is_derived_from(const std::string& base_name)\n\t{\n";
out << "\t\tnames ns;\n";
out << "\t\tget_base_names(ns);\n";
out << "\t\treturn ns.find(\"class \" + base_name) != ns.end();\n\t}\n\n";
}
void dump_is_template_decl(clang::raw_ostream& out) const
{
out << "\tstatic bool is_template_decl()\n\t{\n";
out << "\t\treturn " << (is_template_decl() ? "true" : "false") << ";\n\t}\n\n";
}
void dump_invokes(clang::raw_ostream& out) const
{
if (!is_abstract()) {
m_methods.dump(out);
}
}
private:
source_class* m_source_class;
invoke_output m_methods;
}; // class reflected_class
#endif // REFLECTED_CLASS_HPP
| 27.478185
| 114
| 0.631693
|
vantonyy
|
e1d87b77a45641841209817e925cd58f4fbcdc38
| 7,996
|
cpp
|
C++
|
source/LibFgBase/src/FgMath.cpp
|
denim2x/FaceGenBaseLibrary
|
52317cf96984a47d7f2d0c5471230d689404101c
|
[
"MIT"
] | null | null | null |
source/LibFgBase/src/FgMath.cpp
|
denim2x/FaceGenBaseLibrary
|
52317cf96984a47d7f2d0c5471230d689404101c
|
[
"MIT"
] | null | null | null |
source/LibFgBase/src/FgMath.cpp
|
denim2x/FaceGenBaseLibrary
|
52317cf96984a47d7f2d0c5471230d689404101c
|
[
"MIT"
] | null | null | null |
//
// Copyright (c) 2019 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
#include "stdafx.h"
#include "FgMath.hpp"
#include "FgRandom.hpp"
#include "FgSyntax.hpp"
using namespace std;
namespace Fg {
// Without a hardware nlz (number of leading zeros) instruction, this function has
// to be iterative (C / C++ doesn't have any keyword for this operator):
uint
numLeadingZeros(uint32 x)
{
uint n = 0;
if (x == 0) return(32);
if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
if (x <= 0x7FFFFFFF) {n = n + 1;}
return n;
}
uint8
numNonzeroBits8(uint8 xx)
{
return
(xx & 1U) + (xx & 2U)/2 + (xx & 4U)/4 + (xx & 8U)/8 +
(xx & 16U)/16 + (xx & 32U)/32 + (xx & 64U)/64 + (xx & 128U)/128;
}
uint16
numNonzeroBits16(uint16 xx)
{
return numNonzeroBits8(xx & 255) + numNonzeroBits8(xx >> 8);
}
uint
numNonzeroBits32(uint32 xx)
{
return
numNonzeroBits8(xx & 255) + numNonzeroBits8((xx >> 8) & 255) +
numNonzeroBits8((xx >> 16) & 255) + numNonzeroBits8((xx >> 24));
}
uint
log2Ceil(uint32 xx)
{
uint logFloor = log2Floor(xx);
if (xx == (1u << logFloor))
return (log2Floor(xx));
else
return (log2Floor(xx) + 1u);
}
// RETURNS: Between 1 and 3 real roots of the equation. Duplicate roots are returned in duplicate.
// The cubic term co-efficient is assumed to be 1.0.
// From Spiegel '99, Mathematical Handbook of Formulas and Tables.
vector<double>
fgSolveCubicReal(
double c0, // constant term
double c1, // first order coefficient
double c2) // second order coefficient
{
vector<double> retval;
double qq = (3.0 * c1 - sqr(c2)) / 9.0,
rr = (9.0 * c1 * c2 - 27.0 * c0 - 2.0 * cube(c2)) / 54.0,
dd = cube(qq) + sqr(rr);
if (dd > 0.0) { // Only one real root
double sqdd = sqrt(dd),
ss = cbrt(rr + sqdd),
tt = cbrt(rr - sqdd);
retval.push_back(ss+tt-(c2/3.0));
return retval;
}
else if (dd == 0.0) { // All real roots, at least 2 equal
double ss = cbrt(rr);
retval.push_back(2.0 * ss - c2 / 3.0);
retval.push_back(-2.0 * ss - c2 / 3.0);
retval.push_back(-2.0 * ss - c2 / 3.0);
}
else { // dd < 0, all distinct real roots
double ss = 2.0 * sqrt(-qq),
theta3 = acos(rr / pow(-qq,1.5)) / 3.0,
c23 = c2 / 3.0;
retval.push_back(ss * cos(theta3) - c23);
retval.push_back(ss * cos(theta3 + 2.0 * pi() / 3.0) - c23);
retval.push_back(ss * cos(theta3 - 2.0 * pi() / 3.0) - c23);
}
return retval;
}
vector<double>
fgConvolve(
const vector<double> & data,
const vector<double> & kernel)
{
FGASSERT(data.size() * kernel.size() > 0);
FGASSERT((kernel.size() % 2) == 1);
size_t kbase = kernel.size()/2;
vector<double> ret(data.size(),0.0);
for (size_t ii=0; ii<ret.size(); ++ii) {
for (size_t jj=kernel.size()-1; jj<kernel.size(); --jj) {
size_t idx = ii + kbase - jj;
if (idx < data.size())
ret[ii] += data[idx] * kernel[jj];
}
}
return ret;
}
vector<double>
fgConvolveGauss(
const std::vector<double> & in,
double stdev)
{
FGASSERT(stdev > 0.0);
// Create kernel w/ 6 stdevs on each side for double since this is 2 parts in 1B:
size_t ksize = round<uint>(stdev * 6);
if (ksize == 0)
return in;
vector<double> kernel(ksize*2+1);
for (size_t ii=0; ii<ksize; ++ii) {
double val = expSafe(-0.5*sqr(ii/stdev));
kernel[ksize+ii] = val;
kernel[ksize-ii] = val;
}
double fac = 1.0 / cSum(kernel);
for (size_t ii=0; ii<kernel.size(); ++ii)
kernel[ii] *= fac;
return fgConvolve(in,kernel);
}
vector<double>
fgRelDiff(const vector<double> & a,const vector<double> & b,double minAbs)
{
vector<double> ret;
FGASSERT(a.size() == b.size());
ret.resize(a.size());
for (size_t ii=0; ii<a.size(); ++ii)
ret[ii] = fgRelDiff(a[ii],b[ii],minAbs);
return ret;
}
// Test by generating 1M numbers and taking the average (should be 1/2) and RMS (should be 1/3).
static
void
testFgRand()
{
randSeedRepeatable();
const uint numSamples = 1000000;
const double num = double(numSamples);
vector<double> vals(numSamples);
double mean = 0.0;
for (uint ii=0; ii<numSamples; ii++)
{
vals[ii] = randUniform();
mean += vals[ii];
}
mean /= num;
double rms = 0.0;
for (uint ii=0; ii<numSamples; ii++)
rms += sqr(vals[ii]);
rms = (rms / num);
fgout << fgnl << "Mean: " << mean << fgnl << "RMS: " << rms;
FGASSERT(std::abs(mean * 2.0 - 1.0) < 0.01); // Should be good to 1 in sqrt(1M)
FGASSERT(std::abs(rms * 3.0 - 1.0) < 0.01);
}
void
fgMathTest(const CLArgs &)
{
OutPush op("Testing rand");
testFgRand();
}
// The following code is a modified part of the 'fastermath' library:
/*
Copyright (c) 2012,2013 Axel Kohlmeyer <akohlmey@gmail.com>
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 <organization> 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 <COPYRIGHT HOLDER> 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.
*/
typedef union
{
double dbl;
struct {int32_t lo,hi;} asInt;
} FgExpFast;
double expFast(double x)
{
x *= 1.4426950408889634074; // Convert to base 2 exponent
double ipart = floor(x+0.5),
fpart = x - ipart;
FgExpFast epart;
epart.asInt.lo = 0;
epart.asInt.hi = (((int) ipart) + 1023) << 20;
double y = fpart*fpart,
px = 2.30933477057345225087e-2;
px = px*y + 2.02020656693165307700e1;
double qx = y + 2.33184211722314911771e2;
px = px*y + 1.51390680115615096133e3;
qx = qx*y + 4.36821166879210612817e3;
px = px * fpart;
y = 1.0 + 2.0*(px/(qx-px));
return epart.dbl*y;
}
}
| 33.316667
| 99
| 0.571661
|
denim2x
|
e1d986085dd2a528d378def0dc53caad3037a98a
| 24,266
|
cpp
|
C++
|
uActor/src/remote/tcp_forwarder.cpp
|
uActor/uActor
|
1180db98f48ad447639a3d625573307d87b28902
|
[
"MIT"
] | 1
|
2021-09-15T12:41:37.000Z
|
2021-09-15T12:41:37.000Z
|
uActor/src/remote/tcp_forwarder.cpp
|
uActor/uActor
|
1180db98f48ad447639a3d625573307d87b28902
|
[
"MIT"
] | null | null | null |
uActor/src/remote/tcp_forwarder.cpp
|
uActor/uActor
|
1180db98f48ad447639a3d625573307d87b28902
|
[
"MIT"
] | null | null | null |
#include "remote/tcp_forwarder.hpp"
#ifdef ESP_IDF
#include <sdkconfig.h>
extern "C" {
#include <esp_event.h>
#include <esp_log.h>
#include <esp_netif.h>
#include <esp_system.h>
#include <esp_wifi.h>
#include <lwip/err.h>
#include <lwip/netdb.h>
#include <lwip/sockets.h>
#include <lwip/sys.h>
}
#else
extern "C" {
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
}
#include <thread>
#endif
#if CONFIG_BENCHMARK_ENABLED
#include <support/testbed.h>
#endif
#include <algorithm>
#include <cmath>
#include <cstring>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "board_functions.hpp"
#include "controllers/telemetry_data.hpp"
#include "support/logger.hpp"
namespace uActor::Remote {
using uActor::Support::Logger;
TCPForwarder::TCPForwarder(TCPAddressArguments address_arguments)
: handle(PubSub::Router::get_instance().new_subscriber()),
_address_arguments(address_arguments) {
PubSub::Filter primary_filter{
PubSub::Constraint(std::string("node_id"), BoardFunctions::NODE_ID),
PubSub::Constraint(std::string("actor_type"), "forwarder"),
PubSub::Constraint(std::string("instance_id"), "1")};
forwarder_subscription_id = handle.subscribe(primary_filter);
PubSub::Filter peer_announcements{
PubSub::Constraint(std::string("type"), "tcp_client_connect"),
PubSub::Constraint(std::string("node_id"), BoardFunctions::NODE_ID),
};
peer_announcement_subscription_id = handle.subscribe(peer_announcements);
PubSub::Filter subscription_update{
PubSub::Constraint(std::string("type"), "local_subscription_update"),
PubSub::Constraint(std::string("publisher_node_id"),
BoardFunctions::NODE_ID),
};
subscription_update_subscription_id = handle.subscribe(subscription_update);
}
void TCPForwarder::os_task(void* args) {
TCPAddressArguments* task_args = reinterpret_cast<TCPAddressArguments*>(args);
TCPForwarder fwd = TCPForwarder(*task_args);
task_args->tcp_forwarder = &fwd;
while (true) {
auto result = fwd.handle.receive(10000);
if (result) {
fwd.receive(std::move(*result));
}
fwd.keepalive();
}
}
void TCPForwarder::tcp_reader_task(void* args) {
TCPForwarder* fwd = reinterpret_cast<TCPForwarder*>(args);
fwd->tcp_reader();
}
void TCPForwarder::receive(PubSub::MatchedPublication&& m) {
std::unique_lock remote_lock(remote_mtx);
if (m.subscription_id == forwarder_subscription_id) {
Logger::warning("TCP-FORWARDER", "Received unhandled message!");
return;
}
if (m.subscription_id == subscription_update_subscription_id) {
Logger::trace("TCP-FORWARDER", "Received subscription update");
if (m.publication.get_str_attr("type") == "local_subscription_update") {
for (auto& receiver : remotes) {
receiver.second.handle_subscription_update_notification(m.publication);
}
}
}
if (m.publication.get_str_attr("type") == "local_subscription_added") {
auto s_receivers = subscription_mapping.find(m.subscription_id);
if (s_receivers != subscription_mapping.end()) {
auto sub_ids = s_receivers->second;
for (const auto& sub_id : sub_ids) {
auto remote_it = remotes.find(sub_id);
if (remote_it != remotes.end()) {
remote_it->second.handle_local_subscription_added(m.publication);
}
}
}
return;
}
if (m.publication.get_str_attr("type") == "local_subscription_removed") {
auto s_receivers = subscription_mapping.find(m.subscription_id);
if (s_receivers != subscription_mapping.end()) {
auto sub_ids = s_receivers->second;
for (const auto& sub_id : sub_ids) {
auto remote_it = remotes.find(sub_id);
if (remote_it != remotes.end()) {
remote_it->second.handle_local_subscription_removed(m.publication);
}
}
}
return;
}
if (m.subscription_id == peer_announcement_subscription_id) {
Logger::trace("TCP-FORWARDER", "Received peer announcement");
if (m.publication.get_str_attr("type") == "tcp_client_connect" &&
m.publication.get_str_attr("node_id") == BoardFunctions::NODE_ID) {
if (m.publication.get_str_attr("peer_node_id") !=
BoardFunctions::NODE_ID) {
std::string peer_ip = std::string(
std::get<std::string_view>(m.publication.get_attr("peer_ip")));
uint32_t peer_port =
std::get<int32_t>(m.publication.get_attr("peer_port"));
create_tcp_client(peer_ip, peer_port);
}
}
}
auto receivers = subscription_mapping.find(m.subscription_id);
if (receivers != subscription_mapping.end()) {
auto sub_ids = receivers->second;
Logger::trace("TCP-FORWARDER",
"Received regualar publication. Subscribers: %d",
sub_ids.size());
std::shared_ptr<std::vector<char>> serialized;
for (uint32_t subscriber_id : sub_ids) {
auto remote_it = remotes.find(subscriber_id);
if (remote_it != remotes.end() && remote_it->second.sock > 0) {
auto& remote = remote_it->second;
if (remote.forwarding_strategy->should_forward(m.publication)) {
if (!serialized) {
serialized = m.publication.to_msg_pack();
uint32_t size_normal = serialized->size() - 4;
*reinterpret_cast<uint32_t*>(serialized->data()) =
htonl(size_normal);
}
auto result = write(&remote, serialized, std::move(remote_lock));
remote_lock = std::move(result.second);
if (result.first) {
Logger::info("TCP-FORWARDER",
"Receive: Publication write failed - shutdown "
"connection - %s:%d",
remote_it->second.partner_ip.data(),
remote_it->second.partner_port);
continue;
}
}
}
}
}
}
void TCPForwarder::remove_local_subscription(uint32_t local_id,
uint32_t sub_id) {
auto it = subscription_mapping.find(sub_id);
if (it != subscription_mapping.end()) {
it->second.erase(local_id);
if (it->second.empty()) {
handle.unsubscribe(sub_id);
subscription_mapping.erase(it);
}
}
}
uint32_t TCPForwarder::add_local_subscription(uint32_t local_id,
PubSub::Filter&& filter) {
uint32_t sub_id = handle.subscribe(std::move(filter));
auto entry = subscription_mapping.find(sub_id);
if (entry != subscription_mapping.end()) {
entry->second.insert(local_id);
} else {
subscription_mapping.emplace(sub_id, std::set<uint32_t>{local_id});
}
return sub_id;
}
uint32_t TCPForwarder::add_remote_subscription(uint32_t local_id,
PubSub::Filter&& filter,
std::string node_id) {
uint32_t sub_id = handle.subscribe(std::move(filter), node_id);
auto entry = subscription_mapping.find(sub_id);
if (entry != subscription_mapping.end()) {
entry->second.insert(local_id);
} else {
subscription_mapping.emplace(sub_id, std::set<uint32_t>{local_id});
}
return sub_id;
}
void TCPForwarder::remove_remote_subscription(uint32_t local_id,
uint32_t sub_id,
std::string /*node_id*/) {
auto it = subscription_mapping.find(sub_id);
if (it != subscription_mapping.end()) {
it->second.erase(local_id);
if (it->second.empty()) {
handle.unsubscribe(sub_id);
subscription_mapping.erase(it);
}
}
}
std::pair<bool, std::unique_lock<std::mutex>> TCPForwarder::write(
RemoteConnection* remote, std::shared_ptr<std::vector<char>> dataset,
std::unique_lock<std::mutex>&& lock) {
Controllers::TelemetryData::increase("written_traffic_size", dataset->size());
remote->write_buffer.push(std::move(dataset));
#if defined(MSG_NOSIGNAL) // POSIX
int flag = MSG_NOSIGNAL | MSG_DONTWAIT;
#elif defined(SO_NOSIGPIPE) // MacOS
int flag = SO_NOSIGPIPE | MSG_DONTWAIT;
#endif
if (!remote->write_buffer.empty()) {
size_t remaining_size =
remote->write_buffer.front()->size() - remote->write_offset;
int written =
send(remote->sock,
remote->write_buffer.front()->data() + remote->write_offset,
remaining_size, flag);
if (written < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
Logger::debug("TCP-FORWARDER", "Write error");
shutdown(remote->sock, SHUT_RDWR);
return std::make_pair(true, std::move(lock));
} else if (written == remaining_size) {
Logger::trace("TCP-FORWARDER", "Write completed");
remote->write_buffer.pop();
remote->write_offset = 0;
} else {
Logger::trace("TCP-FORWARDER", "Write progress");
if (written > 0) {
remote->write_offset += written;
}
signal_select_change();
}
remote->last_write_contact = BoardFunctions::seconds_timestamp();
}
return std::make_pair(false, std::move(lock));
}
void TCPForwarder::tcp_reader() {
fd_set read_sockets;
fd_set write_sockets;
fd_set error_sockets;
int addr_family = AF_INET;
int ip_protocol = IPPROTO_IP;
// NOLINTNEXTLINE (cppcoreguidelines-pro-type-member-init, hicpp-member-init)
sockaddr_in dest_addr;
dest_addr.sin_addr.s_addr = inet_addr(_address_arguments.listen_ip.c_str());
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(_address_arguments.port);
listen_sock = socket(addr_family, SOCK_STREAM, ip_protocol);
if (listen_sock < 0) {
Logger::warning("TCP-FORWARDER",
"Unable to create server socket - error %d", errno);
return;
}
int reuse = 1;
setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, static_cast<void*>(&reuse),
sizeof(reuse));
setsockopt(listen_sock, SOL_SOCKET, SO_REUSEPORT, static_cast<void*>(&reuse),
sizeof(reuse));
int err = bind(listen_sock, reinterpret_cast<sockaddr*>(&dest_addr),
sizeof(dest_addr));
if (err != 0) {
Logger::error("TCP-FORWARDER", "Server socket unable to bind - error %d\n",
errno);
close(listen_sock);
listen_sock = 0;
}
Logger::info("TCP-FORWARDER", "Server socket bound: %s:%d",
_address_arguments.listen_ip.data(), _address_arguments.port);
if (_address_arguments.external_port_hint > 0 ||
_address_arguments.external_address_hint.length() > 0) {
std::string external_address =
_address_arguments.external_address_hint.length() > 0
? _address_arguments.external_address_hint
: _address_arguments.listen_ip;
uint16_t external_port = _address_arguments.external_port_hint > 0
? _address_arguments.external_port_hint
: _address_arguments.port;
Logger::info("TCP-FORWARDER",
"TCP Server socket externally reachable at: %s:%d",
external_address.data(), external_port);
}
#if CONFIG_BENCHMARK_ENABLED
if (_address_arguments.external_address_hint.length() > 0) {
testbed_log_rt_string("address",
_address_arguments.external_address_hint.data());
} else {
// testbed_log_rt_string("address", _address_arguments.listen_ip.data());
}
if (_address_arguments.external_port_hint > 0) {
testbed_log_rt_integer("port", _address_arguments.external_port_hint);
} else {
testbed_log_rt_integer("port", _address_arguments.port);
}
#endif
err = listen(listen_sock, 1);
if (err != 0) {
Logger::error("TCP-FORWARDER", "Server socket listen error - %d", errno);
close(listen_sock);
listen_sock = 0;
}
signal_socket = socket(addr_family, SOCK_DGRAM, ip_protocol);
if (signal_socket < 0) {
Logger::error("TCP-FORWARDER", "Signal socket creation error - %d", errno);
}
// NOLINTNEXTLINE (cppcoreguidelines-pro-type-member-init, hicpp-member-init)
sockaddr_in signal_dest_addr;
signal_dest_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
signal_dest_addr.sin_family = AF_INET;
signal_dest_addr.sin_port = htons(_address_arguments.port);
err = bind(signal_socket, (struct sockaddr*)&signal_dest_addr,
sizeof(dest_addr));
if (err != 0) {
Logger::error("TCP-FORWARDER", "Signal socket bind error - %d", errno);
} else {
Logger::debug("TCP-FORWARDER", "Signal socket bound");
}
signal_socket_write_handler = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (signal_socket_write_handler < 0) {
Logger::error("TCP-FORWARDER",
"Signal socket write handle creation error - %d", errno);
}
while (true) {
std::unique_lock remote_lock(remote_mtx);
FD_ZERO(&read_sockets);
FD_ZERO(&write_sockets);
FD_ZERO(&error_sockets);
FD_SET(listen_sock, &read_sockets);
FD_SET(listen_sock, &write_sockets);
FD_SET(listen_sock, &error_sockets);
FD_SET(signal_socket, &read_sockets);
FD_SET(signal_socket, &error_sockets);
int max_val = std::max(listen_sock, signal_socket);
for (const auto& remote_pair : remotes) {
FD_SET(remote_pair.second.sock, &read_sockets);
if (!remote_pair.second.write_buffer.empty()) {
FD_SET(remote_pair.second.sock, &write_sockets);
}
FD_SET(remote_pair.second.sock, &error_sockets);
max_val = std::max(max_val, remote_pair.second.sock);
}
timeval timeout{}; // We need to set a timeout to allow for new connections
timeout.tv_sec = 1; // to be added by other threads
remote_lock.unlock();
int num_ready = select(max_val + 1, &read_sockets, &write_sockets,
&error_sockets, &timeout);
remote_lock.lock();
if (num_ready > 0) {
std::vector<uint> to_delete;
for (auto& remote_pair : remotes) {
uActor::Remote::RemoteConnection& remote = remote_pair.second;
if (remote.sock > 0) {
if (FD_ISSET(remote.sock, &error_sockets)) {
Logger::debug("TCP-FORWARDER", "Event Loop: Error");
shutdown(remote.sock, SHUT_RDWR);
close(remote.sock);
to_delete.push_back(remote_pair.first);
continue;
}
if (FD_ISSET(remote.sock, &read_sockets)) {
Logger::trace("TCP-FORWARDER", "Event Loop: Read");
if (data_handler(&remote)) {
Logger::info(
"TCP-FORWARDER",
"Read error/zero length message. Closing connection - %s:%d",
remote.partner_ip.data(), remote.partner_port);
shutdown(remote.sock, SHUT_RDWR);
close(remote.sock);
to_delete.push_back(remote_pair.first);
continue;
}
}
if (FD_ISSET(remote.sock, &write_sockets)) {
Logger::trace("TCP-FORWARDER", "Event Loop: Write");
if (write_handler(&remote)) {
Logger::info("TCP-FORWARDER",
"Event Loop: Closing connection - %s:%d",
remote.partner_ip.data(), remote.partner_port);
shutdown(remote.sock, SHUT_RDWR);
close(remote.sock);
to_delete.push_back(remote_pair.first);
}
}
} else {
Logger::error(
"TCP-FORWARDER",
"Event Loop: Socket should have already been deleted %s:%d!",
remote.partner_ip.data(), remote.partner_port);
to_delete.push_back(remote_pair.first);
}
}
for (auto item : to_delete) {
remotes.erase(item);
}
if (FD_ISSET(listen_sock, &read_sockets)) {
listen_handler();
}
if (FD_ISSET(listen_sock, &write_sockets)) {
Logger::info("TCP-FORWARDER", "Event Loop: Listen sock wants to write");
}
if (FD_ISSET(listen_sock, &error_sockets)) {
Logger::fatal("TCP-FORWARDER", "Event Loop: Listen sock error");
}
if (FD_ISSET(signal_socket, &read_sockets)) {
char buf[8];
recv(signal_socket, buf, sizeof(buf), MSG_DONTWAIT);
}
if (FD_ISSET(signal_socket, &error_sockets)) {
Logger::fatal("TCP-FORWARDER", "Event Loop: Signal socket error");
}
}
}
}
void TCPForwarder::create_tcp_client(std::string_view peer_ip, uint32_t port) {
int addr_family = AF_INET;
int ip_protocol = IPPROTO_IP;
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
sockaddr_in dest_addr;
dest_addr.sin_addr.s_addr = inet_addr(peer_ip.data());
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(port);
int sock_id = socket(addr_family, SOCK_STREAM, ip_protocol);
if (sock_id < 0) {
Logger::error("TCP-FORWARDER", "Client socker create error - %d", errno);
return;
}
int err = connect(sock_id, reinterpret_cast<sockaddr*>(&dest_addr),
sizeof(dest_addr));
if (err != 0) {
Logger::error("TCP-FORWARDER", "Client socket connect error - %s:%d - %d",
peer_ip.data(), port, errno);
close(sock_id);
return;
}
Logger::info("TCP-FORWARDER", "Client socket connected - %s:%d",
peer_ip.data(), port);
set_socket_options(sock_id);
add_remote_connection(sock_id, std::string(peer_ip), port,
uActor::Remote::ConnectionRole::CLIENT);
}
void TCPForwarder::listen_handler() {
int sock_id = 0;
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
struct sockaddr_in6 source_addr;
uint addr_len = sizeof(source_addr);
sock_id =
accept(listen_sock, reinterpret_cast<sockaddr*>(&source_addr), &addr_len);
if (sock_id < 0) {
Logger::error("TCP-FORWARDER",
"Server unable to accept connection - error %d", errno);
return;
} else if (sock_id == 0) {
Logger::error("TCP-FORWARDER", "Accept failed");
return;
}
char addr_string[INET6_ADDRSTRLEN];
uint16_t remote_port = 0;
if (source_addr.sin6_family == PF_INET) {
auto* addr = reinterpret_cast<sockaddr_in*>(&source_addr);
inet_ntop(addr->sin_family, &addr->sin_addr, addr_string, INET_ADDRSTRLEN);
remote_port = ntohs(addr->sin_port);
} else if (source_addr.sin6_family == PF_INET6) {
inet_ntop(source_addr.sin6_family, &source_addr.sin6_addr, addr_string,
INET6_ADDRSTRLEN);
remote_port = ntohs(source_addr.sin6_port);
}
Logger::info("TCP-FORWARDER", "Connection accepted - %s:%d", addr_string,
remote_port);
set_socket_options(sock_id);
add_remote_connection(sock_id, std::string(addr_string), remote_port,
uActor::Remote::ConnectionRole::SERVER);
}
bool TCPForwarder::data_handler(uActor::Remote::RemoteConnection* remote) {
remote->last_read_contact = BoardFunctions::seconds_timestamp();
remote->len =
recv(remote->sock, remote->rx_buffer.data(), remote->rx_buffer.size(), 0);
if (remote->len < 0) {
Logger::error("TCP-FORWARDER", "Error occurred during receive - %d", errno);
return true;
} else if (remote->len == 0) {
Logger::info("TCP-FORWARDER", "Connection closed - %s:%d",
remote->partner_ip.data(), remote->partner_port);
return true;
} else {
remote->process_data(remote->len, remote->rx_buffer.data());
return false;
}
}
bool TCPForwarder::write_handler(uActor::Remote::RemoteConnection* remote) {
#if defined(MSG_NOSIGNAL) // POSIX
int flag = MSG_NOSIGNAL | MSG_DONTWAIT;
#elif defined(SO_NOSIGPIPE) // MacOS
int flag = SO_NOSIGPIPE | MSG_DONTWAIT;
#endif
while (!remote->write_buffer.empty()) {
size_t remaining_size =
remote->write_buffer.front()->size() - remote->write_offset;
int written =
send(remote->sock,
remote->write_buffer.front()->data() + remote->write_offset,
remaining_size, flag);
if (written < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
Logger::debug("TCP-FORWARDER", "Write error");
return true;
} else if (written == remaining_size) {
Logger::trace("TCP-FORWARDER", "Write completed");
remote->write_buffer.pop();
remote->write_offset = 0;
} else {
Logger::trace("TCP-FORWARDER", "Write progress");
if (written > 0) {
remote->write_offset += written;
}
break;
}
remote->last_write_contact = BoardFunctions::seconds_timestamp();
}
return false;
}
void TCPForwarder::keepalive() {
std::set<uint32_t> to_check;
auto buffer = std::make_shared<std::vector<char>>(4, 0);
std::unique_lock lock(remote_mtx);
for (const auto& remote : remotes) {
if (BoardFunctions::seconds_timestamp() - remote.second.last_read_contact >
120 &&
remote.second.last_read_contact > 0) {
Logger::info(
"TCP-FORWARDER", "Read check failed: %s - last contact: %d",
remote.second.partner_node_id.c_str(),
BoardFunctions::timestamp() - remote.second.last_read_contact);
shutdown(remote.second.sock, SHUT_RDWR);
continue;
}
if (BoardFunctions::seconds_timestamp() - remote.second.last_write_contact >
10) {
to_check.insert(remote.first);
}
}
for (uint32_t remote_id : to_check) {
auto remote_it = remotes.find(remote_id);
if (remote_it == remotes.end()) {
continue;
}
auto result = write(&remote_it->second, buffer, std::move(lock));
lock = std::move(result.second);
if (result.first) {
Logger::info("TCP-FORWARDER", "Write check failed");
} else {
Logger::trace("TCP-FORWARDER", "Write check %s",
remote_it->second.partner_node_id.c_str());
remote_it->second.last_write_contact =
BoardFunctions::seconds_timestamp();
}
}
}
void TCPForwarder::add_remote_connection(int socket_id, std::string remote_addr,
uint16_t remote_port,
uActor::Remote::ConnectionRole role) {
uint32_t remote_id = next_local_id++;
if (auto [remote_it, inserted] =
remotes.try_emplace(remote_id, remote_id, socket_id, remote_addr,
remote_port, role, this);
inserted) {
remote_it->second.last_read_contact = BoardFunctions::seconds_timestamp();
if (role == uActor::Remote::ConnectionRole::CLIENT) {
remote_it->second.send_routing_info();
}
signal_select_change();
Logger::trace("TCP-FORWARDER", "Remote connection added");
} else {
Logger::warning("TCP-FORWARDER",
"Remote connection not inserted, closing "
"connection - "
"%s:%d!",
remote_addr.c_str(), remote_port);
shutdown(socket_id, 0);
close(socket_id);
}
}
void TCPForwarder::signal_select_change() {
// NOLINTNEXTLINE (cppcoreguidelines-pro-type-member-init, hicpp-member-init)
sockaddr_in signal_dest_addr;
signal_dest_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
signal_dest_addr.sin_family = AF_INET;
signal_dest_addr.sin_port = htons(_address_arguments.port);
sendto(signal_socket_write_handler, "A", strlen("A"), 0,
(struct sockaddr*)&signal_dest_addr, sizeof(signal_dest_addr));
}
void TCPForwarder::set_socket_options(int socket_id) {
int nodelay = 1;
setsockopt(socket_id, IPPROTO_TCP, TCP_NODELAY, static_cast<void*>(&nodelay),
sizeof(nodelay));
// TODO(raphaelhetzel) Reevaluate the need for this
// as we have an application-level keepalive system
// uint32_t true_flag = 1;
// uint32_t keepcnt = 3;
// uint32_t keepidle = 60;
// uint32_t keepintvl = 30;
// setsockopt(socket_id, SOL_SOCKET, SO_KEEPALIVE, &true_flag,
// sizeof(uint32_t)); setsockopt(socket_id, IPPROTO_TCP, TCP_KEEPCNT,
// &keepcnt, sizeof(uint32_t)); setsockopt(socket_id, IPPROTO_TCP,
// TCP_KEEPIDLE, &keepidle, sizeof(uint32_t)); setsockopt(socket_id,
// IPPROTO_TCP, TCP_KEEPINTVL, &keepintvl,
// sizeof(uint32_t));
}
} // namespace uActor::Remote
| 35.476608
| 80
| 0.644194
|
uActor
|
e1dbe60944c57a75fd86fb97dc39bd4caadc98fb
| 3,731
|
cc
|
C++
|
test/internal_util/mold_equiv.cc
|
mariuslundblad/disir-c
|
ae831250cfbf033a755c91e62e8af7d82135d0d8
|
[
"Apache-2.0"
] | 4
|
2017-06-19T09:59:50.000Z
|
2019-03-20T18:49:11.000Z
|
test/internal_util/mold_equiv.cc
|
mariuslundblad/disir-c
|
ae831250cfbf033a755c91e62e8af7d82135d0d8
|
[
"Apache-2.0"
] | 18
|
2017-06-25T22:19:00.000Z
|
2019-11-28T13:16:26.000Z
|
test/internal_util/mold_equiv.cc
|
mariuslundblad/disir-c
|
ae831250cfbf033a755c91e62e8af7d82135d0d8
|
[
"Apache-2.0"
] | 2
|
2017-10-31T11:19:55.000Z
|
2019-11-28T12:13:13.000Z
|
#include <gtest/gtest.h>
#include "test_helper.h"
#include <disir/disir.h>
// PRIVATE API
extern "C" {
#include "disir_private.h"
#include "context_private.h"
}
class MoldEquivTest : public testing::DisirTestTestPlugin
{
void SetUp()
{
DisirTestTestPlugin::SetUp ();
status = disir_mold_read (instance, "test", "basic_section", &mold);
ASSERT_STATUS (DISIR_STATUS_OK, status);
ASSERT_TRUE (mold != NULL);
}
void TearDown()
{
if (mold)
{
status = disir_mold_finished (&mold);
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
if (context_section)
{
status = dc_destroy (&context_section);
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
if (context_config)
{
status = dc_destroy (&context_config);
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
DisirTestTestPlugin::TearDown ();
}
public:
enum disir_status status;
struct disir_mold *mold = NULL;
struct disir_context *context_mold = NULL;
struct disir_context *context_config = NULL;
struct disir_context *context_section = NULL;
};
TEST_F (MoldEquivTest, test_get_correct_mold_equiv_type)
{
enum disir_context_type type;
status = dc_config_begin (mold, &context_config);
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dc_begin (context_config,
DISIR_CONTEXT_SECTION, &context_section);
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dc_set_name (context_section, "section_name", strlen ("section_name"));
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dx_get_mold_equiv_type (context_section, "k1", &type);
ASSERT_STATUS (DISIR_STATUS_OK, status);
ASSERT_EQ (DISIR_CONTEXT_KEYVAL, type);
}
TEST_F (MoldEquivTest, mold_equiv_should_not_exist)
{
enum disir_context_type type;
status = dc_config_begin (mold, &context_config);
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dc_begin (context_config,
DISIR_CONTEXT_SECTION, &context_section);
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dc_set_name (context_section, "section_name", strlen ("section_name"));
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dx_get_mold_equiv_type (context_section, "wrong", &type);
ASSERT_STATUS (DISIR_STATUS_NOT_EXIST, status);
}
TEST_F (MoldEquivTest, section_mold_equiv_should_exist)
{
enum disir_context_type type;
status = dc_config_begin (mold, &context_config);
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dx_get_mold_equiv_type (context_config, "section_name", &type);
ASSERT_STATUS (DISIR_STATUS_OK, status);
ASSERT_EQ (DISIR_CONTEXT_SECTION, type);
}
TEST_F (MoldEquivTest, fail_on_invalid_input)
{
status = dx_get_mold_equiv_type (NULL, NULL, NULL);
ASSERT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
}
TEST_F (MoldEquivTest, fail_on_wrong_context)
{
struct disir_context *context_keyval;
enum disir_context_type type;
status = dc_config_begin (mold, &context_config);
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dc_begin (context_config, DISIR_CONTEXT_KEYVAL, &context_keyval);
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dx_get_mold_equiv_type (context_keyval, "fakename", &type);
ASSERT_STATUS (DISIR_STATUS_WRONG_CONTEXT, status);
}
TEST_F (MoldEquivTest, fail_on_wrong_root_context)
{
struct disir_context *mold_context;
enum disir_context_type type;
mold_context = dc_mold_getcontext (mold);
status = dx_get_mold_equiv_type (mold_context, "fakename", &type);
ASSERT_STATUS (DISIR_STATUS_WRONG_CONTEXT, status);
}
| 28.052632
| 84
| 0.704637
|
mariuslundblad
|
e1dc6ae39a26b07ca815e365bd1813bb32e72696
| 48,679
|
cpp
|
C++
|
core/src/HElib/OldEvalMap.cpp
|
fionser/CODA
|
db234a1e9761d379fb96ae17eef3b77254f8781c
|
[
"MIT"
] | 12
|
2017-02-24T19:28:07.000Z
|
2021-02-05T04:40:47.000Z
|
core/src/HElib/OldEvalMap.cpp
|
fionser/CODA
|
db234a1e9761d379fb96ae17eef3b77254f8781c
|
[
"MIT"
] | 1
|
2017-04-15T03:41:18.000Z
|
2017-04-24T09:06:15.000Z
|
core/src/HElib/OldEvalMap.cpp
|
fionser/CODA
|
db234a1e9761d379fb96ae17eef3b77254f8781c
|
[
"MIT"
] | 6
|
2017-05-14T10:12:50.000Z
|
2021-02-07T03:50:56.000Z
|
/* Copyright (C) 2012-2014 IBM Corp.
* 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.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "OldEvalMap.h"
#include "powerful.h"
//! \cond FALSE (make doxygen ignore these classes)
template<class type>
class Step1Matrix : public PlaintextBlockMatrixInterface<type>
{
public:
PA_INJECT(type)
private:
const EncryptedArray& ea;
shared_ptr<CubeSignature> sig;
long dim;
Mat< mat_R > A;
public:
// constructor
Step1Matrix(const EncryptedArray& _ea,
shared_ptr<CubeSignature> _sig,
const Vec<long>& reps,
long _dim,
long cofactor,
bool invert = false);
virtual const EncryptedArray& getEA() const { return ea; }
virtual bool get(mat_R& out, long i, long j) const;
};
template<class type>
bool Step1Matrix<type>::get(mat_R& out, long i, long j) const
{
long i1 = sig->getCoord(i, dim);
long j1 = sig->getCoord(j, dim);
if (sig->addCoord(i, dim, -i1) != sig->addCoord(j, dim, -j1))
return true;
out = A[i1][j1];
return false;
}
template<class type>
Step1Matrix<type>::Step1Matrix(const EncryptedArray& _ea,
shared_ptr<CubeSignature> _sig,
const Vec<long>& reps,
long _dim,
long cofactor,
bool invert)
: ea(_ea), sig(_sig), dim(_dim)
{
RBak bak; bak.save(); ea.getAlMod().restoreContext();
const RX& G = ea.getDerived(type()).getG();
assert(dim == sig->getNumDims() - 1);
assert(sig->getSize() == ea.size());
long sz = sig->getDim(dim);
assert(sz == reps.length());
long d = deg(G);
// so sz == phi(m_last)/d, where d = deg(G) = order of p mod m
Vec<RX> points;
points.SetLength(sz);
for (long j = 0; j < sz; j++)
points[j] = RX(reps[j]*cofactor, 1) % G;
Mat<RX> AA;
AA.SetDims(sz*d, sz);
for (long j = 0; j < sz; j++)
AA[0][j] = 1;
for (long i = 1; i < sz*d; i++)
for (long j = 0; j < sz; j++)
AA[i][j] = (AA[i-1][j] * points[j]) % G;
A.SetDims(sz, sz);
for (long i = 0; i < sz; i++)
for (long j = 0; j < sz; j++) {
A[i][j].SetDims(d, d);
for (long k = 0; k < d; k++)
VectorCopy(A[i][j][k], AA[i*d + k][j], d);
}
if (invert) {
REBak ebak; ebak.save(); ea.getDerived(type()).restoreContextForG();
mat_R A1, A2;
A1.SetDims(sz*d, sz*d);
for (long i = 0; i < sz*d; i++)
for (long j = 0; j < sz*d; j++)
A1[i][j] = A[i/d][j/d][i%d][j%d];
long p = ea.getAlMod().getZMStar().getP();
long r = ea.getAlMod().getR();
ppInvert(A2, A1, p, r);
for (long i = 0; i < sz*d; i++)
for (long j = 0; j < sz*d; j++)
A[i/d][j/d][i%d][j%d] = A2[i][j];
}
}
PlaintextBlockMatrixBaseInterface*
buildStep1Matrix(const EncryptedArray& ea,
shared_ptr<CubeSignature> sig,
const Vec<long>& reps,
long dim,
long cofactor,
bool invert = false)
{
switch (ea.getAlMod().getTag()) {
case PA_GF2_tag:
return new Step1Matrix<PA_GF2>(ea, sig, reps, dim, cofactor, invert);
case PA_zz_p_tag:
return new Step1Matrix<PA_zz_p>(ea, sig, reps, dim, cofactor, invert);
default: return 0;
}
}
/***** END Step1 stuff *****/
template<class type>
class Step2Matrix : public PlaintextMatrixInterface<type>
{
public:
PA_INJECT(type)
private:
const EncryptedArray& ea;
shared_ptr<CubeSignature> sig;
long dim;
Mat<RX> A;
public:
// constructor
Step2Matrix(const EncryptedArray& _ea,
shared_ptr<CubeSignature> _sig,
const Vec<long>& reps,
long _dim,
long cofactor,
bool invert = false);
virtual const EncryptedArray& getEA() const { return ea; }
virtual bool get(RX& out, long i, long j) const;
};
template<class type>
bool Step2Matrix<type>::get(RX& out, long i, long j) const
{
long i1 = sig->getCoord(i, dim);
long j1 = sig->getCoord(j, dim);
if (sig->addCoord(i, dim, -i1) != sig->addCoord(j, dim, -j1))
return true;
out = A[i1][j1];
return false;
}
template<class type>
Step2Matrix<type>::Step2Matrix(const EncryptedArray& _ea,
shared_ptr<CubeSignature> _sig,
const Vec<long>& reps,
long _dim,
long cofactor,
bool invert)
: ea(_ea), sig(_sig), dim(_dim)
{
RBak bak; bak.save(); ea.getAlMod().restoreContext();
const RX& G = ea.getDerived(type()).getG();
long sz = sig->getDim(dim);
assert(sz == reps.length());
Vec<RX> points;
points.SetLength(sz);
for (long j = 0; j < sz; j++)
points[j] = RX(reps[j]*cofactor, 1) % G;
A.SetDims(sz, sz);
for (long j = 0; j < sz; j++)
A[0][j] = 1;
for (long i = 1; i < sz; i++)
for (long j = 0; j < sz; j++)
A[i][j] = (A[i-1][j] * points[j]) % G;
if (invert) {
REBak ebak; ebak.save(); ea.getDerived(type()).restoreContextForG();
mat_RE A1, A2;
conv(A1, A);
long p = ea.getAlMod().getZMStar().getP();
long r = ea.getAlMod().getR();
ppInvert(A2, A1, p, r);
conv(A, A2);
}
}
PlaintextMatrixBaseInterface*
buildStep2Matrix(const EncryptedArray& ea,
shared_ptr<CubeSignature> sig,
const Vec<long>& reps,
long dim,
long cofactor,
bool invert = false)
{
switch (ea.getAlMod().getTag()) {
case PA_GF2_tag:
return new Step2Matrix<PA_GF2>(ea, sig, reps, dim, cofactor, invert);
case PA_zz_p_tag:
return new Step2Matrix<PA_zz_p>(ea, sig, reps, dim, cofactor, invert);
default: return 0;
}
}
// two-step tower stuff...
class TowerBase {
public:
virtual ~TowerBase() { }
};
template<class type>
class Tower : public TowerBase {
public:
PA_INJECT(type)
long cofactor, d1, d2, p, r;
long d;
RE zeta; // = [X^cofactor mod G]
RX H; // = the min poly of zeta over R
Mat<R> M2, M2i;
// M2 is the matrix that takes us from the two-step tower
// to the one-step tower, and M2i is its inverse.
mutable shared_ptr< Mat<RE> > linPolyMatrix;
Tower(long _cofactor, long _d1, long _d2, long _p, long _r)
: cofactor(_cofactor), d1(_d1), d2(_d2), p(_p), r(_r)
{
d = RE::degree();
assert(d == d1*d2);
const RXModulus& G = RE::modulus();
zeta = conv<RE>(RX(cofactor, 1)); // zeta = [X^cofactor mod G]
// compute H = min poly of zeta over R
Mat<R> M1;
M1.SetDims(d1, d);
for (long i = 0; i < d1; i++) {
VectorCopy(M1[i], rep(power(zeta, i)), d);
}
Vec<R> V1;
VectorCopy(V1, rep(power(zeta, d1)), d);
Mat<R> M1sq;
Mat<R> R1;
R1.SetDims(d, d1);
for (;;) {
for (long i = 0; i < d; i++)
for (long j = 0; j < d1; j++)
random(R1[i][j]);
M1sq = M1*R1;
Mat<long> M1sqInt = conv< Mat<long> >(M1sq);
{
RBak bak; bak.save();
GenericModulus<R>::init(p);
Mat<R> M1sq_modp = conv< Mat<R> >(M1sqInt);
if (determinant(M1sq_modp) != 0) break;
}
}
Vec<R> V1sq = V1*R1;
Mat<R> M1sqi;
ppInvert(M1sqi, M1sq, p, r);
Vec<R> W1 = V1sq * M1sqi;
assert(W1*M1 == V1);
H = RX(d1, 1) - conv<RX>(W1);
// H is the min poly of zeta
assert(eval(H, zeta) == 0);
// compute matrices M2 and M2i
M2.SetDims(d, d);
for (long i = 0; i < d2; i++) {
// construct rows [i..i+d1)
for (long j = 0; j < d1; j++) {
VectorCopy(M2[i*d1+j], (rep(power(zeta, j)) << i) % G, d);
}
}
ppInvert(M2i, M2, p, r);
}
// converts an object represented in the two-step
// tower representation to the one-step representation
RE convert2to1(const Vec<RX>& v) const
{
assert(v.length() <= d2);
Vec<R> w;
w.SetLength(d);
for (long i = 0; i < v.length(); i++) {
assert(deg(v[i]) < d1);
for (long j = 0; j <= deg(v[i]); j++)
w[i*d1 + j] = v[i][j];
}
Vec<R> z = w*M2;
return conv<RE>( conv<RX>( z ) );
}
// performs the reverse conversion
Vec<RX> convert1to2(const RE& beta) const
{
Vec<R> z = VectorCopy(rep(beta), d);
Vec<R> w = z*M2i;
Vec<RX> res;
res.SetLength(d2);
for (long i = 0; i < d2; i++) {
Vec<R> tmp;
tmp.SetLength(d1);
for (long j = 0; j < d1; j++)
tmp[j] = w[i*d1+j];
res[i] = conv<RX>(tmp);
}
return res;
}
void buildLinPolyMatrix(Mat<RE>& M) const
{
ZZ q = power_ZZ(p, d1);
M.SetDims(d2, d2);
for (long j = 0; j < d2; j++)
conv(M[0][j], RX(j, 1));
for (long i = 1; i < d2; i++)
for (long j = 0; j < d2; j++)
M[i][j] = power(M[i-1][j], q);
}
void buildLinPolyCoeffs(Vec<RE>& C_out, const Vec<RE>& L) const
{
FHE_TIMER_START;
if (!linPolyMatrix) {
FHE_NTIMER_START(buildLinPolyCoeffs_buildMatrix);
Mat<RE> M;
buildLinPolyMatrix(M);
Mat<RE> Minv;
ppInvert(Minv, M, p, r);
linPolyMatrix = shared_ptr< Mat<RE> >(new Mat<RE>(Minv) );
}
Vec<RE> C;
mul(C, L, *linPolyMatrix);
C_out = C;
}
void applyLinPoly(RE& beta, const Vec<RE>& C, const RE& alpha) const
{
assert(d2 == C.length());
ZZ q = power_ZZ(p, d1);
RE gamma, res;
gamma = conv<RE>(RX(1, 1));
res = C[0]*alpha;
for (long i = 1; i < d2; i++) {
gamma = power(gamma, q);
res += C[i]*conv<RE>(CompMod(rep(alpha), rep(gamma), RE::modulus()));
}
beta = res;
}
void print(const EncryptedArray& ea, ostream& s, const NewPlaintextArray& v, long nrows) const
{
vector<ZZX> v1;
decode(ea, v1, v);
Vec<RX> v2;
convert(v2, v1);
for (long i = 0; i < v2.length(); i++) {
if (i % nrows == 0) s << "\n";
s << convert1to2(conv<RE>(v2[i])) << "\n";
}
}
};
template class Tower<PA_GF2>;
template class Tower<PA_zz_p>;
TowerBase* buildTowerBase(const EncryptedArray& ea,
long cofactor, long d1, long d2)
{
long p = ea.getAlMod().getZMStar().getP();
long r = ea.getAlMod().getR();
switch (ea.getAlMod().getTag()) {
case PA_GF2_tag: {
GF2EBak ebak; ebak.save();
ea.restoreContextForG();
return new Tower<PA_GF2>(cofactor, d1, d2, p, r);
}
case PA_zz_p_tag: {
zz_pBak bak; bak.save(); zz_pEBak ebak; ebak.save();
ea.restoreContext(); ea.restoreContextForG();
return new Tower<PA_zz_p>(cofactor, d1, d2, p, r);
}
default: return 0;
}
}
template<class type>
class Step1aMatrix : public PlaintextBlockMatrixInterface<type>
{
public:
PA_INJECT(type)
private:
const EncryptedArray& ea;
long cofactor, d1, d2, phim1;
shared_ptr<TowerBase> towerBase;
bool invert;
Mat< mat_R > A;
public:
// constructor
Step1aMatrix(const EncryptedArray& _ea,
const Vec<long>& reps,
long _cofactor, long _d1, long _d2, long _phim1,
shared_ptr<TowerBase> _towerBase,
bool _invert = false);
virtual const EncryptedArray& getEA() const { return ea; }
virtual bool get(mat_R& out, long i, long j) const;
};
template<class type>
bool Step1aMatrix<type>::get(mat_R& out, long i, long j) const
{
long sz = phim1/d1;
long i_lo = i*d2;
long i_hi = i_lo + d2 - 1;
long j_lo = j*d2;
long j_hi = j_lo + d2 - 1;
if (i_hi/sz < j_lo/sz || j_hi/sz < i_lo/sz) return true;
long d = d1*d2;
Mat<R> tmp;
tmp.SetDims(d, d);
clear(tmp);
for (long i1 = i_lo; i1 <= i_hi; i1++)
for (long j1 = j_lo; j1 <= j_hi; j1++)
if (i1/sz == j1/sz) {
long i2 = i1 % sz;
long j2 = j1 % sz;
for (long i3 = 0; i3 < d1; i3++)
for (long j3 = 0; j3 < d1; j3++)
tmp[(i1-i_lo)*d1 + i3][(j1-j_lo)*d1 + j3] = A[i2][j2][i3][j3];
}
Tower<type> *tower = dynamic_cast<Tower<type> *>(towerBase.get());
if (invert)
mul(out, tower->M2i, tmp);
else
mul(out, tmp, tower->M2);
return false;
}
template<class type>
Step1aMatrix<type>::Step1aMatrix(const EncryptedArray& _ea,
const Vec<long>& reps,
long _cofactor, long _d1, long _d2, long _phim1,
shared_ptr<TowerBase> _towerBase,
bool _invert)
: ea(_ea), cofactor(_cofactor), d1(_d1), d2(_d2), phim1(_phim1),
towerBase(_towerBase), invert(_invert)
{
RBak bak; bak.save(); ea.getAlMod().restoreContext();
REBak ebak; ebak.save(); ea.getDerived(type()).restoreContextForG();
long p = ea.getAlMod().getZMStar().getP();
long r = ea.getAlMod().getR();
Tower<type> *tower = dynamic_cast<Tower<type> *>(towerBase.get());
const RX& H = tower->H;
assert(phim1 % d1 == 0);
long sz = phim1/d1;
Vec<RX> points;
points.SetLength(sz);
for (long j = 0; j < sz; j++)
points[j] = RX(reps[j], 1) % H;
Mat<RX> AA;
AA.SetDims(sz*d1, sz);
for (long j = 0; j < sz; j++)
AA[0][j] = 1;
for (long i = 1; i < sz*d1; i++)
for (long j = 0; j < sz; j++)
AA[i][j] = (AA[i-1][j] * points[j]) % H;
A.SetDims(sz, sz);
for (long i = 0; i < sz; i++)
for (long j = 0; j < sz; j++) {
A[i][j].SetDims(d1, d1);
for (long k = 0; k < d1; k++)
VectorCopy(A[i][j][k], AA[i*d1 + k][j], d1);
}
if (invert) {
Mat<R> A1, A2;
A1.SetDims(sz*d1, sz*d1);
for (long i = 0; i < sz*d1; i++)
for (long j = 0; j < sz*d1; j++)
A1[i][j] = A[i/d1][j/d1][i%d1][j%d1];
ppInvert(A2, A1, p, r);
for (long i = 0; i < sz*d1; i++)
for (long j = 0; j < sz*d1; j++)
A[i/d1][j/d1][i%d1][j%d1] = A2[i][j];
}
}
PlaintextBlockMatrixBaseInterface*
buildStep1aMatrix(const EncryptedArray& ea,
const Vec<long>& reps,
long cofactor, long d1, long d2, long phim1,
shared_ptr<TowerBase> towerBase,
bool invert = false)
{
switch (ea.getAlMod().getTag()) {
case PA_GF2_tag:
return new Step1aMatrix<PA_GF2>(ea, reps, cofactor, d1, d2, phim1, towerBase, invert);
case PA_zz_p_tag:
return new Step1aMatrix<PA_zz_p>(ea, reps, cofactor, d1, d2, phim1, towerBase, invert);
default: return 0;
}
}
/***** END Step1a stuff *****/
class Step2aShuffleBase {
public:
Vec<long> new_order;
virtual void apply(NewPlaintextArray& v) const = 0;
virtual void apply(Ctxt& v) const = 0;
};
template<class type>
class Step2aShuffle : public Step2aShuffleBase
{
public:
PA_INJECT(type)
virtual void apply(NewPlaintextArray& v) const
{
if (invert)
applyBack(v);
else
applyFwd(v);
}
virtual void apply(Ctxt& v) const
{
if (invert)
applyBack(v);
else
applyFwd(v);
}
private:
const EncryptedArray& ea;
shared_ptr<CubeSignature> sig;
Vec<long> reps;
long dim;
long cofactor;
shared_ptr<TowerBase> towerBase;
bool invert;
long p, r, d, d1, d2, phim1, phim2, nrows;
long hfactor;
Vec<long> cshift;
Mat<long> intraSlotPerm;
Mat<long> eval_reordering;
Mat<RE> eval_mat;
Mat<RX> inv_mat;
bool get(Vec<RE>& entry, long i, long j) const;
bool iget(Vec<RE>& entry, long i, long j) const;
typedef bool (Step2aShuffle<type>::*get_type)(Vec<RE>&, long, long) const;
void mat_mul(NewPlaintextArray& ctxt, get_type) const;
void mat_mul(Ctxt& ctxt, get_type) const;
void applyBack(NewPlaintextArray& v) const;
void applyBack(Ctxt& v) const;
void applyFwd(NewPlaintextArray& v) const;
void applyFwd(Ctxt& v) const;
public:
// constructor
Step2aShuffle(const EncryptedArray& _ea,
shared_ptr<CubeSignature> _sig,
const Vec<long>& _reps,
long _dim,
long _cofactor,
shared_ptr<TowerBase> _towerBase,
bool _invert = false);
};
template<class type>
Step2aShuffle<type>::Step2aShuffle(const EncryptedArray& _ea,
shared_ptr<CubeSignature> _sig,
const Vec<long>& _reps,
long _dim,
long _cofactor,
shared_ptr<TowerBase> _towerBase,
bool _invert)
: ea(_ea), sig(_sig), reps(_reps), dim(_dim), cofactor(_cofactor),
towerBase(_towerBase), invert(_invert)
{
RBak bak; bak.save(); ea.getAlMod().restoreContext();
REBak ebak; ebak.save(); ea.getDerived(type()).restoreContextForG();
Tower<type> *tower = dynamic_cast<Tower<type> *>(towerBase.get());
p = tower->p;
r = tower->r;
d = tower->d;
d1 = tower->d1;
d2 = tower->d2;
phim1 = sig->getDim(dim+1); // actually, phim1/d1
phim2 = sig->getDim(dim) * d2;
// cout << "phim1=" << phim1 << ", phim2=" << phim2 << ", d2=" << d2 << "\n";
nrows = phim1*phim2/d2;
hfactor = GCD(d2, phim1);
cshift.SetLength(d2);
Mat< Pair<long, long> > mapping;
mapping.SetDims(nrows, d2);
for (long i = 0; i < phim1*phim2; i++)
mapping[i/d2][i%d2] = Pair<long,long>(i%phim1, i/phim1);
// cout << "mapping:\n";
// cout << mapping << "\n";
Mat<long> hshift;
hshift.SetDims(nrows, d2/hfactor);
for (long j = 0 ; j < d2/hfactor; j++) {
hshift[0][j] = 0;
for (long i = 1; i < nrows; i++)
if (mapping[i][j*hfactor].a != 0)
hshift[i][j] = hshift[i-1][j];
else
hshift[i][j] = (hshift[i-1][j] + 1) % hfactor;
}
// cout << "hshift:\n";
// cout << hshift << "\n";
// apply the hshift's to mapping
for (long i = 0; i < nrows; i++) {
for (long j = 0; j < d2/hfactor; j++) {
// rotate subarray mapping[i][j*hfactor..j*hfactor+hfactor-1]
// by hshift[i][j]
long amt = hshift[i][j];
Vec< Pair<long, long> > tmp1, tmp2;
tmp1.SetLength(hfactor);
tmp2.SetLength(hfactor);
for (long k = 0; k < hfactor; k++) tmp1[k] = mapping[i][j*hfactor+k];
for (long k = 0; k < hfactor; k++) tmp2[(k+amt)%hfactor] = tmp1[k];
for (long k = 0; k < hfactor; k++) mapping[i][j*hfactor+k] = tmp2[k];
}
}
// cout << "mapping:\n";
// cout << mapping << "\n";
for (long j = 0; j < d2; j++) {
long amt = 0;
while (mapping[0][j].a != 0) {
amt++;
// rotate column j of mapping mapping by 1
Vec< Pair<long, long> > tmp1, tmp2;
tmp1.SetLength(nrows);
tmp2.SetLength(nrows);
for (long i = 0; i < nrows; i++) tmp1[i] = mapping[i][j];
for (long i = 0; i < nrows; i++) tmp2[(i+1)%nrows] = tmp1[i];
for (long i = 0; i < nrows; i++) mapping[i][j] = tmp2[i];
}
cshift[j] = amt;
}
// cout << "mapping:\n";
// cout << mapping << "\n";
new_order.SetLength(phim1);
for (long i = 0; i < phim1; i++)
new_order[i] = mapping[i][0].a;
// cout << new_order << "\n";
intraSlotPerm.SetDims(nrows, d2);
for (long i = 0; i < nrows; i++)
for (long j = 0; j < d2; j++)
intraSlotPerm[i][j] = (j/hfactor)*hfactor + mcMod(j - hshift[i][j/hfactor], hfactor);
eval_reordering.SetDims(phim1, phim2);
for (long i = 0; i < nrows; i++)
for (long j = 0; j < d2; j++) {
eval_reordering[i % phim1][(i / phim1)*d2 + j] = mapping[i][j].b;
assert(mapping[i][j].a == new_order[i % phim1]);
}
// cout << "eval_reordering: \n";
// cout << eval_reordering << "\n";
eval_mat.SetDims(phim2, phim2/d2);
Vec<RE> points;
points.SetLength(phim2/d2);
for (long j = 0; j < phim2/d2; j++)
points[j] = conv<RE>(RX(reps[j]*cofactor, 1));
for (long j = 0; j < phim2/d2; j++)
eval_mat[0][j] = 1;
for (long i = 1; i < phim2; i++)
for (long j = 0; j < phim2/d2; j++)
eval_mat[i][j] = eval_mat[i-1][j] * points[j];
if (invert) {
Mat<RX> inv_mat1;
inv_mat1.SetDims(phim2, phim2);
for (long i = 0; i < phim2; i++) {
for (long j = 0; j < phim2/d2; j++) {
Vec<RX> tmp1 = tower->convert1to2(eval_mat[i][j]);
for (long k = 0; k < d2; k++)
inv_mat1[i][j*d2+k] = tmp1[k];
}
}
eval_mat.kill(); // we no longer need it
{ // temporarily switch RE::modulus to the minpoly of the subring
REBak ebak1; ebak1.save();
RE::init(tower->H);
Mat<RE> inv_mat2, inv_mat3;
conv(inv_mat2, inv_mat1);
ppInvert(inv_mat3, inv_mat2, p, r);
conv(inv_mat, inv_mat3);
}
}
}
template<class type>
bool Step2aShuffle<type>::get(Vec<RE>& entry, long i, long j) const
{
long i1 = sig->getCoord(i, dim);
long j1 = sig->getCoord(j, dim);
if (sig->addCoord(i, dim, -i1) != sig->addCoord(j, dim, -j1))
return true;
long i2 = sig->getCoord(i, dim+1);
for (long i3 = 0; i3 < d2; i3++) {
entry[i3] = eval_mat[eval_reordering[i2][i1*d2+i3]][j1];
}
return false;
}
template<class type>
bool Step2aShuffle<type>::iget(Vec<RE>& entry, long i, long j) const
{
long i1 = sig->getCoord(i, dim);
long j1 = sig->getCoord(j, dim);
if (sig->addCoord(i, dim, -i1) != sig->addCoord(j, dim, -j1))
return true;
long j2 = sig->getCoord(j, dim+1);
Mat<RX> tmp;
tmp.SetDims(d2, d2);
for (long i3 = 0; i3 < d2; i3++)
for (long j3 = 0; j3 < d2; j3++)
tmp[i3][j3] = inv_mat[i1*d2+i3][eval_reordering[j2][j1*d2+j3]];
Tower<type> *tower = dynamic_cast<Tower<type> *>(towerBase.get());
for (long i3 = 0; i3 < d2; i3++) {
entry[i3] = tower->convert2to1(tmp[i3]);
}
return false;
}
template<class type>
void Step2aShuffle<type>::mat_mul(NewPlaintextArray& ctxt, get_type get_fn) const
{
Tower<type> *tower = dynamic_cast<Tower<type> *>(towerBase.get());
long nslots = ea.size();
// ctxt.cleanUp();
NewPlaintextArray res(ea);
Vec<RE> entry;
entry.SetLength(d2);
Vec<RE> C;
C.SetLength(d2);
Vec< Vec<RX> > diag;
diag.SetLength(nslots);
for (long j = 0; j < nslots; j++) diag[j].SetLength(d2);
for (long i = 0; i < nslots; i++) {
// process diagonal i
bool zDiag = true;
long nzLast = -1;
for (long j = 0; j < nslots; j++) {
bool zEntry = (this->*get_fn)(entry, mcMod(j-i, nslots), j);
if (!zEntry) { // non-empty entry
zDiag = false; // mark diagonal as non-empty
// clear entries between last nonzero entry and this one
for (long jj = nzLast+1; jj < j; jj++) {
for (long k = 0; k < d2; k++)
clear(diag[jj][k]);
}
nzLast = j;
// compute the lin poly coeffs
tower->buildLinPolyCoeffs(C, entry);
conv(diag[j], C);
}
}
if (zDiag) continue; // zero diagonal, continue
// clear trailing zero entries
for (long jj = nzLast+1; jj < nslots; jj++) {
for (long k = 0; k < d2; k++)
clear(diag[jj][k]);
}
// now diag[j] contains the lin poly coeffs
NewPlaintextArray shCtxt = ctxt;
rotate(ea, shCtxt, i);
// apply the linearlized polynomial
for (long k = 0; k < d2; k++) {
// compute the constant
bool zConst = true;
vector<ZZX> cvec;
cvec.resize(nslots);
for (long j = 0; j < nslots; j++) {
convert(cvec[j], diag[j][k]);
if (!IsZero(cvec[j])) zConst = false;
}
if (zConst) continue;
NewPlaintextArray cpoly(ea);
encode(ea, cpoly, cvec);
// FIXME: record the encoded polynomial for future use
NewPlaintextArray shCtxt1 = shCtxt;
frobeniusAutomorph(ea, shCtxt1, k*d1);
mul(ea, shCtxt1, cpoly);
add(ea, res, shCtxt1);
}
}
ctxt = res;
}
// FIXME: this mat_mul can probably be replaced by one that
// is more like the mat_mul1D routine in EncryptedArray
template<class type>
void Step2aShuffle<type>::mat_mul(Ctxt& ctxt, get_type get_fn) const
{
Tower<type> *tower = dynamic_cast<Tower<type> *>(towerBase.get());
long nslots = ea.size();
ctxt.cleanUp();
Ctxt res(ZeroCtxtLike, ctxt);
Vec<RE> entry;
entry.SetLength(d2);
Vec<RE> C;
C.SetLength(d2);
Vec< Vec<RX> > diag;
diag.SetLength(nslots);
for (long j = 0; j < nslots; j++) diag[j].SetLength(d2);
for (long i = 0; i < nslots; i++) {
// process diagonal i
bool zDiag = true;
long nzLast = -1;
for (long j = 0; j < nslots; j++) {
bool zEntry = (this->*get_fn)(entry, mcMod(j-i, nslots), j);
if (!zEntry) { // non-empty entry
zDiag = false; // mark diagonal as non-empty
// clear entries between last nonzero entry and this one
for (long jj = nzLast+1; jj < j; jj++) {
for (long k = 0; k < d2; k++)
clear(diag[jj][k]);
}
nzLast = j;
// compute the lin poly coeffs
tower->buildLinPolyCoeffs(C, entry);
conv(diag[j], C);
}
}
if (zDiag) continue; // zero diagonal, continue
// clear trailing zero entries
for (long jj = nzLast+1; jj < nslots; jj++) {
for (long k = 0; k < d2; k++)
clear(diag[jj][k]);
}
// now diag[j] contains the lin poly coeffs
Ctxt shCtxt = ctxt;
ea.rotate(shCtxt, i);
// apply the linearlized polynomial
for (long k = 0; k < d2; k++) {
// compute the constant
bool zConst = true;
vector<ZZX> cvec;
cvec.resize(nslots);
for (long j = 0; j < nslots; j++) {
convert(cvec[j], diag[j][k]);
if (!IsZero(cvec[j])) zConst = false;
}
if (zConst) continue;
ZZX cpoly;
ea.encode(cpoly, cvec);
// FIXME: record the encoded polynomial for future use
Ctxt shCtxt1 = shCtxt;
shCtxt1.frobeniusAutomorph(k*d1);
shCtxt1.multByConstant(cpoly);
res += shCtxt1;
}
}
ctxt = res;
}
template<class type>
void Step2aShuffle<type>::applyFwd(NewPlaintextArray& v) const
{
RBak bak; bak.save(); ea.getAlMod().restoreContext();
REBak ebak; ebak.save(); ea.getDerived(type()).restoreContextForG();
Tower<type> *tower = dynamic_cast<Tower<type> *>(towerBase.get());
long nslots = ea.size();
// cout << "starting shuffle...\n";
// tower->print(ea, cout, v, nrows);
// build linPolyCoeffs
Mat< Vec<ZZX> > C;
C.SetDims(d2, d2);
for (long i = 0; i < d2; i++)
for (long j = 0; j < d2; j++)
C[i][j].SetLength(nrows);
// C[i][j][k] is the j-th lin-poly coefficient
// of the map that projects subslot intraSlotPerm[k][i]
// onto subslot i
for (long k = 0; k < nrows; k++) {
for (long i = 0; i < d2; i++) {
long idx_in = intraSlotPerm[k][i];
long idx_out = i;
Vec< Vec<RX> > map2;
map2.SetLength(d2);
map2[idx_in].SetLength(idx_out+1);
map2[idx_in][idx_out] = 1;
// map2 projects idx_in ontot idx_out
Vec<RE> map1;
map1.SetLength(d2);
for (long j = 0; j < d2; j++)
map1[j] = tower->convert2to1(map2[j]);
Vec<RE> C1;
tower->buildLinPolyCoeffs(C1, map1);
for (long j = 0; j < d2; j++)
C[i][j][k] = conv<ZZX>(rep(C1[j]));
}
}
// mask each sub-slot
Vec< shared_ptr<NewPlaintextArray> > frobvec;
frobvec.SetLength(d2);
for (long j = 0; j < d2; j++) {
shared_ptr<NewPlaintextArray> ptr(new NewPlaintextArray(v));
frobeniusAutomorph(ea, *ptr, j*d1);
frobvec[j] = ptr;
}
Vec< shared_ptr<NewPlaintextArray> > colvec;
colvec.SetLength(d2);
for (long i = 0; i < d2; i++) {
shared_ptr<NewPlaintextArray> acc(new NewPlaintextArray(ea));
for (long j = 0; j < d2; j++) {
NewPlaintextArray const1(ea);
vector<ZZX> vec1;
vec1.resize(nslots);
for (long k = 0; k < nslots; k++)
vec1[k] = C[i][j][k % nrows];
encode(ea, const1, vec1);
NewPlaintextArray ctxt1(*frobvec[j]);
mul(ea, ctxt1, const1);
add(ea, *acc, ctxt1);
}
colvec[i] = acc;
}
// for (long i = 0; i < d2; i++) {
// cout << "column " << i << "\n";
// tower->print(ea, cout, *colvec[i], nrows);
// }
// rotate each subslot
for (long i = 0; i < d2; i++) {
if (cshift[i] == 0) continue;
if (nrows == nslots) {
// simple rotation
rotate(ea, *colvec[i], cshift[i]);
}
else {
// synthetic rotation
vector<long> mask;
mask.resize(nslots);
for (long j = 0; j < nslots; j++)
mask[j] = ((j % nrows) < (nrows - cshift[i]));
NewPlaintextArray emask(ea);
encode(ea, emask, mask);
NewPlaintextArray tmp1(*colvec[i]), tmp2(*colvec[i]);
mul(ea, tmp1, emask);
sub(ea, tmp2, tmp1);
rotate(ea, tmp1, cshift[i]);
rotate(ea, tmp2, -(nrows-cshift[i]));
add(ea, tmp1, tmp2);
*colvec[i] = tmp1;
}
}
// for (long i = 0; i < d2; i++) {
// cout << "column " << i << "\n";
// tower->print(ea, cout, *colvec[i], nrows);
// }
// combine columns
NewPlaintextArray v1(ea);
for (long i = 0; i < d2; i++)
add(ea, v1, *colvec[i]);
// apply the matrix
mat_mul(v1, &Step2aShuffle<type>::get);
v = v1;
}
template<class type>
void Step2aShuffle<type>::applyBack(NewPlaintextArray& v) const
{
RBak bak; bak.save(); ea.getAlMod().restoreContext();
REBak ebak; ebak.save(); ea.getDerived(type()).restoreContextForG();
Tower<type> *tower = dynamic_cast<Tower<type> *>(towerBase.get());
long nslots = ea.size();
mat_mul(v, &Step2aShuffle<type>::iget);
Mat< Vec<ZZX> > C;
C.SetDims(d2, d2);
for (long i = 0; i < d2; i++)
for (long j = 0; j < d2; j++)
C[i][j].SetLength(nrows);
// C[i][j][k] is the j-th lin-poly coefficient
// of the map that projects subslot i
// onto subslot i if hfactor == 1, or
// onto subslot 0 if hfactor != 1
for (long k = 0; k < nrows; k++) {
for (long i = 0; i < d2; i++) {
long idx_in = i;
long idx_out = (hfactor == 1) ? i : 0;
Vec< Vec<RX> > map2;
map2.SetLength(d2);
map2[idx_in].SetLength(idx_out+1);
map2[idx_in][idx_out] = 1;
// map2 projects idx_in ontot idx_out
Vec<RE> map1;
map1.SetLength(d2);
for (long j = 0; j < d2; j++)
map1[j] = tower->convert2to1(map2[j]);
Vec<RE> C1;
tower->buildLinPolyCoeffs(C1, map1);
for (long j = 0; j < d2; j++)
C[i][j][k] = conv<ZZX>(rep(C1[j]));
}
}
// mask each sub-slot
Vec< shared_ptr<NewPlaintextArray> > frobvec;
frobvec.SetLength(d2);
for (long j = 0; j < d2; j++) {
shared_ptr<NewPlaintextArray> ptr(new NewPlaintextArray(v));
frobeniusAutomorph(ea, *ptr, j*d1);
frobvec[j] = ptr;
}
Vec< shared_ptr<NewPlaintextArray> > colvec;
colvec.SetLength(d2);
for (long i = 0; i < d2; i++) {
shared_ptr<NewPlaintextArray> acc(new NewPlaintextArray(ea));
for (long j = 0; j < d2; j++) {
NewPlaintextArray const1(ea);
vector<ZZX> vec1;
vec1.resize(nslots);
for (long k = 0; k < nslots; k++)
vec1[k] = C[i][j][k % nrows];
encode(ea, const1, vec1);
NewPlaintextArray ctxt1(*frobvec[j]);
mul(ea, ctxt1, const1);
add(ea, *acc, ctxt1);
}
colvec[i] = acc;
}
// rotate each subslot
for (long i = 0; i < d2; i++) {
long shamt = mcMod(-cshift[i], nrows);
if (shamt == 0) continue;
if (nrows == nslots) {
// simple rotation
rotate(ea, *colvec[i], shamt);
}
else {
// synthetic rotation
vector<long> mask;
mask.resize(nslots);
for (long j = 0; j < nslots; j++)
mask[j] = ((j % nrows) < (nrows - shamt));
NewPlaintextArray emask(ea);
encode(ea, emask, mask);
NewPlaintextArray tmp1(*colvec[i]), tmp2(*colvec[i]);
mul(ea, tmp1, emask);
sub(ea, tmp2, tmp1);
rotate(ea, tmp1, shamt);
rotate(ea, tmp2, -(nrows-shamt));
add(ea, tmp1, tmp2);
*colvec[i] = tmp1;
}
}
// combine columns...
// optimized to avoid unnecessary constant muls
// when hfactor == 1
NewPlaintextArray v1(ea);
if (hfactor == 1) {
for (long i = 0; i < d2; i++) {
add(ea, v1, *colvec[i]);
}
}
else {
for (long i = 0; i < d2; i++) {
NewPlaintextArray const1(ea);
vector<ZZX> vec1;
vec1.resize(nslots);
for (long k = 0; k < nslots; k++)
vec1[k] = conv<ZZX>(RX(intraSlotPerm[k%nrows][i], 1) % RE::modulus());
encode(ea, const1, vec1);
NewPlaintextArray ctxt1(*colvec[i]);
mul(ea, ctxt1, const1);
add(ea, v1, ctxt1);
}
}
v = v1;
}
template<class type>
void Step2aShuffle<type>::applyBack(Ctxt& v) const
{
RBak bak; bak.save(); ea.getAlMod().restoreContext();
REBak ebak; ebak.save(); ea.getDerived(type()).restoreContextForG();
Tower<type> *tower = dynamic_cast<Tower<type> *>(towerBase.get());
long nslots = ea.size();
mat_mul(v, &Step2aShuffle<type>::iget);
v.cleanUp();
Mat< Vec<ZZX> > C;
C.SetDims(d2, d2);
for (long i = 0; i < d2; i++)
for (long j = 0; j < d2; j++)
C[i][j].SetLength(nrows);
// C[i][j][k] is the j-th lin-poly coefficient
// of the map that projects subslot i
// onto subslot i if hfactor == 1, or
// onto subslot 0 if hfactor != 1
for (long k = 0; k < nrows; k++) {
for (long i = 0; i < d2; i++) {
long idx_in = i;
long idx_out = (hfactor == 1) ? i : 0;
Vec< Vec<RX> > map2;
map2.SetLength(d2);
map2[idx_in].SetLength(idx_out+1);
map2[idx_in][idx_out] = 1;
// map2 projects idx_in ontot idx_out
Vec<RE> map1;
map1.SetLength(d2);
for (long j = 0; j < d2; j++)
map1[j] = tower->convert2to1(map2[j]);
Vec<RE> C1;
tower->buildLinPolyCoeffs(C1, map1);
for (long j = 0; j < d2; j++)
C[i][j][k] = conv<ZZX>(rep(C1[j]));
}
}
// mask each sub-slot
Vec< shared_ptr<Ctxt> > frobvec;
frobvec.SetLength(d2);
for (long j = 0; j < d2; j++) {
shared_ptr<Ctxt> ptr(new Ctxt(v));
ptr->frobeniusAutomorph(j*d1);
frobvec[j] = ptr;
}
Vec< shared_ptr<Ctxt> > colvec;
colvec.SetLength(d2);
for (long i = 0; i < d2; i++) {
shared_ptr<Ctxt> acc(new Ctxt(ZeroCtxtLike, v));
for (long j = 0; j < d2; j++) {
ZZX const1;
vector<ZZX> vec1;
vec1.resize(nslots);
for (long k = 0; k < nslots; k++)
vec1[k] = C[i][j][k % nrows];
ea.encode(const1, vec1);
Ctxt ctxt1(*frobvec[j]);
ctxt1.multByConstant(const1);
(*acc) += ctxt1;
}
colvec[i] = acc;
}
// rotate each subslot
for (long i = 0; i < d2; i++) {
long shamt = mcMod(-cshift[i], nrows);
if (shamt == 0) continue;
if (nrows == nslots) {
// simple rotation
ea.rotate(*colvec[i], shamt);
}
else {
// synthetic rotation
vector<long> mask;
mask.resize(nslots);
for (long j = 0; j < nslots; j++)
mask[j] = ((j % nrows) < (nrows - shamt));
ZZX emask;
ea.encode(emask, mask);
Ctxt tmp1(*colvec[i]), tmp2(*colvec[i]);
tmp1.multByConstant(emask);
tmp2 -= tmp1;
ea.rotate(tmp1, shamt);
ea.rotate(tmp2, -(nrows-shamt));
tmp1 += tmp2;
*colvec[i] = tmp1;
}
}
// combine columns...
// optimized to avoid unnecessary constant muls
// when hfactor == 1
Ctxt v1(ZeroCtxtLike, v);
if (hfactor == 1) {
for (long i = 0; i < d2; i++) {
v1 += *colvec[i];
}
}
else {
for (long i = 0; i < d2; i++) {
ZZX const1;
vector<ZZX> vec1;
vec1.resize(nslots);
for (long k = 0; k < nslots; k++)
vec1[k] = conv<ZZX>(RX(intraSlotPerm[k%nrows][i], 1) % RE::modulus());
ea.encode(const1, vec1);
Ctxt ctxt1(*colvec[i]);
ctxt1.multByConstant(const1);
v1 += ctxt1;
}
}
v = v1;
}
template<class type>
void Step2aShuffle<type>::applyFwd(Ctxt& v) const
{
RBak bak; bak.save(); ea.getAlMod().restoreContext();
REBak ebak; ebak.save(); ea.getDerived(type()).restoreContextForG();
Tower<type> *tower = dynamic_cast<Tower<type> *>(towerBase.get());
long nslots = ea.size();
// cout << "starting shuffle...\n";
// tower->print(ea, cout, v, nrows);
// build linPolyCoeffs
v.cleanUp();
Mat< Vec<ZZX> > C;
C.SetDims(d2, d2);
for (long i = 0; i < d2; i++)
for (long j = 0; j < d2; j++)
C[i][j].SetLength(nrows);
// C[i][j][k] is the j-th lin-poly coefficient
// of the map that projects subslot intraSlotPerm[k][i]
// onto subslot i
for (long k = 0; k < nrows; k++) {
for (long i = 0; i < d2; i++) {
long idx_in = intraSlotPerm[k][i];
long idx_out = i;
Vec< Vec<RX> > map2;
map2.SetLength(d2);
map2[idx_in].SetLength(idx_out+1);
map2[idx_in][idx_out] = 1;
// map2 projects idx_in ontot idx_out
Vec<RE> map1;
map1.SetLength(d2);
for (long j = 0; j < d2; j++)
map1[j] = tower->convert2to1(map2[j]);
Vec<RE> C1;
tower->buildLinPolyCoeffs(C1, map1);
for (long j = 0; j < d2; j++)
C[i][j][k] = conv<ZZX>(rep(C1[j]));
}
}
// FIXME: in the case where nrows != nslots, which
// is the same as saying we are at dimension 0, we can
// avoid the extra masking depth incurred for the
// synthetic rotations, by folding them into
// the masking/frobenius step. A similar optimization
// applies to the applyBack routine.
// mask each sub-slot
Vec< shared_ptr<Ctxt> > frobvec;
frobvec.SetLength(d2);
for (long j = 0; j < d2; j++) {
shared_ptr<Ctxt> ptr(new Ctxt(v));
ptr->frobeniusAutomorph(j*d1);
frobvec[j] = ptr;
}
Vec< shared_ptr<Ctxt> > colvec;
colvec.SetLength(d2);
for (long i = 0; i < d2; i++) {
shared_ptr<Ctxt> acc(new Ctxt(ZeroCtxtLike, v));
for (long j = 0; j < d2; j++) {
ZZX const1;
vector<ZZX> vec1;
vec1.resize(nslots);
for (long k = 0; k < nslots; k++)
vec1[k] = C[i][j][k % nrows];
ea.encode(const1, vec1);
Ctxt ctxt1(*frobvec[j]);
ctxt1.multByConstant(const1);
(*acc) += ctxt1;
}
colvec[i] = acc;
}
// for (long i = 0; i < d2; i++) {
// cout << "column " << i << "\n";
// tower->print(ea, cout, *colvec[i], nrows);
// }
// rotate each subslot
for (long i = 0; i < d2; i++) {
if (cshift[i] == 0) continue;
if (nrows == nslots) {
// simple rotation
ea.rotate(*colvec[i], cshift[i]);
}
else {
// synthetic rotation
vector<long> mask;
mask.resize(nslots);
for (long j = 0; j < nslots; j++)
mask[j] = ((j % nrows) < (nrows - cshift[i]));
ZZX emask;
ea.encode(emask, mask);
Ctxt tmp1(*colvec[i]), tmp2(*colvec[i]);
tmp1.multByConstant(emask);
tmp2 -= tmp1;
ea.rotate(tmp1, cshift[i]);
ea.rotate(tmp2, -(nrows-cshift[i]));
tmp1 += tmp2;
*colvec[i] = tmp1;
}
}
// for (long i = 0; i < d2; i++) {
// cout << "column " << i << "\n";
// tower->print(ea, cout, *colvec[i], nrows);
// }
// conbine columns
Ctxt v1(ZeroCtxtLike, v);
for (long i = 0; i < d2; i++)
v1 += *colvec[i];
// apply the matrix
mat_mul(v1, &Step2aShuffle<type>::get);
v = v1;
}
Step2aShuffleBase*
buildStep2aShuffle(const EncryptedArray& ea,
shared_ptr<CubeSignature> sig,
const Vec<long>& reps,
long dim,
long cofactor,
shared_ptr<TowerBase> towerBase,
bool invert = false)
{
switch (ea.getAlMod().getTag()) {
case PA_GF2_tag:
return new Step2aShuffle<PA_GF2>(ea, sig, reps, dim, cofactor, towerBase, invert);
case PA_zz_p_tag:
return new Step2aShuffle<PA_zz_p>(ea, sig, reps, dim, cofactor, towerBase, invert);
default: return 0;
}
}
/***** END Step2a stuff *****/
void init_representatives(Vec<long>& representatives, long m, long p)
{
Vec<bool> available;
available.SetLength(m);
long num_available = 0;
for (long i = 0; i < m; i++) {
if (GCD(i, m) == 1) {
available[i] = true;
num_available++;
}
else
available[i] = false;
}
representatives.SetLength(0);
while (num_available > 0) {
// choose next available at random
long i;
do {
i = RandomBnd(m);
} while (!available[i]);
append(representatives, i);
// mark all conjugates as unavailable
long j = i;
do {
available[j] = false;
num_available--;
j = MulMod(j, p, m);
} while (j != i);
}
}
void init_slot_mappings(Vec<long>& slot_index,
Vec<long>& slot_rotate,
const Vec<long>& representatives,
long m,
long p,
const FHEcontext& context)
{
long nslots = representatives.length();
assert(nslots == long(context.zMStar.getNSlots()));
slot_index.SetLength(nslots);
slot_rotate.SetLength(nslots);
Vec<bool> used; // for debugging
used.SetLength(nslots);
for (long i = 0; i < nslots; i++) used[i] = false;
for (long i = 0; i < nslots; i++) {
long t = representatives[i];
long h = 0;
long idx;
while ((idx = context.zMStar.indexOfRep(InvMod(t, m))) == -1) {
t = MulMod(t, p, m);
h++;
}
assert(!used[idx]);
used[idx] = true;
slot_index[idx] = i;
slot_rotate[idx] = h;
}
}
// apply p^{vec[i]} to slot i
void frobeniusAutomorph(Ctxt& ctxt, const EncryptedArray& ea, const Vec<long>& vec)
{
long d = ea.getDegree();
long nslots = ea.size();
// construct masks
Vec<ZZX> masks;
masks.SetLength(d);
for (long i = 0; i < d; i++) {
vector<long> mask1_vec;
mask1_vec.resize(nslots);
for (long j = 0; j < nslots; j++)
mask1_vec[j] = (mcMod(vec[j], d) == i);
ZZX mask1_poly;
ea.encode(mask1_poly, mask1_vec);
masks[i] = mask1_poly;
}
ctxt.cleanUp();
Ctxt acc(ZeroCtxtLike, ctxt);
for (long i = 0; i < d; i++) {
if (masks[i] != 0) {
Ctxt tmp = ctxt;
tmp.frobeniusAutomorph(i);
tmp.multByConstant(masks[i]);
acc += tmp;
}
}
ctxt = acc;
}
OldEvalMap::OldEvalMap(const EncryptedArray& _ea, const Vec<long>& mvec,
long width, bool _invert)
: ea(_ea), invert(_invert)
{
const FHEcontext& context = ea.getContext();
const PAlgebra& zMStar = context.zMStar;
long p = zMStar.getP();
long d = zMStar.getOrdP();
// FIXME: we should check that ea was initilized with
// G == factors[0], but this is a slight pain to check
// currently
nfactors = mvec.length();
assert(nfactors > 0);
for (long i = 0; i < nfactors; i++)
for (long j = i+1; j < nfactors; j++)
assert(GCD(mvec[i], mvec[j]) == 1);
long m = computeProd(mvec);
assert(m == long(zMStar.getM()));
Vec<long> phivec(INIT_SIZE, nfactors);
for (long i = 0; i < nfactors; i++) phivec[i] = phi_N(mvec[i]);
long phim = computeProd(phivec);
Vec<long> dprodvec(INIT_SIZE, nfactors+1);
dprodvec[nfactors] = 1;
for (long i = nfactors-1; i >= 0; i--)
dprodvec[i] = dprodvec[i+1] *
multOrd(PowerMod(p % mvec[i], dprodvec[i+1], mvec[i]), mvec[i]);
Vec<long> dvec(INIT_SIZE, nfactors);
for (long i = 0; i < nfactors; i++)
dvec[i] = dprodvec[i] / dprodvec[i+1];
long nslots = phim/d;
assert(d == dprodvec[0]);
assert(nslots == long(zMStar.getNSlots()));
long inertPrefix = 0;
for (long i = 0; i < nfactors && dvec[i] == 1; i++) {
inertPrefix++;
}
if (inertPrefix == nfactors-1)
easy = true;
else if (inertPrefix == nfactors-2)
easy = false;
else
Error("OldEvalMap: case not handled: bad inertPrefix");
Vec< Vec<long> > local_reps(INIT_SIZE, nfactors);
for (long i = 0; i < nfactors; i++)
init_representatives(local_reps[i], mvec[i],
PowerMod(p % mvec[i], dprodvec[i+1], mvec[i]));
Vec<long> crtvec(INIT_SIZE, nfactors);
for (long i = 0; i < nfactors; i++)
crtvec[i] = (m/mvec[i]) * InvMod((m/mvec[i]) % mvec[i], mvec[i]);
Vec<long> redphivec(INIT_SIZE, nfactors);
for (long i = 0; i < nfactors; i++)
redphivec[i] = phivec[i]/dvec[i];
CubeSignature redphisig(redphivec);
Vec<long> global_reps(INIT_SIZE, phim/d);
for (long i = 0; i < phim/d; i++) {
global_reps[i] = 0;
for (long j = 0; j < nfactors; j++) {
long i1 = redphisig.getCoord(i, j);
global_reps[i] = (global_reps[i] + crtvec[j]*local_reps[j][i1]) % m;
}
}
Vec<long> slot_index;
init_slot_mappings(slot_index, slot_rotate, global_reps, m, p, context);
Vec< shared_ptr<CubeSignature> > sig_sequence;
sig_sequence.SetLength(nfactors+1);
sig_sequence[nfactors] = shared_ptr<CubeSignature>(new CubeSignature(phivec));
Vec<long> reduced_phivec = phivec;
for (long dim = nfactors-1; dim >= 0; dim--) {
reduced_phivec[dim] /= dvec[dim];
sig_sequence[dim] =
shared_ptr<CubeSignature>(new CubeSignature(reduced_phivec));
}
if (easy) {
long dim = nfactors - 1;
mat1 = shared_ptr<PlaintextBlockMatrixBaseInterface>(
buildStep1Matrix(ea, sig_sequence[dim], local_reps[dim], dim, m/mvec[dim], invert));
matvec.SetLength(nfactors-1);
while (dim > 0) {
dim--;
matvec[dim] = shared_ptr<PlaintextMatrixBaseInterface>(
buildStep2Matrix(ea, sig_sequence[dim], local_reps[dim], dim, m/mvec[dim], invert));
}
}
else {
long m1 = mvec[nfactors-1];
long cofactor = m/m1;
long d1 = dvec[nfactors-1];
long d2 = d/d1;
tower = shared_ptr<TowerBase>(buildTowerBase(ea, cofactor, d1, d2));
long dim = nfactors-1;
mat1 = shared_ptr<PlaintextBlockMatrixBaseInterface>(
buildStep1aMatrix(ea, local_reps[dim], cofactor, d1, d2, phivec[dim], tower, invert));
dim--;
shuffle = shared_ptr<Step2aShuffleBase>(
buildStep2aShuffle(ea, sig_sequence[dim], local_reps[dim], dim, m/mvec[dim], tower, invert));
long phim1 = shuffle->new_order.length();
Vec<long> no_i; // inverse function
no_i.SetLength(phim1);
for (long i = 0; i < phim1; i++)
no_i[shuffle->new_order[i]] = i;
Vec<long> slot_index1;
slot_index1.SetLength(nslots);
for (long i = 0; i < nslots; i++)
slot_index1[i] = (slot_index[i]/phim1)*phim1 + no_i[slot_index[i] % phim1];
slot_index = slot_index1;
matvec.SetLength(nfactors-2);
while (dim > 0) {
dim--;
matvec[dim] = shared_ptr<PlaintextMatrixBaseInterface>(
buildStep2Matrix(ea, sig_sequence[dim], local_reps[dim], dim, m/mvec[dim], invert));
}
}
if (invert) {
Vec<long> slot_index_i; // inverse function
slot_index_i.SetLength(nslots);
for (long i = 0; i < nslots; i++)
slot_index_i[slot_index[i]] = i;
slot_index = slot_index_i;
for (long i = 0; i < nslots; i++)
slot_rotate[i] = mcMod(-slot_rotate[i], d);
}
Vec<GenDescriptor> gvec(INIT_SIZE, ea.dimension());
for (long i=0; i<ea.dimension(); i++)
gvec[i] = GenDescriptor(/*order=*/ea.sizeOfDimension(i),
/*good=*/ ea.nativeDimension(i), /*genIdx=*/i);
GeneratorTrees trees;
long cost = trees.buildOptimalTrees(gvec, width);
if (cost == NTL_MAX_LONG)
Error("OldEvalMap: can't build network for given width");
net = shared_ptr<PermNetwork>(new PermNetwork(slot_index, trees));
}
void OldEvalMap::apply(Ctxt& ctxt) const
{
if (!invert) {
// forward direction
mat_mul(ea, ctxt, *mat1);
if (!easy) shuffle->apply(ctxt);
for (long i = matvec.length()-1; i >= 0; i--)
mat_mul(ea, ctxt, *matvec[i]);
net->applyToCtxt(ctxt, ea);
frobeniusAutomorph(ctxt, ea, slot_rotate);
}
else {
frobeniusAutomorph(ctxt, ea, slot_rotate);
net->applyToCtxt(ctxt, ea);
for (long i = 0; i < matvec.length(); i++)
mat_mul(ea, ctxt, *matvec[i]);
if (!easy) shuffle->apply(ctxt);
mat_mul(ea, ctxt, *mat1);
}
}
//! \endcond
| 23.459759
| 99
| 0.55792
|
fionser
|
e1df65219b599cd4192ed2fa2a59b7d463803b94
| 12,858
|
cpp
|
C++
|
PC/LoadWholeMap/LoadWholeMap.cpp
|
JuniorDjjr/LoadWholeMap
|
b935084f38cba199c066ed41d935f11dd38266b7
|
[
"MIT"
] | 2
|
2021-11-18T16:53:35.000Z
|
2022-03-23T09:25:24.000Z
|
PC/LoadWholeMap/LoadWholeMap.cpp
|
JuniorDjjr/LoadWholeMap
|
b935084f38cba199c066ed41d935f11dd38266b7
|
[
"MIT"
] | null | null | null |
PC/LoadWholeMap/LoadWholeMap.cpp
|
JuniorDjjr/LoadWholeMap
|
b935084f38cba199c066ed41d935f11dd38266b7
|
[
"MIT"
] | 1
|
2021-11-18T16:53:39.000Z
|
2021-11-18T16:53:39.000Z
|
#include "plugin.h"
#include "..\injector\assembly.hpp"
#include "CStreaming.h"
#include "IniReader/IniReader.h"
#include "CIplStore.h"
#include "extensions/ScriptCommands.h"
#include "CMessages.h"
#include "CTimer.h"
#include "CPopCycle.h"
#include "CAnimManager.h"
#include <vector>
using namespace plugin;
using namespace std;
using namespace injector;
const int MAX_MB = 2000;
const int MULT_MB_TO_BYTE = 1048576;
constexpr unsigned int MAX_BYTE_LIMIT = (MAX_MB * MULT_MB_TO_BYTE);
class LoadWholeMap {
public:
LoadWholeMap() {
static unsigned int streamMemoryForced = 0;
static int totalBinaryIPLconfig = 0;
static int totalBinaryIPLloaded = 0;
static int loadCheck = 0;
static float removeUnusedWhenPercent = 0.0f;
static int lastTimeRemoveUnused = 0;
static int gameStartedAfterLoad = 0;
static int removeUnusedIntervalMs = 0;
static fstream lg;
static CIniReader ini("ImprovedStreaming.ini");
static bool loadBinaryIPLs = ini.ReadInteger("Settings", "LoadBinaryIPLs", 0) == 1;
static bool preLoadLODs = ini.ReadInteger("Settings", "PreLoadLODs", 0) == 1;
static bool preLoadAnims = ini.ReadInteger("Settings", "PreLoadAnims", 0) == 1;
static int logMode = ini.ReadInteger("Settings", "LogMode", -1);
static std::vector<void*> lods; // CEntity*
if (logMode >= 0) {
lg.open("ImprovedStreaming.log", fstream::out | fstream::trunc);
lg << "v1.0" << endl;
}
Events::initRwEvent += []
{
if (GetModuleHandleA("LoadWholeMap.SA.asi")) {
MessageBoxA(0, "'LoadWholeMap.SA.asi' is now 'ImprovedStreaming.SA.asi'. Delete the old mod.", "ImprovedStreaming.SA.asi", 0);
}
/*if (loadBinaryIPLs)
{
static std::vector<std::string> IPLStreamNames;
totalBinaryIPLconfig = 0;
ifstream stream("LoadWholeMap_BinaryIPLs.dat");
for (string line; getline(stream, line); ) {
if (line[0] != ';' && line[0] != '#') {
while (getline(stream, line) && line.compare("end")) {
if (line[0] != ';' && line[0] != '#') {
char name[32];
int loadWhen; // not used anymore
if (sscanf(line.c_str(), "%s %i", name, &loadWhen) >= 1)
{
IPLStreamNames.push_back(name);
}
}
}
}
}
// Based on ThirteenAG's project2dfx
// Not working now (even original p2dfx code didn't work)
struct LoadAllBinaryIPLs
{
void operator()(injector::reg_pack&)
{
static auto CIplStoreLoad = (char *(__cdecl *)()) 0x5D54A0;
CIplStoreLoad();
static auto IplFilePoolLocate = (int(__cdecl *)(const char *name)) 0x404AC0;
static auto CIplStoreRequestIplAndIgnore = (char *(__cdecl *)(int a1)) 0x405850;
injector::address_manager::singleton().IsHoodlum() ?
injector::WriteMemory<char>(0x015651C1 + 3, 0, true) :
injector::WriteMemory<char>(0x405881 + 3, 0, true);
for (auto it = IPLStreamNames.cbegin(); it != IPLStreamNames.cend(); it++)
{
lg << "Loading IPL " << (string)*it << "\n";
lg.flush();
CIplStoreRequestIplAndIgnore(IplFilePoolLocate(it->c_str()));
}
injector::address_manager::singleton().IsHoodlum() ?
injector::WriteMemory<char>(0x015651C1 + 3, 1, true) :
injector::WriteMemory<char>(0x405881 + 3, 1, true);
}
}; injector::MakeInline<LoadAllBinaryIPLs>(0x5D19A4);
}*/
// by ThirteenAG
if (preLoadLODs) {
// not hooked yet (p2dfx may hook it)
// ...but this mod enabled other stuff that is better than how p2dfx works
//if (injector::ReadMemory<uint32_t>(0x5B5295, true) == 0x2248BF0F) {
injector::MakeInline<0x5B5295, 0x5B5295 + 8>([](injector::reg_pack& regs)
{
regs.ecx = *(uint16_t*)(regs.eax + 0x22); // mah let's make it unsigned
regs.edx = *(uint16_t*)(regs.esi + 0x22);
lods.push_back((void*)regs.eax);
});
//}
}
};
// ---------------------------------------------------
Events::initScriptsEvent.after += []
{
loadCheck = 1;
};
Events::processScriptsEvent.after += []
{
if (loadCheck < 3) // ignore first thicks
{
loadCheck++;
return;
}
if (streamMemoryForced > 0) {
if (CStreaming::ms_memoryAvailable < streamMemoryForced) {
CStreaming::ms_memoryAvailable = streamMemoryForced;
}
}
/*if (totalBinaryIPLconfig > 0 && totalBinaryIPLloaded < totalBinaryIPLconfig)
{
for (unsigned int i = 0; i < GetBinaryIPLconfigVector().size(); i++) {
if (GetBinaryIPLconfigVector()[i].loaded == false && CTimer::m_snTimeInMilliseconds > GetBinaryIPLconfigVector()[i].loadWhen)
{
CIplStore::RequestIplAndIgnore(GetBinaryIPLconfigVector()[i].slot);
GetBinaryIPLconfigVector()[i].loaded = true;
totalBinaryIPLloaded++;
}
}
}*/
if (loadCheck == 3)
{
if (!(GetKeyState(0x10) & 0x8000)) // SHIFT
{
streamMemoryForced = ini.ReadInteger("Settings", "StreamMemoryForced", 0);
if (streamMemoryForced > 0)
{
if (streamMemoryForced > MAX_MB) {
streamMemoryForced = MAX_BYTE_LIMIT;
}
else {
streamMemoryForced *= MULT_MB_TO_BYTE;
}
CStreaming::ms_memoryAvailable = streamMemoryForced;
}
removeUnusedWhenPercent = ini.ReadFloat("Settings", "RemoveUnusedWhenPercent", 0.0f);
removeUnusedIntervalMs = ini.ReadInteger("Settings", "RemoveUnusedInterval", 60);
CTimer::Stop();
if (preLoadLODs) {
// Based on ThirteenAG's project2dfx
if (lods.size() > 0) {
// Put the id of the lods in another container
std::vector<uint16_t> lods_id(lods.size());
std::transform(lods.begin(), lods.end(), lods_id.begin(), [](void* entity)
{
return *(uint16_t*)((uintptr_t)(entity)+0x22);
});
// Load all lod models
std::for_each(lods_id.begin(), std::unique(lods_id.begin(), lods_id.end()), [](uint16_t id) { CStreaming::RequestModel(id, eStreamingFlags::MISSION_REQUIRED); });
CStreaming::LoadAllRequestedModels(false);
// Instantiate all lod entities RwObject
//if (false) {
std::for_each(lods.begin(), lods.end(), [](void* entity) {
auto rwObject = *(void**)((uintptr_t)(entity)+0x18);
if (rwObject == nullptr) {
//lg << "Loading LOD " << (int)entity << ".\n";
//injector::thiscall<void(void*)>::vtbl<7>(entity);
CallMethod<0x533D30>(entity);
}
});
//}
}
}
if (preLoadAnims) {
int animBlocksIdStart = injector::ReadMemory<int>(0x48C36B + 2, true);
for (int id = 1; id < CAnimManager::ms_numAnimBlocks; ++id) {
if (logMode >= 1)
{
lg << "Start loading anim " << id << endl;
}
CStreaming::RequestModel(id + animBlocksIdStart, eStreamingFlags::MISSION_REQUIRED);
CAnimManager::AddAnimBlockRef(id);
}
CStreaming::LoadAllRequestedModels(false);
if (logMode >= 1)
{
lg << "Finished loading anims." << endl;
}
}
int i = 0;
while (true)
{
int loadEach = 0;
int startId = -1;
int endId = -1;
int ignoreStart = -1;
int ignoreEnd = -1;
int biggerThan = -1;
int smallerThan = -1;
int ignorePedGroup = -1;
bool keepLoaded = true;
i++;
string range = "Range" + to_string(i);
loadEach = ini.ReadInteger(range, "LoadEach", 0);
startId = ini.ReadInteger(range, "Start", -1);
endId = ini.ReadInteger(range, "End", -1);
ignoreStart = ini.ReadInteger(range, "IgnoreStart", -1);
ignoreEnd = ini.ReadInteger(range, "IgnoreEnd", -1);
biggerThan = ini.ReadInteger(range, "IfBiggerThan", -1);
smallerThan = ini.ReadInteger(range, "IfSmallerThan", -1);
ignorePedGroup = ini.ReadInteger(range, "IgnorePedGroup", -1) - 1;
keepLoaded = ini.ReadInteger(range, "KeepLoaded", 0) == true;
if (startId <= 0 && endId <= 0) break;
if (ini.ReadInteger(range, "Enabled", 0) != 1) continue;
if (logMode >= 0) {
lg << "Start loading ID Range: " << i << "\n";
lg.flush();
}
if (endId >= startId)
{
for (int model = startId; model <= endId; model++)
{
if (GetKeyState(0x10) & 0x8000) break; // SHIFT
if ((ignoreStart <= 0 && ignoreEnd <= 0) || (model > ignoreEnd || model < ignoreStart))
{
if (CStreaming::ms_aInfoForModel[model].m_nCdSize != 0)
{
if ((biggerThan <= 0 && smallerThan <= 0) || (CStreaming::ms_aInfoForModel[model].m_nCdSize >= biggerThan && CStreaming::ms_aInfoForModel[model].m_nCdSize <= smallerThan))
{
check_limit_to_load:
if ((signed int)CStreaming::ms_memoryUsed > (signed int)(CStreaming::ms_memoryAvailable - 50000000))
{
if (CStreaming::ms_memoryAvailable >= MAX_BYTE_LIMIT)
{
if (logMode >= 0) {
lg << "ERROR: Not enough space\n";
}
CMessages::AddMessageJumpQ((char*)"~r~ERROR Load Whole Map: Not enough space. Try to disable some ranges, configure or use other settings.", 8000, false, false);
}
else {
if (streamMemoryForced > 0) {
if (IncreaseStreamingMemoryLimit(256)) {
streamMemoryForced = CStreaming::ms_memoryAvailable;
if (logMode >= 0) {
lg << "Streaming memory automatically increased to " << streamMemoryForced << " \n";
}
goto check_limit_to_load;
}
}
else {
if (logMode >= 0) {
lg << "ERROR: Not enough space. Try to increase the streaming memory.\n";
}
CMessages::AddMessageJumpQ((char*)"~r~ERROR Load Whole Map: Not enough space. Try to increase the streaming memory.", 8000, false, false);
}
}
if (logMode >= 0) {
lg.flush();
}
break;
}
else
{
if (ignorePedGroup > 0 && CPopCycle::IsPedInGroup(model, ignorePedGroup)) {
if (logMode >= 1)
{
lg << "Model " << model << " is ignored. Pedgroup: " << ignorePedGroup << "\n";
lg.flush();
}
continue;
}
if (logMode >= 1)
{
lg << "Loading " << model << " size " << CStreaming::ms_aInfoForModel[model].m_nCdSize << "\n";
lg.flush();
}
CStreaming::RequestModel(model, keepLoaded ? eStreamingFlags::MISSION_REQUIRED : eStreamingFlags::GAME_REQUIRED);
if (CStreaming::ms_numModelsRequested >= loadEach) CStreaming::LoadAllRequestedModels(false);
}
}
}
}
}
CStreaming::LoadAllRequestedModels(false);
}
if (logMode >= 0) {
lg << "Finished loading ID Range: " << i << "\n";
lg.flush();
}
}
// last margin check
if ((signed int)CStreaming::ms_memoryUsed > (signed int)(CStreaming::ms_memoryAvailable - 50000000))
{
if (IncreaseStreamingMemoryLimit(128)) {
streamMemoryForced = CStreaming::ms_memoryAvailable;
if (logMode >= 0) {
lg << "Streaming memory automatically increased to " << streamMemoryForced << " after loading (margin).\n";
}
}
}
if (logMode >= 0) {
lg.flush();
}
CTimer::Update();
gameStartedAfterLoad = CTimer::m_snTimeInMilliseconds;
}
loadCheck = 4;
}
if (loadCheck == 4) {
if (removeUnusedWhenPercent > 0.0 ) {
float memUsedPercent = (float)((float)CStreaming::ms_memoryUsed / (float)CStreaming::ms_memoryAvailable) * 100.0f;
if (memUsedPercent >= removeUnusedWhenPercent) {
// If memory usage is near limit, decrease the remove interval
int removeUnusedIntervalMsTweaked = removeUnusedIntervalMs;
if (memUsedPercent > 95.0f && removeUnusedIntervalMsTweaked > 0) {
removeUnusedIntervalMsTweaked / 2;
}
if ((CTimer::m_snTimeInMilliseconds - lastTimeRemoveUnused) > removeUnusedIntervalMsTweaked) {
//CStreaming::RemoveAllUnusedModels();
CStreaming::RemoveLeastUsedModel(0);
//CStreaming::MakeSpaceFor(10000000);
//CMessages::AddMessageJumpQ((char*)"Clear", 500, false, false);
lastTimeRemoveUnused = CTimer::m_snTimeInMilliseconds;
}
}
}
}
};
}
static bool IncreaseStreamingMemoryLimit(unsigned int mb) {
unsigned int increaseBytes = mb *= MULT_MB_TO_BYTE;
unsigned int newLimit = CStreaming::ms_memoryAvailable + increaseBytes;
if (newLimit <= 0) return false;
if (newLimit >= MAX_BYTE_LIMIT) newLimit = MAX_BYTE_LIMIT;
CStreaming::ms_memoryAvailable = newLimit;
return true;
}
} loadWholeMap;
| 33.310881
| 181
| 0.595349
|
JuniorDjjr
|
e1eeec7f8af18ef409b8368a2ff6ff299158eb6b
| 3,973
|
hpp
|
C++
|
include/codegen/include/UnityEngine/Experimental/Rendering/GraphicsFormatUtility.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/UnityEngine/Experimental/Rendering/GraphicsFormatUtility.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/UnityEngine/Experimental/Rendering/GraphicsFormatUtility.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:33 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::Experimental::Rendering
namespace UnityEngine::Experimental::Rendering {
// Forward declaring type: GraphicsFormat
struct GraphicsFormat;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: TextureFormat
struct TextureFormat;
// Forward declaring type: RenderTextureFormat
struct RenderTextureFormat;
// Forward declaring type: RenderTextureReadWrite
struct RenderTextureReadWrite;
}
// Completed forward declares
// Type namespace: UnityEngine.Experimental.Rendering
namespace UnityEngine::Experimental::Rendering {
// Autogenerated type: UnityEngine.Experimental.Rendering.GraphicsFormatUtility
class GraphicsFormatUtility : public ::Il2CppObject {
public:
// static public UnityEngine.Experimental.Rendering.GraphicsFormat GetGraphicsFormat(UnityEngine.TextureFormat format, System.Boolean isSRGB)
// Offset: 0x12F0574
static UnityEngine::Experimental::Rendering::GraphicsFormat GetGraphicsFormat(UnityEngine::TextureFormat format, bool isSRGB);
// static private UnityEngine.Experimental.Rendering.GraphicsFormat GetGraphicsFormat_Native_TextureFormat(UnityEngine.TextureFormat format, System.Boolean isSRGB)
// Offset: 0x12F6C80
static UnityEngine::Experimental::Rendering::GraphicsFormat GetGraphicsFormat_Native_TextureFormat(UnityEngine::TextureFormat format, bool isSRGB);
// static public UnityEngine.Experimental.Rendering.GraphicsFormat GetGraphicsFormat(UnityEngine.RenderTextureFormat format, System.Boolean isSRGB)
// Offset: 0x12F6CD0
static UnityEngine::Experimental::Rendering::GraphicsFormat GetGraphicsFormat(UnityEngine::RenderTextureFormat format, bool isSRGB);
// static private UnityEngine.Experimental.Rendering.GraphicsFormat GetGraphicsFormat_Native_RenderTextureFormat(UnityEngine.RenderTextureFormat format, System.Boolean isSRGB)
// Offset: 0x12F6D20
static UnityEngine::Experimental::Rendering::GraphicsFormat GetGraphicsFormat_Native_RenderTextureFormat(UnityEngine::RenderTextureFormat format, bool isSRGB);
// static public UnityEngine.Experimental.Rendering.GraphicsFormat GetGraphicsFormat(UnityEngine.RenderTextureFormat format, UnityEngine.RenderTextureReadWrite readWrite)
// Offset: 0x12F6D70
static UnityEngine::Experimental::Rendering::GraphicsFormat GetGraphicsFormat(UnityEngine::RenderTextureFormat format, UnityEngine::RenderTextureReadWrite readWrite);
// static public System.Boolean IsSRGBFormat(UnityEngine.Experimental.Rendering.GraphicsFormat format)
// Offset: 0x12F6DE0
static bool IsSRGBFormat(UnityEngine::Experimental::Rendering::GraphicsFormat format);
// static public UnityEngine.RenderTextureFormat GetRenderTextureFormat(UnityEngine.Experimental.Rendering.GraphicsFormat format)
// Offset: 0x12F6E20
static UnityEngine::RenderTextureFormat GetRenderTextureFormat(UnityEngine::Experimental::Rendering::GraphicsFormat format);
// static System.Boolean IsCompressedTextureFormat(UnityEngine.TextureFormat format)
// Offset: 0x12F6E60
static bool IsCompressedTextureFormat(UnityEngine::TextureFormat format);
// static public System.Boolean IsCrunchFormat(UnityEngine.TextureFormat format)
// Offset: 0x12F05C4
static bool IsCrunchFormat(UnityEngine::TextureFormat format);
}; // UnityEngine.Experimental.Rendering.GraphicsFormatUtility
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Experimental::Rendering::GraphicsFormatUtility*, "UnityEngine.Experimental.Rendering", "GraphicsFormatUtility");
#pragma pack(pop)
| 62.078125
| 179
| 0.80292
|
Futuremappermydud
|
e1efba02058aabf69b39d61fa9354907dd77877f
| 8,022
|
cpp
|
C++
|
tests/utils/seed_index_merger.cpp
|
FreshDISKANN/FreshDISKANN
|
c7750ed7ae2df202b3f3a98477199963245c8ba7
|
[
"MIT"
] | 6
|
2020-10-13T11:30:53.000Z
|
2021-12-03T15:50:15.000Z
|
tests/utils/seed_index_merger.cpp
|
FreshDISKANN/FreshDISKANN
|
c7750ed7ae2df202b3f3a98477199963245c8ba7
|
[
"MIT"
] | null | null | null |
tests/utils/seed_index_merger.cpp
|
FreshDISKANN/FreshDISKANN
|
c7750ed7ae2df202b3f3a98477199963245c8ba7
|
[
"MIT"
] | 3
|
2020-10-13T11:30:55.000Z
|
2021-12-02T14:29:42.000Z
|
#include "utils.h"
#include <algorithm>
#include <cassert>
#include <random>
#include <thread>
#include <vector>
#include "tsl/robin_set.h"
#define ENTRY_POINT 52292725
//#define ENTRY_POINT 123742
template<typename T, typename TagT = uint32_t>
void dump_to_disk(const T *all_pts, const uint64_t ndims,
const std::string & filename,
const std::vector<uint32_t> &tags) {
T * new_data = new T[ndims * tags.size()];
TagT *new_tags = new TagT[tags.size()];
std::string tag_filename = filename + ".tags";
std::string data_filename = filename + ".data";
std::cout << "# points : " << tags.size() << "\n";
std::cout << "Tag file : " << tag_filename << "\n";
std::cout << "Data file : " << data_filename << "\n";
std::ofstream tag_writer(tag_filename);
for (uint64_t i = 0; i < tags.size(); i++) {
// tag_writer << tags[i] << std::endl;
*(new_tags + i) = tags[i];
memcpy(new_data + (i * ndims), all_pts + (tags[i] * ndims),
ndims * sizeof(float));
}
// tag_writer.close();
diskann::save_bin<TagT>(tag_filename, new_tags, tags.size(), 1);
diskann::save_bin<T>(data_filename, new_data, tags.size(), ndims);
delete new_data;
delete new_tags;
}
template<typename T>
void run(const uint32_t base_count, const uint32_t num_mem_indices,
const uint32_t delete_count, const uint32_t incr_count,
const uint32_t num_cycles, const std::string &in_file,
const std::string &out_prefix, const std::string &deleted_tags_file) {
// random number generator
std::random_device dev;
std::mt19937 rng(dev());
T * all_points = nullptr;
uint64_t npts, ndims;
diskann::load_bin(in_file, all_points, npts, ndims);
std::cout << "Loaded " << npts << " pts x " << ndims << " dims\n";
// assert(npts >= base_count + num_mem_indices);
std::vector<uint32_t> tags(npts);
std::iota(tags.begin(), tags.end(), 0);
std::cout << "Base Index : choosing " << base_count << " points\n";
std::vector<uint32_t> base_tags(tags.begin(), tags.begin() + base_count);
tsl::robin_set<uint32_t> active_tags;
tsl::robin_set<uint32_t> inactive_tags;
tsl::robin_set<uint32_t> new_active_tags;
tsl::robin_set<uint32_t> new_inactive_tags;
for (uint32_t i = 0; i < base_count; i++) {
active_tags.insert(i);
}
for (uint32_t i = base_count; i < npts; i++) {
inactive_tags.insert(i);
}
std::cout << "Dumping base set \n";
// write base
dump_to_disk(all_points, ndims, out_prefix + "_base", base_tags);
std::vector<uint32_t> delete_vec;
std::vector<uint32_t> insert_vec;
uint32_t count = 0;
while (count++ < num_cycles) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dis(0, 1);
new_active_tags.clear();
new_inactive_tags.clear();
delete_vec.clear();
insert_vec.clear();
float active_tags_sampling_rate = (float) ((std::min)(
(1.0 * delete_count) / (1.0 * active_tags.size()), 1.0));
for (auto iter = active_tags.begin(); iter != active_tags.end(); iter++) {
if (dis(gen) < active_tags_sampling_rate && *iter != ENTRY_POINT) {
delete_vec.emplace_back(*iter);
new_inactive_tags.insert(*iter);
} else
new_active_tags.insert(*iter);
}
float inactive_tags_sampling_rate = (float) ((std::min)(
(1.0 * incr_count) / (1.0 * inactive_tags.size()), 1.0));
for (auto iter = inactive_tags.begin(); iter != inactive_tags.end();
iter++) {
if (dis(gen) < inactive_tags_sampling_rate) {
insert_vec.emplace_back(*iter);
new_active_tags.insert(*iter);
} else
new_inactive_tags.insert(*iter);
}
std::cout << "Merge program will insert " << insert_vec.size()
<< " points and delete " << delete_vec.size()
<< " points in round " << count << std::endl;
active_tags.swap(new_active_tags);
inactive_tags.swap(new_inactive_tags);
// TODO (correct) :: enable shuffling tags for better randomness
// std::shuffle(tags.begin(), tags.end(), rng);
// split tags
const uint64_t mem_count =
ROUND_UP(insert_vec.size(), num_mem_indices) / num_mem_indices;
std::vector<std::vector<uint32_t>> mem_tags(num_mem_indices);
uint64_t cur_start = 0;
for (uint64_t i = 0; i < num_mem_indices; i++) {
std::vector<uint32_t> &ith_tags = mem_tags[i];
uint64_t new_start = std::min(cur_start + mem_count, insert_vec.size());
std::cout << "Index #" << i + 1 << " : choosing " << new_start - cur_start
<< " points\n";
ith_tags.insert(ith_tags.end(), insert_vec.begin() + cur_start,
insert_vec.begin() + new_start);
cur_start = new_start;
}
// write mem
for (uint64_t i = 0; i < num_mem_indices; i++) {
std::cout << "Dumping mem set #" << i + 1 << "\n";
dump_to_disk(all_points, ndims,
out_prefix + "_cycle_" + std::to_string(count) + "_mem_" +
std::to_string(i + 1),
mem_tags[i]);
}
// re-shuffle tags to get delete list
// std::shuffle(tags.begin(), tags.end(), rng);
std::ofstream deleted_tags_writer(deleted_tags_file + "_cycle_" +
std::to_string(count));
for (uint64_t i = 0; i < delete_vec.size(); i++) {
deleted_tags_writer << delete_vec[i] << std::endl;
}
deleted_tags_writer.close();
// add remaining tags to final list
// std::vector<uint64_t> rem_tags(tags.begin() + delete_count, tags.end());
// std::sort(rem_tags.begin(), rem_tags.end());
// write mem
// std::cout << "Dumping {all} \\ {deleted} set\n";
// dump_to_disk(all_points, ndims, out_prefix + "_oneshot", rem_tags);
}
// free all points
delete all_points;
}
int main(int argc, char **argv) {
if (argc != 10) {
std::cout << "Correct usage: " << argv[0]
<< " <type[int8/uint8/float]> <base_count> <num_mem_indices>"
<< " <delete_count> <incr count> <num_cycles> <in_file> "
"<out_prefix> <deleted_tags_file>"
<< std::endl;
exit(-1);
}
std::cout.setf(std::ios::unitbuf);
int arg_no = 1;
std::string index_type = argv[arg_no++];
const uint32_t base_count = std::atoi(argv[arg_no++]);
std::cout << "# base points : " << base_count << "\n";
const uint32_t num_mem_indices = std::atoi(argv[arg_no++]);
std::cout << "# mem indices : " << num_mem_indices << "\n";
const uint32_t delete_count = std::atoi(argv[arg_no++]);
std::cout << "# deleted tags per cycle : " << delete_count << "\n";
const uint32_t incr_count = std::atoi(argv[arg_no++]);
std::cout << "# inserted tags per cycle : " << incr_count << "\n";
const uint32_t num_cycles = std::atoi(argv[arg_no++]);
std::cout << "# cycles : " << num_cycles << "\n";
const std::string in_file = argv[arg_no++];
std::cout << "In file : " << in_file << "\n";
const std::string out_prefix = argv[arg_no++];
std::cout << "Out prefix : " << out_prefix << "\n";
const std::string deleted_tags_file = argv[arg_no++];
std::cout << "Deleted tags file prefix : " << deleted_tags_file << "\n";
if (index_type == std::string("float")) {
run<float>(base_count, num_mem_indices, delete_count, incr_count,
num_cycles, in_file, out_prefix, deleted_tags_file);
} else if (index_type == std::string("uint8")) {
run<uint8_t>(base_count, num_mem_indices, delete_count, incr_count,
num_cycles, in_file, out_prefix, deleted_tags_file);
} else if (index_type == std::string("int8")) {
run<int8_t>(base_count, num_mem_indices, delete_count, incr_count,
num_cycles, in_file, out_prefix, deleted_tags_file);
} else {
std::cout << "Unsupported type : " << index_type << "\n";
}
std::cout << "Exiting\n";
}
| 37.138889
| 80
| 0.605211
|
FreshDISKANN
|
e1f19e4865980a315248e15d6c3bc644ddc95046
| 5,088
|
cpp
|
C++
|
Game/Cards/Trap/WidespreadRuin.cpp
|
CrusaderCrab/YugiohPhantomRealm
|
79bd1e9948d2d2d29acf042fd412804c30562a8e
|
[
"Zlib"
] | 13
|
2018-04-13T22:10:00.000Z
|
2022-01-01T08:26:23.000Z
|
Game/Cards/Trap/WidespreadRuin.cpp
|
CrusaderCrab/YugiohPhantomRealm
|
79bd1e9948d2d2d29acf042fd412804c30562a8e
|
[
"Zlib"
] | null | null | null |
Game/Cards/Trap/WidespreadRuin.cpp
|
CrusaderCrab/YugiohPhantomRealm
|
79bd1e9948d2d2d29acf042fd412804c30562a8e
|
[
"Zlib"
] | 3
|
2017-02-22T16:35:06.000Z
|
2019-12-21T20:39:23.000Z
|
#include <Game\Cards\Trap\WidespreadRuin.h>
#include <Game\Cards\Trap\TrapUnit.h>
#include <Game\Animation\FadeUnit.h>
#include <Game\Duel\Board.h>
#include <Game\VectorUnit.h>
#include <Game\Animation\MovementUnit.h>
#include <Utility\SoundUnit.h>
#include <Game\Animation\ParticlesUnit.h>
#include <Game\Cards\CardCreatorUnit.h>
#include <iostream>
#define ZYUG_IDLE 0
#define ZYUG_START 1
#define ZYUG_FADEIN 2
#define ZYUG_BURNUP 3
#define ZYUG_FADECARD 4
#define ZYUG_FADEOUT 5
#define ZYUG_RETURN 6
#define ZYUG_END 7
#define ZYUG_X_OFF 1.5f
namespace Card{
void WidespreadRuin::startup(){
Game::WaitUnit::startup();
renderingFade = false;
chain = ZYUG_START;
attackCard = &(theBoard.board[theBoard.aP[0]][theBoard.aP[1]]);
attackCard->bigRender.startup();
defender = &(theBoard.board[trapUnit.cardCol][trapUnit.cardRow]);
defender->bigRender.startup();
setupBigCards();
hasCards = true;
}
void WidespreadRuin::setupBigCards(){
attackCard->bigRender.ignoreCamera = true;
attackCard->bigRender.scale = pos.batBigCardScale;
attackCard->bigRender.position = mov.addXOffset(pos.batBigCardPos, -ZYUG_X_OFF);
attackCard->bigRender.doRender = true;
attackCard->bigRender.raiseStat = false;
attackCard->bigRender.emphasis(YUG_BIG_CARD_EMPHASIS_BOTH);
attackCard->bigRender.rotationMatrix = glm::mat4();
defender->bigRender.ignoreCamera = true;
defender->bigRender.scale = pos.batBigCardScale;
defender->bigRender.position = mov.addXOffset(pos.batBigCardPos, pos.batBigCardXOffset + ZYUG_X_OFF);
defender->bigRender.doRender = true;
defender->bigRender.raiseStat = false;
defender->bigRender.emphasis(YUG_BIG_CARD_EMPHASIS_BOTH);
defender->bigRender.rotationMatrix = glm::mat4();
}
void WidespreadRuin::cleanup(){
}
void WidespreadRuin::update(){
if(hasCards){
attackCard->bigRender.update();
defender->bigRender.update();
}
if(!isWaiting){
switch(chain){
case ZYUG_START:
startUpdate();
break;
case ZYUG_FADEIN:
fadeInUpdate();
break;
case ZYUG_BURNUP:
burnUpdate();
break;
case ZYUG_FADECARD:
fadeCardUpdate();
break;
case ZYUG_FADEOUT:
fadeOutUpdate();
break;
case ZYUG_RETURN:
returnUpdate();
break;
case ZYUG_END:
endUpdate();
break;
default:
break;
}
}else{
continueWaiting();
}
}
void WidespreadRuin::render(){
if(renderingFade){
fadeUnit.render(YUG_FADE_LOCAL);
}
if(hasCards){
attackCard->bigRender.render();
defender->bigRender.render();
}
}
void WidespreadRuin::startUpdate(){
theBoard.trapBeforeParticles = true;
theBoard.currentPlayerView(pos.wait[2]);
theBoard.LP.hide();
theBoard.field.hide();
fadeUnit.renderBlock = true;
renderingFade = true;
chain = ZYUG_FADEIN;
wait(0.3f);
}
void WidespreadRuin::fadeInUpdate(){
fadeUnit.changeZ(pos.nc_z[5]-0.001f);
fadeUnit.sheet.amtran = glm::vec4(0.001f,0.0f,0.0f,0.0f);
fadeUnit.fadeTo(YUG_FADE_BLACK, pos.wait[5]);
attackCard->bigRender.interpolate(pos.batBigCardPos, 0.5f);
defender->bigRender.interpolate(mov.addXOffset(pos.batBigCardPos,pos.batBigCardXOffset),0.5f);
chain = ZYUG_BURNUP;
wait(0.7f);
}
void WidespreadRuin::burnUpdate(){
particleUnit.swapFlames();
particleUnit.particleAmtran = glm::vec4(0.5f,0.1f,0.9f,1.0f);
glm::vec3 posi = mov.addZOffset(attackCard->bigRender.position, 0.025f);
soundUnit.playOnce("GameData/sounds/battle/CardBurnup02.wav");
particleUnit.burnup(
YUG_PARTICLE_BURN_MON,
mov.addYOffset(posi, -0.2f),
0.27f, 0.45f, 0.6f);
chain = ZYUG_FADECARD;
wait(0.57f);
}
void WidespreadRuin::fadeCardUpdate(){
attackCard->bigRender.doRender = false;
defender->bigRender.amtran = glm::vec4(1.0f,1.0f,1.0f,1.0f);
defender->bigRender.interpolateAmtran(glm::vec4(1.0f,1.0f,1.0f,0.0f),0.3f);
chain = ZYUG_FADEOUT;
wait(0.3f);
theBoard.cP[0] = theBoard.aP[0];
theBoard.cP[1] = theBoard.aP[1];
theBoard.lockRowMovement = false;
theBoard.battleCursor.turnon();
theBoard.currentPlayer->toBoardView();
theBoard.underlay.viewingBoard();
}
void WidespreadRuin::fadeOutUpdate(){
particleUnit.swapFlames();
attackCard->smallRender.cleanup();
attackCard->bigRender.cleanup();
attackCard->cleanup();
theBoard.board[theBoard.aP[0]][theBoard.aP[1]] = cardCreator.blankCard();
defender->bigRender.cleanup();
hasCards = false;
renderingFade = false;
fadeUnit.renderBlock = false;
fadeUnit.fadeTo(YUG_FADE_CLEAR,0.2f);
chain = ZYUG_RETURN;
wait(0.2f);
}
void WidespreadRuin::returnUpdate(){
theBoard.LP.reveal();
theBoard.field.reveal();
theBoard.lockRowMovement = false;
chain = ZYUG_IDLE;
trapUnit.magicEnd = false;
theBoard.trapBeforeParticles = false;
trapUnit.chain = YUG_TRAP_CH_SPECIFIC_END;
}
void WidespreadRuin::endUpdate(){
}
bool WidespreadRuin::listen(int info){
if(info == YUG_TRAP_ATTACK){
return true;
}
return false;
}
}
| 27.208556
| 104
| 0.700079
|
CrusaderCrab
|
e1f349badd9cd232744e4f42e3f7982c3afeb495
| 2,522
|
cpp
|
C++
|
test/path_mutex_test.cpp
|
taylorb-microsoft/winss
|
ede93f84a5d9585502db5190f2ec6365858f695a
|
[
"Apache-2.0"
] | 52
|
2017-01-05T23:39:38.000Z
|
2020-06-04T03:00:11.000Z
|
test/path_mutex_test.cpp
|
morganstanley/winss
|
ede93f84a5d9585502db5190f2ec6365858f695a
|
[
"Apache-2.0"
] | 24
|
2017-01-05T05:07:34.000Z
|
2018-03-09T00:50:58.000Z
|
test/path_mutex_test.cpp
|
morganstanley/winss
|
ede93f84a5d9585502db5190f2ec6365858f695a
|
[
"Apache-2.0"
] | 7
|
2016-12-27T20:55:20.000Z
|
2018-03-09T00:32:19.000Z
|
/*
* Copyright 2016-2017 Morgan Stanley
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <thread>
#include <functional>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "winss/winss.hpp"
#include "winss/path_mutex.hpp"
#include "mock_interface.hpp"
#include "mock_windows_interface.hpp"
using ::testing::_;
using ::testing::NiceMock;
namespace winss {
class PathMutexTest : public testing::Test {
};
TEST_F(PathMutexTest, Name) {
winss::PathMutex mutex1("does_not_exit", "");
winss::PathMutex mutex2("does_not_exit", "test1");
EXPECT_EQ(0, mutex1.GetName().find("Global\\"));
EXPECT_EQ(std::string::npos, mutex1.GetName().find("_"));
EXPECT_NE(std::string::npos, mutex2.GetName().find("_test1"));
}
TEST_F(PathMutexTest, Lock) {
MockInterface<winss::MockWindowsInterface> windows;
windows->SetupDefaults();
EXPECT_CALL(*windows, ReleaseMutex(_)).Times(1);
EXPECT_CALL(*windows, CloseHandle(_)).Times(1);
winss::PathMutex mutex("does_not_exit", "test2");
EXPECT_TRUE(mutex.CanLock());
EXPECT_FALSE(mutex.HasLock());
EXPECT_TRUE(mutex.Lock());
EXPECT_TRUE(mutex.HasLock());
EXPECT_TRUE(mutex.Lock());
EXPECT_TRUE(mutex.HasLock());
EXPECT_TRUE(mutex.CanLock());
}
TEST_F(PathMutexTest, MutlipleInstances) {
MockInterface<winss::MockWindowsInterface> windows;
windows->SetupDefaults();
EXPECT_CALL(*windows, ReleaseMutex(_)).Times(1);
EXPECT_CALL(*windows, CloseHandle(_)).Times(2);
winss::PathMutex mutex1("does_not_exit", "test3");
winss::PathMutex mutex2("does_not_exit", "test3");
EXPECT_TRUE(mutex1.CanLock());
EXPECT_TRUE(mutex2.CanLock());
EXPECT_FALSE(mutex1.HasLock());
EXPECT_FALSE(mutex2.HasLock());
auto set = [](winss::PathMutex* mutex) {
mutex->Lock();
};
std::thread mt1(set, &mutex1);
std::thread mt2(set, &mutex2);
mt1.join();
mt2.join();
EXPECT_NE(mutex1.HasLock(), mutex2.HasLock());
}
} // namespace winss
| 28.022222
| 74
| 0.698652
|
taylorb-microsoft
|
e1f58969e994a7fe9eb671b094d4a74b760c050c
| 3,776
|
cpp
|
C++
|
cell_based/src/cell/cycle/AbstractCellCycleModel.cpp
|
DGermano8/ChasteDom
|
539a3a811698214c0938489b0cfdffd1abccf667
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
cell_based/src/cell/cycle/AbstractCellCycleModel.cpp
|
DGermano8/ChasteDom
|
539a3a811698214c0938489b0cfdffd1abccf667
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
cell_based/src/cell/cycle/AbstractCellCycleModel.cpp
|
DGermano8/ChasteDom
|
539a3a811698214c0938489b0cfdffd1abccf667
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2005-2018, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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 "AbstractCellCycleModel.hpp"
AbstractCellCycleModel::AbstractCellCycleModel()
: mBirthTime(SimulationTime::Instance()->GetTime()),
mReadyToDivide(false),
mDimension(UNSIGNED_UNSET)
{
}
AbstractCellCycleModel::~AbstractCellCycleModel()
{
}
AbstractCellCycleModel::AbstractCellCycleModel(const AbstractCellCycleModel& rModel)
: mBirthTime(rModel.mBirthTime),
mReadyToDivide(rModel.mReadyToDivide),
mDimension(rModel.mDimension)
{
}
void AbstractCellCycleModel::Initialise()
{
}
void AbstractCellCycleModel::InitialiseDaughterCell()
{
}
void AbstractCellCycleModel::SetCell(CellPtr pCell)
{
mpCell = pCell;
}
CellPtr AbstractCellCycleModel::GetCell()
{
assert(mpCell != nullptr);
return mpCell;
}
void AbstractCellCycleModel::SetBirthTime(double birthTime)
{
mBirthTime = birthTime;
}
double AbstractCellCycleModel::GetBirthTime() const
{
return mBirthTime;
}
double AbstractCellCycleModel::GetAge()
{
return SimulationTime::Instance()->GetTime() - mBirthTime;
}
void AbstractCellCycleModel::ResetForDivision()
{
assert(mReadyToDivide);
mReadyToDivide = false;
mBirthTime = SimulationTime::Instance()->GetTime();
}
void AbstractCellCycleModel::SetDimension(unsigned dimension)
{
if (dimension != 1 && dimension !=2 && dimension != 3 && dimension != UNSIGNED_UNSET)
{
EXCEPTION("Dimension must be 1, 2, 3 or UNSIGNED_UNSET");
}
mDimension = dimension;
}
unsigned AbstractCellCycleModel::GetDimension() const
{
return mDimension;
}
bool AbstractCellCycleModel::CanCellTerminallyDifferentiate()
{
return true;
}
void AbstractCellCycleModel::OutputCellCycleModelInfo(out_stream& rParamsFile)
{
std::string cell_cycle_model_type = GetIdentifier();
*rParamsFile << "\t\t<" << cell_cycle_model_type << ">\n";
OutputCellCycleModelParameters(rParamsFile);
*rParamsFile << "\t\t</" << cell_cycle_model_type << ">\n";
}
void AbstractCellCycleModel::OutputCellCycleModelParameters(out_stream& rParamsFile)
{
// None to output
}
| 29.271318
| 89
| 0.768273
|
DGermano8
|
e1f7b3dcccd0b0c064ff83a57a79b62754165240
| 486
|
hpp
|
C++
|
include/generic/projection/projection_plane_3.hpp
|
shikanle/gfx
|
772db3ddd66c294beaf17319f6b3803abe3ce0df
|
[
"Apache-2.0"
] | 4
|
2022-01-06T14:06:03.000Z
|
2022-01-07T01:13:58.000Z
|
include/generic/projection/projection_plane_3.hpp
|
shikanle/gfx
|
772db3ddd66c294beaf17319f6b3803abe3ce0df
|
[
"Apache-2.0"
] | null | null | null |
include/generic/projection/projection_plane_3.hpp
|
shikanle/gfx
|
772db3ddd66c294beaf17319f6b3803abe3ce0df
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "projection.hpp"
#include "../../geometry/plane_3.hpp"
template <typename float_system>
class projection_plane_3 : public projection<plane_3<float_system> > {
public:
declare_projection_types(plane_3);
public:
virtual bool project(const vector_t &p, domain_value_t &result) override {
auto v = p - this->geometry->center;
result.x = this->geometry->axis_x * v;
result.y = this->geometry->axis_y * v;
return true;
}
};
| 27
| 78
| 0.679012
|
shikanle
|
e1f9b9ed8709db0305345e1640379457783823b8
| 641
|
hpp
|
C++
|
src/3rdPartyLibraries/UPR/examples/cuda/test-cuda-runtime.hpp
|
goliat90/edg4x-rose
|
75984d718a5235fb1433e7cab1991ade8d44f9ac
|
[
"BSD-3-Clause"
] | 4
|
2015-03-17T13:52:21.000Z
|
2022-01-12T05:32:47.000Z
|
src/3rdPartyLibraries/UPR/examples/cuda/test-cuda-runtime.hpp
|
goliat90/edg4x-rose
|
75984d718a5235fb1433e7cab1991ade8d44f9ac
|
[
"BSD-3-Clause"
] | null | null | null |
src/3rdPartyLibraries/UPR/examples/cuda/test-cuda-runtime.hpp
|
goliat90/edg4x-rose
|
75984d718a5235fb1433e7cab1991ade8d44f9ac
|
[
"BSD-3-Clause"
] | 2
|
2019-02-19T01:27:51.000Z
|
2019-02-19T12:29:49.000Z
|
/**
* /author Tristan Vanderbruggen (vanderbruggentristan@gmail.com)
* /date 08/2012
*/
#ifndef __TEST_CUDA_RUNTIME_HPP__
#define __TEST_CUDA_RUNTIME_HPP__
#include "UPR/cuda-runtime.hpp"
namespace UPR {
class Task_1 : public CUDA_ExecTask {
// TODO
};
class App_CUDA_Scheduler : public CUDA_Scheduler {
protected:
virtual void init();
public:
App_CUDA_Scheduler(unsigned long n);
virtual ~App_CUDA_Scheduler();
virtual void print(std::ostream&) const;
static Task * build_task_1(Executor * executor, unsigned i, unsigned j, Data * a, Data * b, Data * r);
};
}
#endif /* __TEST_CUDA_RUNTIME_HPP__ */
| 19.424242
| 106
| 0.712949
|
goliat90
|
c0033911c819dc28049fb7768735dac6f0712f1e
| 1,485
|
cpp
|
C++
|
examples/cppcon_2020/07_oneTBB_observers/solutions/observer-solved.cpp
|
alvdd/oneTBB
|
d87e076d530007b48f619b2f58b53fb0d1a173b1
|
[
"Apache-2.0"
] | null | null | null |
examples/cppcon_2020/07_oneTBB_observers/solutions/observer-solved.cpp
|
alvdd/oneTBB
|
d87e076d530007b48f619b2f58b53fb0d1a173b1
|
[
"Apache-2.0"
] | null | null | null |
examples/cppcon_2020/07_oneTBB_observers/solutions/observer-solved.cpp
|
alvdd/oneTBB
|
d87e076d530007b48f619b2f58b53fb0d1a173b1
|
[
"Apache-2.0"
] | null | null | null |
//==============================================================
// Copyright (c) 2020 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
// =============================================================
#include <exception>
#include <iostream>
#include <tbb/tbb.h>
#define INCORRECT_VALUE -1
thread_local int my_tid = INCORRECT_VALUE;
class tid_observer : public tbb::task_scheduler_observer {
public:
tid_observer(tbb::task_arena &a) : tbb::task_scheduler_observer{a} { observe(true); }
void on_scheduler_entry( bool is_worker ) override {
// STEP 3.A: replace the INCORRECT_VALUE with a call to tbb::this_task_arena::current_thread_index()
my_tid = tbb::this_task_arena::current_thread_index();
}
};
int main() {
tbb::task_arena a;
// STEP 3.B: construct a tid_observer, passing "a" to the constructor
tid_observer to(a);
try {
a.execute([]() {
tbb::parallel_for(0, 1000000, [](int i) {
const int time_per_iteration = 1000; // 1 us
auto t0 = std::chrono::high_resolution_clock::now();
while ((std::chrono::high_resolution_clock::now() - t0).count() < time_per_iteration);
if (my_tid == -1 || my_tid != tbb::this_task_arena::current_thread_index()) {
std::cout << "my_tid not set correctly on entry!\n";
throw std::exception{};
}
});
});
} catch (...) {
std::cout << "Did not complete loop.\n";
return 1;
}
std::cout << "Completed loop.\n";
return 0;
}
| 32.282609
| 104
| 0.593266
|
alvdd
|
c0040656c30f694cb15c50eb3cd408fb7809b20e
| 881
|
cpp
|
C++
|
spoj/BYTESM2.cpp
|
amitdu6ey/Online-Judge-Submissions
|
9585aec29228211454bca5cf1d5738f49fb0aa8f
|
[
"MIT"
] | 5
|
2020-06-30T12:44:25.000Z
|
2021-07-14T06:35:57.000Z
|
spoj/BYTESM2.cpp
|
amitdu6ey/Online-Judge-Submissions
|
9585aec29228211454bca5cf1d5738f49fb0aa8f
|
[
"MIT"
] | null | null | null |
spoj/BYTESM2.cpp
|
amitdu6ey/Online-Judge-Submissions
|
9585aec29228211454bca5cf1d5738f49fb0aa8f
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int a[109][109];
int dp[109][109];
void solve(){
int h,w;
cin>>h>>w;
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
cin>>a[i][j];
}
}
for(int i=0;i<w;i++){
dp[h-1][i]=a[h-1][i];
}
for(int i=h-2;i>=0;i--){
for(int j=0;j<w;j++){
int max_coins=0;
for(int k=max(0,j-1);k<=min(w-1,j+1);k++){
max_coins = max(max_coins,dp[i+1][k]);
}
dp[i][j]=a[i][j]+max_coins;
}
}
int ans=0;
for(int i=0;i<w;i++){
//cout<<dp[0][i]<<", ";
ans = max(ans, dp[0][i]);
}
cout<<ans<<endl;
return;
}
int main(){
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
int test=1;
cin>>test;
while(test--){
solve();
}
return 0;
}
| 18.744681
| 54
| 0.413167
|
amitdu6ey
|
c009cf175467d3020cb951d3654dec31412ad5f6
| 382
|
hpp
|
C++
|
res_mgr/res_config.hpp
|
dennisding/thread_work
|
f425255d0fcb54e1839211416d760bde5a69a9b6
|
[
"MIT"
] | null | null | null |
res_mgr/res_config.hpp
|
dennisding/thread_work
|
f425255d0fcb54e1839211416d760bde5a69a9b6
|
[
"MIT"
] | null | null | null |
res_mgr/res_config.hpp
|
dennisding/thread_work
|
f425255d0fcb54e1839211416d760bde5a69a9b6
|
[
"MIT"
] | null | null | null |
#pragma once
//#include <string>
//#include <memory>
//
//template <typename type>
//struct res_info
//{
//};
//
////template <typename type>
////struct res_type
////{
////
////};
//
//class res_type
//{
//public:
// virtual ~res_type() {}
//
// virtual int as_int() = 0;
// virtual std::string as_string() = 0;
//};
//
//template <typename type>
//struct res_type_info
//{
//
//};
| 12.733333
| 39
| 0.575916
|
dennisding
|
c00c5eed4a89b0ac6d81413374c2b50df823759a
| 5,047
|
cpp
|
C++
|
Hollow_Faith/Motor2D/j1Collision.cpp
|
juanha2/PlatformerGame
|
f95af3cb237ff8fcb59f16f58598ca0a94cf9f1c
|
[
"Unlicense"
] | 4
|
2019-10-27T16:47:13.000Z
|
2020-03-16T17:02:36.000Z
|
Hollow_Faith/Motor2D/j1Collision.cpp
|
juanha2/PlatformerGame
|
f95af3cb237ff8fcb59f16f58598ca0a94cf9f1c
|
[
"Unlicense"
] | null | null | null |
Hollow_Faith/Motor2D/j1Collision.cpp
|
juanha2/PlatformerGame
|
f95af3cb237ff8fcb59f16f58598ca0a94cf9f1c
|
[
"Unlicense"
] | 8
|
2019-12-19T15:16:50.000Z
|
2020-06-14T22:12:33.000Z
|
#include "j1App.h"
#include "j1Render.h"
#include "j1Input.h"
#include "j1Collision.h"
#include "j1Player.h"
#include "j1Scene.h"
#include "p2Log.h"
j1Collision::j1Collision()
{
name.create("colliders");
for (uint i = 0; i < MAX_COLLIDERS; ++i)
colliders[i] = nullptr;
matrix[COLLIDER_PLAYER][COLLIDER_FLOOR] = true;
matrix[COLLIDER_PLAYER][COLLIDER_PLAYER] = false;
matrix[COLLIDER_PLAYER][COLLIDER_CLIMB] = true;
matrix[COLLIDER_PLAYER][COLLIDER_DEATH] = true;
matrix[COLLIDER_PLAYER][COLLIDER_WIN] = true;
matrix[COLLIDER_PLAYER][COLLIDER_NONE] = true;
matrix[COLLIDER_PLAYER][COLLIDER_PLATFORM] = true;
matrix[COLLIDER_PLAYER][COLLIDER_COINS] = true;
matrix[COLLIDER_PLAYER][COLLIDER_ENEMY] = true;
matrix[COLLIDER_PLAYER][COLLIDER_BONFIRE] = true;
matrix[COLLIDER_ENEMY][COLLIDER_ENEMY] = false;
matrix[COLLIDER_ENEMY][COLLIDER_STONE] = true;
matrix[COLLIDER_STONE][COLLIDER_FLOOR] = true;
matrix[COLLIDER_STONE][COLLIDER_ENEMY] = true;
matrix[COLLIDER_COINS][COLLIDER_PLAYER] = true;
matrix[COLLIDER_ENEMY][COLLIDER_FLOOR] = true;
matrix[COLLIDER_ENEMY][COLLIDER_PLAYER] = false;
matrix[COLLIDER_ENEMY][COLLIDER_NONE] = true;
matrix[COLLIDER_ENEMY][COLLIDER_PLATFORM] = true;
matrix[COLLIDER_ENEMY][COLLIDER_DEATH] = true;
matrix[COLLIDER_BONFIRE][COLLIDER_PLAYER] = true;
}
// Destructor
j1Collision::~j1Collision()
{}
bool j1Collision::PreUpdate()
{
BROFILER_CATEGORY("Collisions_PreUpdate", Profiler::Color::SandyBrown);
// Remove all colliders scheduled for deletion
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
if (colliders[i] != nullptr && colliders[i]->to_delete == true)
{
delete colliders[i];
colliders[i] = nullptr;
}
}
return true;
}
// Called before render is available
bool j1Collision::Update(float dt)
{
BROFILER_CATEGORY("Collisions_Update", Profiler::Color::Brown);
// Calculate collisions
Collider* c1;
Collider* c2;
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
// skip empty colliders
if (colliders[i] == nullptr)
continue;
c1 = colliders[i];
// avoid checking collisions already checked
for (uint k = i + 1; k < MAX_COLLIDERS; ++k)
{
// skip empty colliders
if (colliders[k] == nullptr)
continue;
c2 = colliders[k];
if (c1->CheckCollision(c2->rect) == true)
{
if (matrix[c1->type][c2->type] && c1->callback)
c1->callback->OnCollision(c1, c2);
if (matrix[c2->type][c1->type] && c2->callback)
c2->callback->OnCollision(c2, c1);
}
}
}
return true;
}
bool j1Collision::PostUpdate()
{
BROFILER_CATEGORY("Collisions_PostUpdate", Profiler::Color::SaddleBrown);
DebugDraw();
return true;
}
void j1Collision::DebugDraw()
{
if (App->scene->debug == false)
return;
Uint8 alpha = 80;
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
if (colliders[i] == nullptr)
continue;
switch (colliders[i]->type)
{
case COLLIDER_NONE: // white
App->render->DrawQuad(colliders[i]->rect, 255, 255, 255, alpha);
break;
case COLLIDER_FLOOR: // blue
App->render->DrawQuad(colliders[i]->rect, 0, 0, 255, alpha);
break;
case COLLIDER_PLAYER: // green
App->render->DrawQuad(colliders[i]->rect, 0, 255, 0, alpha);
break;
case COLLIDER_PLATFORM: // white
App->render->DrawQuad(colliders[i]->rect, 255, 0, 255, alpha);
break;
case COLLIDER_CLIMB: // white
App->render->DrawQuad(colliders[i]->rect, 100, 0, 100, alpha);
break;
case COLLIDER_DEATH: // white
App->render->DrawQuad(colliders[i]->rect, 0, 109, 109,alpha);
break;
case COLLIDER_WIN: // white
App->render->DrawQuad(colliders[i]->rect, 255, 0, 0, alpha);
break;
case COLLIDER_ENEMY:
App->render->DrawQuad(colliders[i]->rect, 255, 0, 0, alpha);
break;
case COLLIDER_STONE:
App->render->DrawQuad(colliders[i]->rect, 255, 255, 0, alpha);
break;
case COLLIDER_BONFIRE:
App->render->DrawQuad(colliders[i]->rect, 255, 255, 0, alpha);
break;
case COLLIDER_COINS:
App->render->DrawQuad(colliders[i]->rect, 255, 0, 0, alpha);
break;
}
}
}
// Called before quitting
bool j1Collision::CleanUp()
{
// Limpiando todos los Colliders
LOG("Freeing all colliders");
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
if (colliders[i] != nullptr)
{
delete colliders[i];
colliders[i] = nullptr;
}
}
return true;
}
Collider* j1Collision::AddCollider(SDL_Rect rect, COLLIDER_TYPE type, j1Entity* callback)
{
Collider* ret = nullptr;
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
if (colliders[i] == nullptr)
{
ret = colliders[i] = new Collider(rect, type, callback);
break;
}
}
return ret;
}
void j1Collision::AddColliderEntity(Collider* collider)
{
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
if (colliders[i] == nullptr)
{
colliders[i] = collider;
break;
}
}
}
// -----------------------------------------------------
bool Collider::CheckCollision(const SDL_Rect& r) const
{
return !((this->rect.x + this->rect.w < r.x || r.x + r.w < this->rect.x) || (this->rect.y + this->rect.h < r.y || r.y + r.h < this->rect.y));
}
| 22.53125
| 142
| 0.665742
|
juanha2
|
c00cdad2ed35d8e3227a8d503a44f189ea4d4d6b
| 571
|
cpp
|
C++
|
algo/pattern/pattern3.cpp
|
iarjunphp/CPP-Learning
|
4946f861cb3f57da2b0beba07a206fafe261aaf4
|
[
"MIT"
] | 77
|
2019-10-28T05:38:51.000Z
|
2022-03-15T01:53:48.000Z
|
algo/pattern/pattern3.cpp
|
iarjunphp/CPP-Learning
|
4946f861cb3f57da2b0beba07a206fafe261aaf4
|
[
"MIT"
] | 3
|
2019-12-26T15:39:55.000Z
|
2020-10-29T14:55:50.000Z
|
algo/pattern/pattern3.cpp
|
iarjunphp/CPP-Learning
|
4946f861cb3f57da2b0beba07a206fafe261aaf4
|
[
"MIT"
] | 24
|
2020-01-08T04:12:52.000Z
|
2022-03-12T22:26:07.000Z
|
#include<iostream>
using namespace std;
int main(){
int n;
cout<<"Enter number of cols"<<endl;
cin>>n;
for(int i=1,k=0;i<=n;i++,k=0){
for(int j=1;j<=(n-i);j++){
cout<<" ";
}
while (k!=(2*i)-1)
{
cout<<"*";
k++;
}
cout<<endl;
}
for(int i=n-1,k=0;i>=1;i--,k=0){
for(int j=1;j<=(n-i);j++){
cout<<" ";
}
while (k!=(2*i)-1)
{
cout<<"*";
k++;
}
cout<<endl;
}
}
| 15.026316
| 39
| 0.313485
|
iarjunphp
|
c00e94d2f212fcf06311e4be28ab537c44a5616d
| 1,219
|
cpp
|
C++
|
nd-coursework/books/cpp/C++17/lib/charconv.cpp
|
crdrisko/nd-grad
|
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
|
[
"MIT"
] | 1
|
2020-09-26T12:38:55.000Z
|
2020-09-26T12:38:55.000Z
|
nd-coursework/books/cpp/C++17/lib/charconv.cpp
|
crdrisko/nd-research
|
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
|
[
"MIT"
] | null | null | null |
nd-coursework/books/cpp/C++17/lib/charconv.cpp
|
crdrisko/nd-research
|
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2017 by Nicolai Josuttis. All rights reserved.
// Licensed under the CCA-4.0 International License. See the LICENSE file in the project root for more information.
//
// Name: charconv.cpp
// Author: crdrisko
// Date: 11/01/2020-11:41:04
// Description: Using to_chars and from_chars to show that the round-trip always results in the same initial value
#include "charconv.hpp"
#include <functional>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
int main()
{
std::vector<double> coll {0.1, 0.3, 0.00001};
// create two slightly different floating-point values:
auto sum1 = std::accumulate(coll.begin(), coll.end(), 0.0, std::plus<>());
auto sum2 = std::accumulate(coll.rbegin(), coll.rend(), 0.0, std::plus<>());
// look the same:
std::cout << "sum1: " << sum1 << '\n';
std::cout << "sum2: " << sum2 << '\n';
// but are different:
std::cout << std::boolalpha << std::setprecision(20);
std::cout << "equal: " << (sum1 == sum2) << '\n'; // false !!
std::cout << "sum1: " << sum1 << '\n';
std::cout << "sum2: " << sum2 << '\n';
std::cout << '\n';
// check round-trip:
d2str2d(sum1);
d2str2d(sum2);
}
| 30.475
| 115
| 0.608696
|
crdrisko
|
c011343c789081a0bf6919a778c2855129ea91f3
| 1,070
|
cpp
|
C++
|
C++/32_C++ClassTemplateSpecialization.cpp
|
BurningTiles/HackerRank
|
1af475bc64b1bf27ab5058230d6e472314679b61
|
[
"MIT"
] | 2
|
2020-11-04T10:12:24.000Z
|
2020-12-05T14:16:28.000Z
|
C++/32_C++ClassTemplateSpecialization.cpp
|
BurningTiles/HackerRank
|
1af475bc64b1bf27ab5058230d6e472314679b61
|
[
"MIT"
] | null | null | null |
C++/32_C++ClassTemplateSpecialization.cpp
|
BurningTiles/HackerRank
|
1af475bc64b1bf27ab5058230d6e472314679b61
|
[
"MIT"
] | null | null | null |
/**
* Author : BurningTiles
* Created : 2020-09-11 16:24:20
* Link : GitHub.com/BurningTiles
* Program : C++ Class Template Specialization
**/
#include <bits/stdc++.h>
using namespace std;
enum class Fruit { apple, orange, pear };
enum class Color { red, green, orange };
template <typename T> struct Traits;
template <>
class Traits<Fruit> {
public:
static string name(int i){
switch (i){
case 0: return "apple";
case 1: return "orange";
case 2: return "pear";
default: return "unknown";
}
}
};
template <>
class Traits<Color> {
public:
static string name(int i) {
switch (i){
case 0: return "red";
case 1: return "green";
case 2: return "orange";
default: return "unknown";
}
}
};
int main()
{
int t = 0; std::cin >> t;
for (int i=0; i!=t; ++i) {
int index1; std::cin >> index1;
int index2; std::cin >> index2;
cout << Traits<Color>::name(index1) << " ";
cout << Traits<Fruit>::name(index2) << "\n";
}
}
/**
Question :
https://www.hackerrank.com/challenges/cpp-class-template-specialization/problem
**/
| 18.448276
| 79
| 0.62243
|
BurningTiles
|
84fcff9071e08f38f83c9b1db33519cbd9007de7
| 1,539
|
cpp
|
C++
|
Educational Round 12/D.cpp
|
kimixuchen/Codeforces
|
1c259e867310d148d813c3ea7cc4f9cad3f21049
|
[
"Apache-2.0"
] | null | null | null |
Educational Round 12/D.cpp
|
kimixuchen/Codeforces
|
1c259e867310d148d813c3ea7cc4f9cad3f21049
|
[
"Apache-2.0"
] | null | null | null |
Educational Round 12/D.cpp
|
kimixuchen/Codeforces
|
1c259e867310d148d813c3ea7cc4f9cad3f21049
|
[
"Apache-2.0"
] | null | null | null |
/**
*Codeforces Educational Round 12 D
*24/04/16 13:56:03
*xuchen
* */
#include <stdio.h>
#include <iostream>
#include <cmath>
#include <cstring>
#include <stdlib.h>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 10000005;
bool prime[N];
int a[1005];
void init()
{
prime[1] = true;
for(int i=2; i<N; ++i)
{
if(!prime[i])
{
for(int j=i*2; j<N; j+=i)
{
prime[j] = true;
}
}
}
}
int main(int argc, char* args[])
{
int n;
int cnt=0, ans;
init();
scanf("%d", &n);
for(int i=0; i<n; ++i)
{
scanf("%d", a+i);
}
for(int i=0; i<n; ++i)
{
if(a[i]==1)
++cnt;
}
if(cnt > 1)
{
ans = cnt;
int t=0;
for(int i=0; i<n; ++i)
{
if(a[i]!=1 && !prime[a[i]+1])
{
ans++;
t = a[i];
break;
}
}
printf("%d\n", ans);
for(int i=0; i<cnt; ++i)
{
printf("1 ");
}
if(t>0)
printf("%d\n", t);
else
printf("\n");
}
else
{
for(int i=0; i<n; ++i)
{
for(int j=i+1; j<n; ++j)
{
if(!prime[a[i]+a[j]])
{
printf("2\n%d %d\n", a[i], a[j]);
return 0;
}
}
}
printf("1\n%d\n", a[0]);
}
return 0;
}
| 17.1
| 53
| 0.34178
|
kimixuchen
|
1700c91dad77fe317ef0bb30d98d8d15871c7a86
| 92
|
cpp
|
C++
|
src/examples/12_module/06_arrays_char/main.cpp
|
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-LeytonLL
|
0c544a3fa189dec5da827efe70fccb9f395cbe7d
|
[
"MIT"
] | null | null | null |
src/examples/12_module/06_arrays_char/main.cpp
|
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-LeytonLL
|
0c544a3fa189dec5da827efe70fccb9f395cbe7d
|
[
"MIT"
] | null | null | null |
src/examples/12_module/06_arrays_char/main.cpp
|
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-LeytonLL
|
0c544a3fa189dec5da827efe70fccb9f395cbe7d
|
[
"MIT"
] | null | null | null |
#include "arrays_char.h"
#include<iostream>
int main()
{
stack_char_array();
return 0;
};
| 11.5
| 24
| 0.695652
|
acc-cosc-1337-fall-2019
|
17015c7577724502a2a655d2330796e8e8efa964
| 4,403
|
cpp
|
C++
|
test/integration/cluster_solver/ctint/ctint_hund_lattice_test.cpp
|
frobnitzem/DCA
|
9f5d16cbfe1a4c4df1d4c8353654dd2882671dca
|
[
"BSD-3-Clause"
] | 1
|
2021-06-16T16:26:22.000Z
|
2021-06-16T16:26:22.000Z
|
test/integration/cluster_solver/ctint/ctint_hund_lattice_test.cpp
|
frobnitzem/DCA
|
9f5d16cbfe1a4c4df1d4c8353654dd2882671dca
|
[
"BSD-3-Clause"
] | 11
|
2020-04-22T14:50:27.000Z
|
2021-09-10T05:43:51.000Z
|
test/integration/cluster_solver/ctint/ctint_hund_lattice_test.cpp
|
frobnitzem/DCA
|
9f5d16cbfe1a4c4df1d4c8353654dd2882671dca
|
[
"BSD-3-Clause"
] | 1
|
2019-09-22T16:33:19.000Z
|
2019-09-22T16:33:19.000Z
|
// Copyright (C) 2018 ETH Zurich
// Copyright (C) 2018 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE.txt for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Giovanni Balduzzi (gbalduzz@itp.phys.ethz.ch)
//
// No-change test for CT-INT.
// Bilayer lattice with two band and two sites.
#include <iostream>
#include <string>
#include "gtest/gtest.h"
#include "dca/function/function.hpp"
#include "dca/io/hdf5/hdf5_reader.hpp"
#include "dca/io/hdf5/hdf5_writer.hpp"
#include "dca/io/json/json_reader.hpp"
#include "dca/math/random/std_random_wrapper.hpp"
#include "dca/phys/dca_data/dca_data.hpp"
#include "dca/phys/dca_step/cluster_solver/ctint/ctint_cluster_solver.hpp"
#include "dca/phys/domains/cluster/symmetries/point_groups/2d/2d_square.hpp"
#include "dca/phys/models/analytic_hamiltonians/hund_lattice.hpp"
#include "dca/phys/models/tight_binding_model.hpp"
#include "dca/parallel/no_threading/no_threading.hpp"
#include "dca/phys/parameters/parameters.hpp"
#include "dca/profiling/null_profiler.hpp"
#include "dca/testing/dca_mpi_test_environment.hpp"
#include "dca/testing/minimalist_printer.hpp"
#include "dca/util/git_version.hpp"
#include "dca/util/modules.hpp"
constexpr bool update_baseline = false;
dca::testing::DcaMpiTestEnvironment* dca_test_env;
const std::string input_dir = DCA_SOURCE_DIR "/test/integration/cluster_solver/ctint/";
TEST(CtintHundLatticeTest, Self_Energy) {
using RngType = dca::math::random::StdRandomWrapper<std::mt19937_64>;
using Lattice = dca::phys::models::HundLattice<dca::phys::domains::D4>;
using Model = dca::phys::models::TightBindingModel<Lattice>;
using Threading = dca::parallel::NoThreading;
using Parameters =
dca::phys::params::Parameters<dca::testing::DcaMpiTestEnvironment::ConcurrencyType, Threading,
dca::profiling::NullProfiler, Model, RngType, dca::phys::solver::CT_INT>;
using Data = dca::phys::DcaData<Parameters>;
using QmcSolverType = dca::phys::solver::CtintClusterSolver<dca::linalg::CPU, Parameters>;
if (dca_test_env->concurrency.id() == dca_test_env->concurrency.first()) {
dca::util::GitVersion::print();
dca::util::Modules::print();
}
Parameters parameters(dca::util::GitVersion::string(), dca_test_env->concurrency);
parameters.read_input_and_broadcast<dca::io::JSONReader>(dca_test_env->input_file_name);
parameters.update_model();
parameters.update_domains();
// Initialize data with G0 computation.
Data data(parameters);
data.initialize();
// Do one integration step.
QmcSolverType qmc_solver(parameters, data);
qmc_solver.initialize();
qmc_solver.integrate();
qmc_solver.finalize();
EXPECT_NEAR(2., qmc_solver.computeDensity(), 1e-2);
if (!update_baseline) {
// Read and confront with previous run.
if (dca_test_env->concurrency.id() == 0) {
Data::SpGreensFunction G_k_w_check(data.G_k_w.get_name());
dca::io::HDF5Reader reader;
reader.open_file(input_dir + "hund_lattice_baseline.hdf5");
reader.open_group("functions");
reader.execute(G_k_w_check);
reader.close_group(), reader.close_file();
for (int i = 0; i < G_k_w_check.size(); i++) {
EXPECT_NEAR(G_k_w_check(i).real(), data.G_k_w(i).real(), 5e-7);
EXPECT_NEAR(G_k_w_check(i).imag(), data.G_k_w(i).imag(), 5e-7);
}
}
}
else {
// Write results
if (dca_test_env->concurrency.id() == dca_test_env->concurrency.first()) {
dca::io::HDF5Writer writer;
writer.open_file(input_dir + "hund_lattice_baseline.hdf5");
writer.open_group("functions");
writer.execute(data.G_k_w);
writer.close_group(), writer.close_file();
}
}
}
int main(int argc, char** argv) {
int result = 0;
::testing::InitGoogleTest(&argc, argv);
dca::parallel::MPIConcurrency concurrency(argc, argv);
dca_test_env =
new dca::testing::DcaMpiTestEnvironment(concurrency, input_dir + "hund_lattice_input.json");
::testing::AddGlobalTestEnvironment(dca_test_env);
::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners();
if (dca_test_env->concurrency.id() != 0) {
delete listeners.Release(listeners.default_result_printer());
listeners.Append(new dca::testing::MinimalistPrinter);
}
result = RUN_ALL_TESTS();
return result;
}
| 36.691667
| 109
| 0.720872
|
frobnitzem
|
1708bfc927cfba97c21c31f017a225de08ce89b5
| 28,658
|
cc
|
C++
|
libcef/browser/menu_model_impl.cc
|
amirbn7/cef
|
732a307c751c2670a35fd9e0e4a491cdfc6bcc6b
|
[
"BSD-3-Clause"
] | null | null | null |
libcef/browser/menu_model_impl.cc
|
amirbn7/cef
|
732a307c751c2670a35fd9e0e4a491cdfc6bcc6b
|
[
"BSD-3-Clause"
] | null | null | null |
libcef/browser/menu_model_impl.cc
|
amirbn7/cef
|
732a307c751c2670a35fd9e0e4a491cdfc6bcc6b
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libcef/browser/menu_model_impl.h"
#include <vector>
#include "libcef/browser/thread_util.h"
#include "libcef/common/task_runner_impl.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "content/public/common/menu_item.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/gfx/geometry/point.h"
namespace {
const int kSeparatorId = -1;
const int kInvalidGroupId = -1;
const int kInvalidCommandId = -1;
const int kDefaultIndex = -1;
const int kInvalidIndex = -2;
// A simple MenuModel implementation that delegates to CefMenuModelImpl.
class CefSimpleMenuModel : public ui::MenuModel {
public:
// The Delegate can be NULL, though if it is items can't be checked or
// disabled.
explicit CefSimpleMenuModel(CefMenuModelImpl* impl) : impl_(impl) {}
// MenuModel methods.
bool HasIcons() const override { return false; }
int GetItemCount() const override { return impl_->GetCount(); }
ItemType GetTypeAt(int index) const override {
switch (impl_->GetTypeAt(index)) {
case MENUITEMTYPE_COMMAND:
return TYPE_COMMAND;
case MENUITEMTYPE_CHECK:
return TYPE_CHECK;
case MENUITEMTYPE_RADIO:
return TYPE_RADIO;
case MENUITEMTYPE_SEPARATOR:
return TYPE_SEPARATOR;
case MENUITEMTYPE_SUBMENU:
return TYPE_SUBMENU;
default:
NOTREACHED();
return TYPE_COMMAND;
}
}
ui::MenuSeparatorType GetSeparatorTypeAt(int index) const override {
return ui::NORMAL_SEPARATOR;
}
int GetCommandIdAt(int index) const override {
return impl_->GetCommandIdAt(index);
}
base::string16 GetLabelAt(int index) const override {
return impl_->GetFormattedLabelAt(index);
}
bool IsItemDynamicAt(int index) const override { return false; }
const gfx::FontList* GetLabelFontListAt(int index) const override {
return impl_->GetLabelFontListAt(index);
}
bool GetAcceleratorAt(int index,
ui::Accelerator* accelerator) const override {
int key_code = 0;
bool shift_pressed = false;
bool ctrl_pressed = false;
bool alt_pressed = false;
if (impl_->GetAcceleratorAt(index, key_code, shift_pressed, ctrl_pressed,
alt_pressed)) {
int modifiers = 0;
if (shift_pressed)
modifiers |= ui::EF_SHIFT_DOWN;
if (ctrl_pressed)
modifiers |= ui::EF_CONTROL_DOWN;
if (alt_pressed)
modifiers |= ui::EF_ALT_DOWN;
*accelerator =
ui::Accelerator(static_cast<ui::KeyboardCode>(key_code), modifiers);
return true;
}
return false;
}
bool IsItemCheckedAt(int index) const override {
return impl_->IsCheckedAt(index);
}
int GetGroupIdAt(int index) const override {
return impl_->GetGroupIdAt(index);
}
bool GetIconAt(int index, gfx::Image* icon) override { return false; }
ui::ButtonMenuItemModel* GetButtonMenuItemAt(int index) const override {
return NULL;
}
bool IsEnabledAt(int index) const override {
return impl_->IsEnabledAt(index);
}
bool IsVisibleAt(int index) const override {
return impl_->IsVisibleAt(index);
}
void ActivatedAt(int index) override { ActivatedAt(index, 0); }
void ActivatedAt(int index, int event_flags) override {
impl_->ActivatedAt(index, static_cast<cef_event_flags_t>(event_flags));
}
MenuModel* GetSubmenuModelAt(int index) const override {
CefRefPtr<CefMenuModel> submenu = impl_->GetSubMenuAt(index);
if (submenu.get())
return static_cast<CefMenuModelImpl*>(submenu.get())->model();
return NULL;
}
void MouseOutsideMenu(const gfx::Point& screen_point) override {
impl_->MouseOutsideMenu(screen_point);
}
void UnhandledOpenSubmenu(bool is_rtl) override {
impl_->UnhandledOpenSubmenu(is_rtl);
}
void UnhandledCloseSubmenu(bool is_rtl) override {
impl_->UnhandledCloseSubmenu(is_rtl);
}
bool GetTextColor(int index,
bool is_minor,
bool is_hovered,
SkColor* override_color) const override {
return impl_->GetTextColor(index, is_minor, is_hovered, override_color);
}
bool GetBackgroundColor(int index,
bool is_hovered,
SkColor* override_color) const override {
return impl_->GetBackgroundColor(index, is_hovered, override_color);
}
void MenuWillShow() override { impl_->MenuWillShow(); }
void MenuWillClose() override { impl_->MenuWillClose(); }
private:
CefMenuModelImpl* impl_;
DISALLOW_COPY_AND_ASSIGN(CefSimpleMenuModel);
};
cef_menu_color_type_t GetMenuColorType(bool is_text,
bool is_accelerator,
bool is_hovered) {
if (is_text) {
if (is_accelerator) {
return is_hovered ? CEF_MENU_COLOR_TEXT_ACCELERATOR_HOVERED
: CEF_MENU_COLOR_TEXT_ACCELERATOR;
}
return is_hovered ? CEF_MENU_COLOR_TEXT_HOVERED : CEF_MENU_COLOR_TEXT;
}
DCHECK(!is_accelerator);
return is_hovered ? CEF_MENU_COLOR_BACKGROUND_HOVERED
: CEF_MENU_COLOR_BACKGROUND;
}
} // namespace
// static
CefRefPtr<CefMenuModel> CefMenuModel::CreateMenuModel(
CefRefPtr<CefMenuModelDelegate> delegate) {
CEF_REQUIRE_UIT_RETURN(nullptr);
DCHECK(delegate);
if (!delegate)
return nullptr;
CefRefPtr<CefMenuModelImpl> menu_model =
new CefMenuModelImpl(nullptr, delegate, false);
return menu_model;
}
struct CefMenuModelImpl::Item {
Item(cef_menu_item_type_t type,
int command_id,
const CefString& label,
int group_id)
: type_(type),
command_id_(command_id),
label_(label),
group_id_(group_id) {}
// Basic information.
cef_menu_item_type_t type_;
int command_id_;
CefString label_;
int group_id_;
CefRefPtr<CefMenuModelImpl> submenu_;
// State information.
bool enabled_ = true;
bool visible_ = true;
bool checked_ = false;
// Accelerator information.
bool has_accelerator_ = false;
int key_code_ = 0;
bool shift_pressed_ = false;
bool ctrl_pressed_ = false;
bool alt_pressed_ = false;
cef_color_t colors_[CEF_MENU_COLOR_COUNT] = {0};
gfx::FontList font_list_;
bool has_font_list_ = false;
};
CefMenuModelImpl::CefMenuModelImpl(
Delegate* delegate,
CefRefPtr<CefMenuModelDelegate> menu_model_delegate,
bool is_submenu)
: supported_thread_id_(base::PlatformThread::CurrentId()),
delegate_(delegate),
menu_model_delegate_(menu_model_delegate),
is_submenu_(is_submenu) {
DCHECK(delegate_ || menu_model_delegate_);
model_.reset(new CefSimpleMenuModel(this));
}
CefMenuModelImpl::~CefMenuModelImpl() {}
bool CefMenuModelImpl::IsSubMenu() {
if (!VerifyContext())
return false;
return is_submenu_;
}
bool CefMenuModelImpl::Clear() {
if (!VerifyContext())
return false;
items_.clear();
return true;
}
int CefMenuModelImpl::GetCount() {
if (!VerifyContext())
return 0;
return static_cast<int>(items_.size());
}
bool CefMenuModelImpl::AddSeparator() {
if (!VerifyContext())
return false;
AppendItem(
Item(MENUITEMTYPE_SEPARATOR, kSeparatorId, CefString(), kInvalidGroupId));
return true;
}
bool CefMenuModelImpl::AddItem(int command_id, const CefString& label) {
if (!VerifyContext())
return false;
AppendItem(Item(MENUITEMTYPE_COMMAND, command_id, label, kInvalidGroupId));
return true;
}
bool CefMenuModelImpl::AddCheckItem(int command_id, const CefString& label) {
if (!VerifyContext())
return false;
AppendItem(Item(MENUITEMTYPE_CHECK, command_id, label, kInvalidGroupId));
return true;
}
bool CefMenuModelImpl::AddRadioItem(int command_id,
const CefString& label,
int group_id) {
if (!VerifyContext())
return false;
AppendItem(Item(MENUITEMTYPE_RADIO, command_id, label, group_id));
return true;
}
CefRefPtr<CefMenuModel> CefMenuModelImpl::AddSubMenu(int command_id,
const CefString& label) {
if (!VerifyContext())
return NULL;
Item item(MENUITEMTYPE_SUBMENU, command_id, label, kInvalidGroupId);
item.submenu_ = new CefMenuModelImpl(delegate_, menu_model_delegate_, true);
AppendItem(item);
return item.submenu_.get();
}
bool CefMenuModelImpl::InsertSeparatorAt(int index) {
if (!VerifyContext())
return false;
InsertItemAt(
Item(MENUITEMTYPE_SEPARATOR, kSeparatorId, CefString(), kInvalidGroupId),
index);
return true;
}
bool CefMenuModelImpl::InsertItemAt(int index,
int command_id,
const CefString& label) {
if (!VerifyContext())
return false;
InsertItemAt(Item(MENUITEMTYPE_COMMAND, command_id, label, kInvalidGroupId),
index);
return true;
}
bool CefMenuModelImpl::InsertCheckItemAt(int index,
int command_id,
const CefString& label) {
if (!VerifyContext())
return false;
InsertItemAt(Item(MENUITEMTYPE_CHECK, command_id, label, kInvalidGroupId),
index);
return true;
}
bool CefMenuModelImpl::InsertRadioItemAt(int index,
int command_id,
const CefString& label,
int group_id) {
if (!VerifyContext())
return false;
InsertItemAt(Item(MENUITEMTYPE_RADIO, command_id, label, group_id), index);
return true;
}
CefRefPtr<CefMenuModel> CefMenuModelImpl::InsertSubMenuAt(
int index,
int command_id,
const CefString& label) {
if (!VerifyContext())
return NULL;
Item item(MENUITEMTYPE_SUBMENU, command_id, label, kInvalidGroupId);
item.submenu_ = new CefMenuModelImpl(delegate_, menu_model_delegate_, true);
InsertItemAt(item, index);
return item.submenu_.get();
}
bool CefMenuModelImpl::Remove(int command_id) {
return RemoveAt(GetIndexOf(command_id));
}
bool CefMenuModelImpl::RemoveAt(int index) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size())) {
items_.erase(items_.begin() + index);
return true;
}
return false;
}
int CefMenuModelImpl::GetIndexOf(int command_id) {
if (!VerifyContext())
return kInvalidIndex;
for (ItemVector::iterator i = items_.begin(); i != items_.end(); ++i) {
if ((*i).command_id_ == command_id) {
return static_cast<int>(std::distance(items_.begin(), i));
}
}
return kInvalidIndex;
}
int CefMenuModelImpl::GetCommandIdAt(int index) {
if (!VerifyContext())
return kInvalidCommandId;
if (index >= 0 && index < static_cast<int>(items_.size()))
return items_[index].command_id_;
return kInvalidCommandId;
}
bool CefMenuModelImpl::SetCommandIdAt(int index, int command_id) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size())) {
items_[index].command_id_ = command_id;
return true;
}
return false;
}
CefString CefMenuModelImpl::GetLabel(int command_id) {
return GetLabelAt(GetIndexOf(command_id));
}
CefString CefMenuModelImpl::GetLabelAt(int index) {
if (!VerifyContext())
return CefString();
if (index >= 0 && index < static_cast<int>(items_.size()))
return items_[index].label_;
return CefString();
}
bool CefMenuModelImpl::SetLabel(int command_id, const CefString& label) {
return SetLabelAt(GetIndexOf(command_id), label);
}
bool CefMenuModelImpl::SetLabelAt(int index, const CefString& label) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size())) {
items_[index].label_ = label;
return true;
}
return false;
}
CefMenuModelImpl::MenuItemType CefMenuModelImpl::GetType(int command_id) {
return GetTypeAt(GetIndexOf(command_id));
}
CefMenuModelImpl::MenuItemType CefMenuModelImpl::GetTypeAt(int index) {
if (!VerifyContext())
return MENUITEMTYPE_NONE;
if (index >= 0 && index < static_cast<int>(items_.size()))
return items_[index].type_;
return MENUITEMTYPE_NONE;
}
int CefMenuModelImpl::GetGroupId(int command_id) {
return GetGroupIdAt(GetIndexOf(command_id));
}
int CefMenuModelImpl::GetGroupIdAt(int index) {
if (!VerifyContext())
return kInvalidGroupId;
if (index >= 0 && index < static_cast<int>(items_.size()))
return items_[index].group_id_;
return kInvalidGroupId;
}
bool CefMenuModelImpl::SetGroupId(int command_id, int group_id) {
return SetGroupIdAt(GetIndexOf(command_id), group_id);
}
bool CefMenuModelImpl::SetGroupIdAt(int index, int group_id) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size())) {
items_[index].group_id_ = group_id;
return true;
}
return false;
}
CefRefPtr<CefMenuModel> CefMenuModelImpl::GetSubMenu(int command_id) {
return GetSubMenuAt(GetIndexOf(command_id));
}
CefRefPtr<CefMenuModel> CefMenuModelImpl::GetSubMenuAt(int index) {
if (!VerifyContext())
return NULL;
if (index >= 0 && index < static_cast<int>(items_.size()))
return items_[index].submenu_.get();
return NULL;
}
bool CefMenuModelImpl::IsVisible(int command_id) {
return IsVisibleAt(GetIndexOf(command_id));
}
bool CefMenuModelImpl::IsVisibleAt(int index) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size()))
return items_[index].visible_;
return false;
}
bool CefMenuModelImpl::SetVisible(int command_id, bool visible) {
return SetVisibleAt(GetIndexOf(command_id), visible);
}
bool CefMenuModelImpl::SetVisibleAt(int index, bool visible) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size())) {
items_[index].visible_ = visible;
return true;
}
return false;
}
bool CefMenuModelImpl::IsEnabled(int command_id) {
return IsEnabledAt(GetIndexOf(command_id));
}
bool CefMenuModelImpl::IsEnabledAt(int index) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size()))
return items_[index].enabled_;
return false;
}
bool CefMenuModelImpl::SetEnabled(int command_id, bool enabled) {
return SetEnabledAt(GetIndexOf(command_id), enabled);
}
bool CefMenuModelImpl::SetEnabledAt(int index, bool enabled) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size())) {
items_[index].enabled_ = enabled;
return true;
}
return false;
}
bool CefMenuModelImpl::IsChecked(int command_id) {
return IsCheckedAt(GetIndexOf(command_id));
}
bool CefMenuModelImpl::IsCheckedAt(int index) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size()))
return items_[index].checked_;
return false;
}
bool CefMenuModelImpl::SetChecked(int command_id, bool checked) {
return SetCheckedAt(GetIndexOf(command_id), checked);
}
bool CefMenuModelImpl::SetCheckedAt(int index, bool checked) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size())) {
items_[index].checked_ = checked;
return true;
}
return false;
}
bool CefMenuModelImpl::HasAccelerator(int command_id) {
return HasAcceleratorAt(GetIndexOf(command_id));
}
bool CefMenuModelImpl::HasAcceleratorAt(int index) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size()))
return items_[index].has_accelerator_;
return false;
}
bool CefMenuModelImpl::SetAccelerator(int command_id,
int key_code,
bool shift_pressed,
bool ctrl_pressed,
bool alt_pressed) {
return SetAcceleratorAt(GetIndexOf(command_id), key_code, shift_pressed,
ctrl_pressed, alt_pressed);
}
bool CefMenuModelImpl::SetAcceleratorAt(int index,
int key_code,
bool shift_pressed,
bool ctrl_pressed,
bool alt_pressed) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size())) {
Item& item = items_[index];
item.has_accelerator_ = true;
item.key_code_ = key_code;
item.shift_pressed_ = shift_pressed;
item.ctrl_pressed_ = ctrl_pressed;
item.alt_pressed_ = alt_pressed;
return true;
}
return false;
}
bool CefMenuModelImpl::RemoveAccelerator(int command_id) {
return RemoveAcceleratorAt(GetIndexOf(command_id));
}
bool CefMenuModelImpl::RemoveAcceleratorAt(int index) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size())) {
Item& item = items_[index];
if (item.has_accelerator_) {
item.has_accelerator_ = false;
item.key_code_ = 0;
item.shift_pressed_ = false;
item.ctrl_pressed_ = false;
item.alt_pressed_ = false;
}
return true;
}
return false;
}
bool CefMenuModelImpl::GetAccelerator(int command_id,
int& key_code,
bool& shift_pressed,
bool& ctrl_pressed,
bool& alt_pressed) {
return GetAcceleratorAt(GetIndexOf(command_id), key_code, shift_pressed,
ctrl_pressed, alt_pressed);
}
bool CefMenuModelImpl::GetAcceleratorAt(int index,
int& key_code,
bool& shift_pressed,
bool& ctrl_pressed,
bool& alt_pressed) {
if (!VerifyContext())
return false;
if (index >= 0 && index < static_cast<int>(items_.size())) {
const Item& item = items_[index];
if (item.has_accelerator_) {
key_code = item.key_code_;
shift_pressed = item.shift_pressed_;
ctrl_pressed = item.ctrl_pressed_;
alt_pressed = item.alt_pressed_;
return true;
}
}
return false;
}
bool CefMenuModelImpl::SetColor(int command_id,
cef_menu_color_type_t color_type,
cef_color_t color) {
return SetColorAt(GetIndexOf(command_id), color_type, color);
}
bool CefMenuModelImpl::SetColorAt(int index,
cef_menu_color_type_t color_type,
cef_color_t color) {
if (!VerifyContext())
return false;
if (color_type < 0 || color_type >= CEF_MENU_COLOR_COUNT)
return false;
if (index == kDefaultIndex) {
default_colors_[color_type] = color;
return true;
}
if (index >= 0 && index < static_cast<int>(items_.size())) {
Item& item = items_[index];
item.colors_[color_type] = color;
return true;
}
return false;
}
bool CefMenuModelImpl::GetColor(int command_id,
cef_menu_color_type_t color_type,
cef_color_t& color) {
return GetColorAt(GetIndexOf(command_id), color_type, color);
}
bool CefMenuModelImpl::GetColorAt(int index,
cef_menu_color_type_t color_type,
cef_color_t& color) {
if (!VerifyContext())
return false;
if (color_type < 0 || color_type >= CEF_MENU_COLOR_COUNT)
return false;
if (index == kDefaultIndex) {
color = default_colors_[color_type];
return true;
}
if (index >= 0 && index < static_cast<int>(items_.size())) {
Item& item = items_[index];
color = item.colors_[color_type];
return true;
}
return false;
}
bool CefMenuModelImpl::SetFontList(int command_id, const CefString& font_list) {
return SetFontListAt(GetIndexOf(command_id), font_list);
}
bool CefMenuModelImpl::SetFontListAt(int index, const CefString& font_list) {
if (!VerifyContext())
return false;
if (index == kDefaultIndex) {
if (font_list.empty()) {
has_default_font_list_ = false;
} else {
default_font_list_ = gfx::FontList(font_list);
has_default_font_list_ = true;
}
return true;
}
if (index >= 0 && index < static_cast<int>(items_.size())) {
Item& item = items_[index];
if (font_list.empty()) {
item.has_font_list_ = false;
} else {
item.font_list_ = gfx::FontList(font_list);
item.has_font_list_ = true;
}
return true;
}
return false;
}
void CefMenuModelImpl::ActivatedAt(int index, cef_event_flags_t event_flags) {
if (!VerifyContext())
return;
const int command_id = GetCommandIdAt(index);
if (delegate_)
delegate_->ExecuteCommand(this, command_id, event_flags);
if (menu_model_delegate_)
menu_model_delegate_->ExecuteCommand(this, command_id, event_flags);
}
void CefMenuModelImpl::MouseOutsideMenu(const gfx::Point& screen_point) {
if (!VerifyContext())
return;
// Allow the callstack to unwind before notifying the delegate since it may
// result in the menu being destroyed.
CefTaskRunnerImpl::GetCurrentTaskRunner()->PostTask(
FROM_HERE,
base::Bind(&CefMenuModelImpl::OnMouseOutsideMenu, this, screen_point));
}
void CefMenuModelImpl::UnhandledOpenSubmenu(bool is_rtl) {
if (!VerifyContext())
return;
// Allow the callstack to unwind before notifying the delegate since it may
// result in the menu being destroyed.
CefTaskRunnerImpl::GetCurrentTaskRunner()->PostTask(
FROM_HERE,
base::Bind(&CefMenuModelImpl::OnUnhandledOpenSubmenu, this, is_rtl));
}
void CefMenuModelImpl::UnhandledCloseSubmenu(bool is_rtl) {
if (!VerifyContext())
return;
// Allow the callstack to unwind before notifying the delegate since it may
// result in the menu being destroyed.
CefTaskRunnerImpl::GetCurrentTaskRunner()->PostTask(
FROM_HERE,
base::Bind(&CefMenuModelImpl::OnUnhandledCloseSubmenu, this, is_rtl));
}
bool CefMenuModelImpl::GetTextColor(int index,
bool is_accelerator,
bool is_hovered,
SkColor* override_color) const {
if (index >= 0 && index < static_cast<int>(items_.size())) {
const Item& item = items_[index];
if (!item.enabled_) {
// Use accelerator color for disabled item text.
is_accelerator = true;
}
const cef_menu_color_type_t color_type =
GetMenuColorType(true, is_accelerator, is_hovered);
if (item.colors_[color_type] != 0) {
*override_color = item.colors_[color_type];
return true;
}
}
const cef_menu_color_type_t color_type =
GetMenuColorType(true, is_accelerator, is_hovered);
if (default_colors_[color_type] != 0) {
*override_color = default_colors_[color_type];
return true;
}
return false;
}
bool CefMenuModelImpl::GetBackgroundColor(int index,
bool is_hovered,
SkColor* override_color) const {
const cef_menu_color_type_t color_type =
GetMenuColorType(false, false, is_hovered);
if (index >= 0 && index < static_cast<int>(items_.size())) {
const Item& item = items_[index];
if (item.colors_[color_type] != 0) {
*override_color = item.colors_[color_type];
return true;
}
}
if (default_colors_[color_type] != 0) {
*override_color = default_colors_[color_type];
return true;
}
return false;
}
void CefMenuModelImpl::MenuWillShow() {
if (!VerifyContext())
return;
if (delegate_)
delegate_->MenuWillShow(this);
if (menu_model_delegate_)
menu_model_delegate_->MenuWillShow(this);
}
void CefMenuModelImpl::MenuWillClose() {
if (!VerifyContext())
return;
if (!auto_notify_menu_closed_)
return;
// Due to how menus work on the different platforms, ActivatedAt will be
// called after this. It's more convenient for the delegate to be called
// afterwards, though, so post a task.
CefTaskRunnerImpl::GetCurrentTaskRunner()->PostTask(
FROM_HERE, base::Bind(&CefMenuModelImpl::OnMenuClosed, this));
}
base::string16 CefMenuModelImpl::GetFormattedLabelAt(int index) {
base::string16 label = GetLabelAt(index).ToString16();
if (delegate_)
delegate_->FormatLabel(this, label);
if (menu_model_delegate_) {
CefString new_label = label;
if (menu_model_delegate_->FormatLabel(this, new_label))
label = new_label;
}
return label;
}
const gfx::FontList* CefMenuModelImpl::GetLabelFontListAt(int index) const {
if (index >= 0 && index < static_cast<int>(items_.size())) {
const Item& item = items_[index];
if (item.has_font_list_)
return &item.font_list_;
}
if (has_default_font_list_)
return &default_font_list_;
return nullptr;
}
bool CefMenuModelImpl::VerifyRefCount() {
if (!VerifyContext())
return false;
if (!HasOneRef())
return false;
for (ItemVector::iterator i = items_.begin(); i != items_.end(); ++i) {
if ((*i).submenu_.get()) {
if (!(*i).submenu_->VerifyRefCount())
return false;
}
}
return true;
}
void CefMenuModelImpl::AddMenuItem(const content::MenuItem& menu_item) {
const int command_id = static_cast<int>(menu_item.action);
switch (menu_item.type) {
case content::MenuItem::OPTION:
AddItem(command_id, menu_item.label);
break;
case content::MenuItem::CHECKABLE_OPTION:
AddCheckItem(command_id, menu_item.label);
break;
case content::MenuItem::GROUP:
AddRadioItem(command_id, menu_item.label, 0);
break;
case content::MenuItem::SEPARATOR:
AddSeparator();
break;
case content::MenuItem::SUBMENU: {
CefRefPtr<CefMenuModelImpl> sub_menu = static_cast<CefMenuModelImpl*>(
AddSubMenu(command_id, menu_item.label).get());
for (size_t i = 0; i < menu_item.submenu.size(); ++i)
sub_menu->AddMenuItem(menu_item.submenu[i]);
break;
}
}
if (!menu_item.enabled && menu_item.type != content::MenuItem::SEPARATOR)
SetEnabled(command_id, false);
if (menu_item.checked &&
(menu_item.type == content::MenuItem::CHECKABLE_OPTION ||
menu_item.type == content::MenuItem::GROUP)) {
SetChecked(command_id, true);
}
}
void CefMenuModelImpl::NotifyMenuClosed() {
DCHECK(!auto_notify_menu_closed_);
OnMenuClosed();
}
void CefMenuModelImpl::AppendItem(const Item& item) {
ValidateItem(item);
items_.push_back(item);
}
void CefMenuModelImpl::InsertItemAt(const Item& item, int index) {
// Sanitize the index.
if (index < 0)
index = 0;
else if (index > static_cast<int>(items_.size()))
index = items_.size();
ValidateItem(item);
items_.insert(items_.begin() + index, item);
}
void CefMenuModelImpl::ValidateItem(const Item& item) {
#if DCHECK_IS_ON()
if (item.type_ == MENUITEMTYPE_SEPARATOR) {
DCHECK_EQ(item.command_id_, kSeparatorId);
} else {
DCHECK_GE(item.command_id_, 0);
}
#endif
}
void CefMenuModelImpl::OnMouseOutsideMenu(const gfx::Point& screen_point) {
if (delegate_)
delegate_->MouseOutsideMenu(this, screen_point);
if (menu_model_delegate_) {
menu_model_delegate_->MouseOutsideMenu(
this, CefPoint(screen_point.x(), screen_point.y()));
}
}
void CefMenuModelImpl::OnUnhandledOpenSubmenu(bool is_rtl) {
if (delegate_)
delegate_->UnhandledOpenSubmenu(this, is_rtl);
if (menu_model_delegate_)
menu_model_delegate_->UnhandledOpenSubmenu(this, is_rtl);
}
void CefMenuModelImpl::OnUnhandledCloseSubmenu(bool is_rtl) {
if (delegate_)
delegate_->UnhandledCloseSubmenu(this, is_rtl);
if (menu_model_delegate_)
menu_model_delegate_->UnhandledCloseSubmenu(this, is_rtl);
}
void CefMenuModelImpl::OnMenuClosed() {
if (delegate_)
delegate_->MenuClosed(this);
if (menu_model_delegate_)
menu_model_delegate_->MenuClosed(this);
}
bool CefMenuModelImpl::VerifyContext() {
if (base::PlatformThread::CurrentId() != supported_thread_id_) {
// This object should only be accessed from the thread that created it.
NOTREACHED();
return false;
}
return true;
}
| 27.76938
| 80
| 0.666097
|
amirbn7
|
170cdc252e7a87a413dc7e5c47f50076b934b462
| 3,406
|
cpp
|
C++
|
test/test_explode.cpp
|
yiyuanzhong/flinter
|
c52655ea5f8e48244fdb59bdf34b915faee57a6e
|
[
"Apache-2.0"
] | 29
|
2016-01-29T09:31:09.000Z
|
2021-07-11T12:00:31.000Z
|
test/test_explode.cpp
|
yiyuanzhong/flinter
|
c52655ea5f8e48244fdb59bdf34b915faee57a6e
|
[
"Apache-2.0"
] | 2
|
2015-03-30T09:59:51.000Z
|
2017-03-13T09:35:18.000Z
|
test/test_explode.cpp
|
yiyuanzhong/flinter
|
c52655ea5f8e48244fdb59bdf34b915faee57a6e
|
[
"Apache-2.0"
] | 17
|
2015-03-28T09:24:53.000Z
|
2021-08-07T10:09:10.000Z
|
#include <flinter/explode.h>
#include <gtest/gtest.h>
#include <list>
#include <string>
#include <vector>
TEST(ExplodeTest, TestExplodeNull0)
{
std::vector<std::string> r;
flinter::explode("", "|", &r, true);
ASSERT_EQ(r.size(), 1u);
EXPECT_TRUE(r[0].empty());
}
TEST(ExplodeTest, TestExplodeNull1)
{
std::vector<std::string> r;
flinter::explode(",", ",", &r, true);
ASSERT_EQ(r.size(), 2u);
EXPECT_TRUE(r[0].empty());
EXPECT_TRUE(r[1].empty());
}
TEST(ExplodeTest, TestExplodeNull2)
{
std::vector<std::string> r;
flinter::explode("||5", "|", &r, true);
ASSERT_EQ(r.size(), 3u);
EXPECT_TRUE(r[0].empty());
EXPECT_TRUE(r[1].empty());
EXPECT_EQ(r[2], "5");
}
TEST(ExplodeTest, TestExplodeNull3)
{
std::vector<std::string> r;
flinter::explode("||6|5,|3|7|||||", "|,", &r, true);
ASSERT_EQ(r.size(), 12u);
EXPECT_TRUE(r[0].empty());
EXPECT_TRUE(r[1].empty());
EXPECT_EQ(r[2], "6");
EXPECT_EQ(r[3], "5");
EXPECT_TRUE(r[4].empty());
EXPECT_EQ(r[5], "3");
EXPECT_EQ(r[6], "7");
EXPECT_TRUE(r[7].empty());
EXPECT_TRUE(r[8].empty());
EXPECT_TRUE(r[9].empty());
EXPECT_TRUE(r[10].empty());
EXPECT_TRUE(r[11].empty());
}
TEST(ExplodeTest, TestExplodeNull4)
{
std::vector<std::string> r;
flinter::explode("6|5||3|7", "||", &r, true);
ASSERT_EQ(r.size(), 5u);
EXPECT_EQ(r[0], "6");
EXPECT_EQ(r[1], "5");
EXPECT_TRUE(r[2].empty());
EXPECT_EQ(r[3], "3");
EXPECT_EQ(r[4], "7");
}
TEST(ExplodeTest, TestExplodeNotNull0)
{
std::list<std::string> s;
flinter::explode("", "|", &s, false);
ASSERT_EQ(s.size(), 0u);
}
TEST(ExplodeTest, TestExplodeNotNull1)
{
std::list<std::string> s;
flinter::explode(",", ",", &s, false);
ASSERT_EQ(s.size(), 0u);
}
TEST(ExplodeTest, TestExplodeNotNull2)
{
std::list<std::string> s;
flinter::explode("||5", "|", &s, false);
ASSERT_EQ(s.size(), 1u);
EXPECT_EQ(s.front(), "5");
}
TEST(ExplodeTest, TestExplodeNotNull3)
{
std::vector<std::string> r;
flinter::explode("||6|5,|3|7|||||", ",|", &r, false);
ASSERT_EQ(r.size(), 4u);
EXPECT_EQ(r[0], "6");
EXPECT_EQ(r[1], "5");
EXPECT_EQ(r[2], "3");
EXPECT_EQ(r[3], "7");
}
TEST(ExplodeTest, TestExplodeNotNull4)
{
std::vector<std::string> r;
flinter::explode("6|5||3|7", "||", &r, false);
ASSERT_EQ(r.size(), 4u);
EXPECT_EQ(r[0], "6");
EXPECT_EQ(r[1], "5");
EXPECT_EQ(r[2], "3");
EXPECT_EQ(r[3], "7");
}
TEST(ExplodeTest, TestExplodeSet)
{
std::set<std::string> r;
flinter::explode("6|5||3|7", "||", &r);
ASSERT_EQ(r.size(), 4u);
std::set<std::string>::iterator p = r.begin();
EXPECT_EQ(*p++, "3");
EXPECT_EQ(*p++, "5");
EXPECT_EQ(*p++, "6");
EXPECT_EQ(*p++, "7");
}
TEST(ExplodeTest, TestImplode)
{
static const char *a[] = { "hello", "world", "abc" };
std::vector<std::string> b(a, a + 3);
std::string o;
flinter::implode("__", a, a + 3, &o);
EXPECT_EQ(o, "hello__world__abc");
flinter::implode(",", b, &o);
EXPECT_EQ(o, "hello,world,abc");
flinter::implode("__", a, a + 1, &o);
EXPECT_EQ(o, "hello");
flinter::implode("__", a, a, &o);
EXPECT_EQ(o, "");
b.clear();
flinter::implode(",", b, &o);
EXPECT_EQ(o, "");
b.push_back("aaa");
flinter::implode(",", b, &o);
EXPECT_EQ(o, "aaa");
}
| 23.818182
| 57
| 0.557546
|
yiyuanzhong
|
1710bcdf5f2e7155043f2ed192f285637d9194a1
| 212
|
cpp
|
C++
|
source/Abstract/Action/LambdaAction.cpp
|
metamaker/custom-global-hotkeys
|
848c1d01504084eaff5ec23ad174b43eb3298ff9
|
[
"MIT"
] | 1
|
2017-03-27T15:58:21.000Z
|
2017-03-27T15:58:21.000Z
|
source/Abstract/Action/LambdaAction.cpp
|
metamaker/custom-global-hotkeys
|
848c1d01504084eaff5ec23ad174b43eb3298ff9
|
[
"MIT"
] | null | null | null |
source/Abstract/Action/LambdaAction.cpp
|
metamaker/custom-global-hotkeys
|
848c1d01504084eaff5ec23ad174b43eb3298ff9
|
[
"MIT"
] | null | null | null |
#include "LambdaAction.h"
using CustomGlobalHotkeys::Action::LambdaAction;
LambdaAction::LambdaAction(TLambdaFunction function):
m_function(function)
{
}
void LambdaAction::execute() const
{
m_function();
}
| 15.142857
| 53
| 0.778302
|
metamaker
|
1715c5796bc9529cdac6dc74c3a5e7a3d4a3d9dd
| 238
|
cpp
|
C++
|
app/src/main/cpp/people/people.cpp
|
kewpieQT/NDKPracticeDemo
|
a843e78761ecff9f1a1a9361f7d430fa6d8a5bc3
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/cpp/people/people.cpp
|
kewpieQT/NDKPracticeDemo
|
a843e78761ecff9f1a1a9361f7d430fa6d8a5bc3
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/cpp/people/people.cpp
|
kewpieQT/NDKPracticeDemo
|
a843e78761ecff9f1a1a9361f7d430fa6d8a5bc3
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by Kewpie Qin on 2020/12/2.
//
#include "people.h"
std::string people::getString() {
return "this is from people";
}
std::string people::getStringFromCStyle(const char *str) {
std::string s(str);
return s;
}
| 14.875
| 58
| 0.642857
|
kewpieQT
|
171828d04d852a9a93dc5979b81ed3e8b98c7ee1
| 13,979
|
ipp
|
C++
|
third_party/include/mvscxx/oglplus/enums/program_resource_property_def.ipp
|
Simmesimme/swift2d
|
147a862208dee56f972361b5325009e020124137
|
[
"MIT"
] | null | null | null |
third_party/include/mvscxx/oglplus/enums/program_resource_property_def.ipp
|
Simmesimme/swift2d
|
147a862208dee56f972361b5325009e020124137
|
[
"MIT"
] | null | null | null |
third_party/include/mvscxx/oglplus/enums/program_resource_property_def.ipp
|
Simmesimme/swift2d
|
147a862208dee56f972361b5325009e020124137
|
[
"MIT"
] | null | null | null |
// File implement/oglplus/enums/program_resource_property_def.ipp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/program_resource_property.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2014 Matus Chochlik.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifdef OGLPLUS_LIST_NEEDS_COMMA
# undef OGLPLUS_LIST_NEEDS_COMMA
#endif
#if defined GL_ARRAY_SIZE
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined ArraySize
# pragma push_macro("ArraySize")
# undef ArraySize
OGLPLUS_ENUM_CLASS_VALUE(ArraySize, GL_ARRAY_SIZE)
# pragma pop_macro("ArraySize")
# else
OGLPLUS_ENUM_CLASS_VALUE(ArraySize, GL_ARRAY_SIZE)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_OFFSET
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined Offset
# pragma push_macro("Offset")
# undef Offset
OGLPLUS_ENUM_CLASS_VALUE(Offset, GL_OFFSET)
# pragma pop_macro("Offset")
# else
OGLPLUS_ENUM_CLASS_VALUE(Offset, GL_OFFSET)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_BLOCK_INDEX
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined BlockIndex
# pragma push_macro("BlockIndex")
# undef BlockIndex
OGLPLUS_ENUM_CLASS_VALUE(BlockIndex, GL_BLOCK_INDEX)
# pragma pop_macro("BlockIndex")
# else
OGLPLUS_ENUM_CLASS_VALUE(BlockIndex, GL_BLOCK_INDEX)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_ARRAY_STRIDE
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined ArrayStride
# pragma push_macro("ArrayStride")
# undef ArrayStride
OGLPLUS_ENUM_CLASS_VALUE(ArrayStride, GL_ARRAY_STRIDE)
# pragma pop_macro("ArrayStride")
# else
OGLPLUS_ENUM_CLASS_VALUE(ArrayStride, GL_ARRAY_STRIDE)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_MATRIX_STRIDE
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined MatrixStride
# pragma push_macro("MatrixStride")
# undef MatrixStride
OGLPLUS_ENUM_CLASS_VALUE(MatrixStride, GL_MATRIX_STRIDE)
# pragma pop_macro("MatrixStride")
# else
OGLPLUS_ENUM_CLASS_VALUE(MatrixStride, GL_MATRIX_STRIDE)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_IS_ROW_MAJOR
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined IsRowMajor
# pragma push_macro("IsRowMajor")
# undef IsRowMajor
OGLPLUS_ENUM_CLASS_VALUE(IsRowMajor, GL_IS_ROW_MAJOR)
# pragma pop_macro("IsRowMajor")
# else
OGLPLUS_ENUM_CLASS_VALUE(IsRowMajor, GL_IS_ROW_MAJOR)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_ATOMIC_COUNTER_BUFFER_INDEX
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined AtomicCounterBufferIndex
# pragma push_macro("AtomicCounterBufferIndex")
# undef AtomicCounterBufferIndex
OGLPLUS_ENUM_CLASS_VALUE(AtomicCounterBufferIndex, GL_ATOMIC_COUNTER_BUFFER_INDEX)
# pragma pop_macro("AtomicCounterBufferIndex")
# else
OGLPLUS_ENUM_CLASS_VALUE(AtomicCounterBufferIndex, GL_ATOMIC_COUNTER_BUFFER_INDEX)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_BUFFER_BINDING
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined BufferBinding
# pragma push_macro("BufferBinding")
# undef BufferBinding
OGLPLUS_ENUM_CLASS_VALUE(BufferBinding, GL_BUFFER_BINDING)
# pragma pop_macro("BufferBinding")
# else
OGLPLUS_ENUM_CLASS_VALUE(BufferBinding, GL_BUFFER_BINDING)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_BUFFER_DATA_SIZE
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined BufferDataSize
# pragma push_macro("BufferDataSize")
# undef BufferDataSize
OGLPLUS_ENUM_CLASS_VALUE(BufferDataSize, GL_BUFFER_DATA_SIZE)
# pragma pop_macro("BufferDataSize")
# else
OGLPLUS_ENUM_CLASS_VALUE(BufferDataSize, GL_BUFFER_DATA_SIZE)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_NUM_ACTIVE_VARIABLES
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined NumActiveVariables
# pragma push_macro("NumActiveVariables")
# undef NumActiveVariables
OGLPLUS_ENUM_CLASS_VALUE(NumActiveVariables, GL_NUM_ACTIVE_VARIABLES)
# pragma pop_macro("NumActiveVariables")
# else
OGLPLUS_ENUM_CLASS_VALUE(NumActiveVariables, GL_NUM_ACTIVE_VARIABLES)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_ACTIVE_VARIABLES
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined ActiveVariables
# pragma push_macro("ActiveVariables")
# undef ActiveVariables
OGLPLUS_ENUM_CLASS_VALUE(ActiveVariables, GL_ACTIVE_VARIABLES)
# pragma pop_macro("ActiveVariables")
# else
OGLPLUS_ENUM_CLASS_VALUE(ActiveVariables, GL_ACTIVE_VARIABLES)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_REFERENCED_BY_VERTEX_SHADER
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined ReferencedByVertexShader
# pragma push_macro("ReferencedByVertexShader")
# undef ReferencedByVertexShader
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByVertexShader, GL_REFERENCED_BY_VERTEX_SHADER)
# pragma pop_macro("ReferencedByVertexShader")
# else
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByVertexShader, GL_REFERENCED_BY_VERTEX_SHADER)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_REFERENCED_BY_TESS_CONTROL_SHADER
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined ReferencedByTessControlShader
# pragma push_macro("ReferencedByTessControlShader")
# undef ReferencedByTessControlShader
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByTessControlShader, GL_REFERENCED_BY_TESS_CONTROL_SHADER)
# pragma pop_macro("ReferencedByTessControlShader")
# else
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByTessControlShader, GL_REFERENCED_BY_TESS_CONTROL_SHADER)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_REFERENCED_BY_TESS_EVALUATION_SHADER
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined ReferencedByTessEvaluationShader
# pragma push_macro("ReferencedByTessEvaluationShader")
# undef ReferencedByTessEvaluationShader
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByTessEvaluationShader, GL_REFERENCED_BY_TESS_EVALUATION_SHADER)
# pragma pop_macro("ReferencedByTessEvaluationShader")
# else
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByTessEvaluationShader, GL_REFERENCED_BY_TESS_EVALUATION_SHADER)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_REFERENCED_BY_GEOMETRY_SHADER
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined ReferencedByGeometryShader
# pragma push_macro("ReferencedByGeometryShader")
# undef ReferencedByGeometryShader
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByGeometryShader, GL_REFERENCED_BY_GEOMETRY_SHADER)
# pragma pop_macro("ReferencedByGeometryShader")
# else
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByGeometryShader, GL_REFERENCED_BY_GEOMETRY_SHADER)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_REFERENCED_BY_FRAGMENT_SHADER
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined ReferencedByFragmentShader
# pragma push_macro("ReferencedByFragmentShader")
# undef ReferencedByFragmentShader
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByFragmentShader, GL_REFERENCED_BY_FRAGMENT_SHADER)
# pragma pop_macro("ReferencedByFragmentShader")
# else
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByFragmentShader, GL_REFERENCED_BY_FRAGMENT_SHADER)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_REFERENCED_BY_COMPUTE_SHADER
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined ReferencedByComputeShader
# pragma push_macro("ReferencedByComputeShader")
# undef ReferencedByComputeShader
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByComputeShader, GL_REFERENCED_BY_COMPUTE_SHADER)
# pragma pop_macro("ReferencedByComputeShader")
# else
OGLPLUS_ENUM_CLASS_VALUE(ReferencedByComputeShader, GL_REFERENCED_BY_COMPUTE_SHADER)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_NUM_COMPATIBLE_SUBROUTINES
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined NumCompatibleSubroutines
# pragma push_macro("NumCompatibleSubroutines")
# undef NumCompatibleSubroutines
OGLPLUS_ENUM_CLASS_VALUE(NumCompatibleSubroutines, GL_NUM_COMPATIBLE_SUBROUTINES)
# pragma pop_macro("NumCompatibleSubroutines")
# else
OGLPLUS_ENUM_CLASS_VALUE(NumCompatibleSubroutines, GL_NUM_COMPATIBLE_SUBROUTINES)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_COMPATIBLE_SUBROUTINES
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined CompatibleSubroutines
# pragma push_macro("CompatibleSubroutines")
# undef CompatibleSubroutines
OGLPLUS_ENUM_CLASS_VALUE(CompatibleSubroutines, GL_COMPATIBLE_SUBROUTINES)
# pragma pop_macro("CompatibleSubroutines")
# else
OGLPLUS_ENUM_CLASS_VALUE(CompatibleSubroutines, GL_COMPATIBLE_SUBROUTINES)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_TOP_LEVEL_ARRAY_SIZE
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined TopLevelArraySize
# pragma push_macro("TopLevelArraySize")
# undef TopLevelArraySize
OGLPLUS_ENUM_CLASS_VALUE(TopLevelArraySize, GL_TOP_LEVEL_ARRAY_SIZE)
# pragma pop_macro("TopLevelArraySize")
# else
OGLPLUS_ENUM_CLASS_VALUE(TopLevelArraySize, GL_TOP_LEVEL_ARRAY_SIZE)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_TOP_LEVEL_ARRAY_STRIDE
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined TopLevelArrayStride
# pragma push_macro("TopLevelArrayStride")
# undef TopLevelArrayStride
OGLPLUS_ENUM_CLASS_VALUE(TopLevelArrayStride, GL_TOP_LEVEL_ARRAY_STRIDE)
# pragma pop_macro("TopLevelArrayStride")
# else
OGLPLUS_ENUM_CLASS_VALUE(TopLevelArrayStride, GL_TOP_LEVEL_ARRAY_STRIDE)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_LOCATION
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined Location
# pragma push_macro("Location")
# undef Location
OGLPLUS_ENUM_CLASS_VALUE(Location, GL_LOCATION)
# pragma pop_macro("Location")
# else
OGLPLUS_ENUM_CLASS_VALUE(Location, GL_LOCATION)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_LOCATION_INDEX
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined LocationIndex
# pragma push_macro("LocationIndex")
# undef LocationIndex
OGLPLUS_ENUM_CLASS_VALUE(LocationIndex, GL_LOCATION_INDEX)
# pragma pop_macro("LocationIndex")
# else
OGLPLUS_ENUM_CLASS_VALUE(LocationIndex, GL_LOCATION_INDEX)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_LOCATION_COMPONENT
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined LocationComponent
# pragma push_macro("LocationComponent")
# undef LocationComponent
OGLPLUS_ENUM_CLASS_VALUE(LocationComponent, GL_LOCATION_COMPONENT)
# pragma pop_macro("LocationComponent")
# else
OGLPLUS_ENUM_CLASS_VALUE(LocationComponent, GL_LOCATION_COMPONENT)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_IS_PER_PATCH
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined IsPerPatch
# pragma push_macro("IsPerPatch")
# undef IsPerPatch
OGLPLUS_ENUM_CLASS_VALUE(IsPerPatch, GL_IS_PER_PATCH)
# pragma pop_macro("IsPerPatch")
# else
OGLPLUS_ENUM_CLASS_VALUE(IsPerPatch, GL_IS_PER_PATCH)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_TRANSFORM_FEEDBACK_BUFFER_INDEX
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined TransformFeedbackBufferIndex
# pragma push_macro("TransformFeedbackBufferIndex")
# undef TransformFeedbackBufferIndex
OGLPLUS_ENUM_CLASS_VALUE(TransformFeedbackBufferIndex, GL_TRANSFORM_FEEDBACK_BUFFER_INDEX)
# pragma pop_macro("TransformFeedbackBufferIndex")
# else
OGLPLUS_ENUM_CLASS_VALUE(TransformFeedbackBufferIndex, GL_TRANSFORM_FEEDBACK_BUFFER_INDEX)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE
# if OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined TransformFeedbackBufferStride
# pragma push_macro("TransformFeedbackBufferStride")
# undef TransformFeedbackBufferStride
OGLPLUS_ENUM_CLASS_VALUE(TransformFeedbackBufferStride, GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE)
# pragma pop_macro("TransformFeedbackBufferStride")
# else
OGLPLUS_ENUM_CLASS_VALUE(TransformFeedbackBufferStride, GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#ifdef OGLPLUS_LIST_NEEDS_COMMA
# undef OGLPLUS_LIST_NEEDS_COMMA
#endif
| 30.926991
| 102
| 0.836183
|
Simmesimme
|
17185798c1d139c484a0bd0d07f22bbbca372dd9
| 639
|
cpp
|
C++
|
chapter04/example4_01.cpp
|
ly-mem-thread/multi_threading
|
284a0c4ae9c7f8e9ba1faa205fb0e6d634d653cb
|
[
"MIT"
] | 213
|
2018-06-23T04:23:12.000Z
|
2022-03-22T09:01:17.000Z
|
chapter04/example4_01.cpp
|
ZhangChiABC/multi_threading
|
284a0c4ae9c7f8e9ba1faa205fb0e6d634d653cb
|
[
"MIT"
] | null | null | null |
chapter04/example4_01.cpp
|
ZhangChiABC/multi_threading
|
284a0c4ae9c7f8e9ba1faa205fb0e6d634d653cb
|
[
"MIT"
] | 101
|
2018-06-29T09:17:00.000Z
|
2022-03-29T09:55:52.000Z
|
//清单4.1 使用std::condition_variable等待数据
std::mutex mut;
std::queue<data_chunk> data_queue;
std::condition_variable data_cond;
void data_preparation_thread()
{
while(more_data_to_prepare())
{
data_chunk const data=prepare_data();
std::lock_guard<std::mutex> lk(mut);
data_queue.push(data);
data_cond.notify_one();
}
}
void data_processing_thread()
{
while(true)
{
std::unique_lock<std::mutex> lk(mut);
//lambda函数编写一个匿名函数作为表达式的一部分,[]作为其引导符
data_cond.wait(lk,[]{return !data_queue.empty();});
data_chunk data=data_queue.front();
data_queue.pop();
lk.unlock();
process(data);
if(is_last_chunk(data))
break;
}
}
| 20.612903
| 53
| 0.719875
|
ly-mem-thread
|
171a2f6a5a3f258ce197fcd6196a9ecd9e67f719
| 6,725
|
cpp
|
C++
|
src/minimizerdownhillsimplex.cpp
|
virtmax/NucMath
|
b2030c19594f3efb9923380fd410870983a0c17a
|
[
"MIT"
] | null | null | null |
src/minimizerdownhillsimplex.cpp
|
virtmax/NucMath
|
b2030c19594f3efb9923380fd410870983a0c17a
|
[
"MIT"
] | null | null | null |
src/minimizerdownhillsimplex.cpp
|
virtmax/NucMath
|
b2030c19594f3efb9923380fd410870983a0c17a
|
[
"MIT"
] | null | null | null |
#include "minimizerdownhillsimplex.h"
nucmath::OPTIMIZER_RETURN_TYPE nucmath::downhill_simplex_optimization(FUNC2MIN opt_func,
const std::vector< std::array<double,3> > &initial_p,
std::vector<double> &result_p,
double tolerance,
size_t max_interations,
size_t number_of_seed_points
)
{
const size_t N = initial_p.size();
const size_t NP = N + 1;
const double a = 1.0, b = 2.0, c = 0.5, d = 0.5;
//const double double_max = std::numeric_limits<double>::max();
OPTIMIZER_RETURN_TYPE ret;
// internal function used to set a proposed optimization point back into the constrained region.
std::function<void (std::vector<double> &)> considerConstrains =
[&](std::vector<double> &p)
{
for(size_t j = 0; j < N; j++)
{
if(p[j] > initial_p[j][2])
{
p[j] = initial_p[j][2];
}
if(p[j] < initial_p[j][1])
{
p[j] = initial_p[j][1];
}
}
};
/*
std::vector<optPoint> trusted_region_points; // only points with "fp < bestpoint.fp+9"
std::function<void (optPoint &)> saveTrustedPoints =
[&](optPoint &p)
{
if(trusted_region_points.size()==0 || (p.fp < trusted_region_points.at(0).fp + 9))
{
trusted_region_points.push_back(p);
std::sort(trusted_region_points.begin(), trusted_region_points.end());
for(auto it = trusted_region_points.crbegin(); it != trusted_region_points.crend(); it++)
{
if((*it).fp > trusted_region_points.at(0).fp + 9)
{
trusted_region_points.erase(trusted_region_points.begin());
it = trusted_region_points.crbegin();
}
else
break;
}
}
};
*/
std::vector<optPoint> points;
for(size_t i= 0; i < NP; i++)
points.push_back(optPoint(N));
result_p.clear();
result_p.resize(N, 0);
optPoint x0(N); // centroid
optPoint xr(N); // reflected point
optPoint xe(N); // expanded point
optPoint xc(N); // contracted point
std::vector<double> start_p;
for(size_t i= 0; i < initial_p.size(); i++)
{
start_p.push_back(initial_p[i][0]);
}
unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 rand_gen(seed1);
// Generate initial points
// take the start point
points[0].p = start_p;
points[0].fp = opt_func(start_p);
// create at least 5 points per parameter
if(number_of_seed_points < NP*5)
number_of_seed_points = NP*5;
// create initial points on a grid over the parameter space
std::vector<double> initial_points;
initial_points.resize(N);
for(size_t k = 0; k < number_of_seed_points; k++)
{
for(size_t j = 0; j < N; j++)
{
std::uniform_real_distribution<double> flatdist(initial_p[j][1], initial_p[j][2]);
initial_points[j] = flatdist(rand_gen);
}
const double temp_fp = opt_func(initial_points);
if(points[NP-1].fp > temp_fp)
{
points[NP-1].p = initial_points;
points[NP-1].fp = temp_fp;
std::sort(points.begin(), points.end());
}
}
bool done = false;
size_t loop_counter = 0;
while(!done)
{
std::sort(points.begin(), points.end()); // 1 2 3 4 5
// calculate the centroid except the worst
x0.p = std::vector<double>(N, 0);
for(size_t i = 0; i < N; i++)
{
for(size_t p = 0; p < N; p++)
{
x0.p[i] += points[p].p[i];
}
x0.p[i] /= static_cast<double>(N);
}
// calculate reflected point xr = x0 + a(x0-xWorst)
for(size_t j = 0; j < N; j++)
{
xr.p[j] = x0.p[j] + a*(x0.p[j] - points[NP-1].p[j]);
}
considerConstrains(xr.p);
xr.fp = opt_func(xr.p);
if(xr.fp < points[0].fp) // reflected point is the best one -> expansion
{
// calculate expaned point
for(size_t j = 0; j < N; j++)
{
xe.p[j] = x0.p[j] + b*(xr.p[j] - x0.p[j]);
}
considerConstrains(xe.p);
xe.fp = opt_func(xe.p);
// replace the worst point with a better one and repeat the algorithm
if(xe.fp < xr.fp)
points[N] = xe;
else
points[N] = xr;
}
else if(xr.fp < points[N].fp) // good direction -> repeat
{
points[N] = xr;
}
else
{
if(xr.fp < points[N].fp)
points[N] = xr;
// calculate contracted point xc = x0 + a(x0-xWorst)
for (size_t j = 0; j < N; j++)
{
xc.p[j] = x0.p[j] + c*(points[N].p[j] - x0.p[j]);
}
considerConstrains(xc.p);
xc.fp = opt_func(xc.p);
if(xc.fp < points[N].fp)
{
points[N] = xc;
}
else // -> shrink
{
for(size_t i = 1; i < NP; i++)
{
for(size_t j = 0; j < N; j++)
{
points[i].p[j] = points[0].p[j] + d*(points[i].p[j] - points[0].p[j]);
}
considerConstrains(points[i].p);
points[i].fp = opt_func(points[i].p);
}
}
}
// search stop, if to many iterations
loop_counter++;
if(loop_counter == max_interations)
{
done = true;
ret = OPTIMIZER_RETURN_TYPE::MaxIterations;
}
// Termination criterion for tolerance
// tolerance > Standard deviation around the current best optimization point?
double fbar = 0;
for(size_t i = 0; i < N; i++)
{
fbar += points[i].fp;
}
fbar /= static_cast<double>(N);
double dhs_tol = 0;
for(size_t i = 0; i < N; i++)
{
dhs_tol += (points[i].fp-fbar)*(points[i].fp-fbar);
}
dhs_tol /= static_cast<double>(N);
if(sqrt(dhs_tol) < tolerance)
{
done = true;
ret = OPTIMIZER_RETURN_TYPE::ToleranceReached;
}
}
result_p = points[0].p;
return ret;
}
| 29.23913
| 101
| 0.477918
|
virtmax
|
171aefaee15b1ae37a501fa634159acb353a964d
| 14,467
|
cc
|
C++
|
src/xzero/http/http2/FrameGenerator.cc
|
pjsaksa/x0
|
96b69e5a54b006e3d929b9934c2708f7967371bb
|
[
"MIT"
] | 24
|
2016-07-10T08:05:11.000Z
|
2021-11-16T10:53:48.000Z
|
src/xzero/http/http2/FrameGenerator.cc
|
pjsaksa/x0
|
96b69e5a54b006e3d929b9934c2708f7967371bb
|
[
"MIT"
] | 14
|
2015-04-12T10:45:26.000Z
|
2016-06-28T22:27:50.000Z
|
src/xzero/http/http2/FrameGenerator.cc
|
pjsaksa/x0
|
96b69e5a54b006e3d929b9934c2708f7967371bb
|
[
"MIT"
] | 4
|
2016-10-05T17:51:38.000Z
|
2020-04-20T07:45:23.000Z
|
// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2018 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/http/http2/FrameGenerator.h>
#include <xzero/http/http2/SettingParameter.h>
#include <xzero/http/HttpRequestInfo.h>
#include <xzero/http/HeaderFieldList.h>
#include <xzero/http/HeaderField.h>
#include <xzero/io/DataChain.h>
#include <xzero/Buffer.h>
#include <xzero/logging.h>
#include <assert.h>
namespace xzero::http::http2 {
constexpr size_t FrameHeaderSize = 9;
constexpr size_t InitialHeaderTableSize = 4096;
//constexpr size_t InitialMaxConcurrentStreams = 0x7fffffff; // (infinite)
//constexpr size_t InitialWindowSize = 65535;
constexpr size_t InitialMaxFrameSize = 16384;
constexpr size_t InitialMaxHeaderListSize = 0x7fffffff; // (infinite)
FrameGenerator::FrameGenerator(DataChain* sink)
: FrameGenerator(sink,
InitialMaxFrameSize,
InitialHeaderTableSize,
InitialMaxHeaderListSize) {
}
FrameGenerator::FrameGenerator(DataChain* sink,
size_t maxFrameSize,
size_t headerTableSize,
size_t maxHeaderListSize)
: sink_(sink),
maxFrameSize_(maxFrameSize),
headerGenerator_(headerTableSize/*TODO: solve this, maxHeaderListSize*/) {
assert(maxFrameSize_ > FrameHeaderSize + 1);
}
void FrameGenerator::setMaxFrameSize(size_t value) {
value = std::max(value, static_cast<size_t>(16384));
maxFrameSize_ = value;
}
void FrameGenerator::generateClientConnectionPreface() {
sink_->write("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
}
void FrameGenerator::generateData(StreamID sid, const BufferRef& data, bool last) {
/*
* +---------------+
* |Pad Length? (8)|
* +-+-------------+-----------------------------------------------+
* |E| Stream Dependency? (31) |
* +-+-------------+-----------------------------------------------+
* | Weight? (8) |
* +-+-------------+-----------------------------------------------+
* | Header Block Fragment (*) ...
* +---------------------------------------------------------------+
* | Padding (*) ...
* +---------------------------------------------------------------+
*/
assert(sid != 0);
constexpr unsigned END_STREAM = 0x01;
//constexpr unsigned PADDED = 0x08;
const size_t maxPayloadSize = maxFrameSize();
size_t offset = 0;
for (;;) {
const size_t remainingDataSize = data.size() - offset;
const size_t payloadSize = std::min(remainingDataSize, maxPayloadSize);
const unsigned flags = !last && payloadSize < remainingDataSize
? 0
: END_STREAM;
generateFrameHeader(FrameType::Data, flags, sid, payloadSize);
sink_->write(data.ref(offset, payloadSize));
offset += payloadSize;
if (offset == data.size())
break;
}
}
void FrameGenerator::generateHeaders(StreamID sid, const HeaderFieldList& headers,
bool last) {
StreamID dependsOnSID = 0;
bool isExclusive = false;
uint8_t weight = 0;
generateHeaders(sid, headers, last, dependsOnSID, isExclusive, weight);
}
void FrameGenerator::generateHeaders(StreamID sid, const HeaderFieldList& headers,
StreamID dependsOnSID,
bool isExclusive,
uint8_t weight,
bool last) {
/* +---------------+
* |Pad Length? (8)|
* +-+-------------+-----------------------------------------------+
* |E| Stream Dependency? (31) |
* +-+-------------+-----------------------------------------------+
* | Weight? (8) |
* +-+-------------+-----------------------------------------------+
* | Header Block Fragment (*) ...
* +---------------------------------------------------------------+
* | Padding (*) ...
* +---------------------------------------------------------------+
*/
constexpr unsigned END_STREAM = 0x01;
constexpr unsigned END_HEADERS = 0x04;
//constexpr unsigned PADDED = 0x08;
constexpr unsigned PRIORITY = 0x20;
assert(sid != 0);
headerGenerator_.clear();
for (const HeaderField& field: headers)
headerGenerator_.generateHeader(field.name(), field.value(),
field.isSensitive());
const BufferRef& payload = headerGenerator_.headerBlock();
unsigned flags = 0;
if (last)
flags |= END_STREAM;
if (dependsOnSID)
flags |= PRIORITY;
if (payload.size() <= maxFrameSize_) {
flags |= END_HEADERS;
generateFrameHeader(FrameType::Headers, flags, sid, payload.size());
if (dependsOnSID) {
if (isExclusive)
write32(dependsOnSID | (1 << 31));
else
write32(dependsOnSID & ~(1 << 31));
write8(weight);
}
} else {
generateFrameHeader(FrameType::Headers, flags, sid, maxFrameSize_);
if (dependsOnSID) {
if (isExclusive)
write32(dependsOnSID | (1 << 31));
else
write32(dependsOnSID & ~(1 << 31));
write8(weight);
}
sink_->write(payload.ref(0, maxFrameSize_));
generateContinuations(sid, payload.ref(maxFrameSize_));
}
}
void FrameGenerator::generatePriority(StreamID sid, bool exclusive,
StreamID dependantStreamID, unsigned weight) {
/*
* +-+-------------------------------------------------------------+
* |E| Stream Dependency (31) |
* +-+-------------+-----------------------------------------------+
* | Weight (8) |
* +-+-------------+
*/
assert(1 <= weight && weight <= 256);
assert(sid != 0);
generateFrameHeader(FrameType::Priority, 0, sid, 5);
write32(dependantStreamID | (exclusive ? (1 << 31) : 0)); // bit 31 is the Exclusive-bit
write8(weight - 1);
}
void FrameGenerator::generateResetStream(StreamID sid, ErrorCode errorCode) {
/*
* +---------------------------------------------------------------+
* | Error Code (32) |
* +---------------------------------------------------------------+
*/
const unsigned flags = 0;
const uint32_t payload = static_cast<uint32_t>(errorCode);
generateFrameHeader(FrameType::ResetStream, flags, sid, sizeof(payload));
write32(payload);
}
void FrameGenerator::generateSettings(
const std::vector<std::pair<SettingParameter, unsigned>>& settings) {
/* a multiple of:
*
* +-------------------------------+
* | Identifier (16) |
* +-------------------------------+-------------------------------+
* | Value (32) |
* +---------------------------------------------------------------+
*/
const size_t payloadSize = settings.size() * 6;
generateFrameHeader(FrameType::Settings, 0, 0, payloadSize);
for (const auto& param: settings) {
write16(static_cast<unsigned>(param.first));
write32(static_cast<unsigned>(param.second));
}
}
void FrameGenerator::generateSettingsAck() {
constexpr unsigned ACK = 0x01;
generateFrameHeader(FrameType::Settings, ACK, 0, 0);
}
void FrameGenerator::generatePushPromise(StreamID sid, StreamID psid,
const HttpRequestInfo& info) {
/*
* +---------------+
* |Pad Length? (8)|
* +-+-------------+-----------------------------------------------+
* |R| Promised Stream ID (31) |
* +-+-----------------------------+-------------------------------+
* | Header Block Fragment (*) ...
* +---------------------------------------------------------------+
* | Padding (*) ...
* +---------------------------------------------------------------+
*/
static constexpr unsigned END_HEADERS = 0x04;
// static constexpr unsigned PADDED = 0x08;
headerGenerator_.clear();
headerGenerator_.generateHeader(":method", info.unparsedMethod());
headerGenerator_.generateHeader(":path", info.path());
headerGenerator_.generateHeader(":scheme", info.scheme());
headerGenerator_.generateHeader(":authority", info.authority());
for (const HeaderField& field: info.headers()) {
if (field.name().empty() || field.name()[0] == ':')
continue;
headerGenerator_.generateHeader(field.name(), field.value(),
field.isSensitive());
}
const BufferRef& payload = headerGenerator_.headerBlock();
if (payload.size() <= maxFrameSize_) {
generateFrameHeader(FrameType::PushPromise, END_HEADERS, sid, payload.size());
write32(psid & ~(1 << 31)); // promised id with R-flag cleared.
sink_->write(payload);
} else {
generateFrameHeader(FrameType::PushPromise, 0, sid, maxFrameSize_);
sink_->write(payload.ref(0, maxFrameSize_));
generateContinuations(sid, payload.ref(maxFrameSize_));
}
}
void FrameGenerator::generateContinuations(StreamID sid, const BufferRef& payload) {
static constexpr unsigned END_HEADERS = 0x04;
auto pos = payload.data();
size_t count = payload.size();
// any middle-CONTINUATION frames
while (count > maxFrameSize_) {
generateFrameHeader(FrameType::Continuation, 0, sid, maxFrameSize_);
sink_->write(pos, maxFrameSize_);
count -= maxFrameSize_;
pos += maxFrameSize_;
}
// last CONTINUATION frame
generateFrameHeader(FrameType::Continuation, END_HEADERS, sid, count);
sink_->write(pos, count);
}
void FrameGenerator::generatePing(uint64_t payload) {
/*
* +---------------------------------------------------------------+
* | Opaque Data (64) |
* +---------------------------------------------------------------+
*/
generateFrameHeader(FrameType::Ping, 0, 0, 8);
write64(payload);
}
void FrameGenerator::generatePing(const BufferRef& payload) {
/*
* +---------------------------------------------------------------+
* | Opaque Data (64) |
* +---------------------------------------------------------------+
*/
assert(payload.size() == 8);
generateFrameHeader(FrameType::Ping, 0, 0, 8);
sink_->write(payload);
}
void FrameGenerator::generatePingAck(const BufferRef& payload) {
/*
* +---------------------------------------------------------------+
* | Opaque Data (64) |
* +---------------------------------------------------------------+
*/
assert(payload.size() == 8);
static constexpr unsigned ACK = 0x01;
generateFrameHeader(FrameType::Ping, ACK, 0, 8);
sink_->write(payload);
}
void FrameGenerator::generatePingAck(uint64_t payload) {
/*
* +---------------------------------------------------------------+
* | Opaque Data (64) |
* +---------------------------------------------------------------+
*/
static constexpr unsigned ACK = 0x01;
generateFrameHeader(FrameType::Ping, ACK, 0, 8);
write64(payload);
}
void FrameGenerator::generateGoAway(StreamID lastStreamID,
ErrorCode errorCode,
const BufferRef& debugData) {
/*
* +-+-------------------------------------------------------------+
* |R| Last-Stream-ID (31) |
* +-+-------------------------------------------------------------+
* | Error Code (32) |
* +---------------------------------------------------------------+
* | Additional Debug Data (*) |
* +---------------------------------------------------------------+
*/
const size_t debugDataSize = std::min(maxFrameSize() - 8, debugData.size());
assert(lastStreamID != 0);
generateFrameHeader(FrameType::GoAway, 0, lastStreamID, debugDataSize + 8);
write32(lastStreamID & ~(1 << 31)); // R-bit cleared out
write32(static_cast<uint32_t>(errorCode));
sink_->write(debugData.data(), debugDataSize);
}
void FrameGenerator::generateWindowUpdate(StreamID sid, size_t size) {
/*
* +-+-------------------------------------------------------------+
* |R| Window Size Increment (31) |
* +-+-------------------------------------------------------------+
*/
assert(size >= 1 && size <= 0x7fffffffllu); // between 1 and 2^31
generateFrameHeader(FrameType::WindowUpdate, 0, sid, 4);
write32(size & ~(1 << 31)); // R-bit cleared out
}
void FrameGenerator::generateFrameHeader(FrameType frameType, unsigned frameFlags,
StreamID streamID, size_t payloadSize) {
/*
* +-----------------------------------------------+
* | Length (24) |
* +---------------+---------------+---------------+
* | Type (8) | Flags (8) |
* +-+-------------+---------------+-------------------------------+
* |R| Stream Identifier (31) |
* +=+=============================================================+
* | Frame Payload (0...) ...
* +---------------------------------------------------------------+
*/
write24(payloadSize);
write8((unsigned) frameType);
write8(frameFlags);
write32(streamID & ~(1 << 31)); // XXX bit 31 is cleared out (reserved)
}
void FrameGenerator::write8(unsigned value) {
sink_->write8(value);
}
void FrameGenerator::write16(unsigned value) {
sink_->write16(value);
}
void FrameGenerator::write24(unsigned value) {
sink_->write24(value);
}
void FrameGenerator::write32(unsigned value) {
sink_->write32(value);
}
void FrameGenerator::write64(uint64_t value) {
sink_->write64(value);
}
} // namespace xzero::http::http2
| 35.114078
| 90
| 0.475496
|
pjsaksa
|
171af1d4a20a3a7a2c9a26d94113ee8330bc7630
| 3,825
|
cpp
|
C++
|
groups/bsl/bslmt/bslmt_turnstile.cpp
|
hughesr/bde
|
d593e3213918b9292c25e08cfc5b6651bacdea0d
|
[
"Apache-2.0"
] | 1
|
2019-01-22T19:44:05.000Z
|
2019-01-22T19:44:05.000Z
|
groups/bsl/bslmt/bslmt_turnstile.cpp
|
anuranrc/bde
|
d593e3213918b9292c25e08cfc5b6651bacdea0d
|
[
"Apache-2.0"
] | null | null | null |
groups/bsl/bslmt/bslmt_turnstile.cpp
|
anuranrc/bde
|
d593e3213918b9292c25e08cfc5b6651bacdea0d
|
[
"Apache-2.0"
] | null | null | null |
// bslmt_turnstile.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <bslmt_turnstile.h>
#include <bslmt_barrier.h> // testing only
#include <bslmt_mutex.h> // testing only
#include <bslmt_threadutil.h>
#include <bsls_systemtime.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bslmt_turnstile_cpp,"$Id$ $CSID$")
namespace BloombergLP {
namespace {
enum { k_MICROSECS_PER_SECOND = 1000 * 1000 };
} // close unnamed namespace
// ---------------
// class Turnstile
// ---------------
// CREATORS
bslmt::Turnstile::Turnstile(double rate, const bsls::TimeInterval& startTime)
{
reset(rate, startTime);
}
// MANIPULATORS
void bslmt::Turnstile::reset(double rate, const bsls::TimeInterval& startTime)
{
d_interval = static_cast<Int64>(k_MICROSECS_PER_SECOND / rate);
d_timestamp = bsls::SystemTime::nowMonotonicClock().totalMicroseconds();
d_nextTurn = d_timestamp + startTime.totalMicroseconds();
}
bsls::Types::Int64 bslmt::Turnstile::waitTurn()
{
enum { k_MIN_TIMER_RESOLUTION = 10 * 1000 };
// Assume that minimum timer resolution applicable to "sleep" on all
// supported platforms is 10 milliseconds.
Int64 timestamp = d_timestamp;
Int64 interval = d_interval;
Int64 nextTurn = d_nextTurn.add(interval) - interval;
Int64 waitTime = 0;
if (nextTurn > timestamp) {
Int64 nowUSec =
bsls::SystemTime::nowMonotonicClock().totalMicroseconds();
d_timestamp = nowUSec;
waitTime = nextTurn - nowUSec;
if (waitTime >= k_MIN_TIMER_RESOLUTION) {
int waitInt = static_cast<int>(waitTime);
if (waitInt == waitTime) {
// This is only good up to 'waitTime == ~35 minutes'
ThreadUtil::microSleep(waitInt);
}
else {
// This will work so long as 'waitTime < ~68 years'
int waitSecs = static_cast<int>((waitTime
/ k_MICROSECS_PER_SECOND));
int waitUSecs = static_cast<int>((waitTime
% k_MICROSECS_PER_SECOND));
ThreadUtil::microSleep(waitUSecs, waitSecs);
}
}
else {
waitTime = 0;
}
}
return waitTime;
}
// ACCESSORS
bsls::Types::Int64 bslmt::Turnstile::lagTime() const
{
Int64 nowUSecs = bsls::SystemTime::nowMonotonicClock().totalMicroseconds();
d_timestamp = nowUSecs;
Int64 delta = nowUSecs - d_nextTurn;
return delta > 0 ? delta : 0;
}
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 32.974138
| 79
| 0.556601
|
hughesr
|
171f0ce2e4dd46b1c7326d69ecc53c3bced40a34
| 1,289
|
hpp
|
C++
|
src/Utilities/ThreadSafeQueue.hpp
|
ClubieDong/BoardGameAI
|
588506278f606fa6bef2864875bf8f78557ef03b
|
[
"MIT"
] | 2
|
2021-05-26T07:17:24.000Z
|
2021-05-26T07:21:16.000Z
|
src/Utilities/ThreadSafeQueue.hpp
|
ClubieDong/ChessAI
|
588506278f606fa6bef2864875bf8f78557ef03b
|
[
"MIT"
] | null | null | null |
src/Utilities/ThreadSafeQueue.hpp
|
ClubieDong/ChessAI
|
588506278f606fa6bef2864875bf8f78557ef03b
|
[
"MIT"
] | null | null | null |
#pragma once
#include <queue>
#include <mutex>
#include <condition_variable>
#include <deque>
template <typename T>
class ThreadSafeQueue
{
private:
std::queue<T> _Queue;
mutable std::mutex _Mtx;
std::condition_variable _CV;
public:
inline explicit ThreadSafeQueue() = default;
ThreadSafeQueue(const ThreadSafeQueue &) = delete;
ThreadSafeQueue &operator=(const ThreadSafeQueue &) = delete;
ThreadSafeQueue(ThreadSafeQueue &&obj) = delete;
ThreadSafeQueue &operator=(ThreadSafeQueue &&obj) = delete;
inline void Push(const T &value)
{
std::lock_guard<std::mutex> lock(_Mtx);
_Queue.push(value);
_CV.notify_one();
}
inline void Push(T &&value)
{
std::lock_guard<std::mutex> lock(_Mtx);
_Queue.push(std::move(value));
_CV.notify_one();
}
inline T Pop()
{
std::unique_lock<std::mutex> lock(_Mtx);
while (_Queue.empty())
_CV.wait(lock);
T front = std::move(_Queue.front());
_Queue.pop();
return front;
}
inline typename std::queue<T>::size_type GetSize() const
{
std::lock_guard<std::mutex> lock(_Mtx);
return _Queue.size();
}
inline bool IsEmpty() const { return GetSize() == 0; }
};
| 23.436364
| 65
| 0.615206
|
ClubieDong
|
17318280684ca9ebfb55e551db233d6f720c048c
| 2,321
|
inl
|
C++
|
src/ScriptSystem/Init/details/UECS_AutoRefl/World_AutoRefl.inl
|
Jerry-Shen0527/Utopia
|
5f40edc814e5f6a33957cdc889524c41c5ef870f
|
[
"MIT"
] | 321
|
2020-10-04T01:43:36.000Z
|
2022-03-31T02:43:38.000Z
|
src/ScriptSystem/Init/details/UECS_AutoRefl/World_AutoRefl.inl
|
Jerry-Shen0527/Utopia
|
5f40edc814e5f6a33957cdc889524c41c5ef870f
|
[
"MIT"
] | 9
|
2020-11-17T04:06:22.000Z
|
2022-02-19T09:05:29.000Z
|
src/ScriptSystem/Init/details/UECS_AutoRefl/World_AutoRefl.inl
|
Jerry-Shen0527/Utopia
|
5f40edc814e5f6a33957cdc889524c41c5ef870f
|
[
"MIT"
] | 41
|
2020-10-09T10:09:34.000Z
|
2022-03-27T02:51:57.000Z
|
// This file is generated by Ubpa::USRefl::AutoRefl
#pragma once
#include <USRefl/USRefl.h>
#include <UTemplate/Func.h>
template<>
struct Ubpa::USRefl::TypeInfo<Ubpa::UECS::World> :
TypeInfoBase<Ubpa::UECS::World>
{
#ifdef UBPA_USREFL_NOT_USE_NAMEOF
static constexpr char name[18] = "Ubpa::UECS::World";
#endif
static constexpr AttrList attrs = {};
static constexpr FieldList fields = {
Field {TSTR(UMeta::constructor), WrapConstructor<Type()>()},
Field {TSTR(UMeta::constructor), WrapConstructor<Type(const UECS::World&)>()},
Field {TSTR(UMeta::constructor), WrapConstructor<Type(UECS::World&&)>()},
Field {TSTR(UMeta::destructor), WrapDestructor<Type>()},
Field {TSTR("systemMngr"), &Type::systemMngr},
Field {TSTR("entityMngr"), &Type::entityMngr},
Field {TSTR("Update"), &Type::Update},
Field {TSTR("AddCommand"), &Type::AddCommand, AttrList {
Attr {TSTR(UMeta::default_functions), std::tuple {
[](Type* __this, std::function<void()> command) { return __this->AddCommand(std::forward<std::function<void()>>(command)); }
}},
}},
Field {TSTR("DumpUpdateJobGraph"), &Type::DumpUpdateJobGraph},
Field {TSTR("GenUpdateFrameGraph"), &Type::GenUpdateFrameGraph},
Field {TSTR("Accept"), &Type::Accept},
Field {TSTR("RunEntityJob"), Ubpa::DecayLambda(
[](
Ubpa::UECS::World* world,
std::function<void(
Ubpa::UECS::World*,
Ubpa::UECS::SingletonsView,
Ubpa::UECS::Entity,
size_t,
Ubpa::UECS::CmptsView
)> func,
Ubpa::UECS::ArchetypeFilter archetypeFilter,
Ubpa::UECS::CmptLocator cmptLocator,
Ubpa::UECS::SingletonLocator singletonLocator,
bool isParallel
) {
world->RunEntityJob(
std::move(func),
isParallel,
std::move(archetypeFilter),
std::move(cmptLocator),
std::move(singletonLocator)
);
}
)},
Field {TSTR("RunChunkJob"), Ubpa::DecayLambda(
[](
Ubpa::UECS::World* world,
std::function<void(
Ubpa::UECS::World*,
Ubpa::UECS::ChunkView,
Ubpa::UECS::SingletonsView
)> func,
Ubpa::UECS::ArchetypeFilter archetypeFilter,
Ubpa::UECS::SingletonLocator singletonLocator,
bool isParallel
) {
world->RunChunkJob(
std::move(func),
std::move(archetypeFilter),
isParallel,
std::move(singletonLocator)
);
}
)},
};
};
| 29.75641
| 128
| 0.661784
|
Jerry-Shen0527
|
173884be24274ff18f2e9d4ee4ff81bc407c4045
| 944
|
cpp
|
C++
|
src/Graphics/Transform.cpp
|
ksmai/fire-web-engine
|
531fd3d2ae78244bf2e2a62571ccbcd6e6c2a5bd
|
[
"MIT"
] | null | null | null |
src/Graphics/Transform.cpp
|
ksmai/fire-web-engine
|
531fd3d2ae78244bf2e2a62571ccbcd6e6c2a5bd
|
[
"MIT"
] | null | null | null |
src/Graphics/Transform.cpp
|
ksmai/fire-web-engine
|
531fd3d2ae78244bf2e2a62571ccbcd6e6c2a5bd
|
[
"MIT"
] | null | null | null |
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "Graphics/Transform.h"
FW::Transform::Transform():
matrix{1.0f},
position{0.0f, 0.0f},
size{1.0f, 1.0f},
radians{0.0f},
dirty{false}
{
}
void FW::Transform::translate(float x, float y) {
position.x += x;
position.y += y;
dirty = true;
}
void FW::Transform::scale(float s) {
scale(s, s);
}
void FW::Transform::scale(float x, float y) {
size.x *= x;
size.y *= y;
dirty = true;
}
void FW::Transform::rotate(float r) {
radians += r;
dirty = true;
}
const float* FW::Transform::getMatrix() const {
if (dirty) {
matrix = glm::scale(
glm::rotate(
glm::translate(
glm::mat4{1.0f},
glm::vec3{position.x, position.y, 0.0f}
),
radians,
glm::vec3{0.0f, 0.0f, 1.0f}
),
glm::vec3{size.x, size.y, 1.0f}
);
dirty = false;
}
return glm::value_ptr(matrix);
}
| 18.153846
| 49
| 0.573093
|
ksmai
|
173c3d5bf1bcc534e90c0f0282aa861e72cda919
| 11,864
|
cc
|
C++
|
src/gn/label.cc
|
steezer/gn
|
52e156194f923abf40c2601cbac4dfa3ad988a08
|
[
"BSD-3-Clause"
] | 84
|
2016-05-06T13:13:21.000Z
|
2022-03-15T02:50:59.000Z
|
src/gn/label.cc
|
steezer/gn
|
52e156194f923abf40c2601cbac4dfa3ad988a08
|
[
"BSD-3-Clause"
] | 4
|
2017-09-29T15:16:43.000Z
|
2018-07-24T11:48:30.000Z
|
src/gn/label.cc
|
steezer/gn
|
52e156194f923abf40c2601cbac4dfa3ad988a08
|
[
"BSD-3-Clause"
] | 39
|
2016-08-04T02:24:56.000Z
|
2022-03-02T02:31:42.000Z
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gn/label.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "gn/err.h"
#include "gn/filesystem_utils.h"
#include "gn/parse_tree.h"
#include "gn/value.h"
#include "util/build_config.h"
namespace {
// We print user visible label names with no trailing slash after the
// directory name.
std::string DirWithNoTrailingSlash(const SourceDir& dir) {
// Be careful not to trim if the input is just "/" or "//".
if (dir.value().size() > 2)
return dir.value().substr(0, dir.value().size() - 1);
return dir.value();
}
// Given the separate-out input (everything before the colon) in the dep rule,
// computes the final build rule. Sets err on failure. On success,
// |*used_implicit| will be set to whether the implicit current directory was
// used. The value is used only for generating error messages.
bool ComputeBuildLocationFromDep(const Value& input_value,
const SourceDir& current_dir,
const std::string_view& source_root,
const std::string_view& input,
SourceDir* result,
Err* err) {
// No rule, use the current location.
if (input.empty()) {
*result = current_dir;
return true;
}
*result =
current_dir.ResolveRelativeDir(input_value, input, err, source_root);
return true;
}
// Given the separated-out target name (after the colon) computes the final
// name, using the implicit name from the previously-generated
// computed_location if necessary. The input_value is used only for generating
// error messages.
bool ComputeTargetNameFromDep(const Value& input_value,
const SourceDir& computed_location,
const std::string_view& input,
StringAtom* result,
Err* err) {
if (!input.empty()) {
// Easy case: input is specified, just use it.
*result = StringAtom(input);
return true;
}
const std::string& loc = computed_location.value();
// Use implicit name. The path will be "//", "//base/", "//base/i18n/", etc.
if (loc.size() <= 2) {
*err = Err(input_value, "This dependency name is empty");
return false;
}
size_t next_to_last_slash = loc.rfind('/', loc.size() - 2);
DCHECK(next_to_last_slash != std::string::npos);
*result = StringAtom(std::string_view{&loc[next_to_last_slash + 1],
loc.size() - next_to_last_slash - 2});
return true;
}
// The original value is used only for error reporting, use the |input| as the
// input to this function (which may be a substring of the original value when
// we're parsing toolchains.
//
// If the output toolchain vars are NULL, then we'll report an error if we
// find a toolchain specified (this is used when recursively parsing toolchain
// labels which themselves can't have toolchain specs).
//
// We assume that the output variables are initialized to empty so we don't
// write them unless we need them to contain something.
//
// Returns true on success. On failure, the out* variables might be written to
// but shouldn't be used.
bool Resolve(const SourceDir& current_dir,
const std::string_view& source_root,
const Label& current_toolchain,
const Value& original_value,
const std::string_view& input,
SourceDir* out_dir,
StringAtom* out_name,
SourceDir* out_toolchain_dir,
StringAtom* out_toolchain_name,
Err* err) {
// To workaround the problem that std::string_view operator[] doesn't return a
// ref.
const char* input_str = input.data();
size_t offset = 0;
#if defined(OS_WIN)
if (IsPathAbsolute(input)) {
size_t drive_letter_pos = input[0] == '/' ? 1 : 0;
if (input.size() > drive_letter_pos + 2 &&
input[drive_letter_pos + 1] == ':' &&
IsSlash(input[drive_letter_pos + 2]) &&
base::IsAsciiAlpha(input[drive_letter_pos])) {
// Skip over the drive letter colon.
offset = drive_letter_pos + 2;
}
}
#endif
size_t path_separator = input.find_first_of(":(", offset);
std::string_view location_piece;
std::string_view name_piece;
std::string_view toolchain_piece;
if (path_separator == std::string::npos) {
location_piece = input;
// Leave name & toolchain piece null.
} else {
location_piece = std::string_view(&input_str[0], path_separator);
size_t toolchain_separator = input.find('(', path_separator);
if (toolchain_separator == std::string::npos) {
name_piece = std::string_view(&input_str[path_separator + 1],
input.size() - path_separator - 1);
// Leave location piece null.
} else if (!out_toolchain_dir) {
// Toolchain specified but not allows in this context.
*err =
Err(original_value, "Toolchain has a toolchain.",
"Your toolchain definition (inside the parens) seems to itself "
"have a\ntoolchain. Don't do this.");
return false;
} else {
// Name piece is everything between the two separators. Note that the
// separators may be the same (e.g. "//foo(bar)" which means empty name.
if (toolchain_separator > path_separator) {
name_piece = std::string_view(&input_str[path_separator + 1],
toolchain_separator - path_separator - 1);
}
// Toolchain name should end in a ) and this should be the end of the
// string.
if (input[input.size() - 1] != ')') {
*err =
Err(original_value, "Bad toolchain name.",
"Toolchain name must end in a \")\" at the end of the label.");
return false;
}
// Subtract off the two parens to just get the toolchain name.
toolchain_piece =
std::string_view(&input_str[toolchain_separator + 1],
input.size() - toolchain_separator - 2);
}
}
// Everything before the separator is the filename.
// We allow three cases:
// Absolute: "//foo:bar" -> /foo:bar
// Target in current file: ":foo" -> <currentdir>:foo
// Path with implicit name: "/foo" -> /foo:foo
if (location_piece.empty() && name_piece.empty()) {
// Can't use both implicit filename and name (":").
*err = Err(original_value, "This doesn't specify a dependency.");
return false;
}
if (!ComputeBuildLocationFromDep(original_value, current_dir, source_root,
location_piece, out_dir, err))
return false;
if (!ComputeTargetNameFromDep(original_value, *out_dir, name_piece, out_name,
err))
return false;
// Last, do the toolchains.
if (out_toolchain_dir) {
// Handle empty toolchain strings. We don't allow normal labels to be
// empty so we can't allow the recursive call of this function to do this
// check.
if (toolchain_piece.empty()) {
*out_toolchain_dir = current_toolchain.dir();
*out_toolchain_name = current_toolchain.name_atom();
return true;
} else {
return Resolve(current_dir, source_root, current_toolchain,
original_value, toolchain_piece, out_toolchain_dir,
out_toolchain_name, nullptr, nullptr, err);
}
}
return true;
}
} // namespace
const char kLabels_Help[] =
R"*(About labels
Everything that can participate in the dependency graph (targets, configs,
and toolchains) are identified by labels. A common label looks like:
//base/test:test_support
This consists of a source-root-absolute path, a colon, and a name. This means
to look for the thing named "test_support" in "base/test/BUILD.gn".
You can also specify system absolute paths if necessary. Typically such
paths would be specified via a build arg so the developer can specify where
the component is on their system.
/usr/local/foo:bar (Posix)
/C:/Program Files/MyLibs:bar (Windows)
Toolchains
A canonical label includes the label of the toolchain being used. Normally,
the toolchain label is implicitly inherited from the current execution
context, but you can override this to specify cross-toolchain dependencies:
//base/test:test_support(//build/toolchain/win:msvc)
Here GN will look for the toolchain definition called "msvc" in the file
"//build/toolchain/win" to know how to compile this target.
Relative labels
If you want to refer to something in the same buildfile, you can omit
the path name and just start with a colon. This format is recommended for
all same-file references.
:base
Labels can be specified as being relative to the current directory.
Stylistically, we prefer to use absolute paths for all non-file-local
references unless a build file needs to be run in different contexts (like a
project needs to be both standalone and pulled into other projects in
difference places in the directory hierarchy).
source/plugin:myplugin
../net:url_request
Implicit names
If a name is unspecified, it will inherit the directory name. Stylistically,
we prefer to omit the colon and name when possible:
//net -> //net:net
//tools/gn -> //tools/gn:gn
)*";
Label::Label() : hash_(ComputeHash()) {}
Label::Label(const SourceDir& dir,
const std::string_view& name,
const SourceDir& toolchain_dir,
const std::string_view& toolchain_name)
: dir_(dir),
name_(StringAtom(name)),
toolchain_dir_(toolchain_dir),
toolchain_name_(StringAtom(toolchain_name)),
hash_(ComputeHash()) {}
Label::Label(const SourceDir& dir, const std::string_view& name)
: dir_(dir), name_(StringAtom(name)),
hash_(ComputeHash()) {}
// static
Label Label::Resolve(const SourceDir& current_dir,
const std::string_view& source_root,
const Label& current_toolchain,
const Value& input,
Err* err) {
Label ret;
if (input.type() != Value::STRING) {
*err = Err(input, "Dependency is not a string.");
return ret;
}
const std::string& input_string = input.string_value();
if (input_string.empty()) {
*err = Err(input, "Dependency string is empty.");
return ret;
}
if (!::Resolve(current_dir, source_root, current_toolchain, input,
input_string, &ret.dir_, &ret.name_, &ret.toolchain_dir_,
&ret.toolchain_name_, err))
return Label();
return ret;
}
Label Label::GetToolchainLabel() const {
return Label(toolchain_dir_, toolchain_name_);
}
Label Label::GetWithNoToolchain() const {
return Label(dir_, name_);
}
std::string Label::GetUserVisibleName(bool include_toolchain) const {
std::string ret;
ret.reserve(dir_.value().size() + name_.str().size() + 1);
if (dir_.is_null())
return ret;
ret = DirWithNoTrailingSlash(dir_);
ret.push_back(':');
ret.append(name_.str());
if (include_toolchain) {
ret.push_back('(');
if (!toolchain_dir_.is_null() && !toolchain_name_.empty()) {
ret.append(DirWithNoTrailingSlash(toolchain_dir_));
ret.push_back(':');
ret.append(toolchain_name_.str());
}
ret.push_back(')');
}
return ret;
}
std::string Label::GetUserVisibleName(const Label& default_toolchain) const {
bool include_toolchain = default_toolchain.dir() != toolchain_dir_ ||
default_toolchain.name_atom() != toolchain_name_;
return GetUserVisibleName(include_toolchain);
}
| 35.73494
| 80
| 0.648095
|
steezer
|
173c3f8c61e5896f098f837048f3ed3f6149d40b
| 8,979
|
cpp
|
C++
|
cpp/open3d/visualization/gui/Util.cpp
|
Dudulle/Open3D
|
ffed2d1bee6d45b6acc4b7ae7133752e50d6ecab
|
[
"MIT"
] | 8
|
2021-03-17T14:24:12.000Z
|
2022-03-30T15:35:27.000Z
|
cpp/open3d/visualization/gui/Util.cpp
|
Dudulle/Open3D
|
ffed2d1bee6d45b6acc4b7ae7133752e50d6ecab
|
[
"MIT"
] | 1
|
2021-11-04T09:22:25.000Z
|
2022-02-14T01:32:31.000Z
|
cpp/open3d/visualization/gui/Util.cpp
|
Dudulle/Open3D
|
ffed2d1bee6d45b6acc4b7ae7133752e50d6ecab
|
[
"MIT"
] | 2
|
2021-08-24T18:06:55.000Z
|
2021-12-17T10:48:34.000Z
|
// ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2021 www.open3d.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------------------------------------------------------
#include "open3d/visualization/gui/Util.h"
#include <cmath>
#include "open3d/utility/FileSystem.h"
#include "open3d/visualization/gui/Color.h"
namespace open3d {
namespace visualization {
namespace gui {
ImVec4 colorToImgui(const Color &color) {
return ImVec4(color.GetRed(), color.GetGreen(), color.GetBlue(),
color.GetAlpha());
}
uint32_t colorToImguiRGBA(const Color &color) {
return IM_COL32(int(std::round(255.0f * color.GetRed())),
int(std::round(255.0f * color.GetGreen())),
int(std::round(255.0f * color.GetBlue())),
int(std::round(255.0f * color.GetAlpha())));
}
std::string FindFontPath(std::string font, FontStyle style) {
using namespace open3d::utility::filesystem;
std::vector<std::string> kNormalSuffixes = {
" Regular.ttf", " Regular.ttc", " Regular.otf", " Normal.ttf",
" Normal.ttc", " Normal.otf", " Medium.ttf", " Medium.ttc",
" Medium.otf", " Narrow.ttf", " Narrow.ttc", " Narrow.otf",
"-Regular.ttf", "-Regular.ttc", "-Regular.otf", "-Normal.ttf",
"-Normal.ttc", "-Normal.otf", "-Medium.ttf", "-Medium.ttc",
"-Medium.otf", "-Narrow.ttf", "-Narrow.ttc", "-Narrow.otf",
"Regular.ttf", "-Regular.ttc", "-Regular.otf", "Normal.ttf",
"Normal.ttc", "Normal.otf", "Medium.ttf", "Medium.ttc",
"Medium.otf", "Narrow.ttf", "Narrow.ttc", "Narrow.otf"};
std::vector<std::string> suffixes;
switch (style) {
case FontStyle::NORMAL:
suffixes = kNormalSuffixes;
break;
case FontStyle::BOLD:
suffixes = {
" Bold.ttf",
" Bold.ttc",
" Bold.otf",
"-Bold.ttf",
"-Bold.ttc",
"-Bold.otf",
"Bold.ttf",
"Bold.ttc",
"Bold.oft"
#if _WIN32
,
"b.ttf",
"b.ttc",
"b.otf"
#endif // _WIN32
};
break;
case FontStyle::ITALIC:
suffixes = {
" Italic.ttf",
" Italic.ttc",
" Italic.otf",
"-Italic.ttf",
"-Italic.ttc",
"-Italic.otf",
"Italic.ttf",
"Italic.ttc",
"Italic.otf",
"-MediumItalic.ttf",
"-MediumItalic.ttc",
"-MediumItalic.otf",
"MediumItalic.ttf",
"MediumItalic.ttc",
"MediumItalic.otf",
"-Oblique.ttf",
"-Oblique.ttc",
"-Oblique.otf",
"Oblique.ttf",
"Oblique.ttc",
"Oblique.otf",
"-MediumOblique.ttf",
"-MediumOblique.ttc",
"-MediumOblique.otf",
"MediumOblique.ttf",
"MediumOblique.ttc",
"MediumOblique.otf"
#if _WIN32
,
"i.ttf",
"i.ttc",
"i.otf"
#endif // _WIN32
};
break;
case FontStyle::BOLD_ITALIC:
suffixes = {
" Bold Italic.ttf",
" Bold Italic.ttc",
" Bold Italic.otf",
"-BoldItalic.ttf",
"-BoldItalic.ttc",
"-BoldItalic.otf",
"BoldItalic.ttf",
"BoldItalic.ttc",
"BoldItalic.oft"
#if _WIN32
,
"bi.ttf",
"bi.ttc",
"bi.otf"
#endif // _WIN32
};
break;
}
if (FileExists(font)) {
if (style == FontStyle::NORMAL) {
return font;
} else {
// The user provided an actual font file, not just a
// font name. Since we are looking for bold and/or italic,
// we need to "stem" the font file and attempt to look for
// the bold and/or italicized versions.
for (auto &suf : kNormalSuffixes) {
if (font.rfind(suf) != std::string::npos) {
font = font.substr(0, font.size() - suf.size());
break;
}
}
// The font name doesn't have any of the suffixes,
// so just remove the extension
font = font.substr(0, font.size() - 4);
// Check if any of the stylized suffixes work
for (auto &suf : suffixes) {
std::string candidate = font + suf;
if (FileExists(candidate)) {
return candidate;
}
}
// Otherwise fail
return "";
}
}
std::string home;
char *raw_home = getenv("HOME");
if (raw_home) { // std::string(nullptr) is undefined
home = raw_home;
}
std::vector<std::string> system_font_paths = {
#ifdef __APPLE__
"/System/Library/Fonts", "/Library/Fonts", home + "/Library/Fonts"
#elif _WIN32
"c:/Windows/Fonts"
#else
"/usr/share/fonts",
home + "/.fonts",
#endif // __APPLE__
};
#ifdef __APPLE__
std::vector<std::string> font_ext = {".ttf", ".ttc", ".otf"};
for (auto &font_path : system_font_paths) {
if (style == FontStyle::NORMAL) {
for (auto &ext : font_ext) {
std::string candidate = font_path + "/" + font + ext;
if (FileExists(candidate)) {
return candidate;
}
}
}
}
for (auto &font_path : system_font_paths) {
for (auto &suf : suffixes) {
std::string candidate = font_path + "/" + font + suf;
if (FileExists(candidate)) {
return candidate;
}
}
}
return "";
#else
std::string font_ttf = font + ".ttf";
std::string font_ttc = font + ".ttc";
std::string font_otf = font + ".otf";
auto is_match = [font, &font_ttf, &font_ttc,
&font_otf](const std::string &path) {
auto filename = GetFileNameWithoutDirectory(path);
auto ext = GetFileExtensionInLowerCase(filename);
if (ext != "ttf" && ext != "ttc" && ext != "otf") {
return false;
}
if (filename == font_ttf || filename == font_ttc ||
filename == font_otf) {
return true;
}
if (filename.find(font) == 0) {
return true;
}
return false;
};
for (auto &font_dir : system_font_paths) {
auto matches = FindFilesRecursively(font_dir, is_match);
if (style == FontStyle::NORMAL) {
for (auto &m : matches) {
if (GetFileNameWithoutExtension(
GetFileNameWithoutDirectory(m)) == font) {
return m;
}
}
}
for (auto &m : matches) {
auto dir = GetFileParentDirectory(m); // has trailing slash
for (auto &suf : suffixes) {
std::string candidate = dir + font + suf;
if (m == candidate) {
return candidate;
}
}
}
}
return "";
#endif // __APPLE__
}
} // namespace gui
} // namespace visualization
} // namespace open3d
| 34.402299
| 80
| 0.484798
|
Dudulle
|
173e4f39208ddebd61ff28f5d3ad6e81823bc8a6
| 1,453
|
cpp
|
C++
|
src/trabalho1/Truck.cpp
|
brunosalgado/programacao-avancada
|
6ce270bf2547a7cc5708a859f54d729f4d951cfe
|
[
"MIT"
] | null | null | null |
src/trabalho1/Truck.cpp
|
brunosalgado/programacao-avancada
|
6ce270bf2547a7cc5708a859f54d729f4d951cfe
|
[
"MIT"
] | null | null | null |
src/trabalho1/Truck.cpp
|
brunosalgado/programacao-avancada
|
6ce270bf2547a7cc5708a859f54d729f4d951cfe
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <iomanip>
#include "Truck.h"
Truck::Truck() : _capacity(0.0), _length(0.0), _height(0.0), Vehicle() {}
Truck::Truck(string plate, int weight, int max_kmh, double price, double capacity, double length, double height) :
_capacity(capacity), _length(length), _height(height), Vehicle (plate, weight, max_kmh, price) { }
void Truck::setCapacity(double capacity) {
_capacity = capacity;
}
double Truck::getCapacity() {
return _capacity;
}
void Truck::setLenght(double length) {
_length = length;
}
double Truck::getLenght() {
return _length;
}
void Truck::setHeight(double height) {
_height = height;
}
double Truck::getHeight() {
return _height;
}
void Truck::print() {
cout << "###########################" << endl;
cout << "########## TRUCK ##########" << endl;
cout << "###########################" << endl;
cout << "Plate........: " << _plate << endl;
cout << "Weight.......: " << _weight << " kg" << endl;
cout << "Km/h.........: " << _max_kmh << " km/h" << endl;
cout << fixed << setprecision(2);
cout << "Price........: R$ " << _price << endl;
cout << fixed << setprecision(2);
cout << "Capacity.....: " << _capacity << " tons"<< endl;
cout << fixed << setprecision(2);
cout << "Length.......: " << _length << " meters" << endl;
cout << fixed << setprecision(2);
cout << "Height.......: " << _height << " meters" << endl;
}
| 29.06
| 114
| 0.542326
|
brunosalgado
|
173edb31653bb326be6a4f5701e9d0ea9d668671
| 3,988
|
hpp
|
C++
|
HugeCTR/include/heapex.hpp
|
ethem-kinginthenorth/HugeCTR
|
37bf562f19c5b67d669eb84cb4031c6d766cb166
|
[
"Apache-2.0"
] | 1
|
2020-07-15T07:33:09.000Z
|
2020-07-15T07:33:09.000Z
|
HugeCTR/include/heapex.hpp
|
ethem-kinginthenorth/HugeCTR
|
37bf562f19c5b67d669eb84cb4031c6d766cb166
|
[
"Apache-2.0"
] | null | null | null |
HugeCTR/include/heapex.hpp
|
ethem-kinginthenorth/HugeCTR
|
37bf562f19c5b67d669eb84cb4031c6d766cb166
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2020, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <vector>
#include "HugeCTR/include/common.hpp"
namespace HugeCTR {
/**
* @brief A thread safe heap implementation for multiple reading and writing.
*
* An requirment of HugeCTR is multiple data reading threads for
* the sake of high input throughput. The specific chunk in a heap
* will be locked while it's in use by one of the threads, and will be
* unlocked when it's checkin.
* Note that at most 32 chunks are avaliable for a heap.
*/
template <typename T>
class HeapEx {
private:
unsigned int higher_bits_{0}, lower_bits_{0};
const int num_chunks_;
std::vector<T> chunks_;
std::mutex mtx_;
std::condition_variable write_cv_, read_cv_;
std::atomic<bool> loop_flag_{true};
int count_{0};
public:
/**
* will try to checkout the chunk id%#chunck
* if not avaliable just hold
*/
void free_chunk_checkout(T** chunk, unsigned int id) {
if (chunk == nullptr) {
CK_THROW_(Error_t::WrongInput, "chunk == nullptr");
}
std::unique_lock<std::mutex> lock(mtx_);
int i = id % num_chunks_;
// thread safe start
while (loop_flag_) {
bool avail = ((lower_bits_ & (~higher_bits_)) >> i) & 1;
if (avail) {
lower_bits_ &= (~(1u << i));
*chunk = &chunks_[i];
break;
}
read_cv_.wait(lock);
}
return;
}
/**
* After writting, check in the chunk
*/
void chunk_write_and_checkin(unsigned int id) {
{
std::lock_guard<std::mutex> lock(mtx_);
int i = id % num_chunks_;
// thread safe start
lower_bits_ |= (1u << i);
higher_bits_ |= (1u << i);
// thread safe end
}
write_cv_.notify_all();
return;
}
/**
* Checkout the data with id count_%chunk
* if not avaliable hold
*/
void data_chunk_checkout(T** chunk) {
if (chunk == nullptr) {
CK_THROW_(Error_t::WrongInput, "chunk == nullptr");
}
std::unique_lock<std::mutex> lock(mtx_);
int i = count_;
// thread safe start
while (loop_flag_) {
bool avail = ((lower_bits_ & higher_bits_) >> i) & 1;
if (avail) {
lower_bits_ &= (~(1u << i));
*chunk = &chunks_[i];
break;
}
write_cv_.wait(lock);
}
return;
}
/**
* Free the chunk count_%chunk after using.
*/
void chunk_free_and_checkin() {
{
std::lock_guard<std::mutex> lock(mtx_);
// thread safe start
lower_bits_ |= (1u << count_);
higher_bits_ &= (~(1u << count_));
// thread safe end
}
read_cv_.notify_all();
count_ = (count_ + 1) % num_chunks_;
return;
}
/**
* break the spin lock.
*/
void break_and_return() {
loop_flag_ = false;
write_cv_.notify_all();
read_cv_.notify_all();
return;
}
/**
* Ctor.
* Make "num" copy of the chunks.
*/
template <typename... Args>
HeapEx(int num, Args&&... args) : num_chunks_(num) {
if (num > static_cast<int>(sizeof(unsigned int) * 8)) {
CK_THROW_(Error_t::OutOfBound, "num > sizeof(unsigned int) * 8");
} else if (num <= 0) {
CK_THROW_(Error_t::WrongInput, "num <= 0");
}
for (int i = 0; i < num; i++) {
chunks_.emplace_back(T(std::forward<Args>(args)...));
}
lower_bits_ = (1ull << num) - 1;
}
};
} // namespace HugeCTR
| 25.729032
| 77
| 0.616851
|
ethem-kinginthenorth
|
1740170b90f1f40cc6db661e6533989ab4c9c523
| 5,648
|
cpp
|
C++
|
Assets/FrameCapturer-master/Plugin/fccore/Encoder/Audio/fcFlacContext.cpp
|
Okashiou/VJx
|
491cc37e3d6eddd78e4c99d5f211c5e2b2d498f0
|
[
"MIT"
] | null | null | null |
Assets/FrameCapturer-master/Plugin/fccore/Encoder/Audio/fcFlacContext.cpp
|
Okashiou/VJx
|
491cc37e3d6eddd78e4c99d5f211c5e2b2d498f0
|
[
"MIT"
] | null | null | null |
Assets/FrameCapturer-master/Plugin/fccore/Encoder/Audio/fcFlacContext.cpp
|
Okashiou/VJx
|
491cc37e3d6eddd78e4c99d5f211c5e2b2d498f0
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "fcInternal.h"
#include "Foundation/fcFoundation.h"
#include "fcFlacContext.h"
#ifdef fcSupportFlac
#ifdef _MSC_VER
#pragma comment(lib, "libFLAC_static.lib")
#pragma comment(lib, "libvorbis_static.lib")
#pragma comment(lib, "libogg_static.lib")
#define FLAC__NO_DLL
#endif
#include "FLAC/stream_encoder.h"
class fcFlacWriter
{
public:
fcFlacWriter(const fcFlacConfig& c, fcStream *s);
~fcFlacWriter();
bool write(const int *samples, int num_samples);
private:
fcStream *m_stream = nullptr;
FLAC__StreamEncoder *m_encoder = nullptr;
};
using fcFlacWriterPtr = std::unique_ptr<fcFlacWriter>;
class fcFlacContext : public fcIFlacContext
{
public:
using AudioBuffer = RawVector<float>;
using AudioBuffers = SharedResources<AudioBuffer>;
fcFlacContext(const fcFlacConfig& c);
~fcFlacContext() override;
void addOutputStream(fcStream *s) override;
bool addSamples(const float *samples, int num_samples) override;
private:
fcFlacConfig m_conf;
std::vector<fcFlacWriterPtr> m_writers;
TaskQueue m_tasks;
AudioBuffers m_buffers;
RawVector<int> m_conversion_buffer;
};
static FLAC__StreamEncoderReadStatus stream_encoder_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
{
auto *f = (fcStream*)client_data;
if (*bytes > 0) {
*bytes = f->read(buffer, *bytes);
if (*bytes == 0)
return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
else
return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
}
else
return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
}
static FLAC__StreamEncoderWriteStatus stream_encoder_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
{
auto *f = (fcStream*)client_data;
if (f->write(buffer, bytes) != bytes)
return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
else
return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
}
static FLAC__StreamEncoderSeekStatus stream_encoder_seekp_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
{
auto *f = (fcStream*)client_data;
f->seekp((size_t)absolute_byte_offset);
return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
}
static FLAC__StreamEncoderTellStatus stream_encoder_tellp_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
{
auto *f = (fcStream*)client_data;
*absolute_byte_offset = f->tellp();
return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
}
fcFlacWriter::fcFlacWriter(const fcFlacConfig& c, fcStream *s)
: m_stream(s)
{
m_stream->addRef();
m_encoder = FLAC__stream_encoder_new();
if (c.verify) {
FLAC__stream_encoder_set_verify(m_encoder, true);
}
FLAC__stream_encoder_set_sample_rate(m_encoder, c.sample_rate);
FLAC__stream_encoder_set_channels(m_encoder, c.num_channels);
FLAC__stream_encoder_set_bits_per_sample(m_encoder, c.bits_per_sample);
FLAC__stream_encoder_set_compression_level(m_encoder, c.compression_level);
FLAC__stream_encoder_set_blocksize(m_encoder, c.block_size);
FLAC__stream_encoder_init_stream(m_encoder, stream_encoder_write_callback_, stream_encoder_seekp_callback_, stream_encoder_tellp_callback_, /*metadata_callback=*/0, /*client_data=*/s);
#ifdef fcDebug
{
FLAC__uint64 absolute_sample;
unsigned frame_number;
unsigned channel;
unsigned sample;
FLAC__int32 expected;
FLAC__int32 got;
printf("testing FLAC__stream_encoder_get_verify_decoder_error_stats()... ");
FLAC__stream_encoder_get_verify_decoder_error_stats(m_encoder, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
printf("OK\n");
}
#endif // fcDebug
}
fcFlacWriter::~fcFlacWriter()
{
if (m_encoder) {
FLAC__stream_encoder_finish(m_encoder);
FLAC__stream_encoder_delete(m_encoder);
m_encoder = nullptr;
}
m_stream->release();
m_stream = nullptr;
}
bool fcFlacWriter::write(const int *samples, int num_samples)
{
return FLAC__stream_encoder_process_interleaved(m_encoder, samples, num_samples) != 0;
}
fcFlacContext::fcFlacContext(const fcFlacConfig& c)
: m_conf(c)
{
m_conf.max_tasks = std::max<int>(m_conf.max_tasks, 1);
for (int i = 0; i < m_conf.max_tasks; ++i) {
m_buffers.emplace();
}
}
fcFlacContext::~fcFlacContext()
{
m_tasks.wait();
m_writers.clear();
}
void fcFlacContext::addOutputStream(fcStream *s)
{
if (s) {
m_writers.emplace_back(new fcFlacWriter(m_conf, s));
}
}
bool fcFlacContext::addSamples(const float *samples, int num_samples)
{
if (!samples || num_samples == 0) { return false; }
auto buf = m_buffers.acquire();
buf->assign(samples, num_samples);
m_tasks.run([this, buf]() {
float scale = float((1 << (m_conf.bits_per_sample - 1)) - 1);
m_conversion_buffer.resize(buf->size());
fcF32ToI32ScaleSamples(m_conversion_buffer.data(), buf->data(), buf->size(), scale);
for (auto& w : m_writers) {
w->write(m_conversion_buffer.data(), (int)m_conversion_buffer.size() / m_conf.num_channels);
}
});
return true;
}
fcIFlacContext* fcFlacCreateContextImpl(const fcFlacConfig *conf)
{
return new fcFlacContext(*conf);
}
#else // fcSupportFlac
fcIFlacContext* fcFlacCreateContextImpl(const fcFlacConfig *conf)
{
return nullptr;
}
#endif // fcSupportFlac
| 28.964103
| 206
| 0.722557
|
Okashiou
|
1740fc1adcf4f884468323051aa40be29365accc
| 5,286
|
cpp
|
C++
|
Sources/VanillaDNN/Layers/DenseLayer.cpp
|
jaegyeom/Vanilla-DNN
|
3a783bbbb7d827b82716516eca1ee9e7803804a7
|
[
"MIT"
] | 4
|
2021-05-20T16:02:43.000Z
|
2021-10-02T02:37:06.000Z
|
Sources/VanillaDNN/Layers/DenseLayer.cpp
|
jaegyeom/Vanilla-DNN
|
3a783bbbb7d827b82716516eca1ee9e7803804a7
|
[
"MIT"
] | 1
|
2021-05-14T18:13:28.000Z
|
2021-05-15T01:57:06.000Z
|
Sources/VanillaDNN/Layers/DenseLayer.cpp
|
jaegyeom/Vanilla-DNN
|
3a783bbbb7d827b82716516eca1ee9e7803804a7
|
[
"MIT"
] | 2
|
2021-05-14T18:00:34.000Z
|
2021-10-31T08:23:35.000Z
|
#ifndef VANILLA_DNN_DENSE_LAYER_CPP
#define VANILLA_DNN_DENSE_LAYER_CPP
#include <VanillaDNN/Layers/DenseLayer.hpp>
DenseLayer::DenseLayer(){
this->dim = 0;
}
DenseLayer::DenseLayer(const DenseLayer& rhs) {
this->dim = rhs.dim;
this->weight = rhs.weight;
this->bias = rhs.bias;
this->setActivation(rhs.getActivationName());
}
DenseLayer::DenseLayer(const int& dim) {
this->dim = dim;
this->weight = Matrix<float>(0,0,0);
this->bias = Vector<float>(0,0);
this->setActivation("None");
}
DenseLayer::DenseLayer(const int& dim, const std::string& _activation) {
this->dim = dim;
this->setActivation(_activation);
}
DenseLayer::~DenseLayer() {
//if (this->preLayer != nullptr) delete preLayer;
}
void DenseLayer::back_propagation(const int& idx){
if(this->preLayer == nullptr) return;
if(this->postLayer.expired() == false){
std::shared_ptr<Layer> post_layer = this->postLayer.lock();
this->dE_do[idx] = post_layer->getFeedback(idx);
}
if(this->activation->getName() == "soft_max"){
Matrix<float> do_dz = this->activation->getActivatedDiff2(this->input[idx]);
this->dE_dz[idx] = do_dz.transpose().dot(this->dE_do[idx]);
}
else{
Vector<float> do_dz = this->activation->getActivatedDiff(this->input[idx]);
this->dE_dz[idx] = this->dE_do[idx] * do_dz;
}
this->dz_dw[idx] = this->preLayer->getOutput(idx);
this->dE_dw[idx] = this->dE_dz[idx].dot(this->dz_dw[idx].transpose());
this->dE_db[idx] = this->dE_dz[idx];
this->feedback[idx] = this->batch_weight[idx].transpose().dot(this->dE_dz[idx]);
return;
}
void DenseLayer::feed_forward(const int& idx){
if(this->preLayer == nullptr){
this->output[idx] = this->input[idx];
}
else{
this->input[idx] = this->batch_weight[idx].dot(this->preLayer->getOutput(idx)) + this->batch_bias[idx];
this->output[idx] = this->activation->getActivated(this->input[idx]);
}
return;
}
void DenseLayer::predict(){
if(this->preLayer == nullptr){
this->output[0] = this->input[0];
}
else{
this->input[0] = this->weight.dot(this->preLayer->getOutput(0)) + this->bias;
this->output[0] = this->activation->getActivated(this->input[0]);
}
return;
}
void DenseLayer::update(){
if(this->preLayer == nullptr) return;
Matrix<float> dw(this->dim,this->preLayer->getDim(),0.0f);
Vector<float> db(this->dim,0.0f);
for(int idx = 0;idx < this->batch_size; idx++){
dw += this->dE_dw[idx];
db += this->dE_db[idx];
}
this->weight -= (this->optimizer->getWeightGradient(dw)) / this->batch_size;
this->bias -= (this->optimizer->getBiasGradient(db)) / this->batch_size;
// this->bias -= db / this->batch_size;
for(int i = 0;i<this->batch_size;i++){
this->batch_weight[i] = this->weight;
this->batch_bias[i] = this->bias;
}
return;
}
void DenseLayer::init(const int& batch_size,std::unique_ptr<Optimizer>& _optimizer){
this->batch_size = batch_size;
this->input.resize(this->batch_size);
this->output.resize(this->batch_size);
if(this->preLayer == nullptr) return;
this->dE_dw.resize(this->batch_size);
this->dE_db.resize(this->batch_size);
this->dE_do.resize(this->batch_size);
this->dE_dz.resize(this->batch_size);
this->dz_db.resize(this->batch_size);
this->dz_dw.resize(this->batch_size);
this->feedback.resize(this->batch_size);
this->weight.resize(this->dim, this->preLayer->getDim());
this->bias.resize(this->dim, 0);
this->weight.setRandom();
this->bias.setRandom();
this->batch_weight.resize(this->batch_size);
this->batch_bias.resize(this->batch_size);
for(int i = 0;i<this->batch_size;i++){
this->batch_weight[i] = this->weight;
this->batch_bias[i] = this->bias;
}
this->setOptimizer(_optimizer);
return;
}
void DenseLayer::setActivation(const std::string& name) {
if("None" == name) this->activation = std::make_unique<Activation>(name);
else if("sigmoid" == name) this->activation = std::make_unique<Sigmoid>(name);
else if("hyper_tan" == name) this->activation = std::make_unique<HyperTan>(name);
else if("relu" == name) this->activation = std::make_unique<ReLU>(name);
else if("leaky_relu" == name) this->activation = std::make_unique<LeakyReLU>(name);
else if("soft_max" == name) this->activation = std::make_unique<SoftMax>(name);
return;
}
void DenseLayer::setInput(const Matrix<float>& _input,const int& idx) {
this->input[idx] = _input;
}
void DenseLayer::setError(const Vector<float>& error,const int& idx) {
this->dE_do[idx] = error;
}
void DenseLayer::setOptimizer(std::unique_ptr<Optimizer>& _optimizer){
this->optimizer = std::unique_ptr<Optimizer>(_optimizer->copy());
return;
}
Matrix<float> DenseLayer::getFeedback(const int& idx){
return this->feedback[idx];
}
Matrix<float> DenseLayer::getOutput(const int& idx){
return this->output[idx];
}
std::shared_ptr<Layer> DenseLayer::getPostLayer(){
std::shared_ptr<Layer> temp = this->postLayer.lock();
return temp;
}
std::shared_ptr<Layer> DenseLayer::getPreLayer(){
return this->preLayer;
}
void DenseLayer::connect(std::shared_ptr<Layer>& cur_layer, std::shared_ptr<Layer>& new_layer){
(std::dynamic_pointer_cast<DenseLayer>(new_layer))->preLayer = cur_layer;
this->postLayer = new_layer;
return;
}
std::string DenseLayer::getActivationName() const{
return this->activation->getName();
}
int DenseLayer::getDim() const{
return this->dim;
}
#endif
| 28.117021
| 105
| 0.699016
|
jaegyeom
|
174158f3202bc26d4e749d884eade32d495dd5b7
| 10,043
|
hpp
|
C++
|
libraries/include/rpc/rpc_msg.hpp
|
WillAchain/lvm
|
1511459593df943be8a431ac968ff23083481da8
|
[
"MIT"
] | 19
|
2017-11-01T02:48:58.000Z
|
2018-04-25T23:07:33.000Z
|
libraries/include/rpc/rpc_msg.hpp
|
WillAchain/lvm
|
1511459593df943be8a431ac968ff23083481da8
|
[
"MIT"
] | 1
|
2017-11-10T01:28:43.000Z
|
2017-11-10T01:28:43.000Z
|
libraries/include/rpc/rpc_msg.hpp
|
WillAchain/lvm
|
1511459593df943be8a431ac968ff23083481da8
|
[
"MIT"
] | 24
|
2017-11-01T03:30:09.000Z
|
2018-12-28T21:57:33.000Z
|
/*
author: saiy
date: 2017.10.17
rpc message
*/
#ifndef _RPC_MSG_H_
#define _RPC_MSG_H_
#include <fc/array.hpp>
#include <fc/io/varint.hpp>
#include <fc/io/raw.hpp>
#include <fc/crypto/ripemd160.hpp>
#include <fc/reflect/variant.hpp>
#include <util/util.hpp>
#include <task/task.hpp>
enum SocketMode {
ASYNC_MODE = 0,
SYNC_MODE,
MODE_COUNT
};
enum LuaRpcMessageTypeEnum {
COMPILE_MESSAGE_TYPE = 0,
COMPILE_RESULT_MESSAGE_TYPE,
COMPILE_SCRIPT_MESSAGE_TPYE,
COMPILE_SCRIPT_RESULT_MESSAGE_TPYE,
CALL_MESSAGE_TYPE,
CALL_RESULT_MESSAGE_TYPE,
REGTISTER_MESSAGE_TYPE,
REGTISTER_RESULT_MESSAGE_TYPE,
UPGRADE_MESSAGE_TYPE,
UPGRADE_RESULT_MESSAGE_TYPE,
TRANSFER_MESSAGE_TYPE,
TRANSFER_RESULT_MESSAGE_TYPE,
DESTROY_MESSAGE_TYPE,
DESTROY_RESULT_MESSAGE_TYPE,
CALL_OFFLINE_MESSAGE_TYPE,
CALL_OFFLINE_RESULT_MESSAGE_TYPE,
HANDLE_EVENTS_MESSAGE_TYPE,
HANDLE_EVENTS_RESULT_MESSAGE_TYPE,
LUA_REQUEST_MESSAGE_TYPE,
LUA_REQUEST_RESULT_MESSAGE_TYPE,
HELLO_MESSAGE_TYPE,
MESSAGE_COUNT
};
struct MessageHeader {
uint32_t size;//number of bytes in message, capped at MAX_MESSAGE_SIZE
uint32_t msg_type;
};
typedef fc::uint160_t MessageHashType;
/**
* Abstracts the process of packing/unpacking a message for a
* particular channel.
*/
struct Message : public MessageHeader {
std::vector<char> data;
Message() {}
Message(Message&& m)
:MessageHeader(m), data(std::move(m.data)) {}
Message(const Message& m)
:MessageHeader(m), data(m.data) {}
/**
* Assumes that T::type specifies the message type
*/
template<typename T>
Message(const T& m) {
msg_type = T::type;
data = fc::raw::pack(m);
size = (uint32_t)data.size();
}
fc::uint160_t id()const {
return fc::ripemd160::hash(data.data(), (uint32_t)data.size());
}
/**
* Automatically checks the type and deserializes T in the
* opposite process from the constructor.
*/
template<typename T>
T as()const {
try {
FC_ASSERT(msg_type == T::type);
T tmp;
if (data.size()) {
fc::datastream<const char*> ds(data.data(), data.size());
fc::raw::unpack(ds, tmp);
} else {
// just to make sure that tmp shouldn't have any data
fc::datastream<const char*> ds(nullptr, 0);
fc::raw::unpack(ds, tmp);
}
return tmp;
}
FC_RETHROW_EXCEPTIONS(warn,
"error unpacking network message as a '${type}' ${x} !=? ${msg_type}",
("type", fc::get_typename<T>::name())
("x", T::type)
("msg_type", msg_type)
);
}
};
//HELLO MSG
//hello msg, lvm send hello-msg to achain only, not receive hello-msg
struct HelloMsgRpc {
static const LuaRpcMessageTypeEnum type;
HelloMsg data;
HelloMsgRpc() {}
HelloMsgRpc(HelloMsg& para) :
data(std::move(para))
{}
};
struct HelloMsgResultRpc {
static const LuaRpcMessageTypeEnum type;
HelloMsgResult data;
HelloMsgResultRpc() {}
HelloMsgResultRpc(HelloMsgResult& para) :
data(std::move(para))
{}
};
//task:
struct CompileTaskRpc {
static const LuaRpcMessageTypeEnum type;
CompileTask data;
CompileTaskRpc() {}
CompileTaskRpc(CompileTask& para) :
data(std::move(para))
{}
};
struct CallTaskRpc {
static const LuaRpcMessageTypeEnum type;
CallTask data;
CallTaskRpc() {}
CallTaskRpc(CallTask& para) :
data(std::move(para))
{}
};
struct RegisterTaskRpc {
static const LuaRpcMessageTypeEnum type;
RegisterTask data;
RegisterTaskRpc() {}
RegisterTaskRpc(RegisterTask& para) :
data(std::move(para))
{}
};
struct UpgradeTaskRpc {
static const LuaRpcMessageTypeEnum type;
UpgradeTask data;
UpgradeTaskRpc() {}
UpgradeTaskRpc(UpgradeTask& para) :
data(std::move(para))
{}
};
struct TransferTaskRpc {
static const LuaRpcMessageTypeEnum type;
TransferTask data;
TransferTaskRpc() {}
TransferTaskRpc(TransferTask& para) :
data(std::move(para))
{}
};
struct DestroyTaskRpc {
static const LuaRpcMessageTypeEnum type;
DestroyTask data;
DestroyTaskRpc() {}
DestroyTaskRpc(DestroyTask& para) :
data(std::move(para))
{}
};
struct LuaRequestTaskRpc {
static const LuaRpcMessageTypeEnum type;
LuaRequestTask data;
LuaRequestTaskRpc() {}
LuaRequestTaskRpc(LuaRequestTask& para) :
data(std::move(para))
{}
};
struct CompileScriptTaskRpc {
static const LuaRpcMessageTypeEnum type;
CompileScriptTask data;
CompileScriptTaskRpc() {}
CompileScriptTaskRpc(CompileScriptTask& para) :
data(std::move(para))
{}
};
struct HandleEventsTaskRpc {
static const LuaRpcMessageTypeEnum type;
HandleEventsTask data;
HandleEventsTaskRpc() {}
HandleEventsTaskRpc(HandleEventsTask& para) :
data(std::move(para))
{}
};
struct CallContractOfflineTaskRpc {
static const LuaRpcMessageTypeEnum type;
CallContractOfflineTask data;
CallContractOfflineTaskRpc() {}
CallContractOfflineTaskRpc(CallContractOfflineTask& para) :
data(std::move(para))
{}
};
//result:
struct CompileTaskResultRpc {
static const LuaRpcMessageTypeEnum type;
CompileTaskResult data;
CompileTaskResultRpc() {}
CompileTaskResultRpc(CompileTaskResult& para) :
data(std::move(para))
{}
};
struct RegisterTaskResultRpc {
static const LuaRpcMessageTypeEnum type;
RegisterTaskResult data;
RegisterTaskResultRpc() {}
RegisterTaskResultRpc(RegisterTaskResult& para) :
data(std::move(para))
{}
};
struct CallTaskResultRpc {
static const LuaRpcMessageTypeEnum type;
CallTaskResult data;
CallTaskResultRpc() {}
CallTaskResultRpc(CallTaskResult& para) :
data(std::move(para))
{}
};
struct TransferTaskResultRpc {
static const LuaRpcMessageTypeEnum type;
TransferTaskResult data;
TransferTaskResultRpc() {}
TransferTaskResultRpc(TransferTaskResult& para) :
data(std::move(para))
{}
};
struct UpgradeTaskResultRpc {
static const LuaRpcMessageTypeEnum type;
UpgradeTaskResult data;
UpgradeTaskResultRpc() {}
UpgradeTaskResultRpc(UpgradeTaskResult& para) :
data(std::move(para))
{}
};
struct DestroyTaskResultRpc {
static const LuaRpcMessageTypeEnum type;
DestroyTaskResult data;
DestroyTaskResultRpc() {}
DestroyTaskResultRpc(DestroyTaskResult& para) :
data(std::move(para))
{}
};
struct LuaRequestTaskResultRpc {
static const LuaRpcMessageTypeEnum type;
LuaRequestTaskResult data;
LuaRequestTaskResultRpc() {}
LuaRequestTaskResultRpc(LuaRequestTaskResult& para) :
data(std::move(para))
{}
};
struct CompileScriptTaskResultRpc {
static const LuaRpcMessageTypeEnum type;
CompileScriptTaskResult data;
CompileScriptTaskResultRpc() {}
CompileScriptTaskResultRpc(CompileScriptTaskResult& para) :
data(std::move(para))
{}
};
struct HandleEventsTaskResultRpc {
static const LuaRpcMessageTypeEnum type;
HandleEventsTaskResult data;
HandleEventsTaskResultRpc() {}
HandleEventsTaskResultRpc(HandleEventsTaskResult& para) :
data(std::move(para))
{}
};
struct CallContractOfflineTaskResultRpc {
static const LuaRpcMessageTypeEnum type;
CallContractOfflineTaskResult data;
CallContractOfflineTaskResultRpc() {}
CallContractOfflineTaskResultRpc(CallContractOfflineTaskResult& para) :
data(std::move(para))
{}
};
FC_REFLECT_ENUM(LuaRpcMessageTypeEnum,
(COMPILE_MESSAGE_TYPE)
(COMPILE_RESULT_MESSAGE_TYPE)
(COMPILE_SCRIPT_MESSAGE_TPYE)
(COMPILE_SCRIPT_RESULT_MESSAGE_TPYE)
(CALL_MESSAGE_TYPE)
(CALL_RESULT_MESSAGE_TYPE)
(REGTISTER_MESSAGE_TYPE)
(REGTISTER_RESULT_MESSAGE_TYPE)
(UPGRADE_MESSAGE_TYPE)
(UPGRADE_RESULT_MESSAGE_TYPE)
(TRANSFER_MESSAGE_TYPE)
(TRANSFER_RESULT_MESSAGE_TYPE)
(DESTROY_MESSAGE_TYPE)
(DESTROY_RESULT_MESSAGE_TYPE)
(CALL_OFFLINE_MESSAGE_TYPE)
(CALL_OFFLINE_RESULT_MESSAGE_TYPE)
(HANDLE_EVENTS_MESSAGE_TYPE)
(HANDLE_EVENTS_RESULT_MESSAGE_TYPE)
(LUA_REQUEST_MESSAGE_TYPE)
(LUA_REQUEST_RESULT_MESSAGE_TYPE)
(HELLO_MESSAGE_TYPE)
)
FC_REFLECT(MessageHeader, (size)(msg_type))
FC_REFLECT_DERIVED(Message, (MessageHeader), (data))
FC_REFLECT(CompileTaskRpc, (data))
FC_REFLECT(CallTaskRpc, (data))
FC_REFLECT(RegisterTaskRpc, (data))
FC_REFLECT(TransferTaskRpc, (data))
FC_REFLECT(UpgradeTaskRpc, (data))
FC_REFLECT(DestroyTaskRpc, (data))
FC_REFLECT(LuaRequestTaskRpc, (data))
FC_REFLECT(CompileScriptTaskRpc, (data))
FC_REFLECT(HandleEventsTaskRpc, (data))
FC_REFLECT(CallContractOfflineTaskRpc, (data))
//result
FC_REFLECT(CompileTaskResultRpc, (data))
FC_REFLECT(RegisterTaskResultRpc, (data))
FC_REFLECT(CallTaskResultRpc, (data))
FC_REFLECT(TransferTaskResultRpc, (data))
FC_REFLECT(UpgradeTaskResultRpc, (data))
FC_REFLECT(DestroyTaskResultRpc, (data))
FC_REFLECT(LuaRequestTaskResultRpc, (data))
FC_REFLECT(CompileScriptTaskResultRpc, (data))
FC_REFLECT(HandleEventsTaskResultRpc, (data))
FC_REFLECT(CallContractOfflineTaskResultRpc, (data))
//hello msg
FC_REFLECT(HelloMsgRpc, (data))
FC_REFLECT(HelloMsgResultRpc, (data))
#endif
| 25.361111
| 101
| 0.657373
|
WillAchain
|
1742e61a23f4e0dc10d0c2422a1a49cb577c48c5
| 14,418
|
cc
|
C++
|
Ghidra/Features/Decompiler/src/decompile/cpp/sleigh_arch.cc
|
Bugasu/ghidra
|
1bfa1aaf33485cec314b96b367c31eff4467b291
|
[
"Apache-2.0"
] | 115
|
2020-04-29T22:58:59.000Z
|
2022-03-21T05:42:12.000Z
|
Ghidra/Features/Decompiler/src/decompile/cpp/sleigh_arch.cc
|
weisJ/ghidra
|
7672d4cc34f2f36365335e8da2d6f6079cc9c357
|
[
"Apache-2.0"
] | 3
|
2020-05-25T11:55:04.000Z
|
2021-07-03T01:51:23.000Z
|
Ghidra/Features/Decompiler/src/decompile/cpp/sleigh_arch.cc
|
weisJ/ghidra
|
7672d4cc34f2f36365335e8da2d6f6079cc9c357
|
[
"Apache-2.0"
] | 19
|
2020-04-29T12:29:46.000Z
|
2022-03-10T02:41:17.000Z
|
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sleigh_arch.hh"
#include "inject_sleigh.hh"
Sleigh *SleighArchitecture::last_sleigh = (Sleigh *)0;
int4 SleighArchitecture::last_languageindex;
vector<LanguageDescription> SleighArchitecture::description;
FileManage SleighArchitecture::specpaths; // Global specfile manager
/// Read file attributes from an XML \<compiler> tag
/// \param el is the XML element
void CompilerTag::restoreXml(const Element *el)
{
name = el->getAttributeValue("name");
spec = el->getAttributeValue("spec");
id = el->getAttributeValue("id");
}
/// Parse an ldefs \<language> tag
/// \param el is the XML element
void LanguageDescription::restoreXml(const Element *el)
{
processor = el->getAttributeValue("processor");
isbigendian = (el->getAttributeValue("endian")=="big");
istringstream s1(el->getAttributeValue("size"));
s1.unsetf(ios::dec | ios::hex | ios::oct);
s1 >> size;
variant = el->getAttributeValue("variant");
version = el->getAttributeValue("version");
slafile = el->getAttributeValue("slafile");
processorspec = el->getAttributeValue("processorspec");
id = el->getAttributeValue("id");
deprecated = false;
for(int4 i=0;i<el->getNumAttributes();++i) {
if (el->getAttributeName(i)=="deprecated")
deprecated = xml_readbool(el->getAttributeValue(i));
}
const List &sublist(el->getChildren());
List::const_iterator subiter;
for(subiter=sublist.begin();subiter!=sublist.end();++subiter) {
const Element *subel = *subiter;
if (subel->getName() == "description")
description = subel->getContent();
else if (subel->getName() == "compiler") {
compilers.push_back(CompilerTag());
compilers.back().restoreXml(subel);
}
else if (subel->getName() == "truncate_space") {
truncations.push_back(TruncationTag());
truncations.back().restoreXml(subel);
}
}
}
/// Pick out the CompilerTag associated with the desired \e compiler \e id string
/// \param nm is the desired id string
/// \return a reference to the matching CompilerTag
const CompilerTag &LanguageDescription::getCompiler(const string &nm) const
{
int4 defaultind = -1;
for(int4 i=0;i<compilers.size();++i) {
if (compilers[i].getId() == nm)
return compilers[i];
if (compilers[i].getId() == "default")
defaultind = i;
}
if (defaultind != -1) // If can't match compiler, return default
return compilers[defaultind];
return compilers[0];
}
/// \brief Read a SLEIGH .ldefs file
///
/// Any \<language> tags are added to the LanguageDescription array
/// \param specfile is the filename of the .ldefs file
/// \param errs is an output stream for printing error messages
void SleighArchitecture::loadLanguageDescription(const string &specfile,ostream &errs)
{
ifstream s(specfile.c_str());
if (!s) return;
Document *doc;
Element *el;
try {
doc = xml_tree(s);
}
catch(XmlError &err) {
errs << "WARNING: Unable to parse sleigh specfile: " << specfile;
return;
}
el = doc->getRoot();
const List &list(el->getChildren());
List::const_iterator iter;
for(iter=list.begin();iter!=list.end();++iter) {
if ((*iter)->getName() != "language") continue;
description.push_back(LanguageDescription());
description.back().restoreXml( *iter );
}
delete doc;
}
SleighArchitecture::~SleighArchitecture(void)
{
translate = (const Translate *)0;
}
string SleighArchitecture::getDescription(void) const
{
return description[languageindex].getDescription();
}
/// If the current \b languageindex matches the \b last_languageindex,
/// try to reuse the previous Sleigh object, so we don't reload
/// the .sla file.
/// \return \b true if it can be reused
bool SleighArchitecture::isTranslateReused(void)
{
if (last_sleigh == (Sleigh *)0) return false;
if (last_languageindex == languageindex) return true;
delete last_sleigh; // It doesn't match so free old Translate
last_sleigh = (Sleigh *)0;
return false;
}
Translate *SleighArchitecture::buildTranslator(DocumentStorage &store)
{ // Build a sleigh translator
if (isTranslateReused()) {
last_sleigh->reset(loader,context);
return last_sleigh;
}
else {
last_sleigh = new Sleigh(loader,context);
last_languageindex = languageindex;
return last_sleigh;
}
}
PcodeInjectLibrary *SleighArchitecture::buildPcodeInjectLibrary(void)
{ // Build the pcode injector based on sleigh
PcodeInjectLibrary *res;
res = new PcodeInjectLibrarySleigh(this,translate->getUniqueBase());
return res;
}
void SleighArchitecture::resolveArchitecture(void)
{ // Find best architecture
if (archid.size() == 0) {
if ((target.size()==0)||(target=="default"))
archid = loader->getArchType();
else
archid = target;
}
if (archid.find("binary-")==0)
archid.erase(0,7);
else if (archid.find("default-")==0)
archid.erase(0,8);
archid = normalizeArchitecture(archid);
string baseid = archid.substr(0,archid.rfind(':'));
int4 i;
languageindex = -1;
for(i=0;i<description.size();++i) {
if (description[i].getId() == baseid) {
languageindex = i;
if (description[i].isDeprecated())
printMessage("WARNING: Language "+baseid+" is deprecated");
break;
}
}
if (languageindex == -1)
throw LowlevelError("No sleigh specification for "+baseid);
}
void SleighArchitecture::buildSpecFile(DocumentStorage &store)
{ // Given a specific language, make sure relevant spec files are loaded
bool language_reuse = isTranslateReused();
const LanguageDescription &language(description[languageindex]);
string compiler = archid.substr(archid.rfind(':')+1);
const CompilerTag &compilertag( language.getCompiler(compiler));
string processorfile;
string compilerfile;
string slafile;
specpaths.findFile(processorfile,language.getProcessorSpec());
specpaths.findFile(compilerfile,compilertag.getSpec());
if (!language_reuse)
specpaths.findFile(slafile,language.getSlaFile());
try {
Document *doc = store.openDocument(processorfile);
store.registerTag(doc->getRoot());
}
catch(XmlError &err) {
ostringstream serr;
serr << "XML error parsing processor specification: " << processorfile;
serr << "\n " << err.explain;
throw SleighError(serr.str());
}
catch(LowlevelError &err) {
ostringstream serr;
serr << "Error reading processor specification: " << processorfile;
serr << "\n " << err.explain;
throw SleighError(serr.str());
}
try {
Document *doc = store.openDocument(compilerfile);
store.registerTag(doc->getRoot());
}
catch(XmlError &err) {
ostringstream serr;
serr << "XML error parsing compiler specification: " << compilerfile;
serr << "\n " << err.explain;
throw SleighError(serr.str());
}
catch(LowlevelError &err) {
ostringstream serr;
serr << "Error reading compiler specification: " << compilerfile;
serr << "\n " << err.explain;
throw SleighError(serr.str());
}
if (!language_reuse) {
try {
Document *doc = store.openDocument(slafile);
store.registerTag(doc->getRoot());
}
catch(XmlError &err) {
ostringstream serr;
serr << "XML error parsing SLEIGH file: " << slafile;
serr << "\n " << err.explain;
throw SleighError(serr.str());
}
catch(LowlevelError &err) {
ostringstream serr;
serr << "Error reading SLEIGH file: " << slafile;
serr << "\n " << err.explain;
throw SleighError(serr.str());
}
}
}
void SleighArchitecture::modifySpaces(Translate *trans)
{
const LanguageDescription &language(description[languageindex]);
for(int4 i=0;i<language.numTruncations();++i) {
trans->truncateSpace(language.getTruncation(i));
}
}
/// Prepare \b this SleighArchitecture for analyzing the given executable image.
/// Full initialization, including creation of the Translate object, still must be
/// performed by calling the init() method.
/// \param fname is the filename of the given executable image
/// \param targ is the optional \e language \e id or other target information
/// \param estream is a pointer to an output stream for writing error messages
SleighArchitecture::SleighArchitecture(const string &fname,const string &targ,ostream *estream)
: Architecture()
{
filename = fname;
target = targ;
errorstream = estream;
}
/// This is run once when spinning up the decompiler.
/// Look for the root .ldefs files within the normal directories and parse them.
/// Use these to populate the list of \e language \e ids that are supported.
/// \param errs is an output stream for writing error messages
void SleighArchitecture::collectSpecFiles(ostream &errs)
{
if (!description.empty()) return; // Have we already collected before
vector<string> testspecs;
vector<string>::iterator iter;
specpaths.matchList(testspecs,".ldefs",true);
for(iter=testspecs.begin();iter!=testspecs.end();++iter)
loadLanguageDescription(*iter,errs);
}
/// \param s is the XML output stream
void SleighArchitecture::saveXmlHeader(ostream &s) const
{
a_v(s,"name",filename);
a_v(s,"target",target);
}
/// \param el is the root XML element
void SleighArchitecture::restoreXmlHeader(const Element *el)
{
filename = el->getAttributeValue("name");
target = el->getAttributeValue("target");
}
/// Given an architecture target string try to recover an
/// appropriate processor name for use in a normalized \e language \e id.
/// \param nm is the given target string
/// \return the processor field
string SleighArchitecture::normalizeProcessor(const string &nm)
{
if (nm.find("386")!=string::npos)
return "x86";
return nm;
}
/// Given an architecture target string try to recover an
/// appropriate endianness string for use in a normalized \e language \e id.
/// \param nm is the given target string
/// \return the endianness field
string SleighArchitecture::normalizeEndian(const string &nm)
{
if (nm.find("big")!=string::npos)
return "BE";
if (nm.find("little")!=string::npos)
return "LE";
return nm;
}
/// Given an architecture target string try to recover an
/// appropriate size string for use in a normalized \e language \e id.
/// \param nm is the given target string
/// \return the size field
string SleighArchitecture::normalizeSize(const string &nm)
{
string res = nm;
string::size_type pos;
pos = res.find("bit");
if (pos != string::npos)
res.erase(pos,3);
pos = res.find('-');
if (pos != string::npos)
res.erase(pos,1);
return res;
}
/// Try to normalize the target string into a valid \e language \e id.
/// In general the target string must already look like a \e language \e id,
/// but it can drop the compiler field and be a little sloppier in its format.
/// \param nm is the given target string
/// \return the normalized \e language \e id
string SleighArchitecture::normalizeArchitecture(const string &nm)
{
string processor;
string endian;
string size;
string variant;
string compile;
string::size_type pos[4];
int4 i;
string::size_type curpos=0;
for(i=0;i<4;++i) {
curpos = nm.find(':',curpos+1);
if (curpos == string::npos) break;
pos[i] = curpos;
}
if ((i!=3)&&(i!=4))
throw LowlevelError("Architecture string does not look like sleigh id: "+nm);
processor = nm.substr(0,pos[0]);
endian = nm.substr(pos[0]+1,pos[1]-pos[0]-1);
size = nm.substr(pos[1]+1,pos[2]-pos[1]-1);
if (i==4) {
variant = nm.substr(pos[2]+1,pos[3]-pos[2]-1);
compile = nm.substr(pos[3]+1);
}
else {
variant = nm.substr(pos[2]+1);
compile = "default";
}
processor = normalizeProcessor(processor);
endian = normalizeEndian(endian);
size = normalizeSize(size);
return processor + ':' + endian + ':' + size + ':' + variant + ':' + compile;
}
/// \brief Scan directories for SLEIGH specification files
///
/// This assumes a standard "Ghidra/Processors/*/data/languages" layout. It
/// scans for all matching directories and prepares for reading .ldefs files.
/// \param rootpath is the root path of the Ghidra installation
void SleighArchitecture::scanForSleighDirectories(const string &rootpath)
{
vector<string> ghidradir;
vector<string> procdir;
vector<string> procdir2;
vector<string> languagesubdirs;
FileManage::scanDirectoryRecursive(ghidradir,"Ghidra",rootpath,2);
for(uint4 i=0;i<ghidradir.size();++i) {
FileManage::scanDirectoryRecursive(procdir,"Processors",ghidradir[i],1); // Look for Processors structure
FileManage::scanDirectoryRecursive(procdir,"contrib",ghidradir[i],1);
}
if (procdir.size()!=0) {
for(uint4 i=0;i<procdir.size();++i)
FileManage::directoryList(procdir2,procdir[i]);
vector<string> datadirs;
for(uint4 i=0;i<procdir2.size();++i)
FileManage::scanDirectoryRecursive(datadirs,"data",procdir2[i],1);
vector<string> languagedirs;
for(uint4 i=0;i<datadirs.size();++i)
FileManage::scanDirectoryRecursive(languagedirs,"languages",datadirs[i],1);
for(uint4 i=0;i<languagedirs.size();++i)
languagesubdirs.push_back( languagedirs[i] );
// In the old version we have to go down one more level to get to the ldefs
for(uint4 i=0;i<languagedirs.size();++i)
FileManage::directoryList(languagesubdirs,languagedirs[i]);
}
// If we haven't matched this directory structure, just use the rootpath as the directory containing
// the ldef
if (languagesubdirs.size() == 0)
languagesubdirs.push_back( rootpath );
for(uint4 i=0;i<languagesubdirs.size();++i)
specpaths.addDir2Path(languagesubdirs[i]);
}
void SleighArchitecture::shutdown(void)
{
if (last_sleigh != (Sleigh *)0) {
delete last_sleigh;
last_sleigh = (Sleigh *)0;
}
// description.clear(); // static vector is destroyed by the normal exit handler
}
| 30.54661
| 109
| 0.689139
|
Bugasu
|
174d714e3f95ef79e330073edf652faa71e9300c
| 3,653
|
cpp
|
C++
|
C++/Object-Oriented Programming in C++/Chapter 4_Structures/7.cpp
|
OjeshManandhar/Code-Backup
|
67a395fe2439725f42ce0a18b4d2e2e65f00695d
|
[
"MIT"
] | 2
|
2019-01-03T14:12:52.000Z
|
2019-03-22T16:13:16.000Z
|
C++/Object-Oriented Programming in C++/Chapter 4_Structures/7.cpp
|
OjeshManandhar/Code-Backup
|
67a395fe2439725f42ce0a18b4d2e2e65f00695d
|
[
"MIT"
] | null | null | null |
C++/Object-Oriented Programming in C++/Chapter 4_Structures/7.cpp
|
OjeshManandhar/Code-Backup
|
67a395fe2439725f42ce0a18b4d2e2e65f00695d
|
[
"MIT"
] | 1
|
2019-01-13T17:54:01.000Z
|
2019-01-13T17:54:01.000Z
|
#include <iostream>
using namespace std;
int main()
{
enum etype
{
laborer = 'l', secretary = 's', manager = 'm', accountant = 'a', executive = 'e', researcher = 'r'
};
struct date
{
int day, mon, year;
};
struct employee
{
int no;
float com;
etype type;
date first_day;
}e1, e2, e3;
char ch;
cout << "Enter data of first employee" << endl;
cout << "Enter employee's number: ";
cin >> e1.no;
cout << "Enter compensation of the employee: $";
cin >> e1.com;
cout << "Enter employee type (first letter only)" << endl
<< "\tlabour, secretart, manager" << endl
<< "\taccountant, executive, researcher: ";
cin >> ch;
e1.type = static_cast<etype>(ch);
cout << "Enter date of first employment [DD/MM/YYYY]: ";
cin >> e1.first_day.day >> ch >> e1.first_day.mon >> ch >> e1.first_day.year;
cout << endl << "Enter data of second employee" << endl;
cout << "Enter employee's number: ";
cin >> e2.no;
cout << "Enter compensation of the employee: $";
cin >> e2.com;
cout << "Enter employee type (first letter only)" << endl
<< "\tlabour, secretart, manager" << endl
<< "\taccountant, executive, researcher: ";
cin >> ch;
e2.type = static_cast<etype>(ch);
cout << "Enter date of first employment [DD/MM/YYYY]: ";
cin >> e2.first_day.day >> ch >> e2.first_day.mon >> ch >> e2.first_day.year;
cout << endl << "Enter data of third employee" << endl;
cout << "Enter employee's number: ";
cin >> e3.no;
cout << "Enter compensation of the employee: $";
cin >> e3.com;
cout << "Enter employee type (first letter only)" << endl
<< "\tlabour, secretart, manager" << endl
<< "\taccountant, executive, researcher: ";
cin >> ch;
e3.type = static_cast<etype>(ch);
cout << "Enter date of first employment [DD/MM/YYYY]: ";
cin >> e3.first_day.day >> ch >> e3.first_day.mon >> ch >> e3.first_day.year;
cout << endl << "Employee No: " << e1.no << '.' << endl;
cout << "Compensation: $" << e1.com << '.' << endl;
cout << "Type: ";
switch (e1.type)
{
case 'l':
cout << "Laborer." << endl;
break;
case 's':
cout << "Secretary." << endl;
break;
case 'm':
cout << "Manager." << endl;
break;
case 'a':
cout << "Accountant." << endl;
break;
case 'e':
cout << "Executive." << endl;
break;
case 'r':
cout << "Researcher." << endl;
break;
}
cout << "Date of first employment: " << e1.first_day.day << '/' << e1.first_day.mon << '/' << e1.first_day.year << '.' << endl;
cout << endl << "Employee No: " << e2.no << '.' << endl;
cout << "Compensation: $" << e2.com << '.' << endl;
cout << "Type: ";
switch (e2.type)
{
case 'l':
cout << "Laborer." << endl;
break;
case 's':
cout << "Secretary." << endl;
break;
case 'm':
cout << "Manager." << endl;
break;
case 'a':
cout << "Accountant." << endl;
break;
case 'e':
cout << "Executive." << endl;
break;
case 'r':
cout << "Researcher." << endl;
break;
}
cout << "Date of first employment: " << e2.first_day.day << '/' << e2.first_day.mon << '/' << e2.first_day.year << '.' << endl;
cout << endl << "Employee No: " << e3.no << '.' << endl;
cout << "Compensation: $" << e3.com << '.' << endl;
cout << "Type: ";
switch (e3.type)
{
case 'l':
cout << "Laborer." << endl;
break;
case 's':
cout << "Secretary." << endl;
break;
case 'm':
cout << "Manager." << endl;
break;
case 'a':
cout << "Accountant." << endl;
break;
case 'e':
cout << "Executive." << endl;
break;
case 'r':
cout << "Researcher." << endl;
break;
}
cout << "Date of first employment: " << e3.first_day.day << '/' << e3.first_day.mon << '/' << e3.first_day.year << '.' << endl;
system("pause");
return 0;
}
| 25.545455
| 128
| 0.570216
|
OjeshManandhar
|
174dd7a05861453228b364159954b61038cc8e58
| 4,608
|
cpp
|
C++
|
Arduino/stewartplatform/src/CANbus.cpp
|
skotterud98/StewartPlatform_Qt
|
d2cae1ed036ec381cda888f49005cb9df380a4a1
|
[
"MIT"
] | 1
|
2022-01-04T13:24:36.000Z
|
2022-01-04T13:24:36.000Z
|
Arduino/stewartplatform/src/CANbus.cpp
|
skotterud98/StewartPlatform_Qt
|
d2cae1ed036ec381cda888f49005cb9df380a4a1
|
[
"MIT"
] | null | null | null |
Arduino/stewartplatform/src/CANbus.cpp
|
skotterud98/StewartPlatform_Qt
|
d2cae1ed036ec381cda888f49005cb9df380a4a1
|
[
"MIT"
] | null | null | null |
#include "CANbus.h"
/*
* Constructor
*/
CANbus::CANbus(Controller* control_ptr)
{
this->reset();
msg_count = 0;
this->control_ptr = control_ptr;
}
/*
* CAN-bus receive ISR
*/
void CANbus::ref_ISR(CAN_FRAME* frame)
{
static float ref_pos[MOTORS_TOT] = {0., 0., 0., 0., 0., 0.};
static float ref_vel[MOTORS_TOT] = {0., 0., 0., 0., 0., 0.};
static uint8_t j = 0;
static uint8_t vel_dir = 0;
switch (frame->id)
{
case 0xA0: // Actuator 1-3 position ref
j = 0;
for (uint8_t i = 0; i < 3; i++)
{
uint16_t in_len = frame->data.byte[j] << 8;
in_len += frame->data.byte[j + 1];
ref_pos[i] = (float) in_len / 100000.;
j+=2;
}
pos_msg[0] = true;
break;
case 0xA1: // Actuator 4-6 position ref
j = 0;
for (uint8_t i = 3; i < 6; i++)
{
uint16_t in_len = frame->data.byte[j] << 8;
in_len += frame->data.byte[j + 1];
ref_pos[i] = (float) in_len / 100000.;
j+=2;
}
pos_msg[1] = true;
break;
case 0xA2: // Actuator 1-3 velocity ref and the direction (out/in) of the velocity
j = 0;
vel_dir = frame->data.byte[6];
for (uint8_t i = 0; i < 3; i++)
{
uint16_t in_vel = frame->data.byte[j] << 8;
in_vel += frame->data.byte[j + 1];
ref_vel[i] = (float) in_vel / 1000000.;
if (!((vel_dir >> i) & 1U))
{
ref_vel[i] *= -1.;
}
j+=2;
}
vel_msg[0] = true;
break;
case 0xA3: // Actuator 4-6 velocity ref and the direction (out/in) of the velocity
j = 0;
vel_dir = frame->data.byte[6];
for (uint8_t i = 3; i < 6; i++)
{
uint16_t in_vel = frame->data.byte[j] << 8;
in_vel += frame->data.byte[j + 1];
ref_vel[i] = (float) in_vel / 1000000.;
if(!((vel_dir >> (i-3)) & 1U))
{
ref_vel[i] *= -1.;
}
j+=2;
}
vel_msg[1] = true;
break;
default:
break;
}
if (pos_msg[0] && pos_msg[1] && vel_msg[0] && vel_msg[1])
{
control_ptr->set_ref_pos(ref_pos);
control_ptr->set_ref_vel(ref_vel);
}
}
/*
* Frame interrupt handler. An inherited virtual function from the due_can library.
* This fuction chooses what callback function to run based on the triggered mailbox.
*/
void CANbus::gotFrame(CAN_FRAME* frame, int mailbox)
{
if(mailbox == SETPOINT_MB) this->ref_ISR(frame);
}
/*
* Reply to CAN-bus with positions of the six actuators and the 12V current-consumption
*/
void CANbus::reply()
{
static uint16_t out_pos[6];
static uint8_t ampere = 0;
for (uint8_t num = 0; num < MOTORS_TOT; num ++)
{
out_pos[num] = (uint16_t)(control_ptr->get_sensorInput(num) * 100000. + 0.5);
}
ampere = control_ptr->getAmpere();
txFrame.id = 0xF0;
txFrame.length = 6;
txFrame.data.byte[0] = (uint8_t)(out_pos[0] >> 8);
txFrame.data.byte[1] = (uint8_t) out_pos[0];
txFrame.data.byte[2] = (uint8_t)(out_pos[1] >> 8);
txFrame.data.byte[3] = (uint8_t) out_pos[1];
txFrame.data.byte[4] = (uint8_t)(out_pos[2] >> 8);
txFrame.data.byte[5] = (uint8_t) out_pos[2];
Can0.sendFrame(txFrame);
txFrame.id = 0xF1;
txFrame.length = 7;
txFrame.data.byte[0] = (uint8_t)(out_pos[3] >> 8);
txFrame.data.byte[1] = (uint8_t) out_pos[3];
txFrame.data.byte[2] = (uint8_t)(out_pos[4] >> 8);
txFrame.data.byte[3] = (uint8_t) out_pos[4];
txFrame.data.byte[4] = (uint8_t)(out_pos[5] >> 8);
txFrame.data.byte[5] = (uint8_t) out_pos[5];
txFrame.data.byte[6] = ampere;
Can0.sendFrame(txFrame);
}
/*
* Resets the boolean variables for each received message
*/
void CANbus::reset()
{
pos_msg[0] = false;
pos_msg[1] = false;
vel_msg[0] = false;
vel_msg[1] = false;
}
/*
* Returns true if all 4 actuator reference messages is received
*/
bool CANbus::received() { return pos_msg[0] && pos_msg[1] && vel_msg[0] && vel_msg[1]; }
| 23.875648
| 93
| 0.488932
|
skotterud98
|
17514004f3041a9af67dc36f5b2ac0ee061f1da9
| 4,402
|
cpp
|
C++
|
src/CBox2DBody.cpp
|
divotkey/astu-box2d
|
0657accc7819e90e610cf923bfc42c4141e03faa
|
[
"MIT"
] | null | null | null |
src/CBox2DBody.cpp
|
divotkey/astu-box2d
|
0657accc7819e90e610cf923bfc42c4141e03faa
|
[
"MIT"
] | null | null | null |
src/CBox2DBody.cpp
|
divotkey/astu-box2d
|
0657accc7819e90e610cf923bfc42c4141e03faa
|
[
"MIT"
] | null | null | null |
/*
* ASTU/Box2D
* An integration of Erin Catto's 2D Physics Engine to AST-Utilities.
*
* Copyright (c) 2020, 2021 Roman Divotkey. All rights reserved.
*/
// Local includes
#include <Suite2D/CPose.h>
#include "CBox2DBody.h"
// Box2D includes
#include <box2d/box2d.h>
using namespace std;
namespace astu::suite2d {
void CBox2DBody::SetType(CBody::Type bodyType)
{
CBody::SetType(bodyType);
if (boxBody) {
switch(bodyType) {
case CBody::Type::Static:
boxBody->SetType(b2BodyType::b2_staticBody);
break;
case CBody::Type::Kinematic:
boxBody->SetType(b2BodyType::b2_kinematicBody);
break;
case CBody::Type::Dynamic:
boxBody->SetType(b2BodyType::b2_dynamicBody);
break;
}
}
}
Vector2f CBox2DBody::GetLinearVelocity() const
{
if (boxBody) {
const b2Vec2& v = boxBody->GetLinearVelocity();
return Vector2f(v.x, v.y);
}
return CBody::GetLinearVelocity();
}
CBody& CBox2DBody::SetLinearVelocity(float vx, float vy)
{
CBody::SetLinearVelocity(vx, vy);
if (boxBody) {
boxBody->SetLinearVelocity(b2Vec2(vx, vy));
}
return *this;
}
float CBox2DBody::GetAngularVelocity() const
{
if (boxBody) {
return boxBody->GetAngularVelocity();
}
return CBody::GetAngularVelocity();
}
CBody& CBox2DBody::SetAngularVelocity(float av)
{
CBody::SetAngularVelocity(av);
if (boxBody) {
boxBody->SetAngularVelocity(av);
}
return *this;
}
void CBox2DBody::SetLinearDamping(float damping)
{
CBody::SetLinearDamping(damping);
if (boxBody) {
boxBody->SetLinearDamping(damping);
}
}
void CBox2DBody::SetAngularDamping(float damping)
{
CBody::SetAngularDamping(damping);
if (boxBody) {
boxBody->SetAngularDamping(damping);
}
}
void CBox2DBody::ApplyTorque(float torque)
{
if (boxBody) {
boxBody->ApplyTorque(torque, true);
}
}
Vector2f CBox2DBody::GetWorldVector(float lvx, float lvy)
{
if (boxBody) {
b2Vec2 wv = boxBody->GetWorldVector(b2Vec2(lvx, lvy));
return Vector2f(wv.x, wv.y);
} else if ( HasParent() && GetParent()->HasComponent<CPose>() ) {
// Use CPose of out entity.
auto& pose = GetParent()->GetComponent<CPose>();
Vector2f result(lvx, lvy);
return result.Rotate(pose.transform.GetRotation());
} else {
// Difficult to decide what to do. Throw an exception instead?
return Vector2f::Zero;
}
}
Vector2f CBox2DBody::GetWorldPoint(float lpx, float lpy)
{
if (boxBody) {
b2Vec2 wp = boxBody->GetWorldPoint(b2Vec2(lpx, lpy));
return Vector2f(wp.x, wp.y);
} else if ( HasParent() && GetParent()->HasComponent<CPose>() ) {
// Use CPose of out entity.
auto& pose = GetParent()->GetComponent<CPose>();
Vector2f result(lpx, lpy);
return result.Rotate(pose.transform.GetRotation())
.Add(pose.transform.GetTranslation());
} else {
// Difficult to decide what to do. Throw an exception instead?
return Vector2f::Zero;
}
}
Vector2f CBox2DBody::GetLocalVector(float wvx, float wvy)
{
if (boxBody) {
b2Vec2 lv = boxBody->GetLocalVector(b2Vec2(wvx, wvy));
return Vector2f(lv.x, lv.y);
}
// Difficult to decide what to do. Throw an exception instead?
return Vector2f::Zero;
}
Vector2f CBox2DBody::GetLocalPoint(float wpx, float wpy)
{
if (boxBody) {
b2Vec2 lp = boxBody->GetLocalPoint(b2Vec2(wpx, wpy));
return Vector2f(lp.x, lp.y);
}
// Difficult to decide what to do. Throw an exception instead?
return Vector2f::Zero;
}
void CBox2DBody::ApplyForce(const Vector2f& force)
{
if (boxBody) {
boxBody->ApplyForceToCenter(b2Vec2(force.x, force.y), true);
}
}
} // end of namespace
| 27.17284
| 74
| 0.559746
|
divotkey
|
1753140eb0e28bf873520b1338235cbbfcedff02
| 92
|
cpp
|
C++
|
Non-Ideone/CodeChef/Practice/START01.cpp
|
beingsushant/BunnyKeCodes
|
018cae93935ee30ce02561d05cda091ebb6e9643
|
[
"MIT"
] | 1
|
2018-02-18T13:59:42.000Z
|
2018-02-18T13:59:42.000Z
|
Non-Ideone/CodeChef/Practice/START01.cpp
|
beingsushant/BunnyKeCodes
|
018cae93935ee30ce02561d05cda091ebb6e9643
|
[
"MIT"
] | null | null | null |
Non-Ideone/CodeChef/Practice/START01.cpp
|
beingsushant/BunnyKeCodes
|
018cae93935ee30ce02561d05cda091ebb6e9643
|
[
"MIT"
] | 2
|
2019-10-31T17:28:17.000Z
|
2019-10-31T17:52:11.000Z
|
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
cout<<n;
return 0;
}
| 8.363636
| 20
| 0.641304
|
beingsushant
|
1755cb0e776a14723d5a1f4b6dfda354eb73ca64
| 1,564
|
hh
|
C++
|
src/proto/core/platform/File.hh
|
kcpikkt/proto
|
2d7458c2ce2f571303de040f660137dc0a1d33de
|
[
"MIT"
] | null | null | null |
src/proto/core/platform/File.hh
|
kcpikkt/proto
|
2d7458c2ce2f571303de040f660137dc0a1d33de
|
[
"MIT"
] | null | null | null |
src/proto/core/platform/File.hh
|
kcpikkt/proto
|
2d7458c2ce2f571303de040f660137dc0a1d33de
|
[
"MIT"
] | null | null | null |
#pragma once
#include "proto/core/common.hh"
#include "proto/core/error-handling.hh"
#include "proto/core/util/Bitfield.hh"
#include "proto/core/util/StringView.hh"
#if defined(PROTO_PLATFORM_WINDOWS)
#error not implemented
#elif defined(PROTO_PLATFORM_MAC)
#error not implemented
#else
# include <stdio.h> // FILE
#endif
namespace proto {
namespace platform {
struct File {
enum Mode : u8 {
read_mode = BIT(0),
write_mode = BIT(1),
overwrite_mode = BIT(2),
read_write_mode = BIT(0) | BIT(1),
read_overwrite_mode = BIT(0) | BIT(2),
//trunc_mode = BIT(2),
//create_mode = BIT(3),
//append_mode = BIT(4),
};
//using Mode = u8;
#if defined(PROTO_PLATFORM_WINDOWS)
#error not implemented
#elif defined(PROTO_PLATFORM_MAC)
#error not implemented
#else
FILE * _file_ptr = nullptr;
#endif
enum : u8 {
mapped_bit = BIT(0),
};
Bitfield<u8> flags;
//constexpr static u8 is_open_bit = BIT(0);
Err open(StringView filename, Mode mode);
u64 size();
u64 write(void const * buf, u64 size);
u64 write(MemBuffer buf);
u64 read(void * mem, u64 size);
u64 read(MemBuffer buf);
void flush();
Err seek(s64 offset);
Err seek_end(s64 offset = 0);
s64 cursor();
MemBuffer map(Mode mode, Span<u64> span = {0,0});
void unmap(MemBuffer mem);
Err resize(u64 size);
Err reserve(u64 size);
Err close();
};
} // namespace platform
} // namespace proto
| 22.342857
| 53
| 0.609974
|
kcpikkt
|
17594d857abe35405ac93da8122c203004e5676c
| 2,569
|
cpp
|
C++
|
src/window.cpp
|
orbitrc/blusher-qt
|
23a868875fbe600a14ea6d49226226fea8931ab6
|
[
"MIT"
] | null | null | null |
src/window.cpp
|
orbitrc/blusher-qt
|
23a868875fbe600a14ea6d49226226fea8931ab6
|
[
"MIT"
] | null | null | null |
src/window.cpp
|
orbitrc/blusher-qt
|
23a868875fbe600a14ea6d49226226fea8931ab6
|
[
"MIT"
] | null | null | null |
#include <blusher/window.h>
#include <blusher/title-bar.h>
#define BLUSHER_SHADOW_WIDTH 40
#define BLUSHER_RESIZE_WIDTH 5
#define BLUSHER_BORDER_WIDTH 1
#define BLUSHER_TITLE_BAR_HEIGHT 30
namespace bl {
Window::Window()
: Surface(nullptr)
{
this->_width = 200;
this->_height = 200;
this->_decoration = static_cast<Surface*>(this);
this->_resize = new Surface(this->_decoration);
this->_border = new Surface(this->_resize);
this->_title_bar = new TitleBar(this->_border);
// Init decoration.
this->update_decoration();
// Init resize.
this->update_resize();
// Init border.
this->update_border();
// Init title bar.
this->update_title_bar();
}
//===================
// Public Methods
//===================
uint32_t Window::width() const
{
return this->_width;
}
uint32_t Window::height() const
{
return this->_height;
}
void Window::show()
{
this->_decoration->show();
this->_decoration->paint();
this->_resize->show();
this->_resize->paint();
this->_border->show();
this->_border->paint();
this->_title_bar->show();
this->_title_bar->paint();
}
void Window::move()
{
}
//====================
// Private Methods
//====================
void Window::update_decoration()
{
this->_decoration->set_geometry(
0,
0,
this->_width + (BLUSHER_SHADOW_WIDTH * 2),
this->_height + (BLUSHER_SHADOW_WIDTH * 2) + BLUSHER_TITLE_BAR_HEIGHT
);
this->_decoration->set_color(Color::from_rgba(0, 0, 0, 100));
}
void Window::update_resize()
{
this->_resize->set_geometry(
BLUSHER_SHADOW_WIDTH - BLUSHER_RESIZE_WIDTH,
BLUSHER_SHADOW_WIDTH - BLUSHER_RESIZE_WIDTH,
this->_width + (BLUSHER_RESIZE_WIDTH * 2),
this->_height + (BLUSHER_RESIZE_WIDTH * 2) + BLUSHER_TITLE_BAR_HEIGHT
);
this->_resize->set_color(Color::from_rgba(255, 0, 0, 100));
}
void Window::update_border()
{
this->_border->set_geometry(
BLUSHER_RESIZE_WIDTH - BLUSHER_BORDER_WIDTH,
BLUSHER_RESIZE_WIDTH - BLUSHER_BORDER_WIDTH,
this->_width + (BLUSHER_BORDER_WIDTH * 2),
this->_height + (BLUSHER_BORDER_WIDTH * 2) + BLUSHER_TITLE_BAR_HEIGHT
);
this->_border->set_color(Color::from_rgb(0, 0, 0));
}
void Window::update_title_bar()
{
this->_title_bar->set_geometry(
BLUSHER_BORDER_WIDTH,
BLUSHER_BORDER_WIDTH,
this->_width,
BLUSHER_TITLE_BAR_HEIGHT
);
this->_title_bar->set_color(Color::from_rgb(100, 100, 100));
}
} // namespace bl
| 21.771186
| 77
| 0.635267
|
orbitrc
|
175ccb0f14e5c055fe1b8c51ce239c6777f8bbc2
| 2,604
|
cpp
|
C++
|
client/src/ui/content/content.cpp
|
zDestinate/InventoryManagement
|
b2f568cbeca3e9fa7e2c1fc213f3b527a6755216
|
[
"MIT"
] | null | null | null |
client/src/ui/content/content.cpp
|
zDestinate/InventoryManagement
|
b2f568cbeca3e9fa7e2c1fc213f3b527a6755216
|
[
"MIT"
] | null | null | null |
client/src/ui/content/content.cpp
|
zDestinate/InventoryManagement
|
b2f568cbeca3e9fa7e2c1fc213f3b527a6755216
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <codecvt>
#include "ui/content/content.h"
#pragma comment(lib, "comctl32.lib")
content::content(HWND hwndParent, int lpParam, int x, int y, int width, int height)
{
hwnd = CreateWindow("STATIC", "", WS_CHILD | WS_VISIBLE , x, y, width, height, hwndParent, (HMENU)lpParam, NULL, NULL);
this->hwndParent = hwndParent;
//SetWindowSubclass(hwnd, ContentProc, lpParam, (DWORD_PTR)this);
}
LRESULT content::ContentProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
//Using the dwRefData we passed from and create this pointer
content* pThis = (content*) dwRefData;
switch (message)
{
case WM_ERASEBKGND:
{
//Get the current HWND Rect
RECT rc;
GetClientRect(hwnd, &rc);
PAINTSTRUCT ps;
HDC hdc;
//Start painting the line base on the focus status
hdc = BeginPaint(hwnd, &ps);
SetBkMode(hdc, TRANSPARENT);
//Paint background
HBRUSH hBackgroundColor;
hBackgroundColor = CreateSolidBrush(pThis->BackgroundColorRGB);
SelectObject(hdc, hBackgroundColor);
FillRect(hdc, &rc, hBackgroundColor);
DeleteObject(hBackgroundColor);
EndPaint(hwnd, &ps);
}
break;
case WM_PAINT:
{
//Get the current HWND Rect
RECT rc;
GetClientRect(hwnd, &rc);
PAINTSTRUCT ps;
HDC hdc;
//Start painting the line base on the focus status
hdc = BeginPaint(hwnd, &ps);
HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
//Restore the font and end painting
SelectObject(hdc, hFont);
EndPaint(hwnd, &ps);
}
break;
}
return DefSubclassProc(hwnd, message, wParam, lParam);
}
void content::DrawBorder(HDC hdc, RECT rc, COLORREF BorderColorRGB, int BorderSize)
{
HBRUSH hBorderColor;
hBorderColor = CreateSolidBrush(BorderColorRGB);
RECT rcBorder = rc;
//Top
rcBorder.bottom = rcBorder.top + BorderSize;
FillRect(hdc, &rcBorder, hBorderColor);
//Bottom
rcBorder = rc;
rcBorder.top = rcBorder.bottom - BorderSize;
FillRect(hdc, &rcBorder, hBorderColor);
//Left
rcBorder = rc;
rcBorder.right = rcBorder.left + BorderSize;
FillRect(hdc, &rcBorder, hBorderColor);
//Right
rcBorder = rc;
rcBorder.left = rcBorder.right - BorderSize;
FillRect(hdc, &rcBorder, hBorderColor);
}
| 27.702128
| 126
| 0.616743
|
zDestinate
|
175d8968efffcd18d5327ebbc452917d2a494d93
| 7,116
|
cpp
|
C++
|
IDE/ChoiceFile.cpp
|
sutao80216/GDevelop
|
79461bf01cc0c626e2f094d3fca940d643f93d76
|
[
"MIT"
] | 1
|
2019-08-24T03:18:42.000Z
|
2019-08-24T03:18:42.000Z
|
IDE/ChoiceFile.cpp
|
sutao80216/GDevelop
|
79461bf01cc0c626e2f094d3fca940d643f93d76
|
[
"MIT"
] | 9
|
2020-04-04T19:26:47.000Z
|
2022-03-25T18:41:20.000Z
|
IDE/ChoiceFile.cpp
|
sutao80216/GDevelop
|
79461bf01cc0c626e2f094d3fca940d643f93d76
|
[
"MIT"
] | 2
|
2020-03-02T05:20:41.000Z
|
2021-05-10T03:59:05.000Z
|
/*
* GDevelop IDE
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights reserved.
* This project is released under the GNU General Public License version 3.
*/
#include "ChoiceFile.h"
//(*InternalHeaders(ChoiceFile)
#include <wx/bitmap.h>
#include <wx/intl.h>
#include <wx/image.h>
#include <wx/string.h>
//*)
#include <wx/filedlg.h>
#include <wx/filename.h>
#include "GDCore/CommonTools.h"
#include "GDCore/IDE/wxTools/SkinHelper.h"
#include "GDCore/IDE/Dialogs/EditStrExpressionDialog.h"
#include "GDCore/Project/Project.h"
#include "GDCore/Tools/HelpFileAccess.h"
namespace gd { class Layout; }
//(*IdInit(ChoiceFile)
const long ChoiceFile::ID_STATICTEXT1 = wxNewId();
const long ChoiceFile::ID_TEXTCTRL1 = wxNewId();
const long ChoiceFile::ID_BUTTON1 = wxNewId();
const long ChoiceFile::ID_STATICTEXT2 = wxNewId();
const long ChoiceFile::ID_STATICLINE1 = wxNewId();
const long ChoiceFile::ID_STATICBITMAP2 = wxNewId();
const long ChoiceFile::ID_HYPERLINKCTRL1 = wxNewId();
const long ChoiceFile::ID_BUTTON4 = wxNewId();
const long ChoiceFile::ID_BUTTON3 = wxNewId();
const long ChoiceFile::ID_BUTTON2 = wxNewId();
//*)
BEGIN_EVENT_TABLE(ChoiceFile,wxDialog)
//(*EventTable(ChoiceFile)
//*)
END_EVENT_TABLE()
ChoiceFile::ChoiceFile(wxWindow* parent, gd::String file_, gd::Project & game_, gd::Layout & scene_) :
file(file_),
game(game_),
scene(scene_)
{
//(*Initialize(ChoiceFile)
wxFlexGridSizer* FlexGridSizer4;
wxFlexGridSizer* FlexGridSizer3;
wxFlexGridSizer* FlexGridSizer2;
wxFlexGridSizer* FlexGridSizer1;
wxFlexGridSizer* FlexGridSizer17;
Create(parent, wxID_ANY, _("Choose a file"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER, _T("wxID_ANY"));
FlexGridSizer1 = new wxFlexGridSizer(0, 1, 0, 0);
FlexGridSizer1->AddGrowableCol(0);
FlexGridSizer1->AddGrowableRow(0);
FlexGridSizer2 = new wxFlexGridSizer(0, 1, 0, 0);
FlexGridSizer2->AddGrowableCol(0);
StaticText1 = new wxStaticText(this, ID_STATICTEXT1, _("Enter a file name :"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT1"));
FlexGridSizer2->Add(StaticText1, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
FlexGridSizer3 = new wxFlexGridSizer(0, 3, 0, 0);
FlexGridSizer3->AddGrowableCol(0);
fileEdit = new wxTextCtrl(this, ID_TEXTCTRL1, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL1"));
FlexGridSizer3->Add(fileEdit, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
browseBt = new wxButton(this, ID_BUTTON1, _("..."), wxDefaultPosition, wxSize(38,23), 0, wxDefaultValidator, _T("ID_BUTTON1"));
FlexGridSizer3->Add(browseBt, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
FlexGridSizer2->Add(FlexGridSizer3, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
StaticText2 = new wxStaticText(this, ID_STATICTEXT2, _("The file is relative to the directory of the .gdg file."), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT2"));
FlexGridSizer2->Add(StaticText2, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
FlexGridSizer1->Add(FlexGridSizer2, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
StaticLine1 = new wxStaticLine(this, ID_STATICLINE1, wxDefaultPosition, wxSize(10,-1), wxLI_HORIZONTAL, _T("ID_STATICLINE1"));
FlexGridSizer1->Add(StaticLine1, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
FlexGridSizer4 = new wxFlexGridSizer(0, 4, 0, 0);
FlexGridSizer4->AddGrowableCol(1);
FlexGridSizer4->AddGrowableRow(0);
FlexGridSizer17 = new wxFlexGridSizer(0, 3, 0, 0);
FlexGridSizer17->AddGrowableRow(0);
StaticBitmap2 = new wxStaticBitmap(this, ID_STATICBITMAP2, gd::SkinHelper::GetIcon("help", 16), wxDefaultPosition, wxDefaultSize, wxNO_BORDER, _T("ID_STATICBITMAP2"));
FlexGridSizer17->Add(StaticBitmap2, 1, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
helpBt = new wxHyperlinkCtrl(this, ID_HYPERLINKCTRL1, _("Help"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_CONTEXTMENU|wxHL_ALIGN_CENTRE|wxNO_BORDER, _T("ID_HYPERLINKCTRL1"));
helpBt->SetToolTip(_("Display help about this window"));
FlexGridSizer17->Add(helpBt, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
FlexGridSizer4->Add(FlexGridSizer17, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
okBt = new wxButton(this, ID_BUTTON4, _("Ok"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON4"));
FlexGridSizer4->Add(okBt, 1, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5);
cancelBt = new wxButton(this, ID_BUTTON3, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON3"));
FlexGridSizer4->Add(cancelBt, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
advancedBt = new wxButton(this, ID_BUTTON2, _("Advanced"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON2"));
FlexGridSizer4->Add(advancedBt, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
FlexGridSizer1->Add(FlexGridSizer4, 1, wxALL|wxEXPAND|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 0);
SetSizer(FlexGridSizer1);
FlexGridSizer1->Fit(this);
FlexGridSizer1->SetSizeHints(this);
Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&ChoiceFile::OnbrowseBtClick);
Connect(ID_HYPERLINKCTRL1,wxEVT_COMMAND_HYPERLINK,(wxObjectEventFunction)&ChoiceFile::OnhelpBtClick);
Connect(ID_BUTTON4,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&ChoiceFile::OnokBtClick);
Connect(ID_BUTTON3,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&ChoiceFile::OncancelBtClick);
Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&ChoiceFile::OnadvancedBtClick);
//*)
if ( file.empty() ) file = "\"\"";
fileEdit->ChangeValue(file);
}
ChoiceFile::~ChoiceFile()
{
//(*Destroy(ChoiceFile)
//*)
}
void ChoiceFile::OnadvancedBtClick(wxCommandEvent& event)
{
gd::EditStrExpressionDialog dialog(this, file, game, scene);
if ( dialog.ShowModal() == 1 )
{
file = dialog.GetExpression();
fileEdit->ChangeValue(file);
}
}
void ChoiceFile::OnokBtClick(wxCommandEvent& event)
{
file = fileEdit->GetValue();
EndModal(1);
}
void ChoiceFile::OncancelBtClick(wxCommandEvent& event)
{
EndModal(0);
}
void ChoiceFile::OnbrowseBtClick(wxCommandEvent& event)
{
wxString gameDirectory = wxFileName::FileName(game.GetProjectFile()).GetPath();
wxFileDialog fileDialog(this, _("Choose a file"), gameDirectory, "", "*.*");
if ( fileDialog.ShowModal() == wxID_OK )
{
//Note that the file is relative to the project directory
wxFileName filename(fileDialog.GetPath()); filename.MakeRelativeTo(gameDirectory);
fileEdit->SetValue("\""+filename.GetFullPath()+"\"");
}
}
void ChoiceFile::OnhelpBtClick(wxCommandEvent& event)
{
gd::HelpFileAccess::Get()->OpenPage("gevelop/documentation/manual/events_editor/parameters");
}
| 46.509804
| 189
| 0.756886
|
sutao80216
|
17629f70e7fc6e5676a6b500f7ae693092c5e342
| 49,168
|
cc
|
C++
|
engine/source/console/console.cc
|
itsasc/Necromantia
|
f41dfa045eb2c3500320767553d75f83df10e6f9
|
[
"MIT"
] | null | null | null |
engine/source/console/console.cc
|
itsasc/Necromantia
|
f41dfa045eb2c3500320767553d75f83df10e6f9
|
[
"MIT"
] | null | null | null |
engine/source/console/console.cc
|
itsasc/Necromantia
|
f41dfa045eb2c3500320767553d75f83df10e6f9
|
[
"MIT"
] | null | null | null |
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "platform/platformTLS.h"
#include "platform/threads/thread.h"
#include "console/console.h"
#include "console/consoleInternal.h"
#include "console/consoleObject.h"
#include "io/fileStream.h"
#include "io/resource/resourceManager.h"
#include "console/ast.h"
#include "collection/findIterator.h"
#include "console/consoleTypes.h"
#include "debug/telnetDebugger.h"
#include "sim/simBase.h"
#include "console/compiler.h"
#include "string/stringStack.h"
#include "component/dynamicConsoleMethodComponent.h"
#include "memory/safeDelete.h"
#include <stdarg.h>
#include "output_ScriptBinding.h"
#include "expando_ScriptBinding.h"
#ifndef _HASHTABLE_H
#include "collection/hashTable.h"
#endif
static Mutex* sLogMutex;
extern StringStack STR;
ExprEvalState gEvalState;
StmtNode *statementList;
ConsoleConstructor *ConsoleConstructor::first = NULL;
bool gWarnUndefinedScriptVariables;
static char scratchBuffer[4096];
CON_DECLARE_PARSER(CMD);
// TO-DO: Console debugger stuff to be cleaned up later
static S32 dbgGetCurrentFrame(void)
{
return gEvalState.stack.size() - 1;
}
static const char * prependDollar ( const char * name )
{
if(name[0] != '$')
{
S32 len = dStrlen(name);
AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
scratchBuffer[0] = '$';
dMemcpy(scratchBuffer + 1, name, len + 1);
name = scratchBuffer;
}
return name;
}
static const char * prependPercent ( const char * name )
{
if(name[0] != '%')
{
S32 len = dStrlen(name);
AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
scratchBuffer[0] = '%';
dMemcpy(scratchBuffer + 1, name, len + 1);
name = scratchBuffer;
}
return name;
}
//--------------------------------------
void ConsoleConstructor::init(const char *cName, const char *fName, const char *usg, S32 minArgs, S32 maxArgs)
{
mina = minArgs;
maxa = maxArgs;
funcName = fName;
usage = usg;
className = cName;
sc = 0; fc = 0; vc = 0; bc = 0; ic = 0;
group = false;
next = first;
ns = false;
first = this;
}
void ConsoleConstructor::setup()
{
for(ConsoleConstructor *walk = first; walk; walk = walk->next)
{
if(walk->sc)
Con::addCommand(walk->className, walk->funcName, walk->sc, walk->usage, walk->mina, walk->maxa);
else if(walk->ic)
Con::addCommand(walk->className, walk->funcName, walk->ic, walk->usage, walk->mina, walk->maxa);
else if(walk->fc)
Con::addCommand(walk->className, walk->funcName, walk->fc, walk->usage, walk->mina, walk->maxa);
else if(walk->vc)
Con::addCommand(walk->className, walk->funcName, walk->vc, walk->usage, walk->mina, walk->maxa);
else if(walk->bc)
Con::addCommand(walk->className, walk->funcName, walk->bc, walk->usage, walk->mina, walk->maxa);
else if(walk->group)
Con::markCommandGroup(walk->className, walk->funcName, walk->usage);
else if(walk->overload)
Con::addOverload(walk->className, walk->funcName, walk->usage);
else if(walk->ns)
{
Namespace* ns = Namespace::find(StringTable->insert(walk->className));
if( ns )
ns->mUsage = walk->usage;
}
else
AssertFatal(false, "Found a ConsoleConstructor with an indeterminate type!");
}
}
ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, StringCallback sfunc, const char *usage, S32 minArgs, S32 maxArgs)
{
init(className, funcName, usage, minArgs, maxArgs);
sc = sfunc;
}
ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, IntCallback ifunc, const char *usage, S32 minArgs, S32 maxArgs)
{
init(className, funcName, usage, minArgs, maxArgs);
ic = ifunc;
}
ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, FloatCallback ffunc, const char *usage, S32 minArgs, S32 maxArgs)
{
init(className, funcName, usage, minArgs, maxArgs);
fc = ffunc;
}
ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, VoidCallback vfunc, const char *usage, S32 minArgs, S32 maxArgs)
{
init(className, funcName, usage, minArgs, maxArgs);
vc = vfunc;
}
ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, BoolCallback bfunc, const char *usage, S32 minArgs, S32 maxArgs)
{
init(className, funcName, usage, minArgs, maxArgs);
bc = bfunc;
}
ConsoleConstructor::ConsoleConstructor(const char* className, const char* groupName, const char* aUsage)
{
init(className, groupName, usage, -1, -2);
group = true;
// Somewhere, the entry list is getting flipped, partially.
// so we have to do tricks to deal with making sure usage
// is properly populated.
// This is probably redundant.
static char * lastUsage = NULL;
if(aUsage)
lastUsage = (char *)aUsage;
usage = lastUsage;
}
ConsoleConstructor::ConsoleConstructor(const char* className, const char* usage)
{
init(className, NULL, usage, -1, -2);
ns = true;
}
namespace Con
{
static Vector<ConsumerCallback> gConsumers(__FILE__, __LINE__);
static DataChunker consoleLogChunker;
static Vector<ConsoleLogEntry> consoleLog(__FILE__, __LINE__);
static bool consoleLogLocked;
static bool logBufferEnabled=true;
static S32 printLevel = 10;
static FileStream consoleLogFile;
static const char *defLogFileName = "console.log";
static S32 consoleLogMode = 0;
static bool active = false;
static bool newLogFile;
static const char *logFileName;
static const int MaxCompletionBufferSize = 4096;
static char completionBuffer[MaxCompletionBufferSize];
static char tabBuffer[MaxCompletionBufferSize] = {0};
static SimObjectPtr<SimObject> tabObject;
static U32 completionBaseStart;
static U32 completionBaseLen;
#ifdef TORQUE_MULTITHREAD
static ThreadIdent gMainThreadID = -1;
#endif
/// Current script file name and root, these are registered as
/// console variables.
/// @{
///
StringTableEntry gCurrentFile;
StringTableEntry gCurrentRoot;
/// @}
void init()
{
AssertFatal(active == false, "Con::init should only be called once.");
// Set up general init values.
active = true;
logFileName = NULL;
newLogFile = true;
gWarnUndefinedScriptVariables = false;
sLogMutex = new Mutex;
#ifdef TORQUE_MULTITHREAD
// Note the main thread ID.
gMainThreadID = ThreadManager::getCurrentThreadId();
#endif
// Initialize subsystems.
Namespace::init();
ConsoleConstructor::setup();
// Set up the parser(s)
CON_ADD_PARSER(CMD, "cs", true); // TorqueScript
// Variables
setVariable("Con::prompt", "% ");
addVariable("Con::logBufferEnabled", TypeBool, &logBufferEnabled);
addVariable("Con::printLevel", TypeS32, &printLevel);
addVariable("Con::warnUndefinedVariables", TypeBool, &gWarnUndefinedScriptVariables);
// Current script file name and root
Con::addVariable( "Con::File", TypeString, &gCurrentFile );
Con::addVariable( "Con::Root", TypeString, &gCurrentRoot );
// Setup the console types.
ConsoleBaseType::initialize();
// And finally, the ACR...
AbstractClassRep::initialize();
}
//--------------------------------------
void shutdown()
{
AssertFatal(active == true, "Con::shutdown should only be called once.");
active = false;
consoleLogFile.close();
Namespace::shutdown();
SAFE_DELETE( sLogMutex );
}
bool isActive()
{
return active;
}
bool isMainThread()
{
#ifdef TORQUE_MULTITHREAD
return ThreadManager::isCurrentThread(gMainThreadID);
#else
// If we're single threaded we're always in the main thread.
return true;
#endif
}
//--------------------------------------
void getLockLog(ConsoleLogEntry *&log, U32 &size)
{
consoleLogLocked = true;
log = consoleLog.address();
size = consoleLog.size();
}
void unlockLog()
{
consoleLogLocked = false;
}
U32 tabComplete(char* inputBuffer, U32 cursorPos, U32 maxResultLength, bool forwardTab)
{
// Check for null input.
if (!inputBuffer[0])
{
return cursorPos;
}
// Cap the max result length.
if (maxResultLength > MaxCompletionBufferSize)
{
maxResultLength = MaxCompletionBufferSize;
}
// See if this is the same partial text as last checked.
if (dStrcmp(tabBuffer, inputBuffer))
{
// If not...
// Save it for checking next time.
dStrcpy(tabBuffer, inputBuffer);
// Scan backward from the cursor position to find the base to complete from.
S32 p = cursorPos;
while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '.') && (inputBuffer[p - 1] != '('))
{
p--;
}
completionBaseStart = p;
completionBaseLen = cursorPos - p;
// Is this function being invoked on an object?
if (inputBuffer[p - 1] == '.')
{
// If so...
if (p <= 1)
{
// Bail if no object identifier.
return cursorPos;
}
// Find the object identifier.
S32 objLast = --p;
while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '('))
{
p--;
}
if (objLast == p)
{
// Bail if no object identifier.
return cursorPos;
}
// Look up the object identifier.
dStrncpy(completionBuffer, inputBuffer + p, objLast - p);
completionBuffer[objLast - p] = 0;
tabObject = Sim::findObject(completionBuffer);
if (!bool(tabObject))
{
// Bail if not found.
return cursorPos;
}
}
else
{
// Not invoked on an object; we'll use the global namespace.
tabObject = 0;
}
}
// Chop off the input text at the cursor position.
inputBuffer[cursorPos] = 0;
// Try to find a completion in the appropriate namespace.
const char *newText;
if (bool(tabObject))
{
newText = tabObject->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
}
else
{
// In the global namespace, we can complete on global vars as well as functions.
if (inputBuffer[completionBaseStart] == '$')
{
newText = gEvalState.globalVars.tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
}
else
{
newText = Namespace::global()->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
}
}
if (newText)
{
// If we got something, append it to the input text.
S32 len = dStrlen(newText);
if (len + completionBaseStart > maxResultLength)
{
len = maxResultLength - completionBaseStart;
}
dStrncpy(inputBuffer + completionBaseStart, newText, len);
inputBuffer[completionBaseStart + len] = 0;
// And set the cursor after it.
cursorPos = completionBaseStart + len;
}
// Save the modified input buffer for checking next time.
dStrcpy(tabBuffer, inputBuffer);
// Return the new (maybe) cursor position.
return cursorPos;
}
//------------------------------------------------------------------------------
static void log(const char *string)
{
// Lock.
MutexHandle mutex;
if( sLogMutex )
mutex.lock( sLogMutex, true );
// Bail if we ain't logging.
if (!consoleLogMode)
{
return;
}
// In mode 1, we open, append, close on each log write.
if ((consoleLogMode & 0x3) == 1)
{
consoleLogFile.open(defLogFileName, FileStream::ReadWrite);
}
// Write to the log if its status is hunky-dory.
if ((consoleLogFile.getStatus() == Stream::Ok) || (consoleLogFile.getStatus() == Stream::EOS))
{
consoleLogFile.setPosition(consoleLogFile.getStreamSize());
// If this is the first write...
if (newLogFile)
{
// Make a header.
Platform::LocalTime lt;
Platform::getLocalTime(lt);
char buffer[128];
dSprintf(buffer, sizeof(buffer), "//-------------------------- %d/%d/%d -- %02d:%02d:%02d -----\r\n",
lt.month + 1,
lt.monthday,
lt.year + 1900,
lt.hour,
lt.min,
lt.sec);
consoleLogFile.write(dStrlen(buffer), buffer);
newLogFile = false;
if (consoleLogMode & 0x4)
{
// Dump anything that has been printed to the console so far.
consoleLogMode -= 0x4;
U32 size, line;
ConsoleLogEntry *log;
getLockLog(log, size);
for (line = 0; line < size; line++)
{
consoleLogFile.write(dStrlen(log[line].mString), log[line].mString);
consoleLogFile.write(2, "\r\n");
}
unlockLog();
}
}
// Now write what we came here to write.
consoleLogFile.write(dStrlen(string), string);
consoleLogFile.write(2, "\r\n");
}
if ((consoleLogMode & 0x3) == 1)
{
consoleLogFile.close();
}
}
//------------------------------------------------------------------------------
void cls( void )
{
if(consoleLogLocked)
return;
consoleLogChunker.freeBlocks();
consoleLog.setSize(0);
};
//------------------------------------------------------------------------------
#if defined( _MSC_VER )
#include <windows.h>
static void _outputDebugString(char* pString)
{
// Format string.
char* pBuffer = pString;
S32 stringLength = dStrlen(pString);
pBuffer += stringLength;
*pBuffer++ = '\r';
*pBuffer++ = '\n';
*pBuffer = '\0';
stringLength = strlen(pString) + 1;
wchar_t *wstr = new wchar_t[stringLength];
dMemset( wstr, 0, stringLength );
// Convert to wide string.
Con::MultiByteToWideChar( CP_ACP, NULL, pString, -1, wstr, stringLength );
// Output string.
Con::OutputDebugStringW( wstr );
delete [] wstr;
}
#endif
//------------------------------------------------------------------------------
static void _printf(ConsoleLogEntry::Level level, ConsoleLogEntry::Type type, const char* fmt)
{
Con::active = false;
char buffer[4096];
U32 offset = 0;
if(gEvalState.traceOn && gEvalState.stack.size())
{
offset = gEvalState.stack.size() * 3;
for(U32 i = 0; i < offset; i++)
buffer[i] = ' ';
}
dSprintf(buffer + offset, sizeof(buffer) - offset, "%s", fmt);
for(U32 i = 0; i < (U32)gConsumers.size(); i++)
gConsumers[i](level, buffer);
Platform::cprintf(buffer);
if(logBufferEnabled || consoleLogMode)
{
char *pos = buffer;
while(*pos)
{
if(*pos == '\t')
*pos = '^';
pos++;
}
pos = buffer;
for(;;)
{
char *eofPos = dStrchr(pos, '\n');
if(eofPos)
*eofPos = 0;
log(pos);
if(logBufferEnabled && !consoleLogLocked)
{
ConsoleLogEntry entry;
entry.mLevel = level;
entry.mType = type;
entry.mString = (const char *)consoleLogChunker.alloc(dStrlen(pos) + 1);
dStrcpy(const_cast<char*>(entry.mString), pos);
consoleLog.push_back(entry);
}
if(!eofPos)
break;
pos = eofPos + 1;
}
}
Con::active = true;
#if defined( _MSC_VER )
_outputDebugString( buffer );
#endif
}
//------------------------------------------------------------------------------
class ConPrinfThreadedEvent : public SimEvent
{
ConsoleLogEntry::Level mLevel;
ConsoleLogEntry::Type mType;
char *mBuf;
public:
ConPrinfThreadedEvent(ConsoleLogEntry::Level level = ConsoleLogEntry::Normal, ConsoleLogEntry::Type type = ConsoleLogEntry::General, const char *buf = NULL)
{
mLevel = level;
mType = type;
if(buf)
{
mBuf = (char*)dMalloc(dStrlen(buf)+1);
dMemcpy((void*)mBuf, (void*)buf, dStrlen(buf));
mBuf[dStrlen(buf)] = 0;
}
else
mBuf = NULL;
}
~ConPrinfThreadedEvent()
{
SAFE_FREE(mBuf);
}
virtual void process(SimObject *object)
{
if(mBuf)
{
switch(mLevel)
{
case ConsoleLogEntry::Normal :
Con::printf(mBuf);
break;
case ConsoleLogEntry::Warning :
Con::warnf(mType, mBuf);
break;
case ConsoleLogEntry::Error :
Con::errorf(mType, mBuf);
break;
case ConsoleLogEntry::NUM_CLASS :
Con::errorf("Unhandled case NUM_CLASS");
break;
}
}
}
};
//------------------------------------------------------------------------------
void printf(const char* fmt,...)
{
va_list argptr;
va_start(argptr, fmt);
char buf[8192];
dVsprintf(buf, sizeof(buf), fmt, argptr);
if(!isMainThread())
Sim::postEvent(Sim::getRootGroup(), new ConPrinfThreadedEvent(ConsoleLogEntry::Normal, ConsoleLogEntry::General, buf), Sim::getTargetTime());
else
_printf(ConsoleLogEntry::Normal, ConsoleLogEntry::General, buf);
va_end(argptr);
}
void warnf(ConsoleLogEntry::Type type, const char* fmt,...)
{
va_list argptr;
va_start(argptr, fmt);
char buf[8192];
dVsprintf(buf, sizeof(buf), fmt, argptr);
if(!isMainThread())
Sim::postEvent(Sim::getRootGroup(), new ConPrinfThreadedEvent(ConsoleLogEntry::Warning, type, buf), Sim::getTargetTime());
else
_printf(ConsoleLogEntry::Warning, type, buf);
va_end(argptr);
}
void errorf(ConsoleLogEntry::Type type, const char* fmt,...)
{
va_list argptr;
va_start(argptr, fmt);
char buf[8192];
dVsprintf(buf, sizeof(buf), fmt, argptr);
if(!isMainThread())
Sim::postEvent(Sim::getRootGroup(), new ConPrinfThreadedEvent(ConsoleLogEntry::Error, type, buf), Sim::getTargetTime());
else
_printf(ConsoleLogEntry::Error, type, buf);
va_end(argptr);
}
void warnf(const char* fmt,...)
{
va_list argptr;
va_start(argptr, fmt);
char buf[8192];
dVsprintf(buf, sizeof(buf), fmt, argptr);
if(!isMainThread())
Sim::postEvent(Sim::getRootGroup(), new ConPrinfThreadedEvent(ConsoleLogEntry::Warning, ConsoleLogEntry::General, buf), Sim::getTargetTime());
else
_printf(ConsoleLogEntry::Warning, ConsoleLogEntry::General, buf);
va_end(argptr);
}
void errorf(const char* fmt,...)
{
va_list argptr;
va_start(argptr, fmt);
char buf[8192];
dVsprintf(buf, sizeof(buf), fmt, argptr);
if(!isMainThread())
Sim::postEvent(Sim::getRootGroup(), new ConPrinfThreadedEvent(ConsoleLogEntry::Error, ConsoleLogEntry::General, buf), Sim::getTargetTime());
else
_printf(ConsoleLogEntry::Error, ConsoleLogEntry::General, buf);
va_end(argptr);
}
//---------------------------------------------------------------------------
void setVariable(const char *name, const char *value)
{
name = prependDollar(name);
gEvalState.globalVars.setVariable(StringTable->insert(name), value);
}
void setLocalVariable(const char *name, const char *value)
{
name = prependPercent(name);
gEvalState.stack.last()->setVariable(StringTable->insert(name), value);
}
void setBoolVariable(const char *varName, bool value)
{
setVariable(varName, value ? "1" : "0");
}
void setIntVariable(const char *varName, S32 value)
{
char scratchBuffer[32];
dSprintf(scratchBuffer, sizeof(scratchBuffer), "%d", value);
setVariable(varName, scratchBuffer);
}
void setFloatVariable(const char *varName, F32 value)
{
char scratchBuffer[32];
dSprintf(scratchBuffer, sizeof(scratchBuffer), "%.9g", value);
setVariable(varName, scratchBuffer);
}
//---------------------------------------------------------------------------
void addConsumer(ConsumerCallback consumer)
{
gConsumers.push_back(consumer);
}
// dhc - found this empty -- trying what I think is a reasonable impl.
void removeConsumer(ConsumerCallback consumer)
{
for(U32 i = 0; i < (U32)gConsumers.size(); i++)
if (gConsumers[i] == consumer)
{ // remove it from the list.
gConsumers.erase(i);
break;
}
}
void stripColorChars(char* line)
{
char* c = line;
char cp = *c;
while (cp)
{
if (cp < 18)
{
// Could be a color control character; let's take a closer look.
if ((cp != 8) && (cp != 9) && (cp != 10) && (cp != 13))
{
// Yep... copy following chars forward over this.
char* cprime = c;
char cpp;
do
{
cpp = *++cprime;
*(cprime - 1) = cpp;
}
while (cpp);
// Back up 1 so we'll check this position again post-copy.
c--;
}
}
cp = *++c;
}
}
const char *getVariable(const char *name)
{
// get the field info from the object..
if(name[0] != '$' && dStrchr(name, '.') && !isFunction(name))
{
S32 len = dStrlen(name);
AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - name too long");
dMemcpy(scratchBuffer, name, len+1);
char * token = dStrtok(scratchBuffer, ".");
SimObject * obj = Sim::findObject(token);
if(!obj)
return("");
token = dStrtok(0, ".\0");
if(!token)
return("");
while(token != NULL)
{
const char * val = obj->getDataField(StringTable->insert(token), 0);
if(!val)
return("");
token = dStrtok(0, ".\0");
if(token)
{
obj = Sim::findObject(token);
if(!obj)
return("");
}
else
return(val);
}
}
name = prependDollar(name);
return gEvalState.globalVars.getVariable(StringTable->insert(name));
}
const char *getLocalVariable(const char *name)
{
name = prependPercent(name);
return gEvalState.stack.last()->getVariable(StringTable->insert(name));
}
bool getBoolVariable(const char *varName, bool def)
{
const char *value = getVariable(varName);
return *value ? dAtob(value) : def;
}
S32 getIntVariable(const char *varName, S32 def)
{
const char *value = getVariable(varName);
return *value ? dAtoi(value) : def;
}
F32 getFloatVariable(const char *varName, F32 def)
{
const char *value = getVariable(varName);
return *value ? dAtof(value) : def;
}
//---------------------------------------------------------------------------
bool addVariable(const char *name, S32 t, void *dp)
{
gEvalState.globalVars.addVariable(name, t, dp);
return true;
}
bool removeVariable(const char *name)
{
name = StringTable->lookup(prependDollar(name));
return name!=0 && gEvalState.globalVars.removeVariable(name);
}
//---------------------------------------------------------------------------
void addCommand(const char *nsName, const char *name,StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs)
{
Namespace *ns = lookupNamespace(nsName);
ns->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
}
void addCommand(const char *nsName, const char *name,VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs)
{
Namespace *ns = lookupNamespace(nsName);
ns->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
}
void addCommand(const char *nsName, const char *name,IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs)
{
Namespace *ns = lookupNamespace(nsName);
ns->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
}
void addCommand(const char *nsName, const char *name,FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs)
{
Namespace *ns = lookupNamespace(nsName);
ns->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
}
void addCommand(const char *nsName, const char *name,BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs)
{
Namespace *ns = lookupNamespace(nsName);
ns->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
}
void markCommandGroup(const char * nsName, const char *name, const char* usage)
{
Namespace *ns = lookupNamespace(nsName);
ns->markGroup(name,usage);
}
void beginCommandGroup(const char * nsName, const char *name, const char* usage)
{
markCommandGroup(nsName, name, usage);
}
void endCommandGroup(const char * nsName, const char *name)
{
markCommandGroup(nsName, name, NULL);
}
void addOverload(const char * nsName, const char * name, const char * altUsage)
{
Namespace *ns = lookupNamespace(nsName);
ns->addOverload(name,altUsage);
}
void addCommand(const char *name,StringCallback cb,const char *usage, S32 minArgs, S32 maxArgs)
{
Namespace::global()->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
}
void addCommand(const char *name,VoidCallback cb,const char *usage, S32 minArgs, S32 maxArgs)
{
Namespace::global()->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
}
void addCommand(const char *name,IntCallback cb,const char *usage, S32 minArgs, S32 maxArgs)
{
Namespace::global()->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
}
void addCommand(const char *name,FloatCallback cb,const char *usage, S32 minArgs, S32 maxArgs)
{
Namespace::global()->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
}
void addCommand(const char *name,BoolCallback cb,const char *usage, S32 minArgs, S32 maxArgs)
{
Namespace::global()->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
}
const char *evaluate(const char* string, bool echo, const char *fileName)
{
if (echo)
Con::printf("%s%s", getVariable( "$Con::Prompt" ), string);
if(fileName)
fileName = StringTable->insert(fileName);
CodeBlock *newCodeBlock = new CodeBlock();
return newCodeBlock->compileExec(fileName, string, false, fileName ? -1 : 0);
}
//------------------------------------------------------------------------------
const char *evaluatef(const char* string, ...)
{
const char * result = NULL;
char * buffer = new char[4096];
if (buffer != NULL)
{
va_list args;
va_start(args, string);
dVsprintf(buffer, 4096, string, args);
va_end (args);
CodeBlock *newCodeBlock = new CodeBlock();
result = newCodeBlock->compileExec(NULL, buffer, false, 0);
delete [] buffer;
buffer = NULL;
}
return result;
}
const char *execute(S32 argc, const char *argv[])
{
#ifdef TORQUE_MULTITHREAD
if(isMainThread())
{
#endif
Namespace::Entry *ent;
StringTableEntry funcName = StringTable->insert(argv[0]);
ent = Namespace::global()->lookup(funcName);
if(!ent)
{
warnf(ConsoleLogEntry::Script, "%s: Unknown command.", argv[0]);
// Clean up arg buffers, if any.
STR.clearFunctionOffset();
return "";
}
const char *ret = ent->execute(argc, argv, &gEvalState);
// Reset the function offset so the stack
// doesn't continue to grow unnecessarily
STR.clearFunctionOffset();
return ret;
#ifdef TORQUE_MULTITHREAD
}
else
{
SimConsoleThreadExecCallback cb;
SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, false, &cb);
Sim::postEvent(Sim::getRootGroup(), evt, Sim::getCurrentTime());
return cb.waitForResult();
}
#endif
}
//------------------------------------------------------------------------------
const char *execute(SimObject *object, S32 argc, const char *argv[],bool thisCallOnly)
{
static char idBuf[16];
if(argc < 2)
return "";
// [neo, 10/05/2007 - #3010]
// Make sure we don't get recursive calls, respect the flag!
// Should we be calling handlesMethod() first?
if( !thisCallOnly )
{
DynamicConsoleMethodComponent *com = dynamic_cast<DynamicConsoleMethodComponent *>(object);
if(com)
com->callMethodArgList(argc, argv, false);
}
if(object->getNamespace())
{
StringTableEntry funcName = StringTable->insert(argv[0]);
Namespace::Entry *ent = object->getNamespace()->lookup(funcName);
if(ent == NULL)
{
//warnf(ConsoleLogEntry::Script, "%s: undefined for object '%s' - id %d", funcName, object->getName(), object->getId());
// Clean up arg buffers, if any.
STR.clearFunctionOffset();
return "";
}
// Twiddle %this argument
const char *oldArg1 = argv[1];
dSprintf(idBuf, sizeof(idBuf), "%d", object->getId());
argv[1] = idBuf;
object->pushScriptCallbackGuard();
SimObject *save = gEvalState.thisObject;
gEvalState.thisObject = object;
const char *ret = ent->execute(argc, argv, &gEvalState);
gEvalState.thisObject = save;
object->popScriptCallbackGuard();
// Twiddle it back
argv[1] = oldArg1;
// Reset the function offset so the stack
// doesn't continue to grow unnecessarily
STR.clearFunctionOffset();
return ret;
}
warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), argv[0]);
return "";
}
const char *executef(SimObject *object, S32 argc, ...)
{
const char *argv[128];
va_list args;
va_start(args, argc);
for(S32 i = 0; i < argc; i++)
argv[i+1] = va_arg(args, const char *);
va_end(args);
argv[0] = argv[1];
argc++;
return execute(object, argc, argv);
}
//------------------------------------------------------------------------------
const char *executef(S32 argc, ...)
{
const char *argv[128];
va_list args;
va_start(args, argc);
for(S32 i = 0; i < argc; i++)
argv[i] = va_arg(args, const char *);
va_end(args);
return execute(argc, argv);
}
//------------------------------------------------------------------------------
bool isFunction(const char *fn)
{
const char *string = StringTable->lookup(fn);
if(!string)
return false;
else
return Namespace::global()->lookup(string) != NULL;
}
//------------------------------------------------------------------------------
void setLogMode(S32 newMode)
{
if ((newMode & 0x3) != (consoleLogMode & 0x3))
{
if (newMode && !consoleLogMode)
{
// Enabling logging when it was previously disabled.
newLogFile = true;
}
if ((consoleLogMode & 0x3) == 2)
{
// Changing away from mode 2, must close logfile.
consoleLogFile.close();
}
else if ((newMode & 0x3) == 2)
{
// Starting mode 2, must open logfile.
consoleLogFile.open(defLogFileName, FileStream::Write);
}
consoleLogMode = newMode;
}
}
Namespace *lookupNamespace(const char *ns)
{
if(!ns)
return Namespace::global();
return Namespace::find(StringTable->insert(ns));
}
bool linkNamespaces(const char *parent, const char *child)
{
Namespace *pns = lookupNamespace(parent);
Namespace *cns = lookupNamespace(child);
if(pns && cns)
return cns->classLinkTo(pns);
return false;
}
bool unlinkNamespaces(const char *parent, const char *child)
{
Namespace *pns = lookupNamespace(parent);
Namespace *cns = lookupNamespace(child);
if(pns && cns)
return cns->unlinkClass(pns);
return false;
}
bool classLinkNamespaces(Namespace *parent, Namespace *child)
{
if(parent && child)
return child->classLinkTo(parent);
return false;
}
void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, EnumTable *tbl, BitSet32 flag)
{
ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
AssertFatal(cbt, "Con::setData - could not resolve type ID!");
cbt->setData((void *) (((const char *)dptr) + index * cbt->getTypeSize()),argc, argv, tbl, flag);
}
const char *getData(S32 type, void *dptr, S32 index, EnumTable *tbl, BitSet32 flag)
{
ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
AssertFatal(cbt, "Con::getData - could not resolve type ID!");
return cbt->getData((void *) (((const char *)dptr) + index * cbt->getTypeSize()), tbl, flag);
}
//------------------------------------------------------------------------------
StringTableEntry getModNameFromPath(const char *path)
{
if(path == NULL || *path == 0)
return NULL;
char buf[1024];
buf[0] = 0;
if(path[0] == '/' || path[1] == ':')
{
// It's an absolute path
const StringTableEntry exePath = Platform::getMainDotCsDir();
U32 len = dStrlen(exePath);
if(dStrnicmp(exePath, path, len) == 0)
{
const char *ptr = path + len + 1;
const char *slash = dStrchr(ptr, '/');
if(slash)
{
dStrncpy(buf, ptr, slash - ptr);
buf[slash - ptr] = 0;
}
else
return NULL;
}
else
return NULL;
}
else
{
const char *slash = dStrchr(path, '/');
if(slash)
{
dStrncpy(buf, path, slash - path);
buf[slash - path] = 0;
}
else
return NULL;
}
return StringTable->insert(buf);
}
//-----------------------------------------------------------------------------
typedef HashMap<StringTableEntry, StringTableEntry> typePathExpandoMap;
static typePathExpandoMap PathExpandos;
//-----------------------------------------------------------------------------
void addPathExpando( const char* pExpandoName, const char* pPath )
{
// Sanity!
AssertFatal( pExpandoName != NULL, "Expando name cannot be NULL." );
AssertFatal( pPath != NULL, "Expando path cannot be NULL." );
// Fetch expando name.
StringTableEntry expandoName = StringTable->insert( pExpandoName );
// Fetch the length of the path.
S32 pathLength = dStrlen(pPath);
char pathBuffer[1024];
// Sanity!
if ( pathLength == 0 || pathLength >= sizeof(pathBuffer) )
{
Con::warnf( "Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath );
return;
}
// Strip repeat slashes.
if ( !Con::stripRepeatSlashes(pathBuffer, pPath, sizeof(pathBuffer) ) )
{
Con::warnf( "Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath );
return;
}
// Fetch new path length.
pathLength = dStrlen(pathBuffer);
// Sanity!
if ( pathLength == 0 )
{
Con::warnf( "Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath );
return;
}
// Remove any terminating slash.
if (pathBuffer[pathLength-1] == '/')
pathBuffer[pathLength-1] = 0;
// Fetch expanded path.
StringTableEntry expandedPath = StringTable->insert( pathBuffer );
// Info.
#if defined(TORQUE_DEBUG)
Con::printf("Adding path expando of '%s' as '%s'.", expandoName, expandedPath );
#endif
// Find any existing path expando.
typePathExpandoMap::iterator expandoItr = PathExpandos.find( pExpandoName );
// Does the expando exist?
if( expandoItr != PathExpandos.end() )
{
// Yes, so modify the path.
expandoItr->value = expandedPath;
return;
}
// Insert expando.
PathExpandos.insert( expandoName, expandedPath );
}
//-----------------------------------------------------------------------------
StringTableEntry getPathExpando( const char* pExpandoName )
{
// Sanity!
AssertFatal( pExpandoName != NULL, "Expando name cannot be NULL." );
// Fetch expando name.
StringTableEntry expandoName = StringTable->insert( pExpandoName );
// Find any existing path expando.
typePathExpandoMap::iterator expandoItr = PathExpandos.find( expandoName );
// Does the expando exist?
if( expandoItr != PathExpandos.end() )
{
// Yes, so return it.
return expandoItr->value;
}
// Not found.
return NULL;
}
//-----------------------------------------------------------------------------
void removePathExpando( const char* pExpandoName )
{
// Sanity!
AssertFatal( pExpandoName != NULL, "Expando name cannot be NULL." );
// Fetch expando name.
StringTableEntry expandoName = StringTable->insert( pExpandoName );
// Find any existing path expando.
typePathExpandoMap::iterator expandoItr = PathExpandos.find( expandoName );
// Does the expando exist?
if ( expandoItr == PathExpandos.end() )
{
// No, so warn.
#if defined(TORQUE_DEBUG)
Con::warnf("Removing path expando of '%s' but it does not exist.", expandoName );
#endif
return;
}
// Info.
#if defined(TORQUE_DEBUG)
Con::printf("Removing path expando of '%s' as '%s'.", expandoName, expandoItr->value );
#endif
// Remove expando.
PathExpandos.erase( expandoItr );
}
//-----------------------------------------------------------------------------
bool isPathExpando( const char* pExpandoName )
{
// Sanity!
AssertFatal( pExpandoName != NULL, "Expando name cannot be NULL." );
// Fetch expando name.
StringTableEntry expandoName = StringTable->insert( pExpandoName );
return PathExpandos.contains( expandoName );
}
//-----------------------------------------------------------------------------
U32 getPathExpandoCount( void )
{
return PathExpandos.size();
}
//-----------------------------------------------------------------------------
StringTableEntry getPathExpandoKey( U32 expandoIndex )
{
// Finish if index is out of range.
if ( expandoIndex >= PathExpandos.size() )
return NULL;
// Find indexed iterator.
typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
while( expandoIndex > 0 ) { ++expandoItr; --expandoIndex; }
return expandoItr->key;
}
//-----------------------------------------------------------------------------
StringTableEntry getPathExpandoValue( U32 expandoIndex )
{
// Finish if index is out of range.
if ( expandoIndex >= PathExpandos.size() )
return NULL;
// Find indexed iterator.
typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
while( expandoIndex > 0 ) { ++expandoItr; --expandoIndex; }
return expandoItr->value;
}
//-----------------------------------------------------------------------------
bool expandPath( char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint, const bool ensureTrailingSlash )
{
char pathBuffer[2048];
const char* pSrc = pSrcPath;
char* pSlash;
// Fetch leading character.
const char leadingToken = *pSrc;
// Fetch following token.
const char followingToken = leadingToken != 0 ? pSrc[1] : 0;
// Expando.
if ( leadingToken == '^' )
{
// Initial prefix search.
const char* pPrefixSrc = pSrc+1;
char* pPrefixDst = pathBuffer;
// Search for end of expando.
while( *pPrefixSrc != '/' && *pPrefixSrc != 0 )
{
// Copy prefix character.
*pPrefixDst++ = *pPrefixSrc++;
}
// Yes, so terminate the expando string.
*pPrefixDst = 0;
// Fetch the expando path.
StringTableEntry expandoPath = getPathExpando(pathBuffer);
// Does the expando exist?
if( expandoPath == NULL )
{
// No, so error.
Con::errorf("expandPath() : Could not find path expando '%s' for path '%s'.", pathBuffer, pSrcPath );
// Are we ensuring the trailing slash?
if ( ensureTrailingSlash )
{
// Yes, so ensure it.
Con::ensureTrailingSlash( pDstPath, pSrcPath );
}
else
{
// No, so just use the source path.
dStrcpy( pDstPath, pSrcPath );
}
return false;
}
// Skip the expando and the following slash.
pSrc += dStrlen(pathBuffer) + 1;
// Format the output path.
dSprintf( pathBuffer, sizeof(pathBuffer), "%s/%s", expandoPath, pSrc );
// Are we ensuring the trailing slash?
if ( ensureTrailingSlash )
{
// Yes, so ensure it.
Con::ensureTrailingSlash( pathBuffer, pathBuffer );
}
// Strip repeat slashes.
Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
return true;
}
// Script-Relative.
if ( leadingToken == '.' )
{
// Fetch the code-block file-path.
const StringTableEntry codeblockFullPath = CodeBlock::getCurrentCodeBlockFullPath();
// Do we have a code block full path?
if( codeblockFullPath == NULL )
{
// No, so error.
Con::errorf("expandPath() : Could not find relative path from code-block for path '%s'.", pSrcPath );
// Are we ensuring the trailing slash?
if ( ensureTrailingSlash )
{
// Yes, so ensure it.
Con::ensureTrailingSlash( pDstPath, pSrcPath );
}
else
{
// No, so just use the source path.
dStrcpy( pDstPath, pSrcPath );
}
return false;
}
// Yes, so use it as the prefix.
dStrncpy(pathBuffer, codeblockFullPath, sizeof(pathBuffer) - 1);
// Find the final slash in the code-block.
pSlash = dStrrchr(pathBuffer, '/');
// Is this a parent directory token?
if ( followingToken == '.' )
{
// Yes, so terminate after the slash so we include it.
pSlash[1] = 0;
}
else
{
// No, it's a current directory token so terminate at the slash so we don't include it.
pSlash[0] = 0;
// Skip the current directory token.
pSrc++;
}
// Format the output path.
dStrncat(pathBuffer, "/", sizeof(pathBuffer) - 1 - strlen(pathBuffer));
dStrncat(pathBuffer, pSrc, sizeof(pathBuffer) - 1 - strlen(pathBuffer));
// Are we ensuring the trailing slash?
if ( ensureTrailingSlash )
{
// Yes, so ensure it.
Con::ensureTrailingSlash( pathBuffer, pathBuffer );
}
// Strip repeat slashes.
Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
return true;
}
// All else.
//Using a special case here because the code below barfs on trying to build a full path for apk reading
#ifdef TORQUE_OS_ANDROID
if (leadingToken == '/' || strstr(pSrcPath, "/") == NULL)
Platform::makeFullPathName( pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint );
else
dSprintf(pathBuffer, sizeof(pathBuffer), "/%s", pSrcPath);
#else
Platform::makeFullPathName( pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint );
#endif
// Are we ensuring the trailing slash?
if ( ensureTrailingSlash )
{
// Yes, so ensure it.
Con::ensureTrailingSlash( pathBuffer, pathBuffer );
}
// Strip repeat slashes.
Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
return true;
}
//-----------------------------------------------------------------------------
bool isBasePath( const char* SrcPath, const char* pBasePath )
{
char expandBuffer[1024];
Con::expandPath( expandBuffer, sizeof(expandBuffer), SrcPath );
return dStrnicmp(pBasePath, expandBuffer, dStrlen( pBasePath ) ) == 0;
}
//-----------------------------------------------------------------------------
void collapsePath( char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint )
{
// Check path against expandos. If there are multiple matches, choose the
// expando that produces the shortest relative path.
char pathBuffer[2048];
// Fetch expando count.
const U32 expandoCount = getPathExpandoCount();
// Iterate expandos.
U32 expandoRelativePathLength = U32_MAX;
for( U32 expandoIndex = 0; expandoIndex < expandoCount; ++expandoIndex )
{
// Fetch expando value (path).
StringTableEntry expandoValue = getPathExpandoValue( expandoIndex );
// Skip if not the base path.
if ( !isBasePath( pSrcPath, expandoValue ) )
continue;
// Fetch path relative to expando path.
StringTableEntry relativePath = Platform::makeRelativePathName( pSrcPath, expandoValue );
// If the relative path is simply a period
if ( relativePath[0] == '.' )
relativePath++;
if ( dStrlen(relativePath) > expandoRelativePathLength )
{
// This expando covers less of the path than any previous one found.
// We will keep the previous one.
continue;
}
// Keep track of the relative path length
expandoRelativePathLength = dStrlen(relativePath);
// Fetch expando key (name).
StringTableEntry expandoName = getPathExpandoKey( expandoIndex );
// Format against expando.
dSprintf( pathBuffer, sizeof(pathBuffer), "^%s/%s", expandoName, relativePath );
}
// Check if we've found a suitable expando
if ( expandoRelativePathLength != U32_MAX )
{
// Strip repeat slashes.
Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
return;
}
// Fetch the working directory.
StringTableEntry workingDirectory = pWorkingDirectoryHint != NULL ? pWorkingDirectoryHint : Platform::getCurrentDirectory();
// Fetch path relative to current directory.
StringTableEntry relativePath = Platform::makeRelativePathName( pSrcPath, workingDirectory );
// If the relative path is simply a period
if ( relativePath[0] == '.' && relativePath[1] != '.' )
relativePath++;
// Format against expando.
dSprintf( pathBuffer, sizeof(pathBuffer), "%s/%s", workingDirectory, relativePath );
// Strip repeat slashes.
Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
}
//-----------------------------------------------------------------------------
void ensureTrailingSlash( char* pDstPath, const char* pSrcPath )
{
// Copy to target.
dStrcpy( pDstPath, pSrcPath );
// Find trailing character index.
S32 trailIndex = dStrlen(pDstPath);
// Ignore if empty string.
if ( trailIndex == 0 )
return;
// Finish if the trailing slash already exists.
if ( pDstPath[trailIndex-1] == '/' )
return;
// Add trailing slash.
pDstPath[trailIndex++] = '/';
pDstPath[trailIndex] = 0;
}
//-----------------------------------------------------------------------------
bool stripRepeatSlashes( char* pDstPath, const char* pSrcPath, S32 dstSize )
{
// Note original destination.
char* pOriginalDst = pDstPath;
// Reset last source character.
char lastSrcChar = 0;
// Search source...
while ( dstSize > 0 )
{
// Fetch characters.
const char srcChar = *pSrcPath++;
// Do we have a repeat slash?
if ( srcChar == '/' && lastSrcChar == '/' )
{
// Yes, so skip it.
continue;
}
// No, so copy character.
*pDstPath++ = srcChar;
// Finish if end of source.
if ( srcChar == 0 )
return true;
// Reduce room left in destination.
dstSize--;
// Set last character.
lastSrcChar = srcChar;
}
// Terminate the destination string as we ran out of room.
*pOriginalDst = 0;
// Fail!
return false;
}
} // end of Console namespace
| 28.686114
| 159
| 0.59256
|
itsasc
|
17656ca8eb87e30ed3dda19c5fe5dafc2576f8e6
| 2,261
|
hpp
|
C++
|
modules/utils/filesystem.hpp
|
psastras/vocabtree
|
c80bc2044e6a107358c7f838427794a830e58bce
|
[
"MIT"
] | 10
|
2015-10-03T17:10:08.000Z
|
2021-02-28T20:36:14.000Z
|
modules/utils/filesystem.hpp
|
psastras/vocabtree
|
c80bc2044e6a107358c7f838427794a830e58bce
|
[
"MIT"
] | null | null | null |
modules/utils/filesystem.hpp
|
psastras/vocabtree
|
c80bc2044e6a107358c7f838427794a830e58bce
|
[
"MIT"
] | 5
|
2017-03-30T02:20:03.000Z
|
2018-03-28T06:29:53.000Z
|
#pragma once
#include "config.hpp"
#include <stdint.h>
#include <opencv2/opencv.hpp>
/// Provides useful wrappers around many filesystem related functionality, including reading writing
/// certain common data structures as well as common operations (ex. file_exists).
namespace filesystem {
/// Returns the basename of the input filepath, including or not including the extension.
std::string basename(const std::string &path, bool include_extension = false);
/// Returns true if file exists at location, else returns false.
bool file_exists(const std::string& name);
/// Recursively creates all directories if needed up to the specified file.
void create_file_directory(const std::string &absfilepath);
/// Writes a cv::Mat structure to the specified location.
bool write_cvmat(const std::string &fname, const cv::Mat &data);
/// Loads a cv::Mat structure from the specified location. Returns true if file exists,
/// false otherwise.
bool load_cvmat(const std::string &fname, cv::Mat &data);
/// Writes the BoW feature to the specified location. First dimension of data is cluster index,
/// second dimension is TF score.
bool write_sparse_vector(const std::string &fname, const std::vector<std::pair<uint32_t, float > > &data);
/// Loads the BoW feature from the specified location. First dimension of data is cluster index,
/// second dimension is TF score.
bool load_sparse_vector(const std::string &fname, std::vector<std::pair<uint32_t, float > > &data);
/// Lists all files in the given directory with an optional extension. The extension must include
/// the dot (ie. ext=".txt"). If recursive is true (default), will recursively enter all directories
std::vector<std::string> list_files(const std::string &path, const std::string &ext = "", bool recursive = true) ;
/// Writes a text file to the input file location given the input string. Returns true if success,
/// false otherwise.
bool write_text(const std::string &fname, const std::string &text);
/// Writes the vector to the specified location.
bool write_vector(const std::string &fname, const std::vector<float> &data);
/// Loads vector BoW feature from the specified location.
bool load_vector(const std::string &fname, std::vector<float> &data);
};
| 57.974359
| 115
| 0.745245
|
psastras
|
17691b24975f17cdde7fe8a147e19f8c166a912c
| 4,091
|
cpp
|
C++
|
Coin3D/src/engines/SoTransformVec3f.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
Coin3D/src/engines/SoTransformVec3f.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
Coin3D/src/engines/SoTransformVec3f.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
/**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* 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 copyright holder 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.
\**************************************************************************/
/*!
\class SoTransformVec3f SoTransformVec3f.h Inventor/engines/SoTransformVec3f.h
\brief The SoTransformVec3f class transforms 3D vectors by a matrix.
\ingroup engines
*/
#include <Inventor/engines/SoTransformVec3f.h>
#include <Inventor/lists/SoEngineOutputList.h>
#include "engines/SoSubEngineP.h"
/*!
\var SoMFVec3f SoTransformVec3f::vector
Set of 3D vector inputs to transform.
*/
/*!
\var SoMFMatrix SoTransformVec3f::matrix
Set of transformation matrices to use on the vectors.
*/
/*!
\var SoEngineOutput SoTransformVec3f::point
(SoMFVec3f) Transformed points.
*/
/*!
\var SoEngineOutput SoTransformVec3f::direction
(SoMFVec3f) Transformed vector directions.
*/
/*!
\var SoEngineOutput SoTransformVec3f::normalDirection
(SoMFVec3f) Normalized transformed vector directions.
*/
SO_ENGINE_SOURCE(SoTransformVec3f);
// doc in parent
void
SoTransformVec3f::initClass(void)
{
SO_ENGINE_INTERNAL_INIT_CLASS(SoTransformVec3f);
}
/*!
Default constructor.
*/
SoTransformVec3f::SoTransformVec3f(void)
{
SO_ENGINE_INTERNAL_CONSTRUCTOR(SoTransformVec3f);
SO_ENGINE_ADD_INPUT(vector, (0.0f, 0.0f, 0.0f));
SO_ENGINE_ADD_INPUT(matrix, (SbMatrix::identity()));
SO_ENGINE_ADD_OUTPUT(point, SoMFVec3f);
SO_ENGINE_ADD_OUTPUT(direction, SoMFVec3f);
SO_ENGINE_ADD_OUTPUT(normalDirection, SoMFVec3f);
}
/*!
Destructor is protected because explicit destruction of engines is
not allowed.
*/
SoTransformVec3f::~SoTransformVec3f()
{
}
// doc in parent
void
SoTransformVec3f::evaluate(void)
{
int numvec = this->vector.getNum();
int nummatrices = this->matrix.getNum();
int numoutputs = SbMax(numvec, nummatrices);
SO_ENGINE_OUTPUT(point, SoMFVec3f, setNum(numoutputs));
SO_ENGINE_OUTPUT(direction, SoMFVec3f, setNum(numoutputs));
SO_ENGINE_OUTPUT(normalDirection, SoMFVec3f, setNum(numoutputs));
SbVec3f pt, dir, ndir;
for (int i = 0; i < numoutputs; i++) {
const SbVec3f & v = this->vector[SbMin(i, numvec-1)];
const SbMatrix & m = this->matrix[SbMin(i, nummatrices-1)];
m.multVecMatrix(v, pt);
m.multDirMatrix(v, dir);
ndir = dir;
(void) ndir.normalize(); // null vector is ok
SO_ENGINE_OUTPUT(point, SoMFVec3f, set1Value(i, pt));
SO_ENGINE_OUTPUT(direction, SoMFVec3f, set1Value(i, dir));
SO_ENGINE_OUTPUT(normalDirection, SoMFVec3f, set1Value(i, ndir));
}
}
| 32.728
| 80
| 0.727206
|
pniaz20
|
176b4645c457b7348a9fec9d79b2422cf26378f9
| 64
|
cpp
|
C++
|
src/external/stb_image.cpp
|
Adanos020/ErupTrace
|
2d359c4d53e758299e8b2d476d945fe2dd2f1c2d
|
[
"MIT"
] | null | null | null |
src/external/stb_image.cpp
|
Adanos020/ErupTrace
|
2d359c4d53e758299e8b2d476d945fe2dd2f1c2d
|
[
"MIT"
] | null | null | null |
src/external/stb_image.cpp
|
Adanos020/ErupTrace
|
2d359c4d53e758299e8b2d476d945fe2dd2f1c2d
|
[
"MIT"
] | null | null | null |
#define STB_IMAGE_IMPLEMENTATION
#include <external/stb_image.h>
| 32
| 32
| 0.859375
|
Adanos020
|
176da841d3cfc0ed8f47e4793551f017cdb3044c
| 442
|
hpp
|
C++
|
src/request.hpp
|
jackim/kiss
|
e9216dfc46c2d047eb107f04d3d99d88ec58f3b5
|
[
"Apache-2.0"
] | null | null | null |
src/request.hpp
|
jackim/kiss
|
e9216dfc46c2d047eb107f04d3d99d88ec58f3b5
|
[
"Apache-2.0"
] | null | null | null |
src/request.hpp
|
jackim/kiss
|
e9216dfc46c2d047eb107f04d3d99d88ec58f3b5
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "http.hpp"
#include <string>
#include <map>
namespace jackim { namespace kiss{
struct Request
{
Http *http;
std::string url;
std::string path;
std::string query;
std::map<std::string , std::string> header;
std::string body;
unsigned short http_major;
unsigned short http_minor;
std::string method;
bool should_keepalive;
};
}}
| 14.733333
| 48
| 0.585973
|
jackim
|
176ee81cc174fcf3ce2b738c6db3e63d7ee3367a
| 1,618
|
cpp
|
C++
|
src/chapter_11_cryptography/problem_092_computing_file_hashes.cpp
|
rturrado/the_modern_cpp_challenge
|
a569a1538802a44c3b7c44134c06c73727f2b5e3
|
[
"MIT"
] | null | null | null |
src/chapter_11_cryptography/problem_092_computing_file_hashes.cpp
|
rturrado/the_modern_cpp_challenge
|
a569a1538802a44c3b7c44134c06c73727f2b5e3
|
[
"MIT"
] | null | null | null |
src/chapter_11_cryptography/problem_092_computing_file_hashes.cpp
|
rturrado/the_modern_cpp_challenge
|
a569a1538802a44c3b7c44134c06c73727f2b5e3
|
[
"MIT"
] | null | null | null |
#include "chapter_11_cryptography.h"
#include <filesystem>
#include <format>
#include <iostream> // cout
#include <vector>
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include "cryptocpp/cryptlib.h"
#include "cryptocpp/files.h" // FileSource
#include "cryptocpp/filters.h" // HashFilter, StringSink
#include "cryptocpp/hex.h" // HexEncoder
#include "cryptocpp/md5.h" // MD5
#include "cryptocpp/sha.h" // SHA1, SHA256
namespace fs = std::filesystem;
template <typename Hash>
std::string get_hash_as_hex_string(const fs::path& file_path)
{
std::string digest{};
Hash hash{};
CryptoPP::FileSource file_source{
file_path.c_str(),
true,
new CryptoPP::HashFilter{hash,
new CryptoPP::HexEncoder{
new CryptoPP::StringSink{digest}
}
}
};
return digest;
}
// Computing file hashes
//
// Write a program that, given a path to a file, computes and prints to the console
// the SHA1, SHA256, and MD5 hash values for the content of the file.
void problem_92_main()
{
const auto input_file_path{ std::filesystem::current_path() / "res" / "fonts" / "calibri.ttf" };
std::cout << std::format("Calculating SHA1, SHA256 and MD5 for file '{}'\n", input_file_path.string());
std::cout << std::format("\tSHA1: '{}'\n", get_hash_as_hex_string<CryptoPP::SHA1>(input_file_path));
std::cout << std::format("\tSHA256: '{}'\n", get_hash_as_hex_string<CryptoPP::SHA256>(input_file_path));
std::cout << std::format("\tMD5: '{}'\n", get_hash_as_hex_string<CryptoPP::Weak::MD5>(input_file_path));
std::cout << "\n";
}
| 28.892857
| 108
| 0.668727
|
rturrado
|
176f763fe5d41dd014235d1d134f35cc55d11c7f
| 1,524
|
cpp
|
C++
|
Days 171 - 180/Day 179/CreateTreeFromPostorderTraversal.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
Days 171 - 180/Day 179/CreateTreeFromPostorderTraversal.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
Days 171 - 180/Day 179/CreateTreeFromPostorderTraversal.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <iterator>
#include <memory>
#include <vector>
struct Node
{
int value;
std::shared_ptr<Node> left;
std::shared_ptr<Node> right;
explicit Node(const int value, const std::shared_ptr<Node>& left = nullptr, const std::shared_ptr<Node>& right = nullptr)
: value(value), left(left), right(right)
{ }
};
std::shared_ptr<Node> GetTreeFromPostorderTraversal(const std::vector<int>& values) noexcept
{
auto head = std::make_shared<Node>(values.back());
if (values.size() == 1)
{
return head;
}
unsigned int partitionIndex = 0;
for (unsigned int i = 0; i < values.size() - 1; ++i)
{
if (values[i] > head->value)
{
partitionIndex = i;
break;
}
}
std::vector<int> lesserValues{ std::cbegin(values), std::cbegin(values) + partitionIndex };
std::vector<int> greaterValues{ std::cbegin(values) + partitionIndex, std::cend(values) - 1 };
head->left = !lesserValues.empty() ? GetTreeFromPostorderTraversal(lesserValues) : nullptr;
head->right = !greaterValues.empty() ? GetTreeFromPostorderTraversal(greaterValues) : nullptr;
return head;
}
std::ostream& operator <<(std::ostream& outputStream, const std::shared_ptr<Node>& head) noexcept
{
if (head == nullptr)
{
outputStream << "- ";
}
else
{
outputStream << head->value << " " << head->left << head->right;
}
return outputStream;
}
int main(int argc, char* argv[])
{
const auto tree = GetTreeFromPostorderTraversal({ 2, 4, 3, 8, 7, 5 });
std::cout << tree << "\n";
std::cin.get();
return 0;
}
| 21.771429
| 122
| 0.667979
|
LucidSigma
|
1775593d194f14f7190addd2bd604091128c04bf
| 1,962
|
hpp
|
C++
|
include/StereoEval.hpp
|
norishigefukushima/OpenCP
|
63090131ec975e834f85b04e84ec29b2893845b2
|
[
"BSD-3-Clause"
] | 137
|
2015-03-27T07:11:19.000Z
|
2022-03-30T05:58:22.000Z
|
include/StereoEval.hpp
|
Pandinosaurus/OpenCP
|
a5234ed531c610d7944fa14d42f7320442ea34a1
|
[
"BSD-3-Clause"
] | 2
|
2016-05-18T06:33:16.000Z
|
2016-07-11T17:39:17.000Z
|
include/StereoEval.hpp
|
Pandinosaurus/OpenCP
|
a5234ed531c610d7944fa14d42f7320442ea34a1
|
[
"BSD-3-Clause"
] | 43
|
2015-02-20T15:34:25.000Z
|
2022-01-27T14:59:37.000Z
|
#pragma once
#include "common.hpp"
namespace cp
{
CP_EXPORT double calcBadPixel(cv::InputArray groundtruth, cv::InputArray disparityImage, cv::InputArray mask, double th, double amp);
CP_EXPORT double calcBadPixel(cv::InputArray groundtruth, cv::InputArray disparityImage, cv::InputArray mask, double th, double amp, cv::OutputArray outErr);
CP_EXPORT void createDisparityALLMask(cv::Mat& src, cv::Mat& dest);
CP_EXPORT void createDisparityNonOcclusionMask(cv::Mat& src, double amp, double thresh, cv::Mat& dest);
class CP_EXPORT StereoEval
{
void threshmap_init();
bool skip_disc = false;
public:
int ignoreLeftBoundary;
bool isInit = false;
std::string message;
cv::Mat state_all;
cv::Mat state_nonocc;
cv::Mat state_disc;
cv::Mat ground_truth;
cv::Mat mask_all;
cv::Mat all_th;
cv::Mat mask_nonocc;
cv::Mat nonocc_th;
cv::Mat mask_disc;
cv::Mat disc_th;
double amp;
double all;
double nonocc;
double disc;
double allMSE;
double nonoccMSE;
double discMSE;
void init(cv::Mat& groundtruth, cv::Mat& maskNonocc, cv::Mat& maskAll, cv::Mat& maskDisc, double amp);
void init(cv::Mat& groundtruth, const double amp, const int ignoreLeftBoundary);
StereoEval();
StereoEval(std::string groundtruthPath, std::string maskNonoccPath, std::string maskAllPath, std::string maskDiscPath, double amp);
StereoEval(cv::Mat& groundtruth, cv::Mat& maskNonocc, cv::Mat& maskAll, cv::Mat& maskDisc, double amp);
StereoEval(cv::Mat& groundtruth, const double amp, const int ignoreLeftBoundary = 0);
std::string getBadPixel(cv::Mat& src, double threshold = 1.0, bool isPrint = true);
std::string getMSE(cv::Mat& src, const int disparity_scale = 1, const bool isPrint = true);
std::string operator() (cv::InputArray src, const double threshold = 1.0, const int disparity_scale = 1, const bool isPrint = true);
void compare(cv::Mat& before, cv::Mat& after, double threshold = 1.0, bool isPrint = true);
};
}
| 37.730769
| 158
| 0.730887
|
norishigefukushima
|
17765bec1b74034842222ffd57f7ef8687d3a376
| 3,446
|
cpp
|
C++
|
src/vendors/OceanOptics/features/eeprom_slots/EEPROMSlotFeature.cpp
|
udyni/seabreeze
|
3d3934f8f0df61c11cef70516cf62a8472cab974
|
[
"MIT"
] | null | null | null |
src/vendors/OceanOptics/features/eeprom_slots/EEPROMSlotFeature.cpp
|
udyni/seabreeze
|
3d3934f8f0df61c11cef70516cf62a8472cab974
|
[
"MIT"
] | null | null | null |
src/vendors/OceanOptics/features/eeprom_slots/EEPROMSlotFeature.cpp
|
udyni/seabreeze
|
3d3934f8f0df61c11cef70516cf62a8472cab974
|
[
"MIT"
] | 1
|
2020-07-03T08:36:47.000Z
|
2020-07-03T08:36:47.000Z
|
/***************************************************//**
* @file EEPROMSlotFeature.cpp
* @date February 2009
* @author Ocean Optics, Inc.
*
* LICENSE:
*
* SeaBreeze Copyright (C) 2014, Ocean Optics Inc
*
* 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 "common/globals.h"
#include "vendors/OceanOptics/features/eeprom_slots/EEPROMSlotFeature.h"
#include "api/seabreezeapi/FeatureFamilies.h"
using namespace seabreeze;
using namespace seabreeze::api;
using namespace std;
EEPROMSlotFeature::EEPROMSlotFeature(unsigned int numSlots) {
this->numberOfSlots = numSlots;
}
EEPROMSlotFeature::~EEPROMSlotFeature() {
}
#ifdef _WINDOWS
#pragma warning (disable: 4101) // unreferenced local variable
#endif
vector< vector<byte> * > *EEPROMSlotFeature::readAllEEPROMSlots(
const Protocol &protocol, const Bus &bus) throw (FeatureException) {
unsigned int i;
vector< vector<byte> * > *retval = new vector< vector<byte> * >();
for(i = 0; i < this->numberOfSlots; i++) {
try {
/* This may throw a FeatureException */
retval[i].push_back(readEEPROMSlot(protocol, bus, i));
} catch (IllegalArgumentException &iae) {
/* This shouldn't be possible since the loop is enumerating
* the known range of slots, but recover anyway
*/
continue;
}
}
return retval;
}
vector<byte> *EEPROMSlotFeature::readEEPROMSlot(const Protocol &protocol,
const Bus &bus, unsigned int slot)
throw (FeatureException, IllegalArgumentException) {
if(slot >= this->numberOfSlots) {
string error("EEPROM slot out of bounds.");
throw IllegalArgumentException(error);
}
/* This may throw a FeatureException. */
return EEPROMSlotFeatureBase::readEEPROMSlot(protocol, bus, slot);
}
int EEPROMSlotFeature::writeEEPROMSlot(const Protocol &protocol,
const Bus &bus, unsigned int slot, const vector<byte> &data)
throw (FeatureException, IllegalArgumentException) {
if(slot >= this->numberOfSlots) {
throw IllegalArgumentException(string("EEPROM slot out of bounds."));
}
return EEPROMSlotFeatureBase::writeEEPROMSlot(protocol, bus, slot, data);
}
FeatureFamily EEPROMSlotFeature::getFeatureFamily() {
FeatureFamilies families;
return families.EEPROM;
}
| 34.808081
| 77
| 0.687464
|
udyni
|
1779ec588e196d65e916646466f3489dc275d7ef
| 3,592
|
cpp
|
C++
|
hal/src/electron/ota_flash_hal.cpp
|
zsoltmazlo/indoor-controller2
|
5fde9f40b30d087af03f6cccdb97821719941955
|
[
"MIT"
] | null | null | null |
hal/src/electron/ota_flash_hal.cpp
|
zsoltmazlo/indoor-controller2
|
5fde9f40b30d087af03f6cccdb97821719941955
|
[
"MIT"
] | null | null | null |
hal/src/electron/ota_flash_hal.cpp
|
zsoltmazlo/indoor-controller2
|
5fde9f40b30d087af03f6cccdb97821719941955
|
[
"MIT"
] | null | null | null |
/**
******************************************************************************
* @file ota_flash_hal.cpp
* @author Matthew McGowan, Satish Nair
* @version V1.0.0
* @date 25-Sept-2014
* @brief
******************************************************************************
Copyright (c) 2013-2015 Particle Industries, Inc. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, either
version 3 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see <http://www.gnu.org/licenses/>.
******************************************************************************
*/
#include <cstring>
#include "ota_module.h"
#include "spark_macros.h"
#include "ota_flash_hal_stm32f2xx.h"
#include "cellular_hal.h"
#include "core_hal.h"
// Electron!
#if MODULAR_FIRMWARE
const module_bounds_t module_bootloader = { 0x4000, 0x8000000, 0x8004000, MODULE_FUNCTION_BOOTLOADER, 0, MODULE_STORE_MAIN };
const module_bounds_t module_system_part1 = { 0x20000, 0x8020000, 0x8040000, MODULE_FUNCTION_SYSTEM_PART, 1, MODULE_STORE_MAIN };
const module_bounds_t module_system_part2 = { 0x20000, 0x8040000, 0x8060000, MODULE_FUNCTION_SYSTEM_PART, 2, MODULE_STORE_MAIN };
const module_bounds_t module_system_part3 = { 0x20000, 0x8060000, 0x8080000, MODULE_FUNCTION_SYSTEM_PART, 3, MODULE_STORE_MAIN };
const module_bounds_t module_user = { 0x20000, 0x8080000, 0x80A0000, MODULE_FUNCTION_USER_PART, 1, MODULE_STORE_MAIN};
const module_bounds_t module_factory = { 0x20000, 0x80A0000, 0x80C0000, MODULE_FUNCTION_USER_PART, 1, MODULE_STORE_FACTORY};
const module_bounds_t* module_bounds[] = { &module_bootloader, &module_system_part1, &module_system_part2, &module_system_part3, &module_user, &module_factory };
const module_bounds_t module_ota = { 0x20000, 0x80C0000, 0x80E0000, MODULE_FUNCTION_NONE, 0, MODULE_STORE_SCRATCHPAD};
#else
const module_bounds_t module_bootloader = { 0x4000, 0x8000000, 0x8004000, MODULE_FUNCTION_BOOTLOADER, 0, MODULE_STORE_MAIN};
const module_bounds_t module_user = { 0x60000, 0x8020000, 0x8080000, MODULE_FUNCTION_MONO_FIRMWARE, 0, MODULE_STORE_MAIN};
const module_bounds_t module_factory = { 0x60000, 0x8080000, 0x80E0000, MODULE_FUNCTION_MONO_FIRMWARE, 0, MODULE_STORE_FACTORY};
const module_bounds_t* module_bounds[] = { &module_bootloader, &module_user, &module_factory };
const module_bounds_t module_ota = { 0x60000, 0x8080000, 0x80E0000, MODULE_FUNCTION_NONE, 0, MODULE_STORE_SCRATCHPAD};
#endif
const unsigned module_bounds_length = arraySize(module_bounds);
void HAL_OTA_Add_System_Info(hal_system_info_t* info, bool create, void* reserved)
{
if (create) {
info->key_value_count = 2;
info->key_values = new key_value[info->key_value_count];
CellularDevice device;
memset(&device, 0, sizeof(device));
device.size = sizeof(device);
cellular_device_info(&device, NULL);
set_key_value(info->key_values, "imei", device.imei);
set_key_value(info->key_values+1, "iccid", device.iccid);
}
else
{
delete info->key_values;
info->key_values = NULL;
}
}
| 46.649351
| 161
| 0.716592
|
zsoltmazlo
|
ed06c65c1e63be00ee6faaacdb928e57878040f2
| 5,616
|
cxx
|
C++
|
lio/VRMLIO.cxx
|
kanait/hsphparam
|
00158f81d00e496fed469779bf73094495ac8671
|
[
"MIT"
] | 1
|
2021-08-23T06:55:22.000Z
|
2021-08-23T06:55:22.000Z
|
lio/VRMLIO.cxx
|
kanait/hsphparam
|
00158f81d00e496fed469779bf73094495ac8671
|
[
"MIT"
] | null | null | null |
lio/VRMLIO.cxx
|
kanait/hsphparam
|
00158f81d00e496fed469779bf73094495ac8671
|
[
"MIT"
] | null | null | null |
////////////////////////////////////////////////////////////////////
//
// $Id: VRMLIO.cxx 2021/06/05 14:00:43 kanai Exp $
//
// Copyright (c) 2021 Takashi Kanai
// Released under the MIT license
//
////////////////////////////////////////////////////////////////////
// for openvrml 0.11.2
#include "envDep.h"
#ifdef WITH_OPENVRML
#include <iostream>
#include <fstream>
//using namespace std;
#include "OpenVRML/field.h"
#include "OpenVRML/vrml97node.h"
#include "OpenVRML/VrmlNode.h"
#include "OpenVRML/VrmlScene.h"
#include "MeshL.hxx"
#include "VertexL.hxx"
#include "FaceL.hxx"
#include "HalfedgeL.hxx"
#include "VRMLIO.hxx"
bool VRMLIO::inputFromFile( const char* const filename )
{
VrmlScene vrmlScene( (const char*) filename, NULL );
sceneToMeshL( vrmlScene );
std::cout << "mesh " << filename << " v " << (int) mesh().vertices().size()
<< " f " << (int) mesh().faces().size() << std::endl;
return true;
}
void VRMLIO::sceneToMeshL( VrmlScene& vrmlScene )
{
VrmlNode* node = vrmlScene.getRoot();
traverse( node );
if ( empty() ) return;
}
//
// out_ppd $B$K$9$Y$F$N(B Shape $B$rDI2C$9$k(B
//
// void VRMLIO::shapeToMeshL( VrmlNodeShape* shape )
void VRMLIO::shapeToMeshL( VrmlNodeShape* shape )
{
// IndexedFaceSet $B$N<hF@(B
VrmlNodeIFaceSet* ifaceset = shape->getGeometry().get()->toIFaceSet();
if ( ifaceset == NULL ) return;
// get coordinates
VrmlMFVec3f& coord = ifaceset->getCoord().get()->toCoordinate()->coordinate();
// float* points = (float*) &coord.getElement(0)[0];
int nverts = (int) coord.getLength();
float* points = (float*) coord.get();
// for refering vertex pointer
std::vector<VertexL*> vertex_p;
for ( int i = 0; i < nverts; ++i )
{
float* v = &(points[3*i]);
Point3f p( v[0], v[1], v[2] );
VertexL* vt = mesh().addVertex( p );
vertex_p.push_back( vt );
std::cout << v[0] << " " << v[1] << " " << v[2] << std::endl;
}
// $BLL$N:BI8Ns$N<hF@(B
VrmlMFInt32& coordIndex = (VrmlMFInt32&) ifaceset->getCoordIndex();
//int fid = 0;
// display("face %d\t", fid );
const long* faces = coordIndex.get();
// first face
FaceL* fc = mesh().addFace();
int nfaces = (int) coordIndex.getLength();
for ( int i = 0; i < nfaces-1; ++i )
{
if ( faces[i] == -1 )
{
// normal
fc->calcNormal();
if ( i == nfaces-2 ) break;
// new face
fc = mesh().addFace();
}
else
{
// add halfedge
mesh().addHalfedge( fc, vertex_p[faces[i]], NULL );
}
}
}
//
// Shape $B$,F~$C$F$$$k(B Node $B$rC5$9(B
//
void VRMLIO::traverse( VrmlNode* node )
{
if ( node->toShape() )
{
shapeToMeshL( node->toShape() );
}
VrmlNodeGroup* group = node->toGroup();
if ( !group ) return;
int n = (int) group->getChildren().getLength();
for ( int i = 0; i < n; ++i )
{
traverse( group->getChildren().getElement(i).get() );
}
}
bool VRMLIO::outputToFile( const char* const filename )
{
ofstream ofs( filename ); if ( !ofs ) return false;
// header
ofs << "#VRML V2.0 utf8" << endl;
if ( type() == VRML_SUBDIV )
{
ofs << "#EVRML_SUBDIV" << endl;
}
else
{
ofs << "#EVRML_POLY" << endl;
}
ofs << "DEF Home Viewpoint {" << endl;
ofs << " position 0 0 1.931" << endl;
ofs << " description \"Home\"" << endl;
ofs << "}" << endl;
ofs << "NavigationInfo {" << endl;
ofs << " type [ \"EXAMINE\", \"ANY\" ]" << endl;
ofs << " avatarSize 0" << endl;
ofs << "}" << endl;
ofs << "Collision {" << endl;
ofs << " collide FALSE" << endl;
ofs << " children [" << endl;
ofs << " Group {" << endl;
ofs << " children [" << endl;
ofs << " DEF Cameras Switch {" << endl;
ofs << " whichChoice -1" << endl;
ofs << " }," << endl;
ofs << " Group {" << endl;
ofs << " children [" << endl;
ofs << " Shape {" << endl;
ofs << " appearance" << endl;
ofs << " Appearance {" << endl;
ofs << " material" << endl;
ofs << " DEF _DefMat Material {" << endl;
ofs << " }" << endl;
ofs << " }" << endl;
ofs << " geometry" << endl;
ofs << " IndexedFaceSet {" << endl;
ofs << " coord" << endl;
ofs << " Coordinate {" << endl;
// vertex
ofs << " point [ ";
int id = 0;
foreach ( list<VertexL*>, mesh().vertices(), vt1 )
{
(*vt1)->setID( id ); ++id;
Point3f& p = (*vt1)->point();
if ( vt1 == mesh().vertices().begin() )
ofs << p.x << " " << p.y << " " << p.z << "," << endl;
else if ( (*vt1) == mesh().vertices().back() )
{
ofs << "\t\t\t\t\t\t\t";
ofs << p.x << " " << p.y << " " << p.z << " ]" << endl;
}
else
{
ofs << "\t\t\t\t\t\t\t";
ofs << p.x << " " << p.y << " " << p.z << "," << endl;
}
}
ofs << " }" << endl;
ofs << " solid FALSE" << endl;
ofs << " creaseAngle 0.5" << endl;
// face
ofs << " coordIndex [ ";
int i = 0;
foreach ( list<FaceL*>, mesh().faces(), fc2 )
{
if ( fc2 != mesh().faces().begin() ) ofs << "\t\t\t\t\t\t\t";
foreach ( list<HalfedgeL*>, (*fc2)->halfedges(), he )
{
ofs << (*he)->vertex()->id() << ", ";
}
if ( (*fc2) != mesh().faces().back() )
ofs << "-1," << endl;
else ofs << "-1 ]" << endl;
}
ofs << " }" << endl;
ofs << " }" << endl;
ofs << " ]" << endl;
ofs << " }" << endl;
ofs << " ]" << endl;
ofs << " }" << endl;
ofs << " ]" << endl;
ofs << "}" << endl;
ofs.close();
return true;
}
#endif // WITH_OPENVRML
| 23.016393
| 80
| 0.490919
|
kanait
|
ed07c50d6aa9d046a2cbe7b36e0f59d31da860fc
| 1,846
|
hpp
|
C++
|
include/glfw-cxx/GammaRamp.hpp
|
Mischa-Alff/glfw-cxx
|
bd335a7c5ac959da0ea1ac009a66b75ada21efb6
|
[
"MIT"
] | 12
|
2015-07-05T15:07:26.000Z
|
2020-07-10T03:15:56.000Z
|
include/glfw-cxx/GammaRamp.hpp
|
TheRealJoe24/glfw-cxx
|
bd335a7c5ac959da0ea1ac009a66b75ada21efb6
|
[
"MIT"
] | 1
|
2016-08-10T16:49:13.000Z
|
2016-08-19T18:23:04.000Z
|
include/glfw-cxx/GammaRamp.hpp
|
TheRealJoe24/glfw-cxx
|
bd335a7c5ac959da0ea1ac009a66b75ada21efb6
|
[
"MIT"
] | 3
|
2017-04-24T14:33:46.000Z
|
2019-06-15T22:15:22.000Z
|
#pragma once
#include <GLFW/glfw3.h>
namespace glfw
{
/*!\brief A class describing gamma ramp parameters.
*/
class GammaRamp
{
private:
GLFWgammaramp m_gammaramp;
public:
/*! \brief Returns an array of values describing the response of the red channel.
* \return An array of values describing the response of the red channel.
*/
unsigned short* GetRed();
/*! \brief Sets the array of values describing the response of the red channel.
* \param[in] red An array of values describing the response of the red channel.
*/
void SetRed(unsigned short* red);
/*! \brief Returns an array of values describing the response of the green channel.
* \return An array of values describing the response of the green channel.
*/
unsigned short* GetGreen();
/*! \brief Sets the array of values describing the response of the green channel.
* \param[in] green An array of values describing the response of the green channel.
*/
void SetGreen(unsigned short* green);
/*! \brief Returns an array of values describing the response of the blue channel.
* \return An array of values describing the response of the blue channel.
*/
unsigned short* GetBlue();
/*! \brief Sets the array of values describing the response of the blue channel.
* \param[in] blue An array of values describing the response of the blue channel.
*/
void SetBlue(unsigned short* blue);
/*! \brief Returns the size of the ramp
* \return The size of the ramp
*/
unsigned int GetSize();
/*! \brief Sets the size of the ramp
* \param[in] size The size of the ramp
*/
void SetSize(unsigned int size);
/*! \brief Returns the C GLFW pointer to the data
* \return the C GLFW pointer to the data
*/
GLFWgammaramp* GetRawPointerData();
GammaRamp(GLFWgammaramp gammaramp);
GammaRamp();
};
}
| 30.766667
| 86
| 0.703142
|
Mischa-Alff
|
ed0828c25cfdeee2038003f864ee0fc8528dcd09
| 187
|
cpp
|
C++
|
LeetCode/c++/69_Sqrt(x).cpp
|
Weak-Chicken/Algo_every_day
|
0976b5986d6c98cb8370ff4239b4a2485f865253
|
[
"MIT"
] | 1
|
2018-02-08T23:50:19.000Z
|
2018-02-08T23:50:19.000Z
|
LeetCode/c++/69_Sqrt(x).cpp
|
Weak-Chicken/Algo_every_day
|
0976b5986d6c98cb8370ff4239b4a2485f865253
|
[
"MIT"
] | 1
|
2018-04-11T19:08:22.000Z
|
2018-04-12T19:24:57.000Z
|
LeetCode/c++/69_Sqrt(x).cpp
|
Weak-Chicken/Cpp_every_day
|
0976b5986d6c98cb8370ff4239b4a2485f865253
|
[
"MIT"
] | null | null | null |
class Solution
{
public:
int mySqrt(int x)
{
for (int i = 0; i <= 46340; i++)
{
if (i * i > x) return i - 1;
}
return 46340;
}
};
| 15.583333
| 40
| 0.379679
|
Weak-Chicken
|
ed0b4c34c10acf7098ba72fa97d86cb78e452cce
| 1,072
|
cc
|
C++
|
cpp/src/tree/postorder.cc
|
dacozai/algorithm-diary
|
8ed5e119e4450e92e63276047ef19bbf422c2770
|
[
"MIT"
] | 1
|
2019-10-17T08:34:55.000Z
|
2019-10-17T08:34:55.000Z
|
cpp/src/tree/postorder.cc
|
dacozai/algorithm-diary
|
8ed5e119e4450e92e63276047ef19bbf422c2770
|
[
"MIT"
] | 1
|
2020-05-24T08:32:13.000Z
|
2020-05-24T08:32:13.000Z
|
cpp/src/tree/postorder.cc
|
dacozai/algorithm-diary
|
8ed5e119e4450e92e63276047ef19bbf422c2770
|
[
"MIT"
] | null | null | null |
#include "test.h"
/** Question no 145 hard Binary Tree Postorder Traversal
* Author : Li-Han, Chen; 陳立瀚
* Date : 24th, January, 2020
* Source : https://leetcode.com/problems/binary-tree-postorder-traversal/
*
* Given a binary tree, return the postorder traversal of its nodes' values.
*
*/
/** Solution
* Runtime 0 ms MeMory 8.6 MB;
* faster than 100.00%, less than 100.00%
* O(n) ; O(n)
*/
class Node {
public:
int val;
std::vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, std::vector<Node*> _children) {
val = _val;
children = _children;
}
};
std::vector<int> postorder(Node* root) {
static const int __ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
std::vector<int> vec;
if (root == NULL) return vec;
for (auto nd: root->children) {
std::vector<int> tmp = postorder(nd);
vec.insert(vec.end(), tmp.begin(), tmp.end());
}
vec.push_back(root->val);
return vec;
}
| 22.333333
| 76
| 0.597948
|
dacozai
|
ed14c70a30fca84051ffab8d97cf833bb694459b
| 5,531
|
cpp
|
C++
|
vkconfig_core/test/test_path_manager.cpp
|
johnzupin/VulkanTools
|
4a4d824b43984d29902f7c8246aab99f0909151d
|
[
"Apache-2.0"
] | null | null | null |
vkconfig_core/test/test_path_manager.cpp
|
johnzupin/VulkanTools
|
4a4d824b43984d29902f7c8246aab99f0909151d
|
[
"Apache-2.0"
] | null | null | null |
vkconfig_core/test/test_path_manager.cpp
|
johnzupin/VulkanTools
|
4a4d824b43984d29902f7c8246aab99f0909151d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2020 Valve Corporation
* Copyright (c) 2020 LunarG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author:
* - Christophe Riccio <christophe@lunarg.com>
*/
#include "../path_manager.h"
#include "../util.h"
#include "../platform.h"
#include <QDir>
#include <QFileInfo>
#include <gtest/gtest.h>
static void Init(PathManager& paths, const QString& path_value) {
for (int i = 0, n = PATH_COUNT; i < n; ++i) {
const PathType path = static_cast<PathType>(i);
paths.SetPath(path, path_value.toStdString());
}
}
static QString InitPath(const char* tail) {
const QDir dir(QString("vkconfig/test_path_manager/") + tail);
const QString native_path(ConvertNativeSeparators(dir.absolutePath().toStdString()).c_str());
return native_path;
}
TEST(test_path_manager, init_first) {
const QString path_value = InitPath("init_first");
PathManager paths;
Init(paths, path_value);
EXPECT_STREQ(path_value.toUtf8().constData(), paths.GetPath(PATH_FIRST));
}
TEST(test_path_manager, init_last) {
const QString path_value = InitPath("init_last");
PathManager paths;
Init(paths, path_value);
EXPECT_STREQ(path_value.toUtf8().constData(), paths.GetPath(PATH_LAST));
}
TEST(test_path_manager, init_all) {
PathManager paths;
paths.Clear();
for (int i = PATH_FIRST, n = PATH_LAST; i <= n; ++i) {
const PathType path = static_cast<PathType>(i);
QString init_path = InitPath("init_all_%d");
std::string path_string = format(init_path.toUtf8().constData(), i);
paths.SetPath(path, path_string.c_str());
EXPECT_STREQ(path_string.c_str(), paths.GetPath(path));
}
}
TEST(test_path_manager, path_format) {
static const char* table[] = {
"/vkconfig/test\\path/format/", "/vkconfig/test\\path/format\\", "/vkconfig\\test/path/format/",
"/vkconfig\\test/path\\format/", "/vkconfig\\test/path/format", "/vkconfig/test/path/format",
"\\vkconfig\\test/path\\format", "/vkconfig/test/path/format/", "\\vkconfig\\test/path\\format\\"};
for (std::size_t i = 0, n = countof(table); i < n; ++i) {
PathManager paths;
paths.Clear();
paths.SetPath(PATH_CONFIGURATION, QDir::homePath().toStdString() + table[i]);
const QString path = paths.GetPath(PATH_CONFIGURATION);
const QString home_path(paths.GetPath(PATH_HOME));
if (VKC_PLATFORM == VKC_PLATFORM_WINDOWS) {
EXPECT_STREQ((home_path + "\\vkconfig\\test\\path\\format").toStdString().c_str(), path.toStdString().c_str());
} else {
EXPECT_STREQ((home_path + "/vkconfig/test/path/format").toStdString().c_str(), path.toStdString().c_str());
}
}
}
// Test that GetPath return the home directory when the stored path is empty
TEST(test_path_manager, empty_home) {
PathManager paths;
paths.Clear();
EXPECT_STRNE(paths.GetPath(PATH_HOME), "");
EXPECT_STREQ(paths.GetPath(PATH_HOME), paths.GetPath(PATH_FIRST));
}
// Test that export path is used as an alternative to import path when import path is empty
TEST(test_path_manager, empty_import) {
PathManager paths;
paths.Clear();
paths.SetPath(PATH_EXPORT_CONFIGURATION, InitPath("empty_import").toStdString());
EXPECT_STRNE(paths.GetPath(PATH_IMPORT_CONFIGURATION), paths.GetPath(PATH_HOME));
EXPECT_STREQ(paths.GetPath(PATH_EXPORT_CONFIGURATION), paths.GetPath(PATH_IMPORT_CONFIGURATION));
}
// Test that import path is used as an alternative to export path when export path is empty
TEST(test_path_manager, empty_export) {
PathManager paths;
paths.Clear();
paths.SetPath(PATH_IMPORT_CONFIGURATION, InitPath("empty_export").toStdString());
EXPECT_STRNE(paths.GetPath(PATH_EXPORT_CONFIGURATION), paths.GetPath(PATH_HOME));
EXPECT_STREQ(paths.GetPath(PATH_IMPORT_CONFIGURATION), paths.GetPath(PATH_EXPORT_CONFIGURATION));
paths.Load();
}
TEST(test_path_manager, check_missing_dir) {
PathManager paths;
paths.Clear();
paths.SetPath(PATH_CONFIGURATION, InitPath("check_missing_dir").toStdString());
EXPECT_TRUE(strstr(paths.GetPath(PATH_CONFIGURATION), "check_missing_dir") != nullptr);
paths.Load();
}
TEST(test_path_manager, check_default_filename) {
PathManager paths;
paths.Clear();
const QString string = paths.GetFullPath(PATH_OVERRIDE_SETTINGS);
EXPECT_TRUE(string.endsWith("vk_layer_settings.txt"));
paths.Load();
}
TEST(test_path_manager, check_default_suffix) {
PathManager paths;
paths.Clear();
const QString string = paths.GetFullPath(PATH_EXPORT_CONFIGURATION, "my_configuration");
EXPECT_TRUE(string.endsWith("my_configuration.json"));
paths.Load();
}
TEST(test_path_manager, check_with_suffix) {
PathManager paths;
paths.Clear();
const QString string = paths.GetFullPath(PATH_EXPORT_CONFIGURATION, "my_configuration.json");
EXPECT_TRUE(string.endsWith("my_configuration.json"));
paths.Load();
}
| 32.535294
| 123
| 0.703851
|
johnzupin
|
ed177f33c902b38b177df32bd5282bc7cc3f1a51
| 3,445
|
hpp
|
C++
|
src/3rd party/boost/boost/graph/topological_sort.hpp
|
OLR-xray/OLR-3.0
|
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
|
[
"Apache-2.0"
] | 8
|
2016-01-25T20:18:51.000Z
|
2019-03-06T07:00:04.000Z
|
CvGameCoreDLL/Boost-1.32.0/include/boost/graph/topological_sort.hpp
|
Imperator-Knoedel/Sunset
|
19c95f4844586b96341f3474b58e0dacaae485b9
|
[
"MIT"
] | null | null | null |
CvGameCoreDLL/Boost-1.32.0/include/boost/graph/topological_sort.hpp
|
Imperator-Knoedel/Sunset
|
19c95f4844586b96341f3474b58e0dacaae485b9
|
[
"MIT"
] | 3
|
2016-02-14T01:20:43.000Z
|
2021-02-03T11:19:11.000Z
|
//
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// This file is part of the Boost Graph Library
//
// You should have received a copy of the License Agreement for the
// Boost Graph Library along with the software; see the file LICENSE.
// If not, contact Office of Research, University of Notre Dame, Notre
// Dame, IN 46556.
//
// Permission to modify the code and to distribute modified code is
// granted, provided the text of this NOTICE is retained, a notice that
// the code was modified is included with the above COPYRIGHT NOTICE and
// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE
// file is distributed with the modified code.
//
// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
// By way of example, but not limitation, Licensor MAKES NO
// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
// OR OTHER RIGHTS.
//=======================================================================
//
#ifndef BOOST_GRAPH_TOPOLOGICAL_SORT_HPP
#define BOOST_GRAPH_TOPOLOGICAL_SORT_HPP
#include <boost/config.hpp>
#include <boost/property_map.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/exception.hpp>
namespace boost {
// Topological sort visitor
//
// This visitor merely writes the linear ordering into an
// OutputIterator. The OutputIterator could be something like an
// ostream_iterator, or it could be a back/front_insert_iterator.
// Note that if it is a back_insert_iterator, the recorded order is
// the reverse topological order. On the other hand, if it is a
// front_insert_iterator, the recorded order is the topological
// order.
//
template <typename OutputIterator>
struct topo_sort_visitor : public dfs_visitor<>
{
topo_sort_visitor(OutputIterator _iter)
: m_iter(_iter) { }
template <typename Edge, typename Graph>
void back_edge(const Edge& u, Graph&) { throw not_a_dag(); }
template <typename Vertex, typename Graph>
void finish_vertex(const Vertex& u, Graph&) { *m_iter++ = u; }
OutputIterator m_iter;
};
// Topological Sort
//
// The topological sort algorithm creates a linear ordering
// of the vertices such that if edge (u,v) appears in the graph,
// then u comes before v in the ordering. The graph must
// be a directed acyclic graph (DAG). The implementation
// consists mainly of a call to depth-first search.
//
template <typename VertexListGraph, typename OutputIterator,
typename P, typename T, typename R>
void topological_sort(VertexListGraph& g, OutputIterator result,
const bgl_named_params<P, T, R>& params)
{
typedef topo_sort_visitor<OutputIterator> TopoVisitor;
depth_first_search(g, params.visitor(TopoVisitor(result)));
}
template <typename VertexListGraph, typename OutputIterator>
void topological_sort(VertexListGraph& g, OutputIterator result)
{
topological_sort(g, result,
bgl_named_params<int, buffer_param_t>(0)); // bogus
}
} // namespace boost
#endif /*BOOST_GRAPH_TOPOLOGICAL_SORT_H*/
| 37.043011
| 73
| 0.702758
|
OLR-xray
|
ed1b1b4f31ee6bc1756a75dd62f67a374c29a8d9
| 690
|
cpp
|
C++
|
keygen/keygen.cpp
|
z-beslaneev/ONVIF_event_server
|
1ccd481f2e380416f50a8707dd578bd8b9b2498c
|
[
"MIT"
] | 2
|
2021-03-16T14:04:00.000Z
|
2021-11-01T15:04:46.000Z
|
keygen/keygen.cpp
|
z-beslaneev/ONVIF_event_server
|
1ccd481f2e380416f50a8707dd578bd8b9b2498c
|
[
"MIT"
] | null | null | null |
keygen/keygen.cpp
|
z-beslaneev/ONVIF_event_server
|
1ccd481f2e380416f50a8707dd578bd8b9b2498c
|
[
"MIT"
] | null | null | null |
#include <fstream>
#include <iostream>
#include <iomanip>
#include <md5Util.h>
#include <sysinfo.h>
int main()
{
std::stringstream sysinfo;
try
{
sysinfo << GetMac() << "||" << GetMicroSDCID() << "||" << GetCPUSerial();
}
catch(std::exception& ex)
{
std::cerr << "Can't get system info: " << ex.what() << std::endl;
return -1;
}
std::ofstream keyFile("/var/lib/SphinxDetectors/server.key", std::ios_base::out | std::ios_base::trunc);
if (!keyFile.is_open())
{
std::cerr << "Can't create server.key file" << std::endl;
return -1;
}
keyFile << StringToMD5(sysinfo.str());
keyFile.close();
std::cout << "Key created succesfully!" << std::endl;
return 0;
}
| 19.166667
| 105
| 0.617391
|
z-beslaneev
|
ed1f39b9ef14e23425a52e1a1accacf4fc4b89cb
| 150
|
cpp
|
C++
|
source/light/Light.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
source/light/Light.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
source/light/Light.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
#include "raytracing/light/Light.h"
namespace rt
{
Light::Light()
: m_shadows(true)
{
}
bool Light::CastsShadows() const
{
return m_shadows;
}
}
| 9.375
| 35
| 0.686667
|
xzrunner
|
ed244531bee2991f8206e0839d0e7eb71a59c0d4
| 8,352
|
cpp
|
C++
|
gui/qt/mainwidgets/periodictablewidget.cpp
|
hein09/vipster
|
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
|
[
"BSD-2-Clause"
] | 6
|
2015-12-02T15:33:27.000Z
|
2017-07-28T17:46:51.000Z
|
gui/qt/mainwidgets/periodictablewidget.cpp
|
hein09/vipster
|
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
|
[
"BSD-2-Clause"
] | 3
|
2018-02-04T16:11:19.000Z
|
2018-03-16T16:23:29.000Z
|
gui/qt/mainwidgets/periodictablewidget.cpp
|
hein09/vipster
|
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
|
[
"BSD-2-Clause"
] | 1
|
2017-07-05T11:44:55.000Z
|
2017-07-05T11:44:55.000Z
|
#include <QPushButton>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QLineEdit>
#include <QColorDialog>
#include <QMessageBox>
#include "periodictablewidget.h"
#include "ui_periodictablewidget.h"
#include "../mainwindow.h"
using namespace Vipster;
template<typename T>
void PeriodicTableWidget::registerProperty(QWidget*, T Element::*)
{}
template<>
void PeriodicTableWidget::registerProperty(QWidget* w, double Element::* prop)
{
connect(static_cast<QDoubleSpinBox*>(w),
qOverload<double>(&QDoubleSpinBox::valueChanged), this,
[prop, this](double newVal){
currentElement->*prop = newVal;
if(isGlobal){
triggerUpdate(GUI::Change::settings);
}else{
triggerUpdate(GUI::Change::settings | GUI::Change::atoms);
}
}
);
connect(this, &PeriodicTableWidget::currentEntryChanged, this,
[prop, w, this](){
QSignalBlocker block{w};
if(currentElement){
w->setEnabled(true);
static_cast<QDoubleSpinBox*>(w)->setValue(
static_cast<double>(currentElement->*prop));
}else{
w->setDisabled(true);
}
}
);
}
template<>
void PeriodicTableWidget::registerProperty(QWidget* w, unsigned int Element::* prop)
{
connect(static_cast<QSpinBox*>(w),
qOverload<int>(&QSpinBox::valueChanged), this,
[prop, this](int newVal){
currentElement->*prop = static_cast<unsigned int>(newVal);
triggerUpdate(GUI::Change::settings);
}
);
connect(this, &PeriodicTableWidget::currentEntryChanged, this,
[prop, w, this](){
QSignalBlocker block{w};
if(currentElement){
w->setEnabled(true);
static_cast<QSpinBox*>(w)->setValue(
static_cast<int>(currentElement->*prop));
}else{
w->setDisabled(true);
}
}
);
}
template<>
void PeriodicTableWidget::registerProperty(QWidget* w, std::string Element::* prop)
{
connect(static_cast<QLineEdit*>(w),
&QLineEdit::editingFinished, this,
[prop, w, this](){
currentElement->*prop = static_cast<QLineEdit*>(w)->text().toStdString();
triggerUpdate(GUI::Change::settings);
}
);
connect(this, &PeriodicTableWidget::currentEntryChanged, this,
[prop, w, this](){
QSignalBlocker block{w};
if(currentElement){
w->setEnabled(true);
static_cast<QLineEdit*>(w)->setText(
QString::fromStdString(currentElement->*prop));
}else{
w->setDisabled(true);
}
}
);
}
template<>
void PeriodicTableWidget::registerProperty(QWidget* w, ColVec Element::* prop)
{
connect(static_cast<QPushButton*>(w),
&QPushButton::clicked, this,
[prop, w, this](){
ColVec& col = currentElement->*prop;
auto oldCol = QColor::fromRgb(col[0], col[1], col[2], col[3]);
auto newCol = QColorDialog::getColor(oldCol, this, QString{},
QColorDialog::ShowAlphaChannel);
if(!newCol.isValid()){
return;
}
col = {static_cast<uint8_t>(newCol.red()),
static_cast<uint8_t>(newCol.green()),
static_cast<uint8_t>(newCol.blue()),
static_cast<uint8_t>(newCol.alpha())};
w->setStyleSheet(QString("background-color: %1").arg(newCol.name()));
triggerUpdate(GUI::Change::settings);
}
);
connect(this, &PeriodicTableWidget::currentEntryChanged, this,
[prop, w, this](){
QSignalBlocker block{w};
if(currentElement){
w->setEnabled(true);
const ColVec& col = currentElement->*prop;
w->setStyleSheet(QString("background-color: rgb(%1,%2,%3)")
.arg(col[0]).arg(col[1]).arg(col[2]));
}else{
w->setDisabled(true);
}
}
);
}
PeriodicTableWidget::PeriodicTableWidget(QWidget *parent, bool isGlobal) :
BaseWidget(parent),
ui(new Ui::PeriodicTableWidget),
isGlobal{isGlobal}
{
ui->setupUi(this);
registerProperty(ui->mSel, &Element::m);
registerProperty(ui->zSel, &Element::Z);
registerProperty(ui->covSel, &Element::covr);
registerProperty(ui->vdwSel, &Element::vdwr);
registerProperty(ui->cpnlSel, &Element::CPNL);
registerProperty(ui->cpppSel, &Element::CPPP);
registerProperty(ui->pwppSel, &Element::PWPP);
registerProperty(ui->colSel, &Element::col);
registerProperty(ui->cutSel, &Element::bondcut);
emit(currentEntryChanged());
ui->toGlobalBut->setVisible(!isGlobal);
ui->fromGlobalBut->setVisible(!isGlobal);
ui->defaultBut->setVisible(isGlobal);
ui->deleteBut->setVisible(isGlobal);
//initialize table if global
if(isGlobal){
// ensure that all regular types are present, irregardless of user settings
for(const auto&[el, _]: Vipster::pte){
master->pte.find_or_fallback(el);
}
setTable(&master->pte);
}
}
PeriodicTableWidget::~PeriodicTableWidget()
{
delete ui;
}
void PeriodicTableWidget::setEntry(QListWidgetItem *item)
{
if(item && table){
auto tmp = table->find(item->text().toStdString());
if(tmp != table->end()){
// if all objects are valid and we got a known type, set everything up
currentName = &tmp->first;
currentElement = &tmp->second;
if(isGlobal){
bool defElem = pte.find(*currentName) != pte.end();
ui->defaultBut->setEnabled(defElem);
ui->deleteBut->setEnabled(!defElem);
}else{
ui->toGlobalBut->setEnabled(true);
ui->fromGlobalBut->setEnabled(master->pte.find(*currentName)
!= master->pte.end());
}
emit(currentEntryChanged());
return;
}
}
// if something's not right, disable widget
currentName = nullptr;
currentElement = nullptr;
if(isGlobal){
ui->defaultBut->setDisabled(true);
ui->deleteBut->setDisabled(true);
}else{
ui->fromGlobalBut->setDisabled(true);
ui->toGlobalBut->setDisabled(true);
}
emit(currentEntryChanged());
}
void PeriodicTableWidget::setTable(PeriodicTable* pte)
{
table = pte;
auto row = ui->pteList->currentRow();
ui->pteList->clear();
if(pte){
for(const auto& entry: *pte){
ui->pteList->addItem(QString::fromStdString(entry.first));
}
}
if (row > ui->pteList->count()) row = ui->pteList->count()-1;
ui->pteList->setCurrentRow(row);
}
void PeriodicTableWidget::changeEntry()
{
GUI::change_t change = GUI::Change::settings;
if(sender() == ui->toGlobalBut){
master->pte[*currentName] = *currentElement;
}else if(sender() == ui->fromGlobalBut){
*currentElement = master->pte.at(*currentName);
change |= GUI::Change::atoms;
}else if(sender() == ui->defaultBut){
*currentElement = Vipster::pte.at(*currentName);
}else if(sender() == ui->deleteBut){
table->erase(table->find(*currentName));
}else{
throw Error{"PeriodicTable: changeEntry called with unknown sender"};
}
setTable(table);
setEntry(ui->pteList->currentItem());
triggerUpdate(change);
}
void PeriodicTableWidget::updateWidget(Vipster::GUI::change_t change)
{
if(updateTriggered) return;
// update table
if(change & GUI::Change::settings) setTable(table);
}
void PeriodicTableWidget::on_helpButton_clicked()
{
QMessageBox::information(this, QString("About periodic tables"), Vipster::PeriodicTableAbout);
}
| 34.37037
| 98
| 0.561901
|
hein09
|
ed268577481fafc0b2405d2dd735f511a150a662
| 15,427
|
cpp
|
C++
|
packages/monte_carlo/event/weight_cutoff/test/tstStandardWeightCutoffRoulette.cpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 10
|
2019-11-14T19:58:30.000Z
|
2021-04-04T17:44:09.000Z
|
packages/monte_carlo/event/weight_cutoff/test/tstStandardWeightCutoffRoulette.cpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 43
|
2020-03-03T19:59:20.000Z
|
2021-09-08T03:36:08.000Z
|
packages/monte_carlo/event/weight_cutoff/test/tstStandardWeightCutoffRoulette.cpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 6
|
2020-02-12T17:37:07.000Z
|
2020-09-08T18:59:51.000Z
|
//---------------------------------------------------------------------------//
//!
//! \file tstStandardWeightCutoffRoulette.cpp
//! \author Luke Kersting
//! \brief Standard weight cutoff roulette unit tests.
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
#include <memory>
// FRENSIE Includes
#include "MonteCarlo_StandardWeightCutoffRoulette.hpp"
#include "MonteCarlo_PhotonState.hpp"
#include "MonteCarlo_ElectronState.hpp"
#include "MonteCarlo_PositronState.hpp"
#include "MonteCarlo_NeutronState.hpp"
#include "Utility_RandomNumberGenerator.hpp"
#include "Utility_OpenMPProperties.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
#include "ArchiveTestHelpers.hpp"
//---------------------------------------------------------------------------//
// Testing Types
//---------------------------------------------------------------------------//
typedef TestArchiveHelper::TestArchives TestArchives;
using boost::units::si::kelvin;
using boost::units::cgs::cubic_centimeter;
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that the cutoff weights can be set
FRENSIE_UNIT_TEST( StandardWeightCutoffRoulette,
setCutoffWeights )
{
auto weight_roulette = std::make_shared<MonteCarlo::StandardWeightCutoffRoulette>();
double threshold_weight = 1e-20;
double survival_weight = 1e-5;
weight_roulette->setCutoffWeights( MonteCarlo::PHOTON,
threshold_weight,
survival_weight );
double test_threshold_weight, test_survival_weight;
weight_roulette->getCutoffWeights( MonteCarlo::PHOTON,
test_threshold_weight,
test_survival_weight );
FRENSIE_CHECK_EQUAL( threshold_weight, test_threshold_weight );
FRENSIE_CHECK_EQUAL( survival_weight, test_survival_weight );
test_threshold_weight = 0.0;
test_survival_weight = 1.0;
weight_roulette->setCutoffWeights( MonteCarlo::NEUTRON,
threshold_weight,
survival_weight );
weight_roulette->getCutoffWeights( MonteCarlo::NEUTRON,
test_threshold_weight,
test_survival_weight );
FRENSIE_CHECK_EQUAL( threshold_weight, test_threshold_weight );
FRENSIE_CHECK_EQUAL( survival_weight, test_survival_weight );
test_threshold_weight = 0.0;
test_survival_weight = 1.0;
weight_roulette->setCutoffWeights( MonteCarlo::ELECTRON,
threshold_weight,
survival_weight );
weight_roulette->getCutoffWeights( MonteCarlo::ELECTRON,
test_threshold_weight,
test_survival_weight );
FRENSIE_CHECK_EQUAL( threshold_weight, test_threshold_weight );
FRENSIE_CHECK_EQUAL( survival_weight, test_survival_weight );
test_threshold_weight = 0.0;
test_survival_weight = 1.0;
weight_roulette->setCutoffWeights( MonteCarlo::POSITRON,
threshold_weight,
survival_weight );
weight_roulette->getCutoffWeights( MonteCarlo::POSITRON,
test_threshold_weight,
test_survival_weight );
FRENSIE_CHECK_EQUAL( threshold_weight, test_threshold_weight );
FRENSIE_CHECK_EQUAL( survival_weight, test_survival_weight );
test_threshold_weight = 0.0;
test_survival_weight = 1.0;
std::set<MonteCarlo::ParticleType> particle_types;
weight_roulette->getParticleTypes( particle_types );
FRENSIE_REQUIRE_EQUAL( particle_types.size(), 4 );
FRENSIE_CHECK( particle_types.count( MonteCarlo::PHOTON ) );
FRENSIE_CHECK( particle_types.count( MonteCarlo::NEUTRON ) );
FRENSIE_CHECK( particle_types.count( MonteCarlo::ELECTRON ) );
FRENSIE_CHECK( particle_types.count( MonteCarlo::POSITRON ) );
}
//---------------------------------------------------------------------------//
// Check that a particle can be rouletted
FRENSIE_UNIT_TEST( StandardWeightCutoffRoulette,
rouletteParticleWeight )
{
std::shared_ptr<MonteCarlo::StandardWeightCutoffRoulette>
weight_roulette( new MonteCarlo::StandardWeightCutoffRoulette );
double threshold_weight = 1e-15;
double survival_weight = 1e-12;
weight_roulette->setCutoffWeights( MonteCarlo::PHOTON,
threshold_weight,
survival_weight );
weight_roulette->setCutoffWeights( MonteCarlo::NEUTRON,
threshold_weight,
survival_weight );
weight_roulette->setCutoffWeights( MonteCarlo::ELECTRON,
threshold_weight,
survival_weight );
weight_roulette->setCutoffWeights( MonteCarlo::POSITRON,
threshold_weight,
survival_weight );
{
MonteCarlo::PhotonState photon( 0 );
photon.setEnergy( 1.0 );
photon.setPosition( 0.0, 0.0, 0.0 );
photon.setDirection( 0.0, 0.0, 1.0 );
photon.setWeight( 9e-16 );
std::vector<double> fake_stream( 2 );
fake_stream[0] = 9e-4; // Particle survives
fake_stream[1] = 9e-4 + 1e-10; // Particle is rouletted
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
weight_roulette->rouletteParticleWeight( photon );
FRENSIE_CHECK_EQUAL( photon.getXPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( photon.getYPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( photon.getZPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( photon.getXDirection(), 0.0 );
FRENSIE_CHECK_EQUAL( photon.getYDirection(), 0.0 );
FRENSIE_CHECK_EQUAL( photon.getZDirection(), 1.0 );
FRENSIE_CHECK_EQUAL( photon.getWeight(), survival_weight );
photon.setWeight( 9e-16 );
weight_roulette->rouletteParticleWeight( photon );
//FRENSIE_CHECK_EQUAL( photon.getWeight(), 0.0 );
FRENSIE_CHECK( photon.isGone() );
Utility::RandomNumberGenerator::unsetFakeStream();
}
{
MonteCarlo::NeutronState neutron( 0 );
neutron.setEnergy( 1.0 );
neutron.setPosition( 0.0, 0.0, 0.0 );
neutron.setDirection( 0.0, 0.0, 1.0 );
neutron.setWeight( 9e-16 );
std::vector<double> fake_stream( 2 );
fake_stream[0] = 9e-4; // Particle survives
fake_stream[1] = 9e-4 + 1e-10; // Particle is rouletted
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
weight_roulette->rouletteParticleWeight( neutron );
FRENSIE_CHECK_EQUAL( neutron.getXPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( neutron.getYPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( neutron.getZPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( neutron.getXDirection(), 0.0 );
FRENSIE_CHECK_EQUAL( neutron.getYDirection(), 0.0 );
FRENSIE_CHECK_EQUAL( neutron.getZDirection(), 1.0 );
FRENSIE_CHECK_EQUAL( neutron.getWeight(), survival_weight );
neutron.setWeight( 9e-16 );
weight_roulette->rouletteParticleWeight( neutron );
//FRENSIE_CHECK_EQUAL( neutron.getWeight(), 0.0 );
FRENSIE_CHECK( neutron.isGone() );
Utility::RandomNumberGenerator::unsetFakeStream();
}
{
MonteCarlo::ElectronState electron( 0 );
electron.setEnergy( 1.0 );
electron.setPosition( 0.0, 0.0, 0.0 );
electron.setDirection( 0.0, 0.0, 1.0 );
electron.setWeight( 9e-16 );
std::vector<double> fake_stream( 2 );
fake_stream[0] = 9e-4; // Particle survives
fake_stream[1] = 9e-4 + 1e-10; // Particle is rouletted
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
weight_roulette->rouletteParticleWeight( electron );
FRENSIE_CHECK_EQUAL( electron.getXPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( electron.getYPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( electron.getZPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( electron.getXDirection(), 0.0 );
FRENSIE_CHECK_EQUAL( electron.getYDirection(), 0.0 );
FRENSIE_CHECK_EQUAL( electron.getZDirection(), 1.0 );
FRENSIE_CHECK_EQUAL( electron.getWeight(), survival_weight );
electron.setWeight( 9e-16 );
weight_roulette->rouletteParticleWeight( electron );
//FRENSIE_CHECK_EQUAL( electron.getWeight(), 0.0 );
FRENSIE_CHECK( electron.isGone() );
Utility::RandomNumberGenerator::unsetFakeStream();
}
{
MonteCarlo::PositronState positron( 0 );
positron.setEnergy( 1.0 );
positron.setPosition( 0.0, 0.0, 0.0 );
positron.setDirection( 0.0, 0.0, 1.0 );
positron.setWeight( 9e-16 );
std::vector<double> fake_stream( 2 );
fake_stream[0] = 9e-4; // Particle survives
fake_stream[1] = 9e-4 + 1e-10; // Particle is rouletted
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
weight_roulette->rouletteParticleWeight( positron );
FRENSIE_CHECK_EQUAL( positron.getXPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( positron.getYPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( positron.getZPosition(), 0.0 );
FRENSIE_CHECK_EQUAL( positron.getXDirection(), 0.0 );
FRENSIE_CHECK_EQUAL( positron.getYDirection(), 0.0 );
FRENSIE_CHECK_EQUAL( positron.getZDirection(), 1.0 );
FRENSIE_CHECK_EQUAL( positron.getWeight(), survival_weight );
positron.setWeight( 9e-16 );
weight_roulette->rouletteParticleWeight( positron );
//FRENSIE_CHECK_EQUAL( positron.getWeight(), 0.0 );
FRENSIE_CHECK( positron.isGone() );
Utility::RandomNumberGenerator::unsetFakeStream();
}
}
//---------------------------------------------------------------------------//
// Check that a weight cutoff roulette can be archived
FRENSIE_UNIT_TEST_TEMPLATE_EXPAND( StandardWeightCutoffRoulette,
archive,
TestArchives )
{
FETCH_TEMPLATE_PARAM( 0, RawOArchive );
FETCH_TEMPLATE_PARAM( 1, RawIArchive );
typedef typename std::remove_pointer<RawOArchive>::type OArchive;
typedef typename std::remove_pointer<RawIArchive>::type IArchive;
std::string archive_base_name( "test_standard_weight_roulette" );
std::ostringstream archive_ostream;
{
std::unique_ptr<OArchive> oarchive;
createOArchive( archive_base_name, archive_ostream, oarchive );
std::shared_ptr<const MonteCarlo::StandardWeightCutoffRoulette>
weight_roulette;
{
std::shared_ptr<MonteCarlo::StandardWeightCutoffRoulette>
tmp_weight_roulette( new MonteCarlo::StandardWeightCutoffRoulette );
double threshold_weight = 1e-15;
double survival_weight = 1e-12;
tmp_weight_roulette->setCutoffWeights( MonteCarlo::PHOTON,
threshold_weight,
survival_weight );
tmp_weight_roulette->setCutoffWeights( MonteCarlo::NEUTRON,
threshold_weight,
survival_weight );
tmp_weight_roulette->setCutoffWeights( MonteCarlo::ELECTRON,
threshold_weight,
survival_weight );
tmp_weight_roulette->setCutoffWeights( MonteCarlo::POSITRON,
threshold_weight,
survival_weight );
weight_roulette = tmp_weight_roulette;
}
std::shared_ptr<const MonteCarlo::WeightCutoffRoulette> base_weight_roulette =
weight_roulette;
FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP(base_weight_roulette) );
FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP(weight_roulette) );
}
// Copy the archive ostream to an istream
std::istringstream archive_istream( archive_ostream.str() );
// Load the archived distributions
std::unique_ptr<IArchive> iarchive;
createIArchive( archive_istream, iarchive );
std::shared_ptr<const MonteCarlo::WeightCutoffRoulette> base_weight_roulette;
std::shared_ptr<const MonteCarlo::StandardWeightCutoffRoulette> weight_roulette;
FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP(base_weight_roulette) );
FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP(weight_roulette) );
iarchive.reset();
FRENSIE_CHECK( weight_roulette.get() == base_weight_roulette.get() );
{
double threshold_weight = 1e-15;
double survival_weight = 1e-12;
double test_threshold_weight = 0.0;
double test_survival_weight = 1.0;
base_weight_roulette->getCutoffWeights( MonteCarlo::PHOTON,
test_threshold_weight,
test_survival_weight );
FRENSIE_CHECK_EQUAL( threshold_weight, test_threshold_weight );
FRENSIE_CHECK_EQUAL( survival_weight, test_survival_weight );
test_threshold_weight = 0.0;
test_survival_weight = 1.0;
base_weight_roulette->getCutoffWeights( MonteCarlo::NEUTRON,
test_threshold_weight,
test_survival_weight );
FRENSIE_CHECK_EQUAL( threshold_weight, test_threshold_weight );
FRENSIE_CHECK_EQUAL( survival_weight, test_survival_weight );
test_threshold_weight = 0.0;
test_survival_weight = 1.0;
base_weight_roulette->getCutoffWeights( MonteCarlo::ELECTRON,
test_threshold_weight,
test_survival_weight );
FRENSIE_CHECK_EQUAL( threshold_weight, test_threshold_weight );
FRENSIE_CHECK_EQUAL( survival_weight, test_survival_weight );
test_threshold_weight = 0.0;
test_survival_weight = 1.0;
base_weight_roulette->getCutoffWeights( MonteCarlo::POSITRON,
test_threshold_weight,
test_survival_weight );
FRENSIE_CHECK_EQUAL( threshold_weight, test_threshold_weight );
FRENSIE_CHECK_EQUAL( survival_weight, test_survival_weight );
test_threshold_weight = 0.0;
test_survival_weight = 1.0;
std::set<MonteCarlo::ParticleType> particle_types;
base_weight_roulette->getParticleTypes( particle_types );
FRENSIE_REQUIRE_EQUAL( particle_types.size(), 4 );
FRENSIE_CHECK( particle_types.count( MonteCarlo::PHOTON ) );
FRENSIE_CHECK( particle_types.count( MonteCarlo::NEUTRON ) );
FRENSIE_CHECK( particle_types.count( MonteCarlo::ELECTRON ) );
FRENSIE_CHECK( particle_types.count( MonteCarlo::POSITRON ) );
}
}
//---------------------------------------------------------------------------//
// Custom setup
//---------------------------------------------------------------------------//
FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN();
FRENSIE_CUSTOM_UNIT_TEST_INIT()
{
// Initialize the random number generator
Utility::RandomNumberGenerator::createStreams();
}
FRENSIE_CUSTOM_UNIT_TEST_SETUP_END();
//---------------------------------------------------------------------------//
// end tstStandardWeightCutoffRoulette.cpp
//---------------------------------------------------------------------------//
| 36.818616
| 93
| 0.624684
|
bam241
|
ed2947c80ffc492eabe3bcd51695782666edb400
| 252
|
cpp
|
C++
|
src/Step/1. Input Output/2588.cpp
|
ljh15952/Baekjoon
|
fd85e5fef0f9fea382628e0c60f4f97dcdc3ec74
|
[
"MIT"
] | null | null | null |
src/Step/1. Input Output/2588.cpp
|
ljh15952/Baekjoon
|
fd85e5fef0f9fea382628e0c60f4f97dcdc3ec74
|
[
"MIT"
] | null | null | null |
src/Step/1. Input Output/2588.cpp
|
ljh15952/Baekjoon
|
fd85e5fef0f9fea382628e0c60f4f97dcdc3ec74
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
using namespace std;
int main(){
int a;
string b;
cin >> a >> b;
cout << a * (b[2]-'0') << endl;
cout << a * (b[1]-'0') << endl;
cout << a * (b[0]-'0') << endl;
cout << a * stoi(b) << endl;
return 0;
}
| 14.823529
| 32
| 0.496032
|
ljh15952
|
ed2ffaab119b99dbdc3a4a35d317e13faac861ac
| 4,159
|
cc
|
C++
|
src/MissionManager/KML.cc
|
matthiasnattke/qgroundcontrol
|
9f87623a1598529a7bf24ab1122d409d02a0aed5
|
[
"Apache-2.0"
] | 6
|
2021-05-01T16:37:00.000Z
|
2022-01-12T10:17:47.000Z
|
src/MissionManager/KML.cc
|
matthiasnattke/qgroundcontrol
|
9f87623a1598529a7bf24ab1122d409d02a0aed5
|
[
"Apache-2.0"
] | 2
|
2020-03-26T04:24:00.000Z
|
2020-03-26T13:53:51.000Z
|
src/MissionManager/KML.cc
|
matthiasnattke/qgroundcontrol
|
9f87623a1598529a7bf24ab1122d409d02a0aed5
|
[
"Apache-2.0"
] | 2
|
2021-05-01T17:29:43.000Z
|
2021-12-26T12:23:24.000Z
|
/****************************************************************************
*
* (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "KML.h"
#include <QDomDocument>
#include <QStringList>
const QString Kml::_version("version=\"1.0\"");
const QString Kml::_encoding("encoding=\"UTF-8\"");
const QString Kml::_opengis("http://www.opengis.net/kml/2.2");
const QString Kml::_qgckml("QGC KML");
Kml::Kml()
{
//create header
createHeader();
//name
createTextElement(_docEle, "name", _qgckml);
//open
createTextElement(_docEle, "open", "1");
//create style
createStyles();
}
void Kml::points(const QStringList& points)
{
//create placemark
QDomElement placemark = _domDocument.createElement("Placemark");
_docEle.appendChild(placemark);
createTextElement(placemark, "styleUrl", "yellowLineGreenPoly");
createTextElement(placemark, "name", "Absolute");
createTextElement(placemark, "visibility", "0");
createTextElement(placemark, "description", "Transparent purple line");
QStringList latLonAlt = points[0].split(",");
QStringList lookAtList({latLonAlt[0], latLonAlt[1], "0" \
, "-100", "45", "2500"});
createLookAt(placemark, lookAtList);
//Add linestring
QDomElement lineString = _domDocument.createElement("LineString");
placemark.appendChild(lineString);
//extruder
createTextElement(lineString, "extruder", "1");
createTextElement(lineString, "tessellate", "1");
createTextElement(lineString, "altitudeMode", "absolute");
QString coordinates;
for(const auto& point : points) {
coordinates += point + "\n";
}
createTextElement(lineString, "coordinates", coordinates);
}
void Kml::save(QDomDocument& document)
{
document = _domDocument;
}
void Kml::createHeader()
{
QDomProcessingInstruction header = _domDocument.createProcessingInstruction("xml", _version + " " + _encoding);
_domDocument.appendChild(header);
QDomElement kml = _domDocument.createElement("kml");
kml.setAttribute("xmlns", _opengis);
_docEle = _domDocument.createElement("Document");
kml.appendChild(_docEle);
_domDocument.appendChild(kml);
}
void Kml::createStyles()
{
QDomElement style = _domDocument.createElement("Style");
style.setAttribute("id", "yellowLineGreenPoly");
createStyleLine(style, "7f00ffff", "4", "7f00ff00");
_docEle.appendChild(style);
}
void Kml::createLookAt(QDomElement& placemark, const QStringList &lookAtList)
{
QDomElement lookAt = _domDocument.createElement("LookAt");
placemark.appendChild(lookAt);
createTextElement(lookAt, "longitude", lookAtList[0]);
createTextElement(lookAt, "latitude", lookAtList[1]);
createTextElement(lookAt, "altitude", lookAtList[2]);
createTextElement(lookAt, "heading", lookAtList[3]);
createTextElement(lookAt, "tilt", lookAtList[4]);
createTextElement(lookAt, "range", lookAtList[5]);
}
void Kml::createTextElement(QDomElement& domEle, const QString& elementName, const QString& textElement)
{
// <elementName>textElement</elementName>
auto element = _domDocument.createElement(elementName);
element.appendChild(_domDocument.createTextNode(textElement));
domEle.appendChild(element);
}
void Kml::createStyleLine(QDomElement& domEle, const QString& lineColor, const QString& lineWidth, const QString& polyColor)
{
/*
<LineStyle>
<color>7f00ffff</color>
<width>4</width>
</LineStyle>
<PolyStyle>
<color>7f00ff00</color>
</PolyStyle>
*/
auto lineStyle = _domDocument.createElement("LineStyle");
auto polyStyle = _domDocument.createElement("PolyStyle");
domEle.appendChild(lineStyle);
domEle.appendChild(polyStyle);
createTextElement(lineStyle, "color", lineColor);
createTextElement(lineStyle, "width", lineWidth);
createTextElement(polyStyle, "color", polyColor);
}
Kml::~Kml()
{
}
| 32.24031
| 124
| 0.679009
|
matthiasnattke
|
ed32f5df7562ea460e63db0ff760da6ac92f91b0
| 1,568
|
cc
|
C++
|
PlotUtils/src/SaveUtils.cc
|
sam7k9621/ManagerUtils
|
7b9317df002b3df6f23ae9e559d35bb1fc15b6f6
|
[
"MIT"
] | null | null | null |
PlotUtils/src/SaveUtils.cc
|
sam7k9621/ManagerUtils
|
7b9317df002b3df6f23ae9e559d35bb1fc15b6f6
|
[
"MIT"
] | null | null | null |
PlotUtils/src/SaveUtils.cc
|
sam7k9621/ManagerUtils
|
7b9317df002b3df6f23ae9e559d35bb1fc15b6f6
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
*
* Filename : SaveUtils.cc
* Description : Plot saving utility functions implementation
* Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*******************************************************************************/
#include "ManagerUtils/SysUtils/interface/PathUtils.hpp"
#include "ManagerUtils/PlotUtils/interface/SaveUtils.hpp"
#include "TCanvas.h"
#include "TFile.h"
#include "TH1.h"
#include <boost/format.hpp>
#include <iostream>
#include <string>
using namespace std;
/******************************************************************************/
namespace mgr{
/******************************************************************************/
void
SaveToPDF( TCanvas* c, const string& filename )
{
CheckPath( filename );
c->SaveAs( filename.c_str() );
}
/******************************************************************************/
void
SaveToROOT( TObject* c, const string& filename, const string& objname )
{
CheckPath( filename );
TFile* myfile = TFile::Open( filename.c_str(), "UPDATE" );
c->Write( objname.c_str(), TFile::kOverwrite );
delete myfile;
}
/* void*/
//SaveToROOT( TH1* h, const string& filename, const string& objname )
//{
//CheckPath( filename );
//TFile* myfile = TFile::Open( filename.c_str(), "UPDATE" );
//h->Write( objname.c_str(), TFile::kOverwrite );
//delete myfile;
/*}*/
};
| 30.153846
| 84
| 0.456633
|
sam7k9621
|
ed34e24a06cea55a33695f8b4d726959e1b9537a
| 375
|
cpp
|
C++
|
SampleCode/ClassTemplate9/main.cpp
|
Team-Godel/Godel
|
43bc2bb6ea28881a3db00dd69c1288cb04278d7d
|
[
"MIT"
] | null | null | null |
SampleCode/ClassTemplate9/main.cpp
|
Team-Godel/Godel
|
43bc2bb6ea28881a3db00dd69c1288cb04278d7d
|
[
"MIT"
] | null | null | null |
SampleCode/ClassTemplate9/main.cpp
|
Team-Godel/Godel
|
43bc2bb6ea28881a3db00dd69c1288cb04278d7d
|
[
"MIT"
] | null | null | null |
#include <GodelLib.h>
using namespace std;
int main(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
GDL *Gobj = new GDL(hInstance, "GDL Application", DEFAULT_POS, DEFAULT_POS, 640, 480); // Create a window
Gobj->showCursor(0); // Disable the cursor
Gobj->update(); // Update the state of the window
return 0;
}
| 23.4375
| 108
| 0.682667
|
Team-Godel
|
ed34f469655f8403cf28b659ccc036f6df8dbf53
| 657
|
cpp
|
C++
|
FireThrow/FireThrow/IntroGame.cpp
|
Oskit-Producciones/C-plus-Games
|
caa307d82555e576a299d3ef03c9d929e43ad05a
|
[
"MIT"
] | null | null | null |
FireThrow/FireThrow/IntroGame.cpp
|
Oskit-Producciones/C-plus-Games
|
caa307d82555e576a299d3ef03c9d929e43ad05a
|
[
"MIT"
] | null | null | null |
FireThrow/FireThrow/IntroGame.cpp
|
Oskit-Producciones/C-plus-Games
|
caa307d82555e576a299d3ef03c9d929e43ad05a
|
[
"MIT"
] | null | null | null |
#include "IntroGame.h"
IntroGame::IntroGame():GameObject(false,"..//Imagenes//Intro.png")
{
Enable(true);
alpha = 0;
sprite.SetColor(sf::Color(255, 255, 255, alpha));
}
void IntroGame::NextFrame()
{
currentframe++;
}
void IntroGame::Draw(RenderWindow *app)
{
if (alpha < 230)
{
sprite.SetColor(sf::Color(255, 255, 255, alpha += 1));
}
else
{
sprite.SetColor(sf::Color(255, 255, 255, 230));
}
GameObject::Draw(app);
}
bool IntroGame::isNextFrame()
{
if(currentframe < maxframes)
{
UpdateFrame();
alpha = 0;
sprite.SetColor(sf::Color(255, 255, 255, alpha));
return true;
}
return false;
}
| 16.846154
| 67
| 0.613394
|
Oskit-Producciones
|
ed36eb53705900dda56c0c6aa336d8b936b3e24c
| 11,929
|
cxx
|
C++
|
libbutl/path-pattern.cxx
|
build2/libbutl
|
405dfa3e28ab71d4f6b5210faba0e3600070a0f3
|
[
"MIT"
] | 6
|
2018-05-31T06:16:37.000Z
|
2021-03-19T10:37:11.000Z
|
libbutl/path-pattern.cxx
|
build2/libbutl
|
405dfa3e28ab71d4f6b5210faba0e3600070a0f3
|
[
"MIT"
] | 3
|
2020-06-19T05:08:42.000Z
|
2021-09-29T05:23:07.000Z
|
libbutl/path-pattern.cxx
|
build2/libbutl
|
405dfa3e28ab71d4f6b5210faba0e3600070a0f3
|
[
"MIT"
] | 1
|
2020-06-16T14:56:48.000Z
|
2020-06-16T14:56:48.000Z
|
// file : libbutl/path-pattern.cxx -*- C++ -*-
// license : MIT; see accompanying LICENSE file
#include <libbutl/path-pattern.hxx>
#include <cassert>
#include <iterator> // reverse_iterator
#include <algorithm> // find()
#include <libbutl/utility.hxx> // lcase()[_WIN32]
#include <libbutl/filesystem.hxx> // path_search()
using namespace std;
namespace butl
{
// patterns
//
static inline bool
match (char c, char pc)
{
#ifndef _WIN32
return c == pc;
#else
return lcase (c) == lcase (pc);
#endif
}
bool
match_bracket (char c, const path_pattern_term& pt)
{
using iterator = string::const_iterator;
assert (pt.bracket ());
iterator i (pt.begin + 1); // Position after '['.
iterator e (pt.end - 1); // Position at ']'.
bool invert (*i == '!');
if (invert)
++i;
bool r (false);
for (iterator b (i); i != e && !r; ++i)
{
char bc (*i);
// If '-' is a first or last character in the bracket expression then
// match it literally and match the range otherwise.
//
if (bc == '-' && i != b && i + 1 != e) // Match the range?
{
// Note that we have already matched the range left endpoint character
// unsuccessfully (otherwise we wouldn't be here), so now we test if
// the character belongs to the (min-char, max-char] range.
//
// Also note that on Windows we match case insensitively and so can't
// just compare the character with the range endpoints. Thus, we
// fallback to matching each range character individually.
//
#ifndef _WIN32
r = c > *(i - 1) && c <= *(i + 1);
#else
for (char bc (*(i - 1) + 1), mx (*(i + 1)); bc <= mx && !r; ++bc)
r = match (c, bc);
#endif
++i; // Position to the range max character.
}
else // Match against the expression character literally.
r = match (c, bc);
}
return r != invert;
}
// Match the name [ni, ne) to the pattern [pi, pe) that may not contain
// bracket expressions. Ranges can be empty.
//
static bool
match_no_brackets (string::const_iterator pi, string::const_iterator pe,
string::const_iterator ni, string::const_iterator ne)
{
using reverse_iterator = std::reverse_iterator<string::const_iterator>;
reverse_iterator rpi (pe);
reverse_iterator rpe (pi);
reverse_iterator rni (ne);
reverse_iterator rne (ni);
// Match the pattern suffix (follows the last *) to the name trailing
// characters.
//
char pc ('\0');
for (; rpi != rpe && (pc = *rpi) != '*' && rni != rne; ++rpi, ++rni)
{
if (!match (*rni, pc) && pc != '?')
return false;
}
// If we got to the (reversed) end of the pattern (no * is encountered)
// than we are done. The success depends on if we got to the (reversed) end
// of the name as well.
//
if (rpi == rpe)
return rni == rne;
// If we didn't reach * in the pattern then we reached the (reversed) end
// of the name. That means we have unmatched non-star terms in the
// pattern, and so match failed.
//
if (pc != '*')
{
assert (rni == rne);
return false;
}
// Match the pattern prefix (ends with the first *) to the name leading
// characters. If they mismatch we failed. Otherwise if this is an only *
// in the pattern (matches whatever is left in the name) then we succeed,
// otherwise we perform backtracking (recursively).
//
pe = rpi.base ();
ne = rni.base ();
// Compare the pattern and the name term by char until the name suffix or
// * is encountered in the pattern (whichever happens first). Fail if a
// char mismatches.
//
for (; (pc = *pi) != '*' && ni != ne; ++pi, ++ni)
{
if (!match (*ni, pc) && pc != '?')
return false;
}
// If we didn't get to * in the pattern then we got to the name suffix.
// That means that the pattern has unmatched non-star terms, and so match
// failed.
//
if (pc != '*')
{
assert (ni == ne);
return false;
}
// If * that we have reached is the last one, then it matches whatever is
// left in the name (including an empty range).
//
if (++pi == pe)
return true;
// Perform backtracking.
//
// From now on, we will call the pattern not-yet-matched part (starting
// the leftmost * and ending the rightmost one inclusively) as pattern, and
// the name not-yet-matched part as name.
//
// Here we sequentially assume that * that starts the pattern matches the
// name leading part (staring from an empty one and iterating till the full
// name). So if, at some iteration, the pattern trailing part (that follows
// the leftmost *) matches the name trailing part, then the pattern matches
// the name.
//
bool r;
for (; !(r = match_no_brackets (pi, pe, ni, ne)) && ni != ne; ++ni) ;
return r;
}
// Match a character against the pattern term.
//
static inline bool
match (char c, const path_pattern_term& pt)
{
switch (pt.type)
{
// Matches any character.
//
case path_pattern_term_type::star:
case path_pattern_term_type::question: return true;
case path_pattern_term_type::bracket:
{
return match_bracket (c, pt);
}
case path_pattern_term_type::literal:
{
return match (c, get_literal (pt));
}
}
assert (false); // Can't be here.
return false;
}
// Match the name [ni, ne) to the pattern [pi, pe). Ranges can be empty.
//
static bool
match (string::const_iterator pi, string::const_iterator pe,
string::const_iterator ni, string::const_iterator ne)
{
// If the pattern doesn't contain the bracket expressions then reduce to
// the "clever" approach (see the implementation notes below for details).
//
if (find (pi, pe, '[') == pe)
return match_no_brackets (pi, pe, ni, ne);
// Match the pattern prefix (precedes the first *) to the name leading
// characters.
//
path_pattern_iterator ppi (pi, pe);
path_pattern_iterator ppe;
path_pattern_term pt;
for (; ppi != ppe && !(pt = *ppi).star () && ni != ne; ++ppi, ++ni)
{
if (!match (*ni, pt))
return false;
}
// If we got to the end of the pattern (no * is encountered) than we are
// done. The success depends on if we got to the end of the name as well.
//
if (ppi == ppe)
return ni == ne;
// If we didn't reach * in the pattern then we reached the end of the
// name. That means we have unmatched non-star terms in the pattern, and
// so match failed.
//
if (!pt.star ())
{
assert (ni == ne);
return false;
}
// If * that we have reached is the last term, then it matches whatever is
// left in the name (including an empty range).
//
if (++ppi == ppe)
return true;
// Switch back to the string iterator and perform backtracking.
//
// From now on, we will call the pattern not-yet-matched part (starting
// the leftmost *) as pattern, and the name not-yet-matched part as name.
//
// Here we sequentially assume that * that starts the pattern matches the
// name leading part (see match_no_brackets() for details).
//
bool r;
for (pi = ppi->begin; !(r = match (pi, pe, ni, ne)) && ni != ne; ++ni) ;
return r;
}
bool
path_match (const string& name, const string& pattern)
{
// Implementation notes:
//
// - This has a good potential of becoming hairy quickly so need to strive
// for an elegant way to implement this.
//
// - Most patterns will contains a single * wildcard with a prefix and/or
// suffix (e.g., *.txt, foo*, f*.txt). Something like this is not very
// common: *foo*.
//
// So it would be nice to have a clever implementation that first
// "anchors" itself with a literal prefix and/or suffix and only then
// continue with backtracking. In other words, reduce:
//
// *.txt vs foo.txt -> * vs foo
// foo* vs foo.txt -> * vs .txt
// f*.txt vs foo.txt -> * vs oo
//
// Note that this approach fails if the pattern may contain bracket
// expressions. You can't easily recognize a suffix scanning backwards
// since * semantics depends on the characters to the left:
//
// f[o*]o - * is not a wildcard
// fo*]o - * is a wildcard
//
// That's why we will start with the straightforward left-to-right
// matching and reduce to the "clever" approach when the remaining part
// of the pattern doesn't contain bracket expressions.
auto pi (pattern.rbegin ());
auto pe (pattern.rend ());
auto ni (name.rbegin ());
auto ne (name.rend ());
// The name doesn't match the pattern if it is of a different type than the
// pattern is.
//
bool pd (pi != pe && path::traits_type::is_separator (*pi));
bool nd (ni != ne && path::traits_type::is_separator (*ni));
if (pd != nd)
return false;
// Skip trailing separators if present.
//
if (pd)
{
++pi;
++ni;
}
return match (pattern.begin (), pi.base (), name.begin (), ni.base ());
}
bool
path_match (const path& entry,
const path& pattern,
const dir_path& start,
path_match_flags flags)
{
bool r (false);
auto match = [&entry, &r] (path&& p, const string&, bool interim)
{
// If we found the entry (possibly through one of the recursive
// components) no need to search further.
//
if (p == entry && !interim)
{
r = true;
return false;
}
return true;
};
path_search (pattern, entry, match, start, flags);
return r;
}
// path_pattern_iterator
//
void path_pattern_iterator::
next ()
{
if (i_ == e_)
{
t_ = nullopt; // Convert the object into the end iterator.
return;
}
auto next = [this] (path_pattern_term_type t)
{
assert (t != path_pattern_term_type::bracket);
t_ = path_pattern_term {t, i_, i_ + 1};
++i_;
};
switch (*i_)
{
case '?':
{
next (path_pattern_term_type::question);
break;
}
case '*':
{
next (path_pattern_term_type::star);
break;
}
case '[':
{
// Try to find the bracket expression end.
//
// Note that '[' doesn't necessarily starts the bracket expression (no
// closing bracket, empty, etc). If that's the case, then we end up
// with the '[' literal terminal.
//
bool expr (false);
for (;;) // Breakout loop.
{
string::const_iterator i (i_ + 1); // Position after '['.
if (i == e_) // Is '[' the pattern last character?
break;
bool invert (*i == '!');
if (invert && ++i == e_) // Is '!' the pattern last character?
break;
// Find the bracket expression end.
//
// Note that the bracket expression may not be empty and ']' is a
// literal if it is the first expression character.
//
for (++i; i != e_ && *i != ']'; ++i) ;
if (i == e_) // The closing bracket is not found?
break;
expr = true;
++i; // Position after ']'.
t_ = path_pattern_term {path_pattern_term_type::bracket, i_, i};
i_ = i;
break;
}
// Fallback to '[' literal if it is not a bracket expression.
//
if (expr)
break;
}
// Fall through.
default:
{
next (path_pattern_term_type::literal);
}
}
}
}
| 28.134434
| 79
| 0.571632
|
build2
|
ed3dd0c8fa7bd7278b15a67812dfd032af549b22
| 3,521
|
cpp
|
C++
|
DataStructures/GraphMain.cpp
|
SimpleTechTalks/SimpleTechTalks
|
eefdb4cffc955f43535f4054d1558978ae0088e1
|
[
"MIT"
] | null | null | null |
DataStructures/GraphMain.cpp
|
SimpleTechTalks/SimpleTechTalks
|
eefdb4cffc955f43535f4054d1558978ae0088e1
|
[
"MIT"
] | null | null | null |
DataStructures/GraphMain.cpp
|
SimpleTechTalks/SimpleTechTalks
|
eefdb4cffc955f43535f4054d1558978ae0088e1
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
#include "GraphDefine.h"
void add_header (const char *line)
{
cout << "========================================================================" << endl;
cout << line << endl;
cout << "========================================================================" << endl;
}
void weightedGraphFunctionality ()
{
Graph g(7, false);
g.addEdgeWithWeight (0, 1, 3);
g.addEdgeWithWeight (0, 2, 2);
g.addEdgeWithWeight (0, 3, 6);
g.addEdgeWithWeight (2, 1, 2);
g.addEdgeWithWeight (1, 4, 6);
g.addEdgeWithWeight (1, 5, 1);
g.addEdgeWithWeight (4, 6, 1);
g.addEdgeWithWeight (5, 6, 5);
g.addEdgeWithWeight (3, 6, 2);
g.addEdgeWithWeight (5, 3, 1);
g.addEdgeWithWeight (1, 0, -5);
g.getEdgesIn2DFormat ();
add_header ("Finding shortest path in weighted graph from Node 0 using Bellman's Ford algo");
g.shortestPathInWeightedGraph (0);
add_header ("Finding shortest path in weighted graph from Node 0 using Dijkstra algo");
g.shortestPathInWeightedGraph_dijkstra (0);
}
int main ()
{
Graph g(5, true);
g.addEdge (1,2);
g.addEdge (0,2);
g.addEdge (3,2);
g.addEdge (4,2);
g.addEdge (1,3);
g.addEdge (1,4);
g.addEdge (1,5);
g.addEdge (1,7);
g.addEdge (1,0);
g.addEdge (2,2);
g.addEdge (3,2);
g.addEdge (4,2);
g.addEdge (5,2);
cout << "Graph has nodes: " << g.getNumberOfNodes () << endl;
cout << "Graph has edges: " << g.getNumberOfEdges () << endl;
add_header ("Printing Edges information in Adjecency Matrix Format.");
g.getEdgesIn2DFormat ();
add_header ("Printing BFS traversal of Graph");
g.BFS (4);
add_header ("Printing DFS traversal of Graph");
g.DFS (0);
add_header ("Checking Graph Connected Status");
cout << "Graph connected status: " << g.isConnectedGraph () << endl;
add_header ("Checking Graph Mother Vertex Information");
g.printMotherVertex ();
Graph g1(5, false);
g1.addEdge (1,2);
g1.addEdge (0,2);
g1.addEdge (3,2);
g1.addEdge (4,2);
g1.addEdge (1,3);
g1.addEdge (1,4);
g1.addEdge (1,5);
g1.addEdge (1,7);
g1.addEdge (1,0);
g1.addEdge (2,2);
g1.addEdge (3,2);
g1.addEdge (4,1);
g1.addEdge (5,2);
cout << "Graph has nodes: " << g1.getNumberOfNodes () << endl;
cout << "Graph has edges: " << g1.getNumberOfEdges () << endl;
add_header ("Printing Edges information in Adjecency Matrix Format.");
g1.getEdges ();
add_header ("Printing BFS traversal of Graph");
g1.BFS (0);
add_header ("Printing DFS traversal of Graph");
g1.DFS (0);
add_header ("Checking Graph Connected Status");
cout << "Graph connected status: " << g1.isConnectedGraph () << endl;
add_header ("Checking Graph Mother Vertex Information");
g1.printMotherVertex ();
add_header ("Sorting Graph Using Topological Sort");
Graph g2(11, false);
g2.addEdge (0,4);
g2.addEdge (1,0);
g2.addEdge (6,1);
g2.addEdge (1,2);
g2.addEdge (1,5);
g2.addEdge (2,3);
g2.addEdge (6,3);
g2.addEdge (3,7);
g2.addEdge (4,8);
g2.addEdge (5,8);
g2.addEdge (9,7);
g2.addEdge (8,9);
g2.addEdge (9,10);
g2.getEdgesIn2DFormat ();
g2.topologicalSort ();
add_header ("Finding shortest path from Node 6");
g2.shortestPathInUnweightedGraph (6);
add_header ("Finding shortest path from Node 0");
g2.shortestPathInUnweightedGraph (0);
weightedGraphFunctionality ();
}
| 31.4375
| 97
| 0.590457
|
SimpleTechTalks
|
ed3e3e3d927bc9cc698220827b30d7426542c5e4
| 510
|
cpp
|
C++
|
test/HttpClientTest.cpp
|
taozhijiang/roo
|
bea672b9274f91f4002a9742e096152b0d62f122
|
[
"BSD-3-Clause"
] | null | null | null |
test/HttpClientTest.cpp
|
taozhijiang/roo
|
bea672b9274f91f4002a9742e096152b0d62f122
|
[
"BSD-3-Clause"
] | null | null | null |
test/HttpClientTest.cpp
|
taozhijiang/roo
|
bea672b9274f91f4002a9742e096152b0d62f122
|
[
"BSD-3-Clause"
] | 2
|
2019-08-23T02:31:42.000Z
|
2020-05-02T00:12:36.000Z
|
#include <gmock/gmock.h>
#include <string>
#include <iostream>
#include <other/HttpClient.h>
using namespace ::testing;
using namespace roo;
TEST(HttpClientTest, HttpClientSmokeTest) {
const char* url_404 = "http://www.example.com/bb";
const char* url_200 = "http://www.example.com/index.html";
auto client = std::make_shared<HttpClient>();
int code = client->GetByHttp(url_404);
ASSERT_THAT(code, Ne(0));
code = client->GetByHttp(url_200);
ASSERT_THAT(code, Eq(0));
}
| 20.4
| 62
| 0.678431
|
taozhijiang
|
ed4b7d4ef2ca4aff73d6d0a5e7254fd29d210efa
| 50,241
|
cpp
|
C++
|
control/mpc_follower/src/mpc_follower_core.cpp
|
loop-perception/AutowareArchitectureProposal.iv
|
5d8dff0db51634f0c42d2a3e87ca423fbee84348
|
[
"Apache-2.0"
] | 1
|
2022-03-09T05:53:04.000Z
|
2022-03-09T05:53:04.000Z
|
control/mpc_follower/src/mpc_follower_core.cpp
|
loop-perception/AutowareArchitectureProposal.iv
|
5d8dff0db51634f0c42d2a3e87ca423fbee84348
|
[
"Apache-2.0"
] | 4
|
2022-01-07T21:21:04.000Z
|
2022-03-14T21:25:37.000Z
|
control/mpc_follower/src/mpc_follower_core.cpp
|
loop-perception/AutowareArchitectureProposal.iv
|
5d8dff0db51634f0c42d2a3e87ca423fbee84348
|
[
"Apache-2.0"
] | 2
|
2021-03-09T00:20:39.000Z
|
2021-04-16T10:23:36.000Z
|
// Copyright 2018-2019 Autoware Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mpc_follower/mpc_follower_core.hpp"
#include <tf2_ros/create_timer_ros.h>
#include <algorithm>
#include <deque>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#define DEG2RAD 3.1415926535 / 180.0
#define RAD2DEG 180.0 / 3.1415926535
using namespace std::literals::chrono_literals;
namespace
{
template <typename T>
void update_param(
const std::vector<rclcpp::Parameter> & parameters, const std::string & name, T & value)
{
auto it = std::find_if(
parameters.cbegin(), parameters.cend(),
[&name](const rclcpp::Parameter & parameter) { return parameter.get_name() == name; });
if (it != parameters.cend()) {
value = it->template get_value<T>();
}
}
} // namespace
MPCFollower::MPCFollower(const rclcpp::NodeOptions & node_options)
: Node("mpc_follower", node_options), tf_buffer_(this->get_clock()), tf_listener_(tf_buffer_)
{
using std::placeholders::_1;
ctrl_period_ = declare_parameter("ctrl_period", 0.03);
enable_path_smoothing_ = declare_parameter("enable_path_smoothing", true);
path_filter_moving_ave_num_ = declare_parameter("path_filter_moving_ave_num", 35);
curvature_smoothing_num_traj_ = declare_parameter("curvature_smoothing_num_traj", 1);
curvature_smoothing_num_ref_steer_ = declare_parameter("curvature_smoothing_num_ref_steer", 35);
traj_resample_dist_ = declare_parameter("traj_resample_dist", 0.1); // [m]
admissible_position_error_ = declare_parameter("admissible_position_error", 5.0);
admissible_yaw_error_rad_ = declare_parameter("admissible_yaw_error_rad", M_PI_2);
use_steer_prediction_ = declare_parameter("use_steer_prediction", false);
mpc_param_.steer_tau = declare_parameter("vehicle_model_steer_tau", 0.1);
/* stop state parameters */
stop_state_entry_ego_speed_ = declare_parameter("stop_state_entry_ego_speed", 0.2); // [m]
stop_state_entry_target_speed_ = declare_parameter("stop_state_entry_target_speed", 0.1); // [m]
/* mpc parameters */
double steer_lim_deg, steer_rate_lim_dps;
steer_lim_deg = declare_parameter("steer_lim_deg", 35.0);
steer_rate_lim_dps = declare_parameter("steer_rate_lim_dps", 150.0);
steer_lim_ = steer_lim_deg * DEG2RAD;
steer_rate_lim_ = steer_rate_lim_dps * DEG2RAD;
const auto vehicle_info = vehicle_info_util::VehicleInfoUtil(*this).getVehicleInfo();
wheelbase_ = vehicle_info.wheel_base_m;
/* vehicle model setup */
vehicle_model_type_ = declare_parameter("vehicle_model_type", "kinematics");
if (vehicle_model_type_ == "kinematics") {
vehicle_model_ptr_ =
std::make_shared<KinematicsBicycleModel>(wheelbase_, steer_lim_, mpc_param_.steer_tau);
} else if (vehicle_model_type_ == "kinematics_no_delay") {
vehicle_model_ptr_ = std::make_shared<KinematicsBicycleModelNoDelay>(wheelbase_, steer_lim_);
} else if (vehicle_model_type_ == "dynamics") {
double mass_fl = declare_parameter("mass_fl", 600);
double mass_fr = declare_parameter("mass_fr", 600);
double mass_rl = declare_parameter("mass_rl", 600);
double mass_rr = declare_parameter("mass_rr", 600);
double cf = declare_parameter("cf", 155494.663);
double cr = declare_parameter("cr", 155494.663);
// vehicle_model_ptr_ is only assigned in ctor, so parameter value have to be passed at init
// time // NOLINT
vehicle_model_ptr_ = std::make_shared<DynamicsBicycleModel>(
wheelbase_, mass_fl, mass_fr, mass_rl, mass_rr, cf, cr);
} else {
RCLCPP_ERROR(get_logger(), "vehicle_model_type is undefined");
}
/* QP solver setup */
const std::string qp_solver_type = declare_parameter("qp_solver_type", "unconstraint_fast");
if (qp_solver_type == "unconstraint_fast") {
qpsolver_ptr_ = std::make_shared<QPSolverEigenLeastSquareLLT>();
} else if (qp_solver_type == "osqp") {
qpsolver_ptr_ = std::make_shared<QPSolverOSQP>(get_logger());
} else {
RCLCPP_ERROR(get_logger(), "qp_solver_type is undefined");
}
/* delay compensation */
{
const double delay_tmp = declare_parameter("input_delay", 0.0);
const int delay_step = std::round(delay_tmp / ctrl_period_);
mpc_param_.input_delay = delay_step * ctrl_period_;
input_buffer_ = std::deque<double>(delay_step, 0.0);
}
/* initialize lowpass filter */
{
const double steering_lpf_cutoff_hz = declare_parameter("steering_lpf_cutoff_hz", 3.0);
const double error_deriv_lpf_cutoff_hz = declare_parameter("error_deriv_lpf_cutoff_hz", 5.0);
lpf_steering_cmd_.initialize(ctrl_period_, steering_lpf_cutoff_hz);
lpf_lateral_error_.initialize(ctrl_period_, error_deriv_lpf_cutoff_hz);
lpf_yaw_error_.initialize(ctrl_period_, error_deriv_lpf_cutoff_hz);
}
/* set up ros system */
initTimer(ctrl_period_);
pub_ctrl_cmd_ =
create_publisher<autoware_control_msgs::msg::ControlCommandStamped>("~/output/control_raw", 1);
pub_predicted_traj_ =
create_publisher<autoware_planning_msgs::msg::Trajectory>("~/output/predicted_trajectory", 1);
sub_ref_path_ = create_subscription<autoware_planning_msgs::msg::Trajectory>(
"~/input/reference_trajectory", rclcpp::QoS{1},
std::bind(&MPCFollower::onTrajectory, this, _1));
sub_current_vel_ = create_subscription<geometry_msgs::msg::TwistStamped>(
"~/input/current_velocity", rclcpp::QoS{1}, std::bind(&MPCFollower::onVelocity, this, _1));
sub_steering_ = create_subscription<autoware_vehicle_msgs::msg::Steering>(
"~/input/current_steering", rclcpp::QoS{1}, std::bind(&MPCFollower::onSteering, this, _1));
/* for debug */
pub_debug_marker_ = create_publisher<visualization_msgs::msg::MarkerArray>("~/debug/markers", 10);
pub_debug_mpc_calc_time_ =
create_publisher<autoware_debug_msgs::msg::Float32Stamped>("~/debug/mpc_calc_time", 1);
pub_debug_values_ =
create_publisher<autoware_debug_msgs::msg::Float32MultiArrayStamped>("~/debug/debug_values", 1);
pub_debug_steer_cmd_ =
create_publisher<autoware_vehicle_msgs::msg::Steering>("~/debug/steering_cmd", 1);
// TODO(Frederik.Beaujean) ctor is too long, should factor out parameter declarations
declareMPCparameters();
/* get parameter updates */
set_param_res_ =
this->add_on_set_parameters_callback(std::bind(&MPCFollower::paramCallback, this, _1));
}
MPCFollower::~MPCFollower()
{
autoware_control_msgs::msg::ControlCommand stop_cmd = getStopControlCommand();
publishCtrlCmd(stop_cmd);
}
void MPCFollower::onTimer()
{
updateCurrentPose();
if (!checkData()) {
publishCtrlCmd(getStopControlCommand());
return;
}
autoware_control_msgs::msg::ControlCommand ctrl_cmd;
if (!is_ctrl_cmd_prev_initialized_) {
ctrl_cmd_prev_ = getInitialControlCommand();
is_ctrl_cmd_prev_initialized_ = true;
}
const bool is_mpc_solved = calculateMPC(&ctrl_cmd);
if (isStoppedState()) {
// Reset input buffer
for (auto & value : input_buffer_) {
value = ctrl_cmd_prev_.steering_angle;
}
// Use previous command value as previous raw steer command
raw_steer_cmd_prev_ = ctrl_cmd_prev_.steering_angle;
publishCtrlCmd(ctrl_cmd_prev_);
return;
}
if (!is_mpc_solved) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (5000ms).count(), "MPC is not solved. publish 0 velocity.");
ctrl_cmd = getStopControlCommand();
}
ctrl_cmd_prev_ = ctrl_cmd;
publishCtrlCmd(ctrl_cmd);
}
bool MPCFollower::checkData()
{
if (!vehicle_model_ptr_ || !qpsolver_ptr_) {
RCLCPP_DEBUG(
get_logger(), "vehicle_model = %d, qp_solver = %d", vehicle_model_ptr_ != nullptr,
qpsolver_ptr_ != nullptr);
return false;
}
if (!current_pose_ptr_ || !current_velocity_ptr_ || !current_steer_ptr_) {
RCLCPP_DEBUG(
get_logger(), "waiting data. pose = %d, velocity = %d, steer = %d",
current_pose_ptr_ != nullptr, current_velocity_ptr_ != nullptr,
current_steer_ptr_ != nullptr);
return false;
}
if (ref_traj_.size() == 0) {
RCLCPP_DEBUG(get_logger(), "trajectory size is zero.");
return false;
}
return true;
}
// TODO(Frederik.Beaujean) This method is too long, could be refactored into many smaller units
bool MPCFollower::calculateMPC(autoware_control_msgs::msg::ControlCommand * ctrl_cmd)
{
auto start = std::chrono::system_clock::now();
if (!ctrl_cmd) {
return false;
}
/* recalculate velocity from ego-velocity with dynamics */
MPCTrajectory reference_trajectory =
applyVelocityDynamicsFilter(ref_traj_, current_velocity_ptr_->twist.linear.x);
MPCData mpc_data;
if (!getData(reference_trajectory, &mpc_data)) {
RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), (1000ms).count(), "fail to get Data.");
return false;
}
/* define initial state for error dynamics */
Eigen::VectorXd x0 = getInitialState(mpc_data);
/* delay compensation */
if (!updateStateForDelayCompensation(reference_trajectory, mpc_data.nearest_time, &x0)) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (1000ms).count(),
"updateStateForDelayCompensation failed. stop computation.");
return false;
}
/* resample ref_traj with mpc sampling time */
MPCTrajectory mpc_resampled_ref_traj;
const double mpc_start_time = mpc_data.nearest_time + mpc_param_.input_delay;
if (!resampleMPCTrajectoryByTime(mpc_start_time, reference_trajectory, &mpc_resampled_ref_traj)) {
RCLCPP_WARN_THROTTLE(
get_logger(), *get_clock(), (1000ms).count(), "trajectory resampling failed.");
return false;
}
/* generate mpc matrix : predict equation Xec = Aex * x0 + Bex * Uex + Wex */
MPCMatrix mpc_matrix = generateMPCMatrix(mpc_resampled_ref_traj);
/* solve quadratic optimization */
Eigen::VectorXd Uex;
if (!executeOptimization(mpc_matrix, x0, &Uex)) {
RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), (1000ms).count(), "optimization failed.");
return false;
}
/* apply saturation and filter */
const double u_saturated = std::max(std::min(Uex(0), steer_lim_), -steer_lim_);
const double u_filtered = lpf_steering_cmd_.filter(u_saturated);
/* set control command */
{
const auto & dt = mpc_param_.prediction_dt;
const int prev_idx = std::max(0, static_cast<int>(mpc_data.nearest_idx) - 1);
ctrl_cmd->steering_angle = u_filtered;
ctrl_cmd->steering_angle_velocity = (Uex(1) - Uex(0)) / dt;
ctrl_cmd->velocity = ref_traj_.vx[mpc_data.nearest_idx];
ctrl_cmd->acceleration = (ref_traj_.vx[mpc_data.nearest_idx] - ref_traj_.vx[prev_idx]) / dt;
}
storeSteerCmd(u_filtered);
/* save input to buffer for delay compensation*/
input_buffer_.push_back(ctrl_cmd->steering_angle);
input_buffer_.pop_front();
raw_steer_cmd_pprev_ = raw_steer_cmd_prev_;
raw_steer_cmd_prev_ = Uex(0);
/* ---------- DEBUG ---------- */
const builtin_interfaces::msg::Time & stamp = current_trajectory_ptr_->header.stamp;
/* publish predicted trajectory */
{
Eigen::VectorXd Xex = mpc_matrix.Aex * x0 + mpc_matrix.Bex * Uex + mpc_matrix.Wex;
MPCTrajectory mpc_predicted_traj;
const auto & traj = mpc_resampled_ref_traj;
for (int i = 0; i < mpc_param_.prediction_horizon; ++i) {
const int DIM_X = vehicle_model_ptr_->getDimX();
const double lat_error = Xex(i * DIM_X);
const double yaw_error = Xex(i * DIM_X + 1);
const double x = traj.x[i] - std::sin(traj.yaw[i]) * lat_error;
const double y = traj.y[i] + std::cos(traj.yaw[i]) * lat_error;
const double z = traj.z[i];
const double yaw = traj.yaw[i] + yaw_error;
const double vx = traj.vx[i];
const double k = traj.k[i];
const double smooth_k = traj.smooth_k[i];
const double relative_time = traj.relative_time[i];
mpc_predicted_traj.push_back(x, y, z, yaw, vx, k, smooth_k, relative_time);
}
autoware_planning_msgs::msg::Trajectory predicted_traj;
predicted_traj.header.stamp = current_trajectory_ptr_->header.stamp;
predicted_traj.header.frame_id = current_trajectory_ptr_->header.frame_id;
MPCUtils::convertToAutowareTrajectory(mpc_predicted_traj, &predicted_traj);
pub_predicted_traj_->publish(predicted_traj);
auto markers = MPCUtils::convertTrajToMarker(
mpc_predicted_traj, "predicted_trajectory", 0.99, 0.99, 0.99, 0.2,
current_trajectory_ptr_->header.frame_id, stamp);
pub_debug_marker_->publish(markers);
}
/* publish debug values */
{
double curr_v = current_velocity_ptr_->twist.linear.x;
double nearest_k = reference_trajectory.k[mpc_data.nearest_idx];
double nearest_smooth_k = reference_trajectory.smooth_k[mpc_data.nearest_idx];
double steer_cmd = ctrl_cmd->steering_angle;
autoware_debug_msgs::msg::Float32MultiArrayStamped d;
d.stamp = stamp;
const auto & ps = mpc_data.predicted_steer;
const auto & W = wheelbase_;
d.data.push_back(steer_cmd); // [0] final steering command (MPC + LPF)
d.data.push_back(Uex(0)); // [1] mpc calculation result
d.data.push_back(mpc_matrix.Uref_ex(0)); // [2] feedforward steering value
d.data.push_back(std::atan(nearest_smooth_k * W)); // [3] feedforward steering value raw
d.data.push_back(mpc_data.steer); // [4] current steering angle
d.data.push_back(mpc_data.lateral_err); // [5] lateral error
d.data.push_back(tf2::getYaw(current_pose_ptr_->pose.orientation)); // [6] current_pose yaw
d.data.push_back(tf2::getYaw(mpc_data.nearest_pose.orientation)); // [7] nearest_pose yaw
d.data.push_back(mpc_data.yaw_err); // [8] yaw error
d.data.push_back(ctrl_cmd->velocity); // [9] command velocities
d.data.push_back(current_velocity_ptr_->twist.linear.x); // [10] measured velocity
d.data.push_back(curr_v * tan(steer_cmd) / W); // [11] angvel from steer command
d.data.push_back(curr_v * tan(mpc_data.steer) / W); // [12] angvel from measured steer
d.data.push_back(curr_v * nearest_smooth_k); // [13] angvel from path curvature
d.data.push_back(nearest_smooth_k); // [14] nearest path curvature (used for feedforward)
d.data.push_back(nearest_k); // [15] nearest path curvature (not smoothed)
d.data.push_back(ps); // [16] predicted steer
d.data.push_back(curr_v * tan(ps) / W); // [17] angvel from predicted steer
pub_debug_values_->publish(d);
}
/* publish computing time */
{
auto end = std::chrono::system_clock::now();
auto t = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() * 1.0e-6;
autoware_debug_msgs::msg::Float32Stamped calc_time;
calc_time.stamp = stamp;
calc_time.data = t; // [ms]
pub_debug_mpc_calc_time_->publish(calc_time);
}
return true;
}
void MPCFollower::resetPrevResult()
{
raw_steer_cmd_prev_ = current_steer_ptr_->data;
raw_steer_cmd_pprev_ = current_steer_ptr_->data;
}
bool MPCFollower::getData(const MPCTrajectory & traj, MPCData * data)
{
static constexpr auto duration = (5000ms).count();
if (!MPCUtils::calcNearestPoseInterp(
traj, current_pose_ptr_->pose, &(data->nearest_pose), &(data->nearest_idx),
&(data->nearest_time), get_logger(), *get_clock())) {
// reset previous MPC result
// Note: When a large deviation from the trajectory occurs, the optimization stops and
// the vehicle will return to the path by re-planning the trajectory or external operation.
// After the recovery, the previous value of the optimization may deviate greatly from
// the actual steer angle, and it may make the optimization result unstable.
resetPrevResult();
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), duration,
"calculateMPC: error in calculating nearest pose. stop mpc.");
return false;
}
/* get data */
data->steer = current_steer_ptr_->data;
data->lateral_err = MPCUtils::calcLateralError(current_pose_ptr_->pose, data->nearest_pose);
data->yaw_err = MPCUtils::normalizeRadian(
tf2::getYaw(current_pose_ptr_->pose.orientation) - tf2::getYaw(data->nearest_pose.orientation));
/* get predicted steer */
if (!steer_prediction_prev_) {
steer_prediction_prev_ = std::make_shared<double>(current_steer_ptr_->data);
}
data->predicted_steer = calcSteerPrediction();
*steer_prediction_prev_ = data->predicted_steer;
/* check error limit */
const double dist_err = MPCUtils::calcDist2d(current_pose_ptr_->pose, data->nearest_pose);
if (dist_err > admissible_position_error_) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), duration, "position error is over limit. error = %fm, limit: %fm",
dist_err, admissible_position_error_);
return false;
}
/* check yaw error limit */
if (std::fabs(data->yaw_err) > admissible_yaw_error_rad_) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), duration, "yaw error is over limit. error = %f deg, limit %f deg",
RAD2DEG * data->yaw_err, RAD2DEG * admissible_yaw_error_rad_);
return false;
}
/* check trajectory time length */
auto end_time = data->nearest_time + mpc_param_.input_delay + getPredictionTime();
if (end_time > traj.relative_time.back()) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (1000ms).count(), "path is too short for prediction.");
return false;
}
return true;
}
double MPCFollower::calcSteerPrediction()
{
auto t_start = time_prev_;
auto t_end = this->now();
time_prev_ = t_end;
const double duration = (t_end - t_start).seconds();
const double time_constant = mpc_param_.steer_tau;
const double initial_response = std::exp(-duration / time_constant) * (*steer_prediction_prev_);
if (ctrl_cmd_vec_.size() <= 2) {
return initial_response;
}
return initial_response + getSteerCmdSum(t_start, t_end, time_constant);
}
double MPCFollower::getSteerCmdSum(
const rclcpp::Time & t_start, const rclcpp::Time & t_end, const double time_constant)
{
if (ctrl_cmd_vec_.size() <= 2) {
return 0.0;
}
// Find first index of control command container
size_t idx = 1;
while (t_start > rclcpp::Time(ctrl_cmd_vec_.at(idx).header.stamp)) {
if ((idx + 1) >= ctrl_cmd_vec_.size()) {
return 0.0;
}
++idx;
}
// Compute steer command input response
double steer_sum = 0.0;
auto t = t_start;
while (t_end > rclcpp::Time(ctrl_cmd_vec_.at(idx).header.stamp)) {
const double duration = (rclcpp::Time(ctrl_cmd_vec_.at(idx).header.stamp) - t).seconds();
t = rclcpp::Time(ctrl_cmd_vec_.at(idx).header.stamp);
steer_sum +=
(1 - std::exp(-duration / time_constant)) * ctrl_cmd_vec_.at(idx - 1).control.steering_angle;
++idx;
if (idx >= ctrl_cmd_vec_.size()) {
break;
}
}
const double duration = (t_end - t).seconds();
steer_sum +=
(1 - std::exp(-duration / time_constant)) * ctrl_cmd_vec_.at(idx - 1).control.steering_angle;
return steer_sum;
}
void MPCFollower::storeSteerCmd(const double steer)
{
const auto time_delayed = this->now() + rclcpp::Duration::from_seconds(mpc_param_.input_delay);
autoware_control_msgs::msg::ControlCommandStamped cmd;
cmd.header.stamp = time_delayed;
cmd.control.steering_angle = steer;
// store published ctrl cmd
ctrl_cmd_vec_.emplace_back(cmd);
if (ctrl_cmd_vec_.size() <= 2) {
return;
}
// remove unused ctrl cmd
constexpr double store_time = 0.3;
if (
(time_delayed - ctrl_cmd_vec_.at(1).header.stamp).seconds() >
mpc_param_.input_delay + store_time) {
ctrl_cmd_vec_.erase(ctrl_cmd_vec_.begin());
}
}
bool MPCFollower::resampleMPCTrajectoryByTime(
double ts, const MPCTrajectory & input, MPCTrajectory * output) const
{
std::vector<double> mpc_time_v;
for (int i = 0; i < mpc_param_.prediction_horizon; ++i) {
mpc_time_v.push_back(ts + i * mpc_param_.prediction_dt);
}
if (!MPCUtils::linearInterpMPCTrajectory(input.relative_time, input, mpc_time_v, output)) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), const_cast<rclcpp::Clock &>(*get_clock()), (1000ms).count(),
"calculateMPC: mpc resample error. stop mpc calculation. check code!");
return false;
}
return true;
}
Eigen::VectorXd MPCFollower::getInitialState(const MPCData & data)
{
const int DIM_X = vehicle_model_ptr_->getDimX();
Eigen::VectorXd x0 = Eigen::VectorXd::Zero(DIM_X);
const auto & lat_err = data.lateral_err;
const auto & steer = use_steer_prediction_ ? data.predicted_steer : data.steer;
const auto & yaw_err = data.yaw_err;
if (vehicle_model_type_ == "kinematics") {
x0 << lat_err, yaw_err, steer;
} else if (vehicle_model_type_ == "kinematics_no_delay") {
x0 << lat_err, yaw_err;
} else if (vehicle_model_type_ == "dynamics") {
double dlat = (lat_err - lateral_error_prev_) / ctrl_period_;
double dyaw = (yaw_err - yaw_error_prev_) / ctrl_period_;
lateral_error_prev_ = lat_err;
yaw_error_prev_ = yaw_err;
dlat = lpf_lateral_error_.filter(dlat);
dyaw = lpf_yaw_error_.filter(dyaw);
x0 << lat_err, dlat, yaw_err, dyaw;
RCLCPP_DEBUG(get_logger(), "(before lpf) dot_lat_err = %f, dot_yaw_err = %f", dlat, dyaw);
RCLCPP_DEBUG(get_logger(), "(after lpf) dot_lat_err = %f, dot_yaw_err = %f", dlat, dyaw);
} else {
RCLCPP_ERROR(get_logger(), "vehicle_model_type is undefined");
}
return x0;
}
bool MPCFollower::updateStateForDelayCompensation(
const MPCTrajectory & traj, const double & start_time, Eigen::VectorXd * x)
{
const int DIM_X = vehicle_model_ptr_->getDimX();
const int DIM_U = vehicle_model_ptr_->getDimU();
const int DIM_Y = vehicle_model_ptr_->getDimY();
Eigen::MatrixXd Ad(DIM_X, DIM_X);
Eigen::MatrixXd Bd(DIM_X, DIM_U);
Eigen::MatrixXd Wd(DIM_X, 1);
Eigen::MatrixXd Cd(DIM_Y, DIM_X);
Eigen::MatrixXd x_curr = *x;
double mpc_curr_time = start_time;
for (unsigned int i = 0; i < input_buffer_.size(); ++i) {
double k = 0.0;
double v = 0.0;
if (
!LinearInterpolate::interpolate(traj.relative_time, traj.k, mpc_curr_time, k) ||
!LinearInterpolate::interpolate(traj.relative_time, traj.vx, mpc_curr_time, v)) {
RCLCPP_ERROR(
get_logger(),
"mpc resample error at delay compensation, stop mpc calculation. check code!");
return false;
}
/* get discrete state matrix A, B, C, W */
vehicle_model_ptr_->setVelocity(v);
vehicle_model_ptr_->setCurvature(k);
vehicle_model_ptr_->calculateDiscreteMatrix(Ad, Bd, Cd, Wd, ctrl_period_);
Eigen::MatrixXd ud = Eigen::MatrixXd::Zero(DIM_U, 1);
ud(0, 0) = input_buffer_.at(i); // for steering input delay
x_curr = Ad * x_curr + Bd * ud + Wd;
mpc_curr_time += ctrl_period_;
}
*x = x_curr;
return true;
}
MPCTrajectory MPCFollower::applyVelocityDynamicsFilter(const MPCTrajectory & input, const double v0)
{
int nearest_idx = MPCUtils::calcNearestIndex(input, current_pose_ptr_->pose);
if (nearest_idx < 0) {
return input;
}
const double acc_lim = mpc_param_.acceleration_limit;
const double tau = mpc_param_.velocity_time_constant;
MPCTrajectory output = input;
MPCUtils::dynamicSmoothingVelocity(nearest_idx, v0, acc_lim, tau, &output);
const double t_ext = 100.0; // extra time to prevent mpc calculation failure due to short time
const double t_end = output.relative_time.back() + getPredictionTime() + t_ext;
const double v_end = 0.0;
output.vx.back() = v_end; // set for end point
output.push_back(
output.x.back(), output.y.back(), output.z.back(), output.yaw.back(), v_end, output.k.back(),
output.smooth_k.back(), t_end);
return output;
}
/*
* predict equation: Xec = Aex * x0 + Bex * Uex + Wex
* cost function: J = Xex' * Qex * Xex + (Uex - Uref)' * R1ex * (Uex - Uref_ex) + Uex' * R2ex * Uex
* Qex = diag([Q,Q,...]), R1ex = diag([R,R,...])
*/
MPCFollower::MPCMatrix MPCFollower::generateMPCMatrix(const MPCTrajectory & reference_trajectory)
{
using Eigen::MatrixXd;
const int N = mpc_param_.prediction_horizon;
const double DT = mpc_param_.prediction_dt;
const int DIM_X = vehicle_model_ptr_->getDimX();
const int DIM_U = vehicle_model_ptr_->getDimU();
const int DIM_Y = vehicle_model_ptr_->getDimY();
MPCMatrix m;
m.Aex = MatrixXd::Zero(DIM_X * N, DIM_X);
m.Bex = MatrixXd::Zero(DIM_X * N, DIM_U * N);
m.Wex = MatrixXd::Zero(DIM_X * N, 1);
m.Cex = MatrixXd::Zero(DIM_Y * N, DIM_X * N);
m.Qex = MatrixXd::Zero(DIM_Y * N, DIM_Y * N);
m.R1ex = MatrixXd::Zero(DIM_U * N, DIM_U * N);
m.R2ex = MatrixXd::Zero(DIM_U * N, DIM_U * N);
m.Uref_ex = MatrixXd::Zero(DIM_U * N, 1);
/* weight matrix depends on the vehicle model */
MatrixXd Q = MatrixXd::Zero(DIM_Y, DIM_Y);
MatrixXd R = MatrixXd::Zero(DIM_U, DIM_U);
MatrixXd Q_adaptive = MatrixXd::Zero(DIM_Y, DIM_Y);
MatrixXd R_adaptive = MatrixXd::Zero(DIM_U, DIM_U);
MatrixXd Ad(DIM_X, DIM_X);
MatrixXd Bd(DIM_X, DIM_U);
MatrixXd Wd(DIM_X, 1);
MatrixXd Cd(DIM_Y, DIM_X);
MatrixXd Uref(DIM_U, 1);
constexpr double ep = 1.0e-3; // large enough to ignore velocity noise
/* predict dynamics for N times */
for (int i = 0; i < N; ++i) {
const double ref_vx = reference_trajectory.vx[i];
const double ref_vx_squared = ref_vx * ref_vx;
// curvature will be 0 when vehicle stops
const double ref_k = reference_trajectory.k[i] * sign_vx_;
const double ref_smooth_k = reference_trajectory.smooth_k[i] * sign_vx_;
/* get discrete state matrix A, B, C, W */
vehicle_model_ptr_->setVelocity(ref_vx);
vehicle_model_ptr_->setCurvature(ref_k);
vehicle_model_ptr_->calculateDiscreteMatrix(Ad, Bd, Cd, Wd, DT);
Q = Eigen::MatrixXd::Zero(DIM_Y, DIM_Y);
R = Eigen::MatrixXd::Zero(DIM_U, DIM_U);
Q(0, 0) = getWeightLatError(ref_k);
Q(1, 1) = getWeightHeadingError(ref_k);
R(0, 0) = getWeightSteerInput(ref_k);
Q_adaptive = Q;
R_adaptive = R;
if (i == N - 1) {
Q_adaptive(0, 0) = mpc_param_.weight_terminal_lat_error;
Q_adaptive(1, 1) = mpc_param_.weight_terminal_heading_error;
}
Q_adaptive(1, 1) += ref_vx_squared * getWeightHeadingErrorSqVel(ref_k);
R_adaptive(0, 0) += ref_vx_squared * getWeightSteerInputSqVel(ref_k);
/* update mpc matrix */
int idx_x_i = i * DIM_X;
int idx_x_i_prev = (i - 1) * DIM_X;
int idx_u_i = i * DIM_U;
int idx_y_i = i * DIM_Y;
if (i == 0) {
m.Aex.block(0, 0, DIM_X, DIM_X) = Ad;
m.Bex.block(0, 0, DIM_X, DIM_U) = Bd;
m.Wex.block(0, 0, DIM_X, 1) = Wd;
} else {
m.Aex.block(idx_x_i, 0, DIM_X, DIM_X) = Ad * m.Aex.block(idx_x_i_prev, 0, DIM_X, DIM_X);
for (int j = 0; j < i; ++j) {
int idx_u_j = j * DIM_U;
m.Bex.block(idx_x_i, idx_u_j, DIM_X, DIM_U) =
Ad * m.Bex.block(idx_x_i_prev, idx_u_j, DIM_X, DIM_U);
}
m.Wex.block(idx_x_i, 0, DIM_X, 1) = Ad * m.Wex.block(idx_x_i_prev, 0, DIM_X, 1) + Wd;
}
m.Bex.block(idx_x_i, idx_u_i, DIM_X, DIM_U) = Bd;
m.Cex.block(idx_y_i, idx_x_i, DIM_Y, DIM_X) = Cd;
m.Qex.block(idx_y_i, idx_y_i, DIM_Y, DIM_Y) = Q_adaptive;
m.R1ex.block(idx_u_i, idx_u_i, DIM_U, DIM_U) = R_adaptive;
/* get reference input (feed-forward) */
vehicle_model_ptr_->setCurvature(ref_smooth_k);
vehicle_model_ptr_->calculateReferenceInput(Uref);
if (std::fabs(Uref(0, 0)) < DEG2RAD * mpc_param_.zero_ff_steer_deg) {
Uref(0, 0) = 0.0; // ignore curvature noise
}
m.Uref_ex.block(i * DIM_U, 0, DIM_U, 1) = Uref;
}
/* add lateral jerk : weight for (v * {u(i) - u(i-1)} )^2 */
for (int i = 0; i < N - 1; ++i) {
const double ref_vx = reference_trajectory.vx[i];
sign_vx_ = ref_vx > ep ? 1 : (ref_vx < -ep ? -1 : sign_vx_);
const double ref_k = reference_trajectory.k[i] * sign_vx_;
const double j = ref_vx * ref_vx * getWeightLatJerk(ref_k) / (DT * DT); // lateral jerk weight
const Eigen::Matrix2d J = (Eigen::Matrix2d() << j, -j, -j, j).finished();
m.R2ex.block(i, i, 2, 2) += J;
}
addSteerWeightR(&m.R1ex);
return m;
}
/*
* solve quadratic optimization.
* cost function: J = Xex' * Qex * Xex + (Uex - Uref)' * R1ex * (Uex - Uref_ex) + Uex' * R2ex * Uex
* , Qex = diag([Q,Q,...]), R1ex = diag([R,R,...])
* constraint matrix : lb < U < ub, lbA < A*U < ubA
* current considered constraint
* - steering limit
* - steering rate limit
*
* (1)lb < u < ub && (2)lbA < Au < ubA --> (3)[lb, lbA] < [I, A]u < [ub, ubA]
* (1)lb < u < ub ...
* [-u_lim] < [ u0 ] < [u_lim]
* [-u_lim] < [ u1 ] < [u_lim]
* ~~~
* [-u_lim] < [ uN ] < [u_lim] (*N... DIM_U)
* (2)lbA < Au < ubA ...
* [prev_u0 - au_lim*ctp] < [ u0 ] < [prev_u0 + au_lim*ctp] (*ctp ... ctrl_period)
* [ -au_lim * dt ] < [u1 - u0] < [ au_lim * dt ]
* [ -au_lim * dt ] < [u2 - u1] < [ au_lim * dt ]
* ~~~
* [ -au_lim * dt ] < [uN-uN-1] < [ au_lim * dt ] (*N... DIM_U)
*/
bool MPCFollower::executeOptimization(
const MPCMatrix & m, const Eigen::VectorXd & x0, Eigen::VectorXd * Uex)
{
using Eigen::MatrixXd;
using Eigen::VectorXd;
if (!isValid(m)) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (1000ms).count(), "model matrix is invalid. stop MPC.");
return false;
}
const int DIM_U_N = mpc_param_.prediction_horizon * vehicle_model_ptr_->getDimU();
// cost function: 1/2 * Uex' * H * Uex + f' * Uex, H = B' * C' * Q * C * B + R
const MatrixXd CB = m.Cex * m.Bex;
const MatrixXd QCB = m.Qex * CB;
// MatrixXd H = CB.transpose() * QCB + m.R1ex + m.R2ex; // This calculation is heavy. looking for
// a good way. //NOLINT
MatrixXd H = MatrixXd::Zero(DIM_U_N, DIM_U_N);
H.triangularView<Eigen::Upper>() = CB.transpose() * QCB;
H.triangularView<Eigen::Upper>() += m.R1ex + m.R2ex;
H.triangularView<Eigen::Lower>() = H.transpose();
MatrixXd f = (m.Cex * (m.Aex * x0 + m.Wex)).transpose() * QCB - m.Uref_ex.transpose() * m.R1ex;
addSteerWeightF(&f);
MatrixXd A = MatrixXd::Identity(DIM_U_N, DIM_U_N);
for (int i = 1; i < DIM_U_N; i++) {
A(i, i - 1) = -1.0;
}
VectorXd lb = VectorXd::Constant(DIM_U_N, -steer_lim_); // min steering angle
VectorXd ub = VectorXd::Constant(DIM_U_N, steer_lim_); // max steering angle
VectorXd lbA = VectorXd::Constant(DIM_U_N, -steer_rate_lim_ * mpc_param_.prediction_dt);
VectorXd ubA = VectorXd::Constant(DIM_U_N, steer_rate_lim_ * mpc_param_.prediction_dt);
lbA(0, 0) = raw_steer_cmd_prev_ - steer_rate_lim_ * ctrl_period_;
ubA(0, 0) = raw_steer_cmd_prev_ + steer_rate_lim_ * ctrl_period_;
auto t_start = std::chrono::system_clock::now();
bool solve_result = qpsolver_ptr_->solve(H, f.transpose(), A, lb, ub, lbA, ubA, *Uex);
auto t_end = std::chrono::system_clock::now();
if (!solve_result) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(get_logger(), *get_clock(), (1000ms).count(), "qp solver error");
return false;
}
{
auto t = std::chrono::duration_cast<std::chrono::nanoseconds>(t_end - t_start).count() * 1.0e-6;
RCLCPP_DEBUG(get_logger(), "qp solver calculation time = %f [ms]", t);
}
if (Uex->array().isNaN().any()) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (1000ms).count(), "model Uex includes NaN, stop MPC.");
return false;
}
return true;
}
void MPCFollower::addSteerWeightR(Eigen::MatrixXd * R_ptr) const
{
const int N = mpc_param_.prediction_horizon;
const double DT = mpc_param_.prediction_dt;
auto & R = *R_ptr;
/* add steering rate : weight for (u(i) - u(i-1) / dt )^2 */
{
const double steer_rate_r = mpc_param_.weight_steer_rate / (DT * DT);
const Eigen::Matrix2d D = steer_rate_r * (Eigen::Matrix2d() << 1.0, -1.0, -1.0, 1.0).finished();
for (int i = 0; i < N - 1; ++i) {
R.block(i, i, 2, 2) += D;
}
if (N > 1) {
// steer rate i = 0
R(0, 0) += mpc_param_.weight_steer_rate / (ctrl_period_ * ctrl_period_);
}
}
/* add steering acceleration : weight for { (u(i+1) - 2*u(i) + u(i-1)) / dt^2 }^2 */
{
const double w = mpc_param_.weight_steer_acc;
const double steer_acc_r = w / std::pow(DT, 4);
const double steer_acc_r_cp1 = w / (std::pow(DT, 3) * ctrl_period_);
const double steer_acc_r_cp2 = w / (std::pow(DT, 2) * std::pow(ctrl_period_, 2));
const double steer_acc_r_cp4 = w / std::pow(ctrl_period_, 4);
const Eigen::Matrix3d D =
steer_acc_r *
(Eigen::Matrix3d() << 1.0, -2.0, 1.0, -2.0, 4.0, -2.0, 1.0, -2.0, 1.0).finished();
for (int i = 1; i < N - 1; ++i) {
R.block(i - 1, i - 1, 3, 3) += D;
}
if (N > 1) {
// steer acc i = 1
R(0, 0) += steer_acc_r * 1.0 + steer_acc_r_cp2 * 1.0 + steer_acc_r_cp1 * 2.0;
R(1, 0) += steer_acc_r * -1.0 + steer_acc_r_cp1 * -1.0;
R(0, 1) += steer_acc_r * -1.0 + steer_acc_r_cp1 * -1.0;
R(1, 1) += steer_acc_r * 1.0;
// steer acc i = 0
R(0, 0) += steer_acc_r_cp4 * 1.0;
}
}
}
void MPCFollower::addSteerWeightF(Eigen::MatrixXd * f_ptr) const
{
if (f_ptr->rows() < 2) {
return;
}
const double DT = mpc_param_.prediction_dt;
auto & f = *f_ptr;
// steer rate for i = 0
f(0, 0) += -2.0 * mpc_param_.weight_steer_rate / (std::pow(DT, 2)) * 0.5;
// const double steer_acc_r = mpc_param_.weight_steer_acc / std::pow(DT, 4);
const double steer_acc_r_cp1 = mpc_param_.weight_steer_acc / (std::pow(DT, 3) * ctrl_period_);
const double steer_acc_r_cp2 =
mpc_param_.weight_steer_acc / (std::pow(DT, 2) * std::pow(ctrl_period_, 2));
const double steer_acc_r_cp4 = mpc_param_.weight_steer_acc / std::pow(ctrl_period_, 4);
// steer acc i = 0
f(0, 0) += ((-2.0 * raw_steer_cmd_prev_ + raw_steer_cmd_pprev_) * steer_acc_r_cp4) * 0.5;
// steer acc for i = 1
f(0, 0) += (-2.0 * raw_steer_cmd_prev_ * (steer_acc_r_cp1 + steer_acc_r_cp2)) * 0.5;
f(0, 1) += (2.0 * raw_steer_cmd_prev_ * steer_acc_r_cp1) * 0.5;
}
double MPCFollower::getPredictionTime() const
{
return (mpc_param_.prediction_horizon - 1) * mpc_param_.prediction_dt + mpc_param_.input_delay +
ctrl_period_;
}
bool MPCFollower::isValid(const MPCMatrix & m) const
{
if (
m.Aex.array().isNaN().any() || m.Bex.array().isNaN().any() || m.Cex.array().isNaN().any() ||
m.Wex.array().isNaN().any() || m.Qex.array().isNaN().any() || m.R1ex.array().isNaN().any() ||
m.R2ex.array().isNaN().any() || m.Uref_ex.array().isNaN().any()) {
return false;
}
if (
m.Aex.array().isInf().any() || m.Bex.array().isInf().any() || m.Cex.array().isInf().any() ||
m.Wex.array().isInf().any() || m.Qex.array().isInf().any() || m.R1ex.array().isInf().any() ||
m.R2ex.array().isInf().any() || m.Uref_ex.array().isInf().any()) {
return false;
}
return true;
}
void MPCFollower::onTrajectory(const autoware_planning_msgs::msg::Trajectory::SharedPtr msg)
{
if (!current_pose_ptr_) {
return;
}
current_trajectory_ptr_ = msg;
if (msg->points.size() < 3) {
RCLCPP_DEBUG(get_logger(), "received path size is < 3, not enough.");
return;
}
if (!isValidTrajectory(*msg)) {
RCLCPP_ERROR(get_logger(), "Trajectory is invalid!! stop computing.");
return;
}
MPCTrajectory mpc_traj_raw; // received raw trajectory
MPCTrajectory mpc_traj_resampled; // resampled trajectory
MPCTrajectory mpc_traj_smoothed; // smooth filtered trajectory
/* resampling */
MPCUtils::convertToMPCTrajectory(*current_trajectory_ptr_, &mpc_traj_raw);
if (!MPCUtils::resampleMPCTrajectoryByDistance(
mpc_traj_raw, traj_resample_dist_, &mpc_traj_resampled)) {
RCLCPP_WARN(get_logger(), "spline error!!!!!!");
return;
}
/* path smoothing */
mpc_traj_smoothed = mpc_traj_resampled;
int mpc_traj_resampled_size = static_cast<int>(mpc_traj_resampled.size());
if (enable_path_smoothing_ && mpc_traj_resampled_size > 2 * path_filter_moving_ave_num_) {
if (
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, mpc_traj_smoothed.x) ||
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, mpc_traj_smoothed.y) ||
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, mpc_traj_smoothed.yaw) ||
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, mpc_traj_smoothed.vx)) {
RCLCPP_DEBUG(get_logger(), "path callback: filtering error. stop filtering.");
mpc_traj_smoothed = mpc_traj_resampled;
}
}
/* calculate yaw angle */
const int nearest_idx = MPCUtils::calcNearestIndex(mpc_traj_smoothed, current_pose_ptr_->pose);
const double ego_yaw = tf2::getYaw(current_pose_ptr_->pose.orientation);
MPCUtils::calcTrajectoryYawFromXY(&mpc_traj_smoothed, nearest_idx, ego_yaw);
MPCUtils::convertEulerAngleToMonotonic(&mpc_traj_smoothed.yaw);
/* calculate curvature */
MPCUtils::calcTrajectoryCurvature(
curvature_smoothing_num_traj_, curvature_smoothing_num_ref_steer_, &mpc_traj_smoothed);
/* add end point with vel=0 on traj for mpc prediction */
{
auto & t = mpc_traj_smoothed;
const double t_ext = 100.0; // extra time to prevent mpc calculation failure due to short time
const double t_end = t.relative_time.back() + getPredictionTime() + t_ext;
const double v_end = 0.0;
t.vx.back() = v_end; // set for end point
t.push_back(
t.x.back(), t.y.back(), t.z.back(), t.yaw.back(), v_end, t.k.back(), t.smooth_k.back(),
t_end);
}
if (!mpc_traj_smoothed.size()) {
RCLCPP_DEBUG(get_logger(), "path callback: trajectory size is undesired.");
return;
}
ref_traj_ = mpc_traj_smoothed;
/* publish debug marker */
{
const auto & stamp = current_trajectory_ptr_->header.stamp;
using MPCUtils::convertTrajToMarker;
visualization_msgs::msg::MarkerArray m;
std::string frame = msg->header.frame_id;
m = convertTrajToMarker(mpc_traj_raw, "trajectory raw", 0.9, 0.5, 0.0, 0.05, frame, stamp);
pub_debug_marker_->publish(m);
m = convertTrajToMarker(
mpc_traj_resampled, "trajectory spline", 0.5, 0.1, 1.0, 0.05, frame, stamp);
pub_debug_marker_->publish(m);
m = convertTrajToMarker(
mpc_traj_smoothed, "trajectory smoothed", 0.0, 1.0, 0.0, 0.05, frame, stamp);
pub_debug_marker_->publish(m);
}
}
void MPCFollower::updateCurrentPose()
{
geometry_msgs::msg::TransformStamped transform;
try {
transform = tf_buffer_.lookupTransform("map", "base_link", tf2::TimePointZero);
} catch (tf2::TransformException & ex) {
RCLCPP_WARN_SKIPFIRST_THROTTLE(
get_logger(), *get_clock(), (5000ms).count(), "cannot get map to base_link transform. %s",
ex.what());
return;
}
geometry_msgs::msg::PoseStamped ps;
ps.header = transform.header;
ps.pose.position.x = transform.transform.translation.x;
ps.pose.position.y = transform.transform.translation.y;
ps.pose.position.z = transform.transform.translation.z;
ps.pose.orientation = transform.transform.rotation;
current_pose_ptr_ = std::make_shared<geometry_msgs::msg::PoseStamped>(ps);
}
void MPCFollower::onSteering(const autoware_vehicle_msgs::msg::Steering::SharedPtr msg)
{
current_steer_ptr_ = msg;
}
void MPCFollower::onVelocity(geometry_msgs::msg::TwistStamped::SharedPtr msg)
{
current_velocity_ptr_ = msg;
}
autoware_control_msgs::msg::ControlCommand MPCFollower::getStopControlCommand() const
{
autoware_control_msgs::msg::ControlCommand cmd;
cmd.steering_angle = steer_cmd_prev_;
cmd.steering_angle_velocity = 0.0;
cmd.velocity = 0.0;
cmd.acceleration = -1.5;
return cmd;
}
autoware_control_msgs::msg::ControlCommand MPCFollower::getInitialControlCommand() const
{
autoware_control_msgs::msg::ControlCommand cmd;
cmd.steering_angle = current_steer_ptr_->data;
cmd.steering_angle_velocity = 0.0;
cmd.velocity = 0.0;
cmd.acceleration = -1.5;
return cmd;
}
bool MPCFollower::isStoppedState() const
{
// Note: This function used to take into account the distance to the stop line
// for the stop state judgement. However, it has been removed since the steering
// control was turned off when approaching/exceeding the stop line on a curve or
// emergency stop situation and it caused large tracking error.
const int nearest = MPCUtils::calcNearestIndex(*current_trajectory_ptr_, current_pose_ptr_->pose);
// If the nearest index is not found, return false
if (nearest < 0) {
return false;
}
const double current_vel = current_velocity_ptr_->twist.linear.x;
const double target_vel = current_trajectory_ptr_->points.at(nearest).twist.linear.x;
if (
std::fabs(current_vel) < stop_state_entry_ego_speed_ &&
std::fabs(target_vel) < stop_state_entry_target_speed_) {
return true;
} else {
return false;
}
}
double MPCFollower::calcStopDistance(const int origin) const
{
constexpr double zero_velocity = std::numeric_limits<double>::epsilon();
const double origin_velocity = current_trajectory_ptr_->points.at(origin).twist.linear.x;
double stop_dist = 0.0;
// search forward
if (std::fabs(origin_velocity) > zero_velocity) {
for (int i = origin + 1; i < static_cast<int>(current_trajectory_ptr_->points.size()) - 1;
++i) {
const auto & p0 = current_trajectory_ptr_->points.at(i);
const auto & p1 = current_trajectory_ptr_->points.at(i - 1);
stop_dist += MPCUtils::calcDist2d(p0.pose, p1.pose);
if (std::fabs(p0.twist.linear.x) < zero_velocity) {
break;
}
}
return stop_dist;
}
// search backward
for (int i = origin - 1; 0 < i; --i) {
const auto & p0 = current_trajectory_ptr_->points.at(i);
const auto & p1 = current_trajectory_ptr_->points.at(i + 1);
if (std::fabs(p0.twist.linear.x) > zero_velocity) {
break;
}
stop_dist -= MPCUtils::calcDist2d(p0.pose, p1.pose);
}
return stop_dist;
}
void MPCFollower::publishCtrlCmd(const autoware_control_msgs::msg::ControlCommand & ctrl_cmd)
{
autoware_control_msgs::msg::ControlCommandStamped cmd;
cmd.header.frame_id = "base_link";
cmd.header.stamp = this->now();
cmd.control = ctrl_cmd;
pub_ctrl_cmd_->publish(cmd);
steer_cmd_prev_ = ctrl_cmd.steering_angle;
autoware_vehicle_msgs::msg::Steering s;
s.data = ctrl_cmd.steering_angle;
s.header = cmd.header;
pub_debug_steer_cmd_->publish(s);
}
void MPCFollower::initTimer(double period_s)
{
auto timer_callback = std::bind(&MPCFollower::onTimer, this);
const auto period_ns =
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::duration<double>(period_s));
timer_ = std::make_shared<rclcpp::GenericTimer<decltype(timer_callback)>>(
this->get_clock(), period_ns, std::move(timer_callback),
this->get_node_base_interface()->get_context());
this->get_node_timers_interface()->add_timer(timer_, nullptr);
}
void MPCFollower::declareMPCparameters()
{
// the type of the ROS parameter is defined by the type of the default value, so 50 is not
// equivalent to 50.0! //NOLINT
mpc_param_.prediction_horizon = declare_parameter("mpc_prediction_horizon", 50);
mpc_param_.prediction_dt = declare_parameter("mpc_prediction_dt", 0.1);
mpc_param_.weight_lat_error = declare_parameter("mpc_weight_lat_error", 0.1);
mpc_param_.weight_heading_error = declare_parameter("mpc_weight_heading_error", 0.0);
mpc_param_.weight_heading_error_squared_vel =
declare_parameter("mpc_weight_heading_error_squared_vel", 0.3);
mpc_param_.weight_steering_input = declare_parameter("mpc_weight_steering_input", 1.0);
mpc_param_.weight_steering_input_squared_vel =
declare_parameter("mpc_weight_steering_input_squared_vel", 0.25);
mpc_param_.weight_lat_jerk = declare_parameter("mpc_weight_lat_jerk", 0.0);
mpc_param_.weight_steer_rate = declare_parameter("mpc_weight_steer_rate", 0.0);
mpc_param_.weight_steer_acc = declare_parameter("mpc_weight_steer_acc", 0.000001);
mpc_param_.low_curvature_weight_lat_error =
declare_parameter("mpc_low_curvature_weight_lat_error", 0.1);
mpc_param_.low_curvature_weight_heading_error =
declare_parameter("mpc_low_curvature_weight_heading_error", 0.0);
mpc_param_.low_curvature_weight_heading_error_squared_vel =
declare_parameter("mpc_low_curvature_weight_heading_error_squared_vel", 0.3);
mpc_param_.low_curvature_weight_steering_input =
declare_parameter("mpc_low_curvature_weight_steering_input", 1.0);
mpc_param_.low_curvature_weight_steering_input_squared_vel =
declare_parameter("mpc_low_curvature_weight_steering_input_squared_vel", 0.25);
mpc_param_.low_curvature_weight_lat_jerk =
declare_parameter("mpc_low_curvature_weight_lat_jerk", 0.0);
mpc_param_.low_curvature_weight_steer_rate =
declare_parameter("mpc_low_curvature_weight_steer_rate", 0.0);
mpc_param_.low_curvature_weight_steer_acc =
declare_parameter("mpc_low_curvature_weight_steer_acc", 0.000001);
mpc_param_.low_curvature_thresh_curvature =
declare_parameter("mpc_low_curvature_thresh_curvature", 0.0);
mpc_param_.weight_terminal_lat_error = declare_parameter("mpc_weight_terminal_lat_error", 1.0);
mpc_param_.weight_terminal_heading_error =
declare_parameter("mpc_weight_terminal_heading_error", 0.1);
mpc_param_.zero_ff_steer_deg = declare_parameter("mpc_zero_ff_steer_deg", 0.5);
mpc_param_.acceleration_limit = declare_parameter("acceleration_limit", 2.0);
mpc_param_.velocity_time_constant = declare_parameter("velocity_time_constant", 0.3);
}
rcl_interfaces::msg::SetParametersResult MPCFollower::paramCallback(
const std::vector<rclcpp::Parameter> & parameters)
{
rcl_interfaces::msg::SetParametersResult result;
result.successful = true;
result.reason = "success";
// strong exception safety wrt MPCParam
MPCParam param = mpc_param_;
try {
update_param(parameters, "mpc_prediction_horizon", param.prediction_horizon);
update_param(parameters, "mpc_prediction_dt", param.prediction_dt);
update_param(parameters, "mpc_weight_lat_error", param.weight_lat_error);
update_param(parameters, "mpc_weight_heading_error", param.weight_heading_error);
update_param(
parameters, "mpc_weight_heading_error_squared_vel", param.weight_heading_error_squared_vel);
update_param(parameters, "mpc_weight_steering_input", param.weight_steering_input);
update_param(
parameters, "mpc_weight_steering_input_squared_vel", param.weight_steering_input_squared_vel);
update_param(parameters, "mpc_weight_lat_jerk", param.weight_lat_jerk);
update_param(parameters, "mpc_weight_steer_rate", param.weight_steer_rate);
update_param(parameters, "mpc_weight_steer_acc", param.weight_steer_acc);
update_param(
parameters, "mpc_low_curvature_weight_lat_error", param.low_curvature_weight_lat_error);
update_param(
parameters, "mpc_low_curvature_weight_heading_error",
param.low_curvature_weight_heading_error);
update_param(
parameters, "mpc_low_curvature_weight_heading_error_squared_vel",
param.low_curvature_weight_heading_error_squared_vel);
update_param(
parameters, "mpc_low_curvature_weight_steering_input",
param.low_curvature_weight_steering_input);
update_param(
parameters, "mpc_low_curvature_weight_steering_input_squared_vel",
param.low_curvature_weight_steering_input_squared_vel);
update_param(
parameters, "mpc_low_curvature_weight_lat_jerk", param.low_curvature_weight_lat_jerk);
update_param(
parameters, "mpc_low_curvature_weight_steer_rate", param.low_curvature_weight_steer_rate);
update_param(
parameters, "mpc_low_curvature_weight_steer_acc", param.low_curvature_weight_steer_acc);
update_param(
parameters, "mpc_low_curvature_thresh_curvature", param.low_curvature_thresh_curvature);
update_param(parameters, "mpc_weight_terminal_lat_error", param.weight_terminal_lat_error);
update_param(
parameters, "mpc_weight_terminal_heading_error", param.weight_terminal_heading_error);
update_param(parameters, "mpc_zero_ff_steer_deg", param.zero_ff_steer_deg);
update_param(parameters, "acceleration_limit", param.acceleration_limit);
update_param(parameters, "velocity_time_constant", param.velocity_time_constant);
// initialize input buffer
update_param(parameters, "input_delay", param.input_delay);
const int delay_step = std::round(param.input_delay / ctrl_period_);
const double delay = delay_step * ctrl_period_;
if (param.input_delay != delay) {
const int delay_step = std::round(param.input_delay / ctrl_period_);
param.input_delay = delay;
input_buffer_ = std::deque<double>(delay_step, 0.0);
}
// transaction succeeds, now assign values
mpc_param_ = param;
} catch (const rclcpp::exceptions::InvalidParameterTypeException & e) {
result.successful = false;
result.reason = e.what();
}
// TODO(Frederik.Beaujean) extend to other params declared in ctor
return result;
}
bool MPCFollower::isValidTrajectory(const autoware_planning_msgs::msg::Trajectory & traj) const
{
for (const auto & points : traj.points) {
const auto & p = points.pose.position;
const auto & o = points.pose.orientation;
const auto & t = points.twist.linear;
const auto & a = points.accel.linear;
if (
!isfinite(p.x) || !isfinite(p.y) || !isfinite(p.z) || !isfinite(o.x) || !isfinite(o.y) ||
!isfinite(o.z) || !isfinite(o.w) || !isfinite(t.x) || !isfinite(t.y) || !isfinite(t.z) ||
!isfinite(a.x) || !isfinite(a.y) || !isfinite(a.z)) {
return false;
}
}
return true;
}
#include <rclcpp_components/register_node_macro.hpp>
RCLCPP_COMPONENTS_REGISTER_NODE(MPCFollower)
| 39.220141
| 100
| 0.699409
|
loop-perception
|
ed4d99bc1997078b804af517225dbf8733350659
| 2,035
|
cpp
|
C++
|
others/DDCC/D_ver2.cpp
|
rajyan/AtCoder
|
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
|
[
"MIT"
] | 1
|
2021-06-01T17:13:44.000Z
|
2021-06-01T17:13:44.000Z
|
others/DDCC/D_ver2.cpp
|
rajyan/AtCoder
|
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
|
[
"MIT"
] | null | null | null |
others/DDCC/D_ver2.cpp
|
rajyan/AtCoder
|
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
|
[
"MIT"
] | null | null | null |
//#include <cassert>
//#include <cstdio>
//#include <cmath>
//#include <iostream>
//#include <iomanip>
//#include <sstream>
//#include <vector>
//#include <set>
//#include <map>
//#include <queue>
//#include <numeric>
//#include <algorithm>
//
//using namespace std;
//using lint = long long;
//constexpr int MOD = 1000000007, INF = 1010101010;
//constexpr lint LINF = 1LL << 60;
//
//template <class T>
//ostream &operator<<(ostream &os, const vector<T> &vec) {
// for (const auto &e : vec) os << e << (&e == &vec.back() ? "\n" : " ");
// return os;
//}
//
//#ifdef _DEBUG
//template <class T>
//void dump(const char* str, T &&h) { cerr << str << " = " << h << "\n"; };
//template <class Head, class... Tail>
//void dump(const char* str, Head &&h, Tail &&... t) {
// while (*str != ',') cerr << *str++; cerr << " = " << h << "\n";
// dump(str + (*(str + 1) == ' ' ? 2 : 1), t...);
//}
//#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)
//#else
//#define DMP(...) ((void)0)
//#endif
//
//void halve(int d, lint c, lint &cnt, vector<int> &rem) {
//
// if (c == 1) {
// rem.emplace_back(d);
// return;
// }
//
// if (c & 1) rem.emplace_back(d);
//
// if (d <= 4) {
// d *= 2;
// cnt += c / 2;
// }
// else {
// d = 1 + 2 * d % 10;
// cnt += c - (c & 1);
// }
//
// halve(d, c / 2, cnt, rem);
//
//};
//
//void simulate(lint &cnt, vector<int> &vec) {
//
// if (vec.size() == 1) return;
//
// assert(vec.size() != 0);
//
// int back1 = vec.back();
// vec.pop_back();
// int back2 = vec.back();
//
// DMP(back1, back2);
//
// int sum = back1 + back2;
// if (sum <= 9) {
// cnt++;
// vec.back() = sum;
// }
// else {
// cnt += 2;
// vec.back() = 1 + sum % 10;
// }
//
// simulate(cnt, vec);
//
//}
//
//int main() {
//
// cin.tie(nullptr);
// ios::sync_with_stdio(false);
//
// int M;
// cin >> M;
// lint ans = 0;
// vector<int> rem;
// for (int i = 0; i < M; i++) {
//
// lint d, c;
// cin >> d >> c;
// halve(d, c, ans, rem);
//
// }
//
// DMP(ans, rem);
// simulate(ans, rem);
//
// cout << ans << "\n";
//
// return 0;
//}
| 18.669725
| 75
| 0.490418
|
rajyan
|
ed567ad96a62ddff18cf733b12d5787962da1e6a
| 804
|
cpp
|
C++
|
290-word-pattern/290-word-pattern.cpp
|
Ananyaas/LeetCodeDaily
|
e134e20ac02f26dc40881c376656d3294be0df2c
|
[
"MIT"
] | 2
|
2022-01-02T19:15:00.000Z
|
2022-01-05T21:12:24.000Z
|
290-word-pattern/290-word-pattern.cpp
|
Ananyaas/LeetCodeDaily
|
e134e20ac02f26dc40881c376656d3294be0df2c
|
[
"MIT"
] | null | null | null |
290-word-pattern/290-word-pattern.cpp
|
Ananyaas/LeetCodeDaily
|
e134e20ac02f26dc40881c376656d3294be0df2c
|
[
"MIT"
] | 1
|
2022-03-11T17:11:07.000Z
|
2022-03-11T17:11:07.000Z
|
class Solution {
public:
bool wordPattern(string pattern, string s) {
vector<string>v(pattern.length()+1);
int j=0;
for(int i=0;i<s.length();i++){
if(s[i]!=' ')
{
v[j]+=s[i];
}
else
j++;
}
map<string,char>ms;
map<char,bool>visited;
for(int i=0;i<v.size();i++){
cout<<v[i]<<endl;
}
for(int i=0;i<v.size();i++){
if(ms.find(v[i])==ms.end() && visited[pattern[i]]==false){
visited[pattern[i]]=true;
ms[v[i]]=pattern[i];
}
else
if(ms[v[i]]!=pattern[i])
return false;
}
return true;
}
};
| 24.363636
| 70
| 0.365672
|
Ananyaas
|
ed5b37cde35b82cfdc3bd8ff014da35df126ed5d
| 2,418
|
cpp
|
C++
|
UVA/NetworkConnections.cpp
|
MartinAparicioPons/Competitive-Programming
|
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
|
[
"Apache-2.0"
] | 1
|
2019-09-29T03:58:35.000Z
|
2019-09-29T03:58:35.000Z
|
UVA/NetworkConnections.cpp
|
MartinAparicioPons/Competitive-Programming
|
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
|
[
"Apache-2.0"
] | null | null | null |
UVA/NetworkConnections.cpp
|
MartinAparicioPons/Competitive-Programming
|
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
|
[
"Apache-2.0"
] | null | null | null |
#include <cctype>
#include <set>
#include <queue>
#include <map>
#include <stack>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <sstream>
#include <cstdlib>
#include <locale>
#include <cmath>
#include <vector>
#include <cstdio>
#include <cstring>
#define scd(x) scanf("%d", &x)
#define scc(x) scanf("%c", &x)
#define scd2(x,y) scanf("%d %d", &x, &y)
#define prd(x) printf("%d\n", x)
#define dprd(x) printf("|| %d\n", x)
#define dprd2(x, y) printf("|| %d | %d\n", x, y)
#define prd2(x,y) printf("%d %d\n", x,y)
#define prnl() printf("\n")
#define prc(c) printf("%c\n", c)
#define fora(i,a,n) for(i = a; i < n; i++)
#define for0(i,n) fora(i, 0, n)
#define _F first
#define _S second
#define _MP make_pair
#define _MT(x, y, z) _MP(x, _MP(y, z))
#define _TL(s) transform(s.begin(), s.end(), s.begin(), ::tolower)
#define _TU(s) transform(s.begin(), s.end(), s.begin(), ::toupper)
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef long long ll;
typedef pair<int, ii> iii;
typedef pair<string, int> si;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<string> vs;
typedef vector< vector<int> > vvi;
class UnionFind {
private:
vi p, rank, setSize;
int numSets;
public:
UnionFind(int N) {
setSize.assign(N, 1); numSets = N; rank.assign(N, 0);
p.assign(N, 0); for (int i = 0; i < N; i++) p[i] = i; }
int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); }
bool isSameSet(int i, int j) { return findSet(i) == findSet(j); }
void unionSet(int i, int j) {
if (!isSameSet(i, j)) { numSets--;
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; }
else { p[x] = y; setSize[y] += setSize[x];
if (rank[x] == rank[y]) rank[y]++; } } }
int numDisjointSets() { return numSets; }
int sizeOfSet(int i) { return setSize[findSet(i)]; }
};
int main(){
int t, n, i, a, b, s, u;
char c, line[1000];
scanf("%d\n", &t);
while(t--){
scanf("%d\n\n", &n);
s = 0; u = 0;
UnionFind UF(n);
while(true){
gets(line);
if((strcmp(line, "") == 0) || feof(stdin)) break;
sscanf(line, "%c %d %d", &c, &a, &b);
a--; b--;
if(c == 'c'){
UF.unionSet(a, b);
} else {
if(UF.isSameSet(a, b))
s++;
else
u++;
}
}
printf("%d,%d\n", s, u);
if(t != 0) prnl();
}
}
| 24.673469
| 73
| 0.563689
|
MartinAparicioPons
|
ed5fa1a09871813ca7bb89af7f31028f0c040d6e
| 3,449
|
cpp
|
C++
|
lab4/150101033_3.cpp
|
mayank-myk/Basic-Datastructure-implementations
|
4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356
|
[
"MIT"
] | null | null | null |
lab4/150101033_3.cpp
|
mayank-myk/Basic-Datastructure-implementations
|
4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356
|
[
"MIT"
] | null | null | null |
lab4/150101033_3.cpp
|
mayank-myk/Basic-Datastructure-implementations
|
4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356
|
[
"MIT"
] | null | null | null |
// mayank agrawal
// 150101033
// To complie type: g++ 150101033_3.cpp -std=c++11 in linux
#include <bits/stdc++.h>
#include <cstdlib>
#include <cstdio>
#include <iostream>
using namespace std;
struct node{
int row;
int col;
int value;
struct node * right;
struct node * down;
};
struct node *createnode(int row,int col,int value){
struct node *temp = new struct node;
temp->row = row;
temp->col = col;
temp->value = value;
return temp;
}
class sparse_matrix{
struct node *right;
struct node *down;
int row,col;
public:
sparse_matrix(int r,int c){ //row or col value of 0 indicates the node is a pointer to a row or column.
row = r;
col = c;
right = new struct node[c];
down = new struct node[r];
for(int i=0;i<r;i++){
down[i].down = &down[(i+1)%r];
down[i].right = &down[i];
down[i].row = i;
down[i].col = 0;
down[i].value = -1;
}
for(int i=0;i<c;i++){
right[i].right = &right[(i+1)%c];
right[i].down = &right[i];
right[i].row = 0;
right[i].col = i;
right[i].value = -1;
}
//pointer right[0] and down[0] are same struct node
right[0].right = &right[1];
right[0].down = &down[1];
down[0] = right[0];
}
void insert(struct node *temp){
int R = temp->row;
int C = temp->col;
struct node *tempC = &right[C];
struct node *tempR = &down[R];
while( (tempC->row)<R || (tempC->down)->row==0 ){
if((tempC->down)->row==0){
temp->down = tempC->down;
tempC->down = temp;
break;
}else if((tempC->down)->row > R){
temp->down = (tempC->down);
tempC->down = temp;
break;
}else{
tempC = tempC->down;
}
}
while( (tempR->col)<C || (tempR->right)->col==0 ){
if((tempR->right)->col==0){
temp->right = tempR->right;
tempR->right = temp;
break;
}else if((tempR->right)->col > C){
temp->right = (tempR->right);
tempR->right = temp;
break;
}else{
tempR= tempR->right;
}
}
}
void largest(){
int maximum=0;
for(int i=1;i<row;i++){
if(down[i].right->col==0) //if that row has no elements
continue;
struct node * temp = (&down[i])->right;
while (temp->col!=0){
if(temp->value > maximum)
maximum = temp->value;
temp = temp->right;
}
}
printf("Maximum element in the matrix is : %d\n",maximum);
}
//The function to display the value of the matrix row-wise .
void row_print(){
cout<<"\nDisplaying value row-wise : \n";
for(int i=1;i<row;i++){
printf("value in row =>%d\n",i);
struct node * temp = (&down[i])->right;
while (temp->col!=0){
printf("row: %d,Col: %d,value: %d\n",temp->row,temp->col,temp->value);
temp = temp->right;
}
}
}
};
int main(){
int r,c,k;
printf("enter the no. of row, column:\n ");
scanf("%d %d",&r,&c);
printf("Enter the number of non -zero elments : ");
scanf("%d",&k);
int a[k][3],t,x,y,flag;
srand(time(NULL));
for(int i=0;i<k;i++){
x = rand()%r + 1;
y = rand()%c + 1;
a[i][1]=x;
a[i][2]=y;
a[i][0]=rand()%1000;
for(int j=0;j<i;j++){
if( x==a[j][1] && y==a[j][2] ){
j--; // to remove those value of <i,j> which are already been used.
break;
}
}
}
sparse_matrix m(r+1,c+1); //m is the class object
for(int i=0;i<k;i++){
m.insert( createnode (a[i][1],a[i][2],a[i][0]) );
}
// function to print the elements row wise
m.row_print();
m.largest();
return 0;
}
| 21.030488
| 108
| 0.551464
|
mayank-myk
|
ed60a20123146118a0edd7b0e761349a80d128ab
| 312
|
hpp
|
C++
|
compendium/test_bundles/TestBundleDSTOI12/src/ServiceImpl.hpp
|
fmilano/CppMicroServices
|
b7e79edb558a63e45f6788e4a8b4e787cf956689
|
[
"Apache-2.0"
] | 588
|
2015-10-07T15:55:08.000Z
|
2022-03-29T00:35:44.000Z
|
compendium/test_bundles/TestBundleDSTOI12/src/ServiceImpl.hpp
|
fmilano/CppMicroServices
|
b7e79edb558a63e45f6788e4a8b4e787cf956689
|
[
"Apache-2.0"
] | 459
|
2015-10-05T23:29:59.000Z
|
2022-03-29T14:13:37.000Z
|
compendium/test_bundles/TestBundleDSTOI12/src/ServiceImpl.hpp
|
fmilano/CppMicroServices
|
b7e79edb558a63e45f6788e4a8b4e787cf956689
|
[
"Apache-2.0"
] | 218
|
2015-11-04T08:19:48.000Z
|
2022-03-24T02:17:08.000Z
|
#ifndef SERVICEIMPL_HPP
#define SERVICEIMPL_HPP
#include "TestInterfaces/Interfaces.hpp"
namespace sample {
class ServiceComponent12 : public test::Interface1
{
public:
ServiceComponent12() = default;
~ServiceComponent12() override;
std::string Description() override;
};
}
#endif // _SERVICE_IMPL_HPP_
| 18.352941
| 50
| 0.775641
|
fmilano
|
ed673c2776dc5598cc3d749d7bc6a8fd1db9a70d
| 2,471
|
cpp
|
C++
|
src/robot/Constants.cpp
|
roboFiddle/7405M_TowerTakeover_Code
|
e16ffab17964ff61a25eac2074da78d0d7577caa
|
[
"MIT"
] | null | null | null |
src/robot/Constants.cpp
|
roboFiddle/7405M_TowerTakeover_Code
|
e16ffab17964ff61a25eac2074da78d0d7577caa
|
[
"MIT"
] | null | null | null |
src/robot/Constants.cpp
|
roboFiddle/7405M_TowerTakeover_Code
|
e16ffab17964ff61a25eac2074da78d0d7577caa
|
[
"MIT"
] | null | null | null |
#include "Constants.hpp"
namespace constants {
units::QLength RobotConstants::kDriveWheelRadius = 2*units::inch;
units::QMass RobotConstants::kRobotMass = 4*units::kg;
units::QMoment RobotConstants::kRobotMoment = 4*units::kgm2;
units::QAngularDrag RobotConstants::kRobotAngularDrag = 0.0;
units::QLength RobotConstants::kDriveWheelTrackWidth = 10 * units::inch;
units::Number RobotConstants::kTrackScrubFactor = 1.0;
units::QLength RobotConstants::kDeadwheelRadius = 1.375*units::inch;
units::QLength RobotConstants::kDeadwheelBaseWidth = 4.1*units::inch;
units::QLength RobotConstants::kDeadwheelBackTurningRadius = 9.45 * units::inch;
units::QAngularSpeed RobotConstants::kDriveSpeedPerVolt = 1.09; // RADIANS / SECOND / VOTL
units::QTorque RobotConstants::kDriveTorquePerVolt = 0.56; // Nm / VOLT
units::Number RobotConstants::kDriveFrictionVoltage = 1.0; // voltage to overcome friction (V)
double RobotConstants::turnKP = 28;
double RobotConstants::turnKI = 0;
double RobotConstants::turnKD = 0;
int RobotConstants::motor_drive_frontleft = 9;
int RobotConstants::motor_drive_backleft = 10;
int RobotConstants::motor_drive_frontright = 2;
int RobotConstants::motor_drive_backright = 5;
int RobotConstants::motor_intake_left = 12; //bricked 11 on 2/21/2020 changed to 12
int RobotConstants::motor_intake_right = 16; //bricked 17 on 2/22/2020 changed to 16
int RobotConstants::motor_tray = 3;
int RobotConstants::motor_lift = 18;
double RobotConstants::MAX_TRAY_RPM = 100;
double RobotConstants::MAX_LIFT_RPM = 200;
double RobotConstants::LIFT_STAGE[1] = {500};
double RobotConstants::TRAY_LIFT[2] = {75, 1800};
double RobotConstants::LIFT_PRESETS[3] = {340, 2200, 3250};
double RobotConstants::trayErrorBeforeLiftStart = 1000;
double RobotConstants::liftErrorBeforeTrayStart = 100;
double RobotConstants::TRAY_SCORE = 3300;
double RobotConstants::SCORE_START_INTAKE = 1000;
double RobotConstants::SCORE_END_INTAKE = 1400;
double RobotConstants::BACK_WHEELBASE_RADIUS = 20;
int RobotConstants::SIDE_VISION_PORT = 0;
int RobotConstants::FORWARD_VISION_PORT = 0;
int RobotConstants::GREEN_SIG = 0;
int RobotConstants::ORANGE_SIG = 0;
int RobotConstants::PURPLE_SIG = 0;
int RobotConstants::IMU_PORT = 1;
double RobotConstants::IMU_TURN_KP = 30;
double RobotConstants::IMU_TURN_KD = 5;
}
| 43.350877
| 98
| 0.734925
|
roboFiddle
|
ed6c965bce32a1aed0d2b1aa897fc1e392e61e3e
| 2,834
|
hpp
|
C++
|
include/codegen/include/System/Text/EncoderFallback.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/System/Text/EncoderFallback.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/System/Text/EncoderFallback.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:42 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Text
namespace System::Text {
// Forward declaring type: EncoderFallbackBuffer
class EncoderFallbackBuffer;
}
// Completed forward declares
// Type namespace: System.Text
namespace System::Text {
// Autogenerated type: System.Text.EncoderFallback
class EncoderFallback : public ::Il2CppObject {
public:
// System.Boolean bIsMicrosoftBestFitFallback
// Offset: 0x10
bool bIsMicrosoftBestFitFallback;
// Get static field: static private System.Text.EncoderFallback replacementFallback
static System::Text::EncoderFallback* _get_replacementFallback();
// Set static field: static private System.Text.EncoderFallback replacementFallback
static void _set_replacementFallback(System::Text::EncoderFallback* value);
// Get static field: static private System.Text.EncoderFallback exceptionFallback
static System::Text::EncoderFallback* _get_exceptionFallback();
// Set static field: static private System.Text.EncoderFallback exceptionFallback
static void _set_exceptionFallback(System::Text::EncoderFallback* value);
// Get static field: static private System.Object s_InternalSyncObject
static ::Il2CppObject* _get_s_InternalSyncObject();
// Set static field: static private System.Object s_InternalSyncObject
static void _set_s_InternalSyncObject(::Il2CppObject* value);
// static private System.Object get_InternalSyncObject()
// Offset: 0x12D8814
static ::Il2CppObject* get_InternalSyncObject();
// static public System.Text.EncoderFallback get_ReplacementFallback()
// Offset: 0x12D2D70
static System::Text::EncoderFallback* get_ReplacementFallback();
// static public System.Text.EncoderFallback get_ExceptionFallback()
// Offset: 0x12D88F8
static System::Text::EncoderFallback* get_ExceptionFallback();
// public System.Text.EncoderFallbackBuffer CreateFallbackBuffer()
// Offset: 0xFFFFFFFF
System::Text::EncoderFallbackBuffer* CreateFallbackBuffer();
// public System.Int32 get_MaxCharCount()
// Offset: 0xFFFFFFFF
int get_MaxCharCount();
// protected System.Void .ctor()
// Offset: 0x12D7F7C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static EncoderFallback* New_ctor();
}; // System.Text.EncoderFallback
}
DEFINE_IL2CPP_ARG_TYPE(System::Text::EncoderFallback*, "System.Text", "EncoderFallback");
#pragma pack(pop)
| 44.984127
| 89
| 0.739238
|
Futuremappermydud
|
ed70bd97497d987130f6f2f8e57ad2d83f38bd35
| 438
|
cpp
|
C++
|
src/boards/mcu/espressif/spi_board.cpp
|
luisgcu/SX126x-Arduino
|
072acaa9f5cdcc8cdf582bd4d2248c232b1c2b08
|
[
"MIT"
] | 118
|
2019-10-02T14:30:43.000Z
|
2022-03-25T10:31:04.000Z
|
src/boards/mcu/espressif/spi_board.cpp
|
luisgcu/SX126x-Arduino
|
072acaa9f5cdcc8cdf582bd4d2248c232b1c2b08
|
[
"MIT"
] | 58
|
2019-08-21T15:30:41.000Z
|
2022-03-04T02:42:14.000Z
|
src/boards/mcu/espressif/spi_board.cpp
|
luisgcu/SX126x-Arduino
|
072acaa9f5cdcc8cdf582bd4d2248c232b1c2b08
|
[
"MIT"
] | 49
|
2019-09-08T15:44:00.000Z
|
2022-03-20T22:42:41.000Z
|
#if defined ESP8266 || defined ESP32
#include <SPI.h>
#include "boards/mcu/board.h"
SPIClass SPI_LORA;
void initSPI(void)
{
#ifdef ESP8266
SPI_LORA.pins(_hwConfig.PIN_LORA_SCLK, _hwConfig.PIN_LORA_MISO, _hwConfig.PIN_LORA_MOSI, _hwConfig.PIN_LORA_NSS);
SPI_LORA.begin();
SPI_LORA.setHwCs(false);
#else
SPI_LORA.begin(_hwConfig.PIN_LORA_SCLK, _hwConfig.PIN_LORA_MISO, _hwConfig.PIN_LORA_MOSI, _hwConfig.PIN_LORA_NSS);
#endif
}
#endif
| 25.764706
| 115
| 0.799087
|
luisgcu
|
ed76770cf59f0fe9c209d72428c36fbf12d46704
| 7,904
|
cc
|
C++
|
cpp/core/libcore/net/tcp_conn.cc
|
cheukw/sample
|
602d5d055c3e11e1e0ba385128e64b9c0aa81305
|
[
"MIT"
] | null | null | null |
cpp/core/libcore/net/tcp_conn.cc
|
cheukw/sample
|
602d5d055c3e11e1e0ba385128e64b9c0aa81305
|
[
"MIT"
] | null | null | null |
cpp/core/libcore/net/tcp_conn.cc
|
cheukw/sample
|
602d5d055c3e11e1e0ba385128e64b9c0aa81305
|
[
"MIT"
] | null | null | null |
#include "net/libevent_headers.h"
#include "net/tcp_conn.h"
#include "net/fd_channel.h"
#include "net/event_loop.h"
#include "net/sockets.h"
#include "net/invoke_timer.h"
TCPConn::TCPConn(EventLoop* l, const std::string& n, net_socket_t sockfd, const std::string& laddr, const std::string& raddr)
: loop_(l)
, fd_(sockfd)
, name_(n)
, local_addr_(laddr)
, remote_addr_(raddr)
, type_(kIncoming)
, status_(kDisconnected)
, high_water_mark_(128 * 1024 * 1024)
, close_delay_(3.000001)
{
if (sockfd >= 0) {
chan_.reset(new FdChannel(l, sockfd, false, false));
chan_->SetReadCallback(std::bind(&TCPConn::HandleRead, this));
chan_->SetWriteCallback(std::bind(&TCPConn::HandleWrite, this));
}
}
TCPConn::~TCPConn() {
assert(status_ == kDisconnected);
if (fd_ >= 0) {
assert(chan_);
assert(fd_ == chan_->fd());
assert(chan_->IsNoneEvent());
EVUTIL_CLOSESOCKET(fd_);
fd_ = INVALID_SOCKET;
}
assert(!delay_close_timer_.get());
}
void TCPConn::Close() {
status_ = kDisconnecting;
auto c = shared_from_this();
auto f = [c]() {
assert(c->loop_->IsInLoopThread());
c->HandleClose();
};
// Use QueueInLoop to fix TCPClient::Close bug when the application delete TCPClient in callback
loop_->QueueInLoop(f);
}
void TCPConn::Send(const std::string& d) {
if (status_ != kConnected) {
return;
}
if (loop_->IsInLoopThread()) {
SendInLoop(d);
} else {
loop_->RunInLoop(std::bind(&TCPConn::SendStringInLoop, shared_from_this(), d));
}
}
void TCPConn::Send(const Slice& message) {
if (status_ != kConnected) {
return;
}
if (loop_->IsInLoopThread()) {
SendInLoop(message);
} else {
loop_->RunInLoop(std::bind(&TCPConn::SendStringInLoop, shared_from_this(), message.ToString()));
}
}
void TCPConn::Send(const void* data, size_t len) {
if (loop_->IsInLoopThread()) {
SendInLoop(data, len);
return;
}
Send(Slice(static_cast<const char*>(data), len));
}
void TCPConn::Send(Buffer* buf) {
if (status_ != kConnected) {
return;
}
if (loop_->IsInLoopThread()) {
SendInLoop(buf->Data(), buf->Length());
buf->Reset();
} else {
loop_->RunInLoop(std::bind(&TCPConn::SendStringInLoop, shared_from_this(), buf->NextAllString()));
}
}
void TCPConn::SendInLoop(const Slice& message) {
SendInLoop(message.data(), message.size());
}
void TCPConn::SendStringInLoop(const std::string& message) {
SendInLoop(message.data(), message.size());
}
void TCPConn::SendInLoop(const void* data, size_t len) {
assert(loop_->IsInLoopThread());
if (status_ == kDisconnected) {
return;
}
ssize_t nwritten = 0;
size_t remaining = len;
bool write_error = false;
// if no data in output queue, writing directly
if (!chan_->IsWritable() && output_buffer_.Length() == 0) {
nwritten = ::send(chan_->fd(), static_cast<const char*>(data), static_cast<int>(len), MSG_NOSIGNAL);
if (nwritten >= 0) {
remaining = len - nwritten;
if (remaining == 0 && write_complete_fn_) {
loop_->QueueInLoop(std::bind(write_complete_fn_, shared_from_this()));
}
} else {
int serrno = errno;
nwritten = 0;
if(!EVUTIL_ERR_RW_RETRIABLE(serrno)) {
if (serrno == EPIPE || serrno == ECONNRESET) {
write_error = true;
}
}
}
}
if (write_error) {
HandleError();
return;
}
assert(!write_error);
assert(remaining <= len);
if(remaining > 0) {
size_t old_len = output_buffer_.Length();
if (old_len + remaining >= high_water_mark_ && old_len < high_water_mark_ && high_water_mark_fn_) {
loop_->QueueInLoop(std::bind(high_water_mark_fn_, shared_from_this(), old_len + remaining));
}
output_buffer_.Append(static_cast<const char*>(data) + nwritten, remaining);
if (!chan_->IsWritable()) {
chan_->EnableWriteEvent();
}
}
}
void TCPConn::HandleRead()
{
assert(loop_->IsInLoopThread());
int serrno = 0;
ssize_t n = input_buffer_.ReadFromFD(chan_->fd(), &serrno);
if (n > 0) {
msg_fn_(shared_from_this(), &input_buffer_);
} else if (n == 0) {
if (type() == kOutgoing) {
// This is an outgoing connection, we own it and it's done. so close it
status_ = kDisconnecting;
HandleClose();
} else {
// Fix the half-closing problem : https://github.com/chenshuo/muduo/pull/117
// This is an incoming connection, we need to preserve the connection for a while so that we can reply to it.
// And we set a timer to close the connection eventually.
chan_->DisableReadEvent();
delay_close_timer_ = loop_->RunAfter(close_delay_, std::bind(&TCPConn::DelayClose, shared_from_this())); // TODO leave it to user layer close.
}
} else {
if (EVUTIL_ERR_RW_RETRIABLE(serrno)) {
} else {
HandleError();
}
}
}
void TCPConn::HandleWrite()
{
assert(loop_->IsInLoopThread());
assert(!chan_->attached() || chan_->IsWritable());
ssize_t n = ::send(fd_, output_buffer_.Data(), static_cast<int>(output_buffer_.Length()), MSG_NOSIGNAL);
if (n > 0) {
output_buffer_.Next(n);
if (output_buffer_.Length() == 0) {
chan_->DisableWriteEvent();
if (write_complete_fn_) {
loop_->QueueInLoop(std::bind(write_complete_fn_, shared_from_this()));
}
}
} else {
int serrno = errno;
if (EVUTIL_ERR_RW_RETRIABLE(serrno)) {
} else {
HandleError();
}
}
}
void TCPConn::DelayClose()
{
assert(loop_->IsInLoopThread());
status_ = kDisconnecting;
assert(delay_close_timer_.get());
delay_close_timer_.reset();
HandleClose();
}
void TCPConn::HandleClose()
{
// Avoid multi calling
if (status_ == kDisconnected) {
return;
}
// We call HandleClose() from TCPConn's method, the status_ is kConnected
// But we call HandleClose() from out of TCPConn's method, the status_ is kDisconnecting
assert(status_ == kDisconnecting);
status_ = kDisconnecting;
assert(loop_->IsInLoopThread());
chan_->DisableAllEvent();
chan_->Close();
TCPConnPtr conn(shared_from_this());
if (delay_close_timer_) {
delay_close_timer_->Cancel();
delay_close_timer_.reset();
}
if (conn_fn_) {
// This callback must be invoked at status kDisconnecting
// e.g. when the TCPClient disconnects with remote server,
// the user layer can decide whether to do the reconnection.
assert(status_ == kDisconnecting);
conn_fn_(conn);
}
if (close_fn_) {
close_fn_(conn);
}
status_ = kDisconnected;
}
void TCPConn::HandleError() {
status_ = kDisconnecting;
HandleClose();
}
void TCPConn::OnAttachedToLoop() {
assert(loop_->IsInLoopThread());
status_ = kConnected;
chan_->EnableReadEvent();
if (conn_fn_) {
conn_fn_(shared_from_this());
}
}
void TCPConn::SetHighWaterMarkCallback(const HighWaterMarkCallback& cb, size_t mark) {
high_water_mark_fn_ = cb;
high_water_mark_ = mark;
}
void TCPConn::SetTCPNoDelay(bool on) {
sockets::SetTCPNoDelay(fd_, on);
}
std::string TCPConn::StatusToString() const {
H_CASE_STRING_BIGIN(status_);
H_CASE_STRING(kDisconnected);
H_CASE_STRING(kConnecting);
H_CASE_STRING(kConnected);
H_CASE_STRING(kDisconnecting);
H_CASE_STRING_END();
}
| 26.702703
| 154
| 0.604504
|
cheukw
|
ed7a09e14953f33b3b15f828b3df4233ae1bef45
| 7,296
|
cpp
|
C++
|
scopehal/VICPSocketTransport.cpp
|
x44203/scopehal
|
984b38431cdf46c3e9c6055b164e03b4f7336a49
|
[
"BSD-3-Clause"
] | null | null | null |
scopehal/VICPSocketTransport.cpp
|
x44203/scopehal
|
984b38431cdf46c3e9c6055b164e03b4f7336a49
|
[
"BSD-3-Clause"
] | null | null | null |
scopehal/VICPSocketTransport.cpp
|
x44203/scopehal
|
984b38431cdf46c3e9c6055b164e03b4f7336a49
|
[
"BSD-3-Clause"
] | 1
|
2020-08-02T14:20:52.000Z
|
2020-08-02T14:20:52.000Z
|
/***********************************************************************************************************************
* *
* ANTIKERNEL v0.1 *
* *
* Copyright (c) 2012-2020 Andrew D. Zonenberg *
* 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 author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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. *
* *
***********************************************************************************************************************/
/**
@file
@author Andrew D. Zonenberg
@brief Implementation of VICPSocketTransport
*/
#include "scopehal.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
VICPSocketTransport::VICPSocketTransport(string args)
: m_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
{
char hostname[128];
unsigned int port = 0;
if(2 != sscanf(args.c_str(), "%127[^:]:%u", hostname, &port))
{
//default if port not specified
m_hostname = args;
m_port = 1861;
}
else
{
m_hostname = hostname;
m_port = port;
}
LogDebug("Connecting to VICP oscilloscope at %s:%d\n", m_hostname.c_str(), m_port);
if(!m_socket.Connect(m_hostname, m_port))
{
m_socket.Close();
LogError("Couldn't connect to socket\n");
return;
}
if(!m_socket.DisableNagle())
{
m_socket.Close();
LogError("Couldn't disable Nagle\n");
return;
}
}
VICPSocketTransport::~VICPSocketTransport()
{
}
bool VICPSocketTransport::IsConnected()
{
return m_socket.IsValid();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Actual transport code
string VICPSocketTransport::GetTransportName()
{
return "vicp";
}
string VICPSocketTransport::GetConnectionString()
{
char tmp[256];
snprintf(tmp, sizeof(tmp), "%s:%u", m_hostname.c_str(), m_port);
return string(tmp);
}
uint8_t VICPSocketTransport::GetNextSequenceNumber()
{
m_lastSequence = m_nextSequence;
//EOI increments the sequence number.
//Wrap mod 256, but skip zero!
m_nextSequence ++;
if(m_nextSequence == 0)
m_nextSequence = 1;
return m_lastSequence;
}
bool VICPSocketTransport::SendCommand(string cmd)
{
//Operation and flags header
string payload;
uint8_t op = OP_DATA | OP_EOI;
//TODO: remote, clear, poll flags
payload += op;
payload += 0x01; //protocol version number
payload += GetNextSequenceNumber();
payload += '\0'; //reserved
//Next 4 header bytes are the message length (network byte order)
uint32_t len = cmd.length();
payload += (len >> 24) & 0xff;
payload += (len >> 16) & 0xff;
payload += (len >> 8) & 0xff;
payload += (len >> 0) & 0xff;
//Add message data
payload += cmd;
//Actually send it
SendRawData(payload.size(), (const unsigned char*)payload.c_str());
return true;
}
string VICPSocketTransport::ReadReply()
{
string payload;
while(true)
{
//Read the header
unsigned char header[8];
ReadRawData(8, header);
//Sanity check
if(header[1] != 1)
{
LogError("Bad VICP protocol version\n");
return "";
}
if(header[2] != m_lastSequence)
{
//LogError("Bad VICP sequence number %d (expected %d)\n", header[2], m_lastSequence);
//return "";
}
if(header[3] != 0)
{
LogError("Bad VICP reserved field\n");
return "";
}
//Read the message data
uint32_t len = (header[4] << 24) | (header[5] << 16) | (header[6] << 8) | header[7];
string rxbuf;
rxbuf.resize(len);
ReadRawData(len, (unsigned char*)&rxbuf[0]);
//Skip empty blocks, or just newlines
if( (len == 0) || (rxbuf == "\n"))
{
//Special handling needed for EOI.
if(header[0] & OP_EOI)
{
//EOI on an empty block is a stop if we have data from previous blocks.
if(!payload.empty())
break;
//But if we have no data, hold off and wait for the next frame
else
continue;
}
}
//Actual frame data
else
payload += rxbuf;
//Check EOI flag
if(header[0] & OP_EOI)
break;
}
//make sure there's a null terminator
payload += "\0";
return payload;
}
void VICPSocketTransport::SendRawData(size_t len, const unsigned char* buf)
{
m_socket.SendLooped(buf, len);
}
void VICPSocketTransport::ReadRawData(size_t len, unsigned char* buf)
{
m_socket.RecvLooped(buf, len);
}
bool VICPSocketTransport::IsCommandBatchingSupported()
{
return true;
}
| 33.62212
| 120
| 0.497396
|
x44203
|
ed7c7062c6784c8205b51a5beed3e2bf783f8d3d
| 1,865
|
cpp
|
C++
|
CK2ToEU4/Source/Mappers/RulerPersonalitiesMapper/RulerPersonalitiesMapper.cpp
|
bavbeerhall/CK2ToEU4
|
a65edfb895b30e80af5bd7045dbfac7e2c5069e9
|
[
"MIT"
] | 2
|
2020-04-25T15:14:10.000Z
|
2020-04-25T18:47:00.000Z
|
CK2ToEU4/Source/Mappers/RulerPersonalitiesMapper/RulerPersonalitiesMapper.cpp
|
dlbuunk/CK2ToEU4
|
5c1755d17a36950d29a6c0ca13e454cb27b767bf
|
[
"MIT"
] | null | null | null |
CK2ToEU4/Source/Mappers/RulerPersonalitiesMapper/RulerPersonalitiesMapper.cpp
|
dlbuunk/CK2ToEU4
|
5c1755d17a36950d29a6c0ca13e454cb27b767bf
|
[
"MIT"
] | null | null | null |
#include "RulerPersonalitiesMapper.h"
#include "../../CK2World/Characters/Character.h"
#include "Log.h"
#include "ParserHelpers.h"
mappers::RulerPersonalitiesMapper::RulerPersonalitiesMapper()
{
LOG(LogLevel::Info) << "-> Parsing Ruler Personalities";
registerKeys();
parseFile("configurables/ruler_personalities.txt");
clearRegisteredKeywords();
LOG(LogLevel::Info) << "<> " << theMappings.size() << " personalities loaded.";
}
mappers::RulerPersonalitiesMapper::RulerPersonalitiesMapper(std::istream& theStream)
{
registerKeys();
parseStream(theStream);
clearRegisteredKeywords();
}
void mappers::RulerPersonalitiesMapper::registerKeys()
{
registerRegex("[a-zA-Z0-9_-]+", [this](const std::string& personality, std::istream& theStream) {
const auto newMapping = RulerPersonalitiesMapping(theStream);
theMappings.insert(std::pair(personality, newMapping));
});
registerRegex("[a-zA-Z0-9\\_.:-]+", commonItems::ignoreItem);
}
std::set<std::string> mappers::RulerPersonalitiesMapper::evaluatePersonalities(const std::pair<int, std::shared_ptr<CK2::Character>>& theCharacter) const
{
// In CK2 they are traits. In EU4 they are personalities.
const auto& incTraits = theCharacter.second->getTraits();
std::set<std::string> ck2Traits;
for (const auto& trait: incTraits)
ck2Traits.insert(trait.second);
std::vector<std::pair<int, std::string>> scoreBoard; // personalityscore, personality
std::set<std::string> toReturn;
for (const auto& mapping: theMappings)
{
auto score = mapping.second.evaluatePersonality(ck2Traits);
scoreBoard.emplace_back(std::pair(score, mapping.first));
}
std::sort(scoreBoard.rbegin(), scoreBoard.rend());
// send back first two. EU4 should deal with excess.
for (auto i = 0; i < std::min(2, static_cast<int>(theMappings.size())); i++)
{
toReturn.insert(scoreBoard[i].second);
}
return toReturn;
}
| 33.303571
| 153
| 0.737265
|
bavbeerhall
|
143b49ce98020dd1388d8a56d385721003bf40b5
| 1,573
|
cpp
|
C++
|
src/blockManagement/block.cpp
|
ivomachado/Trabalho1BD
|
291a52ae8a24c7dc0ec2a87543b8260e1953c354
|
[
"MIT"
] | 2
|
2019-05-16T13:52:40.000Z
|
2019-05-31T20:05:18.000Z
|
src/blockManagement/block.cpp
|
ivomachado/Trabalho1BD
|
291a52ae8a24c7dc0ec2a87543b8260e1953c354
|
[
"MIT"
] | null | null | null |
src/blockManagement/block.cpp
|
ivomachado/Trabalho1BD
|
291a52ae8a24c7dc0ec2a87543b8260e1953c354
|
[
"MIT"
] | null | null | null |
#include "block.hpp"
#include "field.hpp"
#include "utils.hpp"
#include <cstdio>
#include <vector>
DiskBlock::DiskBlock(std::vector<Field>& recordFields)
{
m_header.m_data.emplace_back(Field::asInteger(0)); //Registros no bloco
m_header.m_data.emplace_back(Field::asInteger(0)); //Apontador para o de overflow
m_recordFields = recordFields;
for (auto& field : m_recordFields) {
m_recordSize += field.size();
}
}
void DiskBlock::readFromFile(FILE* file)
{
fread(m_buffer, sizeof(char), DiskBlock::SIZE, file);
readFromBuffer();
}
void DiskBlock::writeToFile(FILE* file)
{
writeToBuffer();
fwrite(m_buffer, sizeof(char), DiskBlock::SIZE, file);
}
void DiskBlock::writeToBuffer()
{
m_header.m_data[0].m_integer = static_cast<int>(m_records.size());
m_bufferPos = m_header.writeToBuffer(m_buffer, 0);
m_bufferPos = Utils::writeVectorToBuffer(m_buffer, m_records, m_bufferPos);
}
void DiskBlock::readFromBuffer()
{
m_bufferPos = m_header.readFromBuffer(m_buffer, 0);
int numberOfRecords = m_header.m_data[0].m_integer;
m_records.resize(0);
for (int i = 0; i < numberOfRecords; i++) {
m_records.emplace_back(m_recordFields);
}
m_bufferPos = Utils::readVectorFromBuffer(m_buffer, m_records, m_bufferPos);
}
bool DiskBlock::fitOneMoreRecord() {
return (m_records.size() + 1) * m_recordSize <= DiskBlock::AVAILABLE_SIZE;
}
bool DiskBlock::insert(const Record& record)
{
if(fitOneMoreRecord()) {
m_records.push_back(record);
return true;
}
return false;
}
| 26.661017
| 85
| 0.698029
|
ivomachado
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.