blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9c295a422447e631748555249a031796077e193d | 8f0a8fb4d2dcf837e1f616a545c995882fa23eb9 | /src/PowerStageController.cc | 70f3a75cea8a932d7d62e17f3a99dd99ba2e323d | [
"MIT"
] | permissive | klaus-liebler/smopla-dps | 88726732a446ff2c130151d4641ed9769e1922ec | ab92c73d16769a09d70b5519792c29a4276543c5 | refs/heads/master | 2020-05-14T20:46:44.154079 | 2019-04-17T20:34:49 | 2019-04-17T20:34:49 | 181,949,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,015 | cc | #include "PowerStageController.hh"
#include "gpio.hh"
#include "math.h"
#include "stm32f1xx_ll_dac.h"
PowerStageController::PowerStageController(const Pin powerControlPin):
powerControlPin(powerControlPin){
}
PowerStageController::~PowerStageController() {
}
void PowerStageController::Begin(){
/** Load default calibration constants */
a_adc_k_coef = A_ADC_K;
a_adc_c_coef = A_ADC_C;
a_dac_k_coef = A_DAC_K;
a_dac_c_coef = A_DAC_C;
v_adc_k_coef = V_ADC_K;
v_adc_c_coef = V_ADC_C;
v_dac_k_coef = V_DAC_K;
v_dac_c_coef = V_DAC_C;
vin_adc_k_coef = VIN_ADC_K;
vin_adc_c_coef = VIN_ADC_C;
/** Load any calibration constants that maybe stored in non-volatile memory (past) */
//todo!!
EnableOutput(false);
}
void PowerStageController::EnableOutput(bool enable)
{
this->outputEnabled = enable;
if (enable) {
#ifdef DPS5015
//gpio_clear(GPIOA, GPIO9); // this is power control on '5015
gpio_set(GPIOB, GPIO11); // B11 is fan control on '5015
gpio_clear(GPIOC, GPIO13); // C13 is power control on '5015
#else
Gpio::Set(this->powerControlPin, false); // B11 is power control on '5005
#endif
} else {
#ifdef DPS5015
//gpio_set(GPIOA, GPIO9); // gpio_set(GPIOB, GPIO11);
gpio_clear(GPIOB, GPIO11); // B11 is fan control on '5015
gpio_set(GPIOC, GPIO13); // C13 is power control on '5015
#else
Gpio::Set(this->powerControlPin, true); // B11 is power control on '5005
#endif
}
}
uint16_t PowerStageController::GetUin()
{
return pwrctl_calc_uin(this->uInRaw);
}
uint16_t PowerStageController::GetUout(){
return pwrctl_calc_uout(this->uOutRaw);
}
uint16_t PowerStageController::GetIOut()
{
return pwrctl_calc_iout(this->iOutRaw);
}
/**
* @brief Calculate V_in based on raw ADC measurement
* @param raw value from ADC
* @retval corresponding voltage in milli volt
*/
uint32_t PowerStageController::pwrctl_calc_uin(uint16_t raw)
{
float value = vin_adc_k_coef * raw + vin_adc_c_coef;
if (value <= 0)
return 0;
else
return value + 0.5f; /** Add 0.5f to value so it is correctly rounded when it is truncated */
}
/**
* @brief Calculate V_out based on raw ADC measurement
* @param raw value from ADC
* @retval corresponding voltage in milli volt
*/
uint32_t PowerStageController::pwrctl_calc_uout(uint16_t raw)
{
float value = v_adc_k_coef * raw + v_adc_c_coef;
if (value <= 0)
return 0;
else
return value + 0.5f; /** Add 0.5f to value so it is correctly rounded when it is truncated */
}
/**
* @brief Calculate DAC setting for requested V_out
* @param v_out_mv requested output voltage
* @retval corresponding 12 bit DAC value
*/
uint16_t PowerStageController::pwrctl_calc_uout_dac(uint32_t v_out_mv)
{
float value = v_dac_k_coef * v_out_mv + v_dac_c_coef;
if (value <= 0)
return 0;
else if (value >= 0xfff)
return 0xfff; /** 12 bits */
else
return value + 0.5f; /** Add 0.5f to value so correct rounding is done when truncated */
}
/**
* @brief Calculate I_out based on raw ADC measurement
* @param raw value from ADC
* @retval corresponding current in milliampere
*/
uint32_t PowerStageController::pwrctl_calc_iout(uint16_t raw)
{
float value = a_adc_k_coef * raw + a_adc_c_coef;
if (value <= 0)
return 0;
else
return value + 0.5f; /** Add 0.5f to value so correct rounding is done when truncated */
}
/**
* @brief Calculate expected raw ADC value based on selected I_limit
* @param i_limit_ma selected I_limit
* @retval expected raw ADC value
*/
uint16_t PowerStageController::pwrctl_calc_ilimit_adc(uint16_t i_limit_ma)
{
float value = (i_limit_ma - a_adc_c_coef) / a_adc_k_coef + 1;
if (value <= 0)
return 0;
else
return value + 0.5f; // Add 0.5 so it is correctly rounded when it is truncated
}
/**
* @brief Calculate expected raw ADC value based on selected V_limit
* @param v_limit_mv selected V_limit
* @retval expected raw ADC value
*/
uint16_t PowerStageController::pwrctl_calc_ulimit_adc(uint16_t v_limit_mv)
{
float value = (v_limit_mv - v_adc_c_coef) / v_adc_k_coef + 1;
if (value <= 0)
return 0;
else
return value + 0.5f; // Add 0.5 so it is correctly rounded when it is truncated
}
/**
* @brief Calculate DAC setting for constant current mode
* @param i_out_ma requested constant current
* @retval corresponding 12 bit DAC value
* @note this formula is valid for the DPS5005 and would probably need changes
* for DPS:es capable of higher current output.
*/
uint16_t PowerStageController::pwrctl_calc_iout_dac(uint32_t i_out_ma)
{
float value = a_dac_k_coef * i_out_ma + a_dac_c_coef;
if (value <= 0)
return 0;
else if (value >= 0xfff)
return 0xfff; /** 12 bits */
else
return value + 0.5f; /** Add 0.5f to value so correct rounding is done when truncated */
}
void PowerStageController::Update(volatile uint16_t *VinVOutIout)
{
this->uOutRaw = VinVOutIout[1]- VinVOutIout[2];
this->uInRaw= VinVOutIout[0];
this->iOutRaw = VinVOutIout[2];
if(this->outputEnabled)
{
LL_DAC_ConvertData12RightAligned(DAC1, LL_DAC_CHANNEL_1, this->uLimitRaw);
LL_DAC_ConvertData12RightAligned(DAC1, LL_DAC_CHANNEL_2, this->iLimitRaw);
}
else
{
LL_DAC_ConvertData12RightAligned(DAC1, LL_DAC_CHANNEL_1, 0);
LL_DAC_ConvertData12RightAligned(DAC1, LL_DAC_CHANNEL_2, 0);
}
}
void PowerStageController::Set(uint16_t uLimit, uint16_t iLimit)
{
//TODO: Gibt es ein Problem wenn man die sequentiell setzt und genau in dem Moment der Regelalgorithmus arbeitet?
//ggf in einen 32bit-Wert verpacken und gemeinsam setzen
this->iLimit=std::min(iLimit, (uint16_t)CONFIG_DPS_MAX_CURRENT);
this->uLimit=std::min(uLimit, (uint16_t)CONFIG_DPS_MAX_VOLTAGE);
this->iLimitRaw=pwrctl_calc_ilimit_adc(this->iLimit);
this->uLimitRaw=pwrctl_calc_ulimit_adc(this->uLimit);
}
| [
"mail@klaus-liebler.de"
] | mail@klaus-liebler.de |
ddd10fe9fec7df038fc7d3d61653493d44856745 | 274bcd10ae2edb19eb7f5500d8ea878a76ed2225 | /LibtorrentWrapper/include/LibtorrentWrapper/Wrapper.h | d49bebf684deab803042b283b3322b4f5f699ac2 | [
"Apache-2.0"
] | permissive | ProtocolONE/cord.libtorrent-wrapper | 8f9803f0828e6bfaa8c3735cc4f3934d2f1fee61 | 7e854967ad21a7188ced1fa85d41da8f799c457c | refs/heads/master | 2020-04-06T13:49:26.382378 | 2018-11-14T08:30:23 | 2018-11-14T08:30:23 | 157,516,008 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,339 | h | #pragma once
#include <LibtorrentWrapper/libtorrentwrapper_global.h>
#include <LibtorrentWrapper/TorrentConfig.h>
#include <LibtorrentWrapper/EventArgs/ProgressEventArgs.h>
#include <QtCore/QObject>
#include <QtCore/QList>
namespace P1 {
namespace Libtorrent
{
class WrapperInternal;
class LIBTORRENTWRAPPER_EXPORT Wrapper : public QObject
{
Q_OBJECT
public:
explicit Wrapper(QObject *parent = 0);
virtual ~Wrapper();
enum Profile {
DEFAULT_PROFILE = 0,
HIGH_PERFORMANCE_SEED = 1,
MIN_MEMORY_USAGE = 2
};
/// <summary>Инициализирует торрент движок. Необходимо выхвать 1 раз перед использованием.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
void initEngine(Wrapper::Profile profile = DEFAULT_PROFILE);
/// <summary>Позволяет изменить профиль торрент движка в активной сессии.</summary>
void setProfile(Wrapper::Profile profile);
/// <summary>Скачать торрент. Где взять торрент файл и куда качать передается через TorrentConfig.
/// Id - идентификатор торрента. По нему будут приходить сигнал и с мпомщью него можно остановить торрент.
/// Если такой торрент уже есть, то закачка будет, либо продолжена, либо торрент начнется снова,
/// в зависимости от настроек.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="id"> Id торрента.</param>
/// <param name="config">Настройки добавляемого торрента.</param>
void start(const QString& id, TorrentConfig& config);
/// <summary>Сгенерировать полностью заполненный fast resume файл на основе торрет файла.</summary>
/// <param name="id">Id торрента.</param>
/// <param name="config">Настройки добавляемого торрента.</param>
void createFastResume(const QString& id, TorrentConfig& config);
/// <summary>Останавливает торрент. Торрент переходит в режим paused.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="id">Id торрента.</param>
void stop(const QString& id);
/// <summary>Закрывает сессию и все зарегистрированные торренты. Происходит сохранение всех фастрезьюмов.
/// Функция может работать до 30 секунд.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
void shutdown();
/// <summary>Удаляет торрент из списка. Сохранение fast resume не происходит, поэтому, если удалять запущеный
/// торрент, то fast resume может быть испорчен или не актуален.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="id">Id торрента.</param>
void remove(const QString& id);
/// <summary>Устанавливает путь до папки, в которую созхраняются файлы fastresume и настройки сессии.</summary>
/// <remarks>Ilya.Tkachenko, 10.04.2012.</remarks>
/// <param name="path">Полный путь до папки с настрйоками.</param>
void setTorrentConfigDirectoryPath(const QString& path);
QString getFastResumeFilePath(const QString& id);
/// <summary>Задает порт, с которым стартует движек торрента. Вызывать его необходимо только до initEngine
/// Вызов этого метода не меняет порт уже запущеного
/// движка. Для смены порта следует использовать метод changeListeningPort.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="port">The port.</param>
void setListeningPort(unsigned short port);
/// <summary>Торрент закрывает текущий прослушиваемый порт и пытается открыть указанный. В случаи неудачи торрент
/// пытается открыть на 0 порту, тем самым система выдает любой свободный.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="port">The port.</param>
void changeListeningPort(unsigned short port);
/// <summary>Gets the listening port.</summary>
/// <remarks>Ilya.Tkachenko, 03.04.2012.</remarks>
/// <returns>.</returns>
unsigned short listeningPort() const;
/// <summary>Sets a upload rate limit.</summary>
/// <remarks>Ilya.Tkachenko, 05.04.2012.</remarks>
/// <param name="bytesPerSecond">The bytes per second.</param>
void setUploadRateLimit(int bytesPerSecond);
/// <summary>Sets a download rate limit.</summary>
/// <remarks>Ilya.Tkachenko, 05.04.2012.</remarks>
/// <param name="bytesPerSecond">The bytes per second.</param>
void setDownloadRateLimit(int bytesPerSecond);
/// <summary>Uploads the rate limit.</summary>
/// <remarks>Ilya.Tkachenko, 05.04.2012.</remarks>
/// <returns>.</returns>
int uploadRateLimit() const;
/// <summary>Downloads the rate limit.</summary>
/// <remarks>Ilya.Tkachenko, 05.04.2012.</remarks>
/// <returns>.</returns>
int downloadRateLimit() const;
/*!
\fn int Wrapper::maxConnection();
\brief Gets the maximum connection.
\author Ilya.Tkachenko
\date 30.05.2012
\return .
*/
int maxConnection();
/*!
\fn void Wrapper::setMaxConnection(int maxConnection);
\brief Sets a maximum connection.
\author Ilya.Tkachenko
\date 30.05.2012
\param maxConnection The maximum connection.
*/
void setMaxConnection(int maxConnection);
/*!
\fn bool Wrapper::seedEnabled() const;
\brief Возвращает включена ли раздача.
\author Ilya.Tkachenko
\date 12.07.2013
\return true if it succeeds, false if it fails.
*/
bool seedEnabled() const;
/*!
\fn void Wrapper::setSeedEnabled(bool value);
\brief Sets a seed enabled.
\author Ilya.Tkachenko
\date 12.07.2013
\param value true to value.
*/
void setSeedEnabled(bool value);
/*!
\fn bool Wrapper::getInfoHash(const QString& path, QString& result);
\brief Gets an information hash.
\author Ilya.Tkachenko
\date 27.07.2013
\param path Полный путь до папки с настрйоками.
\param [in,out] result The result.
\return true if it succeeds, false if it fails.
*/
bool getInfoHash(const QString& path, QString& result);
/*!
\fn bool Wrapper::getFileList(const QString& path, QList<QString> &result);
\brief Gets a relative path file list.
\author Ilya.Tkachenko
\date 29.07.2013
\param path Полный путь до папки с настрйоками.
\param [in,out] result The result.
\return true if it succeeds, false if it fails.
*/
bool getFileList(const QString& path, QList<QString> &result);
/*!
\fn Wrapper::setCredentials(const QString &userId, const QString &hash);
\brief Устанавливает идентификатор пользователя, выполняеющего загрузку торрента. Подробнее в QGNA-1319.
\param userId Идентификатор пользователя
\param hash Хеш для текущего идентификатора
*/
void setCredentials(const QString &userId, const QString &hash);
/*!
\fn Wrapper::resetCredentials();
\brief Сбрасывает выставленные с помощью setCredentials данные пользователя.
*/
void resetCredentials();
public slots:
/*!
\fn void Wrapper::pauseSession();
\brief Останавливаются все торренты.
\author Ilya.Tkachenko
\date 31.07.2012
*/
void pauseSession();
/*!
\fn void Wrapper::resumeSession();
\brief Возобновляется работа торрента. Приэтом состояние торрентов возвращается на предыдущее перед вызовом
pauseSession().
\author Ilya.Tkachenko
\date 31.07.2012
*/
void resumeSession();
signals:
/// <summary>Listening port changed. Do not call before InitEngine.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="port">The port.</param>
void listeningPortChanged(unsigned short port);
/// <summary>Progress.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="args">Progress event information.</param>
void progressChanged(P1::Libtorrent::EventArgs::ProgressEventArgs args);
/// <summary>Трекер вернул ошибку.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="id"> Id торрента.</param>
/// <param name="failCountInARow">Количество ошибок подряд.</param>
/// <param name="httpStatusCode"> Http код ответа от трекера.</param>
void trackerFailed(QString id, int failCountInARow, int httpStatusCode);
/// <summary>Ошибка чтения/записи файла.</summary>
/// <remarks>Ilya.Tkachenko, 30.03.2012.</remarks>
/// <param name="id"> Id торрента.</param>
/// <param name="filePath"> Полный путь до файла.</param>
/// <param name="errorCode">Код ошибки. Откуда брать расшифровку пока не совсем понятно.
/// Коды похожи на те что указаны в ec_xlate (%BOOST_ROOT%\interprocess\errors.hpp).
/// Например, 112 - нехватка места на диске - ERROR_DISK_FULL</param>
void fileError(QString id, QString filePath, int errorCode);
/*!
\fn void Wrapper::torrentError(QString id);
\brief Torrent error.
\author Ilya.Tkachenko
\date 12.05.2012
\param id Id торрента.
*/
void torrentError(QString id);
/// <summary>Listen fail.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="port"> The port.</param>
/// <param name="errorCode"> Код ошибки. Откуда брать расшифровку пока не совсем понятно. Коды
/// похожи на те что указаны в ec_xlate (%BOOST_ROOT%\interprocess\errors.hpp). Например, 112 -
/// нехватка места на диске - ERROR_DISK_FULL.</param>
void listenFailed(int port, int errorCode);
/// <summary>Torrent status changed.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="id"> Id торрента.</param>
/// <param name="oldState">State of the old.</param>
/// <param name="newState">State of the new.</param>
void torrentStatusChanged(QString id,
P1::Libtorrent::EventArgs::ProgressEventArgs::TorrentStatus oldState,
P1::Libtorrent::EventArgs::ProgressEventArgs::TorrentStatus newState);
/// <summary>Torrent download finished.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="id">Id торрента.</param>
void torrentDownloadFinished(QString id);
/// <summary>Torrent resumed.</summary>
/// <remarks>Ilya.Tkachenko, 02.04.2012.</remarks>
/// <param name="id">Id торрента.</param>
void torrentResumed(QString id);
void startTorrentFailed(QString id, int errorCode);
void torrentPaused(QString id);
void torrentRehashed(QString id, bool isComplete);
private:
WrapperInternal *_internalWrapper;
};
}
}
| [
"Clipeus@live.com"
] | Clipeus@live.com |
3570e985d08384e5a92645ecdee162125d22241c | 9aebfc1352ce7cc1519cc3f595eea7dfd5fa40e0 | /src/main.cpp | b1855a7fd45d6fe1464bd5ed898dbe68be8ac80f | [] | no_license | m2enu/study_opencv | 0c40c6774c5e7ca4b07598e1527880b94c712e26 | 1d1793a304d0dc79a03965bf3434f148e608397d | refs/heads/master | 2020-06-16T16:31:38.333504 | 2019-07-15T11:15:50 | 2019-07-15T11:15:50 | 195,530,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,822 | cpp | #include <stdint.h>
#include <iostream>
#include <opencv2/opencv.hpp>
/* <!-- {{{1 --> function declarations
*/
static void tutorial(void);
static void answer001(void);
static void answer002(void);
static void answer003(void);
static void answer004(void);
static void answer005(void);
static void answer006(void);
static void answer007(void);
static void answer008(void);
static void answer009(void);
/** <!-- {{{1 --> @brief definition of OpenCV study function
*/
typedef void (*opencv_func_t)(void);
/** <!-- {{{1 --> @brief OpenCV Function Table
*/
static const opencv_func_t FUNC_TABLE[] = {
tutorial,
answer001,
answer002,
answer003,
answer004,
answer005,
answer006,
answer007,
answer008,
answer009,
};
/** <!-- {{{1 --> @brief OpenCV Tutorial
*/
static void tutorial(void)
{
// open
cv::Mat img1 = cv::imread(RESOURCE_DIR "imori.jpg", cv::IMREAD_COLOR);
if (img1.empty()) {
std::cout << "image is empty." << std::endl;
return;
}
cv::Mat img2 = img1.clone();
// paint left top in RED
const int32_t width = img1.rows;
const int32_t height = img1.cols;
int32_t x, y;
for (x = 0; x < (width / 2); x++) {
for (y = 0; y < (height / 2); y++) {
img1.at<cv::Vec3b>(y, x)[0] = 0;
img1.at<cv::Vec3b>(y, x)[1] = 0;
img1.at<cv::Vec3b>(y, x)[2] = 255;
}
}
// swap R,B left top
uint8_t r, b;
for (x = 0; x < (width / 2); x++) {
for (y = 0; y < (height / 2); y++) {
b = img2.at<cv::Vec3b>(y, x)[0];
r = img2.at<cv::Vec3b>(y, x)[2];
img2.at<cv::Vec3b>(y, x)[0] = r;
img2.at<cv::Vec3b>(y, x)[2] = b;
}
}
// save image
cv::imwrite("out.jpg", img2);
// concat images
const cv::Mat tmp[3] = {
img1,
cv::Mat(cv::Size(10, height), CV_8UC3, cv::Scalar(0, 0, 0)),
img2,
};
cv::Mat disp;
cv::hconcat(tmp, 3, disp);
cv::imshow("Tutorial", disp);
cv::waitKey(0);
cv::destroyAllWindows();
}
/** <!-- {{{1 --> @brief Answer of Question 001
*/
static void answer001(void)
{
// open
cv::Mat img = cv::imread(RESOURCE_DIR "imori.jpg", cv::IMREAD_COLOR);
if (img.empty()) {
std::cout << "image is empty." << std::endl;
return;
}
// swap Red / Blue
const int32_t width = img.rows;
const int32_t height = img.cols;
int32_t x, y;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
uint8_t b = img.at<cv::Vec3b>(y, x)[0];
img.at<cv::Vec3b>(y, x)[0] = img.at<cv::Vec3b>(y, x)[2];
img.at<cv::Vec3b>(y, x)[2] = b;
}
}
cv::imshow("Answer001", img);
cv::waitKey(0);
cv::destroyAllWindows();
}
/** <!-- {{{1 --> @brief Answer of Question 002
*/
static void answer002(void)
{
// open
cv::Mat img = cv::imread(RESOURCE_DIR "imori.jpg", cv::IMREAD_COLOR);
if (img.empty()) {
std::cout << "image is empty." << std::endl;
return;
}
// Grayscale
const int32_t width = img.rows;
const int32_t height = img.cols;
cv::Mat out = cv::Mat::zeros(width, height, CV_8UC1);
int32_t x, y;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
uint8_t b = img.at<cv::Vec3b>(y, x)[0];
uint8_t g = img.at<cv::Vec3b>(y, x)[1];
uint8_t r = img.at<cv::Vec3b>(y, x)[2];
out.at<uint8_t>(y, x) = (uint8_t)(
0.2126 * (float)r + 0.7152 * (float)g + 0.0722 * (float)b);
}
}
cv::imshow("Answer002", out);
cv::waitKey(0);
cv::destroyAllWindows();
}
/** <!-- {{{1 --> @brief Answer of Question 003
*/
static void answer003(void)
{
// open
cv::Mat img = cv::imread(RESOURCE_DIR "imori.jpg", cv::IMREAD_COLOR);
if (img.empty()) {
std::cout << "image is empty." << std::endl;
return;
}
// Binarization
const int32_t width = img.rows;
const int32_t height = img.cols;
cv::Mat out = cv::Mat::zeros(width, height, CV_8UC1);
int32_t x, y;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
uint8_t b = img.at<cv::Vec3b>(y, x)[0];
uint8_t g = img.at<cv::Vec3b>(y, x)[1];
uint8_t r = img.at<cv::Vec3b>(y, x)[2];
uint8_t v = (uint8_t)(
0.2126 * (float)r + 0.7152 * (float)g + 0.0722 * (float)b);
out.at<uint8_t>(y, x) = (uint8_t)((v < 128) ? 0: 255);
}
}
cv::imshow("Answer003", out);
cv::waitKey(0);
cv::destroyAllWindows();
}
/** <!-- {{{1 --> @brief Answer of Question 004
*/
static void answer004(void)
{
// open
cv::Mat img = cv::imread(RESOURCE_DIR "imori.jpg", cv::IMREAD_COLOR);
if (img.empty()) {
std::cout << "image is empty." << std::endl;
return;
}
// Grayscale
const int32_t width = img.rows;
const int32_t height = img.cols;
cv::Mat out = cv::Mat::zeros(width, height, CV_8UC1);
int32_t x, y;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
uint8_t b = img.at<cv::Vec3b>(y, x)[0];
uint8_t g = img.at<cv::Vec3b>(y, x)[1];
uint8_t r = img.at<cv::Vec3b>(y, x)[2];
out.at<uint8_t>(y, x) = (uint8_t)(
0.2126 * (float)r + 0.7152 * (float)g + 0.0722 * (float)b);
}
}
// Otsu's Binarization method
int32_t th = 0;
float max_sb = 0.0f;
for (int32_t t = 0; t < 255; t++) {
int32_t w0 = 0;
int32_t w1 = 0;
float m0 = 0.0f;
float m1 = 0.0f;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
int32_t v = (int32_t)(out.at<uint8_t>(y, x));
if (v < t) {
w0++;
m0 += (float)v;
} else {
w1++;
m1 += (float)v;
}
}
}
m0 /= (float)w0;
m1 /= (float)w1;
float sb = (
((float)w0 / (float)(width * height)) *
((float)w1 / (float)(width * height)) *
(m0 - m1) * (m0 - m1));
if (sb > max_sb) {
max_sb = sb;
th = t;
}
}
std::cout << "threshold = " << th << std::endl;
// Binarization
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
uint8_t v = (uint8_t)out.at<uint8_t>(y, x);
out.at<uint8_t>(y, x) = (uint8_t)((v < th) ? 0: 255);
}
}
cv::imshow("Answer004", out);
cv::waitKey(0);
cv::destroyAllWindows();
}
/** <!-- {{{1 --> @brief Answer of Question 005
*/
static void answer005(void)
{
// open
cv::Mat img = cv::imread(RESOURCE_DIR "imori.jpg", cv::IMREAD_COLOR);
if (img.empty()) {
std::cout << "image is empty." << std::endl;
return;
}
// RGB to HSV to RGB
const int32_t width = img.rows;
const int32_t height = img.cols;
cv::Mat out = cv::Mat::zeros(width, height, CV_8UC3);
int32_t x, y;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
float b = (float)img.at<cv::Vec3b>(y, x)[0] / 255.0f;
float g = (float)img.at<cv::Vec3b>(y, x)[1] / 255.0f;
float r = (float)img.at<cv::Vec3b>(y, x)[2] / 255.0f;
float c_max = fmax(r, fmax(g, b));
float c_min = fmin(r, fmin(g, b));
// RGB to HSV
float h = 0.0f;
if (c_max == c_min) {
;
} else if (c_min == b) {
h = 60.0f * (g - r) / (c_max - c_min) + 60.0f;
} else if (c_min == r) {
h = 60.0f * (b - g) / (c_max - c_min) + 180.0f;
} else if (c_min == g) {
h = 60.0f * (r - b) / (c_max - c_min) + 300.0f;
}
float v = c_max;
float s = c_max - c_min;
// invert Hue
h = fmod((h + 180.0f), 360);
// HSV to RGB
float cc = s;
float hh = h / 60.0f;
float xx = cc * (1.0f - fabs(fmod(hh, 2) - 1.0f));
r = g = b = (v - cc);
if (hh < 1.0f) {
r += cc;
g += xx;
} else if (hh < 2.0f) {
r += xx;
g += cc;
} else if (hh < 3.0f) {
g += cc;
b += xx;
} else if (hh < 4.0f) {
g += xx;
b += cc;
} else if (hh < 5.0f) {
r += xx;
b += cc;
} else if (hh < 6.0f) {
r += cc;
b += xx;
}
out.at<cv::Vec3b>(y, x)[0] = (uint8_t)(b * 255);
out.at<cv::Vec3b>(y, x)[1] = (uint8_t)(g * 255);
out.at<cv::Vec3b>(y, x)[2] = (uint8_t)(r * 255);
}
}
cv::imshow("Answer005", out);
cv::waitKey(0);
cv::destroyAllWindows();
}
/** <!-- {{{1 --> @brief Answer of Question 006
*/
static void answer006(void)
{
cv::Mat img = cv::imread(RESOURCE_DIR "imori.jpg", cv::IMREAD_COLOR);
if (img.empty()) {
std::cout << "image is empty." << std::endl;
return;
}
const int32_t width = img.rows;
const int32_t height = img.cols;
cv::Mat out = cv::Mat::zeros(height, width, CV_8UC3);
int32_t x, y, c;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
for (c = 0; c < 3; c++) {
uint8_t v = img.at<cv::Vec3b>(y, x)[c];
v = 32 + 64 * ((v >> 6) & 0x03);
out.at<cv::Vec3b>(y, x)[c] = v;
}
}
}
cv::imshow("Answer006", out);
cv::waitKey(0);
cv::destroyAllWindows();
}
/** <!-- {{{1 --> @brief Answer of Question 007
*/
static void answer007(void)
{
cv::Mat img = cv::imread(RESOURCE_DIR "imori.jpg", cv::IMREAD_COLOR);
if (img.empty()) {
std::cout << "image is empty." << std::endl;
return;
}
const int32_t width = img.rows;
const int32_t height = img.cols;
cv::Mat out = cv::Mat::zeros(height, width, CV_8UC3);
int32_t ix, iy, x, y, c;
const int32_t r = 8;
for (ix = 0; ix < width; ix+= r) {
for (iy = 0; iy < height; iy += r) {
for (c = 0; c < 3; c++) {
uint32_t v = 0;
for (x = 0; x < r; x++) {
for (y = 0; y < r; y++) {
v += img.at<cv::Vec3b>(y + iy, x + ix)[c];
}
}
v >>= 6;
for (x = 0; x < r; x++) {
for (y = 0; y < r; y++) {
out.at<cv::Vec3b>(y + iy, x + ix)[c] = (uint8_t)v;
}
}
}
}
}
cv::imshow("Answer007", out);
cv::waitKey(0);
cv::destroyAllWindows();
}
/** <!-- {{{1 --> @brief Answer of Question 008
*/
static void answer008(void)
{
cv::Mat img = cv::imread(RESOURCE_DIR "imori.jpg", cv::IMREAD_COLOR);
if (img.empty()) {
std::cout << "image is empty." << std::endl;
return;
}
const int32_t width = img.rows;
const int32_t height = img.cols;
cv::Mat out = cv::Mat::zeros(height, width, CV_8UC3);
int32_t ix, iy, x, y, c;
const int32_t r = 8;
for (ix = 0; ix < width; ix+= r) {
for (iy = 0; iy < height; iy += r) {
for (c = 0; c < 3; c++) {
uint8_t v = 0;
uint8_t vmax = 0;
for (x = 0; x < r; x++) {
for (y = 0; y < r; y++) {
v = img.at<cv::Vec3b>(y + iy, x + ix)[c];
vmax = (v > vmax) ? v: vmax;
}
}
for (x = 0; x < r; x++) {
for (y = 0; y < r; y++) {
out.at<cv::Vec3b>(y + iy, x + ix)[c] = vmax;
}
}
}
}
}
cv::imshow("Answer008", out);
cv::waitKey(0);
cv::destroyAllWindows();
}
/** <!-- {{{1 --> @brief Answer of Question 009
*/
static void answer009(void)
{
cv::Mat img = cv::imread(RESOURCE_DIR "imori_noise.jpg", cv::IMREAD_COLOR);
if (img.empty()) {
std::cout << "image is empty." << std::endl;
return;
}
// kernel
int32_t x, y, ix, iy, c;
const float sigma = 1.3f;
const int32_t k_size = 3;
const int32_t k_offset = -1;
float kernel[k_size][k_size];
float sum_kernel = 0.0f;
for (x = 0; x < k_size; x++) {
for (y = 0; y < k_size; y++) {
ix = x + k_offset;
iy = y + k_offset;
kernel[y][x] = (1.0f / sqrt(2.0f * M_PI) / sigma) * exp(
(float)((ix * ix) + (iy * iy)) / -2.0f / sigma / sigma);
sum_kernel += kernel[y][x];
}
}
for (x = 0; x < k_size; x++) {
for (y = 0; y < k_size; y++) {
kernel[y][x] /= sum_kernel;
}
}
// filtering
const int32_t width = img.rows;
const int32_t height = img.cols;
cv::Mat out = cv::Mat::zeros(height, width, CV_8UC3);
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
for (c = 0; c < 3; c++) {
float v = 0.0f;
for (ix = 0; ix < k_size; ix++) {
for (iy = 0; iy < k_size; iy++) {
int32_t ax = x + ix + k_offset;
int32_t ay = y + iy + k_offset;
if ((ax < 0) || (ax > width)) {
continue;
} else if ((ay < 0) || (ay > height)) {
continue;
}
v += ((float)img.at<cv::Vec3b>(ay, ax)[c] * kernel[iy][ix]);
}
}
out.at<cv::Vec3b>(y, x)[c] = v;
}
}
}
cv::imshow("Answer009", out);
cv::waitKey(0);
cv::destroyAllWindows();
}
/** <!-- {{{1 --> @brief main function
* @return result of main
* @retval 0: success
*/
int main(int argc, const char** argv)
{
if (argc < 2) {
return -1;
}
// parse argument
uint32_t n = 0;
try {
n = std::stoul(argv[1]);
} catch (const std::invalid_argument& e) {
std::cout << "invalid argument: " << argv[1] << std::endl;
return -2;
} catch (const std::out_of_range& e) {
std::cout << "out of range: " << argv[1] << std::endl;
return -3;
}
if (n >= (sizeof(FUNC_TABLE) / sizeof(FUNC_TABLE[0]))) {
return -4;
}
// call function
FUNC_TABLE[n]();
return 0;
}
// end of file {{{1
// vim:ft=cpp:et:nowrap:fdm=marker
| [
"m2enu915vogel@gmail.com"
] | m2enu915vogel@gmail.com |
d5cc1697379f38f3eca96427ab374c49febecd7a | 12bc158f28f1b867791bf43be0190c5bc3f15ee4 | /src/Cat.h | ac82543268f422d1c1dd753d90ffb41d1ffe7670 | [] | no_license | myhendry/bootcamp | a2d542e2101a76aaa923e03e122e06937821bf90 | 4337040fe00e4a281522fd0629770ff77caa06aa | refs/heads/master | 2020-11-24T17:48:17.263358 | 2019-12-18T03:34:36 | 2019-12-18T03:34:36 | 228,279,354 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 178 | h | /*
* Cat.h
*
* Created on: 15 Dec 2019
* Author: hendrylim
*/
#ifndef CAT_H_
#define CAT_H_
class Cat {
public:
void speak();
void jump();
};
#endif /* CAT_H_ */
| [
"myhendry@gmail.com"
] | myhendry@gmail.com |
d180e4df26b4938c02f1ab5a192ea60d8d2d95de | 4e5488ca16bbbbae430a87486d51ab4c9c7cc959 | /strongtalk/src/cpp/main/vm/oop/MethodOopDescriptor.hpp | f7c1dcb965dc9ca567ccfc1ec899ed2a0864e643 | [] | no_license | RalfBarkow/strongtalk-2020 | 3cbf0286b18e3ac48b315509e77215e8ed4c6bcd | b51c02d5e30c0c728fece29037fdcd81f7f5803a | refs/heads/master | 2023-03-19T06:22:52.079759 | 2021-03-14T20:27:14 | 2021-03-14T20:27:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,010 | hpp | //
// (C) 1994 - 2021, The Strongtalk authors and contributors
// Refer to the "COPYRIGHTS" file at the root of this source tree for complete licence and copyright terms
//
#pragma once
#include "vm/platform/platform.hpp"
#include "vm/oop/MemOopDescriptor.hpp"
#include "vm/interpreter/MissingMethodBuilder.hpp"
#include "vm/interpreter/ByteCodes.hpp"
#include "vm/runtime/Frame.hpp"
#include "vm/runtime/flags.hpp"
#include "vm/utility/GrowableArray.hpp"
#include "vm/utility/ConsoleOutputStream.hpp"
// A methodOop is a method with byte codes.
const std::int32_t method_size_mask_bitno = 2;
const std::int32_t method_size_mask_size = 18;
const std::int32_t method_args_mask_bitno = method_size_mask_bitno + method_size_mask_size;
const std::int32_t method_args_mask_size = 4;
const std::int32_t method_flags_mask_bitno = method_args_mask_bitno + method_args_mask_size;
const std::int32_t method_flags_mask_size = 8;
class InterpretedInlineCache;
class MethodOopDescriptor : public MemOopDescriptor {
private:
ObjectArrayOop _debugInfo; //
Oop _selector_or_method; // selector for normal methods, enclosing method for blocks
std::int32_t _counters; // invocation counter and sharing counter
SmallIntegerOop _size_and_flags; //
// [flags (8 bits), nofArgs (4 bits), size in oops (18 bits), tag (2 bits)]
MethodOopDescriptor *addr() const {
return (MethodOopDescriptor *) MemOopDescriptor::addr();
}
// returns the header size of a methodOop
static std::int32_t header_size() {
return sizeof( MethodOopDescriptor ) / OOP_SIZE;
}
public:
// offsets for code generation
static std::int32_t selector_or_method_byte_offset() {
return std::int32_t( &( ( (MethodOopDescriptor *) nullptr )->_selector_or_method ) ) - MEMOOP_TAG;
}
static std::int32_t counters_byte_offset() {
return std::int32_t( &( ( (MethodOopDescriptor *) nullptr )->_counters ) ) - MEMOOP_TAG;
}
static std::int32_t codes_byte_offset() {
return sizeof( MethodOopDescriptor ) - MEMOOP_TAG;
}
SmallIntegerOop size_and_flags() const {
return addr()->_size_and_flags;
}
void set_size_and_flags( std::int32_t size, std::int32_t nofArgs, std::int32_t flags ) {
addr()->_size_and_flags = (SmallIntegerOop) ( ( flags << method_flags_mask_bitno ) + ( nofArgs << method_args_mask_bitno ) + ( size << method_size_mask_bitno ) );
}
std::int32_t flags() const {
return get_unsigned_bitfield( (std::int32_t) size_and_flags(), method_flags_mask_bitno, method_flags_mask_size );
}
void set_flags( std::int32_t flags ) {
set_size_and_flags( size_of_codes(), nofArgs(), flags );
}
std::int32_t nofArgs() const { // number of arguments (excluding receiver)
return get_unsigned_bitfield( (std::int32_t) size_and_flags(), method_args_mask_bitno, method_args_mask_size );
}
public:
friend MethodOop as_methodOop( void *p );
void bootstrap_object( Bootstrap *stream );
// Tester
bool is_blockMethod() const {
return not selector_or_method()->isSymbol();
}
ObjectArrayOop debugInfo() const {
return addr()->_debugInfo;
}
void set_debugInfo( ObjectArrayOop d ) {
addr()->_debugInfo = d;
}
SymbolOop selector() const;
MethodOop parent() const; // returns the enclosing block or method (for blocks), or nullptr
MethodOop home() const; // returns the enclosing method (for blocks), or itself
Oop selector_or_method() const {
return addr()->_selector_or_method;
}
void set_selector_or_method( Oop value ) {
addr()->_selector_or_method = value;
}
// returns the enclosing method's selector (block methods only)
SymbolOop enclosing_method_selector() const;
// returns the source if the debugInfo is present, otherwise nullptr.
ByteArrayOop source();
// returns the tempInfo if the debugInfo is present, otherwise nullptr.
ObjectArrayOop tempInfo();
// Generates an array with fileout information.
// The array contains pair of information:
// (true, SmallInteger) means character
// (false, Oop) means Oop
ObjectArrayOop fileout_body();
// Accessor operaions on counters.
// invocation counter - tells how many times this methodOop has been executed (may decay over time)
// sharing counter - tells how many callers this methodOop has.
enum {
_short_size = 16, //
_invocation_count_offset = _short_size, //
_invocation_count_width = _short_size, //
_invocation_count_max = ( 1 << _short_size ) - 1, //
_sharing_count_offset = 0, //
_sharing_count_width = _short_size, //
_sharing_count_max = ( 1 << _short_size ) - 1 //
};
std::int32_t counters() const {
return addr()->_counters;
}
void set_counters( std::int32_t inv, std::int32_t share ) {
addr()->_counters = ( inv << _invocation_count_offset ) | share;
}
// Invocation counter
std::int32_t invocation_count() const {
return get_unsigned_bitfield( counters(), _invocation_count_offset, _invocation_count_width );
}
void set_invocation_count( std::int32_t value ) {
set_counters( value, sharing_count() );
}
void decay_invocation_count( double decay_factor );
// Sharing counter (number of callers)
std::int32_t sharing_count() const {
return get_unsigned_bitfield( counters(), _sharing_count_offset, _sharing_count_width );
}
void set_sharing_count( std::int32_t value ) {
set_counters( invocation_count(), value );
}
void inc_sharing_count();
void dec_sharing_count();
bool was_never_executed(); // was method never executed? (count = 0, empty inline caches)
std::int32_t size_of_codes() const { // size of byte codes in words
return get_unsigned_bitfield( (std::int32_t) size_and_flags(), method_size_mask_bitno, method_size_mask_size );
}
void set_size_of_code( std::int32_t size ) {
set_size_and_flags( size, nofArgs(), flags() );
}
// Returns a pointer to the hybrid code at 'offset'
std::uint8_t *codes( std::int32_t offset = 1 ) const {
return (std::uint8_t *) addr() + sizeof( MethodOopDescriptor ) + offset - 1;
}
std::uint8_t *codes_end() const {
return codes() + size_of_codes() * OOP_SIZE;
}
// find methodOop given an hcode pointer
static MethodOop methodOop_from_hcode( std::uint8_t *hp );
std::uint8_t byte_at( std::int32_t offset ) const {
return *codes( offset );
}
void byte_at_put( std::int32_t offset, std::uint8_t c ) {
*codes( offset ) = c;
}
std::int32_t word_at( std::int32_t offset ) const {
return *(std::int32_t *) codes( offset );
}
void word_at_put( std::int32_t offset, std::uint32_t w ) {
*(std::int32_t *) codes( offset ) = w;
}
Oop oop_at( std::int32_t offset ) const {
return *(Oop *) codes( offset );
}
void oop_at_put( std::int32_t offset, Oop obj ) {
*(Oop *) codes( offset ) = obj;
}
// Returns the next byte code index based on hp.
std::int32_t next_byteCodeIndex_from( std::uint8_t *hp ) const;
// Returns the current byte code index based on hp (points to the next byte code)
std::int32_t byteCodeIndex_from( std::uint8_t *hp ) const;
std::int32_t number_of_arguments() const;
// Returns the number of temporaries allocated by the interpreter
// (excluding receiver & float temporaries, which may come afterwards).
std::int32_t number_of_stack_temporaries() const;
// Method with hardwired floating-point operations
bool has_float_temporaries() const {
return *codes( 1 ) == static_cast<std::uint8_t>(ByteCodes::Code::float_allocate);
}
std::int32_t number_of_float_temporaries() const {
return has_float_temporaries() ? *codes( 3 ) : 0;
}
std::int32_t float_expression_stack_size() const {
return has_float_temporaries() ? *codes( 4 ) : 0;
}
std::int32_t total_number_of_floats() const {
return number_of_float_temporaries() + float_expression_stack_size();
}
// Stack frame layout if there's a float section (offset & size in oops relative to ebp)
std::int32_t float_offset( std::int32_t float_no ) const;
std::int32_t float_section_start_offset() const {
return frame_temp_offset - number_of_stack_temporaries();
}
std::int32_t float_section_size() const {
return total_number_of_floats() * SIZEOF_FLOAT / OOP_SIZE;
}
// Testers
bool is_accessMethod() const {
return *codes() == static_cast<std::uint8_t>(ByteCodes::Code::return_instVar);
}
bool is_primitiveMethod() const;
// For predicted sends (small_int_t +, -, *, etc.)
bool is_special_primitiveMethod() const {
return *codes( 1 ) == static_cast<std::uint8_t>(ByteCodes::Code::special_primitive_send_1_hint);
}
ByteCodes::Code special_primitive_code() const;
// Information needed by the optimizing compiler
//
// Incoming_Info describes the possible Oop kinds that a methodOop gets 'from' the
// outside (via the closure) when invoked. Currently, the incoming Oop is stored in
// the recv and temp0 stack location for blocks, and in the recv location only for
// methods (ordinary send). This should change at some point and the incoming Oop
// should be stored in the recv location only (allows better stack usage).
//
// Temporaries_Info is used to compute the number of stack-allocated temporaries. If
// more than two temporaries are needed, the very first bytecode is an allocate temp
// byte code (bytecode invariant).
enum Flags {
// general flags
containsNonLocalReturnFlag = 0, //
allocatesContextFlag = 1, //
mustBeCustomizedFlag = 2, //
isCustomizedFlag = 3, //
// method specific flags (overlapping with block specific flags)
methodInfoFlags = isCustomizedFlag + 1, //
methodInfoSize = 2, //
// block specific flags (overlapping with method specific flags)
blockInfoFlags = methodInfoFlags, //
blockInfoSize = methodInfoSize //
};
// Flags for inlining
enum Method_Inlining_Info {
never_inline = 0, //
normal_inline = 1, //
always_inline = 2, //
};
Method_Inlining_Info method_inlining_info() const;
void set_method_inlining_info( Method_Inlining_Info info );
enum Block_Info {
expects_nil = 0, // 'clean' block
expects_self = 1, // 'copying' block
expects_parameter = 2, // 'copying' block
expects_context = 3 // 'full' block
};
Block_Info block_info() const;
// Tells if an activation of this method has a context stored as temp 0.
bool activation_has_context() const {
return allocatesInterpretedContext() or ( is_blockMethod() and expectsContext() );
}
// Tells if byteCodeIndex is a context allocation
bool in_context_allocation( std::int32_t byteCodeIndex ) const;
bool containsNonLocalReturn() const {
return isBitSet( flags(), containsNonLocalReturnFlag );
}
bool allocatesInterpretedContext() const {
return isBitSet( flags(), allocatesContextFlag );
}
bool mustBeCustomizedToClass() const {
return isBitSet( flags(), mustBeCustomizedFlag );
}
bool expectsContext() const {
return block_info() == expects_context;
}
bool hasNestedBlocks() const;
bool is_clean_block() const {
return block_info() == expects_nil;
}
bool is_copying_block() const {
return block_info() == expects_self or block_info() == expects_parameter;
}
bool is_full_block() const {
return block_info() == expects_context;
}
// Method customization
bool has_instVar_access() const {
return true;
} // for now - conservative - FIX THIS
bool has_classVar_access() const {
return true;
} // for now - conservative - FIX THIS
bool has_inlineCache() const {
return true;
} // for now - conservative - FIX THIS
bool is_customized() const {
return isBitSet( flags(), isCustomizedFlag );
}
bool should_be_customized() const {
return has_instVar_access() or has_classVar_access() or has_inlineCache();
}
// Returns a deep copy of the methodOop
MethodOop copy_for_customization() const;
// Customize method to klass
void customize_for( KlassOop klass, MixinOop mixin );
void uncustomize_for( MixinOop mixin );
// Uplevel accesses via contexts
std::int32_t lexicalDistance( std::int32_t contextNo ); // for uplevel accesses; see comment in .c file
std::int32_t contextNo( std::int32_t lexicalDistance ); // inverse of lexicalDistance()
// Computes the number of interpreter contexts from here up to the home method
std::int32_t context_chain_length() const;
// Clears all the inline caches in the method.
void clear_inline_caches();
// Cleanup all inline caches
void cleanup_inline_caches();
// Computes the estimated cost of a method by summing
// cost of all byte codes (see code_cost in methodOop.cpp).
std::int32_t estimated_inline_cost( KlassOop receiverKlass );
// Finds the byteCodeIndex based on the next byteCodeIndex
// Returns -1 if the search failed.
std::int32_t find_byteCodeIndex_from( std::int32_t nbyteCodeIndex ) const;
// Returns the next byteCodeIndex
std::int32_t next_byteCodeIndex( std::int32_t byteCodeIndex ) const;
// Returns the end byteCodeIndex (excluding the padding)
std::int32_t end_byteCodeIndex() const;
// Returns the inline cache associated with the send at byteCodeIndex.
InterpretedInlineCache *ic_at( std::int32_t byteCodeIndex ) const;
// Returns an array of byte code indecies contributing to the expression stack
GrowableArray<std::int32_t> *expression_stack_mapping( std::int32_t byteCodeIndex );
// For debugging only
void print_codes();
void pretty_print();
// Printing support
void print_value_for( KlassOop receiver_klass, ConsoleOutputStream *stream = nullptr );
// Inlining database support
void print_inlining_database_on( ConsoleOutputStream *stream );
std::int32_t byteCodeIndex_for_block_method( MethodOop inner );
MethodOop block_method_at( std::int32_t byteCodeIndex );
// Returns the numbers of temporaries allocated in a context.
// self_in_context tells if self is copied into context.
// Note: This function is extremely slow, so please use it for
// verify and debug code only.
std::int32_t number_of_context_temporaries( bool *self_in_context = nullptr );
// Checks if the context matches this method
void verify_context( ContextOop con );
// Query primitives
ObjectArrayOop referenced_instance_variable_names( MixinOop mixin ) const;
ObjectArrayOop referenced_class_variable_names() const;
ObjectArrayOop referenced_global_names() const;
ObjectArrayOop senders() const;
friend class MethodKlass;
};
inline MethodOop as_methodOop( void *p ) {
return MethodOop( as_memOop( p ) );
}
class StopInSelector : public ValueObject {
private:
static bool ignored;
bool enable;
bool stop;
FlagSetting oldFlag;
public:
StopInSelector( const char *class_name, const char *name, KlassOop klass, Oop method_or_selector, bool &fl = StopInSelector::ignored, bool stop = true );
};
| [
"hello@georgecox.com"
] | hello@georgecox.com |
d305620f5f74e19a2583155aabd23e1f9d4199cb | 75170796d8bdb28af03535327c6b2e3a9db5aff7 | /old/betacopter/old/betacopter34rc5-v21r/libraries/SITL/SIM_Multicopter.h | a24dc59e71fdefe462552c07d9ea17da15074f3f | [] | no_license | olliw42/storm32bgc | 3428f2c4ea4de2709fd7070f5f02a480ecd0c343 | 1bc59f3f62aedb958c01c4ae1583a59d60ab9ecf | refs/heads/master | 2023-04-29T10:18:41.201912 | 2023-04-16T12:32:24 | 2023-04-16T12:32:24 | 14,874,975 | 509 | 284 | null | null | null | null | UTF-8 | C++ | false | false | 1,458 | h | /// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
multicopter simulator class
*/
#pragma once
#include "SIM_Aircraft.h"
#include "SIM_Motor.h"
#include "SIM_Frame.h"
namespace SITL {
/*
a multicopter simulator
*/
class MultiCopter : public Aircraft {
public:
MultiCopter(const char *home_str, const char *frame_str);
/* update model by one time step */
void update(const struct sitl_input &input);
/* static object creator */
static Aircraft *create(const char *home_str, const char *frame_str) {
return new MultiCopter(home_str, frame_str);
}
protected:
// calculate rotational and linear accelerations
void calculate_forces(const struct sitl_input &input, Vector3f &rot_accel, Vector3f &body_accel);
Frame *frame;
};
}
| [
"waldmanns@gmx.de"
] | waldmanns@gmx.de |
12fef39a8b9b628afad885581623a1e963a124d2 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/106/678/CWE590_Free_Memory_Not_on_Heap__delete_array_long_declare_41.cpp | 34af3e5b8b422430fb7411e6647ab43b9720a620 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,773 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_long_declare_41.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml
Template File: sources-sink-41.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: declare Data buffer is declared on the stack
* GoodSource: Allocate memory on the heap
* Sink:
* BadSink : Print then free data
* Flow Variant: 41 Data flow: data passed as an argument from one function to another in the same source file
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_array_long_declare_41
{
#ifndef OMITBAD
void badSink(long * data)
{
printLongLine(data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
void bad()
{
long * data;
data = NULL; /* Initialize data */
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
long dataBuffer[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i] = 5L;
}
}
data = dataBuffer;
}
badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
void goodG2BSink(long * data)
{
printLongLine(data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
long * data;
data = NULL; /* Initialize data */
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
long * dataBuffer = new long[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i] = 5L;
}
}
data = dataBuffer;
}
goodG2BSink(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE590_Free_Memory_Not_on_Heap__delete_array_long_declare_41; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
e37f804e87b04402a39c86018a149a8e317beb89 | 98bb672dd2b2a5786053960ee3d60853c6d22ab5 | /CSCI 61/Binary_Search_Tree/node.cpp | 136ec866e190d57b20c9536e9449e805d3016b00 | [] | no_license | patselover/CSCI-10-60-61 | 6d6a9c1096197cc5e6fdc0d73597b3ce030a7031 | 7f21bd681d395c696a4bbece1c1f97dda36d2031 | refs/heads/master | 2021-04-29T14:28:20.209958 | 2018-02-16T17:03:29 | 2018-02-16T17:03:29 | 121,773,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 372 | cpp | #include "node.h"
#include <string>
//CONSTRUCTOR
node::node(const int & init_data, node * right, node * left){
_data = init_data;
_right_link = right;
_left_link = left;
}
void node::set_left_link(node * link){
_left_link = link;
}
void node::set_right_link(node * link){
_right_link = link;
}
void node::set_value(int value){
_data = value;
}
| [
"patselover@gmail.com"
] | patselover@gmail.com |
60db67f82e210e67aa3a6e2672457ce24d3bc8ac | cccfb7be281ca89f8682c144eac0d5d5559b2deb | /chrome/browser/lacros/lacros_extension_apps_publisher.cc | ac7b2b5f55e47635c42eef3dc50ac21d55b6c503 | [
"BSD-3-Clause"
] | permissive | SREERAGI18/chromium | 172b23d07568a4e3873983bf49b37adc92453dd0 | fd8a8914ca0183f0add65ae55f04e287543c7d4a | refs/heads/master | 2023-08-27T17:45:48.928019 | 2021-11-11T22:24:28 | 2021-11-11T22:24:28 | 428,659,250 | 1 | 0 | BSD-3-Clause | 2021-11-16T13:08:14 | 2021-11-16T13:08:14 | null | UTF-8 | C++ | false | false | 16,227 | cc | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/lacros/lacros_extension_apps_publisher.h"
#include <utility>
#include "base/containers/extend.h"
#include "base/scoped_observation.h"
#include "chrome/browser/apps/app_service/intent_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_ui_util.h"
#include "chrome/browser/lacros/lacros_extension_apps_utility.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/app_list/extension_app_utils.h"
#include "chrome/browser/ui/lacros/window_utility.h"
#include "chromeos/crosapi/mojom/app_window_tracker.mojom.h"
#include "chromeos/lacros/lacros_service.h"
#include "components/services/app_service/public/mojom/types.mojom.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/app_window/app_window_registry.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_prefs_observer.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_observer.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/management_policy.h"
#include "extensions/browser/unloaded_extension_reason.h"
namespace {
// Returns whether the extension is a chrome app. This class only tracks
// chrome apps.
bool IsChromeApp(const extensions::Extension* extension) {
return extension->is_platform_app();
}
apps::mojom::InstallReason GetInstallReason(
const extensions::Extension* extension) {
if (extensions::Manifest::IsComponentLocation(extension->location()))
return apps::mojom::InstallReason::kSystem;
if (extensions::Manifest::IsPolicyLocation(extension->location()))
return apps::mojom::InstallReason::kPolicy;
if (extension->was_installed_by_oem())
return apps::mojom::InstallReason::kOem;
if (extension->was_installed_by_default())
return apps::mojom::InstallReason::kDefault;
return apps::mojom::InstallReason::kUser;
}
} // namespace
// This class tracks all extension apps associated with a given Profile*. The
// observation of ExtensionPrefsObserver and ExtensionRegistryObserver is used
// to track AppService publisher events. The observation of AppsWindowRegistry
// is used to track window creation and destruction.
class LacrosExtensionAppsPublisher::ProfileTracker
: public extensions::ExtensionPrefsObserver,
public extensions::ExtensionRegistryObserver,
public extensions::AppWindowRegistry::Observer {
using Readiness = apps::mojom::Readiness;
public:
ProfileTracker(Profile* profile, LacrosExtensionAppsPublisher* publisher)
: profile_(profile), publisher_(publisher) {
// Start observing for relevant events.
prefs_observation_.Observe(extensions::ExtensionPrefs::Get(profile_));
registry_observation_.Observe(extensions::ExtensionRegistry::Get(profile_));
app_window_registry_observation_.Observe(
extensions::AppWindowRegistry::Get(profile_));
// Populate initial conditions [e.g. installed apps prior to starting
// observation].
std::vector<apps::mojom::AppPtr> apps;
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(profile_);
for (const scoped_refptr<const extensions::Extension> extension :
registry->enabled_extensions()) {
if (IsChromeApp(extension.get())) {
apps.push_back(MakeApp(extension.get(), Readiness::kReady));
}
}
for (const scoped_refptr<const extensions::Extension> extension :
registry->disabled_extensions()) {
if (IsChromeApp(extension.get())) {
apps.push_back(MakeApp(extension.get(), Readiness::kDisabledByUser));
}
}
for (const scoped_refptr<const extensions::Extension> extension :
registry->terminated_extensions()) {
if (IsChromeApp(extension.get())) {
apps.push_back(MakeApp(extension.get(), Readiness::kTerminated));
}
}
if (!apps.empty())
Publish(std::move(apps));
// Populate initial conditions [e.g. app windows created prior to starting
// observation].
for (extensions::AppWindow* app_window :
extensions::AppWindowRegistry::Get(profile_)->app_windows()) {
OnAppWindowAdded(app_window);
}
}
~ProfileTracker() override = default;
private:
// extensions::ExtensionPrefsObserver overrides.
void OnExtensionLastLaunchTimeChanged(
const std::string& app_id,
const base::Time& last_launch_time) override {
const auto* extension =
lacros_extension_apps_utility::MaybeGetPackagedV2App(profile_, app_id);
if (!extension)
return;
Publish(MakeApp(extension, Readiness::kReady));
}
void OnExtensionPrefsWillBeDestroyed(
extensions::ExtensionPrefs* prefs) override {
DCHECK(prefs_observation_.IsObservingSource(prefs));
prefs_observation_.Reset();
}
// extensions::ExtensionRegistryObserver overrides.
void OnExtensionLoaded(content::BrowserContext* browser_context,
const extensions::Extension* extension) override {
if (!IsChromeApp(extension))
return;
apps::mojom::AppPtr app = MakeApp(extension, Readiness::kReady);
Publish(std::move(app));
}
void OnExtensionUnloaded(
content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionReason reason) override {
if (!IsChromeApp(extension))
return;
Readiness readiness = Readiness::kUnknown;
switch (reason) {
case extensions::UnloadedExtensionReason::DISABLE:
readiness = Readiness::kDisabledByUser;
break;
case extensions::UnloadedExtensionReason::BLOCKLIST:
readiness = Readiness::kDisabledByBlocklist;
break;
case extensions::UnloadedExtensionReason::TERMINATE:
readiness = Readiness::kTerminated;
break;
case extensions::UnloadedExtensionReason::UNINSTALL:
// App readiness will be updated by OnExtensionUninstalled(). We defer
// to that method.
return;
case extensions::UnloadedExtensionReason::UNDEFINED:
case extensions::UnloadedExtensionReason::UPDATE:
case extensions::UnloadedExtensionReason::PROFILE_SHUTDOWN:
case extensions::UnloadedExtensionReason::LOCK_ALL:
case extensions::UnloadedExtensionReason::MIGRATED_TO_COMPONENT:
return;
}
apps::mojom::AppPtr app = MakeApp(extension, readiness);
Publish(std::move(app));
}
void OnExtensionInstalled(content::BrowserContext* browser_context,
const extensions::Extension* extension,
bool is_update) override {
if (!IsChromeApp(extension))
return;
apps::mojom::AppPtr app = MakeApp(extension, Readiness::kReady);
Publish(std::move(app));
}
void OnExtensionUninstalled(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UninstallReason reason) override {
if (!IsChromeApp(extension))
return;
apps::mojom::AppPtr app =
MakeApp(extension, reason == extensions::UNINSTALL_REASON_MIGRATED
? Readiness::kUninstalledByMigration
: Readiness::kUninstalledByUser);
Publish(std::move(app));
}
void OnShutdown(extensions::ExtensionRegistry* registry) override {
registry_observation_.Reset();
}
// AppWindowRegistry::Observer overrides.
void OnAppWindowAdded(extensions::AppWindow* app_window) override {
std::string muxed_id = lacros_extension_apps_utility::MuxId(
profile_, app_window->GetExtension());
std::string window_id = lacros_window_utility::GetRootWindowUniqueId(
app_window->GetNativeWindow());
app_window_id_cache_[app_window] = window_id;
publisher_->OnAppWindowAdded(muxed_id, window_id);
}
void OnAppWindowRemoved(extensions::AppWindow* app_window) override {
auto it = app_window_id_cache_.find(app_window);
DCHECK(it != app_window_id_cache_.end());
std::string muxed_id = lacros_extension_apps_utility::MuxId(
profile_, app_window->GetExtension());
std::string window_id = it->second;
publisher_->OnAppWindowRemoved(muxed_id, window_id);
}
// Publishes a differential update to the app service.
void Publish(apps::mojom::AppPtr app) {
std::vector<apps::mojom::AppPtr> apps;
apps.push_back(std::move(app));
Publish(std::move(apps));
}
// Publishes a vector of differential updates to the app service.
void Publish(std::vector<apps::mojom::AppPtr> apps) {
publisher_->Publish(std::move(apps));
}
// Whether the app should be shown in the launcher, shelf, etc.
bool ShouldShow(const extensions::Extension* extension) {
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(profile_);
const std::string& app_id = extension->id();
// These three extension sets are the same three consulted by the
// constructor. Importantly, it will exclude previously installed but
// currently uninstalled extensions.
bool connected = registry->enabled_extensions().Contains(app_id) ||
registry->disabled_extensions().Contains(app_id) ||
registry->terminated_extensions().Contains(app_id);
if (!connected)
return false;
return extensions::ui_util::ShouldDisplayInAppLauncher(extension, profile_);
}
// Creates an AppPtr from an extension.
apps::mojom::AppPtr MakeApp(const extensions::Extension* extension,
Readiness readiness) {
DCHECK(IsChromeApp(extension));
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_type = apps::mojom::AppType::kStandaloneBrowserExtension;
app->app_id = lacros_extension_apps_utility::MuxId(profile_, extension);
app->readiness = readiness;
app->name = extension->name();
app->short_name = extension->short_name();
// We always use an empty icon key since we currently do not support
// dynamically changing icons or modifying the appearance of icons.
// This bug is tracked at https://crbug.com/1248499, but given that Chrome
// Apps is deprecated, it's unclear if we'll ever get around to implementing
// this functionality.
app->icon_key = apps::mojom::IconKey::New();
auto* prefs = extensions::ExtensionPrefs::Get(profile_);
if (prefs) {
app->last_launch_time = prefs->GetLastLaunchTime(extension->id());
app->install_time = prefs->GetInstallTime(extension->id());
} else {
app->last_launch_time = base::Time();
app->install_time = base::Time();
}
app->install_reason = GetInstallReason(extension);
app->recommendable = apps::mojom::OptionalBool::kTrue;
app->searchable = apps::mojom::OptionalBool::kTrue;
app->paused = apps::mojom::OptionalBool::kFalse;
apps::mojom::OptionalBool show = ShouldShow(extension)
? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
app->show_in_launcher = show;
app->show_in_shelf = show;
app->show_in_search = show;
app->show_in_management = extension->ShouldDisplayInAppLauncher()
? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
app->handles_intents = show;
const extensions::ManagementPolicy* policy =
extensions::ExtensionSystem::Get(profile_)->management_policy();
app->allow_uninstall = (policy->UserMayModifySettings(extension, nullptr) &&
!policy->MustRemainInstalled(extension, nullptr))
? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
// Add file_handlers.
base::Extend(app->intent_filters,
apps_util::CreateChromeAppIntentFilters(extension));
return app;
}
// This pointer is guaranteed to be valid and to outlive this object.
Profile* const profile_;
// This pointer is guaranteed to be valid and to outlive this object.
LacrosExtensionAppsPublisher* const publisher_;
// Observes both extension prefs and registry for events that affect
// extensions.
base::ScopedObservation<extensions::ExtensionPrefs,
extensions::ExtensionPrefsObserver>
prefs_observation_{this};
base::ScopedObservation<extensions::ExtensionRegistry,
extensions::ExtensionRegistryObserver>
registry_observation_{this};
// Observes AppWindowRegistry for app window creation and destruction.
base::ScopedObservation<extensions::AppWindowRegistry,
extensions::AppWindowRegistry::Observer>
app_window_registry_observation_{this};
// Records the window id associated with an app window. This is needed since
// the app window destruction callback occurs after the window is destroyed.
std::map<extensions::AppWindow*, std::string> app_window_id_cache_;
};
LacrosExtensionAppsPublisher::LacrosExtensionAppsPublisher() = default;
LacrosExtensionAppsPublisher::~LacrosExtensionAppsPublisher() = default;
void LacrosExtensionAppsPublisher::Initialize() {
if (!InitializeCrosapi())
return;
profile_manager_observation_.Observe(g_browser_process->profile_manager());
auto profiles = g_browser_process->profile_manager()->GetLoadedProfiles();
for (auto* profile : profiles) {
// TODO(https://crbug.com/1254894): The app id is not stable for secondary
// profiles and cannot be stored in sync. Thus, the app cannot be published
// at all.
if (!profile->IsMainProfile())
continue;
profile_trackers_[profile] =
std::make_unique<ProfileTracker>(profile, this);
}
}
bool LacrosExtensionAppsPublisher::InitializeCrosapi() {
// Ash is too old to support the chrome app publisher interface.
int crosapiVersion = chromeos::LacrosService::Get()->GetInterfaceVersion(
crosapi::mojom::Crosapi::Uuid_);
int minRequiredVersion = static_cast<int>(
crosapi::mojom::Crosapi::kBindChromeAppPublisherMinVersion);
if (crosapiVersion < minRequiredVersion)
return false;
// Ash is too old to support the chrome app window tracker interface.
if (!chromeos::LacrosService::Get()
->IsAvailable<crosapi::mojom::AppWindowTracker>()) {
return false;
}
chromeos::LacrosService::Get()
->BindPendingReceiverOrRemote<
mojo::PendingReceiver<crosapi::mojom::AppPublisher>,
&crosapi::mojom::Crosapi::BindChromeAppPublisher>(
publisher_.BindNewPipeAndPassReceiver());
return true;
}
void LacrosExtensionAppsPublisher::Publish(
std::vector<apps::mojom::AppPtr> apps) {
publisher_->OnApps(std::move(apps));
}
void LacrosExtensionAppsPublisher::OnAppWindowAdded(
const std::string& app_id,
const std::string& window_id) {
chromeos::LacrosService::Get()
->GetRemote<crosapi::mojom::AppWindowTracker>()
->OnAppWindowAdded(app_id, window_id);
}
void LacrosExtensionAppsPublisher::OnAppWindowRemoved(
const std::string& app_id,
const std::string& window_id) {
chromeos::LacrosService::Get()
->GetRemote<crosapi::mojom::AppWindowTracker>()
->OnAppWindowRemoved(app_id, window_id);
}
void LacrosExtensionAppsPublisher::OnProfileAdded(Profile* profile) {
// TODO(https://crbug.com/1254894): The app id is not stable for secondary
// profiles and cannot be stored in sync. Thus, the app cannot be published
// at all.
if (!profile->IsMainProfile())
return;
profile_trackers_[profile] = std::make_unique<ProfileTracker>(profile, this);
}
void LacrosExtensionAppsPublisher::OnProfileMarkedForPermanentDeletion(
Profile* profile) {
profile_trackers_.erase(profile);
}
void LacrosExtensionAppsPublisher::OnProfileManagerDestroying() {
profile_manager_observation_.Reset();
}
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
3992c54e0e40e66693baefbcdf1f5afbf4367bd4 | 54df3460be17467f1f55cf11dd5c5f07a3855e1d | /031702132/src/Sudoku/Sudoku/sudoku.cpp | 71293a520e7f5af79bee865a05b756fcf97f6800 | [] | no_license | jiangjz0010/031702132 | cc0de6a9be068e88622e3759e1946749b605bef7 | 3d7323ed4545808c030cda9bd8b0e2fa67999f78 | refs/heads/master | 2020-07-22T02:38:42.137023 | 2019-10-25T15:36:40 | 2019-10-25T15:36:40 | 210,255,261 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,581 | cpp | #include <iostream>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iomanip>
#include <stdlib.h>
using namespace std;
int a[10][10];//用来存储数独
int n; //所求的棋面数
int m;//数独的阶数
int sign = 0;//成功标记
FILE* fp1;
FILE* fp2;
bool judge_row_col(int x, int key)/*判断数独的每一列每一行是否重复*/
{
int row = x / m;
int col = x % m;
for (int i = 0; i < m; i++)/*判断行 */
{
if (a[row][i] == key)
{
return false;
}
}
for (int i = 0; i < m; i++)/*判断列*/
{
if (a[i][col] == key)
{
return false;
}
}
return true;
}
void print()/*把求解完的数独写入txt*/
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
fprintf(fp2, "%d", a[i][j]);/*写入txt*/
if (j < m - 1)
{
fprintf(fp2, " ");
}
}
fprintf(fp2, "\n");
}
}
void DFS(int x)/* 深搜构造数独 */
{
if (sign)/*如果已经完成 直接返回*/
{
return;
}
if (x == m * m)/* 说明所有的都符合,数独求解完毕,退出递归 */
{
print();
sign = 1;
return;
}
int row = x / m;
int col = x % m;
if (a[row][col] != 0)/*当前位不为空时跳过*/
{
DFS(x + 1);
}
else /* 否则对当前位进行枚举测试 */
{
for (int i = 1; i <= m; i++)
{
if (judge_row_col(x, i))
{
a[row][col] = i;/* 继续搜索 */
DFS(x + 1);/* 返回时如果构造成功,则直接退出 */
a[row][col] = 0;
}
}
}
}
int main(int argc, char* argv[])/*将答案按照要求输出*/
{
m = atoi(argv[2]);/*数独阶数*/
n = atoi(argv[4]);/*待求解的数独面数*/
char* inputfile = argv[6];/*输入的文件名:比如m3n5.txt*/
char* outputfile = argv[8];/*输出的文件名:比如outm3n5.txt*/
fp1 = fopen(inputfile, "r");/*打开输入文件*/
if (fp1 == NULL)/*如果文件不存在,返回错误*/
{
return -1;
}
fp2 = fopen(outputfile, "w");/*打开输出文件*/
if (fp2 == NULL) /*如果文件不存在,返回错误*/
{
return -1;
}
fclose(fp2);
while (n--)/*依次读取输入文件中的数独*/
{
int i, j;
memset(a, 0, sizeof(a));
sign = 0;
for (i = 0; i < m; i++)
{
for (j = 0; j < m; j++)
{
fscanf(fp1, "%d", &a[i][j]);/*读取数独*/
}
}
fp2 = fopen(outputfile, "a");/*打开输出文件*/
DFS(0);
if (n > 0)
{
fprintf(fp2, "\n");/*写入输出至文件*/
}
fclose(fp2);/*关闭输出文件*/
}
fclose(fp1);/*关闭输入文件*/
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
51dfcc9590d14c19acff5c43fcd29736f484b8fc | f24e48592d519af6c15e8fd4c68e7e21746bc80e | /include/spear/atomtypes/GAFF.hpp | 8c476784e79589bf543debbd5d07d90487aeb13e | [
"BSD-2-Clause"
] | permissive | chopralab/spear | 2481187c69f779eee6efedae7847f2a2bcc26066 | d45ffc907ab1730789413dd04afb347a26f35154 | refs/heads/master | 2020-06-23T16:23:10.411151 | 2019-07-24T16:59:37 | 2019-07-24T16:59:37 | 198,677,846 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,264 | hpp | // Spear: Statistical Platform for Elucidating moleculAr Reactivity
// Copyright (C) Purdue University -- BSD license
#ifndef SPEAR_GAFF_HPP
#define SPEAR_GAFF_HPP
#include "spear/AtomType.hpp"
#include <map>
namespace Spear {
class Molecule;
class SPEAR_EXPORT GAFF : public AtomType {
public:
GAFF(const Molecule& mol);
const std::string& name() const override {
return name_;
}
size_t add_atom(size_t new_idx) override;
void add_bond(size_t idx1, size_t idx2, Bond::Order bo) override;
void remove_atom(size_t idx) override {
erase(begin() + static_cast<std::ptrdiff_t>(idx));
}
bool is_aromatic(size_t atom_id) const override;
bool is_planar(size_t atom_id) const override;
Hybridization hybridization(size_t /*atom_id*/) const override {
return Hybridization::FORCED;
}
private:
size_t add_atom_(size_t new_idx);
const Molecule& mol_;
const std::string name_ = "gaff";
};
template<> std::string SPEAR_EXPORT atomtype_name_for_id<GAFF>(size_t id);
template<> size_t SPEAR_EXPORT atomtype_id_for_name<GAFF>(const std::string& name);
template<> size_t SPEAR_EXPORT atomtype_id_count<GAFF>();
template<> double SPEAR_EXPORT van_der_waals<GAFF>(size_t id);
}
#endif
| [
"finej@purdue.edu"
] | finej@purdue.edu |
d32e369358d6e5dcf28646668f6a080d2ff83386 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /remoting/client/input/touch_input_strategy.h | 94e6625f9a6151adbb07172812720d3b57568fc3 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 3,101 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef REMOTING_CLIENT_TOUCH_INPUT_INPUT_STRATEGY_H_
#define REMOTING_CLIENT_TOUCH_INPUT_INPUT_STRATEGY_H_
#include "remoting/client/ui/view_matrix.h"
namespace remoting {
class DesktopViewport;
// This is an interface used by GestureInterpreter to customize the way gestures
// are handled.
class TouchInputStrategy {
public:
enum TouchFeedbackType {
TAP_FEEDBACK,
DRAG_FEEDBACK,
};
enum Gesture {
NONE,
ZOOM,
DRAG,
};
virtual ~TouchInputStrategy() {}
// Called when the GestureInterpreter receives a zoom gesture. The
// implementation is responsible for modifying the viewport and observing the
// change.
virtual void HandleZoom(const ViewMatrix::Point& pivot,
float scale,
DesktopViewport* viewport) = 0;
// Called when the GestureInterpreter receives a pan gesture. The
// implementation is responsible for modifying the viewport and observing the
// change.
// simultaneous_gesture: Gesture that is simultaneously in progress.
// Returns true if this changes the cursor position.
virtual bool HandlePan(const ViewMatrix::Vector2D& translation,
Gesture simultaneous_gesture,
DesktopViewport* viewport) = 0;
// Called when a touch input (which will end up injecting a mouse event at
// certain position in the host) is done at |touch_point|.
// The implementation should move the cursor to proper position.
//
// Returns true if |touch_point| is a valid input, false otherwise. If the
// input is not valid, the implementation should not change its cursor
// position.
virtual bool TrackTouchInput(const ViewMatrix::Point& touch_point,
const DesktopViewport& viewport) = 0;
// Returns the current cursor position.
virtual ViewMatrix::Point GetCursorPosition() const = 0;
// Focuses the viewport on the cursor position if necessary.
virtual void FocusViewportOnCursor(DesktopViewport* viewport) const = 0;
// Maps a vector (or movement) in the surface coordinate to the vector to be
// used on the desktop. For example it can be used to map a scroll gesture
// on the screen to change in mouse wheel position.
virtual ViewMatrix::Vector2D MapScreenVectorToDesktop(
const ViewMatrix::Vector2D& delta,
const DesktopViewport& viewport) const = 0;
// Returns the maximum radius of the feedback animation on the surface's
// coordinate for the given input type. The feedback will then be shown on the
// cursor positions returned by GetCursorPosition(). Return 0 if no feedback
// should be shown.
virtual float GetFeedbackRadius(TouchFeedbackType type) const = 0;
// Returns true if the input strategy maintains a visible cursor on the
// desktop.
virtual bool IsCursorVisible() const = 0;
};
} // namespace remoting
#endif // REMOTING_CLIENT_TOUCH_INPUT_INPUT_STRATEGY_H_
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
d1e7d433e8113b2c81561aa0d04a5582e17dcfb2 | 0d6011e5dea88bc2929d4ed94233ed497b26126e | /MyProject/Framework001/Framework001/main.cpp | 9120cb87cee8f88fe34cf39da3bf5d0a0efa0358 | [] | no_license | semin0427/DirectX11 | 03b8cc2ecf4c7432fda73baeafbaa3d758b2c03e | 113a3878fda815474ef4e6cd4a3910b41cb9b660 | refs/heads/master | 2021-05-05T21:28:48.818645 | 2018-01-24T04:12:14 | 2018-01-24T04:12:14 | 115,517,619 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 741 | cpp | ////////////////////////////////////////////////////////////////////////////////
// Filename: main.cpp
////////////////////////////////////////////////////////////////////////////////
#include "systemclass.h"
//int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow)
int main(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow)
{
SystemClass* System;
bool result;
// Create the system object.
System = new SystemClass;
if (!System)
{
return 0;
}
// Initialize and run the system object.
result = System->Initialize();
if (result)
{
System->Run();
}
// Shutdown and release the system object.
System->Shutdown();
delete System;
System = 0;
return 0;
} | [
"semin0427@naver.com"
] | semin0427@naver.com |
6c9de827ca2ed87cebee8edf6a731e4435da27a1 | c894cd35c59ac6166f2fea40e18e6aa65333ce2e | /MyChat/ChattingClient/NanaChattingClient/NanaChattingClient/TcpNetwork.cpp | b2260b24ed3ee6fa2355ef0dad12d49a8727d184 | [] | no_license | skdn159/GameServerLearning | 49ac9fb9db87ee926a61a3972aabb16873c8b8c3 | e01dd1ad3c14337664eaca6d6aa391ac5e91211c | refs/heads/master | 2020-04-06T07:02:41.021719 | 2016-09-07T02:01:41 | 2016-09-07T02:01:41 | 61,171,206 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,762 | cpp | #include "TcpNetwork.h"
TcpNetwork::TcpNetwork()
{
}
TcpNetwork::~TcpNetwork()
{
}
bool TcpNetwork::ConnectTo(const char* hostIP, int port)
{
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
return false;
}
m_sock = socket(AF_INET, SOCK_STREAM, 0);
if (m_sock == INVALID_SOCKET) {
return false;
}
SOCKADDR_IN s_addr_in;
ZeroMemory(&s_addr_in, sizeof(s_addr_in));
s_addr_in.sin_family = AF_INET;
s_addr_in.sin_port = htons(port);
inet_pton(AF_INET, hostIP, (void *)&s_addr_in.sin_addr.s_addr);
//connect
if (connect(m_sock, (SOCKADDR*)&s_addr_in, sizeof(s_addr_in)) != 0) {
return false;
}
//ClientLog("Connetct Server Success!\n");
m_IsConnected = true;
//socket Nonblocking
NonBlock(m_sock);
m_Thread = std::thread([&]() { Update(); });
return true;
}
void TcpNetwork::DisConnect()
{
if (m_IsConnected)
{
closesocket(m_sock);
Clear();
}
if (m_Thread.joinable()) {
m_Thread.join();
}
}
void TcpNetwork::SendPacket(const short packetId, const short dataSize, char* pData)
{
char data[MAX_PACKET_SIZE] = { 0, };
PacketHeader pktHeader{ packetId, dataSize };
memcpy(&data[0], (char*)&pktHeader, PACKET_HEADER_SIZE);
if (dataSize > 0) {
memcpy(&data[PACKET_HEADER_SIZE], pData, dataSize);
}
send(m_sock, data, dataSize + PACKET_HEADER_SIZE, 0);
}
void TcpNetwork::Update()
{
while (m_IsConnected)
{
//log("running...");
RecvData();
RecvBufferProcess();
}
}
RecvPacketInfo TcpNetwork::GetPacket()
{
std::lock_guard<std::mutex> guard(m_mutex);
if (m_PacketQueue.empty()) {
return RecvPacketInfo();
}
auto packet = m_PacketQueue.front();
m_PacketQueue.pop_front();
return packet;
}
void TcpNetwork::NonBlock(SOCKET s)
{
u_long u10n = 1L;
ioctlsocket(s, FIONBIO, (unsigned long*)&u10n);
}
void TcpNetwork::RecvData()
{
fd_set read_set;
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 100;
FD_ZERO(&read_set);
FD_SET(m_sock, &read_set);
if (select(m_sock + 1, &read_set, NULL, NULL, &tv) < 0) {
return;
}
if (FD_ISSET(m_sock, &read_set))
{
char recvBuff[MAX_PACKET_SIZE];
auto recvSize = recv(m_sock, recvBuff, MAX_PACKET_SIZE, 0);
if (recvSize == 0)
{
//ClientLog("RecvData Error!Connection Failed...");
return;
}
if (recvSize < 0)
{
// NonBlock
if (WSAGetLastError() != WSAEWOULDBLOCK)
{
//ClientLog("WSAGetLastError()!=WSAEWOULDBLOCK Error!");
return;
}
}
//Buffer Overflow
if ((m_recvSize + recvSize) >= MAX_SOCK_RECV_BUFFER)
{
//ClientLog("Buffer Overflow Error!");
return;
}
memcpy(&m_RecvBuffer[m_recvSize], recvBuff, recvSize);
m_recvSize += recvSize;
}
}
void TcpNetwork::RecvBufferProcess()
{
auto readPos = 0;
const auto dataSize = m_recvSize;
PacketHeader* pPktHeader;
while ((dataSize - readPos) > PACKET_HEADER_SIZE)
{
pPktHeader = (PacketHeader*)&m_RecvBuffer[readPos];
readPos += PACKET_HEADER_SIZE;
if (pPktHeader->BodySize > (dataSize - readPos))
{
break;
}
if (pPktHeader->BodySize > MAX_PACKET_SIZE)
{
return;// NET_ERROR_CODE::RECV_CLIENT_MAX_PACKET;
}
AddPacketQueue(pPktHeader->Id, pPktHeader->BodySize, &m_RecvBuffer[readPos]);
readPos += pPktHeader->BodySize;
}
m_recvSize -= readPos;
if (m_recvSize > 0)
{
memcpy(m_RecvBuffer, &m_RecvBuffer[readPos], m_recvSize);
}
}
void TcpNetwork::AddPacketQueue(const short pktId, const short bodySize, char* pDataPos)
{
RecvPacketInfo packetInfo;
packetInfo.PacketId = pktId;
packetInfo.PacketBodySize = bodySize;
packetInfo.pData = new char[bodySize];
memcpy(packetInfo.pData, pDataPos, bodySize);
std::lock_guard<std::mutex> guard(m_mutex);
m_PacketQueue.push_back(packetInfo);
}
void TcpNetwork::Clear()
{
m_IsConnected = false;
m_recvSize = 0;
m_PacketQueue.clear();
}
| [
"skdn159@naver.com"
] | skdn159@naver.com |
5260b7b16224c6d18f9a5695f6a03837eee406d9 | d789b0da588b5a0d3be82bb6e02d245ae91004bc | /3.7-2/3.7-2/程序设计-6.cpp | e6998e1fb1a8a1c88ec2921d7aa0cb31b29bdfa1 | [] | no_license | xx123456xx/C- | e8e19e345a5eb938f025b8b782b97c381c623afb | 533cd06e4574b7f8523173562ec14b3962812dac | refs/heads/master | 2023-03-21T14:09:29.337595 | 2021-03-21T14:02:46 | 2021-03-21T14:02:49 | 342,441,563 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 538 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
float fun(float a)
{
int tmp=0;
tmp=(int)(a*1000+5)/10;//单精度数a乘以1000后再加5,相当于对a中的第三位小数进行四舍五入,除以10后将其赋给一个长整型时,就把第三位小数后的数全部截取
return (float)tmp/100.0;//除以100,保留两位小数
}
int main()
{
float a;
system("CLS");
printf("Enter a: ");
scanf("%f",&a);
printf("The oringinal data is :");
printf("%f\n\n",a);
printf("The result :%f\n",fun(a));
} | [
"2359707894@qq.com"
] | 2359707894@qq.com |
3aa91111189e3bae21d4699789bc85dee9ca1261 | 699a07206dad2d5edc5bae8e51365ebcd1497984 | /src/core/model/unix-system-mutex.cc | 687a5d5ec0d6b72616e558900084349ad04b202e | [] | no_license | anyonepaw/ns3-iot-realisation | d5bc126968a737e476e656b21a5810241b9905bd | 02353ae9f1c8b4dc186a63b1e2f260a91aaa0447 | refs/heads/master | 2020-04-23T23:00:02.343096 | 2019-06-02T12:19:52 | 2019-06-02T12:19:52 | 171,520,704 | 7 | 5 | null | 2019-05-30T15:20:42 | 2019-02-19T17:44:57 | C++ | UTF-8 | C++ | false | false | 3,990 | cc | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mathieu Lacage <mathieu.lacage.inria.fr>
*/
#include <pthread.h>
#include <cstring>
#include <cerrno> // for strerror
#include "fatal-error.h"
#include "system-mutex.h"
#include "log.h"
/**
* @file
* @ingroup thread
* Mutex critical section primitive definitions for Unix-like systems.
*/
namespace ns3 {
NS_LOG_COMPONENT_DEFINE_MASK ("SystemMutex", ns3::LOG_PREFIX_TIME);
/** System-dependent implementation of SystemMutex. */
class SystemMutexPrivate {
public:
SystemMutexPrivate ();
~SystemMutexPrivate ();
void Lock (void); /**< Acquire ownership of the mutex. */
void Unlock (void); /**< Release ownership of the mutex. */
private:
pthread_mutex_t m_mutex; /**< The mutex. */
};
SystemMutexPrivate::SystemMutexPrivate ()
{
NS_LOG_FUNCTION (this);
pthread_mutexattr_t attr;
pthread_mutexattr_init (&attr);
//
// Make this an error checking mutex. This will check to see if the current
// thread already owns the mutex before trying to lock it. Instead of
// deadlocking it returns an error. It will also check to make sure a thread
// has previously called pthread_mutex_lock when it calls pthread_mutex_unlock.
//
// Linux and OS X (at least) have, of course chosen different names for the
// error checking flags just to make life difficult.
//
#if defined (PTHREAD_MUTEX_ERRORCHECK_NP)
pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
#else
pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK);
#endif
pthread_mutex_init (&m_mutex, &attr);
}
SystemMutexPrivate::~SystemMutexPrivate()
{
NS_LOG_FUNCTION (this);
pthread_mutex_destroy (&m_mutex);
}
void
SystemMutexPrivate::Lock (void)
{
NS_LOG_FUNCTION (this);
int rc = pthread_mutex_lock (&m_mutex);
if (rc != 0)
{
NS_FATAL_ERROR ("SystemMutexPrivate::Lock()"
"pthread_mutex_lock failed: " << rc << " = \"" <<
std::strerror (rc) << "\"");
}
}
void
SystemMutexPrivate::Unlock (void)
{
NS_LOG_FUNCTION (this);
int rc = pthread_mutex_unlock (&m_mutex);
if (rc != 0)
{
NS_FATAL_ERROR ("SystemMutexPrivate::Unlock()"
"pthread_mutex_unlock failed: " << rc << " = \"" <<
std::strerror (rc) << "\"");
}
}
SystemMutex::SystemMutex()
: m_priv (new SystemMutexPrivate ())
{
NS_LOG_FUNCTION (this);
}
SystemMutex::~SystemMutex()
{
NS_LOG_FUNCTION (this);
delete m_priv;
}
void
SystemMutex::Lock ()
{
NS_LOG_FUNCTION (this);
m_priv->Lock ();
}
void
SystemMutex::Unlock ()
{
NS_LOG_FUNCTION (this);
m_priv->Unlock ();
}
CriticalSection::CriticalSection (SystemMutex &mutex)
: m_mutex (mutex)
{
NS_LOG_FUNCTION (this << &mutex);
m_mutex.Lock ();
}
CriticalSection::~CriticalSection ()
{
NS_LOG_FUNCTION (this);
m_mutex.Unlock ();
}
} // namespace ns3 | [
"gabrielcarvfer@gmail.com"
] | gabrielcarvfer@gmail.com |
30a19119ed5f8befdcaa13583c86c3c21227169e | 23fa8a73b133e4f61558361a12a04aa4ff0385d0 | /runtime/ejs-regexp.c | 9f4ae3308162c4cefc4471fb6025ea3635502049 | [
"MIT"
] | permissive | soundyogi/echojs | 3a4929fccf21f48eb7ff42b04c062ecd271c2814 | 1c284eae7d027eb827e335d333c8f2cd28b839b0 | refs/heads/master | 2021-01-11T08:51:33.632317 | 2016-10-23T05:59:58 | 2016-10-23T05:59:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47,005 | c | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=4 sw=4 et tw=99 ft=cpp:
*/
#include <string.h>
#include "ejs-array.h"
#include "ejs-ops.h"
#include "ejs-value.h"
#include "ejs-regexp.h"
#include "ejs-function.h"
#include "ejs-string.h"
#include "ejs-error.h"
#include "ejs-symbol.h"
#include "ejs-proxy.h"
#include "ejs-number.h"
#include "pcre.h"
static EJS_NATIVE_FUNC(_ejs_RegExp_impl);
static const unsigned char* pcre16_tables;
EJSBool IsRegExp(ejsval argument) {
// 1. If Type(argument) is not Object, return false.
if (!EJSVAL_IS_OBJECT(argument))
return EJS_FALSE;
// 2. Let isRegExp be Get(argument, @@match).
// 3. ReturnIfAbrupt(isRegExp).
ejsval isRegExp = Get(argument, _ejs_Symbol_match);
// 4. If isRegExp is not undefined, return ToBoolean(isRegExp).
if (!EJSVAL_IS_UNDEFINED(isRegExp))
return ToEJSBool(isRegExp);
// 5. If argument has a [[RegExpMatcher]] internal slot, return true.
if (EJSVAL_IS_REGEXP(argument))
return EJS_TRUE;
// 6. Return false.
return EJS_FALSE;
}
ejsval
_ejs_regexp_new (ejsval pattern, ejsval flags)
{
EJSRegExp* rv = _ejs_gc_new(EJSRegExp);
_ejs_init_object ((EJSObject*)rv, _ejs_RegExp_prototype, &_ejs_RegExp_specops);
ejsval args[2] = { pattern, flags };
// XXX this is wrong
ejsval thisarg = OBJECT_TO_EJSVAL(rv);
return _ejs_RegExp_impl (_ejs_null, &thisarg, 2, args, _ejs_undefined);
}
ejsval
_ejs_regexp_new_utf8 (const char *pattern, const char *flags)
{
return _ejs_regexp_new (_ejs_string_new_utf8 (pattern),
_ejs_string_new_utf8 (flags));
}
ejsval
_ejs_regexp_replace(ejsval str, ejsval search_re, ejsval replace)
{
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(search_re);
pcre16_extra extra;
memset (&extra, 0, sizeof(extra));
pcre16* code = (pcre16*)re->compiled_pattern;
int capture_count;
pcre16_fullinfo (code, NULL, PCRE_INFO_CAPTURECOUNT, &capture_count);
int ovec_count = 3 * (1 + capture_count);
int* ovec = malloc(sizeof(int) * ovec_count);
int cur_off = 0;
do {
EJSPrimString *flat_str = _ejs_string_flatten (str);
jschar *chars_str = flat_str->data.flat;
int rv = pcre16_exec(code, &extra,
chars_str, flat_str->length, cur_off,
PCRE_NO_UTF16_CHECK, ovec, ovec_count);
if (rv < 0)
break;
ejsval replaceval;
if (EJSVAL_IS_FUNCTION(replace)) {
ejsval substr_match = _ejs_string_new_substring (str, ovec[0], ovec[1] - ovec[0]);
ejsval capture = _ejs_string_new_substring (str, ovec[2], ovec[3] - ovec[2]);
_ejs_log ("substring match is %s\n", ucs2_to_utf8(_ejs_string_flatten(substr_match)->data.flat));
_ejs_log ("capture is %s\n", ucs2_to_utf8(_ejs_string_flatten(capture)->data.flat));
int argc = 3;
ejsval args[3];
args[0] = substr_match;
args[1] = capture;
args[2] = _ejs_undefined;
ejsval undef_this = _ejs_undefined;
replaceval = ToString(_ejs_invoke_closure (replace, &undef_this, argc, args, _ejs_undefined));
}
else {
replaceval = ToString(replace);
}
if (ovec[0] == 0) {
// we matched from the beginning of the string, so nothing from there to prepend
str = _ejs_string_concat (replaceval, _ejs_string_new_substring (str, ovec[1], flat_str->length - ovec[1]));
}
else {
str = _ejs_string_concatv (_ejs_string_new_substring (str, 0, ovec[0]),
replaceval,
_ejs_string_new_substring (str, ovec[1], flat_str->length - ovec[1]),
_ejs_null);
}
cur_off = ovec[1];
// if the RegExp object was created without a 'g' flag, only replace the first match
if (!re->global)
break;
} while (EJS_TRUE);
free (ovec);
return str;
}
// ES2015, June 2015
// 21.2.3.2.1 Runtime Semantics: RegExpAlloc ( newTarget )
static ejsval
RegExpAlloc(ejsval newTarget) {
// 1. Let obj be OrdinaryCreateFromConstructor(newTarget, "%RegExpPrototype%", «[[RegExpMatcher]], [[OriginalSource]], [[OriginalFlags]]»).
// 2. ReturnIfAbrupt(obj).
ejsval obj = OrdinaryCreateFromConstructor(newTarget, _ejs_RegExp_prototype, &_ejs_RegExp_specops);
// 3. Let status be DefinePropertyOrThrow(obj, "lastIndex", PropertyDescriptor {[[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false}).
EJSPropertyDesc* desc = _ejs_propertydesc_new();
_ejs_property_desc_set_writable(desc, EJS_TRUE);
_ejs_property_desc_set_enumerable(desc, EJS_FALSE);
_ejs_property_desc_set_configurable(desc, EJS_FALSE);
ejsval exc;
DefinePropertyOrThrow(obj, _ejs_atom_lastIndex, desc, &exc);
// 4. Assert: status is not an abrupt completion.
// XXX
// 5. Return obj.
return obj;
}
// ES2015, June 2015
// 21.2.3.2.2 Runtime Semantics: RegExpInitialize ( obj, pattern, flags )
static ejsval
RegExpInitialize(ejsval obj, ejsval pattern, ejsval flags) {
ejsval P, F;
// 1. If pattern is undefined, let P be the empty String.
if (EJSVAL_IS_UNDEFINED(pattern))
P = _ejs_atom_empty;
// 2. Else, let P be ToString(pattern).
// 3. ReturnIfAbrupt(P).
else
P = ToString(pattern);
// 4. If flags is undefined, let F be the empty String.
if (EJSVAL_IS_UNDEFINED(flags))
F = _ejs_atom_empty;
// 5. Else, let F be ToString(flags).
// 6. ReturnIfAbrupt(F).
else
F = ToString(flags);
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(obj);
// 7. If F contains any code unit other than "g", "i", "m", "u", or "y" or if it contains the same code unit more than once, throw a SyntaxError exception.
// 8. If F contains "u", let BMP be false; else let BMP be true.
EJSPrimString *flat_flags = _ejs_string_flatten(F);
jschar* chars = flat_flags->data.flat;
for (int i = 0; i < flat_flags->length; i ++) {
if (chars[i] == 'g' && !re->global) { re->global = EJS_TRUE; continue; }
else if (chars[i] == 'i' && !re->ignoreCase) { re->ignoreCase = EJS_TRUE; continue; }
else if (chars[i] == 'm' && !re->multiline) { re->multiline = EJS_TRUE; continue; }
else if (chars[i] == 'y' && !re->sticky) { re->sticky = EJS_TRUE; continue; }
else if (chars[i] == 'u' && !re->unicode) { re->unicode = EJS_TRUE; continue; }
_ejs_throw_nativeerror_utf8 (EJS_SYNTAX_ERROR, "Invalid flag supplied to RegExp constructor");
}
// 9. If BMP is true, then
// a. Parse P using the grammars in 21.2.1 and interpreting each
// of its 16-bit elements as a Unicode BMP code point. UTF-16
// decoding is not applied to the elements. The goal symbol for
// the parse is Pattern. Throw a SyntaxError exception if P did
// not conform to the grammar, if any elements of P were not
// matched by the parse, or if any Early Error conditions exist.
// b. Let patternCharacters be a List whose elements are the code unit elements of P.
// 10. Else
// a. Parse P using the grammars in 21.2.1 and interpreting P as UTF-16 encoded Unicode code points (6.1.4). The goal symbol for the parse is Pattern[U]. Throw a SyntaxError exception if P did not conform to the grammar, if any elements of P were not matched by the parse, or if any Early Error conditions exist.
// b. Let patternCharacters be a List whose elements are the code points resulting from applying UTF-16 decoding to P’s sequence of elements.
// 11. Set the value of obj’s [[OriginalSource]] internal slot to P.
re->pattern = P;
// 12. Set the value of obj’s [[OriginalFlags]] internal slot to F.
re->flags = F;
// 13. Set obj’s [[RegExpMatcher]] internal slot to the internal procedure that evaluates the above parse of P by applying the semantics provided in 21.2.2 using patternCharacters as the pattern’s List of SourceCharacter values and F as the flag parameters.
EJSPrimString *flat_pattern = _ejs_string_flatten(P);
chars = flat_pattern->data.flat;
const char *pcre_error;
int pcre_erroffset;
re->compiled_pattern = pcre16_compile(chars,
PCRE_UTF16 | PCRE_NO_UTF16_CHECK,
&pcre_error, &pcre_erroffset,
pcre16_tables);
// 14. Let setStatus be Set(obj, "lastIndex", 0, true).
// 15. ReturnIfAbrupt(setStatus).
Put(obj, _ejs_atom_lastIndex, NUMBER_TO_EJSVAL(0), EJS_TRUE);
// 16. Return obj.
return obj;
}
ejsval _ejs_RegExp EJSVAL_ALIGNMENT;
ejsval _ejs_RegExp_prototype EJSVAL_ALIGNMENT;
// ES2015, June 2015
// 21.2.3.1 RegExp ( pattern, flags )
static EJS_NATIVE_FUNC(_ejs_RegExp_impl) {
ejsval pattern = _ejs_undefined;
ejsval flags = _ejs_undefined;
if (argc > 0) pattern = args[0];
if (argc > 1) flags = args[1];
// 1. Let patternIsRegExp be IsRegExp(pattern).
// 2. ReturnIfAbrupt(patternIsRegExp).
EJSBool patternIsRegExp = IsRegExp(pattern);
// 3. If NewTarget is not undefined, let newTarget be NewTarget.
if (!EJSVAL_IS_UNDEFINED(newTarget))
;
// 4. Else,
else {
// a. Let newTarget be the active function object.
newTarget = _ejs_RegExp;
// b. If patternIsRegExp is true and flags is undefined, then
if (patternIsRegExp && EJSVAL_IS_UNDEFINED(flags)) {
// i. Let patternConstructor be Get(pattern, "constructor").
// ii. ReturnIfAbrupt(patternConstructor).
ejsval patternConstructor = Get(pattern, _ejs_atom_constructor);
// iii. If SameValue(newTarget, patternConstructor) is true, return pattern.
if (SameValue(newTarget, patternConstructor))
return pattern;
}
}
ejsval P, F;
// 5. If Type(pattern) is Object and pattern has a [[RegExpMatcher]] internal slot, then
if (EJSVAL_IS_REGEXP(pattern)) {
// a. Let P be the value of pattern’s [[OriginalSource]] internal slot.
P = ((EJSRegExp*)EJSVAL_TO_OBJECT(pattern))->pattern;
// b. If flags is undefined, let F be the value of pattern’s [[OriginalFlags]] internal slot.
if (EJSVAL_IS_UNDEFINED(flags))
F = ((EJSRegExp*)EJSVAL_TO_OBJECT(pattern))->flags;
// c. Else, let F be flags.
else
F = flags;
}
// 6. Else if patternIsRegExp is true, then
else if (patternIsRegExp) {
// a. Let P be Get(pattern, "source").
// b. ReturnIfAbrupt(P).
P = Get(pattern, _ejs_atom_source);
// c. If flags is undefined, then
if (EJSVAL_IS_UNDEFINED(flags)) {
// i. Let F be Get(pattern, "flags").
// ii. ReturnIfAbrupt(F).
F = Get(pattern, _ejs_atom_flags);
}
// d. Else, let F be flags.
else
F = flags;
}
// 7. Else,
else {
// a. Let P be pattern.
P = pattern;
// b. Let F be flags.
F = flags;
}
// 8. Let O be RegExpAlloc(newTarget).
// 9. ReturnIfAbrupt(O).
ejsval O = RegExpAlloc(newTarget);
// 10. Return RegExpInitialize(O, P, F)
return RegExpInitialize(O, P, F);
}
// ES6 21.2.5.2.2
// Runtime Semantics: RegExpBuiltinExec ( R, S ) Abstract Operation
static ejsval
RegExpBuiltinExec(ejsval R, ejsval S)
{
// 1. Assert: R is an initialized RegExp instance.
EJS_ASSERT(EJSVAL_IS_REGEXP(R));
// 2. Assert: Type(S) is String.
EJS_ASSERT(EJSVAL_IS_STRING_TYPE(S));
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(R);
// 3. Let length be the number of code units in S.
int length = EJSVAL_TO_STRLEN(S);
// 4. Let lastIndex be Get(R,"lastIndex").
ejsval lastIndex = Get(R, _ejs_atom_lastIndex);
// 5. Let i be ToLength(lastIndex).
// 6. ReturnIfAbrupt(i).
int64_t i = ToLength(lastIndex);
// 7. Let global be ToBoolean(Get(R, "global")).
// 8. ReturnIfAbrupt(global).
EJSBool global = ToEJSBool(Get(R, _ejs_atom_global));
// 9. Let sticky be ToBoolean(Get(R, "sticky")).
// 10. ReturnIfAbrupt(sticky).
EJSBool sticky = ToEJSBool(Get(R, _ejs_atom_sticky));
// 11. If global is false and sticky is false, then let i = 0.
if (!global && !sticky)
i = 0;
ejsval subject = S;
pcre16_extra extra;
memset (&extra, 0, sizeof(extra));
EJSPrimString *flat_subject = _ejs_string_flatten (subject);
jschar* subject_chars = flat_subject->data.flat;
int ovec[60];
// 12. Let matcher be the value of R’s [[RegExpMatcher]] internal slot.
pcre16* matcher = (pcre16*)re->compiled_pattern;
// 13. Let flags be the value of R’s [[OriginalFlags]] internal slot.
// XXX
// 14. If flags contains "u" then let fullUnicode be true, else let fullUnicode be false.
EJSBool fullUnicode = re->unicode;
// 15. Let matchSucceeded be false.
EJSBool matchSucceeded = EJS_FALSE;
int r;
#if false
// 16. Repeat, while matchSucceeded is false
while (!matchSucceeded) {
// a. If i < 0 or i > length, then
if (i < 0 || i > length) {
// i. Let putStatus be Put(R, "lastIndex", 0, true).
// ii. ReturnIfAbrupt(putStatus).
Put(R, _ejs_atom_lastIndex, NUMBER_TO_EJSVAL(0), EJS_TRUE);
// iii. Return null.
return _ejs_null;
}
// b. Let r be the result of calling matcher with arguments S and i.
r = pcre16_exec(matcher, &extra, subject_chars, length, i,
PCRE_NO_UTF16_CHECK, ovec, 3);
// c. If r is failure, then
if (r == PCRE_ERROR_NOMATCH) {
// i. If sticky is true, then
if (sticky) {
// 1. Let putStatus be Put(R, "lastIndex", 0, true).
// 2. ReturnIfAbrupt(putStatus).
Put(R, _ejs_atom_lastIndex, NUMBER_TO_EJSVAL(0), EJS_TRUE);
// 3. Return null.
return _ejs_null;
}
// ii. Let i = i+1.
i = i + 1;
}
else {
// d. else
// i. Assert: r is a State.
// ii. Set matchSucceeded to true.
matchSucceeded = EJS_TRUE;
}
}
#else
r = pcre16_exec(matcher, &extra, subject_chars, length, i,
PCRE_NO_UTF16_CHECK, ovec, sizeof(ovec)/sizeof(ovec[0]));
if (r == PCRE_ERROR_NOMATCH) {
Put(R, _ejs_atom_lastIndex, NUMBER_TO_EJSVAL(0), EJS_TRUE);
return _ejs_null;
}
i = ovec[0];
#endif
// 17. Let e be r's endIndex value.
int e = ovec[1];
// 18. If fullUnicode is true, then
if (fullUnicode) {
// a. e is an index into the Input character list, derived from S, matched by matcher. Let eUTF be the smallest
// index into S that corresponds to the character at element e of Input. If e is greater than the length of
// Input, then eUTF is 1 + the number of code units in S.
// b. Let e be eUTF.
EJS_NOT_IMPLEMENTED();
}
// 19. If global is true or sticky is true,
if (global || sticky) {
// a. Let putStatus be the result of Put(R, "lastIndex", e, true).
// b. ReturnIfAbrupt(putStatus).
Put(R, _ejs_atom_lastIndex, NUMBER_TO_EJSVAL(e), EJS_TRUE);
}
// 20. Let n be the length of r's captures List. (This is the same value as 21.2.2.1's NcapturingParens.)
int n = r - 1;
// 21. Let A be the result of the abstract operation ArrayCreate(n + 1).
ejsval A = _ejs_array_new(n+1, EJS_FALSE);
// 22. Assert: The value of A’s "length" property is n + 1.
// 23. Let matchIndex be i.
int matchIndex = i;
// 24. Assert: The following CreateDataProperty calls will not result in an abrupt completion.
// 25. Perform CreateDataProperty(A, "index", matchIndex).
_ejs_object_setprop (A, _ejs_atom_index, NUMBER_TO_EJSVAL(matchIndex));
// 26. Perform CreateDataProperty(A, "input", S).
_ejs_object_setprop (A, _ejs_atom_input, S);
// 27. Let matchedSubstr be the matched substring (i.e. the portion of S between offset i inclusive and offset e exclusive).
ejsval matchedSubstr = _ejs_string_new_substring(S, i, e-i);
// 28. Perform CreateDataProperty(A, "0", matchedSubstr).
EJS_DENSE_ARRAY_ELEMENTS(A)[0] = matchedSubstr;
// 29. For each integer i such that i > 0 and i <= n
for (int i = 1; i <= n; i ++) {
// a. Let captureI be ith element of r's captures List.
ejsval capturedValue;
// b. If captureI is undefined, then let capturedValue be undefined.
if (ovec[i*2] == ovec[i*2+1]) {
capturedValue = _ejs_undefined;
}
else {
// c. Else if fullUnicode is true,
if (fullUnicode) {
// i. Assert: captureI is a List of code points.
// ii. Let capturedValue be a string whose code units are the UTF-16Encoding (10.1.1) of the code points of capture.
EJS_NOT_IMPLEMENTED();
}
// d. Else, fullUnicode is false,
else {
// i. Assert: captureI is a List of code units.
// ii. Let capturedValue be a string consisting of the code units of captureI.
capturedValue = _ejs_string_new_substring(S, ovec[i*2], ovec[i*2+1]-ovec[i*2]);
}
}
// e. Perform CreateDataProperty(A, ToString(i) , capturedValue).
EJS_DENSE_ARRAY_ELEMENTS(A)[i] = capturedValue;
}
// 30. Return A.
return A;
}
static ejsval
RegExpExec(ejsval R, ejsval S)
{
// 1. Assert: Type(R) is Object.
// 2. Assert: Type(S) is String.
// 3. Let exec be Get(R, "exec").
// 4. ReturnIfAbrupt(exec).
ejsval exec = Get(R, _ejs_atom_exec);
// 5. If IsCallable(exec) is true, then
if (EJSVAL_IS_FUNCTION(exec)) {
// a. Let result be Call(exec, R, «S»).
// b. ReturnIfAbrupt(result).
ejsval result = _ejs_invoke_closure(exec, &R, 1, &S, _ejs_undefined);
// c. If Type(result) is neither Object or Null, then throw a TypeError exception.
if (!EJSVAL_IS_OBJECT(result) && !EJSVAL_IS_NULL(result))
_ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "'exec' returned non-object, non-null value");
// d. Return(result).
return result;
}
// 6. If R does not have a [[RegExpMatcher]] internal slot, then throw a TypeError exception.
// 7. If the value of R’s [[RegExpMatcher]] internal slot is undefined, then throw a TypeError exception.
if (!EJSVAL_IS_REGEXP(R))
_ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "'this' is not a RegExp");
// 8. Return RegExpBuiltinExec(R, S).
return RegExpBuiltinExec(R, S);
}
// ES6 21.2.5.2
// RegExp.prototype.exec ( string )
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_exec) {
ejsval string = _ejs_undefined;
if (argc > 0) string = args[0];
// 1. Let R be the this value.
ejsval R = *_this;
// 2. If Type(R) is not Object, then throw a TypeError exception.
if (!EJSVAL_IS_OBJECT(R))
_ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "non-object 'this' in RegExp.prototype.exec");
// 3. If R does not have a [[RegExpMatcher]] internal slot, then throw a TypeError exception.
// 4. If the value of R’s [[RegExpMatcher]] internal slot is undefined, then throw a TypeError exception.
if (!EJSVAL_IS_OBJECT(R))
_ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "non-RegExp 'this' in RegExp.prototype.exec");
// 5. Let S be ToString(string)
// 6. ReturnIfAbrupt(S).
ejsval S = ToString(string);
// 7. Return RegExpBuiltinExec(R, S).
return RegExpBuiltinExec(R, S);
}
// ECMA262: 15.10.6.3
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_test) {
if (!EJSVAL_IS_REGEXP(*_this))
EJS_NOT_IMPLEMENTED();
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(*_this);
ejsval subject = _ejs_undefined;
if (argc > 0) subject = args[0];
pcre16_extra extra;
memset (&extra, 0, sizeof(extra));
EJSPrimString *flat_subject = _ejs_string_flatten (subject);
jschar* subject_chars = flat_subject->data.flat;
int ovec[3];
int rv = pcre16_exec((pcre16*)re->compiled_pattern, &extra,
subject_chars, flat_subject->length, 0,
PCRE_NO_UTF16_CHECK, ovec, 3);
return rv == PCRE_ERROR_NOMATCH ? _ejs_false : _ejs_true;
}
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_toString) {
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(*_this);
return _ejs_string_concatv (_ejs_atom_slash, re->pattern, _ejs_atom_slash, re->flags, _ejs_null);
}
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_get_global) {
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(*_this);
return BOOLEAN_TO_EJSVAL(re->global);
}
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_get_ignoreCase) {
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(*_this);
return BOOLEAN_TO_EJSVAL(re->ignoreCase);
}
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_get_lastIndex) {
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(*_this);
return NUMBER_TO_EJSVAL(re->lastIndex);
}
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_get_multiline) {
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(*_this);
return BOOLEAN_TO_EJSVAL(re->multiline);
}
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_get_sticky) {
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(*_this);
return BOOLEAN_TO_EJSVAL(re->sticky);
}
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_get_unicode) {
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(*_this);
return BOOLEAN_TO_EJSVAL(re->unicode);
}
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_get_source) {
EJSRegExp* re = (EJSRegExp*)EJSVAL_TO_OBJECT(*_this);
return re->pattern;
}
// ES6 21.2.5.3
// get RegExp.prototype.flags ( )
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_get_flags) {
// 1. Let R be the this value.
ejsval R = *_this;
// 2. If Type(R) is not Object, then throw a TypeError exception.
if (!EJSVAL_IS_OBJECT(R))
_ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "get Regexp.prototype.flags called with non-object 'this'");
// 3. Let result be the empty String.
char result_buf[6];
memset (result_buf, 0, sizeof(result_buf));
char* p = result_buf;
// 4. Let global be ToBoolean(Get(R, "global")).
// 5. ReturnIfAbrupt(global).
EJSBool global = ToEJSBool(Get(R, _ejs_atom_global));
// 6. If global is true, then append "g" as the last code unit of result.
if (global) *p++ = 'g';
// 7. Let ignoreCase be ToBoolean(Get(R, "ignoreCase")).
// 8. ReturnIfAbrupt(ignoreCase).
EJSBool ignoreCase = ToEJSBool(Get(R, _ejs_atom_ignoreCase));
// 9. If ignoreCase is true, then append "i" as the last code unit of result.
if (ignoreCase) *p++ = 'i';
// 10. Let multiline be ToBoolean(Get(R, "multiline")).
// 11. ReturnIfAbrupt(multiline).
EJSBool multiline = ToEJSBool(Get(R, _ejs_atom_multiline));
// 12. If multiline is true, then append "m" as the last code unit of result.
if (multiline) *p++ = 'm';
// 13. Let sticky be ToBoolean(Get(R, "sticky")).
// 14. ReturnIfAbrupt(sticky).
EJSBool sticky = ToEJSBool(Get(R, _ejs_atom_sticky));
// 15. If sticky is true, then append "y" as the last code unit of result.
if (sticky) *p++ = 'y';
// 16. Let unicode be ToBoolean(Get(R, "unicode")).
// 17. ReturnIfAbrupt(unicode).
EJSBool unicode = ToEJSBool(Get(R, _ejs_atom_unicode));
// 18. If unicode is true, then append "u" as the last code unit of result.
if (unicode) *p++ = 'u';
// 19. Return result.
return _ejs_string_new_utf8(result_buf);
}
static EJS_NATIVE_FUNC(_ejs_RegExp_get_species) {
return _ejs_RegExp;
}
// ES6 21.2.5.6
// RegExp.prototype [ @@match ] ( string )
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_match) {
ejsval string = _ejs_undefined;
if (argc > 0) string = args[0];
// 1. Let rx be the this value.
ejsval rx = *_this;
// 2. If Type(rx) is not Object, then throw a TypeError exception.
if (!EJSVAL_IS_OBJECT(rx))
_ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "Regexp[Symbol.match] called with non-object 'this'");
// 3. Let S be ToString(string)
// 4. ReturnIfAbrupt(S).
ejsval S = ToString(string);
// 5. Let global be ToBoolean(Get(rx, "global")).
// 6. ReturnIfAbrupt(global).
ejsval global = ToBoolean(Get(rx, _ejs_atom_global));
// 7. If global is not true, then
if (!EJSVAL_TO_BOOLEAN(global)) {
// a. Return the result of RegExpExec(rx, S).
return RegExpExec(rx, S);
}
// 8. Else global is true,
else {
// a. Let putStatus be Put(rx, "lastIndex", 0, true).
// b. ReturnIfAbrupt(putStatus).
Put(rx, _ejs_atom_lastIndex, NUMBER_TO_EJSVAL(0), EJS_TRUE);
// c. Let A be ArrayCreate(0).
ejsval A = _ejs_array_new(0, EJS_FALSE);
// d. Let previousLastIndex be 0.
int previousLastIndex = 0;
// e. Let n be 0.
int n = 0;
// f. Repeat,
while (EJS_TRUE) {
// i. Let result be RegExpExec(rx, S).
// ii. ReturnIfAbrupt(result).
ejsval result = RegExpExec(rx, S);
// iii. If result is null, then
if (EJSVAL_IS_NULL(result)) {
// 1. If n=0, then return null.
if (n == 0)
return _ejs_null;
else
// 2. Else, return A.
return A;
}
// iv. Else result is not null,
else {
// 1. Let thisIndex be ToInteger(Get(rx, "lastIndex")).
// 2. ReturnIfAbrupt(thisIndex).
int thisIndex = ToInteger(Get(rx, _ejs_atom_lastIndex));
// 3. If thisIndex = previousLastIndex then
if (thisIndex == previousLastIndex) {
// a. Let putStatus be Put(rx, "lastIndex", thisIndex+1, true).
// b. ReturnIfAbrupt(putStatus).
Put(rx, _ejs_atom_lastIndex, NUMBER_TO_EJSVAL(thisIndex+1), EJS_TRUE);
// c. Set previousLastIndex to thisIndex+1.
previousLastIndex = thisIndex + 1;
}
// 4. Else,
else {
// a. Set previousLastIndex to thisIndex.
previousLastIndex = thisIndex;
}
// 5. Let matchStr be Get(result, "0").
ejsval matchStr = Get(result, _ejs_atom_0);
// 6. Let status be CreateDataProperty(A, ToString(n), matchStr).
// 7. Assert: status is true.
_ejs_object_define_value_property (A, ToString(NUMBER_TO_EJSVAL(n)), matchStr, EJS_PROP_FLAGS_ENUMERABLE | EJS_PROP_FLAGS_CONFIGURABLE | EJS_PROP_FLAGS_WRITABLE);
// 8. Increment n.
n++;
}
}
}
}
// ES6 21.2.5.8
// RegExp.prototype [ @@replace ] ( string, replaceValue )
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_replace) {
ejsval string = _ejs_undefined;
if (argc > 0) string = args[0];
ejsval replaceValue = _ejs_undefined;
if (argc > 1) replaceValue = args[1];
// 1. Let rx be the this value.
ejsval rx = *_this;
// 2. If Type(rx) is not Object, then throw a TypeError exception.
if (!EJSVAL_IS_OBJECT(rx))
_ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "Regexp.prototype[Symbol.replace] called with non-object 'this'");
// 3. Let S be ToString(string).
// 4. ReturnIfAbrupt(S).
ejsval S = ToString(string);
// 5. Let lengthS be the number of code unit elements in S.
int lengthS = EJSVAL_TO_STRLEN(S);
// 6. Let functionalReplace be IsCallable(replaceValue).
EJSBool functionalReplace = EJSVAL_IS_FUNCTION(replaceValue);
// 7. If functionalReplace is false, then
if (!functionalReplace) {
// a. Let replaceValue be ToString(replaceValue).
// b. ReturnIfAbrupt(replaceValue).
replaceValue = ToString(replaceValue);
}
// 8. Let global be ToBoolean(Get(rx, "global")).
// 9. ReturnIfAbrupt(global).
EJSBool global = ToEJSBool(Get(rx, _ejs_atom_global));
// 10. If global is true, then
if (global) {
// a. Let putStatus be Put(rx, "lastIndex", 0, true).
// b. ReturnIfAbrupt(putStatus).
Put(rx, _ejs_atom_lastIndex, NUMBER_TO_EJSVAL(0), EJS_TRUE);
}
// 11. Let previousLastIndex be 0.
int previousLastIndex = 0;
// 12. Let results be a new empty List.
ejsval results = _ejs_array_new(0, EJS_FALSE);
// 13. Let done be false.
EJSBool done = EJS_FALSE;
// 14. Repeat, while done is false
while (!done) {
// a. Let result be RegExpExec(rx, S).
// b. ReturnIfAbrupt(result).
ejsval result = RegExpExec(rx, S);
// c. If result is null, then set done to true.
if (EJSVAL_IS_NULL(result))
done = EJS_TRUE;
// d. Else result is not null,
else {
// i. Append result to the end of results.
_ejs_array_push_dense(results, 1, &result);
// ii. If global is false, then set done to true.
if (!global)
done = EJS_TRUE;
// iii. Else,
else {
// 1. Let matchStr be ToString(Get(result, "0")).
// 2. ReturnIfAbrupt(matchStr).
ejsval matchStr = ToString(Get(result, _ejs_atom_0));
// 3. If matchStr is the empty String, then
if (EJSVAL_TO_BOOLEAN(_ejs_op_strict_eq (matchStr, _ejs_atom_empty))) {
// a. Let thisIndex be ToLength(Get(rx, "lastIndex")).
// b. ReturnIfAbrupt(thisIndex).
int64_t thisIndex = ToLength(Get(rx, _ejs_atom_lastIndex));
// c. Let putStatus be Put(rx, "lastIndex", thisIndex+1, true).
// d. ReturnIfAbrupt(putStatus).
Put(rx, _ejs_atom_lastIndex, NUMBER_TO_EJSVAL(thisIndex+1), EJS_TRUE);
}
}
}
}
// 15. Let accumulatedResult be the empty String value.
ejsval accumulatedResult = _ejs_atom_empty;
// 16. Let nextSourcePosition be 0.
int64_t nextSourcePosition = 0;
EJS_ASSERT(EJSVAL_IS_DENSE_ARRAY(results));
// 17. Repeat, for each result in results,
for (int i = 0, e = EJS_ARRAY_LEN(results); i < e; i ++) {
ejsval result = EJS_DENSE_ARRAY_ELEMENTS(results)[i];
// a. Let nCaptures be ToLength(Get(result, "length")).
// b. ReturnIfAbrupt(nCaptures).
int64_t nCaptures = ToLength(Get(result, _ejs_atom_length));
// c. Let nCaptures be max(nCaptures − 1, 0).
nCaptures = MAX(nCaptures - 1, 0);
// d. Let matched be ToString(Get(result, "0")).
// e. ReturnIfAbrupt(matched).
ejsval matched = ToString(Get(result, _ejs_atom_0));
// f. Let matchLength be the number of code units in matched.
int matchLength = EJSVAL_TO_STRLEN(matched);
// g. Let position be ToInteger(Get(result, "index")).
// h. ReturnIfAbrupt(position).
int64_t position = ToInteger(Get(result, _ejs_atom_index));
// i. Let position be max(min(position, lengthS), 0).
position = MAX(MIN(position, lengthS), 0);
// j. Let n be 1.
int n = 1;
// k. Let captures be an empty List.
ejsval captures = _ejs_array_new(0, EJS_FALSE);
// l. Repeat while n <= nCaptures
while (n <= nCaptures) {
// i. Let capN be Get(result, ToString(n)).
ejsval capN = Get(result, ToString(NUMBER_TO_EJSVAL(n)));
// ii. If Type(capN) is not Undefined, then let capN be ToString(capN).
if (!EJSVAL_IS_UNDEFINED(capN))
capN = ToString(capN);
// iii. ReturnIfAbrupt(capN).
// iv. Append capN as the last element of captures.
_ejs_array_push_dense(captures, 1, &capN);
// v. Let n be n+1
n = n + 1;
}
ejsval replacement;
// m. If functionalReplace is true, then
if (functionalReplace) {
// i. Let replacerArgs be the List (matched).
int numReplacerArgs = EJS_ARRAY_LEN(captures) + 3;
ejsval* replacerArgs = (ejsval*)alloca(sizeof(ejsval) * numReplacerArgs);
*replacerArgs = matched;
// ii. Append in list order the elements of captures to the end of the List replacerArgs.
memmove(replacerArgs + 1, EJS_DENSE_ARRAY_ELEMENTS(captures), (numReplacerArgs - 3) * sizeof(ejsval));
// iii. Append position and S as the last two elements of replacerArgs.
replacerArgs[numReplacerArgs - 2] = NUMBER_TO_EJSVAL(position);
replacerArgs[numReplacerArgs - 1] = S;
// iv. Let replValue be Call(replaceValue, undefined, replacerArgs).
ejsval undef_this = _ejs_undefined;
ejsval replValue = _ejs_invoke_closure(replaceValue, &undef_this, numReplacerArgs, replacerArgs, _ejs_undefined);
// v. Let replacement be ToString(replValue).
replacement = ToString(replValue);
}
// n. Else,
else {
// i. Let replacement be GetReplaceSubstitution(matched, S, position, captures, replaceValue).
replacement = GetReplaceSubstitution(matched, S, position, captures, replaceValue);
}
// o. ReturnIfAbrupt(replacement).
// p. If position >= nextSourcePosition, then
if (position >= nextSourcePosition) {
// i. NOTE position should not normally move backwards. If it does, it is in indication of a ill-behaving
// RegExp subclass or use of an access triggered side-effect to change the global flag or other
// characteristics of rx. In such cases, the corresponding substitution is ignored.
// ii. Let accumulatedResult be the String formed by concatenating the code units of the current
// value of accumulatedResult with the substring of S consisting of the code units from
// nextSourcePosition (inclusive) up to position (exclusive) and with the code units of
// replacement.
accumulatedResult = _ejs_string_concatv(accumulatedResult,
_ejs_string_new_substring(S, nextSourcePosition, position - nextSourcePosition),
replacement,
_ejs_undefined);
// iii. Let nextSourcePosition be position + matchLength.
nextSourcePosition = position + matchLength;
}
}
// 18. If nextSourcePosition >= lengthS, then return accumulatedResult.
if (nextSourcePosition >= lengthS)
return accumulatedResult;
// 19. Return the String formed by concatenating the code units of accumulatedResult with the substring
// of S consisting of the code units from nextSourcePosition (inclusive) up through the final code unit
// of S (inclusive).
return _ejs_string_concat(accumulatedResult,
_ejs_string_new_substring(S, nextSourcePosition, EJSVAL_TO_STRLEN(S) - nextSourcePosition));
}
// ES2015, June 2015
// 21.2.5.11 RegExp.prototype [ @@split ] ( string, limit )
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_split) {
ejsval string = _ejs_undefined;
if (argc > 0) string = args[0];
ejsval limit = _ejs_undefined;
if (argc > 1) limit = args[1];
// 1. Let rx be the this value.
ejsval rx = *_this;
// 2. If Type(rx) is not Object, throw a TypeError exception.
if (!EJSVAL_IS_OBJECT(rx))
_ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "Regexp.prototype[Symbol.split] called with non-object 'this'");
// 3. Let S be ToString(string).
// 4. ReturnIfAbrupt(S).
ejsval S = ToString(string);
jschar* S_chars = EJSVAL_TO_FLAT_STRING(S);
// 5. Let C be SpeciesConstructor(rx, %RegExp%).
// 6. ReturnIfAbrupt(C).
ejsval C = SpeciesConstructor(rx, _ejs_RegExp);
// 7. Let flags be ToString(Get(rx, "flags"))
// 8. ReturnIfAbrupt(flags).
ejsval flags = ToString(Get(rx, _ejs_atom_flags));
// 9. If flags contains "u",then let unicodeMatching be true.
// 10. Else, let unicodeMatching be false.
// XXX
EJSBool unicodeMatching = EJS_FALSE;
// 11. If flags contains "y", let newFlags be flags.
// 12. Else, let newFlags be the string that is the concatenation of flags and "y".
ejsval newFlags = flags;
// XXX
// 13. Let splitter be Construct(C, «rx, newFlags»).
// 14. ReturnIfAbrupt(splitter).
ejsval construct_args[] = { rx, newFlags };
ejsval splitter = Construct(C, C, 2, construct_args);
// 15. Let A be ArrayCreate(0).
ejsval A = _ejs_array_new(0, EJS_FALSE);
// 16. Let lengthA be 0.
int lengthA = 0;
// 17. If limit is undefined, let lim = 2^53–1; else let lim = ToLength(limit).
// 18. ReturnIfAbrupt(lim).
int64_t lim = EJSVAL_IS_UNDEFINED(limit) ? EJS_MAX_SAFE_INTEGER : ToLength(limit);
// 19. Let size be the number of elements in S.
int size = EJSVAL_TO_STRLEN(S);
// 20. Let p = 0.
int p = 0;
// 21. If lim = 0, return A.
if (lim == 0) return A;
// 22. If size = 0, then
if (size == 0) {
// a. Let z be RegExpExec(splitter, S).
// b. ReturnIfAbrupt(z).
ejsval z = RegExpExec(splitter, S);
// c. If z is not null, return A.
if (!EJSVAL_IS_NULL(z)) return A;
// d. Assert: The following call will never result in an abrupt completion.
// e. Perform CreateDataProperty(A, "0", S).
_ejs_array_push_dense(A, 1, &S);
// f. Return A.
return A;
}
// 23. Let q = p.
int q = p;
// 24. Repeat, while q < size
while (q < size) {
// a. Let putStatus be Put(splitter, "lastIndex", q, true).
// b. ReturnIfAbrupt(putStatus).
Put(splitter, _ejs_atom_lastIndex, NUMBER_TO_EJSVAL(q), EJS_TRUE);
// c. Let z be RegExpExec(splitter, S).
// d. ReturnIfAbrupt(z).
ejsval z = RegExpExec(splitter, S);
// e. If z is null, let q be AdvanceStringIndex(S, q, unicodeMatching)
// XXX this branch of the if is from an older version
if (EJSVAL_IS_NULL(z)) {
// i. If unicodeMatching is true, then
if (unicodeMatching) {
// 1. Let first be the code unit value of the element at index q in the String S.
jschar first = S_chars[q];
// 2. If first ≥ 0xD800 and first ≤ 0xDBFF and q+1 ≠ size, then
if (first >= 0xD800 && first <= 0xDBFF && q < size-1) {
// a. Let second be the code unit value of the element at index q+1 in the String S.
jschar second = S_chars[q+1];
// b. If second ≥ 0xDC00 and second ≤ 0xDFFF, then
if (second >= 0xDC00 && second <= 0xDFFF)
// i. Let q = q+1.
q++;
}
}
// ii. Let q = q+1.
q++;
}
// f. Else z is not null,
else {
// i. Let e be ToLength(Get(splitter, "lastIndex")).
// ii. ReturnIfAbrupt(e).
int64_t e = ToLength(Get(splitter, _ejs_atom_lastIndex));
// iii. If e = p, let q be AdvanceStringIndex(S, q, unicodeMatching).
// XXX this branch of the if is from an older version
if (e == p) {
// 1. If unicodeMatching is true, then
if (unicodeMatching) {
// a. Let first be the code unit value of the element at index q in the String S.
jschar first = S_chars[q];
// b. If first ≥ 0xD800 and first ≤ 0xDBFF and q+1 ≠ size, then
if (first >= 0xD800 && first <= 0xDBFF && q < size-1) {
// i. Let second be the code unit value of the element at index q+1 in the String S.
jschar second = S_chars[q+1];
// ii. If second ≥ 0xDC00 and second ≤ 0xDFFF, then
if (second >= 0xDC00 && second <= 0xDFFF)
// 1. Let q = q+1.
q++;
}
}
// 2. Let q = q+1.
q++;
}
// iv. Else e ≠ p,
else {
// 1. Let T be a String value equal to the substring of S consisting of the elements at indices p (inclusive) through q (exclusive).
ejsval T = _ejs_string_new_substring(S, p, q-p);
// 2. Assert: The following call will never result in an abrupt completion.
// 3. Perform CreateDataProperty(A, ToString(lengthA), T).
_ejs_array_push_dense(A, 1, &T);
// 4. Let lengthA be lengthA +1.
lengthA++;
// 5. If lengthA = lim, return A.
if (lengthA == lim) return A;
// 6. Let p = e.
p = e;
// 7. Let numberOfCaptures be ToLength(Get(z, "length")).
// 8. ReturnIfAbrupt(numberOfCaptures).
int64_t numberOfCaptures = ToLength(Get(z, _ejs_atom_length));
// 9. Let numberOfCaptures be max(numberOfCaptures-1, 0).
numberOfCaptures = MAX(numberOfCaptures-1, 0);
// 10. Let i be 1.
int i = 1;
// 11. Repeat, while i ≤ numberOfCaptures.
while (i <= numberOfCaptures) {
EJS_NOT_IMPLEMENTED();
// a. Let nextCapture be Get(z, ToString(i)).
// b. ReturnIfAbrupt(nextCapture).
// c. Perform CreateDataProperty(A, ToString(lengthA), nextCapture).
// d. Let i be i +1.
// e. Let lengthA be lengthA +1.
// f. If lengthA = lim, return A.
}
// 12. Let q = p.
q = p;
}
}
}
// 25. Let T be a String value equal to the substring of S consisting of the elements at indices p (inclusive) through size (exclusive).
ejsval T = _ejs_string_new_substring(S, p, size-p);
// 26. Assert: The following call will never result in an abrupt completion.
// 27. Perform CreateDataProperty(A, ToString(lengthA), T ).
_ejs_array_push_dense(A, 1, &T);
// 28. Return A.
return A;
}
// ES6 21.2.5.9
// RegExp.prototype [ @@search ] ( string )
static EJS_NATIVE_FUNC(_ejs_RegExp_prototype_search) {
EJS_NOT_IMPLEMENTED();
}
void
_ejs_regexp_init(ejsval global)
{
pcre16_tables = pcre16_maketables();
_ejs_RegExp = _ejs_function_new_without_proto (_ejs_null, _ejs_atom_RegExp, _ejs_RegExp_impl);
_ejs_object_setprop (global, _ejs_atom_RegExp, _ejs_RegExp);
_ejs_gc_add_root (&_ejs_RegExp_prototype);
_ejs_RegExp_prototype = _ejs_object_new(_ejs_null, &_ejs_RegExp_specops);
EJSRegExp* re_proto = (EJSRegExp*)EJSVAL_TO_OBJECT(_ejs_RegExp_prototype);
re_proto->pattern = _ejs_string_new_utf8("(?:)");
re_proto->flags = _ejs_atom_empty;
_ejs_object_setprop (_ejs_RegExp, _ejs_atom_prototype, _ejs_RegExp_prototype);
#define OBJ_METHOD(x) EJS_INSTALL_ATOM_FUNCTION(_ejs_RegExp, x, _ejs_RegExp_##x)
#define PROTO_METHOD(x) EJS_INSTALL_ATOM_FUNCTION(_ejs_RegExp_prototype, x, _ejs_RegExp_prototype_##x)
#define PROTO_METHOD_VAL(x) EJS_INSTALL_ATOM_FUNCTION_VAL(_ejs_RegExp_prototype, x, _ejs_RegExp_prototype_##x)
#define PROTO_GETTER(x) EJS_INSTALL_ATOM_GETTER(_ejs_RegExp_prototype, x, _ejs_RegExp_prototype_get_##x)
_ejs_gc_add_root (&_ejs_RegExp_prototype_exec_closure);
_ejs_RegExp_prototype_exec_closure = PROTO_METHOD_VAL(exec);
PROTO_METHOD(test);
PROTO_METHOD(toString);
PROTO_GETTER(global);
PROTO_GETTER(ignoreCase);
PROTO_GETTER(lastIndex);
PROTO_GETTER(multiline);
PROTO_GETTER(source);
PROTO_GETTER(sticky);
PROTO_GETTER(unicode);
PROTO_GETTER(flags);
#undef OBJ_METHOD
#undef PROTO_METHOD
EJS_INSTALL_SYMBOL_FUNCTION_FLAGS (_ejs_RegExp_prototype, match, _ejs_RegExp_prototype_match, EJS_PROP_NOT_ENUMERABLE | EJS_PROP_WRITABLE | EJS_PROP_CONFIGURABLE);
EJS_INSTALL_SYMBOL_FUNCTION_FLAGS (_ejs_RegExp_prototype, replace, _ejs_RegExp_prototype_replace, EJS_PROP_NOT_ENUMERABLE | EJS_PROP_WRITABLE | EJS_PROP_CONFIGURABLE);
EJS_INSTALL_SYMBOL_FUNCTION_FLAGS (_ejs_RegExp_prototype, split, _ejs_RegExp_prototype_split, EJS_PROP_NOT_ENUMERABLE | EJS_PROP_WRITABLE | EJS_PROP_CONFIGURABLE);
EJS_INSTALL_SYMBOL_FUNCTION_FLAGS (_ejs_RegExp_prototype, search, _ejs_RegExp_prototype_search, EJS_PROP_NOT_ENUMERABLE | EJS_PROP_WRITABLE | EJS_PROP_CONFIGURABLE);
EJS_INSTALL_SYMBOL_GETTER(_ejs_RegExp, species, _ejs_RegExp_get_species);
}
static EJSObject*
_ejs_regexp_specop_allocate()
{
return (EJSObject*)_ejs_gc_new(EJSRegExp);
}
static void
_ejs_regexp_specop_scan (EJSObject* obj, EJSValueFunc scan_func)
{
EJSRegExp *re = (EJSRegExp*)obj;
scan_func (re->pattern);
scan_func (re->flags);
_ejs_Object_specops.Scan (obj, scan_func);
}
EJS_DEFINE_CLASS(RegExp,
OP_INHERIT, // [[GetPrototypeOf]]
OP_INHERIT, // [[SetPrototypeOf]]
OP_INHERIT, // [[IsExtensible]]
OP_INHERIT, // [[PreventExtensions]]
OP_INHERIT, // [[GetOwnProperty]]
OP_INHERIT, // [[DefineOwnProperty]]
OP_INHERIT, // [[HasProperty]]
OP_INHERIT, // [[Get]]
OP_INHERIT, // [[Set]]
OP_INHERIT, // [[Delete]]
OP_INHERIT, // [[Enumerate]]
OP_INHERIT, // [[OwnPropertyKeys]]
OP_INHERIT, // [[Call]]
OP_INHERIT, // [[Construct]]
_ejs_regexp_specop_allocate,
OP_INHERIT, // [[Finalize]]
_ejs_regexp_specop_scan
)
| [
"toshok@gmail.com"
] | toshok@gmail.com |
7e4c854fc92a1b0ff13b01b9adb20f61bf18856b | d84967ba1e6adc72e120f84524c51ad57912df5a | /devel/electron14/files/patch-chrome_browser_shutdown__signal__handlers__posix.cc | 0208949849ab0c35ee6d56b5eb7a791133277843 | [] | no_license | tagattie/FreeBSD-Electron | f191d03c067d03ad3007e7748de905da06ba67f9 | af26f766e772bb04db5eb95148ee071101301e4e | refs/heads/master | 2023-09-04T10:56:17.446818 | 2023-09-04T09:03:11 | 2023-09-04T09:03:11 | 176,520,396 | 73 | 9 | null | 2023-08-31T03:29:16 | 2019-03-19T13:41:20 | C++ | UTF-8 | C++ | false | false | 736 | cc | --- chrome/browser/shutdown_signal_handlers_posix.cc.orig 2021-09-14 01:51:51 UTC
+++ chrome/browser/shutdown_signal_handlers_posix.cc
@@ -186,7 +186,11 @@ void InstallShutdownSignalHandlers(
g_pipe_pid = getpid();
g_shutdown_pipe_read_fd = pipefd[0];
g_shutdown_pipe_write_fd = pipefd[1];
-#if !defined(ADDRESS_SANITIZER)
+#if defined(OS_BSD)
+ // PTHREAD_STACK_MIN causes Chromium to crash under FreeBSD,
+ // we request the default pthread stack size by specifying 0 here.
+ const size_t kShutdownDetectorThreadStackSize = 0;
+#elif !defined(ADDRESS_SANITIZER)
const size_t kShutdownDetectorThreadStackSize = PTHREAD_STACK_MIN * 2;
#else
// ASan instrumentation bloats the stack frames, so we need to increase the
| [
"tagattie@gmail.com"
] | tagattie@gmail.com |
003f980b25c579a4387e0de15a9d9bdf5d06e5d9 | 4e1ffa74ae15e7d12f20156fe97f919596457023 | /test/lib/helper.cpp | ebc272d01496e611227ee3cbf5522912b7fe3461 | [
"MIT"
] | permissive | behlec/nuschl | 268bd001d89ee2809b331c15d19a6829f50f27ba | 35dbdd6dca8e59387623cc8a23f71324e07ea98c | refs/heads/master | 2021-03-19T15:44:44.339035 | 2018-05-01T09:20:33 | 2018-05-01T09:20:33 | 111,215,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 165 | cpp | #include <nuschl/unittests/helper.hpp>
const nuschl::s_exp *nuschl::make_number(int i, memory::s_exp_pool *pool) {
return pool->create(make_atom(number{i}));
}
| [
"behlec@gmail.com"
] | behlec@gmail.com |
f5bd57cd92e2dcbfe94ae2c89e6b74743da98882 | e43d84b05d34eaad67064be4356c6a711fc17a21 | /FontXCommandLine/FCLDatabase.cpp | a8b8b0169555f662964bb77142aaa0dc714c3929 | [
"MIT"
] | permissive | frinkr/FontViewer | 5bb3593960426db8399679180bb2bbfff879aac8 | 6dbd24ca605605edc01aa172327238c932a14082 | refs/heads/master | 2022-03-12T23:14:06.602826 | 2022-02-24T02:08:17 | 2022-02-24T02:08:17 | 126,189,660 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,874 | cpp | #include <QStandardPaths>
#include <QDir>
#include "FontX/FXLog.h"
#include "FCL.h"
#include "FCLDatabase.h"
namespace {
FXVector<FXString> systemFontFolders() {
QStringList folders = QStandardPaths::standardLocations(QStandardPaths::FontsLocation);
#if defined(Q_OS_MAC)
if (!folders.contains("/System/Library/Assets") && !folders.contains("/System/Library/Assets/"))
folders << "/System/Library/Assets";
if (!folders.contains("/System/Library/AssetsV2") && !folders.contains("/System/Library/AssetsV2/"))
folders << "/System/Library/AssetsV2";
#endif
FXVector<FXString> dirs;
for (const auto & dir : folders)
dirs.push_back(toStdString(QDir::toNativeSeparators(dir)));
return dirs;
}
FXString dbFilePath() {
QDir folder(QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)));
if (!folder.exists())
folder.mkpath(".");
return toStdString(folder.filePath("FontXCommandLine.db"));
}
}
FXPtr<const FCLDatabase>
FCLDatabase::instance() {
static auto inst = std::make_shared<FCLDatabase>(systemFontFolders(), dbFilePath(), [](size_t current, size_t total, const FXString& file) {
//FX_VERBOSE_INFO(current << "/" << total << ": caching " << file);
return true;
});;
return inst;
}
namespace {
FXVector<FXPtr<FCLDatabaseProcessor>> sDbProcessors;
}
const FXVector<FXPtr<FCLDatabaseProcessor>> &
FCLGetDatabaseProcessors() {
return sDbProcessors;
}
void
FCLAddDatabaseProcessors(FXPtr<FCLDatabaseProcessor> processor) {
sDbProcessors.push_back(processor);
}
FXPtr<FCLDatabaseProcessor>
FCLFindDatabaseProcessors(const FXString & name) {
for (auto proc : sDbProcessors) {
if (proc->name() == name)
return proc;
}
return nullptr;
}
| [
"frinkr@outlook.com"
] | frinkr@outlook.com |
6d2f3db956bc227a6f4bf1a8a73ac3887ce17d06 | 29f2549998b45a046930f3b1c5e3024791b1be16 | /include/llvm/Target/TargetLowering.h | 00a455c36091270a7f5381e20cacf33c82c1e195 | [
"NCSA"
] | permissive | fanfuqiang/iec-61131_new | eda210bd30a6a32e3d14c3d3e87f51b179124c72 | fde56fdefd60e33facaa07661e388ed6c916c763 | refs/heads/master | 2016-09-05T14:59:12.678870 | 2015-02-06T23:55:09 | 2015-02-06T23:55:09 | 30,048,552 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 77,674 | h | //===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes how to lower LLVM code to machine code. This has two
// main components:
//
// 1. Which ValueTypes are natively supported by the target.
// 2. Which operations are supported for supported ValueTypes.
// 3. Cost thresholds for alternative implementations of certain operations.
//
// In addition it has a few other components, like information about FP
// immediates.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TARGET_TARGETLOWERING_H
#define LLVM_TARGET_TARGETLOWERING_H
#include "llvm/CallingConv.h"
#include "llvm/InlineAsm.h"
#include "llvm/CodeGen/SelectionDAGNodes.h"
#include "llvm/CodeGen/RuntimeLibcalls.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/DebugLoc.h"
#include "llvm/Target/TargetMachine.h"
#include <climits>
#include <map>
#include <vector>
namespace llvm {
class AllocaInst;
class CallInst;
class Function;
class FastISel;
class MachineBasicBlock;
class MachineFunction;
class MachineFrameInfo;
class MachineInstr;
class MachineModuleInfo;
class DwarfWriter;
class SDNode;
class SDValue;
class SelectionDAG;
class TargetData;
class TargetMachine;
class TargetRegisterClass;
class TargetSubtarget;
class TargetLoweringObjectFile;
class Value;
// FIXME: should this be here?
namespace TLSModel {
enum Model {
GeneralDynamic,
LocalDynamic,
InitialExec,
LocalExec
};
}
TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc);
//===----------------------------------------------------------------------===//
/// TargetLowering - This class defines information used to lower LLVM code to
/// legal SelectionDAG operators that the target instruction selector can accept
/// natively.
///
/// This class also defines callbacks that targets must implement to lower
/// target-specific constructs to SelectionDAG operators.
///
class TargetLowering {
TargetLowering(const TargetLowering&); // DO NOT IMPLEMENT
void operator=(const TargetLowering&); // DO NOT IMPLEMENT
public:
/// LegalizeAction - This enum indicates whether operations are valid for a
/// target, and if not, what action should be used to make them valid.
enum LegalizeAction {
Legal, // The target natively supports this operation.
Promote, // This operation should be executed in a larger type.
Expand, // Try to expand this to other ops, otherwise use a libcall.
Custom // Use the LowerOperation hook to implement custom lowering.
};
enum BooleanContent { // How the target represents true/false values.
UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
ZeroOrOneBooleanContent, // All bits zero except for bit 0.
ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
};
enum SchedPreference {
SchedulingForLatency, // Scheduling for shortest total latency.
SchedulingForRegPressure // Scheduling for lowest register pressure.
};
/// NOTE: The constructor takes ownership of TLOF.
explicit TargetLowering(TargetMachine &TM, TargetLoweringObjectFile *TLOF);
virtual ~TargetLowering();
TargetMachine &getTargetMachine() const { return TM; }
const TargetData *getTargetData() const { return TD; }
TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
bool isBigEndian() const { return !IsLittleEndian; }
bool isLittleEndian() const { return IsLittleEndian; }
MVT getPointerTy() const { return PointerTy; }
MVT getShiftAmountTy() const { return ShiftAmountTy; }
/// usesGlobalOffsetTable - Return true if this target uses a GOT for PIC
/// codegen.
bool usesGlobalOffsetTable() const { return UsesGlobalOffsetTable; }
/// isSelectExpensive - Return true if the select operation is expensive for
/// this target.
bool isSelectExpensive() const { return SelectIsExpensive; }
/// isIntDivCheap() - Return true if integer divide is usually cheaper than
/// a sequence of several shifts, adds, and multiplies for this target.
bool isIntDivCheap() const { return IntDivIsCheap; }
/// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of
/// srl/add/sra.
bool isPow2DivCheap() const { return Pow2DivIsCheap; }
/// getSetCCResultType - Return the ValueType of the result of SETCC
/// operations. Also used to obtain the target's preferred type for
/// the condition operand of SELECT and BRCOND nodes. In the case of
/// BRCOND the argument passed is MVT::Other since there are no other
/// operands to get a type hint from.
virtual
MVT::SimpleValueType getSetCCResultType(EVT VT) const;
/// getBooleanContents - For targets without i1 registers, this gives the
/// nature of the high-bits of boolean values held in types wider than i1.
/// "Boolean values" are special true/false values produced by nodes like
/// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
/// Not to be confused with general values promoted from i1.
BooleanContent getBooleanContents() const { return BooleanContents;}
/// getSchedulingPreference - Return target scheduling preference.
SchedPreference getSchedulingPreference() const {
return SchedPreferenceInfo;
}
/// getRegClassFor - Return the register class that should be used for the
/// specified value type. This may only be called on legal types.
TargetRegisterClass *getRegClassFor(EVT VT) const {
assert(VT.isSimple() && "getRegClassFor called on illegal type!");
TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT().SimpleTy];
assert(RC && "This value type is not natively supported!");
return RC;
}
/// isTypeLegal - Return true if the target has native support for the
/// specified value type. This means that it has a register that directly
/// holds it without promotions or expansions.
bool isTypeLegal(EVT VT) const {
assert(!VT.isSimple() ||
(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
}
class ValueTypeActionImpl {
/// ValueTypeActions - This is a bitvector that contains two bits for each
/// value type, where the two bits correspond to the LegalizeAction enum.
/// This can be queried with "getTypeAction(VT)".
/// dimension by (MVT::MAX_ALLOWED_VALUETYPE/32) * 2
uint32_t ValueTypeActions[(MVT::MAX_ALLOWED_VALUETYPE/32)*2];
public:
ValueTypeActionImpl() {
ValueTypeActions[0] = ValueTypeActions[1] = 0;
ValueTypeActions[2] = ValueTypeActions[3] = 0;
}
ValueTypeActionImpl(const ValueTypeActionImpl &RHS) {
ValueTypeActions[0] = RHS.ValueTypeActions[0];
ValueTypeActions[1] = RHS.ValueTypeActions[1];
ValueTypeActions[2] = RHS.ValueTypeActions[2];
ValueTypeActions[3] = RHS.ValueTypeActions[3];
}
LegalizeAction getTypeAction(LLVMContext &Context, EVT VT) const {
if (VT.isExtended()) {
if (VT.isVector()) {
return VT.isPow2VectorType() ? Expand : Promote;
}
if (VT.isInteger())
// First promote to a power-of-two size, then expand if necessary.
return VT == VT.getRoundIntegerType(Context) ? Expand : Promote;
assert(0 && "Unsupported extended type!");
return Legal;
}
unsigned I = VT.getSimpleVT().SimpleTy;
assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
return (LegalizeAction)((ValueTypeActions[I>>4] >> ((2*I) & 31)) & 3);
}
void setTypeAction(EVT VT, LegalizeAction Action) {
unsigned I = VT.getSimpleVT().SimpleTy;
assert(I<4*array_lengthof(ValueTypeActions)*sizeof(ValueTypeActions[0]));
ValueTypeActions[I>>4] |= Action << ((I*2) & 31);
}
};
const ValueTypeActionImpl &getValueTypeActions() const {
return ValueTypeActions;
}
/// getTypeAction - Return how we should legalize values of this type, either
/// it is already legal (return 'Legal') or we need to promote it to a larger
/// type (return 'Promote'), or we need to expand it into multiple registers
/// of smaller integer type (return 'Expand'). 'Custom' is not an option.
LegalizeAction getTypeAction(LLVMContext &Context, EVT VT) const {
return ValueTypeActions.getTypeAction(Context, VT);
}
/// getTypeToTransformTo - For types supported by the target, this is an
/// identity function. For types that must be promoted to larger types, this
/// returns the larger type to promote to. For integer types that are larger
/// than the largest integer register, this contains one step in the expansion
/// to get to the smaller register. For illegal floating point types, this
/// returns the integer type to transform to.
EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
if (VT.isSimple()) {
assert((unsigned)VT.getSimpleVT().SimpleTy <
array_lengthof(TransformToType));
EVT NVT = TransformToType[VT.getSimpleVT().SimpleTy];
assert(getTypeAction(Context, NVT) != Promote &&
"Promote may not follow Expand or Promote");
return NVT;
}
if (VT.isVector()) {
EVT NVT = VT.getPow2VectorType(Context);
if (NVT == VT) {
// Vector length is a power of 2 - split to half the size.
unsigned NumElts = VT.getVectorNumElements();
EVT EltVT = VT.getVectorElementType();
return (NumElts == 1) ?
EltVT : EVT::getVectorVT(Context, EltVT, NumElts / 2);
}
// Promote to a power of two size, avoiding multi-step promotion.
return getTypeAction(Context, NVT) == Promote ?
getTypeToTransformTo(Context, NVT) : NVT;
} else if (VT.isInteger()) {
EVT NVT = VT.getRoundIntegerType(Context);
if (NVT == VT)
// Size is a power of two - expand to half the size.
return EVT::getIntegerVT(Context, VT.getSizeInBits() / 2);
else
// Promote to a power of two size, avoiding multi-step promotion.
return getTypeAction(Context, NVT) == Promote ?
getTypeToTransformTo(Context, NVT) : NVT;
}
assert(0 && "Unsupported extended type!");
return MVT(MVT::Other); // Not reached
}
/// getTypeToExpandTo - For types supported by the target, this is an
/// identity function. For types that must be expanded (i.e. integer types
/// that are larger than the largest integer register or illegal floating
/// point types), this returns the largest legal type it will be expanded to.
EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
assert(!VT.isVector());
while (true) {
switch (getTypeAction(Context, VT)) {
case Legal:
return VT;
case Expand:
VT = getTypeToTransformTo(Context, VT);
break;
default:
assert(false && "Type is not legal nor is it to be expanded!");
return VT;
}
}
return VT;
}
/// getVectorTypeBreakdown - Vector types are broken down into some number of
/// legal first class types. For example, EVT::v8f32 maps to 2 EVT::v4f32
/// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack.
/// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86.
///
/// This method returns the number of registers needed, and the VT for each
/// register. It also returns the VT and quantity of the intermediate values
/// before they are promoted/expanded.
///
unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
EVT &IntermediateVT,
unsigned &NumIntermediates,
EVT &RegisterVT) const;
/// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the
/// intrinsic will need to map to a MemIntrinsicNode (touches memory). If
/// this is the case, it returns true and store the intrinsic
/// information into the IntrinsicInfo that was passed to the function.
typedef struct IntrinsicInfo {
unsigned opc; // target opcode
EVT memVT; // memory VT
const Value* ptrVal; // value representing memory location
int offset; // offset off of ptrVal
unsigned align; // alignment
bool vol; // is volatile?
bool readMem; // reads memory?
bool writeMem; // writes memory?
} IntrinisicInfo;
virtual bool getTgtMemIntrinsic(IntrinsicInfo& Info,
CallInst &I, unsigned Intrinsic) {
return false;
}
/// getWidenVectorType: given a vector type, returns the type to widen to
/// (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
/// If there is no vector type that we want to widen to, returns MVT::Other
/// When and were to widen is target dependent based on the cost of
/// scalarizing vs using the wider vector type.
virtual EVT getWidenVectorType(EVT VT) const;
typedef std::vector<APFloat>::const_iterator legal_fpimm_iterator;
legal_fpimm_iterator legal_fpimm_begin() const {
return LegalFPImmediates.begin();
}
legal_fpimm_iterator legal_fpimm_end() const {
return LegalFPImmediates.end();
}
/// isShuffleMaskLegal - Targets can use this to indicate that they only
/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
/// are assumed to be legal.
virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &Mask,
EVT VT) const {
return true;
}
/// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is
/// used by Targets can use this to indicate if there is a suitable
/// VECTOR_SHUFFLE that can be used to replace a VAND with a constant
/// pool entry.
virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
EVT VT) const {
return false;
}
/// getOperationAction - Return how this operation should be treated: either
/// it is legal, needs to be promoted to a larger size, needs to be
/// expanded to some other code sequence, or the target has a custom expander
/// for it.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
if (VT.isExtended()) return Expand;
assert(Op < array_lengthof(OpActions[0]) &&
(unsigned)VT.getSimpleVT().SimpleTy < sizeof(OpActions[0][0])*8 &&
"Table isn't big enough!");
unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
unsigned J = I & 31;
I = I >> 5;
return (LegalizeAction)((OpActions[I][Op] >> (J*2) ) & 3);
}
/// isOperationLegalOrCustom - Return true if the specified operation is
/// legal on this target or can be made legal with custom lowering. This
/// is used to help guide high-level lowering decisions.
bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
return (VT == MVT::Other || isTypeLegal(VT)) &&
(getOperationAction(Op, VT) == Legal ||
getOperationAction(Op, VT) == Custom);
}
/// isOperationLegal - Return true if the specified operation is legal on this
/// target.
bool isOperationLegal(unsigned Op, EVT VT) const {
return (VT == MVT::Other || isTypeLegal(VT)) &&
getOperationAction(Op, VT) == Legal;
}
/// getLoadExtAction - Return how this load with extension should be treated:
/// either it is legal, needs to be promoted to a larger size, needs to be
/// expanded to some other code sequence, or the target has a custom expander
/// for it.
LegalizeAction getLoadExtAction(unsigned LType, EVT VT) const {
assert(LType < array_lengthof(LoadExtActions) &&
(unsigned)VT.getSimpleVT().SimpleTy < sizeof(LoadExtActions[0])*4 &&
"Table isn't big enough!");
return (LegalizeAction)((LoadExtActions[LType] >>
(2*VT.getSimpleVT().SimpleTy)) & 3);
}
/// isLoadExtLegal - Return true if the specified load with extension is legal
/// on this target.
bool isLoadExtLegal(unsigned LType, EVT VT) const {
return VT.isSimple() &&
(getLoadExtAction(LType, VT) == Legal ||
getLoadExtAction(LType, VT) == Custom);
}
/// getTruncStoreAction - Return how this store with truncation should be
/// treated: either it is legal, needs to be promoted to a larger size, needs
/// to be expanded to some other code sequence, or the target has a custom
/// expander for it.
LegalizeAction getTruncStoreAction(EVT ValVT,
EVT MemVT) const {
assert((unsigned)ValVT.getSimpleVT().SimpleTy <
array_lengthof(TruncStoreActions) &&
(unsigned)MemVT.getSimpleVT().SimpleTy <
sizeof(TruncStoreActions[0])*4 &&
"Table isn't big enough!");
return (LegalizeAction)((TruncStoreActions[ValVT.getSimpleVT().SimpleTy] >>
(2*MemVT.getSimpleVT().SimpleTy)) & 3);
}
/// isTruncStoreLegal - Return true if the specified store with truncation is
/// legal on this target.
bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
return isTypeLegal(ValVT) && MemVT.isSimple() &&
(getTruncStoreAction(ValVT, MemVT) == Legal ||
getTruncStoreAction(ValVT, MemVT) == Custom);
}
/// getIndexedLoadAction - Return how the indexed load should be treated:
/// either it is legal, needs to be promoted to a larger size, needs to be
/// expanded to some other code sequence, or the target has a custom expander
/// for it.
LegalizeAction
getIndexedLoadAction(unsigned IdxMode, EVT VT) const {
assert( IdxMode < array_lengthof(IndexedModeActions[0][0]) &&
((unsigned)VT.getSimpleVT().SimpleTy) < MVT::LAST_VALUETYPE &&
"Table isn't big enough!");
return (LegalizeAction)((IndexedModeActions[
(unsigned)VT.getSimpleVT().SimpleTy][0][IdxMode]));
}
/// isIndexedLoadLegal - Return true if the specified indexed load is legal
/// on this target.
bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
return VT.isSimple() &&
(getIndexedLoadAction(IdxMode, VT) == Legal ||
getIndexedLoadAction(IdxMode, VT) == Custom);
}
/// getIndexedStoreAction - Return how the indexed store should be treated:
/// either it is legal, needs to be promoted to a larger size, needs to be
/// expanded to some other code sequence, or the target has a custom expander
/// for it.
LegalizeAction
getIndexedStoreAction(unsigned IdxMode, EVT VT) const {
assert(IdxMode < array_lengthof(IndexedModeActions[0][1]) &&
(unsigned)VT.getSimpleVT().SimpleTy < MVT::LAST_VALUETYPE &&
"Table isn't big enough!");
return (LegalizeAction)((IndexedModeActions[
(unsigned)VT.getSimpleVT().SimpleTy][1][IdxMode]));
}
/// isIndexedStoreLegal - Return true if the specified indexed load is legal
/// on this target.
bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
return VT.isSimple() &&
(getIndexedStoreAction(IdxMode, VT) == Legal ||
getIndexedStoreAction(IdxMode, VT) == Custom);
}
/// getConvertAction - Return how the conversion should be treated:
/// either it is legal, needs to be promoted to a larger size, needs to be
/// expanded to some other code sequence, or the target has a custom expander
/// for it.
LegalizeAction
getConvertAction(EVT FromVT, EVT ToVT) const {
assert((unsigned)FromVT.getSimpleVT().SimpleTy <
array_lengthof(ConvertActions) &&
(unsigned)ToVT.getSimpleVT().SimpleTy <
sizeof(ConvertActions[0])*4 &&
"Table isn't big enough!");
return (LegalizeAction)((ConvertActions[FromVT.getSimpleVT().SimpleTy] >>
(2*ToVT.getSimpleVT().SimpleTy)) & 3);
}
/// isConvertLegal - Return true if the specified conversion is legal
/// on this target.
bool isConvertLegal(EVT FromVT, EVT ToVT) const {
return isTypeLegal(FromVT) && isTypeLegal(ToVT) &&
(getConvertAction(FromVT, ToVT) == Legal ||
getConvertAction(FromVT, ToVT) == Custom);
}
/// getCondCodeAction - Return how the condition code should be treated:
/// either it is legal, needs to be expanded to some other code sequence,
/// or the target has a custom expander for it.
LegalizeAction
getCondCodeAction(ISD::CondCode CC, EVT VT) const {
assert((unsigned)CC < array_lengthof(CondCodeActions) &&
(unsigned)VT.getSimpleVT().SimpleTy < sizeof(CondCodeActions[0])*4 &&
"Table isn't big enough!");
LegalizeAction Action = (LegalizeAction)
((CondCodeActions[CC] >> (2*VT.getSimpleVT().SimpleTy)) & 3);
assert(Action != Promote && "Can't promote condition code!");
return Action;
}
/// isCondCodeLegal - Return true if the specified condition code is legal
/// on this target.
bool isCondCodeLegal(ISD::CondCode CC, EVT VT) const {
return getCondCodeAction(CC, VT) == Legal ||
getCondCodeAction(CC, VT) == Custom;
}
/// getTypeToPromoteTo - If the action for this operation is to promote, this
/// method returns the ValueType to promote to.
EVT getTypeToPromoteTo(unsigned Op, EVT VT) const {
assert(getOperationAction(Op, VT) == Promote &&
"This operation isn't promoted!");
// See if this has an explicit type specified.
std::map<std::pair<unsigned, MVT::SimpleValueType>,
MVT::SimpleValueType>::const_iterator PTTI =
PromoteToType.find(std::make_pair(Op, VT.getSimpleVT().SimpleTy));
if (PTTI != PromoteToType.end()) return PTTI->second;
assert((VT.isInteger() || VT.isFloatingPoint()) &&
"Cannot autopromote this type, add it with AddPromotedToType.");
EVT NVT = VT;
do {
NVT = (MVT::SimpleValueType)(NVT.getSimpleVT().SimpleTy+1);
assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
"Didn't find type to promote to!");
} while (!isTypeLegal(NVT) ||
getOperationAction(Op, NVT) == Promote);
return NVT;
}
/// getValueType - Return the EVT corresponding to this LLVM type.
/// This is fixed by the LLVM operations except for the pointer size. If
/// AllowUnknown is true, this will return MVT::Other for types with no EVT
/// counterpart (e.g. structs), otherwise it will assert.
EVT getValueType(const Type *Ty, bool AllowUnknown = false) const {
EVT VT = EVT::getEVT(Ty, AllowUnknown);
return VT == MVT:: iPTR ? PointerTy : VT;
}
/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
/// function arguments in the caller parameter area. This is the actual
/// alignment, not its logarithm.
virtual unsigned getByValTypeAlignment(const Type *Ty) const;
/// getRegisterType - Return the type of registers that this ValueType will
/// eventually require.
EVT getRegisterType(MVT VT) const {
assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
return RegisterTypeForVT[VT.SimpleTy];
}
/// getRegisterType - Return the type of registers that this ValueType will
/// eventually require.
EVT getRegisterType(LLVMContext &Context, EVT VT) const {
if (VT.isSimple()) {
assert((unsigned)VT.getSimpleVT().SimpleTy <
array_lengthof(RegisterTypeForVT));
return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
}
if (VT.isVector()) {
EVT VT1, RegisterVT;
unsigned NumIntermediates;
(void)getVectorTypeBreakdown(Context, VT, VT1,
NumIntermediates, RegisterVT);
return RegisterVT;
}
if (VT.isInteger()) {
return getRegisterType(Context, getTypeToTransformTo(Context, VT));
}
assert(0 && "Unsupported extended type!");
return EVT(MVT::Other); // Not reached
}
/// getNumRegisters - Return the number of registers that this ValueType will
/// eventually require. This is one for any types promoted to live in larger
/// registers, but may be more than one for types (like i64) that are split
/// into pieces. For types like i140, which are first promoted then expanded,
/// it is the number of registers needed to hold all the bits of the original
/// type. For an i140 on a 32 bit machine this means 5 registers.
unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
if (VT.isSimple()) {
assert((unsigned)VT.getSimpleVT().SimpleTy <
array_lengthof(NumRegistersForVT));
return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
}
if (VT.isVector()) {
EVT VT1, VT2;
unsigned NumIntermediates;
return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
}
if (VT.isInteger()) {
unsigned BitWidth = VT.getSizeInBits();
unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
return (BitWidth + RegWidth - 1) / RegWidth;
}
assert(0 && "Unsupported extended type!");
return 0; // Not reached
}
/// ShouldShrinkFPConstant - If true, then instruction selection should
/// seek to shrink the FP constant of the specified type to a smaller type
/// in order to save space and / or reduce runtime.
virtual bool ShouldShrinkFPConstant(EVT VT) const { return true; }
/// hasTargetDAGCombine - If true, the target has custom DAG combine
/// transformations that it can perform for the specified node.
bool hasTargetDAGCombine(ISD::NodeType NT) const {
assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
}
/// This function returns the maximum number of store operations permitted
/// to replace a call to llvm.memset. The value is set by the target at the
/// performance threshold for such a replacement.
/// @brief Get maximum # of store operations permitted for llvm.memset
unsigned getMaxStoresPerMemset() const { return maxStoresPerMemset; }
/// This function returns the maximum number of store operations permitted
/// to replace a call to llvm.memcpy. The value is set by the target at the
/// performance threshold for such a replacement.
/// @brief Get maximum # of store operations permitted for llvm.memcpy
unsigned getMaxStoresPerMemcpy() const { return maxStoresPerMemcpy; }
/// This function returns the maximum number of store operations permitted
/// to replace a call to llvm.memmove. The value is set by the target at the
/// performance threshold for such a replacement.
/// @brief Get maximum # of store operations permitted for llvm.memmove
unsigned getMaxStoresPerMemmove() const { return maxStoresPerMemmove; }
/// This function returns true if the target allows unaligned memory accesses.
/// of the specified type. This is used, for example, in situations where an
/// array copy/move/set is converted to a sequence of store operations. It's
/// use helps to ensure that such replacements don't generate code that causes
/// an alignment error (trap) on the target machine.
/// @brief Determine if the target supports unaligned memory accesses.
virtual bool allowsUnalignedMemoryAccesses(EVT VT) const {
return false;
}
/// This function returns true if the target would benefit from code placement
/// optimization.
/// @brief Determine if the target should perform code placement optimization.
bool shouldOptimizeCodePlacement() const {
return benefitFromCodePlacementOpt;
}
/// getOptimalMemOpType - Returns the target specific optimal type for load
/// and store operations as a result of memset, memcpy, and memmove lowering.
/// It returns EVT::iAny if SelectionDAG should be responsible for
/// determining it.
virtual EVT getOptimalMemOpType(uint64_t Size, unsigned Align,
bool isSrcConst, bool isSrcStr,
SelectionDAG &DAG) const {
return MVT::iAny;
}
/// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp
/// to implement llvm.setjmp.
bool usesUnderscoreSetJmp() const {
return UseUnderscoreSetJmp;
}
/// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp
/// to implement llvm.longjmp.
bool usesUnderscoreLongJmp() const {
return UseUnderscoreLongJmp;
}
/// getStackPointerRegisterToSaveRestore - If a physical register, this
/// specifies the register that llvm.savestack/llvm.restorestack should save
/// and restore.
unsigned getStackPointerRegisterToSaveRestore() const {
return StackPointerRegisterToSaveRestore;
}
/// getExceptionAddressRegister - If a physical register, this returns
/// the register that receives the exception address on entry to a landing
/// pad.
unsigned getExceptionAddressRegister() const {
return ExceptionPointerRegister;
}
/// getExceptionSelectorRegister - If a physical register, this returns
/// the register that receives the exception typeid on entry to a landing
/// pad.
unsigned getExceptionSelectorRegister() const {
return ExceptionSelectorRegister;
}
/// getJumpBufSize - returns the target's jmp_buf size in bytes (if never
/// set, the default is 200)
unsigned getJumpBufSize() const {
return JumpBufSize;
}
/// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
/// (if never set, the default is 0)
unsigned getJumpBufAlignment() const {
return JumpBufAlignment;
}
/// getIfCvtBlockLimit - returns the target specific if-conversion block size
/// limit. Any block whose size is greater should not be predicated.
unsigned getIfCvtBlockSizeLimit() const {
return IfCvtBlockSizeLimit;
}
/// getIfCvtDupBlockLimit - returns the target specific size limit for a
/// block to be considered for duplication. Any block whose size is greater
/// should not be duplicated to facilitate its predication.
unsigned getIfCvtDupBlockSizeLimit() const {
return IfCvtDupBlockSizeLimit;
}
/// getPrefLoopAlignment - return the preferred loop alignment.
///
unsigned getPrefLoopAlignment() const {
return PrefLoopAlignment;
}
/// getPreIndexedAddressParts - returns true by value, base pointer and
/// offset pointer and addressing mode by reference if the node's address
/// can be legally represented as pre-indexed load / store address.
virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base,
SDValue &Offset,
ISD::MemIndexedMode &AM,
SelectionDAG &DAG) const {
return false;
}
/// getPostIndexedAddressParts - returns true by value, base pointer and
/// offset pointer and addressing mode by reference if this node can be
/// combined with a load / store to form a post-indexed load / store.
virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
SDValue &Base, SDValue &Offset,
ISD::MemIndexedMode &AM,
SelectionDAG &DAG) const {
return false;
}
/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
/// jumptable.
virtual SDValue getPICJumpTableRelocBase(SDValue Table,
SelectionDAG &DAG) const;
/// isOffsetFoldingLegal - Return true if folding a constant offset
/// with the given GlobalAddress is legal. It is frequently not legal in
/// PIC relocation models.
virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
/// getFunctionAlignment - Return the Log2 alignment of this function.
virtual unsigned getFunctionAlignment(const Function *) const = 0;
//===--------------------------------------------------------------------===//
// TargetLowering Optimization Methods
//
/// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two
/// SDValues for returning information from TargetLowering to its clients
/// that want to combine
struct TargetLoweringOpt {
SelectionDAG &DAG;
SDValue Old;
SDValue New;
explicit TargetLoweringOpt(SelectionDAG &InDAG) : DAG(InDAG) {}
bool CombineTo(SDValue O, SDValue N) {
Old = O;
New = N;
return true;
}
/// ShrinkDemandedConstant - Check to see if the specified operand of the
/// specified instruction is a constant integer. If so, check to see if
/// there are any bits set in the constant that are not demanded. If so,
/// shrink the constant and return true.
bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
/// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
/// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
/// cast, but it could be generalized for targets with other types of
/// implicit widening casts.
bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
DebugLoc dl);
};
/// SimplifyDemandedBits - Look at Op. At this point, we know that only the
/// DemandedMask bits of the result of Op are ever used downstream. If we can
/// use this information to simplify Op, create a new simplified DAG node and
/// return true, returning the original and new nodes in Old and New.
/// Otherwise, analyze the expression and return a mask of KnownOne and
/// KnownZero bits for the expression (used to simplify the caller).
/// The KnownZero/One bits may only be accurate for those bits in the
/// DemandedMask.
bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
APInt &KnownZero, APInt &KnownOne,
TargetLoweringOpt &TLO, unsigned Depth = 0) const;
/// computeMaskedBitsForTargetNode - Determine which of the bits specified in
/// Mask are known to be either zero or one and return them in the
/// KnownZero/KnownOne bitsets.
virtual void computeMaskedBitsForTargetNode(const SDValue Op,
const APInt &Mask,
APInt &KnownZero,
APInt &KnownOne,
const SelectionDAG &DAG,
unsigned Depth = 0) const;
/// ComputeNumSignBitsForTargetNode - This method can be implemented by
/// targets that want to expose additional information about sign bits to the
/// DAG Combiner.
virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
unsigned Depth = 0) const;
struct DAGCombinerInfo {
void *DC; // The DAG Combiner object.
bool BeforeLegalize;
bool BeforeLegalizeOps;
bool CalledByLegalizer;
public:
SelectionDAG &DAG;
DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc)
: DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo),
CalledByLegalizer(cl), DAG(dag) {}
bool isBeforeLegalize() const { return BeforeLegalize; }
bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; }
bool isCalledByLegalizer() const { return CalledByLegalizer; }
void AddToWorklist(SDNode *N);
SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
bool AddTo = true);
SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
};
/// SimplifySetCC - Try to simplify a setcc built with the specified operands
/// and cc. If it is unable to simplify it, return a null SDValue.
SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
ISD::CondCode Cond, bool foldBooleans,
DAGCombinerInfo &DCI, DebugLoc dl) const;
/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
/// node is a GlobalAddress + offset.
virtual bool
isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) const;
/// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
/// location that is 'Dist' units away from the location that the 'Base' load
/// is loading from.
bool isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes,
int Dist, const MachineFrameInfo *MFI) const;
/// PerformDAGCombine - This method will be invoked for all target nodes and
/// for any target-independent nodes that the target has registered with
/// invoke it for.
///
/// The semantics are as follows:
/// Return Value:
/// SDValue.Val == 0 - No change was made
/// SDValue.Val == N - N was replaced, is dead, and is already handled.
/// otherwise - N should be replaced by the returned Operand.
///
/// In addition, methods provided by DAGCombinerInfo may be used to perform
/// more complex transformations.
///
virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
//===--------------------------------------------------------------------===//
// TargetLowering Configuration Methods - These methods should be invoked by
// the derived class constructor to configure this object for the target.
//
protected:
/// setUsesGlobalOffsetTable - Specify that this target does or doesn't use a
/// GOT for PC-relative code.
void setUsesGlobalOffsetTable(bool V) { UsesGlobalOffsetTable = V; }
/// setShiftAmountType - Describe the type that should be used for shift
/// amounts. This type defaults to the pointer type.
void setShiftAmountType(MVT VT) { ShiftAmountTy = VT; }
/// setBooleanContents - Specify how the target extends the result of a
/// boolean value from i1 to a wider type. See getBooleanContents.
void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
/// setSchedulingPreference - Specify the target scheduling preference.
void setSchedulingPreference(SchedPreference Pref) {
SchedPreferenceInfo = Pref;
}
/// setUseUnderscoreSetJmp - Indicate whether this target prefers to
/// use _setjmp to implement llvm.setjmp or the non _ version.
/// Defaults to false.
void setUseUnderscoreSetJmp(bool Val) {
UseUnderscoreSetJmp = Val;
}
/// setUseUnderscoreLongJmp - Indicate whether this target prefers to
/// use _longjmp to implement llvm.longjmp or the non _ version.
/// Defaults to false.
void setUseUnderscoreLongJmp(bool Val) {
UseUnderscoreLongJmp = Val;
}
/// setStackPointerRegisterToSaveRestore - If set to a physical register, this
/// specifies the register that llvm.savestack/llvm.restorestack should save
/// and restore.
void setStackPointerRegisterToSaveRestore(unsigned R) {
StackPointerRegisterToSaveRestore = R;
}
/// setExceptionPointerRegister - If set to a physical register, this sets
/// the register that receives the exception address on entry to a landing
/// pad.
void setExceptionPointerRegister(unsigned R) {
ExceptionPointerRegister = R;
}
/// setExceptionSelectorRegister - If set to a physical register, this sets
/// the register that receives the exception typeid on entry to a landing
/// pad.
void setExceptionSelectorRegister(unsigned R) {
ExceptionSelectorRegister = R;
}
/// SelectIsExpensive - Tells the code generator not to expand operations
/// into sequences that use the select operations if possible.
void setSelectIsExpensive() { SelectIsExpensive = true; }
/// setIntDivIsCheap - Tells the code generator that integer divide is
/// expensive, and if possible, should be replaced by an alternate sequence
/// of instructions not containing an integer divide.
void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
/// setPow2DivIsCheap - Tells the code generator that it shouldn't generate
/// srl/add/sra for a signed divide by power of two, and let the target handle
/// it.
void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
/// addRegisterClass - Add the specified register class as an available
/// regclass for the specified value type. This indicates the selector can
/// handle values of that class natively.
void addRegisterClass(EVT VT, TargetRegisterClass *RC) {
assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
AvailableRegClasses.push_back(std::make_pair(VT, RC));
RegClassForVT[VT.getSimpleVT().SimpleTy] = RC;
}
/// computeRegisterProperties - Once all of the register classes are added,
/// this allows us to compute derived properties we expose.
void computeRegisterProperties();
/// setOperationAction - Indicate that the specified operation does not work
/// with the specified type and indicate what to do about it.
void setOperationAction(unsigned Op, MVT VT,
LegalizeAction Action) {
unsigned I = (unsigned)VT.SimpleTy;
unsigned J = I & 31;
I = I >> 5;
OpActions[I][Op] &= ~(uint64_t(3UL) << (J*2));
OpActions[I][Op] |= (uint64_t)Action << (J*2);
}
/// setLoadExtAction - Indicate that the specified load with extension does
/// not work with the with specified type and indicate what to do about it.
void setLoadExtAction(unsigned ExtType, MVT VT,
LegalizeAction Action) {
assert((unsigned)VT.SimpleTy < sizeof(LoadExtActions[0])*4 &&
ExtType < array_lengthof(LoadExtActions) &&
"Table isn't big enough!");
LoadExtActions[ExtType] &= ~(uint64_t(3UL) << VT.SimpleTy*2);
LoadExtActions[ExtType] |= (uint64_t)Action << VT.SimpleTy*2;
}
/// setTruncStoreAction - Indicate that the specified truncating store does
/// not work with the with specified type and indicate what to do about it.
void setTruncStoreAction(MVT ValVT, MVT MemVT,
LegalizeAction Action) {
assert((unsigned)ValVT.SimpleTy < array_lengthof(TruncStoreActions) &&
(unsigned)MemVT.SimpleTy < sizeof(TruncStoreActions[0])*4 &&
"Table isn't big enough!");
TruncStoreActions[ValVT.SimpleTy] &= ~(uint64_t(3UL) << MemVT.SimpleTy*2);
TruncStoreActions[ValVT.SimpleTy] |= (uint64_t)Action << MemVT.SimpleTy*2;
}
/// setIndexedLoadAction - Indicate that the specified indexed load does or
/// does not work with the with specified type and indicate what to do abort
/// it. NOTE: All indexed mode loads are initialized to Expand in
/// TargetLowering.cpp
void setIndexedLoadAction(unsigned IdxMode, MVT VT,
LegalizeAction Action) {
assert((unsigned)VT.SimpleTy < MVT::LAST_VALUETYPE &&
IdxMode < array_lengthof(IndexedModeActions[0][0]) &&
"Table isn't big enough!");
IndexedModeActions[(unsigned)VT.SimpleTy][0][IdxMode] = (uint8_t)Action;
}
/// setIndexedStoreAction - Indicate that the specified indexed store does or
/// does not work with the with specified type and indicate what to do about
/// it. NOTE: All indexed mode stores are initialized to Expand in
/// TargetLowering.cpp
void setIndexedStoreAction(unsigned IdxMode, MVT VT,
LegalizeAction Action) {
assert((unsigned)VT.SimpleTy < MVT::LAST_VALUETYPE &&
IdxMode < array_lengthof(IndexedModeActions[0][1] ) &&
"Table isn't big enough!");
IndexedModeActions[(unsigned)VT.SimpleTy][1][IdxMode] = (uint8_t)Action;
}
/// setConvertAction - Indicate that the specified conversion does or does
/// not work with the with specified type and indicate what to do about it.
void setConvertAction(MVT FromVT, MVT ToVT,
LegalizeAction Action) {
assert((unsigned)FromVT.SimpleTy < array_lengthof(ConvertActions) &&
(unsigned)ToVT.SimpleTy < sizeof(ConvertActions[0])*4 &&
"Table isn't big enough!");
ConvertActions[FromVT.SimpleTy] &= ~(uint64_t(3UL) << ToVT.SimpleTy*2);
ConvertActions[FromVT.SimpleTy] |= (uint64_t)Action << ToVT.SimpleTy*2;
}
/// setCondCodeAction - Indicate that the specified condition code is or isn't
/// supported on the target and indicate what to do about it.
void setCondCodeAction(ISD::CondCode CC, MVT VT,
LegalizeAction Action) {
assert((unsigned)VT.SimpleTy < sizeof(CondCodeActions[0])*4 &&
(unsigned)CC < array_lengthof(CondCodeActions) &&
"Table isn't big enough!");
CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.SimpleTy*2);
CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.SimpleTy*2;
}
/// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the
/// promotion code defaults to trying a larger integer/fp until it can find
/// one that works. If that default is insufficient, this method can be used
/// by the target to override the default.
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
}
/// addLegalFPImmediate - Indicate that this target can instruction select
/// the specified FP immediate natively.
void addLegalFPImmediate(const APFloat& Imm) {
LegalFPImmediates.push_back(Imm);
}
/// setTargetDAGCombine - Targets should invoke this method for each target
/// independent node that they want to provide a custom DAG combiner for by
/// implementing the PerformDAGCombine virtual method.
void setTargetDAGCombine(ISD::NodeType NT) {
assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
}
/// setJumpBufSize - Set the target's required jmp_buf buffer size (in
/// bytes); default is 200
void setJumpBufSize(unsigned Size) {
JumpBufSize = Size;
}
/// setJumpBufAlignment - Set the target's required jmp_buf buffer
/// alignment (in bytes); default is 0
void setJumpBufAlignment(unsigned Align) {
JumpBufAlignment = Align;
}
/// setIfCvtBlockSizeLimit - Set the target's if-conversion block size
/// limit (in number of instructions); default is 2.
void setIfCvtBlockSizeLimit(unsigned Limit) {
IfCvtBlockSizeLimit = Limit;
}
/// setIfCvtDupBlockSizeLimit - Set the target's block size limit (in number
/// of instructions) to be considered for code duplication during
/// if-conversion; default is 2.
void setIfCvtDupBlockSizeLimit(unsigned Limit) {
IfCvtDupBlockSizeLimit = Limit;
}
/// setPrefLoopAlignment - Set the target's preferred loop alignment. Default
/// alignment is zero, it means the target does not care about loop alignment.
void setPrefLoopAlignment(unsigned Align) {
PrefLoopAlignment = Align;
}
public:
virtual const TargetSubtarget *getSubtarget() {
assert(0 && "Not Implemented");
return NULL; // this is here to silence compiler errors
}
//===--------------------------------------------------------------------===//
// Lowering methods - These methods must be implemented by targets so that
// the SelectionDAGLowering code knows how to lower these.
//
/// LowerFormalArguments - This hook must be implemented to lower the
/// incoming (formal) arguments, described by the Ins array, into the
/// specified DAG. The implementation should fill in the InVals array
/// with legal-type argument values, and return the resulting token
/// chain value.
///
virtual SDValue
LowerFormalArguments(SDValue Chain,
unsigned CallConv, bool isVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins,
DebugLoc dl, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) {
assert(0 && "Not Implemented");
return SDValue(); // this is here to silence compiler errors
}
/// LowerCallTo - This function lowers an abstract call to a function into an
/// actual call. This returns a pair of operands. The first element is the
/// return value for the function (if RetTy is not VoidTy). The second
/// element is the outgoing token chain. It calls LowerCall to do the actual
/// lowering.
struct ArgListEntry {
SDValue Node;
const Type* Ty;
bool isSExt : 1;
bool isZExt : 1;
bool isInReg : 1;
bool isSRet : 1;
bool isNest : 1;
bool isByVal : 1;
uint16_t Alignment;
ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
isSRet(false), isNest(false), isByVal(false), Alignment(0) { }
};
typedef std::vector<ArgListEntry> ArgListTy;
std::pair<SDValue, SDValue>
LowerCallTo(SDValue Chain, const Type *RetTy, bool RetSExt, bool RetZExt,
bool isVarArg, bool isInreg, unsigned NumFixedArgs,
unsigned CallConv, bool isTailCall, bool isReturnValueUsed,
SDValue Callee, ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl);
/// LowerCall - This hook must be implemented to lower calls into the
/// the specified DAG. The outgoing arguments to the call are described
/// by the Outs array, and the values to be returned by the call are
/// described by the Ins array. The implementation should fill in the
/// InVals array with legal-type return values from the call, and return
/// the resulting token chain value.
///
/// The isTailCall flag here is normative. If it is true, the
/// implementation must emit a tail call. The
/// IsEligibleForTailCallOptimization hook should be used to catch
/// cases that cannot be handled.
///
virtual SDValue
LowerCall(SDValue Chain, SDValue Callee,
unsigned CallConv, bool isVarArg, bool isTailCall,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<ISD::InputArg> &Ins,
DebugLoc dl, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) {
assert(0 && "Not Implemented");
return SDValue(); // this is here to silence compiler errors
}
/// LowerReturn - This hook must be implemented to lower outgoing
/// return values, described by the Outs array, into the specified
/// DAG. The implementation should return the resulting token chain
/// value.
///
virtual SDValue
LowerReturn(SDValue Chain, unsigned CallConv, bool isVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
DebugLoc dl, SelectionDAG &DAG) {
assert(0 && "Not Implemented");
return SDValue(); // this is here to silence compiler errors
}
/// EmitTargetCodeForMemcpy - Emit target-specific code that performs a
/// memcpy. This can be used by targets to provide code sequences for cases
/// that don't fit the target's parameters for simple loads/stores and can be
/// more efficient than using a library call. This function can return a null
/// SDValue if the target declines to use custom code and a different
/// lowering strategy should be used.
///
/// If AlwaysInline is true, the size is constant and the target should not
/// emit any calls and is strongly encouraged to attempt to emit inline code
/// even if it is beyond the usual threshold because this intrinsic is being
/// expanded in a place where calls are not feasible (e.g. within the prologue
/// for another call). If the target chooses to decline an AlwaysInline
/// request here, legalize will resort to using simple loads and stores.
virtual SDValue
EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
SDValue Chain,
SDValue Op1, SDValue Op2,
SDValue Op3, unsigned Align,
bool AlwaysInline,
const Value *DstSV, uint64_t DstOff,
const Value *SrcSV, uint64_t SrcOff) {
return SDValue();
}
/// EmitTargetCodeForMemmove - Emit target-specific code that performs a
/// memmove. This can be used by targets to provide code sequences for cases
/// that don't fit the target's parameters for simple loads/stores and can be
/// more efficient than using a library call. This function can return a null
/// SDValue if the target declines to use custom code and a different
/// lowering strategy should be used.
virtual SDValue
EmitTargetCodeForMemmove(SelectionDAG &DAG, DebugLoc dl,
SDValue Chain,
SDValue Op1, SDValue Op2,
SDValue Op3, unsigned Align,
const Value *DstSV, uint64_t DstOff,
const Value *SrcSV, uint64_t SrcOff) {
return SDValue();
}
/// EmitTargetCodeForMemset - Emit target-specific code that performs a
/// memset. This can be used by targets to provide code sequences for cases
/// that don't fit the target's parameters for simple stores and can be more
/// efficient than using a library call. This function can return a null
/// SDValue if the target declines to use custom code and a different
/// lowering strategy should be used.
virtual SDValue
EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
SDValue Chain,
SDValue Op1, SDValue Op2,
SDValue Op3, unsigned Align,
const Value *DstSV, uint64_t DstOff) {
return SDValue();
}
/// LowerOperationWrapper - This callback is invoked by the type legalizer
/// to legalize nodes with an illegal operand type but legal result types.
/// It replaces the LowerOperation callback in the type Legalizer.
/// The reason we can not do away with LowerOperation entirely is that
/// LegalizeDAG isn't yet ready to use this callback.
/// TODO: Consider merging with ReplaceNodeResults.
/// The target places new result values for the node in Results (their number
/// and types must exactly match those of the original return values of
/// the node), or leaves Results empty, which indicates that the node is not
/// to be custom lowered after all.
/// The default implementation calls LowerOperation.
virtual void LowerOperationWrapper(SDNode *N,
SmallVectorImpl<SDValue> &Results,
SelectionDAG &DAG);
/// LowerOperation - This callback is invoked for operations that are
/// unsupported by the target, which are registered to use 'custom' lowering,
/// and whose defined values are all legal.
/// If the target has no operations that require custom lowering, it need not
/// implement this. The default implementation of this aborts.
virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG);
/// ReplaceNodeResults - This callback is invoked when a node result type is
/// illegal for the target, and the operation was registered to use 'custom'
/// lowering for that result type. The target places new result values for
/// the node in Results (their number and types must exactly match those of
/// the original return values of the node), or leaves Results empty, which
/// indicates that the node is not to be custom lowered after all.
///
/// If the target has no operations that require custom lowering, it need not
/// implement this. The default implementation aborts.
virtual void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
SelectionDAG &DAG) {
assert(0 && "ReplaceNodeResults not implemented for this target!");
}
/// IsEligibleForTailCallOptimization - Check whether the call is eligible for
/// tail call optimization. Targets which want to do tail call optimization
/// should override this function.
virtual bool
IsEligibleForTailCallOptimization(SDValue Callee,
unsigned CalleeCC,
bool isVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins,
SelectionDAG& DAG) const {
// Conservative default: no calls are eligible.
return false;
}
/// GetPossiblePreceedingTailCall - Get preceeding TailCallNodeOpCode node if
/// it exists. Skip a possible ISD::TokenFactor.
static SDValue GetPossiblePreceedingTailCall(SDValue Chain,
unsigned TailCallNodeOpCode) {
if (Chain.getOpcode() == TailCallNodeOpCode) {
return Chain;
} else if (Chain.getOpcode() == ISD::TokenFactor) {
if (Chain.getNumOperands() &&
Chain.getOperand(0).getOpcode() == TailCallNodeOpCode)
return Chain.getOperand(0);
}
return Chain;
}
/// getTargetNodeName() - This method returns the name of a target specific
/// DAG node.
virtual const char *getTargetNodeName(unsigned Opcode) const;
/// createFastISel - This method returns a target specific FastISel object,
/// or null if the target does not support "fast" ISel.
virtual FastISel *
createFastISel(MachineFunction &,
MachineModuleInfo *, DwarfWriter *,
DenseMap<const Value *, unsigned> &,
DenseMap<const BasicBlock *, MachineBasicBlock *> &,
DenseMap<const AllocaInst *, int> &
#ifndef NDEBUG
, SmallSet<Instruction*, 8> &CatchInfoLost
#endif
) {
return 0;
}
//===--------------------------------------------------------------------===//
// Inline Asm Support hooks
//
/// ExpandInlineAsm - This hook allows the target to expand an inline asm
/// call to be explicit llvm code if it wants to. This is useful for
/// turning simple inline asms into LLVM intrinsics, which gives the
/// compiler more information about the behavior of the code.
virtual bool ExpandInlineAsm(CallInst *CI) const {
return false;
}
enum ConstraintType {
C_Register, // Constraint represents specific register(s).
C_RegisterClass, // Constraint represents any of register(s) in class.
C_Memory, // Memory constraint.
C_Other, // Something else.
C_Unknown // Unsupported constraint.
};
/// AsmOperandInfo - This contains information for each constraint that we are
/// lowering.
struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
/// ConstraintCode - This contains the actual string for the code, like "m".
/// TargetLowering picks the 'best' code from ConstraintInfo::Codes that
/// most closely matches the operand.
std::string ConstraintCode;
/// ConstraintType - Information about the constraint code, e.g. Register,
/// RegisterClass, Memory, Other, Unknown.
TargetLowering::ConstraintType ConstraintType;
/// CallOperandval - If this is the result output operand or a
/// clobber, this is null, otherwise it is the incoming operand to the
/// CallInst. This gets modified as the asm is processed.
Value *CallOperandVal;
/// ConstraintVT - The ValueType for the operand value.
EVT ConstraintVT;
/// isMatchingInputConstraint - Return true of this is an input operand that
/// is a matching constraint like "4".
bool isMatchingInputConstraint() const;
/// getMatchedOperand - If this is an input matching constraint, this method
/// returns the output operand it matches.
unsigned getMatchedOperand() const;
AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
: InlineAsm::ConstraintInfo(info),
ConstraintType(TargetLowering::C_Unknown),
CallOperandVal(0), ConstraintVT(MVT::Other) {
}
};
/// ComputeConstraintToUse - Determines the constraint code and constraint
/// type to use for the specific AsmOperandInfo, setting
/// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand
/// being passed in is available, it can be passed in as Op, otherwise an
/// empty SDValue can be passed. If hasMemory is true it means one of the asm
/// constraint of the inline asm instruction being processed is 'm'.
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
SDValue Op,
bool hasMemory,
SelectionDAG *DAG = 0) const;
/// getConstraintType - Given a constraint, return the type of constraint it
/// is for this target.
virtual ConstraintType getConstraintType(const std::string &Constraint) const;
/// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
/// return a list of registers that can be used to satisfy the constraint.
/// This should only be used for C_RegisterClass constraints.
virtual std::vector<unsigned>
getRegClassForInlineAsmConstraint(const std::string &Constraint,
EVT VT) const;
/// getRegForInlineAsmConstraint - Given a physical register constraint (e.g.
/// {edx}), return the register number and the register class for the
/// register.
///
/// Given a register class constraint, like 'r', if this corresponds directly
/// to an LLVM register class, return a register of 0 and the register class
/// pointer.
///
/// This should only be used for C_Register constraints. On error,
/// this returns a register number of 0 and a null register class pointer..
virtual std::pair<unsigned, const TargetRegisterClass*>
getRegForInlineAsmConstraint(const std::string &Constraint,
EVT VT) const;
/// LowerXConstraint - try to replace an X constraint, which matches anything,
/// with another that has more specific requirements based on the type of the
/// corresponding operand. This returns null if there is no replacement to
/// make.
virtual const char *LowerXConstraint(EVT ConstraintVT) const;
/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
/// vector. If it is invalid, don't add anything to Ops. If hasMemory is true
/// it means one of the asm constraint of the inline asm instruction being
/// processed is 'm'.
virtual void LowerAsmOperandForConstraint(SDValue Op, char ConstraintLetter,
bool hasMemory,
std::vector<SDValue> &Ops,
SelectionDAG &DAG) const;
//===--------------------------------------------------------------------===//
// Scheduler hooks
//
// EmitInstrWithCustomInserter - This method should be implemented by targets
// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
// instructions are special in various ways, which require special support to
// insert. The specified MachineInstr is created but not inserted into any
// basic blocks, and the scheduler passes ownership of it to this method.
virtual MachineBasicBlock *EmitInstrWithCustomInserter(MachineInstr *MI,
MachineBasicBlock *MBB) const;
//===--------------------------------------------------------------------===//
// Addressing mode description hooks (used by LSR etc).
//
/// AddrMode - This represents an addressing mode of:
/// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
/// If BaseGV is null, there is no BaseGV.
/// If BaseOffs is zero, there is no base offset.
/// If HasBaseReg is false, there is no base register.
/// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
/// no scale.
///
struct AddrMode {
GlobalValue *BaseGV;
int64_t BaseOffs;
bool HasBaseReg;
int64_t Scale;
AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
};
/// isLegalAddressingMode - Return true if the addressing mode represented by
/// AM is legal for this target, for a load/store of the specified type.
/// The type may be VoidTy, in which case only return true if the addressing
/// mode is legal for a load/store of any legal type.
/// TODO: Handle pre/postinc as well.
virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const;
/// isTruncateFree - Return true if it's free to truncate a value of
/// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
/// register EAX to i16 by referencing its sub-register AX.
virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const {
return false;
}
virtual bool isTruncateFree(EVT VT1, EVT VT2) const {
return false;
}
/// isZExtFree - Return true if any actual instruction that defines a
/// value of type Ty1 implicit zero-extends the value to Ty2 in the result
/// register. This does not necessarily include registers defined in
/// unknown ways, such as incoming arguments, or copies from unknown
/// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this
/// does not necessarily apply to truncate instructions. e.g. on x86-64,
/// all instructions that define 32-bit values implicit zero-extend the
/// result out to 64 bits.
virtual bool isZExtFree(const Type *Ty1, const Type *Ty2) const {
return false;
}
virtual bool isZExtFree(EVT VT1, EVT VT2) const {
return false;
}
/// isNarrowingProfitable - Return true if it's profitable to narrow
/// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
/// from i32 to i8 but not from i32 to i16.
virtual bool isNarrowingProfitable(EVT VT1, EVT VT2) const {
return false;
}
//===--------------------------------------------------------------------===//
// Div utility functions
//
SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG,
std::vector<SDNode*>* Created) const;
SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG,
std::vector<SDNode*>* Created) const;
//===--------------------------------------------------------------------===//
// Runtime Library hooks
//
/// setLibcallName - Rename the default libcall routine name for the specified
/// libcall.
void setLibcallName(RTLIB::Libcall Call, const char *Name) {
LibcallRoutineNames[Call] = Name;
}
/// getLibcallName - Get the libcall routine name for the specified libcall.
///
const char *getLibcallName(RTLIB::Libcall Call) const {
return LibcallRoutineNames[Call];
}
/// setCmpLibcallCC - Override the default CondCode to be used to test the
/// result of the comparison libcall against zero.
void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
CmpLibcallCCs[Call] = CC;
}
/// getCmpLibcallCC - Get the CondCode that's to be used to test the result of
/// the comparison libcall against zero.
ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
return CmpLibcallCCs[Call];
}
/// setLibcallCallingConv - Set the CallingConv that should be used for the
/// specified libcall.
void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
LibcallCallingConvs[Call] = CC;
}
/// getLibcallCallingConv - Get the CallingConv that should be used for the
/// specified libcall.
CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
return LibcallCallingConvs[Call];
}
private:
TargetMachine &TM;
const TargetData *TD;
TargetLoweringObjectFile &TLOF;
/// PointerTy - The type to use for pointers, usually i32 or i64.
///
MVT PointerTy;
/// IsLittleEndian - True if this is a little endian target.
///
bool IsLittleEndian;
/// UsesGlobalOffsetTable - True if this target uses a GOT for PIC codegen.
///
bool UsesGlobalOffsetTable;
/// SelectIsExpensive - Tells the code generator not to expand operations
/// into sequences that use the select operations if possible.
bool SelectIsExpensive;
/// IntDivIsCheap - Tells the code generator not to expand integer divides by
/// constants into a sequence of muls, adds, and shifts. This is a hack until
/// a real cost model is in place. If we ever optimize for size, this will be
/// set to true unconditionally.
bool IntDivIsCheap;
/// Pow2DivIsCheap - Tells the code generator that it shouldn't generate
/// srl/add/sra for a signed divide by power of two, and let the target handle
/// it.
bool Pow2DivIsCheap;
/// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement
/// llvm.setjmp. Defaults to false.
bool UseUnderscoreSetJmp;
/// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement
/// llvm.longjmp. Defaults to false.
bool UseUnderscoreLongJmp;
/// ShiftAmountTy - The type to use for shift amounts, usually i8 or whatever
/// PointerTy is.
MVT ShiftAmountTy;
/// BooleanContents - Information about the contents of the high-bits in
/// boolean values held in a type wider than i1. See getBooleanContents.
BooleanContent BooleanContents;
/// SchedPreferenceInfo - The target scheduling preference: shortest possible
/// total cycles or lowest register usage.
SchedPreference SchedPreferenceInfo;
/// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers
unsigned JumpBufSize;
/// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf
/// buffers
unsigned JumpBufAlignment;
/// IfCvtBlockSizeLimit - The maximum allowed size for a block to be
/// if-converted.
unsigned IfCvtBlockSizeLimit;
/// IfCvtDupBlockSizeLimit - The maximum allowed size for a block to be
/// duplicated during if-conversion.
unsigned IfCvtDupBlockSizeLimit;
/// PrefLoopAlignment - The perferred loop alignment.
///
unsigned PrefLoopAlignment;
/// StackPointerRegisterToSaveRestore - If set to a physical register, this
/// specifies the register that llvm.savestack/llvm.restorestack should save
/// and restore.
unsigned StackPointerRegisterToSaveRestore;
/// ExceptionPointerRegister - If set to a physical register, this specifies
/// the register that receives the exception address on entry to a landing
/// pad.
unsigned ExceptionPointerRegister;
/// ExceptionSelectorRegister - If set to a physical register, this specifies
/// the register that receives the exception typeid on entry to a landing
/// pad.
unsigned ExceptionSelectorRegister;
/// RegClassForVT - This indicates the default register class to use for
/// each ValueType the target supports natively.
TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
EVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
/// TransformToType - For any value types we are promoting or expanding, this
/// contains the value type that we are changing to. For Expanded types, this
/// contains one step of the expand (e.g. i64 -> i32), even if there are
/// multiple steps required (e.g. i64 -> i16). For types natively supported
/// by the system, this holds the same type (e.g. i32 -> i32).
EVT TransformToType[MVT::LAST_VALUETYPE];
/// OpActions - For each operation and each value type, keep a LegalizeAction
/// that indicates how instruction selection should deal with the operation.
/// Most operations are Legal (aka, supported natively by the target), but
/// operations that are not should be described. Note that operations on
/// non-legal value types are not described here.
/// This array is accessed using VT.getSimpleVT(), so it is subject to
/// the MVT::MAX_ALLOWED_VALUETYPE * 2 bits.
uint64_t OpActions[MVT::MAX_ALLOWED_VALUETYPE/(sizeof(uint64_t)*4)][ISD::BUILTIN_OP_END];
/// LoadExtActions - For each load of load extension type and each value type,
/// keep a LegalizeAction that indicates how instruction selection should deal
/// with the load.
uint64_t LoadExtActions[ISD::LAST_LOADEXT_TYPE];
/// TruncStoreActions - For each truncating store, keep a LegalizeAction that
/// indicates how instruction selection should deal with the store.
uint64_t TruncStoreActions[MVT::LAST_VALUETYPE];
/// IndexedModeActions - For each indexed mode and each value type,
/// keep a pair of LegalizeAction that indicates how instruction
/// selection should deal with the load / store. The first
/// dimension is now the value_type for the reference. The second
/// dimension is the load [0] vs. store[1]. The third dimension
/// represents the various modes for load store.
uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][2][ISD::LAST_INDEXED_MODE];
/// ConvertActions - For each conversion from source type to destination type,
/// keep a LegalizeAction that indicates how instruction selection should
/// deal with the conversion.
/// Currently, this is used only for floating->floating conversions
/// (FP_EXTEND and FP_ROUND).
uint64_t ConvertActions[MVT::LAST_VALUETYPE];
/// CondCodeActions - For each condition code (ISD::CondCode) keep a
/// LegalizeAction that indicates how instruction selection should
/// deal with the condition code.
uint64_t CondCodeActions[ISD::SETCC_INVALID];
ValueTypeActionImpl ValueTypeActions;
std::vector<APFloat> LegalFPImmediates;
std::vector<std::pair<EVT, TargetRegisterClass*> > AvailableRegClasses;
/// TargetDAGCombineArray - Targets can specify ISD nodes that they would
/// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(),
/// which sets a bit in this array.
unsigned char
TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
/// PromoteToType - For operations that must be promoted to a specific type,
/// this holds the destination type. This map should be sparse, so don't hold
/// it as an array.
///
/// Targets add entries to this map with AddPromotedToType(..), clients access
/// this with getTypeToPromoteTo(..).
std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
PromoteToType;
/// LibcallRoutineNames - Stores the name each libcall.
///
const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
/// CmpLibcallCCs - The ISD::CondCode that should be used to test the result
/// of each of the comparison libcall against zero.
ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
/// LibcallCallingConvs - Stores the CallingConv that should be used for each
/// libcall.
CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
protected:
/// When lowering \@llvm.memset this field specifies the maximum number of
/// store operations that may be substituted for the call to memset. Targets
/// must set this value based on the cost threshold for that target. Targets
/// should assume that the memset will be done using as many of the largest
/// store operations first, followed by smaller ones, if necessary, per
/// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
/// with 16-bit alignment would result in four 2-byte stores and one 1-byte
/// store. This only applies to setting a constant array of a constant size.
/// @brief Specify maximum number of store instructions per memset call.
unsigned maxStoresPerMemset;
/// When lowering \@llvm.memcpy this field specifies the maximum number of
/// store operations that may be substituted for a call to memcpy. Targets
/// must set this value based on the cost threshold for that target. Targets
/// should assume that the memcpy will be done using as many of the largest
/// store operations first, followed by smaller ones, if necessary, per
/// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
/// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
/// and one 1-byte store. This only applies to copying a constant array of
/// constant size.
/// @brief Specify maximum bytes of store instructions per memcpy call.
unsigned maxStoresPerMemcpy;
/// When lowering \@llvm.memmove this field specifies the maximum number of
/// store instructions that may be substituted for a call to memmove. Targets
/// must set this value based on the cost threshold for that target. Targets
/// should assume that the memmove will be done using as many of the largest
/// store operations first, followed by smaller ones, if necessary, per
/// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
/// with 8-bit alignment would result in nine 1-byte stores. This only
/// applies to copying a constant array of constant size.
/// @brief Specify maximum bytes of store instructions per memmove call.
unsigned maxStoresPerMemmove;
/// This field specifies whether the target can benefit from code placement
/// optimization.
bool benefitFromCodePlacementOpt;
};
} // end llvm namespace
#endif
| [
"feqin1023@gmail.com"
] | feqin1023@gmail.com |
2e588eebdd19324e0790ceb660787f9b8601e127 | 9de2c6b81f51ae4ab37b52e40f0135cd423bcea6 | /01_10_preprocessor/main.cpp | 87400a32c6848e53d99deeb59385f8cb429e2c00 | [] | no_license | StevenJL/learncpp | 4705a5211a87aa13505707c65ea5ba387a39beb9 | 994c843c5f780f5adc56113ab2cb9ad5297db3be | refs/heads/master | 2020-06-04T13:02:14.597844 | 2015-04-14T07:49:39 | 2015-04-14T07:49:39 | 33,918,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41 | cpp | #include "add.h"
#include "subtract.h"
| [
"sli@bleacherreport.com"
] | sli@bleacherreport.com |
a0d32c1fa842bd3771a67fc842dd7c4790a07800 | 327f995c3dd8bc34bcf3d1d00f42bafa68be48a5 | /Week 4/interval_list_intersections.cpp | 11f50629a6e39febac2ebb30a658941c41691525 | [] | no_license | varun-sirpal10/leetcode-may-challenge | e6fea90841260b18a838f205c0286b54b8379c63 | dc19f3eeeccf5581e01da16e12c854953c9d920b | refs/heads/master | 2022-09-27T05:32:53.593747 | 2020-05-31T07:39:54 | 2020-05-31T07:39:54 | 260,434,316 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 700 | cpp | class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
int i=0,j=0;
vector<vector<int>> result;
while(i < A.size() and j < B.size()){
int start = max(A[i][0],B[j][0]);
int end = min(A[i][1],B[j][1]);
vector<int> res = {start,end};
if(start <= end){
result.push_back(res);
}
if(A[i][1] < B[j][1]){
i++;
}
else{
j++;
}
}
return result;
}
}; | [
"varunsirpal5@gmail.com"
] | varunsirpal5@gmail.com |
70c1e611b49990e87e1c9b8e29fee746bdd851c1 | 503b22a5890eefcbf187fac2067e07f97830cbe9 | /cpp/barcode.cpp | 2398e01f4d302ea14f7dd0c17ed32fd9250f10b7 | [] | no_license | Wenhao-Chen/OpenCVApps | 5f6b2bb839d3249e31f171e96dc0756b3c7f9932 | e7e76fadcc4ca85fdbe3abb85ca422c465c499d6 | refs/heads/master | 2021-05-28T17:56:37.409518 | 2015-02-13T20:35:38 | 2015-02-13T20:35:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,828 | cpp | #include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int getUnitWidth(const Mat widthRow)
{
int unitWidth = widthRow.at<int>(0, 1) + widthRow.at<int>(0, 2) +
widthRow.at<int>(0, 3) + widthRow.at<int>(0, 28) +
widthRow.at<int>(0, 29) + widthRow.at<int>(0, 30) +
widthRow.at<int>(0, 31) + widthRow.at<int>(0, 32) +
widthRow.at<int>(0, 57) + widthRow.at<int>(0, 58) +
widthRow.at<int>(0, 59);
unitWidth = unitWidth / 11;
return unitWidth;
}
int getMatch(int combo[4])
{
if (combo[0] == 3 && combo[1] == 2 && combo[2] == 1 && combo[3] == 1)
return 0;
if (combo[0] == 2 && combo[1] == 2 && combo[2] == 2 && combo[3] == 1)
return 1;
if (combo[0] == 2 && combo[1] == 1 && combo[2] == 2 && combo[3] == 2)
return 2;
if (combo[0] == 1 && combo[1] == 4 && combo[2] == 1 && combo[3] == 1)
return 3;
if (combo[0] == 1 && combo[1] == 1 && combo[2] == 3 && combo[3] == 2)
return 4;
if (combo[0] == 1 && combo[1] == 2 && combo[2] == 3 && combo[3] == 1)
return 5;
if (combo[0] == 1 && combo[1] == 1 && combo[2] == 1 && combo[3] == 4)
return 6;
if (combo[0] == 1 && combo[1] == 3 && combo[2] == 1 && combo[3] == 2)
return 7;
if (combo[0] == 1 && combo[1] == 2 && combo[2] == 1 && combo[3] == 3)
return 8;
if (combo[0] == 3 && combo[1] == 1 && combo[2] == 1 && combo[3] == 2)
return 9;
return 10;
}
int parseDigit(int w1, int w2, int w3, int w4, int unitWidth)
{
int digit = 10;
if (w1*w2*w3*w4 == 0)
return digit;
if ((w1 + w2 + w3 + w4) < 5 * unitWidth)
return digit;
int i1 = w1 / unitWidth;
int i2 = w2 / unitWidth;
int i3 = w3 / unitWidth;
int i4 = w4 / unitWidth;
while ((i1 + i2 + i3 + i4) < 7)
{
i1 *= 2;
i2 *= 2;
i3 *= 2;
i4 *= 2;
}
int combo[4] = { i1, i2, i3, i4 };
if ((i1 + i2 + i3 + i4 > 7)){
int diff = i1 + i2 + i3 + i4 - 7;
int subtractLog[4] = { 0, 0, 0, 0 };
int attempNo = 0;
while (diff > 0 && attempNo < 20)
{
attempNo++;
if (subtractLog[0] == 1 &&
subtractLog[1] == 1 &&
subtractLog[2] == 1 &&
subtractLog[3] == 1)
{
subtractLog[0] = 0;
subtractLog[1] = 0;
subtractLog[2] = 0;
subtractLog[3] = 0;
}
// find largest index, then subtract 1;
// next time find another untouched largest index, then subtract 1;
// ... until sum equals 7;
int largestIndex = -1, largestWidth = 1;
for (int i = 0; i < 4; i++)
{
if (combo[i] > largestWidth && subtractLog[i] == 0)
{
largestIndex = i;
largestWidth = combo[i];
}
}
if (largestIndex == -1 || combo[largestIndex] == 1)
break;
else
{
combo[largestIndex]--;
subtractLog[largestIndex] = 1;
}
diff = combo[0] + combo[1] + combo[2] + combo[3] - 7;
}
}
digit = getMatch(combo);
return digit;
}
void doBarcode(int barcodeID)
{
Mat img = imread(
"barcode_" + to_string(barcodeID) + ".jpg",
CV_LOAD_IMAGE_GRAYSCALE) > 128;
Mat se = Mat::ones(5,1,CV_8U);
erode(img, img, se);
// 1. collect a matrix widthMatrix (61*n) from the valid rows
Mat widthMatrix = Mat::zeros(img.rows, 61, CV_32S);
for (int i = 0; i < img.rows; i++)
{
Mat barRow = img.row(i);
int widthIndex = 0;
uchar lastPixel = 255;
for (int j = 0; j < img.cols; j++)
{
uchar currentPixel = img.at<uchar>(i, j);
if (currentPixel == lastPixel)
{
widthMatrix.at<int>(i, widthIndex)++;
}
else if (widthIndex < 60)
{
widthMatrix.at<int>(i, ++widthIndex)++;
lastPixel = currentPixel;
}
}
}
// 2. for each row in widthMatrix, get UNIT_WIDTH, get the width combos of 12 DIGITS, find match
Mat digitMatrix = Mat::ones(12, widthMatrix.rows, CV_8U) * 10;
for (int i = 0; i < widthMatrix.rows; i++)
{
Mat widthRow = widthMatrix.row(i);
if (countNonZero(widthRow) != 61)
continue;
int unitWidth = getUnitWidth(widthRow);
int digitIndex = 0;
for (int j = 4; j < 54; j+=4)
{
if (j == 28)
j = 33;
int w1 = widthMatrix.at<int>(i, j);
int w2 = widthMatrix.at<int>(i, j + 1);
int w3 = widthMatrix.at<int>(i, j + 2);
int w4 = widthMatrix.at<int>(i, j + 3);
int digit = parseDigit(w1, w2, w3, w4, unitWidth);
digitMatrix.at<uchar>(digitIndex++, i) = (uchar)digit;
}
}
widthMatrix.release();
// 3. pick the most frequently appeared as result digit
int bestResult[12], index = 0;
for (int i = 0; i < 12; i++)
{
// build a map, then in the end pick the most frequent one
map<char, int> frequencyMap;
for (int j = 0; j < digitMatrix.cols; j++)
{
char digit = digitMatrix.at<char>(i, j);
map<char, int>::iterator it = frequencyMap.find(digit);
if (it != frequencyMap.end())
it->second++;
else
frequencyMap.insert(pair<char, int>(digit, 1));
}
// find the most frequent one (beside 10)
char bestDigit = -1, highestFreq = 0;
for (map<char, int>::const_iterator it = frequencyMap.begin();
it != frequencyMap.end(); ++it)
{
uchar digit = it->first;
if (digit == 10)
continue;
int freq = it->second;
if (freq > highestFreq)
{
bestDigit = digit;
highestFreq = freq;
}
}
bestResult[index++] = bestDigit;
}
String print = "";
for (int i = 0; i < 12; i++)
if (bestResult[i] != -1)
print = print + to_string(bestResult[i]);
else print = print + "*";
cout << "result: " << print << endl;
img = imread(
"barcode_" + to_string(barcodeID) + ".jpg",
CV_LOAD_IMAGE_COLOR);
double imgWidth = img.rows;
double fontScale = imgWidth / 210;
putText(img,
print,
cvPoint(img.rows/8, img.cols * 3 / 10),
CV_FONT_HERSHEY_SIMPLEX,
fontScale,
Scalar(0, 0, 255),
2);
imwrite("barcode_result_" + to_string(barcodeID) + ".png", img);
}
int main()
{
for (int i = 1; i < 6; i++)
doBarcode(i);
return 0;
}
| [
"xjtujack@gmail.com"
] | xjtujack@gmail.com |
9034a10e812dd9c16a47cc93c20a8c69a42c3d1f | b38a71daf368c26414bc89925a33917842e0504e | /lib/rawkit-worker/src/rawkit-worker.cpp | 5fc7d6bca112f397a4203cf2703af60d99291387 | [
"MIT"
] | permissive | tmpvar/rawkit | 6884f4f9f5d97bed03350361ac24eb493dbc3e2b | 0dee2bdf9e11e9033988a0d9d1e52603263c6aca | refs/heads/master | 2023-06-19T15:44:19.770373 | 2021-11-01T23:30:45 | 2021-11-01T23:31:34 | 286,560,098 | 15 | 0 | MIT | 2020-10-08T23:11:33 | 2020-08-10T19:19:46 | C++ | UTF-8 | C++ | false | false | 8,204 | cpp | #include <rawkit/worker.h>
#include <rawkit-jit-internal.h>
#include <rawkit-gpu-internal.h>
#include <rawkit-hot-internal.h>
#include <inttypes.h>
extern void worker_hot_init(rawkit_jit_t *jit);
#include <ghc/filesystem.hpp>
namespace fs = ghc::filesystem;
#include <concurrentqeueue.h>
#include <thread>
#include <atomic>
#include <chrono>
#include <atomic>
using namespace std;
rawkit_gpu_t *rawkit_worker_default_gpu(rawkit_worker_t *worker);
struct WorkerState {
using PayloadType = void *;
moodycamel::ConcurrentQueue<PayloadType> host_rx;
moodycamel::ConcurrentQueue<PayloadType> host_tx;
rawkit_hot_context_t hot_ctx;
// Vulkan synchronisation state
atomic<u64> timeline_counter = 0;
VkSemaphore timeline_semaphore = VK_NULL_HANDLE;
struct ThreadWrap {
atomic<bool> complete;
thread *t = nullptr;
ThreadWrap(WorkerState *state) {
complete.store(false);
t = new thread(WorkerState::thread_tick, state, this);
}
~ThreadWrap() {
if (t) {
if (t->joinable()) {
complete.store(true);
t->join();
}
delete t;
t = nullptr;
}
}
};
static void thread_tick(WorkerState *worker_state, ThreadWrap *thread_wrap) {
while(!thread_wrap->complete.load()) {
rawkit_jit_tick_status result = rawkit_jit_tick(worker_state->jit);
if (result == RAWKIT_JIT_TICK_ERROR) {
uint32_t i = 0;
rawkit_jit_message_t msg;
while (rawkit_jit_get_message(worker_state->jit, i, &msg)) {
if (i == 0) {
fprintf(stderr, "program compilation issues\n");
}
const char *level_str = "<null>";
switch (msg.level) {
case RAWKIT_JIT_MESSAGE_LEVEL_NOTE: level_str = "note"; break;
case RAWKIT_JIT_MESSAGE_LEVEL_WARNING: level_str = "warning"; break;
case RAWKIT_JIT_MESSAGE_LEVEL_REMARK: level_str = "remark"; break;
case RAWKIT_JIT_MESSAGE_LEVEL_ERROR: level_str = "error"; break;
case RAWKIT_JIT_MESSAGE_LEVEL_FATAL: level_str = "fatal"; break;
default:
level_str = "none";
}
fprintf(stderr, "%s %s:%u:%u %s\n",
level_str,
msg.filename,
msg.line,
msg.column,
msg.str
);
i++;
}
}
if (result == RAWKIT_JIT_TICK_BUILT) {
rawkit_jit_call_setup(worker_state->jit);
}
if (worker_state->gpu.valid) {
rawkit_gpu_tick(&worker_state->gpu);
}
rawkit_jit_call_loop(worker_state->jit);
std::this_thread::sleep_for (std::chrono::milliseconds(1));
}
}
ThreadWrap *thread_wrap = nullptr;
rawkit_jit_t *jit = nullptr;
const char *full_path = nullptr;
rawkit_worker_t *worker = nullptr;
using GetHostWorkerFn = function<rawkit_worker_t *()>;
GetHostWorkerFn get_host_worker_fn = nullptr;
rawkit_gpu_t gpu = {};
rawkit_worker_t *get_worker() {
return this->worker;
}
rawkit_gpu_t *get_parent_gpu() {
return rawkit_default_gpu();
}
char worker_host_address_define[512] = "";
WorkerState(rawkit_worker_t *w, const char *full_path, bool jit_debug) {
worker = w;
this->full_path = full_path;
jit = rawkit_jit_create(full_path);
rawkit_jit_set_debug(jit, jit_debug);
worker_hot_init(jit);
rawkit_jit_add_export(jit, "rawkit_worker_default_gpu", rawkit_worker_default_gpu);
rawkit_jit_add_define(jit, "-DRAWKIT_WORKER=1");
snprintf(
worker_host_address_define,
sizeof(worker_host_address_define) - 1,
"-DRAWKIT_WORKER_HOST_ADDRESS=((rawkit_worker_t *)(uintptr_t(0x%" PRIxPTR ")))",
intptr_t(w)
);
rawkit_jit_add_define(jit, worker_host_address_define);
thread_wrap = new ThreadWrap(this);
{
VkSemaphoreTypeCreateInfo timelineCreateInfo;
timelineCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO;
timelineCreateInfo.pNext = NULL;
timelineCreateInfo.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE;
timelineCreateInfo.initialValue = 0;
VkSemaphoreCreateInfo createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
createInfo.pNext = &timelineCreateInfo;
createInfo.flags = 0;
vkCreateSemaphore(
rawkit_default_gpu()->device,
&createInfo,
NULL,
&timeline_semaphore
);
}
}
};
rawkit_worker_t *rawkit_worker_create_ex(const char *name, const char *file, const char *from_file, bool jit_debug) {
fs::path full_path(file);
if (!fs::exists(full_path)) {
fs::path rel_dir = fs::path(from_file).remove_filename();
full_path = fs::absolute(rel_dir / full_path);
}
char tmp[2048] = "\0";
snprintf(tmp, sizeof(tmp)-1, "rawkit-worker/%s-%s", name, full_path.string().c_str());
rawkit_worker_t *worker = rawkit_hot_resource(tmp, rawkit_worker_t);
strncpy(
worker->full_path,
full_path.string().c_str(),
sizeof(worker->full_path) - 1
);
if (!worker->_state) {
WorkerState *state = new WorkerState(
worker,
worker->full_path,
jit_debug
);
worker->_state = (void *)state;
}
return worker;
}
void rawkit_worker_send_ex(rawkit_worker_t *worker, void *data, u32 size, bool worker_to_host) {
if (!worker || !worker->_state || !data) {
printf("rawkit_worker_send_ex worker or worker->_state or was null\n");
return;
}
auto state = (WorkerState *)worker->_state;
auto &q = worker_to_host
? state->host_rx
: state->host_tx;
auto *msg = ps_create_value(rawkit_worker_message_t, NULL);
msg->data = malloc(size);
msg->len = size;
memcpy(msg->data, data, size);
q.enqueue(msg);
}
rawkit_worker_message_t *rawkit_worker_recv_ex(rawkit_worker_t *worker, bool worker_to_host) {
if (!worker || !worker->_state) {
printf("rawkit_worker_recv_ex worker or worker->_state was null\n");
return nullptr;
}
auto state = (WorkerState *)worker->_state;
auto &q = worker_to_host
? state->host_tx
: state->host_rx;
void *mem = nullptr;
if (!q.try_dequeue(mem)) {
return nullptr;
}
auto msg = (rawkit_worker_message_t *)mem;
if (msg && (!msg->data || !msg->len)) {
rawkit_worker_message_release(msg);
return nullptr;
}
return (rawkit_worker_message_t *)msg;
}
rawkit_worker_queue_status_t rawkit_worker_queue_status(rawkit_worker_t *worker) {
if (!worker || !worker->_state) {
return {};
}
auto state = (WorkerState *)worker->_state;
rawkit_worker_queue_status_t ret = {};
ret.rx_count = state->host_rx.size_approx();
ret.tx_count = state->host_tx.size_approx();
return ret;
}
VkSemaphore rawkit_worker_timeline_semaphore(rawkit_worker_t *worker) {
if (!worker || !worker->_state) {
return VK_NULL_HANDLE;
}
auto state = (WorkerState *)worker->_state;
return state->timeline_semaphore;
}
u64 rawkit_worker_timeline_counter_next(rawkit_worker_t *worker) {
if (!worker || !worker->_state) {
printf("ERROR: rawkit_worker_timeline_counter_next: invalid worker\n");
return 0;
}
auto state = (WorkerState *)worker->_state;
return state->timeline_counter.fetch_add(1, std::memory_order_seq_cst);
}
rawkit_hot_context_t *rawkit_worker_hot_context(rawkit_worker_t *worker) {
if (!worker || !worker->_state) {
return nullptr;
}
auto state = (WorkerState *)worker->_state;
return &state->hot_ctx;
}
rawkit_gpu_t *rawkit_worker_default_gpu(rawkit_worker_t *worker) {
if (!worker || !worker->_state) {
return nullptr;
}
auto state = (WorkerState *)worker->_state;
auto gpu = &state->gpu;
if (!state->gpu.valid) {
// TODO: copy gpu
auto root = rawkit_default_gpu();
if (!root || !root->valid) {
return nullptr;
}
gpu->instance = root->instance;
gpu->physical_device = root->physical_device;
gpu->physical_device_properties = root->physical_device_properties;
gpu->physical_device_subgroup_properties = root->physical_device_subgroup_properties;
gpu->device = root->device;
gpu->allocator = root->allocator;
gpu->_state = new GPUState();
gpu->valid = true;
}
return gpu;
} | [
"tmpvar@gmail.com"
] | tmpvar@gmail.com |
f59104740d0839d91c871b2d278f8e1cb7034b26 | 771a5f9d99fdd2431b8883cee39cf82d5e2c9b59 | /SDK/GameplayTasks_parameters.h | 9c447ef507e61c72d6abbe97e1918031d8503c7d | [
"MIT"
] | permissive | zanzo420/Sea-Of-Thieves-SDK | 6305accd032cc95478ede67d28981e041c154dce | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | refs/heads/master | 2023-03-25T22:25:21.800004 | 2021-03-20T00:51:04 | 2021-03-20T00:51:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,525 | h | #pragma once
// Name: SeaOfThieves, Version: 2.0.23
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function GameplayTasks.GameplayTask.ReadyForActivation
struct UGameplayTask_ReadyForActivation_Params
{
};
// DelegateFunction GameplayTasks.GameplayTask.GenericGameplayTaskDelegate__DelegateSignature
struct UGameplayTask_GenericGameplayTaskDelegate__DelegateSignature_Params
{
};
// Function GameplayTasks.GameplayTask.EndTask
struct UGameplayTask_EndTask_Params
{
};
// Function GameplayTasks.GameplayTask_SpawnActor.SpawnActor
struct UGameplayTask_SpawnActor_SpawnActor_Params
{
TScriptInterface<class UGameplayTaskOwnerInterface> TaskOwner; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, UObjectWrapper)
struct FVector SpawnLocation; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
struct FRotator SpawnRotation; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
class UClass* Class; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash)
bool bSpawnOnlyOnAuthority; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay)
class UGameplayTask_SpawnActor* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function GameplayTasks.GameplayTask_SpawnActor.FinishSpawningActor
struct UGameplayTask_SpawnActor_FinishSpawningActor_Params
{
class UObject* WorldContextObject; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class AActor* SpawnedActor; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function GameplayTasks.GameplayTask_SpawnActor.BeginSpawningActor
struct UGameplayTask_SpawnActor_BeginSpawningActor_Params
{
class UObject* WorldContextObject; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class AActor* SpawnedActor; // (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
};
// Function GameplayTasks.GameplayTask_WaitDelay.TaskWaitDelay
struct UGameplayTask_WaitDelay_TaskWaitDelay_Params
{
TScriptInterface<class UGameplayTaskOwnerInterface> TaskOwner; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, UObjectWrapper)
float Time; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UGameplayTask_WaitDelay* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// DelegateFunction GameplayTasks.GameplayTask_WaitDelay.TaskDelayDelegate__DelegateSignature
struct UGameplayTask_WaitDelay_TaskDelayDelegate__DelegateSignature_Params
{
};
// Function GameplayTasks.GameplayTasksComponent.OnRep_SimulatedTasks
struct UGameplayTasksComponent_OnRep_SimulatedTasks_Params
{
};
// Function GameplayTasks.GameplayTasksComponent.K2_RunGameplayTask
struct UGameplayTasksComponent_K2_RunGameplayTask_Params
{
TScriptInterface<class UGameplayTaskOwnerInterface> TaskOwner; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper)
class UGameplayTask* Task; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
unsigned char Priority; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
TArray<class UClass*> AdditionalRequiredResources; // (Parm, ZeroConstructor, AdvancedDisplay, UObjectWrapper)
TArray<class UClass*> AdditionalClaimedResources; // (Parm, ZeroConstructor, AdvancedDisplay, UObjectWrapper)
TEnumAsByte<GameplayTasks_EGameplayTaskRunResult> ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"40242723+alxalx14@users.noreply.github.com"
] | 40242723+alxalx14@users.noreply.github.com |
3fed79977313b21565086cb60a6eec23e32b2455 | f05df17ca7a992258b07b031ed101516aaf71987 | /.vscode/cquery_cached_index/c@@users@ekint@documents@github@285z_tt/src@285z-library@initop.cpp | 7c6a1972ea1afe98790be03891a6eee765b0df57 | [] | no_license | ekkin2/285Z_TT | 11f45463233f1ca20d4cfbf856daa472cd1382bb | e76ab3fc0da65501402445f130f0ed7977723ff3 | refs/heads/master | 2022-03-04T20:29:14.768074 | 2019-10-26T01:53:14 | 2019-10-26T01:53:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,902 | cpp | #include "285Z-Main/initRobot.hpp"
//File
Controller joystick;
Timer timer;
//PID Controller
const double liftkP = 0.001;
const double liftkI = 0.0001;
const double liftkD = 0.0001;
//TODO: WILL HAVE TO MODIFY WHEN WE HAVE TWO MOTORS FOR ANGLER
const int ANGLER_MOTOR_PORT = 7;
auto anglerController = AsyncControllerFactory::posPID(ANGLER_MOTOR_PORT, liftkP, liftkI, liftkD);
//This is where we initialize the specific buttons
ControllerButton btnVert(ControllerDigital::L2); //Make stack vertical
ControllerButton btnAngle(ControllerDigital::L1); //Make stack angled
ControllerButton btnIntake(ControllerDigital::R2); //Start Intake
ControllerButton btnIntakeRev(ControllerDigital::R1);
ControllerButton btnLazyMode(ControllerDigital::up);
//BOOLEANS FOR TOGGLE
bool driveStyleToggle {TANK};
bool intakeToggleBool {false};
bool liftUp {false};
bool lazy {false};
void liftVert() {
//-1690 degrees
//TODO: Change angler1 to angler when there are two motors
joystick.setText(0, 0, std::to_string(angler1.getPosition()));
if (btnVert.changedToPressed())
{
anglerController.setTarget(-1690);
}
}
void lowerFlat(){
//TODO: Change angler1 to angler when there are two motors
joystick.setText(0, 0, std::to_string(angler1.getPosition()));
if (btnAngle.changedToPressed())
{
anglerController.setTarget(0);
//angler1.moveAbsolute(0, 100);
}
}
// INTAKE FUNCTIONS //
void intakeToggle ()
{
if (btnIntake.changedToPressed())
{
intakeToggleBool = !intakeToggleBool;
}
else if(intakeToggleBool)
{
intake.moveVelocity (600);
}
else
{
intake.moveVelocity (0);
}
}
void intakeRev()
{
if (btnIntakeRev.isPressed())
{
intake.moveVelocity (-100);
}
}
// DRIVE FUNCTIONS //
void lazyMode ()
{
drive.stop();
driveL.tarePosition();
driveR.tarePosition();
driveL.setBrakeMode(AbstractMotor::brakeMode::hold);
driveR.setBrakeMode(AbstractMotor::brakeMode::hold);
pros::Task::delay(500);
driveL.moveAbsolute(0, 200);
driveR.moveAbsolute(0, 200);
joystick.setText(0, 0, "Active Brake: On");
}
void doArcade ()
{
if (!lazy)
{
driveL.setBrakeMode(AbstractMotor::brakeMode::brake);
driveR.setBrakeMode(AbstractMotor::brakeMode::brake);
drive.arcade
(
joystick.getAnalog(ControllerAnalog::leftY),
joystick.getAnalog(ControllerAnalog::rightX)
);
}
else
lazyMode();
}
void doTank ()
{
if (!lazy)
{
driveL.setBrakeMode(AbstractMotor::brakeMode::hold);
driveR.setBrakeMode(AbstractMotor::brakeMode::hold);
drive.tank
(
joystick.getAnalog(ControllerAnalog::leftY),
joystick.getAnalog(ControllerAnalog::rightY)
);
}
else
lazyMode();
}
void driveStyle (int style)
{
if(style == ARCADE){
doArcade();
} else if (style == TANK){
doTank();
} else {
doTank();
}
}
| [
"ekintiu@gmail.com"
] | ekintiu@gmail.com |
f16a1abaa0c9557039c864fa5c8ae49c2e21b6f2 | 0636e69f7cc3a94c49d6d481c0120d168d832ebf | /Solutions/Codeforces/241_DIV2/A/A copy.cpp | 003ff5f6aa8f9b2e4e6876f9eaba3aa16f7d2a39 | [] | no_license | TurtleShip/ProgrammingContests | 33e0e261341e8f78c3d8d3bd66bbad0f511acc61 | 2ebd93f9b3d50c10a10c8731d17193e69382ca9b | refs/heads/master | 2021-01-13T02:07:37.539205 | 2016-11-30T18:50:46 | 2016-11-30T18:50:46 | 18,936,833 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,797 | cpp | #include <iostream>
#include <vector>
using namespace std;
int GREATER_THAN = 0; // >
int LESS_THAN = 1; // <
int GREATER_THAN_OR_EQUAL_TO = 2; // >=
int LESS_THAN_OR_EQUAL_TO = 3; // <=
vector< pair<int, int> > V;
bool shouldBeSmaller;
bool isGood(int Y) {
bool pass = true;
for(int i=0; pass && i < V.size(); i++) {
int eq = V[i].first;
int X = V[i].second;
if(eq == GREATER_THAN) {
// printf("%d > %d\n", Y, X);
pass = Y > X;
if(!pass) shouldBeSmaller = false;
}
else if(eq == LESS_THAN) {
// printf("%d < %d\n", Y, X);
pass = Y < X;
if(!pass) shouldBeSmaller = true;
}
else if(eq == GREATER_THAN_OR_EQUAL_TO) {
// printf("%d >= %d\n", Y, X);
pass = Y >= X;
if(!pass) shouldBeSmaller = false;
}
else {
// printf("%d <= %d\n", Y, X);
pass = Y <= X;
if(!pass) shouldBeSmaller = true;
}
}
return pass;
}
int main() {
int N, num, actualEq;
cin>>N;
string eq, ans;
for(int i=0; i < N; i++) {
cin>>eq>>num>>ans;
if(eq == ">") {
if(ans == "Y") actualEq = GREATER_THAN;
else actualEq = LESS_THAN_OR_EQUAL_TO;
} else if( eq == "<") {
if(ans == "Y") actualEq = LESS_THAN;
else actualEq = GREATER_THAN_OR_EQUAL_TO;
} else if( eq == ">=" ) {
if(ans == "Y") actualEq = GREATER_THAN_OR_EQUAL_TO;
else actualEq = LESS_THAN;
} else { // eq == "<="
if(ans == "Y") actualEq = LESS_THAN_OR_EQUAL_TO;
else actualEq = GREATER_THAN;
}
V.push_back( make_pair(actualEq, num) );
}
int low = -2000000000;
int high = 2000000000;
int prev = low;
int mid;
while(low < high) {
mid = (low + high) / 2;
if(prev == mid) break;
prev = mid;
if(isGood(mid)) break;
if(shouldBeSmaller) high = mid;
else low = mid;
}
if(!isGood(mid)) cout<<"Impossible"<<endl;
else cout<<mid<<endl;
return 0;
} | [
"sk765@cornell.edu"
] | sk765@cornell.edu |
a610715162161a99251675bf04d9f491d6d52fb9 | 0d093635e5f9136225f5b004aa5e3d7f7b327196 | /Projekt---Power-Virus-CPU-i7/Projekt---Power-Virus-CPU-i7.cpp | 2117d6a05c874ab7f7f7efc302ea4ac16a7333f5 | [
"Unlicense"
] | permissive | Dejmon/Projekt---Power-Virus-CPU-i7 | 21d050d79caa74f6605e6dd223b0a0a405ecfa4f | 9dedd35fcf5a9448b8b2afb630f25322f1447a03 | refs/heads/master | 2016-09-13T23:44:17.765924 | 2016-04-12T15:07:31 | 2016-04-12T15:07:31 | 56,069,227 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 852 | cpp | // Projekt---Power-Virus-CPU-i7.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <thread>
#include <iostream>
#include <windows.h>
#include <random>
#define NUM_OF_CORES 8
void test()
{
long double c = 0.0, a = 3.5434, b = 43.2322, d = 0.4, e = 0.0;
int f = 0, g = 2, h = 5;
for (int i = 0; i < 1000000000000; i++)
{
//fdiv
c = a / b;
//fadd
e = a + b;
//ALU div
f = h / g;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
std::thread *thread_tab = new std::thread[8];
for (int i = 0; i < NUM_OF_CORES; i++)
{
thread_tab[i] = std::thread(test);
std::cout << "Startuje watek: " << i << std::endl;
}
for (int i = 0; i < NUM_OF_CORES; i++)
{
//czekamy, aż wątki przestaną pracować - umrą, następuje ich synchronizacja
thread_tab[i].join();
}
delete[] thread_tab;
return 0;
}
| [
"dejmon10@gmail.com"
] | dejmon10@gmail.com |
d8eca2f589c52f8bfa5a7f485e3214423b07a559 | 5c81fdd8b13f1d0c3f60529e414ce281c74f2038 | /games/PewPew/levelobject.cpp | 4f4272320631ca48e4259c63dc54f3ed9a9e547a | [] | no_license | Borf/playallthegames | 32dd327706cbf872e4c03d8e21f41d8dd9b93543 | 345f56bcf0e76400424b922b38bc391cb4317cba | refs/heads/master | 2021-01-18T23:10:34.381387 | 2018-04-01T17:01:50 | 2018-04-01T17:01:50 | 31,627,712 | 9 | 5 | null | 2017-06-06T19:58:35 | 2015-03-03T23:43:08 | C++ | UTF-8 | C++ | false | false | 8,143 | cpp | #include "levelobject.h"
#include "level.h"
#include "CollisionProps.h"
#include "collisionlayers.h"
#include <algorithm>
#include <glm/gtc/matrix_transform.hpp>
#include <Box2D/Box2D.h>
#include <blib/Util.h>
#include <blib/util/StreamIn.h>
#include <blib/util/FileSystem.h>
#include <blib/util/Log.h>
using blib::util::Log;
template<>
void LevelObject<SpriteGameObject>::myInit(Level* level)
{
sprite = level->objectTextureMap->addTexture("assets/games/pewpew/textures/level/objects/" + stringValues["texture"]);
if(hasStringValue("texture2"))
{
texture1 = sprite;
texture2 = level->objectTextureMap->addTexture("assets/games/pewpew/textures/level/objects/" + stringValues["texture2"]);
}
}
void LevelObjectBase::doAction(std::string action)
{
if(type == "piston")
{
if(action == "pistontoggle")
stringValues["state"] = stringValues["state"] == "open" ? "closed" : "open";
if(action == "pistonopen")
stringValues["state"] = "open";
if(action == "pistonclose")
stringValues["state"] = "close";
}
}
template <>
glm::mat4 LevelObject<SpriteGameObject>::getMatrix() const { return glm::scale(GameObject<SpriteGameObject, PhysicsGameObject>::getMatrix(this), glm::vec3(size.x / sprite->width, size.y / sprite->height, 1.0f)); }
template <>
glm::mat4 LevelObject<InvisibleGameObject>::getMatrix() const { return GameObject<InvisibleGameObject, PhysicsGameObject>::getMatrix(this); };
template <>
glm::mat4 LevelObject<AnimationGameObject>::getMatrix() const { return GameObject<AnimationGameObject, PhysicsGameObject>::getMatrix(this); };
template <class animationtype>
void LevelObject<animationtype>::init( Level* level, b2World* world )
{
myInit(level);
if(type == "gravityobject" || type == "piston" || type == "engine" || type == "trampoline" || type == "spikes" || type == "anchor" || type == "button")
{
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
if(type == "piston" || type == "engine" || type == "trampoline" || type == "spikes")
bodyDef.type = b2_kinematicBody;
if(hasStringValue("movable"))
if(stringValues["movable"] == "false")
bodyDef.type = b2_kinematicBody;
if(type == "anchor")
bodyDef.type = b2_staticBody;
bodyDef.position.Set((position.x+size.x/2.0f)/128, (position.y+size.y/2.0f)/128.0f);
bodyDef.angle = glm::radians(0.0f);
if(hasFloatValue("angle"))
bodyDef.angle = glm::radians(floatValues["angle"]);
bodyDef.angularVelocity = 0;
bodyDef.allowSleep = false;
/*b2Body* */body = world->CreateBody(&bodyDef);
body->SetUserData(new GravityObjectCollision(this));
if(type == "spikes" || type == "anchor")
stringValues["shape"] = "box";
if(type == "piston" || type == "button")
stringValues["shape"] = "file";
if(hasFloatValue("gravity"))
body->SetGravityScale(floatValues["gravity"]);
std::list<b2Shape*> shapes = buildShape(stringValues["shape"]);
for(std::list<b2Shape*>::iterator it = shapes.begin(); it != shapes.end(); it++)
{
b2FixtureDef fixtureDef;
fixtureDef.shape = *it;
fixtureDef.density = 10.0f;//non-0 = static
fixtureDef.friction = 1.0f;
fixtureDef.restitution = 0.2f;
fixtureDef.filter.categoryBits = COL_OBJECTS;
fixtureDef.filter.maskBits = COL_ALL - COL_BUTTERFLY - COL_SCARF;
if(type == "trampoline")
fixtureDef.restitution = 0.99f;
else if(type == "anchor")
{
fixtureDef.filter.categoryBits = 0;
fixtureDef.filter.maskBits = 0;
}
else if(type == "button")
{
if(stringValues["texture"] == "pressureplate.png")
{
fixtureDef.density = 1000.0f;
fixtureDef.restitution = 0;
}
else
fixtureDef.density = 0.1f;
}
body->CreateFixture(&fixtureDef);
}
}
}
void ButtonLevelObject::init(Level* level, b2World* world)
{
lastTriggerTime = 0;
LevelObject<SpriteGameObject>::init(level, world);
body->SetGravityScale(0);
body->SetUserData(new ButtonCollision(this));
b2BodyDef anchorDef;
anchorDef.type = b2_staticBody;
anchorDef.position.Set(body->GetWorldCenter().x, body->GetWorldCenter().y);
anchor = world->CreateBody(&anchorDef);
b2PolygonShape anchorShape;
anchorShape.SetAsBox(size.x/128.0f/8.0f, size.y/128.0f/8.0f);
b2FixtureDef anchorFixtureDef;
anchorFixtureDef.filter.maskBits = 0;
anchorFixtureDef.shape = &anchorShape;
anchorFixtureDef.density = 0;//non-0 = static
anchor->CreateFixture(&anchorFixtureDef);
b2Vec2 center = body->GetWorldCenter();
b2DistanceJointDef jointDef;
jointDef.Initialize(anchor, body, anchor->GetWorldCenter(), body->GetWorldCenter());
jointDef.collideConnected = false;
jointDef.dampingRatio = 2.0f;
jointDef.frequencyHz = 1.5f;
joint1 = (b2DistanceJoint*)world->CreateJoint(&jointDef);
b2Vec2 axis(glm::cos(glm::radians(floatValues["angle"]+90)), glm::sin(glm::radians(floatValues["angle"]+90)));
b2PrismaticJointDef joint2Def;
joint2Def.Initialize(anchor, body, anchor->GetWorldCenter(), axis);
joint2 = world->CreateJoint(&joint2Def);
}
void ButtonLevelObject::cleanWorld(b2World* world)
{
world->DestroyJoint(joint1);
world->DestroyJoint(joint2);
LevelObject<SpriteGameObject>::cleanWorld(world);
world->DestroyBody(anchor);
}
std::list<b2Shape*> LevelObjectBase::buildShape( const std::string &shapeName, const std::string &filename)
{
std::list<b2Shape*> ret;
if(stringValues["shape"] == "circle")
{
b2CircleShape* shape = new b2CircleShape();
shape->m_radius = size.x/128/2; //TODO: ellipse?
ret.push_back(shape);
}
else if(stringValues["shape"] == "box")
{
b2PolygonShape* shape = new b2PolygonShape();
shape->SetAsBox(size.x/128.0f/2.0f, size.y/128.0f/2.0f);
ret.push_back(shape);
}
else if(stringValues["shape"] == "file")
{
blib::util::StreamIn* colFile = NULL;
if(filename == "")
colFile = blib::util::FileSystem::openRead("assets/games/pewpew/textures/level/objects/" + stringValues["texture"] + ".col");
else
colFile = blib::util::FileSystem::openRead("assets/games/pewpew/textures/level/objects/" + filename + ".col");
int nVertices = blib::util::swapByteOrder(colFile->readInt());
std::vector<b2Vec2> colVertices;
for(int ii = 0; ii < nVertices; ii++)
{
float x = blib::util::swapByteOrder(colFile->readFloat());
float y = blib::util::swapByteOrder(colFile->readFloat());
colVertices.push_back(b2Vec2(x/128.0f,y/128.0f));
}
int nPolygons = blib::util::swapByteOrder(colFile->readInt());
for(int ii = 0; ii < nPolygons; ii++)
{
int v1 = blib::util::swapByteOrder(colFile->readInt());
int v2 = blib::util::swapByteOrder(colFile->readInt());
int v3 = blib::util::swapByteOrder(colFile->readInt());
b2PolygonShape* shape = new b2PolygonShape();
b2Vec2 colVerts[3];
colVerts[0] = colVertices[v1];
colVerts[1] = colVertices[v2];
colVerts[2] = colVertices[v3];
//ccw determination
float total = 0;
total += colVertices[v2].y*colVertices[v1].x - colVertices[v2].x*colVertices[v1].y;
total += colVertices[v3].y*colVertices[v2].x - colVertices[v3].x*colVertices[v2].y;
total += colVertices[v1].y*colVertices[v3].x - colVertices[v1].x*colVertices[v3].y;
bool ccw = total < 0;
if(ccw)
std::swap(colVerts[0], colVerts[2]);
shape->Set(colVerts, 3);
ret.push_back(shape);
}
delete colFile;
}
else
{
Log::out<<"Unknown collision type! "<<stringValues["shape"]<<Log::newline;
}
return ret;
}
bool LevelObjectBase::hasStringValue( std::string name )
{
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
return stringValues.find(name) != stringValues.end();
}
bool LevelObjectBase::hasFloatValue( std::string name )
{
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
return floatValues.find(name) != floatValues.end();
}
bool LevelObjectBase::contains( glm::vec2 point )
{
return point.x > position.x && point.x < position.x + size.x &&
point.y > position.y && point.y < position.y + size.y;
}
glm::vec2 LevelObjectBase::getCenter()
{
return position + size*glm::vec2(0.5f, -0.5f);
}
template class LevelObject<SpriteGameObject>;
template class LevelObject<InvisibleGameObject>;
template class LevelObject<AnimationGameObject>;
| [
"borfje@gmail.com"
] | borfje@gmail.com |
21d57155fcc65111e2f78461ef667c8ee3f92909 | 01d3a14aad2fcae4c50eeb11200abb000a61602d | /engine-kernelcpp/javaproxy/com__sos__scheduler__engine__kernel__variable__VariableSet.cxx | 80886e675e3f265fc0c66aca57962b0f33357cc3 | [] | no_license | sos-berlin/scheduler-engine | 25718d27c879b8f66095080c029142cb7b7e6289 | bcbf5b7b033447428b13dde5ad8132068348c726 | refs/heads/release/1.13 | 2023-09-03T04:48:38.328859 | 2023-07-11T13:56:00 | 2023-07-11T13:56:00 | 5,357,855 | 11 | 12 | null | 2023-03-20T17:02:12 | 2012-08-09T16:08:16 | C++ | UTF-8 | C++ | false | false | 1,666 | cxx | // *** Generated by com.sos.scheduler.engine.cplusplus.generator ***
#include "_precompiled.h"
#include "com__sos__scheduler__engine__kernel__variable__VariableSet.h"
#include "com__sos__scheduler__engine__cplusplus__runtime__Sister.h"
#include "java__lang__Object.h"
#include "java__lang__String.h"
namespace javaproxy { namespace com { namespace sos { namespace scheduler { namespace engine { namespace kernel { namespace variable {
struct VariableSet__class : ::zschimmer::javabridge::Class
{
VariableSet__class(const string& class_name);
~VariableSet__class();
static const ::zschimmer::javabridge::class_factory< VariableSet__class > class_factory;
};
const ::zschimmer::javabridge::class_factory< VariableSet__class > VariableSet__class::class_factory ("com.sos.scheduler.engine.kernel.variable.VariableSet");
VariableSet__class::VariableSet__class(const string& class_name) :
::zschimmer::javabridge::Class(class_name)
{}
VariableSet__class::~VariableSet__class() {}
VariableSet::VariableSet(jobject jo) { if (jo) assign_(jo); }
VariableSet::VariableSet(const VariableSet& o) { assign_(o.get_jobject()); }
#ifdef Z_HAS_MOVE_CONSTRUCTOR
VariableSet::VariableSet(VariableSet&& o) { set_jobject(o.get_jobject()); o.set_jobject(NULL); }
#endif
VariableSet::~VariableSet() { assign_(NULL); }
::zschimmer::javabridge::Class* VariableSet::java_object_class_() const { return _class.get(); }
::zschimmer::javabridge::Class* VariableSet::java_class_() { return VariableSet__class::class_factory.clas(); }
void VariableSet::Lazy_class::initialize() const {
_value = VariableSet__class::class_factory.clas();
}
}}}}}}}
| [
"jz@c11b8382-0eeb-0310-9acf-d3b3cacd313b"
] | jz@c11b8382-0eeb-0310-9acf-d3b3cacd313b |
6dca939412720e8d7e312e61043450d343dffbcb | 9a3b99b1eeb4f10400a799b51d789d0fde156be9 | /crowcoin/src/clientversion.h | 81cc0f3f81d4be66a8afc9dc1077d016c4f149ed | [
"MIT"
] | permissive | aijs/blockchain | 077e7e8bf515cac5afde04498e560f300041ceff | 89ee5dc0b243847688d7063820dc1ec58394c896 | refs/heads/master | 2020-03-28T02:55:05.362321 | 2018-08-20T09:58:32 | 2018-08-20T09:58:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,098 | h | // Copyright (c) 2009-2015 The Crowcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef CROWCOIN_CLIENTVERSION_H
#define CROWCOIN_CLIENTVERSION_H
#if defined(HAVE_CONFIG_H)
#include "config/crowcoin-config.h"
#else
/**
* client versioning and copyright year
*/
//! These need to be macros, as clientversion.cpp's and crowcoin*-res.rc's voodoo requires it
#define CLIENT_VERSION_MAJOR 0
#define CLIENT_VERSION_MINOR 12
#define CLIENT_VERSION_REVISION 1
#define CLIENT_VERSION_BUILD 0
//! Set to true for release, false for prerelease or test build
#define CLIENT_VERSION_IS_RELEASE true
/**
* Copyright year (2009-this)
* Todo: update this when changing our copyright comments in the source
*/
#define COPYRIGHT_YEAR 2016
#endif //HAVE_CONFIG_H
/**
* Converts the parameter X to a string after macro replacement on X has been performed.
* Don't merge these into one macro!
*/
#define STRINGIZE(X) DO_STRINGIZE(X)
#define DO_STRINGIZE(X) #X
//! Copyright string used in Windows .rc files
#define COPYRIGHT_STR "2009-" STRINGIZE(COPYRIGHT_YEAR) " The Crowcoin Core Developers"
/**
* crowcoind-res.rc includes this file, but it cannot cope with real c++ code.
* WINDRES_PREPROC is defined to indicate that its pre-processor is running.
* Anything other than a define should be guarded below.
*/
#if !defined(WINDRES_PREPROC)
#include <string>
#include <vector>
static const int CLIENT_VERSION =
1000000 * CLIENT_VERSION_MAJOR
+ 10000 * CLIENT_VERSION_MINOR
+ 100 * CLIENT_VERSION_REVISION
+ 1 * CLIENT_VERSION_BUILD;
extern const std::string CLIENT_NAME;
extern const std::string CLIENT_BUILD;
extern const std::string CLIENT_DATE;
std::string FormatFullVersion();
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
#endif // WINDRES_PREPROC
#endif // CROWCOIN_CLIENTVERSION_H
| [
"mistydew@qq.com"
] | mistydew@qq.com |
9994ed26c1486aa676289e426ac79fa7b487c487 | 2e02f4a1333b593cd45ea6e8aadb21e1fb4b3e2f | /CodeForces/D/1183 D.cpp | 278d8bcf1c50c3e37e0cced0696d28ec6c9d211e | [] | no_license | rahul-goel/CompetitiveProgramming | 33c42145a5807ce1e1b94334faeeb960ad381edb | 7c042b81dd9208137bbbd34e397baa55c85ff793 | refs/heads/master | 2022-09-25T04:26:16.173096 | 2022-09-05T18:26:23 | 2022-09-05T18:26:23 | 231,899,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,985 | cpp | /*
Created by Rahul Goel.
*/
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#include <queue>
#include <deque>
#include <stack>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
using namespace std;
typedef long long ll;
ll mod = 1000000007;
const int INF = 1e9;
const ll LINF = 1e18;
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define all(c) (c).begin(), (c).end()
#define pii pair < ll, ll >
#define vi vector < ll >
#define vb vector < bool >
#define vvi vector < vector < ll > >
#define vvb vector < vector < bool > >
#define vpii vector < pair < ll, ll > >
#define vvpii vector < vector < pair < ll, ll > > >
#define present(c,x) ((c).find(x) != (c).end())//for sets,maps,multimaps
#define cpresent(c,x) (find(all(c),x) != (c).end())//for vectors
#define min_pq(t) priority_queue < t, vector < t >, greater < t > >
#define max_pq(t) priority_queue < t >
#define pb push_back
#define ff first
#define ss second
ll mod_sum() { return 0ll; }
template<typename T, typename... Args>
T mod_sum(T a, Args... args) { return ((a + mod_sum(args...))%mod + mod)%mod; }
ll mod_prod() { return 1ll; }
template<typename T, typename... Args>
T mod_product(T a, Args... args) { return (a*mod_product(args...))%mod; }
// --------------------------------------------------------------
ll solve(){
ll n;
cin >> n;
vi vec(n), freq(n, 0);
for(ll i=0; i<n; i++){
cin >> vec[i];
freq[--vec[i]]++;
}
ll size = 0, prev = LINF;
vi arr;
for(ll &x : freq)
if(x)
arr.pb(x);
sort(all(arr), greater<ll>());
for(ll i=1; i<arr.size(); i++){
if(arr[i] >= arr[i-1])
arr[i] = arr[i-1]-1;
}
for(ll x : arr)
size += max(0ll, x);
cout << size << endl;
return 0;
}
int main(){
fastio;
ll t = 1;
cin >> t;
while(t--)
solve();
return 0;
}
| [
"rahulgoellko@gmail.com"
] | rahulgoellko@gmail.com |
6a071c0d84cbda09a295faa814668ad3707bc8dd | a44a1646890841c8b0928012a2659fa6c52c231d | /gdax_zorro_plugin/gdax/json.h | 9b2e14f563a802908810b3f67815e4b644ddb7f5 | [
"MIT"
] | permissive | kzhdev/gdax_zorro_plugin | b504fd9f0092f59d9fa966c3c840c9acfa317928 | 796e15cf57662ec05a854ca24de80d37565dac6d | refs/heads/main | 2023-04-27T14:08:36.061144 | 2021-04-27T03:36:23 | 2021-04-27T03:36:23 | 342,425,828 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,906 | h | #include "rapidjson/document.h"
#include <vector>
namespace gdax {
template<typename T>
struct Parser {
const T& json;
Parser(const T& j) : json(j) {}
template<typename U>
bool get(const char* name, U& value) const;
template<>
bool get<std::string>(const char* name, std::string& value) const {
if (json.HasMember(name) && json[name].IsString()) {
value = json[name].GetString();
return true;
}
return false;
}
template<>
bool get<int32_t>(const char* name, int32_t& value) const {
if (json.HasMember(name)) {
if (json[name].IsInt()) {
value = json[name].GetInt();
return true;
}
if (json[name].IsUint()) {
value = json[name].GetUint();
return true;
}
if (json[name].IsString()) {
value = atoi(json[name].GetString());
return true;
}
}
return false;
}
template<>
bool get<uint32_t>(const char* name, uint32_t& value) const {
if (json.HasMember(name)) {
if (json[name].IsUint()) {
value = json[name].GetUint();
return true;
}
if (json[name].IsInt()) {
value = json[name].GetInt();
return true;
}
if (json[name].IsString()) {
value = atoi(json[name].GetString());
}
}
return false;
}
template<>
bool get<int64_t>(const char* name, int64_t& value) const {
if (json.HasMember(name)) {
if (json[name].IsInt64()) {
value = json[name].GetInt64();
return true;
}
if (json[name].IsUint64()) {
value = json[name].GetUint64();
return true;
}
if (json[name].IsString()) {
value = _atoi64(json[name].GetString());
return true;
}
}
return false;
}
template<>
bool get<uint64_t>(const char* name, uint64_t& value) const {
if (json.HasMember(name)) {
if (json[name].IsUint64()) {
value = json[name].GetUint64();
return true;
}
if (json[name].IsInt64()) {
value = json[name].GetInt64();
return true;
}
if (json[name].IsString()) {
value = _atoi64(json[name].GetString());
return true;
}
}
return false;
}
template<>
bool get<bool>(const char* name, bool& value) const {
if (json.HasMember(name) && json[name].IsBool()) {
value = json[name].GetBool();
return true;
}
return false;
}
template<>
bool get<double>(const char* name, double& value) const {
if (json.HasMember(name)) {
auto type = json[name].GetType();
if (json[name].IsNumber()) {
value = json[name].GetDouble();
return true;
}
if (json[name].IsString()) {
value = atof(json[name].GetString());
return true;
}
}
return false;
}
template<>
bool get<float>(const char* name, float& value) const {
if (json.HasMember(name)) {
if (json[name].IsNumber()) {
value = json[name].GetFloat();
return true;
}
if (json[name].IsString()) {
value = (float)atof(json[name].GetString());
return true;
}
}
return false;
}
template<>
bool get<std::vector<double>>(const char* name, std::vector<double>& value) const {
if (json.HasMember(name) && json[name].IsArray()) {
for (auto& item : json[name].GetArray()) {
if (item.IsNumber()) {
value.push_back(item.GetDouble());
}
}
return true;
}
return false;
}
template<>
bool get<std::vector<float>>(const char* name, std::vector<float>& value) const {
if (json.HasMember(name) && json[name].IsArray()) {
for (auto& item : json[name].GetArray()) {
if (item.IsNumber()) {
value.push_back(item.GetFloat());
}
}
return true;
}
return false;
}
template<>
bool get<std::vector<uint64_t>>(const char* name, std::vector<uint64_t>& value) const {
if (json.HasMember(name) && json[name].IsArray()) {
for (auto& item : json[name].GetArray()) {
if (item.IsNumber()) {
value.push_back(item.GetUint64());
}
}
return true;
}
return false;
}
template<typename U>
U get(const char* name) const {
if (json.HasMember(name) && json[name].IsString()) {
return json[name].GetString();
}
return "";
}
};
}
| [
"kzhdev@gmail.com"
] | kzhdev@gmail.com |
0126fac58a838cdb651d8a079f562ba0a8dbccb2 | 8ed61980185397f8a11ad5851e3ffff09682c501 | /thirdparty/GeometricTools/WildMagic5/LibGraphics/SceneGraph/Wm5Polysegment.inl | edc337b109248678106f0f32884590df5b2cee22 | [
"BSD-2-Clause-Views"
] | permissive | SoMa-Project/vision | 8975a2b368f69538a05bd57b0c3eda553b783b55 | ea8199d98edc363b2be79baa7c691da3a5a6cc86 | refs/heads/melodic | 2023-04-12T22:49:13.125788 | 2021-01-11T15:28:30 | 2021-01-11T15:28:30 | 80,823,825 | 1 | 0 | NOASSERTION | 2021-04-20T21:27:03 | 2017-02-03T11:36:44 | C++ | UTF-8 | C++ | false | false | 665 | inl | // Geometric Tools, LLC
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
//----------------------------------------------------------------------------
inline int Polysegment::GetNumSegments () const
{
return mNumSegments;
}
//----------------------------------------------------------------------------
inline bool Polysegment::GetContiguous () const
{
return mContiguous;
}
//----------------------------------------------------------------------------
| [
"j.abele@tu-berlin.de"
] | j.abele@tu-berlin.de |
831e78d75f1955830a1679473e17f80e6a4a5c99 | b5fe5ba20c4ac3a0fc19132114354c6cfb230837 | /SystemBiblioteki/zalogowanyczytelnik.h | 848b8f54d794f8e29fc6017196b387cc291d5012 | [] | no_license | Maks98791/Library-System-cpp | 975faffb3be1a15fd7a5affabc96b8deb89e14df | 1776b38ff438ebbb2f93ce55c2d9e4b188c6c564 | refs/heads/master | 2020-12-13T05:30:18.719709 | 2020-06-28T17:21:56 | 2020-06-28T17:21:56 | 234,324,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | h | #ifndef ZALOGOWANYCZYTELNIK_H
#define ZALOGOWANYCZYTELNIK_H
#include <QDialog>
namespace Ui {
class zalogowanyCzytelnik;
}
class zalogowanyCzytelnik : public QDialog
{
Q_OBJECT
public:
explicit zalogowanyCzytelnik(QWidget *parent = 0);
~zalogowanyCzytelnik();
private slots:
void on_pushButton_clicked();
private:
Ui::zalogowanyCzytelnik *ui;
};
#endif // ZALOGOWANYCZYTELNIK_H
| [
"49254280+Maks791@users.noreply.github.com"
] | 49254280+Maks791@users.noreply.github.com |
34808106e46ee1bc9c997b850b31c11d6b20b38a | 3784495ba55d26e22302a803861c4ba197fd82c7 | /venv/lib/python3.6/site-packages/torch/lib/include/ATen/CUDAHalfType.h | 7d973a8457cef0c2672777942b5d5f8a04516417 | [
"MIT"
] | permissive | databill86/HyperFoods | cf7c31f5a6eb5c0d0ddb250fd045ca68eb5e0789 | 9267937c8c70fd84017c0f153c241d2686a356dd | refs/heads/master | 2021-01-06T17:08:48.736498 | 2020-02-11T05:02:18 | 2020-02-11T05:02:18 | 241,407,659 | 3 | 0 | MIT | 2020-02-18T16:15:48 | 2020-02-18T16:15:47 | null | UTF-8 | C++ | false | false | 82,215 | h | #pragma once
// @generated by aten/src/ATen/gen.py
#include "ATen/CPUTypeDefault.h"
#include "ATen/Context.h"
#include "ATen/CheckGenerator.h"
#include <ATen/cuda/ATenCUDAGeneral.h>
#include <ATen/DeviceGuard.h>
#include <ATen/cuda/CUDADevice.h>
#include <ATen/cuda/CUDATypeDefault.h>
#ifdef _MSC_VER
#ifdef Type
#undef Type
#endif
#endif
namespace at {
struct CUDAHalfType final : public CUDATypeDefault {
explicit CUDAHalfType();
virtual ScalarType scalarType() const override;
virtual caffe2::TypeMeta typeMeta() const override;
virtual Backend backend() const override;
virtual const char * toString() const override;
virtual size_t elementSizeInBytes() const override;
virtual TypeID ID() const override;
// example
// virtual Tensor * add(Tensor & a, Tensor & b) override;
Tensor & _th_set_(Tensor & self, Storage source) const override;
Tensor & _th_set_(Tensor & self, Storage source, int64_t storage_offset, IntList size, IntList stride) const override;
Tensor & _th_set_(Tensor & self, const Tensor & source) const override;
Tensor & _th_set_(Tensor & self) const override;
Tensor & _th_fill_(Tensor & self, Scalar value) const override;
Tensor & _th_fill_(Tensor & self, const Tensor & value) const override;
bool _th_is_set_to(const Tensor & self, const Tensor & tensor) const override;
Tensor & s__th_masked_fill_(Tensor & self, const Tensor & mask, Scalar value) const override;
Tensor & s__th_masked_fill_(Tensor & self, const Tensor & mask, const Tensor & value) const override;
Tensor & s__th_masked_scatter_(Tensor & self, const Tensor & mask, const Tensor & source) const override;
Tensor & s__th_masked_select_out(Tensor & result, const Tensor & self, const Tensor & mask) const override;
Tensor s__th_masked_select(const Tensor & self, const Tensor & mask) const override;
Tensor & _th_nonzero_out(Tensor & result, const Tensor & self) const override;
Tensor _th_nonzero(const Tensor & self) const override;
Tensor _th_clone(const Tensor & self) const override;
Tensor _th_view(const Tensor & self, IntList size) const override;
Tensor & _th_resize_as_(Tensor & self, const Tensor & the_template) const override;
Tensor & _th_index_select_out(Tensor & result, const Tensor & self, int64_t dim, const Tensor & index) const override;
Tensor _th_index_select(const Tensor & self, int64_t dim, const Tensor & index) const override;
Tensor & _th_index_copy_(Tensor & self, int64_t dim, const Tensor & index, const Tensor & source) const override;
Tensor & _th_take_out(Tensor & result, const Tensor & self, const Tensor & index) const override;
Tensor _th_take(const Tensor & self, const Tensor & index) const override;
Tensor & _th_put_(Tensor & self, const Tensor & index, const Tensor & source, bool accumulate) const override;
Tensor & _th_index_add_(Tensor & self, int64_t dim, const Tensor & index, const Tensor & source) const override;
Tensor & _th_index_fill_(Tensor & self, int64_t dim, const Tensor & index, Scalar value) const override;
Tensor & _th_index_fill_(Tensor & self, int64_t dim, const Tensor & index, const Tensor & value) const override;
Tensor & _th_unfold_out(Tensor & result, const Tensor & self, int64_t dimension, int64_t size, int64_t step) const override;
Tensor _th_unfold(const Tensor & self, int64_t dimension, int64_t size, int64_t step) const override;
Tensor & _th_range_out(Tensor & result, Scalar start, Scalar end, Scalar step) const override;
Tensor _th_range(Scalar start, Scalar end, Scalar step) const override;
Tensor & _th_arange_out(Tensor & result, Scalar start, Scalar end, Scalar step) const override;
Tensor _th_arange(Scalar start, Scalar end, Scalar step) const override;
Tensor & _th_arange_out(Tensor & result, Scalar end) const override;
Tensor _th_arange(Scalar end) const override;
Tensor & _th_scatter_(Tensor & self, int64_t dim, const Tensor & index, const Tensor & src) const override;
Tensor & _th_scatter_(Tensor & self, int64_t dim, const Tensor & index, Scalar value) const override;
Tensor & _th_scatter_add_(Tensor & self, int64_t dim, const Tensor & index, const Tensor & src) const override;
Tensor & _th_gather_out(Tensor & result, const Tensor & self, int64_t dim, const Tensor & index) const override;
Tensor _th_gather(const Tensor & self, int64_t dim, const Tensor & index) const override;
bool _th_equal(const Tensor & self, const Tensor & other) const override;
Tensor & _th_and_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_and(const Tensor & self, Scalar other) const override;
Tensor & s__th_and_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_and(const Tensor & self, const Tensor & other) const override;
Tensor & _th_iand_(Tensor & self, Scalar other) const override;
Tensor & s__th_iand_(Tensor & self, const Tensor & other) const override;
Tensor & _th_or_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_or(const Tensor & self, Scalar other) const override;
Tensor & s__th_or_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_or(const Tensor & self, const Tensor & other) const override;
Tensor & _th_ior_(Tensor & self, Scalar other) const override;
Tensor & s__th_ior_(Tensor & self, const Tensor & other) const override;
Tensor & _th_xor_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_xor(const Tensor & self, Scalar other) const override;
Tensor & s__th_xor_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_xor(const Tensor & self, const Tensor & other) const override;
Tensor & _th_ixor_(Tensor & self, Scalar other) const override;
Tensor & s__th_ixor_(Tensor & self, const Tensor & other) const override;
Tensor & _th_lshift_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_lshift(const Tensor & self, Scalar other) const override;
Tensor & s__th_lshift_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_lshift(const Tensor & self, const Tensor & other) const override;
Tensor & _th_ilshift_(Tensor & self, Scalar other) const override;
Tensor & s__th_ilshift_(Tensor & self, const Tensor & other) const override;
Tensor & _th_rshift_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_rshift(const Tensor & self, Scalar other) const override;
Tensor & s__th_rshift_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_rshift(const Tensor & self, const Tensor & other) const override;
Tensor & _th_irshift_(Tensor & self, Scalar other) const override;
Tensor & s__th_irshift_(Tensor & self, const Tensor & other) const override;
Tensor & _th_lt_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_lt(const Tensor & self, Scalar other) const override;
Tensor & s__th_lt_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_lt(const Tensor & self, const Tensor & other) const override;
Tensor & _th_lt_(Tensor & self, Scalar other) const override;
Tensor & s__th_lt_(Tensor & self, const Tensor & other) const override;
Tensor & _th_gt_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_gt(const Tensor & self, Scalar other) const override;
Tensor & s__th_gt_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_gt(const Tensor & self, const Tensor & other) const override;
Tensor & _th_gt_(Tensor & self, Scalar other) const override;
Tensor & s__th_gt_(Tensor & self, const Tensor & other) const override;
Tensor & _th_le_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_le(const Tensor & self, Scalar other) const override;
Tensor & s__th_le_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_le(const Tensor & self, const Tensor & other) const override;
Tensor & _th_le_(Tensor & self, Scalar other) const override;
Tensor & s__th_le_(Tensor & self, const Tensor & other) const override;
Tensor & _th_ge_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_ge(const Tensor & self, Scalar other) const override;
Tensor & s__th_ge_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_ge(const Tensor & self, const Tensor & other) const override;
Tensor & _th_ge_(Tensor & self, Scalar other) const override;
Tensor & s__th_ge_(Tensor & self, const Tensor & other) const override;
Tensor & _th_eq_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_eq(const Tensor & self, Scalar other) const override;
Tensor & s__th_eq_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_eq(const Tensor & self, const Tensor & other) const override;
Tensor & _th_eq_(Tensor & self, Scalar other) const override;
Tensor & s__th_eq_(Tensor & self, const Tensor & other) const override;
Tensor & _th_ne_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_ne(const Tensor & self, Scalar other) const override;
Tensor & s__th_ne_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_ne(const Tensor & self, const Tensor & other) const override;
Tensor & _th_ne_(Tensor & self, Scalar other) const override;
Tensor & s__th_ne_(Tensor & self, const Tensor & other) const override;
Tensor & s__th_min_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_min(const Tensor & self, const Tensor & other) const override;
Tensor _th_min(const Tensor & self) const override;
std::tuple<Tensor &,Tensor &> _th_min_out(Tensor & min, Tensor & min_indices, const Tensor & self, int64_t dim, bool keepdim) const override;
std::tuple<Tensor,Tensor> _th_min(const Tensor & self, int64_t dim, bool keepdim) const override;
Tensor & s__th_max_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_max(const Tensor & self, const Tensor & other) const override;
Tensor _th_max(const Tensor & self) const override;
std::tuple<Tensor &,Tensor &> _th_max_out(Tensor & max, Tensor & max_indices, const Tensor & self, int64_t dim, bool keepdim) const override;
std::tuple<Tensor,Tensor> _th_max(const Tensor & self, int64_t dim, bool keepdim) const override;
std::tuple<Tensor &,Tensor &> _th_mode_out(Tensor & values, Tensor & indices, const Tensor & self, int64_t dim, bool keepdim) const override;
std::tuple<Tensor,Tensor> _th_mode(const Tensor & self, int64_t dim, bool keepdim) const override;
Tensor _th_median(const Tensor & self) const override;
std::tuple<Tensor &,Tensor &> _th_median_out(Tensor & values, Tensor & indices, const Tensor & self, int64_t dim, bool keepdim) const override;
std::tuple<Tensor,Tensor> _th_median(const Tensor & self, int64_t dim, bool keepdim) const override;
std::tuple<Tensor &,Tensor &> _th_sort_out(Tensor & values, Tensor & indices, const Tensor & self, int64_t dim, bool descending) const override;
std::tuple<Tensor,Tensor> _th_sort(const Tensor & self, int64_t dim, bool descending) const override;
std::tuple<Tensor &,Tensor &> _th_topk_out(Tensor & values, Tensor & indices, const Tensor & self, int64_t k, int64_t dim, bool largest, bool sorted) const override;
std::tuple<Tensor,Tensor> _th_topk(const Tensor & self, int64_t k, int64_t dim, bool largest, bool sorted) const override;
Tensor & _th_abs_out(Tensor & result, const Tensor & self) const override;
Tensor _th_abs(const Tensor & self) const override;
Tensor & _th_sigmoid_out(Tensor & result, const Tensor & self) const override;
Tensor _th_sigmoid(const Tensor & self) const override;
Tensor & _th_log_out(Tensor & result, const Tensor & self) const override;
Tensor _th_log(const Tensor & self) const override;
Tensor & _th_log10_out(Tensor & result, const Tensor & self) const override;
Tensor _th_log10(const Tensor & self) const override;
Tensor & _th_log1p_out(Tensor & result, const Tensor & self) const override;
Tensor _th_log1p(const Tensor & self) const override;
Tensor & _th_log2_out(Tensor & result, const Tensor & self) const override;
Tensor _th_log2(const Tensor & self) const override;
Tensor & _th_lgamma_out(Tensor & result, const Tensor & self) const override;
Tensor _th_lgamma(const Tensor & self) const override;
Tensor & _th_lgamma_(Tensor & self) const override;
Tensor & _th_digamma_out(Tensor & result, const Tensor & self) const override;
Tensor _th_digamma(const Tensor & self) const override;
Tensor & _th_digamma_(Tensor & self) const override;
Tensor & _th_polygamma_out(Tensor & result, int64_t n, const Tensor & self) const override;
Tensor _th_polygamma(int64_t n, const Tensor & self) const override;
Tensor & _th_polygamma_(Tensor & self, int64_t n) const override;
Tensor & _th_exp_out(Tensor & result, const Tensor & self) const override;
Tensor _th_exp(const Tensor & self) const override;
Tensor & _th_expm1_out(Tensor & result, const Tensor & self) const override;
Tensor _th_expm1(const Tensor & self) const override;
Tensor & _th_cos_out(Tensor & result, const Tensor & self) const override;
Tensor _th_cos(const Tensor & self) const override;
Tensor & _th_acos_out(Tensor & result, const Tensor & self) const override;
Tensor _th_acos(const Tensor & self) const override;
Tensor & _th_cosh_out(Tensor & result, const Tensor & self) const override;
Tensor _th_cosh(const Tensor & self) const override;
Tensor & _th_sin_out(Tensor & result, const Tensor & self) const override;
Tensor _th_sin(const Tensor & self) const override;
Tensor & _th_asin_out(Tensor & result, const Tensor & self) const override;
Tensor _th_asin(const Tensor & self) const override;
Tensor & _th_sinh_out(Tensor & result, const Tensor & self) const override;
Tensor _th_sinh(const Tensor & self) const override;
Tensor & _th_tan_out(Tensor & result, const Tensor & self) const override;
Tensor _th_tan(const Tensor & self) const override;
Tensor & _th_atan_out(Tensor & result, const Tensor & self) const override;
Tensor _th_atan(const Tensor & self) const override;
Tensor & _th_tanh_out(Tensor & result, const Tensor & self) const override;
Tensor _th_tanh(const Tensor & self) const override;
Tensor & _th_erf_out(Tensor & result, const Tensor & self) const override;
Tensor _th_erf(const Tensor & self) const override;
Tensor & _th_erfc_out(Tensor & result, const Tensor & self) const override;
Tensor _th_erfc(const Tensor & self) const override;
Tensor & _th_erfinv_(Tensor & self) const override;
Tensor & _th_erfinv_out(Tensor & result, const Tensor & self) const override;
Tensor _th_erfinv(const Tensor & self) const override;
Tensor & _th_sqrt_out(Tensor & result, const Tensor & self) const override;
Tensor _th_sqrt(const Tensor & self) const override;
Tensor & _th_rsqrt_out(Tensor & result, const Tensor & self) const override;
Tensor _th_rsqrt(const Tensor & self) const override;
Tensor & _th_ceil_out(Tensor & result, const Tensor & self) const override;
Tensor _th_ceil(const Tensor & self) const override;
Tensor & _th_floor_out(Tensor & result, const Tensor & self) const override;
Tensor _th_floor(const Tensor & self) const override;
Tensor & _th_round_out(Tensor & result, const Tensor & self) const override;
Tensor _th_round(const Tensor & self) const override;
Tensor & _th_trunc_out(Tensor & result, const Tensor & self) const override;
Tensor _th_trunc(const Tensor & self) const override;
Tensor & _th_frac_(Tensor & self) const override;
Tensor & _th_frac_out(Tensor & result, const Tensor & self) const override;
Tensor _th_frac(const Tensor & self) const override;
Tensor & _th_var_out(Tensor & result, const Tensor & self, int64_t dim, bool unbiased, bool keepdim) const override;
Tensor _th_var(const Tensor & self, int64_t dim, bool unbiased, bool keepdim) const override;
Tensor _th_var(const Tensor & self, bool unbiased) const override;
Tensor & _th_std_out(Tensor & result, const Tensor & self, int64_t dim, bool unbiased, bool keepdim) const override;
Tensor _th_std(const Tensor & self, int64_t dim, bool unbiased, bool keepdim) const override;
Tensor _th_std(const Tensor & self, bool unbiased) const override;
Tensor _th_norm(const Tensor & self, Scalar p) const override;
Tensor & _th_norm_out(Tensor & result, const Tensor & self, Scalar p, int64_t dim, bool keepdim) const override;
Tensor _th_norm(const Tensor & self, Scalar p, int64_t dim, bool keepdim) const override;
Tensor & _th_renorm_out(Tensor & result, const Tensor & self, Scalar p, int64_t dim, Scalar maxnorm) const override;
Tensor _th_renorm(const Tensor & self, Scalar p, int64_t dim, Scalar maxnorm) const override;
Tensor & _th_renorm_(Tensor & self, Scalar p, int64_t dim, Scalar maxnorm) const override;
Tensor s__th_dist(const Tensor & self, const Tensor & other, Scalar p) const override;
Tensor & _th_reciprocal_out(Tensor & result, const Tensor & self) const override;
Tensor _th_reciprocal(const Tensor & self) const override;
Tensor & _th_reciprocal_(Tensor & self) const override;
Tensor & _th_neg_out(Tensor & result, const Tensor & self) const override;
Tensor _th_neg(const Tensor & self) const override;
Tensor & _th_neg_(Tensor & self) const override;
Tensor & s__th_atan2_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_atan2(const Tensor & self, const Tensor & other) const override;
Tensor & s__th_atan2_(Tensor & self, const Tensor & other) const override;
Tensor & _th_pow_out(Tensor & result, const Tensor & self, Scalar exponent) const override;
Tensor _th_pow(const Tensor & self, Scalar exponent) const override;
Tensor & s__th_pow_out(Tensor & result, const Tensor & self, const Tensor & exponent) const override;
Tensor s__th_pow(const Tensor & self, const Tensor & exponent) const override;
Tensor & _th_pow_out(Tensor & result, Scalar self, const Tensor & exponent) const override;
Tensor _th_pow(Scalar self, const Tensor & exponent) const override;
Tensor & _th_pow_(Tensor & self, Scalar exponent) const override;
Tensor & s__th_pow_(Tensor & self, const Tensor & exponent) const override;
Tensor & s__th_lerp_out(Tensor & result, const Tensor & self, const Tensor & end, Scalar weight) const override;
Tensor s__th_lerp(const Tensor & self, const Tensor & end, Scalar weight) const override;
Tensor & s__th_lerp_(Tensor & self, const Tensor & end, Scalar weight) const override;
Tensor & _th_zero_(Tensor & self) const override;
Tensor & _th_cumsum_out(Tensor & result, const Tensor & self, int64_t dim) const override;
Tensor _th_cumsum(const Tensor & self, int64_t dim) const override;
Tensor & _th_cumprod_out(Tensor & result, const Tensor & self, int64_t dim) const override;
Tensor _th_cumprod(const Tensor & self, int64_t dim) const override;
Tensor & _th_sign_out(Tensor & result, const Tensor & self) const override;
Tensor _th_sign(const Tensor & self) const override;
Tensor & _th_sign_(Tensor & self) const override;
Tensor _th_trace(const Tensor & self) const override;
Tensor & _th_fmod_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_fmod(const Tensor & self, Scalar other) const override;
Tensor & s__th_fmod_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_fmod(const Tensor & self, const Tensor & other) const override;
Tensor & _th_fmod_(Tensor & self, Scalar other) const override;
Tensor & s__th_fmod_(Tensor & self, const Tensor & other) const override;
Tensor & _th_remainder_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor _th_remainder(const Tensor & self, Scalar other) const override;
Tensor & s__th_remainder_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor s__th_remainder(const Tensor & self, const Tensor & other) const override;
Tensor & _th_remainder_(Tensor & self, Scalar other) const override;
Tensor & s__th_remainder_(Tensor & self, const Tensor & other) const override;
Tensor & _th_clamp_out(Tensor & result, const Tensor & self, Scalar min, Scalar max) const override;
Tensor _th_clamp(const Tensor & self, Scalar min, Scalar max) const override;
Tensor & _th_clamp_min_out(Tensor & result, const Tensor & self, Scalar min) const override;
Tensor _th_clamp_min(const Tensor & self, Scalar min) const override;
Tensor & _th_clamp_max_out(Tensor & result, const Tensor & self, Scalar max) const override;
Tensor _th_clamp_max(const Tensor & self, Scalar max) const override;
Tensor _th_dot(const Tensor & self, const Tensor & tensor) const override;
Tensor & _th_tril_out(Tensor & result, const Tensor & self, int64_t diagonal) const override;
Tensor _th_tril(const Tensor & self, int64_t diagonal) const override;
Tensor & _th_tril_(Tensor & self, int64_t diagonal) const override;
Tensor & _th_triu_out(Tensor & result, const Tensor & self, int64_t diagonal) const override;
Tensor _th_triu(const Tensor & self, int64_t diagonal) const override;
Tensor & _th_triu_(Tensor & self, int64_t diagonal) const override;
Tensor & _th_cross_out(Tensor & result, const Tensor & self, const Tensor & other, int64_t dim) const override;
Tensor _th_cross(const Tensor & self, const Tensor & other, int64_t dim) const override;
Tensor & _th_diag_out(Tensor & result, const Tensor & self, int64_t diagonal) const override;
Tensor _th_diag(const Tensor & self, int64_t diagonal) const override;
Tensor & s__th_addmm_out(Tensor & result, const Tensor & self, const Tensor & mat1, const Tensor & mat2, Scalar beta, Scalar alpha) const override;
Tensor s__th_addmm(const Tensor & self, const Tensor & mat1, const Tensor & mat2, Scalar beta, Scalar alpha) const override;
Tensor & _th_addmm_(Tensor & self, const Tensor & mat1, const Tensor & mat2, Scalar beta, Scalar alpha) const override;
Tensor & s__th_addmv_out(Tensor & result, const Tensor & self, const Tensor & mat, const Tensor & vec, Scalar beta, Scalar alpha) const override;
Tensor s__th_addmv(const Tensor & self, const Tensor & mat, const Tensor & vec, Scalar beta, Scalar alpha) const override;
Tensor & _th_addmv_(Tensor & self, const Tensor & mat, const Tensor & vec, Scalar beta, Scalar alpha) const override;
Tensor & s__th_addr_out(Tensor & result, const Tensor & self, const Tensor & vec1, const Tensor & vec2, Scalar beta, Scalar alpha) const override;
Tensor s__th_addr(const Tensor & self, const Tensor & vec1, const Tensor & vec2, Scalar beta, Scalar alpha) const override;
Tensor & _th_addr_(Tensor & self, const Tensor & vec1, const Tensor & vec2, Scalar beta, Scalar alpha) const override;
Tensor & _th_ger_out(Tensor & result, const Tensor & self, const Tensor & vec2) const override;
Tensor _th_ger(const Tensor & self, const Tensor & vec2) const override;
Tensor & _th_mv_out(Tensor & result, const Tensor & self, const Tensor & vec) const override;
Tensor _th_mv(const Tensor & self, const Tensor & vec) const override;
Tensor & _th_mm_out(Tensor & result, const Tensor & self, const Tensor & mat2) const override;
Tensor _th_mm(const Tensor & self, const Tensor & mat2) const override;
Tensor & _th_bmm_out(Tensor & result, const Tensor & self, const Tensor & mat2) const override;
Tensor _th_bmm(const Tensor & self, const Tensor & mat2) const override;
Tensor & s__th_addbmm_out(Tensor & result, const Tensor & self, const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) const override;
Tensor s__th_addbmm(const Tensor & self, const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) const override;
Tensor & _th_addbmm_(Tensor & self, const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) const override;
Tensor & s__th_baddbmm_out(Tensor & result, const Tensor & self, const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) const override;
Tensor s__th_baddbmm(const Tensor & self, const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) const override;
Tensor & s__th_addcmul_out(Tensor & result, const Tensor & self, const Tensor & tensor1, const Tensor & tensor2, Scalar value) const override;
Tensor s__th_addcmul(const Tensor & self, const Tensor & tensor1, const Tensor & tensor2, Scalar value) const override;
Tensor & s__th_addcmul_(Tensor & self, const Tensor & tensor1, const Tensor & tensor2, Scalar value) const override;
Tensor & s__th_addcdiv_out(Tensor & result, const Tensor & self, const Tensor & tensor1, const Tensor & tensor2, Scalar value) const override;
Tensor s__th_addcdiv(const Tensor & self, const Tensor & tensor1, const Tensor & tensor2, Scalar value) const override;
Tensor & s__th_addcdiv_(Tensor & self, const Tensor & tensor1, const Tensor & tensor2, Scalar value) const override;
std::tuple<Tensor &,Tensor &> _th_btrifact_out(Tensor & result, Tensor & pivots, const Tensor & self, bool pivot) const override;
std::tuple<Tensor,Tensor> _th_btrifact(const Tensor & self, bool pivot) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _th_btrifact_with_info_out(Tensor & result, Tensor & pivots, Tensor & info, const Tensor & self, bool pivot) const override;
std::tuple<Tensor,Tensor,Tensor> _th_btrifact_with_info(const Tensor & self, bool pivot) const override;
Tensor & _th_btrisolve_out(Tensor & result, const Tensor & self, const Tensor & LU_data, const Tensor & LU_pivots) const override;
Tensor _th_btrisolve(const Tensor & self, const Tensor & LU_data, const Tensor & LU_pivots) const override;
Tensor & _th_random_(Tensor & self, int64_t from, int64_t to, Generator * generator) const override;
Tensor & _th_random_(Tensor & self, int64_t to, Generator * generator) const override;
Tensor & _th_random_(Tensor & self, Generator * generator) const override;
Tensor & _th_multinomial_out(Tensor & result, const Tensor & self, int64_t num_samples, bool replacement, Generator * generator) const override;
Tensor _th_multinomial(const Tensor & self, int64_t num_samples, bool replacement, Generator * generator) const override;
Tensor & _th_uniform_(Tensor & self, double from, double to, Generator * generator) const override;
Tensor & _th_normal_out(Tensor & output, const Tensor & mean, double std, Generator * generator) const override;
Tensor _th_normal(const Tensor & mean, double std, Generator * generator) const override;
Tensor & _th_normal_out(Tensor & output, double mean, const Tensor & std, Generator * generator) const override;
Tensor _th_normal(double mean, const Tensor & std, Generator * generator) const override;
Tensor & _th_normal_out(Tensor & output, const Tensor & mean, const Tensor & std, Generator * generator) const override;
Tensor _th_normal(const Tensor & mean, const Tensor & std, Generator * generator) const override;
Tensor & _th_normal_(Tensor & self, double mean, double std, Generator * generator) const override;
Tensor & _th_cauchy_(Tensor & self, double median, double sigma, Generator * generator) const override;
Tensor & _th_log_normal_(Tensor & self, double mean, double std, Generator * generator) const override;
Tensor & _th_exponential_(Tensor & self, double lambd, Generator * generator) const override;
Tensor & _th_geometric_(Tensor & self, double p, Generator * generator) const override;
Tensor _th_tensor(Storage storage, int64_t storageOffset, IntList size, IntList stride) const override;
Tensor _th_tensor(IntList size, IntList stride) const override;
Tensor _th_alias(const Tensor & self) const override;
Tensor & _th_copy_ignoring_overlaps_(Tensor & self, const Tensor & src) const override;
Tensor & _th_cat_out(Tensor & self, TensorList tensors, int64_t dim) const override;
Tensor _th_cat(TensorList tensors, int64_t dim) const override;
Tensor & _thnn_binary_cross_entropy_forward_out(Tensor & output, const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction) const override;
Tensor _thnn_binary_cross_entropy_forward(const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction) const override;
Tensor & _thnn_binary_cross_entropy_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction) const override;
Tensor _thnn_binary_cross_entropy_backward(const Tensor & grad_output, const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction) const override;
Tensor & _thnn_l1_loss_forward_out(Tensor & output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor _thnn_l1_loss_forward(const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor & _thnn_l1_loss_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor _thnn_l1_loss_backward(const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor & _thnn_mse_loss_forward_out(Tensor & output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor _thnn_mse_loss_forward(const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor & _thnn_mse_loss_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor _thnn_mse_loss_backward(const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor & _thnn_multi_margin_loss_forward_out(Tensor & output, const Tensor & self, const Tensor & target, Scalar p, Scalar margin, const Tensor & weight, int64_t reduction) const override;
Tensor _thnn_multi_margin_loss_forward(const Tensor & self, const Tensor & target, Scalar p, Scalar margin, const Tensor & weight, int64_t reduction) const override;
Tensor & _thnn_multi_margin_loss_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & target, Scalar p, Scalar margin, const Tensor & weight, int64_t reduction) const override;
Tensor _thnn_multi_margin_loss_backward(const Tensor & grad_output, const Tensor & self, const Tensor & target, Scalar p, Scalar margin, const Tensor & weight, int64_t reduction) const override;
std::tuple<Tensor &,Tensor &> _thnn_multilabel_margin_loss_forward_out(Tensor & output, Tensor & is_target, const Tensor & self, const Tensor & target, int64_t reduction) const override;
std::tuple<Tensor,Tensor> _thnn_multilabel_margin_loss_forward(const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor & _thnn_multilabel_margin_loss_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction, const Tensor & is_target) const override;
Tensor _thnn_multilabel_margin_loss_backward(const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction, const Tensor & is_target) const override;
std::tuple<Tensor &,Tensor &> _thnn_nll_loss_forward_out(Tensor & output, Tensor & total_weight, const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction, int64_t ignore_index) const override;
std::tuple<Tensor,Tensor> _thnn_nll_loss_forward(const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction, int64_t ignore_index) const override;
Tensor & _thnn_nll_loss_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction, int64_t ignore_index, const Tensor & total_weight) const override;
Tensor _thnn_nll_loss_backward(const Tensor & grad_output, const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction, int64_t ignore_index, const Tensor & total_weight) const override;
std::tuple<Tensor &,Tensor &> _thnn_nll_loss2d_forward_out(Tensor & output, Tensor & total_weight, const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction, int64_t ignore_index) const override;
std::tuple<Tensor,Tensor> _thnn_nll_loss2d_forward(const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction, int64_t ignore_index) const override;
Tensor & _thnn_nll_loss2d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction, int64_t ignore_index, const Tensor & total_weight) const override;
Tensor _thnn_nll_loss2d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & target, const Tensor & weight, int64_t reduction, int64_t ignore_index, const Tensor & total_weight) const override;
Tensor & _thnn_smooth_l1_loss_forward_out(Tensor & output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor _thnn_smooth_l1_loss_forward(const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor & _thnn_smooth_l1_loss_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor _thnn_smooth_l1_loss_backward(const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor & _thnn_soft_margin_loss_forward_out(Tensor & output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor _thnn_soft_margin_loss_forward(const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor & _thnn_soft_margin_loss_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor _thnn_soft_margin_loss_backward(const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor & _thnn_elu_forward_out(Tensor & output, const Tensor & self, Scalar alpha, Scalar scale, Scalar input_scale) const override;
Tensor _thnn_elu_forward(const Tensor & self, Scalar alpha, Scalar scale, Scalar input_scale) const override;
Tensor & _thnn_elu_backward_out(Tensor & grad_input, const Tensor & grad_output, Scalar alpha, Scalar scale, Scalar input_scale, const Tensor & output) const override;
Tensor _thnn_elu_backward(const Tensor & grad_output, Scalar alpha, Scalar scale, Scalar input_scale, const Tensor & output) const override;
Tensor & _thnn_elu_forward_(Tensor & self, Scalar alpha, Scalar scale, Scalar input_scale) const override;
Tensor & _thnn_glu_forward_out(Tensor & output, const Tensor & self, int64_t dim) const override;
Tensor _thnn_glu_forward(const Tensor & self, int64_t dim) const override;
Tensor & _thnn_glu_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, int64_t dim) const override;
Tensor _thnn_glu_backward(const Tensor & grad_output, const Tensor & self, int64_t dim) const override;
Tensor & _thnn_hardtanh_forward_out(Tensor & output, const Tensor & self, Scalar min_val, Scalar max_val) const override;
Tensor _thnn_hardtanh_forward(const Tensor & self, Scalar min_val, Scalar max_val) const override;
Tensor & _thnn_hardtanh_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, Scalar min_val, Scalar max_val) const override;
Tensor _thnn_hardtanh_backward(const Tensor & grad_output, const Tensor & self, Scalar min_val, Scalar max_val) const override;
Tensor & _thnn_hardtanh_forward_(Tensor & self, Scalar min_val, Scalar max_val) const override;
Tensor & _thnn_leaky_relu_forward_out(Tensor & output, const Tensor & self, Scalar negative_slope) const override;
Tensor _thnn_leaky_relu_forward(const Tensor & self, Scalar negative_slope) const override;
Tensor & _thnn_leaky_relu_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, Scalar negative_slope) const override;
Tensor _thnn_leaky_relu_backward(const Tensor & grad_output, const Tensor & self, Scalar negative_slope) const override;
Tensor & _thnn_leaky_relu_forward_(Tensor & self, Scalar negative_slope) const override;
std::tuple<Tensor &,Tensor &> _thnn_log_sigmoid_forward_out(Tensor & output, Tensor & buffer, const Tensor & self) const override;
std::tuple<Tensor,Tensor> _thnn_log_sigmoid_forward(const Tensor & self) const override;
Tensor & _thnn_log_sigmoid_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & buffer) const override;
Tensor _thnn_log_sigmoid_backward(const Tensor & grad_output, const Tensor & self, const Tensor & buffer) const override;
Tensor & _thnn_rrelu_with_noise_forward_out(Tensor & output, const Tensor & self, const Tensor & noise, Scalar lower, Scalar upper, bool training, Generator * generator) const override;
Tensor _thnn_rrelu_with_noise_forward(const Tensor & self, const Tensor & noise, Scalar lower, Scalar upper, bool training, Generator * generator) const override;
Tensor & _thnn_rrelu_with_noise_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & noise, Scalar lower, Scalar upper, bool training) const override;
Tensor _thnn_rrelu_with_noise_backward(const Tensor & grad_output, const Tensor & self, const Tensor & noise, Scalar lower, Scalar upper, bool training) const override;
Tensor & _thnn_rrelu_with_noise_forward_(Tensor & self, const Tensor & noise, Scalar lower, Scalar upper, bool training, Generator * generator) const override;
Tensor & _thnn_softplus_forward_out(Tensor & output, const Tensor & self, Scalar beta, Scalar threshold) const override;
Tensor _thnn_softplus_forward(const Tensor & self, Scalar beta, Scalar threshold) const override;
Tensor & _thnn_softplus_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, Scalar beta, Scalar threshold, const Tensor & output) const override;
Tensor _thnn_softplus_backward(const Tensor & grad_output, const Tensor & self, Scalar beta, Scalar threshold, const Tensor & output) const override;
Tensor & _thnn_softshrink_forward_out(Tensor & output, const Tensor & self, Scalar lambd) const override;
Tensor _thnn_softshrink_forward(const Tensor & self, Scalar lambd) const override;
Tensor & _thnn_softshrink_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, Scalar lambd) const override;
Tensor _thnn_softshrink_backward(const Tensor & grad_output, const Tensor & self, Scalar lambd) const override;
Tensor & _thnn_adaptive_avg_pool2d_forward_out(Tensor & output, const Tensor & self, IntList output_size) const override;
Tensor _thnn_adaptive_avg_pool2d_forward(const Tensor & self, IntList output_size) const override;
Tensor & _thnn_adaptive_avg_pool2d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self) const override;
Tensor _thnn_adaptive_avg_pool2d_backward(const Tensor & grad_output, const Tensor & self) const override;
Tensor & _thnn_adaptive_avg_pool3d_forward_out(Tensor & output, const Tensor & self, IntList output_size) const override;
Tensor _thnn_adaptive_avg_pool3d_forward(const Tensor & self, IntList output_size) const override;
Tensor & _thnn_adaptive_avg_pool3d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self) const override;
Tensor _thnn_adaptive_avg_pool3d_backward(const Tensor & grad_output, const Tensor & self) const override;
std::tuple<Tensor &,Tensor &> _thnn_adaptive_max_pool2d_forward_out(Tensor & output, Tensor & indices, const Tensor & self, IntList output_size) const override;
std::tuple<Tensor,Tensor> _thnn_adaptive_max_pool2d_forward(const Tensor & self, IntList output_size) const override;
Tensor & _thnn_adaptive_max_pool2d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & indices) const override;
Tensor _thnn_adaptive_max_pool2d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & indices) const override;
std::tuple<Tensor &,Tensor &> _thnn_adaptive_max_pool3d_forward_out(Tensor & output, Tensor & indices, const Tensor & self, IntList output_size) const override;
std::tuple<Tensor,Tensor> _thnn_adaptive_max_pool3d_forward(const Tensor & self, IntList output_size) const override;
Tensor & _thnn_adaptive_max_pool3d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & indices) const override;
Tensor _thnn_adaptive_max_pool3d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & indices) const override;
Tensor & _thnn_avg_pool2d_forward_out(Tensor & output, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, bool ceil_mode, bool count_include_pad) const override;
Tensor _thnn_avg_pool2d_forward(const Tensor & self, IntList kernel_size, IntList stride, IntList padding, bool ceil_mode, bool count_include_pad) const override;
Tensor & _thnn_avg_pool2d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, bool ceil_mode, bool count_include_pad) const override;
Tensor _thnn_avg_pool2d_backward(const Tensor & grad_output, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, bool ceil_mode, bool count_include_pad) const override;
Tensor & _thnn_avg_pool3d_forward_out(Tensor & output, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, bool ceil_mode, bool count_include_pad) const override;
Tensor _thnn_avg_pool3d_forward(const Tensor & self, IntList kernel_size, IntList stride, IntList padding, bool ceil_mode, bool count_include_pad) const override;
Tensor & _thnn_avg_pool3d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, bool ceil_mode, bool count_include_pad) const override;
Tensor _thnn_avg_pool3d_backward(const Tensor & grad_output, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, bool ceil_mode, bool count_include_pad) const override;
std::tuple<Tensor &,Tensor &> _thnn_fractional_max_pool2d_forward_out(Tensor & output, Tensor & indices, const Tensor & self, IntList kernel_size, IntList output_size, const Tensor & random_samples) const override;
std::tuple<Tensor,Tensor> _thnn_fractional_max_pool2d_forward(const Tensor & self, IntList kernel_size, IntList output_size, const Tensor & random_samples) const override;
Tensor & _thnn_fractional_max_pool2d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, IntList kernel_size, IntList output_size, const Tensor & indices) const override;
Tensor _thnn_fractional_max_pool2d_backward(const Tensor & grad_output, const Tensor & self, IntList kernel_size, IntList output_size, const Tensor & indices) const override;
std::tuple<Tensor &,Tensor &> _thnn_max_pool2d_with_indices_forward_out(Tensor & output, Tensor & indices, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, IntList dilation, bool ceil_mode) const override;
std::tuple<Tensor,Tensor> _thnn_max_pool2d_with_indices_forward(const Tensor & self, IntList kernel_size, IntList stride, IntList padding, IntList dilation, bool ceil_mode) const override;
Tensor & _thnn_max_pool2d_with_indices_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, IntList dilation, bool ceil_mode, const Tensor & indices) const override;
Tensor _thnn_max_pool2d_with_indices_backward(const Tensor & grad_output, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, IntList dilation, bool ceil_mode, const Tensor & indices) const override;
std::tuple<Tensor &,Tensor &> _thnn_max_pool3d_with_indices_forward_out(Tensor & output, Tensor & indices, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, IntList dilation, bool ceil_mode) const override;
std::tuple<Tensor,Tensor> _thnn_max_pool3d_with_indices_forward(const Tensor & self, IntList kernel_size, IntList stride, IntList padding, IntList dilation, bool ceil_mode) const override;
Tensor & _thnn_max_pool3d_with_indices_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, IntList dilation, bool ceil_mode, const Tensor & indices) const override;
Tensor _thnn_max_pool3d_with_indices_backward(const Tensor & grad_output, const Tensor & self, IntList kernel_size, IntList stride, IntList padding, IntList dilation, bool ceil_mode, const Tensor & indices) const override;
Tensor & _thnn_max_unpool2d_forward_out(Tensor & output, const Tensor & self, const Tensor & indices, IntList output_size) const override;
Tensor _thnn_max_unpool2d_forward(const Tensor & self, const Tensor & indices, IntList output_size) const override;
Tensor & _thnn_max_unpool2d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & indices, IntList output_size) const override;
Tensor _thnn_max_unpool2d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & indices, IntList output_size) const override;
Tensor & _thnn_max_unpool3d_forward_out(Tensor & output, const Tensor & self, const Tensor & indices, IntList output_size, IntList stride, IntList padding) const override;
Tensor _thnn_max_unpool3d_forward(const Tensor & self, const Tensor & indices, IntList output_size, IntList stride, IntList padding) const override;
Tensor & _thnn_max_unpool3d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, const Tensor & indices, IntList output_size, IntList stride, IntList padding) const override;
Tensor _thnn_max_unpool3d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & indices, IntList output_size, IntList stride, IntList padding) const override;
Tensor & _thnn_reflection_pad1d_forward_out(Tensor & output, const Tensor & self, IntList padding) const override;
Tensor _thnn_reflection_pad1d_forward(const Tensor & self, IntList padding) const override;
Tensor & _thnn_reflection_pad1d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, IntList padding) const override;
Tensor _thnn_reflection_pad1d_backward(const Tensor & grad_output, const Tensor & self, IntList padding) const override;
Tensor & _thnn_reflection_pad2d_forward_out(Tensor & output, const Tensor & self, IntList padding) const override;
Tensor _thnn_reflection_pad2d_forward(const Tensor & self, IntList padding) const override;
Tensor & _thnn_reflection_pad2d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, IntList padding) const override;
Tensor _thnn_reflection_pad2d_backward(const Tensor & grad_output, const Tensor & self, IntList padding) const override;
Tensor & _thnn_replication_pad1d_forward_out(Tensor & output, const Tensor & self, IntList padding) const override;
Tensor _thnn_replication_pad1d_forward(const Tensor & self, IntList padding) const override;
Tensor & _thnn_replication_pad1d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, IntList padding) const override;
Tensor _thnn_replication_pad1d_backward(const Tensor & grad_output, const Tensor & self, IntList padding) const override;
Tensor & _thnn_replication_pad2d_forward_out(Tensor & output, const Tensor & self, IntList padding) const override;
Tensor _thnn_replication_pad2d_forward(const Tensor & self, IntList padding) const override;
Tensor & _thnn_replication_pad2d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, IntList padding) const override;
Tensor _thnn_replication_pad2d_backward(const Tensor & grad_output, const Tensor & self, IntList padding) const override;
Tensor & _thnn_replication_pad3d_forward_out(Tensor & output, const Tensor & self, IntList padding) const override;
Tensor _thnn_replication_pad3d_forward(const Tensor & self, IntList padding) const override;
Tensor & _thnn_replication_pad3d_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & self, IntList padding) const override;
Tensor _thnn_replication_pad3d_backward(const Tensor & grad_output, const Tensor & self, IntList padding) const override;
Tensor & _thnn_upsample_linear1d_forward_out(Tensor & output, const Tensor & self, IntList output_size, bool align_corners) const override;
Tensor _thnn_upsample_linear1d_forward(const Tensor & self, IntList output_size, bool align_corners) const override;
Tensor & _thnn_upsample_linear1d_backward_out(Tensor & grad_input, const Tensor & grad_output, IntList output_size, IntList input_size, bool align_corners) const override;
Tensor _thnn_upsample_linear1d_backward(const Tensor & grad_output, IntList output_size, IntList input_size, bool align_corners) const override;
Tensor & _thnn_upsample_bilinear2d_forward_out(Tensor & output, const Tensor & self, IntList output_size, bool align_corners) const override;
Tensor _thnn_upsample_bilinear2d_forward(const Tensor & self, IntList output_size, bool align_corners) const override;
Tensor & _thnn_upsample_bilinear2d_backward_out(Tensor & grad_input, const Tensor & grad_output, IntList output_size, IntList input_size, bool align_corners) const override;
Tensor _thnn_upsample_bilinear2d_backward(const Tensor & grad_output, IntList output_size, IntList input_size, bool align_corners) const override;
Tensor & _thnn_upsample_trilinear3d_forward_out(Tensor & output, const Tensor & self, IntList output_size, bool align_corners) const override;
Tensor _thnn_upsample_trilinear3d_forward(const Tensor & self, IntList output_size, bool align_corners) const override;
Tensor & _thnn_upsample_trilinear3d_backward_out(Tensor & grad_input, const Tensor & grad_output, IntList output_size, IntList input_size, bool align_corners) const override;
Tensor _thnn_upsample_trilinear3d_backward(const Tensor & grad_output, IntList output_size, IntList input_size, bool align_corners) const override;
Tensor & _thnn_upsample_nearest1d_forward_out(Tensor & output, const Tensor & self, IntList output_size) const override;
Tensor _thnn_upsample_nearest1d_forward(const Tensor & self, IntList output_size) const override;
Tensor & _thnn_upsample_nearest1d_backward_out(Tensor & grad_input, const Tensor & grad_output, IntList output_size, IntList input_size) const override;
Tensor _thnn_upsample_nearest1d_backward(const Tensor & grad_output, IntList output_size, IntList input_size) const override;
Tensor & _thnn_upsample_nearest2d_forward_out(Tensor & output, const Tensor & self, IntList output_size) const override;
Tensor _thnn_upsample_nearest2d_forward(const Tensor & self, IntList output_size) const override;
Tensor & _thnn_upsample_nearest2d_backward_out(Tensor & grad_input, const Tensor & grad_output, IntList output_size, IntList input_size) const override;
Tensor _thnn_upsample_nearest2d_backward(const Tensor & grad_output, IntList output_size, IntList input_size) const override;
Tensor & _thnn_upsample_nearest3d_forward_out(Tensor & output, const Tensor & self, IntList output_size) const override;
Tensor _thnn_upsample_nearest3d_forward(const Tensor & self, IntList output_size) const override;
Tensor & _thnn_upsample_nearest3d_backward_out(Tensor & grad_input, const Tensor & grad_output, IntList output_size, IntList input_size) const override;
Tensor _thnn_upsample_nearest3d_backward(const Tensor & grad_output, IntList output_size, IntList input_size) const override;
Tensor & _thnn_sigmoid_forward_out(Tensor & output, const Tensor & self) const override;
Tensor _thnn_sigmoid_forward(const Tensor & self) const override;
Tensor & _thnn_sigmoid_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & output) const override;
Tensor _thnn_sigmoid_backward(const Tensor & grad_output, const Tensor & output) const override;
Tensor & _thnn_tanh_forward_out(Tensor & output, const Tensor & self) const override;
Tensor _thnn_tanh_forward(const Tensor & self) const override;
Tensor & _thnn_tanh_backward_out(Tensor & grad_input, const Tensor & grad_output, const Tensor & output) const override;
Tensor _thnn_tanh_backward(const Tensor & grad_output, const Tensor & output) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _thnn_conv_transpose2d_forward_out(Tensor & output, Tensor & columns, Tensor & ones, const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding, IntList output_padding, IntList dilation) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_conv_transpose2d_forward(const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding, IntList output_padding, IntList dilation) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _thnn_conv_transpose2d_backward_out(Tensor & grad_input, Tensor & grad_weight, Tensor & grad_bias, const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, IntList output_padding, IntList dilation, const Tensor & columns, const Tensor & ones) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_conv_transpose2d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, IntList output_padding, IntList dilation, const Tensor & columns, const Tensor & ones, std::array<bool,3> output_mask) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _thnn_conv_transpose3d_forward_out(Tensor & output, Tensor & finput, Tensor & fgrad_input, const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding, IntList output_padding, IntList dilation) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_conv_transpose3d_forward(const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding, IntList output_padding, IntList dilation) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _thnn_conv_transpose3d_backward_out(Tensor & grad_input, Tensor & grad_weight, Tensor & grad_bias, const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, IntList output_padding, IntList dilation, const Tensor & finput, const Tensor & fgrad_input) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_conv_transpose3d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, IntList output_padding, IntList dilation, const Tensor & finput, const Tensor & fgrad_input, std::array<bool,3> output_mask) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _thnn_conv2d_forward_out(Tensor & output, Tensor & finput, Tensor & fgrad_input, const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_conv2d_forward(const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _thnn_conv2d_backward_out(Tensor & grad_input, Tensor & grad_weight, Tensor & grad_bias, const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, const Tensor & finput, const Tensor & fgrad_input) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_conv2d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, const Tensor & finput, const Tensor & fgrad_input, std::array<bool,3> output_mask) const override;
Tensor & _thnn_conv_depthwise2d_forward_out(Tensor & output, const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding, IntList dilation) const override;
Tensor _thnn_conv_depthwise2d_forward(const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding, IntList dilation) const override;
std::tuple<Tensor &,Tensor &> _thnn_conv_depthwise2d_backward_out(Tensor & grad_input, Tensor & grad_weight, const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, IntList dilation) const override;
std::tuple<Tensor,Tensor> _thnn_conv_depthwise2d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, IntList dilation, std::array<bool,2> output_mask) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _thnn_conv_dilated2d_forward_out(Tensor & output, Tensor & columns, Tensor & ones, const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding, IntList dilation) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_conv_dilated2d_forward(const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding, IntList dilation) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _thnn_conv_dilated2d_backward_out(Tensor & grad_input, Tensor & grad_weight, Tensor & grad_bias, const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, IntList dilation, const Tensor & columns, const Tensor & ones) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_conv_dilated2d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, IntList dilation, const Tensor & columns, const Tensor & ones, std::array<bool,3> output_mask) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _thnn_conv_dilated3d_forward_out(Tensor & output, Tensor & columns, Tensor & ones, const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding, IntList dilation) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_conv_dilated3d_forward(const Tensor & self, const Tensor & weight, IntList kernel_size, const Tensor & bias, IntList stride, IntList padding, IntList dilation) const override;
std::tuple<Tensor &,Tensor &,Tensor &> _thnn_conv_dilated3d_backward_out(Tensor & grad_input, Tensor & grad_weight, Tensor & grad_bias, const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, IntList dilation, const Tensor & columns, const Tensor & ones) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_conv_dilated3d_backward(const Tensor & grad_output, const Tensor & self, const Tensor & weight, IntList kernel_size, IntList stride, IntList padding, IntList dilation, const Tensor & columns, const Tensor & ones, std::array<bool,3> output_mask) const override;
std::tuple<Tensor,Tensor> _cudnn_ctc_loss(const Tensor & log_probs, const Tensor & targets, IntList input_lengths, IntList target_lengths, int64_t blank, bool deterministic) const override;
Tensor _cudnn_rnn_flatten_weight(TensorList weight_arr, int64_t weight_stride0, int64_t input_size, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, bool bidirectional) const override;
std::tuple<Tensor,Tensor,Tensor,Tensor,Tensor> _cudnn_rnn(const Tensor & input, TensorList weight, int64_t weight_stride0, const Tensor & weight_buf, const Tensor & hx, const Tensor & cx, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, IntList batch_sizes, const Tensor & dropout_state) const override;
std::tuple<Tensor,Tensor,Tensor,std::vector<Tensor>> _cudnn_rnn_backward(const Tensor & input, TensorList weight, int64_t weight_stride0, const Tensor & weight_buf, const Tensor & hx, const Tensor & cx, const Tensor & output, const Tensor & grad_output, const Tensor & grad_hy, const Tensor & grad_cy, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, IntList batch_sizes, const Tensor & dropout_state, const Tensor & reserve, std::array<bool,4> output_mask) const override;
Tensor _cudnn_init_dropout_state(double dropout, bool train, int64_t dropout_seed, const TensorOptions & options) const override;
std::tuple<Tensor,Tensor> _fused_dropout(const Tensor & self, double p, Generator * generator) const override;
Tensor _masked_scale(const Tensor & self, const Tensor & mask, double scale) const override;
Tensor & abs_(Tensor & self) const override;
Tensor & abs_out(Tensor & result, const Tensor & self) const override;
Tensor & acos_(Tensor & self) const override;
Tensor & acos_out(Tensor & result, const Tensor & self) const override;
Tensor & asin_(Tensor & self) const override;
Tensor & asin_out(Tensor & result, const Tensor & self) const override;
Tensor & atan_(Tensor & self) const override;
Tensor & atan_out(Tensor & result, const Tensor & self) const override;
Tensor baddbmm(const Tensor & self, const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) const override;
Tensor & baddbmm_(Tensor & self, const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) const override;
Tensor & baddbmm_out(Tensor & result, const Tensor & self, const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) const override;
Tensor & bernoulli_(Tensor & self, const Tensor & p, Generator * generator) const override;
Tensor & bernoulli_(Tensor & self, double p, Generator * generator) const override;
Tensor bincount(const Tensor & self, const Tensor & weights, int64_t minlength) const override;
Tensor bmm(const Tensor & self, const Tensor & mat2) const override;
Tensor & bmm_out(Tensor & result, const Tensor & self, const Tensor & mat2) const override;
Tensor & ceil_(Tensor & self) const override;
Tensor & ceil_out(Tensor & result, const Tensor & self) const override;
Tensor & clamp_(Tensor & self, c10::optional<Scalar> min, c10::optional<Scalar> max) const override;
Tensor & clamp_out(Tensor & result, const Tensor & self, c10::optional<Scalar> min, c10::optional<Scalar> max) const override;
Tensor & clamp_max_(Tensor & self, Scalar max) const override;
Tensor & clamp_max_out(Tensor & result, const Tensor & self, Scalar max) const override;
Tensor & clamp_min_(Tensor & self, Scalar min) const override;
Tensor & clamp_min_out(Tensor & result, const Tensor & self, Scalar min) const override;
Tensor & s_copy_(Tensor & self, const Tensor & src, bool non_blocking) const override;
Tensor _s_copy_from(const Tensor & self, const Tensor & dst, bool non_blocking) const override;
void _copy_same_type_(Tensor & self, const Tensor & src) const override;
Tensor & cos_(Tensor & self) const override;
Tensor & cos_out(Tensor & result, const Tensor & self) const override;
Tensor & cosh_(Tensor & self) const override;
Tensor & cosh_out(Tensor & result, const Tensor & self) const override;
Tensor cudnn_affine_grid_generator(const Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W) const override;
Tensor cudnn_affine_grid_generator_backward(const Tensor & grad, int64_t N, int64_t C, int64_t H, int64_t W) const override;
std::tuple<Tensor,Tensor,Tensor> cudnn_batch_norm(const Tensor & input, const Tensor & weight, const Tensor & bias, const Tensor & running_mean, const Tensor & running_var, bool training, double exponential_average_factor, double epsilon) const override;
std::tuple<Tensor,Tensor,Tensor> cudnn_batch_norm_backward(const Tensor & input, const Tensor & grad_output, const Tensor & weight, const Tensor & running_mean, const Tensor & running_var, const Tensor & save_mean, const Tensor & save_var, double epsilon) const override;
Tensor cudnn_convolution(const Tensor & self, const Tensor & weight, const Tensor & bias, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
Tensor cudnn_convolution_backward_input(IntList self_size, const Tensor & grad_output, const Tensor & weight, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
std::tuple<Tensor,Tensor,Tensor> cudnn_convolution_backward(const Tensor & self, const Tensor & grad_output, const Tensor & weight, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic, std::array<bool,3> output_mask) const override;
Tensor cudnn_convolution_backward_bias(const Tensor & grad_output) const override;
Tensor cudnn_convolution_backward_weight(IntList weight_size, const Tensor & grad_output, const Tensor & self, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
Tensor cudnn_convolution_transpose(const Tensor & self, const Tensor & weight, const Tensor & bias, IntList padding, IntList output_padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
std::tuple<Tensor,Tensor,Tensor> cudnn_convolution_transpose_backward(const Tensor & self, const Tensor & grad_output, const Tensor & weight, IntList padding, IntList output_padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic, std::array<bool,3> output_mask) const override;
Tensor cudnn_convolution_transpose_backward_bias(const Tensor & grad_output) const override;
Tensor cudnn_convolution_transpose_backward_input(const Tensor & grad_output, const Tensor & weight, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
Tensor cudnn_convolution_transpose_backward_weight(IntList weight_size, const Tensor & grad_output, const Tensor & self, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
Tensor cudnn_grid_sampler(const Tensor & self, const Tensor & grid) const override;
std::tuple<Tensor,Tensor> cudnn_grid_sampler_backward(const Tensor & self, const Tensor & grid, const Tensor & grad_output) const override;
std::tuple<Tensor,Tensor> _ctc_loss(const Tensor & log_probs, const Tensor & targets, IntList input_lengths, IntList target_lengths, int64_t blank) const override;
Tensor _ctc_loss_backward(const Tensor & grad, const Tensor & log_probs, const Tensor & targets, IntList input_lengths, IntList target_lengths, const Tensor & neg_log_likelihood, const Tensor & log_alpha, int64_t blank) const override;
Tensor embedding_dense_backward(const Tensor & grad, const Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq) const override;
Tensor & embedding_renorm_(Tensor & self, const Tensor & indices, double max_norm, double norm_type) const override;
std::tuple<Tensor,Tensor,Tensor,Tensor> _embedding_bag(const Tensor & weight, const Tensor & indices, const Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse) const override;
Tensor _embedding_bag_dense_backward(const Tensor & grad, const Tensor & indices, const Tensor & offsets, const Tensor & offset2bag, const Tensor & bag_size, const Tensor & maximum_indices, int64_t num_weights, bool scale_grad_by_freq, int64_t mode) const override;
Tensor empty(IntList size, const TensorOptions & options) const override;
Tensor & resize_(Tensor & self, IntList size) const override;
Tensor & erf_(Tensor & self) const override;
Tensor & erf_out(Tensor & result, const Tensor & self) const override;
Tensor & erfc_(Tensor & self) const override;
Tensor & erfc_out(Tensor & result, const Tensor & self) const override;
Tensor & exp_(Tensor & self) const override;
Tensor & exp_out(Tensor & result, const Tensor & self) const override;
Tensor & expm1_(Tensor & self) const override;
Tensor & expm1_out(Tensor & result, const Tensor & self) const override;
Tensor & eye_out(Tensor & result, int64_t n) const override;
Tensor & eye_out(Tensor & result, int64_t n, int64_t m) const override;
Tensor & floor_(Tensor & self) const override;
Tensor & floor_out(Tensor & result, const Tensor & self) const override;
Tensor grid_sampler_2d(const Tensor & input, const Tensor & grid, int64_t interpolation_mode, int64_t padding_mode) const override;
std::tuple<Tensor,Tensor> grid_sampler_2d_backward(const Tensor & grad_output, const Tensor & input, const Tensor & grid, int64_t interpolation_mode, int64_t padding_mode) const override;
Tensor grid_sampler_3d(const Tensor & input, const Tensor & grid, int64_t interpolation_mode, int64_t padding_mode) const override;
std::tuple<Tensor,Tensor> grid_sampler_3d_backward(const Tensor & grad_output, const Tensor & input, const Tensor & grid, int64_t interpolation_mode, int64_t padding_mode) const override;
std::tuple<Tensor,Tensor> _gesv_helper(const Tensor & self, const Tensor & A) const override;
Tensor _fft_with_size(const Tensor & self, int64_t signal_ndim, bool complex_input, bool complex_output, bool inverse, IntList checked_signal_sizes, bool normalized, bool onesided, IntList output_sizes) const override;
Tensor _inverse_helper(const Tensor & self) const override;
Tensor kl_div_backward(const Tensor & grad_output, const Tensor & self, const Tensor & target, int64_t reduction) const override;
Tensor & log_(Tensor & self) const override;
Tensor & log_out(Tensor & result, const Tensor & self) const override;
Tensor & log10_(Tensor & self) const override;
Tensor & log10_out(Tensor & result, const Tensor & self) const override;
Tensor & log1p_(Tensor & self) const override;
Tensor & log1p_out(Tensor & result, const Tensor & self) const override;
Tensor & log2_(Tensor & self) const override;
Tensor & log2_out(Tensor & result, const Tensor & self) const override;
Tensor _log_softmax(const Tensor & self, int64_t dim, bool half_to_float) const override;
Tensor _log_softmax_backward_data(const Tensor & grad_output, const Tensor & output, int64_t dim, const Tensor & self) const override;
std::tuple<Tensor,Tensor,Tensor> miopen_batch_norm(const Tensor & input, const Tensor & weight, const Tensor & bias, const Tensor & running_mean, const Tensor & running_var, bool training, double exponential_average_factor, double epsilon) const override;
std::tuple<Tensor,Tensor,Tensor> miopen_batch_norm_backward(const Tensor & input, const Tensor & grad_output, const Tensor & weight, const Tensor & running_mean, const Tensor & running_var, const Tensor & save_mean, const Tensor & save_var, double epsilon) const override;
Tensor miopen_convolution(const Tensor & self, const Tensor & weight, const Tensor & bias, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
Tensor miopen_convolution_backward_input(IntList self_size, const Tensor & grad_output, const Tensor & weight, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
std::tuple<Tensor,Tensor,Tensor> miopen_convolution_backward(const Tensor & self, const Tensor & grad_output, const Tensor & weight, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic, std::array<bool,3> output_mask) const override;
Tensor miopen_convolution_backward_bias(const Tensor & grad_output) const override;
Tensor miopen_convolution_backward_weight(IntList weight_size, const Tensor & grad_output, const Tensor & self, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
Tensor miopen_convolution_transpose(const Tensor & self, const Tensor & weight, const Tensor & bias, IntList padding, IntList output_padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
std::tuple<Tensor,Tensor,Tensor> miopen_convolution_transpose_backward(const Tensor & self, const Tensor & grad_output, const Tensor & weight, IntList padding, IntList output_padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic, std::array<bool,3> output_mask) const override;
Tensor miopen_convolution_transpose_backward_input(const Tensor & grad_output, const Tensor & weight, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
Tensor miopen_convolution_transpose_backward_weight(IntList weight_size, const Tensor & grad_output, const Tensor & self, IntList padding, IntList stride, IntList dilation, int64_t groups, bool benchmark, bool deterministic) const override;
Tensor narrow_copy(const Tensor & self, int64_t dim, int64_t start, int64_t length) const override;
std::tuple<Tensor,Tensor,Tensor> native_batch_norm(const Tensor & input, const Tensor & weight, const Tensor & bias, const Tensor & running_mean, const Tensor & running_var, bool training, double momentum, double eps) const override;
std::tuple<Tensor,Tensor,Tensor> native_batch_norm_backward(const Tensor & grad_out, const Tensor & input, const Tensor & weight, const Tensor & running_mean, const Tensor & running_var, const Tensor & save_mean, const Tensor & save_invstd, bool train, double eps, std::array<bool,3> output_mask) const override;
Tensor & randperm_out(Tensor & result, int64_t n, Generator * generator) const override;
std::tuple<Tensor,Tensor> RoiPooling2d_forward(const Tensor & input, const Tensor & rois, int64_t pooledHeight, int64_t pooledWidth, double spatialScale) const override;
Tensor RoiPooling2d_backward(const Tensor & input, const Tensor & rois, int64_t pooledHeight, int64_t pooledWidth, double spatialScale, const Tensor & gradOutput, const Tensor & argmaxes) const override;
Tensor & round_(Tensor & self) const override;
Tensor & round_out(Tensor & result, const Tensor & self) const override;
Tensor prelu(const Tensor & self, const Tensor & weight) const override;
std::tuple<Tensor,Tensor> prelu_backward(const Tensor & grad_output, const Tensor & self, const Tensor & weight) const override;
Tensor hardshrink(const Tensor & self, Scalar lambd) const override;
Tensor hardshrink_backward(const Tensor & grad_out, const Tensor & self, Scalar lambd) const override;
Tensor & rsqrt_(Tensor & self) const override;
Tensor & rsqrt_out(Tensor & result, const Tensor & self) const override;
Tensor & sigmoid_(Tensor & self) const override;
Tensor & sigmoid_out(Tensor & result, const Tensor & self) const override;
Tensor & sin_(Tensor & self) const override;
Tensor & sin_out(Tensor & result, const Tensor & self) const override;
Tensor & sinh_(Tensor & self) const override;
Tensor & sinh_out(Tensor & result, const Tensor & self) const override;
Tensor _softmax(const Tensor & self, int64_t dim, bool half_to_float) const override;
Tensor _softmax_backward_data(const Tensor & grad_output, const Tensor & output, int64_t dim, const Tensor & self) const override;
Tensor & _sparse_add_out(Tensor & result, const Tensor & self, const Tensor & other, Scalar alpha) const override;
Tensor & _sparse_dense_add_out(Tensor & result, const Tensor & self, SparseTensorRef other, Scalar alpha) const override;
Tensor & _sparse_div_zerodim_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor & _sparse_div_scalar_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor & _sparse_mul_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor & _sparse_mul_zerodim_out(Tensor & result, const Tensor & self, const Tensor & other) const override;
Tensor & _sparse_mul_scalar_out(Tensor & result, const Tensor & self, Scalar other) const override;
Tensor & sspaddmm_out(Tensor & result, const Tensor & self, const Tensor & mat1, const Tensor & mat2, Scalar beta, Scalar alpha) const override;
Tensor & sqrt_(Tensor & self) const override;
Tensor & sqrt_out(Tensor & result, const Tensor & self) const override;
Tensor & tan_(Tensor & self) const override;
Tensor & tan_out(Tensor & result, const Tensor & self) const override;
Tensor & tanh_(Tensor & self) const override;
Tensor & tanh_out(Tensor & result, const Tensor & self) const override;
Tensor flip(const Tensor & self, IntList dims) const override;
Tensor roll(const Tensor & self, IntList shifts, IntList dims) const override;
Tensor & trunc_(Tensor & self) const override;
Tensor & trunc_out(Tensor & result, const Tensor & self) const override;
std::tuple<Tensor,Tensor> _unique(const Tensor & self, bool sorted, bool return_inverse) const override;
std::tuple<Tensor,Tensor> _unique_dim(const Tensor & self, int64_t dim, bool sorted, bool return_inverse) const override;
Tensor _s_where(const Tensor & condition, const Tensor & self, const Tensor & other) const override;
std::tuple<Tensor,Tensor> _weight_norm_cuda_interface(const Tensor & v, const Tensor & g, int64_t dim) const override;
std::tuple<Tensor,Tensor> _weight_norm_cuda_interface_backward(const Tensor & grad_w, const Tensor & saved_v, const Tensor & saved_g, const Tensor & saved_norms, int64_t dim) const override;
Tensor _standard_gamma_grad(const Tensor & self, const Tensor & output) const override;
Tensor _standard_gamma(const Tensor & self, Generator * generator) const override;
Tensor poisson(const Tensor & self, Generator * generator) const override;
Tensor native_norm(const Tensor & self, Scalar p) const override;
Tensor _sparse_sum_backward(const Tensor & grad, const Tensor & self, IntList dim) const override;
Tensor native_clone(const Tensor & self) const override;
Tensor & native_resize_as_(Tensor & self, const Tensor & the_template) const override;
Tensor & native_pow_out(Tensor & result, const Tensor & self, Scalar exponent) const override;
Tensor native_pow(const Tensor & self, Scalar exponent) const override;
Tensor & native_zero_(Tensor & self) const override;
Tensor & s_native_addmm_out(Tensor & result, const Tensor & self, const Tensor & mat1, const Tensor & mat2, Scalar beta, Scalar alpha) const override;
Tensor s_native_addmm(const Tensor & self, const Tensor & mat1, const Tensor & mat2, Scalar beta, Scalar alpha) const override;
Tensor & s_native_addmm_(Tensor & self, const Tensor & mat1, const Tensor & mat2, Scalar beta, Scalar alpha) const override;
Tensor _sparse_coo_tensor_with_dims(int64_t sparse_dim, int64_t dense_dim, IntList size, const TensorOptions & options) const override;
Tensor _sparse_coo_tensor_with_dims_and_tensors(int64_t sparse_dim, int64_t dense_dim, IntList size, const Tensor & indices, const Tensor & values, const TensorOptions & options) const override;
Tensor & sparse_resize_(Tensor & self, IntList size, int64_t sparse_dim, int64_t dense_dim) const override;
Tensor & sparse_resize_and_clear_(Tensor & self, IntList size, int64_t sparse_dim, int64_t dense_dim) const override;
Tensor sparse_mask(const Tensor & self, SparseTensorRef mask) const override;
Tensor to_dense(const Tensor & self) const override;
int64_t sparse_dim(const Tensor & self) const override;
int64_t dense_dim(const Tensor & self) const override;
int64_t _nnz(const Tensor & self) const override;
Tensor coalesce(const Tensor & self) const override;
bool is_coalesced(const Tensor & self) const override;
Tensor _indices(const Tensor & self) const override;
Tensor _values(const Tensor & self) const override;
Tensor & _coalesced_(Tensor & self, bool coalesced) const override;
Tensor indices(const Tensor & self) const override;
Tensor values(const Tensor & self) const override;
Tensor & hspmm_out(Tensor & result, const Tensor & mat1, const Tensor & mat2) const override;
Tensor hspmm(const Tensor & mat1, const Tensor & mat2) const override;
Tensor & copy_sparse_to_sparse_(Tensor & self, const Tensor & src, bool non_blocking) const override;
Tensor to_sparse(const Tensor & self, int64_t sparse_dim) const override;
Tensor to_sparse(const Tensor & self) const override;
Scalar _local_scalar_dense(const Tensor & self) const override;
std::tuple<Tensor,Tensor,Tensor> _thnn_fused_lstm_cell(const Tensor & input_gates, const Tensor & hidden_gates, const Tensor & cx, const Tensor & input_bias, const Tensor & hidden_bias) const override;
std::tuple<Tensor,Tensor,Tensor,Tensor,Tensor> _thnn_fused_lstm_cell_backward(const Tensor & grad_hy, const Tensor & grad_cy, const Tensor & cx, const Tensor & cy, const Tensor & workspace, bool has_bias) const override;
std::tuple<Tensor,Tensor> _thnn_fused_gru_cell(const Tensor & input_gates, const Tensor & hidden_gates, const Tensor & hx, const Tensor & input_bias, const Tensor & hidden_bias) const override;
std::tuple<Tensor,Tensor,Tensor,Tensor,Tensor> _thnn_fused_gru_cell_backward(const Tensor & grad_hy, const Tensor & workspace, bool has_bias) const override;
Tensor _cholesky_helper(const Tensor & self, bool upper) const override;
Tensor _potrs_helper(const Tensor & self, const Tensor & A, bool upper) const override;
};
} // namespace at
| [
"luis20dr@gmail.com"
] | luis20dr@gmail.com |
12b7f123d3cbb9dab9aaf259885eb35faff9eb75 | 5af68d43b182694e6955be8de0a84ecea20c078d | /BlackCat.Platform.Win32/PlatformImp/Script/bcScriptReference.cpp | 42dd71f9a831683e267819ce1e3c7d95c4415f71 | [] | no_license | coder965/BlackCat-Engine | 1ed5c3d33c67c537eaa1ae7d1afe40192296e03f | a692f95d5c5f0c86ababa0c5ecc06531f569f500 | refs/heads/master | 2020-03-18T21:41:31.035603 | 2017-04-15T16:53:26 | 2017-04-15T16:53:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 894 | cpp | // [10/11/2016 MRB]
#include "PlatformImp/PlatformImpPCH.h"
#include "PlatformImp/bcExport.h"
#include "PlatformImp/Script/bcScriptReference.h"
namespace black_cat
{
namespace platform
{
template<>
BC_PLATFORMIMP_DLL
bc_platform_script_reference< core_platform::g_api_win32 >::bc_platform_script_reference()
{
}
template<>
BC_PLATFORMIMP_DLL
bc_platform_script_reference< core_platform::g_api_win32 >::bc_platform_script_reference(const bc_platform_script_reference& p_other) noexcept
{
}
template<>
BC_PLATFORMIMP_DLL
bc_platform_script_reference< core_platform::g_api_win32 >::~bc_platform_script_reference()
{
}
template<>
BC_PLATFORMIMP_DLL
bc_platform_script_reference< core_platform::g_api_win32 >& bc_platform_script_reference< core_platform::g_api_win32 >::operator=(const bc_platform_script_reference&) noexcept
{
return *this;
}
}
}
| [
"mohammad.r.barzegar@gmail.com"
] | mohammad.r.barzegar@gmail.com |
e9220d3156e94627b6a0094e495bf215bceb0332 | e995045f93726a1c51ee5c8eac32516d21206503 | /libraries/stdlib/ArgumentParser.h | 281fb8e2c71b833d5335eac5f0e8c194e571ba49 | [
"MIT"
] | permissive | pdpdds/CyanOS | 9b4d3c497a9b7fc8a1d9a8cce7cb8f0029f54513 | 1e42772911299a40aab0e7aac50181b180941800 | refs/heads/master | 2023-08-28T17:30:23.864817 | 2021-10-11T15:07:07 | 2021-10-11T15:07:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 359 | h | #include "Assert.h"
#include "String.h"
#include "StringView.h"
#include "Types.h"
#include "Vector.h"
class ArgumentParser
{
private:
String m_data;
Vector<StringView> m_argument_list;
void trim_arguments();
public:
ArgumentParser(StringView argument);
~ArgumentParser() = default;
size_t count() const;
StringView operator[](size_t) const;
};
| [
"aymen.sekhri@live.fr"
] | aymen.sekhri@live.fr |
466bf5b7e19f8fdb7d9cdfac2387382b800c7ba1 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /extensions/browser/api/networking_config/networking_config_service.h | 4473dda15f646f91d148aaf7c0e03ca96768b596 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 6,139 | h | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_API_NETWORKING_CONFIG_NETWORKING_CONFIG_SERVICE_H_
#define EXTENSIONS_BROWSER_API_NETWORKING_CONFIG_NETWORKING_CONFIG_SERVICE_H_
#include <map>
#include <memory>
#include <string>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_observer.h"
#include "base/values.h"
#include "components/keyed_service/core/keyed_service.h"
#include "content/public/browser/browser_context.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_observer.h"
namespace extensions {
// This class provides the session-scoped storage backing the networking config
// extension API. Currently only the parts relevant for captive portal handling
// are implemented.
class NetworkingConfigService : public ExtensionRegistryObserver,
public KeyedService {
public:
class EventDelegate {
public:
EventDelegate() {}
virtual ~EventDelegate() {}
virtual bool HasExtensionRegisteredForEvent(
const std::string& extension_id) const = 0;
private:
DISALLOW_COPY_AND_ASSIGN(EventDelegate);
};
// Indicates the authentication state of the portal.
enum AuthenticationState { NOTRY, TRYING, SUCCESS, REJECTED, FAILED };
// Provides information about the current authentication state of the portal.
struct AuthenticationResult {
AuthenticationResult();
AuthenticationResult(ExtensionId extension_id,
std::string guid,
AuthenticationState authentication_state);
ExtensionId extension_id;
std::string guid;
AuthenticationState authentication_state;
};
// Note: |extension_registry| must outlive this class.
NetworkingConfigService(content::BrowserContext* browser_context,
std::unique_ptr<EventDelegate> event_delegate,
ExtensionRegistry* extension_registry);
~NetworkingConfigService() override;
// ExtensionRegistryObserver
void OnExtensionUnloaded(content::BrowserContext* browser_context,
const Extension* extension,
UnloadedExtensionReason reason) override;
// Returns the extension id registered for |hex_ssid|. If no extension is
// registered for this |hex_ssid|, the function returns an empty string.
// |hex_ssid|: SSID in hex encoding.
std::string LookupExtensionIdForHexSsid(std::string hex_ssid) const;
// Returns true if the extension with id |extension_id| registered for
// |onCaptivePortalDetected| events, otherwise false.
bool IsRegisteredForCaptivePortalEvent(const std::string& extension_id) const;
// Registers |hex_ssid| as being handled by the extension with extension ID
// |extension_id|. Returns true on success and false if another extension
// already registered for |hex_ssid|.
// |hex_ssid|: SSID in hex encoding of the network to be registered.
// |extension_id|: Extension ID of the extension handling the network
// configuration for this network.
bool RegisterHexSsid(std::string hex_ssid, const std::string& extension_id);
// Unregisters extension with the ID |extension_id| removing all associated
// HexSSIDs from the map.
// |extension_id|: ID identifying the extenion to be removed
void UnregisterExtension(const std::string& extensionId);
// Returns the current AuthenticationResult.
const AuthenticationResult& GetAuthenticationResult() const;
// Sets the authentication_state to NOTRY and clears all other fields.
void ResetAuthenticationResult();
// Sets the current AuthenticationResult.
void SetAuthenticationResult(
const AuthenticationResult& authentication_result);
// Sends a PortalDetected event for the network with |guid| to the extension
// with |extension_id|.
// |authentication_callback| is stored and called if the extension finishes
// authentication succesfully. This Service handles at most one portal
// detection at a time, i.e. another call to this function or a not successful
// authentication will drop a previously provided |authentication_callback|.
void DispatchPortalDetectedEvent(
const std::string& extension_id,
const std::string& guid,
const base::Closure& authentication_callback);
private:
void OnGotProperties(const std::string& extension_id,
const std::string& guid,
const base::Closure& authentication_callback,
const std::string& service_path,
const base::DictionaryValue& onc_network_config);
void OnGetPropertiesFailed(const std::string& extension_id,
const std::string& guid,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data);
// Creates the captive portal event about the network with guid |guid| that is
// to be dispatched to the extension identified by |extension_id|. |bssid|
// contains a human readable, hex-encoded version of the BSSID with bytes
// separated by colons, e.g. 45:67:89:ab:cd:ef.
std::unique_ptr<Event> CreatePortalDetectedEventAndDispatch(
const std::string& extension_id,
const std::string& guid,
const std::string* bssid);
content::BrowserContext* const browser_context_;
AuthenticationResult authentication_result_;
base::Closure authentication_callback_;
ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
registry_observer_;
std::unique_ptr<EventDelegate> event_delegate_;
// This map associates a given hex encoded SSID to an extension entry.
std::map<std::string, std::string> hex_ssid_to_extension_id_;
base::WeakPtrFactory<NetworkingConfigService> weak_factory_;
};
} // namespace extensions
#endif // EXTENSIONS_BROWSER_API_NETWORKING_CONFIG_NETWORKING_CONFIG_SERVICE_H_
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
472ea81a614225d6196473a8d2271122ce2ae7c6 | a2e04e4eac1cf93bb4c1d429e266197152536a87 | /Cpp/SDK/MeshMemoryConstraintCategory_AI_Skeleton_Coral_classes.h | 34f41450606ec429b01bb9a41108c8612d581445 | [] | no_license | zH4x-SDK/zSoT-SDK | 83a4b9fcdf628637613197cf644b7f4d101bb0cb | 61af221bee23701a5df5f60091f96f2cf929846e | refs/heads/main | 2023-07-16T18:23:41.914014 | 2021-08-27T15:44:23 | 2021-08-27T15:44:23 | 400,555,804 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 890 | h | #pragma once
// Name: SoT, Version: 2.2.1.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass MeshMemoryConstraintCategory_AI_Skeleton_Coral.MeshMemoryConstraintCategory_AI_Skeleton_Coral_C
// 0x0000 (FullSize[0x0028] - InheritedSize[0x0028])
class UMeshMemoryConstraintCategory_AI_Skeleton_Coral_C : public UMeshMemoryConstraintCategory
{
public:
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass MeshMemoryConstraintCategory_AI_Skeleton_Coral.MeshMemoryConstraintCategory_AI_Skeleton_Coral_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
ff612cc6de7615f4168e340a50658df224a07e1b | 4b6a2285e076b6e2c3f29a161cd4697e519f6aeb | /d01/ex05/Karen.hpp | 3302746c43cf2316d94972581a55ea50e139b643 | [] | no_license | lulu4747/cpp_piscine | 0e5812c9d09065b9aee1f14637bdbb8058e78b1d | 51e01c32fb1a7b16e5dc1b1508dad0b715830cbb | refs/heads/master | 2023-08-21T10:58:48.567413 | 2021-10-19T14:43:55 | 2021-10-19T14:43:55 | 383,465,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 368 | hpp | #ifndef KAREN_HPP
# define KAREN_HPP
# include <string>
class Karen{
public:
Karen(void);
~Karen(void);
void complain(std::string level);
private:
void debug(void);
void info(void);
void warning(void);
void error(void);
typedef struct s_func{
std::string level;
void (Karen::*func)(void);
} t_func;
t_func _FunctionTab[4];
};
#endif | [
"ludogriph@gmail.com"
] | ludogriph@gmail.com |
3b8982ad799d2a9b1b63c269f1a45def77d77d0e | 2eca8bd48871d424de176b964e6da5bd0f1f5fe2 | /Tenth Floor Maze/Controller/iEngine.h | 192ac1c8d29fc6442ad5ecf42832fe9511023f4f | [] | no_license | Altelus/10th-Floor-Maze | b1a2f2eeefee4e039ac09b5c3f03ae88ae975720 | bc8a89726e2e5ab679abbe7baeb3ef7573eab0d9 | refs/heads/master | 2021-01-13T00:50:13.774625 | 2015-06-06T20:27:58 | 2015-06-06T20:27:58 | 36,966,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | h | #ifndef _I_ENGINE_H_
#define _I_ENGINE_H_
/* Engine Interface
*
* iEngine.h
* fwk4gps version 1.0
* gam666/dps901
* August 30 2010
* copyright (c) 2010 Chris Szalwinski
* distributed under TPL - see ../Licenses.txt
*/
//-------------------------------- iEngine ------------------------------------
//
// iEngine is the Interface to the Engine for the Model and Direct-Device
// Components
//
class iContext;
class iEngine {
public:
// configuration functions
virtual void interrogate(void*) = 0;
virtual void reset() = 0;
// initialization function
virtual void restore() = 0;
// execution function
virtual int run() = 0;
virtual void resize() const = 0;
virtual bool isActive() const = 0;
// termination functions
virtual void suspend() = 0;
virtual void Delete() const = 0;
};
extern "C"
iEngine* CreateEngine(void*, int, iContext*);
extern "C"
iEngine* EngineAddress();
#endif | [
"Altelus@gmail.com"
] | Altelus@gmail.com |
85a360e0a55fe83c47431a3b9f2b1650a0674856 | e46227a39d9fcd2c611f60d1d3692ea40d1b9058 | /ConsoleApplication1/random.cpp | 98b9927e90eac9c08021fc92ab54fb2610c6b5a7 | [] | no_license | 99sun99/cplusplus_practice | c774df5ec9cc64e174f82ba9a47f9f17982e1682 | 968dddfbc4adcdc488f1dc8306f0f8fd235c366a | refs/heads/master | 2022-04-21T16:43:36.296450 | 2020-04-19T01:20:52 | 2020-04-19T01:20:52 | 242,638,684 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,250 | cpp | #include "pch.h"
#include<iostream>
#include<random>
#include<vector>
#include<tuple> //C++11
#include<algorithm>
#include<ctime> //use time(nullptr) for seed
#include<cmath> //use sqrt
using namespace std;
typedef tuple<double, double> point;
ostream& operator<<(ostream& out, const point& pt)
{
out << "( " << get<0>(pt) << ", ";
out << get<1>(pt) << ") ";
return out;
}
default_random_engine e(time(nullptr)); //seed in constructor
point random_point()
{
uniform_real_distribution<double> u(0, 1);
point temp;
get<0>(temp) = u(e);
get<1>(temp) = u(e);
return temp;
}
double mc_count(double f(double), vector<point>::iterator first, vector <point>::iterator last)
{
int trials = 0; int below = 0;
for (first; first != last; ++first) {
++trials;
if (f(get<0>(*first)) > get<1>(*first))
++below;
}
return(1.0* below / trials);
}
int main()
{
int data_size;
cout << " How Many Points? " << endl;
cin >> data_size;
vector<point> data(data_size);
for (auto& element : data)
{
element = random_point();
cout << "element"<< element << endl;
}
cout << " PI by MC integration is " <<
4.0 * mc_count([](double x) { return (sqrt(1 - x * x)); }, data.begin(), data.end());
cout << endl;
return 0;
} | [
"sunyuan0099@163.com"
] | sunyuan0099@163.com |
bc559e763d05b745faec396bb13ed6a84427e6ac | c5bac95c360ca624fe53775f5338be4a38c5db92 | /FileTypes.h | 1d69f7392c5ffcd9551473b77e0acf27b2a3b0f4 | [] | no_license | HerrAndersson/seamcarving | dc98cc924c6b10865152704863251595b141f987 | 72461e5eb4daf5805f5b3e064985d6857aa4bc18 | refs/heads/master | 2020-05-20T14:01:41.884298 | 2015-05-26T18:42:05 | 2015-05-26T18:42:05 | 33,544,684 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 763 | h | #pragma once
#include <string>
#include "stdafx.h"
using namespace std;
const int PNG = 1;
const int JPEG = 2;
const int JPG = 2;
const int NEG_INF = -2147000000;
const int INF = 2147000000;
struct Point
{
int x, y;
Point()
{
}
Point(int x, int y)
{
this->x = x;
this->y = y;
}
};
struct Pixel
{
BYTE r;
BYTE g;
BYTE b;
int energy;
Pixel()
{
r = 0;
g = 0;
b = 0;
energy = NEG_INF;
}
Pixel(BYTE red, BYTE green, BYTE blue)
{
r = red;
g = green;
b = blue;
energy = NEG_INF;
}
BYTE RGBtoGray()
{
return (BYTE)((int)(r + g + b) / 3);
}
BYTE EnergyToColor()
{
//return (BYTE)(energy / 255);
return (BYTE)(energy / (255*3)); //255^2 - 0 ger max energy för varje färg, tre ggr ger delat med 255*3
}
}; | [
"anderssonjonas94@gmail.com"
] | anderssonjonas94@gmail.com |
9c349797122abb5425e642beacf69d52457b8c1f | b0dd7779c225971e71ae12c1093dc75ed9889921 | /tools/regression/src/compiler_status.cpp | bfb17920862e31a38b7039a338f8f58bc4f2c555 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | blackberry/Boost | 6e653cd91a7806855a162347a5aeebd2a8c055a2 | fc90c3fde129c62565c023f091eddc4a7ed9902b | refs/heads/1_48_0-gnu | 2021-01-15T14:31:33.706351 | 2013-06-25T16:02:41 | 2013-06-25T16:02:41 | 2,599,411 | 244 | 154 | BSL-1.0 | 2018-10-13T18:35:09 | 2011-10-18T14:25:18 | C++ | UTF-8 | C++ | false | false | 37,948 | cpp | // Generate Compiler Status HTML from jam regression test output -----------//
// Copyright Beman Dawes 2002.
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
// See http://www.boost.org/tools/regression/ for documentation.
/*******************************************************************************
Please contact the maintainer, bdawes <at> acm <dot> org, before making
any non-trivial changes.
This program was designed to work unchanged on all platforms and
configurations. All output which is platform or configuration dependent
is obtained from external sources such as the .xml file from
process_jam_log execution, the tools/build/xxx-tools.jam files, or the
output of the config_info tests.
Please avoid adding platform or configuration dependencies during
program maintenance.
*******************************************************************************/
#include <boost/config/warning_disable.hpp>
#include "boost/config.hpp"
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/convenience.hpp"
#include "boost/filesystem/fstream.hpp"
#include "detail/tiny_xml.hpp"
namespace fs = boost::filesystem;
namespace xml = boost::tiny_xml;
#include <cstdlib> // for abort, exit
#include <cctype> // for toupper
#include <string>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <ctime>
#include <stdexcept>
#include <cassert>
using std::string;
const string pass_msg( "Pass" );
const string warn_msg( "<i>Warn</i>" );
const string fail_msg( "<font color=\"#FF0000\"><i>Fail</i></font>" );
const string note_msg( "<sup>*</sup>" );
const string missing_residue_msg( "<i>Missing</i>" );
const std::size_t max_compile_msg_size = 10000;
namespace
{
fs::path boost_root; // boost-root complete path
fs::path locate_root; // locate-root (AKA ALL_LOCATE_TARGET) complete path
bool compile_time;
bool run_time;
bool ignore_pass;
bool no_warn;
bool no_links;
bool boost_build_v2 = true;
fs::path jamfile_path;
fs::directory_iterator end_itr;
// It's immportant for reliability that we find the same compilers for each
// test, and that they match the column header. So save the names at the
// time column headings are generated.
std::vector<string> toolsets;
fs::ifstream jamfile;
fs::ofstream report;
fs::ofstream links_file;
string links_name;
fs::path notes_path;
string notes_html;
fs::path notes_map_path;
typedef std::multimap< string, string > notes_map; // key is test_name-toolset,
// value is note bookmark
notes_map notes;
string specific_compiler; // if running on one toolset only
const string empty_string;
std::vector<int> error_count;
// prefix for library and test hyperlink prefix
string svn_root ( "http://svn.boost.org/trac/boost/browser/trunk/" );
string url_prefix_dir_view( svn_root );
string url_prefix_checkout_view( svn_root );
string url_suffix_text_view( "" );
// get revision number (as a string) if boost_root is svn working copy -----//
string revision( const fs::path & boost_root )
{
string rev;
fs::path entries( boost_root / ".svn" / "entries" );
fs::ifstream entries_file( entries );
if ( entries_file )
{
std::getline( entries_file, rev );
std::getline( entries_file, rev );
std::getline( entries_file, rev );
std::getline( entries_file, rev ); // revision number as a string
}
return rev;
}
// build notes_bookmarks from notes HTML -----------------------------------//
void build_notes_bookmarks()
{
if ( notes_map_path.empty() ) return;
fs::ifstream notes_map_file( notes_map_path );
if ( !notes_map_file )
{
std::cerr << "Could not open --notes-map input file: " << notes_map_path.string() << std::endl;
std::exit( 1 );
}
string line;
while( std::getline( notes_map_file, line ) )
{
string::size_type pos = 0;
if ( (pos = line.find( ',', pos )) == string::npos ) continue;
string key(line.substr( 0, pos ) );
string bookmark( line.substr( pos+1 ) );
// std::cout << "inserting \"" << key << "\",\"" << bookmark << "\"\n";
notes.insert( notes_map::value_type( key, bookmark ) );
}
}
// load_notes_html ---------------------------------------------------------//
bool load_notes_html()
{
if ( notes_path.empty() ) return false;
fs::ifstream notes_file( notes_path );
if ( !notes_file )
{
std::cerr << "Could not open --notes input file: " << notes_path.string() << std::endl;
std::exit( 1 );
}
string line;
bool in_body( false );
while( std::getline( notes_file, line ) )
{
if ( in_body && line.find( "</body>" ) != string::npos ) in_body = false;
if ( in_body ) notes_html += line;
else if ( line.find( "<body>" ) ) in_body = true;
}
return true;
}
// relative path between two paths -----------------------------------------//
void relative_path( const fs::path & from, const fs::path & to,
fs::path & target )
{
if ( from.string().size() <= to.string().size() ) return;
target /= "..";
relative_path( from.branch_path(), to, target );
return;
}
// extract object library name from target directory string ----------------//
string extract_object_library_name( const string & s )
{
string t( s );
string::size_type pos = t.find( "/build/" );
if ( pos != string::npos ) pos += 7;
else if ( (pos = t.find( "/test/" )) != string::npos ) pos += 6;
else return "";
return t.substr( pos, t.find( "/", pos ) - pos );
}
// find_file ---------------------------------------------------------------//
// given a directory to recursively search
bool find_file( const fs::path & dir_path, const string & name,
fs::path & path_found, const string & ignore_dir_named="" )
{
if ( !fs::exists( dir_path ) ) return false;
for ( fs::directory_iterator itr( dir_path ); itr != end_itr; ++itr )
if ( fs::is_directory( *itr )
&& itr->path().filename() != ignore_dir_named )
{
if ( find_file( *itr, name, path_found ) ) return true;
}
else if ( itr->path().filename() == name )
{
path_found = *itr;
return true;
}
return false;
}
// platform_desc -----------------------------------------------------------//
string platform_desc()
{
string result = BOOST_PLATFORM;
result[0] = std::toupper( result[0] );
return result;
}
// version_desc ------------------------------------------------------------//
// from locate-root/status/bin/config_info.test/xxx/.../config_info.output
string version_desc( const string & compiler_name )
{
string result;
fs::path dot_output_path;
if ( find_file( locate_root / "bin/boost/status/config_info.test"
/ compiler_name, "config_info.output", dot_output_path )
|| find_file( locate_root / "status/bin/config_info.test"
/ compiler_name, "config_info.output", dot_output_path ) )
{
fs::ifstream file( dot_output_path );
if ( file )
{
if( std::getline( file, result ) )
{
string::size_type pos = result.find( "version " );
if ( pos != string::npos )
{
result.erase( 0, pos+8 );
}
else result.clear();
}
}
}
return result;
}
// compiler_desc -----------------------------------------------------------//
// from boost-root/tools/build/xxx-tools.jam
string compiler_desc( const string & compiler_name )
{
string result;
fs::path tools_path( boost_root / "tools/build/v1" / (compiler_name
+ "-tools.jam") );
if ( !fs::exists( tools_path ) )
tools_path = boost_root / "tools/build" / (compiler_name + "-tools.jam");
fs::ifstream file( tools_path );
if ( file )
{
while( std::getline( file, result ) )
{
if ( result.substr( 0, 3 ) == "#//" )
{
result.erase( 0, 3 );
return result;
}
}
result.clear();
}
return result;
}
// target_directory --------------------------------------------------------//
// this amounts to a request to find a unique leaf directory
fs::path target_directory( const fs::path & root )
{
if ( !fs::exists( root ) ) return fs::path("no-such-path");
fs::path child;
for ( fs::directory_iterator itr( root ); itr != end_itr; ++itr )
{
if ( fs::is_directory( *itr ) )
{
// SunCC creates an internal subdirectory everywhere it writes
// object files. This confuses the target_directory() algorithm.
// This patch ignores the SunCC internal directory. Jens Maurer
if ( itr->path().filename() == "SunWS_cache" ) continue;
// SGI does something similar for template instantiations. Jens Maurer
if( itr->path().filename() == "ii_files" ) continue;
if ( child.empty() ) child = *itr;
else
{
std::cout << "Warning: only first of two target possibilities will be reported for: \n "
<< root.string() << ": " << child.filename()
<< " and " << itr->path().filename() << "\n";
}
}
}
if ( child.empty() ) return root; // this dir has no children
return target_directory( child );
}
// element_content ---------------------------------------------------------//
const string & element_content(
const xml::element & root, const string & name )
{
static string empty_string;
xml::element_list::const_iterator itr;
for ( itr = root.elements.begin();
itr != root.elements.end() && (*itr)->name != name;
++itr ) {}
return itr != root.elements.end() ? (*itr)->content : empty_string;
}
// find_element ------------------------------------------------------------//
const xml::element empty_element;
const xml::element & find_element(
const xml::element & root, const string & name )
{
xml::element_list::const_iterator itr;
for ( itr = root.elements.begin();
itr != root.elements.end() && (*itr)->name != name;
++itr ) {}
return itr != root.elements.end() ? *((*itr).get()) : empty_element;
}
// attribute_value ----------------------------------------------------------//
const string & attribute_value( const xml::element & element,
const string & attribute_name )
{
static const string empty_string;
xml::attribute_list::const_iterator atr;
for ( atr = element.attributes.begin();
atr != element.attributes.end() && atr->name != attribute_name;
++atr ) {}
return atr == element.attributes.end() ? empty_string : atr->value;
}
// find_bin_path -----------------------------------------------------------//
// Takes a relative path from boost root to a Jamfile.
// Returns the directory where the build targets from
// that Jamfile are located. If not found, emits a warning
// and returns empty path.
const fs::path find_bin_path(const string& relative)
{
fs::path bin_path;
if (boost_build_v2)
{
if ( relative == "status" )
bin_path = locate_root / "bin.v2" / "libs";
else
{
bin_path = locate_root / "bin.v2" / relative;
if (!fs::exists(bin_path))
bin_path = locate_root / "bin" / relative;
}
if (!fs::exists(bin_path))
{
std::cerr << "warning: could not find build results for '"
<< relative << "'.\n";
std::cerr << "warning: tried directory "
<< bin_path.string() << "\n";
bin_path = "";
}
}
else
{
bin_path = locate_root / "bin/boost" / relative;
if (!fs::exists(bin_path))
{
bin_path = locate_root / "bin" / relative / "bin";
if (!fs::exists(bin_path))
{
bin_path = fs::path( locate_root / relative / "bin" );
if (!fs::exists(bin_path))
{
bin_path = fs::path( locate_root / "bin/boost/libs" /
relative.substr( relative.find( '/' )+1 ) );
}
}
}
if (!fs::exists(bin_path))
{
std::cerr << "warning: could not find build results for '"
<< relative << "'.\n";
bin_path = "";
}
}
return bin_path;
}
// generate_report ---------------------------------------------------------//
// return 0 if nothing generated, 1 otherwise, except 2 if compiler msgs
int generate_report( const xml::element & db,
const string & source_library_name,
const string & test_type,
const string & test_name, // possibly object library name
const string & toolset,
bool pass,
bool always_show_run_output = false )
{
// compile msgs sometimes modified, so make a local copy
string compile( ((pass && no_warn)
? empty_string : element_content( db, "compile" )) );
const string & link( pass ? empty_string : element_content( db, "link" ) );
const string & run( (pass && !always_show_run_output)
? empty_string : element_content( db, "run" ) );
string lib( (pass ? empty_string : element_content( db, "lib" )) );
string::size_type pos;
if ( (pos = compile.find("30 DAY EVALUATION LICENSE")) != string::npos )
{
compile.erase(pos, 25);
while ( compile[0] == '\n' || compile[0] == '\r' ) compile.erase(0,1);
}
// some compilers output the filename even if there are no errors or
// warnings; detect this if one line of output and it contains no space.
pos = compile.find( '\n', 1 );
if ( pos != string::npos && compile.size()-pos <= 2
&& compile.find( ' ' ) == string::npos ) compile.clear();
if ( lib.empty()
&& (compile.empty() || test_type == "compile_fail")
&& link.empty() && run.empty() ) return 0;
int result = 1; // some kind of msg for sure
// limit compile message length
if ( compile.size() > max_compile_msg_size )
{
compile.erase( max_compile_msg_size );
compile += "...\n (remainder deleted because of excessive size)\n";
}
links_file << "<h2><a name=\""
<< source_library_name << "-" << test_name << "-" << toolset << "\">"
<< source_library_name << " - " << test_name << " - " << toolset << "</a></h2>\n";
if ( !compile.empty() )
{
++result;
links_file << "<h3>Compiler output:</h3><pre>"
<< compile << "</pre>\n";
}
if ( !link.empty() )
links_file << "<h3>Linker output:</h3><pre>" << link << "</pre>\n";
if ( !run.empty() )
links_file << "<h3>Run output:</h3><pre>" << run << "</pre>\n";
// for an object library failure, generate a reference to the object
// library failure message, and (once only) generate the object
// library failure message itself
static std::set< string > failed_lib_target_dirs; // only generate once
if ( !lib.empty() )
{
if ( lib[0] == '\n' ) lib.erase( 0, 1 );
string object_library_name( extract_object_library_name( lib ) );
// changing the target directory naming scheme breaks
// extract_object_library_name()
assert( !object_library_name.empty() );
if ( object_library_name.empty() )
std::cerr << "Failed to extract object library name from " << lib << "\n";
links_file << "<h3>Library build failure: </h3>\n"
"See <a href=\"#"
<< source_library_name << "-"
<< object_library_name << "-" << toolset << "\">"
<< source_library_name << " - "
<< object_library_name << " - " << toolset << "</a>";
if ( failed_lib_target_dirs.find( lib ) == failed_lib_target_dirs.end() )
{
failed_lib_target_dirs.insert( lib );
fs::path pth( locate_root / lib / "test_log.xml" );
fs::ifstream file( pth );
if ( file )
{
xml::element_ptr db = xml::parse( file, pth.string() );
generate_report( *db, source_library_name, test_type, object_library_name, toolset, false );
}
else
{
links_file << "<h2><a name=\""
<< object_library_name << "-" << toolset << "\">"
<< object_library_name << " - " << toolset << "</a></h2>\n"
"test_log.xml not found\n";
}
}
}
return result;
}
// add_notes --------------------------------------------------------------//
void add_notes( const string & key, bool fail, string & sep, string & target )
{
notes_map::const_iterator itr = notes.lower_bound( key );
if ( itr != notes.end() && itr->first == key )
{
for ( ; itr != notes.end() && itr->first == key; ++itr )
{
string note_desc( itr->second[0] == '-'
? itr->second.substr( 1 ) : itr->second );
if ( fail || itr->second[0] == '-' )
{
target += sep;
sep = ",";
target += "<a href=\"";
target += "#";
target += note_desc;
target += "\">";
target += note_desc;
target += "</a>";
}
}
}
}
// get_notes -------------------------------------------------------------//
string get_notes( const string & toolset,
const string & library, const string & test, bool fail )
{
string sep;
string target( "<sup>" );
add_notes( toolset + "/" + library + "/" + test, fail, sep, target );
add_notes( "*/" + library + "/" + test, fail, sep, target );
add_notes( toolset + "/" + library + "/*", fail, sep, target );
add_notes( "*/" + library + "/*", fail, sep, target );
if ( target == "<sup>" ) target.clear();
else target += "</sup>";
return target;
}
// do_cell ---------------------------------------------------------------//
bool do_cell(
int compiler,
const string & lib_name,
const fs::path & test_dir,
const string & test_type,
const string & test_name,
const string & toolset,
string & target,
bool always_show_run_output )
// return true if any results except simple pass_msg
{
fs::path target_dir( target_directory( test_dir / toolset ) );
bool pass = false;
if ( !fs::exists( target_dir / "test_log.xml" ) )
{
std::cerr << "Missing test_log.xml in target:\n "
<< target_dir.string() << "\n";
target += "<td>" + missing_residue_msg + "</td>";
return true;
}
int anything_generated = 0;
bool note = false;
fs::path pth( target_dir / "test_log.xml" );
fs::ifstream file( pth );
if ( !file )
{
std::cerr << "Can't open test_log.xml in target:\n "
<< target_dir.string() << "\n";
target += "<td>" + missing_residue_msg + "</td>";
return false;
}
xml::element_ptr dbp = xml::parse( file, pth.string() );
const xml::element & db( *dbp );
std::string test_type_base( test_type );
if ( test_type_base == "run_pyd" ) test_type_base = "run";
else if ( test_type_base.size() > 5 )
{
const string::size_type trailer = test_type_base.size() - 5;
if ( test_type_base.substr( trailer ) == "_fail" )
{
test_type_base.erase( trailer );
}
}
const xml::element & test_type_element( find_element( db, test_type_base ) );
pass = !test_type_element.name.empty()
&& attribute_value( test_type_element, "result" ) != "fail";
if ( !no_links )
{
note = attribute_value( test_type_element, "result" ) == "note";
// generate bookmarked report of results, and link to it
anything_generated
= generate_report( db, lib_name, test_type, test_name, toolset, pass,
always_show_run_output || note );
}
target += "<td>";
// generate the status table cell pass/warn/fail HTML
if ( anything_generated != 0 )
{
target += "<a href=\"";
target += links_name;
target += "#";
target += lib_name;
target += "-";
target += test_name;
target += "-";
target += toolset;
target += "\">";
target += pass
? (anything_generated < 2 ? pass_msg : warn_msg)
: fail_msg;
target += "</a>";
if ( pass && note ) target += note_msg;
}
else target += pass ? pass_msg : fail_msg;
// if notes, generate the superscript HTML
if ( !notes.empty() )
target += get_notes( toolset, lib_name, test_name, !pass );
// generate compile-time if requested
if ( compile_time )
{
const xml::element & compile_element( find_element( db, "compile" ) );
if ( !compile_element.name.empty() )
{
string times = attribute_value( compile_element, "timings" );
if ( !times.empty() )
{
target += "<br>";
target += times.substr( 0, times.find( " " ) );
}
}
}
// generate run-time if requested
if ( run_time )
{
const xml::element & run_element( find_element( db, "run" ) );
if ( !run_element.name.empty() )
{
string times = attribute_value( run_element, "timings" );
if ( !times.empty() )
{
target += "<br>";
target += times.substr( 0, times.find( " " ) );
}
}
}
if ( !pass ) ++error_count[compiler];
target += "</td>";
return (anything_generated != 0) || !pass;
}
// do_row ------------------------------------------------------------------//
void do_row(
const fs::path & test_dir, // locate_root / "status/bin/any_test.test"
const string & test_name, // "any_test"
string & target )
{
// get library name, test-type, test-program path, etc., from the .xml file
string lib_name;
string test_path( test_name ); // test_name is default if missing .test
string test_type( "unknown" );
bool always_show_run_output( false );
fs::path xml_file_path;
if ( find_file( test_dir, "test_log.xml", xml_file_path ) )
{
fs::ifstream file( xml_file_path );
if ( file )
{
xml::element_ptr dbp = xml::parse( file, xml_file_path.string() );
const xml::element & db( *dbp );
test_path = attribute_value( db, "test-program" );
lib_name = attribute_value( db, "library" );
test_type = attribute_value( db, "test-type" );
always_show_run_output
= attribute_value( db, "show-run-output" ) == "true";
}
}
// generate the library name, test name, and test type table data
string::size_type row_start_pos = target.size();
target += "<tr><td><a href=\"" + url_prefix_dir_view + "/libs/" + lib_name
+ "\">" + lib_name + "</a></td>";
target += "<td><a href=\"" + url_prefix_checkout_view + "/" + test_path
+ url_suffix_text_view + "\">" + test_name + "</a>";
if ( compile_time ) target += "<br> Compile time:";
if ( run_time ) target += "<br> Run time:";
target += "</td>";
target += "<td>" + test_type + "</td>";
bool no_warn_save = no_warn;
//if ( test_type.find( "fail" ) != string::npos ) no_warn = true;
// for each compiler, generate <td>...</td> html
bool anything_to_report = false;
int compiler = 0;
for ( std::vector<string>::const_iterator itr=toolsets.begin();
itr != toolsets.end(); ++itr, ++compiler )
{
anything_to_report |= do_cell( compiler, lib_name, test_dir, test_type, test_name, *itr, target,
always_show_run_output );
}
target += "</tr>";
if ( ignore_pass && !anything_to_report ) target.erase( row_start_pos );
no_warn = no_warn_save;
}
// do_rows_for_sub_tree ----------------------------------------------------//
void do_rows_for_sub_tree(
const fs::path & bin_dir, std::vector<string> & results )
{
for ( fs::directory_iterator itr( bin_dir ); itr != end_itr; ++itr )
{
if ( fs::is_directory( *itr )
&& itr->path().string().find( ".test" ) == (itr->path().string().size()-5) )
{
results.push_back( std::string() );
do_row( *itr,
itr->path().filename().string().substr( 0,
itr->path().filename().string().size()-5 ),
results[results.size()-1] );
}
}
}
// find_compilers ------------------------------------------------------------//
void find_compilers(const fs::path & bin_dir)
{
fs::directory_iterator compiler_itr( bin_dir );
if ( specific_compiler.empty() )
std::clog << "Using " << bin_dir.string() << " to determine compilers\n";
for (; compiler_itr != end_itr; ++compiler_itr )
{
if ( fs::is_directory( *compiler_itr ) // check just to be sure
&& compiler_itr->path().filename() != "test" ) // avoid strange directory (Jamfile bug?)
{
if ( specific_compiler.size() != 0
&& specific_compiler != compiler_itr->path().filename() ) continue;
toolsets.push_back( compiler_itr->path().filename().string() );
string desc( compiler_desc( compiler_itr->path().filename().string() ) );
string vers( version_desc( compiler_itr->path().filename().string() ) );
report << "<td>"
<< (desc.size() ? desc : compiler_itr->path().filename().string())
<< (vers.size() ? (string( "<br>" ) + vers ) : string( "" ))
<< "</td>\n";
error_count.push_back( 0 );
}
}
}
// do_table_body -----------------------------------------------------------//
void do_table_body( const fs::path & bin_dir )
{
// rows are held in a vector so they can be sorted, if desired.
std::vector<string> results;
// do primary bin directory
do_rows_for_sub_tree( bin_dir, results );
// do subinclude bin directories
jamfile.clear();
jamfile.seekg(0);
string line;
bool run_tests = false;
while( std::getline( jamfile, line ) )
{
bool v2(false);
string::size_type sub_pos( line.find( "subinclude" ) );
if ( sub_pos == string::npos ) {
sub_pos = line.find( "build-project" );
v2 = true;
}
if ( sub_pos != string::npos
&& line.find( '#' ) > sub_pos )
{
if (v2)
sub_pos = line.find_first_not_of( " \t./", sub_pos+13 );
else
sub_pos = line.find_first_not_of( " \t./", sub_pos+10 );
if ( sub_pos == string::npos ) continue;
string subinclude_bin_dir(
line.substr( sub_pos, line.find_first_of( " \t", sub_pos )-sub_pos ) );
fs::path bin_path = find_bin_path(subinclude_bin_dir);
if (!bin_path.empty())
do_rows_for_sub_tree( bin_path, results );
}
if ( ! run_tests )
{
string::size_type run_pos = line.find("run-tests");
if ( run_pos != string::npos && line.find_first_not_of(" \t") == run_pos )
run_tests = true;
}
else
{
if ( line.find(";") != string::npos )
run_tests = false;
else
{
string::size_type pos = line.find_first_not_of( " \t" );
if ( pos != string::npos && line[pos] != '#' )
{
string::size_type end_pos = line.find_first_of(" \t#", pos);
string::iterator end = end_pos != string::npos ? line.begin() + end_pos : line.end();
string run_tests_bin_dir(line.begin() + pos, end);
fs::path bin_path = find_bin_path("libs/" + run_tests_bin_dir);
if (!bin_path.empty())
do_rows_for_sub_tree( bin_path, results );
}
}
}
}
std::sort( results.begin(), results.end() );
for ( std::vector<string>::iterator v(results.begin());
v != results.end(); ++v )
{ report << *v << "\n"; }
}
// do_table ----------------------------------------------------------------//
void do_table()
{
// Find test result locations, trying:
// - Boost.Build V1 location with ALL_LOCATE_TARGET
// - Boost.Build V2 location with top-lelve "build-dir"
// - Boost.Build V1 location without ALL_LOCATE_TARGET
string relative( fs::initial_path().string() );
#ifdef BOOST_WINDOWS_API
if (relative.size() > 1 && relative[1] == ':') relative[0] = std::tolower(relative[0]);
#endif
if ( relative.find(boost_root.string()) != string::npos )
relative.erase( 0, boost_root.string().size()+1 );
else if ( relative.find(locate_root.string()) != string::npos )
relative.erase( 0, locate_root.string().size()+1 );
fs::path bin_path = find_bin_path(relative);
report << "<table border=\"1\" cellspacing=\"0\" cellpadding=\"5\">\n";
// generate the column headings
report << "<tr><td>Library</td><td>Test Name</td>\n"
"<td><a href=\"compiler_status.html#test-type\">Test Type</a></td>\n";
if ( relative == "status" )
{
fs::recursive_directory_iterator ritr( bin_path );
fs::recursive_directory_iterator end_ritr;
while ( ritr != end_ritr
&& ((ritr->path().string().find( ".test" ) != (ritr->path().string().size()-5))
|| !fs::is_directory( *ritr )))
++ritr; // bypass chaff
if ( ritr != end_ritr )
{
find_compilers( *ritr );
}
}
else
{
fs::directory_iterator itr( bin_path );
while ( itr != end_itr
&& ((itr->path().string().find( ".test" ) != (itr->path().string().size()-5))
|| !fs::is_directory( *itr )))
++itr; // bypass chaff
if ( itr != end_itr )
{
find_compilers( *itr );
}
}
report << "</tr>\n";
// now the rest of the table body
do_table_body( bin_path );
// error total row
report << "<tr> <td> </td><td>Number of Failures</td><td> </td>\n";
// for each compiler, generate <td>...</td> html
int compiler = 0;
for ( std::vector<string>::const_iterator itr=toolsets.begin();
itr != toolsets.end(); ++itr, ++compiler )
{
report << "<td align=\"center\">" << error_count[compiler] << "</td>\n";
}
report << "</tr>\n</table>\n";
}
} // unnamed namespace
// main --------------------------------------------------------------------//
#define BOOST_NO_CPP_MAIN_SUCCESS_MESSAGE
#include <boost/test/included/prg_exec_monitor.hpp>
int cpp_main( int argc, char * argv[] ) // note name!
{
fs::path comment_path;
while ( argc > 1 && *argv[1] == '-' )
{
if ( argc > 2 && std::strcmp( argv[1], "--compiler" ) == 0 )
{ specific_compiler = argv[2]; --argc; ++argv; }
else if ( argc > 2 && std::strcmp( argv[1], "--locate-root" ) == 0 )
{ locate_root = fs::path( argv[2] ); --argc; ++argv; }
else if ( argc > 2 && std::strcmp( argv[1], "--comment" ) == 0 )
{ comment_path = fs::path( argv[2] ); --argc; ++argv; }
else if ( argc > 2 && std::strcmp( argv[1], "--notes" ) == 0 )
{ notes_path = fs::path( argv[2] ); --argc; ++argv; }
else if ( argc > 2 && std::strcmp( argv[1], "--notes-map" ) == 0 )
{ notes_map_path = fs::path( argv[2] ); --argc; ++argv; }
else if ( std::strcmp( argv[1], "--ignore-pass" ) == 0 ) ignore_pass = true;
else if ( std::strcmp( argv[1], "--no-warn" ) == 0 ) no_warn = true;
else if ( std::strcmp( argv[1], "--v1" ) == 0 ) boost_build_v2 = false;
else if ( std::strcmp( argv[1], "--v2" ) == 0 ) boost_build_v2 = true;
else if ( argc > 2 && std::strcmp( argv[1], "--jamfile" ) == 0)
{ jamfile_path = fs::path( argv[2] ); --argc; ++argv; }
else if ( std::strcmp( argv[1], "--compile-time" ) == 0 ) compile_time = true;
else if ( std::strcmp( argv[1], "--run-time" ) == 0 ) run_time = true;
else { std::cerr << "Unknown option: " << argv[1] << "\n"; argc = 1; }
--argc;
++argv;
}
if ( argc != 3 && argc != 4 )
{
std::cerr <<
"Usage: compiler_status [options...] boost-root status-file [links-file]\n"
" boost-root is the path to the boost tree root directory.\n"
" status-file and links-file are paths to the output files.\n"
"Must be run from directory containing Jamfile\n"
" options: --compiler name Run for named compiler only\n"
" --locate-root path Path to ALL_LOCATE_TARGET for bjam;\n"
" default boost-root.\n"
" --comment path Path to file containing HTML\n"
" to be copied into status-file.\n"
" --notes path Path to file containing HTML\n"
" to be copied into status-file.\n"
" --notes-map path Path to file of toolset/test,n lines, where\n"
" n is number of note bookmark in --notes file.\n"
" --jamfile path Path to Jamfile. By default \"Jamfile\".\n"
" --v1 Assume Boost.Build version 1.\n"
" --v2 Assume Boost.Build version 2. (default)\n"
" --ignore-pass Ignore passing tests.\n"
" --no-warn Do not report warnings.\n"
" --compile-time Show compile time.\n"
" --run-time Show run time.\n"
"Example: compiler_status --compiler gcc /boost-root cs.html cs-links.html\n"
"Note: Only the leaf of the links-file path and --notes file string are\n"
"used in status-file HTML links. Thus for browsing, status-file,\n"
"links-file, and --notes file must all be in the same directory.\n"
;
return 1;
}
boost_root = fs::path( argv[1] );
if ( locate_root.empty() ) locate_root = boost_root;
if (jamfile_path.empty())
if (boost_build_v2)
jamfile_path = "Jamfile.v2";
else
jamfile_path = "Jamfile";
jamfile_path = fs::absolute( jamfile_path, fs::initial_path() );
jamfile.open( jamfile_path );
if ( !jamfile )
{
std::cerr << "Could not open Jamfile: " << jamfile_path.string() << std::endl;
return 1;
}
report.open( fs::path( argv[2] ) );
if ( !report )
{
std::cerr << "Could not open report output file: " << argv[2] << std::endl;
return 1;
}
if ( argc == 4 )
{
fs::path links_path( argv[3] );
links_name = links_path.filename().string();
links_file.open( links_path );
if ( !links_file )
{
std::cerr << "Could not open links output file: " << argv[3] << std::endl;
return 1;
}
}
else no_links = true;
build_notes_bookmarks();
char run_date[128];
std::time_t tod;
std::time( &tod );
std::strftime( run_date, sizeof(run_date),
"%X UTC, %A %d %B %Y", std::gmtime( &tod ) );
std::string rev = revision( boost_root );
report << "<html>\n"
"<head>\n"
"<title>Boost Test Results</title>\n"
"</head>\n"
"<body bgcolor=\"#ffffff\" text=\"#000000\">\n"
"<table border=\"0\">\n"
"<tr>\n"
"<td><img border=\"0\" src=\"http://www.boost.org/boost.png\" width=\"277\" "
"height=\"86\"></td>\n"
"<td>\n"
"<h1>Boost Test Results - " + platform_desc() + "</h1>\n"
"<b>Run</b> "
<< run_date;
if ( !rev.empty() ) report << ", <b>Revision</b> " << rev;
report << "\n";
if ( compile_time )
report << "<p>Times reported are elapsed wall clock time in seconds.</p>\n";
if ( !comment_path.empty() )
{
fs::ifstream comment_file( comment_path );
if ( !comment_file )
{
std::cerr << "Could not open \"--comment\" input file: " << comment_path.string() << std::endl;
return 1;
}
char c;
while ( comment_file.get( c ) ) { report.put( c ); }
}
report << "</td>\n</table>\n<br>\n";
if ( !no_links )
{
links_file
<< "<html>\n"
"<head>\n"
"<title>Boost Test Details</title>\n"
"</head>\n"
"<body bgcolor=\"#ffffff\" text=\"#000000\">\n"
"<table border=\"0\">\n"
"<tr>\n"
"<td><img border=\"0\" src=\"http://www.boost.org/boost.png\" width=\"277\" "
"height=\"86\"></td>\n"
"<td>\n"
"<h1>Boost Test Details - " + platform_desc() + "</h1>\n"
"<b>Run Date:</b> "
<< run_date;
if ( !rev.empty() ) links_file << ", <b>Revision</b> " << rev;
links_file << "\n</td>\n</table>\n<br>\n";
}
do_table();
if ( load_notes_html() ) report << notes_html << "\n";
report << "</body>\n"
"</html>\n"
;
if ( !no_links )
{
links_file
<< "</body>\n"
"</html>\n"
;
}
return 0;
}
| [
"tvaneerd@rim.com"
] | tvaneerd@rim.com |
0cf63ae59de55487b8c8046a38461b009deba187 | fc75446fc3cfff7a21faf6627db7b3a01b7aaf51 | /Header/Gameplay/AI/FlockDataManager.h | 9653eee1df14949fed7adb83af2f045370ec2192 | [
"MIT"
] | permissive | BryanBrouwer/FormationalFlocking | a9047076db234a6cf319d26d837214b09a03898a | 32a02f4293e7e79ca91db2c7920267b27b1a5c61 | refs/heads/main | 2023-05-08T17:09:13.381208 | 2021-06-06T13:04:58 | 2021-06-06T13:04:58 | 374,344,975 | 0 | 0 | MIT | 2021-06-06T13:04:58 | 2021-06-06T11:40:12 | C++ | UTF-8 | C++ | false | false | 1,779 | h | #pragma once
#include <json.hpp>
enum class EnumFlockVariables
{
cohesionBias = 0,
separationBias = 1,
alignmentBias = 2,
perceptionRadius = 3,
fieldOfView = 4,
maxPerceived = 5,
cellSize = 6,
acceptanceDistance = 7,
collisionRange = 8,
collisionBias = 9,
maxToCollide = 10,
speed = 11
};
struct FlockVariables
{
float cohesionBias;
float separationBias;
float alignmentBias;
float perceptionRadius;
float fieldOfView;
int maxPerceived;
float cellSize;
float acceptanceDistance;
float collisionRange;
float collisionBias;
int maxToCollide;
float speed;
//float variables[11];
};
//Class used to manage the data related to the flocking variables, including reading the variables from the JSON file.
class FlockDataManager
{
public:
static FlockDataManager& getInstance()
{
static FlockDataManager instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
FlockDataManager(FlockDataManager const&) = delete;
void operator=(FlockDataManager const&) = delete;
//Sets the path to the JSON file used to read the flocking variables from.
void SetJsonFile(const char* filePath);
float GetFormationSpeedFromJson();
float GetFormationSpeed() const;
void ResetFormationSpeed();
float GetCellSizeFromJson();
float GetCellSize() const;
void ResetCellSize();
//Gets a specific flocking variable directly from the JSON file without updating the global variable.
float GetFlockVariableFromJson(EnumFlockVariables neededVariable);
//Reads the JSON file in order to reset/update all global flocking variables.
void ResetMainFlockVariables();
FlockVariables MainFlockVariables{};
private:
FlockDataManager() = default;
float formationSpeed{};
float cellSize{};
nlohmann::json flockJson;
};
| [
"bryanbrouwerus@gmail.com"
] | bryanbrouwerus@gmail.com |
48b4e61857d60ae1a1da7b6710e2dc8e2257c9db | dfc9d85b228bb88649cf0c30f4929bb412808b08 | /Lab 6/wordPuzzle.cpp | 297c8484400e3d6aa6926f5251f874973342a1c7 | [] | no_license | avonstar21/CS-2150 | afad856e235aab65651942d0b3614469ae75472e | dd9f452d524a67cd8e24f81a737a3d029a2f7d2b | refs/heads/main | 2023-01-31T21:18:20.204650 | 2020-12-16T05:07:23 | 2020-12-16T05:07:23 | 321,806,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,557 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include "HashTable.h"
#include "timer.h"
#include <unordered_set>
using namespace std;
#define MAXROWS 500
#define MAXCOLS 500
char grid[MAXROWS][MAXCOLS];
bool readInGrid(string filename, int& rows, int& cols);
string getWordInGrid(int startRow, int startCol, int dir, int len,
int numRows, int numCols);
int main(int argc, char **argv){
timer t;
//t.start();
string gridFilename = argv[2];
string dictFilename = argv[1];
int wordCount = 0;
//HashTable dict;
ifstream toRead;
string word;
int arrSize = 0;
toRead.open(dictFilename);
while(getline(toRead,word)){
// dict.insert(word);
arrSize++;
}
toRead.close();
HashTable dict(arrSize);
toRead.open(dictFilename);
//getline(toRead,word);
//dict.insert(word);
while(getline(toRead,word)){
dict.insert(word);
}
toRead.close();
//ifstream gridRead;
//gridRead.open(gridFilename);
int rows = 0;
int columns = 0;
bool x = readInGrid(gridFilename, rows, columns);
t.start();
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
for(int dir = 0; dir < 8; dir++){
for(int len = 3; len <= 22; len++){
string ans = getWordInGrid(i,j,dir,len,MAXROWS,MAXCOLS);
if(ans.length()>= 3 && dict.contains(ans) == true){
//wordCount++;
if(dir == 0){
cout<< "N (" << i << ", " << j << "): " << ans << endl;
wordCount++;
break;
//wordCount++;
}else if(dir == 1){
cout<< "NE (" << i << ", " << j << "): " << ans << endl;
wordCount++;
break;
wordCount++;
}else if(dir == 2){
cout<< "E (" << i << ", " << j << "): " << ans << endl;
wordCount++;
break;
//wordCount++;
}else if(dir == 3){
cout<< "SE (" << i << ", " << j << "): " << ans << endl;
wordCount++;
break;
//wordCount++;
}else if(dir == 4){
cout<< "S (" << i << ", " << j << "): " << ans << endl;
wordCount++;
break;
//wordCount++;
}else if(dir == 5){
cout<< "SW (" << i << ", " << j << "): " << ans << endl;
wordCount++;
break;
//wordCount++;
}else if(dir == 6){
cout<< "W (" << i << ", " << j << "): " << ans << endl;
wordCount++;
break;
// wordCount++;
}else if(dir == 7){
cout<< "NW (" << i << ", " << j << "): " << ans << endl;
wordCount++;
break;
//wordCount++;
}
//wordCount++;
}
}
}
}
}
cout << wordCount <<" words found" << endl;
t.stop();
//int timeMe = t.getTime() * 1000;
//cout<< timeMe << endl;
return 0;
}
bool readInGrid(string filename, int& rows, int& cols) {
// try to open the file
ifstream file(filename);
// upon an error, return false
if (!file.is_open()) {
return false;
}
// first comes the number of rows
file >> rows;
//cout << "There are " << rows << " rows." << endl;
// then the columns
file >> cols;
//cout << "There are " << cols << " cols." << endl;
// and finally the grid itself
string data;
file >> data;
// close the file
file.close();
// convert the string read in to the 2-D grid format into the
// grid[][] array.
// In the process, we'll print the grid to the screen as well.
int pos = 0; // the current position in the input data
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
grid[r][c] = data[pos++];
//cout << grid[r][c];
}
//cout << endl;
}
return true;
}
string getWordInGrid (int startRow, int startCol, int dir, int len,
int numRows, int numCols) {
// the static-ness of this variable prevents it from being
// re-declared upon each function invocation. It also prevents it
// from being deallocated between invocations. It's probably not
// good programming practice, but it's an efficient means to return
// a value.
static string output;
output.clear(); // Since it's static we need to clear it
output.reserve(256); // Can't set capacity in the constructor so do it the first time here
// the position in the output array, the current row, and the
// current column
int r = startRow, c = startCol;
// iterate once for each character in the output
for (int i = 0; i < len; i++) {
// if the current row or column is out of bounds, then break
if (c >= numCols || r >= numRows || r < 0 || c < 0) {
break;
}
// set the next character in the output array to the next letter
// in the grid
output += grid[r][c];
// move in the direction specified by the parameter
switch (dir) { // assumes grid[0][0] is in the upper-left
case 0:
r--;
break; // north
case 1:
r--;
c++;
break; // north-east
case 2:
c++;
break; // east
case 3:
r++;
c++;
break; // south-east
case 4:
r++;
break; // south
case 5:
r++;
c--;
break; // south-west
case 6:
c--;
break; // west
case 7:
r--;
c--;
break; // north-west
}
}
return output;
}
| [
"noreply@github.com"
] | noreply@github.com |
077f857285facf8e38f937224957875e7aa92e94 | 72975a4bd6b9dff774edab2280859877f7046a4a | /oop9and10_1/oop9and10_1/oop9and10_1.cpp | f682745e0c187d4a24f3c7852fe635aa6bdc76e4 | [] | no_license | EugeneMv/OOPlab9and10 | df10092fd19b1ef2e81294f450b7b4d407805013 | 83a47bae7adbd02d9b61dca9973a415a2bcf1ad4 | refs/heads/master | 2020-06-14T05:54:44.050222 | 2016-11-30T20:24:39 | 2016-11-30T20:24:39 | 75,223,933 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,383 | cpp | #include "stdafx.h"
#include <iostream>
#include <list>
#include <map>
#include <deque>
#include <string>
#include <iterator>
#include <initializer_list>
using namespace std;
void main() {
setlocale(LC_CTYPE, "rus");
multimap<string, long, less<string>> lst;
lst.insert(pair<string, float>("a", 1.2));
lst.insert(pair<string, float>("b", 2.3));
lst.insert(pair<string, float>("c", 3.4));
lst.insert(pair<string, float>("d", 4.5));
lst.insert(pair<string, float>("d", 5.6));
cout << " контейнер lst: " << endl;
for (auto el : lst)
{
cout << el.first << ":" << el.second << " ";
}
cout << endl << " удаление некоторых элеметов по их ключам и добавление новых " << endl;
lst.erase("d");
lst.erase("c");
lst.insert(pair<string, float>("c", 7));
cout << " контейнер lst: " << endl;
for (auto el : lst)
{
cout << el.first << ":" << el.second << endl;
}
cout << " вывод при помощи итераторов: " << endl;
map<string, long>::iterator it;
for (it = lst.begin(); it != lst.end(); it++)
{
cout << it->first << ":" << it->second << endl;
}
cout << " вывод при помощи revers итераторов: " << endl;
map<string, long>::reverse_iterator rit;
for (rit = lst.rbegin(); rit != lst.rend(); rit++)
{
cout << rit->first << ":" << rit->second << endl;
}
cout << " вывод при помощи const итераторов: " << endl;
map<string, long>::const_iterator cit;
for (cit = lst.cbegin(); cit != lst.cend(); cit++)
{
cout << cit->first << ":" << cit->second << endl;
}
cout << " создаем очередь и заполняем её " << endl;
deque<float> deq;
for (int i = 0; i < 3; i++)
deq.push_back(i + 5);
cout << "очередь deq: ";
for (auto el : deq)
{
cout << el << " ";
}
cout << endl;
cout << "объединение контейнеров";
deque<float>::iterator list_begin = deq.begin();
deque<float>::iterator list_end = deq.end();
for (auto list_iter = list_begin; list_iter != list_end; list_iter++)
{
lst.insert(pair<string, float>("other", *list_iter));
}
cout << " контейнер lst: " << endl;
for (auto el : lst)
{
cout << el.first << ":" << el.second << endl;
}
} | [
"jeka.m.xd@gmail.com"
] | jeka.m.xd@gmail.com |
ffc60371dc98e9450889c71b8a04042b8fbee68d | c62b065166777feaa92786cc34bd30a534f8e02c | /字符串/序列自动机.cpp | 8c4f5834306c1024d3bf75955c79cfd2e493618a | [] | no_license | hpumengzhao/Template-of-ACM-ICPC | c3ce047840a407615e9be762119a098849317e04 | 9a4244fb7f107b213acb9da9294405eea89a2f7c | refs/heads/master | 2020-05-26T18:36:29.951699 | 2019-10-30T06:49:28 | 2019-10-30T06:49:28 | 188,337,991 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | #include<bits/stdc++.h>
using namespace std;
const int N = 1e5+100;
const int INF = 0x3f3f3f3f;
char s[N];
char t[N];
struct sub_AM{
int nxt[N][27];
void init(char *s){
int l=strlen(s);
for(int i=0;i<26;i++) nxt[l][i]=INF;
for(int i=l-1;i>=0;i--){
for(int j=0;j<26;j++){
nxt[i][j]=nxt[i+1][j];
}
nxt[i][s[i]-'a']=i;
}
}
bool find(char *t){
int pos=-1;
int l=strlen(t);
for(int i=0;i<l;i++){
pos=nxt[pos+1][t[i]-'a'];
if(pos==INF) return 0;
}
return 1;
}
}solve;
int main(){
scanf("%s",s);
solve.init(s);
int q;
scanf("%d",&q);
while(q--){
scanf("%s",t);
if(solve.find(t)){
puts("Yes");
}
else puts("No");
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
bf003980428050bc02df068881cc7e05ed7c6f0f | c9796a20cf56aa01ecbc2ff3985703b17bfb51fe | /leetcode/FlipGame/a.cpp | 9f61b9fda0d3ce23f69aedae004a964e8f3980f9 | [] | no_license | iamslash/learntocode | a62329710d36b21f8025961c0ad9b333c10e973a | 63faf361cd4eefe0f6f1e50c49ea22577a75ea74 | refs/heads/master | 2023-08-31T08:20:08.608771 | 2023-08-31T00:05:06 | 2023-08-31T00:05:06 | 52,074,001 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 599 | cpp | #include <cstdio>
#include <vector>
#include <string>
// 4ms 100.00% 9.8MB 100.00%
// O(N) O(N)
class Solution {
public:
std::vector<std::string> generatePossibleNextMoves(std::string s) {
int n = s.size();
std::vector<std::string> rslt;
for (int i = 1; i < n; ++i) {
if (s[i] == '+' && s[i-1] == '+') {
s[i] = s[i-1] = '-';
rslt.push_back(s);
s[i] = s[i-1] = '+';
}
}
return rslt;
}
};
int main() {
Solution sln;
auto rslt = sln.generatePossibleNextMoves("++++");
for (auto& a : rslt)
printf("%s\n", a.c_str());
return 0;
} | [
"iamslash@gmail.com"
] | iamslash@gmail.com |
0432334c6faa259a0b01c2fca5f04ebcd366597c | 4117060b1b09d1834ebe6d05fa6efbae70c821fc | /include/engine.h | 856edee35bc31d2190fc870c104088008951b560 | [
"MIT"
] | permissive | akevli/CubeSST | 42fc6cfce3708bf08f015bac0656e24f967aef17 | 93ec795c464a52db3adbd6d90fd51e972d316bfd | refs/heads/master | 2022-04-25T21:52:30.113047 | 2020-05-05T04:10:58 | 2020-05-05T04:10:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | h | //
// Created by valkee on 4/25/2020.
//
#ifndef FINALPROJECT_ENGINE_H
#define FINALPROJECT_ENGINE_H
#include <string>
#include <vector>
std::string GetScrambledState(std::vector<std::string> scramble);
void ResetSolvedState();
#endif // FINALPROJECT_ENGINE_H
| [
"akli2@illinois.edu"
] | akli2@illinois.edu |
95ec947b503b398422fa928aa67fed8306c595af | e05c23618619f516e6d6af629c950cec30a79afa | /bricks/brick-proc | 0495c5ff7c1a69dec1350e2ac0035ed361b370d9 | [] | no_license | paradise-fi/bricks | cddc2ff6bb7aee077ddee1dbf582f857b34b7ea6 | 228124641d168cb7b3977f0c45eba95e5997127c | refs/heads/master | 2021-01-23T09:48:39.484555 | 2017-11-05T20:26:59 | 2017-11-12T12:03:42 | 102,602,611 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,827 | // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*-
/*
* (c) 2016 Vladimír Štill <xstill@fi.muni.cz>
*/
/* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. */
#include <brick-except>
#include <brick-fs>
#include <brick-string>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <iostream>
#include <future>
#include <memory>
#if defined( __unix__ ) || defined( __divine__ )
#include <termios.h>
#include <unistd.h>
#include <signal.h>
#include <spawn.h>
#include <sys/wait.h>
#endif
#ifndef BRICK_PROC
#define BRICK_PROC
namespace brick {
namespace proc {
struct ProcError : brick::except::Error
{
using brick::except::Error::Error;
};
enum SpawnOptsEnum : unsigned {
None = 0,
CaptureStdout = 0x1,
CaptureStderr = 0x2,
ShowCmd = 0x100
};
struct SpawnOpts {
SpawnOpts( SpawnOptsEnum f ) : flags( f ) { }
SpawnOpts( unsigned f ) : flags( SpawnOptsEnum( f ) ) { }
explicit SpawnOpts( std::string in ) : hasStdin( true ), in( in ) { }
bool hasFlag( SpawnOptsEnum f ) const { return (flags & f) == f; }
bool hasStdin = false;
std::string in;
SpawnOptsEnum flags = None;
};
inline SpawnOpts StdinString( std::string in ) { return SpawnOpts( in ); }
inline SpawnOpts operator|( SpawnOpts a, SpawnOpts b ) {
a.flags = SpawnOptsEnum( a.flags | b.flags );
ASSERT( !(a.hasStdin && b.hasStdin) );
if ( b.hasStdin ) {
a.hasStdin = true;
a.in = std::move( b.in );
}
return a;
}
struct SystemOutput {
SystemOutput( int exitcode, int signal, std::string out, std::string err ) :
_exitcode( exitcode ), _signal( signal ), _out( out ), _err( err )
{ }
bool ok() const { return _exitcode == 0 && _signal == 0; }
explicit operator bool() const { return ok(); }
int exitcode() const { return _exitcode; }
int signal() const { return _signal; }
const std::string &out() const { return _out; }
const std::string &err() const { return _err; }
private:
int _exitcode;
int _signal;
std::string _out;
std::string _err;
};
inline namespace {
std::string to_string( const SystemOutput &o ) {
std::stringstream ss;
ss << "exitcode = " << o.exitcode() << ", signal = " << o.signal() << std::endl;
for ( auto x : { std::make_pair( "stdout", &o.out() ), std::make_pair( "stderr", &o.err() ) } ) {
if ( !x.second->empty() ) {
ss << x.first << ":" << std::endl;
std::stringstream data( *x.second );
std::string line;
while ( std::getline( ss, line ) )
ss << " " << line << std::endl;
ss << std::endl;
}
}
return ss.str();
}
}
struct Pipe {
Pipe() {
if ( ::pipe( _fds ) == -1 )
throw ProcError( "could not create pipe" );
}
~Pipe() { close(); }
void close() {
closeRead();
closeWrite();
}
void closeRead() {
int r = _fds[0];
_fds[0] = -1;
if ( r >= 0 )
::close( r );
}
void closeWrite() {
int w = _fds[1];
_fds[1] = -1;
if ( w >= 0 )
::close( w );
}
std::string drain() {
std::string str;
char data[ 1024 ];
long n;
do {
n = ::read( read(), data, sizeof( data ) );
if ( n > 0 )
str += std::string( data, n );
} while( n > 0 );
return str;
}
void push( std::string s ) {
const char *ptr = s.data();
const char *const end = ptr + s.size();
int r = 0;
while ( ptr < end && r >= 0 ) {
r = ::write( write(), ptr, end - ptr );
ptr += r;
}
}
int read() const { return _fds[0]; }
int write() const { return _fds[1]; }
#ifdef __unix__
void attachStdout() { ::dup2( write(), STDOUT_FILENO ); }
void attachStderr() { ::dup2( write(), STDERR_FILENO ); }
void attachStdin() { ::dup2( read(), STDIN_FILENO ); }
#else
#error attach* fuctions are not supporrted on this platfrom
#endif
private:
int _fds[2];
};
inline SystemOutput spawnAndWait( SpawnOpts opts, std::vector< std::string > args )
{
if ( opts.hasFlag( ShowCmd ) ) {
std::cerr << "+ ";
std::copy( args.begin(), args.end(), std::ostream_iterator< std::string >( std::cerr, " " ) );
std::cerr << std::endl;
}
std::vector< const char * > cargs;
std::transform( args.begin(), args.end(), std::back_inserter( cargs ),
[]( const std::string &s ) { return s.c_str(); } );
cargs.push_back( nullptr );
std::string out, err;
#ifdef __unix__
std::future< void > inf;
std::future< std::string > outf, errf;
std::unique_ptr< Pipe > inp, outp, errp;
if ( opts.hasStdin )
inp = std::make_unique< Pipe >();
if ( opts.hasFlag( CaptureStdout ) )
outp = std::make_unique< Pipe >();
if ( opts.hasFlag( CaptureStderr ) )
errp = std::make_unique< Pipe >();
pid_t pid;
if ( (pid = ::fork()) == 0 ) {
if ( inp ) {
inp->attachStdin();
inp->close();
}
if ( outp ) {
outp->attachStdout();
outp->close();
}
if ( errp ) {
errp->attachStderr();
errp->close();
}
::execvp( cargs[ 0 ], const_cast< char *const * >( cargs.data() ) );
std::terminate();
} else if ( pid > 0 ) {
if ( inp ) {
inp->closeRead();
inf = std::async( std::launch::async, [&] { inp->push( opts.in ); inp->close(); } );
}
if ( outp ) {
outp->closeWrite();
outf = std::async( std::launch::async, [&] { return outp->drain(); } );
}
if ( errp ) {
errp->closeWrite();
errf = std::async( std::launch::async, [&] { return errp->drain(); } );
}
int status;
int r = ::waitpid( pid, &status, 0 );
if ( inf.valid() )
inf.get();
out = outf.valid() ? outf.get() : "";
err = errf.valid() ? errf.get() : "";
if ( r < 0 )
throw ProcError( "waitpid error" );
return SystemOutput( WIFEXITED( status ) ? WEXITSTATUS( status ) : 0,
WIFSIGNALED( status ) ? WTERMSIG( status ) : 0,
out, err );
} else
throw ProcError( "fork failed" );
#else
#error implementation of brick::proc::spawnAndWait for this platform is missing
#endif
}
inline SystemOutput spawnAndWait( std::vector< std::string > args ) {
return spawnAndWait( None, args );
}
template< typename... Args >
SystemOutput spawnAndWait( SpawnOpts opts, Args &&...args ) {
return spawnAndWait( opts, std::vector< std::string >{ std::forward< Args >( args )... } );
}
template< typename... Args >
SystemOutput spawnAndWait( SpawnOptsEnum opts, Args &&...args ) {
return spawnAndWait( SpawnOpts( opts ), std::forward< Args >( args )... );
}
template< typename... Args >
SystemOutput spawnAndWait( unsigned opts, Args &&...args ) { // note: result of | on SpawnOptsEnum in unsigned
return spawnAndWait( SpawnOpts( SpawnOptsEnum( opts ) ), std::forward< Args >( args )... );
}
template< typename... Args >
SystemOutput spawnAndWait( Args &&...args ) {
return spawnAndWait( None, std::forward< Args >( args )... );
}
inline SystemOutput shellSpawnAndWait( SpawnOpts opts, std::string shellcmd ) {
#ifdef __unix__
return spawnAndWait( opts, "/bin/sh", "-c", shellcmd );
#else
#error shell spawn is not supported on this platform
#endif
}
inline SystemOutput shellSpawnAndWait( std::string shellcmd ) {
return shellSpawnAndWait( None, shellcmd );
}
struct XTerm
{
struct
{
int pid = 0;
int masterfd, slavefd;
std::unique_ptr< std::iostream > stream;
std::unique_ptr< brick::fs::PosixBuf > buf;
} _d;
struct SBuf : fs::PosixBuf
{
using fs::PosixBuf::PosixBuf;
int sync()
{
char tmp[ _buf_size * 2 ];
int i = 0;
for ( auto p = pbase(); p < pptr(); ++p )
{
if ( *p == '\n' )
tmp[ i++ ] = '\r';
tmp[ i++ ] = *p;
}
do_sync( tmp, i );
return 0;
}
};
void open()
{
_d.masterfd = posix_openpt( O_RDWR );
if ( grantpt( _d.masterfd ) )
throw std::system_error( errno, std::system_category(),
"Could not grantpt()." );
if ( unlockpt( _d.masterfd ) )
throw std::system_error( errno, std::system_category(),
"Could not unlockpt()." );
const char *slavepts = ptsname( _d.masterfd );
if ( !slavepts )
throw std::system_error( errno, std::system_category(),
"Could not ptsname()." );
_d.slavefd = ::open( slavepts, O_RDWR );
if ( _d.slavefd < 0 )
throw std::system_error( errno, std::system_category(),
"Could not open slave PTS." );
std::string slave = std::string( "-S" ) +
slavepts + "/" + brick::string::fmt( _d.slavefd );
const char *argv[] = { "xterm", slave.c_str(), nullptr };
posix_spawnp( &_d.pid, "xterm", nullptr, nullptr,
const_cast< char ** >( argv ), environ );
char buf[8];
::read( _d.masterfd, buf, 8 ); /* handshake */
struct termios tio;
tcgetattr( _d.slavefd, &tio );
tio.c_lflag = 0; /* no ECHO means we don't read things back */
tio.c_iflag = 0;
tio.c_oflag = 0;
tcsetattr( _d.slavefd, TCSANOW, &tio );
_d.buf.reset( new SBuf( _d.masterfd ) );
_d.stream.reset( new std::iostream( _d.buf.get() ) );
}
std::iostream &stream() { return *_d.stream; }
XTerm() = default;
XTerm( const XTerm & ) = delete;
XTerm( XTerm &&o )
{
_d = std::move( o._d );
o._d.pid = 0;
}
~XTerm()
{
if ( _d.pid )
{
kill( _d.pid, SIGTERM );
close( _d.masterfd );
close( _d.slavefd );
waitpid( _d.pid, nullptr, 0 );
}
_d.pid = 0;
}
};
}
namespace t_proc {
struct TestSpawn {
TEST( basic_true ) {
auto r = proc::spawnAndWait( "true" );
ASSERT_EQ( r.exitcode(), 0 );
ASSERT_EQ( r.signal(), 0 );
ASSERT( r );
}
TEST( basic_false ) {
auto r = proc::spawnAndWait( "false" );
ASSERT_LT( 0, r.exitcode() );
ASSERT_EQ( r.signal(), 0 );
ASSERT( !r );
}
TEST( echo1 ) {
auto r = proc::spawnAndWait( proc::CaptureStdout, "printf", "a" );
ASSERT( r );
ASSERT_EQ( r.out(), "a" );
ASSERT_EQ( r.err(), "" );
}
TEST( echo2 ) {
auto r = proc::spawnAndWait( proc::CaptureStdout | proc::CaptureStderr, "printf", "a" );
ASSERT( r );
ASSERT_EQ( r.out(), "a" );
ASSERT_EQ( r.err(), "" );
}
TEST( echoSpec ) {
auto r = proc::spawnAndWait( proc::CaptureStdout, "printf", "a\nb" );
ASSERT( r );
ASSERT_EQ( r.out(), "a\nb" );
ASSERT_EQ( r.err(), "" );
}
TEST( shellEchoStdout ) {
auto r = proc::shellSpawnAndWait( proc::CaptureStdout, "printf a" );
ASSERT( r );
ASSERT_EQ( r.out(), "a" );
ASSERT_EQ( r.err(), "" );
}
TEST( shellEchoStderr ) {
auto r = proc::shellSpawnAndWait( proc::CaptureStdout | proc::CaptureStderr, "printf a >&2" );
ASSERT( r );
ASSERT_EQ( r.out(), "" );
ASSERT_EQ( r.err(), "a" );
}
TEST( in_basic ) {
auto r = proc::spawnAndWait( proc::StdinString( "abcbd" ) | proc::CaptureStdout | proc::CaptureStderr,
"sed", "s/b/x/g" );
ASSERT( r );
ASSERT_EQ( r.out(), "axcxd" );
ASSERT_EQ( r.err(), "" );
}
TEST( in_lined ) {
auto r = proc::spawnAndWait( proc::StdinString( "abcbd\nebfg\n" ) | proc::CaptureStdout | proc::CaptureStderr,
"sed", "s/b/x/g" );
ASSERT( r );
ASSERT_EQ( r.out(), "axcxd\nexfg\n" );
ASSERT_EQ( r.err(), "" );
}
};
};
}
#endif // BRICK_PROC
// vim: syntax=cpp tabstop=4 shiftwidth=4 expandtab ft=cpp
| [
"vl.still@gmail.com"
] | vl.still@gmail.com | |
15dfe1d8325797dfadfc8a7beff984f408dbdb47 | 297497957c531d81ba286bc91253fbbb78b4d8be | /third_party/libwebrtc/video/encoder_rtcp_feedback.h | a1f629d357a3ec4c75413a4942d725e7b705677f | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | marco-c/gecko-dev-comments-removed | 7a9dd34045b07e6b22f0c636c0a836b9e639f9d3 | 61942784fb157763e65608e5a29b3729b0aa66fa | refs/heads/master | 2023-08-09T18:55:25.895853 | 2023-08-01T00:40:39 | 2023-08-01T00:40:39 | 211,297,481 | 0 | 0 | NOASSERTION | 2019-09-29T01:27:49 | 2019-09-27T10:44:24 | C++ | UTF-8 | C++ | false | false | 1,822 | h |
#ifndef VIDEO_ENCODER_RTCP_FEEDBACK_H_
#define VIDEO_ENCODER_RTCP_FEEDBACK_H_
#include <functional>
#include <vector>
#include "api/sequence_checker.h"
#include "api/units/time_delta.h"
#include "api/units/timestamp.h"
#include "call/rtp_video_sender_interface.h"
#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "rtc_base/system/no_unique_address.h"
#include "system_wrappers/include/clock.h"
#include "video/video_stream_encoder_interface.h"
namespace webrtc {
class VideoStreamEncoderInterface;
class EncoderRtcpFeedback : public RtcpIntraFrameObserver,
public RtcpLossNotificationObserver {
public:
EncoderRtcpFeedback(
Clock* clock,
const std::vector<uint32_t>& ssrcs,
VideoStreamEncoderInterface* encoder,
std::function<std::vector<RtpSequenceNumberMap::Info>(
uint32_t ssrc,
const std::vector<uint16_t>& seq_nums)> get_packet_infos);
~EncoderRtcpFeedback() override = default;
void OnReceivedIntraFrameRequest(uint32_t ssrc) override;
void OnReceivedLossNotification(uint32_t ssrc,
uint16_t seq_num_of_last_decodable,
uint16_t seq_num_of_last_received,
bool decodability_flag) override;
private:
Clock* const clock_;
const std::vector<uint32_t> ssrcs_;
const std::function<std::vector<RtpSequenceNumberMap::Info>(
uint32_t ssrc,
const std::vector<uint16_t>& seq_nums)>
get_packet_infos_;
VideoStreamEncoderInterface* const video_stream_encoder_;
RTC_NO_UNIQUE_ADDRESS SequenceChecker packet_delivery_queue_;
Timestamp time_last_packet_delivery_queue_
RTC_GUARDED_BY(packet_delivery_queue_);
const TimeDelta min_keyframe_send_interval_;
};
}
#endif
| [
"mcastelluccio@mozilla.com"
] | mcastelluccio@mozilla.com |
be2c0b6db862ce5969ee001cfc22aa790eb2ee64 | ac99de1e8713e7df268e1c5003ee4bf17e0ddb80 | /3/template/main.cpp | f0981d1f5936db7eb30657d435423c003876d0e4 | [] | no_license | ShigiDono/cg8 | dcf438f3021a6b3b6e9344e8252dce14209ae8f4 | e47630b16a2ccd89610b1190e877b04177d751d6 | refs/heads/master | 2016-09-03T07:21:01.816925 | 2013-06-02T06:31:55 | 2013-06-02T06:31:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,389 | cpp | #include "../../utils/utils.h"
#include <time.h>
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif//_USE_MATH_DEFINES
#include <math.h>
const unsigned int INTERVAL = 17;// 60 per sec
const unsigned int WIDTH = 800;
const unsigned int HEIGHT = 600;
//dirty hack
#define CLEAR_COLOR .1f, .1f, .1f, 1.0f
shader_t *main_shader;
model_t *triangle;
GLuint lightDir;
glm::vec3 light_vec = glm::vec3(1.0f);
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Use our shader
// 1rst attribute buffer : vertices
glm::mat4 model = glm::rotate(main_shader->view, 60.0f*clock()/CLOCKS_PER_SEC, glm::vec3(0.0, 1.0, 1.0));//60 degrees per sec
glUniform3f(lightDir, light_vec.x, light_vec.y, light_vec.z);
triangle->draw_indexed(model, GL_TRIANGLES, triangle->count);
/* main_shader->set_view_matrix(model);
main_shader->bind();
vertex_buffer->bind();
color_buffer->bind();
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle
glDisableVertexAttribArray(0);*/
// Swap buffers
glutSwapBuffers();
}
void update(int value) {
// Call update() again in 'interval' milliseconds
glutTimerFunc(INTERVAL, update, 0);
// Redisplay frame
glutPostRedisplay();
}
void mouse_motion(int x, int y) {
light_vec.x = 10.0f*(-0.5f + (float)x/WIDTH);
light_vec.y = -10.0f*(-0.5f + (float)y/HEIGHT);
light_vec.z = 1.0f;
}
void init() {
glClearColor(CLEAR_COLOR);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glViewport(0, 0, WIDTH, HEIGHT);
glm::mat4 projection = glm::perspectiveFov(45.0f, (float)WIDTH, (float)HEIGHT, .01f, 100.0f);
glm::mat4 view = glm::lookAt(glm::vec3(0, 0, 5), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0));
main_shader = new shader_t("shader.vs", "shader.fs");
main_shader->set_projection_matrix(projection);
main_shader->set_view_matrix(view);
lightDir = glGetUniformLocation(main_shader->program, "lightDir");
unsigned int sphere_vertical_segs = 30;
unsigned int sphere_radial_segs = 30;
float sphere_radius = 1.0f;
float r = sphere_radius;
std::vector<float> tmp_mesh;
std::vector<float> tmp_norm;
std::vector<float> tmp_colr;
std::vector<unsigned short> tmp_indx;
// sphere in radial coordinates
// may be optimized even more
for (int i = 0; i < sphere_vertical_segs; ++i) {
float y1 = cos(M_PI*i/sphere_vertical_segs);
float y2 = cos(M_PI*(i + 1)/sphere_vertical_segs);
float _y1 = sin(M_PI*i/sphere_vertical_segs);
float _y2 = sin(M_PI*(i + 1)/sphere_vertical_segs);
for (int j = 0; j < sphere_radial_segs; ++j) {
float x1 = cos(2*M_PI*j/sphere_radial_segs);
float x2 = cos(2*M_PI*(j + 1)/sphere_radial_segs);
float z1 = sin(2*M_PI*j/sphere_radial_segs);
float z2 = sin(2*M_PI*(j + 1)/sphere_radial_segs);
unsigned int index_offset = (i*sphere_radial_segs + j)*4;
tmp_mesh.push_back(r*_y1*x1); tmp_mesh.push_back(r*y1); tmp_mesh.push_back(r*_y1*z1);
tmp_norm.push_back(_y1*x1); tmp_norm.push_back(y1); tmp_norm.push_back(_y1*z1);
tmp_mesh.push_back(r*_y1*x2); tmp_mesh.push_back(r*y1); tmp_mesh.push_back(r*_y1*z2);
tmp_norm.push_back(_y1*x2); tmp_norm.push_back(y1); tmp_norm.push_back(_y1*z2);
tmp_mesh.push_back(r*_y2*x1); tmp_mesh.push_back(r*y2); tmp_mesh.push_back(r*_y2*z1);
tmp_norm.push_back(_y2*x1); tmp_norm.push_back(y2); tmp_norm.push_back(_y2*z1);
tmp_mesh.push_back(r*_y2*x2); tmp_mesh.push_back(r*y2); tmp_mesh.push_back(r*_y2*z2);
tmp_norm.push_back(_y2*x2); tmp_norm.push_back(y2); tmp_norm.push_back(_y2*z2);
tmp_indx.push_back(index_offset + 0);
tmp_indx.push_back(index_offset + 1);
tmp_indx.push_back(index_offset + 3);
tmp_indx.push_back(index_offset + 0);
tmp_indx.push_back(index_offset + 2);
tmp_indx.push_back(index_offset + 3);
}
}
buffer_t *vertex_buffer = new buffer_t(0, &tmp_mesh[0], tmp_mesh.size());
buffer_t *norm_buffer = new buffer_t(1, &tmp_norm[0], tmp_norm.size());
buffer_t *indx_buffer = new buffer_t(&tmp_indx[0], tmp_indx.size());
triangle = new model_t(main_shader);
triangle->buffers.push_back(indx_buffer);
triangle->buffers.push_back(vertex_buffer);
triangle->buffers.push_back(norm_buffer);
triangle->count = tmp_indx.size();
}
int main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(WIDTH, HEIGHT);
//glutInitWindowPosition (100, 100);
glutCreateWindow("3rd task");
GLenum err = glewInit();
if (err != GLEW_OK)
exit(1); // or handle the error in a nicer way
if (!GLEW_VERSION_3_0) // check that the machine supports the 2.1 API.
exit(1); // or handle the error in a nicer way
init ();
glutDisplayFunc(display);
glutPassiveMotionFunc(mouse_motion);
glutMotionFunc(mouse_motion);
glutTimerFunc(INTERVAL, update, 0);
glutMainLoop();
delete main_shader;
delete triangle;
//delete vertex_buffer;
//delete color_buffer;
return 0; /* ISO C requires main to return int. */
} | [
"shigidono@gmail.com"
] | shigidono@gmail.com |
cd3791adba31ab5fd996756318d99bafea582d7b | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /Graphs/2461.cpp | 8d2d523cfec626e40d3b27b722a5535bccb665b0 | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 706 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#define N 1000000
#define INF 100000000000000
#define MOD 1000000007
#define LL long long int
using namespace std;
vector<int> g[N];
int col[N],ANS=0;
void dfs(int node,int prnt,int currcol) {
if (col[node]!=currcol) {
ANS++;
currcol=col[node];
}
for (auto it:g[node]) if (it!=prnt) {
dfs(it,node,currcol);
}
}
int main() {
int n,i,reach=0,m,x,y;
cin >> n;
for (i=2;i<=n;i++) {
cin >> x;
g[x].push_back(i);
g[i].push_back(x);
}
for (i=1;i<=n;i++) cin >> col[i];
dfs(1,-1,0);
cout << ANS << '\n';
return 0;
}
| [
"mukeshchugani10@gmail.com"
] | mukeshchugani10@gmail.com |
dd2ee6bd367082dc05c1631ccaf08d46b8aa6821 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/webrtc/modules/audio_processing/aec3/suppression_gain_unittest.cc | 02de706c776478d17f365fe82ac263995716e421 | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-google-patent-license-webrtc",
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 6,079 | cc | /*
* Copyright (c) 2017 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/audio_processing/aec3/suppression_gain.h"
#include "modules/audio_processing/aec3/aec_state.h"
#include "modules/audio_processing/aec3/render_delay_buffer.h"
#include "modules/audio_processing/aec3/subtractor.h"
#include "modules/audio_processing/aec3/subtractor_output.h"
#include "modules/audio_processing/logging/apm_data_dumper.h"
#include "rtc_base/checks.h"
#include "system_wrappers/include/cpu_features_wrapper.h"
#include "test/gtest.h"
namespace webrtc {
namespace aec3 {
#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
// Verifies that the check for non-null output gains works.
TEST(SuppressionGainDeathTest, NullOutputGains) {
std::vector<std::array<float, kFftLengthBy2Plus1>> E2(1, {0.0f});
std::vector<std::array<float, kFftLengthBy2Plus1>> R2(1, {0.0f});
std::vector<std::array<float, kFftLengthBy2Plus1>> R2_unbounded(1, {0.0f});
std::vector<std::array<float, kFftLengthBy2Plus1>> S2(1);
std::vector<std::array<float, kFftLengthBy2Plus1>> N2(1, {0.0f});
for (auto& S2_k : S2) {
S2_k.fill(0.1f);
}
FftData E;
FftData Y;
E.re.fill(0.0f);
E.im.fill(0.0f);
Y.re.fill(0.0f);
Y.im.fill(0.0f);
float high_bands_gain;
AecState aec_state(EchoCanceller3Config{}, 1);
EXPECT_DEATH(
SuppressionGain(EchoCanceller3Config{}, DetectOptimization(), 16000, 1)
.GetGain(E2, S2, R2, R2_unbounded, N2,
RenderSignalAnalyzer((EchoCanceller3Config{})), aec_state,
Block(3, 1), false, &high_bands_gain, nullptr),
"");
}
#endif
// Does a sanity check that the gains are correctly computed.
TEST(SuppressionGain, BasicGainComputation) {
constexpr size_t kNumRenderChannels = 1;
constexpr size_t kNumCaptureChannels = 2;
constexpr int kSampleRateHz = 16000;
constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz);
SuppressionGain suppression_gain(EchoCanceller3Config(), DetectOptimization(),
kSampleRateHz, kNumCaptureChannels);
RenderSignalAnalyzer analyzer(EchoCanceller3Config{});
float high_bands_gain;
std::vector<std::array<float, kFftLengthBy2Plus1>> E2(kNumCaptureChannels);
std::vector<std::array<float, kFftLengthBy2Plus1>> S2(kNumCaptureChannels,
{0.0f});
std::vector<std::array<float, kFftLengthBy2Plus1>> Y2(kNumCaptureChannels);
std::vector<std::array<float, kFftLengthBy2Plus1>> R2(kNumCaptureChannels);
std::vector<std::array<float, kFftLengthBy2Plus1>> R2_unbounded(
kNumCaptureChannels);
std::vector<std::array<float, kFftLengthBy2Plus1>> N2(kNumCaptureChannels);
std::array<float, kFftLengthBy2Plus1> g;
std::vector<SubtractorOutput> output(kNumCaptureChannels);
Block x(kNumBands, kNumRenderChannels);
EchoCanceller3Config config;
AecState aec_state(config, kNumCaptureChannels);
ApmDataDumper data_dumper(42);
Subtractor subtractor(config, kNumRenderChannels, kNumCaptureChannels,
&data_dumper, DetectOptimization());
std::unique_ptr<RenderDelayBuffer> render_delay_buffer(
RenderDelayBuffer::Create(config, kSampleRateHz, kNumRenderChannels));
absl::optional<DelayEstimate> delay_estimate;
// Ensure that a strong noise is detected to mask any echoes.
for (size_t ch = 0; ch < kNumCaptureChannels; ++ch) {
E2[ch].fill(10.f);
Y2[ch].fill(10.f);
R2[ch].fill(0.1f);
R2_unbounded[ch].fill(0.1f);
N2[ch].fill(100.0f);
}
for (auto& subtractor_output : output) {
subtractor_output.Reset();
}
// Ensure that the gain is no longer forced to zero.
for (int k = 0; k <= kNumBlocksPerSecond / 5 + 1; ++k) {
aec_state.Update(delay_estimate, subtractor.FilterFrequencyResponses(),
subtractor.FilterImpulseResponses(),
*render_delay_buffer->GetRenderBuffer(), E2, Y2, output);
}
for (int k = 0; k < 100; ++k) {
aec_state.Update(delay_estimate, subtractor.FilterFrequencyResponses(),
subtractor.FilterImpulseResponses(),
*render_delay_buffer->GetRenderBuffer(), E2, Y2, output);
suppression_gain.GetGain(E2, S2, R2, R2_unbounded, N2, analyzer, aec_state,
x, false, &high_bands_gain, &g);
}
std::for_each(g.begin(), g.end(),
[](float a) { EXPECT_NEAR(1.0f, a, 0.001f); });
// Ensure that a strong nearend is detected to mask any echoes.
for (size_t ch = 0; ch < kNumCaptureChannels; ++ch) {
E2[ch].fill(100.f);
Y2[ch].fill(100.f);
R2[ch].fill(0.1f);
R2_unbounded[ch].fill(0.1f);
S2[ch].fill(0.1f);
N2[ch].fill(0.f);
}
for (int k = 0; k < 100; ++k) {
aec_state.Update(delay_estimate, subtractor.FilterFrequencyResponses(),
subtractor.FilterImpulseResponses(),
*render_delay_buffer->GetRenderBuffer(), E2, Y2, output);
suppression_gain.GetGain(E2, S2, R2, R2_unbounded, N2, analyzer, aec_state,
x, false, &high_bands_gain, &g);
}
std::for_each(g.begin(), g.end(),
[](float a) { EXPECT_NEAR(1.0f, a, 0.001f); });
// Add a strong echo to one of the channels and ensure that it is suppressed.
E2[1].fill(1000000000.0f);
R2[1].fill(10000000000000.0f);
R2_unbounded[1].fill(10000000000000.0f);
for (int k = 0; k < 10; ++k) {
suppression_gain.GetGain(E2, S2, R2, R2_unbounded, N2, analyzer, aec_state,
x, false, &high_bands_gain, &g);
}
std::for_each(g.begin(), g.end(),
[](float a) { EXPECT_NEAR(0.0f, a, 0.001f); });
}
} // namespace aec3
} // namespace webrtc
| [
"jengelh@inai.de"
] | jengelh@inai.de |
d45b39f1e5fd488594a0b2d17aaf236f3021bd6a | 30ae14d3cfdb321fcf1c417ea91ee685b5c2e308 | /Assets/Plugins/iOS/FileList.cpp | 8503cf1a8d5af701ce84f6e5f2223843de5a1cef | [] | no_license | p0e0o0p0l0e0/shenyuclient | 04224b55e51b2c06cde6b31640c284b253a0c492 | c2c0024a315185561f876720f45217f8c361af9d | refs/heads/master | 2020-04-06T17:56:48.213551 | 2018-04-27T09:28:02 | 2018-04-27T09:28:02 | 157,679,186 | 1 | 0 | null | 2018-11-15T08:41:27 | 2018-11-15T08:41:27 | null | UTF-8 | C++ | false | false | 23,514 | cpp | /*
* Copyright (c) 2014, Oculus VR, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "FileList.h"
#if _RAKNET_SUPPORT_FileOperations==1
#include <stdio.h> // RAKNET_DEBUG_PRINTF
#include "RakAssert.h"
#if defined(ANDROID)
#elif defined(_WIN32) || defined(__CYGWIN__)
#include <io.h>
#elif !defined ( __APPLE__ ) && !defined ( __APPLE_CC__ ) && !defined ( __PPC__ ) && !defined ( __FreeBSD__ ) && !defined ( __S3E__ )
#include <sys/io.h>
#endif
#ifdef _WIN32
// For mkdir
#include <direct.h>
#else
#include <sys/stat.h>
#endif
//#include "DR_SHA1.h"
#include "DS_Queue.h"
#include "StringCompressor.h"
#include "BitStream.h"
#include "FileOperations.h"
#include "SuperFastHash.h"
#include "RakAssert.h"
#include "LinuxStrings.h"
#define MAX_FILENAME_LENGTH 512
static const unsigned HASH_LENGTH=4;
using namespace RakNet;
// alloca
#if defined(_WIN32)
#include <malloc.h>
#else
#if !defined ( __FreeBSD__ )
#include <alloca.h>
#endif
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include "_FindFirst.h"
#include <stdint.h> //defines intptr_t
#endif
#include "RakAlloca.h"
//int RAK_DLL_EXPORT FileListNodeComp( char * const &key, const FileListNode &data )
//{
// return strcmp(key, data.filename);
//}
STATIC_FACTORY_DEFINITIONS(FileListProgress,FileListProgress)
STATIC_FACTORY_DEFINITIONS(FLP_Printf,FLP_Printf)
STATIC_FACTORY_DEFINITIONS(FileList,FileList)
#ifdef _MSC_VER
#pragma warning( push )
#endif
/// First callback called when FileList::AddFilesFromDirectory() starts
void FLP_Printf::OnAddFilesFromDirectoryStarted(FileList *fileList, char *dir) {
(void) fileList;
RAKNET_DEBUG_PRINTF("Adding files from directory %s\n",dir);}
/// Called for each directory, when that directory begins processing
void FLP_Printf::OnDirectory(FileList *fileList, char *dir, unsigned int directoriesRemaining) {
(void) fileList;
RAKNET_DEBUG_PRINTF("Adding %s. %i remaining.\n", dir, directoriesRemaining);}
void FLP_Printf::OnFilePushesComplete( SystemAddress systemAddress, unsigned short setID )
{
(void) setID;
char str[32];
systemAddress.ToString(true, (char*) str);
RAKNET_DEBUG_PRINTF("File pushes complete to %s\n", str);
}
void FLP_Printf::OnSendAborted( SystemAddress systemAddress )
{
char str[32];
systemAddress.ToString(true, (char*) str);
RAKNET_DEBUG_PRINTF("Send aborted to %s\n", str);
}
FileList::FileList()
{
}
FileList::~FileList()
{
Clear();
}
void FileList::AddFile(const char *filepath, const char *filename, FileListNodeContext context)
{
if (filepath==0 || filename==0)
return;
char *data;
//std::fstream file;
//file.open(filename, std::ios::in | std::ios::binary);
FILE *fp = fopen(filepath, "rb");
if (fp==0)
return;
fseek(fp, 0, SEEK_END);
int length = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (length > (int) ((unsigned int)-1 / 8))
{
// If this assert hits, split up your file. You could also change BitSize_t in RakNetTypes.h to unsigned long long but this is not recommended for performance reasons
RakAssert("Cannot add files over 536 MB" && 0);
fclose(fp);
return;
}
#if USE_ALLOCA==1
bool usedAlloca=false;
if (length < MAX_ALLOCA_STACK_ALLOCATION)
{
data = ( char* ) alloca( length );
usedAlloca=true;
}
else
#endif
{
data = (char*) rakMalloc_Ex( length, _FILE_AND_LINE_ );
RakAssert(data);
}
fread(data, 1, length, fp);
AddFile(filename, filepath, data, length, length, context);
fclose(fp);
#if USE_ALLOCA==1
if (usedAlloca==false)
#endif
rakFree_Ex(data, _FILE_AND_LINE_ );
}
void FileList::AddFile(const char *filename, const char *fullPathToFile, const char *data, const unsigned dataLength, const unsigned fileLength, FileListNodeContext context, bool isAReference, bool takeDataPointer)
{
if (filename==0)
return;
if (strlen(filename)>MAX_FILENAME_LENGTH)
{
// Should be enough for anyone
RakAssert(0);
return;
}
// If adding a reference, do not send data
RakAssert(isAReference==false || data==0);
// Avoid duplicate insertions unless the data is different, in which case overwrite the old data
unsigned i;
for (i=0; i<fileList.Size();i++)
{
if (strcmp(fileList[i].filename, filename)==0)
{
if (fileList[i].fileLengthBytes==fileLength && fileList[i].dataLengthBytes==dataLength &&
(dataLength==0 || fileList[i].data==0 ||
memcmp(fileList[i].data, data, dataLength)==0
))
// Exact same file already here
return;
// File of the same name, but different contents, so overwrite
rakFree_Ex(fileList[i].data, _FILE_AND_LINE_ );
fileList.RemoveAtIndex(i);
break;
}
}
FileListNode n;
// size_t fileNameLen = strlen(filename);
if (dataLength && data)
{
if (takeDataPointer)
{
n.data=(char*) data;
}
else
{
n.data=(char*) rakMalloc_Ex( dataLength, _FILE_AND_LINE_ );
RakAssert(n.data);
memcpy(n.data, data, dataLength);
}
}
else
n.data=0;
n.dataLengthBytes=dataLength;
n.fileLengthBytes=fileLength;
n.isAReference=isAReference;
n.context=context;
if (n.context.dataPtr==0)
n.context.dataPtr=n.data;
if (n.context.dataLength==0)
n.context.dataLength=dataLength;
n.filename=filename;
n.fullPathToFile=fullPathToFile;
fileList.Insert(n, _FILE_AND_LINE_);
}
void FileList::AddFilesFromDirectory(const char *applicationDirectory, const char *subDirectory, bool writeHash, bool writeData, bool recursive, FileListNodeContext context)
{
DataStructures::Queue<char*> dirList;
char root[260];
char fullPath[520];
_finddata_t fileInfo;
intptr_t dir;
FILE *fp;
char *dirSoFar, *fileData;
dirSoFar=(char*) rakMalloc_Ex( 520, _FILE_AND_LINE_ );
RakAssert(dirSoFar);
if (applicationDirectory)
strcpy(root, applicationDirectory);
else
root[0]=0;
int rootLen=(int)strlen(root);
if (rootLen)
{
strcpy(dirSoFar, root);
if (FixEndingSlash(dirSoFar))
rootLen++;
}
else
dirSoFar[0]=0;
if (subDirectory)
{
strcat(dirSoFar, subDirectory);
FixEndingSlash(dirSoFar);
}
for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++)
fileListProgressCallbacks[flpcIndex]->OnAddFilesFromDirectoryStarted(this, dirSoFar);
// RAKNET_DEBUG_PRINTF("Adding files from directory %s\n",dirSoFar);
dirList.Push(dirSoFar, _FILE_AND_LINE_ );
while (dirList.Size())
{
dirSoFar=dirList.Pop();
strcpy(fullPath, dirSoFar);
// Changed from *.* to * for Linux compatibility
strcat(fullPath, "*");
dir=_findfirst(fullPath, &fileInfo );
if (dir==-1)
{
_findclose(dir);
rakFree_Ex(dirSoFar, _FILE_AND_LINE_ );
unsigned i;
for (i=0; i < dirList.Size(); i++)
rakFree_Ex(dirList[i], _FILE_AND_LINE_ );
return;
}
// RAKNET_DEBUG_PRINTF("Adding %s. %i remaining.\n", fullPath, dirList.Size());
for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++)
fileListProgressCallbacks[flpcIndex]->OnDirectory(this, fullPath, dirList.Size());
do
{
// no guarantee these entries are first...
if (strcmp("." , fileInfo.name) == 0 ||
strcmp("..", fileInfo.name) == 0)
{
continue;
}
if ((fileInfo.attrib & (_A_HIDDEN | _A_SUBDIR | _A_SYSTEM))==0)
{
strcpy(fullPath, dirSoFar);
strcat(fullPath, fileInfo.name);
fileData=0;
for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++)
fileListProgressCallbacks[flpcIndex]->OnFile(this, dirSoFar, fileInfo.name, fileInfo.size);
if (writeData && writeHash)
{
fp = fopen(fullPath, "rb");
if (fp)
{
fileData= (char*) rakMalloc_Ex( fileInfo.size+HASH_LENGTH, _FILE_AND_LINE_ );
RakAssert(fileData);
fread(fileData+HASH_LENGTH, fileInfo.size, 1, fp);
fclose(fp);
unsigned int hash = SuperFastHash(fileData+HASH_LENGTH, fileInfo.size);
if (RakNet::BitStream::DoEndianSwap())
RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash));
memcpy(fileData, &hash, HASH_LENGTH);
// sha1.Reset();
// sha1.Update( ( unsigned char* ) fileData+HASH_LENGTH, fileInfo.size );
// sha1.Final();
// memcpy(fileData, sha1.GetHash(), HASH_LENGTH);
// File data and hash
AddFile((const char*)fullPath+rootLen, fullPath, fileData, fileInfo.size+HASH_LENGTH, fileInfo.size, context);
}
}
else if (writeHash)
{
// sha1.Reset();
// DR_SHA1.hashFile((char*)fullPath);
// sha1.Final();
unsigned int hash = SuperFastHashFile(fullPath);
if (RakNet::BitStream::DoEndianSwap())
RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash));
// Hash only
// AddFile((const char*)fullPath+rootLen, (const char*)sha1.GetHash(), HASH_LENGTH, fileInfo.size, context);
AddFile((const char*)fullPath+rootLen, fullPath, (const char*)&hash, HASH_LENGTH, fileInfo.size, context);
}
else if (writeData)
{
fileData= (char*) rakMalloc_Ex( fileInfo.size, _FILE_AND_LINE_ );
RakAssert(fileData);
fp = fopen(fullPath, "rb");
fread(fileData, fileInfo.size, 1, fp);
fclose(fp);
// File data only
AddFile(fullPath+rootLen, fullPath, fileData, fileInfo.size, fileInfo.size, context);
}
else
{
// Just the filename
AddFile(fullPath+rootLen, fullPath, 0, 0, fileInfo.size, context);
}
if (fileData)
rakFree_Ex(fileData, _FILE_AND_LINE_ );
}
else if ((fileInfo.attrib & _A_SUBDIR) && (fileInfo.attrib & (_A_HIDDEN | _A_SYSTEM))==0 && recursive)
{
char *newDir=(char*) rakMalloc_Ex( 520, _FILE_AND_LINE_ );
RakAssert(newDir);
strcpy(newDir, dirSoFar);
strcat(newDir, fileInfo.name);
strcat(newDir, "/");
dirList.Push(newDir, _FILE_AND_LINE_ );
}
} while (_findnext(dir, &fileInfo ) != -1);
_findclose(dir);
rakFree_Ex(dirSoFar, _FILE_AND_LINE_ );
}
}
void FileList::Clear(void)
{
unsigned i;
for (i=0; i<fileList.Size(); i++)
{
rakFree_Ex(fileList[i].data, _FILE_AND_LINE_ );
}
fileList.Clear(false, _FILE_AND_LINE_);
}
void FileList::Serialize(RakNet::BitStream *outBitStream)
{
outBitStream->WriteCompressed(fileList.Size());
unsigned i;
for (i=0; i < fileList.Size(); i++)
{
outBitStream->WriteCompressed(fileList[i].context.op);
outBitStream->WriteCompressed(fileList[i].context.flnc_extraData1);
outBitStream->WriteCompressed(fileList[i].context.flnc_extraData2);
StringCompressor::Instance()->EncodeString(fileList[i].filename.C_String(), MAX_FILENAME_LENGTH, outBitStream);
bool writeFileData = (fileList[i].dataLengthBytes>0)==true;
outBitStream->Write(writeFileData);
if (writeFileData)
{
outBitStream->WriteCompressed(fileList[i].dataLengthBytes);
outBitStream->Write(fileList[i].data, fileList[i].dataLengthBytes);
}
outBitStream->Write((bool)(fileList[i].fileLengthBytes==fileList[i].dataLengthBytes));
if (fileList[i].fileLengthBytes!=fileList[i].dataLengthBytes)
outBitStream->WriteCompressed(fileList[i].fileLengthBytes);
}
}
bool FileList::Deserialize(RakNet::BitStream *inBitStream)
{
bool b, dataLenNonZero=false, fileLenMatchesDataLen=false;
char filename[512];
uint32_t fileListSize;
FileListNode n;
b=inBitStream->ReadCompressed(fileListSize);
#ifdef _DEBUG
RakAssert(b);
RakAssert(fileListSize < 10000);
#endif
if (b==false || fileListSize > 10000)
return false; // Sanity check
Clear();
unsigned i;
for (i=0; i < fileListSize; i++)
{
inBitStream->ReadCompressed(n.context.op);
inBitStream->ReadCompressed(n.context.flnc_extraData1);
inBitStream->ReadCompressed(n.context.flnc_extraData2);
StringCompressor::Instance()->DecodeString((char*)filename, MAX_FILENAME_LENGTH, inBitStream);
inBitStream->Read(dataLenNonZero);
if (dataLenNonZero)
{
inBitStream->ReadCompressed(n.dataLengthBytes);
// sanity check
if (n.dataLengthBytes>2000000000)
{
#ifdef _DEBUG
RakAssert(n.dataLengthBytes<=2000000000);
#endif
return false;
}
n.data=(char*) rakMalloc_Ex( (size_t) n.dataLengthBytes, _FILE_AND_LINE_ );
RakAssert(n.data);
inBitStream->Read(n.data, n.dataLengthBytes);
}
else
{
n.dataLengthBytes=0;
n.data=0;
}
b=inBitStream->Read(fileLenMatchesDataLen);
if (fileLenMatchesDataLen)
n.fileLengthBytes=(unsigned) n.dataLengthBytes;
else
b=inBitStream->ReadCompressed(n.fileLengthBytes);
#ifdef _DEBUG
RakAssert(b);
#endif
if (b==0)
{
Clear();
return false;
}
n.filename=filename;
n.fullPathToFile=filename;
fileList.Insert(n, _FILE_AND_LINE_);
}
return true;
}
void FileList::GetDeltaToCurrent(FileList *input, FileList *output, const char *dirSubset, const char *remoteSubdir)
{
// For all files in this list that do not match the input list, write them to the output list.
// dirSubset allows checking only a portion of the files in this list.
unsigned thisIndex, inputIndex;
unsigned dirSubsetLen, localPathLen, remoteSubdirLen;
bool match;
if (dirSubset)
dirSubsetLen = (unsigned int) strlen(dirSubset);
else
dirSubsetLen = 0;
if (remoteSubdir && remoteSubdir[0])
{
remoteSubdirLen=(unsigned int) strlen(remoteSubdir);
if (IsSlash(remoteSubdir[remoteSubdirLen-1]))
remoteSubdirLen--;
}
else
remoteSubdirLen=0;
for (thisIndex=0; thisIndex < fileList.Size(); thisIndex++)
{
localPathLen = (unsigned int) fileList[thisIndex].filename.GetLength();
while (localPathLen>0)
{
if (IsSlash(fileList[thisIndex].filename[localPathLen-1]))
{
localPathLen--;
break;
}
localPathLen--;
}
// fileList[thisIndex].filename has to match dirSubset and be shorter or equal to it in length.
if (dirSubsetLen>0 &&
(localPathLen<dirSubsetLen ||
_strnicmp(fileList[thisIndex].filename.C_String(), dirSubset, dirSubsetLen)!=0 ||
(localPathLen>dirSubsetLen && IsSlash(fileList[thisIndex].filename[dirSubsetLen])==false)))
continue;
match=false;
for (inputIndex=0; inputIndex < input->fileList.Size(); inputIndex++)
{
// If the filenames, hashes, and lengths match then skip this element in fileList. Otherwise write it to output
if (_stricmp(input->fileList[inputIndex].filename.C_String()+remoteSubdirLen,fileList[thisIndex].filename.C_String()+dirSubsetLen)==0)
{
match=true;
if (input->fileList[inputIndex].fileLengthBytes==fileList[thisIndex].fileLengthBytes &&
input->fileList[inputIndex].dataLengthBytes==fileList[thisIndex].dataLengthBytes &&
memcmp(input->fileList[inputIndex].data,fileList[thisIndex].data,(size_t) fileList[thisIndex].dataLengthBytes)==0)
{
// File exists on both machines and is the same.
break;
}
else
{
// File exists on both machines and is not the same.
output->AddFile(fileList[thisIndex].filename, fileList[thisIndex].fullPathToFile, 0,0, fileList[thisIndex].fileLengthBytes, FileListNodeContext(0,0,0,0), false);
break;
}
}
}
if (match==false)
{
// Other system does not have the file at all
output->AddFile(fileList[thisIndex].filename, fileList[thisIndex].fullPathToFile, 0,0, fileList[thisIndex].fileLengthBytes, FileListNodeContext(0,0,0,0), false);
}
}
}
void FileList::ListMissingOrChangedFiles(const char *applicationDirectory, FileList *missingOrChangedFiles, bool alwaysWriteHash, bool neverWriteHash)
{
unsigned fileLength;
// CSHA1 sha1;
FILE *fp;
char fullPath[512];
unsigned i;
// char *fileData;
for (i=0; i < fileList.Size(); i++)
{
strcpy(fullPath, applicationDirectory);
FixEndingSlash(fullPath);
strcat(fullPath,fileList[i].filename);
fp=fopen(fullPath, "rb");
if (fp==0)
{
missingOrChangedFiles->AddFile(fileList[i].filename, fileList[i].fullPathToFile, 0, 0, 0, FileListNodeContext(0,0,0,0), false);
}
else
{
fseek(fp, 0, SEEK_END);
fileLength = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (fileLength != fileList[i].fileLengthBytes && alwaysWriteHash==false)
{
missingOrChangedFiles->AddFile(fileList[i].filename, fileList[i].fullPathToFile, 0, 0, fileLength, FileListNodeContext(0,0,0,0), false);
}
else
{
// fileData= (char*) rakMalloc_Ex( fileLength, _FILE_AND_LINE_ );
// fread(fileData, fileLength, 1, fp);
// sha1.Reset();
// sha1.Update( ( unsigned char* ) fileData, fileLength );
// sha1.Final();
// rakFree_Ex(fileData, _FILE_AND_LINE_ );
unsigned int hash = SuperFastHashFilePtr(fp);
if (RakNet::BitStream::DoEndianSwap())
RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash));
//if (fileLength != fileList[i].fileLength || memcmp( sha1.GetHash(), fileList[i].data, HASH_LENGTH)!=0)
if (fileLength != fileList[i].fileLengthBytes || memcmp( &hash, fileList[i].data, HASH_LENGTH)!=0)
{
if (neverWriteHash==false)
// missingOrChangedFiles->AddFile((const char*)fileList[i].filename, (const char*)sha1.GetHash(), HASH_LENGTH, fileLength, 0);
missingOrChangedFiles->AddFile((const char*)fileList[i].filename, (const char*)fileList[i].fullPathToFile, (const char *) &hash, HASH_LENGTH, fileLength, FileListNodeContext(0,0,0,0), false);
else
missingOrChangedFiles->AddFile((const char*)fileList[i].filename, (const char*)fileList[i].fullPathToFile, 0, 0, fileLength, FileListNodeContext(0,0,0,0), false);
}
}
fclose(fp);
}
}
}
void FileList::PopulateDataFromDisk(const char *applicationDirectory, bool writeFileData, bool writeFileHash, bool removeUnknownFiles)
{
FILE *fp;
char fullPath[512];
unsigned i;
// CSHA1 sha1;
i=0;
while (i < fileList.Size())
{
rakFree_Ex(fileList[i].data, _FILE_AND_LINE_ );
strcpy(fullPath, applicationDirectory);
FixEndingSlash(fullPath);
strcat(fullPath,fileList[i].filename.C_String());
fp=fopen(fullPath, "rb");
if (fp)
{
if (writeFileHash || writeFileData)
{
fseek(fp, 0, SEEK_END);
fileList[i].fileLengthBytes = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (writeFileHash)
{
if (writeFileData)
{
// Hash + data so offset the data by HASH_LENGTH
fileList[i].data=(char*) rakMalloc_Ex( fileList[i].fileLengthBytes+HASH_LENGTH, _FILE_AND_LINE_ );
RakAssert(fileList[i].data);
fread(fileList[i].data+HASH_LENGTH, fileList[i].fileLengthBytes, 1, fp);
// sha1.Reset();
// sha1.Update((unsigned char*)fileList[i].data+HASH_LENGTH, fileList[i].fileLength);
// sha1.Final();
unsigned int hash = SuperFastHash(fileList[i].data+HASH_LENGTH, fileList[i].fileLengthBytes);
if (RakNet::BitStream::DoEndianSwap())
RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash));
// memcpy(fileList[i].data, sha1.GetHash(), HASH_LENGTH);
memcpy(fileList[i].data, &hash, HASH_LENGTH);
}
else
{
// Hash only
fileList[i].dataLengthBytes=HASH_LENGTH;
if (fileList[i].fileLengthBytes < HASH_LENGTH)
fileList[i].data=(char*) rakMalloc_Ex( HASH_LENGTH, _FILE_AND_LINE_ );
else
fileList[i].data=(char*) rakMalloc_Ex( fileList[i].fileLengthBytes, _FILE_AND_LINE_ );
RakAssert(fileList[i].data);
fread(fileList[i].data, fileList[i].fileLengthBytes, 1, fp);
// sha1.Reset();
// sha1.Update((unsigned char*)fileList[i].data, fileList[i].fileLength);
// sha1.Final();
unsigned int hash = SuperFastHash(fileList[i].data, fileList[i].fileLengthBytes);
if (RakNet::BitStream::DoEndianSwap())
RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash));
// memcpy(fileList[i].data, sha1.GetHash(), HASH_LENGTH);
memcpy(fileList[i].data, &hash, HASH_LENGTH);
}
}
else
{
// Data only
fileList[i].dataLengthBytes=fileList[i].fileLengthBytes;
fileList[i].data=(char*) rakMalloc_Ex( fileList[i].fileLengthBytes, _FILE_AND_LINE_ );
RakAssert(fileList[i].data);
fread(fileList[i].data, fileList[i].fileLengthBytes, 1, fp);
}
fclose(fp);
i++;
}
else
{
fileList[i].data=0;
fileList[i].dataLengthBytes=0;
}
}
else
{
if (removeUnknownFiles)
{
fileList.RemoveAtIndex(i);
}
else
i++;
}
}
}
void FileList::FlagFilesAsReferences(void)
{
for (unsigned int i=0; i < fileList.Size(); i++)
{
fileList[i].isAReference=true;
fileList[i].dataLengthBytes=fileList[i].fileLengthBytes;
}
}
void FileList::WriteDataToDisk(const char *applicationDirectory)
{
char fullPath[512];
unsigned i,j;
for (i=0; i < fileList.Size(); i++)
{
strcpy(fullPath, applicationDirectory);
FixEndingSlash(fullPath);
strcat(fullPath,fileList[i].filename.C_String());
// Security - Don't allow .. in the filename anywhere so you can't write outside of the root directory
for (j=1; j < fileList[i].filename.GetLength(); j++)
{
if (fileList[i].filename[j]=='.' && fileList[i].filename[j-1]=='.')
{
#ifdef _DEBUG
RakAssert(0);
#endif
// Just cancel the write entirely
return;
}
}
WriteFileWithDirectories(fullPath, fileList[i].data, (unsigned int) fileList[i].dataLengthBytes);
}
}
#ifdef _MSC_VER
#pragma warning( disable : 4996 ) // unlink declared deprecated by Microsoft in order to make it harder to be cross platform. I don't agree it's deprecated.
#endif
void FileList::DeleteFiles(const char *applicationDirectory)
{
char fullPath[512];
unsigned i,j;
for (i=0; i < fileList.Size(); i++)
{
// The filename should not have .. in the path - if it does ignore it
for (j=1; j < fileList[i].filename.GetLength(); j++)
{
if (fileList[i].filename[j]=='.' && fileList[i].filename[j-1]=='.')
{
#ifdef _DEBUG
RakAssert(0);
#endif
// Just cancel the deletion entirely
return;
}
}
strcpy(fullPath, applicationDirectory);
FixEndingSlash(fullPath);
strcat(fullPath, fileList[i].filename.C_String());
// Do not rename to _unlink as linux uses unlink
#if defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT)
int result = _unlink(fullPath);
#else
int result = unlink(fullPath);
#endif
if (result!=0)
{
RAKNET_DEBUG_PRINTF("FileList::DeleteFiles: unlink (%s) failed.\n", fullPath);
}
}
}
void FileList::AddCallback(FileListProgress *cb)
{
if (cb==0)
return;
if ((unsigned int) fileListProgressCallbacks.GetIndexOf(cb)==(unsigned int)-1)
fileListProgressCallbacks.Push(cb, _FILE_AND_LINE_);
}
void FileList::RemoveCallback(FileListProgress *cb)
{
unsigned int idx = fileListProgressCallbacks.GetIndexOf(cb);
if (idx!=(unsigned int) -1)
fileListProgressCallbacks.RemoveAtIndex(idx);
}
void FileList::ClearCallbacks(void)
{
fileListProgressCallbacks.Clear(true, _FILE_AND_LINE_);
}
void FileList::GetCallbacks(DataStructures::List<FileListProgress*> &callbacks)
{
callbacks = fileListProgressCallbacks;
}
bool FileList::FixEndingSlash(char *str)
{
#ifdef _WIN32
if (str[strlen(str)-1]!='/' && str[strlen(str)-1]!='\\')
{
strcat(str, "\\"); // Only \ works with system commands, used by AutopatcherClient
return true;
}
#else
if (str[strlen(str)-1]!='\\' && str[strlen(str)-1]!='/')
{
strcat(str, "/"); // Only / works with Linux
return true;
}
#endif
return false;
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif
#endif // _RAKNET_SUPPORT_FileOperations
| [
"8197492@qq.com"
] | 8197492@qq.com |
c13c2323a9835685dbb87925aaf78b4f204c09bb | 24a910a2a986628da089c0fb5f33215c5324a523 | /week-04/day-2/ex03_Flyable/Flyable.h | 9c70560fb65d7326e31564951fdab8d1e3955412 | [] | no_license | green-fox-academy/chama-balintkemeny | f0ab33fccd01f17c1250a0c5c74b20a5ac061c8d | 515d9f644a39731bbe3d56bdba570226c254119b | refs/heads/master | 2020-07-23T12:41:16.690604 | 2020-01-29T08:46:49 | 2020-01-29T08:46:49 | 207,557,164 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | h | //
// Created by Kemény Bálint on 2019. 10. 01..
//
#ifndef EX03_FLYABLE_FLYABLE_H
#define EX03_FLYABLE_FLYABLE_H
#include <string>
class Flyable {
public:
virtual void land()=0;
virtual void fly()=0;
virtual void takeOff()=0;
};
#endif //EX03_FLYABLE_FLYABLE_H
| [
"balintkemeny@gmail.com"
] | balintkemeny@gmail.com |
859d0005ffa96f6a3adf55f4553fa2b7a01fe8cf | 61fb1bf48c8eeeda8ecb2c40fcec1d3277ba6935 | /patoBase/patouser.cpp | 9de44027ca3ac6d8c387e4287a5f80bf1868a5a9 | [] | no_license | matherthal/pato-scm | 172497f3e5c6d71a2cbbd2db132282fb36ba4871 | ba573dad95afa0c0440f1ae7d5b52a2736459b10 | refs/heads/master | 2020-05-20T08:48:12.286498 | 2011-11-25T11:05:23 | 2011-11-25T11:05:23 | 33,139,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 307 | cpp | #include "patouser.h"
PatoUser::PatoUser()
{
}
void PatoUser::setId(int id)
{
m_idUser = id;
}
int PatoUser::getId()
{
return m_idUser;
}
void PatoUser::setName( std::string& name )
{
m_nameUser = name;
}
std::string PatoUser::getName( )
{
return m_nameUser;
}
| [
"rafael@Micro-Mariana"
] | rafael@Micro-Mariana |
0ee9124dc7cd5fc0a796f5623d54b40202024638 | ab699344a6e6fd1a8f93b89eeae5fa5ba16df6fe | /ProtoParams/Alogrithm/MaxMinValueCheck.h | f34a3f0b76ec8c458a14d53ea038c70b806e735a | [] | no_license | LiPorkLi/BatteryFilmCheck | 94fb082962adf1eb019f44f88b958a2916631ff2 | c048163ac0d10cb7db2e7506b7e0c8d8f8a96a20 | refs/heads/master | 2020-04-13T18:48:46.794281 | 2018-12-29T01:49:29 | 2018-12-29T01:49:29 | 163,385,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 969 | h | #pragma once
#include "CheckMethod.h"
#include "AlogrithmBase.h"
class CMaxMinValueCheck : public CCheckMethod, public CAlogrithmBase
{
public:
CMaxMinValueCheck(MainParam::param* p, std::shared_ptr<CRunTimeHandle> pHandle);
~CMaxMinValueCheck();
bool TrainTemplate(cv::Mat& img, bool bIncrementTrain = true);
bool check(cv::Mat& img, cv::Mat& diffImg, double* dTime);
bool check(cv::cuda::GpuMat& img, cv::cuda::GpuMat& diffImg, double* dTime){ return true; };
void SetParam(void* param);
private:
int m_iTrainCount;
cv::Mat m_rowMin, m_rowMax;
cv::Mat m_freamMin, m_freamMax;
int m_iThreshold_low, m_iThreshold_high;
std::vector<std::future<bool>> m_vecReturn;
void GetMaxMinModel(cv::Mat& imgFream, cv::Mat& rowMin, cv::Mat& rowMax, int iFreadIdx/* = 0*/);
void ExtendLineToFream(cv::Size& imgSize, cv::Mat& rowImg, cv::Mat& FreamImg);
bool MaxMinCheckThread(cv::Mat* img, cv::Rect& rtTruth, cv::Mat* imgMin, cv::Mat* imgMax, cv::Mat* DiffImg);
};
| [
"2498319684@qq.com"
] | 2498319684@qq.com |
3ea3a404084b7595bf724a029e18433a165caceb | e0b10f2a9b95c5f2f9e59315fb66e3fb2ecc07f9 | /exe_service/bench/inc/app/bench_app.hpp | 81bb9c96559acbc477eaa1b0f333bcfa59ebe260 | [
"Apache-2.0"
] | permissive | jar-git/cmake-template | d93b28546a05058dfaf02c44af722137ef25f51a | 828fc8ad9c1be8241ec8873fb91109d4ca77d821 | refs/heads/master | 2022-04-15T06:36:57.515003 | 2022-03-28T06:40:35 | 2022-03-28T06:40:35 | 104,624,266 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 855 | hpp | // Copyright 2017 Jani Arola, 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.
#ifndef TEMPLATE_BENCH_APP_HPP
#define TEMPLATE_BENCH_APP_HPP
namespace benchmark {
class State;
} // namespace benchmark
// NOLINTNEXTLINE (runtime/references)
void run_application(benchmark::State& state);
#endif //TEMPLATE_BENCH_APP_HPP
| [
"jar.x64@gmail.com"
] | jar.x64@gmail.com |
31fd4aa833605302c8ffb9f6d41cc1df4bb49edf | 4801a41e721304d92c6f22f140e149c928ebcbd0 | /BattleTank/Source/BattleTank/Public/TankAIController.h | 742100d393d70475b0db0b36c83d7ee3d757966a | [] | no_license | aerenyasar/04_BattleTank | e9215503cd63d4ef0ff10ad190b2f2ffdd74b533 | f2b557b37085cb48c9ca974a1ff7689662f81099 | refs/heads/master | 2021-05-08T16:58:38.171180 | 2018-05-29T14:10:57 | 2018-05-29T14:10:57 | 120,181,488 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "AIController.h"
#include "Engine/World.h"
#include "GameFramework/Actor.h"
#include "TankAIController.generated.h"
class ATank;
class UTankAimingComponent;
/**
*
*/
UCLASS()
class BATTLETANK_API ATankAIController : public AAIController
{
GENERATED_BODY()
public:
virtual void Tick(float DeltaTime) override;
protected:
UPROPERTY(EditAnywhere, Category = Setup)
float AcceptanceRadius = 8000;
private:
void BeginPlay() override;
UTankAimingComponent* AimingComponent = nullptr;
virtual void SetPawn(APawn * InPawn) override;
UFUNCTION()
void OnTankDeath(); //DELEGATE METHOD
};
| [
"alperenyasar@sabanciuniv.edu"
] | alperenyasar@sabanciuniv.edu |
2d9f4a59c9de9503a7b363288388db48427675e1 | 933c10b822d59422194d9ac2515ae6354eb6a101 | /2017/b1025.cpp | 333960aa4d41efaf6b1eff2af385043c6685dcb5 | [] | no_license | tibousi/PAT_2017 | 9cf8adfd366a27ef1d143b0effebf7040060947b | 4321d04b26503d8b63951694b18664f41b42ac89 | refs/heads/master | 2020-03-23T13:04:35.226042 | 2018-07-20T04:54:36 | 2018-07-20T04:54:36 | 141,597,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | cpp | #include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=100010;
struct node{
int data;
int address;
int next;
int order;
}Node[maxn];
bool cmp(node a,node b){
return a.order<b.order;
}
int main(){
for(int i=0;i<maxn;i++){
Node[i].order=maxn;
}
int first,n,k,adress;
scanf("%d%d%d",&first,&n,&k);
for(int i=0;i<n;i++){
scanf("%d",&adress);
scanf("%d%d",&Node[adress].data,&Node[adress].next);
Node[adress].address=adress;
}
int p=first,count=0;
while(p!=-1){
Node[p].order=count++;
p=Node[p].next;
}
sort(Node,Node+maxn,cmp);
int num=count/k;
int end=count%k;
int know=0;
for(int j=0;j<num;j++){
for(int i=know+k-1;i>=know;i--){
printf("%.5d %d %.5d\n",Node[i].address,Node[i].data,Node[i-1].next);
}
know=know+k;
}
if(end!=0){
for(int i=know;i<count;i++){
printf("%.5d %d %.5d\n",Node[i].address,Node[i].data,Node[i-1].next);
}
}
return 0;
}
| [
"ysxj123@sina.cn"
] | ysxj123@sina.cn |
61afc68e26019ccb41bd147eed0b4f944abc604d | 09072267801a1dd95d41ebeb79c9ee0026fca245 | /CS162 Project 5/CS162 Project 5/engineering.hpp | 3ab566a435a93a8b9514311774e62c99cafd0ec0 | [] | no_license | buteaut/CS162 | 2c1457feccdc2c667a1dc73f32f92ea244787d91 | 4b55518ba9b2f87f7e3633261d98bd659fb38966 | refs/heads/master | 2021-03-24T12:25:10.255380 | 2018-03-29T03:17:35 | 2018-03-29T03:17:35 | 78,910,609 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 487 | hpp | /*********************************************************************************
** Program name: Project 5 (Engineering Header File)
** Author: Thomas Buteau
** Date: 3-21-17
** Description: Engineering header file.
**
*********************************************************************************/
#ifndef ENGINEERING_HPP
#define ENGINEERING_HPP
#include "rooms.hpp"
class Engineering : public Rooms
{
protected:
public:
Engineering();
virtual ~Engineering();
};
#endif
| [
"buteaut@oregonstate.edu"
] | buteaut@oregonstate.edu |
9122f8b42e4a63c934dca89dc9faaed2a9f1daff | dbbf11a647ad4c53a7d6e66786c9f10b34d48105 | /stack&queue&linklist/链表/main.cpp | 65ec82a9d8ab572569e48bac5f770e3e33b1006e | [] | no_license | a1991221/AlgorithmTraining | 62472044d4890fa3216e79ba30b97d167bc7aaca | 70d227ad910cc3245ecb9b707794f4128a6eb769 | refs/heads/master | 2021-01-22T11:04:50.166088 | 2017-03-27T12:10:36 | 2017-03-27T12:10:36 | 92,669,623 | 1 | 0 | null | 2017-05-28T15:27:44 | 2017-05-28T15:27:44 | null | UTF-8 | C++ | false | false | 519 | cpp | #include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct node{
int data;
struct node *next;
};
int main()
{
struct node *head,*p,*q,*t;
int i,a,n;
cin>>n;
head ==NULL;
for(i=1;i<=n;i++){
cin>>a;
p=(struct node *)malloc(sizeof(struct node));
p->data = a;
p->next = NULL;
if(head == NULL){
head = p;
}
else
q->next =p;
q=p;
}
t=head;
while(t!=NULL){
cout<<t->data<<" ";
t=t->next;
}
return 0;
}
| [
"1790617178@qq.com"
] | 1790617178@qq.com |
212d022d204948c79fce2bd20f4ab6ff90fa0e56 | dede3be5536dccd5bb7153036085db470463480a | /Qt-50-QItemDelegate_delegates_in_a_QTableview/dialog.h | 63692be134bd0ae8ad4f48ba0ea01bd3fe67e6da | [] | no_license | DoozyX/QtProgrammingTutorial | ce1ec17f34f6fe5c5ac992dce16b5dd6100d72fd | 05da065f0d3ef6aa502c57afb18710ebed0c24c4 | refs/heads/master | 2021-09-03T23:26:12.850142 | 2018-01-02T15:44:57 | 2018-01-02T15:44:57 | 111,606,046 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | h | #ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QtCore>
#include <QtGui>
#include "delegate.h"
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
private:
Ui::Dialog *ui;
QStandardItemModel *model;
Delegate *delegate;
};
#endif // DIALOG_H
| [
"slobodan_kletnikov@hotmail.com"
] | slobodan_kletnikov@hotmail.com |
e85c4a57f4d755598b7013302b633dd862361d38 | b1b734ab75a6fe114733d3c0b8ca5046d54b407d | /third_party/ComputeLibrary/src/core/CL/kernels/CLPixelWiseMultiplicationKernel.cpp | 6dba9c0f956e7c8e91d7896e04fb520bcaf52f49 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"Apache-2.0",
"MIT"
] | permissive | waybarrios/video_nonlocal_net_caffe2 | 754fea2b96318d677144f16faadf59cb6b00189b | b19c2ac3ddc1836d90d7d0fccb60d710c017253e | refs/heads/master | 2020-04-20T03:15:12.286080 | 2019-01-31T20:44:01 | 2019-01-31T20:44:01 | 168,593,110 | 0 | 0 | Apache-2.0 | 2019-01-31T20:40:40 | 2019-01-31T20:40:39 | null | UTF-8 | C++ | false | false | 10,489 | cpp | /*
* Copyright (c) 2016, 2017 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "arm_compute/core/CL/kernels/CLPixelWiseMultiplicationKernel.h"
#include "arm_compute/core/CL/CLHelpers.h"
#include "arm_compute/core/CL/CLKernelLibrary.h"
#include "arm_compute/core/CL/ICLTensor.h"
#include "arm_compute/core/CL/OpenCL.h"
#include "arm_compute/core/Error.h"
#include "arm_compute/core/Helpers.h"
#include "arm_compute/core/TensorInfo.h"
#include "arm_compute/core/Validate.h"
#include "arm_compute/core/Window.h"
#include <cmath>
#include <cstdlib>
#include <set>
#include <string>
using namespace arm_compute;
namespace
{
Status validate_arguments(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output, float scale,
ConvertPolicy overflow_policy, RoundingPolicy rounding_policy)
{
ARM_COMPUTE_UNUSED(overflow_policy);
ARM_COMPUTE_UNUSED(rounding_policy);
ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input1, 1, DataType::U8, DataType::QS8, DataType::QS16, DataType::S16, DataType::F16, DataType::F32);
ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input2, 1, DataType::U8, DataType::QS8, DataType::QS16, DataType::S16, DataType::F16, DataType::F32);
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(input1, input2);
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_FIXED_POINT(input1, input2);
ARM_COMPUTE_RETURN_ERROR_ON_MSG(scale < 0, "Scale cannot be negative.");
if(is_data_type_fixed_point(input1->data_type()))
{
// All data types must be all QS8 or all QS16
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input1, input2);
ARM_COMPUTE_RETURN_ERROR_ON_MSG(scale != 1, "Unsupported scaling factor for QS8/QS16. Scale must be 1.");
}
// Validate in case of configured output
if((output != nullptr) && (output->total_size() != 0))
{
ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(output, 1, DataType::U8, DataType::QS8, DataType::QS16, DataType::S16, DataType::F16, DataType::F32);
ARM_COMPUTE_RETURN_ERROR_ON_MSG(output->data_type() == DataType::U8 && (input1->data_type() != DataType::U8 || input2->data_type() != DataType::U8),
"Output can only be U8 if both inputs are U8");
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(input1, output);
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_FIXED_POINT(input1, output);
if(is_data_type_fixed_point(input1->data_type()))
{
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input1, output);
}
}
return Status{};
}
std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input1, ITensorInfo *input2, ITensorInfo *output)
{
constexpr unsigned int num_elems_processed_per_iteration = 16;
Window win = calculate_max_window(*input1, Steps(num_elems_processed_per_iteration));
AccessWindowHorizontal input1_access(input1, 0, num_elems_processed_per_iteration);
AccessWindowHorizontal input2_access(input2, 0, num_elems_processed_per_iteration);
AccessWindowHorizontal output_access(output, 0, num_elems_processed_per_iteration);
bool window_changed = update_window_and_padding(win, input1_access, input2_access, output_access);
ValidRegion valid_region = intersect_valid_regions(input1->valid_region(),
input2->valid_region());
output_access.set_valid_region(win, valid_region);
Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
return std::make_pair(err, win);
}
} // namespace
CLPixelWiseMultiplicationKernel::CLPixelWiseMultiplicationKernel()
: _input1(nullptr), _input2(nullptr), _output(nullptr)
{
}
void CLPixelWiseMultiplicationKernel::configure(const ICLTensor *input1, const ICLTensor *input2, ICLTensor *output, float scale,
ConvertPolicy overflow_policy, RoundingPolicy rounding_policy)
{
ARM_COMPUTE_ERROR_ON_NULLPTR(input1, input2, output);
// Auto initialize output if not initialized
{
set_shape_if_empty(*output->info(), input1->info()->tensor_shape());
if(input1->info()->data_type() == DataType::S16 || input2->info()->data_type() == DataType::S16)
{
set_format_if_unknown(*output->info(), Format::S16);
}
else if(input1->info()->data_type() == DataType::F32 || input2->info()->data_type() == DataType::F32)
{
set_format_if_unknown(*output->info(), Format::F32);
}
}
ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input1->info(), input2->info(), output->info(),
scale, overflow_policy, rounding_policy));
_input1 = input1;
_input2 = input2;
_output = output;
int scale_int = -1;
// Extract sign, exponent and mantissa
int exponent = 0;
float normalized_mantissa = std::frexp(scale, &exponent);
// Use int scaling if factor is equal to 1/2^n for 0 <= n <= 15
// frexp returns 0.5 as mantissa which means that the exponent will be in the range of -1 <= e <= 14
// Moreover, it will be negative as we deal with 1/2^n
if((normalized_mantissa == 0.5f) && (-14 <= exponent) && (exponent <= 1))
{
// Store the positive exponent. We know that we compute 1/2^n
// Additionally we need to subtract 1 to compensate that frexp used a mantissa of 0.5
scale_int = std::abs(exponent - 1);
}
std::string data_type;
std::string compute_type;
// Check if it has float inputs and output
if(is_data_type_float(input1->info()->data_type()) || is_data_type_float(input2->info()->data_type()))
{
scale_int = -1;
compute_type = (input1->info()->data_type() == DataType::F32 || input2->info()->data_type() == DataType::F32) ? "float" : "half";
data_type = "DATA_TYPE_FLOAT";
}
else
{
if(input1->info()->data_type() == DataType::S16 || input2->info()->data_type() == DataType::S16)
{
compute_type = "int";
}
else if(input1->info()->data_type() == DataType::QS8)
{
compute_type = "qs8";
}
else if(input1->info()->data_type() == DataType::QS16)
{
compute_type = "qs16";
}
else
{
compute_type = "ushort";
}
data_type = "DATA_TYPE_INT";
}
// Construct kernel name
std::string kernel_name = "pixelwise_mul";
kernel_name += (scale_int >= 0) ? "_int" : "_float";
// Set kernel build options
std::set<std::string> build_opts;
build_opts.emplace((overflow_policy == ConvertPolicy::WRAP || is_data_type_float(output->info()->data_type())) ? "-DWRAP" : "-DSATURATE");
build_opts.emplace((rounding_policy == RoundingPolicy::TO_ZERO) ? "-DROUND=_rtz" : "-DROUND=_rte");
if(is_data_type_fixed_point(input1->info()->data_type()))
{
build_opts.emplace("-DFIXED_POINT_POSITION=" + support::cpp11::to_string(input1->info()->fixed_point_position()));
}
build_opts.emplace("-DDATA_TYPE_IN1=" + get_cl_type_from_data_type(input1->info()->data_type()));
build_opts.emplace("-DDATA_TYPE_IN2=" + get_cl_type_from_data_type(input2->info()->data_type()));
build_opts.emplace("-DDATA_TYPE_OUT=" + get_cl_type_from_data_type(output->info()->data_type()));
build_opts.emplace("-DDATA_TYPE_RES=" + compute_type);
build_opts.emplace("-D" + data_type);
// Create kernel
_kernel = static_cast<cl::Kernel>(CLKernelLibrary::get().create_kernel(kernel_name, build_opts));
// Set scale argument
unsigned int idx = 3 * num_arguments_per_3D_tensor(); //Skip the inputs and output parameters
if(scale_int >= 0)
{
_kernel.setArg(idx++, scale_int);
}
else
{
_kernel.setArg(idx++, scale);
}
// Configure kernel window
auto win_config = validate_and_configure_window(input1->info(), input2->info(), output->info());
ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
ICLKernel::configure(win_config.second);
}
Status CLPixelWiseMultiplicationKernel::validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output, float scale,
ConvertPolicy overflow_policy, RoundingPolicy rounding_policy)
{
ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input1, input2, output, scale, overflow_policy, rounding_policy));
ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input1->clone().get(), input2->clone().get(), output->clone().get()).first);
return Status{};
}
void CLPixelWiseMultiplicationKernel::run(const Window &window, cl::CommandQueue &queue)
{
ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(ICLKernel::window(), window);
Window collapsed = window.collapse_if_possible(ICLKernel::window(), Window::DimZ);
Window slice = collapsed.first_slice_window_3D();
do
{
unsigned int idx = 0;
add_3D_tensor_argument(idx, _input1, slice);
add_3D_tensor_argument(idx, _input2, slice);
add_3D_tensor_argument(idx, _output, slice);
enqueue(queue, *this, slice);
}
while(collapsed.slide_window_slice_3D(slice));
}
| [
"gemfield@civilnet.cn"
] | gemfield@civilnet.cn |
35cdb0c2841244b93033761d2942f3faa7c638ca | 6edcad19b112b54182d3a9fd1d6098a0aa3caa49 | /minilab_v2/src/minilab_node.cpp | b405fcbf02e215d548821424579379f55501df7c | [] | no_license | EnovaROBOTICS/Mini-Lab | 8f7b964909fb6d5e64a7c851595974ac93fd7267 | 812f6e0cb4d7367da1d8aa57f6f4778863b738b6 | refs/heads/master | 2021-01-15T11:43:33.202917 | 2015-08-05T11:43:43 | 2015-08-05T11:43:43 | 40,241,547 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,317 | cpp | #include <sstream>
#include <ros/ros.h>
#include <std_msgs/Float64.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/Pose2D.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include "serial.hpp"
#include "roboclaw.hpp"
// Geometrical paramters
#define WHEEL_RADIUS (0.123825/2.) // m
#define Wheelbase (0.380)
// CPR + Gear
#define CPR_CODEUR 2048 // tics / tr
#define GEAR_RATIO 16 //
#define CPR_GEAR (CPR_CODEUR*4*GEAR_RATIO) // tics / tr (quadrature)
#define VMAX_MOT (3000) // rpm
#define VMAX ((VMAX_MOT/GEAR_RATIO)/60*CPR_GEAR) // tics / s (quad)
#define PI (3.145926)
// Unit conversion
#define M_2_TICS (CPR_GEAR/(2*PI*WHEEL_RADIUS))
#define TICS_2_M (1/M_2_TICS)
// Motor disposition
#define LEFT 0
#define RIGHT 1
// Gloal variables
int raw_motor_encoder[2]; // motor encoders tics (quad)
int raw_motor_encoder_prev[2]; // previous
int raw_motor_delta_encoder[2]; // delta
double wheel_velocity[2];
double battery_voltage;
ros::Time current_time, last_time;
ros::Time last_cmd_vel_time;
// jointstate
// odom
RoboClaw *motors_driver;
//-----------------------------------------------------------------------------
void cmd_vel_cb(const geometry_msgs::Twist::ConstPtr& msg)
{
double vx = msg->linear.x;
double wz = msg->angular.z;
double v_right = vx + (Wheelbase/2.)*wz;
double v_left = vx - (Wheelbase/2.)*wz;
double v_right_raw = v_right*M_2_TICS;
double v_left_raw = v_left *M_2_TICS;
// ROS_INFO("cmd_vel = (%.2f,%.2f) -> (%.2f,%.2f) -> (%i,%i)",
// vx,wz, v_left, v_right, (int)v_left_raw, (int)v_right_raw);
// Inverted rotation sign on right wheel
motors_driver->set_PID_target(RIGHT, -(int) v_right_raw);
motors_driver->set_PID_target(LEFT, (int) v_left_raw);
last_cmd_vel_time = ros::Time::now();
}
//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
std_msgs::Float64 v_batt_msg;
// initial position
double x = 0;
double y = 0;
double th = 0;
// Init driver
motors_driver = new RoboClaw(128);
if(motors_driver->init("/dev/ttyRoboClaw", 38400, 10e3))
return 1;
motors_driver->read_firmware();
printf("Power voltage : %.2f V\n", motors_driver->get_power_voltage());
motors_driver->reset_encoders();
for(int id=0;id<2;id++) {
motors_driver->set_PID_parameters(id, 22100, 6100, 1500, VMAX);
usleep(200e3);
motors_driver->set_PID_target(id,0);
}
// Init ROS
ros::init(argc, argv, "minilab_node");
ros::NodeHandle n;
ros::Publisher batt_volt_pub = n.advertise<std_msgs::Float64>("v_batt", 10 );
ros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>("odom", 10 );
tf::TransformBroadcaster odom_broadcaster;
ros::Subscriber cmd_vel_sub = n.subscribe("cmd_vel", 10, cmd_vel_cb);
ros::Rate loop_rate(10);
// Init Data
last_cmd_vel_time = ros::Time::now();
current_time = ros::Time::now();
last_time = ros::Time::now();
// Main loop
while (ros::ok())
{
ros::spinOnce();
current_time = ros::Time::now();
double last_cmd_vel_dt = (current_time-last_cmd_vel_time).toSec();
//ROS_INFO("last time = %.2f", last_cmd_vel_dt);
if(last_cmd_vel_dt>1.0) {
motors_driver->set_PID_target(RIGHT, 0);
motors_driver->set_PID_target(LEFT, 0);
}
// Get wheel encoder measurments
// Inverted rotation sign on right wheel
raw_motor_encoder_prev[LEFT] = raw_motor_encoder[LEFT];
raw_motor_encoder_prev[RIGHT] = raw_motor_encoder[RIGHT];
raw_motor_encoder[LEFT] = +motors_driver->get_encoder(LEFT);
usleep(20e3);
raw_motor_encoder[RIGHT] = -motors_driver->get_encoder(RIGHT);
usleep(20e3);
raw_motor_delta_encoder[LEFT]=
raw_motor_encoder[LEFT]-raw_motor_encoder_prev[LEFT];
raw_motor_delta_encoder[RIGHT]=
raw_motor_encoder[RIGHT]-raw_motor_encoder_prev[RIGHT];
battery_voltage = motors_driver->get_power_voltage();
v_batt_msg.data = battery_voltage;
batt_volt_pub.publish(v_batt_msg);
// Compute robot delta pos in tics
int raw_delta_x = (raw_motor_delta_encoder[RIGHT]
+raw_motor_delta_encoder[LEFT])/2;
int raw_delta_theta = (raw_motor_delta_encoder[RIGHT]
-raw_motor_delta_encoder[LEFT])/Wheelbase;
// Compute robot delta pos in m
double dl = raw_delta_x * TICS_2_M;
double dth = raw_delta_theta * TICS_2_M;
/*
ROS_INFO("Vr, Vl = %i, %i",
raw_motor_delta_encoder[LEFT],
raw_motor_delta_encoder[RIGHT]);
*/
//ROS_INFO("dl, dth = %.3f, %.3f", dl, dth);
ROS_INFO("Volts = %.3f", battery_voltage);
//compute odometry in a typical way given the velocities of the robot
double dt = (current_time - last_time).toSec();
double delta_x = dl * cos(th);
double delta_y = dl * sin(th);
double delta_th = dth;
x += delta_x;
y += delta_y;
th += delta_th;
//since all odometry is 6DOF we'll need a quaternion created from yaw
geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th);
//first, we'll publish the transform over tf
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = current_time;
odom_trans.header.frame_id = "odom";
odom_trans.child_frame_id = "base_footprint";
odom_trans.transform.translation.x = x;
odom_trans.transform.translation.y = y;
odom_trans.transform.translation.z = 0.0;
odom_trans.transform.rotation = odom_quat;
//send the transform
odom_broadcaster.sendTransform(odom_trans);
//next, we'll publish the odometry message over ROS
nav_msgs::Odometry odom;
odom.header.stamp = current_time;
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odom_quat;
//set the velocity
odom.child_frame_id = "base_footprint";
odom.twist.twist.linear.x = dl/dt;
odom.twist.twist.linear.y = 0;
odom.twist.twist.angular.z = dth/dt;
//publish the message
odom_pub.publish(odom);
last_time = current_time;
loop_rate.sleep();
}
return 0;
}
| [
"nabilskhirigabbouj@gmail.com"
] | nabilskhirigabbouj@gmail.com |
ec4df3bbe7d5c371d456500d8cf5922346928017 | 1c8a0fcf0aece43cb2cf30d1ecf2d84a74a734c3 | /leet_easy_c++/leet_359/leet_359a.cpp | 10e60401da50d004f918b96c1c946d9ba2321a09 | [] | no_license | zmeeks/leet_code | df936d38aa63115150fb464c74d6a112f1669d89 | ea3d7201c3f5b2db2ca6fc526e0f9bc36e17bfad | refs/heads/master | 2021-01-20T22:20:21.487734 | 2017-12-06T10:36:22 | 2017-12-06T10:36:22 | 101,813,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | cpp | class Logger {
public:
/** Initialize your data structure here. */
Logger() {
}
/** Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity. */
bool shouldPrintMessage(int timestamp, string message) {
int last;
if(umap.count(message) == 0){
umap[message]=timestamp;
return true;
}
else if(timestamp-umap[message]>= 10){
umap[message]=timestamp;
return true;
}
else{
return false;
}
}
private:
unordered_map<string, int> umap;
};
/**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* bool param_1 = obj.shouldPrintMessage(timestamp,message);
*/ | [
"noreply@github.com"
] | noreply@github.com |
540d70a5d36c8fffe191f5e6573f565524ff3f1e | 99d412d467b06b0409f366380bfe289fb3688c7d | /misc/modp_newforms.cc | 81c2caf6958d789f39a238456158cfef4448f5e9 | [] | no_license | jwbober/ntlib | 279ec6030e8925fff70274c851aae4960ead7473 | 61102f36d2cc5dcfbd72b80f0da42f6c1a69b6cc | refs/heads/master | 2020-04-06T13:54:02.966465 | 2018-09-11T11:50:51 | 2018-09-11T11:50:51 | 46,086,969 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | cc | #include "modform_modp.h"
#include "classnumbers.h"
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main(int argc, char ** argv) {
int level;
int chi_number;
int weight;
int ncoeffs;
long p;
init_classnumbers();
level = atoi(argv[1]);
weight = atoi(argv[2]);
chi_number = atoi(argv[3]);
ncoeffs = atoi(argv[4]);
p = atol(argv[5]);
cout << level << endl
<< weight << endl
<< chi_number << endl
<< ncoeffs << endl
<< p << endl;
int verbose = 0;
if(argc > 6) verbose = atoi(argv[6]);
DirichletGroup G(level);
if(GCD(level, chi_number) != 1) return 0;
DirichletCharacter chi = G.character(chi_number);
if(chi.is_even() && weight % 2 == 1) return 0;
if(!chi.is_even() && weight % 2 == 0) return 0;
cuspforms_modp * S = get_cuspforms_modp(chi, weight, p, verbose);
nmod_mat_t newforms;
cout << "here" << endl;
S->newforms(newforms, ncoeffs);
return 0;
}
| [
"jwbober@gmail.com"
] | jwbober@gmail.com |
de2a833a787ce61aff0e7e4939fb270d6d729eda | e86da2918b68ea8beb05e89906ed7f9bff3383f2 | /1169 - Monkeys on Twin Tower/1169 - Monkeys on Twin Tower.cpp | b18f737a8da2e8bc207e2f911b8d41b456ce5f1f | [] | no_license | diptapaul/Lightoj-Problem-Solution | b9939908f054338a9782d05ecbaee7021d73e386 | b6aca0050b7502692ced754c1e8dde5278e6778c | refs/heads/master | 2021-01-01T17:19:59.811444 | 2018-01-25T06:14:23 | 2018-01-25T06:14:23 | 98,051,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 938 | cpp | #include <bits/stdc++.h>
typedef long long int ll;
using namespace std;
int n, cs = 1, tc, a1[2][1005], t1[2][1005], dp[2][1005], vis[1005][1005];
int rec(int i, int j)
{
if(j > n - 1) return 0;
if(vis[i][j] == cs) return dp[i][j];
vis[i][j] = cs;
int ret = a1[i][j];
ret += min(rec(i, j + 1), rec(!i, j + 1) + t1[i][j]);
return dp[i][j] = ret;
}
int main()
{
#ifdef O_Amay_Bhalobaseni
freopen("in.txt", "r", stdin);
//freopen("in11.txt", "w+", stdout);
#endif /// O_Amay_Bhalobaseni
int i;
scanf("%d", &tc);
while(tc-- && ~scanf("%d", &n))
{
for(i = 0; i < n; i++) scanf("%d", &a1[0][i]);
for(i = 0; i < n; i++) scanf("%d", &a1[1][i]);
for(i = 0; i < n - 1; i++) scanf("%d", &t1[0][i]);
for(i = 0; i < n - 1; i++) scanf("%d", &t1[1][i]);
printf("Case %d: %d\n", cs, min(rec(0, 0), rec(1, 0)));
cs++;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
276e3598e4da7366559ede09c829ea2b6e7cc68f | cd327aee5966e332c384b1a59eeab0e20c45c6bd | /Source/Sks/Src/Accelero/IntelliSS7/tools/src/asncc_wip/asncc_visitor.h | aa6a126aad56619e32f57f82b5cd9cfe76db0633 | [] | no_license | komi-jangra/A_TEST | 4ae3b7c31f0db75e210f0b7e514c14cee5b24443 | 117f4d702d241de6074903be0e5a579f450fff91 | refs/heads/master | 2021-01-22T23:48:28.202567 | 2017-03-21T07:15:15 | 2017-03-21T07:15:15 | 85,664,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,194 | h | ////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 1999 IntelliNet Technologies, Inc. All Rights Reserved. //
// Manufactured in the United States of America. //
// 1990 W. New Haven Ste. 312, Melbourne, Florida, 32904 U.S.A. //
// //
// This product and related documentation is protected by copyright and //
// distributed under licenses restricting its use, copying, distribution //
// and decompilation. No part of this product or related documentation //
// may be reproduced in any form by any means without prior written //
// authorization of IntelliNet Technologies and its licensors, if any. //
// //
// RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the //
// government is subject to restrictions as set forth in subparagraph //
// (c)(1)(ii) of the Rights in Technical Data and Computer Software //
// clause at DFARS 252.227-7013 and FAR 52.227-19. //
// //
////////////////////////////////////////////////////////////////////////////////
// //
// CONTRACT: INTERNAL //
// //
////////////////////////////////////////////////////////////////////////////////
//
// ID: $Id: asncc_visitor.h,v 1.1.1.1 2007-10-08 11:12:08 bsccs2 Exp $
//
////////////////////////////////////////////////////////////////////////////////
#if !defined(_ASNCC_VISITOR_H_)
#define _ASNCC_VISITOR_H_
#include <asncc.h>
#include <asncc_assertion.h>
////////////////////////////////////////////////////////////////////////////////
class Module;
class ImportedModule;
class TypeDef;
class Type;
class BitStringType;
class BooleanType;
class ChoiceType;
class EnumeratedType;
class IntegerType;
class NullType;
class ObjectIdentifierType;
class OctetStringType;
class RealType;
class SequenceType;
class SequenceOfType;
class SetType;
class SetOfType;
class DefinedType;
class AnyType;
class AnyDefinedByType;
class ValueDef;
class Value;
class BitStringValue;
class BooleanValue;
class CharacterStringValue;
class ChoiceValue;
class EnumeratedValue;
class IntegerValue;
class ObjectIdentifierValue;
class OctetStringValue;
class MaxValue;
class MinValue;
class NullValue;
class RealValue;
class SequenceValue;
class DefinedValue;
class AnyValue;
class NamedNumber;
class Tag;
class Constraint;
class ConstraintElement;
class ConstrainAllConstraintElement;
class ElementListConstraintElement;
class SingleValueConstraintElement;
class ValueRangeConstraintElement;
class NestedConstraintConstraintElement;
class SizeConstraintElement;
class FromConstraintElement;
class WithComponentConstraintElement;
class InnerTypeConstraintElement;
class UserDefinedConstraintElement;
class SubTypeConstraintElement;
typedef std::list<Constraint*> ConstraintList;
typedef std::list<Type*> TypeList;
////////////////////////////////////////////////////////////////////////////////
//
// Visitor interface.
//
class Visitor
{
public:
Visitor()
: iterPosition(ITER_BEGIN),
iterSize(0),
visitRecursive(false),
visitFlattened(false)
{}
// Default copy constructor ok.
// Default destructor ok (no memory management).
// Default assignment operator ok.
////////////////////////////////////////////////////////////////////////////
virtual void
VisitModuleBegin(Module* module)
{}
virtual void
VisitModuleEnd(Module* module)
{}
virtual void
VisitImportedModule(ImportedModule* importedModule)
{}
////////////////////////////////////////////////////////////////////////////
virtual void
VisitTypeDefBegin(TypeDef* typeDef)
{}
virtual void
VisitTypeDefEnd(TypeDef* typeDef)
{}
virtual void
VisitTypeBegin(Type* type)
{}
virtual void
VisitTypeEnd(Type* type)
{}
virtual void VisitTypeDefaultValue(Type* type, Value* value);
virtual void VisitTypeConstraintList(ConstraintList* constraintList);
virtual void
VisitBitStringTypeBegin(BitStringType* bitStringType)
{}
virtual void
VisitBitStringTypeEnd(BitStringType* bitStringType)
{}
virtual void
VisitBooleanType(BooleanType* booleanType)
{}
virtual void
VisitChoiceTypeBegin(ChoiceType* choiceType)
{}
virtual void
VisitChoiceTypeEnd(ChoiceType* choiceType)
{}
virtual void VisitChoiceTypeList(TypeList* typeList);
virtual void
VisitEnumeratedTypeBegin(EnumeratedType* enumeratedType)
{}
virtual void
VisitEnumeratedTypeEnd(EnumeratedType* enumeratedType)
{}
virtual void
VisitIntegerTypeBegin(IntegerType* integerType)
{}
virtual void
VisitIntegerTypeEnd(IntegerType* integerType)
{}
virtual void
VisitObjectIdentifierType(ObjectIdentifierType* objectIdentifierType)
{}
virtual void
VisitNullType(NullType* nullType)
{}
virtual void
VisitRealType(RealType* realType)
{}
virtual void
VisitSequenceTypeBegin(SequenceType* sequenceType)
{}
virtual void
VisitSequenceTypeEnd(SequenceType* sequenceType)
{}
virtual void VisitSequenceTypeList(TypeList* typeList);
virtual void
VisitSequenceOfTypeBegin(SequenceOfType* sequenceOfType)
{}
virtual void
VisitSequenceOfTypeEnd(SequenceOfType* sequenceOfType)
{}
virtual void VisitSequenceOfTypeType(Type* type);
virtual void VisitSequenceOfConstraint(Constraint* constraint);
virtual void
VisitSetTypeBegin(SetType* setType)
{}
virtual void
VisitSetTypeEnd(SetType* setType)
{}
virtual void VisitSetTypeList(TypeList* typeList);
virtual void
VisitSetOfTypeBegin(SetOfType* setOfType)
{}
virtual void
VisitSetOfTypeEnd(SetOfType* setOfType)
{}
virtual void VisitSetOfTypeType(Type* type);
virtual void VisitSetOfConstraint(Constraint* constraint);
virtual void
VisitOctetStringType(OctetStringType* octetStringType)
{}
virtual void
VisitDefinedType(DefinedType* definedType)
{}
virtual void
VisitAnyType(AnyType* anyType)
{}
virtual void
VisitAnyDefinedByType(AnyDefinedByType* anyDefinedByType)
{}
////////////////////////////////////////////////////////////////////////////
virtual void
VisitValueDefBegin(ValueDef* valueDef)
{}
virtual void
VisitValueDefMiddle(ValueDef* valueDef)
{}
virtual void
VisitValueDefEnd(ValueDef* valueDef)
{}
virtual void VisitValueDefType(ValueDef* valueDef, Type* type);
virtual void
VisitValueBegin(Value* value)
{}
virtual void
VisitValueEnd(Value* value)
{}
virtual void
VisitBitStringValue(BitStringValue* bitStringValue)
{}
virtual void
VisitBooleanValue(BooleanValue* booleanValue)
{}
virtual void
VisitCharacterStringValue(CharacterStringValue* characterStringValue)
{}
virtual void
VisitChoiceValue(ChoiceValue* choiceValue)
{}
virtual void
VisitEnumeratedValue(EnumeratedValue* enumeratedValue)
{}
virtual void
VisitIntegerValue(IntegerValue* integerValue)
{}
virtual void
VisitObjectIdentifierValue(ObjectIdentifierValue* objectIdentifierValue)
{}
virtual void
VisitOctetStringValue(OctetStringValue* octetStringValue)
{}
virtual void
VisitMaxValue(MaxValue* maxValue)
{}
virtual void
VisitMinValue(MinValue* minValue)
{}
virtual void
VisitNullValue(NullValue* nullValue)
{}
virtual void
VisitRealValue(RealValue* realValue)
{}
virtual void
VisitSequenceValueBegin(SequenceValue* sequenceValue)
{}
virtual void
VisitSequenceValueEnd(SequenceValue* sequenceValue)
{}
virtual void
VisitDefinedValue(DefinedValue* definedValue)
{}
virtual void
VisitAnyValue(AnyValue* anyValue)
{}
////////////////////////////////////////////////////////////////////////////
virtual void
VisitNamedNumberBegin(NamedNumber* namedNumber)
{}
virtual void
VisitNamedNumberEnd(NamedNumber* namedNumber)
{}
virtual void
VisitTag(Tag* tag)
{}
virtual void
VisitConstraintBegin(Constraint* constraint)
{}
virtual void
VisitConstraintEnd(Constraint* constraint)
{}
virtual void
VisitConstrainAllConstraintElementBegin(
ConstrainAllConstraintElement*
constrainAllConstraintElement)
{}
virtual void
VisitConstrainAllConstraintElementEnd(
ConstrainAllConstraintElement*
constrainAllConstraintElement)
{}
virtual void
VisitElementListConstraintElementBegin(
ElementListConstraintElement*
elementListConstraintElement)
{}
virtual void
VisitElementListConstraintElementEnd(
ElementListConstraintElement*
elementListConstraintElement)
{}
virtual void
VisitSingleValueConstraintElementBegin(
SingleValueConstraintElement*
singleValueConstraintElement)
{}
virtual void
VisitSingleValueConstraintElementEnd(
SingleValueConstraintElement*
singleValueConstraintElement)
{}
virtual void
VisitValueRangeConstraintElementBegin(
ValueRangeConstraintElement*
valueRangeConstraintElement)
{}
virtual void
VisitValueRangeConstraintElementMiddle(
ValueRangeConstraintElement*
valueRangeConstraintElement)
{}
virtual void
VisitValueRangeConstraintElementEnd(
ValueRangeConstraintElement*
valueRangeConstraintElement)
{}
virtual void
VisitNestedConstraintConstraintElementBegin(
NestedConstraintConstraintElement*
nestedConstraintConstraintElement)
{}
virtual void
VisitNestedConstraintConstraintElementEnd(
NestedConstraintConstraintElement*
nestedConstraintConstraintElement)
{}
virtual void
VisitSizeConstraintElementBegin(
SizeConstraintElement*
sizeConstraintElement)
{}
virtual void
VisitSizeConstraintElementEnd(
SizeConstraintElement*
sizeConstraintElement)
{}
virtual void
VisitFromConstraintElementBegin(
FromConstraintElement*
fromConstraintElement)
{}
virtual void
VisitFromConstraintElementEnd(
FromConstraintElement*
fromConstraintElement)
{}
virtual void
VisitWithComponentConstraintElementBegin(
WithComponentConstraintElement*
withComponentConstraintElement)
{}
virtual void
VisitWithComponentConstraintElementEnd(
WithComponentConstraintElement*
withComponentConstraintElement)
{}
virtual void
VisitInnerTypeConstraintElementBegin(
InnerTypeConstraintElement*
innerTypeConstraintElement)
{}
virtual void
VisitInnerTypeConstraintElementEnd(
InnerTypeConstraintElement*
innerTypeConstraintElement)
{}
virtual void
VisitUserDefinedConstraintElementBegin(
UserDefinedConstraintElement*
userDefinedConstraintElement)
{}
virtual void
VisitUserDefinedConstraintElementEnd(
UserDefinedConstraintElement*
userDefinedConstraintElement)
{}
virtual void
VisitSubTypeConstraintElementBegin(
SubTypeConstraintElement*
subTypeConstraintElement)
{}
virtual void
VisitSubTypeConstraintElementEnd(
SubTypeConstraintElement*
subTypeConstraintElement)
{}
////////////////////////////////////////////////////////////////////////////
typedef unsigned int IterSize;
void
SetIterBegin()
{ iterPosition = ITER_BEGIN; }
bool
IsIterBegin() const
{ return iterPosition == ITER_BEGIN; }
void
SetIterMiddle()
{ iterPosition = ITER_MIDDLE; }
bool
IsIterMiddle() const
{ return iterPosition == ITER_MIDDLE; }
void
SetIterEnd()
{ iterPosition = ITER_END; }
bool
IsIterEnd()
{ return iterPosition == ITER_END; }
void
SetIterSize(IterSize iterSizeParam)
{ iterSize = iterSizeParam; }
IterSize
GetIterSize() const
{ return iterSize; }
void
PushIterContext()
{
iterPositionStack.push_front(iterPosition);
iterSizeStack.push_front(iterSize);
}
bool
IsIterContextPushed() const
{ return !(iterPositionStack.empty() || iterSizeStack.empty()); }
void
PopIterContext()
{
REQUIRE(IsIterContextPushed());
iterPosition = iterPositionStack.front();
iterPositionStack.pop_front();
iterSize = iterSizeStack.front();
iterSizeStack.pop_front();
}
////////////////////////////////////////////////////////////////////////////
void
SetVisitRecursive()
{ visitRecursive = true; }
void
UnsetVisitRecursive()
{ visitRecursive = false; }
bool
VisitRecursive() const
{ return visitRecursive; }
void
SetVisitFlattened()
{ visitFlattened = true; }
void
UnsetVisitFlattened()
{ visitFlattened = false; }
bool
VisitFlattened() const
{ return visitFlattened; }
////////////////////////////////////////////////////////////////////////////
protected:
enum IterPosition {
ITER_BEGIN,
ITER_MIDDLE,
ITER_END
};
IterPosition iterPosition;
IterSize iterSize;
// IterPosition Context push/pop.
std::list<IterPosition> iterPositionStack;
// IterSize Context push/pop.
std::list<IterSize> iterSizeStack;
bool visitRecursive;
bool visitFlattened;
};
#endif // !defined(_ASNCC_VISITOR_H_)
| [
"komal.jangra@imrggn.com"
] | komal.jangra@imrggn.com |
220dd076e281d1c7b3b81715f4fb515275b337ac | 175258c7a397db643af7204eb6ab7403af28740c | /cpp/expression_division.h | 00ef9650e1e67404eb593484f84253a7ddf1975a | [] | no_license | vakaras/Taylor | 9e9e0f966e83d8ad7ce2c5f07aa6ea2e3a65ae9a | 25637fa4fcc3fd6e2920f31269e2db0fa21491e6 | refs/heads/master | 2016-09-06T02:38:01.151542 | 2011-01-06T08:08:55 | 2011-01-06T08:08:55 | 1,195,423 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,392 | h | #ifndef TAYLOR_CPP_EXPRESSION_DIVISION
#define TAYLOR_CPP_EXPRESSION_DIVISION
#include "expression.h"
class ExpressionDivision: public Expression {
// Attributes.
private:
const Expression
*numerator,
*denominator;
// Methods.
long getNumeratorPrecision(int precision) const {
// FIXME: Write normal.
return precision;
}
long getDenominatorPrecision(int precision) const {
// FIXME: Write normal.
return precision;
}
public:
ExpressionDivision(
const Expression &_numerator, const Expression &_denominator) {
numerator = &_numerator;
denominator = &_denominator;
}
Number &count(long digits) const {
#ifdef DEBUG
LOG("DIVISION");
#endif
long precision_numerator = this->getNumeratorPrecision(digits);
long precision_denominator = this->getDenominatorPrecision(digits);
Number &number = numerator->count(precision_numerator);
number /= denominator->count(precision_denominator);
return number;
}
Expression &clone() const {
Expression © = *(new ExpressionDivision(
numerator->clone(), denominator->clone()));
return copy;
}
std::string latex() const {
std::string repr = std::string(" \\left( ");
repr += " \\frac{ " + numerator->latex() + " }";
repr += "{ " + denominator->latex() + " } \\right) ";
return repr;
}
};
#endif
| [
"vastrauskas@gmail.com"
] | vastrauskas@gmail.com |
2652cd8acb66a3b371a709936c107ef4d30c2da2 | e3d27453d4f233bb603f37854f3639439b1e1f0b | /KiemTra/KiemTra.cpp | 45e993c1e664b5ef48302166264991e9e0869bd5 | [] | no_license | tungcheng/FAMI-NhaDauTuTaiBa-2010 | bd6fd1e60e188e3a1e7ae57d35965c717231cf71 | e7797acc2b85cbd62e796996bd7cc8d54a9d34fb | refs/heads/master | 2021-01-17T19:09:47.675693 | 2016-07-12T07:37:41 | 2016-07-12T07:37:41 | 63,136,960 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,782 | cpp | #include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
FILE *fileStockList, *fileDateList, *fileMatrix, *fileOut, *fileIn;
const int MAX_STOCK = 201, MAX_DAY = 251; // 201 - 251
const float LE_PHI = 0.003;
char cStockList[MAX_STOCK+1][10], cDateList[MAX_DAY+1][15];
float fMatrix[MAX_STOCK+1][MAX_DAY+1];
float fGiaTriHienTai = 1000000, fGiaTriKiLuc = 1000000;
int iPhuongAnHienTai[MAX_DAY+1][3], iPhuongAnKiLuc[MAX_DAY+1][3];
float fGiaTriNgay[MAX_DAY+1];
// void khoiTaoPA();
void taoStockList();
void taoDateList();
void taoMatrix();
void kiemTra();
// void lietKeTime(int iNgay);
// int iTimMax(int iNgayDau, int iNgayCuoi);
// void capNhatGiaTri(float fDau, float fCuoi, int iNumber);
// void capNhatPhuongAn(int iStock, int iNgayDau, int iNgayCuoi, int iNumber);
// void quayLuiGiaTri(float fDau, float fCuoi, int iNumber);
// void quayLuiPhuongAn(int iStock, int iNgayDau, int iNgayCuoi, int iNumber);
// void capNhatKiLuc();
// void inKetQua();
void main()
{
// khoiTaoPA();
taoStockList();
taoDateList();
taoMatrix();
kiemTra();
// lietKeTime(1);
// inKetQua();
}
void khoiTaoPA()
{
int i, j;
for(i=0; i <= MAX_DAY; i++)
for(j=0; j < 3; j++) iPhuongAnHienTai[i][j] = 0;
}
void taoStockList()
{
int i=1;
char cInName[64], s[10];
do
{
printf("\nNhap ten file Danh sach CP: ");
scanf("%63s", cInName);
if((fileStockList = fopen (cInName, "r")) == NULL)
printf("\nTen file nhap khong dung!");
}
while((fileStockList = fopen (cInName, "r")) == NULL);
while(feof(fileStockList)==0)
{
fscanf(fileStockList, "%s", s);
strcpy(cStockList[i],s);
i++;
}
fclose(fileStockList);
}
void taoDateList()
{
int i=251;
char cInName[64], s[15];
do
{
printf("\nNhap ten file Danh sach Ngay: ");
scanf("%63s", cInName);
if((fileDateList = fopen (cInName, "r")) == NULL)
printf("\nTen file nhap khong dung!");
}
while((fileDateList = fopen (cInName, "r")) == NULL);
while(feof(fileDateList)==0)
{
fscanf(fileDateList, "%s", s);
strcpy(cDateList[i],s);
i--;
}
fclose(fileDateList);
}
void taoMatrix()
{
int i,j;
char cInName[64];
do
{
printf("\nNhap ten file Ma tran Gia tri: ");
scanf("%63s", cInName);
if((fileMatrix = fopen (cInName, "r")) == NULL)
printf("\nTen file nhap khong dung!");
}
while((fileMatrix = fopen (cInName, "r")) == NULL);
for(i=1; i <= MAX_STOCK; i++)
for(j=1; j <= MAX_DAY; j++)
fscanf(fileMatrix, "%f", &fMatrix[i][j]);
fclose(fileMatrix);
}
void kiemTra()
{
char cInName[64], cTenCP[10];
char cNgay1[12], cNgay2[12], cGiaTri[50];
int iSoLuong, iSttCP, iSttNgay1, iSttNgay2;
float f = 1000000;
fileOut = fopen("Out.txt", "w");
do
{
printf("\nNhap ten file Phuong An Giao Dich: ");
scanf("%63s", cInName);
if((fileIn = fopen (cInName, "r")) == NULL)
printf("\nTen file nhap khong dung!");
}
while((fileIn = fopen (cInName, "r")) == NULL);
while(feof(fileIn)==0)
{
fscanf(fileIn, "%s", cTenCP);
fscanf(fileIn, "%s", cNgay1);
fscanf(fileIn, "%s", cNgay2);
fscanf(fileIn, "%d", &iSoLuong);
fscanf(fileIn, "%s", cGiaTri);
for(int i=1; i<=MAX_STOCK; i++)
if(strcmp(cTenCP, cStockList[i])==0) iSttCP = i;
for(int i=1; i<=MAX_DAY; i++)
{
if(strcmp(cNgay1, cDateList[i])==0) iSttNgay1 = i;
if(strcmp(cNgay2, cDateList[i])==0) iSttNgay2 = i;
}
f = f - iSoLuong*10*fMatrix[iSttCP][iSttNgay1]*(1 + LE_PHI);
if(f<0) printf("\nError: f < 0");
f = f + iSoLuong*10*fMatrix[iSttCP][iSttNgay2]*(1 - LE_PHI);
}
printf("\nGia tri dau tu la: %f", f);
printf("\n");
fprintf(fileOut, "Gia tri dau tu la : %f", f);
getch();
system("pause");
}
| [
"tungchengvn@gmail.com"
] | tungchengvn@gmail.com |
3403f89656d3fcfe6db9bf1cab605fe891711831 | a4a03d391f0c911e5b0aed27fe21e4eb36624609 | /POJ/2288/18800446_AC_672ms_25784kB.cpp | f727430ef906fd71b0eaa9a15425fc84627cc5ef | [] | no_license | jiaaaaaaaqi/ACM_Code | 5e689bed9261ba768cfbfa01b39bd8fb0992e560 | 66b222d15544f6477cd04190c0d7397f232ed15e | refs/heads/master | 2020-05-21T21:38:57.727420 | 2019-12-11T14:30:52 | 2019-12-11T14:30:52 | 186,153,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,636 | cpp | /***************************************************************
> File Name : a.cpp
> Author : Jiaaaaaaaqi
> Created Time : 2019年03月19日 星期二 00时31分01秒
***************************************************************/
#include <map>
#include <set>
#include <list>
#include <ctime>
#include <cmath>
#include <stack>
#include <queue>
#include <cfloat>
#include <string>
#include <vector>
#include <cstdio>
#include <bitset>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define lowbit(x) x & (-x)
#define mes(a, b) memset(a, b, sizeof a)
#define fi first
#define se second
#define pii pair<int, int>
typedef unsigned long long int ull;
typedef long long int ll;
const int maxn = 14;
const int maxm = 1e5 + 10;
const ll mod = 1e9 + 7;
const ll INF = 1e18 + 100;
const int inf = 0x3f3f3f3f;
const double pi = acos(-1.0);
const double eps = 1e-8;
using namespace std;
int n, m;
int cas, tol, T;
ll a[maxn];
bool maps[maxn][maxn];
ll dp[1<<maxn][maxn][maxn], num[1<<maxn][maxn][maxn];
void init() {
mes(a, 0);
mes(maps, 0);
int mx = (1<<n)-1;
for(int i=0; i<=mx; i++) {
for(int j=0; j<=n; j++) {
for(int k=0; k<=n; k++) {
dp[i][j][k] = 0;
num[i][j][k] = 0;
}
}
}
}
int main() {
scanf("%d", &T);
while(T--) {
scanf("%d%d", &n, &m);
init();
for(int i=1; i<=n; i++) scanf("%lld", &a[i]);
a[0] = 0;
for(int i=1, u, v; i<=m; i++) {
scanf("%d%d", &u, &v);
maps[u][v] = maps[v][u] = 1;
}
for(int i=1; i<=n; i++) {
dp[1<<(i-1)][0][i] = a[i];
num[1<<(i-1)][0][i] = 1;
maps[0][i] = 1;
}
int mx = (1<<n)-1;
for(int i=1; i<=mx; i++) {
for(int l2=0; l2<=n; l2++) {
for(int l1=1; l1<=n; l1++) {
if(!dp[i][l2][l1]) continue;
if(!maps[l2][l1]) continue;
for(int l0=1; l0<=n; l0++) {
if(!maps[l1][l0]) continue;
if(i & (1<<(l0-1))) continue;
int now = i | (1<<(l0-1));
ll tmp = (dp[i][l2][l1] + a[l0] + a[l0]*a[l1]);
if(maps[l2][l0]) tmp += a[l2]*a[l1]*a[l0];
if(dp[now][l1][l0] < tmp) {
dp[now][l1][l0] = tmp;
num[now][l1][l0] = num[i][l2][l1];
} else if(dp[now][l1][l0] == tmp) {
num[now][l1][l0] += num[i][l2][l1];
}
}
}
}
}
ll ans = 0, tol = 0;
for(int i=0; i<=n; i++) {
for(int j=1; j<=n; j++) {
if(!maps[i][j]) continue;
if(ans < dp[mx][i][j]) {
ans = dp[mx][i][j];
tol = num[mx][i][j];
} else if(ans == dp[mx][i][j]) {
tol += num[mx][i][j];
}
}
}
printf("%lld %lld\n", ans, n==1 ? tol : tol>>1);
}
return 0;
}
| [
"735301510@qq.com"
] | 735301510@qq.com |
5bffa20dae7a285a28b2612765be9f83729ea9a7 | 79d343002bb63a44f8ab0dbac0c9f4ec54078c3a | /lib/libc/include/any-windows-any/msdatsrc.h | f11392f5f56c3a6ac1d535dc2c5ce555d760e605 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"MIT"
] | permissive | ziglang/zig | 4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5 | f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c | refs/heads/master | 2023-08-31T13:16:45.980913 | 2023-08-31T05:50:29 | 2023-08-31T05:50:29 | 40,276,274 | 25,560 | 2,399 | MIT | 2023-09-14T21:09:50 | 2015-08-06T00:51:28 | Zig | UTF-8 | C++ | false | false | 7,480 | h | /**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 440
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __msdatsrc_h__
#define __msdatsrc_h__
#ifndef __DataSourceListener_FWD_DEFINED__
#define __DataSourceListener_FWD_DEFINED__
typedef struct DataSourceListener DataSourceListener;
#endif
#ifndef __DataSource_FWD_DEFINED__
#define __DataSource_FWD_DEFINED__
typedef struct DataSource DataSource;
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef __MIDL_user_allocate_free_DEFINED__
#define __MIDL_user_allocate_free_DEFINED__
void *__RPC_API MIDL_user_allocate(size_t);
void __RPC_API MIDL_user_free(void *);
#endif
#define IDataSource DataSource
#define IDataSourceListener DataSourceListener
EXTERN_C const IID CATID_DataSource;
EXTERN_C const IID CATID_DataConsumer;
extern RPC_IF_HANDLE __MIDL_itf_msdatsrc_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_msdatsrc_0000_v0_0_s_ifspec;
#ifndef __MSDATASRC_LIBRARY_DEFINED__
#define __MSDATASRC_LIBRARY_DEFINED__
typedef BSTR DataMember;
EXTERN_C const IID LIBID_MSDATASRC;
#ifndef __DataSourceListener_INTERFACE_DEFINED__
#define __DataSourceListener_INTERFACE_DEFINED__
EXTERN_C const IID IID_DataSourceListener;
#if defined(__cplusplus) && !defined(CINTERFACE)
struct DataSourceListener : public IUnknown {
public:
virtual HRESULT WINAPI dataMemberChanged(DataMember bstrDM) = 0;
virtual HRESULT WINAPI dataMemberAdded(DataMember bstrDM) = 0;
virtual HRESULT WINAPI dataMemberRemoved(DataMember bstrDM) = 0;
};
#else
typedef struct DataSourceListenerVtbl {
BEGIN_INTERFACE
HRESULT (WINAPI *QueryInterface)(DataSourceListener *This,REFIID riid,void **ppvObject);
ULONG (WINAPI *AddRef)(DataSourceListener *This);
ULONG (WINAPI *Release)(DataSourceListener *This);
HRESULT (WINAPI *dataMemberChanged)(DataSourceListener *This,DataMember bstrDM);
HRESULT (WINAPI *dataMemberAdded)(DataSourceListener *This,DataMember bstrDM);
HRESULT (WINAPI *dataMemberRemoved)(DataSourceListener *This,DataMember bstrDM);
END_INTERFACE
} DataSourceListenerVtbl;
struct DataSourceListener {
CONST_VTBL struct DataSourceListenerVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define DataSourceListener_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject)
#define DataSourceListener_AddRef(This) (This)->lpVtbl->AddRef(This)
#define DataSourceListener_Release(This) (This)->lpVtbl->Release(This)
#define DataSourceListener_dataMemberChanged(This,bstrDM) (This)->lpVtbl->dataMemberChanged(This,bstrDM)
#define DataSourceListener_dataMemberAdded(This,bstrDM) (This)->lpVtbl->dataMemberAdded(This,bstrDM)
#define DataSourceListener_dataMemberRemoved(This,bstrDM) (This)->lpVtbl->dataMemberRemoved(This,bstrDM)
#endif
#endif
HRESULT WINAPI DataSourceListener_dataMemberChanged_Proxy(DataSourceListener *This,DataMember bstrDM);
void __RPC_STUB DataSourceListener_dataMemberChanged_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase);
HRESULT WINAPI DataSourceListener_dataMemberAdded_Proxy(DataSourceListener *This,DataMember bstrDM);
void __RPC_STUB DataSourceListener_dataMemberAdded_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase);
HRESULT WINAPI DataSourceListener_dataMemberRemoved_Proxy(DataSourceListener *This,DataMember bstrDM);
void __RPC_STUB DataSourceListener_dataMemberRemoved_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase);
#endif
#ifndef __DataSource_INTERFACE_DEFINED__
#define __DataSource_INTERFACE_DEFINED__
EXTERN_C const IID IID_DataSource;
#if defined(__cplusplus) && !defined(CINTERFACE)
struct DataSource : public IUnknown {
public:
virtual HRESULT WINAPI getDataMember(DataMember bstrDM,REFIID riid,IUnknown **ppunk) = 0;
virtual HRESULT WINAPI getDataMemberName(__LONG32 lIndex,DataMember *pbstrDM) = 0;
virtual HRESULT WINAPI getDataMemberCount(__LONG32 *plCount) = 0;
virtual HRESULT WINAPI addDataSourceListener(DataSourceListener *pDSL) = 0;
virtual HRESULT WINAPI removeDataSourceListener(DataSourceListener *pDSL) = 0;
};
#else
typedef struct DataSourceVtbl {
BEGIN_INTERFACE
HRESULT (WINAPI *QueryInterface)(DataSource *This,REFIID riid,void **ppvObject);
ULONG (WINAPI *AddRef)(DataSource *This);
ULONG (WINAPI *Release)(DataSource *This);
HRESULT (WINAPI *getDataMember)(DataSource *This,DataMember bstrDM,REFIID riid,IUnknown **ppunk);
HRESULT (WINAPI *getDataMemberName)(DataSource *This,__LONG32 lIndex,DataMember *pbstrDM);
HRESULT (WINAPI *getDataMemberCount)(DataSource *This,__LONG32 *plCount);
HRESULT (WINAPI *addDataSourceListener)(DataSource *This,DataSourceListener *pDSL);
HRESULT (WINAPI *removeDataSourceListener)(DataSource *This,DataSourceListener *pDSL);
END_INTERFACE
} DataSourceVtbl;
struct DataSource {
CONST_VTBL struct DataSourceVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define DataSource_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject)
#define DataSource_AddRef(This) (This)->lpVtbl->AddRef(This)
#define DataSource_Release(This) (This)->lpVtbl->Release(This)
#define DataSource_getDataMember(This,bstrDM,riid,ppunk) (This)->lpVtbl->getDataMember(This,bstrDM,riid,ppunk)
#define DataSource_getDataMemberName(This,lIndex,pbstrDM) (This)->lpVtbl->getDataMemberName(This,lIndex,pbstrDM)
#define DataSource_getDataMemberCount(This,plCount) (This)->lpVtbl->getDataMemberCount(This,plCount)
#define DataSource_addDataSourceListener(This,pDSL) (This)->lpVtbl->addDataSourceListener(This,pDSL)
#define DataSource_removeDataSourceListener(This,pDSL) (This)->lpVtbl->removeDataSourceListener(This,pDSL)
#endif
#endif
HRESULT WINAPI DataSource_getDataMember_Proxy(DataSource *This,DataMember bstrDM,REFIID riid,IUnknown **ppunk);
void __RPC_STUB DataSource_getDataMember_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase);
HRESULT WINAPI DataSource_getDataMemberName_Proxy(DataSource *This,__LONG32 lIndex,DataMember *pbstrDM);
void __RPC_STUB DataSource_getDataMemberName_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase);
HRESULT WINAPI DataSource_getDataMemberCount_Proxy(DataSource *This,__LONG32 *plCount);
void __RPC_STUB DataSource_getDataMemberCount_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase);
HRESULT WINAPI DataSource_addDataSourceListener_Proxy(DataSource *This,DataSourceListener *pDSL);
void __RPC_STUB DataSource_addDataSourceListener_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase);
HRESULT WINAPI DataSource_removeDataSourceListener_Proxy(DataSource *This,DataSourceListener *pDSL);
void __RPC_STUB DataSource_removeDataSourceListener_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase);
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif
| [
"andrew@ziglang.org"
] | andrew@ziglang.org |
408ab838371d3243177a6a126a8754567e9f74c3 | 167f6115169fd842146c4551cf7737d5ef009f14 | /src/ieee.h | b6a43cc5d3848451c6d73591f6850134d69f4a80 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | LLNL/zhw | 18bb50ed0d73e245b549d74d7e8df55211867731 | 1ed49d54326ab007ba6e648c8eec168f40556817 | refs/heads/master | 2023-06-10T18:07:24.150718 | 2022-12-01T20:55:44 | 2022-12-01T20:55:44 | 279,988,557 | 11 | 5 | BSD-3-Clause | 2022-12-01T20:55:46 | 2020-07-15T21:56:18 | C++ | UTF-8 | C++ | false | false | 2,404 | h |
#ifndef IEEE_H
#define IEEE_H
#include "systemc.h"
//-----------------------------------------------------------------------------
// IEEE floating-point type
//-----------------------------------------------------------------------------
template<int E, int F>
struct fp_t {
static constexpr int ebits = E; // exponent bits
static constexpr int fbits = F; // fraction bits
static constexpr int bits = 1+E+F; // total bits
// exponent bias
// When E (bits) = 8, ebias = 127
// When E (bits) = 11, ebias = 1023
static constexpr int ebias = (1 << (E-1))-1;
typedef sc_int <bits> si_t;
typedef sc_uint<bits> ui_t;
typedef sc_uint<F> frac_t;
typedef sc_uint<E> expo_t;
typedef sc_uint<1> sign_t;
frac_t frac;
expo_t expo; // biased by ebias
sign_t sign;
fp_t(ui_t ui)
{
(sign,expo,frac) = ui;
}
fp_t(sc_dt::uint64 ui = 0)
{
(sign,expo,frac) = ui;
}
fp_t& operator=(ui_t ui)
{
(sign,expo,frac) = ui;
return *this;
}
operator ui_t() const
{
return (sign,expo,frac);
}
bool operator==(const fp_t& fp)
{
return
this->frac == fp.frac &&
this->expo == fp.expo &&
this->sign == fp.sign;
}
//---------- conditional int types ----------//
typedef typename std::conditional<bits==32, int, long long>::type sic_t;
typedef typename std::conditional<bits==32, unsigned int, unsigned long long>::type uic_t;
#if !defined(__SYNTHESIS__)
//---------- real_t ----------//
typedef typename std::conditional<bits==32, float, double>::type real_t;
explicit fp_t(real_t r)
{
sc_dt::uint64 ui = 0;
std::memcpy(&ui, &r, sizeof(r));
(sign,expo,frac) = ui;
}
fp_t& operator=(real_t r)
{
sc_dt::uint64 ui = 0;
std::memcpy(&ui, &r, sizeof(r));
(sign,expo,frac) = ui;
return *this;
}
real_t to_real() const
{
sc_dt::uint64 ui = (sign,expo,frac);
real_t r;
std::memcpy(&r, &ui, sizeof(r));
return r;
}
#endif // end !__SYNTHESIS__
};
template<int E, int F>
inline std::ostream& operator<<(std::ostream& os, const fp_t<E,F>& fp)
{
os << hex << fp.sign << ':' << fp.expo << ':' << fp.frac;
#if !defined(__SYNTHESIS__)
os << ", " << fp.to_real();
#endif // end !__SYNTHESIS__
return os;
}
template<int E, int F>
void sc_trace(sc_trace_file* tf, const fp_t<E,F>& ob, const std::string& nm)
{
sc_trace(tf, ob.frac, nm+".frac");
sc_trace(tf, ob.expo, nm+".expo");
sc_trace(tf, ob.sign, nm+".sign");
}
#endif // IEEE_H
| [
"lloyd23@llnl.gov"
] | lloyd23@llnl.gov |
fe445c4e1f1a8878148d434c273db174e98c5e71 | 246789f077d6166acd0880ff28d0cbcc756f1c2e | /src/wallet/wallet.h | 2ef97052d1d539d0883d7a7b31e1fb0063cb2eb7 | [
"MIT"
] | permissive | Jerthade/SteelHorseCoin | ea8b86abd625eaea63aea994b322f28bc2d27e5e | 0fe0d0d742265fea862345ede0498ddba8a10e12 | refs/heads/master | 2020-04-29T05:45:18.091259 | 2019-03-18T03:11:24 | 2019-03-18T03:11:24 | 174,908,499 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,997 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2019 The SteelHorseCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_WALLET_WALLET_H
#define BITCOIN_WALLET_WALLET_H
#include "amount.h"
#include "base58.h"
#include "streams.h"
#include "tinyformat.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include "validationinterface.h"
#include "script/ismine.h"
#include "wallet/crypter.h"
#include "wallet/walletdb.h"
#include "wallet/rpcwallet.h"
#include "privatesend.h"
#include <algorithm>
#include <atomic>
#include <map>
#include <set>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
extern CWallet* pwalletMain;
/**
* Settings
*/
extern CFeeRate payTxFee;
extern unsigned int nTxConfirmTarget;
extern bool bSpendZeroConfChange;
extern bool fSendFreeTransactions;
extern bool bBIP69Enabled;
static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
//! -paytxfee default
static const CAmount DEFAULT_TRANSACTION_FEE = 0;
//! -fallbackfee default
static const CAmount DEFAULT_FALLBACK_FEE = 1000;
//! -mintxfee default
static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
//! minimum recommended increment for BIP 125 replacement txs
static const CAmount WALLET_INCREMENTAL_RELAY_FEE = 5000;
//! target minimum change amount
static const CAmount MIN_CHANGE = CENT;
//! final minimum change amount after paying for fees
static const CAmount MIN_FINAL_CHANGE = MIN_CHANGE/2;
//! Default for -spendzeroconfchange
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
//! Default for -sendfreetransactions
static const bool DEFAULT_SEND_FREE_TRANSACTIONS = false;
//! Default for -walletrejectlongchains
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
//! -txconfirmtarget default
static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
//! Largest (in bytes) free transaction we're willing to create
static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
static const bool DEFAULT_WALLETBROADCAST = true;
static const bool DEFAULT_DISABLE_WALLET = false;
extern const char * DEFAULT_WALLET_DAT;
//! if set, all keys will be derived by using BIP39/BIP44
static const bool DEFAULT_USE_HD_WALLET = false;
bool AutoBackupWallet (CWallet* wallet, const std::string& strWalletFile_, std::string& strBackupWarningRet, std::string& strBackupErrorRet);
class CBlockIndex;
class CCoinControl;
class COutput;
class CReserveKey;
class CScript;
class CTxMemPool;
class CWalletTx;
/** (client) version numbers for particular wallet features */
enum WalletFeature
{
FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
FEATURE_WALLETCRYPT = 40000, // wallet encryption
FEATURE_COMPRPUBKEY = 60000, // compressed public keys
FEATURE_HD = 120200, // Hierarchical key derivation after BIP32 (HD Wallet), BIP44 (multi-coin), BIP39 (mnemonic)
// which uses on-the-fly private key derivation
FEATURE_LATEST = 61000
};
enum AvailableCoinsType
{
ALL_COINS,
ONLY_DENOMINATED,
ONLY_NONDENOMINATED,
ONLY_1000, // find masternode outputs including locked ones (use with caution)
ONLY_PRIVATESEND_COLLATERAL
};
struct CompactTallyItem
{
CTxDestination txdest;
CAmount nAmount;
std::vector<COutPoint> vecOutPoints;
CompactTallyItem()
{
nAmount = 0;
}
};
/** A key pool entry */
class CKeyPool
{
public:
int64_t nTime;
CPubKey vchPubKey;
bool fInternal; // for change outputs
CKeyPool();
CKeyPool(const CPubKey& vchPubKeyIn, bool fInternalIn);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
int nVersion = s.GetVersion();
if (!(s.GetType() & SER_GETHASH))
READWRITE(nVersion);
READWRITE(nTime);
READWRITE(vchPubKey);
if (ser_action.ForRead()) {
try {
READWRITE(fInternal);
}
catch (std::ios_base::failure&) {
/* flag as external address if we can't read the internal boolean
(this will be the case for any wallet before the HD chain split version) */
fInternal = false;
}
}
else {
READWRITE(fInternal);
}
}
};
/** Address book data */
class CAddressBookData
{
public:
std::string name;
std::string purpose;
CAddressBookData()
{
purpose = "unknown";
}
typedef std::map<std::string, std::string> StringMap;
StringMap destdata;
};
struct CRecipient
{
CScript scriptPubKey;
CAmount nAmount;
bool fSubtractFeeFromAmount;
};
typedef std::map<std::string, std::string> mapValue_t;
static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
{
if (!mapValue.count("n"))
{
nOrderPos = -1; // TODO: calculate elsewhere
return;
}
nOrderPos = atoi64(mapValue["n"].c_str());
}
static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
{
if (nOrderPos == -1)
return;
mapValue["n"] = i64tostr(nOrderPos);
}
struct COutputEntry
{
CTxDestination destination;
CAmount amount;
int vout;
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx
{
private:
/** Constant used in hashBlock to indicate tx has been abandoned */
static const uint256 ABANDON_HASH;
public:
CTransactionRef tx;
uint256 hashBlock;
/* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
* block in the chain we know this or any in-wallet dependency conflicts
* with. Older clients interpret nIndex == -1 as unconfirmed for backward
* compatibility.
*/
int nIndex;
CMerkleTx()
{
SetTx(MakeTransactionRef());
Init();
}
CMerkleTx(CTransactionRef arg)
{
SetTx(std::move(arg));
Init();
}
/** Helper conversion operator to allow passing CMerkleTx where CTransaction is expected.
* TODO: adapt callers and remove this operator. */
operator const CTransaction&() const { return *tx; }
void Init()
{
hashBlock = uint256();
nIndex = -1;
}
void SetTx(CTransactionRef arg)
{
tx = std::move(arg);
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
READWRITE(tx);
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
}
void SetMerkleBranch(const CBlockIndex* pIndex, int posInBlock);
/**
* Return depth of transaction in blockchain:
* <0 : conflicts with a transaction this deep in the blockchain
* 0 : in memory pool, waiting to be included in a block
* >=1 : this many blocks deep in the main chain
*/
int GetDepthInMainChain(const CBlockIndex* &pindexRet, bool enableIX = true) const;
int GetDepthInMainChain(bool enableIX = true) const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet, enableIX); }
bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; }
int GetBlocksToMaturity() const;
/** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
bool AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state);
bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
void setAbandoned() { hashBlock = ABANDON_HASH; }
const uint256& GetHash() const { return tx->GetHash(); }
bool IsCoinBase() const { return tx->IsCoinBase(); }
};
/**
* A transaction with a bunch of additional info that only the owner cares about.
* It includes any unrecorded transactions needed to link it back to the block chain.
*/
class CWalletTx : public CMerkleTx
{
private:
const CWallet* pwallet;
public:
mapValue_t mapValue;
std::vector<std::pair<std::string, std::string> > vOrderForm;
unsigned int fTimeReceivedIsTxTime;
unsigned int nTimeReceived; //!< time received by this node
unsigned int nTimeSmart;
/**
* From me flag is set to 1 for transactions that were created by the wallet
* on this bitcoin node, and set to 0 for transactions that were created
* externally and came in through the network or sendrawtransaction RPC.
*/
char fFromMe;
std::string strFromAccount;
int64_t nOrderPos; //!< position in ordered transaction list
// memory only
mutable bool fDebitCached;
mutable bool fCreditCached;
mutable bool fImmatureCreditCached;
mutable bool fAvailableCreditCached;
mutable bool fAnonymizedCreditCached;
mutable bool fDenomUnconfCreditCached;
mutable bool fDenomConfCreditCached;
mutable bool fWatchDebitCached;
mutable bool fWatchCreditCached;
mutable bool fImmatureWatchCreditCached;
mutable bool fAvailableWatchCreditCached;
mutable bool fChangeCached;
mutable CAmount nDebitCached;
mutable CAmount nCreditCached;
mutable CAmount nImmatureCreditCached;
mutable CAmount nAvailableCreditCached;
mutable CAmount nAnonymizedCreditCached;
mutable CAmount nDenomUnconfCreditCached;
mutable CAmount nDenomConfCreditCached;
mutable CAmount nWatchDebitCached;
mutable CAmount nWatchCreditCached;
mutable CAmount nImmatureWatchCreditCached;
mutable CAmount nAvailableWatchCreditCached;
mutable CAmount nChangeCached;
CWalletTx()
{
Init(NULL);
}
CWalletTx(const CWallet* pwalletIn, CTransactionRef arg) : CMerkleTx(std::move(arg))
{
Init(pwalletIn);
}
void Init(const CWallet* pwalletIn)
{
pwallet = pwalletIn;
mapValue.clear();
vOrderForm.clear();
fTimeReceivedIsTxTime = false;
nTimeReceived = 0;
nTimeSmart = 0;
fFromMe = false;
strFromAccount.clear();
fDebitCached = false;
fCreditCached = false;
fImmatureCreditCached = false;
fAvailableCreditCached = false;
fAnonymizedCreditCached = false;
fDenomUnconfCreditCached = false;
fDenomConfCreditCached = false;
fWatchDebitCached = false;
fWatchCreditCached = false;
fImmatureWatchCreditCached = false;
fAvailableWatchCreditCached = false;
fChangeCached = false;
nDebitCached = 0;
nCreditCached = 0;
nImmatureCreditCached = 0;
nAvailableCreditCached = 0;
nAnonymizedCreditCached = 0;
nDenomUnconfCreditCached = 0;
nDenomConfCreditCached = 0;
nWatchDebitCached = 0;
nWatchCreditCached = 0;
nAvailableWatchCreditCached = 0;
nImmatureWatchCreditCached = 0;
nChangeCached = 0;
nOrderPos = -1;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
if (ser_action.ForRead())
Init(NULL);
char fSpent = false;
if (!ser_action.ForRead())
{
mapValue["fromaccount"] = strFromAccount;
WriteOrderPos(nOrderPos, mapValue);
if (nTimeSmart)
mapValue["timesmart"] = strprintf("%u", nTimeSmart);
}
READWRITE(*(CMerkleTx*)this);
std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
READWRITE(vUnused);
READWRITE(mapValue);
READWRITE(vOrderForm);
READWRITE(fTimeReceivedIsTxTime);
READWRITE(nTimeReceived);
READWRITE(fFromMe);
READWRITE(fSpent);
if (ser_action.ForRead())
{
strFromAccount = mapValue["fromaccount"];
ReadOrderPos(nOrderPos, mapValue);
nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
}
mapValue.erase("fromaccount");
mapValue.erase("version");
mapValue.erase("spent");
mapValue.erase("n");
mapValue.erase("timesmart");
}
//! make sure balances are recalculated
void MarkDirty()
{
fCreditCached = false;
fAvailableCreditCached = false;
fImmatureCreditCached = false;
fAnonymizedCreditCached = false;
fDenomUnconfCreditCached = false;
fDenomConfCreditCached = false;
fWatchDebitCached = false;
fWatchCreditCached = false;
fAvailableWatchCreditCached = false;
fImmatureWatchCreditCached = false;
fDebitCached = false;
fChangeCached = false;
}
void BindWallet(CWallet *pwalletIn)
{
pwallet = pwalletIn;
MarkDirty();
}
//! filter decides which addresses will count towards the debit
CAmount GetDebit(const isminefilter& filter) const;
CAmount GetCredit(const isminefilter& filter) const;
CAmount GetImmatureCredit(bool fUseCache=true) const;
CAmount GetAvailableCredit(bool fUseCache=true) const;
CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
CAmount GetChange() const;
CAmount GetAnonymizedCredit(bool fUseCache=true) const;
CAmount GetDenominatedCredit(bool unconfirmed, bool fUseCache=true) const;
void GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
bool IsFromMe(const isminefilter& filter) const
{
return (GetDebit(filter) > 0);
}
// True if only scriptSigs are different
bool IsEquivalentTo(const CWalletTx& tx) const;
bool InMempool() const;
bool IsTrusted() const;
int64_t GetTxTime() const;
int GetRequestCount() const;
bool RelayWalletTransaction(CConnman* connman, const std::string& strCommand="tx");
std::set<uint256> GetConflicts() const;
};
class COutput
{
public:
const CWalletTx *tx;
int i;
int nDepth;
bool fSpendable;
bool fSolvable;
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn)
{
tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn;
}
//Used with Darksend. Will return largest nondenom, then denominations, then very small inputs
int Priority() const;
std::string ToString() const;
};
/** Private key that includes an expiration date in case it never gets used. */
class CWalletKey
{
public:
CPrivKey vchPrivKey;
int64_t nTimeCreated;
int64_t nTimeExpires;
std::string strComment;
//! todo: add something to note what created it (user, getnewaddress, change)
//! maybe should have a map<string, string> property map
CWalletKey(int64_t nExpires=0);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
int nVersion = s.GetVersion();
if (!(s.GetType() & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPrivKey);
READWRITE(nTimeCreated);
READWRITE(nTimeExpires);
READWRITE(LIMITED_STRING(strComment, 65536));
}
};
/**
* Internal transfers.
* Database key is acentry<account><counter>.
*/
class CAccountingEntry
{
public:
std::string strAccount;
CAmount nCreditDebit;
int64_t nTime;
std::string strOtherAccount;
std::string strComment;
mapValue_t mapValue;
int64_t nOrderPos; //!< position in ordered transaction list
uint64_t nEntryNo;
CAccountingEntry()
{
SetNull();
}
void SetNull()
{
nCreditDebit = 0;
nTime = 0;
strAccount.clear();
strOtherAccount.clear();
strComment.clear();
nOrderPos = -1;
nEntryNo = 0;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
int nVersion = s.GetVersion();
if (!(s.GetType() & SER_GETHASH))
READWRITE(nVersion);
//! Note: strAccount is serialized as part of the key, not here.
READWRITE(nCreditDebit);
READWRITE(nTime);
READWRITE(LIMITED_STRING(strOtherAccount, 65536));
if (!ser_action.ForRead())
{
WriteOrderPos(nOrderPos, mapValue);
if (!(mapValue.empty() && _ssExtra.empty()))
{
CDataStream ss(s.GetType(), s.GetVersion());
ss.insert(ss.begin(), '\0');
ss << mapValue;
ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
strComment.append(ss.str());
}
}
READWRITE(LIMITED_STRING(strComment, 65536));
size_t nSepPos = strComment.find("\0", 0, 1);
if (ser_action.ForRead())
{
mapValue.clear();
if (std::string::npos != nSepPos)
{
CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), s.GetType(), s.GetVersion());
ss >> mapValue;
_ssExtra = std::vector<char>(ss.begin(), ss.end());
}
ReadOrderPos(nOrderPos, mapValue);
}
if (std::string::npos != nSepPos)
strComment.erase(nSepPos);
mapValue.erase("n");
}
private:
std::vector<char> _ssExtra;
};
/**
* A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
* and provides the ability to create new transactions.
*/
class CWallet : public CCryptoKeyStore, public CValidationInterface
{
private:
static std::atomic<bool> fFlushThreadRunning;
/**
* Select a set of coins such that nValueRet >= nTargetValue and at least
* all coins from coinControl are selected; Never select unconfirmed coins
* if they are not ours
*/
bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend = true) const;
CWalletDB *pwalletdbEncryption;
//! the current wallet version: clients below this version are not able to load the wallet
int nWalletVersion;
//! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
int nWalletMaxVersion;
int64_t nNextResend;
int64_t nLastResend;
bool fBroadcastTransactions;
mutable bool fAnonymizableTallyCached;
mutable std::vector<CompactTallyItem> vecAnonymizableTallyCached;
mutable bool fAnonymizableTallyCachedNonDenom;
mutable std::vector<CompactTallyItem> vecAnonymizableTallyCachedNonDenom;
/**
* Used to keep track of spent outpoints, and
* detect and report conflicts (double-spends or
* mutated transactions where the mutant gets mined).
*/
typedef std::multimap<COutPoint, uint256> TxSpends;
TxSpends mapTxSpends;
void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
void AddToSpends(const uint256& wtxid);
std::set<COutPoint> setWalletUTXO;
/* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
/* HD derive new child key (on internal or external chain) */
void DeriveNewChildKey(const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal /*= false*/);
bool fFileBacked;
std::set<int64_t> setInternalKeyPool;
std::set<int64_t> setExternalKeyPool;
int64_t nTimeFirstKey;
/**
* Private version of AddWatchOnly method which does not accept a
* timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
* the watch key did not previously have a timestamp associated with it.
* Because this is an inherited virtual method, it is accessible despite
* being marked private, but it is marked private anyway to encourage use
* of the other AddWatchOnly which accepts a timestamp and sets
* nTimeFirstKey more intelligently for more efficient rescans.
*/
bool AddWatchOnly(const CScript& dest) override;
public:
/*
* Main wallet lock.
* This lock protects all the fields added by CWallet
* except for:
* fFileBacked (immutable after instantiation)
* strWalletFile (immutable after instantiation)
*/
mutable CCriticalSection cs_wallet;
const std::string strWalletFile;
void LoadKeyPool(int nIndex, const CKeyPool &keypool)
{
if (keypool.fInternal) {
setInternalKeyPool.insert(nIndex);
} else {
setExternalKeyPool.insert(nIndex);
}
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (mapKeyMetadata.count(keyid) == 0)
mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
// Map from Key ID (for regular keys) or Script ID (for watch-only keys) to
// key metadata.
std::map<CTxDestination, CKeyMetadata> mapKeyMetadata;
typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
MasterKeyMap mapMasterKeys;
unsigned int nMasterKeyMaxID;
CWallet()
{
SetNull();
}
CWallet(const std::string& strWalletFileIn)
: strWalletFile(strWalletFileIn)
{
SetNull();
fFileBacked = true;
}
~CWallet()
{
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
}
void SetNull()
{
nWalletVersion = FEATURE_BASE;
nWalletMaxVersion = FEATURE_BASE;
fFileBacked = false;
nMasterKeyMaxID = 0;
pwalletdbEncryption = NULL;
nOrderPosNext = 0;
nNextResend = 0;
nLastResend = 0;
nTimeFirstKey = 0;
fBroadcastTransactions = false;
fAnonymizableTallyCached = false;
fAnonymizableTallyCachedNonDenom = false;
vecAnonymizableTallyCached.clear();
vecAnonymizableTallyCachedNonDenom.clear();
}
std::map<uint256, CWalletTx> mapWallet;
std::list<CAccountingEntry> laccentries;
typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef std::multimap<int64_t, TxPair > TxItems;
TxItems wtxOrdered;
int64_t nOrderPosNext;
std::map<uint256, int> mapRequestCount;
std::map<CTxDestination, CAddressBookData> mapAddressBook;
CPubKey vchDefaultKey;
std::set<COutPoint> setLockedCoins;
int64_t nKeysLeftSinceAutoBackup;
std::map<CKeyID, CHDPubKey> mapHdPubKeys; //<! memory map of HD extended pubkeys
const CWalletTx* GetWalletTx(const uint256& hash) const;
//! check whether we are allowed to upgrade (or already support) to the named feature
bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
/**
* populate vCoins with vector of available COutputs.
*/
void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend = false) const;
/**
* Shuffle and select coins until nTargetValue is reached while avoiding
* small change; This method is stochastic for some inputs and upon
* completion the coin set and corresponding actual target value is
* assembled
*/
bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool fUseInstantSend = false) const;
// Coin selection
bool SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxDSIn>& vecTxDSInRet, std::vector<COutput>& vCoinsRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax);
bool GetCollateralTxDSIn(CTxDSIn& txdsinRet, CAmount& nValueRet) const;
bool SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vecTxInRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax) const;
bool SelectCoinsGrouppedByAddresses(std::vector<CompactTallyItem>& vecTallyRet, bool fSkipDenominated = true, bool fAnonymizable = true, bool fSkipUnconfirmed = true) const;
/// Get 1000STHC output and keys which can be used for the Masternode
bool GetMasternodeOutpointAndKeys(COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet, const std::string& strTxHash = "", const std::string& strOutputIndex = "");
/// Extract txin information and keys from output
bool GetOutpointAndKeysFromOutput(const COutput& out, COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet);
bool HasCollateralInputs(bool fOnlyConfirmed = true) const;
int CountInputsWithAmount(CAmount nInputAmount);
// get the PrivateSend chain depth for a given input
int GetRealOutpointPrivateSendRounds(const COutPoint& outpoint, int nRounds) const;
// respect current settings
int GetOutpointPrivateSendRounds(const COutPoint& outpoint) const;
bool IsDenominated(const COutPoint& outpoint) const;
bool IsSpent(const uint256& hash, unsigned int n) const;
bool IsLockedCoin(uint256 hash, unsigned int n) const;
void LockCoin(const COutPoint& output);
void UnlockCoin(const COutPoint& output);
void UnlockAllCoins();
void ListLockedCoins(std::vector<COutPoint>& vOutpts);
/**
* keystore implementation
* Generate a new key
*/
CPubKey GenerateNewKey(uint32_t nAccountIndex, bool fInternal /*= false*/);
//! HaveKey implementation that also checks the mapHdPubKeys
bool HaveKey(const CKeyID &address) const override;
//! GetPubKey implementation that also checks the mapHdPubKeys
bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const override;
//! GetKey implementation that can derive a HD private key on the fly
bool GetKey(const CKeyID &address, CKey& keyOut) const override;
//! Adds a HDPubKey into the wallet(database)
bool AddHDPubKey(const CExtPubKey &extPubKey, bool fInternal);
//! loads a HDPubKey into the wallets memory
bool LoadHDPubKey(const CHDPubKey &hdPubKey);
//! Adds a key to the store, and saves it to disk.
bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
//! Adds a key to the store, without saving it to disk (used by LoadWallet)
bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
//! Load metadata (used by LoadWallet)
bool LoadKeyMetadata(const CTxDestination& pubKey, const CKeyMetadata &metadata);
bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
void UpdateTimeFirstKey(int64_t nCreateTime);
//! Adds an encrypted key to the store, and saves it to disk.
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) override;
//! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
bool AddCScript(const CScript& redeemScript) override;
bool LoadCScript(const CScript& redeemScript);
//! Adds a destination data tuple to the store, and saves it to disk
bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
//! Erases a destination data tuple in the store and on disk
bool EraseDestData(const CTxDestination &dest, const std::string &key);
//! Adds a destination data tuple to the store, without saving it to disk
bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
//! Look up a destination data tuple in the store, return true if found false otherwise
bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
//! Adds a watch-only address to the store, and saves it to disk.
bool AddWatchOnly(const CScript& dest, int64_t nCreateTime);
bool RemoveWatchOnly(const CScript &dest) override;
//! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool LoadWatchOnly(const CScript &dest);
bool Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnly = false);
bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
bool EncryptWallet(const SecureString& strWalletPassphrase);
void GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const;
/**
* Increment the next transaction order id
* @return next transaction order id
*/
int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
DBErrors ReorderTransactions();
bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = "");
bool GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew = false);
void MarkDirty();
bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
bool LoadToWallet(const CWalletTx& wtxIn);
void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock) override;
bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate);
CBlockIndex* ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
void ReacceptWalletTransactions();
void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman) override;
std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman);
CAmount GetBalance() const;
CAmount GetUnconfirmedBalance() const;
CAmount GetImmatureBalance() const;
CAmount GetWatchOnlyBalance() const;
CAmount GetUnconfirmedWatchOnlyBalance() const;
CAmount GetImmatureWatchOnlyBalance() const;
CAmount GetAnonymizableBalance(bool fSkipDenominated = false, bool fSkipUnconfirmed = true) const;
CAmount GetAnonymizedBalance() const;
float GetAverageAnonymizedRounds() const;
CAmount GetNormalizedAnonymizedBalance() const;
CAmount GetNeedsToBeAnonymizedBalance(CAmount nMinBalance = 0) const;
CAmount GetDenominatedBalance(bool unconfirmed=false) const;
bool GetBudgetSystemCollateralTX(CTransactionRef& tx, uint256 hash, CAmount amount, bool fUseInstantSend);
bool GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, CAmount amount, bool fUseInstantSend);
/**
* Insert additional inputs into the transaction by
* calling CreateTransaction();
*/
bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, bool keepReserveKey = true, const CTxDestination& destChange = CNoDestination());
/**
* Create a new transaction paying the recipients with a set of coins
* selected by SelectCoins(); Also create the change output, when needed
* @note passing nChangePosInOut as -1 will result in setting a random position
*/
bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend=false);
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state, const std::string& strCommand="tx");
bool CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason);
bool ConvertList(std::vector<CTxIn> vecTxIn, std::vector<CAmount>& vecAmounts);
void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries);
bool AddAccountingEntry(const CAccountingEntry&);
bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb);
static CFeeRate minTxFee;
static CFeeRate fallbackFee;
/**
* Estimate the minimum fee considering user set parameters
* and the required fee
*/
static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
/**
* Estimate the minimum fee considering required fee and targetFee or if 0
* then fee estimation for nConfirmTarget
*/
static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, CAmount targetFee);
/**
* Return the minimum required fee taking into account the
* floating relay fee and user set minimum transaction fee
*/
static CAmount GetRequiredFee(unsigned int nTxBytes);
bool NewKeyPool();
size_t KeypoolCountExternalKeys();
size_t KeypoolCountInternalKeys();
bool TopUpKeyPool(unsigned int kpSize = 0);
void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fInternal);
void KeepKey(int64_t nIndex);
void ReturnKey(int64_t nIndex, bool fInternal);
bool GetKeyFromPool(CPubKey &key, bool fInternal /*= false*/);
int64_t GetOldestKeyPoolTime();
void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
std::set< std::set<CTxDestination> > GetAddressGroupings();
std::map<CTxDestination, CAmount> GetAddressBalances();
CAmount GetAccountBalance(const std::string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf);
CAmount GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf);
std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
isminetype IsMine(const CTxIn& txin) const;
/**
* Returns amount of debit if the input matches the
* filter, otherwise returns 0
*/
CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
isminetype IsMine(const CTxOut& txout) const;
CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
bool IsChange(const CTxOut& txout) const;
CAmount GetChange(const CTxOut& txout) const;
bool IsMine(const CTransaction& tx) const;
/** should probably be renamed to IsRelevantToMe */
bool IsFromMe(const CTransaction& tx) const;
CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
/** Returns whether all of the inputs match the filter */
bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
CAmount GetChange(const CTransaction& tx) const;
void SetBestChain(const CBlockLocator& loc) override;
DBErrors LoadWallet(bool& fFirstRunRet);
DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut);
bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
bool DelAddressBook(const CTxDestination& address);
bool UpdatedTransaction(const uint256 &hashTx) override;
void Inventory(const uint256 &hash) override
{
{
LOCK(cs_wallet);
std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
if (mi != mapRequestCount.end())
(*mi).second++;
}
}
void GetScriptForMining(boost::shared_ptr<CReserveScript> &script) override;
void ResetRequestCount(const uint256 &hash) override
{
LOCK(cs_wallet);
mapRequestCount[hash] = 0;
};
unsigned int GetKeyPoolSize()
{
AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool
return setInternalKeyPool.size() + setExternalKeyPool.size();
}
bool SetDefaultKey(const CPubKey &vchPubKey);
//! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
//! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
bool SetMaxVersion(int nVersion);
//! get the current wallet format (the oldest client version guaranteed to understand this wallet)
int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
//! Get wallet transactions that conflict with given transaction (spend same outputs)
std::set<uint256> GetConflicts(const uint256& txid) const;
//! Flush wallet (bitdb flush)
void Flush(bool shutdown=false);
//! Verify the wallet database and perform salvage if required
static bool Verify();
/**
* Address book entry changed.
* @note called with lock cs_wallet held.
*/
boost::signals2::signal<void (CWallet *wallet, const CTxDestination
&address, const std::string &label, bool isMine,
const std::string &purpose,
ChangeType status)> NotifyAddressBookChanged;
/**
* Wallet transaction added, removed or updated.
* @note called with lock cs_wallet held.
*/
boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
ChangeType status)> NotifyTransactionChanged;
/** Show progress e.g. for rescan */
boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
/** Watch-only address added */
boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
/** Inquire whether this wallet broadcasts transactions. */
bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
/** Set whether this wallet broadcasts transactions. */
void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
/* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
bool AbandonTransaction(const uint256& hashTx);
/* Returns the wallets help message */
static std::string GetWalletHelpString(bool showDebug);
/* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
static CWallet* CreateWalletFromFile(const std::string walletFile);
static bool InitLoadWallet();
/**
* Wallet post-init setup
* Gives the wallet a chance to register repetitive tasks and complete post-init tasks
*/
void postInitProcess(boost::thread_group& threadGroup);
/* Wallets parameter interaction */
static bool ParameterInteraction();
/* Initialize AutoBackup functionality */
static bool InitAutoBackup();
bool BackupWallet(const std::string& strDest);
/**
* HD Wallet Functions
*/
/* Returns true if HD is enabled */
bool IsHDEnabled();
/* Generates a new HD chain */
void GenerateNewHDChain();
/* Set the HD chain model (chain child index counters) */
bool SetHDChain(const CHDChain& chain, bool memonly);
bool SetCryptedHDChain(const CHDChain& chain, bool memonly);
bool GetDecryptedHDChain(CHDChain& hdChainRet);
};
/** A key allocated from the key pool. */
class CReserveKey : public CReserveScript
{
protected:
CWallet* pwallet;
int64_t nIndex;
CPubKey vchPubKey;
bool fInternal;
public:
CReserveKey(CWallet* pwalletIn)
{
nIndex = -1;
pwallet = pwalletIn;
fInternal = false;
}
~CReserveKey()
{
ReturnKey();
}
void ReturnKey();
bool GetReservedKey(CPubKey &pubkey, bool fInternalIn /*= false*/);
void KeepKey();
void KeepScript() override { KeepKey(); }
};
/**
* Account information.
* Stored in wallet with key "acc"+string account name.
*/
class CAccount
{
public:
CPubKey vchPubKey;
CAccount()
{
SetNull();
}
void SetNull()
{
vchPubKey = CPubKey();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
int nVersion = s.GetVersion();
if (!(s.GetType() & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPubKey);
}
};
#endif // BITCOIN_WALLET_WALLET_H
| [
"jerthade@gmail.com"
] | jerthade@gmail.com |
e35456e4165dee72aa199174277ab805ed4cd37c | 55d560fe6678a3edc9232ef14de8fafd7b7ece12 | /libs/tti/test/test_has_template_cp_compile.cpp | 292a4434d75e0b53d13d9b71ace933fa004be512 | [
"BSL-1.0"
] | permissive | stardog-union/boost | ec3abeeef1b45389228df031bf25b470d3d123c5 | caa4a540db892caa92e5346e0094c63dea51cbfb | refs/heads/stardog/develop | 2021-06-25T02:15:10.697006 | 2020-11-17T19:50:35 | 2020-11-17T19:50:35 | 148,681,713 | 0 | 0 | BSL-1.0 | 2020-11-17T19:50:36 | 2018-09-13T18:38:54 | C++ | UTF-8 | C++ | false | false | 970 | cpp |
// (C) Copyright Edward Diener 2011
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#include "test_has_template_cp.hpp"
#include <boost/mpl/assert.hpp>
int main()
{
// You can always instantiate without compiler errors
BOOST_TTI_HAS_TEMPLATE_GEN(TemplateNotExist)<AnotherType> aVar1;
// Compile time asserts
BOOST_MPL_ASSERT((BOOST_TTI_HAS_TEMPLATE_GEN(ATPMemberTemplate)<AType>));
BOOST_MPL_ASSERT((BOOST_TTI_HAS_TEMPLATE_GEN(AMemberTemplate)<AType>));
BOOST_MPL_ASSERT((BOOST_TTI_HAS_TEMPLATE_GEN(SomeMemberTemplate)<AnotherType>));
BOOST_MPL_ASSERT((BOOST_TTI_HAS_TEMPLATE_GEN(SimpleTMP)<AnotherType>));
BOOST_MPL_ASSERT((HaveCL<AType>));
BOOST_MPL_ASSERT((HaveAnotherMT<AType>));
BOOST_MPL_ASSERT((ATemplateWithParms<AnotherType>));
return 0;
}
| [
"james.pack@stardog.com"
] | james.pack@stardog.com |
d2c63cd33cb4122d37d6ddf462e17a16955ffd9d | b3a3b060498764a0bc11945eed0e3f8960752f52 | /inference/LinearSolver.h | c805e76c75669c841df0df3ec4a31fca0dcdd3bb | [] | no_license | ottj/sopnet | f3bf7a640473e0c848c9ab1054ab77205364b2a6 | 1b0a789dbc8b902aa3f74f8c9263c1fef21e01bd | refs/heads/master | 2021-01-18T11:59:54.761357 | 2012-07-17T23:15:18 | 2012-07-17T23:15:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,029 | h | #ifndef INFERENCE_LINEAR_SOLVER_H__
#define INFERENCE_LINEAR_SOLVER_H__
#include <string>
#include <boost/shared_ptr.hpp>
#include <pipeline/all.h>
#include "DefaultFactory.h"
#include "LinearConstraints.h"
#include "LinearObjective.h"
#include "LinearSolverBackend.h"
#include "LinearSolverBackendFactory.h"
#include "LinearSolverParameters.h"
#include "Solution.h"
/**
* Abstract class for linear program solvers. Implementations are supposed to
* solve the following (integer) linear program:
*
* min <a,x>
* s.t. Ax == b
* Cx <= d
* optionally: x_i \in {0,1} for all i
*
* Where (A,b) describes all linear equality constraints, (C,d) all linear
* inequality constraints and x is the solution vector. a is a real-valued
* vector denoting the coefficients of the objective.
*
* The implementation is supposed to accept the inputs
*
* objective : LinearObjective
* constraints : LinearConstraints
* parameters : SolverParameters
*
* and provide the output
*
* solution : Solution.
*/
class LinearSolver : public pipeline::SimpleProcessNode {
public:
LinearSolver(const LinearSolverBackendFactory& backendFactory = DefaultFactory());
~LinearSolver();
private:
void onObjectiveModified(const pipeline::Modified& signal);
void onLinearConstraintsModified(const pipeline::Modified& signal);
void onParametersModified(const pipeline::Modified& signal);
////////////////////////
// pipeline interface //
////////////////////////
pipeline::Input<LinearObjective> _objective;
pipeline::Input<LinearConstraints> _linearConstraints;
pipeline::Input<LinearSolverParameters> _parameters;
pipeline::Output<Solution> _solution;
void updateOutputs();
////////////////////
// solver backend //
////////////////////
void updateLinearProgram();
void solve();
unsigned int getNumVariables();
LinearSolverBackend* _solver;
bool _objectiveDirty;
bool _linearConstraintsDirty;
bool _parametersDirty;
};
#endif // INFERENCE_LINEAR_SOLVER_H__
| [
"funke@ini.ch"
] | funke@ini.ch |
4383ea8060a0fc44dfae97f77c56498641c6f843 | 73e7c20803be5d8ae467af1feba8a4a7fe219f4b | /Modules/Filtering/LabelMap/include/itkShapeUniqueLabelMapFilter.h | fbd0386bebdb81de302f77337bbf762eb303c42d | [
"LicenseRef-scancode-other-permissive",
"SMLNJ",
"BSD-3-Clause",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-free-unknown",
"BSD-4.3TAHOE",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"IJG",
... | permissive | CIBC-Internal/itk | deaa8aabe3995f3465ec70a46805bd333967ed5b | 6f7b1014a73857115d6da738583492008bea8205 | refs/heads/master | 2021-01-10T18:48:58.502855 | 2018-01-26T21:25:51 | 2018-01-26T21:25:51 | 31,582,564 | 0 | 2 | Apache-2.0 | 2018-05-21T07:59:53 | 2015-03-03T06:12:12 | C++ | UTF-8 | C++ | false | false | 11,626 | h | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 itkShapeUniqueLabelMapFilter_h
#define itkShapeUniqueLabelMapFilter_h
#include "itkInPlaceLabelMapFilter.h"
#include "itkShapeLabelObjectAccessors.h"
#include "itkProgressReporter.h"
#include <queue>
#include "itkMath.h"
namespace itk
{
/** \class ShapeUniqueLabelMapFilter
* \brief Remove some pixels in the label object according to the value of their shape attribute to ensure that a pixel is not in to objects
*
* \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.
*
* This implementation was taken from the Insight Journal paper:
* https://hdl.handle.net/1926/584 or
* http://www.insight-journal.org/browse/publication/176
*
* \sa ShapeLabelObject, BinaryShapeOpeningImageFilter, LabelStatisticsOpeningImageFilter
* \ingroup ImageEnhancement MathematicalMorphologyImageFilters
* \ingroup ITKLabelMap
*/
template< typename TImage >
class ShapeUniqueLabelMapFilter:
public InPlaceLabelMapFilter< TImage >
{
public:
/** Standard class typedefs. */
typedef ShapeUniqueLabelMapFilter Self;
typedef InPlaceLabelMapFilter< TImage > Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
/** Some convenient typedefs. */
typedef TImage ImageType;
typedef typename ImageType::Pointer ImagePointer;
typedef typename ImageType::ConstPointer ImageConstPointer;
typedef typename ImageType::PixelType PixelType;
typedef typename ImageType::IndexType IndexType;
typedef typename ImageType::LabelObjectType LabelObjectType;
typedef typename LabelObjectType::LineType LineType;
typedef typename LabelObjectType::AttributeType AttributeType;
/** ImageDimension constants */
itkStaticConstMacro(ImageDimension, unsigned int,
TImage::ImageDimension);
/** Standard New method. */
itkNewMacro(Self);
/** Runtime information support. */
itkTypeMacro(ShapeUniqueLabelMapFilter,
InPlaceLabelMapFilter);
#ifdef ITK_USE_CONCEPT_CHECKING
// Begin concept checking
/* itkConceptMacro(InputEqualityComparableCheck,
(Concept::EqualityComparable<InputImagePixelType>));
itkConceptMacro(IntConvertibleToInputCheck,
(Concept::Convertible<int, InputImagePixelType>));
itkConceptMacro(InputOStreamWritableCheck,
(Concept::OStreamWritable<InputImagePixelType>));*/
// End concept checking
#endif
/**
* Set/Get the ordering of the objects. By default, the objects with
* a the largest attribute value are kept. If set to true, the filter
* to keeps the object with the smallest attribute instead.
*/
itkGetConstMacro(ReverseOrdering, bool);
itkSetMacro(ReverseOrdering, bool);
itkBooleanMacro(ReverseOrdering);
/**
* Set/Get the attribute to use to select the object to remove. The default
* is "Size".
*/
itkGetConstMacro(Attribute, AttributeType);
itkSetMacro(Attribute, AttributeType);
void SetAttribute(const std::string & s)
{
this->SetAttribute( LabelObjectType::GetAttributeFromName(s) );
}
protected:
ShapeUniqueLabelMapFilter();
~ShapeUniqueLabelMapFilter() {}
virtual void GenerateData() ITK_OVERRIDE;
template< typename TAttributeAccessor >
void TemplatedGenerateData(const TAttributeAccessor & accessor)
{
// Allocate the output
this->AllocateOutputs();
// the priority queue to store all the lines of all the objects sorted
typedef typename std::priority_queue< LineOfLabelObject, std::vector< LineOfLabelObject >,
LineOfLabelObjectComparator > PriorityQueueType;
PriorityQueueType priorityQueue;
ProgressReporter progress(this, 0, 1);
// TODO: really report the progress
for ( typename ImageType::Iterator it( this->GetLabelMap() );
! it.IsAtEnd();
++it )
{
LabelObjectType *labelObject = it.GetLabelObject();
// may reduce the number of lines to proceed
labelObject->Optimize();
typename LabelObjectType::ConstLineIterator lit( labelObject );
while( ! lit.IsAtEnd() )
{
priorityQueue.push( LineOfLabelObject(lit.GetLine(), labelObject) );
++lit;
}
// clear the lines to read them later
labelObject->Clear();
// go to the next label
// progress.CompletedPixel();
}
if ( priorityQueue.empty() )
{
// nothing to do
return;
}
typedef typename std::deque< LineOfLabelObject > LinesType;
LinesType lines;
lines.push_back( priorityQueue.top() );
LineOfLabelObject prev = lines.back();
IndexType prevIdx = prev.line.GetIndex();
priorityQueue.pop();
while ( !priorityQueue.empty() )
{
LineOfLabelObject l = priorityQueue.top();
IndexType idx = l.line.GetIndex();
priorityQueue.pop();
bool newMainLine = false;
// don't check dim 0!
for ( unsigned int i = 1; i < ImageDimension; i++ )
{
if ( idx[i] != prevIdx[i] )
{
newMainLine = true;
}
}
if ( newMainLine )
{
// just push the line
lines.push_back(l);
}
else
{
OffsetValueType prevLength = prev.line.GetLength();
OffsetValueType length = l.line.GetLength();
if ( prevIdx[0] + prevLength >= idx[0] )
{
// the lines are overlapping. We need to choose which line to keep.
// the label, the only "attribute" to be guaranteed to be unique, is
// used to choose
// which line to keep. This is necessary to avoid the case where a
// part of a label is over
// a second label, and below in another part of the image.
bool keepCurrent;
typename TAttributeAccessor::AttributeValueType prevAttr = accessor(prev.labelObject);
typename TAttributeAccessor::AttributeValueType attr = accessor(l.labelObject);
// this may be changed to a single boolean expression, but may become
// quite difficult to read
if ( Math::ExactlyEquals(attr, prevAttr) )
{
if ( l.labelObject->GetLabel() > prev.labelObject->GetLabel() )
{
keepCurrent = !m_ReverseOrdering;
}
else
{
keepCurrent = m_ReverseOrdering;
}
}
else
{
if ( attr > prevAttr )
{
keepCurrent = !m_ReverseOrdering;
}
else
{
keepCurrent = m_ReverseOrdering;
}
}
if ( keepCurrent )
{
// keep the current one. We must truncate the previous one to remove
// the
// overlap, and take care of the end of the previous line if it
// extends
// after the current one.
if ( prevIdx[0] + prevLength > idx[0] + length )
{
// the previous line is longer than the current one. Lets take its
// tail and
// add it to the priority queue
IndexType newIdx = idx;
newIdx[0] = idx[0] + length;
OffsetValueType newLength = prevIdx[0] + prevLength - newIdx[0];
priorityQueue.push( LineOfLabelObject(LineType(newIdx, newLength), prev.labelObject) );
}
// truncate the previous line to let some place for the current one
prevLength = idx[0] - prevIdx[0];
if ( prevLength != 0 )
{
lines.back(). line.SetLength(idx[0] - prevIdx[0]);
}
else
{
// length is 0 - no need to keep that line
lines.pop_back();
}
// and push the current one
lines.push_back(l);
}
else
{
// keep the previous one. If the previous line fully overlap the
// current one,
// the current one is fully discarded.
if ( prevIdx[0] + prevLength > idx[0] + length )
{
// discarding the current line - just do nothing
}
else
{
IndexType newIdx = idx;
newIdx[0] = prevIdx[0] + prevLength;
OffsetValueType newLength = idx[0] + length - newIdx[0];
l.line.SetIndex(newIdx);
l.line.SetLength(newLength);
lines.push_back(l);
}
}
}
else
{
// no overlap - things are just fine already
lines.push_back(l);
}
}
// store the current line as the previous one, and go to the next one.
prev = lines.back();
prevIdx = prev.line.GetIndex();
}
// put the lines in their object
for ( size_t i = 0; i < lines.size(); ++i )
{
LineOfLabelObject & l = lines[i];
l.labelObject->AddLine(l.line);
}
// remove objects without lines
typename ImageType::Iterator it( this->GetLabelMap() );
while ( ! it.IsAtEnd() )
{
typename LabelObjectType::LabelType label = it.GetLabel();
LabelObjectType *labelObject = it.GetLabelObject();
if ( labelObject->Empty() )
{
// must increment the iterator before removing the object to avoid
// invalidating the iterator
++it;
this->GetLabelMap()->RemoveLabel(label);
}
else
{
++it;
}
}
}
virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;
AttributeType m_Attribute;
private:
ShapeUniqueLabelMapFilter(const Self &) ITK_DELETE_FUNCTION;
void operator=(const Self &) ITK_DELETE_FUNCTION;
bool m_ReverseOrdering;
struct LineOfLabelObject {
typedef typename LabelObjectType::LineType LineType;
LineOfLabelObject(const LineType _line, LabelObjectType *_lo)
{
this->line = _line;
this->labelObject = _lo;
}
LineType line;
LabelObjectType *labelObject;
};
class LineOfLabelObjectComparator
{
public:
bool operator()(const LineOfLabelObject & lla, const LineOfLabelObject & llb)
{
for ( int i = ImageDimension - 1; i >= 0; i-- )
{
if ( lla.line.GetIndex()[i] > llb.line.GetIndex()[i] )
{
return true;
}
else if ( lla.line.GetIndex()[i] < llb.line.GetIndex()[i] )
{
return false;
}
}
return false;
}
};
}; // end of class
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkShapeUniqueLabelMapFilter.hxx"
#endif
#endif
| [
"ayla@sci.utah.edu"
] | ayla@sci.utah.edu |
73f0c95c5056edc556babca614b16c624cdc51f4 | dc29086e666691d3d1f1371708ca860c7393fd8f | /src/DBServer/Src/db_plugin.h | 768de7e5215336c16a60c1eb2f28f2dfdb195b8c | [] | no_license | preboy/9DayGame | acb9ee02500a7a6a8b3470d4c6adbfbd517c442a | 4947b402e5e9e9cd430ea178b8bf6debc05abbf4 | refs/heads/master | 2021-01-11T14:11:59.060933 | 2017-02-10T14:46:12 | 2017-02-10T14:46:12 | 81,573,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | h | #pragma once
#include <list>
using namespace std;
#include "LibEngine/plugin.h"
using namespace LibEngine;
#include "LibNetwork/socket_client.h"
namespace DBServer
{
struct stLSServer
{
int LSID;
int LSStatus;
string LSName;
stLSServer()
{
LSID = 0;
LSStatus = 0;
}
int init(UINT nSocket)
{
static int nserialID = 0;
nserialID++;
LSID = nserialID;
socket_client*pSocket = (socket_client*)nSocket;
return nserialID;
}
};
class db_plugin : public Plugin
{
public:
db_plugin(void);
~db_plugin(void);
public:
virtual MSG_CODE MsgProc( message* pMSG );
private:
void on_test( CHAR* pData, USHORT uLen );
stLSServer* get_LS(UINT id);
private:
list<stLSServer> m_lstLSServer;
};
}
| [
"preboy@126.com"
] | preboy@126.com |
8f38923f1f9e9e6c2fbaf5c3f88a3ea2d61ec32b | c40b21b737c8906d104d6e1a63904884b8ec345d | /Operator/UTOP_CheckWhiteChart/UTOP_CheckWhiteChart.cpp | 2c03d82b0e759cb0db939e3dc5d87c7aeac01ef2 | [] | no_license | liupengsyk/UTS_NEW | f4eac1f327126eda4dd0bfaae0a1372a77263175 | 0fa04109a0f0808dd973a6f86cc0133f068ea02d | refs/heads/master | 2020-06-03T02:30:18.394317 | 2019-01-30T02:32:32 | 2019-01-30T02:32:32 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,420 | cpp | // UTOP_CheckWhiteChart.cpp : 定義 DLL 的初始化常式。
//
#include "stdafx.h"
#include "UTOP_CheckWhiteChart.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
//
//TODO: 如果這個 DLL 是動態地對 MFC DLL 連結,
// 那麼從這個 DLL 匯出的任何會呼叫
// MFC 內部的函式,都必須在函式一開頭加上 AFX_MANAGE_STATE
// 巨集。
//
// 例如:
//
// extern "C" BOOL PASCAL EXPORT ExportedFunction()
// {
// AFX_MANAGE_STATE(AfxGetStaticModuleState());
// // 此處為正常函式主體
// }
//
// 這個巨集一定要出現在每一個
// 函式中,才能夠呼叫 MFC 的內部。這意味著
// 它必須是函式內的第一個陳述式
// ,甚至必須在任何物件變數宣告前面
// ,因為它們的建構函式可能會產生對 MFC
// DLL 內部的呼叫。
//
// 請參閱 MFC 技術提示 33 和 58 中的
// 詳細資料。
//
// CUTOP_CheckWhiteChartApp
BEGIN_MESSAGE_MAP(CUTOP_CheckWhiteChartApp, CWinApp)
END_MESSAGE_MAP()
// CUTOP_CheckWhiteChartApp 建構
CUTOP_CheckWhiteChartApp::CUTOP_CheckWhiteChartApp()
{
// TODO: 在此加入建構程式碼,
// 將所有重要的初始設定加入 InitInstance 中
}
// 僅有的一個 CUTOP_CheckWhiteChartApp 物件
CUTOP_CheckWhiteChartApp theApp;
// CUTOP_CheckWhiteChartApp 初始設定
BOOL CUTOP_CheckWhiteChartApp::InitInstance()
{
CWinApp::InitInstance();
return TRUE;
}
| [
"2411804080@qq.com"
] | 2411804080@qq.com |
5a497cc05ff4f51a38e3269d2155c3a4dd164adc | 51c1c5e9b8489ef8afa029b162aaf4c8f8bda7fc | /easyshape/src/libshape/Symbol.cpp | 4262a173af4dfac670f6ec9959c97aa9e82ae6e9 | [
"MIT"
] | permissive | aimoonchen/easyeditor | 3e5c77f0173a40a802fd73d7b741c064095d83e6 | 9dabdbfb8ad7b00c992d997d6662752130d5a02d | refs/heads/master | 2021-04-26T23:06:27.016240 | 2018-02-12T02:28:50 | 2018-02-12T02:28:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,147 | cpp | #include "Symbol.h"
#include "FileIO.h"
#include "PolygonShape.h"
#include <easyimage.h>
#include <ee/Config.h>
#include <ee/FileHelper.h>
#include <ee/SettingData.h>
#include <ee/Visitor.h>
#include <ee/Sprite.h>
#include <ee/SymbolType.h>
#include <sprite2/RenderParams.h>
#include <gum/JsonSerializer.h>
#include <gum/FilepathHelper.h>
#include <fstream>
namespace eshape
{
Symbol::Symbol()
: m_bg(NULL)
{
}
s2::RenderReturn Symbol::DrawTree(cooking::DisplayList* dlist, const s2::RenderParams& rp, const s2::Sprite* spr) const
{
s2::RenderParams p = rp;
if (spr) {
p.mt = spr->GetLocalMat() * rp.mt;
p.col_common = spr->GetColorCommon() * rp.col_common;
p.col_map = spr->GetColorMap() * rp.col_map;
}
if (m_bg) {
m_bg->DrawTree(nullptr, p, spr);
}
if (ee::Config::Instance()->GetSettings().visible_shape)
{
for (size_t i = 0, n = m_bg_outline.size(); i < n; ++i) {
m_bg_outline[i]->Draw(dlist, p);
}
s2::ShapeSymbol::DrawTree(nullptr, rp, spr);
}
return s2::RENDER_OK;
}
void Symbol::ReloadTexture() const
{
if (m_bg) {
m_bg->ReloadTexture();
}
}
void Symbol::Traverse(ee::RefVisitor<ee::Shape>& visitor) const
{
for (int i = 0, n = m_bg_outline.size(); i < n; ++i) {
bool next;
visitor.Visit(m_bg_outline[i], next);
if (!next) return;
}
bool next;
visitor.Visit(std::dynamic_pointer_cast<ee::Shape>(m_shape), next);
}
bool Symbol::Add(ee::ShapePtr& shape)
{
SetShape(std::move(shape));
return shape != NULL;
}
bool Symbol::Remove(const ee::ShapePtr& shape)
{
if (m_shape == shape) {
SetShape(NULL);
return true;
} else {
return false;
}
}
bool Symbol::Clear()
{
bool ret = !m_bg_outline.empty() || m_shape != NULL;
m_bg_outline.clear();
m_shape.reset();
return ret;
}
void Symbol::SetBG(const ee::SymPtr& bg)
{
if (m_bg != bg) {
LoadBGOutline(bg);
LoadBGTriStrip(bg);
}
m_bg = bg;
}
void Symbol::StoreToFile(const char* filename) const
{
FileIO::StoreToFile(filename, *dynamic_cast<ee::Shape*>(m_shape.get()), m_bg);
}
// sm::rect Symbol::GetBoundingImpl(const s2::Sprite* spr, const s2::Actor* actor, bool cache) const
// {
// sm::rect b;
// for (size_t i = 0, n = m_bg_outline.size(); i < n; ++i) {
// b.Combine(m_bg_outline[i]->GetBounding());
// }
// b.Combine(s2::ShapeSymbol::GetBounding(spr));
// return b;
// }
bool Symbol::LoadResources()
{
if (m_filepath == ee::SYM_SHAPE_TAG) {
return true;
}
if (!gum::FilepathHelper::Exists(m_filepath.c_str())) {
return false;
}
Clear();
m_shape = FileIO::LoadFromFile(m_filepath.c_str(), m_bg);
return true;
}
void Symbol::LoadBGOutline(const ee::SymPtr& bg)
{
m_bg_outline.clear();
if (!bg) {
return;
}
std::string filepath = ee::FileHelper::GetFilenameAddTag(
bg->GetFilepath(), eimage::OUTLINE_FILE_TAG, "json");
if (!ee::FileHelper::IsFileExist(filepath)) {
return;
}
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
CU_VEC<sm::vec2> vertices;
gum::JsonSerializer::Load(value["normal"], vertices);
if (!vertices.empty()) {
auto shape = std::make_unique<PolygonShape>(vertices);
m_bg_outline.push_back(std::move(shape));
}
}
void Symbol::LoadBGTriStrip(const ee::SymPtr& bg)
{
m_bg_tri_strips.clear();
std::string filepath = ee::FileHelper::GetFilenameAddTag(
bg->GetFilepath(), eimage::TRI_STRIP_FILE_TAG, "json");
if (!ee::FileHelper::IsFileExist(filepath)) {
return;
}
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
int i = 0;
Json::Value strip_val = value["strips"][i++];
while (!strip_val.isNull()) {
CU_VEC<sm::vec2> strip;
gum::JsonSerializer::Load(strip_val, strip);
m_bg_tri_strips.push_back(strip);
strip_val = value["strip"][i++];
}
}
ShapeType Symbol::GetShapeType() const
{
if (!m_shape) {
return ST_UNKNOWN;
} else {
return get_shape_type(dynamic_cast<ee::Shape*>(m_shape.get())->GetShapeDesc());
}
}
} | [
"zhuguang@ejoy.com"
] | zhuguang@ejoy.com |
bd722021d4be2d0913d8877051b6c4c113afd9af | 3a903028bdb3b0ce604588a2358fb3c1bc990baf | /vta/vtalib/include/arm_compute/runtime/CL/functions/CLActivationLayer.h | 632487c78d647e208ec94a419ec4dfdebade013c | [
"Apache-2.0"
] | permissive | snizzer/nest-compiler | 21a8a069ede526bbf969d1dfe71950cd5698c853 | c6ac790ed12807f2e0855e3aa0170cb149dc237d | refs/heads/main | 2023-06-11T10:15:31.030619 | 2021-07-06T01:53:01 | 2021-07-06T01:53:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,180 | h | /*
* Copyright (c) 2016-2020 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
#ifndef ARM_COMPUTE_CLACTIVATIONLAYER_H
#define ARM_COMPUTE_CLACTIVATIONLAYER_H
#include "arm_compute/runtime/CL/ICLOperator.h"
#include "arm_compute/runtime/CL/ICLSimpleFunction.h"
#include "arm_compute/core/Types.h"
namespace arm_compute
{
class ICLTensor;
/** Basic function to run @ref CLActivationLayerKernel
*
* @note The function simulates an activation layer with the specified activation function.
*/
class CLActivationLayer : public IFunction
{
public:
/** Constructor
*
* @param[in] ctx Runtime context to be used by the function
*/
CLActivationLayer(CLRuntimeContext *ctx = nullptr);
/** Destructor */
~CLActivationLayer();
/** Prevent instances of this class from being copied (As this class contains pointers) */
CLActivationLayer(const CLActivationLayer &) = delete;
/** Default move constructor */
CLActivationLayer(CLActivationLayer &&);
/** Prevent instances of this class from being copied (As this class contains pointers) */
CLActivationLayer &operator=(const CLActivationLayer &) = delete;
/** Default move assignment operator */
CLActivationLayer &operator=(CLActivationLayer &&);
/** Set the input and output tensor.
*
* @note If the output tensor is a nullptr or is equal to the input, the activation function will be performed in-place
*
* @param[in, out] input Source tensor. In case of @p output tensor = nullptr, this tensor will store the result
* of the activation function. Data types supported: QASYMM8/QASYMM8_SIGNED/QSYMM16/F16/F32.
* @param[out] output Destination tensor. Data type supported: same as @p input
* @param[in] act_info Activation layer parameters.
*/
void configure(ICLTensor *input, ICLTensor *output, ActivationLayerInfo act_info);
/** Set the input and output tensor.
*
* @note If the output tensor is a nullptr or is equal to the input, the activation function will be performed in-place
*
* @param[in] compile_context The compile context to be used.
* @param[in, out] input Source tensor. In case of @p output tensor = nullptr, this tensor will store the result
* of the activation function. Data types supported: QASYMM8/QASYMM8_SIGNED/QSYMM16/F16/F32.
* @param[out] output Destination tensor. Data type supported: same as @p input
* @param[in] act_info Activation layer parameters.
*/
void configure(const CLCompileContext &compile_context, ICLTensor *input, ICLTensor *output, ActivationLayerInfo act_info);
/** Static function to check if given info will lead to a valid configuration of @ref CLActivationLayer
*
* @param[in] input Source tensor info. In case of @p output tensor info = nullptr, this tensor will store the result
* of the activation function. Data types supported: QASYMM8/QASYMM8_SIGNED/QSYMM16/F16/F32.
* @param[in] output Destination tensor info. Data type supported: same as @p input
* @param[in] act_info Activation layer information.
*
* @return a status
*/
static Status validate(const ITensorInfo *input, const ITensorInfo *output, const ActivationLayerInfo &act_info);
// Inherited methods overridden:
void run() override;
private:
struct Impl;
std::unique_ptr<Impl> _impl;
};
namespace experimental
{
/** Basic function to run @ref CLActivationLayerKernel */
class CLActivation : public ICLOperator
{
public:
/** Set the input and output tensor.
*
* @param[in] compile_context The compile context to be used.
* @param[in, out] input Source tensor info. In case of @p output tensor = nullptr, this tensor will store the result
* of the activation function. Data types supported: QASYMM8/QASYMM8_SIGNED/QSYMM16/F16/F32.
* @param[out] output Destination tensor info. Data type supported: same as @p input
* @param[in] act_info Activation layer parameters.
*/
void configure(const CLCompileContext &compile_context, ITensorInfo *input, ITensorInfo *output, ActivationLayerInfo act_info);
/** Static function to check if given info will lead to a valid configuration of @ref CLActivationLayer
*
* @param[in] input Source tensor info. In case of @p output tensor info = nullptr, this tensor will store the result
* of the activation function. Data types supported: QASYMM8/QASYMM8_SIGNED/QSYMM16/F16/F32.
* @param[in] output Destination tensor info. Data type supported: same as @p input
* @param[in] act_info Activation layer information.
*
* @return a status
*/
static Status validate(const ITensorInfo *input, const ITensorInfo *output, const ActivationLayerInfo &act_info);
};
} // namespace experimental
} // namespace arm_compute
#endif /* ARM_COMPUTE_CLACTIVATIONLAYER_H */
| [
"yongin.kwon@etri.re.kr"
] | yongin.kwon@etri.re.kr |
e87cba8b7e07e7564e05ec92ed2367baca7dedfe | e7209a5cb12250ae052ca882a3570c874b4c7dcf | /src/EngineManaged/Bindings/Buffer.cpp | 9dd1c26c42b398474d46cf747ac7c5464e8e0585 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | akumetsuv/flood | 3af52fc3934c289f72b4ca7828b90ce3a054dcda | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | refs/heads/master | 2020-12-25T10:50:21.301224 | 2013-03-24T06:05:56 | 2013-03-24T06:05:56 | 8,084,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,731 | cpp | /************************************************************************
*
* Flood Project © (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#include "_Marshal.h"
#include "Buffer.h"
#include "GeometryBuffer.h"
#include "VertexBuffer.h"
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace clix;
Flood::Buffer::Buffer(::Buffer* native)
{
NativePtr = native;
}
Flood::Buffer::Buffer(System::IntPtr native)
{
NativePtr = (::Buffer*)native.ToPointer();
}
Flood::Buffer::Buffer()
{
NativePtr = new ::Buffer();
}
Flood::Buffer::Buffer(Flood::BufferUsage usage, Flood::BufferAccess access)
{
auto arg0 = (::BufferUsage)usage;
auto arg1 = (::BufferAccess)access;
NativePtr = new ::Buffer(arg0, arg1);
}
Flood::BufferUsage Flood::Buffer::GetBufferUsage()
{
auto ret = NativePtr->getBufferUsage();
return (Flood::BufferUsage)ret;
}
void Flood::Buffer::SetBufferUsage(Flood::BufferUsage v)
{
auto arg0 = (::BufferUsage)v;
NativePtr->setBufferUsage(arg0);
}
Flood::BufferAccess Flood::Buffer::GetBufferAccess()
{
auto ret = NativePtr->getBufferAccess();
return (Flood::BufferAccess)ret;
}
void Flood::Buffer::SetBufferAccess(Flood::BufferAccess v)
{
auto arg0 = (::BufferAccess)v;
NativePtr->setBufferAccess(arg0);
}
Flood::GeometryBuffer^ Flood::Buffer::GetGeometryBuffer()
{
auto ret = NativePtr->getGeometryBuffer();
return gcnew Flood::GeometryBuffer((::GeometryBuffer*)ret);
}
void Flood::Buffer::SetGeometryBuffer(Flood::GeometryBuffer^ v)
{
auto arg0 = v->NativePtr;
NativePtr->setGeometryBuffer(arg0);
}
| [
"ripzonetriton@gmail.com"
] | ripzonetriton@gmail.com |
91edf8ecf7a5ea153b90c0a3b9d29d04b9f5e606 | 4f245ace2bba2b5014fc6c59444c5af02514f0d3 | /class/forward_list.h | ed17ab19095119fe75528f02ed688a013d3689cf | [] | no_license | marcus-rb/Cxx-Data-Structures | 03d9b9a475cbd3d8179603ddda6f8bdb5b43c31a | 5ecdad9aadb6de4535bdfa0104f37cd840db005c | refs/heads/master | 2023-01-04T05:06:15.596761 | 2020-10-31T17:24:08 | 2020-10-31T17:24:08 | 302,742,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,263 | h | #pragma once
// CLASS SETUP
/* [ ] constructor
* [ ] destructor
* [ ] operator=
* [ ] assign
*
*/
#include "..\core\custom_def.h"
#include "..\utility\iterator.h"
#include "..\utility\memory.h"
_CUSTOM_BEGIN_
template <typename flist_type>
class forward_list_iterator : public base_forward_iterator<typename flist_type::value_type, forward_list_iterator<flist_type> {
public:
using T_ptr = typename flist_type::T_ptr;
using T_ref = typename flist_type::T_ref;
using value_type = typename flist_type::value_type;
};
template <typename T, typename alloc = allocator<T>>
class forward_list {
public:
using iterator = forward_list_iterator<forward_list<T, alloc>>;
using T_ptr = T*;
using T_ref = T&;
using const_T_ptr = const T*;
using const_T_ref = const T&;
using value_type = T;
private:
class list_node;
list_node* m_head;
list_node* m_tail;
public:
forward_list() : m_head(nullptr), m_tail(nullptr) noexcept;
// --- ELEMENT ACCESS ---
// --- ITERATORS ---
// --- MODIFIERS ---
private:
class list_node {
T_ptr m_list_data;
list_node* m_next;
};
};
_CUSTOM_END_
template <typename T, typename alloc = custom::allocator<T>>
bool operator==(custom::forward_list<T, alloc>& lhs, custom::forward_list<T, alloc>& rhs) {
} | [
"marcus.benrud@gmail.com"
] | marcus.benrud@gmail.com |
041e3d345b43932348394c17ebf2ca6003bf18f3 | 7b927021c1a076953345eac018fc3fc036fe550d | /PyBoost/PyBoost.cpp | 897fee8b498c00d4468fa0bbbbd9e8901e879b9b | [] | no_license | wjl158/CPython | a3bfc803852c2a27324a5618f5b7a870739501b0 | dc81e8bb3a2f9cd73a582bddba7358d3006a3e4d | refs/heads/master | 2020-04-14T13:40:07.489501 | 2016-09-14T15:47:26 | 2016-09-14T15:47:26 | 68,209,674 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 889 | cpp | // PyBoost.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<boost/python.hpp>
using namespace boost::python;
int _tmain(int argc, _TCHAR* argv[])
{
Py_Initialize();
// 检查初始化是否成功
if ( !Py_IsInitialized() )
{
return -1;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
object mainModule;
object mainNamespace;
try
{
mainModule = import("__main__");
mainNamespace = mainModule.attr("__dict__");
exec("import os", mainNamespace, mainNamespace);
exec("print(os.getcwd())", mainNamespace, mainNamespace);
}
catch( ... )
{
if (PyErr_Occurred())
PyErr_Print();
}
//// 关闭Python
//
//Py_Finalize();
system("pause");
return 0;
}
| [
"229259139@qq.com"
] | 229259139@qq.com |
e4a91d0b5784582e018d0ba044c397c41c19d55f | 10bbcec1f79b08e9ec848999208c261778fe7d15 | /3DR/S5/background/system/controlDict | 8d32152d7ee771ab562c7fbf11d7d00d76b55ae6 | [] | no_license | JoeHu1997/3D | bd4c30cad9361987ab1e1e9490f3dd703796ff4a | 68d58205232c565e793ef58163721f5b584e5c20 | refs/heads/master | 2023-08-30T00:58:30.744180 | 2021-11-11T13:01:09 | 2021-11-11T13:01:09 | 391,794,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,918 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1812 |
| \\ / A nd | Web: www.OpenFOAM.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "system";
object controlDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
libs ("liboverset.so");
application overInterDyMFoam;
startFrom startTime;
startTime 0.0;
stopAt endTime;
endTime 12.0;
deltaT 0.001;
writeControl adjustableRunTime;
writeInterval 0.05;
purgeWrite 0;
writeFormat ascii;
writePrecision 12;
writeCompression off;
timeFormat general;
timePrecision 6;
runTimeModifiable yes;
adjustTimeStep yes;
maxCo 1.0;
maxAlphaCo 1.0;
maxDeltaT 0.001;
functions
{
line1
{
type probesCable;
libs ("libsampling.so");
fields (U);
probeLocations
(
#include "pointLocation1.txt"
);
}
line2
{
type probesCable;
libs ("libsampling.so");
fields (U);
probeLocations
(
#include "pointLocation2.txt"
);
}
line3
{
type probesCable;
libs ("libsampling.so");
fields (U);
probeLocations
(
#include "pointLocation3.txt"
);
}
line4
{
type probesCable;
libs ("libsampling.so");
fields (U);
probeLocations
(
#include "pointLocation4.txt"
);
}
}
// ************************************************************************* //
| [
"62299081+JoeHu1997@users.noreply.github.com"
] | 62299081+JoeHu1997@users.noreply.github.com | |
42be8485741e42060e092f5536c9c09ce9a133d6 | c35b99786d9fdc69372e2895334974a71713d989 | /Controller.cpp | df0caaef8284797af4c357854463952e315d3d2f | [] | no_license | infation/Longana-Cplusplus | 57244340a57202b12179992eb53c49ff1c7fe0c8 | 8d7b29b07bd594b3e458437ca7ba953f67190d5f | refs/heads/master | 2021-07-03T02:22:42.261567 | 2017-09-22T05:04:48 | 2017-09-22T05:04:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 88 | cpp | #include "Controller.h"
Controller::Controller()
{
}
Controller::~Controller()
{
}
| [
"sminev@ramapo.edu"
] | sminev@ramapo.edu |
54a874751f133572ef7d6915691bec3226e114fb | e80704c889329b9df9f2903435df6687160ff516 | /src/kop_interface/src/main.cc | 2152cf747da908f5a01c643f5b50002c2c2463f2 | [] | no_license | Aramist/kit-of-parts-simulation | 92b4937b17637b110aa707f3c74dbc3c43161017 | 53c19ab319f832da0f56f6df1a46c0158b2dbb4c | refs/heads/master | 2020-05-17T20:54:37.090955 | 2019-04-30T21:50:33 | 2019-04-30T21:50:33 | 183,956,297 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,322 | cc | #include <functional>
#include <vector>
#include "ros/ros.h"
#include "ros/console.h"
#include "std_msgs/Float64.h"
#include "geometry_msgs/Vector3.h"
using geometry_msgs::Vector3;
void commandCallback(const Vector3::ConstPtr &command, const double &d, const double &r,
const std::vector<ros::Publisher> &leftSide,
const std::vector<ros::Publisher> &rightSide) {
double velocity = command->x;
double angular = command->y;
double left = -(2 * velocity - d * angular) / (2 * r); // The negative is there to invert the motors
double right = -(2 * velocity + d * angular) / (2 * r);
for (const ros::Publisher &wheel : leftSide) {
std_msgs::Float64 msg;
msg.data = left;
wheel.publish(msg);
}
for (const ros::Publisher &wheel : rightSide) {
std_msgs::Float64 msg;
msg.data = right;
wheel.publish(msg);
}
}
int main(int argc, char **argv) {
ros::init(argc, argv, "kop_interface");
ros::NodeHandle handle;
double baseWidth = 0.0;
double wheelRadius = 0.0;
if (!(handle.getParam("robot_params/wheelbase_width", baseWidth)
&& handle.getParam("robot_params/wheel_radius", wheelRadius))) {
ROS_ERROR("Failed to read radius and wheelbase width parameters from parameter server");
return -1;
}
std::vector<ros::Publisher> rightPubs;
rightPubs.push_back(handle.advertise<std_msgs::Float64>(
"/kop/pid/rf/setpoint", 5));
rightPubs.push_back(handle.advertise<std_msgs::Float64>(
"/kop/pid/rm/setpoint", 5));
rightPubs.push_back(handle.advertise<std_msgs::Float64>(
"/kop/pid/rr/setpoint", 5));
std::vector<ros::Publisher> leftPubs;
leftPubs.push_back(handle.advertise<std_msgs::Float64>(
"/kop/pid/lf/setpoint", 5));
leftPubs.push_back(handle.advertise<std_msgs::Float64>(
"/kop/pid/lm/setpoint", 5));
leftPubs.push_back(handle.advertise<std_msgs::Float64>(
"/kop/pid/lr/setpoint", 5));
ros::Subscriber command = handle.subscribe<Vector3>(
"/kop/interface/drive_command", 1,
std::bind(&commandCallback, std::placeholders::_1,
baseWidth, wheelRadius, leftPubs, rightPubs));
ros::spin();
}
| [
"aramis.tanelus@gmail.com"
] | aramis.tanelus@gmail.com |
f12a3caf2387000ff6ed603e07dbaf744d660a2a | 43ae1d4dbb622fe109979759dc162c56b26a04ad | /PAT/PAT_A1031_hello world for U.cpp | a0392e12c22918a6a82bea5129c95fad41679e44 | [] | no_license | lalaland1921/OnlineJudge | a06475c3ef57ec962ce117e5b4087f5df2f79d52 | f55f94c333f18a044588088b8a001108f3d8f7bc | refs/heads/master | 2021-01-16T06:51:26.314738 | 2020-02-25T23:59:19 | 2020-02-25T23:59:19 | 243,014,834 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 355 | cpp | #include <iostream>
#include <cmath>
#include <string.h>
using namespace std;
int main()
{
int n=0,n1,n2;
char a[81];
cin>>a;
n=strlen(a);
n1=min((n-1)/2,(n+2)/3);
n2=n+2-2*n1;
for(int i=0;i<n1-1;i++)
{
cout<<a[i];
for(int j=0;j<n2-2;j++)
cout<<" ";
cout<<a[n-1-i]<<endl;
}
for(int i=n1-1;i<n1+n2-1;i++)
{
cout<<a[i];
}
return 0;
}
| [
"798302969@qq.com"
] | 798302969@qq.com |
ed742a5624a4aa33fd9c88c9158ecbcb60e16753 | f22aac466c4267b31d70c02181a3536fd749573e | /gameEngine/gameEngine/Observers/ObserverHandler.cpp | 91578c5ea8eb1dd246ed2d2cefd81a449043ebc9 | [
"MIT"
] | permissive | ComputerScienceTrolls/simpleGameGL | 16f05e524444f164b3e26dd27bb6237b8417e964 | 81e25f690f5825bf633685e9d7d2771a3d61f4c7 | refs/heads/master | 2021-01-16T00:42:10.383614 | 2018-06-18T18:50:21 | 2018-06-18T18:50:21 | 99,971,888 | 0 | 0 | MIT | 2018-06-18T18:50:40 | 2017-08-10T23:12:57 | C | UTF-8 | C++ | false | false | 1,155 | cpp | #include "ObserverHandler.h"
#include <iostream>
//auto ptr instance of class, when program ends it will delete itself
std::auto_ptr<ObserverHandler> ObserverHandler::instance;
ObserverHandler::ObserverHandler()
{
}
//singleton gets instance if it exists, if not create then return it.
ObserverHandler* ObserverHandler::getInstance()
{
if (instance.get() == nullptr)
{
instance.reset(new ObserverHandler());
}
return instance.get();
}
//add an observer to observerhandler, to run later.
void ObserverHandler::addObserver(AbstractObserver &obs)
{
observers_.insert(&obs);
}
//remove registered observer from observerhandler.
void ObserverHandler::removeObserver(AbstractObserver &obs)
{
observers_.erase(&obs);
}
//run all observers registered to observer handler.
void ObserverHandler::NotifyObservers()
{
std::set<AbstractObserver*>::iterator itr;
for ( itr = observers_.begin();
itr != observers_.end(); itr++ )
(*itr)->Notify();
}
//return number of registered observers
size_t ObserverHandler::getNumberOfObservers()
{
return observers_.size();
}
ObserverHandler::~ObserverHandler()
{
}
| [
"linkthayer@sbcglobal.net"
] | linkthayer@sbcglobal.net |
f550d297c46d1970e4371f5233240cf40683c6bb | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/10/57a69cbe805cb3/main.cpp | d58d35e8af4a3c849d6d0029cbf5dad130951e79 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,893 | cpp | typedef boost::variant<FileAttributes, EnableTelemetry, DefineBinaryData, PlaceObject, PlaceObject2, PlaceObject3, RemoveObject, RemoveObject2, ShowFrame, SetBackgroundColor, FrameLabel, Protect, End, ExportAssets, ImportAssets, EnableDebugger, EnableDebugger2, ScriptLimits, SetTabIndex, ImportAssets2, SymbolClass, Metadata, DefineScalingGrid, DefineSceneAndFrameLabelData, DefineShape, DefineShape2, DefineShape3, DefineShape4, DefineFont, DefineFontInfo, DefineFontInfo2, DefineFont2, DefineFont3, DefineFontAlignZones, DefineFontName, DefineText, DefineText2, DefineEditText, CSMTextSettings, DefineFont4, DefineSound, StartSound, StartSound2, SoundStreamHead, SoundStreamHead2, SoundStreamBlock, DefineButton, DefineButton2, DefineButtonCxform, DefineButtonSound, DefineSprite, DefineVideoStream, VideoFrame, DoAction, Play, Stop, NextFrame, PreviousFrame, GotoFrame, GotoLabel, WaitForFrame, GetURL, StopSounds, ToggleQuality, SetTarget, Add, Divide, Multiply, Subtract, Equals, Less, And, Not, Or, StringAdd, StringEquals, StringExact, StringLength, MBStringExact, MBStringLength, StringLess, Pop, Push, AsciiToChar, CharToAscii, ToInteger, MBAsciiToChar, MBCharToAscii, Call, If, Jump, GetVariable, SetVariable, GetURL2, GetProperty, GotoFrame2, RemoveSprite, SetProperty, SetTarget2, StartDrag, WaitForFrame2, CloneSprite, EndDrag, Trace, GetTime, RandomNumber, CallFunction, CallMethod, ConstantPool, DefineFunction, DefineLocal, DefineLocal2, Delete, Delete2, Enumerate, Equals2, GetMember, InitArray, InitObject, NewMethod, NewObject, SetMember, TargetPath, With, ToNumber, ToString, TypeOf, Add2, Less2, Modulo, BitAnd, BitLShift, BitOr, BitRShift, BitURShift, Decrement, Increment, PushDuplicate, Return, StackSwap, StoreRegister, DoInitAction, InstanceOf, Enumerate2, StrictEquals, Greater, StringGreater, DefineFunction2, Extends, CastOp, ImplementsOp, Try, Throw, DoABC> Tag; | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
5fc27e98e5484aa3f5a4bcf986ed49dad438a6f4 | 64ecbedbf4b34d8e4d527fdb79af2dde0a1d450f | /Contests/RoTopCoder-2012/paal111.cpp | 9e57d494bef6b452f3ab6998c357b9e10d77ef26 | [] | no_license | palcu/algo | af48db75a745191be9c540c10169f9e80247071b | 0ac904f5f6c36b8d0775775ebed78f1ff550aea6 | refs/heads/master | 2021-01-18T01:40:58.017979 | 2020-12-25T12:14:40 | 2020-12-25T12:14:40 | 2,050,312 | 7 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 949 | cpp | /*
Alex Palcuie === http://palcu.blogspot.com/
Valcea
like
*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <utility>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <algorithm>
#include <climits>
using namespace std;
const int NMAX = 100006;
int nPers, nLikes;
int v[NMAX];
int main(){
freopen("like.in", "r", stdin);
freopen("like.out", "w", stdout);
scanf("%d%d", &nPers, &nLikes);
int i, sol; sol = nPers;
int x,y;
for(i=0; i<nLikes; i++){
scanf("%d%d", &x, &y);
if(x == y)
continue;
int grupX = x, grupY = y;
int lgX = 0, lgY = 0;
while(v[grupX] != 0){
grupX = v[grupX];
lgX ++;
}
while(v[grupY] != 0){
grupY = v[grupY];
lgY ++;
}
if (grupX != grupY){
sol --;
if(lgX > lgY)
v[grupY] = grupX;
else
v[grupX] = grupY;
}
}
printf("%d\n", sol);
return 0;
}
| [
"alex.palcuie@gmail.com"
] | alex.palcuie@gmail.com |
c986ad7e6703066eae5edec019c2821b4ede5823 | 163cfaa731ff1a889b9bb21d41e9a27d791c8268 | /project1/MyMatrix.h | 42aa86afa18145a398f722f2c7d933bd2a5bd3c3 | [] | no_license | StarOceanReimi/QC_Summer_CS_780 | 5fb9963dae344002a5befb9bf8649b455109360f | f1ba455ce645742f1aaa39e024b1f8640cea3af9 | refs/heads/master | 2021-01-20T19:36:26.089036 | 2016-06-29T15:33:14 | 2016-06-29T15:33:14 | 60,573,297 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,597 | h | #include <iostream>
#include <stdlib.h>
using namespace std;
class MyMatrix {
private:
int rows_low, rows_high, column_low, column_high;
int rows_size, column_size;
int **p;
void init(int rl, int rh, int cl, int ch);
void destroy();
public:
MyMatrix(int rh, int ch) {
init(0, rh, 0, ch);
};
MyMatrix(int rl, int rh, int cl, int ch) {
init(rl, rh, cl, ch);
};
MyMatrix(const MyMatrix &m) {
rows_low = m.rows_low;
rows_high = m.rows_high;
column_low = m.column_low;
column_high = m.column_high;
rows_size = m.rows_size;
column_size = m.column_size;
p = new int*[rows_size];
for(int i=0; i<rows_size; i++) {
p[i] = new int[column_size];
for(int j=0; j<column_size; j++) {
p[i][j] = m.p[i][j];
}
}
};
~MyMatrix() {
destroy();
}
int Rows() { return rows_size; }
int Columns() { return column_size; }
int* operator[](int i) {
if(i < rows_low || i > rows_high) {
cout << "index " << i << " out of range" << endl;
exit(1);
}
return p[i-rows_low];
}
MyMatrix operator*(const MyMatrix &m) {
if(column_size != m.rows_size) {
cout << "Columns not match Rows. Can not multiply." << endl;
exit(1);
}
MyMatrix newMatrix(rows_size, m.column_size);
for(int i=0; i<rows_size; i++) {
for(int j=0; j<m.column_size; j++) {
int sum = 0;
for(int x=0; x<column_size; x++) {
sum += p[i][x] * m.p[x][j];
}
newMatrix[i][j] = sum;
}
}
return newMatrix;
}
MyMatrix& operator=(const MyMatrix &m) {
if(this == &m) return *this;
destroy();
rows_low = m.rows_low;
rows_high = m.rows_high;
column_low = m.column_low;
column_high = m.column_high;
rows_size = m.rows_size;
column_size = m.column_size;
p = new int*[rows_size];
for(int i=0; i<rows_size; i++) {
p[i] = new int[column_size];
for(int j=0; j<column_size; j++) {
p[i][j] = m.p[i][j];
}
}
return *this;
}
friend ostream& operator<<(ostream& os, MyMatrix m);
};
void MyMatrix::init(int rl, int rh, int cl, int ch) {
rows_size = rh - rl;
column_size = ch - cl;
if(rows_size <= 0 || column_size <= 0) {
cout << "construct error in bounds definition." << endl;
exit(1);
}
rows_low = rl;
rows_high = rh;
column_low = cl;
column_high = ch;
p = new int*[rows_size];
for(int i=0; i<rows_size; i++)
p[i] = new int[column_size];
}
void MyMatrix::destroy() {
for(int i=0; i<rows_size; i++)
delete [] p[i];
delete [] p;
}
ostream& operator<<(ostream& os, MyMatrix m) {
for(int i=0; i<m.rows_size; i++) {
cout << "[";
for(int j=0; j<m.column_size; j++) {
if(j == 0) {
cout << m.p[i][j];
} else {
cout << "," << m.p[i][j];
}
}
cout << "]" << endl;
}
return os;
}
| [
"saiqiuli@gmail.com"
] | saiqiuli@gmail.com |
ab5e738afb4eaa7a5d10699559321b20db0c4855 | 597907bcd17ceb0e477780b39140a961b7399bf3 | /sym-link/errors.cpp | 7e502db931c24540c537a1727dc8e8bfc2eafc29 | [] | no_license | Stateford/symbolic-linker | 1220697333052bdfe35f857aaa01751abc2a60df | 0b134c9b0bea59388cd65607752c9e46f0ba9d1d | refs/heads/master | 2020-04-17T12:47:12.576893 | 2019-01-20T18:38:18 | 2019-01-20T18:38:18 | 166,591,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | #include "stdafx.h"
#include "errors.h"
namespace SymLink
{
Error::Error(const char* message) : std::exception(message) {};
Error::Error(std::string message) : std::exception(message.c_str())
{
}
} | [
"idietmoran@gmail.com"
] | idietmoran@gmail.com |
64bc6dee08dce68a291f0fa18d6fd6572ffbfdf2 | 9b17f84f716812f68490bbf685e0fb585dc2c2f9 | /linux/db/GeneralPool.cpp | 6c1e960fab557ff63e99084a5c7f00fcf9116939 | [] | no_license | SiteView/eccmeteor | 5f2e81dbf373290cf3b21c3df061c34843f807d1 | 12439345a9d50395c52d879b8777a31d042475a7 | refs/heads/master | 2020-05-30T12:15:18.035344 | 2013-11-29T09:02:07 | 2013-12-02T02:38:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,253 | cpp | #include "GeneralPool.h"
#include "somefunc.h"
GeneralPool::GeneralPool(void)
{
m_hashtablesize=hashtablesize;
m_data.resetsize(m_hashtablesize);
m_changed=false;
}
GeneralPool::GeneralPool(word filepath):PoolBase(filepath)
{
m_hashtablesize=hashtablesize;
m_data.resetsize(m_hashtablesize);
m_changed=false;
}
GeneralPool::~GeneralPool(void)
{
if(m_changed)
Submit();
COMMONDATAMAP::iterator it;
while(m_data.findnext(it))
{
Section *ps=(*it).getvalue();
if(ps)
delete ps;
}
}
S_UINT GeneralPool::GetRawDataSize(void)
{
S_UINT len=0,tlen=sizeof(S_UINT);
len+=tlen; //m_hashtablesize
len+=tlen; //data count;
//WORDLIST::iterator wit;
//Section **pdata=NULL;
//for(wit=m_SectionOrder.begin();wit!=m_SectionOrder.end();wit++)
//{
// pdata=m_data.find((*wit));
// if(pdata!=NULL)
// {
// len+=tlen; //data len;
// len+=(*pdata)->GetRawDataSize();
// }
//}
COMMONDATAMAP::iterator it;
while(m_data.findnext(it))
{
len+=tlen; //len size;
len+=(*it).getvalue()->GetRawDataSize();
}
return len;
}
char* GeneralPool::GetRawData(char *lpbuf,S_UINT bufsize)
{
if(lpbuf==NULL)
return NULL;
if(bufsize<GetRawDataSize())
return NULL;
S_UINT len=0,tlen=sizeof(S_UINT);
char *pt=lpbuf;
memmove(pt,&m_hashtablesize,tlen);
pt+=tlen;
len=m_data.size();
//len=m_SectionOrder.size();
memmove(pt,&len,tlen);
pt+=tlen;
//WORDLIST::iterator wit;
//Section **pdata=NULL;
//for(wit=m_SectionOrder.begin();wit!=m_SectionOrder.end();wit++)
//{
// pdata=m_data.find((*wit));
// if(pdata!=NULL)
// {
// len=(*pdata)->GetRawDataSize();
// memmove(pt,&len,tlen);
// pt+=tlen;
// if(!(*pdata)->GetRawData(pt,len))
// return NULL;
// pt+=len;
// }
//}
COMMONDATAMAP::iterator it;
while(m_data.findnext(it))
{
len=(*it).getvalue()->GetRawDataSize();
memmove(pt,&len,tlen);
pt+=tlen;
if(!(*it).getvalue()->GetRawData(pt,len))
return NULL;
pt+=len;
}
return lpbuf;
}
BOOL GeneralPool::CreateObjectByRawData(const char *lpbuf,S_UINT bufsize)
{
if(lpbuf==NULL)
return false;
S_UINT len=0,tlen=sizeof(S_UINT);
try{
const char *pend=lpbuf+bufsize;
const char *pt=lpbuf;
memmove(&m_hashtablesize,pt,tlen);
pt+=tlen;
if(m_hashtablesize<=0)
return false;
m_data.resetsize(m_hashtablesize);
S_UINT count=0;
memmove(&count,pt,tlen);
pt+=tlen;
Section *ps=NULL;
for(S_UINT i=0;i<count;i++)
{
memmove(&len,pt,tlen);
pt+=tlen;
ps=new Section();
if(!ps)
return false;
if(!ps->CreateObjectByRawData(pt,len))
return false;
m_data.insert(ps->GetSection(),ps);
m_SectionOrder.push_back(ps->GetSection());
pt+=len;
}
}catch(...)
{
return false;
}
return true;
}
bool GeneralPool::Load(void)
{
S_UINT len=0;
try{
{
ost::ThreadFile fl(m_FilePath.getword());
len =fl.getCapacity();
}
if(len<=0)
return false;
ost::MappedFile file(m_FilePath.getword(),0,len,ost::File::accessReadWrite);
char*p=(char *)file.fetch(0,len);
if(p)
{
return CreateObjectByRawData(p,len);
}
}catch(...)
{
#ifdef WIN32
printf("Load GeneralPool Exception,Errorid:%d,filename:%s",::GetLastError(),m_FilePath.getword());
#else
printf("Load GeneralPool Exception,filename:%s",m_FilePath.getword());
#endif
return false;
}
return false;
}
bool GeneralPool::Submit()
{
ost::MutexLock lock(m_UpdateLock);
if(!m_changed)
return true;
S_UINT len=this->GetRawDataSize();
try{
if(!CheckFileSize(m_FilePath.getword(),len))
{
printf("failed to CheckFileSize,in GeneralPool::Submit\n");
return false;
}
ost::MappedFile file(m_FilePath.getword(),ost::File::accessReadWrite,len);
char *p=(char *)file.fetch(0,len);
if(p)
{
if(this->GetRawData(p,len)==NULL)
return false;
}
}catch(...)
{
#ifdef WIN32
printf("Submit GeneralPool Exception,Errorid:%d,filename:%s\n",::GetLastError(),m_FilePath.getword());
#else
printf("Submit GeneralPool Exception,filename:%s\n",m_FilePath.getword());
#endif
return false;
}
m_changed=false;
return true;
}
bool GeneralPool::WriteData(word section,word key,void *data,S_UINT len)
{
MutexLock lock(m_UpdateLock);
if(!Find(section))
{
Section *ps=new Section();
if(!ps)
return false;
ps->PutSection(section);
if(!ps->Push(key,(const char *)data,len))
return false;
m_data[section]=ps;
m_SectionOrder.push_back(section);
m_changed=true;
return true;
}else
{
m_changed=true;
return m_data[section]->Push(key,(const char *)data,len);
}
return true;
}
bool GeneralPool::GetData(word section,word key,void *data,S_UINT &len)
{
if(!Find(section))
return false;
void *pdata=NULL;
S_UINT dlen=0;
if(!m_data[section]->Pop(key,(void **)&pdata,dlen))
return false;
if(data==NULL)
{
len=dlen;
return true;
}
if(len<dlen)
return false;
memcpy(data,pdata,dlen);
return true;
}
bool GeneralPool::WriteManyString(word section, const char *data,S_UINT datalen)
{
MutexLock lock(m_UpdateLock);
try{
NodeData ndata;
CreateNodeDataByRawData(ndata, data ,datalen);
if(ndata.empty())
return true;
if(!Find(section))
{
Section *ps=new Section();
if(!ps)
return false;
m_changed=true;
ps->PutSection(section);
for(NodeData::const_iterator nit=ndata.begin(); nit!=ndata.end(); ++nit)
ps->Push(nit->first.c_str(), nit->second.c_str());
m_data[section]=ps;
m_SectionOrder.push_back(section);
return true;
}else
{
m_changed=true;
for(NodeData::const_iterator nit=ndata.begin(); nit!=ndata.end(); ++nit)
m_data[section]->Push(nit->first.c_str(), nit->second.c_str());
return true;
}
}
catch(...)
{
cout<<" Exception in WriteManyString into IniFile."<<endl;
return false;
}
return true;
}
bool GeneralPool::WriteString(word section, word key, word str)
{
MutexLock lock(m_UpdateLock);
if(!Find(section))
{
Section *ps=new Section();
if(!ps)
return false;
ps->PutSection(section);
if(!ps->Push(key,str))
return false;
m_data[section]=ps;
m_SectionOrder.push_back(section);
m_changed=true;
return true;
}else
{
m_changed=true;
return m_data[section]->Push(key,str);
}
return true;
}
word GeneralPool::GetString(word section, word key,word defaultret)
{
if(!Find(section))
return defaultret;
word str;
if(!m_data[section]->Pop(key,str))
return defaultret;
return str;
}
bool GeneralPool::WriteInt(word section,word key,int value)
{
MutexLock lock(m_UpdateLock);
if(!Find(section))
{
Section *ps=new Section();
if(!ps)
return false;
ps->PutSection(section);
if(!ps->Push(key,value))
return false;
m_data[section]=ps;
m_SectionOrder.push_back(section);
m_changed=true;
return true;
}else
{
m_changed=true;
return m_data[section]->Push(key,value);
}
return true;
}
int GeneralPool::GetInt(word section,word key, int defaultret)
{
if(!Find(section))
return defaultret;
int value=0;
if(!m_data[section]->Pop(key,value))
return defaultret;
return value;
}
bool GeneralPool::GetSectionsName(std::list<string> §ions,std::string inifilename)
{
std::set<string> names; std::set<string>::iterator sit;
std::set<string> sectodel;
string sname;
WORDLIST::iterator it;
for(it=m_SectionOrder.begin();it!=m_SectionOrder.end();it++)
{
sname= (*it).getword();
sit= names.find(sname);
if(sit!=names.end())
{
sectodel.insert(sname);
continue;
}
sections.push_back(sname);
names.insert(sname);
}
if(sectodel.empty())
return true;
else
{
MutexLock lock(m_UpdateLock);
for(sit=sectodel.begin(); sit!=sectodel.end(); ++sit)
DeleteSectionInSectionOrder(sit->c_str());
printf("inifile: %s \n deleted %d duplicate section-name in SectionOrder.\n",inifilename.c_str(),sectodel.size());
m_changed=true;
}
Submit();
/* COMMONDATAMAP::iterator it;
while(m_data.findnext(it))
{
sections.push_back((*it).getkey().getword());
}
*/
return true;
}
bool GeneralPool::GetKeysName(word section,std::list<string> &keylist)
{
if(!Find(section))
return false;
return m_data[section]->GetKeys(keylist);
}
int GeneralPool::GetValueTypeBySectionAndKey(word section,word key)
{
if(!Find(section))
return -1;
return m_data[section]->GetValueTypeByKey(key);
}
| [
"james.cjt@gmail.com"
] | james.cjt@gmail.com |
312ca4b69bc6e8e6d68fe89e3d7f065dc86ef1dc | ed046ba2caab99d11d2b97932be83d87329416b3 | /src/Datalogger/main.cpp | 38afd0da379b29e8de3c5f650ebba9822325abe5 | [
"MIT"
] | permissive | lati1013/Self-Balancing-Bike | 72d02bfa2bb0d07f31abf1c6629e939c7fddfc4e | 77fa325ad4b3de77687985a04c470a149f01b501 | refs/heads/master | 2020-03-30T06:28:20.210050 | 2018-09-29T20:39:57 | 2018-09-29T20:39:57 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,530 | cpp | #include "cMeasurementLog.h"
#include <fstream>
#include <vector>
#include <string>
void make_example_sinus(cMeasurementLog<float, float>& pLog, float amplitude, float frequency, float total_time, float time_step);
int main()
{
// Wir geben jeder Messreihe einen Namen
//
std::vector<std::string> column_header;
column_header.push_back("Zeit[sec]");
column_header.push_back("Spannung [mV]");
// in den <> werden die Anzahl und der jeweilige Datentyp der Messreihen angegeben
// Im Beispiel: 1. Zeit, 2. Wert
cMeasurementLog<float, float> example_measurements(column_header);
// Fülle Beispiel mit sinus
make_example_sinus(example_measurements, 5.0f, 1.0f, 5.0f, 0.05f);
// Gewünschtes Format exportieren
std::string mes = example_measurements.exprt("");
// In Datei speichern
// Auf esp per wifi herunterladbar zukünftig
//
std::ofstream out("example_measurement.txt");
out << mes;
out.close();
// --> Beliebige Datentypen möglich! <--
/*
cMeasurementLog<std::string, float> mes;
mes.write("Hallo", 0);
mes.write("das ist", 2.32f);
mes.write("ein Test!", 21.532f);
std::string res = mes.exprt("");
*/
return 0;
}
// Fülle Messblatt mit test sinus
//
void make_example_sinus(
cMeasurementLog<float, float>& pLog,
float amplitude, float frequency,
float total_time, float time_step)
{
int num_ticks = total_time / time_step;
for (int tk = 0; tk < num_ticks; tk++)
{
float time = tk * time_step;
pLog.write(time, amplitude * sin(2.0*PI*frequency * time));
}
} | [
"philipp.kirsch94@googlemail.com"
] | philipp.kirsch94@googlemail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.