blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
83ea93210f8e922b9f37402ab96493ca242d3dc5 | 693ef12b1413de6942f510c63e017d96f06a01e0 | /LAB3_EXCEPTION/include/lab3.1_ex.hpp | 16d93eab8170c06c9e581738c007c8b985b03d38 | [] | no_license | MACIEKz8/JiPP | b038bf421a6634bafe1ceb02fb4e943e6f7b0912 | c9c3901e7adfda9d3b4e84d6005a8449fdba1467 | refs/heads/master | 2023-04-29T15:00:32.743910 | 2021-05-10T11:36:51 | 2021-05-10T11:36:51 | 303,344,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,315 | hpp | #include <iostream>
#include <fstream>
#include "lab3_ex.hpp"
#include "exceptions.cpp"
using namespace std;
macierz::macierz(int n, int m)
{
wiersz=n;
kolumna=m;
try
{
if (n<=0 || m<=0)
{
LessOrEqualZero error;
throw error;
}
tab=new double *[wiersz];
for(int i=0;i<wiersz;i++)
tab[i]=new double[kolumna];
for (int i=0;i<wiersz;i++)
{
for(int j=0;j<kolumna;j++)
{
tab[i][j]=0;
}
}
}
catch(exception &e)
{
cout<<e.what()<<endl;
}
}
macierz::macierz(int n)
{
wiersz=n;
kolumna=n;
try
{
if(n<=0)
{
LessOrEqualZero error;
throw error;
}
tab=new double *[wiersz];
for(int i=0;i<wiersz;i++)
tab[i]=new double[wiersz];
for (int i=0;i<wiersz;i++)
{
for(int j=0;j<wiersz;j++)
{
tab[i][j]=0;
}
}
}
catch(exception &e)
{
cout<<e.what()<<endl;
}
}
void macierz::set(int n, int m, double val)
{
try
{
if( n>wiersz || m>kolumna)
{
WrongSize error;
throw error;
}
else if(n<0 || m<0)
{
LessZero error;
throw error;
}
else
tab[n][m]=val;
}
catch(exception &e)
{
cout<< e.what() <<endl;
}
}
double macierz::get(int n, int m)
{
try
{
if( n>wiersz || m>kolumna)
{
WrongSize error;
throw error;
}
else if(n<0 || m<0)
{
LessZero error;
throw error;
}
else
return tab[n][m];
}
catch(exception &e)
{
cout<< e.what() <<endl;
}
}
macierz macierz::add(macierz mac)
{
try
{
if(mac.rows()!=wiersz || mac.cols() !=kolumna)
{
IndexError error;
throw error;
}
}
catch(exception &e)
{
cout<< e.what() <<endl;
}
macierz wynik(mac.rows(),mac.cols());
for(int i=0;i<mac.rows();i++)
{
for(int j=0;j<mac.cols();j++)
{
wynik.tab[i][j] = mac.tab[i][j]+tab[i][j];
}
}
return wynik;
}
macierz macierz::subtract(macierz mac)
{
try
{
if(mac.rows()!=wiersz || mac.cols() !=kolumna)
{
IndexError error;
throw error;
}
}
catch(exception &e)
{
cout<< e.what() <<endl;
}
macierz roznica(mac.rows(),mac.cols());
for(int i=0;i<mac.rows();i++)
{
for(int j=0;j<mac.cols();j++)
roznica.tab[i][j]=tab[i][j]-mac.tab[i][j];
}
return roznica;
}
macierz macierz::multiply(macierz mac)
{
try
{
if(mac.rows()!=kolumna)
{
IndexError error;
throw error;
}
}
catch(exception &e)
{
cout<< e.what() <<endl;
}
double wynik;
macierz iloczyn(wiersz,mac.cols());
for (int i = 0; i < wiersz; i++)
{
for (int j = 0; j < mac.kolumna; j++)
{
wynik=0;
for (int k = 0; k < mac.wiersz; k++)
{
wynik+=tab[i][k]*mac.tab[k][j];
}
iloczyn.tab[i][j]=wynik;
}
}
return iloczyn;
}
int macierz::cols()
{
return kolumna;
}
int macierz::rows()
{
return wiersz;
}
void macierz::print()
{
for(int i=0;i<wiersz;i++)
{
for(int j=0;j<kolumna;j++)
cout<<"tab["<<i<<"]["<<j<<"] = "<<tab[i][j]<<" "<<'\t';
cout<<endl;
}
cout<<endl;
}
void macierz::store(string filename, string path)
{
fstream plik;
plik.open(path,ios_base::out);
try
{
if(plik.is_open())
{
plik<<"Number of rows: "<<rows()<<" Number of cols: "<<cols()<<endl;
for(int i =0;i<wiersz;i++)
{
for(int j =0;j<kolumna;j++)
{
plik<<tab[i][j]<<" ";
}
plik<<endl;
}
plik.close();
}
else
{
FileOpen error;
throw error;
}
}
catch(const std::exception& e)
{
cout<< e.what() <<endl;
}
}
macierz::macierz(string path)
{
fstream plik;
plik.open(path);
int wiersz1,kolumna1;
try
{
if(plik.is_open())
{
plik>>wiersz1;
plik>>kolumna1;
wiersz=wiersz1;
kolumna=kolumna1;
tab = new double*[wiersz];
for (int i=0;i<wiersz;i++)
{
tab[i]=new double[kolumna];
}
for (int i = 0; i < wiersz; i++)
{
for (int j = 0; j < kolumna; j++)
{
plik >> tab[i][j];
}
}
plik.close();
}
else
{
FileOpen error;
throw error;
}
}
catch(const std::exception& e)
{
cout<< e.what() <<endl;
}
}; | [
"maciej.zawisz@student.pk.edu.pl"
] | maciej.zawisz@student.pk.edu.pl |
789bce962dcb781785a396c085a9dc511b323c91 | 6e5e0030daa0b048be1fa0c91b3310dd329fd25c | /viewer3d.cpp | 2dbb1bc3236ea8256093e4c838c0d8548b4ae9a3 | [] | no_license | TatianaVR/AxiOMA | 32ab02a568963ea28d631d9a5fae17757ccdf073 | b6b9b1aefe4710826a905142bd9c435be4981a6f | refs/heads/master | 2020-06-14T05:16:17.607762 | 2019-07-24T18:47:02 | 2019-07-24T18:47:02 | 194,914,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,136 | cpp | #include "viewer3d.h"
#include "ui_viewer3d.h"
#include "math_addition.h"
using namespace std;
Viewer3D::Viewer3D(QWidget *parent) :
QWidget(parent),
ui(new Ui::Viewer3D)
{
ui->setupUi(this);
this->setWindowFlags(Qt::FramelessWindowHint); //нет рамки
connect(ui->viewType, SIGNAL(currentIndexChanged(int)), ui->drawGL, SLOT(receiveViewType(int)));
connect(ui->SetAxis, SIGNAL(currentIndexChanged(int)), ui->drawGL, SLOT(changeRotationAxis()));
connect(ui->mesh_density, SIGNAL(valueChanged(int)), ui->drawGL, SLOT(receiveDensity(int)));
connect(ui->ModelLight, SIGNAL(currentTextChanged(const QString)), ui->drawGL, SLOT(receiveModelLight(const QString)));
connect(this, SIGNAL(sendPointsData(QVector <double>, QVector <double>)), ui->drawGL, SLOT(receivePointsData(QVector <double>, QVector <double>)));
connect(this, SIGNAL(sendDiffuseColor(QColor)), ui->drawGL, SLOT(receiveDiffuseColor(QColor)));
connect(this, SIGNAL(sendSpecularColor(QColor)), ui->drawGL, SLOT(receiveSpecularColor(QColor)));
connect(this, SIGNAL(sendLightModelAttributes(QVector <QString>, QVector <double>)), ui->drawGL, SLOT(receiveLightModelAttributes(QVector <QString>, QVector <double>)));
connect(this, SIGNAL(sendLightSettings(QVector3D, QVector3D)), ui->drawGL, SLOT(receiveLightSettings(QVector3D, QVector3D)));
foreach (QDoubleSpinBox * spinBox, ui->LightAttributes->findChildren<QDoubleSpinBox *>())
{
connect(spinBox, SIGNAL(valueChanged(double)), this, SLOT(updateLightModelAttributes()));
}
foreach (QSpinBox * spinBox, ui->groupBox_4->findChildren<QSpinBox *>())
{
connect(spinBox, SIGNAL(valueChanged(int)), this, SLOT(updateLightSettings()));
}
emit ui->viewType->currentIndexChanged(ui->viewType->currentIndex());
emit ui->ModelLight->currentTextChanged(ui->ModelLight->currentText());
emit ui->mesh_density->valueChanged(ui->mesh_density->value());
emit sendDiffuseColor(ui->figureColor->palette().button().color());
emit sendSpecularColor(ui->highlightColor->palette().button().color());
on_ModelLight_currentIndexChanged(0);
}
Viewer3D::~Viewer3D()
{
delete ui;
}
void Viewer3D::receivePointsData(QVector <double> X, QVector <double> Z)
{
emit sendPointsData(X, Z);
}
void Viewer3D::updateLightModelAttributes()
{
getAttributes();
emit sendLightModelAttributes(attributeName, attributeValue);
}
void Viewer3D::updateLightSettings()
{
QVector3D lightPosition(ui->lightX->value(), ui->lightY->value(), ui->lightZ->value());
QVector3D eyePosition(ui->eyeX->value(), ui->eyeY->value(), ui->eyeZ->value());
emit sendLightSettings(lightPosition, eyePosition);
}
void Viewer3D::on_EndButton_clicked()
{
close();
}
void Viewer3D::on_figureColor_clicked()
{
QPalette myPalette = ui->figureColor->palette();
QColor color = QColorDialog::getColor(myPalette.button().color());
if (!color.isValid())
{
return;
}
myPalette.setColor(ui->figureColor->backgroundRole(), color);
ui->figureColor->setPalette(myPalette);
emit sendDiffuseColor(color);
}
void Viewer3D::on_highlightColor_clicked()
{
QPalette myPalette = ui->highlightColor->palette();
QColor color = QColorDialog::getColor(myPalette.button().color());
if (!color.isValid())
{
return;
}
myPalette.setColor(ui->highlightColor->backgroundRole(), color);
ui->highlightColor->setPalette(myPalette);
emit sendSpecularColor(color);
}
void Viewer3D::on_ModelLight_currentIndexChanged(int index)
{
ui->LightAttributes->setCurrentIndex(index);
getAttributes();
emit sendLightModelAttributes(attributeName, attributeValue);
}
void Viewer3D::getAttributes()
{
attributeName.clear();
attributeValue.clear();
foreach (QLabel * label, ui->LightAttributes->currentWidget()->findChildren<QLabel *>())
{
attributeName.append(label->text());
}
foreach (QDoubleSpinBox * spinBox, ui->LightAttributes->currentWidget()->findChildren<QDoubleSpinBox *>())
{
attributeValue.append(spinBox->value());
}
}
| [
"tsivkina@vrconcept.net"
] | tsivkina@vrconcept.net |
9fd0d449d4d2c64b5fcafa831055f04c3c44c200 | 26ad4cc35496d364b31396e43a863aee08ef2636 | /SDK/SoT_BP_ipg_gen_trousers_02_Desc_classes.hpp | ab08f91e32472c4b997d7069cc53c9d5c74d0674 | [] | no_license | cw100/SoT-SDK | ddb9b19ce6ae623299b2b02dee51c29581537ba1 | 3e6f12384c8e21ed83ef56f00030ca0506d297fb | refs/heads/master | 2020-05-05T12:09:55.938323 | 2019-03-20T14:11:57 | 2019-03-20T14:11:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 757 | hpp | #pragma once
// Sea of Thieves (1.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_ipg_gen_trousers_02_Desc_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_ipg_gen_trousers_02_Desc.BP_ipg_gen_trousers_02_Desc_C
// 0x0000 (0x00E0 - 0x00E0)
class UBP_ipg_gen_trousers_02_Desc_C : public UClothingDesc
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_ipg_gen_trousers_02_Desc.BP_ipg_gen_trousers_02_Desc_C"));
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
3b35c8d3dd3a6109c8d80e752e40a5a1e33ac862 | c3442c04fa2d739a3fbd6ac93a7119c1d18fc873 | /cie-pkcs11/Cryptopp/pwdbased.h | 20828a91c08f535cda1b3756280d8bb252b6b9cd | [
"BSD-3-Clause"
] | permissive | italia/cie-middleware-macos | 47542b2cde1e98cdf35d0e7d0ad91744530e0110 | e26910245026dc091c6c1dec6999395e8669ce63 | refs/heads/master | 2023-06-23T16:10:05.809155 | 2023-06-05T13:02:56 | 2023-06-05T13:02:56 | 147,847,859 | 16 | 4 | BSD-3-Clause | 2023-06-15T09:09:17 | 2018-09-07T16:20:45 | C++ | UTF-8 | C++ | false | false | 15,652 | h | // pwdbased.h - originally written and placed in the public domain by Wei Dai
// Cutover to KeyDerivationFunction interface by Uri Blumenthal
// Marcel Raad and Jeffrey Walton in March 2018.
/// \file pwdbased.h
/// \brief Password based key derivation functions
#ifndef CRYPTOPP_PWDBASED_H
#define CRYPTOPP_PWDBASED_H
#include "cryptlib.h"
#include "hrtimer.h"
#include "integer.h"
#include "argnames.h"
#include "hmac.h"
NAMESPACE_BEGIN(CryptoPP)
// ******************** PBKDF1 ********************
/// \brief PBKDF1 from PKCS #5
/// \tparam T a HashTransformation class
template <class T>
class PKCS5_PBKDF1 : public PasswordBasedKeyDerivationFunction
{
public:
virtual ~PKCS5_PBKDF1() {}
static std::string StaticAlgorithmName () {
const std::string name(std::string("PBKDF1(") +
std::string(T::StaticAlgorithmName()) + std::string(")"));
return name;
}
// KeyDerivationFunction interface
std::string AlgorithmName() const {
return StaticAlgorithmName();
}
// KeyDerivationFunction interface
size_t MaxDerivedKeyLength() const {
return static_cast<size_t>(T::DIGESTSIZE);
}
// KeyDerivationFunction interface
size_t GetValidDerivedLength(size_t keylength) const;
// KeyDerivationFunction interface
virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen,
const NameValuePairs& params = g_nullNameValuePairs) const;
/// \brief Derive a key from a secret seed
/// \param derived the derived output buffer
/// \param derivedLen the size of the derived buffer, in bytes
/// \param purpose a purpose byte
/// \param secret the seed input buffer
/// \param secretLen the size of the secret buffer, in bytes
/// \param salt the salt input buffer
/// \param saltLen the size of the salt buffer, in bytes
/// \param iterations the number of iterations
/// \param timeInSeconds the in seconds
/// \returns the number of iterations performed
/// \throws InvalidDerivedLength if <tt>derivedLen</tt> is invalid for the scheme
/// \details DeriveKey() provides a standard interface to derive a key from
/// a seed and other parameters. Each class that derives from KeyDerivationFunction
/// provides an overload that accepts most parameters used by the derivation function.
/// \details If <tt>timeInSeconds</tt> is <tt>> 0.0</tt> then DeriveKey will run for
/// the specified amount of time. If <tt>timeInSeconds</tt> is <tt>0.0</tt> then DeriveKey
/// will run for the specified number of iterations.
/// \details PKCS #5 says PBKDF1 should only take 8-byte salts. This implementation
/// allows salts of any length.
size_t DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds=0) const;
protected:
// KeyDerivationFunction interface
const Algorithm & GetAlgorithm() const {
return *this;
}
};
template <class T>
size_t PKCS5_PBKDF1<T>::GetValidDerivedLength(size_t keylength) const
{
if (keylength > MaxDerivedLength())
return MaxDerivedLength();
return keylength;
}
template <class T>
size_t PKCS5_PBKDF1<T>::DeriveKey(byte *derived, size_t derivedLen,
const byte *secret, size_t secretLen, const NameValuePairs& params) const
{
CRYPTOPP_ASSERT(secret /*&& secretLen*/);
CRYPTOPP_ASSERT(derived && derivedLen);
CRYPTOPP_ASSERT(derivedLen <= MaxDerivedLength());
byte purpose = (byte)params.GetIntValueWithDefault("Purpose", 0);
unsigned int iterations = (unsigned int)params.GetIntValueWithDefault("Iterations", 1);
double timeInSeconds = 0.0f;
(void)params.GetValue("TimeInSeconds", timeInSeconds);
ConstByteArrayParameter salt;
(void)params.GetValue(Name::Salt(), salt);
return DeriveKey(derived, derivedLen, purpose, secret, secretLen, salt.begin(), salt.size(), iterations, timeInSeconds);
}
template <class T>
size_t PKCS5_PBKDF1<T>::DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const
{
CRYPTOPP_ASSERT(secret /*&& secretLen*/);
CRYPTOPP_ASSERT(derived && derivedLen);
CRYPTOPP_ASSERT(derivedLen <= MaxDerivedLength());
CRYPTOPP_ASSERT(iterations > 0 || timeInSeconds > 0);
CRYPTOPP_UNUSED(purpose);
ThrowIfInvalidDerivedLength(derivedLen);
// Business logic
if (!iterations) { iterations = 1; }
T hash;
hash.Update(secret, secretLen);
hash.Update(salt, saltLen);
SecByteBlock buffer(hash.DigestSize());
hash.Final(buffer);
unsigned int i;
ThreadUserTimer timer;
if (timeInSeconds)
timer.StartTimer();
for (i=1; i<iterations || (timeInSeconds && (i%128!=0 || timer.ElapsedTimeAsDouble() < timeInSeconds)); i++)
hash.CalculateDigest(buffer, buffer, buffer.size());
memcpy(derived, buffer, derivedLen);
return i;
}
// ******************** PKCS5_PBKDF2_HMAC ********************
/// \brief PBKDF2 from PKCS #5
/// \tparam T a HashTransformation class
template <class T>
class PKCS5_PBKDF2_HMAC : public PasswordBasedKeyDerivationFunction
{
public:
virtual ~PKCS5_PBKDF2_HMAC() {}
static std::string StaticAlgorithmName () {
const std::string name(std::string("PBKDF2_HMAC(") +
std::string(T::StaticAlgorithmName()) + std::string(")"));
return name;
}
// KeyDerivationFunction interface
std::string AlgorithmName() const {
return StaticAlgorithmName();
}
// KeyDerivationFunction interface
// should multiply by T::DIGESTSIZE, but gets overflow that way
size_t MaxDerivedKeyLength() const {
return 0xffffffffU;
}
// KeyDerivationFunction interface
size_t GetValidDerivedLength(size_t keylength) const;
// KeyDerivationFunction interface
size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen,
const NameValuePairs& params = g_nullNameValuePairs) const;
/// \brief Derive a key from a secret seed
/// \param derived the derived output buffer
/// \param derivedLen the size of the derived buffer, in bytes
/// \param purpose a purpose byte
/// \param secret the seed input buffer
/// \param secretLen the size of the secret buffer, in bytes
/// \param salt the salt input buffer
/// \param saltLen the size of the salt buffer, in bytes
/// \param iterations the number of iterations
/// \param timeInSeconds the in seconds
/// \returns the number of iterations performed
/// \throws InvalidDerivedLength if <tt>derivedLen</tt> is invalid for the scheme
/// \details DeriveKey() provides a standard interface to derive a key from
/// a seed and other parameters. Each class that derives from KeyDerivationFunction
/// provides an overload that accepts most parameters used by the derivation function.
/// \details If <tt>timeInSeconds</tt> is <tt>> 0.0</tt> then DeriveKey will run for
/// the specified amount of time. If <tt>timeInSeconds</tt> is <tt>0.0</tt> then DeriveKey
/// will run for the specified number of iterations.
size_t DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen,
const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds=0) const;
protected:
// KeyDerivationFunction interface
const Algorithm & GetAlgorithm() const {
return *this;
}
};
template <class T>
size_t PKCS5_PBKDF2_HMAC<T>::GetValidDerivedLength(size_t keylength) const
{
if (keylength > MaxDerivedLength())
return MaxDerivedLength();
return keylength;
}
template <class T>
size_t PKCS5_PBKDF2_HMAC<T>::DeriveKey(byte *derived, size_t derivedLen,
const byte *secret, size_t secretLen, const NameValuePairs& params) const
{
CRYPTOPP_ASSERT(secret /*&& secretLen*/);
CRYPTOPP_ASSERT(derived && derivedLen);
CRYPTOPP_ASSERT(derivedLen <= MaxDerivedLength());
byte purpose = (byte)params.GetIntValueWithDefault("Purpose", 0);
unsigned int iterations = (unsigned int)params.GetIntValueWithDefault("Iterations", 1);
double timeInSeconds = 0.0f;
(void)params.GetValue("TimeInSeconds", timeInSeconds);
ConstByteArrayParameter salt;
(void)params.GetValue(Name::Salt(), salt);
return DeriveKey(derived, derivedLen, purpose, secret, secretLen, salt.begin(), salt.size(), iterations, timeInSeconds);
}
template <class T>
size_t PKCS5_PBKDF2_HMAC<T>::DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const
{
CRYPTOPP_ASSERT(secret /*&& secretLen*/);
CRYPTOPP_ASSERT(derived && derivedLen);
CRYPTOPP_ASSERT(derivedLen <= MaxDerivedLength());
CRYPTOPP_ASSERT(iterations > 0 || timeInSeconds > 0);
CRYPTOPP_UNUSED(purpose);
ThrowIfInvalidDerivedLength(derivedLen);
// Business logic
if (!iterations) { iterations = 1; }
HMAC<T> hmac(secret, secretLen);
SecByteBlock buffer(hmac.DigestSize());
ThreadUserTimer timer;
unsigned int i=1;
while (derivedLen > 0)
{
hmac.Update(salt, saltLen);
unsigned int j;
for (j=0; j<4; j++)
{
byte b = byte(i >> ((3-j)*8));
hmac.Update(&b, 1);
}
hmac.Final(buffer);
#if CRYPTOPP_MSC_VERSION
const size_t segmentLen = STDMIN(derivedLen, buffer.size());
memcpy_s(derived, segmentLen, buffer, segmentLen);
#else
const size_t segmentLen = STDMIN(derivedLen, buffer.size());
memcpy(derived, buffer, segmentLen);
#endif
if (timeInSeconds)
{
timeInSeconds = timeInSeconds / ((derivedLen + buffer.size() - 1) / buffer.size());
timer.StartTimer();
}
for (j=1; j<iterations || (timeInSeconds && (j%128!=0 || timer.ElapsedTimeAsDouble() < timeInSeconds)); j++)
{
hmac.CalculateDigest(buffer, buffer, buffer.size());
xorbuf(derived, buffer, segmentLen);
}
if (timeInSeconds)
{
iterations = j;
timeInSeconds = 0;
}
derived += segmentLen;
derivedLen -= segmentLen;
i++;
}
return iterations;
}
// ******************** PKCS12_PBKDF ********************
/// \brief PBKDF from PKCS #12, appendix B
/// \tparam T a HashTransformation class
template <class T>
class PKCS12_PBKDF : public PasswordBasedKeyDerivationFunction
{
public:
virtual ~PKCS12_PBKDF() {}
static std::string StaticAlgorithmName () {
const std::string name(std::string("PBKDF_PKCS12(") +
std::string(T::StaticAlgorithmName()) + std::string(")"));
return name;
}
// KeyDerivationFunction interface
std::string AlgorithmName() const {
return StaticAlgorithmName();
}
// TODO - check this
size_t MaxDerivedKeyLength() const {
return static_cast<size_t>(-1);
}
// KeyDerivationFunction interface
size_t GetValidDerivedLength(size_t keylength) const;
// KeyDerivationFunction interface
size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen,
const NameValuePairs& params = g_nullNameValuePairs) const;
/// \brief Derive a key from a secret seed
/// \param derived the derived output buffer
/// \param derivedLen the size of the derived buffer, in bytes
/// \param purpose a purpose byte
/// \param secret the seed input buffer
/// \param secretLen the size of the secret buffer, in bytes
/// \param salt the salt input buffer
/// \param saltLen the size of the salt buffer, in bytes
/// \param iterations the number of iterations
/// \param timeInSeconds the in seconds
/// \returns the number of iterations performed
/// \throws InvalidDerivedLength if <tt>derivedLen</tt> is invalid for the scheme
/// \details DeriveKey() provides a standard interface to derive a key from
/// a seed and other parameters. Each class that derives from KeyDerivationFunction
/// provides an overload that accepts most parameters used by the derivation function.
/// \details If <tt>timeInSeconds</tt> is <tt>> 0.0</tt> then DeriveKey will run for
/// the specified amount of time. If <tt>timeInSeconds</tt> is <tt>0.0</tt> then DeriveKey
/// will run for the specified number of iterations.
size_t DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen,
const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const;
protected:
// KeyDerivationFunction interface
const Algorithm & GetAlgorithm() const {
return *this;
}
};
template <class T>
size_t PKCS12_PBKDF<T>::GetValidDerivedLength(size_t keylength) const
{
if (keylength > MaxDerivedLength())
return MaxDerivedLength();
return keylength;
}
template <class T>
size_t PKCS12_PBKDF<T>::DeriveKey(byte *derived, size_t derivedLen,
const byte *secret, size_t secretLen, const NameValuePairs& params) const
{
CRYPTOPP_ASSERT(secret /*&& secretLen*/);
CRYPTOPP_ASSERT(derived && derivedLen);
CRYPTOPP_ASSERT(derivedLen <= MaxDerivedLength());
byte purpose = (byte)params.GetIntValueWithDefault("Purpose", 0);
unsigned int iterations = (unsigned int)params.GetIntValueWithDefault("Iterations", 1);
double timeInSeconds = 0.0f;
(void)params.GetValue("TimeInSeconds", timeInSeconds);
// NULL or 0 length salt OK
ConstByteArrayParameter salt;
(void)params.GetValue(Name::Salt(), salt);
return DeriveKey(derived, derivedLen, purpose, secret, secretLen, salt.begin(), salt.size(), iterations, timeInSeconds);
}
template <class T>
size_t PKCS12_PBKDF<T>::DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const
{
CRYPTOPP_ASSERT(secret /*&& secretLen*/);
CRYPTOPP_ASSERT(derived && derivedLen);
CRYPTOPP_ASSERT(derivedLen <= MaxDerivedLength());
CRYPTOPP_ASSERT(iterations > 0 || timeInSeconds > 0);
ThrowIfInvalidDerivedLength(derivedLen);
// Business logic
if (!iterations) { iterations = 1; }
const size_t v = T::BLOCKSIZE; // v is in bytes rather than bits as in PKCS #12
const size_t DLen = v, SLen = RoundUpToMultipleOf(saltLen, v);
const size_t PLen = RoundUpToMultipleOf(secretLen, v), ILen = SLen + PLen;
SecByteBlock buffer(DLen + SLen + PLen);
byte *D = buffer, *S = buffer+DLen, *P = buffer+DLen+SLen, *I = S;
memset(D, purpose, DLen);
size_t i;
for (i=0; i<SLen; i++)
S[i] = salt[i % saltLen];
for (i=0; i<PLen; i++)
P[i] = secret[i % secretLen];
T hash;
SecByteBlock Ai(T::DIGESTSIZE), B(v);
ThreadUserTimer timer;
while (derivedLen > 0)
{
hash.CalculateDigest(Ai, buffer, buffer.size());
if (timeInSeconds)
{
timeInSeconds = timeInSeconds / ((derivedLen + Ai.size() - 1) / Ai.size());
timer.StartTimer();
}
for (i=1; i<iterations || (timeInSeconds && (i%128!=0 || timer.ElapsedTimeAsDouble() < timeInSeconds)); i++)
hash.CalculateDigest(Ai, Ai, Ai.size());
if (timeInSeconds)
{
iterations = (unsigned int)i;
timeInSeconds = 0;
}
for (i=0; i<B.size(); i++)
B[i] = Ai[i % Ai.size()];
Integer B1(B, B.size());
++B1;
for (i=0; i<ILen; i+=v)
(Integer(I+i, v) + B1).Encode(I+i, v);
#if CRYPTOPP_MSC_VERSION
const size_t segmentLen = STDMIN(derivedLen, Ai.size());
memcpy_s(derived, segmentLen, Ai, segmentLen);
#else
const size_t segmentLen = STDMIN(derivedLen, Ai.size());
std::memcpy(derived, Ai, segmentLen);
#endif
derived += segmentLen;
derivedLen -= segmentLen;
}
return iterations;
}
NAMESPACE_END
#endif
| [
"ugos@666-Mac.local"
] | ugos@666-Mac.local |
330a084b7fde6fc76822d0e9d6f787736c757505 | 2ae26f1c8e8eeff8886cfc9388c7ee8e76279d5a | /tests/lexy/dsl/whitespace.cpp | ef5cab30d0d49b716c2630dec6e9f371f714cf5f | [
"BSL-1.0"
] | permissive | JYLeeLYJ/lexy | 6c7980d42b811c5f07463e607b6b13982478ae99 | ada8a03479bcb4c4edc3094b0ff363cf0b3aefe1 | refs/heads/main | 2023-02-09T17:32:18.383320 | 2021-01-08T20:29:07 | 2021-01-08T20:41:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,216 | cpp | // Copyright (C) 2020-2021 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#include <lexy/dsl/whitespace.hpp>
#include "verify.hpp"
#include <lexy/dsl/if.hpp>
#include <lexy/dsl/label.hpp>
TEST_CASE("dsl::whitespaced()")
{
SUBCASE("simple")
{
static constexpr auto rule = whitespaced(LEXY_LIT("abc"), LEXY_LIT(" "));
CHECK(lexy::is_rule<decltype(rule)>);
CHECK(lexy::is_branch<decltype(rule)>);
struct callback
{
const char* str;
LEXY_VERIFY_FN int success(const char* cur)
{
return int(cur - str) - 3;
}
LEXY_VERIFY_FN int error(test_error<lexy::expected_literal> e)
{
LEXY_VERIFY_CHECK(e.string() == "abc");
return -1;
}
};
auto empty = LEXY_VERIFY("");
CHECK(empty == -1);
auto abc = LEXY_VERIFY("abc");
CHECK(abc == 0);
auto space_abc = LEXY_VERIFY(" abc");
CHECK(space_abc == 1);
auto space_space_abc = LEXY_VERIFY(" abc");
CHECK(space_space_abc == 2);
}
SUBCASE("branch")
{
static constexpr auto rule_
= whitespaced(LEXY_LIT("abc") >> lexy::dsl::id<0>, LEXY_LIT(" "));
CHECK(lexy::is_rule<decltype(rule_)>);
CHECK(lexy::is_branch<decltype(rule_)>);
static constexpr auto rule = if_(rule_);
struct callback
{
const char* str;
LEXY_VERIFY_FN int success(const char* cur)
{
LEXY_VERIFY_CHECK(cur == str);
return 0;
}
LEXY_VERIFY_FN int success(const char* cur, lexy::id<0>)
{
return int(cur - str);
}
};
auto empty = LEXY_VERIFY("");
CHECK(empty == 0);
auto abc = LEXY_VERIFY("abc");
CHECK(abc == 3);
auto space_abc = LEXY_VERIFY(" abc");
CHECK(space_abc == 4);
auto space_space_abc = LEXY_VERIFY(" abc");
CHECK(space_space_abc == 5);
}
}
| [
"git@foonathan.net"
] | git@foonathan.net |
4477b1d1792458b13a05c123e2939b6c1581db70 | 6124839f29efdf1ac1eaf0d18fc3edf31336c841 | /Game.h | aebcd02079185d38f3395c7ce0c7dc0a532b2e7b | [] | no_license | SawyerCzupka/ConnectFour | 1e4ef192e52f900de93ed12851b256d48f167f49 | 2849e88e74fe44a44feb099c02521dc4c1cd9ed9 | refs/heads/master | 2023-06-09T23:50:13.651797 | 2023-05-24T15:32:55 | 2023-05-24T15:32:55 | 350,835,730 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | h | //
// Created by Sawyer on 3/22/2021.
//
#ifndef CONNECTFOUR_GAME_H
#define CONNECTFOUR_GAME_H
#include "Player.h"
#include "Board.h"
class Game {
public:
// Constructor
Game(const std::string& one, const std::string& two, bool isAiGame = false);
// Methods
void test();
[[ noreturn ]] void mainloop();
private:
// Instance Variables
Player* player1;
Player* player2;
Board gameBoard;
// Methods
static void printIntroduction();
static void printDirections();
void printScoreReport();
static void printMenu();
static int getMenuResponse();
int handleBranchResponses(int arr);
void playRound();
};
#endif //CONNECTFOUR_GAME_H
| [
"sawyerczupka@gmail.com"
] | sawyerczupka@gmail.com |
a92fa338956924d0d444dc6bacc3599a7ba53c4f | a8e536b2d09839183e53f5d117554e5c9a03b22e | /幼儿园信息管理系统/ForKids/ForKids/ForKidsView.cpp | 1c6e2229fd7f926daa8704ac910bfb9cf006e243 | [] | no_license | BaiMath/ForKids | 4b20ed320bbf9db6036003bee80b931af77a63ac | 2ff2730062d79e66c5fb6f6aae5e4f34664c9278 | refs/heads/master | 2016-09-05T14:03:55.562911 | 2014-02-24T15:28:07 | 2014-02-24T15:28:07 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,214 | cpp | // 这段 MFC 示例源代码演示如何使用 MFC Microsoft Office Fluent 用户界面
// (“Fluent UI”)。该示例仅供参考,
// 用以补充《Microsoft 基础类参考》和
// MFC C++ 库软件随附的相关电子文档。
// 复制、使用或分发 Fluent UI 的许可条款是单独提供的。
// 若要了解有关 Fluent UI 许可计划的详细信息,请访问
// http://msdn.microsoft.com/officeui。
//
// 版权所有(C) Microsoft Corporation
// 保留所有权利。
// ForKidsView.cpp : CForKidsView 类的实现
//
#include "stdafx.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义,并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "ForKids.h"
#endif
#include "ForKidsDoc.h"
#include "ForKidsView.h"
using namespace ForKids::UI;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CForKidsView
IMPLEMENT_DYNCREATE(CForKidsView, CView)
BEGIN_MESSAGE_MAP(CForKidsView, CView)
// 标准打印命令
ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CForKidsView::OnFilePrintPreview)
ON_WM_CONTEXTMENU()
ON_WM_RBUTTONUP()
ON_WM_SIZE()
END_MESSAGE_MAP()
// CForKidsView 构造/析构
CForKidsView::CForKidsView():m_bLoadMainPanel(FALSE)
{
// TODO: 在此处添加构造代码
}
CForKidsView::~CForKidsView()
{
}
BOOL CForKidsView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return CView::PreCreateWindow(cs);
}
// CForKidsView 绘制
void CForKidsView::OnDraw(CDC* /*pDC*/)
{
CForKidsDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
}
// CForKidsView 打印
void CForKidsView::OnFilePrintPreview()
{
#ifndef SHARED_HANDLERS
AFXPrintPreview(this);
#endif
}
BOOL CForKidsView::OnPreparePrinting(CPrintInfo* pInfo)
{
// 默认准备
return DoPreparePrinting(pInfo);
}
void CForKidsView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 添加额外的打印前进行的初始化过程
}
void CForKidsView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 添加打印后进行的清理过程
}
void CForKidsView::OnRButtonUp(UINT /* nFlags */, CPoint point)
{
ClientToScreen(&point);
OnContextMenu(this, point);
}
void CForKidsView::OnContextMenu(CWnd* /* pWnd */, CPoint point)
{
#ifndef SHARED_HANDLERS
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE);
#endif
}
// CForKidsView 诊断
#ifdef _DEBUG
void CForKidsView::AssertValid() const
{
CView::AssertValid();
}
void CForKidsView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CForKidsDoc* CForKidsView::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CForKidsDoc)));
return (CForKidsDoc*)m_pDocument;
}
#endif //_DEBUG
// CForKidsView 消息处理程序
void CForKidsView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
// TODO: 在此处添加消息处理程序代码
if(this->m_hWnd!=NULL)
{
if(!m_bLoadMainPanel)
{
m_gcMainPanel = gcnew Panel;
::SetParent((HWND)m_gcMainPanel->Handle.ToInt32(),this->m_hWnd);
//DataGridView^ gcDGV = gcnew DataGridView;
//Label^ gcLabel = gcnew Label;
//gcLabel->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;
//gcLabel->Text=L"一个测试:这是一个C# Label控件,嵌入在基于C++语言的Ribbon风格MFC框架视图中;如果你看到这个能实现,那么所有在C#中能完成的功能,在这里也能完成!";
//gcLabel->AutoSize=FALSE;
//gcLabel->Font=gcnew System::Drawing::Font(gcLabel->Font->FontFamily,20,System::Drawing::FontStyle::Bold);
//gcLabel->Dock=DockStyle::Fill;
//m_gcMainPanel->Controls->Add(gcLabel);
KidBaseCtrl^ gcCtrl = gcnew KidBaseCtrl;
gcCtrl->Dock=DockStyle::Fill;
m_gcMainPanel->Controls->Add(gcCtrl);
m_bLoadMainPanel=true;
}
RECT rect;
this->GetClientRect(&rect);
::MoveWindow((HWND)m_gcMainPanel->Handle.ToInt32(),0,0,rect.right,rect.bottom,TRUE);
}
}
| [
"littles1010@sina.cn"
] | littles1010@sina.cn |
1ea391bb4b8504f79665b21559ece7672514e5bb | 137946bff2f27e0dbc272daae448791eda536839 | /DirectX/DirectX/Texture2D.h | 7a91c9911479860708bdaf4299bd35e206c20153 | [] | no_license | soelusoelu/20_10_kojin | 71d494330fa9b260d08fbd0c6b21f44158c2d505 | 051ee216288134e43f5f17f6505d9fccd8a53ef7 | refs/heads/master | 2023-01-30T20:25:10.147749 | 2020-12-07T01:29:18 | 2020-12-07T01:29:18 | 306,239,246 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 678 | h | #pragma once
#include "SubResourceDesc.h"
#include "Texture2DDesc.h"
#include "../System/SystemInclude.h"
class Texture2D {
public:
Texture2D(const Texture2DDesc& desc, const SubResourceDesc* data = nullptr);
Texture2D(Microsoft::WRL::ComPtr<ID3D11Texture2D> texture2D);
~Texture2D();
ID3D11Texture2D* texture2D() const;
const Texture2DDesc& desc() const;
private:
D3D11_TEXTURE2D_DESC toTexture2DDesc(const Texture2DDesc& desc) const;
//コピー禁止
Texture2D(const Texture2D&) = delete;
Texture2D& operator=(const Texture2D&) = delete;
private:
Microsoft::WRL::ComPtr<ID3D11Texture2D> mTexture2D;
Texture2DDesc mDesc;
};
| [
"llmn.0419@gmail.com"
] | llmn.0419@gmail.com |
6bb0fba363083488b21cbc9f0f72b6adbd733b76 | 18d59285ccd65751b14967d2cae9284afa8c213c | /Include/Components/RootComponent.hpp | 765219e5353f3a7e45bdecb780bd902c0796cc01 | [] | no_license | rarosu/BTH-Gomoku | 801319616b01cfa0b7175f16eb1ce472360e2aca | dc1d7be81dcbee0a5e7097f15f0ed401ec4d527d | refs/heads/master | 2021-01-01T16:05:35.385640 | 2014-01-04T19:30:19 | 2014-01-04T19:30:19 | 3,273,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | hpp | #ifndef ROOTCOMPONENT_HPP
#define ROOTCOMPONENT_HPP
#include "WinInclude.hpp"
#include "ComponentGroup.hpp"
#include "Console.hpp"
namespace Components
{
class RootComponent : public ComponentGroup
{
public:
RootComponent(ID3D10Device* device, int width, int height);
virtual ~RootComponent();
void Refresh(GameTime gameTime, const InputState& currInputState, const InputState& prevInputState);
void Draw();
void SetFocusedComponent(Component* component);
bool HasFocus();
static Console& GetConsole();
protected:
//D3DXVECTOR2 GetPosition() const;
private:
static RootComponent* sInstance;
Console* mConsole;
};
}
#endif | [
"kim.restad@hotmail.com"
] | kim.restad@hotmail.com |
630c86ed792c5eb57a9c084c1693de8823ce0859 | 5ad92e61fd0b5b238a95b922e111cbae79584e1b | /examples/example_cpp_15_puzzle_demo/src/PuzzleFramework/PuzzleFramework.h | a133f767e2abb2d2590538811d4c24b61de1df64 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | hsjsjsjdjwksks/Mengine | f44022d19411ff67514de5efe2ef166a63189b85 | 41c659ccf76236ee8cb206b8aa6849aa83f8ca26 | refs/heads/master | 2022-12-16T23:29:25.644129 | 2020-09-15T22:25:25 | 2020-09-15T22:25:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 433 | h | #pragma once
#include "Kernel/FrameworkBase.h"
#include "Kernel/Observable.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
class PuzzleFramework
: public FrameworkBase
{
public:
PuzzleFramework();
~PuzzleFramework() override;
protected:
bool _initializeFramework() override;
void _finalizeFramework() override;
};
}
| [
"lenin@syneforge.com"
] | lenin@syneforge.com |
589f1fccd16ed92f5329a2dd627c5b6beaa4f63a | b1dec29bc53b7695e1ad8ea644acd6fd087f3c89 | /labs/lab5/app.cpp | fcf306e150965a33ae1fbda2a61b819855a55008 | [] | no_license | tbieker/CS260 | fcb224fb061962c26dd571b0754bbaf8b882e422 | d3847a38e96651af8411a342b5a0a5b7ba76c882 | refs/heads/master | 2021-01-17T12:58:14.071880 | 2016-06-13T19:52:20 | 2016-06-13T19:52:20 | 56,574,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,105 | cpp | #include <iostream>
#include "clist.h"
using namespace std;
#pragma GCC diagnostic ignored "-Wunused-variable"
int main()
{
node* head{nullptr};
/* Builds a circular linked list with a random number of nodes
*containing randomly-chosen numbers.
*/
build(head);
display(head);
// PUT YOUR CODE HERE to call the functions assigned,
// and print out the results. For example,
//
// cout << "iterative sum: " << sum(head) << endl;
//
// The code for your functions should be in clist.cpp.
cout << "Iterative count: " << count(head) << endl;
cout << "Recursive count: " << countR(head) << endl;
cout << "Iterative sum: " << sum(head) << endl;
cout << "Recursive sum: " << sumR(head) << endl;
// When called the 2nd time, this also prints the total
// of the numbers in the nodes.
display(head);
int nNodesFreed{0};
node* n{head};
node* temp;
while( n != head || ! nNodesFreed) {
temp = n->next;
delete n;
n = temp;
nNodesFreed++;
}
cout << "# nodes freed: " << nNodesFreed << endl;
//destroy(head);
return 0;
}
| [
"tyler.bieker@gmail.com"
] | tyler.bieker@gmail.com |
e815bbdf40961b8f634e4129f9a00b0f9d1f982c | 9033695d5861ca41126c8e90021f01249ab7b952 | /tile.h | d98273487c5ff036cd98a5b8d75268b005fe3212 | [] | no_license | evanskiev/Chess | c75cc7353f783de85495b17f8a0e076639ee1c22 | 30c0954e6a6112e10d4845f8757095f3031fe6a5 | refs/heads/master | 2021-01-10T20:38:26.059697 | 2015-07-22T19:50:12 | 2015-07-22T19:50:12 | 39,251,526 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 615 | h | #ifndef TILE_H
#define TILE_H
#include "chessfigure.h"
#include <QLabel>
#include <QMouseEvent>
#include <QDebug>
class Tile : public QLabel
{
private:
int tileColor;
int row;
int col;
public:
Tile(QWidget* pParent=0, Qt::WindowFlags f=0);
ChessFigure *figure;
void drawTile();
void drawFigure();
void setFigure(ChessFigure *newFigure);
void mousePressEvent(QMouseEvent *event);
void validation(Tile *tile);
void setTileColor(int value);
int getRow() const;
int getCol() const;
void setRow(int value);
void setCol(int value);
};
#endif // TILE_H
| [
"evanskiev@gmail.com"
] | evanskiev@gmail.com |
447339b39f3e6b5aa434fcaf507316b069e420af | 6b8fff0eeb75ad266af0ec2b9e9aaf28462c2a73 | /Sapi_Dataset/Data/user8/labor9/feladat1/person.h | aade4282c7f7928a749fa0406ec29d53f721ab49 | [] | no_license | kotunde/SourceFileAnalyzer_featureSearch_and_classification | 030ab8e39dd79bcc029b38d68760c6366d425df5 | 9a3467e6aae5455142bc7a5805787f9b17112d17 | refs/heads/master | 2020-09-22T04:04:41.722623 | 2019-12-07T11:59:06 | 2019-12-07T11:59:06 | 225,040,703 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 388 | h | #ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED
#include <iostream>
using namespace std;
class Szemely
{
protected:
string vezetekNev;
string keresztNev;
int szuletesiEv;
public:
Szemely(string, string, int);
void virtual print(ostream&) const;
friend ostream& operator<<(ostream &os, const Szemely& sz);
};
#endif // PERSON_H_INCLUDED
| [
"tundekoncsard3566@gmail.com"
] | tundekoncsard3566@gmail.com |
d3e18dc2f2b662393c5b17b938872fc5c5a2a739 | e4d601b0750bd9dcc0e580f1f765f343855e6f7a | /kaldi-wangke/src/chain/chain-den-graph.h | b2510651f39267c3bd325c6ad9ebd5699b175386 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | PeiwenWu/Adaptation-Interspeech18 | 01b426cd6d6a2d7a896aacaf4ad01eb3251151f7 | 576206abf8d1305e4a86891868ad97ddfb2bbf84 | refs/heads/master | 2021-03-03T04:16:43.146100 | 2019-11-25T05:44:27 | 2019-11-25T05:44:27 | 245,930,967 | 1 | 0 | MIT | 2020-03-09T02:57:58 | 2020-03-09T02:57:57 | null | UTF-8 | C++ | false | false | 7,208 | h | // chain/chain-den-graph.h
// Copyright 2015 Johns Hopkins University (Author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#ifndef KALDI_CHAIN_CHAIN_DEN_GRAPH_H_
#define KALDI_CHAIN_CHAIN_DEN_GRAPH_H_
#include <vector>
#include <map>
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "fstext/fstext-lib.h"
#include "tree/context-dep.h"
#include "lat/kaldi-lattice.h"
#include "matrix/kaldi-matrix.h"
#include "chain/chain-datastruct.h"
#include "hmm/transition-model.h"
#include "cudamatrix/cu-matrix.h"
#include "cudamatrix/cu-vector.h"
#include "cudamatrix/cu-array.h"
namespace kaldi {
namespace chain {
/** This class is responsible for storing the FST that we use as the
'anti-model' or 'denominator-model', that models all possible phone
sequences (or most possible phone sequences, depending how we built it)..
It stores the FST in a format where we can access both the transitions out
of each state, and the transitions into each state.
This class supports both GPU and non-GPU operation, but is optimized for
GPU.
*/
class DenominatorGraph {
public:
// the number of states in the HMM.
int32 NumStates() const;
// the number of PDFs (the labels on the transitions are numbered from 0 to
// NumPdfs() - 1).
int32 NumPdfs() const { return num_pdfs_; }
DenominatorGraph();
// Initialize from epsilon-free acceptor FST with pdf-ids plus one as the
// labels. 'num_pdfs' is only needeed for checking.
DenominatorGraph(const fst::StdVectorFst &fst,
int32 num_pdfs);
// returns the pointer to the forward-transitions array, indexed by hmm-state,
// which will be on the GPU if we're using a GPU.
const Int32Pair *ForwardTransitions() const;
// returns the pointer to the backward-transitions array, indexed by
// hmm-state, which will be on the GPU if we're using a GPU.
const Int32Pair *BackwardTransitions() const;
// returns the array to the actual transitions (this is indexed by the ranges
// returned from the ForwardTransitions and BackwardTransitions arrays). The
// memory will be GPU memory if we are using a GPU.
const DenominatorGraphTransition *Transitions() const;
// returns the initial-probs of the HMM-states... note, these initial-probs
// don't mean initial at the start of the file, because we usually train on
// pieces of a file. They are approximate initial-probs obtained by running
// the HMM for a fixed number of time-steps (e.g. 100) and averaging the
// posteriors over those time-steps. The exact values won't be very critical.
// Note: we renormalize each HMM-state to sum to one before doing this.
const CuVector<BaseFloat> &InitialProbs() const;
// This function outputs a modifified version of the FST that was used to
// build this object, that has an initial-state with epsilon transitions to
// each state, with weight determined by initial_probs_; and has each original
// state being final with probability one (note: we remove epsilons). This is
// used in computing the 'penalty_logprob' of the Supervision objects, to
// ensure that the objective function is never positive, which makes it more
// easily interpretable. 'ifst' must be the same FST that was provided to the
// constructor of this object. [note: ifst and ofst may be the same object.]
// This function ensures that 'ofst' is ilabel sorted (which will be useful in
// composition).
void GetNormalizationFst(const fst::StdVectorFst &ifst,
fst::StdVectorFst *ofst);
// This function is only used in testing code.
void ScaleInitialProbs(BaseFloat s) { initial_probs_.Scale(s); }
// Use default copy constructor and assignment operator.
private:
// functions called from the constructor
void SetTransitions(const fst::StdVectorFst &fst, int32 num_pfds);
// work out the initial-probs. Note, there are no final-probs; we treat all
// states as final with probability one [we have a justification for this..
// assuming it's roughly a well-normalized HMM, this makes sense; note that we
// train on chunks, so the beginning and end of a chunk appear at arbitrary
// points in the sequence. At both beginning and end of the chunk, we limit
// ourselves to only those pdf-ids that were allowed in the numerator
// sequence.
void SetInitialProbs(const fst::StdVectorFst &fst);
// forward_transitions_ is an array, indexed by hmm-state index,
// of start and end indexes into the transition_ array, which
// give us the set of transitions out of this state.
CuArray<Int32Pair> forward_transitions_;
// backward_transitions_ is an array, indexed by hmm-state index,
// of start and end indexes into the transition_ array, which
// give us the set of transitions out of this state.
CuArray<Int32Pair> backward_transitions_;
// This stores the actual transitions.
CuArray<DenominatorGraphTransition> transitions_;
// The initial-probability of all states, used on the first frame of a
// sequence [although we also apply the constraint that on the first frame,
// only pdf-ids that were active on the 1st frame of the numerator, are
// active. Because in general sequences won't start at the start of files, we
// make this a generic probability distribution close to the limiting
// distribution of the HMM. This isn't too critical.
CuVector<BaseFloat> initial_probs_;
int32 num_pdfs_;
};
// Function that does acceptor minimization without weight pushing...
// this is useful when constructing the denominator graph.
void MinimizeAcceptorNoPush(fst::StdVectorFst *fst);
// Utility function used while building the graph. Converts
// transition-ids to pdf-ids plus one. Assumes 'fst'
// is an acceptor, but does not check this (only looks at its
// ilabels).
void MapFstToPdfIdsPlusOne(const TransitionModel &trans_model,
fst::StdVectorFst *fst);
// Starting from an acceptor on phones that represents some kind of compiled
// language model (with no disambiguation symbols), this funtion creates the
// denominator-graph. Note: there is similar code in chain-supervision.cc, when
// creating the supervision graph.
void CreateDenominatorFst(const ContextDependency &ctx_dep,
const TransitionModel &trans_model,
const fst::StdVectorFst &phone_lm,
fst::StdVectorFst *den_graph);
} // namespace chain
} // namespace kaldi
#endif // KALDI_CHAIN_CHAIN_DEN_GRAPH_H_
| [
"wangkenpu@foxmail.com"
] | wangkenpu@foxmail.com |
df8abc3db11e11997cb685c442157169bd062fba | ee4f338aebedc47b06bd08fd35eada5aa81c7a91 | /SDK/BZ_BP_ContainerPlayerDeathChest_classes.hpp | 47ddf44e0a44b08d0f24a9f07d6bc201fab10d76 | [] | no_license | Hengle/BlazingSails_SDK | 5cf1ff31e0ac314aa841d7b55d0409e3e659e488 | 8a70c90a01d65c6cbd25f3dfdd1a8262714d3a60 | refs/heads/master | 2023-03-17T11:11:09.896530 | 2020-01-28T19:46:17 | 2020-01-28T19:46:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,445 | hpp | #pragma once
// BlazingSails (Dumped by Hinnie) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_ContainerPlayerDeathChest.BP_ContainerPlayerDeathChest_C
// 0x000B (0x0449 - 0x043E)
class ABP_ContainerPlayerDeathChest_C : public ABP_ContainerBase_C
{
public:
unsigned char UnknownData00[0x2]; // 0x043E(0x0002) MISSED OFFSET
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0440(0x0008) (ZeroConstructor, Transient, DuplicateTransient)
bool EnableEmptyCheck; // 0x0448(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_ContainerPlayerDeathChest.BP_ContainerPlayerDeathChest_C");
return ptr;
}
void UserConstructionScript();
void ReceiveBeginPlay();
void ReceiveTick(float* DeltaSeconds);
void ExecuteUbergraph_BP_ContainerPlayerDeathChest(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"hsibma02@gmail.com"
] | hsibma02@gmail.com |
b73c006db5b315c2bb43c6f6de1601651974ea97 | 8d0c93e7c8611862a1c1dd400e148b34dfbd74ba | /src/governance-vote.cpp | 438b07cc038807aab9a4a1359af57ce42562d663 | [
"MIT"
] | permissive | CyberSensei1/MoonDEXCoin | 2acd4b94252705613410809ebe28b05a33f778f0 | 4fecb2d5544222b46d2093fddace74e24bfe325a | refs/heads/master | 2020-03-18T17:04:47.633236 | 2018-05-20T14:51:11 | 2018-05-20T14:51:11 | 135,004,975 | 0 | 1 | null | 2018-05-27T00:51:32 | 2018-05-27T00:51:31 | null | UTF-8 | C++ | false | false | 10,283 | cpp | // Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The MoonDEX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "darksend.h"
#include "governance-vote.h"
#include "masternodeman.h"
#include "util.h"
#include <boost/lexical_cast.hpp>
std::string CGovernanceVoting::ConvertOutcomeToString(vote_outcome_enum_t nOutcome)
{
switch(nOutcome)
{
case VOTE_OUTCOME_NONE:
return "NONE"; break;
case VOTE_OUTCOME_YES:
return "YES"; break;
case VOTE_OUTCOME_NO:
return "NO"; break;
case VOTE_OUTCOME_ABSTAIN:
return "ABSTAIN"; break;
}
return "error";
}
std::string CGovernanceVoting::ConvertSignalToString(vote_signal_enum_t nSignal)
{
string strReturn = "NONE";
switch(nSignal)
{
case VOTE_SIGNAL_NONE:
strReturn = "NONE";
break;
case VOTE_SIGNAL_FUNDING:
strReturn = "FUNDING";
break;
case VOTE_SIGNAL_VALID:
strReturn = "VALID";
break;
case VOTE_SIGNAL_DELETE:
strReturn = "DELETE";
break;
case VOTE_SIGNAL_ENDORSED:
strReturn = "ENDORSED";
break;
case VOTE_SIGNAL_NOOP1:
strReturn = "NOOP1";
break;
case VOTE_SIGNAL_NOOP2:
strReturn = "NOOP2";
break;
case VOTE_SIGNAL_NOOP3:
strReturn = "NOOP3";
break;
case VOTE_SIGNAL_NOOP4:
strReturn = "NOOP4";
break;
case VOTE_SIGNAL_NOOP5:
strReturn = "NOOP5";
break;
case VOTE_SIGNAL_NOOP6:
strReturn = "NOOP6";
break;
case VOTE_SIGNAL_NOOP7:
strReturn = "NOOP7";
break;
case VOTE_SIGNAL_NOOP8:
strReturn = "NOOP8";
break;
case VOTE_SIGNAL_NOOP9:
strReturn = "NOOP9";
break;
case VOTE_SIGNAL_NOOP10:
strReturn = "NOOP10";
break;
case VOTE_SIGNAL_NOOP11:
strReturn = "NOOP11";
break;
case VOTE_SIGNAL_CUSTOM1:
strReturn = "CUSTOM1";
break;
case VOTE_SIGNAL_CUSTOM2:
strReturn = "CUSTOM2";
break;
case VOTE_SIGNAL_CUSTOM3:
strReturn = "CUSTOM3";
break;
case VOTE_SIGNAL_CUSTOM4:
strReturn = "CUSTOM4";
break;
case VOTE_SIGNAL_CUSTOM5:
strReturn = "CUSTOM5";
break;
case VOTE_SIGNAL_CUSTOM6:
strReturn = "CUSTOM6";
break;
case VOTE_SIGNAL_CUSTOM7:
strReturn = "CUSTOM7";
break;
case VOTE_SIGNAL_CUSTOM8:
strReturn = "CUSTOM8";
break;
case VOTE_SIGNAL_CUSTOM9:
strReturn = "CUSTOM9";
break;
case VOTE_SIGNAL_CUSTOM10:
strReturn = "CUSTOM10";
break;
case VOTE_SIGNAL_CUSTOM11:
strReturn = "CUSTOM11";
break;
case VOTE_SIGNAL_CUSTOM12:
strReturn = "CUSTOM12";
break;
case VOTE_SIGNAL_CUSTOM13:
strReturn = "CUSTOM13";
break;
case VOTE_SIGNAL_CUSTOM14:
strReturn = "CUSTOM14";
break;
case VOTE_SIGNAL_CUSTOM15:
strReturn = "CUSTOM15";
break;
case VOTE_SIGNAL_CUSTOM16:
strReturn = "CUSTOM16";
break;
case VOTE_SIGNAL_CUSTOM17:
strReturn = "CUSTOM17";
break;
case VOTE_SIGNAL_CUSTOM18:
strReturn = "CUSTOM18";
break;
case VOTE_SIGNAL_CUSTOM19:
strReturn = "CUSTOM19";
break;
case VOTE_SIGNAL_CUSTOM20:
strReturn = "CUSTOM20";
break;
}
return strReturn;
}
vote_outcome_enum_t CGovernanceVoting::ConvertVoteOutcome(std::string strVoteOutcome)
{
vote_outcome_enum_t eVote = VOTE_OUTCOME_NONE;
if(strVoteOutcome == "yes") {
eVote = VOTE_OUTCOME_YES;
}
else if(strVoteOutcome == "no") {
eVote = VOTE_OUTCOME_NO;
}
else if(strVoteOutcome == "abstain") {
eVote = VOTE_OUTCOME_ABSTAIN;
}
return eVote;
}
vote_signal_enum_t CGovernanceVoting::ConvertVoteSignal(std::string strVoteSignal)
{
vote_signal_enum_t eSignal = VOTE_SIGNAL_NONE;
if(strVoteSignal == "funding") {
eSignal = VOTE_SIGNAL_FUNDING;
}
else if(strVoteSignal == "valid") {
eSignal = VOTE_SIGNAL_VALID;
}
if(strVoteSignal == "delete") {
eSignal = VOTE_SIGNAL_DELETE;
}
if(strVoteSignal == "endorsed") {
eSignal = VOTE_SIGNAL_ENDORSED;
}
if(eSignal != VOTE_SIGNAL_NONE) {
return eSignal;
}
// ID FIVE THROUGH CUSTOM_START ARE TO BE USED BY GOVERNANCE ENGINE / TRIGGER SYSTEM
// convert custom sentinel outcomes to integer and store
try {
int i = boost::lexical_cast<int>(strVoteSignal);
if(i < VOTE_SIGNAL_CUSTOM1 || i > VOTE_SIGNAL_CUSTOM20) {
eSignal = VOTE_SIGNAL_NONE;
}
else {
eSignal = vote_signal_enum_t(i);
}
}
catch(std::exception const & e)
{
std::ostringstream ostr;
ostr << "CGovernanceVote::ConvertVoteSignal: error : " << e.what() << std::endl;
LogPrintf(ostr.str().c_str());
}
return eSignal;
}
CGovernanceVote::CGovernanceVote()
: fValid(true),
fSynced(false),
nVoteSignal(int(VOTE_SIGNAL_NONE)),
vinMasternode(),
nParentHash(),
nVoteOutcome(int(VOTE_OUTCOME_NONE)),
nTime(0),
vchSig()
{}
CGovernanceVote::CGovernanceVote(CTxIn vinMasternodeIn, uint256 nParentHashIn, vote_signal_enum_t eVoteSignalIn, vote_outcome_enum_t eVoteOutcomeIn)
: fValid(true),
fSynced(false),
nVoteSignal(eVoteSignalIn),
vinMasternode(vinMasternodeIn),
nParentHash(nParentHashIn),
nVoteOutcome(eVoteOutcomeIn),
nTime(GetAdjustedTime()),
vchSig()
{}
void CGovernanceVote::Relay() const
{
CInv inv(MSG_GOVERNANCE_OBJECT_VOTE, GetHash());
RelayInv(inv, PROTOCOL_VERSION);
}
bool CGovernanceVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode)
{
// Choose coins to use
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
std::string strError;
std::string strMessage = vinMasternode.prevout.ToStringShort() + "|" + nParentHash.ToString() + "|" +
boost::lexical_cast<std::string>(nVoteSignal) + "|" + boost::lexical_cast<std::string>(nVoteOutcome) + "|" + boost::lexical_cast<std::string>(nTime);
if(!darkSendSigner.SignMessage(strMessage, vchSig, keyMasternode)) {
LogPrintf("CGovernanceVote::Sign -- SignMessage() failed\n");
return false;
}
if(!darkSendSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) {
LogPrintf("CGovernanceVote::Sign -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
return true;
}
bool CGovernanceVote::IsValid(bool fSignatureCheck) const
{
if(nTime > GetTime() + (60*60)) {
LogPrint("gobject", "CGovernanceVote::IsValid -- vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", GetHash().ToString(), nTime, GetTime() + (60*60));
return false;
}
// support up to 50 actions (implemented in sentinel)
if(nVoteSignal > MAX_SUPPORTED_VOTE_SIGNAL)
{
LogPrint("gobject", "CGovernanceVote::IsValid -- Client attempted to vote on invalid signal(%d) - %s\n", nVoteSignal, GetHash().ToString());
return false;
}
// 0=none, 1=yes, 2=no, 3=abstain. Beyond that reject votes
if(nVoteOutcome > 3)
{
LogPrint("gobject", "CGovernanceVote::IsValid -- Client attempted to vote on invalid outcome(%d) - %s\n", nVoteSignal, GetHash().ToString());
return false;
}
masternode_info_t infoMn = mnodeman.GetMasternodeInfo(vinMasternode);
if(!infoMn.fInfoValid) {
LogPrint("gobject", "CGovernanceVote::IsValid -- Unknown Masternode - %s\n", vinMasternode.prevout.ToStringShort());
return false;
}
if(!fSignatureCheck) return true;
std::string strError;
std::string strMessage = vinMasternode.prevout.ToStringShort() + "|" + nParentHash.ToString() + "|" +
boost::lexical_cast<std::string>(nVoteSignal) + "|" + boost::lexical_cast<std::string>(nVoteOutcome) + "|" + boost::lexical_cast<std::string>(nTime);
if(!darkSendSigner.VerifyMessage(infoMn.pubKeyMasternode, vchSig, strMessage, strError)) {
LogPrintf("CGovernanceVote::IsValid -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
return true;
}
bool operator==(const CGovernanceVote& vote1, const CGovernanceVote& vote2)
{
bool fResult = ((vote1.vinMasternode == vote2.vinMasternode) &&
(vote1.nParentHash == vote2.nParentHash) &&
(vote1.nVoteOutcome == vote2.nVoteOutcome) &&
(vote1.nVoteSignal == vote2.nVoteSignal) &&
(vote1.nTime == vote2.nTime));
return fResult;
}
bool operator<(const CGovernanceVote& vote1, const CGovernanceVote& vote2)
{
bool fResult = (vote1.vinMasternode < vote2.vinMasternode);
if(!fResult) {
return false;
}
fResult = (vote1.vinMasternode == vote2.vinMasternode);
fResult = fResult && (vote1.nParentHash < vote2.nParentHash);
if(!fResult) {
return false;
}
fResult = fResult && (vote1.nParentHash == vote2.nParentHash);
fResult = fResult && (vote1.nVoteOutcome < vote2.nVoteOutcome);
if(!fResult) {
return false;
}
fResult = fResult && (vote1.nVoteOutcome == vote2.nVoteOutcome);
fResult = fResult && (vote1.nVoteSignal == vote2.nVoteSignal);
if(!fResult) {
return false;
}
fResult = fResult && (vote1.nVoteSignal == vote2.nVoteSignal);
fResult = fResult && (vote1.nTime < vote2.nTime);
return fResult;
}
| [
""
] | |
9a54a53664584967b8497a9663c75ee64a610044 | 4e4be78caea501e1e85e34e52fb09c0f2895f265 | /example/src/ofApp.cpp | 16397088b7ef195ab7c2363243ceb9bfa640afc4 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | bakercp/ofxPlayer | e0380c755c27af2662c38d1e3026ab7623073ad1 | ebf7907c91276f91f07970cdd5d321fce71f4737 | refs/heads/master | 2021-01-21T04:43:39.091999 | 2018-03-12T03:45:20 | 2018-03-12T03:45:20 | 54,444,126 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 520 | cpp | //
// Copyright (c) 2014 Christopher Baker <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#include "ofApp.h"
void ofApp::setup()
{
ofSetFrameRate(30);
ofEnableAlphaBlending();
// ofx::SensorEventArgs::List events = ofx::SensorEventUtils::load(ofx::SensorEventArgs::TYPE_ROTATION_VECTOR, "Rotation.txt");
//
// ofx::PlayableBufferHandle<std::vector<ofx::SensorEventArgs> > handle(events);
}
void ofApp::draw()
{
ofBackgroundGradient(ofColor::white, ofColor::black);
}
| [
"me@christopherbaker.net"
] | me@christopherbaker.net |
9df8b0635800bf7a4472c6cf07472c9a280e65bc | 5ba136082ad709197ef98bf6a00ec71d3ab1e4bf | /VIVADO_GAUSS/vivado-library/Rozmycie_Gaussa/solution1/syn/systemc/filtr_Gauss_mac_muladd_6ns_8ns_14ns_15_1_1.h | 39071a2ac11a33691426741fb0cabc0308ac559a | [
"MIT"
] | permissive | asias96/HLS | 73455d47a244308be9b4e4fa4fd7fb6394eabc56 | 37af5a0698651b41d115300225fed279532f4ac9 | refs/heads/master | 2020-08-08T05:39:35.036722 | 2020-01-22T10:28:27 | 2020-01-22T10:30:27 | 213,733,814 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,344 | h | // ==============================================================
// File generated on Wed Jan 22 10:55:50 CET 2020
// Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC v2018.3 (64-bit)
// SW Build 2405991 on Thu Dec 6 23:36:41 MST 2018
// IP Build 2404404 on Fri Dec 7 01:43:56 MST 2018
// Copyright 1986-2018 Xilinx, Inc. All Rights Reserved.
// ==============================================================
#ifndef __filtr_Gauss_mac_muladd_6ns_8ns_14ns_15_1_1__HH__
#define __filtr_Gauss_mac_muladd_6ns_8ns_14ns_15_1_1__HH__
#include "simcore_mac_2.h"
#include <systemc>
template<
int ID,
int NUM_STAGE,
int din0_WIDTH,
int din1_WIDTH,
int din2_WIDTH,
int dout_WIDTH>
SC_MODULE(filtr_Gauss_mac_muladd_6ns_8ns_14ns_15_1_1) {
sc_core::sc_in< sc_dt::sc_lv<din0_WIDTH> > din0;
sc_core::sc_in< sc_dt::sc_lv<din1_WIDTH> > din1;
sc_core::sc_in< sc_dt::sc_lv<din2_WIDTH> > din2;
sc_core::sc_out< sc_dt::sc_lv<dout_WIDTH> > dout;
simcore_mac_2<ID, 1, din0_WIDTH, din1_WIDTH, din2_WIDTH, dout_WIDTH> simcore_mac_2_U;
SC_CTOR(filtr_Gauss_mac_muladd_6ns_8ns_14ns_15_1_1): simcore_mac_2_U ("simcore_mac_2_U") {
simcore_mac_2_U.din0(din0);
simcore_mac_2_U.din1(din1);
simcore_mac_2_U.din2(din2);
simcore_mac_2_U.dout(dout);
}
};
#endif //
| [
"astanisz7@o2.pl"
] | astanisz7@o2.pl |
258686b2a06cdfcdfc167c8a4fa831999fce191e | 8c57e2a76f0c125d379b068984cd2a47d5b46bcf | /Classes/Score.h | f0dd543749be3b8e6bb9c0055e588a34f44f4660 | [
"MIT"
] | permissive | richy486/InvaderR | 6cab31cd427d5ac8c8912c9b9030c89cc11602bd | 8ec02836a68eb61e2aa6c7c9bfbb92256ece7a0d | refs/heads/master | 2021-01-10T19:16:15.309004 | 2017-09-17T21:36:18 | 2017-09-17T21:36:18 | 4,476,426 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 892 | h | //
// Score.h
// Invader
//
// Created by Richard Adem on 30/12/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
// For storing score and updating the visual score.
#pragma once
#ifndef _SCORE_H_
#define _SCORE_H_
static const int s_scoreKill = 50;
class Score
{
public:
~Score();
static Score* GetInstance();
void Update(float seconds);
void Draw();
void AddToScore(int val);
void ResetScore();
int GetCurrentActualScore();
int GetVisualScore();
int GetHighScore();
bool CheckChangeHighScore(); // returns if there is a new high score.
private:
Score();
int m_currentActualScore; // this is the real score, as soon as you get points this is correct.
int m_visualScore; // this is the score that is displayed on screen, so it can count up and look nice.
int m_highScore;
void LoadHighScore();
void SaveHighScore();
};
#endif // _SCORE_H_ | [
"richy486@gmail.com"
] | richy486@gmail.com |
9849a3cf6e8f5ed0f3a1c90c00b156209c54e97a | 5c8a0d7752e7c37e207f28a7e03d96a5011f8d68 | /MapTweet/iOS/Classes/Native/System_Xml_U3CPrivateImplementationDetailsU3E_U24A1957337327.h | dd7e64574b0bc5eaf91681e8bc3dad82bb768e95 | [] | no_license | anothercookiecrumbles/ar_storytelling | 8119ed664c707790b58fbb0dcf75ccd8cf9a831b | 002f9b8d36a6f6918f2d2c27c46b893591997c39 | refs/heads/master | 2021-01-18T20:00:46.547573 | 2017-03-10T05:39:49 | 2017-03-10T05:39:49 | 84,522,882 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 617 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_ValueType3507792607.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <PrivateImplementationDetails>/$ArrayType$8
struct U24ArrayTypeU248_t1957337328
{
public:
union
{
struct
{
union
{
};
};
uint8_t U24ArrayTypeU248_t1957337328__padding[8];
};
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"priyanjana@mac.com"
] | priyanjana@mac.com |
fc30ade31f5c9e2a6f8f23db1643adb57fd7e909 | 31ac07ecd9225639bee0d08d00f037bd511e9552 | /externals/OCCTLib/inc/Quantity_LuminousExposition.hxx | df9e3cc88f44c0f3fe6f36f090a6f37f85ea4aea | [] | no_license | litao1009/SimpleRoom | 4520e0034e4f90b81b922657b27f201842e68e8e | 287de738c10b86ff8f61b15e3b8afdfedbcb2211 | refs/heads/master | 2021-01-20T19:56:39.507899 | 2016-07-29T08:01:57 | 2016-07-29T08:01:57 | 64,462,604 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _Quantity_LuminousExposition_HeaderFile
#define _Quantity_LuminousExposition_HeaderFile
#ifndef _Standard_Real_HeaderFile
#include <Standard_Real.hxx>
#endif
typedef Standard_Real Quantity_LuminousExposition;
#define Quantity_LuminousExposition_Type_() Standard_Real_Type_()
#endif
| [
"litao1009@gmail.com"
] | litao1009@gmail.com |
e1ac92f4afbf3cd740ccf3fc3e389ae7bb90e008 | 4ea6a61aef7ddd8785d75513a8ea73576f103d1e | /benchmarks/real-verification/inspircd-2.0.5/src/modules/m_sha256.cpp | 707853a49490865d27a64cb1a254b47a7db07264 | [] | no_license | probertool/Prober | 287190a03b6d6a40ba77295ccef132226f800420 | c75047af835ba7ddf60fb3f72f686ea4c56a08b5 | refs/heads/master | 2020-09-09T07:45:33.005153 | 2019-11-13T05:39:15 | 2019-11-13T05:39:15 | 221,385,993 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,616 | cpp | /* +------------------------------------+
* | Inspire Internet Relay Chat Daemon |
* +------------------------------------+
*
* InspIRCd: (C) 2002-2010 InspIRCd Development Team
* See: http://wiki.inspircd.org/Credits
*
* This program is free but copyrighted software; see
* the file COPYING for details.
*
* ---------------------------------------------------
*/
/* m_sha256 - Based on m_opersha256 written by Special <john@yarbbles.com>
* Modified and improved by Craig Edwards, December 2006.
*
*
* FIPS 180-2 SHA-224/256/384/512 implementation
* Last update: 05/23/2005
* Issue date: 04/30/2005
*
* Copyright (C) 2005 Olivier Gay <olivier.gay@a3.epfl.ch>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
*/
/* $ModDesc: Allows for SHA-256 encrypted oper passwords */
#include "inspircd.h"
#ifdef HAS_STDINT
#include <stdint.h>
#endif
#include "hash.h"
#ifndef HAS_STDINT
typedef unsigned int uint32_t;
#endif
#define SHA256_DIGEST_SIZE (256 / 8)
#define SHA256_BLOCK_SIZE (512 / 8)
/** An sha 256 context, used by m_opersha256
*/
class SHA256Context
{
public:
unsigned int tot_len;
unsigned int len;
unsigned char block[2 * SHA256_BLOCK_SIZE];
uint32_t h[8];
};
#define SHFR(x, n) (x >> n)
#define ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n)))
#define ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n)))
#define CH(x, y, z) ((x & y) ^ (~x & z))
#define MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z))
#define SHA256_F1(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
#define SHA256_F2(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
#define SHA256_F3(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHFR(x, 3))
#define SHA256_F4(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHFR(x, 10))
#define UNPACK32(x, str) \
{ \
*((str) + 3) = (uint8_t) ((x) ); \
*((str) + 2) = (uint8_t) ((x) >> 8); \
*((str) + 1) = (uint8_t) ((x) >> 16); \
*((str) + 0) = (uint8_t) ((x) >> 24); \
}
#define PACK32(str, x) \
{ \
*(x) = ((uint32_t) *((str) + 3) ) \
| ((uint32_t) *((str) + 2) << 8) \
| ((uint32_t) *((str) + 1) << 16) \
| ((uint32_t) *((str) + 0) << 24); \
}
/* Macros used for loops unrolling */
#define SHA256_SCR(i) \
{ \
w[i] = SHA256_F4(w[i - 2]) + w[i - 7] \
+ SHA256_F3(w[i - 15]) + w[i - 16]; \
}
const unsigned int sha256_h0[8] =
{
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
};
uint32_t sha256_k[64] =
{
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
class HashSHA256 : public HashProvider
{
void SHA256Init(SHA256Context *ctx, const unsigned int* ikey)
{
if (ikey)
{
for (int i = 0; i < 8; i++)
ctx->h[i] = ikey[i];
}
else
{
for (int i = 0; i < 8; i++)
ctx->h[i] = sha256_h0[i];
}
ctx->len = 0;
ctx->tot_len = 0;
}
void SHA256Transform(SHA256Context *ctx, unsigned char *message, unsigned int block_nb)
{
uint32_t w[64];
uint32_t wv[8];
unsigned char *sub_block;
for (unsigned int i = 1; i <= block_nb; i++)
{
int j;
sub_block = message + ((i - 1) << 6);
for (j = 0; j < 16; j++)
PACK32(&sub_block[j << 2], &w[j]);
for (j = 16; j < 64; j++)
SHA256_SCR(j);
for (j = 0; j < 8; j++)
wv[j] = ctx->h[j];
for (j = 0; j < 64; j++)
{
uint32_t t1 = wv[7] + SHA256_F2(wv[4]) + CH(wv[4], wv[5], wv[6]) + sha256_k[j] + w[j];
uint32_t t2 = SHA256_F1(wv[0]) + MAJ(wv[0], wv[1], wv[2]);
wv[7] = wv[6];
wv[6] = wv[5];
wv[5] = wv[4];
wv[4] = wv[3] + t1;
wv[3] = wv[2];
wv[2] = wv[1];
wv[1] = wv[0];
wv[0] = t1 + t2;
}
for (j = 0; j < 8; j++)
ctx->h[j] += wv[j];
}
}
void SHA256Update(SHA256Context *ctx, unsigned char *message, unsigned int len)
{
/*
* XXX here be dragons!
* After many hours of pouring over this, I think I've found the problem.
* When Special created our module from the reference one, he used:
*
* unsigned int rem_len = SHA256_BLOCK_SIZE - ctx->len;
*
* instead of the reference's version of:
*
* unsigned int tmp_len = SHA256_BLOCK_SIZE - ctx->len;
* unsigned int rem_len = len < tmp_len ? len : tmp_len;
*
* I've changed back to the reference version of this code, and it seems to work with no errors.
* So I'm inclined to believe this was the problem..
* -- w00t (January 06, 2008)
*/
unsigned int tmp_len = SHA256_BLOCK_SIZE - ctx->len;
unsigned int rem_len = len < tmp_len ? len : tmp_len;
memcpy(&ctx->block[ctx->len], message, rem_len);
if (ctx->len + len < SHA256_BLOCK_SIZE)
{
ctx->len += len;
return;
}
unsigned int new_len = len - rem_len;
unsigned int block_nb = new_len / SHA256_BLOCK_SIZE;
unsigned char *shifted_message = message + rem_len;
SHA256Transform(ctx, ctx->block, 1);
SHA256Transform(ctx, shifted_message, block_nb);
rem_len = new_len % SHA256_BLOCK_SIZE;
memcpy(ctx->block, &shifted_message[block_nb << 6],rem_len);
ctx->len = rem_len;
ctx->tot_len += (block_nb + 1) << 6;
}
void SHA256Final(SHA256Context *ctx, unsigned char *digest)
{
unsigned int block_nb = (1 + ((SHA256_BLOCK_SIZE - 9) < (ctx->len % SHA256_BLOCK_SIZE)));
unsigned int len_b = (ctx->tot_len + ctx->len) << 3;
unsigned int pm_len = block_nb << 6;
memset(ctx->block + ctx->len, 0, pm_len - ctx->len);
ctx->block[ctx->len] = 0x80;
UNPACK32(len_b, ctx->block + pm_len - 4);
SHA256Transform(ctx, ctx->block, block_nb);
for (int i = 0 ; i < 8; i++)
UNPACK32(ctx->h[i], &digest[i << 2]);
}
void SHA256(const char *src, unsigned char *dest, unsigned int len)
{
SHA256Context ctx;
SHA256Init(&ctx, NULL);
SHA256Update(&ctx, (unsigned char *)src, len);
SHA256Final(&ctx, dest);
}
public:
std::string sum(const std::string& data)
{
unsigned char bytes[SHA256_DIGEST_SIZE];
SHA256(data.data(), bytes, data.length());
return std::string((char*)bytes, SHA256_DIGEST_SIZE);
}
std::string sumIV(unsigned int* IV, const char* HexMap, const std::string &sdata)
{
return "";
}
HashSHA256(Module* parent) : HashProvider(parent, "hash/sha256", 32, 64) {}
};
class ModuleSHA256 : public Module
{
HashSHA256 sha;
public:
ModuleSHA256() : sha(this)
{
ServerInstance->Modules->AddService(sha);
}
Version GetVersion()
{
return Version("Implements SHA-256 hashing", VF_VENDOR);
}
};
MODULE_INIT(ModuleSHA256)
| [
"hongyuliu@salsa2.it.utsa.edu"
] | hongyuliu@salsa2.it.utsa.edu |
7cf1e07505f07b7b5ee80e1a0957d513615b286c | d9e54df30cbdfaeedc1b9a5a491e1307852e0c2b | /Utility/BaseSystem.h | ef8b0a45252a18545bf36bb8e0182964dee2617d | [] | no_license | FrancisVIA/Factory_Pattern | f7fed3791e8a5ce7b95c6f95559074a567142608 | 552c85da2c031caae72782df92b8b56716c948d0 | refs/heads/master | 2016-09-12T20:33:06.704604 | 2016-04-21T10:51:21 | 2016-04-21T10:51:21 | 56,034,289 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | h | #ifndef BASESYSTEM_H
#define BASESYSTEM_H
#include "stdafx.h"
#include <string>
class BaseSystem
{
public:
BaseSystem();
~BaseSystem();
bool Init();
int MainLoop();
protected:
void SetName(char* );
void SetGuid();
char guid_buf[128];
private:
MSG msg;
char system_name[256];
};
#endif | [
"FrancisSong@via.com.cn"
] | FrancisSong@via.com.cn |
da6cce0c31d0b6922d2d97fda927a747652201fc | 350b7ef6a1ec5ae62ac57a076d5d407a2cb568aa | /p37/p37_miyapy.cpp | abd41e52bedfa26b2be1e6ac3a5a52e97cbf748d | [] | no_license | illmaticindustries/ProConPractice | 7560862ac0297d1209466ef584780778c713ef42 | 646b9563dfb61d0f37eceeee9df77c0cebe286f9 | refs/heads/master | 2021-01-10T10:19:23.879217 | 2018-05-19T04:40:32 | 2018-05-19T04:40:32 | 44,866,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,290 | cpp | #include <stdio.h>
#include <queue>
using namespace std;
#define BUF_SIZE 10000
void print_maze(int n,int m, char *maze);
int n;
int m;
struct pos{
int x;
int y;
};
int main(void){
char maze[BUF_SIZE];
//input
printf("input n\r\n");
scanf("%d",&n);
printf("input m\r\n");
scanf("%d",&m);
printf("input maze\r\n");
for(int i=0;i<n;i++){
scanf("%s",maze+i*m);
}
print_maze(n,m,maze);
int Sx,Sy;//start
//search start
for(int i=0;i<n*m;i++){
if(maze[i]=='S'){
Sx = i%m;
Sy = i/m;
}
}
struct pos G;
//search goal
for(int i=0;i<n*m;i++){
if(maze[i]=='G'){
G.x = i%m;
G.y = i/m;
}
}
queue<struct pos> q1;
struct pos a;
a.x = Sx;a.y=Sy;
q1.push(a); //set start position
int count = 0;
int num = 0;//size of packman
int flag = 1;//loop flag
while(flag){
num = q1.size();
for(int i=0;i<num;i++){
struct pos p = q1.front();
if((p.x==G.x)&&(p.y==G.y)){
printf("%d\r\n",count);
flag = 0;//down flag
break;
}
maze[p.y*m+p.x]='#';
//check up
if((p.y>0)&&(maze[p.y*m+p.x-m]!='#')){
struct pos a;
a.x = p.x;
a.y= p.y-1;
q1.push(a);
}
//check left
if((p.x>0)&&(maze[p.y*m+p.x-1]!='#')){
struct pos a;
a.x = p.x-1;
a.y= p.y;
q1.push(a);
}
//check right
if((p.x<m)&&(maze[p.y*m+p.x+1]!='#')){
struct pos a;
a.x = p.x+1;
a.y= p.y;
q1.push(a);
}
//check down
if((p.y<n)&&(maze[p.y*m+p.x+m]!='#')){
struct pos a;
a.x = p.x;
a.y= p.y+1;
q1.push(a);
}
q1.pop();
}
count++;
}
}
void print_maze(int n,int m,char *maze){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
printf("%c",maze[m*i+j]);
}
printf("\r\n");
}
}
| [
"scotsdowneroad@gmail.com"
] | scotsdowneroad@gmail.com |
b588a7f323d5163e47e06d714b2f424be50a6b42 | f10437233ad240009685ec927bb47c654238e606 | /MatchGame/Engine/scene/SceneManager.cpp | c84a85668eaab6c0d21ca893d532344aa8c35578 | [] | no_license | xuan-yuan-frank/MatchGame | e8cab2dd55e5c2597896f96adf99f8945c123e29 | f875742fb0d7e1910ee372fd31162fe2f3697079 | refs/heads/master | 2023-02-07T09:24:02.327732 | 2016-09-22T11:16:18 | 2016-09-22T11:16:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,387 | cpp |
//#include <iostream>
#include <fstream>
#include <sstream>
#include "SceneManager.hpp"
#include "ScenePanel.hpp"
#include "../Font.hpp"
namespace XYGame
{
SceneManager::SceneManager()
{
}
SceneManager::~SceneManager()
{
for (ScenePanelContainer::iterator iter = mContainer.begin();
iter != mContainer.end();
++iter)
{
delete (*iter);
}
mContainer.clear();
}
void SceneManager::RenderScene()
{
for (ScenePanelContainer::const_iterator iter = mContainer.cbegin();
iter != mContainer.cend();
++iter)
{
(*iter)->Render();
}
}
int SceneManager::GetWidgetsCount() const
{
int count = 0;
for (ScenePanelContainer::const_iterator iter = mContainer.cbegin();
iter != mContainer.cend();
++iter)
{
count += (*iter)->GetWidgetsCount();
}
return count;
}
bool CompareScenePanel(ScenePanel* left, ScenePanel* right)
{
return left->GetPanelID() < right->GetPanelID();
}
ScenePanel* SceneManager::InternalGetScenePanel(int panelId)
{
ScenePanelContainer::iterator iter = mContainer.begin();
while (iter != mContainer.end() && (*iter)->GetPanelID() < panelId)
{
++iter;
}
if (iter != mContainer.end() && (*iter)->GetPanelID() == panelId)
{
return *iter;
}
else
{
ScenePanel* panel = new ScenePanel();
panel->SetPanelID(panelId);
mContainer.insert(iter, panel);
return panel;
}
}
const Font* SceneManager::LoadFont(int fontId, const std::string& glyphPath, std::shared_ptr<Texture> tex)
{
if (mFontMap.find(fontId) != mFontMap.end())
throw new std::runtime_error(std::string("Font exist"));
if (tex.get() == NULL)
throw new std::runtime_error(std::string("Font texture is NULL"));
std::ifstream fin(glyphPath.c_str());
std::string line;
std::vector<int> lineValues;
std::vector< std::vector<int> > glyphs;
while (std::getline(fin, line))
{
std::stringstream ss(line);
lineValues.clear();
int v = 0;
while (ss >> v)
{
lineValues.push_back(v);
if (ss.peek() == ',')
ss.ignore();
}
glyphs.push_back(lineValues);
}
mFontMap[fontId] = new Font(glyphs, tex);
return mFontMap[fontId];
}
void SceneManager::UnloadFont(int fontId)
{
std::map<int, const Font*>::iterator iter = mFontMap.find(fontId);
if (iter != mFontMap.end())
{
delete iter->second;
mFontMap.erase(iter);
}
}
const Font* SceneManager::GetFont(int fontId) const
{
std::map<int, const Font*>::const_iterator iter = mFontMap.find(fontId);
if (iter != mFontMap.end())
{
return iter->second;
}
return NULL;
}
}
| [
"felk2005@gmail.com"
] | felk2005@gmail.com |
1689159e1f5594e7f280a3284a737a87a89a511e | 1f11c82d96cbbfa32268f31337449d9a3b43ac69 | /example/aka_example2.cpp | 2f75622b673688c7905a580e90c4a184e74933c8 | [] | no_license | radekwyrwas/akalib | a59b436a2bc09b1ac3b76cd44155bbf39469153e | 7c816442f344efe5a95c56bed7cf7cb0e1b4a22c | refs/heads/master | 2021-01-23T13:42:06.988221 | 2014-07-30T19:46:27 | 2014-07-30T19:46:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,252 | cpp | /* -------------------------------------------------------------------------
* Copyright (c) 2013, Andrew Kalotay Associates. All rights reserved. *
This example code is provided to users of the AKA Library.
see usage() below
------------------------------------------------------------------------- */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
#ifdef _MSC_VER /* include implementation of getopts -- see end of file */
const char *optarg = NULL;
int optind = 0;
int getopt(int, char *const *, const char *);
#else
#include <unistd.h>
#endif
#include "akaapi.hpp"
#include "akaerrno.h"
using namespace AndrewKalotayAssociates;
/* forward declarations */
void usage();
bool msgs(Status *);
#define INSECS(x) ((double) (x) / CLOCKS_PER_SEC)
/* -----------------------------------------------------------------
Purpose: start here
Returns:
----------------------------------------------------------------- */
int
main(int argc, char *argv[])
{
/* user options */
int c;
int cnt;
double rate, coupon;
Date pvdate(2000, 01, 01);
bool quiet = false;
enum { FLAT, LINEAR, ASYM } ctype = FLAT;
Date mdate(2030, 01, 01);
double vol = 0;
bool bullet = false;
int days = 1;
bool fromoas = true; // go from oas to price
double quote = 0;
const char *keyfile = "./akalib.key";
/* timing variables */
clock_t start = 0;
bool timing = false;
while((c = getopt(argc, argv, "a:bc:d:fm:p:qT:tv:z"))!= EOF) {
switch(c) {
case 'a' :
keyfile = optarg;
break;
case 'b' :
bullet = true;
break;
case 'c' :
switch(tolower(*optarg)) {
case 'f' :
ctype = FLAT;
break;
case 'a' :
ctype = ASYM;
break;
case 'l' :
ctype = LINEAR;
break;
}
break;
case 'd' :
days = atoi(optarg);
break;
case 'f' :
// ignoring for campatibility with C example
break;
case 'm' :
mdate = Date(optarg, Date::MDY);
break;
case 'p' :
pvdate = Date(optarg, Date::MDY);
break;
case 'q' : /* get the OAS from a quoted price*/
fromoas = false;
quote = 100; /* use price of par */
break;
case 't' :
timing = true;
quiet = true;
break;
case 'v' :
vol = atof(optarg);
break;
case 'z':
quiet = true;
break;
default :
usage();
return 0;
break;
}
}
argc -= optind;
argv += optind;
if (argc == 0) {
usage();
return 1;
}
rate = atof(argv[0]);
if (argc > 1)
coupon = atof(argv[1]);
else
coupon = rate;
Initialization akareg(keyfile);
if (akareg.Error() > 0) {
fprintf(stderr, "ERROR: %s\n", akareg.ErrorString());
return akareg.Error();
}
InterestRateModel model;
if (!model.SetVolatility(vol))
printf("Warning: invalid volatility '%f', using 0\n", vol);
if (!model.SetRate(.5, rate)) {
printf("Warning: invalid input rate '%f', using 2%%\n", rate);
rate = 2;
model.SetRate(.5, rate);
}
if (ctype == LINEAR) {
model.SetRate(1, rate + .01);
model.SetRate(30, rate + .3);
}
else if (ctype == ASYM) {
double terms[] = { 1, 3, 5, 7, 10, 15, 30 };
for (unsigned int i = 0; i < sizeof(terms) / sizeof(terms[0]); i++)
model.SetRate(terms[i], rate + 2 * (1 - 1.0 /terms[i]));
}
if (quiet == false) {
printf("Making a par rate curve with %.2g volatility", vol);
printf(", %0.0f yr = %.2f%%", 1.0, model.GetRate(1));
printf(", %0.0f yr = %.2f%%", 30.0, model.GetRate(30));
}
if (timing)
start = clock();
model.Solve();
if (timing) {
start = clock() - start;
printf("Seconds to fit the base curve = %0.2f\n", INSECS(start));
}
if (!msgs(&model))
return model.Error();
/* make the bond */
if (quiet == false)
printf("\nMaking a 30 year %.10g%% bond maturing on %ld",
coupon, mdate.Libdate());
Date idate(mdate.YearOf() - 30, mdate.MonthOf(), mdate.DayOf());
Bond bond("example", idate, mdate, coupon);
if (!msgs(&bond))
return bond.Error();
if (!bullet) {
Date cdate(idate.YearOf() + 5, idate.MonthOf(), idate.DayOf());
if (quiet == false)
printf(" callable %ld at par", cdate.Libdate());
if (!bond.SetCall(cdate, 100))
printf("failed to add call at %ld\n", cdate.Libdate());
}
if (quiet == false)
printf("\n\n");
if (quiet == false) {
const char underline[] = "--------------------";
const char *fmt = "%10.10s %8.8s %8.8s %8.8s %8.8s %8.8s";
printf(fmt, "pvdate ", fromoas ? "price" : "oas",
"accrued", "optval", "duration", "convex.");
printf("\n");
printf(fmt, underline, underline, underline,
underline, underline, underline);
printf("\n");
}
Value value(bond, model, pvdate);
if (!msgs(&value))
return value.Error();
/* loop through pvdates */
start = clock();
for (cnt = 0; pvdate < mdate && cnt < days; pvdate += 1, cnt++) {
if (cnt > 0) {
value.Reset(bond, pvdate);
if (!msgs(&value))
break;
}
double oas = fromoas ? quote : value.OAS(quote);
double price = fromoas ? value.Price(quote) : quote;
if (!msgs(&value) || oas == Value::BadValue || price == Value::BadValue)
break;
if (quiet == false) {
Duration duration = value.EffectiveDuration(oas);
printf("%02d/%02d/%04d %8.3f %8.3f %8.3f %8.3f %8.3f",
pvdate.MonthOf(), pvdate.DayOf(), pvdate.YearOf(),
fromoas ? price : oas,
value.Accrued(), value.OptionValue(oas),
duration.duration, duration.convexity);
printf("\n");
}
}
if (timing)
printf("\nSeconds to value the bond for %d pvdates = %0.2f\n",
cnt, INSECS(clock() - start));
return 0;
}
/* -----------------------------------------------------------------
Purpose: display usage messate
Returns: nothing
----------------------------------------------------------------- */
void
usage()
{
printf("Purpose: value a 30 year bond\n");
printf("Usage: [FLAGS] <discount-rate> [<coupon> : defaults to rate]\n");
printf(
"\nFlags:\n"
"\t-a key-file -- load akalib key from file, default ./akalib.key\n"
"\t-b -- bond is bullet bond\n");
printf(
"\t-c <curve-type> -- make the curve be:\n"
"\t\tflat -- same rate (default)\n"
"\t\tlinear -- grow linearly (slowly)\n"
"\t\tasymptotic -- grow (quickly) but level off\n");
printf(
"\t-d <cnt> -- set number of pvdates to value (default 1)\n"
"\t-m <mdate> -- set bond maturity date, default 1/1/2030\n"
"\t-p <pvdate> -- set initial pvdate to value, default bond dated date\n");
printf(
"\t-q -- use price of 100 as quote, default use oas of zero\n"
"\t-T <arg> -- set tax rates as: income[,short[,long[,superlong]]]\n"
"\t-t -- display timings\n"
"\t-v <vol> -- set curve volatility, default zero\n"
"\t-z -- silent mode, no output, for timing\n");
printf("%s\n", Initialization::VersionString());
}
/* -----------------------------------------------------------------
Purpose: print warnings and errors, if any
Returns: true if no errors, else false
----------------------------------------------------------------- */
bool
msgs(Status *status)
{
for (int i = 0; i < status->WarningCount(); i++)
fprintf(stdout, "Warning: %2d \"%s\"\n",
status->Warning(i), status->WarningString(i));
if (status->Error() > 0)
fprintf(stdout, "%2d \"%s\"\n", status->Error(),
status->ErrorString());
return status->Error() == 0;
}
/* -----------------------------------------------------------------
Purpose: try and get the key from a file
Returns: success true/false
----------------------------------------------------------------- */
bool
readkey(const char *fname, long *key, char *uname, int namesize)
{
FILE *fp;
char linestr[200];
bool ret = false;
*key = 0;
*uname = '\0';
fp = fopen(fname, "r");
if (fp == NULL)
fprintf(stderr, "Error: unable to open akakey file %s\n", fname);
else if (fgets(linestr, sizeof(linestr), fp) == NULL ||
(*key = atol(linestr)) == 0)
fprintf(stderr, "Error: missing key line from akakey file %s\n",
fname);
else if (fgets(linestr, sizeof(linestr), fp) == NULL)
fprintf(stderr, "Error: missing user name line from akakey file %s\n",
fname);
else {
int i;
for (i = 0; i < namesize; i++)
if (linestr[i] == '\0' || linestr[i] == '\n' || linestr[i] == '\r')
break;
else
uname[i] = linestr[i];
uname[i] = '\0';
ret = i > 0;
if (!ret)
fprintf(stderr, "Error: empty user name line from akakey file %s\n",
fname);
}
if (fp != NULL) fclose(fp);
return ret;
}
#ifdef _MSC_VER
#include <string.h>
/* -----------------------------------------------------------------
Purpose: extremely simplified version of getopt for microsoft
Returns:
----------------------------------------------------------------- */
int
getopt (int argc, char *const *argv, const char *opts)
{
int c = EOF;
optind += 1;
optarg = NULL;
if (optind < argc && argv[optind][0] == '-') {
const char *opt = NULL;
c = argv[optind][1];
opt = strchr(opts, c);
if (opt) {
if (opt[1] == ':') {
if (optind < argc -1) {
optind++;
optarg = argv[optind];
}
else
c = '?';
}
}
else
c = '?';
}
return c;
}
#endif
| [
"keithalewis@live.com"
] | keithalewis@live.com |
d0d4cdb978be4760cb7720717bb8f76e6f9b50cc | 9cebad70e3983c5f6b46b87c7ee8bef265122ee4 | /SingularitiesToQuad/main.cpp | ba04d8cc77ae96c75d896c0517261faebcca63f5 | [] | no_license | bigwater01/SingularitiesToQuad | a4bb00e64fd99b4994817aeb87ce710327c2c4f6 | 0555bb475b61b514d3011d8b1bad6923e4101771 | refs/heads/master | 2022-04-03T07:59:19.789419 | 2020-01-07T16:15:20 | 2020-01-07T16:15:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | cpp | #include "SingularitiesToQuad.h"
int main(int argc, char* argv[])
{
if (argc < 2)
{
return -1;
}
string mesh_filename = string(argv[1]);
string cut_filename = string(argv[2]);
string output_filename;
if (argc == 4)
output_filename = string(argv[3]);
else
{
auto pos = mesh_filename.find(".m");
if (pos == mesh_filename.length())
output_filename = mesh_filename + ".output.m";
else
output_filename = mesh_filename.substr(0, pos) + ".output.m";
}
SingularitiesToQuad* map = new SingularitiesToQuad();
map->readMesh(mesh_filename);
map->readCuts(cut_filename);
map->traceAllComponents();
map->writeMesh(output_filename);
return 0;
} | [
"bigwater01@gmail.com"
] | bigwater01@gmail.com |
a341acdc0d4f77d75028d2e60bde9bc40a1c7f4b | 2b6fe987b3ca2343781f21bb7dc11ba0980ad080 | /S2CBench_v1.1/fft/main.cpp | 682488e01fd905c3ed02d3f6ca4ada7e54b00cf5 | [] | no_license | campkeith/s2cbench | fe8323e87b5d00d1482853f57f8a09064d2dcdf5 | 16372abe53ed3b4bde9f97151766898e94c9024f | refs/heads/master | 2021-01-10T13:27:21.959102 | 2015-05-29T18:04:47 | 2015-05-29T18:04:47 | 36,332,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,967 | cpp | //========================================================================================
//
// File Name : main.cpp
// Description : Testbench for FFT
// Release Date : 16/07/2013
// Author : PolyU DARC Lab
// Benjamin Carrion Schafer, Anushree Mahapatra
//
// Revision History
//---------------------------------------------------------------------------------------
// Date Version Author Description
//----------------------------------------------------------------------------------------
//16/07/2013 1.0 PolyU DARC Lab Main FFT testbench top module
//
// g++ -o fft.exe main.cpp tb_fft.cpp fft.cpp -I$SYSTEMC_HOME/include -L$SYSTEMC_HOME/lib -lsystemc -lm
//=======================================================================================
#include "fft.h"
#include "tb_fft.h"
int sc_main(int argc, char** argv)
{
sc_clock clk("clk", 25, SC_NS, 0.5, 12.5, SC_NS, true);
sc_signal<bool> rst;
sc_signal<sc_fixed<32,16, SC_TRN, SC_WRAP> > in_real;
sc_signal<sc_fixed<32,16, SC_TRN, SC_WRAP> > in_imag;
sc_signal<sc_fixed<32,16, SC_TRN, SC_WRAP> > out_real;
sc_signal<sc_fixed<32,16, SC_TRN, SC_WRAP> > out_imag;
sc_signal<bool> data_valid;
sc_signal<bool> data_ack;
sc_signal<bool> data_req;
sc_signal<bool> data_ready;
fft u_FFT("FFT");
test_fft test("test_FFT");
//connect to bubble sort
u_FFT.clk( clk );
u_FFT.rst( rst );
u_FFT.in_real( in_real);
u_FFT.in_imag( in_imag);
u_FFT.data_valid( data_valid );
u_FFT.data_ack( data_ack );
u_FFT.out_real( out_real);
u_FFT.out_imag( out_imag);
u_FFT.data_req( data_req);
u_FFT.data_ready( data_ready);
// connect to test bench
test.clk( clk );
test.rst( rst );
test.in_real( in_real);
test.in_imag( in_imag);
test.data_valid( data_valid );
test.data_ack( data_ack );
test.out_real( out_real);
test.out_imag( out_imag);
test.data_req( data_req);
test.data_ready( data_ready);
#ifdef WAVE_DUMP
// Trace files
sc_trace_file* trace_file = sc_create_vcd_trace_file("trace_behav");
// Top level signals
sc_trace(trace_file, clk , "clk");
sc_trace(trace_file, rst , "rst");
sc_trace(trace_file, in_real , "in_real");
sc_trace(trace_file, in_imag , "in_imag");
sc_trace(trace_file, data_valid , "data_valid");
sc_trace(trace_file, data_ack , "data_ack");
sc_trace(trace_file, out_real , "out_real");
sc_trace(trace_file, out_imag , "out_imag");
sc_trace(trace_file, data_req , "data_req");
sc_trace(trace_file, data_ready , "data_ready");
#endif // End WAVE_DUMP
sc_start( 25, SC_NS );
rst.write(0);
sc_start( 25, SC_NS );
rst.write(1);
sc_start();
#ifdef WAVE_DUMP
sc_close_vcd_trace_file(trace_file);
#endif
return 0;
};
| [
"b.carrionschafer@polyu.edu.hk"
] | b.carrionschafer@polyu.edu.hk |
ca53100c53fd7f910dcef800df0a34f23d9b20ac | 2b2c30622c94101cf4733fa2151a8eb3a4e69815 | /RobotArm/RobotArmCPP/3rdinterpolate.h | e1467b5b2fffd2479b57a3183888ae7737a65a90 | [] | no_license | wxqwuxiangqian/RobotArm | 8fb0e3de360597225c8b02d689524b23e1efe9c8 | 5b54bb1c792b5ace178ea219fcdd9c1fae238805 | refs/heads/master | 2021-09-06T01:44:27.308650 | 2018-02-01T10:52:48 | 2018-02-01T10:52:48 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,693 | h | /*
* 3rdinterpolate.h
* 机械臂 插补
* Created on: 2018-1-18
* Author: Leo
*/
#pragma once
//#include <math.h>
#include <string.h>
//#include <iostream>
enum ProfileType // 枚举类型
{
unDefine, // 未指定类型
polynomial_3rd_T, // 3次多项式
};
// 1、接口类定义
class R_INTERP_BASE
{
public:
R_INTERP_BASE(){ };
~R_INTERP_BASE(){ };
// returns the current profile type
virtual ProfileType profileType() const = 0;
/// returns true if all time intervals are non negative
/// and all pos vel acc values are inside the limits.
virtual bool isValidMovement() const = 0;
/// get total duration 持续时间 of the trajectory.
virtual double getDuration() const = 0;
/// get the position, velocity and acceleration at passed time >= 0
virtual double pos(double t) const = 0;
virtual double vel(double t) const = 0;
virtual double acc(double t) const = 0;
virtual double jerk(double t) const { return 0;} //加速度变化率
// get the maximum velocity acceleration and jerk at of the profile
virtual double max_vel() const = 0;
virtual double max_acc() const = 0;
virtual double max_jerk() const = 0;
// scale 测量 a planned profile 外形 to a longer duration 持续时间
virtual double scaleToDuration(double newDuration){ return newDuration; };
};
// 2、3次多项式类定义
class Polynomial:public R_INTERP_BASE
{
public:
Polynomial()
{
// _plannedProfile = false;
}
~Polynomial()
{
//delete[] Coefficient系数;
};
virtual double getDuration() const;
virtual double pos(double t) const;
virtual double vel(double t) const;
virtual double acc(double t) const;
virtual double jerk(double t) const;
virtual bool isValidMovement() const;
virtual double scaleToDuration(double newDuration);
virtual ProfileType profileType()const{ return _pType;}
virtual double max_vel() const;
virtual double max_acc() const;
virtual double max_jerk() const;
// 定时
void plan3rdProfileT(double t0, double tf, double p0, double pf, double v0, double vf);
//返回多项式参数
void Show_coefficient(double* coe);
private:
double _x[2];
double _v[2]; // ?[0] is start condition, ?[3] is end condition.
double _t[2];
double _a[2];
ProfileType _pType; // 3rd or 5th polynomial
bool _plannedProfile; // flag indication whether a profile was computed
double _coefficient[6]; // Coefficients of the polynomial _coefficient[0]- _coefficient[5] 分别代表5次-0次
};
// 3、通用插补类定义——扩展算法接口
class R_INTERP
{
public:
// constructor
R_INTERP()
{
_pType = unDefine;
_tStart = 0.0;
_tTerminal = 0.0;
_pStart = 0.0;
_pTarget = 0.0;
_vStart = 0.0;
_vTarget = 0.0;
_aStart = 0.0;
_aTarget = 0.0;
_v_limit = 0.0;
_a_limit = 0.0;
_j_limit = 0.0;
_polynomial = nullptr;
_pCurProfileType = nullptr;
}
// destructor
~R_INTERP()
{
_polynomial = nullptr;
_pCurProfileType = nullptr;
}
// set limit values for movement parameters
void setLimit (double vel_Limit, double acc_Limit, double jerk_Limit)
{_v_limit = vel_Limit;_a_limit = acc_Limit;_j_limit = jerk_Limit;}
void setLimit (double vel_Limit, double acc_Limit)
{setLimit (vel_Limit, acc_Limit, acc_Limit*3.0);}
void setLimit (double vel_Limit)
{setLimit (vel_Limit, vel_Limit*3.0);}
// set target values for movement parameters
void setTarget(double pf, double vf, double af)
{_pTarget = pf; _vTarget = vf; _aTarget = af;}
void setTarget(double pf, double vf)
{setTarget(pf,vf,0.0);}
void setTarget(double pf)
{setTarget(pf,0.0,0.0);}
// set start values for movement parameters
void setStart(double p0,double v0,double a0)
{_pStart = p0; _vStart = v0; _aStart = a0;}
void setStart(double p0,double v0)
{setStart(p0,v0,0.0);}
void setStart(double p0)
{setStart(p0,0.0,0.0);}
// set the start time
void setStartTime(double t0){_tStart = t0;}
// for some profile type, like TRIGONOMETRIC,
// terminal time needed to be given
void setTargetTime(double tf){_tTerminal = tf;}
// set the profile type for movement parameters
void setProfileType(ProfileType profile)
{_pType = profile;}
// Returns the duration the full movement will need.
double getDuration() const {return _pCurProfileType->getDuration();}
// returns true if all time intervals are non negative
// and all pos vel acc values are inside the limits.
bool isValidMovement() const{return _pCurProfileType->isValidMovement();}
// Scales an already planned profile to a longer duration.
double scaleToDuration(double newDuration)
{return _pCurProfileType->scaleToDuration(newDuration);}
// get the position, velocity and acceleration at passed time >= 0
double pos(double t) const {return _pCurProfileType->pos(t);}
double vel(double t) const {return _pCurProfileType->vel(t);}
double acc(double t) const {return _pCurProfileType->acc(t);}
double jerk(double t) const {return _pCurProfileType->jerk(t);}
/// plan the time optimal profile
bool planProfile();
bool plan3rdProfileT(double t0, double tf, double p0,double pf, double v0, double vf);
private:
ProfileType _pType;
R_INTERP(const R_INTERP&);
Polynomial* _polynomial;
R_INTERP_BASE* _pCurProfileType;
double _pTarget; ///< target position
double _vTarget; ///< target velocity
double _aTarget; ///< target acceleration
double _pStart; ///< start position
double _vStart; ///< start velocity
double _aStart; ///< start acceleration
double _tStart; ///< start time
double _tTerminal; ///< terminal time
double _v_limit; ///< limit for velocity
double _a_limit; ///< limit for acceleration
double _j_limit; ///< limit for jerk
}; | [
"huipengly@gmail.com"
] | huipengly@gmail.com |
ae234e85d084594564b01070452e9db4327a27ca | b95b7a231f250f17688484de5592bccc3c439d3e | /Array/q82.cpp | e3404466fb95bde0ad8e8a0edb61fb3ddc14177d | [] | no_license | GuanyiLi-Craig/interview | 725e91a107bf11daf2120b5bd2e4d86f7b6804ea | 87269f436c92fc2ed34a2b51168836f5272b74f6 | refs/heads/master | 2021-08-30T03:59:26.590964 | 2017-12-15T23:49:08 | 2017-12-15T23:49:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,204 | cpp | /****************************************************************************************************
82. Remove Duplicates from Sorted List II
-----------------------------------------------------------------------------------------------------
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers
from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
****************************************************************************************************/
#include "problems\problems\Header.h"
namespace std
{
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head==NULL || head->next==NULL) return head;
ListNode* dphead = new ListNode(0);
dphead->next=head;
ListNode* cphead = dphead;
bool qdup = false;
while(head->next!=NULL)
{
if (head->val==head->next->val)
{
qdup=true;
head->next = head->next->next;
}
else
{
if (qdup)
{
head->val = head->next->val;
head->next=head->next->next;
qdup=false;
}
else
{
head=head->next;
cphead=cphead->next; // ***
}
}
}
if(qdup) cphead->next=NULL; // ***
return dphead->next;
}
};
}
/****************************************************************************************************
Note
the cphead is the one step slower than the head, so, if in the end there is duplication, the cphead
is used to set the NULL in the end.
****************************************************************************************************/ | [
"bitforce.studio@gmail.com"
] | bitforce.studio@gmail.com |
e38ddd8bfb53099dedc1c4e466f515f7b550b5a2 | b2abf6c2310b4df0a26df1c01410785a2668b8fb | /paper.h | 96da5289d28f1728b7ace3a40561401977863d7a | [] | no_license | 0TheFox0/MayaReports | 9635e91df3d1e1ab23885a57ea8e8cdb3c6843cf | 63084010853c2254ace396b225420d635e903b25 | refs/heads/master | 2016-09-16T02:41:15.952939 | 2013-09-05T17:42:38 | 2013-09-05T17:42:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,973 | h | #ifndef PAPER_H
#define PAPER_H
#include <QFileDialog>
#include <QApplication>
#include <QGraphicsRectItem>
#include <QPainter>
#include <QPrinter>
#include <QPdfWriter>
#include <QDomNode>
#include "detailsection.h"
#include "pageheadersection.h"
/*namespace Paper_size {
struct _size {
double width;
double heigth;
};
_size StandarSizes [];
}*/
class Paper :public QObject, public QGraphicsRectItem
{
Q_OBJECT
public:
explicit Paper(QGraphicsItem *parent = 0);
Q_PROPERTY(_Orientacion Orientacion READ Orientacion WRITE setOrientacion NOTIFY orientacionChanged)
Q_PROPERTY(double margenSuperior READ margenSuperior WRITE setmargenSuperior NOTIFY margenSuperiorChanged)
Q_PROPERTY(double margenInferior READ margenInferior WRITE setmargenInferior NOTIFY margenInferiroChanged)
Q_PROPERTY(double margenIzquierdo READ margenIzquierdo WRITE setmargenIzquierdo NOTIFY margenIzquierdoChanged)
Q_PROPERTY(double margenDerecho READ margenDerecho WRITE setmargenDerecho NOTIFY margenDerechoChanged)
Q_ENUMS (_Orientacion)
enum _Orientacion { Retrato , Apaisado };
Q_ENUMS (_Sizes)
enum _Sizes { A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,
B0,B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,
C5E,Comm10E,DLE,Executive,Folio,
Ledger,Legal,Letter,Tabloid,
Custom};
Q_ENUMS (itemType)
enum itemType { RoundRectIt , Label, Linea , CodeBarIt , Imagen, Campo , CampoRelacional};
_Orientacion Orientacion() const;
QRectF margin();
QRectF paper();
_Sizes StandartSize();
double margenSuperior() const;
double margenInferior() const;
double margenIzquierdo() const;
double margenDerecho() const;
void setSize(_Sizes siz, double w=0, double h=0, _Orientacion o=Retrato);
bool addSection(QString nombre ,Section::SectionType sectionType);
void removeSection(QString nombre);
void prepareItemInsert(itemType sectionType);
void stopInsertingItems();
bool parseXML(QString xml, QString &error);
int save(QString file );
QDomDocument preview();
QList<Section *> getSeccionPool() const;
void removeItems(QList<QGraphicsItem *> items);
void insertSection(Section* sec);
void subirSeccion(QString name);
void bajarSeccion(QString name);
void borrarSeccion(QString name);
void updatePaper();
static qreal cmToPx(double cm);
static qreal pxTocm(int px);
signals:
void orientacionChanged(_Orientacion arg);
void margenSuperiorChanged(double arg);
void margenInferiroChanged(double arg);
void margenIzquierdoChanged(double arg);
void margenDerechoChanged(double arg);
void itemInserted();
public slots:
void setOrientacion(_Orientacion arg);
void setMargen(double arg);
void setmargenSuperior(double arg);
void setmargenInferior(double arg);
void setmargenIzquierdo(double arg);
void setmargenDerecho(double arg);
void reCalculateSeccion(Section * = 0);
private slots:
void itemMoved(Container *);
private:
_Orientacion m_orientacion;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
void setSize(double w, double h);
_Sizes mySize;
double m_margenSuperior;
itemType _insertingType;
bool _inserting;
QPointF _insertingPoint;
QList<Section *> seccionPool;
void _insertSection(Section* sec);
QList<Container*> itemPool;
void insertRoundRect(Section *);
void insertLabel(Section *sec);
void insertLinea(Section *);
void insertCodeBar(Section *);
void insertImagen(Section *);
void insertCampo(Section *sec);
void insertCampoRelacional(Section *sec);
double m_margenInferiro;
double m_margenIzquierdo;
double m_margenDerecho;
};
#endif // PAPER_H
| [
"0thefox0@gmail.com"
] | 0thefox0@gmail.com |
8e9a66275d32a7abde5072a41790605e9985577e | 26483b49e5b5a86aa0338711bad5948945d5ba30 | /GGJ2015/Source/GGJ2015/GameMode/GGJ2015PlayerController.h | 54825d5a5dff477067bfbfa3cb8d0409b95cf5ba | [] | no_license | ZKShao/GGJ2015 | bac662729eb5132b6dc3c430283846f7b380f3c8 | d421f9cb7151eccdc1a5e07143db06eca4ff2c09 | refs/heads/master | 2021-01-25T07:27:58.842184 | 2015-01-24T14:41:06 | 2015-01-24T14:41:06 | 29,757,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | h | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/PlayerController.h"
#include "GGJ2015PlayerController.generated.h"
UCLASS()
class AGGJ2015PlayerController : public APlayerController
{
GENERATED_BODY()
public:
AGGJ2015PlayerController(const FObjectInitializer& ObjectInitializer);
protected:
/** True if the controlled character should navigate to the mouse cursor. */
uint32 bMoveToMouseCursor : 1;
// Begin PlayerController interface
virtual void PlayerTick(float DeltaTime) override;
virtual void SetupInputComponent() override;
// End PlayerController interface
/** Navigate player to the current mouse cursor location. */
void MoveToMouseCursor();
/** Navigate player to the current touch location. */
void MoveToTouchLocation(const ETouchIndex::Type FingerIndex, const FVector Location);
/** Navigate player to the given world location. */
void SetNewMoveDestination(const FVector DestLocation);
/** Input handlers for SetDestination action. */
void OnSetDestinationPressed();
void OnSetDestinationReleased();
};
| [
"zhikang.shao@gmail.com"
] | zhikang.shao@gmail.com |
ba26bcc35a242556149c9b08b5a582900ef11398 | 574b207e8608e288274a8450bcf9f3635fff38d6 | /13_greedy_prob/8_save_energy.cpp | 731894e8775b66c5eb47556005dccd0bbf49725f | [
"MIT"
] | permissive | anujjain5699/Coding-Ninjas-Competitive-1 | eabce470e790ddf209d23ef15f49133efb47176d | 791dfd800d5ca6def63da12ad286d49edda736a0 | refs/heads/master | 2023-07-16T02:58:38.538649 | 2021-09-02T11:35:48 | 2021-09-02T11:35:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | cpp | // https://www.codechef.com/problems/SVENGY
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ll n;
cin>>n;
// inputs
ll a[n];
for(ll i=0;i<n;i++){
cin>>a[i];
}
// logic
// for i select next j based on conditions given
// then make that j as i and move forward
// we have to include the first always
ll cost=0;
// ll i=0;
for(ll i=0;i<n-1;){
ll j=i+1;
for(;j<n-1;j++){
if(
(abs(a[i])>abs(a[j]))
||
((abs(a[i])==abs(a[j]))&&a[i]>0)
){
break;
}
}
cost += (j-i)*a[i] + ((j*j - i*i)*a[i]*a[i]);
i=j;
}
cout<<cost<<endl;
} | [
"yashsn2127@gmail.com"
] | yashsn2127@gmail.com |
e5c46db7cc6f7912727ab3c82cd9a1720550c8be | 43441cde04695a2bf62a7a5f7db4072aa0a6d366 | /vc60/ROBOT3D/POS.H | 839f16753042728210b43a3e626184d865d3b2ea | [] | no_license | crespo2014/cpp-lib | a8aaf4b963d3bf41f91db3832dd51bcf601d54ee | de6b653bf4c689fc5ceb3e9fe0f4fe47d79acf95 | refs/heads/master | 2020-12-24T15:23:32.396924 | 2016-03-21T11:53:37 | 2016-03-21T11:53:37 | 26,559,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 633 | h | // Pos.h: interface for the CPos class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_POS_H__B17EB9E1_6514_11D3_A767_0000E856599A__INCLUDED_)
#define AFX_POS_H__B17EB9E1_6514_11D3_A767_0000E856599A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class AFX_EXT_CLASS CPos
{
public:
virtual void Paint();
void GetPos(double* points);
void SetPos(double* points);
virtual LPCSTR GetMov();
CPos();
virtual ~CPos();
double m_Position[3];
private:
};
#endif // !defined(AFX_POS_H__B17EB9E1_6514_11D3_A767_0000E856599A__INCLUDED_)
| [
"lester.crespo.es@gmail.com"
] | lester.crespo.es@gmail.com |
18d41c2ef4e86441fd04701ec985cfb21adc08f5 | cd256d0c419c3bfd149c33d3900a297fd58fc6ff | /xls/data_structures/graph_contraction.h | 71c0f32c757acb6b9d1430ded29dbbfa6150f392 | [
"Apache-2.0"
] | permissive | QuantamHD/xls | c9df3ef8247bdba854a6f629bf41929f62e149aa | 98232a4711bfcd10099942d0b470377ed7fac32c | refs/heads/main | 2023-09-01T00:34:09.717833 | 2021-09-13T16:25:36 | 2021-09-13T16:26:21 | 406,078,990 | 0 | 0 | Apache-2.0 | 2021-09-13T18:05:37 | 2021-09-13T18:05:36 | null | UTF-8 | C++ | false | false | 10,907 | h | // Copyright 2021 The XLS Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef XLS_DATA_STRUCTURES_GRAPH_CONTRACTION_H_
#define XLS_DATA_STRUCTURES_GRAPH_CONTRACTION_H_
#include "absl/container/btree_set.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/types/optional.h"
#include "xls/common/logging/log_message.h"
#include "xls/common/logging/logging.h"
#include "xls/data_structures/union_find_map.h"
namespace xls {
template <typename K, typename V>
static absl::flat_hash_set<K> Keys(const absl::flat_hash_map<K, V>& map) {
absl::flat_hash_set<K> result;
for (const auto& pair : map) {
result.insert(pair.first);
}
return result;
}
// A graph data structure that supports vertex identification.
//
// Parameter `V` is the type of vertices, which is expected to be cheap to copy.
// Parameter `VW` is the type of vertex weights.
// Parameter `EW` is the type of edge weights.
template <typename V, typename VW, typename EW>
class GraphContraction {
public:
// Adds a vertex to the graph with the given `weight` associated to it.
void AddVertex(const V& vertex, const VW& weight) {
vertex_weights_.Insert(vertex, weight);
if (!out_edges_.Contains(vertex)) {
out_edges_.Insert(vertex, {});
}
if (!in_edges_.Contains(vertex)) {
in_edges_.Insert(vertex, {});
}
}
// Adds an edge from the given `source` to the given `target` with the given
// `weight` associated to it. If an edge with that source and target already
// exists, the given `weight` replaces the previous weight. Returns false if
// either the source or target is not a previously inserted vertex, and
// returns true otherwise. The graph is unchanged if false is returned.
bool AddEdge(const V& source, const V& target, const EW& weight) {
if (!(vertex_weights_.Contains(source) &&
vertex_weights_.Contains(target))) {
return false;
}
auto merge_map = [](absl::flat_hash_map<V, EW> a,
absl::flat_hash_map<V, EW> b) {
absl::flat_hash_map<V, EW> result;
result.merge(a);
result.merge(b);
return result;
};
out_edges_.Insert(source, {{target, weight}}, merge_map);
in_edges_.Insert(target, {{source, weight}}, merge_map);
return true;
}
// Identifies two vertices (a generalization of edge contraction). The vertex
// weights of the identified vertices are combined with `vw_merge`. If vertex
// identification results in multiple edges (a multigraph), the edge weights
// are combined using `ew_merge`. Returns false (and leaves the graph in an
// unmodified state) iff one of the given vertices is nonexistent.
//
// `vw_merge` should have a type compatible with
// `std::function<VW(const VW&, const VW&)>`.
//
// `ew_merge` should have a type compatible with
// `std::function<EW(const EW&, const EW&)>`.
template <typename FV, typename FE>
bool IdentifyVertices(const V& x, const V& y, FV vw_merge, FE ew_merge) {
if (!(vertex_weights_.Contains(x) && vertex_weights_.Contains(y))) {
return false;
}
if (vertex_weights_.Find(x)->first == vertex_weights_.Find(y)->first) {
return true;
}
vertex_weights_.Union(x, y, vw_merge);
V rep = vertex_weights_.Find(x).value().first; // y would give same result
auto merge_map = [&](const absl::flat_hash_map<V, EW>& a,
const absl::flat_hash_map<V, EW>& b) {
absl::flat_hash_map<V, EW> result;
for (const auto& [vertex, edge_weight] : a) {
V key = ((vertex == x) || (vertex == y)) ? rep : vertex;
result.insert_or_assign(key, result.contains(key)
? ew_merge(result.at(key), edge_weight)
: edge_weight);
}
for (const auto& [vertex, edge_weight] : b) {
V key = ((vertex == x) || (vertex == y)) ? rep : vertex;
result.insert_or_assign(key, result.contains(key)
? ew_merge(result.at(key), edge_weight)
: edge_weight);
}
return result;
};
absl::flat_hash_set<V> edges_out_of_x = Keys(out_edges_.Find(x)->second);
absl::flat_hash_set<V> edges_out_of_y = Keys(out_edges_.Find(y)->second);
absl::flat_hash_set<V> edges_into_x = Keys(in_edges_.Find(x)->second);
absl::flat_hash_set<V> edges_into_y = Keys(in_edges_.Find(y)->second);
out_edges_.Union(x, y, merge_map);
in_edges_.Union(x, y, merge_map);
// Given a vertex with at least one edge pointing into/out of `x` or `y`,
// patch those out edges up so that they point to/from `rep`.
auto patch_up_edges =
[&](const V& vertex, UnionFindMap<V, absl::flat_hash_map<V, EW>>* map) {
XLS_CHECK(map->Find(vertex).has_value())
<< "Inconsistency between in_edges_ and out_edges_ detected";
absl::flat_hash_map<V, EW>& edges = map->Find(vertex)->second;
if (edges.contains(x) && edges.contains(y)) {
EW weight = ew_merge(edges.at(x), edges.at(y));
edges.erase(x);
edges.erase(y);
edges.insert_or_assign(rep, weight);
} else if (edges.contains(x)) {
EW weight = edges.at(x);
edges.erase(x);
edges.insert_or_assign(rep, weight);
} else if (edges.contains(y)) {
EW weight = edges.at(y);
edges.erase(y);
edges.insert_or_assign(rep, weight);
} else {
XLS_CHECK(false)
<< "Inconsistency between in_edges_ and out_edges_ detected";
}
};
for (const V& source : edges_into_x) {
patch_up_edges(source, &out_edges_);
}
for (const V& source : edges_into_y) {
patch_up_edges(source, &out_edges_);
}
for (const V& target : edges_out_of_x) {
patch_up_edges(target, &in_edges_);
}
for (const V& target : edges_out_of_y) {
patch_up_edges(target, &in_edges_);
}
return true;
}
// Returns true iff the given vertex has previously been added to the graph
// using `AddVertex`.
bool Contains(const V& vertex) { return vertex_weights_.Contains(vertex); }
// Returns the set of vertices in the graph. If some set of vertices have been
// identified, an arbitrary element of that set will be present in this list.
absl::flat_hash_set<V> Vertices() {
return vertex_weights_.GetRepresentatives();
}
// Returns the representative of the equivalence class of identified vertices
// to which the given vertex belongs.
absl::optional<V> RepresentativeOf(const V& vertex) {
if (auto pair = vertex_weights_.Find(vertex)) {
return pair->first;
}
return absl::nullopt;
}
// Returns the edges that point out of the given vertex, and their weights.
absl::flat_hash_map<V, EW> EdgesOutOf(const V& vertex) {
if (auto pair = out_edges_.Find(vertex)) {
return pair->second;
}
return {};
}
// Returns the edges that point into the given vertex, and their weights.
absl::flat_hash_map<V, EW> EdgesInto(const V& vertex) {
if (auto pair = in_edges_.Find(vertex)) {
return pair->second;
}
return {};
}
// Returns the weight of the given vertex.
absl::optional<VW> WeightOf(const V& vertex) {
if (auto v = vertex_weights_.Find(vertex)) {
return v.value().second;
}
return absl::nullopt;
}
// Returns the weight of the given edge.
absl::optional<EW> WeightOf(const V& source, const V& target) {
absl::flat_hash_map<V, EW> edges = EdgesOutOf(source);
if (edges.contains(target)) {
return edges.at(target);
}
return absl::nullopt;
}
// Returns a topological sort of the nodes in the graph if the graph is
// acyclic, otherwise returns absl::nullopt.
absl::optional<std::vector<V>> TopologicalSort() {
std::vector<V> result;
// Kahn's algorithm
std::vector<V> active;
absl::flat_hash_map<V, int64_t> edge_count;
for (const V& vertex : Vertices()) {
edge_count[vertex] = EdgesInto(vertex).size();
if (edge_count.at(vertex) == 0) {
active.push_back(vertex);
}
}
while (!active.empty()) {
V source = active.back();
active.pop_back();
result.push_back(source);
for (const auto& [target, weight] : EdgesOutOf(source)) {
edge_count.at(target)--;
if (edge_count.at(target) == 0) {
active.push_back(target);
}
}
}
if (result.size() != Vertices().size()) {
return absl::nullopt;
}
return result;
}
// All-pairs longest paths in an acyclic graph.
// The length of a path is measured by the total vertex weight encountered
// along that path, using `operator+` and `std::max` on `VW`.
// The outer map key is the source of the path and the inner map key is the
// sink of the path. Those keys only exist if a path exists from that source
// to that sink.
// Returns absl::nullopt if the graph contains a cycle.
absl::optional<absl::flat_hash_map<V, absl::flat_hash_map<V, VW>>>
LongestNodePaths() {
absl::flat_hash_map<V, absl::flat_hash_map<V, VW>> result;
for (V vertex : Vertices()) {
// The graph must be acyclic, so the longest path from any vertex to
// itself has weight equal to the weight of that vertex.
result[vertex] = {{vertex, WeightOf(vertex).value()}};
}
if (absl::optional<std::vector<V>> topo = TopologicalSort()) {
for (const V& vertex : *topo) {
for (auto& [source, targets] : result) {
for (const auto& [pred, edge_weight] : EdgesInto(vertex)) {
if (targets.contains(pred)) {
VW new_weight = targets[pred] + WeightOf(vertex).value();
targets[vertex] = targets.contains(vertex)
? std::max(targets.at(vertex), new_weight)
: new_weight;
}
}
}
}
} else {
return absl::nullopt;
}
return result;
}
private:
UnionFindMap<V, VW> vertex_weights_;
UnionFindMap<V, absl::flat_hash_map<V, EW>> out_edges_;
UnionFindMap<V, absl::flat_hash_map<V, EW>> in_edges_;
};
} // namespace xls
#endif // XLS_DATA_STRUCTURES_GRAPH_CONTRACTION_H_
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
e047d81f2c0e61221159e4359fed317c84bab5ef | e325728fcc0a610cc1f72f41c1c0d947ee3bbcb6 | /deps/v8/src/wasm/wasm-heap.cc | b7d13b067fae2ee8f124ebb5ce165ddbf7695c6f | [
"BSD-3-Clause",
"bzip2-1.0.6",
"SunPro",
"LicenseRef-scancode-unicode",
"NAIST-2003",
"Zlib",
"LicenseRef-scancode-openssl",
"Artistic-2.0",
"ISC",
"MIT",
"NTP",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"ICU"
] | permissive | Let0s/node | e3c10c65ebe37b8eb4056a6365fa675292c5b7f9 | 5a1aeab2dbe22be141579181c3381831d516182c | refs/heads/master | 2020-05-24T07:38:54.995920 | 2018-01-05T22:24:10 | 2018-01-09T10:20:46 | 112,639,928 | 3 | 0 | NOASSERTION | 2019-12-12T11:14:58 | 2017-11-30T17:24:29 | JavaScript | UTF-8 | C++ | false | false | 3,197 | cc | // Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/wasm/wasm-heap.h"
namespace v8 {
namespace internal {
namespace wasm {
DisjointAllocationPool::DisjointAllocationPool(Address start, Address end) {
ranges_.push_back({start, end});
}
void DisjointAllocationPool::Merge(DisjointAllocationPool&& other) {
auto dest_it = ranges_.begin();
auto dest_end = ranges_.end();
for (auto src_it = other.ranges_.begin(), src_end = other.ranges_.end();
src_it != src_end;) {
if (dest_it == dest_end) {
// everything else coming from src will be inserted
// at the back of ranges_ from now on.
ranges_.push_back(*src_it);
++src_it;
continue;
}
// Before or adjacent to dest. Insert or merge, and advance
// just src.
if (dest_it->first >= src_it->second) {
if (dest_it->first == src_it->second) {
dest_it->first = src_it->first;
} else {
ranges_.insert(dest_it, {src_it->first, src_it->second});
}
++src_it;
continue;
}
// Src is strictly after dest. Skip over this dest.
if (dest_it->second < src_it->first) {
++dest_it;
continue;
}
// Src is adjacent from above. Merge and advance
// just src, because the next src, if any, is bound to be
// strictly above the newly-formed range.
DCHECK_EQ(dest_it->second, src_it->first);
dest_it->second = src_it->second;
++src_it;
// Now that we merged, maybe this new range is adjacent to
// the next. Since we assume src to have come from the
// same original memory pool, it follows that the next src
// must be above or adjacent to the new bubble.
auto next_dest = dest_it;
++next_dest;
if (next_dest != dest_end && dest_it->second == next_dest->first) {
dest_it->second = next_dest->second;
ranges_.erase(next_dest);
}
// src_it points now at the next, if any, src
DCHECK_IMPLIES(src_it != src_end, src_it->first >= dest_it->second);
}
}
DisjointAllocationPool DisjointAllocationPool::Extract(size_t size,
ExtractionMode mode) {
DisjointAllocationPool ret;
for (auto it = ranges_.begin(), end = ranges_.end(); it != end;) {
auto current = it;
++it;
DCHECK_LT(current->first, current->second);
size_t current_size = reinterpret_cast<size_t>(current->second) -
reinterpret_cast<size_t>(current->first);
if (size == current_size) {
ret.ranges_.push_back(*current);
ranges_.erase(current);
return ret;
}
if (size < current_size) {
ret.ranges_.push_back({current->first, current->first + size});
current->first += size;
DCHECK(current->first < current->second);
return ret;
}
if (mode != kContiguous) {
size -= current_size;
ret.ranges_.push_back(*current);
ranges_.erase(current);
}
}
if (size > 0) {
Merge(std::move(ret));
return {};
}
return ret;
}
} // namespace wasm
} // namespace internal
} // namespace v8
| [
"targos@protonmail.com"
] | targos@protonmail.com |
0aa98103e4d55cab8f852e2e908e08a96219775a | d96912ca5c921d13f16e9f74fe0addb27e7c92f8 | /1.计算器 策略工厂结合/1.计算器 策略工厂结合/main.cpp | 399750013614321ef6e525f276b417d7f287974f | [] | no_license | TzRay/DesignPattern-c-example- | 6b45789bbf32d3d2717177d7f960344797d6bc04 | c65f49e1d47d9a6bde67dbdd640912895b697de1 | refs/heads/master | 2020-03-11T18:41:35.551608 | 2018-04-19T08:42:07 | 2018-04-19T08:42:07 | 130,185,042 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | cpp | #include <iostream>
#include "operatorfs.h"
using namespace std;
int main()
{
double num1, num2;
char o1;
cout << "Plz enter your frist number.\n";
cin >> num1;
cout << "Plz enter your operation.\n";
cin >> o1;
cout << "Plz enter your second number.\n";
cin >> num2;
Operationfs oper = Operationfs(o1, num1, num2);
cout << "The result is " << oper.GetResult() << "." << endl;
system("pause");
} | [
"3148734@qq.com"
] | 3148734@qq.com |
b04920f77b29b3323f3a085d98fe2518bb968fd9 | 0641d87fac176bab11c613e64050330246569e5c | /tags/cldr-21M1/source/i18n/ucol_elm.cpp | ae9269fbde24669e3c0ad46556964bec2c1c78df | [
"LicenseRef-scancode-unicode",
"ICU"
] | permissive | svn2github/libicu_full | ecf883cedfe024efa5aeda4c8527f227a9dbf100 | f1246dcb7fec5a23ebd6d36ff3515ff0395aeb29 | refs/heads/master | 2021-01-01T17:00:58.555108 | 2015-01-27T16:59:40 | 2015-01-27T16:59:40 | 9,308,333 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 81,990 | cpp | /*
*******************************************************************************
*
* Copyright (C) 2001-2011, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: ucaelems.cpp
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created 02/22/2001
* created by: Vladimir Weinstein
*
* This program reads the Franctional UCA table and generates
* internal format for UCA table as well as inverse UCA table.
* It then writes binary files containing the data: ucadata.dat
* & invuca.dat
*
* date name comments
* 03/02/2001 synwee added setMaxExpansion
* 03/07/2001 synwee merged UCA's maxexpansion and tailoring's
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/uchar.h"
#include "unicode/unistr.h"
#include "unicode/ucoleitr.h"
#include "unicode/normlzr.h"
#include "unicode/utf16.h"
#include "normalizer2impl.h"
#include "ucol_elm.h"
#include "ucol_tok.h"
#include "ucol_cnt.h"
#include "unicode/caniter.h"
#include "cmemory.h"
U_NAMESPACE_USE
static uint32_t uprv_uca_processContraction(CntTable *contractions, UCAElements *element, uint32_t existingCE, UErrorCode *status);
U_CDECL_BEGIN
static int32_t U_CALLCONV
prefixLookupHash(const UHashTok e) {
UCAElements *element = (UCAElements *)e.pointer;
UChar buf[256];
UHashTok key;
key.pointer = buf;
uprv_memcpy(buf, element->cPoints, element->cSize*sizeof(UChar));
buf[element->cSize] = 0;
//key.pointer = element->cPoints;
//element->cPoints[element->cSize] = 0;
return uhash_hashUChars(key);
}
static int8_t U_CALLCONV
prefixLookupComp(const UHashTok e1, const UHashTok e2) {
UCAElements *element1 = (UCAElements *)e1.pointer;
UCAElements *element2 = (UCAElements *)e2.pointer;
UChar buf1[256];
UHashTok key1;
key1.pointer = buf1;
uprv_memcpy(buf1, element1->cPoints, element1->cSize*sizeof(UChar));
buf1[element1->cSize] = 0;
UChar buf2[256];
UHashTok key2;
key2.pointer = buf2;
uprv_memcpy(buf2, element2->cPoints, element2->cSize*sizeof(UChar));
buf2[element2->cSize] = 0;
return uhash_compareUChars(key1, key2);
}
U_CDECL_END
static int32_t uprv_uca_addExpansion(ExpansionTable *expansions, uint32_t value, UErrorCode *status) {
if(U_FAILURE(*status)) {
return 0;
}
if(expansions->CEs == NULL) {
expansions->CEs = (uint32_t *)uprv_malloc(INIT_EXP_TABLE_SIZE*sizeof(uint32_t));
/* test for NULL */
if (expansions->CEs == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
expansions->size = INIT_EXP_TABLE_SIZE;
expansions->position = 0;
}
if(expansions->position == expansions->size) {
uint32_t *newData = (uint32_t *)uprv_realloc(expansions->CEs, 2*expansions->size*sizeof(uint32_t));
if(newData == NULL) {
#ifdef UCOL_DEBUG
fprintf(stderr, "out of memory for expansions\n");
#endif
*status = U_MEMORY_ALLOCATION_ERROR;
return -1;
}
expansions->CEs = newData;
expansions->size *= 2;
}
expansions->CEs[expansions->position] = value;
return(expansions->position++);
}
U_CAPI tempUCATable* U_EXPORT2
uprv_uca_initTempTable(UCATableHeader *image, UColOptionSet *opts, const UCollator *UCA, UColCETags initTag, UColCETags supplementaryInitTag, UErrorCode *status) {
MaxJamoExpansionTable *maxjet;
MaxExpansionTable *maxet;
tempUCATable *t = (tempUCATable *)uprv_malloc(sizeof(tempUCATable));
/* test for NULL */
if (t == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
}
uprv_memset(t, 0, sizeof(tempUCATable));
maxet = (MaxExpansionTable *)uprv_malloc(sizeof(MaxExpansionTable));
if (maxet == NULL) {
goto allocation_failure;
}
uprv_memset(maxet, 0, sizeof(MaxExpansionTable));
t->maxExpansions = maxet;
maxjet = (MaxJamoExpansionTable *)uprv_malloc(sizeof(MaxJamoExpansionTable));
if (maxjet == NULL) {
goto allocation_failure;
}
uprv_memset(maxjet, 0, sizeof(MaxJamoExpansionTable));
t->maxJamoExpansions = maxjet;
t->image = image;
t->options = opts;
t->UCA = UCA;
t->expansions = (ExpansionTable *)uprv_malloc(sizeof(ExpansionTable));
/* test for NULL */
if (t->expansions == NULL) {
goto allocation_failure;
}
uprv_memset(t->expansions, 0, sizeof(ExpansionTable));
t->mapping = utrie_open(NULL, NULL, UCOL_ELM_TRIE_CAPACITY,
UCOL_SPECIAL_FLAG | (initTag<<24),
UCOL_SPECIAL_FLAG | (supplementaryInitTag << 24),
TRUE); // Do your own mallocs for the structure, array and have linear Latin 1
if (U_FAILURE(*status)) {
goto allocation_failure;
}
t->prefixLookup = uhash_open(prefixLookupHash, prefixLookupComp, NULL, status);
if (U_FAILURE(*status)) {
goto allocation_failure;
}
uhash_setValueDeleter(t->prefixLookup, uprv_free);
t->contractions = uprv_cnttab_open(t->mapping, status);
if (U_FAILURE(*status)) {
goto cleanup;
}
/* copy UCA's maxexpansion and merge as we go along */
if (UCA != NULL) {
/* adding an extra initial value for easier manipulation */
maxet->size = (int32_t)(UCA->lastEndExpansionCE - UCA->endExpansionCE) + 2;
maxet->position = maxet->size - 1;
maxet->endExpansionCE =
(uint32_t *)uprv_malloc(sizeof(uint32_t) * maxet->size);
/* test for NULL */
if (maxet->endExpansionCE == NULL) {
goto allocation_failure;
}
maxet->expansionCESize =
(uint8_t *)uprv_malloc(sizeof(uint8_t) * maxet->size);
/* test for NULL */
if (maxet->expansionCESize == NULL) {
goto allocation_failure;
}
/* initialized value */
*(maxet->endExpansionCE) = 0;
*(maxet->expansionCESize) = 0;
uprv_memcpy(maxet->endExpansionCE + 1, UCA->endExpansionCE,
sizeof(uint32_t) * (maxet->size - 1));
uprv_memcpy(maxet->expansionCESize + 1, UCA->expansionCESize,
sizeof(uint8_t) * (maxet->size - 1));
}
else {
maxet->size = 0;
}
maxjet->endExpansionCE = NULL;
maxjet->isV = NULL;
maxjet->size = 0;
maxjet->position = 0;
maxjet->maxLSize = 1;
maxjet->maxVSize = 1;
maxjet->maxTSize = 1;
t->unsafeCP = (uint8_t *)uprv_malloc(UCOL_UNSAFECP_TABLE_SIZE);
/* test for NULL */
if (t->unsafeCP == NULL) {
goto allocation_failure;
}
t->contrEndCP = (uint8_t *)uprv_malloc(UCOL_UNSAFECP_TABLE_SIZE);
/* test for NULL */
if (t->contrEndCP == NULL) {
goto allocation_failure;
}
uprv_memset(t->unsafeCP, 0, UCOL_UNSAFECP_TABLE_SIZE);
uprv_memset(t->contrEndCP, 0, UCOL_UNSAFECP_TABLE_SIZE);
t->cmLookup = NULL;
return t;
allocation_failure:
*status = U_MEMORY_ALLOCATION_ERROR;
cleanup:
uprv_uca_closeTempTable(t);
return NULL;
}
static tempUCATable* U_EXPORT2
uprv_uca_cloneTempTable(tempUCATable *t, UErrorCode *status) {
if(U_FAILURE(*status)) {
return NULL;
}
tempUCATable *r = (tempUCATable *)uprv_malloc(sizeof(tempUCATable));
/* test for NULL */
if (r == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
}
uprv_memset(r, 0, sizeof(tempUCATable));
/* mapping */
if(t->mapping != NULL) {
/*r->mapping = ucmpe32_clone(t->mapping, status);*/
r->mapping = utrie_clone(NULL, t->mapping, NULL, 0);
}
// a hashing clone function would be very nice. We have none currently...
// However, we should be good, as closing should not produce any prefixed elements.
r->prefixLookup = NULL; // prefixes are not used in closing
/* expansions */
if(t->expansions != NULL) {
r->expansions = (ExpansionTable *)uprv_malloc(sizeof(ExpansionTable));
/* test for NULL */
if (r->expansions == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
r->expansions->position = t->expansions->position;
r->expansions->size = t->expansions->size;
if(t->expansions->CEs != NULL) {
r->expansions->CEs = (uint32_t *)uprv_malloc(sizeof(uint32_t)*t->expansions->size);
/* test for NULL */
if (r->expansions->CEs == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
uprv_memcpy(r->expansions->CEs, t->expansions->CEs, sizeof(uint32_t)*t->expansions->position);
} else {
r->expansions->CEs = NULL;
}
}
if(t->contractions != NULL) {
r->contractions = uprv_cnttab_clone(t->contractions, status);
// Check for cloning failure.
if (r->contractions == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
r->contractions->mapping = r->mapping;
}
if(t->maxExpansions != NULL) {
r->maxExpansions = (MaxExpansionTable *)uprv_malloc(sizeof(MaxExpansionTable));
/* test for NULL */
if (r->maxExpansions == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
r->maxExpansions->size = t->maxExpansions->size;
r->maxExpansions->position = t->maxExpansions->position;
if(t->maxExpansions->endExpansionCE != NULL) {
r->maxExpansions->endExpansionCE = (uint32_t *)uprv_malloc(sizeof(uint32_t)*t->maxExpansions->size);
/* test for NULL */
if (r->maxExpansions->endExpansionCE == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
uprv_memset(r->maxExpansions->endExpansionCE, 0xDB, sizeof(uint32_t)*t->maxExpansions->size);
uprv_memcpy(r->maxExpansions->endExpansionCE, t->maxExpansions->endExpansionCE, t->maxExpansions->position*sizeof(uint32_t));
} else {
r->maxExpansions->endExpansionCE = NULL;
}
if(t->maxExpansions->expansionCESize != NULL) {
r->maxExpansions->expansionCESize = (uint8_t *)uprv_malloc(sizeof(uint8_t)*t->maxExpansions->size);
/* test for NULL */
if (r->maxExpansions->expansionCESize == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
uprv_memset(r->maxExpansions->expansionCESize, 0xDB, sizeof(uint8_t)*t->maxExpansions->size);
uprv_memcpy(r->maxExpansions->expansionCESize, t->maxExpansions->expansionCESize, t->maxExpansions->position*sizeof(uint8_t));
} else {
r->maxExpansions->expansionCESize = NULL;
}
}
if(t->maxJamoExpansions != NULL) {
r->maxJamoExpansions = (MaxJamoExpansionTable *)uprv_malloc(sizeof(MaxJamoExpansionTable));
/* test for NULL */
if (r->maxJamoExpansions == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
r->maxJamoExpansions->size = t->maxJamoExpansions->size;
r->maxJamoExpansions->position = t->maxJamoExpansions->position;
r->maxJamoExpansions->maxLSize = t->maxJamoExpansions->maxLSize;
r->maxJamoExpansions->maxVSize = t->maxJamoExpansions->maxVSize;
r->maxJamoExpansions->maxTSize = t->maxJamoExpansions->maxTSize;
if(t->maxJamoExpansions->size != 0) {
r->maxJamoExpansions->endExpansionCE = (uint32_t *)uprv_malloc(sizeof(uint32_t)*t->maxJamoExpansions->size);
/* test for NULL */
if (r->maxJamoExpansions->endExpansionCE == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
uprv_memcpy(r->maxJamoExpansions->endExpansionCE, t->maxJamoExpansions->endExpansionCE, t->maxJamoExpansions->position*sizeof(uint32_t));
r->maxJamoExpansions->isV = (UBool *)uprv_malloc(sizeof(UBool)*t->maxJamoExpansions->size);
/* test for NULL */
if (r->maxJamoExpansions->isV == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
uprv_memcpy(r->maxJamoExpansions->isV, t->maxJamoExpansions->isV, t->maxJamoExpansions->position*sizeof(UBool));
} else {
r->maxJamoExpansions->endExpansionCE = NULL;
r->maxJamoExpansions->isV = NULL;
}
}
if(t->unsafeCP != NULL) {
r->unsafeCP = (uint8_t *)uprv_malloc(UCOL_UNSAFECP_TABLE_SIZE);
/* test for NULL */
if (r->unsafeCP == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
uprv_memcpy(r->unsafeCP, t->unsafeCP, UCOL_UNSAFECP_TABLE_SIZE);
}
if(t->contrEndCP != NULL) {
r->contrEndCP = (uint8_t *)uprv_malloc(UCOL_UNSAFECP_TABLE_SIZE);
/* test for NULL */
if (r->contrEndCP == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
goto cleanup;
}
uprv_memcpy(r->contrEndCP, t->contrEndCP, UCOL_UNSAFECP_TABLE_SIZE);
}
r->UCA = t->UCA;
r->image = t->image;
r->options = t->options;
return r;
cleanup:
uprv_uca_closeTempTable(t);
return NULL;
}
U_CAPI void U_EXPORT2
uprv_uca_closeTempTable(tempUCATable *t) {
if(t != NULL) {
if (t->expansions != NULL) {
uprv_free(t->expansions->CEs);
uprv_free(t->expansions);
}
if(t->contractions != NULL) {
uprv_cnttab_close(t->contractions);
}
if (t->mapping != NULL) {
utrie_close(t->mapping);
}
if(t->prefixLookup != NULL) {
uhash_close(t->prefixLookup);
}
if (t->maxExpansions != NULL) {
uprv_free(t->maxExpansions->endExpansionCE);
uprv_free(t->maxExpansions->expansionCESize);
uprv_free(t->maxExpansions);
}
if (t->maxJamoExpansions->size > 0) {
uprv_free(t->maxJamoExpansions->endExpansionCE);
uprv_free(t->maxJamoExpansions->isV);
}
uprv_free(t->maxJamoExpansions);
uprv_free(t->unsafeCP);
uprv_free(t->contrEndCP);
if (t->cmLookup != NULL) {
uprv_free(t->cmLookup->cPoints);
uprv_free(t->cmLookup);
}
uprv_free(t);
}
}
/**
* Looks for the maximum length of all expansion sequences ending with the same
* collation element. The size required for maxexpansion and maxsize is
* returned if the arrays are too small.
* @param endexpansion the last expansion collation element to be added
* @param expansionsize size of the expansion
* @param maxexpansion data structure to store the maximum expansion data.
* @param status error status
* @returns size of the maxexpansion and maxsize used.
*/
static int uprv_uca_setMaxExpansion(uint32_t endexpansion,
uint8_t expansionsize,
MaxExpansionTable *maxexpansion,
UErrorCode *status)
{
if (maxexpansion->size == 0) {
/* we'll always make the first element 0, for easier manipulation */
maxexpansion->endExpansionCE =
(uint32_t *)uprv_malloc(INIT_EXP_TABLE_SIZE * sizeof(int32_t));
/* test for NULL */
if (maxexpansion->endExpansionCE == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
*(maxexpansion->endExpansionCE) = 0;
maxexpansion->expansionCESize =
(uint8_t *)uprv_malloc(INIT_EXP_TABLE_SIZE * sizeof(uint8_t));
/* test for NULL */;
if (maxexpansion->expansionCESize == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
*(maxexpansion->expansionCESize) = 0;
maxexpansion->size = INIT_EXP_TABLE_SIZE;
maxexpansion->position = 0;
}
if (maxexpansion->position + 1 == maxexpansion->size) {
uint32_t *neweece = (uint32_t *)uprv_realloc(maxexpansion->endExpansionCE,
2 * maxexpansion->size * sizeof(uint32_t));
if (neweece == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
maxexpansion->endExpansionCE = neweece;
uint8_t *neweces = (uint8_t *)uprv_realloc(maxexpansion->expansionCESize,
2 * maxexpansion->size * sizeof(uint8_t));
if (neweces == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
maxexpansion->expansionCESize = neweces;
maxexpansion->size *= 2;
}
uint32_t *pendexpansionce = maxexpansion->endExpansionCE;
uint8_t *pexpansionsize = maxexpansion->expansionCESize;
int pos = maxexpansion->position;
uint32_t *start = pendexpansionce;
uint32_t *limit = pendexpansionce + pos;
/* using binary search to determine if last expansion element is
already in the array */
uint32_t *mid;
int result = -1;
while (start < limit - 1) {
mid = start + ((limit - start) >> 1);
if (endexpansion <= *mid) {
limit = mid;
}
else {
start = mid;
}
}
if (*start == endexpansion) {
result = (int)(start - pendexpansionce);
}
else if (*limit == endexpansion) {
result = (int)(limit - pendexpansionce);
}
if (result > -1) {
/* found the ce in expansion, we'll just modify the size if it is
smaller */
uint8_t *currentsize = pexpansionsize + result;
if (*currentsize < expansionsize) {
*currentsize = expansionsize;
}
}
else {
/* we'll need to squeeze the value into the array.
initial implementation. */
/* shifting the subarray down by 1 */
int shiftsize = (int)((pendexpansionce + pos) - start);
uint32_t *shiftpos = start + 1;
uint8_t *sizeshiftpos = pexpansionsize + (shiftpos - pendexpansionce);
/* okay need to rearrange the array into sorted order */
if (shiftsize == 0 /*|| *(pendexpansionce + pos) < endexpansion*/) { /* the commented part is actually both redundant and dangerous */
*(pendexpansionce + pos + 1) = endexpansion;
*(pexpansionsize + pos + 1) = expansionsize;
}
else {
uprv_memmove(shiftpos + 1, shiftpos, shiftsize * sizeof(int32_t));
uprv_memmove(sizeshiftpos + 1, sizeshiftpos,
shiftsize * sizeof(uint8_t));
*shiftpos = endexpansion;
*sizeshiftpos = expansionsize;
}
maxexpansion->position ++;
#ifdef UCOL_DEBUG
int temp;
UBool found = FALSE;
for (temp = 0; temp < maxexpansion->position; temp ++) {
if (pendexpansionce[temp] >= pendexpansionce[temp + 1]) {
fprintf(stderr, "expansions %d\n", temp);
}
if (pendexpansionce[temp] == endexpansion) {
found =TRUE;
if (pexpansionsize[temp] < expansionsize) {
fprintf(stderr, "expansions size %d\n", temp);
}
}
}
if (pendexpansionce[temp] == endexpansion) {
found =TRUE;
if (pexpansionsize[temp] < expansionsize) {
fprintf(stderr, "expansions size %d\n", temp);
}
}
if (!found)
fprintf(stderr, "expansion not found %d\n", temp);
#endif
}
return maxexpansion->position;
}
/**
* Sets the maximum length of all jamo expansion sequences ending with the same
* collation element. The size required for maxexpansion and maxsize is
* returned if the arrays are too small.
* @param ch the jamo codepoint
* @param endexpansion the last expansion collation element to be added
* @param expansionsize size of the expansion
* @param maxexpansion data structure to store the maximum expansion data.
* @param status error status
* @returns size of the maxexpansion and maxsize used.
*/
static int uprv_uca_setMaxJamoExpansion(UChar ch,
uint32_t endexpansion,
uint8_t expansionsize,
MaxJamoExpansionTable *maxexpansion,
UErrorCode *status)
{
UBool isV = TRUE;
if (((uint32_t)ch - 0x1100) <= (0x1112 - 0x1100)) {
/* determines L for Jamo, doesn't need to store this since it is never
at the end of a expansion */
if (maxexpansion->maxLSize < expansionsize) {
maxexpansion->maxLSize = expansionsize;
}
return maxexpansion->position;
}
if (((uint32_t)ch - 0x1161) <= (0x1175 - 0x1161)) {
/* determines V for Jamo */
if (maxexpansion->maxVSize < expansionsize) {
maxexpansion->maxVSize = expansionsize;
}
}
if (((uint32_t)ch - 0x11A8) <= (0x11C2 - 0x11A8)) {
isV = FALSE;
/* determines T for Jamo */
if (maxexpansion->maxTSize < expansionsize) {
maxexpansion->maxTSize = expansionsize;
}
}
if (maxexpansion->size == 0) {
/* we'll always make the first element 0, for easier manipulation */
maxexpansion->endExpansionCE =
(uint32_t *)uprv_malloc(INIT_EXP_TABLE_SIZE * sizeof(uint32_t));
/* test for NULL */;
if (maxexpansion->endExpansionCE == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
*(maxexpansion->endExpansionCE) = 0;
maxexpansion->isV =
(UBool *)uprv_malloc(INIT_EXP_TABLE_SIZE * sizeof(UBool));
/* test for NULL */;
if (maxexpansion->isV == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
uprv_free(maxexpansion->endExpansionCE);
maxexpansion->endExpansionCE = NULL;
return 0;
}
*(maxexpansion->isV) = 0;
maxexpansion->size = INIT_EXP_TABLE_SIZE;
maxexpansion->position = 0;
}
if (maxexpansion->position + 1 == maxexpansion->size) {
maxexpansion->size *= 2;
maxexpansion->endExpansionCE = (uint32_t *)uprv_realloc(maxexpansion->endExpansionCE,
maxexpansion->size * sizeof(uint32_t));
if (maxexpansion->endExpansionCE == NULL) {
#ifdef UCOL_DEBUG
fprintf(stderr, "out of memory for maxExpansions\n");
#endif
*status = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
maxexpansion->isV = (UBool *)uprv_realloc(maxexpansion->isV,
maxexpansion->size * sizeof(UBool));
if (maxexpansion->isV == NULL) {
#ifdef UCOL_DEBUG
fprintf(stderr, "out of memory for maxExpansions\n");
#endif
*status = U_MEMORY_ALLOCATION_ERROR;
uprv_free(maxexpansion->endExpansionCE);
maxexpansion->endExpansionCE = NULL;
return 0;
}
}
uint32_t *pendexpansionce = maxexpansion->endExpansionCE;
int pos = maxexpansion->position;
while (pos > 0) {
pos --;
if (*(pendexpansionce + pos) == endexpansion) {
return maxexpansion->position;
}
}
*(pendexpansionce + maxexpansion->position) = endexpansion;
*(maxexpansion->isV + maxexpansion->position) = isV;
maxexpansion->position ++;
return maxexpansion->position;
}
static void ContrEndCPSet(uint8_t *table, UChar c) {
uint32_t hash;
uint8_t *htByte;
hash = c;
if (hash >= UCOL_UNSAFECP_TABLE_SIZE*8) {
hash = (hash & UCOL_UNSAFECP_TABLE_MASK) + 256;
}
htByte = &table[hash>>3];
*htByte |= (1 << (hash & 7));
}
static void unsafeCPSet(uint8_t *table, UChar c) {
uint32_t hash;
uint8_t *htByte;
hash = c;
if (hash >= UCOL_UNSAFECP_TABLE_SIZE*8) {
if (hash >= 0xd800 && hash <= 0xf8ff) {
/* Part of a surrogate, or in private use area. */
/* These don't go in the table */
return;
}
hash = (hash & UCOL_UNSAFECP_TABLE_MASK) + 256;
}
htByte = &table[hash>>3];
*htByte |= (1 << (hash & 7));
}
static void
uprv_uca_createCMTable(tempUCATable *t, int32_t noOfCM, UErrorCode *status) {
t->cmLookup = (CombinClassTable *)uprv_malloc(sizeof(CombinClassTable));
if (t->cmLookup==NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return;
}
t->cmLookup->cPoints=(UChar *)uprv_malloc(noOfCM*sizeof(UChar));
if (t->cmLookup->cPoints ==NULL) {
uprv_free(t->cmLookup);
t->cmLookup = NULL;
*status = U_MEMORY_ALLOCATION_ERROR;
return;
}
t->cmLookup->size=noOfCM;
uprv_memset(t->cmLookup->index, 0, sizeof(t->cmLookup->index));
return;
}
static void
uprv_uca_copyCMTable(tempUCATable *t, UChar *cm, uint16_t *index) {
int32_t count=0;
for (int32_t i=0; i<256; ++i) {
if (index[i]>0) {
// cPoints is ordered by combining class value.
uprv_memcpy(t->cmLookup->cPoints+count, cm+(i<<8), index[i]*sizeof(UChar));
count += index[i];
}
t->cmLookup->index[i]=count;
}
return;
}
/* 1. to the UnsafeCP hash table, add all chars with combining class != 0 */
/* 2. build combining marks table for all chars with combining class != 0 */
static void uprv_uca_unsafeCPAddCCNZ(tempUCATable *t, UErrorCode *status) {
UChar c;
uint16_t fcd; // Hi byte is lead combining class.
// lo byte is trailing combing class.
const uint16_t *fcdTrieIndex;
UChar32 fcdHighStart;
UBool buildCMTable = (t->cmLookup==NULL); // flag for building combining class table
UChar *cm=NULL;
uint16_t index[256];
int32_t count=0;
fcdTrieIndex = unorm_getFCDTrieIndex(fcdHighStart, status);
if (U_FAILURE(*status)) {
return;
}
if (buildCMTable) {
if (cm==NULL) {
cm = (UChar *)uprv_malloc(sizeof(UChar)*UCOL_MAX_CM_TAB);
if (cm==NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
uprv_memset(index, 0, sizeof(index));
}
for (c=0; c<0xffff; c++) {
fcd = unorm_getFCD16(fcdTrieIndex, c);
if (fcd >= 0x100 || // if the leading combining class(c) > 0 ||
(U16_IS_LEAD(c) && fcd != 0)) {// c is a leading surrogate with some FCD data
if (buildCMTable) {
uint32_t cClass = fcd & 0xff;
//uint32_t temp=(cClass<<8)+index[cClass];
cm[(cClass<<8)+index[cClass]] = c; //
index[cClass]++;
count++;
}
unsafeCPSet(t->unsafeCP, c);
}
}
// copy to cm table
if (buildCMTable) {
uprv_uca_createCMTable(t, count, status);
if(U_FAILURE(*status)) {
if (cm!=NULL) {
uprv_free(cm);
}
return;
}
uprv_uca_copyCMTable(t, cm, index);
}
if(t->prefixLookup != NULL) {
int32_t i = -1;
const UHashElement *e = NULL;
UCAElements *element = NULL;
UChar NFCbuf[256];
uint32_t NFCbufLen = 0;
while((e = uhash_nextElement(t->prefixLookup, &i)) != NULL) {
element = (UCAElements *)e->value.pointer;
// codepoints here are in the NFD form. We need to add the
// first code point of the NFC form to unsafe, because
// strcoll needs to backup over them.
NFCbufLen = unorm_normalize(element->cPoints, element->cSize, UNORM_NFC, 0,
NFCbuf, 256, status);
unsafeCPSet(t->unsafeCP, NFCbuf[0]);
}
}
if (cm!=NULL) {
uprv_free(cm);
}
}
static uint32_t uprv_uca_addPrefix(tempUCATable *t, uint32_t CE,
UCAElements *element, UErrorCode *status)
{
// currently the longest prefix we're supporting in Japanese is two characters
// long. Although this table could quite easily mimic complete contraction stuff
// there is no good reason to make a general solution, as it would require some
// error prone messing.
CntTable *contractions = t->contractions;
UChar32 cp;
uint32_t cpsize = 0;
UChar *oldCP = element->cPoints;
uint32_t oldCPSize = element->cSize;
contractions->currentTag = SPEC_PROC_TAG;
// here, we will normalize & add prefix to the table.
uint32_t j = 0;
#ifdef UCOL_DEBUG
for(j=0; j<element->cSize; j++) {
fprintf(stdout, "CP: %04X ", element->cPoints[j]);
}
fprintf(stdout, "El: %08X Pref: ", CE);
for(j=0; j<element->prefixSize; j++) {
fprintf(stdout, "%04X ", element->prefix[j]);
}
fprintf(stdout, "%08X ", element->mapCE);
#endif
for (j = 1; j<element->prefixSize; j++) { /* First add NFD prefix chars to unsafe CP hash table */
// Unless it is a trail surrogate, which is handled algoritmically and
// shouldn't take up space in the table.
if(!(U16_IS_TRAIL(element->prefix[j]))) {
unsafeCPSet(t->unsafeCP, element->prefix[j]);
}
}
UChar tempPrefix = 0;
for(j = 0; j < /*nfcSize*/element->prefixSize/2; j++) { // prefixes are going to be looked up backwards
// therefore, we will promptly reverse the prefix buffer...
tempPrefix = *(/*nfcBuffer*/element->prefix+element->prefixSize-j-1);
*(/*nfcBuffer*/element->prefix+element->prefixSize-j-1) = element->prefix[j];
element->prefix[j] = tempPrefix;
}
#ifdef UCOL_DEBUG
fprintf(stdout, "Reversed: ");
for(j=0; j<element->prefixSize; j++) {
fprintf(stdout, "%04X ", element->prefix[j]);
}
fprintf(stdout, "%08X\n", element->mapCE);
#endif
// the first codepoint is also unsafe, as it forms a 'contraction' with the prefix
if(!(U16_IS_TRAIL(element->cPoints[0]))) {
unsafeCPSet(t->unsafeCP, element->cPoints[0]);
}
// Maybe we need this... To handle prefixes completely in the forward direction...
//if(element->cSize == 1) {
// if(!(U16_IS_TRAIL(element->cPoints[0]))) {
// ContrEndCPSet(t->contrEndCP, element->cPoints[0]);
// }
//}
element->cPoints = element->prefix;
element->cSize = element->prefixSize;
// Add the last char of the contraction to the contraction-end hash table.
// unless it is a trail surrogate, which is handled algorithmically and
// shouldn't be in the table
if(!(U16_IS_TRAIL(element->cPoints[element->cSize -1]))) {
ContrEndCPSet(t->contrEndCP, element->cPoints[element->cSize -1]);
}
// First we need to check if contractions starts with a surrogate
U16_NEXT(element->cPoints, cpsize, element->cSize, cp);
// If there are any Jamos in the contraction, we should turn on special
// processing for Jamos
if(UCOL_ISJAMO(element->prefix[0])) {
t->image->jamoSpecial = TRUE;
}
/* then we need to deal with it */
/* we could aready have something in table - or we might not */
if(!isPrefix(CE)) {
/* if it wasn't contraction, we wouldn't end up here*/
int32_t firstContractionOffset = 0;
firstContractionOffset = uprv_cnttab_addContraction(contractions, UPRV_CNTTAB_NEWELEMENT, 0, CE, status);
uint32_t newCE = uprv_uca_processContraction(contractions, element, UCOL_NOT_FOUND, status);
uprv_cnttab_addContraction(contractions, firstContractionOffset, *element->prefix, newCE, status);
uprv_cnttab_addContraction(contractions, firstContractionOffset, 0xFFFF, CE, status);
CE = constructContractCE(SPEC_PROC_TAG, firstContractionOffset);
} else { /* we are adding to existing contraction */
/* there were already some elements in the table, so we need to add a new contraction */
/* Two things can happen here: either the codepoint is already in the table, or it is not */
int32_t position = uprv_cnttab_findCP(contractions, CE, *element->prefix, status);
if(position > 0) { /* if it is we just continue down the chain */
uint32_t eCE = uprv_cnttab_getCE(contractions, CE, position, status);
uint32_t newCE = uprv_uca_processContraction(contractions, element, eCE, status);
uprv_cnttab_setContraction(contractions, CE, position, *(element->prefix), newCE, status);
} else { /* if it isn't, we will have to create a new sequence */
uprv_uca_processContraction(contractions, element, UCOL_NOT_FOUND, status);
uprv_cnttab_insertContraction(contractions, CE, *(element->prefix), element->mapCE, status);
}
}
element->cPoints = oldCP;
element->cSize = oldCPSize;
return CE;
}
// Note regarding surrogate handling: We are interested only in the single
// or leading surrogates in a contraction. If a surrogate is somewhere else
// in the contraction, it is going to be handled as a pair of code units,
// as it doesn't affect the performance AND handling surrogates specially
// would complicate code way too much.
static uint32_t uprv_uca_addContraction(tempUCATable *t, uint32_t CE,
UCAElements *element, UErrorCode *status)
{
CntTable *contractions = t->contractions;
UChar32 cp;
uint32_t cpsize = 0;
contractions->currentTag = CONTRACTION_TAG;
// First we need to check if contractions starts with a surrogate
U16_NEXT(element->cPoints, cpsize, element->cSize, cp);
if(cpsize<element->cSize) { // This is a real contraction, if there are other characters after the first
uint32_t j = 0;
for (j=1; j<element->cSize; j++) { /* First add contraction chars to unsafe CP hash table */
// Unless it is a trail surrogate, which is handled algoritmically and
// shouldn't take up space in the table.
if(!(U16_IS_TRAIL(element->cPoints[j]))) {
unsafeCPSet(t->unsafeCP, element->cPoints[j]);
}
}
// Add the last char of the contraction to the contraction-end hash table.
// unless it is a trail surrogate, which is handled algorithmically and
// shouldn't be in the table
if(!(U16_IS_TRAIL(element->cPoints[element->cSize -1]))) {
ContrEndCPSet(t->contrEndCP, element->cPoints[element->cSize -1]);
}
// If there are any Jamos in the contraction, we should turn on special
// processing for Jamos
if(UCOL_ISJAMO(element->cPoints[0])) {
t->image->jamoSpecial = TRUE;
}
/* then we need to deal with it */
/* we could aready have something in table - or we might not */
element->cPoints+=cpsize;
element->cSize-=cpsize;
if(!isContraction(CE)) {
/* if it wasn't contraction, we wouldn't end up here*/
int32_t firstContractionOffset = 0;
firstContractionOffset = uprv_cnttab_addContraction(contractions, UPRV_CNTTAB_NEWELEMENT, 0, CE, status);
uint32_t newCE = uprv_uca_processContraction(contractions, element, UCOL_NOT_FOUND, status);
uprv_cnttab_addContraction(contractions, firstContractionOffset, *element->cPoints, newCE, status);
uprv_cnttab_addContraction(contractions, firstContractionOffset, 0xFFFF, CE, status);
CE = constructContractCE(CONTRACTION_TAG, firstContractionOffset);
} else { /* we are adding to existing contraction */
/* there were already some elements in the table, so we need to add a new contraction */
/* Two things can happen here: either the codepoint is already in the table, or it is not */
int32_t position = uprv_cnttab_findCP(contractions, CE, *element->cPoints, status);
if(position > 0) { /* if it is we just continue down the chain */
uint32_t eCE = uprv_cnttab_getCE(contractions, CE, position, status);
uint32_t newCE = uprv_uca_processContraction(contractions, element, eCE, status);
uprv_cnttab_setContraction(contractions, CE, position, *(element->cPoints), newCE, status);
} else { /* if it isn't, we will have to create a new sequence */
uint32_t newCE = uprv_uca_processContraction(contractions, element, UCOL_NOT_FOUND, status);
uprv_cnttab_insertContraction(contractions, CE, *(element->cPoints), newCE, status);
}
}
element->cPoints-=cpsize;
element->cSize+=cpsize;
/*ucmpe32_set(t->mapping, cp, CE);*/
utrie_set32(t->mapping, cp, CE);
} else if(!isContraction(CE)) { /* this is just a surrogate, and there is no contraction */
/*ucmpe32_set(t->mapping, cp, element->mapCE);*/
utrie_set32(t->mapping, cp, element->mapCE);
} else { /* fill out the first stage of the contraction with the surrogate CE */
uprv_cnttab_changeContraction(contractions, CE, 0, element->mapCE, status);
uprv_cnttab_changeContraction(contractions, CE, 0xFFFF, element->mapCE, status);
}
return CE;
}
static uint32_t uprv_uca_processContraction(CntTable *contractions, UCAElements *element, uint32_t existingCE, UErrorCode *status) {
int32_t firstContractionOffset = 0;
// uint32_t contractionElement = UCOL_NOT_FOUND;
if(U_FAILURE(*status)) {
return UCOL_NOT_FOUND;
}
/* end of recursion */
if(element->cSize == 1) {
if(isCntTableElement(existingCE) && ((UColCETags)getCETag(existingCE) == contractions->currentTag)) {
uprv_cnttab_changeContraction(contractions, existingCE, 0, element->mapCE, status);
uprv_cnttab_changeContraction(contractions, existingCE, 0xFFFF, element->mapCE, status);
return existingCE;
} else {
return element->mapCE; /*can't do just that. existingCe might be a contraction, meaning that we need to do another step */
}
}
/* this recursion currently feeds on the only element we have... We will have to copy it in order to accomodate */
/* for both backward and forward cycles */
/* we encountered either an empty space or a non-contraction element */
/* this means we are constructing a new contraction sequence */
element->cPoints++;
element->cSize--;
if(!isCntTableElement(existingCE)) {
/* if it wasn't contraction, we wouldn't end up here*/
firstContractionOffset = uprv_cnttab_addContraction(contractions, UPRV_CNTTAB_NEWELEMENT, 0, existingCE, status);
uint32_t newCE = uprv_uca_processContraction(contractions, element, UCOL_NOT_FOUND, status);
uprv_cnttab_addContraction(contractions, firstContractionOffset, *element->cPoints, newCE, status);
uprv_cnttab_addContraction(contractions, firstContractionOffset, 0xFFFF, existingCE, status);
existingCE = constructContractCE(contractions->currentTag, firstContractionOffset);
} else { /* we are adding to existing contraction */
/* there were already some elements in the table, so we need to add a new contraction */
/* Two things can happen here: either the codepoint is already in the table, or it is not */
int32_t position = uprv_cnttab_findCP(contractions, existingCE, *element->cPoints, status);
if(position > 0) { /* if it is we just continue down the chain */
uint32_t eCE = uprv_cnttab_getCE(contractions, existingCE, position, status);
uint32_t newCE = uprv_uca_processContraction(contractions, element, eCE, status);
uprv_cnttab_setContraction(contractions, existingCE, position, *(element->cPoints), newCE, status);
} else { /* if it isn't, we will have to create a new sequence */
uint32_t newCE = uprv_uca_processContraction(contractions, element, UCOL_NOT_FOUND, status);
uprv_cnttab_insertContraction(contractions, existingCE, *(element->cPoints), newCE, status);
}
}
element->cPoints--;
element->cSize++;
return existingCE;
}
static uint32_t uprv_uca_finalizeAddition(tempUCATable *t, UCAElements *element, UErrorCode *status) {
uint32_t CE = UCOL_NOT_FOUND;
// This should add a completely ignorable element to the
// unsafe table, so that backward iteration will skip
// over it when treating contractions.
uint32_t i = 0;
if(element->mapCE == 0) {
for(i = 0; i < element->cSize; i++) {
if(!U16_IS_TRAIL(element->cPoints[i])) {
unsafeCPSet(t->unsafeCP, element->cPoints[i]);
}
}
}
if(element->cSize > 1) { /* we're adding a contraction */
uint32_t i = 0;
UChar32 cp;
U16_NEXT(element->cPoints, i, element->cSize, cp);
/*CE = ucmpe32_get(t->mapping, cp);*/
CE = utrie_get32(t->mapping, cp, NULL);
CE = uprv_uca_addContraction(t, CE, element, status);
} else { /* easy case, */
/*CE = ucmpe32_get(t->mapping, element->cPoints[0]);*/
CE = utrie_get32(t->mapping, element->cPoints[0], NULL);
if( CE != UCOL_NOT_FOUND) {
if(isCntTableElement(CE) /*isContraction(CE)*/) { /* adding a non contraction element (thai, expansion, single) to already existing contraction */
if(!isPrefix(element->mapCE)) { // we cannot reenter prefix elements - as we are going to create a dead loop
// Only expansions and regular CEs can go here... Contractions will never happen in this place
uprv_cnttab_setContraction(t->contractions, CE, 0, 0, element->mapCE, status);
/* This loop has to change the CE at the end of contraction REDO!*/
uprv_cnttab_changeLastCE(t->contractions, CE, element->mapCE, status);
}
} else {
/*ucmpe32_set(t->mapping, element->cPoints[0], element->mapCE);*/
utrie_set32(t->mapping, element->cPoints[0], element->mapCE);
if ((element->prefixSize!=0) && (!isSpecial(CE) || (getCETag(CE)!=IMPLICIT_TAG))) {
UCAElements *origElem = (UCAElements *)uprv_malloc(sizeof(UCAElements));
/* test for NULL */
if (origElem== NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
/* copy the original UCA value */
origElem->prefixSize = 0;
origElem->prefix = NULL;
origElem->cPoints = origElem->uchars;
origElem->cPoints[0] = element->cPoints[0];
origElem->cSize = 1;
origElem->CEs[0]=CE;
origElem->mapCE=CE;
origElem->noOfCEs=1;
uprv_uca_finalizeAddition(t, origElem, status);
uprv_free(origElem);
}
#ifdef UCOL_DEBUG
fprintf(stderr, "Warning - trying to overwrite existing data %08X for cp %04X with %08X\n", CE, element->cPoints[0], element->CEs[0]);
//*status = U_ILLEGAL_ARGUMENT_ERROR;
#endif
}
} else {
/*ucmpe32_set(t->mapping, element->cPoints[0], element->mapCE);*/
utrie_set32(t->mapping, element->cPoints[0], element->mapCE);
}
}
return CE;
}
/* This adds a read element, while testing for existence */
U_CAPI uint32_t U_EXPORT2
uprv_uca_addAnElement(tempUCATable *t, UCAElements *element, UErrorCode *status) {
U_NAMESPACE_USE
ExpansionTable *expansions = t->expansions;
uint32_t i = 1;
uint32_t expansion = 0;
uint32_t CE;
if(U_FAILURE(*status)) {
return 0xFFFF;
}
element->mapCE = 0; // clear mapCE so that we can catch expansions
if(element->noOfCEs == 1) {
element->mapCE = element->CEs[0];
} else {
/* ICU 2.1 long primaries */
/* unfortunately, it looks like we have to look for a long primary here */
/* since in canonical closure we are going to hit some long primaries from */
/* the first phase, and they will come back as continuations/expansions */
/* destroying the effect of the previous opitimization */
/* A long primary is a three byte primary with starting secondaries and tertiaries */
/* It can appear in long runs of only primary differences (like east Asian tailorings) */
/* also, it should not be an expansion, as expansions would break with this */
// This part came in from ucol_bld.cpp
//if(tok->expansion == 0
//&& noOfBytes[0] == 3 && noOfBytes[1] == 1 && noOfBytes[2] == 1
//&& CEparts[1] == (UCOL_BYTE_COMMON << 24) && CEparts[2] == (UCOL_BYTE_COMMON << 24)) {
/* we will construct a special CE that will go unchanged to the table */
if(element->noOfCEs == 2 // a two CE expansion
&& isContinuation(element->CEs[1]) // which is a continuation
&& (element->CEs[1] & (~(0xFF << 24 | UCOL_CONTINUATION_MARKER))) == 0 // that has only primaries in continuation,
&& (((element->CEs[0]>>8) & 0xFF) == UCOL_BYTE_COMMON) // a common secondary
&& ((element->CEs[0] & 0xFF) == UCOL_BYTE_COMMON) // and a common tertiary
)
{
#ifdef UCOL_DEBUG
fprintf(stdout, "Long primary %04X\n", element->cPoints[0]);
#endif
element->mapCE = UCOL_SPECIAL_FLAG | (LONG_PRIMARY_TAG<<24) // a long primary special
| ((element->CEs[0]>>8) & 0xFFFF00) // first and second byte of primary
| ((element->CEs[1]>>24) & 0xFF); // third byte of primary
}
else {
expansion = (uint32_t)(UCOL_SPECIAL_FLAG | (EXPANSION_TAG<<UCOL_TAG_SHIFT)
| (((uprv_uca_addExpansion(expansions, element->CEs[0], status)+(headersize>>2))<<4)
& 0xFFFFF0));
for(i = 1; i<element->noOfCEs; i++) {
uprv_uca_addExpansion(expansions, element->CEs[i], status);
}
if(element->noOfCEs <= 0xF) {
expansion |= element->noOfCEs;
} else {
uprv_uca_addExpansion(expansions, 0, status);
}
element->mapCE = expansion;
uprv_uca_setMaxExpansion(element->CEs[element->noOfCEs - 1],
(uint8_t)element->noOfCEs,
t->maxExpansions,
status);
if(UCOL_ISJAMO(element->cPoints[0])) {
t->image->jamoSpecial = TRUE;
uprv_uca_setMaxJamoExpansion(element->cPoints[0],
element->CEs[element->noOfCEs - 1],
(uint8_t)element->noOfCEs,
t->maxJamoExpansions,
status);
}
if (U_FAILURE(*status)) {
return 0;
}
}
}
// We treat digits differently - they are "uber special" and should be
// processed differently if numeric collation is on.
UChar32 uniChar = 0;
//printElement(element);
if ((element->cSize == 2) && U16_IS_LEAD(element->cPoints[0])){
uniChar = U16_GET_SUPPLEMENTARY(element->cPoints[0], element->cPoints[1]);
} else if (element->cSize == 1){
uniChar = element->cPoints[0];
}
// Here, we either have one normal CE OR mapCE is set. Therefore, we stuff only
// one element to the expansion buffer. When we encounter a digit and we don't
// do numeric collation, we will just pick the CE we have and break out of case
// (see ucol.cpp ucol_prv_getSpecialCE && ucol_prv_getSpecialPrevCE). If we picked
// a special, further processing will occur. If it's a simple CE, we'll return due
// to how the loop is constructed.
if (uniChar != 0 && u_isdigit(uniChar)){
expansion = (uint32_t)(UCOL_SPECIAL_FLAG | (DIGIT_TAG<<UCOL_TAG_SHIFT) | 1); // prepare the element
if(element->mapCE) { // if there is an expansion, we'll pick it here
expansion |= ((uprv_uca_addExpansion(expansions, element->mapCE, status)+(headersize>>2))<<4);
} else {
expansion |= ((uprv_uca_addExpansion(expansions, element->CEs[0], status)+(headersize>>2))<<4);
}
element->mapCE = expansion;
// Need to go back to the beginning of the digit string if in the middle!
if(uniChar <= 0xFFFF) { // supplementaries are always unsafe. API takes UChars
unsafeCPSet(t->unsafeCP, (UChar)uniChar);
}
}
// here we want to add the prefix structure.
// I will try to process it as a reverse contraction, if possible.
// prefix buffer is already reversed.
if(element->prefixSize!=0) {
// We keep the seen prefix starter elements in a hashtable
// we need it to be able to distinguish between the simple
// codepoints and prefix starters. Also, we need to use it
// for canonical closure.
UCAElements *composed = (UCAElements *)uprv_malloc(sizeof(UCAElements));
/* test for NULL */
if (composed == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
uprv_memcpy(composed, element, sizeof(UCAElements));
composed->cPoints = composed->uchars;
composed->prefix = composed->prefixChars;
composed->prefixSize = unorm_normalize(element->prefix, element->prefixSize, UNORM_NFC, 0, composed->prefix, 128, status);
if(t->prefixLookup != NULL) {
UCAElements *uCE = (UCAElements *)uhash_get(t->prefixLookup, element);
if(uCE != NULL) { // there is already a set of code points here
element->mapCE = uprv_uca_addPrefix(t, uCE->mapCE, element, status);
} else { // no code points, so this spot is clean
element->mapCE = uprv_uca_addPrefix(t, UCOL_NOT_FOUND, element, status);
uCE = (UCAElements *)uprv_malloc(sizeof(UCAElements));
/* test for NULL */
if (uCE == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
uprv_memcpy(uCE, element, sizeof(UCAElements));
uCE->cPoints = uCE->uchars;
uhash_put(t->prefixLookup, uCE, uCE, status);
}
if(composed->prefixSize != element->prefixSize || uprv_memcmp(composed->prefix, element->prefix, element->prefixSize)) {
// do it!
composed->mapCE = uprv_uca_addPrefix(t, element->mapCE, composed, status);
}
}
uprv_free(composed);
}
// We need to use the canonical iterator here
// the way we do it is to generate the canonically equivalent strings
// for the contraction and then add the sequences that pass FCD check
if(element->cSize > 1 && !(element->cSize==2 && U16_IS_LEAD(element->cPoints[0]) && U16_IS_TRAIL(element->cPoints[1]))) { // this is a contraction, we should check whether a composed form should also be included
UnicodeString source(element->cPoints, element->cSize);
CanonicalIterator it(source, *status);
source = it.next();
while(!source.isBogus()) {
if(Normalizer::quickCheck(source, UNORM_FCD, *status) != UNORM_NO) {
element->cSize = source.extract(element->cPoints, 128, *status);
uprv_uca_finalizeAddition(t, element, status);
}
source = it.next();
}
CE = element->mapCE;
} else {
CE = uprv_uca_finalizeAddition(t, element, status);
}
return CE;
}
/*void uprv_uca_getMaxExpansionJamo(CompactEIntArray *mapping, */
static void uprv_uca_getMaxExpansionJamo(UNewTrie *mapping,
MaxExpansionTable *maxexpansion,
MaxJamoExpansionTable *maxjamoexpansion,
UBool jamospecial,
UErrorCode *status)
{
const uint32_t VBASE = 0x1161;
const uint32_t TBASE = 0x11A8;
const uint32_t VCOUNT = 21;
const uint32_t TCOUNT = 28;
uint32_t v = VBASE + VCOUNT - 1;
uint32_t t = TBASE + TCOUNT - 1;
uint32_t ce;
while (v >= VBASE) {
/*ce = ucmpe32_get(mapping, v);*/
ce = utrie_get32(mapping, v, NULL);
if (ce < UCOL_SPECIAL_FLAG) {
uprv_uca_setMaxExpansion(ce, 2, maxexpansion, status);
}
v --;
}
while (t >= TBASE)
{
/*ce = ucmpe32_get(mapping, t);*/
ce = utrie_get32(mapping, t, NULL);
if (ce < UCOL_SPECIAL_FLAG) {
uprv_uca_setMaxExpansion(ce, 3, maxexpansion, status);
}
t --;
}
/* According to the docs, 99% of the time, the Jamo will not be special */
if (jamospecial) {
/* gets the max expansion in all unicode characters */
int count = maxjamoexpansion->position;
uint8_t maxTSize = (uint8_t)(maxjamoexpansion->maxLSize +
maxjamoexpansion->maxVSize +
maxjamoexpansion->maxTSize);
uint8_t maxVSize = (uint8_t)(maxjamoexpansion->maxLSize +
maxjamoexpansion->maxVSize);
while (count > 0) {
count --;
if (*(maxjamoexpansion->isV + count) == TRUE) {
uprv_uca_setMaxExpansion(
*(maxjamoexpansion->endExpansionCE + count),
maxVSize, maxexpansion, status);
}
else {
uprv_uca_setMaxExpansion(
*(maxjamoexpansion->endExpansionCE + count),
maxTSize, maxexpansion, status);
}
}
}
}
U_CDECL_BEGIN
static inline uint32_t U_CALLCONV
getFoldedValue(UNewTrie *trie, UChar32 start, int32_t offset)
{
uint32_t value;
uint32_t tag;
UChar32 limit;
UBool inBlockZero;
limit=start+0x400;
while(start<limit) {
value=utrie_get32(trie, start, &inBlockZero);
tag = getCETag(value);
if(inBlockZero == TRUE) {
start+=UTRIE_DATA_BLOCK_LENGTH;
} else if(!(isSpecial(value) && (tag == IMPLICIT_TAG || tag == NOT_FOUND_TAG))) {
/* These are values that are starting in either UCA (IMPLICIT_TAG) or in the
* tailorings (NOT_FOUND_TAG). Presence of these tags means that there is
* nothing in this position and that it should be skipped.
*/
#ifdef UCOL_DEBUG
static int32_t count = 1;
fprintf(stdout, "%i, Folded %08X, value %08X\n", count++, start, value);
#endif
return (uint32_t)(UCOL_SPECIAL_FLAG | (SURROGATE_TAG<<24) | offset);
} else {
++start;
}
}
return 0;
}
U_CDECL_END
#ifdef UCOL_DEBUG
// This is a debug function to print the contents of a trie.
// It is used in conjuction with the code around utrie_unserialize call
UBool enumRange(const void *context, UChar32 start, UChar32 limit, uint32_t value) {
if(start<0x10000) {
fprintf(stdout, "%08X, %08X, %08X\n", start, limit, value);
} else {
fprintf(stdout, "%08X=%04X %04X, %08X=%04X %04X, %08X\n", start, U16_LEAD(start), U16_TRAIL(start), limit, U16_LEAD(limit), U16_TRAIL(limit), value);
}
return TRUE;
}
int32_t
myGetFoldingOffset(uint32_t data) {
if(data > UCOL_NOT_FOUND && getCETag(data) == SURROGATE_TAG) {
return (data&0xFFFFFF);
} else {
return 0;
}
}
#endif
U_CAPI UCATableHeader* U_EXPORT2
uprv_uca_assembleTable(tempUCATable *t, UErrorCode *status) {
/*CompactEIntArray *mapping = t->mapping;*/
UNewTrie *mapping = t->mapping;
ExpansionTable *expansions = t->expansions;
CntTable *contractions = t->contractions;
MaxExpansionTable *maxexpansion = t->maxExpansions;
if(U_FAILURE(*status)) {
return NULL;
}
uint32_t beforeContractions = (uint32_t)((headersize+paddedsize(expansions->position*sizeof(uint32_t)))/sizeof(UChar));
int32_t contractionsSize = 0;
contractionsSize = uprv_cnttab_constructTable(contractions, beforeContractions, status);
/* the following operation depends on the trie data. Therefore, we have to do it before */
/* the trie is compacted */
/* sets jamo expansions */
uprv_uca_getMaxExpansionJamo(mapping, maxexpansion, t->maxJamoExpansions,
t->image->jamoSpecial, status);
/*ucmpe32_compact(mapping);*/
/*UMemoryStream *ms = uprv_mstrm_openNew(8192);*/
/*int32_t mappingSize = ucmpe32_flattenMem(mapping, ms);*/
/*const uint8_t *flattened = uprv_mstrm_getBuffer(ms, &mappingSize);*/
// After setting the jamo expansions, compact the trie and get the needed size
int32_t mappingSize = utrie_serialize(mapping, NULL, 0, getFoldedValue /*getFoldedValue*/, FALSE, status);
uint32_t tableOffset = 0;
uint8_t *dataStart;
/* TODO: LATIN1 array is now in the utrie - it should be removed from the calculation */
uint32_t toAllocate =(uint32_t)(headersize+
paddedsize(expansions->position*sizeof(uint32_t))+
paddedsize(mappingSize)+
paddedsize(contractionsSize*(sizeof(UChar)+sizeof(uint32_t)))+
//paddedsize(0x100*sizeof(uint32_t)) /* Latin1 is now included in the trie */
/* maxexpansion array */
+ paddedsize(maxexpansion->position * sizeof(uint32_t)) +
/* maxexpansion size array */
paddedsize(maxexpansion->position * sizeof(uint8_t)) +
paddedsize(UCOL_UNSAFECP_TABLE_SIZE) + /* Unsafe chars */
paddedsize(UCOL_UNSAFECP_TABLE_SIZE)); /* Contraction Ending chars */
dataStart = (uint8_t *)uprv_malloc(toAllocate);
/* test for NULL */
if (dataStart == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
}
UCATableHeader *myData = (UCATableHeader *)dataStart;
// Please, do reset all the fields!
uprv_memset(dataStart, 0, toAllocate);
// Make sure we know this is reset
myData->magic = UCOL_HEADER_MAGIC;
myData->isBigEndian = U_IS_BIG_ENDIAN;
myData->charSetFamily = U_CHARSET_FAMILY;
myData->formatVersion[0] = UCA_FORMAT_VERSION_0;
myData->formatVersion[1] = UCA_FORMAT_VERSION_1;
myData->formatVersion[2] = UCA_FORMAT_VERSION_2;
myData->formatVersion[3] = UCA_FORMAT_VERSION_3;
myData->jamoSpecial = t->image->jamoSpecial;
// Don't copy stuff from UCA header!
//uprv_memcpy(myData, t->image, sizeof(UCATableHeader));
myData->contractionSize = contractionsSize;
tableOffset += (uint32_t)(paddedsize(sizeof(UCATableHeader)));
myData->options = tableOffset;
uprv_memcpy(dataStart+tableOffset, t->options, sizeof(UColOptionSet));
tableOffset += (uint32_t)(paddedsize(sizeof(UColOptionSet)));
/* copy expansions */
/*myData->expansion = (uint32_t *)dataStart+tableOffset;*/
myData->expansion = tableOffset;
uprv_memcpy(dataStart+tableOffset, expansions->CEs, expansions->position*sizeof(uint32_t));
tableOffset += (uint32_t)(paddedsize(expansions->position*sizeof(uint32_t)));
/* contractions block */
if(contractionsSize != 0) {
/* copy contraction index */
/*myData->contractionIndex = (UChar *)(dataStart+tableOffset);*/
myData->contractionIndex = tableOffset;
uprv_memcpy(dataStart+tableOffset, contractions->codePoints, contractionsSize*sizeof(UChar));
tableOffset += (uint32_t)(paddedsize(contractionsSize*sizeof(UChar)));
/* copy contraction collation elements */
/*myData->contractionCEs = (uint32_t *)(dataStart+tableOffset);*/
myData->contractionCEs = tableOffset;
uprv_memcpy(dataStart+tableOffset, contractions->CEs, contractionsSize*sizeof(uint32_t));
tableOffset += (uint32_t)(paddedsize(contractionsSize*sizeof(uint32_t)));
} else {
myData->contractionIndex = 0;
myData->contractionCEs = 0;
}
/* copy mapping table */
/*myData->mappingPosition = dataStart+tableOffset;*/
/*myData->mappingPosition = tableOffset;*/
/*uprv_memcpy(dataStart+tableOffset, flattened, mappingSize);*/
myData->mappingPosition = tableOffset;
utrie_serialize(mapping, dataStart+tableOffset, toAllocate-tableOffset, getFoldedValue, FALSE, status);
#ifdef UCOL_DEBUG
// This is debug code to dump the contents of the trie. It needs two functions defined above
{
UTrie UCAt = { 0 };
uint32_t trieWord;
utrie_unserialize(&UCAt, dataStart+tableOffset, 9999999, status);
UCAt.getFoldingOffset = myGetFoldingOffset;
if(U_SUCCESS(*status)) {
utrie_enum(&UCAt, NULL, enumRange, NULL);
}
trieWord = UTRIE_GET32_FROM_LEAD(&UCAt, 0xDC01);
}
#endif
tableOffset += paddedsize(mappingSize);
int32_t i = 0;
/* copy max expansion table */
myData->endExpansionCE = tableOffset;
myData->endExpansionCECount = maxexpansion->position - 1;
/* not copying the first element which is a dummy */
uprv_memcpy(dataStart + tableOffset, maxexpansion->endExpansionCE + 1,
(maxexpansion->position - 1) * sizeof(uint32_t));
tableOffset += (uint32_t)(paddedsize((maxexpansion->position)* sizeof(uint32_t)));
myData->expansionCESize = tableOffset;
uprv_memcpy(dataStart + tableOffset, maxexpansion->expansionCESize + 1,
(maxexpansion->position - 1) * sizeof(uint8_t));
tableOffset += (uint32_t)(paddedsize((maxexpansion->position)* sizeof(uint8_t)));
/* Unsafe chars table. Finish it off, then copy it. */
uprv_uca_unsafeCPAddCCNZ(t, status);
if (t->UCA != 0) { /* Or in unsafebits from UCA, making a combined table. */
for (i=0; i<UCOL_UNSAFECP_TABLE_SIZE; i++) {
t->unsafeCP[i] |= t->UCA->unsafeCP[i];
}
}
myData->unsafeCP = tableOffset;
uprv_memcpy(dataStart + tableOffset, t->unsafeCP, UCOL_UNSAFECP_TABLE_SIZE);
tableOffset += paddedsize(UCOL_UNSAFECP_TABLE_SIZE);
/* Finish building Contraction Ending chars hash table and then copy it out. */
if (t->UCA != 0) { /* Or in unsafebits from UCA, making a combined table. */
for (i=0; i<UCOL_UNSAFECP_TABLE_SIZE; i++) {
t->contrEndCP[i] |= t->UCA->contrEndCP[i];
}
}
myData->contrEndCP = tableOffset;
uprv_memcpy(dataStart + tableOffset, t->contrEndCP, UCOL_UNSAFECP_TABLE_SIZE);
tableOffset += paddedsize(UCOL_UNSAFECP_TABLE_SIZE);
if(tableOffset != toAllocate) {
#ifdef UCOL_DEBUG
fprintf(stderr, "calculation screwup!!! Expected to write %i but wrote %i instead!!!\n", toAllocate, tableOffset);
#endif
*status = U_INTERNAL_PROGRAM_ERROR;
uprv_free(dataStart);
return 0;
}
myData->size = tableOffset;
/* This should happen upon ressurection */
/*const uint8_t *mapPosition = (uint8_t*)myData+myData->mappingPosition;*/
/*uprv_mstrm_close(ms);*/
return myData;
}
struct enumStruct {
tempUCATable *t;
UCollator *tempColl;
UCollationElements* colEl;
const Normalizer2Impl *nfcImpl;
UnicodeSet *closed;
int32_t noOfClosures;
UErrorCode *status;
};
U_CDECL_BEGIN
static UBool U_CALLCONV
_enumCategoryRangeClosureCategory(const void *context, UChar32 start, UChar32 limit, UCharCategory type) {
if (type != U_UNASSIGNED && type != U_PRIVATE_USE_CHAR) { // if the range is assigned - we might ommit more categories later
UErrorCode *status = ((enumStruct *)context)->status;
tempUCATable *t = ((enumStruct *)context)->t;
UCollator *tempColl = ((enumStruct *)context)->tempColl;
UCollationElements* colEl = ((enumStruct *)context)->colEl;
UCAElements el;
UChar decompBuffer[4];
const UChar *decomp;
int32_t noOfDec = 0;
UChar32 u32 = 0;
UChar comp[2];
uint32_t len = 0;
for(u32 = start; u32 < limit; u32++) {
decomp = ((enumStruct *)context)->nfcImpl->
getDecomposition(u32, decompBuffer, noOfDec);
//if((noOfDec = unorm_normalize(comp, len, UNORM_NFD, 0, decomp, 256, status)) > 1
//|| (noOfDec == 1 && *decomp != (UChar)u32))
if(decomp != NULL)
{
len = 0;
U16_APPEND_UNSAFE(comp, len, u32);
if(ucol_strcoll(tempColl, comp, len, decomp, noOfDec) != UCOL_EQUAL) {
#ifdef UCOL_DEBUG
fprintf(stderr, "Closure: U+%04X -> ", u32);
UChar32 c;
int32_t i = 0;
while(i < noOfDec) {
U16_NEXT(decomp, i, noOfDec, c);
fprintf(stderr, "%04X ", c);
}
fprintf(stderr, "\n");
// print CEs for code point vs. decomposition
fprintf(stderr, "U+%04X CEs: ", u32);
UCollationElements *iter = ucol_openElements(tempColl, comp, len, status);
int32_t ce;
while((ce = ucol_next(iter, status)) != UCOL_NULLORDER) {
fprintf(stderr, "%08X ", ce);
}
fprintf(stderr, "\nDecomp CEs: ");
ucol_setText(iter, decomp, noOfDec, status);
while((ce = ucol_next(iter, status)) != UCOL_NULLORDER) {
fprintf(stderr, "%08X ", ce);
}
fprintf(stderr, "\n");
ucol_closeElements(iter);
#endif
if(((enumStruct *)context)->closed != NULL) {
((enumStruct *)context)->closed->add(u32);
}
((enumStruct *)context)->noOfClosures++;
el.cPoints = (UChar *)decomp;
el.cSize = noOfDec;
el.noOfCEs = 0;
el.prefix = el.prefixChars;
el.prefixSize = 0;
UCAElements *prefix=(UCAElements *)uhash_get(t->prefixLookup, &el);
el.cPoints = comp;
el.cSize = len;
el.prefix = el.prefixChars;
el.prefixSize = 0;
if(prefix == NULL) {
el.noOfCEs = 0;
ucol_setText(colEl, decomp, noOfDec, status);
while((el.CEs[el.noOfCEs] = ucol_next(colEl, status)) != (uint32_t)UCOL_NULLORDER) {
el.noOfCEs++;
}
} else {
el.noOfCEs = 1;
el.CEs[0] = prefix->mapCE;
// This character uses a prefix. We have to add it
// to the unsafe table, as it decomposed form is already
// in. In Japanese, this happens for \u309e & \u30fe
// Since unsafeCPSet is static in ucol_elm, we are going
// to wrap it up in the uprv_uca_unsafeCPAddCCNZ function
}
uprv_uca_addAnElement(t, &el, status);
}
}
}
}
return TRUE;
}
U_CDECL_END
static void
uprv_uca_setMapCE(tempUCATable *t, UCAElements *element, UErrorCode *status) {
uint32_t expansion = 0;
int32_t j;
ExpansionTable *expansions = t->expansions;
if(element->noOfCEs == 2 // a two CE expansion
&& isContinuation(element->CEs[1]) // which is a continuation
&& (element->CEs[1] & (~(0xFF << 24 | UCOL_CONTINUATION_MARKER))) == 0 // that has only primaries in continuation,
&& (((element->CEs[0]>>8) & 0xFF) == UCOL_BYTE_COMMON) // a common secondary
&& ((element->CEs[0] & 0xFF) == UCOL_BYTE_COMMON) // and a common tertiary
) {
element->mapCE = UCOL_SPECIAL_FLAG | (LONG_PRIMARY_TAG<<24) // a long primary special
| ((element->CEs[0]>>8) & 0xFFFF00) // first and second byte of primary
| ((element->CEs[1]>>24) & 0xFF); // third byte of primary
} else {
expansion = (uint32_t)(UCOL_SPECIAL_FLAG | (EXPANSION_TAG<<UCOL_TAG_SHIFT)
| (((uprv_uca_addExpansion(expansions, element->CEs[0], status)+(headersize>>2))<<4)
& 0xFFFFF0));
for(j = 1; j<(int32_t)element->noOfCEs; j++) {
uprv_uca_addExpansion(expansions, element->CEs[j], status);
}
if(element->noOfCEs <= 0xF) {
expansion |= element->noOfCEs;
} else {
uprv_uca_addExpansion(expansions, 0, status);
}
element->mapCE = expansion;
uprv_uca_setMaxExpansion(element->CEs[element->noOfCEs - 1],
(uint8_t)element->noOfCEs,
t->maxExpansions,
status);
}
}
static void
uprv_uca_addFCD4AccentedContractions(tempUCATable *t,
UCollationElements* colEl,
UChar *data,
int32_t len,
UCAElements *el,
UErrorCode *status) {
UChar decomp[256], comp[256];
int32_t decLen, compLen;
decLen = unorm_normalize(data, len, UNORM_NFD, 0, decomp, 256, status);
compLen = unorm_normalize(data, len, UNORM_NFC, 0, comp, 256, status);
decomp[decLen] = comp[compLen] = 0;
el->cPoints = decomp;
el->cSize = decLen;
el->noOfCEs = 0;
el->prefixSize = 0;
el->prefix = el->prefixChars;
UCAElements *prefix=(UCAElements *)uhash_get(t->prefixLookup, el);
el->cPoints = comp;
el->cSize = compLen;
el->prefix = el->prefixChars;
el->prefixSize = 0;
if(prefix == NULL) {
el->noOfCEs = 0;
ucol_setText(colEl, decomp, decLen, status);
while((el->CEs[el->noOfCEs] = ucol_next(colEl, status)) != (uint32_t)UCOL_NULLORDER) {
el->noOfCEs++;
}
uprv_uca_setMapCE(t, el, status);
uprv_uca_addAnElement(t, el, status);
}
}
static void
uprv_uca_addMultiCMContractions(tempUCATable *t,
UCollationElements* colEl,
tempTailorContext *c,
UCAElements *el,
UErrorCode *status) {
CombinClassTable *cmLookup = t->cmLookup;
UChar newDecomp[256];
int32_t maxComp, newDecLen;
UChar32 fcdHighStart;
const uint16_t *fcdTrieIndex = unorm_getFCDTrieIndex(fcdHighStart, status);
if (U_FAILURE(*status)) {
return;
}
int16_t curClass = (unorm_getFCD16(fcdTrieIndex, c->tailoringCM) & 0xff);
CompData *precomp = c->precomp;
int32_t compLen = c->compLen;
UChar *comp = c->comp;
maxComp = c->precompLen;
for (int32_t j=0; j < maxComp; j++) {
int32_t count=0;
do {
if ( count == 0 ) { // Decompose the saved precomposed char.
UChar temp[2];
temp[0]=precomp[j].cp;
temp[1]=0;
newDecLen = unorm_normalize(temp, 1, UNORM_NFD, 0,
newDecomp, sizeof(newDecomp)/sizeof(UChar), status);
newDecomp[newDecLen++] = cmLookup->cPoints[c->cmPos];
}
else { // swap 2 combining marks when they are equal.
uprv_memcpy(newDecomp, c->decomp, sizeof(UChar)*(c->decompLen));
newDecLen = c->decompLen;
newDecomp[newDecLen++] = precomp[j].cClass;
}
newDecomp[newDecLen] = 0;
compLen = unorm_normalize(newDecomp, newDecLen, UNORM_NFC, 0,
comp, 256, status);
if (compLen==1) {
comp[compLen++] = newDecomp[newDecLen++] = c->tailoringCM;
comp[compLen] = newDecomp[newDecLen] = 0;
el->cPoints = newDecomp;
el->cSize = newDecLen;
UCAElements *prefix=(UCAElements *)uhash_get(t->prefixLookup, el);
el->cPoints = c->comp;
el->cSize = compLen;
el->prefix = el->prefixChars;
el->prefixSize = 0;
if(prefix == NULL) {
el->noOfCEs = 0;
ucol_setText(colEl, newDecomp, newDecLen, status);
while((el->CEs[el->noOfCEs] = ucol_next(colEl, status)) != (uint32_t)UCOL_NULLORDER) {
el->noOfCEs++;
}
uprv_uca_setMapCE(t, el, status);
uprv_uca_finalizeAddition(t, el, status);
// Save the current precomposed char and its class to find any
// other combining mark combinations.
precomp[c->precompLen].cp=comp[0];
precomp[c->precompLen].cClass = curClass;
c->precompLen++;
}
}
} while (++count<2 && (precomp[j].cClass == curClass));
}
}
static void
uprv_uca_addTailCanonicalClosures(tempUCATable *t,
UCollationElements* colEl,
UChar baseCh,
UChar cMark,
UCAElements *el,
UErrorCode *status) {
CombinClassTable *cmLookup = t->cmLookup;
UChar32 fcdHighStart;
const uint16_t *fcdTrieIndex = unorm_getFCDTrieIndex(fcdHighStart, status);
if (U_FAILURE(*status)) {
return;
}
int16_t maxIndex = (unorm_getFCD16(fcdTrieIndex, cMark) & 0xff );
UCAElements element;
uint16_t *index;
UChar decomp[256];
UChar comp[256];
CompData precomp[256]; // precomposed array
int32_t precompLen = 0; // count for precomp
int32_t i, len, decompLen, curClass, replacedPos;
tempTailorContext c;
if ( cmLookup == NULL ) {
return;
}
index = cmLookup->index;
int32_t cClass=(unorm_getFCD16(fcdTrieIndex, cMark) & 0xff);
maxIndex = (int32_t)index[(unorm_getFCD16(fcdTrieIndex, cMark) & 0xff)-1];
c.comp = comp;
c.decomp = decomp;
c.precomp = precomp;
c.tailoringCM = cMark;
if (cClass>0) {
maxIndex = (int32_t)index[cClass-1];
}
else {
maxIndex=0;
}
decomp[0]=baseCh;
for ( i=0; i<maxIndex ; i++ ) {
decomp[1] = cmLookup->cPoints[i];
decomp[2]=0;
decompLen=2;
len = unorm_normalize(decomp, decompLen, UNORM_NFC, 0, comp, 256, status);
if (len==1) {
// Save the current precomposed char and its class to find any
// other combining mark combinations.
precomp[precompLen].cp=comp[0];
curClass = precomp[precompLen].cClass =
index[unorm_getFCD16(fcdTrieIndex, decomp[1]) & 0xff];
precompLen++;
replacedPos=0;
for (decompLen=0; decompLen< (int32_t)el->cSize; decompLen++) {
decomp[decompLen] = el->cPoints[decompLen];
if (decomp[decompLen]==cMark) {
replacedPos = decompLen; // record the position for later use
}
}
if ( replacedPos != 0 ) {
decomp[replacedPos]=cmLookup->cPoints[i];
}
decomp[decompLen] = 0;
len = unorm_normalize(decomp, decompLen, UNORM_NFC, 0, comp, 256, status);
comp[len++] = decomp[decompLen++] = cMark;
comp[len] = decomp[decompLen] = 0;
element.cPoints = decomp;
element.cSize = decompLen;
element.noOfCEs = 0;
element.prefix = el->prefixChars;
element.prefixSize = 0;
UCAElements *prefix=(UCAElements *)uhash_get(t->prefixLookup, &element);
element.cPoints = comp;
element.cSize = len;
element.prefix = el->prefixChars;
element.prefixSize = 0;
if(prefix == NULL) {
element.noOfCEs = 0;
ucol_setText(colEl, decomp, decompLen, status);
while((element.CEs[element.noOfCEs] = ucol_next(colEl, status)) != (uint32_t)UCOL_NULLORDER) {
element.noOfCEs++;
}
uprv_uca_setMapCE(t, &element, status);
uprv_uca_finalizeAddition(t, &element, status);
}
// This is a fix for tailoring contractions with accented
// character at the end of contraction string.
if ((len>2) &&
(unorm_getFCD16(fcdTrieIndex, comp[len-2]) & 0xff00)==0) {
uprv_uca_addFCD4AccentedContractions(t, colEl, comp, len, &element, status);
}
if (precompLen >1) {
c.compLen = len;
c.decompLen = decompLen;
c.precompLen = precompLen;
c.cmPos = i;
uprv_uca_addMultiCMContractions(t, colEl, &c, &element, status);
precompLen = c.precompLen;
}
}
}
}
U_CFUNC int32_t U_EXPORT2
uprv_uca_canonicalClosure(tempUCATable *t,
UColTokenParser *src,
UnicodeSet *closed,
UErrorCode *status)
{
enumStruct context;
context.closed = closed;
context.noOfClosures = 0;
UCAElements el;
UColToken *tok;
uint32_t i = 0, j = 0;
UChar baseChar, firstCM;
UChar32 fcdHighStart;
const uint16_t *fcdTrieIndex = unorm_getFCDTrieIndex(fcdHighStart, status);
context.nfcImpl=Normalizer2Factory::getNFCImpl(*status);
if(U_FAILURE(*status)) {
return 0;
}
UCollator *tempColl = NULL;
tempUCATable *tempTable = uprv_uca_cloneTempTable(t, status);
// Check for null pointer
if (U_FAILURE(*status)) {
return 0;
}
UCATableHeader *tempData = uprv_uca_assembleTable(tempTable, status);
tempColl = ucol_initCollator(tempData, 0, t->UCA, status);
if ( tempTable->cmLookup != NULL ) {
t->cmLookup = tempTable->cmLookup; // copy over to t
tempTable->cmLookup = NULL;
}
uprv_uca_closeTempTable(tempTable);
if(U_SUCCESS(*status)) {
tempColl->ucaRules = NULL;
tempColl->actualLocale = NULL;
tempColl->validLocale = NULL;
tempColl->requestedLocale = NULL;
tempColl->hasRealData = TRUE;
tempColl->freeImageOnClose = TRUE;
} else if(tempData != 0) {
uprv_free(tempData);
}
/* produce canonical closure */
UCollationElements* colEl = ucol_openElements(tempColl, NULL, 0, status);
// Check for null pointer
if (U_FAILURE(*status)) {
return 0;
}
context.t = t;
context.tempColl = tempColl;
context.colEl = colEl;
context.status = status;
u_enumCharTypes(_enumCategoryRangeClosureCategory, &context);
if ( (src==NULL) || !src->buildCCTabFlag ) {
ucol_closeElements(colEl);
ucol_close(tempColl);
return context.noOfClosures; // no extra contraction needed to add
}
for (i=0; i < src->resultLen; i++) {
baseChar = firstCM= (UChar)0;
tok = src->lh[i].first;
while (tok != NULL && U_SUCCESS(*status)) {
el.prefix = el.prefixChars;
el.cPoints = el.uchars;
if(tok->prefix != 0) {
el.prefixSize = tok->prefix>>24;
uprv_memcpy(el.prefix, src->source + (tok->prefix & 0x00FFFFFF), el.prefixSize*sizeof(UChar));
el.cSize = (tok->source >> 24)-(tok->prefix>>24);
uprv_memcpy(el.uchars, (tok->source & 0x00FFFFFF)+(tok->prefix>>24) + src->source, el.cSize*sizeof(UChar));
} else {
el.prefixSize = 0;
*el.prefix = 0;
el.cSize = (tok->source >> 24);
uprv_memcpy(el.uchars, (tok->source & 0x00FFFFFF) + src->source, el.cSize*sizeof(UChar));
}
if(src->UCA != NULL) {
for(j = 0; j<el.cSize; j++) {
int16_t fcd = unorm_getFCD16(fcdTrieIndex, el.cPoints[j]);
if ( (fcd & 0xff) == 0 ) {
baseChar = el.cPoints[j]; // last base character
firstCM=0; // reset combining mark value
}
else {
if ( (baseChar!=0) && (firstCM==0) ) {
firstCM = el.cPoints[j]; // first combining mark
}
}
}
}
if ( (baseChar!= (UChar)0) && (firstCM != (UChar)0) ) {
// find all the canonical rules
uprv_uca_addTailCanonicalClosures(t, colEl, baseChar, firstCM, &el, status);
}
tok = tok->next;
}
}
ucol_closeElements(colEl);
ucol_close(tempColl);
return context.noOfClosures;
}
#endif /* #if !UCONFIG_NO_COLLATION */
| [
"emmons@251d0590-4201-4cf1-90de-194747b24ca1"
] | emmons@251d0590-4201-4cf1-90de-194747b24ca1 |
b17baa481dc9d1498bc04da252c2e2e42f8c9a28 | 7ec7d09ccdc49338497bddde23a23ae653b60883 | /square-string-match/generate.cpp | 5003e5b3dbf7492894cc2d029d5e2bf06aad3480 | [] | no_license | dmytrolev/algorithms | 0799be0cb1d983c60a95e98f9b5c95ba48fc6505 | 9b006f46037e13d20b77d9cfa73c0dc515d48714 | refs/heads/master | 2021-07-12T11:56:26.049943 | 2017-10-16T12:42:44 | 2017-10-16T12:42:44 | 61,023,437 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,825 | cpp | #include <iostream>
#include <cstdlib>
#include <initializer_list>
#include "square.h"
#ifdef UNITS
#include "../test/units.cpp"
#endif
#ifdef ALGO_DEBUG
#include "../test/debug.cpp"
#else
#define TRACE(message)
#define TRACE_LINE(message)
#define ASSERT(expr)
#endif
#ifdef UNITS
void unit_tests() {
test_header("test units");
square test{{'a', 'b', 'c'},
{'d', 'e', 'f'}};
std::cout << test.at(1, 2) << std::endl;
}
#endif
int main() {
#ifdef UNITS
unit_tests();
return 0;
#endif
constexpr int pattern_rows = 30, pattern_cols = 30;
constexpr int matrix_rows = 1000, matrix_cols = 1000;
assert(pattern_rows <= matrix_rows);
assert(pattern_cols <= matrix_cols);
square pattern(pattern_rows, pattern_cols),
matrix(matrix_rows, matrix_cols);
for(int r = 0; r < matrix_rows; ++r) {
for(int c = 0; c < matrix_cols; ++c) {
matrix.at(r, c) = 'a' + (std::rand() % ('z' - 'a'));
}
}
int result_r = std::rand() % (matrix_rows - pattern_rows + 1);
int result_c = std::rand() % (matrix_cols - pattern_cols + 1);
for(int r = 0; r < pattern_rows; ++r) {
for(int c = 0; c < pattern_cols; ++c) {
pattern.at(r, c) = 'a' + (std::rand() % ('z' - 'a'));
matrix.at(result_r + r, result_c + c) = pattern.at(r, c);
}
}
std::cout << "input:\n";
std::cout << pattern_rows << " " << pattern_cols << std::endl;
for(int r = 0; r < pattern_rows; ++r) {
for(int c = 0; c < pattern_cols; ++c)
std::cout << pattern.at(r, c);
std::cout << "\n";
}
std::cout << matrix_rows << " " << matrix_cols << std::endl;
for(int r = 0; r < matrix_rows; ++r) {
for(int c = 0; c < matrix_cols; ++c)
std::cout << matrix.at(r, c);
std::cout << "\n";
}
std::cout << "output:\n";
std::cout << result_r << " " << result_c << std::endl;
return 0;
}
| [
"ldimat@gmail.com"
] | ldimat@gmail.com |
5ecd9f454b00df700a90a9c5bce1e3faf2bd27bc | 977e805639fe79488c80e54c1a273c93a873e625 | /src/qt/utilitydialog.cpp | 59dc3165c2c8128b1b5e1354edd751007188074e | [
"MIT"
] | permissive | ZsuDev/Mangaka-Core | adbb767b48560446944d004a499421c6b1a50849 | f09f91bf7fa73e6843a5ad11fd64106723196a65 | refs/heads/master | 2020-03-21T00:18:53.599763 | 2018-05-15T07:15:31 | 2018-05-15T07:15:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,929 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The Mangaka developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "utilitydialog.h"
#include "ui_helpmessagedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "intro.h"
#include "guiutil.h"
#include "clientversion.h"
#include "init.h"
#include "util.h"
#include <stdio.h>
#include <QCloseEvent>
#include <QLabel>
#include <QRegExp>
#include <QTextTable>
#include <QTextCursor>
#include <QVBoxLayout>
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget* parent, bool about) : QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nHelpMessageDialogWindow", this->size(), this);
QString version = tr("Mangaka Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
/* On x86 add a bit specifier to the version so that users can distinguish between
* 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
*/
#if defined(__x86_64__)
version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__)
version += " " + tr("(%1-bit)").arg(32);
#endif
if (about) {
setWindowTitle(tr("About Mangaka Core"));
/// HTML-format the license message from the core
QString licenseInfo = QString::fromStdString(LicenseInfo());
QString licenseInfoHTML = licenseInfo;
// Make URLs clickable
QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
uri.setMinimal(true); // use non-greedy matching
licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
// Replace newlines with HTML breaks
licenseInfoHTML.replace("\n\n", "<br><br>");
ui->aboutMessage->setTextFormat(Qt::RichText);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
text = version + "\n" + licenseInfo;
ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML);
ui->aboutMessage->setWordWrap(true);
ui->helpMessage->setVisible(false);
} else {
setWindowTitle(tr("Command-line options"));
QString header = tr("Usage:") + "\n" +
" mangaka-qt [" + tr("command-line options") + "] " + "\n";
QTextCursor cursor(ui->helpMessage->document());
cursor.insertText(version);
cursor.insertBlock();
cursor.insertText(header);
cursor.insertBlock();
std::string strUsage = HelpMessage(HMM_BITCOIN_QT);
strUsage += HelpMessageGroup(tr("UI Options:").toStdString());
strUsage += HelpMessageOpt("-choosedatadir", strprintf(tr("Choose data directory on startup (default: %u)").toStdString(), DEFAULT_CHOOSE_DATADIR));
strUsage += HelpMessageOpt("-lang=<lang>", tr("Set language, for example \"de_DE\" (default: system locale)").toStdString());
strUsage += HelpMessageOpt("-min", tr("Start minimized").toStdString());
strUsage += HelpMessageOpt("-rootcertificates=<file>", tr("Set SSL root certificates for payment request (default: -system-)").toStdString());
strUsage += HelpMessageOpt("-splash", strprintf(tr("Show splash screen on startup (default: %u)").toStdString(), DEFAULT_SPLASHSCREEN));
QString coreOptions = QString::fromStdString(strUsage);
text = version + "\n" + header + "\n" + coreOptions;
QTextTableFormat tf;
tf.setBorderStyle(QTextFrameFormat::BorderStyle_None);
tf.setCellPadding(2);
QVector<QTextLength> widths;
widths << QTextLength(QTextLength::PercentageLength, 35);
widths << QTextLength(QTextLength::PercentageLength, 65);
tf.setColumnWidthConstraints(widths);
QTextCharFormat bold;
bold.setFontWeight(QFont::Bold);
Q_FOREACH (const QString &line, coreOptions.split("\n")) {
if (line.startsWith(" -"))
{
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::PreviousCell);
cursor.movePosition(QTextCursor::NextRow);
cursor.insertText(line.trimmed());
cursor.movePosition(QTextCursor::NextCell);
} else if (line.startsWith(" ")) {
cursor.insertText(line.trimmed()+' ');
} else if (line.size() > 0) {
//Title of a group
if (cursor.currentTable())
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::Down);
cursor.insertText(line.trimmed(), bold);
cursor.insertTable(1, 2, tf);
}
}
ui->helpMessage->moveCursor(QTextCursor::Start);
ui->scrollArea->setVisible(false);
}
}
HelpMessageDialog::~HelpMessageDialog()
{
GUIUtil::saveWindowGeometry("nHelpMessageDialogWindow", this);
delete ui;
}
void HelpMessageDialog::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
fprintf(stdout, "%s\n", qPrintable(text));
}
void HelpMessageDialog::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
void HelpMessageDialog::on_okButton_accepted()
{
close();
}
/** "Shutdown" window */
ShutdownWindow::ShutdownWindow(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f)
{
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(new QLabel(
tr("Mangaka Core is shutting down...") + "<br /><br />" +
tr("Do not shut down the computer until this window disappears.")));
setLayout(layout);
}
void ShutdownWindow::showShutdownWindow(BitcoinGUI* window)
{
if (!window)
return;
// Show a simple window indicating shutdown status
QWidget* shutdownWindow = new ShutdownWindow();
// We don't hold a direct pointer to the shutdown window after creation, so use
// Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually.
shutdownWindow->setAttribute(Qt::WA_DeleteOnClose);
shutdownWindow->setWindowTitle(window->windowTitle());
// Center shutdown window at where main window was
const QPoint global = window->mapToGlobal(window->rect().center());
shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2);
shutdownWindow->show();
}
void ShutdownWindow::closeEvent(QCloseEvent* event)
{
event->ignore();
}
| [
"mangakacoin@gmail.com"
] | mangakacoin@gmail.com |
c5052c7aba41f69db14228cdf1da9b36699bb9e6 | d160bb839227b14bb25e6b1b70c8dffb8d270274 | /MCMS/Main/Processes/McmsNetwork/McmsNetworkLib/CMngntRmx2000.cpp | 2e19cb2fff2330543eca3657be3f997ed99f28cc | [] | no_license | somesh-ballia/mcms | 62a58baffee123a2af427b21fa7979beb1e39dd3 | 41aaa87d5f3b38bc186749861140fef464ddadd4 | refs/heads/master | 2020-12-02T22:04:46.442309 | 2017-07-03T06:02:21 | 2017-07-03T06:02:21 | 96,075,113 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,993 | cpp | /*
* CMngntRmx2000.cpp
*
* Created on: Jul 29, 2013
* Author: stanny
*/
#include "CMngntRmx2000.h"
#include "Trace.h"
#include "TraceStream.h"
#include "NetCommonDefines.h"
namespace McmsNetworkPackage {
CMngntRmx2000::CMngntRmx2000() {
}
CMngntRmx2000::~CMngntRmx2000() {
}
/*
STATUS CMngntRmx2000::ConfigureEthernetSettingsCpu(eConfigInterfaceType ifType, ePortSpeedType portSpeed)
{
if (!IsSystemFlagExist(flagIsTarget) )
{
TRACESTR(eLevelDebug) << "CMngntRmx2000 - no configuration should be done on Pizzas";
return STATUS_OK;
}
std::string stParams = ParsePortSpeed(portSpeed);
std::string eth = GetDeviceName(ifType);
std::string cmd;
//only for inner NIC eth0, settings are hardcoded
if("eth0" == eth)
stParams = "speed 100 autoneg off duplex full";
cmd = "/sbin/ethtool -s " + eth + " " + stParams;
std::string answer;
STATUS stat = SystemPipedCommand(cmd.c_str(),answer);
TRACESTR(stat ? eLevelError:eLevelInfoNormal) <<
"CMngntRmx2000::SetEthSetting :" << cmd << std::endl << answer;
if(STATUS_OK != stat)
{
stat = STATUS_FAIL;
}
return stat;
}
*/
eConfigInterfaceNum CMngntRmx2000::GetInterfaceNum(const eConfigInterfaceType ifType,eIpType ipType)
{
eConfigInterfaceNum retIfNum = eEth0;
//check if simulation
if(!IsSystemFlagExist(flagIsTarget))
return eEth0;
switch(ifType)
{
case(eSeparatedManagmentNetwork):
retIfNum = eEth0_2197;
break;
case(eInternalNetwork):
retIfNum = eEth0_2093;
break;
case(eSignalingNetwork):
retIfNum = eEth0_alias_2;
break;
case(eSeparatedSignalingNetwork):
retIfNum = eEth0_2198;
break;
case(eSeparatedSignalingNetwork_1_1):
retIfNum = eEth0_2012;
break;
case(eSeparatedSignalingNetwork_1_2):
retIfNum = eEth0_2013;
break;
case(eSeparatedSignalingNetwork_2_1):
retIfNum = eEth0_2022;
break;
case(eSeparatedSignalingNetwork_2_2):
retIfNum = eEth0_2023;
break;
case(ePermanentNetwork):
retIfNum = eEth0_2097;
break;
case eManagmentNetwork:
if(eIpType_IpV6 == ipType )
retIfNum =eEth0;
else
retIfNum = eEth0_alias_1;
break;
default:
retIfNum = eEth0_alias_1;
break;
}
return retIfNum;
}
eConfigDeviceName CMngntRmx2000::GetInterfaceDeviceNum(const eConfigInterfaceType ifType)
{
return eEth_0;
}
STATUS CMngntRmx2000::OnPreHandleNetworkSeparationConfigurations()
{
if(IsSystemFlagExist(flagSeperatedNetwork)&& IsSystemFlagExist(flagJitcMode))
{
TRACESTR(eLevelDebug) << "CMngntRmx2000 - is in Jitc and Network separation do network separation";
return STATUS_OK;
}
else
TRACESTR(eLevelDebug) << "CMngntRmx2000 - is NOT in Jitc and Network separation do not do network separation";
return MANGMENT_RMX200_STATUS_NO_NET_SEPERATION;
}
} /* namespace McmsNetworkPackage */
| [
"somesh.ballia@gmail.com"
] | somesh.ballia@gmail.com |
0a3a813bcf7a9668cecde69cac8d277c123d646a | 37a59450e0390266f87ea7b553c77a27fce56e44 | /Teacher/05Richer/step7_src_完成12345467/blockmgr.cpp | 46873434616ba603e5c0b5a727112e32136ed9d1 | [] | no_license | Ynjxsjmh/Monopoly | 231c78dc4944eebfd794846e8585e10cda644c19 | aeb0cc43e6e1d382c35aa918c26a6c34551b9a2d | refs/heads/master | 2021-07-20T01:04:43.684371 | 2020-07-07T14:16:06 | 2020-07-07T14:16:06 | 156,078,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | cpp | ///======================================================================
/// Project: Richer02
/// FileName: blockmgr.cpp
/// Desc: Richer 02
/// Author: Chen Wei
///======================================================================
#include "global.h"
#include "block.h"
#include "blockmgr.h"
BlockMgr* BlockMgr::mgr = nullptr;
BlockMgr* BlockMgr::getMgr()
{
if(mgr == nullptr) {
mgr = new BlockMgr;
}
return mgr;
}
void BlockMgr::releaseMgr()
{
delete mgr;
mgr = nullptr;
}
BlockMgr::BlockMgr()
{
prototypes[BlockID::NONE_BLOCK] = nullptr;
prototypes[BlockID::MONEY_BLOCK] = new MoneyBlock;
prototypes[BlockID::TRIP_BLOCK] = new TripBlock;
prototypes[BlockID::BAR_BLOCK] = new BarBlock;
prototypes[BlockID::SLIDE_BLOCK] = new SlideBlock;
}
BlockMgr::~BlockMgr()
{
//dtor
for(int i = 0; i < BlockID::BLOCK_COUNT; ++i) {
delete prototypes[i];
}
}
Block* BlockMgr::cloneBlock(int blockID)
{
if(blockID > BlockID::NONE_BLOCK && blockID < BlockID::BLOCK_COUNT) {
return prototypes[blockID]->clone();
}
return nullptr;
}
void BlockMgr::setPrototype(int blockID, Block* proto)
{
delete prototypes[blockID];
prototypes[blockID] = proto;
}
| [
"ynjxsjmh@gmail.com"
] | ynjxsjmh@gmail.com |
30f2d1ada61aa5350447039066adcad716322643 | f188da1a6a0c420713b35fb6421ab92804015004 | /changing_volume.cpp | 865c769b187209173d2ce4611e969b6d37c0599e | [] | no_license | nimishkapoor/cp_files | 4234eedd1035455b1b265a07fd78df104a2cff1f | acf28fa2ec442bbb1c6c4ef198e29d763e23d85d | refs/heads/master | 2020-05-30T16:13:24.845973 | 2019-12-08T20:17:17 | 2019-12-08T20:17:17 | 189,840,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{
int t;
cin>>t;
while(t--)
{
ll a,b;
cin>>a>>b;
ll x=max(a,b);
ll y=min(a,b);
ll dif=(x-y);
ll ans=0;
ans+=dif/5;
if(dif>=5)
{
dif-=5*ans;
}
ans+=dif/2;
if(dif>=2)
{
dif-=2*(dif/2);
}
if(dif==1)
{
ans++;
}
cout<<ans<<endl;
}
return 0;
}
| [
"nmshkpr@gmail.com"
] | nmshkpr@gmail.com |
ec8aa7d33259ff34cc9bbe490f588c9b4bebb31f | 5d525f82bd3a9395deb0caedf5dfb533ecb98ed4 | /Quelle.cpp | ed1e0466bd795d061542195f39d4544de4f91904 | [] | no_license | Wunderlag/BunnyGameWithClasses | e4979032891a153c277365a02c15ac484b753c7e | 49c890462418f2eb4f02911b78593201710bd31c | refs/heads/master | 2021-01-01T06:10:58.019733 | 2015-01-13T13:27:24 | 2015-01-13T13:27:24 | 29,190,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | cpp |
#include <iostream>
#include <string>
#include <random>
#include "Bunny.h"
using namespace std;
int main()
{
// creating first bunnies
Bunny::createBunnies(5, 'y'); // first parameter determines how many bunnies will be created, 2nd parameter only on gamestart 'y', else 'n'
// bunny breeding
int gameOver{ 1 };
while (gameOver >= 1)
{
Bunny::ageBunnies();
Bunny::createBunnies(Bunny::countBunnies(), 'n');
Bunny::listBunnies();
cout << "\nBirths: " << Bunny::countBunnies() << endl;
Bunny::makeBunniesCrazy();
system("PAUSE");
}
// Test output
//listOutput();
// cout << "\nErgebnis:\n" << bunnyCounting() << endl;
system("PAUSE");
return 0;
}
| [
"manuelgruenwald1@gmail.com"
] | manuelgruenwald1@gmail.com |
8ad9e87cc7751c3e20e71f3dca6bddc5011249d9 | effdc2a761c5fda7e4c3fedb0d874e194e2e3c78 | /Data-Structure/segment-tree.cc | c4231cd6d87dbc9142ee0167f9e7ba09b9592d9e | [] | no_license | duanqn/AC_lib | 286d955462e1a8b5447c27f6b41b1603004e9965 | 305fbabb9c7bcf3d8a4fbbc17bd9248492332cd9 | refs/heads/master | 2020-07-12T22:24:19.410464 | 2015-08-21T09:42:53 | 2015-08-21T09:42:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | cc | //@ Segment Tree
struct tree
{
int l, r;
tree *lc, *rc;
info i;
tree (int _l, int _r)
{
l = _l, r = _r;
lc = rc = 0;
if (l == r)
{
i = info(1, 1); // ...
return;
}
int m = (l + r) >> 1;
lc = new tree(l, m);
rc = new tree(m + 1, r);
i = lc->i + rc->i;
}
void modify (int p)
{
if (l == r)
{
i = info(0, 0); // ...
return;
}
int m = (l + r) >> 1;
if (p <= m) lc->modify(p);
else rc->modify(p);
i = lc->i + rc->i;
}
info query (int ql, int qr)
{
if (ql > qr) return info(0, 0);
if (ql <= l && r <= qr) return i;
int m = (l + r) >> 1;
info res(0, 0); // ...
if (ql <= m) res = lc->query(ql, qr);
if (qr > m) res = res + rc->query(ql, qr);
return res;
}
} *root;
| [
"wzy196@gmail.com"
] | wzy196@gmail.com |
56fe89ae1d46d0baba98d97b0fd081ad077cecce | 86be792acfc88fc25226fb24a0155d8eb6a4bb17 | /transmission_interface_extensions/include/transmission_interface_extensions/slider_crank_transmission_loader.hpp | a3b3afd74f3410eccc55d5e59019baf3c7c66d5f | [
"MIT"
] | permissive | yoshito-n-students/ros_control_extensions | 655bbaf6939e2e99bc0aaf106cba4884300338dc | 1eee21217708dcee80aa3d91b2c6415c1f4feffa | refs/heads/master | 2021-10-27T22:38:23.061846 | 2021-10-19T04:23:35 | 2021-10-19T04:23:35 | 228,334,348 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,631 | hpp | #ifndef TRANSMISSION_INTERFACE_EXTENSIONS_SLIDER_CRANK_TRANSMISSION_LOADER_HPP
#define TRANSMISSION_INTERFACE_EXTENSIONS_SLIDER_CRANK_TRANSMISSION_LOADER_HPP
#include <stdexcept>
#include <string>
#include <vector>
#include <ros/console.h>
#include <transmission_interface/transmission_interface_exception.h>
#include <transmission_interface/transmission_loader.h>
#include <transmission_interface_extensions/common_namespaces.hpp>
#include <transmission_interface_extensions/slider_crank_transmission.hpp>
#include <boost/lexical_cast.hpp>
namespace transmission_interface_extensions {
class SliderCrankTransmissionLoader : public ti::TransmissionLoader {
public:
virtual ti::TransmissionSharedPtr load(const ti::TransmissionInfo &src_info) {
try {
SliderCrankTransmissionInfo dst_info;
parseActuator(src_info, &dst_info);
parseJoints(src_info, &dst_info);
return ti::TransmissionSharedPtr(new SliderCrankTransmission(dst_info));
} catch (const std::exception &ex) {
ROS_ERROR_STREAM("Exception caught on loading SliderCrankTransmission named "
<< src_info.name_ << ": " << ex.what());
return ti::TransmissionSharedPtr();
}
}
private:
//
// helper functions to parse xml
//
// raw values in a xml element
static double parseOptionalValue(const TiXmlElement &xml, const std::string &child_name,
const double default_value) {
const TiXmlElement *const child(xml.FirstChildElement(child_name));
return child ? boost::lexical_cast< double >(child->GetText()) : default_value;
}
static double parseRequiredValue(const TiXmlElement &xml, const std::string &child_name) {
const TiXmlElement *const child(xml.FirstChildElement(child_name));
if (!child) {
throw ti::TransmissionInterfaceException("Missing required element <" + child_name + ">");
}
return boost::lexical_cast< double >(child->GetText());
}
// <actuator> element in xml
static void parseActuator(const ti::TransmissionInfo &src_info,
SliderCrankTransmissionInfo *dst_info) {
// make sure exactly 1 actuator is given
if (src_info.actuators_.size() != 1) {
throw ti::TransmissionInterfaceException(
"Invalid number of actuators: " +
boost::lexical_cast< std::string >(src_info.actuators_.size()));
}
// parse params from the <actuator> element
const TiXmlElement actuator_el(loadXmlElement(src_info.actuators_[0].xml_element_));
dst_info->actuator_reduction = parseOptionalValue(actuator_el, "mechanicalReduction", 1.);
}
// <joint> element in xml
static std::size_t findJointByRole(const std::vector< ti::JointInfo > &joints,
const std::string &role) {
for (std::size_t i = 0; i < joints.size(); ++i) {
if (joints[i].role_ == role) {
return i;
}
}
throw ti::TransmissionInterfaceException("No joint with the role of " + role);
}
static void parseJoints(const ti::TransmissionInfo &src_info,
SliderCrankTransmissionInfo *dst_info) {
// makes sure exactly 3 joint are given
if (src_info.joints_.size() != 3) {
throw ti::TransmissionInterfaceException(
"Invalid number of joints: " +
boost::lexical_cast< std::string >(src_info.joints_.size()));
}
// parse params from the <joint> element with "crank" role
dst_info->crank_joint_id = findJointByRole(src_info.joints_, "crank");
const TiXmlElement crank_joint_el(
loadXmlElement(src_info.joints_[dst_info->crank_joint_id].xml_element_));
dst_info->crank_offset = parseOptionalValue(crank_joint_el, "offset", 0.);
dst_info->crank_length = parseRequiredValue(crank_joint_el, "length");
// parse params from the <joint> element with "bar" role
dst_info->bar_joint_id = findJointByRole(src_info.joints_, "bar");
const TiXmlElement bar_joint_el(
loadXmlElement(src_info.joints_[dst_info->bar_joint_id].xml_element_));
dst_info->bar_length = parseRequiredValue(bar_joint_el, "length");
// parse params from the <joint> element with "slider" role
dst_info->slider_joint_id = findJointByRole(src_info.joints_, "slider");
const TiXmlElement slider_joint_el(
loadXmlElement(src_info.joints_[dst_info->slider_joint_id].xml_element_));
dst_info->slider_offset_x = parseOptionalValue(slider_joint_el, "offsetX", 0.);
dst_info->slider_offset_y = parseOptionalValue(slider_joint_el, "offsetY", 0.);
}
};
} // namespace transmission_interface_extensions
#endif
| [
"okada@rm.is.tohoku.ac.jp"
] | okada@rm.is.tohoku.ac.jp |
ad4191e6f980c6849819a0ff0067bb651d547f8a | 671b33372cd8eaf6b63284b03b94fbaf5eb8134e | /protocols/zlight/zl_Panic.cc | af506fb01f00bff94f13000da79b12533100c08a | [
"MIT"
] | permissive | LPD-EPFL/consensusinside | 41f0888dc7c0f9bd25f1ff75781e7141ffa21894 | 4ba9c5274a9ef5bd5f0406b70d3a321e7100c8ac | refs/heads/master | 2020-12-24T15:13:51.072881 | 2014-11-30T11:27:41 | 2014-11-30T11:27:41 | 23,539,134 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 840 | cc | #include <strings.h>
#include "th_assert.h"
#include "zl_Message_tags.h"
#include "zl_Replica.h"
#include "zl_Panic.h"
#include "zl_Request.h"
#include "zl_Principal.h"
#define MAX_NON_DET_SIZE 8
zl_Panic::zl_Panic(zl_Panic_rep *cont)
{
th_assert(ALIGNED(cont), "Improperly aligned pointer");
msg = cont;
max_size = -1; // To prevent contents from being deallocated or trimmed
}
zl_Panic::zl_Panic(zl_Request *req) :
zl_Message(zl_Panic_tag, zl_Max_message_size)
{
rep().cid = req->client_id();
rep().req_id = req->request_id();
set_size(sizeof(zl_Panic_rep));
}
bool zl_Panic::convert(zl_Message *m1, zl_Panic *&m2)
{
if (!m1->has_tag(zl_Panic_tag, sizeof(zl_Panic_rep)))
return false;
// m1->trim(); We trim the OR message after authenticating the message
m2 = (zl_Panic*)m1;
return true;
}
| [
"tudor.david@gmail.com"
] | tudor.david@gmail.com |
10baa99d28bcf4db073dba36fb2ebfcf5e402749 | 43452fbcbe43bda467cd24e5f161c93535bc2bd5 | /src/geomega/src/MDDetector.cxx | 9701ae2f4caccb861ed1b22f78e1270ed0154373 | [] | no_license | xtsinghua/megalib | cae2e256ad5ddf9d7b6cdb9d2b680a76dd902e4f | 0bd5c161c606c32a642efb34a963b6e2c07b81a0 | refs/heads/master | 2021-01-11T05:46:51.442857 | 2015-04-15T17:56:22 | 2015-04-15T17:56:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55,470 | cxx | /*
* MDDetector.cxx
*
*
* Copyright (C) by Andreas Zoglauer.
* All rights reserved.
*
*
* This code implementation is the intellectual property of
* Andreas Zoglauer.
*
* By copying, distributing or modifying the Program (or any work
* based on the Program) you indicate your acceptance of this statement,
* and all its terms.
*
*/
////////////////////////////////////////////////////////////////////////////////
//
// MDDetector
//
////////////////////////////////////////////////////////////////////////////////
// Include the header:
#include "MDDetector.h"
// Standard libs:
#include <limits>
#include <iostream>
using namespace std;
// ROOT libs:
#include "TMath.h"
// MEGALib libs:
#include "MAssert.h"
#include "MStreams.h"
#include "MDShapeBRIK.h"
////////////////////////////////////////////////////////////////////////////////
#ifdef ___CINT___
ClassImp(MDDetector)
#endif
////////////////////////////////////////////////////////////////////////////////
int MDDetector::m_IDCounter = 1;
int MDDetector::m_SensIDCounter = 1;
// Never ever change this numbering, unless you want to break the sim files!!!!
const int MDDetector::c_NoDetectorType = 0;
const int MDDetector::c_Strip2D = 1;
const int MDDetector::c_Calorimeter = 2;
const int MDDetector::c_Strip3D = 3;
const int MDDetector::c_ACS = 4;
const int MDDetector::c_Scintillator = 4;
const int MDDetector::c_DriftChamber = 5;
const int MDDetector::c_Strip3DDirectional = 6;
const int MDDetector::c_AngerCamera = 7;
const int MDDetector::c_Voxel3D = 8;
const int MDDetector::c_MinDetector = 1;
const int MDDetector::c_MaxDetector = 8;
const MString MDDetector::c_NoDetectorTypeName = "NoDetectorType";
const MString MDDetector::c_Strip2DName = "Strip2D";
const MString MDDetector::c_CalorimeterName = "Calorimeter";
const MString MDDetector::c_Strip3DName = "Strip3D";
const MString MDDetector::c_ACSName = "Scintillator";
const MString MDDetector::c_ScintillatorName = "Scintillator";
const MString MDDetector::c_DriftChamberName = "DriftChamber";
const MString MDDetector::c_Strip3DDirectionalName = "Strip3DDirectional";
const MString MDDetector::c_AngerCameraName = "AngerCamera";
const MString MDDetector::c_Voxel3DName = "Voxel3D";
const int MDDetector::c_EnergyResolutionTypeUnknown = 0;
const int MDDetector::c_EnergyResolutionTypeNone = 1;
const int MDDetector::c_EnergyResolutionTypeIdeal = 2;
const int MDDetector::c_EnergyResolutionTypeGauss = 3;
const int MDDetector::c_EnergyResolutionTypeLorentz = 4;
const int MDDetector::c_EnergyResolutionTypeGaussLandau = 5;
const int MDDetector::c_EnergyLossTypeUnknown = 0;
const int MDDetector::c_EnergyLossTypeNone = 1;
const int MDDetector::c_EnergyLossTypeMap = 2;
const int MDDetector::c_TimeResolutionTypeUnknown = 0;
const int MDDetector::c_TimeResolutionTypeNone = 1;
const int MDDetector::c_TimeResolutionTypeIdeal = 2;
const int MDDetector::c_TimeResolutionTypeGauss = 3;
const int MDDetector::c_DepthResolutionTypeUnknown = 0;
const int MDDetector::c_DepthResolutionTypeNone = 1;
const int MDDetector::c_DepthResolutionTypeIdeal = 2;
const int MDDetector::c_DepthResolutionTypeGauss = 3;
const int MDDetector::c_GuardringEnergyResolutionTypeUnknown = 0;
const int MDDetector::c_GuardringEnergyResolutionTypeNone = 1;
const int MDDetector::c_GuardringEnergyResolutionTypeIdeal = 2;
const int MDDetector::c_GuardringEnergyResolutionTypeGauss = 3;
////////////////////////////////////////////////////////////////////////////////
MDDetector::MDDetector(MString Name)
{
// default constructor
// ID of this detector:
if (m_IDCounter == numeric_limits<int>::max()) {
m_IDCounter = 0;
} else {
m_ID = m_IDCounter++;
}
m_Name = Name;
m_Description = "Unknown";
m_Type = c_NoDetectorType;
m_DetectorVolume = 0;
m_CommonVolume = 0;
m_StructuralDimension = g_VectorNotDefined;
m_StructuralPitch = g_VectorNotDefined;
m_StructuralOffset = g_VectorNotDefined;
m_StructuralSize = g_VectorNotDefined;
m_IsNamedDetector = false;
m_NamedAfter = 0;
m_NoiseThresholdEqualsTriggerThresholdSet = false;
m_NoiseThresholdEqualsTriggerThreshold = false;
m_NoiseThreshold = g_DoubleNotDefined;
m_NoiseThresholdSigma = g_DoubleNotDefined;
m_TriggerThreshold = g_DoubleNotDefined;
m_TriggerThresholdSigma = g_DoubleNotDefined;
m_FailureRate = g_DoubleNotDefined;
m_Overflow = g_DoubleNotDefined;
m_OverflowSigma = g_DoubleNotDefined;
m_EnergyLossType = c_EnergyLossTypeUnknown;
m_EnergyResolutionType = c_EnergyResolutionTypeUnknown;
m_TimeResolutionType = c_TimeResolutionTypeUnknown;
m_PulseShapeSet = false;
m_PulseShape = 0;
m_PulseShapeMin = 0;
m_PulseShapeMax = 0;
m_NoiseActive = true;
m_UseDivisions = false;
m_ShortNameDivisionX = g_StringNotDefined;
m_ShortNameDivisionY = g_StringNotDefined;
m_ShortNameDivisionZ = g_StringNotDefined;
m_HasGuardring = false;
m_AreBlockedTriggerChannelsUsed = false;
m_EnergyCalibrationSet = false;
m_UseEnergyCalibration = false;
}
////////////////////////////////////////////////////////////////////////////////
MDDetector::MDDetector(const MDDetector& D)
{
// Copy constructor
m_Name = D.m_Name;
m_Type = D.m_Type;
m_Description = D.m_Description;
for (unsigned int i = 0; i < m_SVs.size(); ++i) {
m_SVs.push_back(D.m_SVs[i]);
}
m_DetectorVolume = D.m_DetectorVolume;
m_CommonVolume = D.m_CommonVolume;
m_ID = m_IDCounter++;
m_SensID = m_SensIDCounter++;
m_IsNamedDetector = D.m_IsNamedDetector;
m_NamedAfter = D.m_NamedAfter;
m_UseDivisions = D.m_UseDivisions;
m_ShortNameDivisionX = D.m_ShortNameDivisionX;
m_ShortNameDivisionY = D.m_ShortNameDivisionY;
m_ShortNameDivisionZ = D.m_ShortNameDivisionZ;
m_EnergyLossType = D.m_EnergyLossType;
m_EnergyLossMap = D.m_EnergyLossMap;
m_EnergyResolutionType = D.m_EnergyResolutionType;
m_EnergyResolutionPeak1 = D.m_EnergyResolutionPeak1;
m_EnergyResolutionWidth1 = D.m_EnergyResolutionWidth1;
m_EnergyResolutionPeak2 = D.m_EnergyResolutionPeak2;
m_EnergyResolutionWidth2 = D.m_EnergyResolutionWidth2;
m_EnergyResolutionRatio = D.m_EnergyResolutionRatio;
m_TimeResolutionType = D.m_TimeResolutionType;
m_TimeResolution = D.m_TimeResolution;
m_FailureRate = D.m_FailureRate;
m_NoiseThresholdEqualsTriggerThresholdSet = D.m_NoiseThresholdEqualsTriggerThresholdSet;
m_NoiseThresholdEqualsTriggerThreshold = D.m_NoiseThresholdEqualsTriggerThreshold;
m_NoiseThreshold = D.m_NoiseThreshold;
m_NoiseThresholdSigma = D.m_NoiseThresholdSigma;
m_TriggerThreshold = D.m_TriggerThreshold;
m_TriggerThresholdSigma = D.m_TriggerThresholdSigma;
m_Overflow = D.m_Overflow;
m_OverflowSigma = D.m_OverflowSigma;
m_StructuralDimension = D.m_StructuralDimension;
m_StructuralSize = D.m_StructuralSize;
m_StructuralOffset = D.m_StructuralOffset;
m_StructuralPitch = D.m_StructuralPitch;
m_HasGuardring = D.m_HasGuardring;
if (D.m_PulseShape != 0) {
m_PulseShape = new TF1(*D.m_PulseShape);
} else {
m_PulseShape = 0;
}
m_PulseShapeMin = D.m_PulseShapeMin;
m_PulseShapeMax = D.m_PulseShapeMax;
m_NoiseActive = D.m_NoiseActive;
m_AreBlockedTriggerChannelsUsed = D.m_AreBlockedTriggerChannelsUsed;
m_BlockedTriggerChannels = D.m_BlockedTriggerChannels;
m_EnergyCalibrationSet = D.m_EnergyCalibrationSet;
m_UseEnergyCalibration = D.m_UseEnergyCalibration;
m_EnergyCalibration = D.m_EnergyCalibration;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::CopyDataToNamedDetectors()
{
//! Copy data to named detectors
if (m_IsNamedDetector == true) return true;
for (unsigned int d = 0; d < m_NamedDetectors.size(); ++d) {
m_NamedDetectors[d]->m_Description = m_Description;
for (unsigned int i = 0; i < m_SVs.size(); ++i) {
m_NamedDetectors[d]->m_SVs.push_back(m_SVs[i]);
}
m_NamedDetectors[d]->m_DetectorVolume = m_DetectorVolume;
m_NamedDetectors[d]->m_UseDivisions = m_UseDivisions;
m_NamedDetectors[d]->m_ShortNameDivisionX = m_ShortNameDivisionX;
m_NamedDetectors[d]->m_ShortNameDivisionY = m_ShortNameDivisionY;
m_NamedDetectors[d]->m_ShortNameDivisionZ = m_ShortNameDivisionZ;
if (m_NamedDetectors[d]->m_EnergyLossType == c_EnergyLossTypeUnknown &&
m_EnergyLossType != c_EnergyLossTypeUnknown) {
m_NamedDetectors[d]->m_EnergyLossType = m_EnergyLossType;
m_NamedDetectors[d]->m_EnergyLossMap = m_EnergyLossMap;
}
if (m_NamedDetectors[d]->m_EnergyResolutionType == c_EnergyResolutionTypeUnknown &&
m_EnergyResolutionType != c_EnergyResolutionTypeUnknown) {
m_NamedDetectors[d]->m_EnergyResolutionType = m_EnergyResolutionType;
m_NamedDetectors[d]->m_EnergyResolutionPeak1 = m_EnergyResolutionPeak1;
m_NamedDetectors[d]->m_EnergyResolutionWidth1 = m_EnergyResolutionWidth1;
m_NamedDetectors[d]->m_EnergyResolutionPeak2 = m_EnergyResolutionPeak2;
m_NamedDetectors[d]->m_EnergyResolutionWidth2 = m_EnergyResolutionWidth2;
m_NamedDetectors[d]->m_EnergyResolutionRatio = m_EnergyResolutionRatio;
}
if (m_NamedDetectors[d]->m_TimeResolutionType == c_TimeResolutionTypeUnknown &&
m_TimeResolutionType != c_TimeResolutionTypeUnknown) {
m_NamedDetectors[d]->m_TimeResolutionType = m_TimeResolutionType;
m_NamedDetectors[d]->m_TimeResolution = m_TimeResolution;
}
if (m_NamedDetectors[d]->m_FailureRate == g_DoubleNotDefined &&
m_FailureRate != g_DoubleNotDefined) {
m_NamedDetectors[d]->m_FailureRate = m_FailureRate;
}
if (m_NamedDetectors[d]->m_NoiseThresholdEqualsTriggerThresholdSet == false &&
m_NoiseThresholdEqualsTriggerThresholdSet == true) {
m_NamedDetectors[d]->m_NoiseThresholdEqualsTriggerThresholdSet = m_NoiseThresholdEqualsTriggerThresholdSet;
m_NamedDetectors[d]->m_NoiseThresholdEqualsTriggerThreshold = m_NoiseThresholdEqualsTriggerThreshold;
}
if (m_NamedDetectors[d]->m_NoiseThreshold == g_DoubleNotDefined &&
m_NoiseThreshold != g_DoubleNotDefined) {
m_NamedDetectors[d]->m_NoiseThreshold = m_NoiseThreshold;
m_NamedDetectors[d]->m_NoiseThresholdSigma = m_NoiseThresholdSigma;
}
if (m_NamedDetectors[d]->m_TriggerThreshold == g_DoubleNotDefined &&
m_TriggerThreshold != g_DoubleNotDefined) {
m_NamedDetectors[d]->m_TriggerThreshold = m_TriggerThreshold;
m_NamedDetectors[d]->m_TriggerThresholdSigma = m_TriggerThresholdSigma;
}
if (m_NamedDetectors[d]->m_Overflow == g_DoubleNotDefined &&
m_Overflow != g_DoubleNotDefined) {
m_NamedDetectors[d]->m_Overflow = m_Overflow;
m_NamedDetectors[d]->m_OverflowSigma = m_OverflowSigma;
}
m_NamedDetectors[d]->m_StructuralDimension = m_StructuralDimension;
m_NamedDetectors[d]->m_StructuralSize = m_StructuralSize;
m_NamedDetectors[d]->m_StructuralOffset = m_StructuralOffset;
m_NamedDetectors[d]->m_StructuralPitch = m_StructuralPitch;
m_NamedDetectors[d]->m_HasGuardring = m_HasGuardring;
if (m_PulseShape != 0) m_NamedDetectors[d]->m_PulseShape = new TF1(*m_PulseShape);
m_NamedDetectors[d]->m_PulseShapeMin = m_PulseShapeMin;
m_NamedDetectors[d]->m_PulseShapeMax = m_PulseShapeMax;
m_NamedDetectors[d]->m_NoiseActive = m_NoiseActive;
m_NamedDetectors[d]->m_AreBlockedTriggerChannelsUsed = m_AreBlockedTriggerChannelsUsed;
m_NamedDetectors[d]->m_BlockedTriggerChannels = m_BlockedTriggerChannels;
if (m_NamedDetectors[d]->m_EnergyCalibrationSet == false &&
m_EnergyCalibrationSet == true) {
m_NamedDetectors[d]->m_EnergyCalibrationSet = m_EnergyCalibrationSet;
m_NamedDetectors[d]->m_UseEnergyCalibration = m_UseEnergyCalibration;
m_NamedDetectors[d]->m_EnergyCalibration = m_EnergyCalibration;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
MDDetector::~MDDetector()
{
// default destructor
delete m_PulseShape;
}
////////////////////////////////////////////////////////////////////////////////
MString MDDetector::GetDetectorTypeName(const int Type)
{
// Return the string description of this detector type:
if (Type == c_Strip2D) {
return c_Strip2DName;
} else if (Type == c_Calorimeter ) {
return c_CalorimeterName;
} else if (Type == c_Strip3D) {
return c_Strip3DName;
} else if (Type == c_ACS || Type == c_Scintillator) {
return c_ScintillatorName;
} else if (Type == c_DriftChamber) {
return c_DriftChamberName;
} else if (Type == c_AngerCamera) {
return c_AngerCameraName;
} else if (Type == c_Voxel3D) {
return c_Voxel3DName;
}
merr<<"Unknown detector type: "<<Type<<endl;
return c_NoDetectorTypeName;
}
////////////////////////////////////////////////////////////////////////////////
int MDDetector::GetDetectorType(const MString& Type)
{
// Return the string description of this detector type:
if (Type == c_Strip2DName) {
return c_Strip2D;
} else if (Type == c_CalorimeterName) {
return c_Calorimeter;
} else if (Type == c_Strip3DName) {
return c_Strip3D;
} else if (Type == c_ACSName || Type == c_ScintillatorName) {
return c_Scintillator;
} else if (Type == c_DriftChamberName) {
return c_DriftChamber;
} else if (Type == c_Strip3DDirectionalName) {
return c_Strip3DDirectional;
} else if (Type == c_AngerCameraName) {
return c_AngerCamera;
}
merr<<"Unknown detector type: "<<Type<<show;
return c_NoDetectorType;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::IsValidDetectorType(const MString& Name)
{
//
if (Name == c_Strip2DName ||
Name == c_CalorimeterName ||
Name == c_Strip3DName ||
Name == c_Strip3DDirectionalName ||
Name == c_ScintillatorName ||
Name == c_DriftChamberName ||
Name == c_AngerCameraName) {
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::IsValidDetectorType(int ID)
{
//
if (ID >= c_MinDetector && ID <= c_MaxDetector) {
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::UseDivisions(const MString& ShortNameX,
const MString& ShortNameY,
const MString& ShortNameZ)
{
m_UseDivisions = true;
m_ShortNameDivisionX = ShortNameX;
m_ShortNameDivisionY = ShortNameY;
m_ShortNameDivisionZ = ShortNameZ;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetNoiseThreshold(const double Threshold)
{
//
m_NoiseThreshold = Threshold;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetNoiseThreshold(const MVector& Position) const
{
//
return m_NoiseThreshold;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetTriggerThreshold(const double Threshold)
{
//
m_TriggerThreshold = Threshold;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetTriggerThreshold(const MVector& Position) const
{
//
return m_TriggerThreshold;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetSecureUpperLimitTriggerThreshold() const
{
// In ANY case the real trigger threshold is below this value:
return 1.25*m_TriggerThreshold + 7.0*m_TriggerThresholdSigma;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetNoiseThresholdSigma(const double ThresholdSigma)
{
//
m_NoiseThresholdSigma = ThresholdSigma;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetNoiseThresholdSigma(const MVector& Position) const
{
//
return m_NoiseThresholdSigma;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetTriggerThresholdSigma(const double ThresholdSigma)
{
//
m_TriggerThresholdSigma = ThresholdSigma;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetTriggerThresholdSigma(const MVector& Position) const
{
//
return m_TriggerThresholdSigma;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetPulseShape(const double Pol0, const double Pol1, const double Pol2,
const double Pol3, const double Pol4, const double Pol5,
const double Pol6, const double Pol7, const double Pol8,
const double Pol9, const double Min, const double Max)
{
m_PulseShapeMin = Min;
m_PulseShapeMax = Max;
delete m_PulseShape;
m_PulseShape = new TF1("PulseShape", "pol9", Min, Max);
m_PulseShape->SetParameters(Pol0, Pol1, Pol2, Pol3, Pol4, Pol5, Pol6, Pol7, Pol8, Pol9);
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::HasTimeResolution() const
{
// Return true if the detector has a time resolution
if (m_TimeResolutionType != c_TimeResolutionTypeNone &&
m_TimeResolutionType != c_TimeResolutionTypeUnknown) {
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::ApplyPulseShape(const double NanoSeconds, const double Energy) const
{
if (m_PulseShape == 0 ||
NanoSeconds < m_PulseShapeMin ||
NanoSeconds > m_PulseShapeMax) {
return 0;
}
return m_PulseShape->Eval(NanoSeconds)*Energy;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::ApplyEnergyResolution(double& Energy, const MVector& Position) const
{
// Noise the energy...
if (m_EnergyResolutionType == c_EnergyResolutionTypeNone) {
Energy = 0;
} else if (m_EnergyResolutionType == c_EnergyResolutionTypeIdeal) {
// do nothing
} else if (m_EnergyResolutionType == c_EnergyResolutionTypeGauss) {
Energy = GetEnergyResolutionPeak1(Energy, Position) +
gRandom->Gaus(0.0, GetEnergyResolutionWidth1(Energy, Position));
} else if (m_EnergyResolutionType == c_EnergyResolutionTypeLorentz) {
double Peak = GetEnergyResolutionPeak1(Energy, Position);
double Width = 2.35/2*GetEnergyResolutionWidth1(Energy, Position);
static const double Min = 0.0025;
double CutOff = sqrt((Width*Width*(1-Min))/Min);
double E = 0.0;
double Height = 0.0;
// sample the Lorentz distribution
do {
E = gRandom->Rndm()*CutOff;
Height = Width*Width/(Width*Width + E*E);
} while (gRandom->Rndm() > Height);
if (gRandom->Rndm() >= 0.5) {
Energy = Peak+E;
} else {
Energy = Peak-E;
}
} else if (m_EnergyResolutionType == c_EnergyResolutionTypeGaussLandau) {
double ScalerGauss = GetEnergyResolutionRatio(Energy, Position);
double SigmaGauss = GetEnergyResolutionWidth1(Energy, Position);
double MeanGauss = GetEnergyResolutionPeak1(Energy, Position);
double ScalerLandau = 1-ScalerGauss;
double SigmaLandau = GetEnergyResolutionWidth2(Energy, Position);
double MeanLandau = GetEnergyResolutionPeak2(Energy, Position);
// Determine the maximum of the distribution for the given input energy
double Max = 0;
double arg = (Energy - MeanGauss)/SigmaGauss;
Max += ScalerGauss*TMath::Exp(-0.5*arg*arg);
Max += ScalerLandau*TMath::Landau(-Energy + MeanLandau, 0, SigmaLandau);
double E;
double EMin = MeanGauss - 10*SigmaLandau-10*SigmaGauss;
if (EMin < 0) EMin = 0;
double EMax = MeanGauss + 4*SigmaLandau+4*SigmaGauss;
double Random = 0.0;
int Trials = 0;
do {
// x-value:
E = gRandom->Rndm()*(EMax - EMin) + EMin;
arg = (E - MeanGauss)/SigmaGauss;
Random = 0.0;
Random += ScalerGauss*TMath::Exp(-0.5*arg*arg);
Random += ScalerLandau*TMath::Landau(-E + MeanLandau, 0, SigmaLandau);
//cout<<"R: "<<Random<<" - Max: "<<Max<<" - Energy: "<<MeanGauss<<endl;
if (++Trials >= 100) {
MeanGauss = 0;
break;
}
} while (Random < gRandom->Rndm()*Max);
Energy = E;
} else {
merr<<"Unknown energy resolution type!!!!"<<endl;
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::ApplyEnergyCalibration(double& Energy) const
{
// Retrieve a calibrated energy
if (m_UseEnergyCalibration == true) {
Energy = m_EnergyCalibration.Evaluate(Energy);
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::ApplyTimeResolution(double& Time, const double Energy) const
{
// Noise the time...
if (m_TimeResolutionType == c_TimeResolutionTypeNone) {
Time = 0;
} else if (m_TimeResolutionType == c_TimeResolutionTypeIdeal) {
// do nothing
} else if (m_TimeResolutionType == c_TimeResolutionTypeGauss) {
Time = gRandom->Gaus(Time, GetTimeResolution(Energy));
} else {
merr<<"Unknown time resolution type: "<<m_TimeResolutionType<<endl;
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::ApplyNoiseThreshold(double& Energy, const MVector& Position) const
{
// Test if the energy is in the noise threshold regime and apply it
double NoiseThreshold = 0.0;
if (m_NoiseThresholdEqualsTriggerThreshold == true) {
// If the flag is set no own noise threshold is given...
NoiseThreshold = gRandom->Gaus(GetTriggerThreshold(Position), m_TriggerThresholdSigma);
} else {
NoiseThreshold = gRandom->Gaus(GetNoiseThreshold(Position), m_NoiseThresholdSigma);
}
if (Energy < NoiseThreshold) {
Energy = 0;
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::ApplyOverflow(double& Energy) const
{
// Test if the energy is in the overflow and apply it
double Overflow = gRandom->Gaus(m_Overflow, m_OverflowSigma);
if (Energy > Overflow) {
Energy = Overflow;
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::IsAboveTriggerThreshold(const double& Energy, const MDGridPoint& Point) const
{
// Is this hit above the trigger threshold ?
// If the channel is blocked from triggering, we are per definition never above the trigger threshold...
if (m_AreBlockedTriggerChannelsUsed == true) {
if (m_BlockedTriggerChannels.GetVoxelValue(Point) > 0.0) {
return false;
}
}
// Given this flag, in case we passed the noise criteria, we also have a trigger:
if (m_NoiseThresholdEqualsTriggerThreshold == true) {
return true;
}
// If you change anything here, make sure to change GetSecureUpperLimitTriggerThreshold !!!!
double NoisedThreshold =
gRandom->Gaus(GetTriggerThreshold(MVector(0.0, 0.0, Point.GetPosition().Z())),
m_TriggerThresholdSigma);
if (Energy > NoisedThreshold) {
return true;
} else {
return false;
}
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetOverflow(const double Overflow)
{
// Set the overflow
m_Overflow = Overflow;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetOverflow() const
{
// Return the overflow
return m_Overflow;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetOverflowSigma(const double Avg)
{
// Set the sigma value for the overflow bin
m_OverflowSigma = Avg;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetOverflowSigma() const
{
// Return the sigma value for the overflow bin
return m_OverflowSigma;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetFailureRate(const double FailureRate)
{
// Set the percentage [0..1] of not connected pixels
m_FailureRate = FailureRate;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetFailureRate() const
{
// Return the percentage [0..1] of not connected pixels
return m_FailureRate;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetStructuralOffset(const MVector& Offset)
{
// Set the Offset to the first sensitive volume from
// -x, -y, -z direction:
//cout<<"Setting struct off for "<<m_Name<<endl;
m_StructuralOffset = Offset;
}
////////////////////////////////////////////////////////////////////////////////
MVector MDDetector::GetStructuralOffset() const
{
// Return the Offset to the first sensitive volume from
// -x, -y, -z direction:
return m_StructuralOffset;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetStructuralPitch(const MVector& Pitch)
{
// Set the pitch between the sensitive volumes of this detector
//cout<<"Setting struct pitch for "<<m_Name<<endl;
m_StructuralPitch = Pitch;
}
////////////////////////////////////////////////////////////////////////////////
MVector MDDetector::GetStructuralPitch() const
{
// Return the pitch between the sensitive volumes of this detector
return m_StructuralPitch;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::AddSensitiveVolume(MDVolume *Volume)
{
// Add a sensitive volume to this detector
m_SVs.push_back(Volume);
Volume->SetSensitiveVolumeID(m_SensIDCounter++);
Volume->SetDetector(this);
}
////////////////////////////////////////////////////////////////////////////////
MDVolume* MDDetector::GetSensitiveVolume(const unsigned int i)
{
//
if (i < GetNSensitiveVolumes()) {
return m_SVs[i];
} else {
mout<<"MDVolume* MDDetector::GetSensitiveVolumeAt(int i)"<<endl;
mout<<"Index ("<<i<<") out of bounds (0, "<<GetNSensitiveVolumes()-1<<")"<<endl;
return 0;
}
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDDetector::GetNSensitiveVolumes() const
{
//
return m_SVs.size();
}
////////////////////////////////////////////////////////////////////////////////
int MDDetector::GetGlobalNSensitiveVolumes() const
{
//
return m_SensIDCounter-1;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetEnergyLossMap(const MString& EnergyLossMap)
{
// Use a energy loss based on a 3D energy loss map
if (m_EnergyLossMap.Set(EnergyLossMap, "DP", MFunction3D::c_InterpolationLinear) == false) {
m_EnergyLossType = c_EnergyLossTypeNone;
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Cannot read energy loss map!"<<endl;
} else {
m_EnergyLossType = c_EnergyLossTypeMap;
}
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::SetEnergyResolutionType(const int EnergyResolutionType)
{
//! Set the energy resolution type, return false if you try to overwrite an existing type
if (m_EnergyResolutionType == EnergyResolutionType) return true;
if (m_EnergyResolutionType != c_EnergyResolutionTypeUnknown) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"You can only set an energy resolution type once!"<<endl;
return false;
}
if (EnergyResolutionType == c_EnergyResolutionTypeIdeal ||
EnergyResolutionType == c_EnergyResolutionTypeNone ||
EnergyResolutionType == c_EnergyResolutionTypeGauss ||
EnergyResolutionType == c_EnergyResolutionTypeLorentz ||
EnergyResolutionType == c_EnergyResolutionTypeGaussLandau) {
m_EnergyResolutionType = EnergyResolutionType;
} else {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Unknown energy resolution type: "<<EnergyResolutionType<<endl;
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetEnergyResolution(const double InputEnergy,
const double Peak1,
const double Width1,
const double Peak2,
const double Width2,
const double Ratio)
{
// Set the energy resolution
if (InputEnergy < 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Input energy for energy resolution needs to be non-negative!"<<endl;
return;
}
if (Peak1 < 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Energy peak for energy resolution needs to be positive!"<<endl;
return;
}
if (Width1 < 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Energy peak width for energy resolution needs to be non-negative!"<<endl;
return;
}
if (Peak2 < 0 && Peak2 != g_DoubleNotDefined) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Energy peak for energy resolution needs to be positive!"<<endl;
return;
}
if (Width2 < 0 && Width2 != g_DoubleNotDefined) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Energy peak width for energy resolution needs to be non-negative!"<<endl;
return;
}
if ((Ratio < 0 || Ratio > 1) && Ratio != g_DoubleNotDefined) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Ratio for energy resolution needs to be between [0..1]!"<<endl;
return;
}
m_EnergyResolutionPeak1.Add(InputEnergy, Peak1);
m_EnergyResolutionWidth1.Add(InputEnergy, Width1);
if (Peak2 != g_DoubleNotDefined) {
m_EnergyResolutionPeak2.Add(InputEnergy, Peak2);
}
if (Width2 != g_DoubleNotDefined) {
m_EnergyResolutionWidth2.Add(InputEnergy, Width2);
}
if (Ratio != g_DoubleNotDefined) {
m_EnergyResolutionRatio.Add(InputEnergy, Ratio);
}
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetEnergyResolutionWidth1(const double Energy, const MVector& Position) const
{
// Some detectors have a depth dependend energy resolution (e.g. Strip 3D ),
// but not the default energy resolution handler here:
double Value = m_EnergyResolutionWidth1.Evaluate(Energy);
if (Value < 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Give more energy resolution values, because the interpolation fails at E="<<Energy<<"keV"<<endl;
mout<<"Energy resolution width 1 value below zero."<<endl;
return 0.0;
}
return Value;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetEnergyResolutionWidth2(const double Energy, const MVector& Position) const
{
// Some detectors have a depth dependend energy resolution (e.g. Strip 3D ),
// but not the default energy resolution handler here:
double Value = m_EnergyResolutionWidth2.Evaluate(Energy);
if (Value < 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Give more energy resolution values, because the interpolation fails at E="<<Energy<<"keV"<<endl;
mout<<"Energy resolution width 2 value below zero."<<endl;
return 0.0;
}
return Value;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetEnergyResolutionPeak1(const double Energy, const MVector& Position) const
{
// Some detectors have a depth dependend energy resolution (e.g. Strip 3D ),
// but not the default energy resolution handler here:
double Value = m_EnergyResolutionPeak1.Evaluate(Energy);
if (Value < 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Give more energy resolution values, because the interpolation fails at E="<<Energy<<"keV"<<endl;
mout<<"Energy resolution peak 1 value below zero."<<endl;
return 0.0;
}
return Value;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetEnergyResolutionPeak2(const double Energy, const MVector& Position) const
{
// Some detectors have a depth dependend energy resolution (e.g. Strip 3D ),
// but not the default energy resolution handler here:
double Value = m_EnergyResolutionPeak2.Evaluate(Energy);
if (Value < 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Give more energy resolution values, because the interpolation fails at E="<<Energy<<"keV"<<endl;
mout<<"Energy resolution peak 2 value below zero."<<endl;
return 0.0;
}
return Value;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetEnergyResolutionRatio(const double Energy, const MVector& Position) const
{
// Some detectors have a depth dependend energy resolution (e.g. Strip 3D ),
// but not the default energy resolution handler here:
double Value = m_EnergyResolutionRatio.Evaluate(Energy);
if (Value < 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Give more energy resolution values, because the interpolation fails at E="<<Energy<<"keV"<<endl;
mout<<"Energy resolution ratio value below zero."<<endl;
return 0.0;
}
if (Value > 1.0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Give more energy resolution values, because the interpolation fails at E="<<Energy<<"keV"<<endl;
mout<<"Energy resolution ratio value above one."<<endl;
return 1.0;
}
return Value;
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetEnergyResolution(const double Energy, const MVector& PositionInDetector) const
{
//! Returns an average energy resolution width
if (m_EnergyResolutionType == c_EnergyResolutionTypeGauss) {
return m_EnergyResolutionWidth1.Evaluate(Energy);
} else if (m_EnergyResolutionType == c_EnergyResolutionTypeLorentz) {
return m_EnergyResolutionWidth1.Evaluate(Energy);
} else if (m_EnergyResolutionType == c_EnergyResolutionTypeGaussLandau) {
mimp<<" *** Info *** in detector "<<m_Name<<endl;
mimp<<"There is no good GetEnergyResolution-function for the Gauss-Landau distribution. Using gauss only..."<<endl;
return m_EnergyResolutionWidth1.Evaluate(Energy);
}
return 0.0;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetEnergyCalibration(const MFunction& EnergyCalibration)
{
// Set a energy calibration function
m_EnergyCalibrationSet = true;
m_EnergyCalibration = EnergyCalibration;
if (m_EnergyCalibration.GetSize() > 0) {
m_UseEnergyCalibration = true;
} else {
m_UseEnergyCalibration = false;
}
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetTimeResolution(const double Energy, const double Sigma)
{
//
m_TimeResolutionType = c_TimeResolutionTypeGauss;
m_TimeResolution.Add(Energy, Sigma);
}
////////////////////////////////////////////////////////////////////////////////
double MDDetector::GetTimeResolution(const double Energy) const
{
//
if (m_TimeResolutionType == c_TimeResolutionTypeNone) {
return numeric_limits<double>::max()/1000;
} else if (m_TimeResolutionType == c_TimeResolutionTypeIdeal) {
return 0;
} else if (m_TimeResolutionType == c_TimeResolutionTypeGauss) {
return m_TimeResolution.Evaluate(Energy);
} else {
merr<<"Unknown time resolution type: "<<m_TimeResolutionType<<endl;
return numeric_limits<double>::max()/1000;
}
}
////////////////////////////////////////////////////////////////////////////////
MVector MDDetector::GetPositionResolution(const MVector& Pos, const double Energy) const
{
return m_StructuralSize;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::SetDetectorVolume(MDVolume* Volume)
{
// Set the volume which represents this detector
m_DetectorVolume = Volume;
Volume->SetIsDetectorVolume(this); // Was commented out during named detectors introduction
}
////////////////////////////////////////////////////////////////////////////////
MDVolume* MDDetector::GetDetectorVolume()
{
// Return the volume, which represents this detector
return m_DetectorVolume;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::Validate()
{
// Make sure everything is reasonable:
if (m_DetectorVolume == 0 && m_SVs.size() == 1) {
SetDetectorVolume(m_SVs[0]);
}
if (m_DetectorVolume == 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Detector has no detector volume!"<<endl;
return false;
}
if (m_DetectorVolume->IsVirtual() == true) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Detector volume "<<m_DetectorVolume->GetName()<<" is not allowed to be virtual!"<<endl;
return false;
}
if (m_DetectorVolume->IsClone() == true) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"A detector volume cannot be generated via <Template>.Copy <detector volume name>)!"<<endl;
mout<<"You can position it several times or it can be part of a cloned mother volume, but it cannot be cloned itself."<<endl;
return false;
}
if (m_SVs.size() == 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Detector has no sensitive volume!"<<endl;
return false;
}
for (unsigned int i = 0; i < m_SVs.size(); ++i) {
if (m_SVs[i]->IsVirtual() == true) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"The sensitive volume is not allowed to be virtual!"<<endl;
return false;
}
}
if (m_SVs.size() == 1 && m_CommonVolume == 0) {
m_CommonVolume = m_DetectorVolume;
}
// In case we have only one sensitive volume and the sensitive volume is identical with the detector volume
// we do not necessarily need a structural pitch and a structural offset
if (m_DetectorVolume == m_SVs[0] || m_SVs.size() > 1) {
if (m_StructuralPitch == g_VectorNotDefined) {
m_StructuralPitch = MVector(0, 0, 0);
}
if (m_StructuralOffset == g_VectorNotDefined) {
m_StructuralOffset = MVector(0, 0, 0);
}
} else {
if (m_StructuralPitch == g_VectorNotDefined) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"No spacing (keyword StructuralPitch) between the sensitive volumes defined"<<endl;
return false;
}
if (m_StructuralOffset == g_VectorNotDefined) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"No offset (keyword StructuralOffset) from the detector volume to the first sensitive volumes defined"<<endl;
return false;
}
}
if (m_StructuralPitch.X() < 0 || m_StructuralPitch.Y() < 0 || m_StructuralPitch.Z() < 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"No component of the structural pitch is allowed to be negative: "<<m_StructuralPitch<<endl;
return false;
}
if (m_StructuralOffset.X() < 0 || m_StructuralOffset.Y() < 0 || m_StructuralOffset.Z() < 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"No component of the structural offset is allowed to be negative: "<<m_StructuralOffset<<endl;
return false;
}
if (m_EnergyResolutionType == c_EnergyResolutionTypeUnknown) {
mout<<" *** Info *** for detector "<<m_Name<<endl;
mout<<"No energy resolution defined --- assuming ideal"<<endl;
m_EnergyResolutionType = c_EnergyResolutionTypeIdeal;
}
if (m_EnergyResolutionType != c_EnergyResolutionTypeIdeal && m_EnergyResolutionType != c_EnergyResolutionTypeNone) {
if (m_EnergyResolutionPeak1.GetSize() < 2) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Please give at least two data points for the energy resolution or state that you don't want an energy resolution."<<endl;
return false;
}
if (m_EnergyResolutionPeak1.GetSize() == 0) {
mout<<" *** Info *** for detector "<<m_Name<<endl;
mout<<"No energy resolution given. Assuming ideal."<<endl;
mout<<"You might add a statement like \""<<m_Name<<".EnergyResolution Ideal\" to your file."<<endl;
m_EnergyResolutionType = c_EnergyResolutionTypeIdeal;
}
}
if (m_EnergyLossType == c_EnergyLossTypeUnknown) {
m_EnergyLossType = c_EnergyLossTypeNone;
}
if (m_EnergyCalibrationSet == false) {
m_UseEnergyCalibration = false;
}
if (m_TimeResolutionType == c_TimeResolutionTypeUnknown) {
m_TimeResolutionType = c_TimeResolutionTypeNone;
}
if (m_NoiseThresholdEqualsTriggerThresholdSet == false) {
m_NoiseThresholdEqualsTriggerThresholdSet = true;
m_NoiseThresholdEqualsTriggerThreshold = false;
}
if (m_NoiseThresholdEqualsTriggerThreshold == true) {
if (m_NoiseThreshold != g_DoubleNotDefined) {
mout<<" *** Info *** for detector "<<m_Name<<endl;
mout<<"Ignoring noise threshold, because NoiseThresholdEqualsTriggerThreshold is set"<<endl;
m_NoiseThreshold = 0;
m_NoiseThresholdSigma = 0;
}
}
if (m_NoiseThreshold == g_DoubleNotDefined) {
if (m_NoiseThresholdEqualsTriggerThreshold == false) {
mout<<" *** Info *** for detector "<<m_Name<<endl;
mout<<"No noise threshold defined --- setting it to zero"<<endl;
}
m_NoiseThreshold = 0;
m_NoiseThresholdSigma = 0;
}
if (m_NoiseThresholdSigma == g_DoubleNotDefined) {
m_NoiseThresholdSigma = 0;
}
if (m_TriggerThreshold == g_DoubleNotDefined) {
mout<<" *** Info *** for detector "<<m_Name<<endl;
mout<<"No trigger threshold defined --- setting it to zero"<<endl;
m_TriggerThreshold = 0;
m_TriggerThresholdSigma = 0;
}
if (m_TriggerThresholdSigma == g_DoubleNotDefined) {
m_TriggerThresholdSigma = 0;
}
if (m_FailureRate == g_DoubleNotDefined) {
// mout<<" *** Info *** for detector "<<m_Name<<endl;
// mout<<"No failure rate defined --- setting it to zero"<<endl;
m_FailureRate = 0;
}
if (m_Overflow == g_DoubleNotDefined) {
// mout<<" *** Info *** for detector "<<m_Name<<endl;
// mout<<"No overflow defined --- setting it to zero"<<endl;
m_Overflow = 10E+20;
m_OverflowSigma = 1;
}
if (m_NoiseThresholdEqualsTriggerThreshold == true &&
(m_NoiseThreshold != 0 || m_NoiseThresholdSigma != 0)) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Setting NoiseThresholdEqualsTriggerThreshold ignores all values of NoiseThreshold and its uncertainty"<<endl;
return false;
}
// The blocked trigger channel have
if (m_IsNamedDetector == true) {
if (m_VolumeSequence.IsEmpty() == true) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"This named detector has no assigned volume/position (use Assign keyword)"<<endl;
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::CreateBlockedTriggerChannelsGrid()
{
// Create the grid only if it is really used
m_BlockedTriggerChannels.Set(MDGrid::c_Voxel, 1, 1);
m_AreBlockedTriggerChannelsUsed = true;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::AreNear(const MVector& Pos1, const MVector& dPos1,
const MVector& Pos2, const MVector& dPos2,
const double Sigma, const int Level) const
{
//
mimp<<"If anybody sees this error message, then let me know... Andreas"<<show;
if (fabs(Pos1[0] - Pos2[0])/(m_StructuralPitch.X() + 2*m_StructuralSize.X()) < 1.1*Level &&
fabs(Pos1[1] - Pos2[1])/(m_StructuralPitch.Y() + 2*m_StructuralSize.Y()) < 1.1*Level) {
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::BlockTriggerChannel(const unsigned int xGrid, const unsigned int yGrid)
{
// Block a channel from triggering
if (m_AreBlockedTriggerChannelsUsed == false) {
CreateBlockedTriggerChannelsGrid();
}
if (m_BlockedTriggerChannels.SetVoxelValue(1.0, xGrid, yGrid) == false) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Grid position: "<<xGrid<<" "<<yGrid<<" does not exist"<<endl;
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::ResetIDs()
{
//
MDDetector::m_IDCounter = 1;
MDDetector::m_SensIDCounter = 1;
}
////////////////////////////////////////////////////////////////////////////////
void MDDetector::ActivateNoising(const bool ActivateNoising)
{
// True if data is noised
m_NoiseActive = ActivateNoising;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::IsVeto(const MVector& Pos, const double Energy) const
{
// Check if we have a veto
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::AddNamedDetector(MDDetector* Detector)
{
//! Add a named detector
if (m_IsNamedDetector == true) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"This is already a named detector and you can not add a named detector to a named detector!"<<endl;
return false;
}
Detector->m_IsNamedDetector = true;
Detector->m_NamedAfter = this;
m_NamedDetectors.push_back(Detector);
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool MDDetector::HasNamedDetector(const MString& Name) const
{
//! Return true if this detector contains the given named detector
for (unsigned int d = 0; d < m_NamedDetectors.size(); ++d) {
if (m_NamedDetectors[d]->m_Name == Name) {
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
MString MDDetector::GetNamedDetectorName(unsigned int i) const
{
//! Return the name of the "named detector"
if (i > m_NamedDetectors.size()) {
merr<<"Index for named detector name out of range: "<<i<<" ( you have "<<m_NamedDetectors.size()<<" named detectors!"<<show;
return "";
}
return m_NamedDetectors[i]->GetName();
}
////////////////////////////////////////////////////////////////////////////////
MDVolumeSequence MDDetector::GetNamedDetectorVolumeSequence(unsigned int i)
{
//! Return the volume sequence of the "named detector"
if (i > m_NamedDetectors.size()) {
merr<<"Index for named detector volume sequence out of range: "<<i<<" ( you have "<<m_NamedDetectors.size()<<" named detectors!"<<show;
return MDVolumeSequence();
}
return m_NamedDetectors[i]->m_VolumeSequence;
}
////////////////////////////////////////////////////////////////////////////////
MDDetector* MDDetector::FindNamedDetector(const MDVolumeSequence& VS)
{
// Find the named detector
for (unsigned int d = 0; d < m_NamedDetectors.size(); ++d) {
//cout<<"A: "<<VS.ToString()<<endl;
//cout<<"B: "<<m_NamedDetectors[d]->m_VolumeSequence.ToString()<<endl;
if (VS.HasSameDetector(m_NamedDetectors[d]->m_VolumeSequence) == true) {
return m_NamedDetectors[d];
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
MVector MDDetector::GetGlobalPosition(const MVector& PositionInDetector, const MString& NamedDetector)
{
//! Use this function to convert a position within a NAMED detector (i.e. uniquely identifyable) into a position in the global coordinate system
MVector Position = g_VectorNotDefined;
if (m_IsNamedDetector == true) {
if (m_VolumeSequence.GetSensitiveVolume() == 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"The named detector's ("<<NamedDetector<<") volume sequence has no sensitive volume --- this should not have happened!"<<endl;
return g_VectorNotDefined;
}
Position = m_VolumeSequence.GetPositionInFirstVolume(PositionInDetector, m_VolumeSequence.GetSensitiveVolume());
} else {
bool Found = false;
for (unsigned int d = 0; d < m_NamedDetectors.size(); ++d) {
if (m_NamedDetectors[d]->m_Name == NamedDetector) {
if (m_NamedDetectors[d]->m_VolumeSequence.GetSensitiveVolume() == 0) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"The named detector's ("<<m_NamedDetectors[d]->m_Name<<") volume sequence has no sensitive volume --- this should not have happened!"<<endl;
return g_VectorNotDefined;
}
Position = m_NamedDetectors[d]->m_VolumeSequence.GetPositionInFirstVolume(PositionInDetector, m_NamedDetectors[d]->m_VolumeSequence.GetSensitiveVolume());
Found = true;
}
}
if (Found == false) {
mout<<" *** Error *** in detector "<<m_Name<<endl;
mout<<"Named detector not found: "<<NamedDetector<<endl;
}
}
return Position;
}
////////////////////////////////////////////////////////////////////////////////
MString MDDetector::ToString() const
{
ostringstream out;
if (m_IsNamedDetector == false) {
out<<"Detector \"";
} else {
out<<"Named detector (named after: "<<m_NamedAfter->m_Name<<") \"";
}
out<<m_Name<<"\" of type "<<GetDetectorTypeName(m_Type)<<endl;
out<<" with detector volume: "<<m_DetectorVolume->GetName()<<endl;
out<<" with sensitive volumes: ";
for (unsigned int i = 0; i < m_SVs.size(); i++) {
out<<m_SVs[i]->GetName()<<" ";
}
out<<endl;
out<<" energy resolution type: "<<m_EnergyResolutionType<<endl;
return out.str().c_str();
}
////////////////////////////////////////////////////////////////////////////////
MString MDDetector::GetGeomegaCommon(bool PrintVolumes,
bool PrintStructural,
bool PrintEnergyResolution,
bool PrintTimeResolution,
bool PrintTriggerThreshold,
bool PrintNoiseThreshold,
bool PrintOverflow,
bool PrintFailureRate,
bool PrintPulseShape) const
{
// Return all common detector characteristics in Geomega-Format
// Function is called by GetGeomega() of derived classes
ostringstream out;
if (PrintVolumes == true) {
out<<m_Name<<".DetectorVolume "<<m_DetectorVolume->GetName()<<endl;
for (unsigned int s = 0; s < m_SVs.size(); ++s) {
out<<m_Name<<".SensitiveVolume "<<m_SVs[s]->GetName()<<endl;
}
}
if (PrintStructural == true) {
out<<m_Name<<".StructuralPitch "
<<m_StructuralPitch.X()<<" "
<<m_StructuralPitch.Y()<<" "
<<m_StructuralPitch.Z()<<endl;
out<<m_Name<<".StructuralOffset "
<<m_StructuralOffset.X()<<" "
<<m_StructuralOffset.Y()<<" "
<<m_StructuralOffset.Z()<<endl;
}
if (PrintEnergyResolution == true) {
if (m_EnergyResolutionType == c_EnergyResolutionTypeGauss) {
out<<m_Name<<".EnergyResolutionType Gauss"<<endl;
} else if (m_EnergyResolutionType == c_EnergyResolutionTypeLorentz) {
out<<m_Name<<".EnergyResolutionType Lorentz "<<endl;
}
for (unsigned int d = 0; d < m_EnergyResolutionPeak1.GetNDataPoints(); ++d) {
out<<m_Name<<".EnergyResolution ";
if (m_EnergyResolutionType == c_EnergyResolutionTypeGauss) {
out<<"Gauss "<<
m_EnergyResolutionPeak1.GetDataPointX(d)<<" "<<
m_EnergyResolutionPeak1.GetDataPointY(d)<<" "<<
m_EnergyResolutionWidth1.GetDataPointY(d)<<endl;
} else if (m_EnergyResolutionType == c_EnergyResolutionTypeLorentz) {
out<<"Lorentz "<<
m_EnergyResolutionPeak1.GetDataPointX(d)<<" "<<
m_EnergyResolutionPeak1.GetDataPointY(d)<<" "<<
m_EnergyResolutionWidth1.GetDataPointY(d)<<endl;
} else if (m_EnergyResolutionType == c_EnergyResolutionTypeGaussLandau) {
out<<"GaussLandau "<<
m_EnergyResolutionPeak1.GetDataPointX(d)<<" "<<
m_EnergyResolutionPeak1.GetDataPointY(d)<<" "<<
m_EnergyResolutionWidth1.GetDataPointY(d)<<" "<<
m_EnergyResolutionPeak2.GetDataPointY(d)<<" "<<
m_EnergyResolutionWidth2.GetDataPointY(d)<<" "<<
m_EnergyResolutionRatio.GetDataPointY(d)<<endl;
}
}
}
if (PrintTimeResolution == true) {
for (int d = 0; d < m_TimeResolution.GetSize(); ++d) {
out<<m_Name<<".TimeResolution "<<
m_TimeResolution.GetDataPointX(d)<<" "<<
m_TimeResolution.GetDataPointY(d)<<endl;
}
}
if (PrintTriggerThreshold == true) { out<<m_Name<<".TriggerThreshold "<<m_TriggerThreshold<<" "<<m_TriggerThresholdSigma<<endl;
}
if (PrintNoiseThreshold == true) {
if (m_NoiseThresholdEqualsTriggerThreshold == true) {
out<<m_Name<<".NoiseThresholdEqualsTriggerThreshold"<<endl;
} else {
out<<m_Name<<".NoiseThreshold "<<m_NoiseThreshold<<" "<<m_NoiseThresholdSigma<<endl;
}
}
if (PrintOverflow == true) {
out<<m_Name<<".Overflow "<<m_Overflow<<" "<<m_OverflowSigma<<endl;
}
if (PrintFailureRate == true) {
out<<m_Name<<".FailureRate "<<m_FailureRate<<endl;
}
if (PrintPulseShape == true) {
if (m_PulseShape != 0) {
out<<m_Name<<".PulseShape "<<
m_PulseShape->GetParameter(0)<<" "<<
m_PulseShape->GetParameter(1)<<" "<<
m_PulseShape->GetParameter(2)<<" "<<
m_PulseShape->GetParameter(3)<<" "<<
m_PulseShape->GetParameter(4)<<" "<<
m_PulseShape->GetParameter(5)<<" "<<
m_PulseShape->GetParameter(6)<<" "<<
m_PulseShape->GetParameter(7)<<" "<<
m_PulseShape->GetParameter(8)<<" "<<
m_PulseShape->GetParameter(9)<<" "<<
m_PulseShapeMin<<" "<<
m_PulseShapeMin<<endl;
}
}
return out.str().c_str();
}
// MDDetector.cxx: the end...
////////////////////////////////////////////////////////////////////////////////
| [
"andreas@megalibtoolkit.com"
] | andreas@megalibtoolkit.com |
ca1d9cef4a0c08544210de049cdb3c93f41b5963 | fb4e09c10145e9125bcd5519a57db6b2c7a53d1e | /vs/vsClient/QOpenCVWidget.h | 79689e13dfd4b6abc8c1638d1fb46362563ce456 | [] | no_license | tsuibin/coderesearch | abe3ac8434819e66c336223e1f2f8a7ece57534a | 3904f1005a2d00d33324f54b9dbd10573809b862 | refs/heads/master | 2020-12-30T14:56:46.851980 | 2020-08-11T15:44:04 | 2020-08-11T15:44:04 | 33,044,795 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 482 | h |
#ifndef QOPENCVWIDGET_H
#define QOPENCVWIDGET_H
#include <opencv/cv.h>
#include <QPixmap>
#include <QLabel>
#include <QWidget>
#include <QVBoxLayout>
#include <QImage>
#include <stdio.h>
class QOpenCVWidget : public QWidget {
private:
QLabel *imagelabel;
QVBoxLayout *layout;
QImage image;
public:
QOpenCVWidget(QWidget *parent = 0);
~QOpenCVWidget(void);
void putImage(IplImage *, int flag);
};
#endif
| [
"tsuibin@akaedu.org@b42ea6be-37b9-11de-8daa-cfecb5f7ff5b"
] | tsuibin@akaedu.org@b42ea6be-37b9-11de-8daa-cfecb5f7ff5b |
213e015fc82494b1ff0fd80a472c42e0cdaace84 | a89a30a000a6c7eef6853aacbe051985f1965d6a | /project_euler/60/test.cpp | 12ee2358940ef4f8db7ae124c89bf230e2bed88c | [] | no_license | ak795/acm | 9edd7d18ddb6efeed8184b91489005aec7425caa | 81787e16e23ce54bf956714865b7162c0188eb3a | refs/heads/master | 2021-01-15T19:36:00.052971 | 2012-02-06T02:25:23 | 2012-02-06T02:25:23 | 44,054,046 | 1 | 0 | null | 2015-10-11T13:53:25 | 2015-10-11T13:53:23 | null | UTF-8 | C++ | false | false | 250 | cpp | #include <set>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
set<int> s;
set<int> s2;
set<int> s3(9);
set_union(s.begin(), s.end(), s2.begin(), s2.end(), s3.begin());
}
| [
"rock.spartacus@gmail.com"
] | rock.spartacus@gmail.com |
a882fdc30f0c15f1de704c5607a7ec1f043d8e9e | 90fe97fac0b734f5443188f9a003433595d42ad0 | /src/wobbly/TableView.h | fdc808a8c98b516a5604f7810c2903eccc408b4a | [
"ISC"
] | permissive | dubhater/Wobbly | 63671fe67704ad72f1560582c461d919c8ee26d6 | 730e15f806817ecd0d5c7bf07d14949a2ba1881c | refs/heads/master | 2022-10-15T15:45:04.909590 | 2022-09-21T08:28:55 | 2022-09-21T08:28:55 | 37,908,938 | 32 | 13 | null | 2022-09-21T08:28:56 | 2015-06-23T09:13:44 | C++ | UTF-8 | C++ | false | false | 1,069 | h | /*
Copyright (c) 2018, John Smith
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
*/
#ifndef TABLEVIEW_H
#define TABLEVIEW_H
#include <QTableView>
class TableView : public QTableView {
Q_OBJECT
public:
TableView(QWidget *parent = Q_NULLPTR);
void setModel(QAbstractItemModel *model);
signals:
void deletePressed();
private:
void keyPressEvent(QKeyEvent *event);
};
#endif // TABLEVIEW_H
| [
"cantabile.desu@gmail.com"
] | cantabile.desu@gmail.com |
cdc2d4cd11211945c57db4a9e1116cd1b52ff90b | e84a10d08e93db20b06d97dcb7a2c35a8ee8359c | /RHI/Public/RenderContext.h | f6eb8c3d5a95a12031da29b63576c549d04acf5d | [
"BSD-2-Clause"
] | permissive | randyfan/NOME3 | 44b142f87105dcaeaa25fa03b79e9ab73de6115d | 26c47cc6d45214e619d89dcc29787528f4db4aeb | refs/heads/master | 2023-07-29T00:24:01.433701 | 2021-09-19T16:45:14 | 2021-09-19T16:45:14 | 293,137,094 | 4 | 6 | null | 2021-03-10T21:26:27 | 2020-09-05T18:58:36 | C++ | UTF-8 | C++ | false | false | 2,195 | h | #pragma once
#include "CopyContext.h"
#include "Pipeline.h"
namespace RHI
{
struct CClearValue
{
union {
float ColorFloat32[4];
int32_t ColorInt32[4];
uint32_t ColorUInt32[4];
};
float Depth;
uint32_t Stencil;
CClearValue(float r, float g, float b, float a)
{
ColorFloat32[0] = r;
ColorFloat32[1] = g;
ColorFloat32[2] = b;
ColorFloat32[3] = a;
}
CClearValue(float d, uint32_t s)
: Depth(d)
, Stencil(s)
{
}
};
class IRenderContext : public ICopyContext
{
public:
typedef std::shared_ptr<IRenderContext> Ref;
virtual ~IRenderContext() = default;
virtual void BeginRenderPass(CRenderPass& renderPass,
const std::vector<CClearValue>& clearValues) = 0;
virtual void NextSubpass() = 0;
virtual void EndRenderPass() = 0;
virtual void BindPipeline(CPipeline& pipeline) = 0;
// Set Viewport Scissor BlendFactor StencilRef
virtual void BindBuffer(CBuffer& buffer, size_t offset, size_t range, uint32_t set,
uint32_t binding, uint32_t index) = 0;
virtual void BindBufferView(CBufferView& bufferView, uint32_t set, uint32_t binding,
uint32_t index) = 0;
virtual void BindConstants(const void* pData, size_t size, uint32_t set, uint32_t binding,
uint32_t index) = 0;
virtual void BindImageView(CImageView& imageView, uint32_t set, uint32_t binding,
uint32_t index) = 0;
virtual void BindSampler(CSampler& sampler, uint32_t set, uint32_t binding, uint32_t index) = 0;
virtual void BindIndexBuffer(CBuffer& buffer, size_t offset, EFormat format) = 0;
virtual void BindVertexBuffer(uint32_t binding, CBuffer& buffer, size_t offset) = 0;
virtual void Draw(uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex,
uint32_t firstInstance) = 0;
virtual void DrawIndexed(uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex,
int32_t vertexOffset, uint32_t firstInstance) = 0;
};
} /* namespace RHI */
| [
"randyfan@berkeley.edu"
] | randyfan@berkeley.edu |
574b32b01319323482ae2dc43bd8f6db9142ae65 | c7fba4d77a7b6213ec22d984ac3587d0637118c3 | /Model.h | 3dd61c35e55ac21e3001bf940577d0440c5d8e31 | [] | no_license | bradleyaus/openglfps | e3a1746ae9912fea4066e23a148f519d93e5558b | f1589304722fdc85bf557e5056a7c44ea25a1647 | refs/heads/master | 2021-07-25T04:10:26.710347 | 2017-11-06T02:38:15 | 2017-11-06T02:38:15 | 109,638,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 985 | h | #ifndef _MODEL_H_
#define _MODEL_H_
#define VALS_PER_VERT 3
#define VALS_PER_TEXCOORDINATE 2
#include "MapType.h"
#include "Shape.h"
#include "Shader.hpp"
#include <cstdio>
#include <vector>
#include <string>
#include <iostream>
#include <unordered_map>
#include <cmath>
class Model
{
private:
std::vector<float> positions;
std::vector<float> normals;
std::vector<float> uvs;
std::vector<unsigned int> indices;
std::vector<Shape> storedShapes;
std::unordered_map<MapType, int> vertexMap;
GLuint vaoHandle;
unsigned int* buffer;
unsigned int bufferSize;
glm::vec3 maximums;
glm::vec3 minimums;
bool foundNormals;
bool foundTexCoords;
bool VBOCreated;
Shader* shader;
public:
Model();
Model(Shader* shader);
~Model();
bool loadModel(std::string path, std::string modelDir = "models/");
bool createVBO(unsigned int programID);
bool render(glm::vec3 position, glm::vec3 scale);
glm::vec3 getCenter();
double getRadius();
GLfloat fillScale;
};
#endif | [
"bradleyquinn140@gmail.com"
] | bradleyquinn140@gmail.com |
9e1cf129957f1d86f9e889aa2e3ac89a79c0d7da | 154dfd2a2130a3a7731a9a9b431e8295fbf82cd2 | /Codeforces/1036G.cpp | 7e17aeb0fffa1f60da5f7a2bc765600443c36372 | [] | no_license | ltf0501/Competitive-Programming | 1f898318eaecae14b6e040ffc7e36a9497ee288c | 9660b28d979721f2befcb590182975f10c9b6ac8 | refs/heads/master | 2022-11-20T21:08:45.651706 | 2020-07-23T11:55:05 | 2020-07-23T11:55:05 | 245,600,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,158 | cpp | #include<bits/stdc++.h>
using namespace std;
#define maxn 1000010
vector<int> g[maxn],v1,v2,v;
int n,m;
int in[maxn],out[maxn];
bool vis[maxn];
queue<int> q;
main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int x,y;scanf("%d%d",&x,&y);
g[x].push_back(y);
out[x]++,in[y]++;
}
for(int i=1;i<=n;i++)if(!in[i])v1.push_back(i);
for(int i=1;i<=n;i++)if(!out[i])v2.push_back(i);
int sz=v1.size();
for(int i=0;i<sz;i++)
{
memset(vis,0,sizeof(vis));
vis[v1[i]]=1;
q.push(v1[i]);
while(!q.empty())
{
int u=q.front();q.pop();
for(int v : g[u])if(!vis[v])
vis[v]=1,q.push(v);
}
int tmp=0;
for(int j=0;j<sz;j++)
if(vis[v2[j]])tmp|=(1<<j);
v.push_back(tmp);
}
sz=v.size();
for(int i=1;i<(1<<sz)-1;i++)
{
int tmp=0;
for(int j=0;j<sz;j++)
if(i&(1<<j))tmp|=v[j];
if(__builtin_popcount(tmp)<=__builtin_popcount(i))
return 0*puts("NO");
}
puts("YES");
return 0;
}
| [
"0110420@stu.nknush.kh.edu.tw"
] | 0110420@stu.nknush.kh.edu.tw |
bf7d179949e8cb5e54a1794815959a1f6936ba5b | eb768a011a52b9d415dd675c4063ce048cadaadc | /CppND-System-Monitor-Project/include/process.h | 97998f81121fdd14a2adc3d47ce64bec6bb19f42 | [
"MIT"
] | permissive | contactst/cppnd | c519cb129191d391d95b04f212789864fa40ee72 | ef5f2f73a5661d26fffdf594f130dba97a8b1a97 | refs/heads/master | 2020-09-28T13:03:44.969377 | 2019-12-30T22:18:36 | 2019-12-30T22:18:36 | 226,784,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 788 | h | #ifndef PROCESS_H
#define PROCESS_H
#include <string>
#include <iterator>
#include <sstream>
#include <iostream>
#include "linux_parser.h"
/*
Basic class for Process representation
It contains relevant attributes as shown below
*/
class Process {
public:
int Pid();
std::string User();
std::string Command();
float CpuUtilization();
std::string Ram();
long int UpTime();
bool operator<(Process& a);
bool operator>(Process& a);
Process(int pid, long Hertz):pid_(pid), Hertz_(Hertz)
{
}
private:
int pid_;
long Hertz_;
float startTime_;
float uTime_;
float sTime_;
float cuTime_;
float csTime_;
};
#endif | [
"stirunel@pop-os.localdomain"
] | stirunel@pop-os.localdomain |
7488dd5f9827c0adabcd3af67fbeab7f36202ea9 | 574cdcc55131068d43fb32d9b53b09d4de654595 | /RideTheFlow/RideTheFlow/src/actor/Cloud.h | a1cdb80528e8343c1ce476a2886602a893701492 | [] | no_license | Jimendaisuki/RideTheFlow | 58a966ea820fbf270307118189e5ebe435807cab | 5c9a68a085974c8149b14ecdf9ad7e6c3a019ece | refs/heads/master | 2020-04-06T11:56:01.428980 | 2016-07-01T03:36:19 | 2016-07-01T03:36:19 | 55,942,178 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 976 | h | #pragma once
#include "Actor.h"
#include <vector>
#include <memory>
//雲
class Cloud :public Actor, public std::enable_shared_from_this<Cloud>
{
public:
Cloud(IWorld& world, const Vector3& position_);
~Cloud();
virtual void Update() override;
virtual void Draw() const override;
virtual void OnCollide(Actor& other, CollisionParameter colpara) override;
//数値リセット
void Reset();
//ステージの外に出ているか?
bool IsStageOut();
private:
//雲の位置をばらつかせるための配列
std::vector<Vector3> cloudPositions;
//サイズ
std::vector<float> cloudsizes;
//現在の座標
Vector3 position;
//移動方向
Vector3 moveVec;
//移動速度
float moveSpeed;
//移動方向切り替え用タイマー
float moveChangeTimer;
float moveChangeTime;
//流れから離れた時間タイマー
float windOutTimer;
//セルフビルボード計算用、カメラから計算
Vector3 up;
Vector3 front;
Vector3 left;
}; | [
"taroramen310@gmail.com"
] | taroramen310@gmail.com |
faece056d3dfc2113dc99eaf2d77c1cec6489c54 | c997f142a464cc98c52f058ede52c610c0a33e22 | /DataStructure/SMatrix/SparseMatrix.cpp | 2575f2c3d1e14afc79efd98966da944691e563b3 | [] | no_license | dusong7/DSS_learn | 2d33175d3cbf8ce266960b577ccb93b8b837484d | 35f07162363343fb384dd7afec9a9af19bc1d1f8 | refs/heads/master | 2021-01-11T01:09:58.840204 | 2017-07-12T13:12:12 | 2017-07-12T13:12:12 | 71,048,697 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,597 | cpp | /*
稀疏矩阵 转换
*/
#include"head.h"
Status TransposeSMatrix(TSMatrix M,TSMatrix &T){
//采用三元组表示,将稀疏矩阵M转置为T
T.mu=M.nu;
T.nu=M.mu;
T.tu=M.tu;
int q,col,p;
if(T.tu){
q=1;
for(col=1; col<=M.nu; ++col)
for(p=1; p<=M.tu; ++p)
if(M.data[p].j==col){
T.data[q].i=M.data[p].j;
T.data[q].j=M.data[p].i;
T.data[q].e=M.data[p].e;
++q;
}
}
return OK;
}
Status FastTransposeSMatrix(TSMatrix M,TSMatrix &T){
//采用三元组顺序表表示,求稀疏矩阵M转置矩阵T
T.mu=M.nu;
T.nu=M.mu;
T.tu=M.tu;
int col,t;
if(T.tu){
int *num=(int *)malloc((M.nu+1)*sizeof(int));
int *cpot=(int *)malloc((M.nu+1)*sizeof(int));
for(col=1;col<=M.nu;++col)num[col]=0;
for(t=1;t<=M.tu;++t)++num[M.data[t].j];//求M中每列所含的非零元素
cpot[1]=1;
for(col=2;col<=M.nu;++col)cpot[col]=cpot[col-1]+num[col-1];
int p,q;
for(p=1;p<=M.tu;++p){
col=M.data[p].j;
q=cpot[col];
//printf("%d %d %d \n",M.data[p].i,M.data[p].j,M.data[p].e);
T.data[q].i=M.data[p].j;
T.data[q].j=M.data[p].i;
T.data[q].e=M.data[p].e;
++cpot[col];
}//for
free(num);
free(cpot);
}//if
return OK;
}
Status InitRLSMatrixRpos(RLSMatrix &M){
//计算各行第一个非零元素的位置
int i;
for(i=1;i<=M.mu;++i)M.rpos[i]=0;
for(i=1;i<=M.tu;++i){
if(M.rpos[M.data[i].i]==0)M.rpos[M.data[i].i]=i;
else if(i<M.rpos[M.data[i].i])M.rpos[M.data[i].i]=i;
}
//for(i=1;i<=M.mu;i++){
// printf("%d\n",M.rpos[i]);
//}
return OK;
}
Status MultSMatrix(RLSMatrix M,RLSMatrix N,RLSMatrix &Q){
//求矩阵乘积Q=M*N,采用逻辑链接存储表示
if(M.nu!=N.mu)return ERROR;
Q.mu=M.mu;
Q.nu=N.nu;
Q.tu=0;
if(M.tu*N.tu!=0){//非零矩阵
int arow,tp,p,q,brow,t,ccol;
int ctemp[MAXSIZE];
for(arow=1;arow<=M.mu;++arow){//逐行处理
for(int i=0;i<MAXSIZE;++i)ctemp[i]=0;//当前各行元素累加器清零
Q.rpos[arow]=Q.tu+1;
if(arow<M.mu)tp=M.rpos[arow+1];
else tp=M.tu+1;
for(p=M.rpos[arow];p<tp;++p){
brow=M.data[p].j;
if(brow<N.mu)t=N.rpos[brow+1];
else t=N.tu+1;
for(q=N.rpos[brow];q<t;++q){
ccol=N.data[q].j;
ctemp[ccol]+=M.data[p].e*N.data[q].e;
}//for q
}//for p 求得Q中第crow(=arow)行的非零元素
for(ccol=1;ccol<=Q.nu;++ccol){
if(ctemp[ccol]){
if(++Q.tu>MAXSIZE)return ERROR;
Q.data[Q.tu].i=arow;
Q.data[Q.tu].j=ccol;
Q.data[Q.tu].e=ctemp[ccol];
}//if
}//for ccol
}//for arow
}//if
return OK;
} | [
"dusong7@hotmail.com"
] | dusong7@hotmail.com |
80d2f00238e601ab01cad18cfac3abe4ee1518ca | 3c87a2e7fc22719998913cefd13f9e64a3c8837c | /wxWidgetsApp/GUIClass.cpp | dfc5241bf641c7ac011faa0a8d3c11217fee8335 | [] | no_license | josassy/cs1220-hw5 | 2b1ff2b49202447b4f25d2ef0ca057dfcfdde9e5 | 26f9ce5336e93a0177cce2ce6cb4eb706f3f77a9 | refs/heads/master | 2020-09-05T23:43:58.847489 | 2019-11-09T04:00:53 | 2019-11-09T04:00:53 | 220,248,019 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,565 | cpp | ///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version Jun 30 2011)
// http://www.wxformbuilder.org/
//
// PLEASE DO "NOT" EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#include "GUIClass.h"
///////////////////////////////////////////////////////////////////////////
GUIClass::GUIClass( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style )
{
this->SetSizeHints( wxSize( 200,200 ), wxDefaultSize );
wxBoxSizer* baseSizer;
baseSizer = new wxBoxSizer( wxVERTICAL );
basePanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
basePanel->SetForegroundColour( wxColour( 255, 255, 255 ) );
basePanel->SetMinSize( wxSize( 200,200 ) );
wxBoxSizer* sizer0;
sizer0 = new wxBoxSizer( wxVERTICAL );
wxGridSizer* sizer00;
sizer00 = new wxGridSizer( 3, 3, 0, 0 );
sizer00->SetMinSize( wxSize( 240,240 ) );
button0 = new wxButton( basePanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 80,80 ), 0 );
button0->SetBackgroundColour( wxColour( 0, 0, 0 ) );
sizer00->Add( button0, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxEXPAND, 2 );
button1 = new wxButton( basePanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 80,80 ), 0 );
button1->SetBackgroundColour( wxColour( 0, 0, 0 ) );
sizer00->Add( button1, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxEXPAND, 2 );
button2 = new wxButton( basePanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 80,80 ), 0 );
button2->SetBackgroundColour( wxColour( 0, 0, 0 ) );
sizer00->Add( button2, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxEXPAND, 2 );
button3 = new wxButton( basePanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 80,80 ), 0 );
button3->SetBackgroundColour( wxColour( 0, 0, 0 ) );
sizer00->Add( button3, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxEXPAND, 2 );
button4 = new wxButton( basePanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 80,80 ), 0 );
button4->SetBackgroundColour( wxColour( 0, 0, 0 ) );
sizer00->Add( button4, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxEXPAND, 2 );
button5 = new wxButton( basePanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 80,80 ), 0 );
button5->SetBackgroundColour( wxColour( 0, 0, 0 ) );
sizer00->Add( button5, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxEXPAND, 2 );
button6 = new wxButton( basePanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 80,80 ), 0 );
button6->SetBackgroundColour( wxColour( 0, 0, 0 ) );
sizer00->Add( button6, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxEXPAND, 2 );
button7 = new wxButton( basePanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 80,80 ), 0 );
button7->SetBackgroundColour( wxColour( 0, 0, 0 ) );
sizer00->Add( button7, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxEXPAND, 2 );
button8 = new wxButton( basePanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 80,80 ), 0 );
button8->SetBackgroundColour( wxColour( 0, 0, 0 ) );
sizer00->Add( button8, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxEXPAND, 2 );
sizer0->Add( sizer00, 10, wxEXPAND|wxALIGN_CENTER_HORIZONTAL, 5 );
wxGridSizer* sizer01;
sizer01 = new wxGridSizer( 0, 2, 0, 0 );
resetButton = new wxButton( basePanel, wxID_ANY, wxT("Reset"), wxDefaultPosition, wxDefaultSize, 0 );
sizer01->Add( resetButton, 0, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 );
exitButton = new wxButton( basePanel, wxID_ANY, wxT("Exit"), wxDefaultPosition, wxDefaultSize, 0 );
sizer01->Add( exitButton, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 );
sizer0->Add( sizer01, 1, wxEXPAND, 5 );
basePanel->SetSizer( sizer0 );
basePanel->Layout();
sizer0->Fit( basePanel );
baseSizer->Add( basePanel, 1, wxEXPAND | wxALL, 0 );
this->SetSizer( baseSizer );
this->Layout();
menuBar = new wxMenuBar( 0 );
fileMenu = new wxMenu();
wxMenuItem* exitMenuItem;
exitMenuItem = new wxMenuItem( fileMenu, wxID_ANY, wxString( wxT("Exit...") ) , wxEmptyString, wxITEM_NORMAL );
fileMenu->Append( exitMenuItem );
menuBar->Append( fileMenu, wxT("File") );
this->SetMenuBar( menuBar );
statusBar = this->CreateStatusBar( 1, wxST_SIZEGRIP, wxID_ANY );
this->Centre( wxBOTH );
// Connect Events
this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( GUIClass::OnClose ) );
button0->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button1->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button2->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button3->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button4->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button5->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button6->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button7->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button8->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
resetButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onResetEvent ), NULL, this );
exitButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onExitEvent ), NULL, this );
this->Connect( exitMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GUIClass::onExitEvent ) );
}
GUIClass::~GUIClass()
{
// Disconnect Events
this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( GUIClass::OnClose ) );
button0->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button1->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button2->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button3->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button4->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button5->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button6->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button7->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
button8->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onButtonClick ), NULL, this );
resetButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onResetEvent ), NULL, this );
exitButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIClass::onExitEvent ), NULL, this );
this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GUIClass::onExitEvent ) );
}
| [
"redrobbin99@gmail.com"
] | redrobbin99@gmail.com |
587d5abda0f89eb430335bd45a6facec686269cf | 0b34dc130e8296d3d61eedf37452be5de41af1c2 | /Udp/ComUdp/Object/serialportobject.h | 5924a614bf7be3a04a75b3ae97b9945bfe50f9a9 | [] | no_license | BIbiLion/LS_Wqiakun2017Test | 67a77c07a33ea4d5f308492580a403774de99b30 | 2955f20d8ac63acd8ace2a553f2e062e9ac26e92 | refs/heads/master | 2021-01-20T14:19:28.468757 | 2017-09-15T08:04:55 | 2017-09-15T08:04:55 | 90,591,454 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,300 | h | #ifndef SERIALPORTOBJECT_H
#define SERIALPORTOBJECT_H
#include <QObject>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QByteArray>
#include "../class/serialattri.h"
class SerialPortObject : public QObject
{
Q_OBJECT
public:
explicit SerialPortObject( QObject *parent = 0);
explicit SerialPortObject(SerialAttri &serialPortAttr, QObject *parent = 0);
~SerialPortObject();
signals:
void sendComRev(QByteArray _byteArray);
public slots:
void initSerialPort(SerialAttri &serialPortAttr);
void dispalySerialPort();
void reveiveData();
void writeDate(QString writeDate);
void errorDispaly(QSerialPort::SerialPortError);
void changePortName(const QString &);
void changeBrauRate(const QString &);
void changeDataBits(const QString &);
void changeParity(const QString &);
void changeStopBits(const QString &);
void BanudRateChangeSlot(qint32,QSerialPort::Directions=QSerialPort::AllDirections);
void dataBitsChangedSlot(QSerialPort::DataBits);
void parityChangedSlot(QSerialPort::Parity);
void stopBitsChangedSlot(QSerialPort::StopBits);
void flowControlChangedSlot(QSerialPort::FlowControl);
private :
QSerialPort * m_serialPort;
//SerialAttri m_serialPortAttr;
};
#endif // SERIALPORTOBJECT_H
| [
"wqiankun89@163.com"
] | wqiankun89@163.com |
89c5f3312a1d47e4e066457e741234bd5deed762 | eaca4f20f7a5903383bb5dc33c654f6754013f0d | /main.cpp | a003236e9ed562f8a98988d81be240bddfa710f3 | [] | no_license | Penguinux/PAMSI | 111aa34fa266df9d87267ef7d71a76f68480d7f5 | 5a104a60cf4042de845d5f8a9d2cb079e0d8d9c9 | refs/heads/master | 2020-03-06T20:29:23.863132 | 2018-03-28T16:13:05 | 2018-03-28T16:13:05 | 127,049,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,461 | cpp | #include"AVLtree.cpp"
#include<iostream>
#include<cstdlib>
using namespace std;
void menu() {
cout << "---------- AVL TREE ----------" << endl;
cout << " 1. Menu" << endl;
cout << " 2. Insert element" << endl;
cout << " 3. Remove element" << endl;
cout << " 4. Display" << endl;
cout << " 5. Advanced display" << endl;
cout << " 6. Clear" << endl;
cout << " 7. Height of the tree" << endl;
cout << " 8. Preorder traversal" << endl;
cout << " 9. Postorder traversal" << endl;
cout << "10. Inorder traversal" << endl;
cout << "11. Exit" << endl;
}
int main() {
int choice;
int value;
AVLTree<int> avl;
menu();
while (1) {
cin >> choice;
switch (choice) {
case 1:
menu();
break;
case 2:
cin >> value;
avl.add(avl.root, value);
break;
case 3:
cin >> value;
avl.remove(avl.root, value);
break;
case 4:
cout << endl;
avl.display(avl.root, 0);
cout << endl;
break;
case 5:
cout << endl;
avl.display_adv(avl.root, 0);
cout << endl;
break;
case 6:
avl.clear(avl.root);
break;
case 7:
avl.treeheight();
break;
case 8:
cout << endl;
avl.preorder(avl.root);
cout << endl;
break;
case 9:
cout << endl;
avl.postorder(avl.root);
cout << endl;
break;
case 10:
cout << endl;
avl.inorder(avl.root);
cout << endl;
break;
case 11:
exit(1);
break;
default:
cout << endl << "Wrong choice" << endl;
}
}
return 0;
}
| [
"penguinux97@gmail.com"
] | penguinux97@gmail.com |
6c17544296c14bbc8d85bde47cc142950301cc52 | 228e00812cc2428c1421565e5be3e04bf3660759 | /simcity.h | b76c8ab188ab896b5038cb66e0d2b65b30f01965 | [
"LicenseRef-scancode-warranty-disclaimer",
"Artistic-1.0",
"MIT"
] | permissive | 4ssfscker/node-sim | dbfbec5d41988a5f4e1562babea89ccc86c04a2f | 2bd3422fd645f415024907c9cf92697057cbc222 | refs/heads/master | 2021-01-24T10:38:14.973367 | 2007-06-09T15:12:10 | 2018-03-04T05:47:05 | 123,057,027 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 11,015 | h | /*
* simcity.h
*
* Copyright (c) 1997 - 2001 Hansjörg Malthaner
*
* This file is part of the Simutrans project and may not be used
* in other projects without written permission of the author.
*/
#ifndef simcity_h
#define simcity_h
#include "simdings.h"
#include "dings/gebaeude.h"
#include "tpl/vector_tpl.h"
#include "tpl/weighted_vector_tpl.h"
#include "tpl/array2d_tpl.h"
class karte_t;
class spieler_t;
class cbuffer_t;
class stadt_info_t;
// part of passengers going to factories or toursit attractions (100% mx)
#define FACTORY_PAX 33 // workers
#define TOURIST_PAX 16 // tourists
// other long-distance travellers
#define MAX_CITY_HISTORY_YEARS 12 // number of years to keep history
#define MAX_CITY_HISTORY_MONTHS 12 // number of months to keep history
#define MAX_CITY_HISTORY 4 // Total number of items in array
#define HIST_CITICENS 0 // total people
#define HIST_GROWTH 1 // growth (just for convenience)
#define HIST_TRANSPORTED 2
#define HIST_GENERATED 3
class cstring_t;
/**
* Die Objecte der Klasse stadt_t bilden die Staedte in Simu. Sie
* wachsen automatisch.
* @version 0.7
* @author Hj. Malthaner
*/
class stadt_t {
/**
* best_t:
*
* Kleine Hilfsklasse - speichert die beste Bewertung einer Position.
*
* @author V. Meyer
*/
class best_t {
sint32 best_wert;
koord best_pos;
public:
void reset(koord pos) { best_wert = 0; best_pos = pos; }
void check(koord pos, sint32 wert) {
if(wert > best_wert) {
best_wert = wert;
best_pos = pos;
}
}
bool found() const { return best_wert > 0; }
koord gib_pos() const { return best_pos;}
// sint32 gib_wert() const { return best_wert; }
};
public:
/**
* Reads city configuration data
* @author Hj. Malthaner
*/
static bool cityrules_init(cstring_t objpathname);
private:
static karte_t *welt;
spieler_t *besitzer_p;
char name[64];
weighted_vector_tpl <const gebaeude_t *> buildings;
array2d_tpl<unsigned char> pax_ziele_alt;
array2d_tpl<unsigned char> pax_ziele_neu;
koord pos; // Gruendungsplanquadrat der Stadt
koord lo, ur; // max size of housing area
// this counter indicate which building will be processed next
uint32 step_count;
/**
* step so every house is asked once per month
* i.e. 262144/(number of houses) per step
* @author Hj. Malthaner
*/
uint32 step_interval;
/**
* next passenger generation timer
* @author Hj. Malthaner
*/
uint32 next_step;
/**
* in this fixed interval, construction will happen
*/
static const uint32 step_bau_interval;
/**
* next construction
* @author Hj. Malthaner
*/
uint32 next_bau_step;
// attribute fuer die Bevoelkerung
sint32 bev; // Bevoelkerung gesamt
sint32 arb; // davon mit Arbeit
sint32 won; // davon mit Wohnung
/**
* Counter: possible passengers in this month
* transient data, not saved
* @author Hj. Malthaner
*/
sint32 pax_erzeugt;
/**
* Counter: transported passengers in this month
* transient data, not saved
* @author Hj. Malthaner
*/
sint32 pax_transport;
/**
* Modifier for city growth
* transient data, not saved
* @author Hj. Malthaner
*/
sint32 wachstum;
/**
* City history
* @author prissi
*/
sint64 city_history_year[MAX_CITY_HISTORY_YEARS][MAX_CITY_HISTORY];
sint64 city_history_month[MAX_CITY_HISTORY_MONTHS][MAX_CITY_HISTORY];
sint32 last_month_bev;
sint32 last_year_bev;
sint32 this_year_pax, this_year_transported;
/* updates the city history
* @author prissi
*/
void roll_history(void);
stadt_info_t *stadt_info;
public:
/**
* Returns pointer to history for city
* @author hsiegeln
*/
sint64* get_city_history_year() { return *city_history_year; }
sint64* get_city_history_month() { return *city_history_month; }
/* returns the money dialoge of a city
* @author prissi
*/
stadt_info_t *gib_stadt_info();
// just needed by stadt_info.cc
static inline karte_t* gib_welt() { return welt; }
/* end of histroy related thingies */
private:
sint32 best_haus_wert;
sint32 best_strasse_wert;
best_t best_haus;
best_t best_strasse;
koord strasse_anfang_pos;
koord strasse_best_anfang_pos;
/**
* Arbeitsplätze der Einwohner
* @author Hj. Malthaner
*/
weighted_vector_tpl<fabrik_t *> arbeiterziele;
/**
* allokiert pax_ziele_alt/neu und init. die werte
* @author Hj. Malthaner
*/
void init_pax_ziele();
// recalculate house informations (used for target selection)
void recount_houses();
// recalcs city borders (after loading and deletion)
void recalc_city_size();
/**
* plant das bauen von Gebaeuden
* @author Hj. Malthaner
*/
void step_bau();
typedef enum { no_return=0, factoy_return, tourist_return, town_return } pax_zieltyp;
/**
* verteilt die Passagiere auf die Haltestellen
* @author Hj. Malthaner
*/
void step_passagiere();
/**
* ein Passagierziel in die Zielkarte eintragen
* @author Hj. Malthaner
*/
void merke_passagier_ziel(koord ziel, sint32 color);
/**
* baut Spezialgebaeude, z.B Stadion
* @author Hj. Malthaner
*/
void check_bau_spezial(bool);
/**
* baut ein angemessenes Rathaus
* @author V. Meyer
*/
void check_bau_rathaus(bool);
/**
* constructs a new consumer
* @author prissi
*/
void check_bau_factory(bool);
void bewerte();
// bewertungsfunktionen fuer den Hauserbau
// wie gut passt so ein Gebaeudetyp an diese Stelle ?
gebaeude_t::typ was_ist_an(koord pos) const;
// find out, what building matches best
void bewerte_res_com_ind(const koord pos, int &ind, int &com, int &res);
/**
* baut ein Gebaeude auf Planquadrat x,y
*/
void baue_gebaeude(koord pos);
void erzeuge_verkehrsteilnehmer(koord pos, sint32 level,koord target);
void renoviere_gebaeude(koord pos);
/**
* baut ein Stueck Strasse
*
* @param k Bauposition
*
* @author Hj. Malthaner, V. Meyer
*/
bool baue_strasse(const koord k, spieler_t *sp, bool forced);
void baue();
/**
* @param pos position to check
* @param regel the rule to evaluate
* @return true on match, false otherwise
* @author Hj. Malthaner
*/
bool bewerte_loc(koord pos, const char *regel, int rotation);
/**
* Check rule in all transformations at given position
* @author Hj. Malthaner
*/
sint32 bewerte_pos(koord pos, const char *regel);
void bewerte_strasse(koord pos, sint32 rd, const char* regel);
void bewerte_haus(koord pos, sint32 rd, const char* regel);
void pruefe_grenzen(koord pos);
// fuer die haltestellennamen
sint32 zentrum_namen_cnt, aussen_namen_cnt;
public:
/**
* sucht arbeitsplätze für die Einwohner
* @author Hj. Malthaner
*/
void verbinde_fabriken();
/* returns all factories connected to this city ...
* @author: prissi
*/
const weighted_vector_tpl<fabrik_t*>& gib_arbeiterziele() const { return arbeiterziele; }
// this function removes houses from the city house list
// (called when removed by player, or by town)
void remove_gebaeude_from_stadt(const gebaeude_t *gb);
// this function adds houses to the city house list
void add_gebaeude_to_stadt(const gebaeude_t *gb);
sint32 gib_pax_erzeugt() const {return pax_erzeugt;}
sint32 gib_pax_transport() const {return pax_transport;}
sint32 gib_wachstum() const {return wachstum;}
/**
* ermittelt die Einwohnerzahl der Stadt
* @author Hj. Malthaner
*/
sint32 gib_einwohner() const {return (buildings.get_sum_weight()*6)+((2*bev-arb-won)>>1);}
/**
* Gibt den Namen der Stadt zurück.
* @author Hj. Malthaner
*/
const char* gib_name() const { return name; }
/**
* Ermöglicht Zugriff auf Namesnarray
* @author Hj. Malthaner
*/
char* access_name() { return name; }
/**
* gibt einen zufällingen gleichverteilten Punkt innerhalb der
* Stadtgrenzen zurück
* @author Hj. Malthaner
*/
koord gib_zufallspunkt() const;
/**
* gibt das pax-statistik-array für letzten monat zurück
* @author Hj. Malthaner
*/
const array2d_tpl<unsigned char>* gib_pax_ziele_alt() const { return &pax_ziele_alt; }
/**
* gibt das pax-statistik-array für den aktuellen monat zurück
* @author Hj. Malthaner
*/
const array2d_tpl<unsigned char>* gib_pax_ziele_neu() const { return &pax_ziele_neu; }
/**
* Erzeugt eine neue Stadt auf Planquadrat (x,y) die dem Spieler sp
* gehoert.
* @param welt Die Karte zu der die Stadt gehoeren soll.
* @param sp Der Besitzer der Stadt.
* @param x x-Planquadratkoordinate
* @param y y-Planquadratkoordinate
* @param number of citizens
* @author Hj. Malthaner
*/
stadt_t(karte_t *welt, spieler_t *sp, koord pos,sint32 citizens);
/**
* Erzeugt eine neue Stadt nach Angaben aus der Datei file.
* @param welt Die Karte zu der die Stadt gehoeren soll.
* @param file Zeiger auf die Datei mit den Stadtbaudaten.
* @see stadt_t::speichern()
* @author Hj. Malthaner
*/
stadt_t(karte_t *welt, loadsave_t *file);
// closes window and that stuff
~stadt_t();
/**
* Speichert die Daten der Stadt in der Datei file so, dass daraus
* die Stadt wieder erzeugt werden kann. Die Gebaude und strassen der
* Stadt werden nicht mit der Stadt gespeichert sondern mit den
* Planquadraten auf denen sie stehen.
* @see stadt_t::stadt_t()
* @see planquadrat_t
* @author Hj. Malthaner
*/
void rdwr(loadsave_t *file);
/**
* Wird am Ende der LAderoutine aufgerufen, wenn die Welt geladen ist
* und nur noch die Datenstrukturenneu verknüpft werden müssen.
* @author Hj. Malthaner
*/
void laden_abschliessen();
/* change size of city
* @author prissi */
void change_size( long delta_citicens );
void step(long delta_t);
void neuer_monat();
/**
* such ein (zufälliges) ziel für einen Passagier
* @author Hj. Malthaner
*/
koord finde_passagier_ziel(pax_zieltyp *will_return);
/**
* Gibt die Gruendungsposition der Stadt zurueck.
* @return die Koordinaten des Gruendungsplanquadrates
* @author Hj. Malthaner
*/
inline koord gib_pos() const {return pos;}
inline koord get_linksoben() const { return lo;}
inline koord get_rechtsunten() const { return ur;}
/**
* Creates a station name
* @param number if >= 0, then a number is added to the name
* @author Hj. Malthaner
*/
const char * haltestellenname(koord pos, const char *typ, sint32 number);
/**
* Erzeugt ein Array zufaelliger Startkoordinaten,
* die fuer eine Stadtgruendung geeignet sind.
* @param wl Die Karte auf der die Stadt gegruendet werden soll.
* @param anzahl die Anzahl der zu liefernden Koordinaten
* @author Hj. Malthaner
*/
static vector_tpl<koord> *random_place(const karte_t *wl, sint32 anzahl); // geeigneten platz zur Stadtgruendung durch Zufall ermitteln
/**
* @return Einen Beschreibungsstring für das Objekt, der z.B. in einem
* Beobachtungsfenster angezeigt wird.
* @author Hj. Malthaner
* @see simwin
*/
char *info(char *buf) const;
/**
* A short info about the city stats
* @author Hj. Malthaner
*/
void get_short_info(cbuffer_t & buf) const;
void add_factory_arbeiterziel(fabrik_t *fab);
};
#endif
| [
"noreply@user558903.github.com"
] | noreply@user558903.github.com |
88cb4a6cf750486db27fc17d1719c73d69c9db51 | bb20ba88cc104e320374612e00fdddd5fefe86d8 | /C++/3rd_Party/CGAL/include/CGAL/IO/OBJ_reader.h | e8be0fe710d9f9e03697576c6071d6e62de2b25f | [] | no_license | cbtogu/3DLearning | 5949e22d16f14a57ab04e0eec0ef1c4364747c76 | 9cfc64ad1e0473aff4e2aef34da50731249d3433 | refs/heads/master | 2022-01-31T10:37:58.177148 | 2017-07-06T15:11:43 | 2017-07-06T15:11:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,593 | h | // Copyright (c) 2016 GeometryFactory
//
// This file is part of CGAL (www.cgal.org); 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.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id: OBJ_reader.h,v 1.2 2017/02/06 12:37:05 Emmanuel.Pot Exp $
//
// Author(s) : Andreas Fabri and Maxime Gimeno
#ifndef CGAL_IO_OBJ_READER_H
#define CGAL_IO_OBJ_READER_H
#include <istream>
#include <vector>
namespace CGAL {
template <class Point_3>
bool
read_OBJ( std::istream& input,
std::vector<Point_3> &points,
std::vector<std::vector<std::size_t> > &faces)
{
Point_3 p;
std::string line;
while(getline(input, line)) {
if(line[0] == 'v' && line[1] == ' ') {
std::istringstream iss(line.substr(1));
iss >> p;
if(!iss)
return false;
points.push_back(p);
}
else if(line[0] == 'f') {
std::istringstream iss(line.substr(1));
int i;
faces.push_back( std::vector<std::size_t>() );
while(iss >> i)
{
faces.back().push_back(i-1);
iss.ignore(256, ' ');
}
}
}
return true;
}
} // namespace CGAL
#endif // CGAL_IO_OBJ_READER_H
| [
"Etienne.Houze@polytechnique.edu"
] | Etienne.Houze@polytechnique.edu |
8079d98e8c7f30e4bef98ad8729e6436ec0c7790 | bff9ee7f0b96ac71e609a50c4b81375768541aab | /deps/src/boost_1_65_1/libs/asio/test/error.cpp | c44782c5817f413d644dc1bb510f5187b3f0d8d7 | [
"BSL-1.0",
"BSD-3-Clause"
] | permissive | rohitativy/turicreate | d7850f848b7ccac80e57e8042dafefc8b949b12b | 1c31ee2d008a1e9eba029bafef6036151510f1ec | refs/heads/master | 2020-03-10T02:38:23.052555 | 2018-04-11T02:20:16 | 2018-04-11T02:20:16 | 129,141,488 | 1 | 0 | BSD-3-Clause | 2018-04-11T19:06:32 | 2018-04-11T19:06:31 | null | UTF-8 | C++ | false | false | 3,203 | cpp | //
// error.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include <boost/asio/error.hpp>
#include <sstream>
#include "unit_test.hpp"
void test_error_code(const boost::system::error_code& code)
{
boost::system::error_code error(code);
BOOST_ASIO_CHECK(code == error);
BOOST_ASIO_CHECK(!code || error);
BOOST_ASIO_CHECK(!code || !!error);
boost::system::error_code error2(error);
BOOST_ASIO_CHECK(error == error2);
BOOST_ASIO_CHECK(!(error != error2));
boost::system::error_code error3;
error3 = error;
BOOST_ASIO_CHECK(error == error3);
BOOST_ASIO_CHECK(!(error != error3));
std::ostringstream os;
os << error;
BOOST_ASIO_CHECK(!os.str().empty());
}
void error_test()
{
test_error_code(boost::asio::error::access_denied);
test_error_code(boost::asio::error::address_family_not_supported);
test_error_code(boost::asio::error::address_in_use);
test_error_code(boost::asio::error::already_connected);
test_error_code(boost::asio::error::already_started);
test_error_code(boost::asio::error::connection_aborted);
test_error_code(boost::asio::error::connection_refused);
test_error_code(boost::asio::error::connection_reset);
test_error_code(boost::asio::error::bad_descriptor);
test_error_code(boost::asio::error::eof);
test_error_code(boost::asio::error::fault);
test_error_code(boost::asio::error::host_not_found);
test_error_code(boost::asio::error::host_not_found_try_again);
test_error_code(boost::asio::error::host_unreachable);
test_error_code(boost::asio::error::in_progress);
test_error_code(boost::asio::error::interrupted);
test_error_code(boost::asio::error::invalid_argument);
test_error_code(boost::asio::error::message_size);
test_error_code(boost::asio::error::network_down);
test_error_code(boost::asio::error::network_reset);
test_error_code(boost::asio::error::network_unreachable);
test_error_code(boost::asio::error::no_descriptors);
test_error_code(boost::asio::error::no_buffer_space);
test_error_code(boost::asio::error::no_data);
test_error_code(boost::asio::error::no_memory);
test_error_code(boost::asio::error::no_permission);
test_error_code(boost::asio::error::no_protocol_option);
test_error_code(boost::asio::error::no_recovery);
test_error_code(boost::asio::error::not_connected);
test_error_code(boost::asio::error::not_socket);
test_error_code(boost::asio::error::operation_aborted);
test_error_code(boost::asio::error::operation_not_supported);
test_error_code(boost::asio::error::service_not_found);
test_error_code(boost::asio::error::shut_down);
test_error_code(boost::asio::error::timed_out);
test_error_code(boost::asio::error::try_again);
test_error_code(boost::asio::error::would_block);
}
BOOST_ASIO_TEST_SUITE
(
"error",
BOOST_ASIO_TEST_CASE(error_test)
)
| [
"znation@apple.com"
] | znation@apple.com |
fb12700d8ec273eab2cf5dad7374ad4afe07ac77 | bbadb0f47158d4b85ae4b97694823c8aab93d50e | /apps/c/CloverLeaf_3D/Tiled/viscosity_kernel_seq_kernel.cpp | 1240c785b20313fcbfb329093d7f7f9f86d72f5b | [] | no_license | yshoraka/OPS | 197d8191dbedc625f3669b511a8b4eadf7a365c4 | 708c0c78157ef8c711fc6118e782f8e5339b9080 | refs/heads/master | 2020-12-24T12:39:49.585629 | 2016-11-02T09:50:54 | 2016-11-02T09:50:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,042 | cpp | //
// auto-generated by ops.py
//
#define OPS_ACC0(x, y, z) \
(n_x * 1 + n_y * xdim0_viscosity_kernel * 1 + \
n_z * xdim0_viscosity_kernel * ydim0_viscosity_kernel * 1 + x + \
xdim0_viscosity_kernel * (y) + \
xdim0_viscosity_kernel * ydim0_viscosity_kernel * (z))
#define OPS_ACC1(x, y, z) \
(n_x * 1 + n_y * xdim1_viscosity_kernel * 1 + \
n_z * xdim1_viscosity_kernel * ydim1_viscosity_kernel * 1 + x + \
xdim1_viscosity_kernel * (y) + \
xdim1_viscosity_kernel * ydim1_viscosity_kernel * (z))
#define OPS_ACC2(x, y, z) \
(n_x * 1 + n_y * xdim2_viscosity_kernel * 0 + \
n_z * xdim2_viscosity_kernel * ydim2_viscosity_kernel * 0 + x + \
xdim2_viscosity_kernel * (y) + \
xdim2_viscosity_kernel * ydim2_viscosity_kernel * (z))
#define OPS_ACC3(x, y, z) \
(n_x * 0 + n_y * xdim3_viscosity_kernel * 1 + \
n_z * xdim3_viscosity_kernel * ydim3_viscosity_kernel * 0 + x + \
xdim3_viscosity_kernel * (y) + \
xdim3_viscosity_kernel * ydim3_viscosity_kernel * (z))
#define OPS_ACC4(x, y, z) \
(n_x * 1 + n_y * xdim4_viscosity_kernel * 1 + \
n_z * xdim4_viscosity_kernel * ydim4_viscosity_kernel * 1 + x + \
xdim4_viscosity_kernel * (y) + \
xdim4_viscosity_kernel * ydim4_viscosity_kernel * (z))
#define OPS_ACC5(x, y, z) \
(n_x * 1 + n_y * xdim5_viscosity_kernel * 1 + \
n_z * xdim5_viscosity_kernel * ydim5_viscosity_kernel * 1 + x + \
xdim5_viscosity_kernel * (y) + \
xdim5_viscosity_kernel * ydim5_viscosity_kernel * (z))
#define OPS_ACC6(x, y, z) \
(n_x * 1 + n_y * xdim6_viscosity_kernel * 1 + \
n_z * xdim6_viscosity_kernel * ydim6_viscosity_kernel * 1 + x + \
xdim6_viscosity_kernel * (y) + \
xdim6_viscosity_kernel * ydim6_viscosity_kernel * (z))
#define OPS_ACC7(x, y, z) \
(n_x * 1 + n_y * xdim7_viscosity_kernel * 1 + \
n_z * xdim7_viscosity_kernel * ydim7_viscosity_kernel * 1 + x + \
xdim7_viscosity_kernel * (y) + \
xdim7_viscosity_kernel * ydim7_viscosity_kernel * (z))
#define OPS_ACC8(x, y, z) \
(n_x * 0 + n_y * xdim8_viscosity_kernel * 0 + \
n_z * xdim8_viscosity_kernel * ydim8_viscosity_kernel * 1 + x + \
xdim8_viscosity_kernel * (y) + \
xdim8_viscosity_kernel * ydim8_viscosity_kernel * (z))
#define OPS_ACC9(x, y, z) \
(n_x * 1 + n_y * xdim9_viscosity_kernel * 1 + \
n_z * xdim9_viscosity_kernel * ydim9_viscosity_kernel * 1 + x + \
xdim9_viscosity_kernel * (y) + \
xdim9_viscosity_kernel * ydim9_viscosity_kernel * (z))
#define OPS_ACC10(x, y, z) \
(n_x * 1 + n_y * xdim10_viscosity_kernel * 1 + \
n_z * xdim10_viscosity_kernel * ydim10_viscosity_kernel * 1 + x + \
xdim10_viscosity_kernel * (y) + \
xdim10_viscosity_kernel * ydim10_viscosity_kernel * (z))
#define OPS_ACC11(x, y, z) \
(n_x * 1 + n_y * xdim11_viscosity_kernel * 1 + \
n_z * xdim11_viscosity_kernel * ydim11_viscosity_kernel * 1 + x + \
xdim11_viscosity_kernel * (y) + \
xdim11_viscosity_kernel * ydim11_viscosity_kernel * (z))
// user function
// host stub function
void ops_par_loop_viscosity_kernel_execute(ops_kernel_descriptor *desc) {
int dim = desc->dim;
int *range = desc->range;
ops_arg arg0 = desc->args[0];
ops_arg arg1 = desc->args[1];
ops_arg arg2 = desc->args[2];
ops_arg arg3 = desc->args[3];
ops_arg arg4 = desc->args[4];
ops_arg arg5 = desc->args[5];
ops_arg arg6 = desc->args[6];
ops_arg arg7 = desc->args[7];
ops_arg arg8 = desc->args[8];
ops_arg arg9 = desc->args[9];
ops_arg arg10 = desc->args[10];
ops_arg arg11 = desc->args[11];
// Timing
double t1, t2, c1, c2;
ops_arg args[12] = {arg0, arg1, arg2, arg3, arg4, arg5,
arg6, arg7, arg8, arg9, arg10, arg11};
#ifdef CHECKPOINTING
if (!ops_checkpointing_before(args, 12, range, 45))
return;
#endif
if (OPS_diags > 1) {
ops_timing_realloc(45, "viscosity_kernel");
OPS_kernels[45].count++;
ops_timers_core(&c2, &t2);
}
// compute locally allocated range for the sub-block
int start[3];
int end[3];
for (int n = 0; n < 3; n++) {
start[n] = range[2 * n];
end[n] = range[2 * n + 1];
}
#ifdef OPS_DEBUG
ops_register_args(args, "viscosity_kernel");
#endif
// set up initial pointers and exchange halos if necessary
int base0 = args[0].dat->base_offset;
const double *__restrict__ xvel0 = (double *)(args[0].data + base0);
int base1 = args[1].dat->base_offset;
const double *__restrict__ yvel0 = (double *)(args[1].data + base1);
int base2 = args[2].dat->base_offset;
const double *__restrict__ celldx = (double *)(args[2].data + base2);
int base3 = args[3].dat->base_offset;
const double *__restrict__ celldy = (double *)(args[3].data + base3);
int base4 = args[4].dat->base_offset;
const double *__restrict__ pressure = (double *)(args[4].data + base4);
int base5 = args[5].dat->base_offset;
const double *__restrict__ density0 = (double *)(args[5].data + base5);
int base6 = args[6].dat->base_offset;
double *__restrict__ viscosity = (double *)(args[6].data + base6);
int base7 = args[7].dat->base_offset;
const double *__restrict__ zvel0 = (double *)(args[7].data + base7);
int base8 = args[8].dat->base_offset;
const double *__restrict__ celldz = (double *)(args[8].data + base8);
int base9 = args[9].dat->base_offset;
const double *__restrict__ xarea = (double *)(args[9].data + base9);
int base10 = args[10].dat->base_offset;
const double *__restrict__ yarea = (double *)(args[10].data + base10);
int base11 = args[11].dat->base_offset;
const double *__restrict__ zarea = (double *)(args[11].data + base11);
// initialize global variable with the dimension of dats
int xdim0_viscosity_kernel = args[0].dat->size[0];
int ydim0_viscosity_kernel = args[0].dat->size[1];
int xdim1_viscosity_kernel = args[1].dat->size[0];
int ydim1_viscosity_kernel = args[1].dat->size[1];
int xdim2_viscosity_kernel = args[2].dat->size[0];
int ydim2_viscosity_kernel = args[2].dat->size[1];
int xdim3_viscosity_kernel = args[3].dat->size[0];
int ydim3_viscosity_kernel = args[3].dat->size[1];
int xdim4_viscosity_kernel = args[4].dat->size[0];
int ydim4_viscosity_kernel = args[4].dat->size[1];
int xdim5_viscosity_kernel = args[5].dat->size[0];
int ydim5_viscosity_kernel = args[5].dat->size[1];
int xdim6_viscosity_kernel = args[6].dat->size[0];
int ydim6_viscosity_kernel = args[6].dat->size[1];
int xdim7_viscosity_kernel = args[7].dat->size[0];
int ydim7_viscosity_kernel = args[7].dat->size[1];
int xdim8_viscosity_kernel = args[8].dat->size[0];
int ydim8_viscosity_kernel = args[8].dat->size[1];
int xdim9_viscosity_kernel = args[9].dat->size[0];
int ydim9_viscosity_kernel = args[9].dat->size[1];
int xdim10_viscosity_kernel = args[10].dat->size[0];
int ydim10_viscosity_kernel = args[10].dat->size[1];
int xdim11_viscosity_kernel = args[11].dat->size[0];
int ydim11_viscosity_kernel = args[11].dat->size[1];
// Halo Exchanges
ops_H_D_exchanges_host(args, 12);
ops_halo_exchanges(args, 12, range);
ops_H_D_exchanges_host(args, 12);
if (OPS_diags > 1) {
ops_timers_core(&c1, &t1);
OPS_kernels[45].mpi_time += t1 - t2;
}
#pragma omp parallel for collapse(2)
for (int n_z = start[2]; n_z < end[2]; n_z++) {
for (int n_y = start[1]; n_y < end[1]; n_y++) {
#ifdef intel
#pragma omp simd
#else
#pragma simd
#endif
for (int n_x = start[0]; n_x < end[0]; n_x++) {
double grad2, pgradx, pgrady, pgradz, pgradx2, pgrady2, pgradz2, grad,
ygrad, xgrad, zgrad, div, limiter, pgrad;
double ugradx1 = xvel0[OPS_ACC0(0, 0, 0)] + xvel0[OPS_ACC0(0, 1, 0)] +
xvel0[OPS_ACC0(0, 0, 1)] + xvel0[OPS_ACC0(0, 1, 1)];
double ugradx2 = xvel0[OPS_ACC0(1, 0, 0)] + xvel0[OPS_ACC0(1, 1, 0)] +
xvel0[OPS_ACC0(1, 0, 1)] + xvel0[OPS_ACC0(1, 1, 1)];
double ugrady1 = xvel0[OPS_ACC0(0, 0, 0)] + xvel0[OPS_ACC0(1, 0, 0)] +
xvel0[OPS_ACC0(0, 0, 1)] + xvel0[OPS_ACC0(1, 0, 1)];
double ugrady2 = xvel0[OPS_ACC0(0, 1, 0)] + xvel0[OPS_ACC0(1, 1, 0)] +
xvel0[OPS_ACC0(0, 1, 1)] + xvel0[OPS_ACC0(1, 1, 1)];
double ugradz1 = xvel0[OPS_ACC0(0, 0, 0)] + xvel0[OPS_ACC0(1, 0, 0)] +
xvel0[OPS_ACC0(0, 1, 0)] + xvel0[OPS_ACC0(1, 1, 0)];
double ugradz2 = xvel0[OPS_ACC0(0, 0, 1)] + xvel0[OPS_ACC0(1, 0, 1)] +
xvel0[OPS_ACC0(0, 1, 1)] + xvel0[OPS_ACC0(1, 1, 1)];
double vgradx1 = yvel0[OPS_ACC1(0, 0, 0)] + yvel0[OPS_ACC1(0, 1, 0)] +
yvel0[OPS_ACC1(0, 0, 1)] + yvel0[OPS_ACC1(0, 1, 1)];
double vgradx2 = yvel0[OPS_ACC1(1, 0, 0)] + yvel0[OPS_ACC1(1, 1, 0)] +
yvel0[OPS_ACC1(1, 0, 1)] + yvel0[OPS_ACC1(1, 1, 1)];
double vgrady1 = yvel0[OPS_ACC1(0, 0, 0)] + yvel0[OPS_ACC1(1, 0, 0)] +
yvel0[OPS_ACC1(0, 0, 1)] + yvel0[OPS_ACC1(1, 0, 1)];
double vgrady2 = yvel0[OPS_ACC1(0, 1, 0)] + yvel0[OPS_ACC1(1, 1, 0)] +
yvel0[OPS_ACC1(0, 1, 1)] + yvel0[OPS_ACC1(1, 1, 1)];
double vgradz1 = yvel0[OPS_ACC1(0, 0, 0)] + yvel0[OPS_ACC1(1, 0, 0)] +
yvel0[OPS_ACC1(0, 1, 0)] + yvel0[OPS_ACC1(1, 1, 0)];
double vgradz2 = yvel0[OPS_ACC1(0, 0, 1)] + yvel0[OPS_ACC1(1, 0, 1)] +
yvel0[OPS_ACC1(0, 1, 1)] + yvel0[OPS_ACC1(1, 1, 1)];
double wgradx1 = zvel0[OPS_ACC7(0, 0, 0)] + zvel0[OPS_ACC7(0, 1, 0)] +
zvel0[OPS_ACC7(0, 0, 1)] + zvel0[OPS_ACC7(0, 1, 1)];
double wgradx2 = zvel0[OPS_ACC7(1, 0, 0)] + zvel0[OPS_ACC7(1, 1, 0)] +
zvel0[OPS_ACC7(1, 0, 1)] + zvel0[OPS_ACC7(1, 1, 1)];
double wgrady1 = zvel0[OPS_ACC7(0, 0, 0)] + zvel0[OPS_ACC7(1, 0, 0)] +
zvel0[OPS_ACC7(0, 0, 1)] + zvel0[OPS_ACC7(1, 0, 1)];
double wgrady2 = zvel0[OPS_ACC7(0, 1, 0)] + zvel0[OPS_ACC7(1, 1, 0)] +
zvel0[OPS_ACC7(0, 1, 1)] + zvel0[OPS_ACC7(1, 1, 1)];
double wgradz1 = zvel0[OPS_ACC7(0, 0, 0)] + zvel0[OPS_ACC7(1, 0, 0)] +
zvel0[OPS_ACC7(0, 1, 0)] + zvel0[OPS_ACC7(1, 1, 0)];
double wgradz2 = zvel0[OPS_ACC7(0, 0, 1)] + zvel0[OPS_ACC7(1, 0, 1)] +
zvel0[OPS_ACC7(0, 1, 1)] + zvel0[OPS_ACC7(1, 1, 1)];
div = xarea[OPS_ACC9(0, 0, 0)] * (ugradx2 - ugradx1) +
yarea[OPS_ACC10(0, 0, 0)] * (vgrady2 - vgrady1) +
zarea[OPS_ACC11(0, 0, 0)] * (wgradz2 - wgradz1);
double xx = 0.25 * (ugradx2 - ugradx1) / (celldx[OPS_ACC2(0, 0, 0)]);
double yy = 0.25 * (vgrady2 - vgrady1) / (celldy[OPS_ACC3(0, 0, 0)]);
double zz = 0.25 * (wgradz2 - wgradz1) / (celldz[OPS_ACC8(0, 0, 0)]);
double xy = 0.25 * (ugrady2 - ugrady1) / (celldy[OPS_ACC3(0, 0, 0)]) +
0.25 * (vgradx2 - vgradx1) / (celldx[OPS_ACC2(0, 0, 0)]);
double xz = 0.25 * (ugradz2 - ugradz1) / (celldz[OPS_ACC8(0, 0, 0)]) +
0.25 * (wgradx2 - wgradx1) / (celldx[OPS_ACC2(0, 0, 0)]);
double yz = 0.25 * (vgradz2 - vgradz1) / (celldz[OPS_ACC8(0, 0, 0)]) +
0.25 * (wgrady2 - wgrady1) / (celldy[OPS_ACC3(0, 0, 0)]);
pgradx = (pressure[OPS_ACC4(1, 0, 0)] - pressure[OPS_ACC4(-1, 0, 0)]) /
(celldx[OPS_ACC2(0, 0, 0)] + celldx[OPS_ACC2(1, 0, 0)]);
pgrady = (pressure[OPS_ACC4(0, 1, 0)] - pressure[OPS_ACC4(0, -1, 0)]) /
(celldy[OPS_ACC3(0, 0, 0)] + celldy[OPS_ACC3(0, 1, 0)]);
pgradz = (pressure[OPS_ACC4(0, 0, 1)] - pressure[OPS_ACC4(0, 0, -1)]) /
(celldz[OPS_ACC8(0, 0, 0)] + celldz[OPS_ACC8(0, 0, 1)]);
pgradx2 = pgradx * pgradx;
pgrady2 = pgrady * pgrady;
pgradz2 = pgradz * pgradz;
limiter =
(xx * pgradx2 + yy * pgrady2 + zz * pgradz2 + xy * pgradx * pgrady +
xz * pgradx * pgradz + yz * pgrady * pgradz) /
MAX(pgradx2 + pgrady2 + pgradz2, 1.0e-16);
if ((limiter > 0.0) || (div >= 0.0)) {
viscosity[OPS_ACC6(0, 0, 0)] = 0.0;
} else {
pgradx = SIGN(MAX(1.0e-16, fabs(pgradx)), pgradx);
pgrady = SIGN(MAX(1.0e-16, fabs(pgrady)), pgrady);
pgradz = SIGN(MAX(1.0e-16, fabs(pgradz)), pgradz);
pgrad = sqrt(pgradx * pgradx + pgrady * pgrady + pgradz * pgradz);
xgrad = fabs(celldx[OPS_ACC2(0, 0, 0)] * pgrad / pgradx);
ygrad = fabs(celldy[OPS_ACC3(0, 0, 0)] * pgrad / pgrady);
zgrad = fabs(celldz[OPS_ACC8(0, 0, 0)] * pgrad / pgradz);
grad = MIN(xgrad, MIN(ygrad, zgrad));
grad2 = grad * grad;
viscosity[OPS_ACC6(0, 0, 0)] =
2.0 * (density0[OPS_ACC5(0, 0, 0)]) * grad2 * limiter * limiter;
}
}
}
}
if (OPS_diags > 1) {
ops_timers_core(&c2, &t2);
OPS_kernels[45].time += t2 - t1;
}
ops_set_dirtybit_host(args, 12);
ops_set_halo_dirtybit3(&args[6], range);
if (OPS_diags > 1) {
// Update kernel record
ops_timers_core(&c1, &t1);
OPS_kernels[45].mpi_time += t1 - t2;
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg0);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg1);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg2);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg3);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg4);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg5);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg6);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg7);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg8);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg9);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg10);
OPS_kernels[45].transfer += ops_compute_transfer(dim, start, end, &arg11);
}
}
#undef OPS_ACC0
#undef OPS_ACC1
#undef OPS_ACC2
#undef OPS_ACC3
#undef OPS_ACC4
#undef OPS_ACC5
#undef OPS_ACC6
#undef OPS_ACC7
#undef OPS_ACC8
#undef OPS_ACC9
#undef OPS_ACC10
#undef OPS_ACC11
void ops_par_loop_viscosity_kernel(char const *name, ops_block block, int dim,
int *range, ops_arg arg0, ops_arg arg1,
ops_arg arg2, ops_arg arg3, ops_arg arg4,
ops_arg arg5, ops_arg arg6, ops_arg arg7,
ops_arg arg8, ops_arg arg9, ops_arg arg10,
ops_arg arg11) {
ops_kernel_descriptor *desc =
(ops_kernel_descriptor *)malloc(sizeof(ops_kernel_descriptor));
desc->name = name;
desc->block = block;
desc->dim = dim;
desc->index = 45;
#ifdef OPS_MPI
sub_block_list sb = OPS_sub_block_list[block->index];
if (!sb->owned)
return;
for (int n = 0; n < 3; n++) {
desc->range[2 * n] = sb->decomp_disp[n];
desc->range[2 * n + 1] = sb->decomp_disp[n] + sb->decomp_size[n];
if (desc->range[2 * n] >= range[2 * n]) {
desc->range[2 * n] = 0;
} else {
desc->range[2 * n] = range[2 * n] - desc->range[2 * n];
}
if (sb->id_m[n] == MPI_PROC_NULL && range[2 * n] < 0)
desc->range[2 * n] = range[2 * n];
if (desc->range[2 * n + 1] >= range[2 * n + 1]) {
desc->range[2 * n + 1] = range[2 * n + 1] - sb->decomp_disp[n];
} else {
desc->range[2 * n + 1] = sb->decomp_size[n];
}
if (sb->id_p[n] == MPI_PROC_NULL &&
(range[2 * n + 1] > sb->decomp_disp[n] + sb->decomp_size[n]))
desc->range[2 * n + 1] +=
(range[2 * n + 1] - sb->decomp_disp[n] - sb->decomp_size[n]);
}
#else // OPS_MPI
for (int i = 0; i < 6; i++) {
desc->range[i] = range[i];
}
#endif // OPS_MPI
desc->nargs = 12;
desc->args = (ops_arg *)malloc(12 * sizeof(ops_arg));
desc->args[0] = arg0;
desc->args[1] = arg1;
desc->args[2] = arg2;
desc->args[3] = arg3;
desc->args[4] = arg4;
desc->args[5] = arg5;
desc->args[6] = arg6;
desc->args[7] = arg7;
desc->args[8] = arg8;
desc->args[9] = arg9;
desc->args[10] = arg10;
desc->args[11] = arg11;
desc->function = ops_par_loop_viscosity_kernel_execute;
ops_enqueue_kernel(desc);
}
| [
"mudalige@octon.arc.ox.ac.uk"
] | mudalige@octon.arc.ox.ac.uk |
ca7407fddf17ccd03d8c4a40112e28be125f822d | e9a9bcc6f33f269c8ca8dd114aa46adca77d8b8b | /TakeAway/reguserdb.h | 81d9b5adb7ddf63af9da0ac87b7a4a7a48e6893d | [] | no_license | ZTL522/TinyTakeawaySystem | e932947c1276197a5f9164f7efc94b617b55362c | 755607732076441a17af6081e4f44fba1e51dec8 | refs/heads/master | 2021-07-15T17:49:16.478851 | 2017-01-26T15:13:58 | 2017-01-26T15:13:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 368 | h | #ifndef REGUSERDB_H
#define REGUSERDB_H
#include "prerequisite.h"
#include "userds.h"
#include "abstractdb.h"
class RegUserDB : public AbstractDB
{
public:
RegUserDB();
bool searchUserByUsername(UserDS& user);
bool addUser(UserDS& user);
bool authUser(UserDS& user);
bool searchUserByUsernameAndPassword(UserDS& user);
};
#endif // REGUSERDB_H
| [
"j88172365@gmail.com"
] | j88172365@gmail.com |
ea74c7c0f1adf11bd47383f7176a492bb33c2e3c | f08e94e6e149677fb40a6036eddb49d98226097c | /Component/Camera2D.hpp | 40f8627e09cc6e7146526ffc90fc21b88173b612 | [] | no_license | Pinkdaoge/wlEngine | 8b608e562714a392e095c19a345525d943633cb8 | 9bb27bf2c007fdc916912a5c0579d677e980d14b | refs/heads/master | 2020-09-28T14:45:36.823040 | 2019-12-02T04:53:34 | 2019-12-02T04:53:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | hpp | #pragma once
#include "Camera.hpp"
#include <glm/matrix.hpp>
#include "../GameObject/Entity.hpp"
#include "../Input.hpp"
#include "../Time.hpp"
namespace wlEngine
{
struct Camera2D : public Camera
{
public:
COMPONENT_DECLARATION_NEW(Camera, Camera2D);
COMPONENT_EDITABLE_DEC();
Camera2D(Entity *go);
Camera2D(Entity *go, void **);
glm::mat4 GetViewMatrix() const override;
glm::mat4 GetProjMatrix() const override;
virtual void SetProjectionMatrix(const float &left, const float &right,
const float &bottom, const float &top, const float &zNear, const float &zFar) override;
float speed = 100.0;
void update();
};
} // namespace wlEngine
| [
"jjiangweilan@gmail.com"
] | jjiangweilan@gmail.com |
c7cc7c3cbdf7e20903ef0218a51fe40499181335 | db57b19e70315c4adb79020c64a1c9d2b4e3cc94 | /system/StringBuilder.cpp | f3e3d0d6f3eed6df526658573bb1410dedb9f9cd | [] | no_license | rock3125/gforce-x | da9d5d75769780939314bf03ac008f9d7362e675 | 3a349ea799dfe1f24fb04bb14b643175730c2d95 | refs/heads/master | 2021-12-25T06:27:14.101284 | 2017-02-20T09:32:44 | 2017-02-20T09:32:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,765 | cpp | #include "standardFirst.h"
#include "system/StringBuilder.h"
//////////////////////////////////////////////////////////
StringBuilder::StringBuilder()
: buffer(NULL)
{
initialSize = 8192;
bufferSize = initialSize;
currentSize = 0;
buffer = new char[bufferSize];
}
StringBuilder::StringBuilder(int _initialSize)
: buffer(NULL)
{
initialSize = _initialSize;
bufferSize = initialSize;
currentSize = 0;
buffer = new char[bufferSize];
}
StringBuilder::~StringBuilder()
{
safe_delete_array(buffer);
bufferSize = 0;
currentSize = 0;
}
void StringBuilder::Clear()
{
safe_delete_array(buffer);
initialSize = 8192;
bufferSize = initialSize;
currentSize = 0;
buffer = new char[bufferSize];
}
int StringBuilder::Length()
{
return currentSize;
}
const char* StringBuilder::GetString()
{
return buffer;
}
void StringBuilder::Append(const std::string& str)
{
Add(str);
}
void StringBuilder::Append(int i)
{
Add(System::Int2Str(i));
}
void StringBuilder::Append(float f)
{
Add(System::Float2Str(f));
}
void StringBuilder::Append(char ch)
{
char buf[2];
buf[0] = ch;
buf[1] = 0;
Add(buf);
}
void StringBuilder::Add(const std::string& str)
{
if ((currentSize + str.size() + 1) > bufferSize)
{
int increase = bufferSize * 2;
if ((str.size() + 1) > bufferSize)
increase = (currentSize + str.size() + 100);
char* newBuffer = new char[increase];
memcpy(newBuffer,buffer,bufferSize);
bufferSize = increase;
safe_delete_array(buffer);
buffer = newBuffer;
}
memcpy(&buffer[currentSize], str.c_str(), str.size()+1);
currentSize += str.size();
}
std::string StringBuilder::ToString()
{
buffer[currentSize] = 0;
return buffer;
}
| [
"peter@peter.co.nz"
] | peter@peter.co.nz |
c18e770bfdb549d3ca65c2826ae4e85b1697479a | ea63052373c80425c2c668f7fe6fcc2dd4998b32 | /libs.h | 0319844572de70d4b00bd98e93b4149d9cde680c | [] | no_license | spczk/CPP-csv_to_txt | be9073d2259b29573753fafb79e9ecddc63edf9f | 87b0dc92c185a1407a5c12ff454d364c5eb1d7ee | refs/heads/master | 2021-09-02T03:25:21.595010 | 2017-12-29T22:55:54 | 2017-12-29T22:55:54 | 115,758,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | h | //
// Created by Igor Śpiączka on 29.12.2017.
//
#ifndef CSV_TO_TXT_LIBS_H
#define CSV_TO_TXT_LIBS_H
#include <iostream>
#include <fstream>
#include <string>
#include "extensions.h"
#endif //CSV_TO_TXT_LIBS_H
| [
"igor.spiaczka@gmail.com"
] | igor.spiaczka@gmail.com |
f7fad0cc34f9bb59d3e3c35abc52c6403d18d4d0 | e4213546785e6737057902c6524e804ffd3e8024 | /Open3D_bk/Visualization/Utility/SelectionPolygon.h | e4234b2b5107d6fe2c3d7d4bf5c5a6819385d679 | [
"BSD-2-Clause"
] | permissive | brain-cog/Brain_inspired_Batch | 358bdc0a1d882d19cfac30232c7c5098114c5fa1 | 8d33f9690a57bd0828d53c8208d905005629afe7 | refs/heads/master | 2020-07-23T08:50:28.849312 | 2019-05-29T01:26:22 | 2019-05-29T01:26:22 | 207,504,653 | 4 | 2 | BSD-2-Clause | 2019-09-10T08:26:45 | 2019-09-10T08:26:44 | null | UTF-8 | C++ | false | false | 3,992 | h | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 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.
// ----------------------------------------------------------------------------
#pragma once
#include <vector>
#include <memory>
#include <Eigen/Core>
#include <Open3D/Geometry/Geometry2D.h>
#include <Open3D/Geometry/Image.h>
namespace open3d {
namespace geometry {
class PointCloud;
class TriangleMesh;
} // namespace geometry
namespace visualization {
class ViewControl;
class SelectionPolygonVolume;
/// A 2D polygon used for selection on screen
/// It is a utility class for Visualization
/// The coordinates in SelectionPolygon are lower-left corner based (the OpenGL
/// convention).
class SelectionPolygon : public geometry::Geometry2D {
public:
enum class SectionPolygonType {
Unfilled = 0,
Rectangle = 1,
Polygon = 2,
};
public:
SelectionPolygon()
: geometry::Geometry2D(geometry::Geometry::GeometryType::Unspecified) {}
~SelectionPolygon() override {}
public:
void Clear() override;
bool IsEmpty() const override;
Eigen::Vector2d GetMinBound() const final;
Eigen::Vector2d GetMaxBound() const final;
void FillPolygon(int width, int height);
std::shared_ptr<geometry::PointCloud> CropPointCloud(
const geometry::PointCloud &input, const ViewControl &view);
std::shared_ptr<geometry::TriangleMesh> CropTriangleMesh(
const geometry::TriangleMesh &input, const ViewControl &view);
std::shared_ptr<SelectionPolygonVolume> CreateSelectionPolygonVolume(
const ViewControl &view);
private:
std::shared_ptr<geometry::PointCloud> CropPointCloudInRectangle(
const geometry::PointCloud &input, const ViewControl &view);
std::shared_ptr<geometry::PointCloud> CropPointCloudInPolygon(
const geometry::PointCloud &input, const ViewControl &view);
std::shared_ptr<geometry::TriangleMesh> CropTriangleMeshInRectangle(
const geometry::TriangleMesh &input, const ViewControl &view);
std::shared_ptr<geometry::TriangleMesh> CropTriangleMeshInPolygon(
const geometry::TriangleMesh &input, const ViewControl &view);
std::vector<size_t> CropInRectangle(
const std::vector<Eigen::Vector3d> &input, const ViewControl &view);
std::vector<size_t> CropInPolygon(const std::vector<Eigen::Vector3d> &input,
const ViewControl &view);
public:
std::vector<Eigen::Vector2d> polygon_;
bool is_closed_ = false;
geometry::Image polygon_interior_mask_;
SectionPolygonType polygon_type_ = SectionPolygonType::Unfilled;
};
} // namespace visualization
} // namespace open3d
| [
"tmczhangtielin@gmail.com"
] | tmczhangtielin@gmail.com |
2bd6347263fc1f218cc48055c41d5c95d2691f4a | 5f60761e2899308c428edb07a9be37e083fdc18d | /libmixed/poller.hpp | d1a0b69712910ba1f76ba518f0b8127036f67856 | [] | no_license | hilander/src | fd60681c0e0ef4ec272bb7736d77017dd406be28 | 7cf4fd71e928f7137d0ae11c767c47e84fb177d5 | refs/heads/master | 2016-09-06T08:02:42.151565 | 2011-05-18T21:37:01 | 2011-05-18T21:37:01 | 1,356,761 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 930 | hpp | #ifndef LIBMIXED_SOCKET_HPP
#define LIBMIXED_SOCKET_HPP
#include <tr1/memory>
#include <map>
#include <vector>
#include <sys/epoll.h>
namespace scheduler
{
class poller
{
public: // typedefs
typedef std::tr1::shared_ptr< poller > ptr;
public:
static ptr get();
/** \brief Triggeruj epoll-a: sprawdź, które sockety coś zapisały / odczytały
* \return true, gdy co najmniej jeden z socketów zmienił stan; false wpw.
*/
std::vector< ::epoll_event >* poll();
bool add( int fd_, uint32_t flags ) throw( std::exception );
bool add( int fd_ ) throw( std::exception );
void remove( int fd_ );
bool contains ( int fd_ );
public:
void init();
~poller();
private:
poller();
poller( poller& );
private:
int _fd;
size_t current_sockets_number;
::epoll_event* watched_sockets;
std::map< int, ::epoll_event > _events;
size_t watched_sockets_size;
};
}
#endif
| [
"mariusz.barycz@gmail.com"
] | mariusz.barycz@gmail.com |
a5fe9cd4121ec8f6cec49503cce4960b7ab77471 | 3d07f3247b027a044f90eee1c744e91a98951dde | /3rdparty/dynamixel_c++/example/protocol2.0/read_write/read_write.cpp | 8288e8078664e6c6ef1ca6423de1dd28fca8b0b3 | [] | no_license | murilomend/humanoid_movement | f93d2ab66fbbfaaff7d4cc906df338e36ce36ea3 | e657538b1d239b8df63ff03875155687a93f5d21 | refs/heads/master | 2020-03-26T08:39:47.810954 | 2018-08-14T12:01:07 | 2018-08-14T12:01:07 | 144,714,031 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,366 | cpp | /*******************************************************************************
* Copyright (c) 2016, ROBOTIS CO., LTD.
* 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 ROBOTIS 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.
*******************************************************************************/
/* Author: Ryu Woon Jung (Leon) */
//
// ********* Read and Write Example *********
//
//
// Available Dynamixel model on this example : All models using Protocol 2.0
// This example is tested with a Dynamixel PRO 54-200, and an USB2DYNAMIXEL
// Be sure that Dynamixel PRO properties are already set as %% ID : 1 / Baudnum : 1 (Baudrate : 57600)
//
#if defined(__linux__) || defined(__APPLE__)
#include <fcntl.h>
#include <termios.h>
#define STDIN_FILENO 0
#elif defined(_WIN32) || defined(_WIN64)
#include <conio.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include "dynamixel_sdk.h" // Uses Dynamixel SDK library
// Control table address
#define ADDR_PRO_TORQUE_ENABLE 562 // Control table address is different in Dynamixel model
#define ADDR_PRO_GOAL_POSITION 596
#define ADDR_PRO_PRESENT_POSITION 611
// Protocol version
#define PROTOCOL_VERSION 2.0 // See which protocol version is used in the Dynamixel
// Default setting
#define DXL_ID 1 // Dynamixel ID: 1
#define BAUDRATE 57600
#define DEVICENAME "/dev/ttyUSB0" // Check which port is being used on your controller
// ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"
#define TORQUE_ENABLE 1 // Value for enabling the torque
#define TORQUE_DISABLE 0 // Value for disabling the torque
#define DXL_MINIMUM_POSITION_VALUE -150000 // Dynamixel will rotate between this value
#define DXL_MAXIMUM_POSITION_VALUE 150000 // and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)
#define DXL_MOVING_STATUS_THRESHOLD 20 // Dynamixel moving status threshold
#define ESC_ASCII_VALUE 0x1b
int getch()
{
#if defined(__linux__) || defined(__APPLE__)
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
#elif defined(_WIN32) || defined(_WIN64)
return _getch();
#endif
}
int kbhit(void)
{
#if defined(__linux__) || defined(__APPLE__)
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if (ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
#elif defined(_WIN32) || defined(_WIN64)
return _kbhit();
#endif
}
int main()
{
// Initialize PortHandler instance
// Set the port path
// Get methods and members of PortHandlerLinux or PortHandlerWindows
dynamixel::PortHandler *portHandler = dynamixel::PortHandler::getPortHandler(DEVICENAME);
// Initialize PacketHandler instance
// Set the protocol version
// Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler
dynamixel::PacketHandler *packetHandler = dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION);
int index = 0;
int dxl_comm_result = COMM_TX_FAIL; // Communication result
int dxl_goal_position[2] = {DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE}; // Goal position
uint8_t dxl_error = 0; // Dynamixel error
int32_t dxl_present_position = 0; // Present position
// Open port
if (portHandler->openPort())
{
printf("Succeeded to open the port!\n");
}
else
{
printf("Failed to open the port!\n");
printf("Press any key to terminate...\n");
getch();
return 0;
}
// Set port baudrate
if (portHandler->setBaudRate(BAUDRATE))
{
printf("Succeeded to change the baudrate!\n");
}
else
{
printf("Failed to change the baudrate!\n");
printf("Press any key to terminate...\n");
getch();
return 0;
}
// Enable Dynamixel Torque
dxl_comm_result = packetHandler->write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE, &dxl_error);
if (dxl_comm_result != COMM_SUCCESS)
{
// printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));
printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));
}
else if (dxl_error != 0)
{
// printf("%s\n", packetHandler->getRxPacketError(dxl_error));
printf("%s\n", packetHandler->getRxPacketError(dxl_error));
}
else
{
printf("Dynamixel has been successfully connected \n");
}
while(1)
{
printf("Press any key to continue! (or press ESC to quit!)\n");
if (getch() == ESC_ASCII_VALUE)
break;
// Write goal position
dxl_comm_result = packetHandler->write4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_GOAL_POSITION, dxl_goal_position[index], &dxl_error);
if (dxl_comm_result != COMM_SUCCESS)
{
printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));
}
else if (dxl_error != 0)
{
printf("%s\n", packetHandler->getRxPacketError(dxl_error));
}
do
{
// Read present position
dxl_comm_result = packetHandler->read4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_PRESENT_POSITION, (uint32_t*)&dxl_present_position, &dxl_error);
if (dxl_comm_result != COMM_SUCCESS)
{
printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));
}
else if (dxl_error != 0)
{
printf("%s\n", packetHandler->getRxPacketError(dxl_error));
}
printf("[ID:%03d] GoalPos:%03d PresPos:%03d\n", DXL_ID, dxl_goal_position[index], dxl_present_position);
}while((abs(dxl_goal_position[index] - dxl_present_position) > DXL_MOVING_STATUS_THRESHOLD));
// Change goal position
if (index == 0)
{
index = 1;
}
else
{
index = 0;
}
}
// Disable Dynamixel Torque
dxl_comm_result = packetHandler->write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE, &dxl_error);
if (dxl_comm_result != COMM_SUCCESS)
{
printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));
}
else if (dxl_error != 0)
{
printf("%s\n", packetHandler->getRxPacketError(dxl_error));
}
// Close port
portHandler->closePort();
return 0;
}
| [
"murilomend@yahoo.com.br"
] | murilomend@yahoo.com.br |
734ab7a14718249367fedd263f91830b79bd5157 | c3cb4a0d8c206a0eff1af01142abfba5f5de398f | /mark.1.2/mark.1.ino | 86abf400c8b49279a882f5c1eef370b606f8a979 | [] | no_license | felypemoura30/carrinho-mark1 | ba4fe82a228877c181e327291b8102a09f084416 | c817e39fca916a1485bddeb0773858bc8622259f | refs/heads/master | 2020-06-08T09:16:59.716326 | 2015-09-03T22:48:52 | 2015-09-03T22:48:52 | 41,752,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,970 | ino | #include <Servo.h> //INCLUSAO DA BIBLIOTECA DO SERVO MOTOR
#include "IRremote.h" //INCLUSAO DA BIBLIOTECA DO CONTROLE IR
#define echoPin 12
//CONFIGURAÇÃO DOS MOTORES A/B
int ENABLEA = 1; //INICIALIZAÇÃO DO MOTOR A
int MOTORA1 = 2;
int MOTORA2 = 3;
int ENABLEB = 4; //INICIALIZAÇÃO DO MOTOR B
int MOTORB1 = 5;
int MOTORB2 = 6;
//CONFIGURAÇÃO DO ULTRASSONICO
int trigger = 13; //DEFINIÇÃO DO PINO DE TRIGGER ULTASSONICO
int echo= 12; //DEFINIÇÃO DO PINO ECHO ULTRASSONICO
int leftscanval, centerscanval, rightscanval, ldiagonalscanval, rdiagonalscanval;
char choice;
//CONFIGURAÇÃO DO CONTROLE IR
int receptor = 11; //DEFINIÇÃO DO PINO DIGITAL DO RECEPTOR IR
IRrecv irrecv(receptor); //INSTANCIA 'irrecv'
decode_results results;
char contcommand;
int modecontrol = 0;
int power = 0;
//PARAMETROS LIMITES DE DISTANCIA
int distancelimit =1;
int sidedistancelimit=12;
int distance;
int numcycles = 0;
char turndirection; //MUDA A DIREÇÃO PARA O LADO SEM OBSTACULOS;
int turntime = 900; //TEMPO PARA O CARRINHO VIRAR EM MILESEGUNDOS;
int thereis;
//INICIALIZAÇÃO DO SERVO
Servo head;
void setup() {
head.attach(0);
head.write(90);
irrecv.enableIRIn(); //INICIA O SENSOR IR
pinMode(MOTORA1, OUTPUT);
pinMode(MOTORA2, OUTPUT);
pinMode(MOTORB1, OUTPUT); //DEFINE AS PORTAS DOS MOTORES COMO SAIDAS
pinMode(MOTORB2, OUTPUT);
pinMode(trigger, OUTPUT); //DEFINE 'trigger' DO ULTRASSONICO COMO SAIDA
pinMode(echo, INPUT); //DEFINE 'echo' DO ULTRASSONICO COMO ENTRADA
//INICIANDO OS MOTORES
digitalWrite(MOTORA1, LOW);
digitalWrite(MOTORA2, LOW);
digitalWrite(MOTORB1, LOW);
digitalWrite(MOTORB2, LOW);
}
void go(){
digitalWrite(MOTORA1, LOW);
digitalWrite(MOTORA2, HIGH);
digitalWrite(MOTORB1, HIGH);
digitalWrite(MOTORB2, LOW);
}
void backwards(){
digitalWrite(MOTORA1, HIGH);
digitalWrite(MOTORA2, LOW);
digitalWrite(MOTORB1, LOW);
digitalWrite(MOTORB2, HIGH);
}
int watch(){
long howfar;
float Temp;
digitalWrite(trigger, LOW);
delay(5);
digitalWrite(trigger, HIGH);
delay (15);
digitalWrite(trigger, LOW);
//howfar = pulseIn(echo, HIGH);
Temp = pulseIn(echoPin, HIGH);
howfar = (Temp/2)/29.1;
howfar = howfar * 0.5;
//howfar= howfar*0.01657; //'howfar' E A DISTANCIA DO OBJETO EM CM
return round(howfar);
}
void turnright(int t){
digitalWrite(MOTORA1, HIGH);
digitalWrite(MOTORA2, LOW);
digitalWrite(MOTORB1, HIGH);
digitalWrite(MOTORB2, LOW);
delay(t);
}
void turnleft(int t){
digitalWrite(MOTORA1, LOW);
digitalWrite(MOTORA2, HIGH);
digitalWrite(MOTORB1, LOW);
digitalWrite(MOTORB2, HIGH);
delay(t);
}
void stopmove(){
digitalWrite(MOTORA1, LOW);
digitalWrite(MOTORA2, LOW);
digitalWrite(MOTORB1, LOW);
digitalWrite(MOTORB2, LOW);
}
void watchsurrounding(){
centerscanval = watch();
if(centerscanval>distancelimit){
stopmove();
}
/*head.write(120);
delay(100);
ldiagonalscanval = watch();
if(ldiagonalscanval>distancelimit){
stopmove();
}
head.write(160);
delay(100);
leftscanval = watch();
if(leftscanval>sidedistancelimit){
stopmove();
}
head.write(120);
delay(100);
ldiagonalscanval = watch();
if(ldiagonalscanval>distancelimit){
stopmove();
}
head.write(90);
delay(100);
centerscanval = watch();
if(centerscanval>distancelimit){
stopmove();
}
head.write(40);
delay(100);
rdiagonalscanval = watch();
if(rdiagonalscanval>distancelimit){
stopmove();*/
head.write(180);
delay(900);
rdiagonalscanval = watch();
if(rdiagonalscanval>distancelimit){
stopmove();
}
head.write(0);
delay(900);
rightscanval = watch();
if(rightscanval>sidedistancelimit){
stopmove();
}
head.write(180);
delay(900);
ldiagonalscanval = watch();
if(ldiagonalscanval>distancelimit){
stopmove();
}
head.write(90);
delay(50);
}
char decide(){
watchsurrounding();
if(leftscanval>rightscanval && leftscanval>centerscanval){
choice ='l';
}
else if(rightscanval>leftscanval && rightscanval>centerscanval){
choice = 'r';
}
else{
choice = 'f';
}
return choice;
}
void translateIR(){
switch(results.value){
case 0xFF18E7: //MOVE PARA FRENTE PRESSIONANDO 2
go();
break;
case 0xFF10EF: //MOVE PARA ESQUERDA PRESSIONANDO 4
turnleft(turntime);
stopmove();
break;
case 0xFF6897: //BOTAO DE 'OK' PRESSIONANDO 0
stopmove();
break;
case 0xFF5AA5: //MOVE PARA A DIREITA PRESSIONANDO 6
turnright(turntime);
stopmove();
break;
case 0xFF4AB5: //MOVE PARA TRAS PRESSIONANDO 8
backwards();
break;
case 0xFF629D: //MUDA O MODO DE OPERAÇÃO PRESSIONANDO MODE
modecontrol = 0;
stopmove();
break;
default:
;
}
delay(500); //nao fazer repetiçoes imediatas
}
void loop(){
if(irrecv.decode(&results)){ //CHECAGEM PARA VER SE O CONTROLE IR ESTA MANDANDO SINAL
if(results.value == 0xFF22DD ){ //LIGA O CARRINHO APERTANDO PLAY/PAUSE
power = 1;
}
if(results.value == 0xFFFFA25D){ //DESLIGA O CARRINHO APERTANDO O BOTAO POWER
stopmove();
power = 0;
}
if(results.value == 0xFF629D){ //MUDA O MODO DE OPERAÇÃO PRESSIONANDO MODE
modecontrol = 1; //ATIVA O MODO DE CONTROLE IR
stopmove(); //O CARRINHO PARA E COMEÇA A RESPONDER AO CONTROLE IR
}
irrecv.resume(); //RECEBE O PROXIMO VALOR
}
while(modecontrol == 1){//O SISTEMA ENTRARA EM LOOP DURANTE O CONTROLE POR IR ATE 'modecontrol = 0' (APERTANDO BOTAO MODE)
if (irrecv.decode(&results)){ // SE ALGUMA COISA FOR RECEBIDA
translateIR(); // FAÇA ALGO DEPEDENDO DO VALOR RECEBIDO
irrecv.resume(); // RECEBA O PROXIMO VALOR
}
}
if(power == 1){
go(); // SE NAO HOUVER NADA DE ERRADO O CARRINHO IRA ANDAR PARA FRENTE
++numcycles;
if(numcycles>10){ // PROCURA OBSTACULOS A CADA CICLO DE 10 LOOPS
watchsurrounding();
if(leftscanval<sidedistancelimit || ldiagonalscanval<distancelimit){
turnright(turntime);
}
if(rightscanval<sidedistancelimit || rdiagonalscanval<distancelimit){
turnleft(turntime);
}
numcycles = 0; //RE STARTA A CONTAGEM DE CICLOS
}
distance = watch(); //USA A FUNÇÃO 'watch();' PARA VER SE NAO A OBSTACULOS A FRENTE
if(distance<distancelimit){ //O CARRINHO SO IRA PARAR SE REALMENTE HOUVER UM GRANDE OBSTACULO A FRENTE
++thereis;
}
if (distance>distancelimit){
thereis=0;} //CONTAGEM E REINICIADA
if (thereis > 25){
stopmove(); // DESDE QUE HAJA ALGO NA FRENTE O CARRINHO PARA
turndirection = decide(); //DECIDE QUAL DIREÇÃO VIRAR.
switch (turndirection){
case 'l':
turnleft(turntime);
break;
case 'r':
turnright(turntime);
break;
case 'f':
; //NAO VIRA SE NAO HOUVER NADA NA FRENTE
break;
}
thereis=0;
}
}
}
| [
"felypemoura30@hotmail.com"
] | felypemoura30@hotmail.com |
bce182dd79dc6db3b7a27881282dd6a68b63e722 | b1072cc3c2b32073466d530d6a3724fe2256da3e | /src/sim/resultfilters.cc | 692d0d9f591195b609eedee04ee37c21b47f86df | [] | no_license | ayjavaid/OMNET_OS3_UAVSim | e66af63ec5988d7b87684a80529690732986b558 | 2a002daa1b32bf3d6883271f0226b70076c32485 | refs/heads/master | 2021-05-15T01:32:08.590544 | 2018-09-25T18:02:42 | 2018-09-25T18:02:42 | 30,726,345 | 7 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 5,656 | cc | //==========================================================================
// RESULTFILTERS.CC - part of
// OMNeT++/OMNEST
// Discrete System Simulation in C++
//
// Author: Andras Varga
//
//==========================================================================
/*--------------------------------------------------------------*
Copyright (C) 1992-2008 Andras Varga
Copyright (C) 2006-2008 OpenSim Ltd.
This file is distributed WITHOUT ANY WARRANTY. See the file
`license' for details on this and other legal matters.
*--------------------------------------------------------------*/
#include "resultfilters.h"
#include "cmessage.h" // PacketBytesFilter
NAMESPACE_BEGIN
// note: we don't register WarmupPeriodFilter and ExpressionFilter
Register_ResultFilter("count", CountFilter);
Register_ResultFilter("constant0", Constant0Filter);
Register_ResultFilter("constant1", Constant1Filter);
Register_ResultFilter("sum", SumFilter);
Register_ResultFilter("mean", MeanFilter);
Register_ResultFilter("min", MinFilter);
Register_ResultFilter("max", MaxFilter);
Register_ResultFilter("last", IdentityFilter); // useful for expressions like: record=last+5
Register_ResultFilter("timeavg", TimeAverageFilter);
Register_ResultFilter("removeRepeats", RemoveRepeatsFilter);
Register_ResultFilter("packetBytes", PacketBytesFilter);
Register_ResultFilter("packetBits", PacketBitsFilter);
Register_ResultFilter("sumPerDuration", SumPerDurationFilter);
void WarmupPeriodFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, bool b)
{
if (t >= getEndWarmupPeriod())
fire(this, t, b);
}
void WarmupPeriodFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, long l)
{
if (t >= getEndWarmupPeriod())
fire(this, t, l);
}
void WarmupPeriodFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, unsigned long l)
{
if (t >= getEndWarmupPeriod())
fire(this, t, l);
}
void WarmupPeriodFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, double d)
{
if (t >= getEndWarmupPeriod())
fire(this, t, d);
}
void WarmupPeriodFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, const SimTime& v)
{
if (t >= getEndWarmupPeriod())
fire(this, t, v);
}
void WarmupPeriodFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, const char *s)
{
if (t >= getEndWarmupPeriod())
fire(this, t, s);
}
void WarmupPeriodFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, cObject *obj)
{
// note: cITimestampedValue stuff was already dispatched to (simtime_t,double) method in base class
if (t >= getEndWarmupPeriod())
fire(this, t, obj);
}
//---
bool TimeAverageFilter::process(simtime_t& t, double& value)
{
bool isFirstValue = startTime < SIMTIME_ZERO;
if (isFirstValue)
startTime = t;
else
weightedSum += lastValue * SIMTIME_DBL(t - lastTime); // always forward-sample-hold
lastTime = t;
lastValue = value;
if (isFirstValue || t==startTime)
return false; // suppress initial 0/0 = NaNs
double interval = SIMTIME_DBL(t - startTime);
value = weightedSum / interval;
return true;
}
//---
bool UnaryExpressionFilter::process(simtime_t& t, double& value)
{
currentTime = t;
currentValue = value;
value = expr.doubleValue();
return true;
}
void NaryExpressionFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, bool b)
{
simtime_t tt = t;
double d = b;
if (process(prev, tt, d))
fire(this, tt, d);
}
void NaryExpressionFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, long l)
{
simtime_t tt = t;
double d = l;
if (process(prev, tt, d))
fire(this, tt, d);
}
void NaryExpressionFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, unsigned long l)
{
simtime_t tt = t;
double d = l;
if (process(prev, tt, d))
fire(this, tt, d);
}
void NaryExpressionFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, double d)
{
simtime_t tt = t;
if (process(prev, tt, d))
fire(this, tt, d);
}
void NaryExpressionFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, const SimTime& v)
{
simtime_t tt = t;
double d = v.dbl();
if (process(prev, tt, d))
fire(this, tt, d);
}
bool NaryExpressionFilter::process(cResultFilter *prev, simtime_t& t, double& value)
{
currentTime = t;
for (int i = 0; i < signalCount; i++) {
if (prevFilters[i] == prev) {
currentValues[i] = value;
value = expr.doubleValue();
return true;
}
}
throw cRuntimeError("unknown signal");
}
Expression::Functor *NaryExpressionFilter::makeValueVariable(int index, cResultFilter *prevFilter)
{
Assert(0 <= index && index <= signalCount);
prevFilters[index] = prevFilter;
currentValues[index] = NaN;
return new ValueVariable(this, &(currentValues[index]));
}
//---
void PacketBytesFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, cObject *object)
{
if (dynamic_cast<cPacket *>(object))
{
cPacket *pk = (cPacket *)object;
fire(this, t, (double)pk->getByteLength());
}
}
//---
void PacketBitsFilter::receiveSignal(cResultFilter *prev, simtime_t_cref t, cObject *object)
{
if (dynamic_cast<cPacket *>(object))
{
cPacket *pk = (cPacket *)object;
fire(this, t, (double)pk->getBitLength());
}
}
//---
bool SumPerDurationFilter::process(simtime_t& t, double& value)
{
sum += value;
value = sum / (t - simulation.getWarmupPeriod());
return true;
}
NAMESPACE_END
| [
"fjahan@fjahan-OptiPlex-9010.(none)"
] | fjahan@fjahan-OptiPlex-9010.(none) |
4489880ec6dfeac6010caae128bfd1a31dd31252 | cb1253a944d694f3439d3bd5cb977df7eb0d183d | /AtCoder/RegularContest/009/B.cpp | 7f5e28bd1312ee1b7f756a145e2a6cc6edd5738e | [] | no_license | RIckyBan/competitive-programming | 91701550a76b54d2ab76d6e23e4c0cc64b975709 | f1592de21d06ff54b81cec5c8477300fae443700 | refs/heads/master | 2022-05-03T06:38:37.141758 | 2022-04-12T14:52:25 | 2022-04-12T14:52:25 | 243,915,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,036 | cpp | #include <iostream>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
#define INF 1e9
#define MAXN 100005
#define MAXM 100005
#define ll long long
#define vi vector<int>
#define vll vector<long long>
#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define pii pair<int, int>
ll ans;
int N;
vector<string> a;
vector<char> b;
map <char, int> mp;
vector<pair<int, string> > vec;
int conv_digit(string S) {
int K = S.size(), res = 0;
rep(i, K) {
res += mp[S[i]] * pow(10, K - 1 - i);
}
return res;
}
void solve(){
rep(i, 10) {
mp[b[i]] = i;
}
rep(i, N) {
pair<int, string> tmp = make_pair(conv_digit(a[i]), a[i]);
vec.push_back(
tmp
);
}
sort(vec.begin(), vec.end());
for(auto v : vec) {
cout << v.second << endl;
}
}
int main(){
b.resize(10);
rep(i, 10) cin >> b[i];
cin >> N;
a.resize(N);
rep(i, N) cin >> a[i];
solve();
}
| [
"rickyban1231@gmail.com"
] | rickyban1231@gmail.com |
77c49c066f4729a23ed3894bf69bc551680ffa91 | fb32369cf6352045e4dae90475e69f63e25e0d4a | /src/main.cpp | d68b1854f79852e3fdb347111870c4e3c47efb78 | [] | no_license | Norman44/Tls-Tcp-socket-wrapper-client | 92c5c2f116efbc66719b51c7e65196b79448103d | 1a388bc4c1b20314add54ea7709cffd335e51be9 | refs/heads/master | 2021-01-04T00:40:05.344936 | 2020-02-13T16:53:22 | 2020-02-13T16:53:22 | 240,306,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 694 | cpp | #include <iostream>
#include <string>
#include "TlsClient.h"
using namespace stream;
int main() {
char buff[1024];
std::string str = "Hello back there!";
std::cout << "TLS client begin ..." << std::endl;
TlsClient tls("10.2.1.58", 8080);
if (tls.tlsConnect() == -1) {
std::cerr << "Error TLS connect" << std::endl;
}
if (tls.tlsSendAll(str) == -1) {
std::cerr << "Error TLS send" << std::endl;
}
if (tls.tlsReceive(buff, sizeof buff) == -1) {
std::cerr << "Error TLS receive" << std::endl;
}
tls.shutdownSsl();
std::cout << buff << std::endl;
std::cout << "TLS client finish." << std::endl;
return 0;
}
| [
"ancimer.andrej@gmail.com"
] | ancimer.andrej@gmail.com |
e8775dbfffb29b12bcf10f097b7a5370ec14ff1d | 9f15d0afecbc8784a1b22a9bd39047eafa33a755 | /EstructuraGeneralizada/CVTKViewer.h | 36043ecf5d91d2985141c4297059cafb37ced91c | [] | no_license | alexandercch/estructurageneralizada | a16215703fec07754e17ac749a6fd41d6af38b04 | 2edf154c0095495839c5e660f55107611b456957 | refs/heads/master | 2021-05-16T09:27:04.793883 | 2017-10-20T00:22:50 | 2017-10-20T00:22:50 | 104,427,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 565 | h | #pragma once
#include <string>
#ifdef READUGRID_EXPORTS
#define READUGRID_API __declspec(dllexport)
#else
#define READUGRID_API __declspec(dllimport)
#endif
using namespace std;
class READUGRID_API CVTKViewer
{
public:
void display_vtk_file(string filename);
void set_graph_from_vtk_file(string filename, int ***graph, int **color, double **area, int *number_of_neighbors, int *size);
void set_vtk_file_from_graph(string filename_sorce, string filename_output, int **color, int number_of_neighbors, int size);
void check_colors(int **color, int size);
};
| [
"alexander.cc.h@gmail.com"
] | alexander.cc.h@gmail.com |
d2dda063ae110e7fa7a8621abd862641ecfac3a9 | ded9bf94ab97845541ad04d447886be163af6741 | /src/rpcmisc.cpp | 7c379f8b2f26535f41fd32ce7cbe5d7e8fc7b20c | [
"MIT"
] | permissive | ultra-pool/dravite | 3671e41c468b7ba998d9639fdf58e4b060bd745e | d7212fa660cc4083c2293e48911d8648b9d6ecea | refs/heads/master | 2020-03-31T11:00:58.836599 | 2018-10-09T23:28:41 | 2018-10-09T23:28:41 | 152,159,482 | 1 | 3 | MIT | 2020-02-08T20:28:44 | 2018-10-08T23:27:36 | C++ | UTF-8 | C++ | false | false | 7,607 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "timedata.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj, diff;
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint())));
obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake())));
}
#endif
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (int64_t)GetTimeOffset()));
obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply)));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.ToStringIPPort() : string())));
obj.push_back(Pair("ip", GetLocalAddress(NULL).ToStringIP()));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("testnet", TestNet()));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", (int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (int64_t)nWalletUnlockTime));
#endif
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
#endif
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <draviteaddress>\n"
"Return information about <draviteaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
#ifdef ENABLE_WALLET
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
#endif
}
return ret;
}
Value validatepubkey(const Array& params, bool fHelp)
{
if (fHelp || !params.size() || params.size() > 2)
throw runtime_error(
"validatepubkey <dravitepubkey>\n"
"Return information about <dravitepubkey>.");
std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str());
CPubKey pubKey(vchPubKey);
bool isValid = pubKey.IsValid();
bool isCompressed = pubKey.IsCompressed();
CKeyID keyID = pubKey.GetID();
CBitcoinAddress address;
address.Set(keyID);
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
ret.push_back(Pair("iscompressed", isCompressed));
#ifdef ENABLE_WALLET
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
#endif
}
return ret;
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <draviteaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
| [
"dravitecoin@gmail.com"
] | dravitecoin@gmail.com |
4342020b455b227a84a575b868a97ac5c7e2244f | 31f5cddb9885fc03b5c05fba5f9727b2f775cf47 | /thirdparty/google/tensorflow/lite/delegates/gpu/cl/buffer.cc | 8947cd430e80e59a92461e87f39a88c66f77c21a | [
"MIT"
] | permissive | timi-liuliang/echo | 2935a34b80b598eeb2c2039d686a15d42907d6f7 | d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24 | refs/heads/master | 2023-08-17T05:35:08.104918 | 2023-08-11T18:10:35 | 2023-08-11T18:10:35 | 124,620,874 | 822 | 102 | MIT | 2021-06-11T14:29:03 | 2018-03-10T04:07:35 | C++ | UTF-8 | C++ | false | false | 4,836 | cc | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/lite/delegates/gpu/cl/buffer.h"
#include <string>
#include "absl/status/status.h"
#include "tensorflow/lite/delegates/gpu/common/data_type.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
absl::Status CreateBuffer(size_t size_in_bytes, bool gpu_read_only,
const void* data, CLContext* context,
Buffer* result) {
cl_mem buffer;
RETURN_IF_ERROR(CreateCLBuffer(context->context(), size_in_bytes,
gpu_read_only, const_cast<void*>(data),
&buffer));
*result = Buffer(buffer, size_in_bytes);
return absl::OkStatus();
}
absl::Status CreateSubBuffer(const Buffer& parent, size_t origin_in_bytes,
size_t size_in_bytes, bool gpu_read_only,
CLContext* context, Buffer* result) {
cl_mem buffer;
if (parent.IsSubBuffer()) {
return absl::InvalidArgumentError(
"Cannot create a sub-buffer from a sub-buffer!");
}
RETURN_IF_ERROR(CreateCLSubBuffer(context->context(), parent.GetMemoryPtr(),
origin_in_bytes, size_in_bytes,
gpu_read_only, &buffer));
*result = Buffer(buffer, size_in_bytes, /*is_sub_buffer=*/true);
return absl::OkStatus();
}
} // namespace
Buffer::Buffer(cl_mem buffer, size_t size_in_bytes, bool is_sub_buffer)
: buffer_(buffer), size_(size_in_bytes), is_sub_buffer_(is_sub_buffer) {}
Buffer::Buffer(Buffer&& buffer)
: buffer_(buffer.buffer_),
size_(buffer.size_),
is_sub_buffer_(buffer.is_sub_buffer_) {
buffer.buffer_ = nullptr;
buffer.size_ = 0;
buffer.is_sub_buffer_ = false;
}
Buffer& Buffer::operator=(Buffer&& buffer) {
if (this != &buffer) {
Release();
std::swap(size_, buffer.size_);
std::swap(buffer_, buffer.buffer_);
std::swap(is_sub_buffer_, buffer.is_sub_buffer_);
}
return *this;
}
void Buffer::Release() {
if (buffer_) {
clReleaseMemObject(buffer_);
buffer_ = nullptr;
size_ = 0;
is_sub_buffer_ = false;
}
}
absl::Status Buffer::GetGPUResources(const GPUObjectDescriptor* obj_ptr,
GPUResourcesWithValue* resources) const {
const auto* buffer_desc = dynamic_cast<const BufferDescriptor*>(obj_ptr);
if (!buffer_desc) {
return absl::InvalidArgumentError("Expected BufferDescriptor on input.");
}
resources->buffers.push_back({"buffer", buffer_});
return absl::OkStatus();
}
absl::Status Buffer::CreateFromBufferDescriptor(const BufferDescriptor& desc,
CLContext* context) {
bool read_only = desc.memory_type == MemoryType::CONSTANT;
uint8_t* data_ptr = desc.data.empty()
? nullptr
: const_cast<unsigned char*>(desc.data.data());
size_ = desc.size;
return CreateCLBuffer(context->context(), desc.size, read_only, data_ptr,
&buffer_);
}
absl::Status CreateReadOnlyBuffer(size_t size_in_bytes, CLContext* context,
Buffer* result) {
return CreateBuffer(size_in_bytes, true, nullptr, context, result);
}
absl::Status CreateReadOnlyBuffer(size_t size_in_bytes, const void* data,
CLContext* context, Buffer* result) {
return CreateBuffer(size_in_bytes, true, data, context, result);
}
absl::Status CreateReadWriteBuffer(size_t size_in_bytes, CLContext* context,
Buffer* result) {
return CreateBuffer(size_in_bytes, false, nullptr, context, result);
}
absl::Status CreateReadWriteSubBuffer(const Buffer& parent,
size_t origin_in_bytes,
size_t size_in_bytes, CLContext* context,
Buffer* result) {
return CreateSubBuffer(parent, origin_in_bytes, size_in_bytes,
/*gpu_read_only=*/false, context, result);
}
} // namespace cl
} // namespace gpu
} // namespace tflite
| [
"qq79402005@gmail.com"
] | qq79402005@gmail.com |
e5f302657a0c8c8b85cd34bde443f4c88da8aee4 | 72301668a11ac7bc19df96d958c49d65464f9793 | /simulator.h | ac86ff214f8818b714770db4237a0bd283e4f7d2 | [] | no_license | milad14000/direct-connect | d563396a06c86b304b90c9806b868b386621ca87 | 1677a0c53c98d6dbb99778a5da72c59baa328ad2 | refs/heads/master | 2021-01-10T06:39:13.712464 | 2015-10-09T22:57:46 | 2015-10-09T22:57:46 | 43,936,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,072 | h | #include "./topology.h"
#include "./generator.h"
#include "./te.h"
#include "./tdm.h"
#include "./dfs.h"
#include <vector>
#include <deque>
class Generator;
class Topology;
namespace NSimulator {
//Base of the simulator
//Input: topo & flowlist_torun
//Output: flowlist_fin
class Simulator {
public:
Simulator() {};
virtual ~Simulator();
//fixed arrival interval
//fixed flow size
//uniform src/dst
//this function is obsolete
void set_FFUgenerator(double avgInt, double flowSize, TDM *tdm, int seed);
//run this after set the topology and flowlist_torun;
virtual void run();
// Helper
// you don't have to setup gen, but it might be helpful to generate the flow
Generator *gen;
// Have to be set before run
Topology *topo;
// Generate after run
vector<Flow*> flowlist_fin;
// Have to be set before run
deque<Flow*> flowlist_torun;
//Traffic demand matrix
TDM *tdm;
//Traffic engineer
TE *te;
// Dynamic flow scheduler
DFS *dfs;
double currentTime;
private:
void initRun();
};
}
| [
"msharif@stanford.edu"
] | msharif@stanford.edu |
1aa69116d6e35b770d689961c21562e1e477c4b7 | 68a8ce50c25be63d0886eace9c9f0e6ad4da8920 | /OpenIRT/include/Image.h | 364cf60ed17966bbbad9fc6640a33cac204df406 | [
"BSD-2-Clause"
] | permissive | sgvrlab/OpenIRT | fb0992a2edeea938de8d051307c6a60b5e9caded | 1a1522ed82f6bb26f1d40dc93024487869045ab2 | refs/heads/master | 2022-07-20T19:19:50.674398 | 2015-06-04T10:07:25 | 2015-06-04T10:07:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,580 | h | #pragma once
#include "rgb.h"
/**
* Central class for image representation.
*
* Stores pixels as individual instances of color classes in an
* twodimensional array. Offers gamma correction and other operations
* on pixels. Most importantly has functions to load and save images
* to/from files.
*
*/
namespace irt
{
class Image
{
public:
Image();
Image(int width, int height, int bpp=3);
virtual ~Image();
void setPixel(int x, int y, const RGBf& color);
void getPixel(int x, int y, RGBf& color) const;
RGBf &getPixel(int x, int y);
void setPixel(int x, int y, const RGB4f& color);
void getPixel(int x, int y, RGB4f& color) const;
RGB4f &getPixel4(int x, int y);
template <int nRaysPerDim> void setPacketPixels(int x, int y, const RGB4f *color);
/*
* Output Functions:
*/
virtual bool writeToFile(const char *filename) {return false;}
/*
* Input Functions
*/
virtual bool loadFromFile(const char *filename) {return false;}
virtual bool loadFromData(unsigned char *data, bool flip = false, bool exchangeRB = false);
/*
* Public Variables
*/
int width, height, bpp; // Dimensions
unsigned char *data; // Image Data
protected:
RGBf tempcolor;
RGB4f tempcolor4;
int rowOffset; // equals width*(Bpp)
};
template <int nRaysPerDim>
void Image::setPacketPixels(int x, int y, const RGB4f *colorPtr) {
unsigned char *basePtr = &data[(y*width + x)*bpp]; // first row
register const __m128 one4 = _mm_set1_ps(1.0f);
register const __m128 twofiftyfive = _mm_set1_ps(255.0f);
// set rectangular pixel region from ray packets
for (int j = 0; j < nRaysPerDim; j++, basePtr -= (2*rowOffset)) {
unsigned char *rowPtr1 = basePtr;
unsigned char *rowPtr2 = rowPtr1 - rowOffset;
for (int i = 0; i < nRaysPerDim; i++) {
__declspec(align(16)) char buffer[16];
#ifdef _M_X64
register __m128i color0 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(one4, colorPtr[0].data4), twofiftyfive)),
_mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(one4, colorPtr[1].data4), twofiftyfive)));
register __m128i color1 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(one4, colorPtr[2].data4), twofiftyfive)),
_mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(one4, colorPtr[3].data4), twofiftyfive)));
#else // 32-bit only:
register __m128i color0 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(one4, _mm_load_ps(colorPtr[0].data)), twofiftyfive)),
_mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(one4, _mm_load_ps(colorPtr[1].data)), twofiftyfive)));
register __m128i color1 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(one4, _mm_load_ps(colorPtr[2].data)), twofiftyfive)),
_mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(one4, _mm_load_ps(colorPtr[3].data)), twofiftyfive)));
#endif
color0 = _mm_packus_epi16(color0, color1);
_mm_store_si128((__m128i *)buffer, color0);
// set colors for one 2x2 ray:
*rowPtr1++ = buffer[0];
*rowPtr1++ = buffer[1];
*rowPtr1++ = buffer[2];
colorPtr++;
*rowPtr1++ = buffer[4];
*rowPtr1++ = buffer[5];
*rowPtr1++ = buffer[6];
colorPtr++;
*rowPtr2++ = buffer[8];
*rowPtr2++ = buffer[9];
*rowPtr2++ = buffer[10];
colorPtr++;
*rowPtr2++ = buffer[12];
*rowPtr2++ = buffer[13];
*rowPtr2++ = buffer[14];
colorPtr++;
}
}
}
inline void Image::setPixel(int x, int y, const RGBf& color) {
assert(x < width && x >= 0 && y < height && y >= 0);
assert(data != 0);
//int offset = ((height - y -1)*width + x)*bpp;
int offset = (y*width + x)*bpp;
data[offset] = (unsigned char)(color.r() * 255);
data[offset + 1] = (unsigned char)(color.g() * 255);
data[offset + 2] = (unsigned char)(color.b() * 255);
}
inline void Image::getPixel(int x, int y, RGBf& color) const {
//assert(x < width && x >= 0 && y < height && y >= 0);
assert(data != 0);
color.setR(data[(width*y + x)*bpp] / 255.0f);
color.setG(data[(width*y + x)*bpp + 1] / 255.0f);
color.setB(data[(width*y + x)*bpp + 2] / 255.0f);
}
inline RGBf &Image::getPixel(int x, int y) {
assert(x < width && x >= 0 && y < height && y >= 0);
assert(data != 0);
tempcolor.setR(data[(width*y + x)*bpp] / 255.0f);
tempcolor.setG(data[(width*y + x)*bpp + 1] / 255.0f);
tempcolor.setB(data[(width*y + x)*bpp + 2] / 255.0f);
return tempcolor;
}
inline void Image::setPixel(int x, int y, const RGB4f& color) {
assert(x < width && x >= 0 && y < height && y >= 0);
assert(data != 0);
//int offset = ((height - y -1)*width + x)*bpp;
int offset = (y*width + x)*bpp;
data[offset] = (unsigned char)(color.r() * 255);
data[offset + 1] = (unsigned char)(color.g() * 255);
data[offset + 2] = (unsigned char)(color.b() * 255);
data[offset + 3] = (unsigned char)(color.a() * 255);
}
inline void Image::getPixel(int x, int y, RGB4f& color) const {
//assert(x < width && x >= 0 && y < height && y >= 0);
assert(data != 0);
color.setR(data[(width*y + x)*bpp] / 255.0f);
color.setG(data[(width*y + x)*bpp + 1] / 255.0f);
color.setB(data[(width*y + x)*bpp + 2] / 255.0f);
color.setA(data[(width*y + x)*bpp + 3] / 255.0f);
}
inline RGB4f &Image::getPixel4(int x, int y) {
assert(x < width && x >= 0 && y < height && y >= 0);
assert(data != 0);
tempcolor4.setR(data[(width*y + x)*bpp] / 255.0f);
tempcolor4.setG(data[(width*y + x)*bpp + 1] / 255.0f);
tempcolor4.setB(data[(width*y + x)*bpp + 2] / 255.0f);
tempcolor4.setA(data[(width*y + x)*bpp + 3] / 255.0f);
return tempcolor4;
}
}; | [
"nedsociety@gmail.com"
] | nedsociety@gmail.com |
d700423db1018f5d9da7cbba8bbe2a37d3f1662e | 12ac357dcf3f7dcf16fd00c5fefc7099a7a19eb6 | /Additionals/GCD/gcd.cpp | e6b17edf00f746146c3f22906665c6592b9c8ab4 | [] | no_license | AdnanHussainTurki/CSM1171 | 3f387045a8997344bc5fe4aec1e48f66b765a92d | 11d075e52e0a18632284d9a5fe80f9cb8f474a5c | refs/heads/master | 2020-08-26T20:29:44.001140 | 2019-11-29T20:22:26 | 2019-11-29T20:22:26 | 217,132,772 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | cpp | /*
* @Author: Adnan
* @Date: 2019-09-16 07:55:45
* @Last Modified by: Adnan
* @Last Modified time: 2019-10-23 22:52:57
*/
#include <iostream>
using namespace std;
int gcd(int a,int b){
if((a%b)==0) {
return b;
}
// cout << a << " = " << b << "*q" << "+" << a%b << endl;
return (gcd(b,a%b));
}
// Method 1
int main() {
cout << "PROGRAM: FINDING GCD";
cout << "\n";
cout << "=========================================================";
int inputOne;
cout << "\nEnter the first integer : ";
cin >> inputOne ;
int inputTwo;
cout << "\nEnter the second integer : ";
cin >> inputTwo ;
// Printing GCD
puts("GCD of given two integers is: ");
cout << gcd(inputOne, inputTwo);
return 0;
} | [
"adnanhussainturki@gmail.com"
] | adnanhussainturki@gmail.com |
62304e19a728e264a875835bbf75b7cb46339c75 | 9d6eeee0f3b3804975e7c693d9f64253ccc76935 | /examples/Blob/Blob.ino | 42402927a58a0e9433dba4f845b54bf399126906 | [
"MIT"
] | permissive | ntgussoni/Firebase-ESP8266 | ddd25b70617394dd0467c8e9d3bd35958236b7f6 | 069b051029f15772d07708751417bb42d3729109 | refs/heads/master | 2020-05-16T01:12:24.470342 | 2019-04-19T17:17:41 | 2019-04-19T17:17:41 | 182,597,394 | 0 | 0 | MIT | 2019-04-23T15:54:51 | 2019-04-22T00:38:06 | C++ | UTF-8 | C++ | false | false | 5,752 | ino | /*
* Created by K. Suwatchai (Mobizt)
*
* Email: k_suwatchai@hotmail.com
*
* Github: https://github.com/mobizt
*
* Copyright (c) 2019 mobizt
*
*/
//This example shows how to store and read binary data from memory to database.
//FirebaseESP8266.h must be included before ESP8266WiFi.h
#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>
#include "SD.h"
#define FIREBASE_HOST "YOUR_FIREBASE_PROJECT.firebaseio.com" //Do not include https:// in FIREBASE_HOST
#define FIREBASE_AUTH "YOUR_FIREBASE_DATABASE_SECRET"
#define WIFI_SSID "YOUR_WIFI_AP"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"
//Define Firebase Data object
FirebaseData firebaseData;
String path = "/ESP8266_Test";
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.println();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
Serial.println("------------------------------------");
Serial.println("Set BLOB data test...");
//Create demo data
uint8_t data[256];
for (int i = 0; i < 256; i++)
data[i] = i;
//Set binary data to database
if (Firebase.setBlob(firebaseData, path + "/Binary/Blob/data", data, sizeof(data)))
{
Serial.println("PASSED");
Serial.println("------------------------------------");
Serial.println();
}
else
{
Serial.println("FAILED");
Serial.println("REASON: " + firebaseData.errorReason());
Serial.println("------------------------------------");
Serial.println();
}
Serial.println("------------------------------------");
Serial.println("Get BLOB data test...");
//Get binary data from database
if (Firebase.getBlob(firebaseData, path + "/Binary/Blob/data"))
{
Serial.println("PASSED");
Serial.println("PATH: " + firebaseData.dataPath());
Serial.println("TYPE: " + firebaseData.dataType());
Serial.print("VALUE: ");
if (firebaseData.dataType() == "int")
Serial.println(firebaseData.intData());
else if (firebaseData.dataType() == "float")
Serial.println(firebaseData.floatData());
else if (firebaseData.dataType() == "boolean")
Serial.println(firebaseData.boolData() == 1 ? "true" : "false");
else if (firebaseData.dataType() == "string")
Serial.println(firebaseData.stringData());
else if (firebaseData.dataType() == "json")
Serial.println(firebaseData.jsonData());
else if (firebaseData.dataType() == "blob")
{
std::vector<uint8_t> blob = firebaseData.blobData();
Serial.println();
for (int i = 0; i < blob.size(); i++)
{
if (i > 0 && i % 16 == 0)
Serial.println();
if (i < 16)
Serial.print("0");
Serial.print(blob[i], HEX);
Serial.print(" ");
}
Serial.println();
}
Serial.println("------------------------------------");
Serial.println();
}
else
{
Serial.println("FAILED");
Serial.println("REASON: " + firebaseData.errorReason());
Serial.println("--------------------------------");
Serial.println();
}
Serial.println("------------------------------------");
Serial.println("Append BLOB data test...");
//Create demo data
for (int i = 0; i < 256; i++)
data[i] = 255 - i;
//Append binary data to database
if (Firebase.pushBlob(firebaseData, path + "/Binary/Blob/Logs", data, sizeof(data)))
{
Serial.println("PASSED");
Serial.println("PATH: " + firebaseData.dataPath());
Serial.println("PUSH NAME: " + firebaseData.pushName());
Serial.println("------------------------------------");
Serial.println();
Serial.println("------------------------------------");
Serial.println("Get appended BLOB data test...");
//Get appended binary data from database
if (Firebase.getBlob(firebaseData, path + "/Binary/Blob/Logs/" + firebaseData.pushName()))
{
Serial.println("PASSED");
Serial.println("PATH: " + firebaseData.dataPath());
Serial.println("TYPE: " + firebaseData.dataType());
Serial.print("VALUE: ");
if (firebaseData.dataType() == "int")
Serial.println(firebaseData.intData());
else if (firebaseData.dataType() == "float")
Serial.println(firebaseData.floatData());
else if (firebaseData.dataType() == "boolean")
Serial.println(firebaseData.boolData() == 1 ? "true" : "false");
else if (firebaseData.dataType() == "string")
Serial.println(firebaseData.stringData());
else if (firebaseData.dataType() == "json")
Serial.println(firebaseData.jsonData());
else if (firebaseData.dataType() == "blob")
{
std::vector<uint8_t> blob = firebaseData.blobData();
Serial.println();
for (int i = 0; i < blob.size(); i++)
{
if (i > 0 && i % 16 == 0)
Serial.println();
if (blob[i] < 16)
Serial.print("0");
Serial.print(blob[i], HEX);
Serial.print(" ");
}
Serial.println();
}
Serial.println("------------------------------------");
Serial.println();
}
else
{
Serial.println("FAILED");
Serial.println("REASON: " + firebaseData.errorReason());
Serial.println("--------------------------------");
Serial.println();
}
}
else
{
Serial.println("FAILED");
Serial.println("REASON: " + firebaseData.errorReason());
Serial.println("------------------------------------");
Serial.println();
}
}
void loop()
{
}
| [
"k_suwatchai@hotmail.com"
] | k_suwatchai@hotmail.com |
03eec7eebb4eeabbc741d5642c900f3e5ac61a88 | 0ad7c258d10747330e0fa699fe6e2ba5e901342f | /1.2/splitter.hpp | 4e70a01810e011b4a569d7361c04efb0163499fc | [] | no_license | samueletorresani/1.0 | de59c7d7d2f4088b97993dde52405810fd0b5639 | dca7ef213a4e0ced6ac7780bf7c716494a225369 | refs/heads/master | 2023-01-22T04:21:56.414861 | 2020-11-30T12:56:21 | 2020-11-30T12:56:21 | 306,843,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 133 | hpp | #ifndef Splitter_H
#define Splitter_H
int splitter(int toSplit, int index){
return (toSplit / powInt(10,index)%10);
}
#endif | [
"samuele.torresani01@gmail.com"
] | samuele.torresani01@gmail.com |
665813be0357e10fce91c1a7c080b1ac3d7ba1c0 | 92458725362d0438107026014284fd8f85bc6b8f | /cpp/string_trim_methods.hpp | f80e79e67c472c71344e260c814a3a0a62729680 | [] | no_license | ravikr126/Data-Structures-And-Algorithms-Hacktoberfest18 | 2628792a707243a2ab295a9f8bc8075217fc2836 | bbc22ab183ea0f2f73f40e1a0ef689ccb228a6d7 | refs/heads/master | 2022-12-22T19:53:41.434687 | 2020-09-30T19:33:52 | 2020-09-30T19:33:52 | 300,038,519 | 2 | 0 | null | 2020-09-30T19:32:17 | 2020-09-30T19:32:16 | null | UTF-8 | C++ | false | false | 1,995 | hpp | #include <vector>
#include <numeric>
#include <string_view>
#include <algorithm>
// trim from start (in place)
inline void ltrim( std::string &s )
{
s.erase( s.begin(), std::find_if( s.begin(), s.end(), []( int ch ) {
return !std::isspace( ch );
} ));
}
// trim from end (in place)
inline void rtrim( std::string &s )
{
s.erase( std::find_if( s.rbegin(), s.rend(), []( int ch ) {
return !std::isspace( ch );
} ).base(), s.end());
}
// trim from start (in place)
inline void ltrim( std::string &s, const std::string &trimmed )
{
s.erase( s.begin(), std::find_if( s.begin(), s.end(), [trimmed]( int ch ) {
return trimmed.find( ch ) == std::string::npos;
} ));
}
// trim from end (in place)
inline void rtrim( std::string &s, const std::string &trimmed )
{
s.erase( std::find_if( s.rbegin(), s.rend(), [trimmed]( int ch ) {
return trimmed.find( ch ) == std::string::npos;
} ).base(), s.end());
}
// trim from both ends (in place)
inline void trim( std::string &s )
{
ltrim( s );
rtrim( s );
}
// trim from start (copying)
inline std::string ltrim_copy( std::string s )
{
ltrim( s );
return s;
}
// trim from end (copying)
inline std::string rtrim_copy( std::string s )
{
rtrim( s );
return s;
}
// trim from both ends (copying)
inline std::string trim_copy( std::string s )
{
trim( s );
return s;
}
// trim from both ends (in place)
inline void trim( std::string &s, const std::string &trimmed )
{
ltrim( s, trimmed );
rtrim( s, trimmed );
}
// trim from start (copying)
inline std::string ltrim_copy( std::string s, const std::string &trimmed )
{
ltrim( s, trimmed );
return s;
}
// trim from end (copying)
inline std::string rtrim_copy( std::string s, const std::string &trimmed )
{
rtrim( s, trimmed );
return s;
}
// trim from both ends (copying)
inline std::string trim_copy( std::string s, const std::string &trimmed )
{
trim( s, trimmed );
return s;
} | [
"asem_alla@msn.com"
] | asem_alla@msn.com |
23f9da0ef99439b4b116158b39aee71963676c80 | ae8a9348748e03cb9590c87740bb1e1df5ad0c50 | /code/convex_opt/src/include/vect_image.hpp | bcda98503637cc6510a78be265d294edfd49983a | [] | no_license | pranavshrikhande/Forgery-Detection-in-Images | 8874fbb40292b4b5f39e5e4d501306aad18c6347 | 0918cf4396822f912a023843a4fc75af6a117de4 | refs/heads/master | 2020-03-28T09:53:23.334576 | 2018-09-09T21:25:03 | 2018-09-09T21:25:03 | 148,067,168 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,350 | hpp | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2016 Image Processing Research Group of University Federico II of Naples ('GRIP-UNINA').
% All rights reserved.
% this software should be used, reproduced and modified only for informational and nonprofit purposes.
%
% By downloading and/or using any of these files, you implicitly agree to all the
% terms of the license, as specified in the document LICENSE.txt
% (included in this package) and online at
% http://www.grip.unina.it/download/LICENSE_OPEN.txt
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
#ifndef VECT_IMAGE_HPP
#define VECT_IMAGE_HPP
#include "image.hpp"
template<typename T>
struct VectImage : public Image<T>
{
typedef typename std::vector<T>::iterator iterator;
typedef typename std::vector<T>::const_iterator const_iterator;
std::vector<T> vect;
/* constructors */
VectImage() {
create(0,0,0,0);
}
VectImage(int N_rows, int N_cols, int N_bands = 1, int N_planes = 1) {
create(N_rows, N_cols, N_bands, N_planes);
}
VectImage(const int* sz) {
create(sz);
}
VectImage(const VectImage &that) {
create( that.size() );
std::copy( that.begin(), that.end(), this->begin() );
}
void create(const int* sz) {
create(sz[0], sz[1], sz[2], sz[3]);
}
void create(int N_rows, int N_cols, int N_bands = 1, int N_planes = 1)
{
vect.resize(N_rows*N_cols*N_bands*N_planes, T());
// data pointer
Image<T>::data = vect.data();
// matrix size
Image<T>::size_[0] = N_rows;
Image<T>::size_[1] = N_cols;
Image<T>::size_[2] = N_bands;
Image<T>::size_[3] = N_planes;
// roi handling
Image<T>::step[0] = Image<T>::size(0);
Image<T>::step[1] = Image<T>::size(0)*Image<T>::size(1);
Image<T>::step[2] = Image<T>::size(0)*Image<T>::size(1)*Image<T>::size(2);
}
/* iterators*/
typename std::vector<T>::const_iterator begin() const {
return vect.begin();
}
typename std::vector<T>::iterator begin() {
return vect.begin();
}
typename std::vector<T>::const_iterator end() const {
return vect.end();
}
typename std::vector<T>::iterator end() {
return vect.end();
}
};
#endif | [
"pranav.shrikhande@gmail.com"
] | pranav.shrikhande@gmail.com |
739e155431b1097ae6121b467366ed8d0f0916f6 | ba808c11d830027e3a4aae714b9624a1d1ae853a | /tests/pe/utils.hpp | 6c45c1a6e7c2cfe047034179b65e567f8f70bb2c | [
"Apache-2.0"
] | permissive | jbremer/LIEF | 609b896a9d63306673883797c16d5f2f1c5292dd | e0de8dd596d836390bdceb1845eb0c38c023b323 | refs/heads/master | 2020-03-22T10:25:57.479864 | 2018-07-05T22:03:42 | 2018-07-05T22:03:42 | 139,902,140 | 0 | 0 | Apache-2.0 | 2018-07-05T21:24:19 | 2018-07-05T21:24:18 | null | UTF-8 | C++ | false | false | 979 | hpp | /* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIEF_PE_TEST_UTILS_H_
#define LIEF_PE_TEST_UTILS_H_
#include <vector>
#include <string>
namespace LIEF {
namespace PE {
namespace Test {
std::vector<std::string> get_test_cases(void);
std::vector<std::string> get_binary_test_cases(void);
std::vector<std::string> get_library_test_cases(void);
std::vector<std::string> get_pe_files(void);
}
}
}
#endif
| [
"romainthomasc@gmail.com"
] | romainthomasc@gmail.com |
982b935ee0dfc0c639d97bce8a7999be0a1a7e41 | a28ec5037765636d5d1cdb4459fc89d84ca8604a | /oxYexporter/xmlDocumentAnimation.cpp | b05bf90a6cfb3f738e90871777e005671ca6d5b9 | [] | no_license | oxydated/Exporter | 334745cbd7ca80ca0614a31b45dd685912be4340 | 5beff33d6a6d105da1ff21319229842b3d58d0ec | refs/heads/master | 2022-01-10T19:54:11.295203 | 2019-05-07T05:47:13 | 2019-05-07T05:47:13 | 165,144,652 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,902 | cpp | #include "xmlDocumentAnimation.h"
namespace oxyde {
namespace exporter {
namespace XML {
oxyDualQuatTrackElement::oxyDualQuatTrackElement(oxyKeyframeElementPtr theParent, int inputNumKeys)
: oxyDocumentElement(theParent, L"dualQuatTrack"),
numKeys(inputNumKeys)
{
buildListOfAttributes();
setElementAttributes();
}
void oxyDualQuatTrackElement::buildListOfAttributes()
{
attributeList.push_back(elementAttribute(L"numKeys", _variant_t(numKeys)));
}
oxyDualQuatKeyElement::oxyDualQuatKeyElement(oxyDualQuatTrackElementPtr theParent, int inputstartTime, int inputendTime)
: oxyDocumentElement(theParent, L"dualQuatKey"),
startTime(inputstartTime),
endTime(inputendTime)
{
buildListOfAttributes();
setElementAttributes();
}
std::shared_ptr<oxyDualQuatKeyElement> oxyDualQuatKeyElement::createDualQuatKey(oxyDualQuatTrackElementPtr theParent,
int inputstartTime, int inputendTime,
float inputqs, float inputqx, float inputqy, float inputqz, float inputdqs, float inputdqx, float inputdqy, float inputdqz,
float inputangle, float inputux, float inputuy, float inputuz, float inputslide, float inputmx, float inputmy, float inputmz
) {
oxyDualQuatKeyElementPtr theKey = std::shared_ptr<oxyDualQuatKeyElement>(new oxyDualQuatKeyElement(theParent, inputstartTime, inputendTime));
std::shared_ptr<startingDualQuatElement> theSDQelemnt = std::shared_ptr<startingDualQuatElement>(new startingDualQuatElement(
theKey, inputqs, inputqx, inputqy, inputqz, inputdqs, inputdqx, inputdqy, inputdqz));
std::shared_ptr<interpolationDataElement> theInterpData = std::shared_ptr<interpolationDataElement>(new interpolationDataElement(
theKey, inputangle, inputux, inputuy, inputuz, inputslide, inputmx, inputmy, inputmz));
return theKey;
}
void oxyDualQuatKeyElement::buildListOfAttributes()
{
attributeList.push_back(elementAttribute(L"startTime", _variant_t(startTime)));
attributeList.push_back(elementAttribute(L"endTime", _variant_t(endTime)));
}
startingDualQuatElement::startingDualQuatElement(oxyDualQuatKeyElementPtr theParent, float inputqs, float inputqx, float inputqy, float inputqz, float inputdqs, float inputdqx, float inputdqy, float inputdqz) :
oxyDocumentElement(theParent, L"startingDualQuat"),
qs(inputqs), qx(inputqx), qy(inputqy), qz(inputqz), dqs(inputdqs), dqx(inputdqx), dqy(inputdqy), dqz(inputdqz)
{
buildListOfAttributes();
setElementAttributes();
}
void startingDualQuatElement::buildListOfAttributes()
{
attributeList.push_back(elementAttribute(L"qs", variantFromFloat(qs)));
attributeList.push_back(elementAttribute(L"qx", variantFromFloat(qx)));
attributeList.push_back(elementAttribute(L"qy", variantFromFloat(qy)));
attributeList.push_back(elementAttribute(L"qz", variantFromFloat(qz)));
attributeList.push_back(elementAttribute(L"dqs", variantFromFloat(dqs)));
attributeList.push_back(elementAttribute(L"dqx", variantFromFloat(dqx)));
attributeList.push_back(elementAttribute(L"dqy", variantFromFloat(dqy)));
attributeList.push_back(elementAttribute(L"dqz", variantFromFloat(dqz)));
}
interpolationDataElement::interpolationDataElement(oxyDualQuatKeyElementPtr theParent, float inputangle, float inputux, float inputuy, float inputuz, float inputslide, float inputmx, float inputmy, float inputmz) :
oxyDocumentElement(theParent, L"interpolationParam"),
angle(inputangle), ux(inputux), uy(inputuy), uz(inputuz), slide(inputslide), mx(inputmx), my(inputmy), mz(inputmz)
{
buildListOfAttributes();
setElementAttributes();
}
void interpolationDataElement::buildListOfAttributes()
{
attributeList.push_back(elementAttribute(L"angle", variantFromFloat(angle)));
attributeList.push_back(elementAttribute(L"ux", variantFromFloat(ux)));
attributeList.push_back(elementAttribute(L"uy", variantFromFloat(uy)));
attributeList.push_back(elementAttribute(L"uz", variantFromFloat(uz)));
attributeList.push_back(elementAttribute(L"slide", variantFromFloat(slide)));
attributeList.push_back(elementAttribute(L"mx", variantFromFloat(mx)));
attributeList.push_back(elementAttribute(L"my", variantFromFloat(my)));
attributeList.push_back(elementAttribute(L"mz", variantFromFloat(mz)));
}
baseSpinnerDataElement::baseSpinnerDataElement(oxyAnimationElementPtr theParent, std::wstring insourceName, float inputqs, float inputqx, float inputqy, float inputqz, float inputdqs, float inputdqx, float inputdqy, float inputdqz) :
oxyDocumentElement(theParent, L"spinnerBase"), sourceName(insourceName),
qs(inputqs), qx(inputqx), qy(inputqy), qz(inputqz), dqs(inputdqs), dqx(inputdqx), dqy(inputdqy), dqz(inputdqz)
{
buildListOfAttributes();
setElementAttributes();
}
void baseSpinnerDataElement::buildListOfAttributes()
{
attributeList.push_back(elementAttribute(L"source", _variant_t(sourceName.data())));
attributeList.push_back(elementAttribute(L"qs", variantFromFloat(qs)));
attributeList.push_back(elementAttribute(L"qx", variantFromFloat(qx)));
attributeList.push_back(elementAttribute(L"qy", variantFromFloat(qy)));
attributeList.push_back(elementAttribute(L"qz", variantFromFloat(qz)));
attributeList.push_back(elementAttribute(L"dqs", variantFromFloat(dqs)));
attributeList.push_back(elementAttribute(L"dqx", variantFromFloat(dqx)));
attributeList.push_back(elementAttribute(L"dqy", variantFromFloat(dqy)));
attributeList.push_back(elementAttribute(L"dqz", variantFromFloat(dqz)));
}
tipSpinnerDataElement::tipSpinnerDataElement(oxyAnimationElementPtr theParent, std::wstring insourceName, float inputqs, float inputqx, float inputqy, float inputqz, float inputdqs, float inputdqx, float inputdqy, float inputdqz) :
oxyDocumentElement(theParent, L"spinnerTip"), sourceName(insourceName),
qs(inputqs), qx(inputqx), qy(inputqy), qz(inputqz), dqs(inputdqs), dqx(inputdqx), dqy(inputdqy), dqz(inputdqz)
{
buildListOfAttributes();
setElementAttributes();
}
void tipSpinnerDataElement::buildListOfAttributes()
{
attributeList.push_back(elementAttribute(L"source", _variant_t(sourceName.data())));
attributeList.push_back(elementAttribute(L"qs", variantFromFloat(qs)));
attributeList.push_back(elementAttribute(L"qx", variantFromFloat(qx)));
attributeList.push_back(elementAttribute(L"qy", variantFromFloat(qy)));
attributeList.push_back(elementAttribute(L"qz", variantFromFloat(qz)));
attributeList.push_back(elementAttribute(L"dqs", variantFromFloat(dqs)));
attributeList.push_back(elementAttribute(L"dqx", variantFromFloat(dqx)));
attributeList.push_back(elementAttribute(L"dqy", variantFromFloat(dqy)));
attributeList.push_back(elementAttribute(L"dqz", variantFromFloat(dqz)));
}
}
}
}
| [
"oxydation@gmail.com"
] | oxydation@gmail.com |
73fcf01fed9f087ae9a42c5466ef57340a44374e | ad822f849322c5dcad78d609f28259031a96c98e | /SDK/T2_Planet_Radiated_functions.cpp | 21437c3cdff35fd8ba83fef44e76b2ca8e728cd4 | [] | no_license | zH4x-SDK/zAstroneer-SDK | 1cdc9c51b60be619202c0258a0dd66bf96898ac4 | 35047f506eaef251a161792fcd2ddd24fe446050 | refs/heads/main | 2023-07-24T08:20:55.346698 | 2021-08-27T13:33:33 | 2021-08-27T13:33:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | cpp |
#include "../SDK.h"
// Name: Astroneer-SDK, Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function T2_Planet_Radiated.T2_Planet_Radiated_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void AT2_Planet_Radiated_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function T2_Planet_Radiated.T2_Planet_Radiated_C.UserConstructionScript");
AT2_Planet_Radiated_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function T2_Planet_Radiated.T2_Planet_Radiated_C.ReceiveBeginPlay
// (Event, Protected, BlueprintEvent)
void AT2_Planet_Radiated_C::ReceiveBeginPlay()
{
static auto fn = UObject::FindObject<UFunction>("Function T2_Planet_Radiated.T2_Planet_Radiated_C.ReceiveBeginPlay");
AT2_Planet_Radiated_C_ReceiveBeginPlay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function T2_Planet_Radiated.T2_Planet_Radiated_C.ExecuteUbergraph_T2_Planet_Radiated
// (HasDefaults)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void AT2_Planet_Radiated_C::ExecuteUbergraph_T2_Planet_Radiated(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function T2_Planet_Radiated.T2_Planet_Radiated_C.ExecuteUbergraph_T2_Planet_Radiated");
AT2_Planet_Radiated_C_ExecuteUbergraph_T2_Planet_Radiated_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
7078685551eeb4714f71b536c436ae8d209e217e | 10be96b8c75b62ba153319f919bc4014c9605d3c | /ARHN1502-ARHN09.cpp | 893ccfb0a141f6b0bb628a063aa59646ce0fa047 | [] | no_license | rahulkushwaha12/Programming-Codes | 4a199f9c236cfd63f78175e8997787efc169c60e | e8474c4d715e2257e17979ad483be4ca0bad9527 | refs/heads/master | 2020-04-16T05:17:11.554482 | 2016-02-09T18:07:43 | 2016-02-09T18:07:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 878 | cpp | //author farzirahu
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
//using namespace std;
int main()
{
int n,q,i,j,l1=0,l2=0,sum=0,l=0,s=0,n1=0,n2=0;
//cin>>n>>q;
scanf("%d%d",&n,&q);
int arr[n];
for(i=0;i<n;i++)
{
//cin>>arr[i];
scanf("%d",&arr[i]);
}
for(i=0;i<q;i++)
{
char str[100];
//gets(str);
fgets (str, 100, stdin);
//scanf ("%[^\n]%*c", str);
l=strlen(str);
printf("%d\n",l);
for(j=4;j<l;j++)
{
if((int)str[j]==32)
{
s=j;
break;
}
}
l1=s-4;
l2=l-s;
if(l1==1)
{
n1=(int)str[4];
}
if(l1==2)
{
n1=(10*(int)str[4])+(int)str[5];
}
if(l1==3)
{
n1=100;
}
if(l2==1)
{
n2=(int)str[s+1];
}
if(l2==2)
{
n2=(10*(int)str[s+1])+(int)str[s+2];
}
if(l2==3)
{
n2=100;
}
for(j=n1-1;j<n2;j++)
{
sum=sum+arr[j];
}
printf("%d\n",sum);
}
return 0;
}
| [
"Rahul Kushwaha"
] | Rahul Kushwaha |
e71838679ad75e286ccb6d404f2f5852fc3791c4 | 1429634358550a3a60728d0ff4dbf552b2362c10 | /Above the Moon - source/IcyTower/Game.h | 07dfee5b49f584a88d96113c40de60f9b17ce860 | [
"CC-BY-3.0"
] | permissive | SpeeritX/above-the-moon | c0e4b5410eedc2e72a64a2b46d218f8976f0d1dd | f8bdd44e71f4b8ffecfcba01dfcd7d4b8f7deabc | refs/heads/master | 2023-01-20T04:35:51.628777 | 2020-11-24T09:37:53 | 2020-11-24T09:37:53 | 274,524,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,594 | h | #pragma once
#include "Player.h"
#include "Background.h"
#include "Walls.h"
#include "StatusBar.h"
#include "GameOverScreen.h"
#include "ComboText.h"
#include <SFML\Graphics.hpp>
#include <SFML\Audio.hpp>
#include <list>
#include <array>
#include <cstdlib>
#include <fstream>
#include <string>
class Game
{
public:
Game(sf::RenderWindow *win, sf::Vector2f windowSize, int highScore);
void reset();
void draw();
bool update();
int getHighscore();
~Game();
private:
const float SPEED_MODIFIER_AFTER_WALL = -0.7;
static const int PLATFORM_HEIGHT = 40;
static const int WALL_WIDTH = 60;
static const int SPACE_BETWEEN_PLATFORMS = 60;
static const int AMOUNT_OF_TEXTURES = 13;
static const int MAX_COMBO_TIME = 80;
const float MAX_WORLD_SPEED = 11;
const float SPEED_MODIFIER = 0.0015;
std::array<sf::Texture, AMOUNT_OF_TEXTURES> platformsTextures_;
sf::RenderWindow *window_;
sf::Vector2f windowSize_;
sf::Vector2f canvasSize_;
std::list<std::pair<sf::Sprite, int>> platforms_;
std::list<ComboText> comboTexts_;
Player *player_;
Background *background;
Walls *walls;
StatusBar *statusBar_;
GameOverScreen *gameOverScreen_;
int minMusicVolume_;
int highScore_;
int floor;
int platformNr;
bool isCombo;
float comboTime;
int comboPoints;
int points;
float worldSpeed_;
bool isGameOn_;
bool isGameOver_;
std::pair<sf::Sprite, int> playerPlatform_;
sf::Font font;
sf::Text textPoints;
sf::Music music;
void getTextures();
void movePlayer();
void moveWorld(float x);
void resetCombo();
bool updatePlatforms();
void updateComboTexts();
};
| [
"jedrek.185@gmail.com"
] | jedrek.185@gmail.com |
8d0c1defed27f106917e372468f234e9895d13ba | 16c25858ef1e5f29f653580d4aacda69a50c3244 | /hikr/build/iOS/Preview/include/Fuse.ScalingModes.h | 87d42d4e7817c0ea0a0627b4873295ac5c112390 | [] | no_license | PoliGomes/tutorialfuse | 69c32ff34ba9236bc3e84e99e00eb116d6f16422 | 0b7fadfe857fed568a5c2899d176acf45249d2b8 | refs/heads/master | 2021-08-16T02:50:08.993542 | 2017-11-18T22:04:56 | 2017-11-18T22:04:56 | 111,242,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | h | // This file was generated based on /usr/local/share/uno/Packages/Fuse.Nodes/1.2.1/$.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.h>
namespace g{namespace Fuse{struct ScalingModes;}}
namespace g{
namespace Fuse{
// public static class ScalingModes :3973
// {
uClassType* ScalingModes_typeof();
struct ScalingModes : uObject
{
static uSStrong<uObject*> Identity_;
static uSStrong<uObject*>& Identity() { return ScalingModes_typeof()->Init(), Identity_; }
};
// }
}} // ::g::Fuse
| [
"poliana.ph@gmail.com"
] | poliana.ph@gmail.com |
d95b0959f55520dfa0c155d6162418c10da0057e | 12e9652e5ab21e5b4a53f0e4ea9e98ed3986e3d0 | /src/translational/test/translational.test.cpp | 693f6d4a2c522536e91ce929de6b4d14cdd03772 | [] | no_license | ameliajo/leapr | 38df10324e99c81ad91e0d60f9d26591b0dbaf37 | 25f752ac315687f717e4da5a64d0b12c731dd003 | refs/heads/master | 2021-06-04T15:15:29.377139 | 2020-11-03T15:43:31 | 2020-11-03T15:43:31 | 310,405,477 | 1 | 0 | null | 2020-11-05T20:05:32 | 2020-11-05T20:05:31 | null | UTF-8 | C++ | false | false | 7,647 | cpp | #define CATCH_CONFIG_MAIN
#include <iostream>
#include <vector>
#include "translational/translational.h"
#include "catch.hpp"
#include "generalTools/testing.h"
#include <range/v3/all.hpp>
TEST_CASE( "trans" ){
std::vector<double> alpha {0.10, 0.20, 0.40, 0.50}, beta {0.15, 0.18, 0.22}, correct;
double transWgt = 0.05, delta = 9e-2, c, temp = 296,
sc = 1.0, scaling = 1.0, lambda_s = 0.23, tbeta = 0.95,
effectiveTemp = 570;
transWgt = 0.5;
tbeta = 0.5;
for ( auto& a : alpha ){ a*= scaling; }
for ( auto& b : beta ){ b*= sc; }
std::vector<double> sab = ranges::view::iota(1,int(alpha.size()*beta.size()+1))
| ranges::view::transform([](auto x){return 1e-3*x;});
GIVEN( "no diffusion" ){
c = 0.0;
WHEN( "translational weight is small" ){
transWgt = 0.05;
tbeta = 0.95;
translational( alpha, beta, transWgt, delta, c, lambda_s, tbeta,
effectiveTemp, temp, sab );
correct = { 1.359940, 8.42100E-1, 3.86253E-1, 1.648607, 1.310258,
8.96480E-1, 1.473408, 1.321628, 1.104853, 1.362848, 1.253072, 1.091452 };
THEN( "S(a,b) and effective temperature outputs are correct" ){
REQUIRE(ranges::equal(sab,correct,equal));
REQUIRE( 556.3 == Approx(effectiveTemp).epsilon(1e-6) );
} // THEN
} // WHEN
WHEN( "translational weight is large" ){
transWgt = 0.5;
tbeta = 0.5;
translational( alpha, beta, transWgt, delta, c, lambda_s, tbeta,
effectiveTemp, temp, sab );
correct = {1.170449, 1.132933, 1.066604, 8.459466E-1, 8.383600E-1,
8.20872E-1, 5.737014E-1, 5.764080E-1, 5.751139E-1, 4.984466E-1,
5.01821E-1, 5.038771E-1 };
THEN( "S(a,b) and effective temperature outputs are correct" ){
REQUIRE(ranges::equal(sab,correct,equal));
REQUIRE( 433 == Approx(effectiveTemp).epsilon(1e-6) );
} // THEN
} // WHEN
WHEN( "alpha and beta values are very small" ){
alpha = {0.001, 0.002, 0.004, 0.005};
beta = {0.0015,0.0018,0.0022};
for ( auto& a : alpha ){ a*= scaling; }
for ( auto& b : beta ){ b*= sc; }
transWgt = 0.05;
tbeta = 0.95;
translational( alpha, beta, transWgt, delta, c, lambda_s, tbeta,
effectiveTemp, temp, sab );
correct = { 39.43256, 39.27908, 38.93495, 28.02756, 27.99394, 27.84877,
19.83799, 19.81991, 19.79582, 17.74976, 17.73555, 17.71663 };
THEN( "S(a,b) and effective temperature outputs are correct" ){
REQUIRE(ranges::equal(sab,correct,equal));
REQUIRE( 556.3 == Approx(effectiveTemp).epsilon(1e-6) );
} // THEN
} // WHEN
WHEN( "translational weight is small" ){
alpha = {0.001,0.002,0.004,0.005};
beta = {0.0015,0.0018,0.0022};
for ( auto& a : alpha ){ a*= scaling; }
for ( auto& b : beta ){ b*= sc; }
std::vector<double> sab = ranges::view::iota(1,int(alpha.size()*beta.size()+1))
| ranges::view::transform([](auto x){return 1e-3*x;});
transWgt = 0.05;
tbeta = 0.95;
translational( alpha, beta, transWgt, delta, c, lambda_s, tbeta,
effectiveTemp, temp, sab );
correct = { 39.43256, 39.27908, 38.93495, 28.02756, 27.99394, 27.84877,
19.83799, 19.81991, 19.79582, 17.74976, 17.73555, 17.71663};
THEN( "S(a,b) and effective temperature outputs are correct" ){
REQUIRE(ranges::equal(sab,correct,equal));
REQUIRE( 556.3 == Approx(effectiveTemp).epsilon(1e-6) );
} // THEN
} // WHEN
WHEN( "translational weight is larger and more alpha,beta values" ){
alpha = {1e-5,1e-4,1e-3,1e-2,1e-1,1.0,10,20,50};
beta = {0.00,1e-5,1e-4,1e-3,1e-2,1e-1,1.0,10,20,50};
for ( auto& a : alpha ){ a*= scaling; }
for ( auto& b : beta ){ b*= sc; }
std::vector<double> sab = ranges::view::iota(1,int(alpha.size()*beta.size()+1))
| ranges::view::transform([](auto x){return 1e-3*x;});
transWgt = 0.2;
tbeta = 0.8;
temp = 596.0;
AND_WHEN( "alpha and beta value are not scaled (lat=0)" ){
translational( alpha, beta, transWgt, delta, c, lambda_s, tbeta,
effectiveTemp, temp, sab );
correct = { 1.994744E2, 1.994727E2, 1.992349E2, 1.761239E2, 5.65913E-3,
5.99113E-3, 6.99912E-3, 7.99998E-3, 8.99994E-3, 5.99283E-3, 6.309085E1,
6.309046E1, 6.308549E1, 6.233784E1, 1.817689E1, 1.59737E-2, 1.69973E-2,
1.79999E-2, 1.89998E-2, 1.06677E-2, 1.996615E1, 1.996604E1, 1.996493E1,
1.994924E1, 1.770957E1, 2.59956E-2, 2.69917E-2, 2.79998E-2, 2.89994E-2,
1.52989E-2, 6.32454940, 6.32454830, 6.32423750, 6.32079240, 6.27130850,
1.92746280, 3.69731E-2, 3.79994E-2, 3.89981E-2, 2.12555E-2, 1.98168440,
1.98172490, 1.98178970, 1.98210100, 1.98488020, 1.83899950, 4.69186E-2,
4.79968E-2, 4.89932E-2, 2.79239E-2, 5.18916E-1, 5.18954E-1, 5.19008E-1,
5.19229E-1, 5.21116E-1, 5.38813E-1, 2.80139E-1, 5.79755E-2, 5.89686E-2,
3.85062E-2, 3.31777E-2, 3.32007E-2, 3.32249E-2, 3.32616E-2, 3.34242E-2,
3.49013E-2, 5.02640E-2, 6.77807E-2, 6.87878E-2, 5.96199E-2, 1.25262E-2,
1.25401E-2, 1.25545E-2, 1.25735E-2, 1.26395E-2, 1.32000E-2, 1.98954E-2,
7.70064E-2, 7.85919E-2, 7.41241E-2, 2.18543E-3, 2.18853E-3, 2.19170E-3,
2.19566E-3, 2.20750E-3, 2.30258E-3, 3.53872E-3, 5.08625E-2, 8.72796E-2,
8.86631E-2 };
THEN( "S(a,b) and effective temperature outputs are correct" ){
REQUIRE(ranges::equal(sab,correct,equal));
REQUIRE( 575.2 == Approx(effectiveTemp).epsilon(1e-6) );
} // THEN
} // AND WHEN
AND_WHEN( "alpha and beta value are not scaled (lat=1)" ){
sc = 0.492608069; scaling = 0.492608069;
for ( auto& a : alpha ){ a*= scaling; }
for ( auto& b : beta ){ b*= sc; }
translational( alpha, beta, transWgt, delta, c, lambda_s, tbeta,
effectiveTemp, temp, sab );
correct = { 2.842070E2, 2.842058E2, 2.840389E2, 2.673005E2, 6.08110E-1,
5.98738E-3, 6.99875E-3, 7.99997E-3, 8.99991E-3, 5.70052E-3, 8.988626E1,
8.988598E1, 8.988249E1, 8.935613E1, 4.868566E1, 1.59626E-2, 1.69962E-2,
1.79999E-2, 1.89997E-2, 1.04688E-2, 2.844125E1, 2.844117E1, 2.844039E1,
2.842937E1, 2.680892E1, 8.75471E-2, 2.69882E-2, 2.79998E-2, 2.89992E-2,
1.52096E-2, 9.00973040, 9.00972940, 9.00950810, 9.00705570, 8.97237470,
5.00259950, 3.69622E-2, 3.79992E-2, 3.89974E-2, 2.08840E-2, 2.84636880,
2.84640640, 2.846444E0, 2.84648650, 2.84657030, 2.73906810, 5.44531E-2,
4.79963E-2, 4.89909E-2, 2.73327E-2, 8.29348E-1, 8.29386E-1, 8.29436E-1,
8.29600E-1, 8.30920E-1, 8.43850E-1, 5.94946E-1, 5.79742E-2, 5.89616E-2,
3.63545E-2, 1.03685E-1, 1.03715E-1, 1.03746E-1, 1.03797E-1, 1.04036E-1,
1.06200E-1, 1.26094E-1, 6.94957E-2, 6.87718E-2, 5.40516E-2, 3.73175E-2,
3.73406E-2, 3.73644E-2, 3.73950E-2, 3.74953E-2, 3.83063E-2, 4.68172E-2,
8.18560E-2, 7.85819E-2, 6.79374E-2, 1.02228E-2, 1.02338E-2, 1.02449E-2,
1.02580E-2, 1.02897E-2, 1.05130E-2, 1.31090E-2, 5.45032E-2, 8.50659E-2,
8.49093E-2 };
THEN( "S(a,b) and effective temperature outputs are correct" ){
REQUIRE(ranges::equal(sab,correct,equal));
REQUIRE( 575.2 == Approx(effectiveTemp).epsilon(1e-6) );
} // THEN
} // AND WHEN
} // WHEN
} // GIVEN
} // TEST CASE
| [
"ameliajo@mit.edu"
] | ameliajo@mit.edu |
68d802c7b30c75522a94b52de89452c1b5ed9018 | 85d3bf0d011079e2b4849366e3c4a6f77b9e2710 | /lnk_parser_cmd/utilities.cpp | 9e1658a8e5505a5747e2a4aa3c15934206d4491f | [] | no_license | greatis/lnk-parser | e1996cc4e19b26d1118237f33fd12e773eb13d81 | 41e7d6d2e8559bbf4ecc8dfce7033ad509b9a515 | refs/heads/master | 2021-01-10T10:57:33.117264 | 2014-03-01T06:48:31 | 2014-03-01T06:48:31 | 46,291,764 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 73,018 | cpp | #include "globals.h"
wchar_t *get_extension_from_filename( wchar_t *filename )
{
if ( filename == NULL )
{
return NULL;
}
unsigned long length = wcslen( filename );
while ( length != 0 && filename[ --length ] != L'.' );
return filename + length;
}
void traverse_directory( wchar_t *path )
{
//int total_directories = 0;
//int total_files = 0;
wchar_t filepath[ MAX_PATH ];
swprintf_s( filepath, MAX_PATH, L"%s\\*", path );
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFileEx( ( LPCWSTR )filepath, FindExInfoStandard, &FindFileData, FindExSearchNameMatch, NULL, 0 );
if ( hFind != INVALID_HANDLE_VALUE )
{
do
{
// See if the file is a directory.
if ( ( FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
{
// Add all directories except "." and ".." (current and parent)
if ( ( wcscmp( FindFileData.cFileName, L"." ) != 0 ) && ( wcscmp( FindFileData.cFileName, L".." ) != 0 ) )
{
// Create new tree node.
wchar_t new_path[ MAX_PATH ];
swprintf_s( new_path, MAX_PATH, L"%s\\%s", path, FindFileData.cFileName );
//wprintf( L"%s\n", new_path );
traverse_directory( new_path );
//total_directories++;
}
}
else
{
// REMOVE THE .BIN WHEN FINISHED
if ( /*_wcsicmp( get_extension_from_filename( FindFileData.cFileName ), L".bin" ) != 0 &&/**/_wcsicmp( get_extension_from_filename( FindFileData.cFileName ), L".lnk" ) != 0 /*&& FindFileData.nFileSizeLow > 18240*/ )
{
continue;
}
wchar_t full_path[ MAX_PATH ];
swprintf_s( full_path, MAX_PATH, L"%s\\%s", path, FindFileData.cFileName );
//wprintf( L"%s\n", full_path );
parse_shortcut( full_path );
//total_files++;
}
} while ( FindNextFile( hFind, &FindFileData ) != 0 );
FindClose( hFind );
}
}
wchar_t *get_showwindow_value( unsigned int sw_value )
{
switch ( sw_value )
{
case SW_HIDE: { return L"SW_HIDE"; } break;
//case SW_SHOWNORMAL:
case SW_NORMAL: { return L"SW_SHOWNORMAL / SW_NORMAL"; } break;
case SW_SHOWMINIMIZED: { return L"SW_SHOWMINIMIZED"; } break;
//case SW_SHOWMAXIMIZED:
case SW_MAXIMIZE: { return L"SW_SHOWMAXIMIZED / SW_MAXIMIZE"; } break;
case SW_SHOWNOACTIVATE: { return L"SW_SHOWNOACTIVATE"; } break;
case SW_SHOW: { return L"SW_SHOW"; } break;
case SW_MINIMIZE: { return L"SW_MINIMIZE"; } break;
case SW_SHOWMINNOACTIVE: { return L"SW_SHOWMINNOACTIVE"; } break;
case SW_SHOWNA: { return L"SW_SHOWNA"; } break;
case SW_RESTORE: { return L"SW_RESTORE"; } break;
case SW_SHOWDEFAULT: { return L"SW_SHOWDEFAULT"; } break;
//case SW_FORCEMINIMIZE:
case SW_MAX: { return L"SW_FORCEMINIMIZE / SW_MAX"; } break;
default:
return L"Unknown";
break;
}
return NULL;
}
wchar_t *get_hot_key_value( unsigned short hk_value )
{
unsigned char low = LOBYTE( hk_value );
unsigned char high = HIBYTE( hk_value );
static wchar_t buf[ 128 ];
// See if the low value is between 0 and 9, or A and Z.
if ( ( low >= 0x30 && low <= 0x39 ) || ( low >= 0x41 && low <= 0x5A ) )
{
swprintf_s( buf, 128, L"%s%s%s%c", ( ( high & HOTKEYF_CONTROL ) != FALSE ? L"Ctrl + " : L"" ), ( ( high & HOTKEYF_SHIFT ) != FALSE ? L"Shift + " : L"" ), ( ( high & HOTKEYF_ALT ) != FALSE ? L"Alt + " : L"" ), low );
}
else
{
wchar_t *vk_key = NULL;
switch ( low )
{
// Common/acceptable key codes.
case 0: { vk_key = L"None"; } break;
case VK_CAPITAL: { vk_key = L"Caps Lock"; } break;
case VK_PRIOR: { vk_key = L"Page Up"; } break;
case VK_NEXT: { vk_key = L"Page Down"; } break;
case VK_END: { vk_key = L"End"; } break;
case VK_HOME: { vk_key = L"Home"; } break;
case VK_LEFT: { vk_key = L"Left"; } break;
case VK_UP: { vk_key = L"Up"; } break;
case VK_RIGHT: { vk_key = L"Right"; } break;
case VK_DOWN: { vk_key = L"Down"; } break;
case VK_INSERT: { vk_key = L"Insert"; } break;
case VK_NUMPAD0: { vk_key = L"Num 0"; } break;
case VK_NUMPAD1: { vk_key = L"Num 1"; } break;
case VK_NUMPAD2: { vk_key = L"Num 2"; } break;
case VK_NUMPAD3: { vk_key = L"Num 3"; } break;
case VK_NUMPAD4: { vk_key = L"Num 4"; } break;
case VK_NUMPAD5: { vk_key = L"Num 5"; } break;
case VK_NUMPAD6: { vk_key = L"Num 6"; } break;
case VK_NUMPAD7: { vk_key = L"Num 7"; } break;
case VK_NUMPAD8: { vk_key = L"Num 8"; } break;
case VK_NUMPAD9: { vk_key = L"Num 9"; } break;
case VK_MULTIPLY: { vk_key = L"Num *"; } break;
case VK_ADD: { vk_key = L"Num +"; } break;
case VK_SUBTRACT: { vk_key = L"Num -"; } break;
case VK_DIVIDE: { vk_key = L"Num /"; } break;
case VK_F1: { vk_key = L"F1"; } break;
case VK_F2: { vk_key = L"F2"; } break;
case VK_F3: { vk_key = L"F3"; } break;
case VK_F4: { vk_key = L"F4"; } break;
case VK_F5: { vk_key = L"F5"; } break;
case VK_F6: { vk_key = L"F6"; } break;
case VK_F7: { vk_key = L"F7"; } break;
case VK_F8: { vk_key = L"F8"; } break;
case VK_F9: { vk_key = L"F9"; } break;
case VK_F10: { vk_key = L"F10"; } break;
case VK_F11: { vk_key = L"F11"; } break;
case VK_F12: { vk_key = L"F12"; } break;
case VK_F13: { vk_key = L"F13"; } break;
case VK_F14: { vk_key = L"F14"; } break;
case VK_F15: { vk_key = L"F15"; } break;
case VK_F16: { vk_key = L"F16"; } break;
case VK_F17: { vk_key = L"F17"; } break;
case VK_F18: { vk_key = L"F18"; } break;
case VK_F19: { vk_key = L"F19"; } break;
case VK_F20: { vk_key = L"F20"; } break;
case VK_F21: { vk_key = L"F21"; } break;
case VK_F22: { vk_key = L"F22"; } break;
case VK_F23: { vk_key = L"F23"; } break;
case VK_F24: { vk_key = L"F24"; } break;
case VK_NUMLOCK: { vk_key = L"Num Lock"; } break;
case VK_SCROLL: { vk_key = L"Scroll Lock"; } break;
case VK_OEM_1: { vk_key = L";"; } break;
case VK_OEM_PLUS: { vk_key = L"="; } break;
case VK_OEM_COMMA: { vk_key = L","; } break;
case VK_OEM_MINUS: { vk_key = L"-"; } break;
case VK_OEM_PERIOD: { vk_key = L"."; } break;
case VK_OEM_2: { vk_key = L"/"; } break;
case VK_OEM_3: { vk_key = L"`"; } break;
case VK_OEM_4: { vk_key = L"["; } break;
case VK_OEM_5: { vk_key = L"\\"; } break;
case VK_OEM_6: { vk_key = L"]"; } break;
case VK_OEM_7: { vk_key = L"\'"; } break;
// Uncommon/unacceptable key codes.
case VK_LBUTTON: { vk_key = L"VK_LBUTTON"; } break;
case VK_RBUTTON: { vk_key = L"VK_RBUTTON"; } break;
case VK_CANCEL: { vk_key = L"VK_CANCEL"; } break;
case VK_MBUTTON: { vk_key = L"VK_MBUTTON"; } break;
case VK_XBUTTON1: { vk_key = L"VK_XBUTTON1"; } break;
case VK_XBUTTON2: { vk_key = L"VK_XBUTTON2"; } break;
case VK_BACK: { vk_key = L"VK_BACK"; } break;
case VK_TAB: { vk_key = L"VK_TAB"; } break;
case VK_CLEAR: { vk_key = L"VK_CLEAR"; } break;
case VK_RETURN: { vk_key = L"VK_RETURN"; } break;
case VK_SHIFT: { vk_key = L"VK_SHIFT"; } break;
case VK_CONTROL: { vk_key = L"VK_CONTROL"; } break;
case VK_MENU: { vk_key = L"VK_MENU"; } break;
case VK_PAUSE: { vk_key = L"VK_PAUSE"; } break;
//case VK_KANA:
//case VK_HANGEUL:
case VK_HANGUL: { vk_key = L"VK_KANA / VK_HANGEUL / VK_HANGUL"; } break;
case VK_JUNJA: { vk_key = L"VK_JUNJA"; } break;
case VK_FINAL: { vk_key = L"VK_FINAL"; } break;
//case VK_HANJA:
case VK_KANJI: { vk_key = L"VK_HANJA / VK_KANJI"; } break;
case VK_ESCAPE: { vk_key = L"VK_ESCAPE"; } break;
case VK_CONVERT: { vk_key = L"VK_CONVERT"; } break;
case VK_NONCONVERT: { vk_key = L"VK_NONCONVERT"; } break;
case VK_ACCEPT: { vk_key = L"VK_ACCEPT"; } break;
case VK_MODECHANGE: { vk_key = L"VK_MODECHANGE"; } break;
case VK_SPACE: { vk_key = L"VK_SPACE"; } break;
case VK_SELECT: { vk_key = L"VK_SELECT"; } break;
case VK_PRINT: { vk_key = L"VK_PRINT"; } break;
case VK_EXECUTE: { vk_key = L"VK_EXECUTE"; } break;
case VK_SNAPSHOT: { vk_key = L"VK_SNAPSHOT"; } break;
case VK_DELETE: { vk_key = L"VK_DELETE"; } break;
case VK_HELP: { vk_key = L"VK_HELP"; } break;
case VK_LWIN: { vk_key = L"VK_LWIN"; } break;
case VK_RWIN: { vk_key = L"VK_RWIN"; } break;
case VK_APPS: { vk_key = L"VK_APPS"; } break;
case VK_SLEEP: { vk_key = L"VK_SLEEP"; } break;
case VK_SEPARATOR: { vk_key = L"VK_SEPARATOR"; } break;
case VK_DECIMAL: { vk_key = L"VK_DECIMAL"; } break;
//case VK_OEM_NEC_EQUAL:
case VK_OEM_FJ_JISHO: { vk_key = L"VK_OEM_NEC_EQUAL / VK_OEM_FJ_JISHO"; } break;
case VK_OEM_FJ_MASSHOU: { vk_key = L"VK_OEM_FJ_MASSHOU"; } break;
case VK_OEM_FJ_TOUROKU: { vk_key = L"VK_OEM_FJ_TOUROKU"; } break;
case VK_OEM_FJ_LOYA: { vk_key = L"VK_OEM_FJ_LOYA"; } break;
case VK_OEM_FJ_ROYA: { vk_key = L"VK_OEM_FJ_ROYA"; } break;
case VK_LSHIFT: { vk_key = L"VK_LSHIFT"; } break;
case VK_RSHIFT: { vk_key = L"VK_RSHIFT"; } break;
case VK_LCONTROL: { vk_key = L"VK_LCONTROL"; } break;
case VK_RCONTROL: { vk_key = L"VK_RCONTROL"; } break;
case VK_LMENU: { vk_key = L"VK_LMENU"; } break;
case VK_RMENU: { vk_key = L"VK_RMENU"; } break;
case VK_BROWSER_BACK: { vk_key = L"VK_BROWSER_BACK"; } break;
case VK_BROWSER_FORWARD: { vk_key = L"VK_BROWSER_FORWARD"; } break;
case VK_BROWSER_REFRESH: { vk_key = L"VK_BROWSER_REFRESH"; } break;
case VK_BROWSER_STOP: { vk_key = L"VK_BROWSER_STOP"; } break;
case VK_BROWSER_SEARCH: { vk_key = L"VK_BROWSER_SEARCH"; } break;
case VK_BROWSER_FAVORITES: { vk_key = L"VK_BROWSER_FAVORITES"; } break;
case VK_BROWSER_HOME: { vk_key = L"VK_BROWSER_HOME"; } break;
case VK_VOLUME_MUTE: { vk_key = L"VK_VOLUME_MUTE"; } break;
case VK_VOLUME_DOWN: { vk_key = L"VK_VOLUME_DOWN"; } break;
case VK_VOLUME_UP: { vk_key = L"VK_VOLUME_UP"; } break;
case VK_MEDIA_NEXT_TRACK: { vk_key = L"VK_MEDIA_NEXT_TRACK"; } break;
case VK_MEDIA_PREV_TRACK: { vk_key = L"VK_MEDIA_PREV_TRACK"; } break;
case VK_MEDIA_STOP: { vk_key = L"VK_MEDIA_STOP"; } break;
case VK_MEDIA_PLAY_PAUSE: { vk_key = L"VK_MEDIA_PLAY_PAUSE"; } break;
case VK_LAUNCH_MAIL: { vk_key = L"VK_LAUNCH_MAIL"; } break;
case VK_LAUNCH_MEDIA_SELECT: { vk_key = L"VK_LAUNCH_MEDIA_SELECT"; } break;
case VK_LAUNCH_APP1: { vk_key = L"VK_LAUNCH_APP1"; } break;
case VK_LAUNCH_APP2: { vk_key = L"VK_LAUNCH_APP2"; } break;
case VK_OEM_8: { vk_key = L"VK_OEM_8"; } break;
case VK_OEM_AX: { vk_key = L"VK_OEM_AX"; } break;
case VK_OEM_102: { vk_key = L"VK_OEM_102"; } break;
case VK_ICO_HELP: { vk_key = L"VK_ICO_HELP"; } break;
case VK_ICO_00: { vk_key = L"VK_ICO_00"; } break;
case VK_PROCESSKEY: { vk_key = L"VK_PROCESSKEY"; } break;
case VK_ICO_CLEAR: { vk_key = L"VK_ICO_CLEAR"; } break;
case VK_PACKET: { vk_key = L"VK_PACKET"; } break;
case VK_OEM_RESET: { vk_key = L"VK_OEM_RESET"; } break;
case VK_OEM_JUMP: { vk_key = L"VK_OEM_JUMP"; } break;
case VK_OEM_PA1: { vk_key = L"VK_OEM_PA1"; } break;
case VK_OEM_PA2: { vk_key = L"VK_OEM_PA2"; } break;
case VK_OEM_PA3: { vk_key = L"VK_OEM_PA3"; } break;
case VK_OEM_WSCTRL: { vk_key = L"VK_OEM_WSCTRL"; } break;
case VK_OEM_CUSEL: { vk_key = L"VK_OEM_CUSEL"; } break;
case VK_OEM_ATTN: { vk_key = L"VK_OEM_ATTN"; } break;
case VK_OEM_FINISH: { vk_key = L"VK_OEM_FINISH"; } break;
case VK_OEM_COPY: { vk_key = L"VK_OEM_COPY"; } break;
case VK_OEM_AUTO: { vk_key = L"VK_OEM_AUTO"; } break;
case VK_OEM_ENLW: { vk_key = L"VK_OEM_ENLW"; } break;
case VK_OEM_BACKTAB: { vk_key = L"VK_OEM_BACKTAB"; } break;
case VK_ATTN: { vk_key = L"VK_ATTN"; } break;
case VK_CRSEL: { vk_key = L"VK_CRSEL"; } break;
case VK_EXSEL: { vk_key = L"VK_EXSEL"; } break;
case VK_EREOF: { vk_key = L"VK_EREOF"; } break;
case VK_PLAY: { vk_key = L"VK_PLAY"; } break;
case VK_ZOOM: { vk_key = L"VK_ZOOM"; } break;
case VK_NONAME: { vk_key = L"VK_NONAME"; } break;
case VK_PA1: { vk_key = L"VK_PA1"; } break;
case VK_OEM_CLEAR: { vk_key = L"VK_OEM_CLEAR"; } break;
// Unused
case 0x07:
case 0x40:
case 0x88:
case 0x89:
case 0x8A:
case 0x8B:
case 0x8C:
case 0x8D:
case 0x8E:
case 0x8F:
case 0x97:
case 0x98:
case 0x99:
case 0x9A:
case 0x9B:
case 0x9C:
case 0x9D:
case 0x9E:
case 0x9F:
case 0xD8:
case 0xD9:
case 0xDA:
case 0xE8:
vk_key = L"Unassigned";
break;
case 0x0A:
case 0x0B:
case 0x5E:
case 0xB8:
case 0xB9:
case 0xC1:
case 0xC2:
case 0xC3:
case 0xC4:
case 0xC5:
case 0xC6:
case 0xC7:
case 0xC8:
case 0xC9:
case 0xCA:
case 0xCB:
case 0xCC:
case 0xCD:
case 0xCE:
case 0xCF:
case 0xD0:
case 0xD1:
case 0xD2:
case 0xD3:
case 0xD4:
case 0xD5:
case 0xD6:
case 0xD7:
case 0xE0:
vk_key = L"Reserved";
break;
default:
vk_key = L"Unknown";
break;
}
swprintf_s( buf, 128, L"%s%s%s%s", ( ( high & HOTKEYF_CONTROL ) != FALSE ? L"Ctrl + " : L"" ), ( ( high & HOTKEYF_SHIFT ) != FALSE ? L"Shift + " : L"" ), ( ( high & HOTKEYF_ALT ) != FALSE ? L"Alt + " : L"" ), vk_key );
}
return buf;
}
wchar_t *get_file_attributes( unsigned int fa_flags )
{
if ( fa_flags == 0 )
{
return L"None";
}
static wchar_t buf[ 512 ];
int size = swprintf_s( buf, 512, L"%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
( ( fa_flags & FILE_ATTRIBUTE_READONLY ) ? L"FILE_ATTRIBUTE_READONLY, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_HIDDEN ) ? L"FILE_ATTRIBUTE_HIDDEN, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_SYSTEM ) ? L"FILE_ATTRIBUTE_SYSTEM, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_DIRECTORY ) ? L"FILE_ATTRIBUTE_DIRECTORY, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_ARCHIVE ) ? L"FILE_ATTRIBUTE_ARCHIVE, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_DEVICE ) ? L"FILE_ATTRIBUTE_DEVICE, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_NORMAL ) ? L"FILE_ATTRIBUTE_NORMAL, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_TEMPORARY ) ? L"FILE_ATTRIBUTE_TEMPORARY, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_SPARSE_FILE ) ? L"FILE_ATTRIBUTE_SPARSE_FILE, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_REPARSE_POINT ) ? L"FILE_ATTRIBUTE_REPARSE_POINT, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_COMPRESSED ) ? L"FILE_ATTRIBUTE_COMPRESSED, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_OFFLINE ) ? L"FILE_ATTRIBUTE_OFFLINE, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED ) ? L"FILE_ATTRIBUTE_NOT_CONTENT_INDEXED, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_ENCRYPTED ) ? L"FILE_ATTRIBUTE_ENCRYPTED, " : L"" ),
( ( fa_flags & FILE_ATTRIBUTE_VIRTUAL ) ? L"FILE_ATTRIBUTE_VIRTUAL" : L"" ) );
if ( size > 1 && buf[ size - 1 ] == L' ' )
{
buf[ size - 2 ] = L'\0';
}
return buf;
}
wchar_t *get_data_flags( unsigned int d_flags )
{
if ( d_flags == 0 )
{
return L"None";
}
static wchar_t buf[ 1024 ];
int size = swprintf_s( buf, 1024, L"%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
( ( d_flags & HasLinkTargetIDList ) ? L"HasLinkTargetIDList, " : L"" ),
( ( d_flags & HasLinkInfo ) ? L"HasLinkInfo, " : L"" ),
( ( d_flags & HasName ) ? L"HasName, " : L"" ),
( ( d_flags & HasRelativePath ) ? L"HasRelativePath, " : L"" ),
( ( d_flags & HasWorkingDir ) ? L"HasWorkingDir, " : L"" ),
( ( d_flags & HasArguments ) ? L"HasArguments, " : L"" ),
( ( d_flags & HasIconLocation ) ? L"HasIconLocation, " : L"" ),
( ( d_flags & IsUnicode ) ? L"IsUnicode, " : L"" ),
( ( d_flags & ForceNoLinkInfo ) ? L"ForceNoLinkInfo, " : L"" ),
( ( d_flags & HasExpString ) ? L"HasExpString, " : L"" ),
( ( d_flags & RunInSeparateProcess ) ? L"RunInSeparateProcess, " : L"" ),
( ( d_flags & Unused1 ) ? L"Unused1, " : L"" ),
( ( d_flags & HasDarwinID ) ? L"HasDarwinID, " : L"" ),
( ( d_flags & RunAsUser ) ? L"RunAsUser, " : L"" ),
( ( d_flags & HasExpIcon ) ? L"HasExpIcon, " : L"" ),
( ( d_flags & NoPidlAlias ) ? L"NoPidlAlias, " : L"" ),
( ( d_flags & Unused2 ) ? L"Unused2, " : L"" ),
( ( d_flags & RunWithShimLayer ) ? L"RunWithShimLayer, " : L"" ),
( ( d_flags & ForceNoLinkTrack ) ? L"ForceNoLinkTrack, " : L"" ),
( ( d_flags & EnableTargetMetadata ) ? L"EnableTargetMetadata, " : L"" ),
( ( d_flags & DisableLinkPathTracking ) ? L"DisableLinkPathTracking, " : L"" ),
( ( d_flags & DisableKnownFolderTracking ) ? L"DisableKnownFolderTracking, " : L"" ),
( ( d_flags & DisableKnownFolderAlias ) ? L"DisableKnownFolderAlias, " : L"" ),
( ( d_flags & AllowLinkToLink ) ? L"AllowLinkToLink, " : L"" ),
( ( d_flags & UnaliasOnSave ) ? L"UnaliasOnSave, " : L"" ),
( ( d_flags & PreferEnvironmentPath ) ? L"PreferEnvironmentPath, " : L"" ),
( ( d_flags & KeepLocalIDListForUNCTarget ) ? L"KeepLocalIDListForUNCTarget" : L"" ) );
if ( size > 1 && buf[ size - 1 ] == L' ' )
{
buf[ size - 2 ] = L'\0';
}
return buf;
}
wchar_t *get_link_info_flags( unsigned int li_flags )
{
if ( li_flags == 0 )
{
return L"None";
}
static wchar_t buf[ 128 ];
int size = swprintf_s( buf, 128, L"%s%s",
( ( li_flags & VolumeIDAndLocalBasePath ) ? L"VolumeIDAndLocalBasePath, " : L"" ),
( ( li_flags & CommonNetworkRelativeLinkAndPathSuffix ) ? L"CommonNetworkRelativeLinkAndPathSuffix" : L"" ) );
if ( size > 1 && buf[ size - 1 ] == L' ' )
{
buf[ size - 2 ] = L'\0';
}
return buf;
}
wchar_t *get_common_network_relative_link_flags( unsigned int cnrl_flags )
{
if ( cnrl_flags == 0 )
{
return L"None";
}
static wchar_t buf[ 128 ];
int size = swprintf_s( buf, 128, L"%s%s",
( ( cnrl_flags & ValidDevice ) ? L"ValidDevice, " : L"" ),
( ( cnrl_flags & ValidNetType ) ? L"ValidNetType" : L"" ) );
if ( size > 1 && buf[ size - 1 ] == L' ' )
{
buf[ size - 2 ] = L'\0';
}
return buf;
}
wchar_t *get_drive_type( unsigned int d_type )
{
switch ( d_type )
{
case DRIVE_UNKNOWN: { return L"DRIVE_UNKNOWN"; } break;
case DRIVE_NO_ROOT_DIR: { return L"DRIVE_NO_ROOT_DIR"; } break;
case DRIVE_REMOVABLE: { return L"DRIVE_REMOVABLE"; } break;
case DRIVE_FIXED: { return L"DRIVE_FIXED"; } break;
case DRIVE_REMOTE: { return L"DRIVE_REMOTE"; } break;
case DRIVE_CDROM: { return L"DRIVE_CDROM"; } break;
case DRIVE_RAMDISK: { return L"DRIVE_RAMDISK"; } break;
default:
return L"Unknown";
break;
}
}
wchar_t *get_network_provider_type( unsigned int np_type )
{
switch ( np_type )
{
case WNNC_NET_MSNET: { return L"WNNC_NET_MSNET"; } break;
case WNNC_NET_LANMAN: { return L"WNNC_NET_LANMAN"; } break;
case WNNC_NET_NETWARE: { return L"WNNC_NET_NETWARE"; } break;
case WNNC_NET_VINES: { return L"WNNC_NET_VINES"; } break;
case WNNC_NET_10NET: { return L"WNNC_NET_10NET"; } break;
case WNNC_NET_LOCUS: { return L"WNNC_NET_LOCUS"; } break;
case WNNC_NET_SUN_PC_NFS: { return L"WNNC_NET_SUN_PC_NFS"; } break;
case WNNC_NET_LANSTEP: { return L"WNNC_NET_LANSTEP"; } break;
case WNNC_NET_9TILES: { return L"WNNC_NET_9TILES"; } break;
case WNNC_NET_LANTASTIC: { return L"WNNC_NET_LANTASTIC"; } break;
case WNNC_NET_AS400: { return L"WNNC_NET_AS400"; } break;
case WNNC_NET_FTP_NFS: { return L"WNNC_NET_FTP_NFS"; } break;
case WNNC_NET_PATHWORKS: { return L"WNNC_NET_PATHWORKS"; } break;
case WNNC_NET_LIFENET: { return L"WNNC_NET_LIFENET"; } break;
case WNNC_NET_POWERLAN: { return L"WNNC_NET_POWERLAN"; } break;
case WNNC_NET_BWNFS: { return L"WNNC_NET_BWNFS"; } break;
case WNNC_NET_COGENT: { return L"WNNC_NET_COGENT"; } break;
case WNNC_NET_FARALLON: { return L"WNNC_NET_FARALLON"; } break;
case WNNC_NET_APPLETALK: { return L"WNNC_NET_APPLETALK"; } break;
case WNNC_NET_INTERGRAPH: { return L"WNNC_NET_INTERGRAPH"; } break;
case WNNC_NET_SYMFONET: { return L"WNNC_NET_SYMFONET"; } break;
case WNNC_NET_CLEARCASE: { return L"WNNC_NET_CLEARCASE"; } break;
case WNNC_NET_FRONTIER: { return L"WNNC_NET_FRONTIER"; } break;
case WNNC_NET_BMC: { return L"WNNC_NET_BMC"; } break;
case WNNC_NET_DCE: { return L"WNNC_NET_DCE"; } break;
case WNNC_NET_AVID: { return L"WNNC_NET_AVID"; } break;
case WNNC_NET_DOCUSPACE: { return L"WNNC_NET_DOCUSPACE"; } break;
case WNNC_NET_MANGOSOFT: { return L"WNNC_NET_MANGOSOFT"; } break;
case WNNC_NET_SERNET: { return L"WNNC_NET_SERNET"; } break;
case WNNC_NET_RIVERFRONT1: { return L"WNNC_NET_RIVERFRONT1"; } break;
case WNNC_NET_RIVERFRONT2: { return L"WNNC_NET_RIVERFRONT2"; } break;
case WNNC_NET_DECORB: { return L"WNNC_NET_DECORB"; } break;
case WNNC_NET_PROTSTOR: { return L"WNNC_NET_PROTSTOR"; } break;
case WNNC_NET_FJ_REDIR: { return L"WNNC_NET_FJ_REDIR"; } break;
case WNNC_NET_DISTINCT: { return L"WNNC_NET_DISTINCT"; } break;
case WNNC_NET_TWINS: { return L"WNNC_NET_TWINS"; } break;
case WNNC_NET_RDR2SAMPLE: { return L"WNNC_NET_RDR2SAMPLE"; } break;
case WNNC_NET_CSC: { return L"WNNC_NET_CSC"; } break;
case WNNC_NET_3IN1: { return L"WNNC_NET_3IN1"; } break;
case WNNC_NET_EXTENDNET: { return L"WNNC_NET_EXTENDNET"; } break;
case WNNC_NET_STAC: { return L"WNNC_NET_STAC"; } break;
case WNNC_NET_FOXBAT: { return L"WNNC_NET_FOXBAT"; } break;
case WNNC_NET_YAHOO: { return L"WNNC_NET_YAHOO"; } break;
case WNNC_NET_EXIFS: { return L"WNNC_NET_EXIFS"; } break;
case WNNC_NET_DAV: { return L"WNNC_NET_DAV"; } break;
case WNNC_NET_KNOWARE: { return L"WNNC_NET_KNOWARE"; } break;
case WNNC_NET_OBJECT_DIRE: { return L"WNNC_NET_OBJECT_DIRE"; } break;
case WNNC_NET_MASFAX: { return L"WNNC_NET_MASFAX"; } break;
case WNNC_NET_HOB_NFS: { return L"WNNC_NET_HOB_NFS"; } break;
case WNNC_NET_SHIVA: { return L"WNNC_NET_SHIVA"; } break;
case WNNC_NET_IBMAL: { return L"WNNC_NET_IBMAL"; } break;
case WNNC_NET_LOCK: { return L"WNNC_NET_LOCK"; } break;
case WNNC_NET_TERMSRV: { return L"WNNC_NET_TERMSRV"; } break;
case WNNC_NET_SRT: { return L"WNNC_NET_SRT"; } break;
case WNNC_NET_QUINCY: { return L"WNNC_NET_QUINCY"; } break;
case WNNC_NET_OPENAFS: { return L"WNNC_NET_OPENAFS"; } break;
case WNNC_NET_AVID1: { return L"WNNC_NET_AVID1"; } break;
case WNNC_NET_DFS: { return L"WNNC_NET_DFS"; } break;
case WNNC_NET_KWNP: { return L"WNNC_NET_KWNP"; } break;
case WNNC_NET_ZENWORKS: { return L"WNNC_NET_ZENWORKS"; } break;
case WNNC_NET_DRIVEONWEB: { return L"WNNC_NET_DRIVEONWEB"; } break;
case WNNC_NET_VMWARE: { return L"WNNC_NET_VMWARE"; } break;
case WNNC_NET_RSFX: { return L"WNNC_NET_RSFX"; } break;
case WNNC_NET_MFILES: { return L"WNNC_NET_MFILES"; } break;
case WNNC_NET_MS_NFS: { return L"WNNC_NET_MS_NFS"; } break;
case WNNC_NET_GOOGLE: { return L"WNNC_NET_GOOGLE"; } break;
case WNNC_CRED_MANAGER: { return L"WNNC_CRED_MANAGER"; } break;
default:
return L"Unknown";
break;
}
}
wchar_t *get_font_family_value( unsigned short ff_value )
{
if ( ff_value == 0 )
{
return L"None";
}
static wchar_t buf[ 128 ];
int size = swprintf_s( buf, 512, L"%s%s%s%s%s%s",
( ( ff_value & FF_DONTCARE ) ? L"FF_DONTCARE, " : L"" ),
( ( ff_value & FF_ROMAN ) ? L"FF_ROMAN, " : L"" ),
( ( ff_value & FF_SWISS ) ? L"FF_SWISS, " : L"" ),
( ( ff_value & FF_MODERN ) ? L"FF_MODERN, " : L"" ),
( ( ff_value & FF_SCRIPT ) ? L"FF_SCRIPT, " : L"" ),
( ( ff_value & FF_DECORATIVE ) ? L"FF_DECORATIVE, " : L"" ) );
if ( size > 1 && buf[ size - 1 ] == L' ' )
{
buf[ size - 2 ] = L'\0';
}
return buf;
}
wchar_t *get_font_weight( unsigned int fw )
{
switch ( fw )
{
case FW_DONTCARE: { return L"FW_DONTCARE"; } break;
case FW_THIN: { return L"FW_THIN"; } break;
//case FW_ULTRALIGHT:
case FW_EXTRALIGHT: { return L"FW_EXTRALIGHT / FW_ULTRALIGHT"; } break;
case FW_LIGHT: { return L"FW_LIGHT"; } break;
//case FW_REGULAR:
case FW_NORMAL: { return L"FW_NORMAL / FW_REGULAR"; } break;
case FW_MEDIUM: { return L"FW_MEDIUM"; } break;
//case FW_DEMIBOLD:
case FW_SEMIBOLD: { return L"FW_SEMIBOLD / FW_DEMIBOLD"; } break;
case FW_BOLD: { return L"FW_BOLD"; } break;
//case FW_ULTRABOLD:
case FW_EXTRABOLD: { return L"FW_EXTRABOLD / FW_ULTRABOLD"; } break;
//case FW_BLACK:
case FW_HEAVY: { return L"FW_HEAVY / FW_BLACK"; } break;
default:
return L"Unknown";
break;
}
}
wchar_t *get_color_flags( unsigned short c_flags )
{
if ( c_flags == 0 )
{
return L"None";
}
static wchar_t buf[ 128 ];
int size = swprintf_s( buf, 512, L"%s%s%s%s%s%s%s%s",
( ( c_flags & FOREGROUND_BLUE ) ? L"FOREGROUND_BLUE, " : L"" ),
( ( c_flags & FOREGROUND_GREEN ) ? L"FOREGROUND_GREEN, " : L"" ),
( ( c_flags & FOREGROUND_RED ) ? L"FOREGROUND_RED, " : L"" ),
( ( c_flags & FOREGROUND_INTENSITY ) ? L"FOREGROUND_INTENSITY, " : L"" ),
( ( c_flags & BACKGROUND_BLUE ) ? L"BACKGROUND_BLUE, " : L"" ),
( ( c_flags & BACKGROUND_GREEN ) ? L"BACKGROUND_GREEN, " : L"" ),
( ( c_flags & BACKGROUND_RED ) ? L"BACKGROUND_RED, " : L"" ),
( ( c_flags & BACKGROUND_INTENSITY ) ? L"BACKGROUND_INTENSITY, " : L"" ) );
if ( size > 1 && buf[ size - 1 ] == L' ' )
{
buf[ size - 2 ] = L'\0';
}
return buf;
}
wchar_t *get_special_folder_type( unsigned int sf_type )
{
switch ( sf_type )
{
case SF_Desktop: { return L"Desktop"; } break;
case SF_Internet: { return L"Internet"; } break;
case SF_Programs: { return L"Programs"; } break;
case SF_Controls: { return L"Controls"; } break;
case SF_Printers: { return L"Printers"; } break;
case SF_Personal: { return L"Personal"; } break;
case SF_Favorites: { return L"Favorites"; } break;
case SF_Startup: { return L"Startup"; } break;
case SF_Recent: { return L"Recent"; } break;
case SF_SendTo: { return L"SendTo"; } break;
case SF_BitBucket: { return L"BitBucket"; } break;
case SF_StartMenu: { return L"StartMenu"; } break;
case SF_MyDocuments: { return L"MyDocuments"; } break;
case SF_MyMusic: { return L"MyMusic"; } break;
case SF_MyVideo: { return L"MyVideo"; } break;
case SF_DesktopDirectory: { return L"DesktopDirectory"; } break;
case SF_Drives: { return L"Drives"; } break;
case SF_Network: { return L"Network"; } break;
case SF_Nethood: { return L"Nethood"; } break;
case SF_Fonts: { return L"Fonts"; } break;
case SF_Templates: { return L"Templates"; } break;
case SF_CommonStartMenu: { return L"CommonStartMenu"; } break;
case SF_CommonPrograms: { return L"CommonPrograms"; } break;
case SF_CommonStartup: { return L"CommonStartup"; } break;
case SF_CommonDesktopDirectory: { return L"CommonDesktopDirectory"; } break;
case SF_AppData: { return L"AppData"; } break;
case SF_PrintHood: { return L"PrintHood"; } break;
case SF_LocalAppData: { return L"LocalAppData"; } break;
case SF_AltStartup: { return L"AltStartup"; } break;
case SF_CommonAltStartup: { return L"CommonAltStartup"; } break;
case SF_CommonFavorites: { return L"CommonFavorites"; } break;
case SF_InternetCache: { return L"InternetCache"; } break;
case SF_Cookies: { return L"Cookies"; } break;
case SF_History: { return L"History"; } break;
case SF_CommonAppData: { return L"CommonAppData"; } break;
case SF_Windows: { return L"Windows"; } break;
case SF_System: { return L"System"; } break;
case SF_ProgramFiles: { return L"ProgramFiles"; } break;
case SF_MyPictures: { return L"MyPictures"; } break;
case SF_Profile: { return L"Profile"; } break;
case SF_SystemX86: { return L"SystemX86"; } break;
case SF_ProgramFilesX86: { return L"ProgramFilesX86"; } break;
case SF_ProgramFilesCommon: { return L"ProgramFilesCommon"; } break;
case SF_ProgramFilesCommonX86: { return L"ProgramFilesCommonX86"; } break;
case SF_CommonTemplates: { return L"CommonTemplates"; } break;
case SF_CommonDocuments: { return L"CommonDocuments"; } break;
case SF_CommonAdminTools: { return L"CommonAdminTools"; } break;
case SF_AdminTools: { return L"AdminTools"; } break;
case SF_Connections: { return L"Connections"; } break;
case SF_CommonMusic: { return L"CommonMusic"; } break;
case SF_CommonPictures: { return L"CommonPictures"; } break;
case SF_CommonVideo: { return L"CommonVideo"; } break;
case SF_Resources: { return L"Resources"; } break;
case SF_ResourcesLocalized: { return L"ResourcesLocalized"; } break;
case SF_CommonOEMLinks: { return L"CommonOEMLinks"; } break;
case SF_CDBurnArea: { return L"CDBurnArea"; } break;
case SF_ComputersNearMe: { return L"ComputersNearMe"; } break;
case SF_FlagCreate: { return L"FlagCreate"; } break;
case SF_FlagDontVerify: { return L"FlagDontVerify"; } break;
case SF_FlagNoAlias: { return L"FlagNoAlias"; } break;
case SF_FlagPerUserInit: { return L"FlagPerUserInit"; } break;
case SF_FlagMask: { return L"FlagMask"; } break;
default:
return L"Unknown";
break;
}
return NULL;
}
wchar_t *get_property_type( unsigned int p_type )
{
switch ( p_type )
{
case VT_EMPTY: { return L"VT_EMPTY"; } break;
case VT_NULL: { return L"VT_NULL"; } break;
case VT_I2: { return L"VT_I2"; } break;
case VT_I4: { return L"VT_I4"; } break;
case VT_R4: { return L"VT_R4"; } break;
case VT_R8: { return L"VT_R8"; } break;
case VT_CY: { return L"VT_CY"; } break;
case VT_DATE: { return L"VT_DATE"; } break;
case VT_BSTR: { return L"VT_BSTR"; } break;
case VT_DISPATCH: { return L"VT_DISPATCH"; } break; // Should not be used
case VT_ERROR: { return L"VT_ERROR"; } break;
case VT_BOOL: { return L"VT_BOOL"; } break;
case VT_VARIANT: { return L"VT_VARIANT"; } break; // Should not be used alone
case VT_UNKNOWN: { return L"VT_UNKNOWN"; } break; // Should not be used
case VT_DECIMAL: { return L"VT_DECIMAL"; } break;
case VT_I1: { return L"VT_I1"; } break;
case VT_UI1: { return L"VT_UI1"; } break;
case VT_UI2: { return L"VT_UI2"; } break;
case VT_UI4: { return L"VT_UI4"; } break;
case VT_I8: { return L"VT_I8"; } break;
case VT_UI8: { return L"VT_UI8"; } break;
case VT_INT: { return L"VT_INT"; } break;
case VT_UINT: { return L"VT_UINT"; } break;
case VT_VOID: { return L"VT_VOID"; } break; // Should not be used
case VT_HRESULT: { return L"VT_HRESULT"; } break; // Should not be used
case VT_PTR: { return L"VT_PTR"; } break; // Should not be used
case VT_SAFEARRAY: { return L"VT_SAFEARRAY"; } break; // Should not be used
case VT_CARRAY: { return L"VT_CARRAY"; } break; // Should not be used
case VT_USERDEFINED: { return L"VT_USERDEFINED"; } break; // Should not be used
case VT_LPSTR: { return L"VT_LPSTR"; } break;
case VT_LPWSTR: { return L"VT_LPWSTR"; } break;
case VT_RECORD: { return L"VT_RECORD"; } break; // Should not be used
case VT_INT_PTR: { return L"VT_INT_PTR"; } break; // Should not be used
case VT_UINT_PTR: { return L"VT_UINT_PTR"; } break; // Should not be used
case VT_FILETIME: { return L"VT_FILETIME"; } break;
case VT_BLOB: { return L"VT_BLOB"; } break;
case VT_STREAM: { return L"VT_STREAM"; } break;
case VT_STORAGE: { return L"VT_STORAGE"; } break;
case VT_STREAMED_OBJECT: { return L"VT_STREAMED_OBJECT"; } break;
case VT_STORED_OBJECT: { return L"VT_STORED_OBJECT"; } break;
case VT_BLOB_OBJECT: { return L"VT_BLOB_OBJECT"; } break;
case VT_CF: { return L"VT_CF"; } break;
case VT_CLSID: { return L"VT_CLSID"; } break;
case VT_VERSIONED_STREAM: { return L"VT_VERSIONED_STREAM"; } break;
//case VT_BSTR_BLOB: // Should not be used
case VT_VECTOR: { return L"VT_VECTOR"; } break; // Should not be used alone
case VT_VECTOR | VT_I2: { return L"VT_VECTOR | VT_I2"; } break;
case VT_VECTOR | VT_I4: { return L"VT_VECTOR | VT_I4"; } break;
case VT_VECTOR | VT_R4: { return L"VT_VECTOR | VT_R4"; } break;
case VT_VECTOR | VT_R8: { return L"VT_VECTOR | VT_R8"; } break;
case VT_VECTOR | VT_CY: { return L"VT_VECTOR | VT_CY"; } break;
case VT_VECTOR | VT_DATE : { return L"VT_VECTOR | VT_DATE "; } break;
case VT_VECTOR | VT_BSTR : { return L"VT_VECTOR | VT_BSTR "; } break;
case VT_VECTOR | VT_ERROR : { return L"VT_VECTOR | VT_ERROR "; } break;
case VT_VECTOR | VT_BOOL : { return L"VT_VECTOR | VT_BOOL "; } break;
case VT_VECTOR | VT_VARIANT: { return L"VT_VECTOR | VT_VARIANT"; } break;
case VT_VECTOR | VT_I1: { return L"VT_VECTOR | VT_I1"; } break;
case VT_VECTOR | VT_UI1: { return L"VT_VECTOR | VT_UI1"; } break;
case VT_VECTOR | VT_UI2: { return L"VT_VECTOR | VT_UI2"; } break;
case VT_VECTOR | VT_UI4: { return L"VT_VECTOR | VT_UI4"; } break;
case VT_VECTOR | VT_I8: { return L"VT_VECTOR | VT_I8"; } break;
case VT_VECTOR | VT_UI8: { return L"VT_VECTOR | VT_UI8"; } break;
case VT_VECTOR | VT_LPSTR: { return L"VT_VECTOR | VT_LPSTR"; } break;
case VT_VECTOR | VT_LPWSTR: { return L"VT_VECTOR | VT_LPWSTR"; } break;
case VT_VECTOR | VT_FILETIME: { return L"VT_VECTOR | VT_FILETIME"; } break;
case VT_VECTOR | VT_CF: { return L"VT_VECTOR | VT_CF"; } break;
case VT_VECTOR | VT_CLSID: { return L"VT_VECTOR | VT_CLSID"; } break;
case VT_ARRAY: { return L"VT_ARRAY"; } break; // Should not be used alone
case VT_ARRAY | VT_I2: { return L"VT_ARRAY | VT_I2"; } break;
case VT_ARRAY | VT_I4: { return L"VT_ARRAY | VT_I4"; } break;
case VT_ARRAY | VT_R4: { return L"VT_ARRAY | VT_R4"; } break;
case VT_ARRAY | VT_R8: { return L"VT_ARRAY | VT_R8"; } break;
case VT_ARRAY | VT_CY: { return L"VT_ARRAY | VT_CY"; } break;
case VT_ARRAY | VT_DATE: { return L"VT_ARRAY | VT_DATE"; } break;
case VT_ARRAY | VT_BSTR: { return L"VT_ARRAY | VT_BSTR"; } break;
case VT_ARRAY | VT_ERROR: { return L"VT_ARRAY | VT_ERROR"; } break;
case VT_ARRAY | VT_BOOL: { return L"VT_ARRAY | VT_BOOL"; } break;
case VT_ARRAY | VT_VARIANT: { return L"VT_ARRAY | VT_VARIANT"; } break;
case VT_ARRAY | VT_DECIMAL: { return L"VT_ARRAY | VT_DECIMAL"; } break;
case VT_ARRAY | VT_I1: { return L"VT_ARRAY | VT_I1"; } break;
case VT_ARRAY | VT_UI1: { return L"VT_ARRAY | VT_UI1"; } break;
case VT_ARRAY | VT_UI2: { return L"VT_ARRAY | VT_UI2"; } break;
case VT_ARRAY | VT_UI4: { return L"VT_ARRAY | VT_UI4"; } break;
case VT_ARRAY | VT_INT: { return L"VT_ARRAY | VT_INT"; } break;
case VT_ARRAY | VT_UINT: { return L"VT_ARRAY | VT_UINT"; } break;
case VT_BYREF: { return L"VT_BYREF"; } break; // Should not be used
case VT_RESERVED: { return L"VT_RESERVED"; } break; // Should not be used
case VT_ILLEGAL: { return L"VT_ILLEGAL"; } break; // Should not be used
//case VT_ILLEGALMASKED: // Should not be used
case VT_TYPEMASK: { return L"VT_BSTR_BLOB / VT_ILLEGALMASKED / VT_TYPEMASK"; } break; // Should not be used
default:
return L"Unknown";
break;
}
return NULL;
}
void buffer_to_guid( unsigned char *buffer, char *guid )
{
int offset = sprintf_s( guid, 64, "%.8x-%.4x-%.4x-", *( ( unsigned int * )buffer ), *( ( unsigned short * )buffer + 2 ), *( ( unsigned short * )buffer + 3 ) );
for ( unsigned char i = 8; i < 16; ++i )
{
if ( offset == 23 )
{
guid[ offset ] = '-';
++offset;
}
offset += sprintf_s( guid + offset, 64 - offset, "%.2x", buffer[ i ] );
}
}
void buffer_to_mac( char *buffer, char *mac )
{
unsigned char offset = 0;
for ( unsigned char i = 0; i < 12; ++i )
{
if ( offset == 2 || offset == 5 || offset == 8 || offset == 11 || offset == 14 )
{
mac[ offset++ ] = ':';
}
mac[ offset++ ] = buffer[ i ];
}
}
void hex_dump( unsigned char *buffer, unsigned int buf_length )
{
unsigned int i = 0;
int hex_offset = 0;
int text_offset = 0;
char hex_buf[ 50 ] = { 0 };
char text_buf[ 17 ] = { 0 };
for ( i = 0; i < buf_length; ++i )
{
if ( i > 0 && i % 8 == 0 )
{
if ( i % 16 == 0 )
{
printf( "%s\t%s\n", hex_buf, text_buf );
hex_offset = text_offset = 0;
}
else
{
hex_buf[ hex_offset++ ] = ' ';
}
}
hex_offset += sprintf_s( hex_buf + hex_offset, 50 - hex_offset, "%.02x ", buffer[ i ] );
text_offset += sprintf_s( text_buf + text_offset, 17 - text_offset, "%c", ( buffer[ i ] < 0x21 || ( buffer[ i ] >= 0x7f && buffer[ i ] <= 0x9f ) ) ? '.' : buffer[ i ] );
}
if ( i > 0 && ( ( i % 8 != 0 ) || ( i % 16 == 8 ) ) ) // 15 or less characters filled.
{
printf( hex_buf );
unsigned char r = ( i % 16 >= 8 ? 8 : 16 ) - ( i % 8 );
while ( r-- )
{
printf( " " );
}
printf( "\t%s\n", text_buf );
}
else // 16 characters filled.
{
printf( "%s\t%s\n", hex_buf, text_buf );
}
}
const clsid_type clsid_list[] = {
{ GUID_AddNewPrograms, "AddNewPrograms" },
{ GUID_AdminTools, "AdminTools" },
{ GUID_AppDataLow, "AppDataLow" },
{ GUID_ApplicationShortcuts, "ApplicationShortcuts" },
{ GUID_AppsFolder, "AppsFolder" },
{ GUID_AppUpdates, "AppUpdates" },
{ GUID_CDBurning, "CDBurning" },
{ GUID_ChangeRemovePrograms, "ChangeRemovePrograms" },
{ GUID_CommonAdminTools, "CommonAdminTools" },
{ GUID_CommonOEMLinks, "CommonOEMLinks" },
{ GUID_CommonPrograms, "CommonPrograms" },
{ GUID_CommonStartMenu, "CommonStartMenu" },
{ GUID_CommonStartup, "CommonStartup" },
{ GUID_CommonTemplates, "CommonTemplates" },
{ GUID_ComputerFolder, "ComputerFolder" },
{ GUID_ConflictFolder, "ConflictFolder" },
{ GUID_ConnectionsFolder, "ConnectionsFolder" },
{ GUID_Contacts, "Contacts" },
{ GUID_ControlPanelFolder, "ControlPanelFolder" },
{ GUID_Cookies, "Cookies" },
{ GUID_Desktop, "Desktop" },
{ GUID_DeviceMetadataStore, "DeviceMetadataStore" },
{ GUID_Documents, "Documents" },
{ GUID_DocumentsLibrary, "DocumentsLibrary" },
{ GUID_Downloads, "Downloads" },
{ GUID_Favorites, "Favorites" },
{ GUID_Fonts, "Fonts" },
{ GUID_Games, "Games" },
{ GUID_GameTasks, "GameTasks" },
{ GUID_History, "History" },
{ GUID_HomeGroup, "HomeGroup" },
{ GUID_HomeGroupCurrentUser, "HomeGroupCurrentUser" },
{ GUID_ImplicitAppShortcuts, "ImplicitAppShortcuts" },
{ GUID_InternetCache, "InternetCache" },
{ GUID_InternetFolder, "InternetFolder" },
{ GUID_Libraries, "Libraries" },
{ GUID_Links, "Links" },
{ GUID_LocalAppData, "LocalAppData" },
{ GUID_LocalAppDataLow, "LocalAppDataLow" },
{ GUID_LocalizedResourcesDir, "LocalizedResourcesDir" },
{ GUID_Music, "Music" },
{ GUID_MusicLibrary, "MusicLibrary" },
{ GUID_NetHood, "NetHood" },
{ GUID_NetworkFolder, "NetworkFolder" },
{ GUID_OriginalImages, "OriginalImages" },
{ GUID_PhotoAlbums, "PhotoAlbums" },
{ GUID_Pictures, "Pictures" },
{ GUID_PicturesLibrary, "PicturesLibrary" },
{ GUID_Playlists, "Playlists" },
{ GUID_PrintersFolder, "PrintersFolder" },
{ GUID_PrintHood, "PrintHood" },
{ GUID_Profile, "Profile" },
{ GUID_ProgramData, "ProgramData" },
{ GUID_ProgramFiles, "ProgramFiles" },
{ GUID_ProgramFilesCommon, "ProgramFilesCommon" },
{ GUID_ProgramFilesCommonX64, "ProgramFilesCommonX64" },
{ GUID_ProgramFilesCommonX86, "ProgramFilesCommonX86" },
{ GUID_ProgramFilesX64, "ProgramFilesX64" },
{ GUID_ProgramFilesX86, "ProgramFilesX86" },
{ GUID_Programs, "Programs" },
{ GUID_Public, "Public" },
{ GUID_PublicDesktop, "PublicDesktop" },
{ GUID_PublicDocuments, "PublicDocuments" },
{ GUID_PublicDownloads, "PublicDownloads" },
{ GUID_PublicGameTasks, "PublicGameTasks" },
{ GUID_PublicLibraries, "PublicLibraries" },
{ GUID_PublicMusic, "PublicMusic" },
{ GUID_PublicPictures, "PublicPictures" },
{ GUID_PublicRingtones, "PublicRingtones" },
{ GUID_PublicUserTiles, "PublicUserTiles" },
{ GUID_PublicVideos, "PublicVideos" },
{ GUID_QuickLaunch, "QuickLaunch" },
{ GUID_Recent, "Recent" },
{ GUID_RecordedTV, "RecordedTV" },
{ GUID_RecordedTVLibrary, "RecordedTVLibrary" },
{ GUID_RecycleBin, "RecycleBin" },
{ GUID_ResourceDir, "ResourceDir" },
{ GUID_Ringtones, "Ringtones" },
{ GUID_RoamingAppData, "RoamingAppData" },
{ GUID_RoamingTiles, "RoamingTiles" },
{ GUID_SampleMusic, "SampleMusic" },
{ GUID_SamplePictures, "SamplePictures" },
{ GUID_SamplePlaylists, "SamplePlaylists" },
{ GUID_SampleVideos, "SampleVideos" },
{ GUID_SavedGames, "SavedGames" },
{ GUID_SavedSearches, "SavedSearches" },
{ GUID_SEARCH_CSC, "SEARCH_CSC" },
{ GUID_SEARCH_MAPI, "SEARCH_MAPI" },
{ GUID_SearchHome, "SearchHome" },
{ GUID_SendTo, "SendTo" },
{ GUID_SidebarDefaultParts, "SidebarDefaultParts" },
{ GUID_SidebarParts, "SidebarParts" },
{ GUID_StartMenu, "StartMenu" },
{ GUID_Startup, "Startup" },
{ GUID_SyncManagerFolder, "SyncManagerFolder" },
{ GUID_SyncResults, "SyncResults" },
{ GUID_SyncSetupFolder, "SyncSetupFolder" },
{ GUID_System, "System" },
{ GUID_SystemX86, "SystemX86" },
{ GUID_Templates, "Templates" },
{ GUID_TreeProperties, "TreeProperties" },
{ GUID_UserPinned, "UserPinned" },
{ GUID_UserProfiles, "UserProfiles" },
{ GUID_UserProgramFiles, "UserProgramFiles" },
{ GUID_UserProgramFilesCommon, "UserProgramFilesCommon" },
{ GUID_UsersFiles, "UsersFiles" },
{ GUID_UsersLibraries, "UsersLibraries" },
{ GUID_UsersLibrariesFolder, "UsersLibrariesFolder" },
{ GUID_UserTiles, "UserTiles" },
{ GUID_Videos, "Videos" },
{ GUID_VideosLibrary, "VideosLibrary" },
{ GUID_Windows, "Windows" },
{ GUID_My_Computer, "My Computer" },
{ GUID_My_Documents, "My Documents" },
{ GUID_Control_Panel, "Control Panel" },
{ GUID_Control_Panel2, "Control Panel" },
{ GUID_Internet_Explorer, "Internet Explorer" },
{ GUID_My_Games, "My Games" },
{ GUID_My_Network_Places, "My Network Places" },
{ GUID_Network_Connections, "Network Connections" },
{ GUID_Printers_and_Faxes, "Printers and Faxes" },
{ GUID_Dial_up_Connection, "Dial-up Connection" },
{ GUID_Show_Desktop, "Show Desktop" },
{ GUID_Users, "Users" },
{ GUID_Window_Switcher, "Window Switcher" },
{ GUID_CD_Burner, "CD Burner" },
{ GUID_CSC_Folder, "CSC Folder" },
{ GUID_Search, "Search" },
{ GUID_Help_and_Support, "Help and Support" },
{ GUID_Windows_Security, "Windows Security" },
{ GUID_Run, "Run..." },
{ GUID_Email, "E-mail" },
{ GUID_Set_Program_Access, "Set Program Access and Defaults" },
{ GUID_Start_Menu_Provider, "StartMenuProviderFolder" },
{ GUID_Start_Menu, "Start Menu" },
{ GUID_Search_Results, "Search Results" },
{ NULL, NULL } };
char *get_clsid_type( char *clsid )
{
for ( int i = 0; clsid_list[ i ].clsid != NULL; i++ )
{
if ( memcmp( clsid, clsid_list[ i ].clsid, 16 ) == 0 )
{
return clsid_list[ i ].name;
}
}
return NULL;
}
char *get_prop_id_type( char *guid, unsigned int prop_id )
{
if ( memcmp( guid, "\xe0\x85\x9f\xF2\xF9\x4f\x68\x10\xAB\x91\x08\x00\x2B\x27\xB3\xD9", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.Title"; } break;
case 3: { return "System.Subject"; } break;
case 4: { return "System.Author"; } break;
case 5: { return "System.Keywords"; } break;
case 6: { return "System.Comment"; } break;
case 8: { return "System.Document.LastAuthor"; } break;
case 9: { return "System.Document.RevisionNumber"; } break;
case 10: { return "System.Document.TotalEditingTime"; } break;
case 11: { return "System.Document.DatePrinted"; } break;
case 12: { return "System.Document.DateCreated"; } break;
case 13: { return "System.Document.DateSaved"; } break;
case 14: { return "System.Document.PageCount"; } break;
case 15: { return "System.Document.WordCount"; } break;
case 16: { return "System.Document.CharacterCount"; } break;
case 18: { return "System.ApplicationName"; } break;
}
}
else if ( memcmp( guid, "\x2e\x37\xa3\x56\x9c\xce\xd2\x11\x9f\x0e\x00\x60\x97\xc6\x86\xf6", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.Music.Artist"; } break;
case 4: { return "System.Music.AlbumTitle"; } break;
case 5: { return "System.Media.Year"; } break;
case 7: { return "System.Music.TrackNumber"; } break;
case 8: { return "AudioTimeLength"; } break;
case 11: { return "System.Music.Genre"; } break;
case 12: { return "System.Music.Lyrics"; } break;
case 13: { return "System.Music.AlbumArtist"; } break;
case 33: { return "System.Music.ContentGroupDescription"; } break;
case 34: { return "System.Music.InitialKey"; } break;
case 35: { return "System.Music.BeatsPerMinute"; } break;
case 36: { return "System.Music.Conductor"; } break;
case 37: { return "System.Music.PartOfSet"; } break;
case 38: { return "System.Media.SubTitle"; } break;
case 39: { return "System.Music.Mood"; } break;
case 100: { return "System.Music.AlbumID"; } break;
}
}
else if ( memcmp( guid, "\x30\xf1\x25\xB7\xEF\x47\x1A\x10\xA5\xF1\x02\x60\x8C\x9E\xEB\xAC", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.ItemFolderNameDisplay"; } break;
case 4: { return "System.ItemTypeText"; } break;
case 10: { return "System.ItemTypeText"; } break;
case 12: { return "System.Size"; } break;
case 13: { return "System.FileAttributes"; } break;
case 14: { return "System.DateModified"; } break;
case 15: { return "System.DateCreated"; } break;
case 16: { return "System.DateAccessed"; } break;
case 19: { return "System.Search.Contents"; } break;
case 21: { return "System.FileFRN"; } break;
}
}
else if ( memcmp( guid, "\xa6\x6a\x63\x28\x3D\x95\xD2\x11\xB5\xD6\x00\xC0\x4F\xD9\x18\xD0", 16 ) == 0 )
{
switch ( prop_id )
{
case 0: { return "System.FindData"; } break;
case 2: { return "System.DescriptionID"; } break;
case 5: { return "System.ComputerName"; } break;
case 6: { return "System.NamespaceCLSID"; } break;
case 8: { return "System.ItemPathDisplayNarrow"; } break;
case 9: { return "System.PerceivedType"; } break;
case 11: { return "System.ItemType"; } break;
case 12: { return "System.FileCount"; } break;
case 14: { return "System.TotalFileSize"; } break;
case 24: { return "System.ParsingName"; } break;
case 25: { return "System.SFGAOFlags"; } break;
case 29: { return "System.ContainedItems"; } break;
case 30: { return "System.ParsingPath"; } break;
case 33: { return "System.IsSendToTarget"; } break;
}
}
else if ( memcmp( guid, "\x02\xd5\xcd\xd5\x9c\x2e\x1b\x10\x93\x97\x08\x00\x2b\x2c\xf9\xae", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.Category"; } break;
case 3: { return "System.Document.PresentationFormat"; } break;
case 4: { return "System.Document.ByteCount"; } break;
case 5: { return "System.Document.LineCount"; } break;
case 6: { return "System.Document.ParagraphCount"; } break;
case 7: { return "System.Document.SlideCount"; } break;
case 8: { return "System.Document.NoteCount"; } break;
case 9: { return "System.Document.HiddenSlideCount"; } break;
case 10: { return "System.Document.MultimediaClipCount"; } break;
case 14: { return "System.Document.Manager"; } break;
case 15: { return "System.Company"; } break;
case 26: { return "System.ContentType"; } break;
case 27: { return "System.ContentStatus"; } break;
case 28: { return "System.Language"; } break;
case 29: { return "System.Document.Version"; } break;
}
}
else if ( memcmp( guid, "\x7f\xb6\x76\x5d\x3d\x9b\xbb\x44\xb6\xae\x25\xda\x4f\x63\x8a\x67", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.IsPinnedToNameSpaceTree"; } break;
case 3: { return "System.IsDefaultSaveLocation"; } break;
case 5: { return "System.IsDefaultNonOwnerSaveLocation"; } break;
case 6: { return "System.OwnerSID"; } break;
case 8: { return "System.IsLocationSupported"; } break;
}
}
else if ( memcmp( guid, "\x53\x7d\xef\x0C\x64\xfa\xD1\x11\xA2\x03\x00\x00\xF8\x1F\xED\xEE", 16 ) == 0 )
{
switch ( prop_id )
{
case 3: { return "System.FileDescription"; } break;
case 4: { return "System.FileVersion"; } break;
case 5: { return "System.InternalName"; } break;
case 6: { return "System.OriginalFileName"; } break;
case 7: { return "System.Software.ProductName"; } break;
case 8: { return "System.Software.ProductVersion"; } break;
case 9: { return "System.Trademarks"; } break;
}
}
else if ( memcmp( guid, "\x92\x04\x44\x64\x8B\x4c\xD1\x11\x70\x8b\x08\x00\x36\xB1\x1A\x03", 16 ) == 0 )
{
switch ( prop_id )
{
case 9: { return "System.Rating"; } break;
case 11: { return "System.Copyright"; } break;
case 12: { return "System.ShareUserRating"; } break;
case 13: { return "System.Media.ClassPrimaryID"; } break;
case 14: { return "System.Media.ClassSecondaryID"; } break;
case 15: { return "System.Media.DVDID"; } break;
case 16: { return "System.Media.MCDI"; } break;
case 17: { return "System.Media.MetadataContentProvider"; } break;
case 18: { return "System.Media.ContentDistributor"; } break;
case 19: { return "System.Music.Composer"; } break;
case 20: { return "System.Video.Director"; } break;
case 21: { return "System.ParentalRating"; } break;
case 22: { return "System.Media.Producer"; } break;
case 23: { return "System.Media.Writer"; } break;
case 24: { return "System.Media.CollectionGroupID"; } break;
case 25: { return "System.Media.CollectionID"; } break;
case 26: { return "System.Media.ContentID"; } break;
case 27: { return "System.Media.CreatorApplication"; } break;
case 28: { return "System.Media.CreatorApplicationVersion"; } break;
case 30: { return "System.Media.Publisher"; } break;
case 31: { return "System.Music.Period"; } break;
case 32: { return "System.Media.AuthorUrl"; } break;
case 33: { return "System.Media.PromotionUrl"; } break;
case 34: { return "System.Media.UserWebUrl"; } break;
case 35: { return "System.Media.UniqueFileIdentifier"; } break;
case 36: { return "System.Media.EncodedBy"; } break;
case 38: { return "System.Media.ProtectionType"; } break;
case 39: { return "System.Media.ProviderRating"; } break;
case 40: { return "System.Media.ProviderStyle"; } break;
case 41: { return "System.Media.UserNoAutoInfo"; } break;
}
}
else if ( memcmp( guid, "\x21\x4a\x94\xc9\x06\xa4\xfe\x48\x82\x25\xae\xc7\xe2\x4c\x21\x1b", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.PropList.FullDetails"; } break;
case 3: { return "System.PropList.TileInfo"; } break;
case 4: { return "System.PropList.InfoTip"; } break;
case 5: { return "System.PropList.QuickTip"; } break;
case 6: { return "System.PropList.PreviewTitle"; } break;
case 8: { return "System.PropList.PreviewDetails"; } break;
case 9: { return "System.PropList.ExtendedTileInfo"; } break;
case 10: { return "System.PropList.FileOperationPrompt"; } break;
case 11: { return "System.PropList.ConflictPrompt"; } break;
case 13: { return "System.PropList.ContentViewModeForBrowse"; } break;
case 14: { return "System.PropList.ContentViewModeForSearch"; } break;
case 17: { return "System.InfoTipText"; } break;
case 500: { return "System.LayoutPattern.ContentViewModeForBrowse"; } break;
case 501: { return "System.LayoutPattern.ContentViewModeForSearch"; } break;
}
}
else if ( memcmp( guid, "\x90\x1c\x69\x49\x17\x7e\x1A\x10\xA9\x1C\x08\x00\x2B\x2E\xCD\xA9", 16 ) == 0 )
{
switch ( prop_id )
{
case 3: { return "System.Search.Rank"; } break;
case 4: { return "System.Search.HitCount"; } break;
case 5: { return "System.Search.EntryID"; } break;
case 8: { return "System.Search.ReverseFileName"; } break;
case 9: { return "System.ItemUrl"; } break;
case 10: { return "System.ContentUrl"; } break;
}
}
else if ( memcmp( guid, "\x40\xe8\x3e\x1e\x2b\xbc\x6c\x47\x82\x37\x2a\xcd\x1a\x83\x9b\x22", 16 ) == 0 )
{
switch ( prop_id )
{
case 3: { return "System.Kind"; } break;
case 6: { return "System.FullText"; } break;
}
}
else if ( memcmp( guid, "\xb1\x16\x6d\x44\xAD\x8d\x70\x48\xA7\x48\x40\x2E\xA4\x3D\x78\x8C", 16 ) == 0 )
{
switch ( prop_id )
{
case 100: { return "System.ThumbnailCacheId"; } break;
}
}
else if ( memcmp( guid, "\x90\x1c\x69\x49\x17\x7e\x1A\x10\xA9\x1C\x08\x00\x2B\x2E\xCD\xA9", 16 ) == 0 )
{
switch ( prop_id )
{
case 3: { return "System.Search.Rank"; } break;
case 4: { return "System.Search.HitCount"; } break;
case 5: { return "System.Search.EntryID"; } break;
case 8: { return "System.Search.ReverseFileName"; } break;
case 9: { return "System.ItemUrl"; } break;
case 10: { return "System.ContentUrl"; } break;
}
}
else if ( memcmp(guid, "\xed\x30\xbd\xDA\x43\x00\x89\x47\xA7\xF8\xD0\x13\xA4\x73\x66\x22", 16 ) == 0 )
{
switch ( prop_id )
{
case 100: { return "System.ItemFolderPathDisplayNarrow"; } break;
}
}
else if ( memcmp( guid, "\x8f\x04\x44\x64\x8B\x4c\xD1\x11\x8B\x70\x08\x00\x36\xB1\x1A\x03", 16 ) == 0 )
{
switch ( prop_id )
{
case 3: { return "System.Image.HorizontalSize"; } break;
case 4: { return "System.Image.VerticalSize"; } break;
case 5: { return "System.Image.HorizontalResolution"; } break;
case 6: { return "System.Image.VerticalResolution"; } break;
case 7: { return "System.Image.BitDepth"; } break;
case 12: { return "System.Media.FrameCount"; } break;
case 13: { return "System.Image.Dimensions"; } break;
}
}
else if ( memcmp( guid, "\x90\x04\x44\x64\x8B\x4c\xD1\x11\x8B\x70\x08\x00\x36\xB1\x1A\x03", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.Audio.Format"; } break;
case 3: { return "System.Media.Duration"; } break;
case 4: { return "System.Audio.EncodingBitrate"; } break;
case 5: { return "System.Audio.SampleRate"; } break;
case 6: { return "System.Audio.SampleSize"; } break;
case 7: { return "System.Audio.ChannelCount"; } break;
case 8: { return "System.Audio.StreamNumber"; } break;
case 9: { return "System.Audio.StreamName"; } break;
case 10: { return "System.Audio.Compression"; } break;
}
}
else if ( memcmp( guid, "\x91\x04\x44\x64\x8B\x4c\xD1\x11\x8B\x70\x08\x00\x36\xB1\x1A\x03", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.Video.StreamName"; } break;
case 3: { return "System.Video.FrameWidth"; } break;
case 4: { return "System.Video.FrameHeight"; } break;
case 6: { return "System.Video.FrameRate"; } break;
case 8: { return "System.Video.EncodingBitrate"; } break;
case 9: { return "System.Video.SampleSize"; } break;
case 10: { return "System.Video.Compression"; } break;
case 11: { return "System.Video.StreamNumber"; } break;
case 42: { return "System.Video.HorizontalAspectRatio"; } break;
case 43: { return "System.Video.TotalBitrate"; } break;
case 44: { return "System.Video.FourCC"; } break;
case 45: { return "System.Video.VerticalAspectRatio"; } break;
case 46: { return "System.Video.TranscodedForSync"; } break;
}
}
else if ( memcmp( guid, "\x91\x04\x44\x64\x8B\x4c\xD1\x11\x8B\x70\x08\x00\x36\xB1\x1A\x03", 16 ) == 0 )
{
switch ( prop_id )
{
case 9: { return "System.Rating"; } break;
case 11: { return "System.Copyright"; } break;
case 12: { return "System.ShareUserRating"; } break;
case 13: { return "System.Media.ClassPrimaryID"; } break;
case 14: { return "System.Media.ClassSecondaryID"; } break;
case 15: { return "System.Media.DVDID"; } break;
case 16: { return "System.Media.MCDI"; } break;
case 17: { return "System.Media.MetadataContentProvider"; } break;
case 18: { return "System.Media.ContentDistributor"; } break;
case 19: { return "System.Music.Composer"; } break;
case 20: { return "System.Video.Director"; } break;
case 21: { return "System.ParentalRating"; } break;
case 22: { return "System.Media.Producer"; } break;
case 23: { return "System.Media.Writer"; } break;
case 24: { return "System.Media.CollectionGroupID"; } break;
case 25: { return "System.Media.CollectionID"; } break;
case 26: { return "System.Media.ContentID"; } break;
case 27: { return "System.Media.CreatorApplication"; } break;
case 28: { return "System.Media.CreatorApplicationVersion"; } break;
case 30: { return "System.Media.Publisher"; } break;
case 31: { return "System.Music.Period"; } break;
case 32: { return "System.Media.AuthorUrl"; } break;
case 33: { return "System.Media.PromotionUrl"; } break;
case 34: { return "System.Media.UserWebUrl"; } break;
case 35: { return "System.Media.UniqueFileIdentifier"; } break;
case 36: { return "System.Media.EncodedBy"; } break;
case 38: { return "System.Media.ProtectionType"; } break;
case 39: { return "System.Media.ProviderRating"; } break;
case 40: { return "System.Media.ProviderStyle"; } break;
case 41: { return "System.Media.UserNoAutoInfo"; } break;
}
}
else if ( memcmp( guid, "\xa1\x1d\xb8\x14\x35\x01\x31\x4d\x96\xD9\x6C\xBF\xC9\x67\x1A\x99", 16 ) == 0 )
{
switch ( prop_id )
{
case 259: { return "System.Image.Compression"; } break;
case 271: { return "System.Photo.CameraManufacturer"; } break;
case 272: { return "System.Photo.CameraModel"; } break;
case 273: { return "System.Photo.CameraSerialNumber"; } break;
case 274: { return "System.Photo.Orientation"; } break;
case 305: { return "System.SoftwareUsed"; } break;
case 18248: { return "System.Photo.Event"; } break;
case 18258: { return "System.DateImported"; } break;
case 33434: { return "System.Photo.ExposureTime"; } break;
case 33437: { return "System.Photo.FNumber"; } break;
case 34850: { return "System.Photo.ExposureProgram"; } break;
case 34855: { return "System.Photo.ISOSpeed"; } break;
case 36867: { return "System.Photo.DateTaken"; } break;
case 37377: { return "System.Photo.ShutterSpeed"; } break;
case 37378: { return "System.Photo.Aperture"; } break;
case 37380: { return "System.Photo.ExposureBias"; } break;
case 37382: { return "System.Photo.SubjectDistance"; } break;
case 37383: { return "System.Photo.MeteringMode"; } break;
case 37384: { return "System.Photo.LightSource"; } break;
case 37385: { return "System.Photo.Flash"; } break;
case 37386: { return "System.Photo.FocalLength"; } break;
case 40961: { return "System.Image.ColorSpace"; } break;
case 41483: { return "System.Photo.FlashEnergy"; } break;
}
}
else if ( memcmp( guid, "\x3c\x0a\xf1\xE4\xE6\x49\x5D\x40\x82\x88\xA2\x3B\xD4\xEE\xAA\x6C", 16 ) == 0 )
{
switch ( prop_id )
{
case 100: { return "System.FileExtension"; } break;
}
}
else if ( memcmp( guid, "\xb4\x74\xdb\xF7\x87\x42\x03\x41\xAF\xBA\xF1\xB1\x3D\xCD\x75\xCF", 16 ) == 0 )
{
switch ( prop_id )
{
case 100: { return "System.ItemDate"; } break;
}
}
else if ( memcmp( guid, "\xe4\x19\xac\xAE\xAE\x89\x08\x45\xB9\xB7\xBB\x86\x7A\xBE\xE2\xED", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.DRM.IsProtected"; } break;
}
}
else if ( memcmp( guid, "\x4c\x58\xe0\xE3\x88\xb7\x5A\x4a\xBB\x20\x7F\x5A\x44\xC9\xAC\xDD", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.Message.BccAddress"; } break;
case 3: { return "System.Message.BccName"; } break;
case 4: { return "System.Message.CcAddress"; } break;
case 5: { return "System.Message.CcName"; } break;
case 6: { return "System.ItemFolderPathDisplay"; } break;
case 7: { return "System.ItemPathDisplay"; } break;
case 9: { return "System.Communication.AccountName"; } break;
case 10: { return "System.IsRead"; } break;
case 11: { return "System.Importance"; } break;
case 12: { return "System.FlagStatus"; } break;
case 13: { return "System.Message.FromAddress"; } break;
case 14: { return "System.Message.FromName"; } break;
case 15: { return "System.Message.Store"; } break;
case 16: { return "System.Message.ToAddress"; } break;
case 17: { return "System.Message.ToName"; } break;
case 18: { return "System.Contact.WebPage"; } break;
case 19: { return "System.Message.DateSent"; } break;
case 20: { return "System.Message.DateReceived"; } break;
case 21: { return "System.Message.AttachmentNames"; } break;
}
}
else if ( memcmp( guid, "\x53\x29\x12\xfd\x93\xfa\xf7\x4e\x92\xc3\x04\xc9\x46\xb2\xf7\xc8", 16 ) == 0 )
{
switch ( prop_id )
{
case 100: { return "System.Music.DisplayArtist"; } break;
}
}
else if ( memcmp( guid, "\x55\x28\x4c\x9F\x79\x9f\x39\x4b\xA8\xD0\xE1\xD4\x2D\xE1\xD5\xF3", 16 ) == 0 )
{
switch ( prop_id )
{
case 2: { return "System.AppUserModel.RelaunchCommand"; } break;
case 3: { return "System.AppUserModel.RelaunchIconResource"; } break;
case 4: { return "System.AppUserModel.RelaunchDisplayNameResource"; } break;
case 5: { return "System.AppUserModel.ID"; } break;
case 6: { return "System.AppUserModel.IsDestListSeparator"; } break;
case 8: { return "System.AppUserModel.ExcludeFromShowInNewInstall"; } break;
case 9: { return "System.AppUserModel.PreventPinning"; } break;
}
}
return NULL;
}
void write_html( HANDLE hFile, wchar_t *buffer, unsigned int &offset )
{
if ( offset > 0 )
{
DWORD written = 0;
int write_length = WideCharToMultiByte( CP_UTF8, 0, buffer, -1, NULL, 0, NULL, NULL );
char *utf8_buf = ( char * )malloc( sizeof( char ) * write_length ); // Includes NULL character.
WideCharToMultiByte( CP_UTF8, 0, buffer, -1, utf8_buf, write_length, NULL, NULL );
WriteFile( hFile, utf8_buf, write_length - 1, &written, NULL );
free( utf8_buf );
offset = 0;
}
}
void write_csv( HANDLE hFile, wchar_t *buffer, unsigned int &offset )
{
if ( offset > 0 )
{
DWORD written = 0;
int write_length = WideCharToMultiByte( CP_UTF8, 0, buffer, -1, NULL, 0, NULL, NULL );
char *utf8_buf = ( char * )malloc( sizeof( char ) * write_length ); // Includes NULL character.
WideCharToMultiByte( CP_UTF8, 0, buffer, -1, utf8_buf, write_length, NULL, NULL );
WriteFile( hFile, utf8_buf, write_length - 1, &written, NULL );
free( utf8_buf );
offset = 0;
}
}
char *random_string()
{
static const char rs[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static char buf[ 11 ];
static unsigned int ran_count = 0;
srand( GetTickCount() + ran_count );
ran_count = ++ran_count % 65535;
for ( int i = 0; i < 10; ++i )
{
buf[ i ] = rs[ rand() % ( sizeof( rs ) - 1 ) ];
}
buf[ 10 ] = 0;
return buf;
}
void write_html_dump( HANDLE hFile, wchar_t *buffer, unsigned int &offset, wchar_t *text, unsigned char *dump_buffer, unsigned int dump_length )
{
char *rs = random_string();
offset += swprintf( buffer + offset, BUFFER_SIZE - offset, L"%s <a href=\"\" onclick=\"t(this,\'%S\');return false;\">Show</a><div id=\"%S\" style=\"display:none\"><pre>", text, rs, rs );
write_html( hFile, buffer, offset );
unsigned int i = 0;
int out_offset = 0;
int hex_offset = 0;
int text_offset = 0;
wchar_t out_buf[ 8193 ];
char hex_buf[ 50 ] = { 0 };
char text_buf[ 65 ] = { 0 }; // We're going to escape < and > with < and > So the maximum size will be 4 times 16, if all characters are <.
int write_length;
char *utf8_buf;
DWORD written = 0;
for ( i = 0; i < dump_length; ++i )
{
if ( i > 0 && i % 8 == 0 )
{
if ( i % 16 == 0 )
{
out_offset += swprintf_s( out_buf + out_offset, 8193 - out_offset, ( i > 16 ? L"\n%S\t%S" : L"%S\t%S" ), hex_buf, text_buf );
if ( out_offset >= 4096 )
{
write_length = WideCharToMultiByte( CP_UTF8, 0, out_buf, -1, NULL, 0, NULL, NULL );
utf8_buf = ( char * )malloc( sizeof( char ) * write_length ); // Includes NULL character.
WideCharToMultiByte( CP_UTF8, 0, out_buf, -1, utf8_buf, write_length, NULL, NULL );
WriteFile( hFile, utf8_buf, write_length - 1, &written, NULL );
free( utf8_buf );
out_offset = 0;
}
hex_offset = text_offset = 0;
}
else
{
hex_buf[ hex_offset++ ] = ' ';
}
}
hex_offset += sprintf_s( hex_buf + hex_offset, 50 - hex_offset, "%.02x ", dump_buffer[ i ] );
if ( dump_buffer[ i ] == '<' )
{
text_offset += sprintf_s( text_buf + text_offset, 65 - text_offset, "<" );
}
else if ( dump_buffer[ i ] == '>' )
{
text_offset += sprintf_s( text_buf + text_offset, 65 - text_offset, ">" );
}
else if ( dump_buffer[ i ] == '&' )
{
text_offset += sprintf_s( text_buf + text_offset, 65 - text_offset, "&" );
}
else
{
text_offset += sprintf_s( text_buf + text_offset, 65 - text_offset, "%c", ( dump_buffer[ i ] < 0x21 || ( dump_buffer[ i ] >= 0x7f && dump_buffer[ i ] <= 0x9f ) ) ? '.' : dump_buffer[ i ] );
}
}
// Dump whatever we didn't write to out_buf.
if ( out_offset > 0 )
{
write_length = WideCharToMultiByte( CP_UTF8, 0, out_buf, -1, NULL, 0, NULL, NULL );
utf8_buf = ( char * )malloc( sizeof( char ) * write_length ); // Includes NULL character.
WideCharToMultiByte( CP_UTF8, 0, out_buf, -1, utf8_buf, write_length, NULL, NULL );
WriteFile( hFile, utf8_buf, write_length - 1, &written, NULL );
free( utf8_buf );
out_offset = 0;
}
// Write to out_buf what we have left in hex_buf and text_buf.
if ( i > 0 && ( ( i % 8 != 0 ) || ( i % 16 == 8 ) ) ) // 15 or less characters filled.
{
out_offset += swprintf_s( out_buf + out_offset, 8193 - out_offset, L"\n%S", hex_buf );
unsigned char r = ( i % 16 >= 8 ? 8 : 16 ) - ( i % 8 );
while ( r-- )
{
out_offset += swprintf_s( out_buf + out_offset, 8193 - out_offset, L" " );
}
out_offset += swprintf_s( out_buf + out_offset, 8193 - out_offset, L"\t%S", text_buf );
}
else // 16 characters filled.
{
out_offset += swprintf_s( out_buf + out_offset, 8193 - out_offset, L"\n%S\t%S", hex_buf, text_buf );
}
write_length = WideCharToMultiByte( CP_UTF8, 0, out_buf, -1, NULL, 0, NULL, NULL );
utf8_buf = ( char * )malloc( sizeof( char ) * write_length ); // Includes NULL character.
WideCharToMultiByte( CP_UTF8, 0, out_buf, -1, utf8_buf, write_length, NULL, NULL );
WriteFile( hFile, utf8_buf, write_length - 1, &written, NULL );
free( utf8_buf );
offset += swprintf( buffer + offset, BUFFER_SIZE - offset, L"</pre></div><br />" );
}
wchar_t *escape_html_unicode( wchar_t *buf )
{
// If a string consists of all & then each will be escaped as such: & In total, we have a string that's 5 times the original length plus the NULL character.
// Let's see if there's actually a character before we allocate memory.
if ( wcschr( buf, L'<' ) != NULL || wcschr( buf, L'>' ) != NULL || wcschr( buf, L'&' ) != NULL )
{
unsigned int string_length = ( 5 * wcslen( buf ) ) + 1;
wchar_t *out = ( wchar_t * )malloc( sizeof( wchar_t ) * string_length );
unsigned int out_offset = 0;
while ( *buf != NULL )
{
if ( *buf == L'<' )
{
wmemcpy_s( out + out_offset, string_length - out_offset, L"<", 4 );
out_offset += 4;
}
else if ( *buf == L'>' )
{
wmemcpy_s( out + out_offset, string_length - out_offset, L">", 4 );
out_offset += 4;
}
else if ( *buf == L'&' )
{
wmemcpy_s( out + out_offset, string_length - out_offset, L"&", 5 );
out_offset += 5;
}
else
{
out[ out_offset++ ] = *buf;
}
++buf;
}
out[ out_offset ] = L'\0';
return out;
}
return NULL;
}
char *escape_html_ascii( char *buf )
{
// If a string consists of all & then each will be escaped as such: & In total, we have a string that's 5 times the original length plus the NULL character.
// Let's see if there's actually a character before we allocate memory.
if ( strchr( buf, L'<' ) != NULL || strchr( buf, L'>' ) != NULL || strchr( buf, L'&' ) != NULL )
{
unsigned int string_length = ( 5 * strlen( buf ) ) + 1;
char *out = ( char * )malloc( sizeof( char ) * string_length );
unsigned int out_offset = 0;
while ( *buf != NULL )
{
if ( *buf == '<' )
{
memcpy_s( out + out_offset, string_length - out_offset, "<", 4 );
out_offset += 4;
}
else if ( *buf == '>' )
{
memcpy_s( out + out_offset, string_length - out_offset, ">", 4 );
out_offset += 4;
}
else if ( *buf == '&' )
{
memcpy_s( out + out_offset, string_length - out_offset, "&", 5 );
out_offset += 5;
}
else
{
out[ out_offset++ ] = *buf;
}
++buf;
}
out[ out_offset ] = '\0';
return out;
}
return NULL;
}
wchar_t *escape_string_unicode( wchar_t *buf )
{
// If a string consists of all " then each will be escaped as such: "" In total, we have a string that's 2 times the original length plus the NULL character.
unsigned int string_length = 0;
wchar_t *out = NULL;
unsigned int out_offset = 0;
wchar_t *last_pos = buf;
wchar_t *cur_pos = wcschr( buf, L'\"' );
// Let's see if there's actually a character before we allocate memory.
if ( cur_pos != NULL )
{
string_length = ( 2 * wcslen( buf ) ) + 1;
out = ( wchar_t * )malloc( sizeof( wchar_t ) * string_length );
while ( cur_pos != NULL )
{
unsigned int run_length = cur_pos - last_pos;
wmemcpy_s( out + out_offset, string_length - out_offset, last_pos, run_length );
out_offset += run_length;
wmemcpy_s( out + out_offset, string_length - out_offset, L"\"\"", 2 );
out_offset += 2;
last_pos = cur_pos + 1;
cur_pos = wcschr( last_pos, '\"' );
}
swprintf_s( out + out_offset, string_length - out_offset, L"%s", last_pos );
}
return out;
}
char *escape_string_ascii( char *buf )
{
// If a string consists of all " then each will be escaped as such: "" In total, we have a string that's 2 times the original length plus the NULL character.
unsigned int string_length = 0;
char *out = NULL;
unsigned int out_offset = 0;
char *last_pos = buf;
char *cur_pos = strchr( buf, '\"' );
// Let's see if there's actually a character before we allocate memory.
if ( cur_pos != NULL )
{
string_length = ( 2 * strlen( buf ) ) + 1;
out = ( char * )malloc( sizeof( char ) * string_length );
while ( cur_pos != NULL )
{
unsigned int run_length = cur_pos - last_pos;
memcpy_s( out + out_offset, string_length - out_offset, last_pos, run_length );
out_offset += run_length;
memcpy_s( out + out_offset, string_length - out_offset, "\"\"", 2 );
out_offset += 2;
last_pos = cur_pos + 1;
cur_pos = strchr( last_pos, '\"' );
}
sprintf_s( out + out_offset, string_length - out_offset, "%s", last_pos );
}
return out;
}
| [
"defeatthefreak@gmail.com"
] | defeatthefreak@gmail.com |
d0726d9aa3be9c6bbc874bdc43bba44d2db0fcf4 | 265f2c427126a18f6fe7a72e3ffc4683888e4330 | /CoreAudioUtilityClasses/CoreAudio/PublicUtility/CACFDistributedNotification.cpp | 28ca397b686253bb23f40390fe169bf794d2a6de | [] | no_license | ocrickard/CocoaSampleCode | 39d05f36c58918d89958df4f2b1c8116c141a7d5 | f81bc9e391368dc8c34e762dd45e59f329a4d4f7 | refs/heads/master | 2021-01-15T17:56:17.895338 | 2013-04-16T09:57:24 | 2013-04-16T09:57:24 | 11,711,657 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,112 | cpp | /*
File: CACFDistributedNotification.cpp
Abstract: CACFDistributedNotification.h
Version: 1.0.2
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2012 Apple Inc. All Rights Reserved.
*/
//==================================================================================================
// Includes
//==================================================================================================
// Self Include
#include "CACFDistributedNotification.h"
// PublicUtility Includes
#include "CADebugMacros.h"
//==================================================================================================
// CACFDistributedNotification
//==================================================================================================
void CACFDistributedNotification::AddObserver(const void* inObserver, CFNotificationCallback inCallback, CFStringRef inName, CFNotificationSuspensionBehavior inSuspensionBehavior)
{
#if !TARGET_OS_IPHONE
CFNotificationCenterRef theCenter = CFNotificationCenterGetDistributedCenter();
CFNotificationSuspensionBehavior theSuspensionBehavior = inSuspensionBehavior;
#else
#pragma unused(inSuspensionBehavior)
CFNotificationCenterRef theCenter = CFNotificationCenterGetDarwinNotifyCenter();
CFNotificationSuspensionBehavior theSuspensionBehavior = 0;
#endif
CFNotificationCenterAddObserver(theCenter, inObserver, inCallback, inName, NULL, theSuspensionBehavior);
}
void CACFDistributedNotification::RemoveObserver(const void* inObserver, CFStringRef inName)
{
#if !TARGET_OS_IPHONE
CFNotificationCenterRef theCenter = CFNotificationCenterGetDistributedCenter();
#else
CFNotificationCenterRef theCenter = CFNotificationCenterGetDarwinNotifyCenter();
#endif
CFNotificationCenterRemoveObserver(theCenter, inObserver, inName, NULL);
}
void CACFDistributedNotification::PostNotification(CFStringRef inName, CFDictionaryRef inUserInfo, bool inPostToAllSessions)
{
#if !TARGET_OS_IPHONE
CFNotificationCenterRef theCenter = CFNotificationCenterGetDistributedCenter();
CFDictionaryRef theUserInfo = inUserInfo;
CFOptionFlags theFlags = kCFNotificationDeliverImmediately;
if(inPostToAllSessions)
{
theFlags += kCFNotificationPostToAllSessions;
}
#else
// flag unsupported features
Assert(inUserInfo == NULL, "CACFDistributedNotification::PostNotification: distributed notifications do not support a payload");
Assert(inPostToAllSessions, "CACFDistributedNotification::PostNotification: distributed notifications do not support per-session delivery");
CFNotificationCenterRef theCenter = CFNotificationCenterGetDarwinNotifyCenter();
CFDictionaryRef theUserInfo = NULL;
CFOptionFlags theFlags = 0;
#endif
CFNotificationCenterPostNotificationWithOptions(theCenter, inName, NULL, theUserInfo, theFlags);
}
| [
"tearnon@live.com"
] | tearnon@live.com |
b8ce1235b0a0d0d313fa0a6738b96f438f5ee40f | c33ebb6bbfcbee2a8e92a3b6e9b2dcd4b7de02b4 | /src/behaviour-tree/tasks/task-mine-tunnel.cpp | aa8fd77c084d8200aaaff6d4df7653c63cb9d929 | [
"MIT"
] | permissive | xterminal86/nrogue | 31c44bcb734b5f8516a726d9609f10d99a647336 | 4f2a3c65463fa0225dfe8834ae5bd237b811b594 | refs/heads/master | 2023-08-08T02:47:01.107493 | 2023-07-28T13:10:38 | 2023-07-28T13:10:38 | 150,626,056 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,757 | cpp | #include "task-mine-tunnel.h"
#include "game-object.h"
#include "map.h"
#include "blackboard.h"
#include "equipment-component.h"
#include "item-component.h"
TaskMineTunnel::TaskMineTunnel(GameObject* objectToControl, bool ignorePickaxe)
: Node(objectToControl)
{
_equipment = _objectToControl->GetComponent<EquipmentComponent>();
_ignorePickaxe = ignorePickaxe;
}
// =============================================================================
BTResult TaskMineTunnel::Run()
{
//DebugLog("[TaskMine]\n");
bool equipmentFail = (_equipment == nullptr
|| _equipment->EquipmentByCategory[EquipmentCategory::WEAPON][0] == nullptr);
if (!_ignorePickaxe && equipmentFail)
{
return BTResult::Failure;
}
int x = _objectToControl->PosX;
int y = _objectToControl->PosY;
int lx = x - 1;
int ly = y - 1;
int hx = x + 1;
int hy = y + 1;
std::vector<Position> toCheck =
{
{ lx, y }, { hx, y }, { x, ly }, { x, hy }
};
//
// Searching for any kind of
//
// ##
// .# <-
// ##
//
// Meaning number of walls around actor should be 3
// and number of walls around the wall to tunnel into
// should be at least 2.
//
int countActor = Map::Instance().CountWallsOrthogonal(x, y);
if (countActor < 3)
{
return BTResult::Failure;
}
//
// Find that empty spot behind the character facing the wall
// we need to tunnel into
//
// .##
// ->.X#
// .##
//
Position found = { -1, -1 };
for (auto& p : toCheck)
{
if (Map::Instance().CurrentLevel->StaticMapObjects[p.X][p.Y] == nullptr)
{
found = p;
break;
}
}
if (found.X == -1)
{
return BTResult::Failure;
}
//
// Wall should be 2 units in the corresponding direction
//
if (found.X > x) found.X -= 2;
else if (found.X < x) found.X += 2;
else if (found.Y > y) found.Y -= 2;
else if (found.Y < y) found.Y += 2;
auto& so = Map::Instance().CurrentLevel->StaticMapObjects[found.X][found.Y];
if (!Util::IsInsideMap(found, Map::Instance().CurrentLevel->MapSize) || so == nullptr)
{
return BTResult::Failure;
}
if (so->Type != GameObjectType::PICKAXEABLE)
{
return BTResult::Failure;
}
if (!_ignorePickaxe)
{
Util::TryToDamageEquipment(_objectToControl, EquipmentCategory::WEAPON, -1);
}
Map::Instance().CurrentLevel->StaticMapObjects[found.X][found.Y]->Attrs.HP.SetMin(0);
Map::Instance().CurrentLevel->StaticMapObjects[found.X][found.Y]->IsDestroyed = true;
_objectToControl->FinishTurn();
auto minedPos = Util::StringFormat("%i,%i", found.X, found.Y);
Blackboard::Instance().Set(_objectToControl->ObjectId(), { Strings::BlackboardKeyLastMinedPos, minedPos });
return BTResult::Success;
}
| [
"xterminal86@gmail.com"
] | xterminal86@gmail.com |
b29c26d317ab06592493a47fdf89ee5317f87348 | b86fae199d0d1eb62be6edc8c56c0dae2b0077a9 | /RobotAlten/CommandHistory.h | be59837e2e03e3d5decd8917407644c505d0402f | [] | no_license | Tudi/TempStorage | 5657fae8876c055d85f535636a18763676bfac9b | 1fcf4df2fdda1ebf34c818a1df0d777e4cc9a864 | refs/heads/master | 2023-07-23T12:47:34.292055 | 2023-07-17T11:24:49 | 2023-07-17T11:24:49 | 55,682,824 | 10 | 5 | null | 2022-12-07T17:50:27 | 2016-04-07T09:42:49 | C | UTF-8 | C++ | false | false | 990 | h | #pragma once
#include <list>
//store executed commands so later we can undo or redo them
class CommandHistory
{
public:
~CommandHistory();
//after a successfull move or fill command, we add them to the history
void StoreCommand(const char* cmd);
//undo the last command. Also inserts it into the redo history
void UndoLastCommand();
//undo the last undo = redo
void RedoLastCommand();
private:
std::list<const char*> StoredCommands;
std::list<const char*> StoredCommandsRedo;
};
//store temporary move command coordinates to be able to undo them
class TempMoveCmd;
class TempCommandHistory
{
public:
~TempCommandHistory();
void ClearHistory();
void StoreCommand(int srcx, int srcy, int dstx, int dsty);
void UndoStoredCommands();
private:
std::list<TempMoveCmd*> StoredCommands;
};
extern CommandHistory UniqueCommandHistory;
#define sCmdHistory UniqueCommandHistory
extern TempCommandHistory UniqueTempCommandHistory;
#define sTempCmdHistory UniqueTempCommandHistory | [
"jozsab1@gmail.com"
] | jozsab1@gmail.com |
42503d6673408088c454ce1e43886151a53707d3 | 5993545f475566a3ad6c64c34d5d87458abac510 | /lib/h26x/sei.cpp | 1fb6694c1585676cedec4600084a45025bf95231 | [
"MIT"
] | permissive | alliance-archive/av | 484d4cb03f95bd458d195bb23f99ebf9aabfbc2b | d17dfd3b18685ae917b369ad891de225884da790 | refs/heads/master | 2020-05-04T17:49:43.355596 | 2019-04-02T23:16:47 | 2019-04-02T23:16:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,188 | cpp | #include "sei.hpp"
namespace h264 {
error sei_message::decode(bitstream* bs) {
while (bs->next_bits(8) == 0xff) {
bs->advance_bits(8);
payloadType += 255;
}
u<8> last_payload_type_byte;
auto err = last_payload_type_byte.decode(bs);
if (err) {
return err;
}
payloadType += last_payload_type_byte;
while (bs->next_bits(8) == 0xff) {
bs->advance_bits(8);
payloadSize += 255;
}
u<8> last_payload_size_byte;
err = last_payload_size_byte.decode(bs);
if (err) {
return err;
}
payloadSize += last_payload_size_byte;
const void* data = nullptr;
if (!bs->read_byte_aligned_bytes(&data, payloadSize)) {
return {"unable to read sei_payload"};
}
sei_payload.assign(reinterpret_cast<const uint8_t*>(data), reinterpret_cast<const uint8_t*>(data) + payloadSize);
return {};
}
error sei_rbsp::decode(bitstream* bs) {
while (bs->more_rbsp_data()) {
struct sei_message msg;
auto err = msg.decode(bs);
if (err) {
return err;
}
sei_message.emplace_back(std::move(msg));
}
return {};
}
} // namespace h264
| [
"noreply@github.aaf.cloud"
] | noreply@github.aaf.cloud |
8d96dff387a8836c0921dbd23791f8a0b80c0070 | 16e68f4edb24500755c4b366f891a26d37e0072a | /include/lbb/concurrency/future_/shared_state.h | 48bb1eaa4fd312f403b8171ed38930d814b1ed68 | [
"MIT"
] | permissive | pan-/lbb | ec97bfa8301ee4e635d6020ff162c568dcd22dc1 | 3ec6cf1dfc6ef9e6915e6436ea678c4e83c9e218 | refs/heads/master | 2021-01-17T12:12:09.295576 | 2018-02-19T12:12:40 | 2018-02-19T12:12:40 | 33,155,428 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,938 | h | #ifndef LBB_CONCURRENCY_FUTURE__SHARED_STATE_H_
#define LBB_CONCURRENCY_FUTURE__SHARED_STATE_H_
#include <lbb/utility.h>
#include <lbb/smartptr.h>
#include <lbb/functional.h>
#include "../mutex.h"
#include "../unique_lock.h"
#include "../condition_variable.h"
#include "../future_error.h"
namespace lbb {
namespace concurrency {
namespace future_ {
template<typename T>
class shared_state {
typedef function<void()> throw_function_t;
enum storage_state_tag {
empty_state,
value_state,
exception_state,
done_state
};
public:
/**
* construct an empty_state shared state
*/
shared_state() : _state(empty_state) { }
~shared_state() {
switch(_state) {
case value_state:
_storage.template as<T*>()->~T();
break;
case exception_state:
_storage.template as<throw_function_t*>()->~throw_function_t();
break;
default:
break;
}
}
/**
* return false if the inner value has already been retrieved
* and true otherwise
*/
bool valid() {
return (_state != done_state) ? true : false;
}
/**
* return true if the state is still empty and false otherwise
*/
bool is_empty() {
return (_state == empty_state);
}
/**
* return the shared state inner value
*/
T get() {
//we wait for the result if there is no result
wait();
//if we have received an exception, we call the function which will
//throw it
if(_state == exception_state) {
_state = done_state;
throw_function_t throw_func(*_storage.template as<throw_function_t*>());
//delete the storage
_storage.template as<throw_function_t*>()->~throw_function_t();
//throw exception, no return from this point
throw_func();
}
//if the promise was satisfied by a continuation, throw
if(_state != value_state) {
throw future_error(future_error::future_already_retrieved);
}
_state = done_state;
T value = move(*(_storage.template as<T*>()));
//release the storage
_storage.template as<T*>()->~T();
return move(value);
}
void wait() {
unique_lock<mutex> lock(_mutex);
if(_state == done_state) {
throw future_error(future_error::future_already_retrieved);
}
if(_state == empty_state) {
_condition.wait(lock);
}
}
void set_value(T value) {
unique_lock<mutex> lock(_mutex);
if(_state != empty_state) {
throw future_error(future_error::promise_already_satisfied);
}
new (_storage.get()) T(move(value));
_state = value_state;
if(_continuation) {
lock.unlock();
_continuation();
} else {
_condition.notify_one();
}
}
template<typename E>
void set_exception(const E& e) {
unique_lock<mutex> lock(_mutex);
if(_state != empty_state) {
throw future_error(future_error::promise_already_satisfied);
}
new (_storage.get()) throw_function_t(bind(throw_exception<E>, e));
_state = exception_state;
if(_continuation) {
lock.unlock();
_continuation();
} else {
_condition.notify_one();
}
}
//TODO : add enable shared from this and pass this as parameter of the
//continuation
void set_continuation(const function<void()>& continuation) {
unique_lock<mutex> lock(_mutex);
//throw if the future was already retrieved
if(_state == done_state) {
throw future_error(future_error::future_already_retrieved);
}
// if the promise has already been satisfied, call the continuation
// otherwise store the continuation
if(_state != empty_state) {
lock.unlock();
continuation();
} else {
_continuation = continuation;
}
}
private:
template<typename E>
static void throw_exception(E e) {
throw e;
}
mutex _mutex;
condition_variable _condition;
storage_state_tag _state;
aligned_union<T, throw_function_t> _storage;
function<void()> _continuation;
};
} // namespace future_
} // namespace concurrency
} // namespace lbb
#endif /* LBB_CONCURRENCY_FUTURE__SHARED_STATE_H_ */
| [
"vcoubard@awox.com"
] | vcoubard@awox.com |
3ac8ceea959900c405276c5d4c40848579c2fea0 | d0c59eab076dd143c20a8a95b5a5244752bbc50e | /src/TestScenes/TestScene11.cpp | f3544e2be7ef021287dee5b13294f2398fa3b527 | [
"MIT"
] | permissive | mikoro/raycer | ac565e673d7c1395242fb22d147290207a8309f6 | 281cbd42cae21c8612ed99d10eb4c113e6daa3d1 | refs/heads/master | 2021-01-18T23:07:02.757798 | 2016-05-11T14:08:59 | 2016-05-11T14:08:59 | 46,738,201 | 33 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,074 | cpp | // Copyright © 2015 Mikko Ronkainen <firstname@mikkoronkainen.com>
// License: MIT, see the LICENSE file.
#include "stdafx.h"
#include "Raytracing/Scene.h"
using namespace Raycer;
// glossy reflections
Scene Scene::createTestScene11()
{
Scene scene;
// CAMERA //
scene.camera.position = Vector3(0.44, 7.05, 7.33);
scene.camera.orientation = EulerAngle(-21.89, 8.77, 0.0);
// BOUNDING SPHERE //
ColorGradientTexture sphereTexture;
sphereTexture.id = 1;
sphereTexture.hasVerticalColorGradient = true;
sphereTexture.verticalColorGradient.addSegment(Color(0.0, 0.0, 0.0), Color(0.0, 0.0, 0.0), 40);
sphereTexture.verticalColorGradient.addSegment(Color(0.0, 0.0, 0.0), Color(0.0, 0.0, 0.05), 60);
sphereTexture.verticalIntensity = 1.0;
Material sphereMaterial;
sphereMaterial.id = 1;
sphereMaterial.diffuseReflectance = Color(1.0, 1.0, 1.0);
sphereMaterial.diffuseMapTextureId = sphereTexture.id;
sphereMaterial.skipLighting = true;
sphereMaterial.invertNormal = true;
Sphere sphere;
sphere.id = 1;
sphere.materialId = sphereMaterial.id;
sphere.position = Vector3(0.0, 0.0, 0.0);
sphere.radius = 1000.0;
scene.textures.colorGradientTextures.push_back(sphereTexture);
scene.materials.push_back(sphereMaterial);
scene.primitives.spheres.push_back(sphere);
// GROUND PLANE //
CheckerTexture groundTexture;
groundTexture.id = 2;
groundTexture.stripeMode = true;
groundTexture.stripeWidth = 0.05;
groundTexture.color1 = Color(0.025, 0.0, 0.0);
groundTexture.color2 = Color(0.0, 0.0, 0.0);
Material groundMaterial;
groundMaterial.id = 2;
groundMaterial.ambientReflectance = Color(1.0, 1.0, 1.0);
groundMaterial.diffuseReflectance = Color(1.0, 1.0, 1.0);
groundMaterial.ambientMapTextureId = groundTexture.id;
groundMaterial.diffuseMapTextureId = groundTexture.id;
groundMaterial.texcoordScale = Vector2(0.5, 0.5);
groundMaterial.rayReflectance = 0.1;
Plane groundPlane;
groundPlane.id = 2;
groundPlane.materialId = groundMaterial.id;
groundPlane.position = Vector3(0.0, 0.0, 0.0);
groundPlane.normal = Vector3(0.0, 1.0, 0.0);
scene.textures.checkerTextures.push_back(groundTexture);
scene.materials.push_back(groundMaterial);
scene.primitives.planes.push_back(groundPlane);
// BOXES //
Material boxMaterial;
Box box;
Instance boxInstance;
boxMaterial.id = 10;
boxMaterial.ambientReflectance = Color(0.0, 0.0, 0.0);
boxMaterial.diffuseReflectance = Color(0.0, 0.0, 0.0);
boxMaterial.rayTransmittance = 1.0;
boxMaterial.refractiveIndex = 1.5;
boxMaterial.rayTransmittanceGlossinessSampleCountSqrt = 2;
boxMaterial.rayTransmittanceGlossiness = 1000.0;
boxMaterial.nonShadowing = true;
box.id = 10;
box.invisible = true;
box.materialId = boxMaterial.id;
box.position = Vector3(0.0, 3.01, -1.0);
box.extent = Vector3(4.0, 6.0, 1.0);
boxInstance.id = 1000;
boxInstance.primitiveId = box.id;
boxInstance.rotate = EulerAngle(0.0, 20.0, 0.0);
scene.materials.push_back(boxMaterial);
scene.primitives.boxes.push_back(box);
scene.primitives.instances.push_back(boxInstance);
boxMaterial.id = 12;
boxMaterial.ambientReflectance = Color(1.0, 1.0, 1.0);
boxMaterial.diffuseReflectance = Color(1.0, 1.0, 1.0);
boxMaterial.rayTransmittance = 0.0;
box.id = 12;
box.invisible = true;
box.materialId = boxMaterial.id;
box.position = Vector3(-1.0, 2.0, -6.0);
box.extent = Vector3(14.0, 4.0, 0.5);
boxInstance.id = 1002;
boxInstance.primitiveId = box.id;
boxInstance.rotate = EulerAngle(0.0, -20.0, 0.0);
scene.materials.push_back(boxMaterial);
scene.primitives.boxes.push_back(box);
scene.primitives.instances.push_back(boxInstance);
// SPHERES //
sphereMaterial = Material();
sphereMaterial.id = 20;
sphereMaterial.ambientReflectance = Color(1.0, 0.0, 0.0);
sphereMaterial.diffuseReflectance = Color(1.0, 0.0, 0.0);
sphereMaterial.nonShadowing = true;
sphere = Sphere();
sphere.id = 20;
sphere.materialId = sphereMaterial.id;
sphere.position = Vector3(-2.5, 1.5, -2.3);
sphere.radius = 1.5;
scene.materials.push_back(sphereMaterial);
scene.primitives.spheres.push_back(sphere);
sphereMaterial = Material();
sphereMaterial.id = 21;
sphereMaterial.ambientReflectance = Color(0.01, 0.01, 0.01);
sphereMaterial.diffuseReflectance = Color(0.01, 0.01, 0.01);
sphereMaterial.rayReflectance = 1.0;
sphereMaterial.rayReflectanceGlossinessSampleCountSqrt = 2;
sphereMaterial.rayReflectanceGlossiness = 50.0;
sphereMaterial.nonShadowing = true;
sphere = Sphere();
sphere.id = 21;
sphere.materialId = sphereMaterial.id;
sphere.position = Vector3(-8.0, 2.0, -6.0);
sphere.radius = 2.0;
scene.materials.push_back(sphereMaterial);
scene.primitives.spheres.push_back(sphere);
// LIGHTS //
scene.lights.ambientLight.color = Color(1.0, 1.0, 1.0);
scene.lights.ambientLight.intensity = 0.1;
PointLight pointLight;
pointLight.color = Color(1.0, 1.0, 1.0);
pointLight.intensity = 2.0;
pointLight.position = Vector3(10.0, 10.0, 10.0);
pointLight.maxDistance = 1000.0;
pointLight.attenuation = 2.0;
scene.lights.pointLights.push_back(pointLight);
return scene;
}
| [
"mikko@mikkoronkainen.com"
] | mikko@mikkoronkainen.com |
99a63991cb1aa0c709938d77691e94d4acbdbbb0 | a35b30a7c345a988e15d376a4ff5c389a6e8b23a | /boost/math/tools/detail/rational_horner3_4.hpp | 3cb88082ce1a6b1f24883ec389f9330514feadfe | [] | no_license | huahang/thirdparty | 55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b | 07a5d64111a55dda631b7e8d34878ca5e5de05ab | refs/heads/master | 2021-01-15T14:29:26.968553 | 2014-02-06T07:35:22 | 2014-02-06T07:35:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 82 | hpp | #include "thirdparty/boost_1_55_0/boost/math/tools/detail/rational_horner3_4.hpp"
| [
"liuhuahang@xiaomi.com"
] | liuhuahang@xiaomi.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.