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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b554ed3ddbc86a6b2b392efd32629fe272ef80d6 | 82685d006a3c55bb7ee00028d222a5b590189bbf | /Sourcecode/mx/core/elements/OtherNotationAttributes.h | 885669fdca2c61c365312dddc9032db0f2f3b995 | [
"MIT"
] | permissive | ailialy/MusicXML-Class-Library | 41b1b6b28a67fd7cdfbbc4fb7c5c936aee4d9eca | 5e1f1cc8831449476f3facfff5cf852d66488d6a | refs/heads/master | 2020-06-18T23:46:50.306435 | 2016-08-22T04:33:44 | 2016-08-22T04:33:44 | 74,932,821 | 2 | 0 | null | 2016-11-28T03:14:23 | 2016-11-28T03:14:23 | null | UTF-8 | C++ | false | false | 1,617 | h | // MusicXML Class Library v0.2
// Copyright (c) 2015 - 2016 by Matthew James Briggs
#pragma once
#include "mx/core/ForwardDeclare.h"
#include "mx/core/AttributesInterface.h"
#include "mx/core/Decimals.h"
#include "mx/core/Enums.h"
#include "mx/core/Integers.h"
#include "mx/core/Strings.h"
#include "mx/core/FontSize.h"
#include <iosfwd>
#include <memory>
#include <vector>
namespace mx
{
namespace core
{
MX_FORWARD_DECLARE_ATTRIBUTES( OtherNotationAttributes )
struct OtherNotationAttributes : public AttributesInterface
{
public:
OtherNotationAttributes();
virtual bool hasValues() const;
virtual std::ostream& toStream( std::ostream& os ) const;
StartStopSingle type;
NumberLevel number;
YesNo printObject;
TenthsValue defaultX;
TenthsValue defaultY;
TenthsValue relativeX;
TenthsValue relativeY;
CommaSeparatedText fontFamily;
FontStyle fontStyle;
FontSize fontSize;
FontWeight fontWeight;
AboveBelow placement;
const bool hasType;
bool hasNumber;
bool hasPrintObject;
bool hasDefaultX;
bool hasDefaultY;
bool hasRelativeX;
bool hasRelativeY;
bool hasFontFamily;
bool hasFontStyle;
bool hasFontSize;
bool hasFontWeight;
bool hasPlacement;
bool fromXElement( std::ostream& message, xml::XElement& xelement );
};
}
}
| [
"matthew.james.briggs@gmail.com"
] | matthew.james.briggs@gmail.com |
316ac1617790059ba1403fe694d0a9ecbe1d1269 | b7e2c62cff4fadf8b7eadda14bf80b367273042e | /build/gcc-obj/sparc64-sun-xomb/libstdc++-v3/include/ext/pb_ds/detail/rb_tree_map_/info_fn_imps.hpp | 23413ab5042fd8cc705da399a2abdefdc8ad2dbf | [] | no_license | att14/ultraxomb | 7fc1b650c876f5dde0fc9c5a3da667321843256e | d75188655b4201133001cdda740cb49170abae1d | refs/heads/master | 2021-01-18T14:25:01.749582 | 2011-12-13T23:02:45 | 2011-12-13T23:02:45 | 2,603,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105 | hpp | /home/att14/ultraxomb/build/gcc-4.5.3/libstdc++-v3/include/ext/pb_ds/detail/rb_tree_map_/info_fn_imps.hpp | [
"att14@pitt.edu"
] | att14@pitt.edu |
8aa4d5445af7a10342505b85c7499d95a3fe7ca0 | 0c7594a3ae72346ae680085152b0f5fe8c29606d | /src/show_similar_images.cc | 0ae785d5b412fc868febc0b9323d14ec42671d26 | [] | no_license | koichiHik/blog_vlfeat_image_compare | ac87b5ea05c9025c80b56433834f29bc9d24b80b | 4783b1a5d57b8b635b4433c39bdb2c1ca0050384 | refs/heads/master | 2022-10-30T01:55:35.720751 | 2020-06-19T02:44:03 | 2020-06-19T02:44:03 | 271,477,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,918 | cc |
// STL
#include <chrono>
#include <filesystem>
#include <fstream>
#include <string>
#include <unordered_map>
// Glog
#include <glog/logging.h>
// GFlag
#include <gflags/gflags.h>
// Cereal
#include <cereal/archives/portable_binary.hpp>
#include <cereal/types/string.hpp>
#include <cereal/types/unordered_map.hpp>
// Eigen
#include <eigen3/Eigen/Core>
// OpenCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
// Matplotlib-CPP
#include "matplotlib-cpp/matplotlibcpp.h"
// Original
#include "eigen_serializable.h"
#include "global_descriptor.h"
#include "image_descriptor.h"
DEFINE_string(image_directory, "", "");
DEFINE_string(sift_directory, "", "");
DEFINE_string(matching_matrix_path, "", "");
DEFINE_string(target_filename, "", "");
// Value defined in CMakeLists.txt file.
static const std::string project_folder_path = PRJ_FOLDER_PATH;
namespace {
void ExtractAllFilePathsInDirectory(const std::string& dir_path,
std::vector<std::string>& filenames) {
namespace fs = std::filesystem;
for (const fs::directory_entry& file : fs::directory_iterator(dir_path)) {
if (!file.is_directory()) {
filenames.push_back(file.path());
}
}
LOG(INFO) << "Count of found files : " << filenames.size();
}
std::string GetFilePath(const std::string& partial_name,
const std::vector<std::string>& filepaths) {
for (const auto path : filepaths) {
if (path.rfind(partial_name) != std::string::npos) {
return path;
}
}
LOG(FATAL);
return "";
}
void LoadKeyPointsAndFeatures(const std::string& bin_file_path, std::vector<KeyPoint>& keypoints,
std::vector<Eigen::VectorXf>& descriptors) {
keypoints.clear();
descriptors.clear();
std::ifstream feature_reader(bin_file_path, std::ios::in | std::ios::binary);
cereal::PortableBinaryInputArchive input_archive(feature_reader);
input_archive(keypoints, descriptors);
}
void LoadImageInfo(const std::vector<std::string>& image_files,
const std::vector<std::string>& feature_files,
std::unordered_map<std::string, ImageInfo>& iamge_info_map,
bool load_images = false) {
if (load_images) {
CHECK_GE(image_files.size(), feature_files.size());
}
int total_size = feature_files.size();
int cnt = 0;
for (const auto feature_path : feature_files) {
const std::string filename_wo_ext =
std::filesystem::path(feature_path).filename().replace_extension("");
LOG(INFO) << "Load image info... " << cnt << " / " << total_size;
cnt++;
std::vector<KeyPoint> keypoints;
std::vector<Eigen::VectorXf> descriptors;
LoadKeyPointsAndFeatures(feature_path, keypoints, descriptors);
cv::Mat image;
if (load_images) {
std::string image_path = GetFilePath(filename_wo_ext, image_files);
image = cv::imread(image_path);
}
iamge_info_map[filename_wo_ext] = ImageInfo(image, keypoints, descriptors);
}
}
void DrawKeyPoints(const std::vector<KeyPoint>& keypoints, cv::Mat& img) {
for (const auto& kp : keypoints) {
int radius = std::pow(2, kp.octave_);
cv::circle(img, cv::Point2i(kp.x_, kp.y_), kp.size_, cv::Scalar(0, 200, 200), 1);
}
}
void DisplayKeyPoints(const std::unordered_map<std::string, ImageInfo>& info_map) {
for (const auto& [key, value] : info_map) {
cv::Mat drawn_img;
value.image_.copyTo(drawn_img);
DrawKeyPoints(value.keypoints_, drawn_img);
cv::imshow("Image", drawn_img);
cv::waitKey(0);
}
}
void CreateMatchingMatrix(const std::string& gmm_file_path, const std::string& matching_matrix_path,
std::unordered_map<std::string, ImageInfo>& image_info_map) {
FisherVectorEncoder fisher_encoder(gmm_file_path);
// X.
LOG(INFO) << "Create filename index map.";
std::unordered_map<std::string, int> filenames_indices;
std::unordered_map<int, std::string> indices_filemanes;
int index = 0;
for (auto citr = image_info_map.cbegin(); citr != image_info_map.cend(); ++citr) {
std::filesystem::path p(citr->first);
std::string filename = p.replace_extension("").filename().string();
filenames_indices[filename] = index;
indices_filemanes[index] = filename;
index++;
}
LOG(INFO) << "Matching matrix computation starts!";
int size = image_info_map.size();
Eigen::MatrixXf matching_matrix(size, size);
LOG(INFO) << "Size : " << size;
for (const auto& [filename1, value] : image_info_map) {
int idx1 = filenames_indices[filename1];
matching_matrix(idx1, idx1) = 0.0;
for (int idx2 = idx1 + 1; idx2 < size; idx2++) {
Eigen::VectorXf feature1 =
fisher_encoder.ComputeFisherVector(image_info_map[filename1].descriptors_);
std::string filename2 = indices_filemanes[idx2];
Eigen::VectorXf feature2 =
fisher_encoder.ComputeFisherVector(image_info_map[filename2].descriptors_);
float score = (feature1 - feature2).squaredNorm();
matching_matrix(idx1, idx2) = score;
matching_matrix(idx2, idx1) = score;
}
}
std::cout << matching_matrix << std::endl;
std::ofstream writer(matching_matrix_path, std::ios::out | std::ios::binary);
cereal::PortableBinaryOutputArchive output_archive(writer);
output_archive(filenames_indices, matching_matrix);
}
void LoadMatchingMatrix(const std::string& filepath,
std::unordered_map<std::string, int>& filenames_indices,
Eigen::MatrixXf& matching_matrix) {
std::ifstream reader(filepath, std::ios::in | std::ios::binary);
cereal::PortableBinaryInputArchive input_archive(reader);
input_archive(filenames_indices, matching_matrix);
}
void ShowTopXImages(const std::string& target_filename, const Eigen::MatrixXf& matching_matrix,
int top_x, std::unordered_map<std::string, int>& filenames_indices,
std::unordered_map<std::string, ImageInfo>& image_info_map) {
std::filesystem::path p(target_filename);
std::string tgt = p.replace_extension("").filename();
if (image_info_map.find(tgt) == image_info_map.end()) {
LOG(INFO) << "File with name : " << tgt << " does not exist.";
}
// X. Create index - filename map.
std::unordered_map<int, std::string> indices_filenames;
for (const auto& [key, value] : filenames_indices) {
indices_filenames[value] = key;
}
// X. Create Vector with Matching Score.
int idx = filenames_indices[tgt];
int len = matching_matrix.cols();
std::vector<float> vec(len);
for (int i = 0; i < len; i++) {
vec[i] = matching_matrix(i, idx);
}
std::vector<float> sorted_score_vec(vec);
std::sort(sorted_score_vec.begin(), sorted_score_vec.end());
cv::imshow("Target Image", image_info_map[tgt].image_);
for (int i = 0; i < top_x; i++) {
int min_idx = std::min_element(vec.begin(), vec.end()) - vec.begin();
float score = vec[min_idx];
vec[min_idx] = std::numeric_limits<float>::max();
// X. Skip query image.
if (score == 0) {
continue;
}
std::string filename = indices_filenames[min_idx];
LOG(INFO) << "Image of score : " << score;
LOG(INFO) << "Filename of image : " << filename;
cv::imshow("Similar Image", image_info_map[filename].image_);
cv::waitKey(0);
}
// X. Skip query image.
std::vector<float> plot_data(sorted_score_vec.begin() + 1, sorted_score_vec.end());
matplotlibcpp::plot(plot_data);
matplotlibcpp::show();
}
} // namespace
int main(int argc, char** argv) {
// X. Initial setting.
google::ParseCommandLineFlags(&argc, &argv, true);
FLAGS_alsologtostderr = 1;
FLAGS_stderrthreshold = google::GLOG_INFO;
google::InitGoogleLogging(argv[0]);
// X. Data directory.
const std::string image_dir =
FLAGS_image_directory.empty() ? project_folder_path + "/images" : FLAGS_image_directory;
const std::string sift_dir =
FLAGS_sift_directory.empty() ? project_folder_path + "/data" : FLAGS_sift_directory;
// X. Extract binary file paths.
std::vector<std::string> image_files, feature_files;
LOG(INFO) << "Load all image file paths.";
ExtractAllFilePathsInDirectory(image_dir, image_files);
LOG(INFO) << "Load all binary file paths.";
ExtractAllFilePathsInDirectory(sift_dir, feature_files);
// X. Deserialize
LOG(INFO) << "Load ImageInfo.";
std::unordered_map<std::string, ImageInfo> image_info_map;
LoadImageInfo(image_files, feature_files, image_info_map, true);
// X. Train GMM with Deserialized data.
LOG(INFO) << "Load matching matrix.";
std::unordered_map<std::string, int> image_indices;
Eigen::MatrixXf matching_matrix;
LoadMatchingMatrix(FLAGS_matching_matrix_path, image_indices, matching_matrix);
// X.
ShowTopXImages(FLAGS_target_filename, matching_matrix, 20, image_indices, image_info_map);
return 0;
}
| [
"rkoichi2001@gmail.com"
] | rkoichi2001@gmail.com |
7720ad427da5c5613dbbac8142fa09374291cf05 | 2a582f35e436cec0addcb822c9f4a213f4712d47 | /include/TensorRestriction.hpp | a9074f4348ffd7854be4e9f4196595abc8f775b7 | [
"Apache-2.0"
] | permissive | CODARcode/MGARD | 10bd77f5a4ca4739d396a2fbc4fc2d83d6780ca3 | 7f9fd661cb8083d5fd5d7c345d5453ddabc3633e | refs/heads/master | 2023-08-04T16:15:23.518453 | 2023-07-14T19:04:19 | 2023-07-21T03:19:57 | 157,610,031 | 32 | 27 | Apache-2.0 | 2023-07-21T03:19:59 | 2018-11-14T20:57:29 | C++ | UTF-8 | C++ | false | false | 2,234 | hpp | #ifndef TENSORRESTRICTION_HPP
#define TENSORRESTRICTION_HPP
//!\file
//!\brief Restriction for tensor product grids.
#include "TensorLinearOperator.hpp"
namespace mgard {
//! Restriction for continuous piecewise linear functions defined on a
//! mesh 'spear.'
template <std::size_t N, typename Real>
class ConstituentRestriction : public ConstituentLinearOperator<N, Real> {
public:
//! Constructor.
//!
//! This constructor is provided so that arrays of this class may be formed. A
//! default-constructed instance must be assigned to before being used.
ConstituentRestriction() = default;
//! Constructor.
//!
//!\param hierarchy Mesh hierarchy on which the functions are defined.
//!\param l Index of the mesh on which the restriction is to be applied. This
//! is the index of the fine mesh (corresponding to the domain).
//!\param dimension Index of the dimension in which the restriction is to be
//! applied.
ConstituentRestriction(const TensorMeshHierarchy<N, Real> &hierarchy,
const std::size_t l, const std::size_t dimension);
private:
using CLO = ConstituentLinearOperator<N, Real>;
//! Indices of the coarse 'spear' in the chosen dimension.
TensorIndexRange coarse_indices;
virtual void
do_operator_parentheses(const std::array<std::size_t, N> multiindex,
Real *const v) const override;
};
//! Restriction for tensor products of continuous piecewise linear functions
//! defined on a Cartesian product mesh hierarchy.
template <std::size_t N, typename Real>
class TensorRestriction : public TensorLinearOperator<N, Real> {
public:
//! Constructor.
//!
//!\param hierarchy Mesh hierarchy on which the functions are defined.
//!\param l Index of the mesh on which the restriction is to be applied. This
//! is the index of the fine mesh (corresponding to the domain).
TensorRestriction(const TensorMeshHierarchy<N, Real> &hierarchy,
const std::size_t l);
private:
using TLO = TensorLinearOperator<N, Real>;
//! Constituent restrictions for each dimension.
const std::array<ConstituentRestriction<N, Real>, N> restrictions;
};
} // namespace mgard
#include "TensorRestriction.tpp"
#endif
| [
"qing.liu@njit.edu"
] | qing.liu@njit.edu |
abd5e215e7bd90ece57d8e285ba0ca25621c9e68 | 8732894f8b3a0be2d10510ffae949dbe350e395e | /src/processPipe.cpp | b365c043cbbbacc163121f3cba166bbdda4a923c | [
"MIT"
] | permissive | KerryL/eBirdDataProcessor | a8cd282669d087ca348bf51051cc827b089d6cf3 | fa8ae60db7f854c44e18f0b65754ce8620afa8eb | refs/heads/master | 2022-12-23T08:24:16.153166 | 2022-12-21T01:42:21 | 2022-12-21T01:42:21 | 88,875,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,649 | cpp | // File: processPipe.cpp
// Date: 7/19/2019
// Auth: K. Loux
// Desc: Wrapper for launching an application connected via a pipe.
// Local headers
#include "processPipe.h"
// OS headers
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#define popen _popen
#define pclose _pclose
#define sleep Sleep
#else
#include <unistd.h>
#endif// _WIN32
#include <fcntl.h>
// Standard C++ headers
#include <cassert>
#include <array>
#include <memory>
#include <stdexcept>
ProcessPipe::~ProcessPipe()
{
stop = true;
if (processThread.joinable())
processThread.join();
}
bool ProcessPipe::Launch(const std::string& command)
{
assert(stop);
stop = false;
try
{
processThread = std::thread(&ProcessPipe::PipeThread, this, command);
}
catch (...)
{
return false;
}
return true;
}
void ProcessPipe::PipeThread(const std::string& command)
{
std::array<char, 128> buffer;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(command.c_str(), "r"), pclose);
if (!pipe)
throw std::runtime_error("popen() failed!");
while (!stop)
{
#ifdef _WIN32
if (WaitForSingleObject(pipe.get(), 1000) == WAIT_OBJECT_0)
#else
while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()))// TODO: Doesn't work properly (it blocks, so application never exits)
#endif// _WIN32
{
std::lock_guard<std::mutex> lock(stdOutMutex);
stdOutBuffer += buffer.data();
}
#ifdef _WIN32
Sleep(100);// To avoid busy waiting
#else
usleep(100000);
#endif
}
}
std::string ProcessPipe::GetStdOutBuffer()
{
std::lock_guard<std::mutex> lock(stdOutMutex);
const std::string s(stdOutBuffer);
stdOutBuffer.clear();
return s;
}
| [
"kerryloux@gmail.com"
] | kerryloux@gmail.com |
7488d552364b70df10f2a28996c09f72f57b7056 | 9b87c038a5ce9b3c0caabb35cd1b8bf44a19c1da | /ColdEyes/Com/SerialPort.h | 4ba3980688be93d6394751170cee7dc62d820016 | [] | no_license | EmbededMind/ColdEyes | 98d519bf80d7f090ce65338d6aae473d07b4731e | 3cb007a76345f0f5751024b66e62a775c32de7f2 | refs/heads/master | 2021-01-11T08:47:14.230784 | 2017-01-05T02:05:56 | 2017-01-05T02:05:56 | 76,835,389 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 6,902 | h | /*
** FILENAME CSerialPort.h
**
** PURPOSE This class can read, write and watch one serial port.
** It sends messages to its owner when something happends on the port
** The class creates a thread for reading and writing so the main
** program is not blocked.
**
** CREATION DATE 15-09-1997
** LAST MODIFICATION 12-11-1997
**
** AUTHOR Remon Spekreijse
**
**
************************************************************************************
** author: mrlong date:2007-12-25
**
** 改进
** 1) 增加ClosePort
** 2) 增加 writetoProt() 两个方法
** 3) 增加 SendData 与 RecvData 方法
**************************************************************************************
***************************************************************************************
** author:liquanhai date:2011-11-04
** 改进
** 1)增加 ClosePort中交出控制权,防止死锁问题
**************************************************************************************
***************************************************************************************
** author:wanglei date:2012-06-12
** 改进
** 1)将InitPort中
** assert(portnr > 0 && portnr < 5);
** 改为
** assert(portnr > 0 && portnr < 255);
** 去掉串口号限制
**
*/
#ifndef __SERIALPORT_H__
#define __SERIALPORT_H__
#define WM_COMM_BREAK_DETECTED WM_USER+1 // A break was detected on input.
#define WM_COMM_CTS_DETECTED WM_USER+2 // The CTS (clear-to-send) signal changed state.
#define WM_COMM_DSR_DETECTED WM_USER+3 // The DSR (data-set-ready) signal changed state.
#define WM_COMM_ERR_DETECTED WM_USER+4 // A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
#define WM_COMM_RING_DETECTED WM_USER+5 // A ring indicator was detected.
#define WM_COMM_RLSD_DETECTED WM_USER+6 // The RLSD (receive-line-signal-detect) signal changed state.
#define WM_COMM_RXCHAR WM_USER+7 // A character was received and placed in the input buffer.
#define WM_COMM_RXFLAG_DETECTED WM_USER+8 // The event character was received and placed in the input buffer.
#define WM_COMM_TXEMPTY_DETECTED WM_USER+9 // The last character in the output buffer was sent.
#define WM_COMM_RXDATA WM_USER+10
#include "stdint.h"
#include "Pattern\IDataHandler.h"
typedef struct onedata {
uint8_t ch[18];
int num;
}onedata;
class CSerialPort
{
private: CSerialPort();
public:
// contruction and destruction
static CSerialPort* GetInstance(int portnr)
{
if (portnr == COM_KB)
{
static CSerialPort ComKB;
return &ComKB;
}
else if(portnr == COM_103)
{
static CSerialPort ComCam;
return &ComCam;
}
else {
return NULL;
}
};
virtual ~CSerialPort();
BOOL ConfigPort(UINT portnr = 1,
UINT baud = 19200,
char parity = 'N',
UINT databits = 8,
UINT stopbits = 1,
DWORD dwCommEvents = EV_RXCHAR | EV_CTS,
UINT writeBufferSize = 512,
DWORD ReadIntervalTimeout = 1000,
DWORD ReadTotalTimeoutMultiplier = 1000,
DWORD ReadTotalTimeoutConstant = 1000,
DWORD WriteTotalTimeoutMultiplier = 1000,
DWORD WriteTotalTimeoutConstant = 1000);
// port initialisation
BOOL InitPort(CWnd* pPortOwner, UINT portnr = 1, UINT baud = 19200,
char parity = 'N', UINT databits = 8, UINT stopsbits = 1,
DWORD dwCommEvents = EV_RXCHAR | EV_CTS, UINT nBufferSize = 512,
DWORD ReadIntervalTimeout = 1000,
DWORD ReadTotalTimeoutMultiplier = 1000,
DWORD ReadTotalTimeoutConstant = 1000,
DWORD WriteTotalTimeoutMultiplier = 1000,
DWORD WriteTotalTimeoutConstant = 1000);
BOOL InitPort(IDataHandler* pDataHandler, UINT portnr = 1, UINT baud = 19200,
char parity = 'N', UINT databits = 8, UINT stopsbits = 1,
DWORD dwCommEvents = EV_RXCHAR | EV_CTS, UINT nBufferSize = 512,
DWORD ReadIntervalTimeout = 1000,
DWORD ReadTotalTimeoutMultiplier = 1000,
DWORD ReadTotalTimeoutConstant = 1000,
DWORD WriteTotalTimeoutMultiplier = 1000,
DWORD WriteTotalTimeoutConstant = 1000);
void AttachWindow(CWnd* pOwnerWin);
void AttachDataHandle(IDataHandler* pDataHandler);
// start/stop comm watching
BOOL StartMonitoring();
BOOL RestartMonitoring();
BOOL StopMonitoring();
DWORD GetWriteBufferSize();
DWORD GetCommEvents();
DCB GetDCB();
void WriteToPort(char* string);
void WriteToPort(char* string,int n); // add by mrlong 2007-12-25
void WriteToPort(LPCTSTR string); // add by mrlong 2007-12-25
void WriteToPort(BYTE* Buffer, int n);// add by mrlong
void ClosePort(); // add by mrlong 2007-12-2
void SendData(LPCTSTR lpszData, const int nLength); //串口发送函数 by mrlong 2008-2-15
BOOL RecvData(LPTSTR lpszData, const int nSize); //串口接收函数 by mrlong 2008-2-15
protected:
#ifdef _DEBUG
HANDLE hOutputHandle;
#endif
// protected memberfunctions
void ProcessErrorMessage(char* ErrorText);
static UINT CommThread(LPVOID pParam);
static void ReceiveData(CSerialPort* port, COMSTAT comstat);
static void WriteChar(CSerialPort* port);
// thread
CWinThread* m_Thread;
// synchronisation objects
CRITICAL_SECTION m_csCommunicationSync;
BOOL m_bThreadAlive;
// handles
HANDLE m_hShutdownEvent; //stop发生的事件
HANDLE m_hComm; // read
HANDLE m_hWriteEvent; // write
// Event array.
// One element is used for each event. There are two event handles for each port.
// A Write event and a receive character event which is located in the overlapped structure (m_ov.hEvent).
// There is a general shutdown when the port is closed.
HANDLE m_hEventArray[3];
// structures
OVERLAPPED m_ov;
COMMTIMEOUTS m_CommTimeouts;
DCB m_dcb;
// owner window
CWnd* m_pOwner;
IDataHandler* m_pDataHandler;
// misc
char* m_szWriteBuffer;
DWORD m_dwCommEvents;
DWORD m_nWriteBufferSize;
UINT m_nPortNr;
int m_nWriteSize; //add by mrlong 2007-12-25
public :
onedata m_queuecom[20];
int m_queueth;
int m_charth;
};
#endif __SERIALPORT_H__
| [
"815407069@qq.com"
] | 815407069@qq.com |
b36653e1cdf8cfc75c5778f622bbb222b948c3a6 | 90a4ce8f411a2f0f319a5efd077941cf70cd8892 | /List.h | bc1ffb48d655d459c827ca2f1a4214efc4469a22 | [] | no_license | alexanderbrannlund/Projekt_DV1490 | 2d53983d12d96421dafd398c5bf764c953b54d8e | 53b130355cf2d3bacf68b55142b61d230a58b550 | refs/heads/master | 2020-03-18T09:18:39.164170 | 2018-05-23T10:57:05 | 2018-05-23T10:57:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,589 | h | #pragma once
#pragma once
template<typename T>
class List
{
public:
List();
virtual ~List();
List(const List& other);
List& operator=(const List& other);
void insertAt(int pos, const T& element) throw(...);
T getAt(int pos) const throw(...);
void removeAt(int pos) throw(...);
bool removeElement(const T& element);
bool findElement(const T& toFind) const;
int length() const;
void getAll(T arr[], int cap) throw(...);
private:
class Node
{
public:
T element;
Node* next;
Node(const T& element)
{
this->element = element;
this->next = nullptr;
}
~Node()
{
//empty
}
};
int nrOfNodes;
Node* first;
};
template<typename T>
inline List<T>::List()
{
this->nrOfNodes = 0;
this->first = nullptr;
}
template<typename T>
inline List<T>::~List()
{
Node* walker = first;
while (walker != nullptr)
{
Node* remove = walker;
walker = walker->next;
delete remove;
}
}
template<typename T>
inline List<T>::List(const List & other)
{
if (other.first == nullptr)
{
this->first = nullptr;
}
else
{
this->nrOfNodes = other.nrOfNodes;
this->first = new Node(other.first->element);
Node* walker = first;
Node* otherWalker = other.first;
while (otherWalker->next != nullptr)
{
walker->next = new Node(otherWalker->next->element);
otherWalker = otherWalker->next;
walker = walker->next;
}
}
}
template<typename T>
inline List<T> & List<T>::operator=(const List & other)
{
if (this != &other)
{
this->~List();
if (other.first == nullptr)
{
this->first = nullptr;
this->nrOfNodes = 0;
}
else
{
this->nrOfNodes = other.nrOfNodes;
this->first = new Node(other.first->element);
Node* walker = first;
Node* otherWalker = other.first;
while (otherWalker->next != nullptr)
{
walker->next = new Node(otherWalker->next->element);
otherWalker = otherWalker->next;
walker = walker->next;
}
}
}
return *this;
}
template<typename T>
inline void List<T>::insertAt(int pos, const T & element) throw(...)
{
if ((pos>this->nrOfNodes) || (pos<0))
{
throw "Invalid position..";
}
Node* temp = new Node(element);
if (pos == 0)
{
temp->next = first;
first = temp;
}
else
{
Node* walker = first;
for (int i = 0; i < pos - 1; i++)
{
walker = walker->next;
}
temp->next = walker->next;
walker->next = temp;
}
this->nrOfNodes++;
}
template<typename T>
inline T List<T>::getAt(int pos) const throw(...)
{
if (pos>this->nrOfNodes || pos<0)
{
throw "Invalid position..";
}
if (this->nrOfNodes == 0)
{
throw"The list is empty..";
}
T retVal;
if (pos == 0)
{
retVal = first->element;
}
else
{
Node* walker = first;
for (int i = 0; i < pos; i++)
{
walker = walker->next;
}
retVal = walker->element;
}
return retVal;
}
template<typename T>
inline void List<T>::removeAt(int pos) throw(...)
{
if (pos>this->nrOfNodes - 1 || pos<0)
{
throw "Invalid position..";
}
Node* current = first;
if (pos == 0)
{
first = current->next;
}
else
{
Node* previous = nullptr;
for (int i = 0; i < pos; i++)
{
previous = current;
current = current->next;
}
previous->next = current->next;
}
delete current;
nrOfNodes--;
}
template<typename T>
inline bool List<T>::removeElement(const T & element)
{
bool removed = false;
bool excist = this->findElement(element);
if (excist)
{
Node* walker = first;
if (walker->element == element)
{
first = walker->next;
removed = true;
}
else {
Node* previous = nullptr;
for (int i = 0; i < nrOfNodes - 1; i++)
{
previous = walker;
walker = walker->next;
if (walker->element == element)
{
previous->next = walker->next;
removed = true;
i = nrOfNodes;
}
}
}
delete walker;
nrOfNodes--;
}
return removed;
}
template<typename T>
inline bool List<T>::findElement(const T & toFind) const
{
bool found = false;
if (first != nullptr)
{
Node* walker = first;
if (walker->element == toFind)
{
found = true;
}
else {
for (int i = 0; i < nrOfNodes - 1; i++)
{
walker = walker->next;
if (walker->element == toFind)
{
found = true;
i = nrOfNodes;
}
}
}
}
return found;
}
template<typename T>
inline int List<T>::length() const
{
return this->nrOfNodes;
}
template<typename T>
inline void List<T>::getAll(T arr[], int cap) throw(...)
{
if (cap<this->nrOfNodes || cap<0)
{
throw "Array capacity to low";
}
Node* walker = first;
for (int i = 0; i < nrOfNodes; i++)
{
arr[i] = walker->element;
walker = walker->next;
}
}
| [
"34121715+alexanderbrannlund@users.noreply.github.com"
] | 34121715+alexanderbrannlund@users.noreply.github.com |
1592f6075fc2c00f659de3aed525458ed2173e66 | 63422d2fd3b1ff6d2d8899ad625eecb86fc7c3db | /Practice/Test.cpp | 9e00864537593a537bfabeea1e93b98ea9e62fac | [] | no_license | brianxchen/practice | 2ac1dc0e62f32ea796211c1e3bcfd51f5eb6b33e | e41002c8ca86310be699b94ad0775f1784786727 | refs/heads/master | 2023-07-06T19:44:03.995176 | 2021-08-14T06:20:29 | 2021-08-14T06:20:29 | 270,399,602 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | #pragma once
#include <iostream>
#include <queue>
using namespace std;
void showq(queue <int> gq)
{
queue <int> g = gq;
while (!g.empty())
{
cout << '\t' << g.front();
g.pop();
}
cout << '\n';
}
void Test2()
{
queue <int> gquiz;
gquiz.push(10);
} | [
"brianchen49@gmail.com"
] | brianchen49@gmail.com |
8f9c87efbc7c93203a0fe15bb40906a20303bf3d | 00a81a1fa10fa43858e978896177f06490c2c7f3 | /src/qt/bitcoinunits.h | 53a7aa0ac10caa56fa49775c0a61f38da14a11af | [
"MIT"
] | permissive | BTCIncognito/NOS-Coin | c61ce1a6c97f48af4dcc3f3c63bcbadaa898c6f0 | e542087d45e53640f2f608553c2377b95a3095e6 | refs/heads/master | 2020-03-19T02:09:44.494248 | 2018-05-30T12:55:12 | 2018-05-30T12:55:12 | 135,604,871 | 0 | 1 | null | 2018-05-31T15:49:40 | 2018-05-31T15:49:40 | null | UTF-8 | C++ | false | false | 4,643 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017 The Nos developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_BITCOINUNITS_H
#define BITCOIN_QT_BITCOINUNITS_H
#include "amount.h"
#include <QAbstractListModel>
#include <QString>
// U+2009 THIN SPACE = UTF-8 E2 80 89
#define REAL_THIN_SP_CP 0x2009
#define REAL_THIN_SP_UTF8 "\xE2\x80\x89"
#define REAL_THIN_SP_HTML " "
// U+200A HAIR SPACE = UTF-8 E2 80 8A
#define HAIR_SP_CP 0x200A
#define HAIR_SP_UTF8 "\xE2\x80\x8A"
#define HAIR_SP_HTML " "
// U+2006 SIX-PER-EM SPACE = UTF-8 E2 80 86
#define SIXPEREM_SP_CP 0x2006
#define SIXPEREM_SP_UTF8 "\xE2\x80\x86"
#define SIXPEREM_SP_HTML " "
// U+2007 FIGURE SPACE = UTF-8 E2 80 87
#define FIGURE_SP_CP 0x2007
#define FIGURE_SP_UTF8 "\xE2\x80\x87"
#define FIGURE_SP_HTML " "
// QMessageBox seems to have a bug whereby it doesn't display thin/hair spaces
// correctly. Workaround is to display a space in a small font. If you
// change this, please test that it doesn't cause the parent span to start
// wrapping.
#define HTML_HACK_SP "<span style='white-space: nowrap; font-size: 6pt'> </span>"
// Define THIN_SP_* variables to be our preferred type of thin space
#define THIN_SP_CP REAL_THIN_SP_CP
#define THIN_SP_UTF8 REAL_THIN_SP_UTF8
#define THIN_SP_HTML HTML_HACK_SP
/** Nos unit definitions. Encapsulates parsing and formatting
and serves as list model for drop-down selection boxes.
*/
class BitcoinUnits : public QAbstractListModel
{
Q_OBJECT
public:
explicit BitcoinUnits(QObject* parent);
/** Nos units.
@note Source: https://en.bitcoin.it/wiki/Units . Please add only sensible ones
*/
enum Unit {
NOS,
mNOS,
uNOS
};
enum SeparatorStyle {
separatorNever,
separatorStandard,
separatorAlways
};
//! @name Static API
//! Unit conversion and formatting
///@{
//! Get list of units, for drop-down box
static QList<Unit> availableUnits();
//! Is unit ID valid?
static bool valid(int unit);
//! Identifier, e.g. for image names
static QString id(int unit);
//! Short name
static QString name(int unit);
//! Longer description
static QString description(int unit);
//! Number of Satoshis (1e-8) per unit
static qint64 factor(int unit);
//! Number of decimals left
static int decimals(int unit);
//! Format as string
static QString format(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
static QString simpleFormat(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
//! Format as string (with unit)
static QString formatWithUnit(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
static QString formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
//! Format as string (with unit) but floor value up to "digits" settings
static QString floorWithUnit(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
static QString floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = separatorStandard);
//! Parse string to coin amount
static bool parse(int unit, const QString& value, CAmount* val_out);
//! Gets title for amount column including current display unit if optionsModel reference available */
static QString getAmountColumnTitle(int unit);
///@}
//! @name AbstractListModel implementation
//! List model for unit drop-down selection box.
///@{
enum RoleIndex {
/** Unit identifier */
UnitRole = Qt::UserRole
};
int rowCount(const QModelIndex& parent) const;
QVariant data(const QModelIndex& index, int role) const;
///@}
static QString removeSpaces(QString text)
{
text.remove(' ');
text.remove(QChar(THIN_SP_CP));
#if (THIN_SP_CP != REAL_THIN_SP_CP)
text.remove(QChar(REAL_THIN_SP_CP));
#endif
return text;
}
//! Return maximum number of base units (Satoshis)
static CAmount maxMoney();
private:
QList<BitcoinUnits::Unit> unitlist;
};
typedef BitcoinUnits::Unit BitcoinUnit;
#endif // BITCOIN_QT_BITCOINUNITS_H
| [
"ratstang@digis.net"
] | ratstang@digis.net |
8e6d7b61089070c87ed75a98aa279e9e789fe5b1 | 56ba2984d5f47c13ebb3ded8a041d43f9522e27f | /inexlib/ourex/SOPHYA/src/HiStats/basedtable.cc | 4179439f379a0915fc2628d17afdac5fbe55ee69 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | gbarrand/TouchSky | 2ad7ec6eef209a8319698829877c20469857dbe1 | a6216fb20fbcf9e38ac62a81cef8c4f053a07b8c | refs/heads/master | 2021-09-11T07:25:41.523286 | 2021-08-31T09:29:39 | 2021-08-31T09:29:39 | 133,839,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 112,083 | cc | //-----------------------------------------------------------
// Class BaseDataTable
// Interface class and common services implementation for
// data organised as row-column tables
// SOPHYA class library - (C) UPS+LAL IN2P3/CNRS , CEA-Irfu
// R. Ansari (C) UPS+LAL IN2P3/CNRS 2005, 2013
//-----------------------------------------------------------
// R. Ansari - Avril 2005 - MAJ : 2013
#include "basedtable.h"
#include <ctype.h>
#include "pexceptions.h"
#include "thsafeop.h"
#include <string.h>
#include <stdio.h>
using namespace std;
namespace SOPHYA {
/*!
\class BaseDataTable
\ingroup HiStats
Base class for data tables. Each row (line) represent a record
and the column contains a given data type. A column may contain
a vector of data with a fixed size vsz.
The following data types are currently supported:
\verbatim
----------------------------------------------------------------------------------------
Integer : 32 bits signed integer (int_4)
LongInteger : 64 bits signed integer (int_8)
Float : single precision float (32 bits, r_4 )
Double : double precision float (64 bits, r_8 )
Complex : single precision complex number (2 x 32 bits, complex<r_4> )
DoubleComplex : double precision complex number (2 x 64 bits, complex<r_8> )
String : character string, variable unbound length (std::string)
DateTime : date/time (SOPHYA::TimeStamp)
Character : character (8 bits, char)
String16 : character string with a maximum length of 15 characters (SOPHYA::String16)
String64 : character string with a maximum length of 63 characters (SOPHYA::String64)
FlagVector16 : array of 16 flags (SOPHYA::FlagVector16)
FlagVector64 : array of 64 flags (SOPHYA::FlagVector64)
----------------------------------------------------------------------------------------
\endverbatim
Data can be appended to the table row by row (AddRow()) and accessed row wise (GetRow()),
or column wise (GetColumn()). Data can also be copied to the table column wise (FillColumn()).
Selected rows and or column can be copied from another table (CopySelectedRows() CopySelectedRowColumns()).
Row-wise and column-wise data merging operations can be also performed between tables
(see CopyFrom() , RowMerge() and ColumnMerge()).
\warning Thread safe fill operation can be activated using the method SetThreadSafe()
Default mode is NON thread-safe fill.
\sa SOPHYA::MuTyV
\sa SOPHYA::DataTableRow
\sa SOPHYA::DataTableRowPtr
\sa SOPHYA::BaseDataTable
*/
/*!
if fgl == true , return LongForm string
\verbatim
----------------------------------------------
FieldType ShortForm LongForm
----------------------------------------------
IntegerField I Integer
LongField L Long Integer
FloatField F Float
DoubleField D Double
ComplexField Zx4 Complex
DoubleComplexField Zx8 DoubleComplex
StringField S String
DateTimeField T DateTime
CharField C Character
FMLStr16Field S16 String16
FMLStr64Field S64 String64
FlagVec16Field B16 FlagVector16
FlagVec64Field B64 FlagVector64
----------------------------------------------
\endverbatim
*/
string BaseDataTable::ColTypeToString(FieldType ft, bool fgl)
{
string rs;
switch (ft) {
case IntegerField :
if (fgl) rs = "Integer";
else rs = "I";
break;
case LongField :
if (fgl) rs = "Long Integer";
else rs = "L";
break;
case FloatField :
if (fgl) rs = "Float";
else rs = "F";
break;
case DoubleField :
if (fgl) rs = "Double";
else rs = "D";
break;
case ComplexField :
if (fgl) rs = "Complex";
else rs = "Zx4";
break;
case DoubleComplexField :
if (fgl) rs = "DoubleComplex";
else rs = "Zx8";
break;
case StringField :
if (fgl) rs = "String";
else rs = "S";
break;
case DateTimeField :
if (fgl) rs = "DateTime";
else rs = "T";
break;
case CharacterField :
if (fgl) rs = "Character";
else rs = "C";
break;
case FMLStr16Field :
if (fgl) rs = "String16";
else rs = "S16";
break;
case FMLStr64Field :
if (fgl) rs = "String64";
else rs = "S64";
break;
case FlagVec16Field :
if (fgl) rs = "FlagVector16";
else rs = "B16";
break;
case FlagVec64Field :
if (fgl) rs = "FlagVector64";
else rs = "B64";
break;
default:
rs = "??";
break;
}
return rs;
}
BaseDataTable::FieldType BaseDataTable::StringToColType(string const & sctyp)
{
if ( (sctyp == "Integer") || (sctyp == "I") ) return IntegerField;
else if ( (sctyp == "Long Integer") || (sctyp == "L") ) return LongField;
else if ( (sctyp == "Float") || (sctyp == "F") ) return FloatField;
else if ( (sctyp == "Double") || (sctyp == "D") ) return DoubleField;
else if ( (sctyp == "Complex") || (sctyp == "Zx4") ) return ComplexField;
else if ( (sctyp == "DoubleComplex") || (sctyp == "Zx8") || (sctyp == "Z") )
return DoubleComplexField;
else if ( (sctyp == "String") || (sctyp == "S") ) return StringField;
else if ( (sctyp == "DateTime") || (sctyp == "T") ) return DateTimeField;
else if ( (sctyp == "Character") || (sctyp == "C") ) return CharacterField;
else if ( (sctyp == "String16") || (sctyp == "S16") ) return FMLStr16Field;
else if ( (sctyp == "String64") || (sctyp == "S64") ) return FMLStr64Field;
else if ( (sctyp == "FlagVector16") || (sctyp == "B16") ) return FlagVec16Field;
else if ( (sctyp == "FlagVector64") || (sctyp == "B64") ) return FlagVec64Field;
else return DoubleField;
}
DataTableCellType BaseDataTable::Convert2DTCellType(FieldType ft)
{
DataTableCellType rt;
switch (ft) {
case IntegerField :
rt = DTC_IntegerType;
break;
case LongField :
rt = DTC_LongType;
break;
case FloatField :
rt = DTC_FloatType;
break;
case DoubleField :
rt = DTC_DoubleType;
break;
case ComplexField :
rt = DTC_ComplexType;
break;
case DoubleComplexField :
rt = DTC_DoubleComplexType;
break;
case StringField :
rt = DTC_StringType;
break;
case DateTimeField :
rt = DTC_DateTimeType;
break;
case CharacterField :
rt = DTC_CharacterType;
break;
case FMLStr16Field :
rt = DTC_FMLStr16Type;
break;
case FMLStr64Field :
rt = DTC_FMLStr64Type;
break;
case FlagVec16Field :
rt = DTC_FlagVec16Type;
break;
case FlagVec64Field :
rt = DTC_FlagVec64Type;
break;
default:
rt = DTC_StringType;
break;
}
return rt;
}
/* Constructeur */
BaseDataTable::BaseDataTable(size_t segsz)
{
mNEnt = 0;
mSegSz = (segsz > 0) ? segsz : 16;
mNSeg = 0;
mVarD = NULL;
mVarMTV = NULL;
mVarMTP = NULL;
mVarTMS = NULL;
mVarStrP = NULL;
mFgVecCol = false;
mInfo = NULL;
mThS = NULL;
SetShowMinMaxFlag();
}
BaseDataTable::~BaseDataTable()
{
if (mVarD) delete[] mVarD;
if (mVarMTV) delete[] mVarMTV;
if (mVarMTP) delete[] mVarMTP;
if (mVarTMS) delete[] mVarTMS;
if (mVarStrP) delete[] mVarStrP;
if (mInfo) delete mInfo;
if (mThS) delete mThS;
}
/*!
\brief Activate or deactivate thread-safe \b AddRow() operations
If fg==true, create an ThSafeOp object in order to insure atomic AddRow()
and GetRow()/GetColumn() operations. if fg==false, the ThSafeOp object (mThS)
of the target DataTable is destroyed.
When activated, the following operations are thread-safe :
- AddRow(const r_8* data)
- AddRow(const MuTyV* data)
- AddRow(DataTableRow const& data)
- FillColumn(size_t k, vector<T> const& v)
- GetRow(size_t n, DataTableRow& row)
- GetRow(size_t n, MuTyV* mtvp)
- GetRowPtr(size_t n, DataTableRowPtr& rowp)
- GetCstRowPtr(size_t n, DataTableRowPtr& rowp)
- GetColumn(size_t k, vector<T> & v)
- GetColumnD(size_t k)
\warning The default AddRow() operation mode for DataTables is NOT thread-safe.
Note also that the thread-safety state is NOT saved to PPF (or FITS) streams.
*/
void BaseDataTable::SetThreadSafe(bool fg)
{
if (fg) {
if (mThS) return;
else mThS = new ThSafeOp();
}
else {
if (mThS) delete mThS;
mThS = NULL;
}
}
/*! \cond
\class DT_TSOP_SYNC
\ingroup HiStats
Classe utilitaire pour faciliter la gestion de lock pour
operations thread-safe BaseDataTable
*/
class DT_TSOP_SYNC {
public:
explicit DT_TSOP_SYNC(ThSafeOp* ths)
{
ths_ = ths;
if (ths_) ths_->lock();
}
~DT_TSOP_SYNC()
{
if (ths_) ths_->unlock();
}
inline ThSafeOp* NOp() { return ths_; }
protected:
ThSafeOp* ths_;
};
/*! \endcond */
/*
If the first table (*this) has already columns, a ParmError exception is generated. Otherwise,
the table (*this) structure, is copied from \b a table. The structure corresponds to
the table column names, types and vector size, as well as column units where applicable.
*/
size_t BaseDataTable::CopyStructure(BaseDataTable const & a)
{
if (NVar() > 0)
throw ParmError("BaseDataTable::CopyStructure() Table already has columns");
if (a.NVar() == 0) {
cout << "BaseDataTable::CopyStructure(a)/Warning Table a is not initialized" << endl;
return 0;
}
for (size_t kk=0; kk<a.mNames.size(); kk++) {
AddColumn(a.mNames[kk].type, a.mNames[kk].nom, a.mNames[kk].vecsz);
bool sdone=false;
Units un=a.GetUnits(kk,sdone);
if (sdone) SetUnits(kk,un);
}
return NVar();
}
/*!
No check on column names is performed. return true is same structure
*/
bool BaseDataTable::CompareStructure(BaseDataTable const & a)
{
if (NVar() != a.NVar()) return false;
for (size_t kk=0; kk<mNames.size(); kk++)
if ( (mNames[kk].type != a.mNames[kk].type) ||
(mNames[kk].vecsz != a.mNames[kk].vecsz) ) return false;
return true;
}
/*!
return true is same structure. The two tables should have the same structure (column type and vector
size), and the same column names.
*/
bool BaseDataTable::CompareStructAndColNames(BaseDataTable const & a)
{
if (NVar() != a.NVar()) return false;
for (size_t kk=0; kk<mNames.size(); kk++)
if ( (mNames[kk].type != a.mNames[kk].type) ||
(mNames[kk].nom != a.mNames[kk].nom) ||
(mNames[kk].vecsz != a.mNames[kk].vecsz) ) return false;
return true;
}
// Definition d'unite
void BaseDataTable::SetUnits(size_t k, const Units& un)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::SetUnits() out of range column index k");
size_t sk = mNames[k].ser;
switch (mNames[k].type) {
case IntegerField :
mIColsP[sk]->SetUnits(un);
break;
case LongField :
mLColsP[sk]->SetUnits(un);
break;
case FloatField :
mFColsP[sk]->SetUnits(un);
break;
case DoubleField :
mDColsP[sk]->SetUnits(un);
break;
case ComplexField :
mYColsP[sk]->SetUnits(un);
break;
case DoubleComplexField :
mZColsP[sk]->SetUnits(un);
break;
case StringField :
mSColsP[sk]->SetUnits(un);
break;
case DateTimeField :
mTColsP[sk]->SetUnits(un);
break;
case CharacterField :
mCColsP[sk]->SetUnits(un);
break;
case FMLStr16Field :
mS16ColsP[sk]->SetUnits(un);
break;
case FMLStr64Field :
mS64ColsP[sk]->SetUnits(un);
break;
case FlagVec16Field :
mB16ColsP[sk]->SetUnits(un);
break;
case FlagVec64Field :
mB64ColsP[sk]->SetUnits(un);
break;
default:
break;
}
return;
}
// Definition d'unite
Units BaseDataTable::GetUnits(size_t k, bool& sdone) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::SetUnits() out of range column index k");
size_t sk = mNames[k].ser;
Units ru;
switch (mNames[k].type) {
case IntegerField :
ru=mIColsP[sk]->GetUnits(sdone);
break;
case LongField :
ru=mLColsP[sk]->GetUnits(sdone);
break;
case FloatField :
ru=mFColsP[sk]->GetUnits(sdone);
break;
case DoubleField :
ru=mDColsP[sk]->GetUnits(sdone);
break;
case ComplexField :
ru=mYColsP[sk]->GetUnits(sdone);
break;
case DoubleComplexField :
ru=mZColsP[sk]->GetUnits(sdone);
break;
case StringField :
ru=mSColsP[sk]->GetUnits(sdone);
break;
case DateTimeField :
ru=mTColsP[sk]->GetUnits(sdone);
break;
case CharacterField :
ru=mCColsP[sk]->GetUnits(sdone);
break;
case FMLStr16Field :
ru=mS16ColsP[sk]->GetUnits(sdone);
break;
case FMLStr64Field :
ru=mS64ColsP[sk]->GetUnits(sdone);
break;
case FlagVec16Field :
ru=mB16ColsP[sk]->GetUnits(sdone);
break;
case FlagVec64Field :
ru=mB64ColsP[sk]->GetUnits(sdone);
break;
default:
break;
}
return ru;
}
//! Check the validity of column name \b cnom - throw exception.
bool BaseDataTable::CheckColName(string const & cnom)
{
size_t l,k;
l = cnom.length();
if (l < 1)
throw ParmError("BaseDataTable::CheckColName() zero length column name");
if (!isalpha(cnom[0]))
throw ParmError("BaseDataTable::CheckColName() first character not alphabetical");
for(k=1; k<l; k++)
if ((!isalnum(cnom[k])) && (cnom[k] != '_'))
throw ParmError("BaseDataTable::CheckColName() Non alphanumeric char in name");
for(k=0; k<mNames.size(); k++)
if (cnom == mNames[k].nom)
throw ParmError("BaseDataTable::CheckColName() already existing name");
return true;
}
/*!
\brief Check the validity of column name \b cnom and correct it if necessary
return true if \b cnom has been changed
*/
bool BaseDataTable::CheckCorrectColName(string& cnom)
{
size_t l,k;
l = cnom.length();
string ssn;
MuTyV mvv = (uint_8)(NCols()+1);
mvv.Convert(ssn);
bool fgrc = false;
if (l < 1) { cnom = "C"+ssn; fgrc = true; }
if (!isalpha(cnom[0])) { cnom = "C"+cnom; fgrc = true; }
for(k=1; k<l; k++)
if ((!isalnum(cnom[k])) && (cnom[k] != '_')) {
cnom[k] = '_'; fgrc = true;
}
bool fgdouble = true;
while (fgdouble) {
fgdouble = false;
for(k=0; k<mNames.size(); k++)
if (cnom == mNames[k].nom) {
fgdouble = true; break;
}
if (fgdouble) { cnom = cnom+ssn; fgrc = true; }
}
return fgrc;
}
// Retourne le nombre total d'elements dans une ligne
size_t BaseDataTable::NItems_in_Row() const
{
size_t rv=0;
for(size_t k=0; k<mNames.size(); k++) rv+=mNames[k].vecsz;
return rv;
}
void BaseDataTable::SetNRows(size_t nrows)
{
if (nrows < NRows()) {
cout << "(Warning) BaseDataTable::SetNRows(" << nrows << ") < NRows()=" << NRows() << " NOT changed " << endl;
return;
}
while (mSegSz*mNSeg < nrows) Extend();
size_t oldnrows=NRows();
mNEnt=nrows;
cout << "(Warning) BaseDataTable::SetNRows() changed " << oldnrows << " -> " << NRows() << endl;
return;
}
/*!
Extends the table (in the row direction). This method is called automatically when needed.
*/
size_t BaseDataTable::Extend()
{
for(size_t k=0; k<mIColsP.size(); k++)
mIColsP[k]->Extend();
for(size_t k=0; k<mLColsP.size(); k++)
mLColsP[k]->Extend();
for(size_t k=0; k<mFColsP.size(); k++)
mFColsP[k]->Extend();
for(size_t k=0; k<mDColsP.size(); k++)
mDColsP[k]->Extend();
for(size_t k=0; k<mYColsP.size(); k++)
mYColsP[k]->Extend();
for(size_t k=0; k<mZColsP.size(); k++)
mZColsP[k]->Extend();
for(size_t k=0; k<mSColsP.size(); k++)
mSColsP[k]->Extend();
for(size_t k=0; k<mTColsP.size(); k++)
mTColsP[k]->Extend();
for(size_t k=0; k<mCColsP.size(); k++)
mCColsP[k]->Extend();
for(size_t k=0; k<mS16ColsP.size(); k++)
mS16ColsP[k]->Extend();
for(size_t k=0; k<mS64ColsP.size(); k++)
mS64ColsP[k]->Extend();
for(size_t k=0; k<mB16ColsP.size(); k++)
mB16ColsP[k]->Extend();
for(size_t k=0; k<mB64ColsP.size(); k++)
mB64ColsP[k]->Extend();
mNSeg++;
return mNSeg;
}
// Retourne une structure
/*!
The returned DataTableRow object can be used for subsequent call to
AddRow() or GetRow() methods.
Generate an exception if called for a table with no columns
*/
DataTableRow BaseDataTable::EmptyRow() const
{
if (NCols() == 0)
throw ParmError("BaseDataTable::EmptyRow() Table has no column !");
vector<string> nms;
vector<size_t> cseqp;
for(size_t k=0; k<NVar(); k++) {
nms.push_back(mNames[k].nom);
cseqp.push_back(mNames[k].vecsz);
}
DataTableRow row(nms, cseqp);
return row;
}
/*!
The returned DataTablePtr object should be used in subsequent calls
GetRowPtr() or NextRowPtr() methods.
The method generates an exception if called for a table with no columns
The use of DataTablePtr object with GetRowPtr() / NextRowPtr() is a more efficient
way of filling the table or accessing its content, as it avoids unnecessary data copies.
\warning: the DataTablePtr returned by EmptyRowPtr() can not be used before
call to GetRowPtr() or NextRowPtr(), as data pointers are invalid ( = NULL)
*/
DataTableRowPtr BaseDataTable::EmptyRowPtr() const
{
if (NCols() == 0)
throw ParmError("BaseDataTable::EmptyRowPtr() Table has no column !");
vector<string> nms;
vector<size_t> csz;
vector<DataTableCellType> ctyp;
for(size_t k=0; k<NVar(); k++) {
ctyp.push_back(Convert2DTCellType(mNames[k].type));
nms.push_back(mNames[k].nom);
csz.push_back(mNames[k].vecsz);
}
DataTableRowPtr rowp(ctyp, nms, csz);
return rowp;
}
//
// A quel index correspond mon nom ?
//
size_t BaseDataTable::IndexNom(char const* nom) const
{
for(size_t k=0; k<NVar(); k++)
if ( mNames[k].nom == nom ) return k;
throw NotFoundExc("BaseDataTable::IndexNom(): unknown column name ");
}
string BaseDataTable::NomIndex(size_t k) const
{
if (k >= NVar())
throw RangeCheckError("BaseDataTable::NomIndex() out of range column index k");
return mNames[k].nom ;
}
//! Adds a row (or line) to the table with r_8* inout data
/*!
The data to be added is provided as an array (vector) of double (r_8).
The necessary data conversion is performed, depending on each
column's data typeconverted to the data type.
Return the new number of table rows (lines / entries)
\param data : Data for each cell of the row to be appended
data[k] k=0..NColumns() if no column with vector content
data[k] k=0..NItems_in_Row() if no column with vector content
*/
size_t BaseDataTable::AddRow(const r_8* data)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (NVar() == 0)
throw ParmError("BaseDataTable::AddRow(const r_8*) Table has no column !");
if (NEntry() == SegmentSize()*NbSegments()) Extend();
size_t n = NEntry();
size_t bid = n/mSegSz;
size_t off = n%mSegSz;
size_t off2 = off;
if (!mFgVecCol) { // Aucune colonne de type vecteur
for(size_t k=0; k<mIColsP.size(); k++)
mIColsP[k]->GetSegment(bid)[off] = (int_4)data[mIColIdx[k]];
for(size_t k=0; k<mLColsP.size(); k++)
mLColsP[k]->GetSegment(bid)[off] = (int_8)data[mLColIdx[k]];
for(size_t k=0; k<mFColsP.size(); k++)
mFColsP[k]->GetSegment(bid)[off] = (r_4)data[mFColIdx[k]];
for(size_t k=0; k<mDColsP.size(); k++)
mDColsP[k]->GetSegment(bid)[off] = data[mDColIdx[k]];
for(size_t k=0; k<mYColsP.size(); k++)
mYColsP[k]->GetSegment(bid)[off] = complex<r_4>(data[mYColIdx[k]],0.);
for(size_t k=0; k<mZColsP.size(); k++)
mZColsP[k]->GetSegment(bid)[off] = complex<r_8>(data[mZColIdx[k]],0.);
for(size_t k=0; k<mSColsP.size(); k++)
mSColsP[k]->GetSegment(bid)[off] = (string)MuTyV(data[mSColIdx[k]]);
for(size_t k=0; k<mTColsP.size(); k++)
mTColsP[k]->GetSegment(bid)[off].Set(data[mTColIdx[k]]);
for(size_t k=0; k<mCColsP.size(); k++)
mCColsP[k]->GetSegment(bid)[off] = '\0';
for(size_t k=0; k<mS16ColsP.size(); k++)
mS16ColsP[k]->GetSegment(bid)[off] = (string)MuTyV(data[mS16ColIdx[k]]);
for(size_t k=0; k<mS64ColsP.size(); k++)
mS64ColsP[k]->GetSegment(bid)[off] = (string)MuTyV(data[mS64ColIdx[k]]);
for(size_t k=0; k<mB16ColsP.size(); k++)
mB16ColsP[k]->GetSegment(bid)[off].clearAll();
for(size_t k=0; k<mB16ColsP.size(); k++)
mB64ColsP[k]->GetSegment(bid)[off].clearAll();
}
else { // Il y a des colonnes avec des contenus de type vecteur
for(size_t k=0; k<mIColsP.size(); k++) {
size_t nitems = mIColsP[k]->NbItems();
if (nitems == 1)
mIColsP[k]->GetSegment(bid)[off] = (int_4)data[mNames[mIColIdx[k]].item_in_row];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mIColsP[k]->GetSegment(bid)[off2+i] = (int_4)data[mNames[mIColIdx[k]].item_in_row+i];
}
}
for(size_t k=0; k<mLColsP.size(); k++) {
size_t nitems = mLColsP[k]->NbItems();
if (nitems == 1)
mLColsP[k]->GetSegment(bid)[off] = (int_8)data[mNames[mLColIdx[k]].item_in_row];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mLColsP[k]->GetSegment(bid)[off2+i] = (int_8)data[mNames[mLColIdx[k]].item_in_row+i];
}
}
for(size_t k=0; k<mFColsP.size(); k++) {
size_t nitems = mFColsP[k]->NbItems();
if (nitems == 1)
mFColsP[k]->GetSegment(bid)[off] = (r_4)data[mNames[mFColIdx[k]].item_in_row];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mFColsP[k]->GetSegment(bid)[off2+i] = (r_4)data[mNames[mFColIdx[k]].item_in_row+i];
}
}
for(size_t k=0; k<mDColsP.size(); k++) {
size_t nitems = mDColsP[k]->NbItems();
if (nitems == 1)
mDColsP[k]->GetSegment(bid)[off] = data[mNames[mDColIdx[k]].item_in_row];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mDColsP[k]->GetSegment(bid)[off2+i] = data[mNames[mDColIdx[k]].item_in_row+i];
}
}
for(size_t k=0; k<mYColsP.size(); k++) {
size_t nitems = mYColsP[k]->NbItems();
if (nitems == 1)
mYColsP[k]->GetSegment(bid)[off] = complex<r_4>(data[mNames[mYColIdx[k]].item_in_row],0.);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mYColsP[k]->GetSegment(bid)[off2+i] = complex<r_4>(data[mNames[mYColIdx[k]].item_in_row+i],0.);
}
}
for(size_t k=0; k<mZColsP.size(); k++) {
size_t nitems = mZColsP[k]->NbItems();
if (nitems == 1)
mZColsP[k]->GetSegment(bid)[off] = complex<r_8>(data[mNames[mZColIdx[k]].item_in_row],0.);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mZColsP[k]->GetSegment(bid)[off2+i] = complex<r_8>(data[mNames[mZColIdx[k]].item_in_row+i],0.);
}
}
for(size_t k=0; k<mSColsP.size(); k++) {
size_t nitems = mSColsP[k]->NbItems();
if (nitems == 1)
mSColsP[k]->GetSegment(bid)[off] = (string)MuTyV(data[mNames[mSColIdx[k]].item_in_row]);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mSColsP[k]->GetSegment(bid)[off2+i] = (string)MuTyV(data[mNames[mSColIdx[k]].item_in_row+i]);
}
}
for(size_t k=0; k<mTColsP.size(); k++) {
size_t nitems = mTColsP[k]->NbItems();
if (nitems == 1)
mTColsP[k]->GetSegment(bid)[off].Set(data[mNames[mTColIdx[k]].item_in_row]);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mTColsP[k]->GetSegment(bid)[off2+i].Set(data[mNames[mTColIdx[k]].item_in_row+i]);
}
}
for(size_t k=0; k<mCColsP.size(); k++) {
size_t nitems = mCColsP[k]->NbItems();
if (nitems == 1)
mCColsP[k]->GetSegment(bid)[off] = '\0';
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mCColsP[k]->GetSegment(bid)[off2+i] = '\0';
}
}
for(size_t k=0; k<mS16ColsP.size(); k++) {
size_t nitems = mS16ColsP[k]->NbItems();
if (nitems == 1)
mS16ColsP[k]->GetSegment(bid)[off] = (string)MuTyV(data[mNames[mS16ColIdx[k]].item_in_row]);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mS16ColsP[k]->GetSegment(bid)[off2+i] = (string)MuTyV(data[mNames[mS16ColIdx[k]].item_in_row+i]);
}
}
for(size_t k=0; k<mS64ColsP.size(); k++) {
size_t nitems = mS64ColsP[k]->NbItems();
if (nitems == 1)
mS64ColsP[k]->GetSegment(bid)[off] = (string)MuTyV(data[mNames[mS64ColIdx[k]].item_in_row]);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mS64ColsP[k]->GetSegment(bid)[off2+i] = (string)MuTyV(data[mNames[mS64ColIdx[k]].item_in_row+i]);
}
}
for(size_t k=0; k<mB16ColsP.size(); k++) {
size_t nitems = mB16ColsP[k]->NbItems();
if (nitems == 1)
mB16ColsP[k]->GetSegment(bid)[off].clearAll();
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mB16ColsP[k]->GetSegment(bid)[off2+i].clearAll();
}
}
for(size_t k=0; k<mB64ColsP.size(); k++) {
size_t nitems = mB64ColsP[k]->NbItems();
if (nitems == 1)
mB64ColsP[k]->GetSegment(bid)[off].clearAll();
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mB64ColsP[k]->GetSegment(bid)[off2+i].clearAll();
}
}
}
mNEnt++;
return mNEnt;
}
//! Adds a row (or line) to the table with input data as an array of MuTyV
/*!
The data to be added is provided as an array (vector) of MuTyV.
The MuTyV class conversion operators are used to match against each
cell data type.
Return the new number of table rows (lines / entries)
\param data : Data (MuTyV*) for each cell of the row to be appended
(data[k] k=0..NbColumns())
*/
size_t BaseDataTable::AddRow(const MuTyV* data)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (NVar() == 0)
throw ParmError("BaseDataTable::AddRow(const MuTyV*) Table has no column !");
if (NEntry() == SegmentSize()*NbSegments()) Extend();
size_t n = NEntry();
size_t bid = n/mSegSz;
size_t off = n%mSegSz;
size_t off2 = off;
complex<r_4> z4; complex<r_8> z8;
string str; TimeStamp tms;
int_8 i8dum;
if (!mFgVecCol) { // Aucune colonne de type vecteur
for(size_t k=0; k<mIColsP.size(); k++)
mIColsP[k]->GetSegment(bid)[off] = (int_4)data[mIColIdx[k]];
for(size_t k=0; k<mLColsP.size(); k++)
mLColsP[k]->GetSegment(bid)[off] = (int_8)data[mLColIdx[k]];
for(size_t k=0; k<mFColsP.size(); k++)
mFColsP[k]->GetSegment(bid)[off] = (r_4)data[mFColIdx[k]];
for(size_t k=0; k<mDColsP.size(); k++)
mDColsP[k]->GetSegment(bid)[off] = (r_8)data[mDColIdx[k]];
for(size_t k=0; k<mYColsP.size(); k++)
mYColsP[k]->GetSegment(bid)[off] =
complex<r_4>(data[mYColIdx[k]].GetRealPart(), data[mYColIdx[k]].GetImagPart());
for(size_t k=0; k<mZColsP.size(); k++)
mZColsP[k]->GetSegment(bid)[off] =
complex<r_8>(data[mZColIdx[k]].GetRealPart(), data[mZColIdx[k]].GetImagPart());
for(size_t k=0; k<mSColsP.size(); k++)
mSColsP[k]->GetSegment(bid)[off] = (string)data[mSColIdx[k]];
for(size_t k=0; k<mTColsP.size(); k++)
mTColsP[k]->GetSegment(bid)[off] = data[mTColIdx[k]].Convert(tms);
for(size_t k=0; k<mCColsP.size(); k++)
mCColsP[k]->GetSegment(bid)[off] = (char)data[mCColIdx[k]];
for(size_t k=0; k<mS16ColsP.size(); k++)
mS16ColsP[k]->GetSegment(bid)[off] = (string)(data[mS16ColIdx[k]]);
for(size_t k=0; k<mS64ColsP.size(); k++)
mS64ColsP[k]->GetSegment(bid)[off] = (string)(data[mS64ColIdx[k]]);
for(size_t k=0; k<mB16ColsP.size(); k++)
mB16ColsP[k]->GetSegment(bid)[off].decodeInteger(data[mB16ColIdx[k]].Convert(i8dum));
for(size_t k=0; k<mB64ColsP.size(); k++)
mB64ColsP[k]->GetSegment(bid)[off].decodeInteger(data[mB64ColIdx[k]].Convert(i8dum));
}
else { // Il y a des colonnes avec des contenus de type vecteur
for(size_t k=0; k<mIColsP.size(); k++) {
size_t nitems = mIColsP[k]->NbItems();
if (nitems == 1)
mIColsP[k]->GetSegment(bid)[off] = (int_4)data[mNames[mIColIdx[k]].item_in_row];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mIColsP[k]->GetSegment(bid)[off2+i] = (int_4)data[mNames[mIColIdx[k]].item_in_row+i];
}
}
for(size_t k=0; k<mLColsP.size(); k++) {
size_t nitems = mLColsP[k]->NbItems();
if (nitems == 1)
mLColsP[k]->GetSegment(bid)[off] = (int_8)data[mNames[mLColIdx[k]].item_in_row];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mLColsP[k]->GetSegment(bid)[off2+i] = (int_8)data[mNames[mLColIdx[k]].item_in_row+i];
}
}
for(size_t k=0; k<mFColsP.size(); k++) {
size_t nitems = mFColsP[k]->NbItems();
if (nitems == 1)
mFColsP[k]->GetSegment(bid)[off] = (r_4)data[mNames[mFColIdx[k]].item_in_row];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mFColsP[k]->GetSegment(bid)[off2+i] = (r_4)data[mNames[mFColIdx[k]].item_in_row+i];
}
}
for(size_t k=0; k<mDColsP.size(); k++) {
size_t nitems = mDColsP[k]->NbItems();
if (nitems == 1)
mDColsP[k]->GetSegment(bid)[off] = (r_8)data[mNames[mDColIdx[k]].item_in_row];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mDColsP[k]->GetSegment(bid)[off2+i] = (r_8)data[mNames[mDColIdx[k]].item_in_row+i];
}
}
for(size_t k=0; k<mYColsP.size(); k++) {
size_t nitems = mYColsP[k]->NbItems();
if (nitems == 1)
mYColsP[k]->GetSegment(bid)[off] = data[mNames[mYColIdx[k]].item_in_row].Convert(z4);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mYColsP[k]->GetSegment(bid)[off2+i] = data[mNames[mYColIdx[k]].item_in_row+i].Convert(z4);
}
}
for(size_t k=0; k<mZColsP.size(); k++) {
size_t nitems = mZColsP[k]->NbItems();
if (nitems == 1)
mZColsP[k]->GetSegment(bid)[off] = data[mNames[mZColIdx[k]].item_in_row].Convert(z8);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mZColsP[k]->GetSegment(bid)[off2+i] = data[mNames[mZColIdx[k]].item_in_row+i].Convert(z8);
}
}
for(size_t k=0; k<mSColsP.size(); k++) {
size_t nitems = mSColsP[k]->NbItems();
if (nitems == 1)
mSColsP[k]->GetSegment(bid)[off] = data[mNames[mSColIdx[k]].item_in_row].Convert(str);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mSColsP[k]->GetSegment(bid)[off2+i] = data[mNames[mSColIdx[k]].item_in_row+i].Convert(str);
}
}
for(size_t k=0; k<mTColsP.size(); k++) {
size_t nitems = mTColsP[k]->NbItems();
if (nitems == 1)
mTColsP[k]->GetSegment(bid)[off] = data[mNames[mTColIdx[k]].item_in_row].Convert(tms);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mTColsP[k]->GetSegment(bid)[off2+i] = data[mNames[mTColIdx[k]].item_in_row+i].Convert(tms);
}
}
for(size_t k=0; k<mCColsP.size(); k++) {
size_t nitems = mCColsP[k]->NbItems();
if (nitems == 1)
mCColsP[k]->GetSegment(bid)[off] = (char)data[mNames[mCColIdx[k]].item_in_row];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mCColsP[k]->GetSegment(bid)[off2+i] = (char)data[mNames[mCColIdx[k]].item_in_row+i];
}
}
for(size_t k=0; k<mS16ColsP.size(); k++) {
size_t nitems = mS16ColsP[k]->NbItems();
if (nitems == 1)
mS16ColsP[k]->GetSegment(bid)[off] = data[mNames[mS16ColIdx[k]].item_in_row].Convert(str);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mS16ColsP[k]->GetSegment(bid)[off2+i] = data[mNames[mS16ColIdx[k]].item_in_row+i].Convert(str);
}
}
for(size_t k=0; k<mS64ColsP.size(); k++) {
size_t nitems = mS64ColsP[k]->NbItems();
if (nitems == 1)
mS64ColsP[k]->GetSegment(bid)[off] = data[mNames[mS64ColIdx[k]].item_in_row].Convert(str);
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mS64ColsP[k]->GetSegment(bid)[off2+i] = data[mNames[mS64ColIdx[k]].item_in_row+i].Convert(str);
}
}
for(size_t k=0; k<mB16ColsP.size(); k++) {
size_t nitems = mB16ColsP[k]->NbItems();
if (nitems == 1)
mB16ColsP[k]->GetSegment(bid)[off].decodeInteger(data[mNames[mB16ColIdx[k]].item_in_row].Convert(i8dum));
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mB16ColsP[k]->GetSegment(bid)[off2+i].decodeInteger(data[mNames[mB16ColIdx[k]].item_in_row+i].Convert(i8dum));
}
}
for(size_t k=0; k<mB64ColsP.size(); k++) {
size_t nitems = mB64ColsP[k]->NbItems();
if (nitems == 1)
mB64ColsP[k]->GetSegment(bid)[off].decodeInteger(data[mNames[mB64ColIdx[k]].item_in_row].Convert(i8dum));
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mB64ColsP[k]->GetSegment(bid)[off2+i].decodeInteger(data[mNames[mB64ColIdx[k]].item_in_row+i].Convert(i8dum));
}
}
}
mNEnt++;
return mNEnt;
}
//! Adds a row (or line) to the table with input data as DataTableRow object
/*!
The internal MuTyV array of the object contains the data and the
MuTyV class conversion operators are used to match against each
cell data type.
Only the size of the input data object is checked.
Return the new number of table rows (lines / entries)
\param data : Data for each cell of the row to be appended
(data[k] k=0..NbColumns())
*/
size_t BaseDataTable::AddRow(DataTableRow const& data)
{
if ( (data.NCols() != NCols()) || (data.Size() != NItems_in_Row()) )
throw SzMismatchError(" BaseDataTable::AddRow(DataTableRow& data) - data.NCols() != NCols() OR data.Size() != NItems_in_Row() ");
return AddRow(data.MTVPtr());
}
//--------------- Methodes de remplissage des colonnes ------------------
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector<int_4> const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector<int_4> v) out of range column index k");
if (mNames[k].type!=IntegerField)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector<int_4> v) NOT IntegerField type column");
size_t sk = mNames[k].ser;
mIColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector<int_8> const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector<int_8> v) out of range column index k");
if (mNames[k].type!=LongField)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector<int_8> v) NOT LongField type column");
size_t sk = mNames[k].ser;
mLColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector<r_4> const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector<r_4> v) out of range column index k");
if (mNames[k].type!=FloatField)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector<r_4> v) NOT FloatField type column");
size_t sk = mNames[k].ser;
mFColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector<r_8> const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector<r_8> v) out of range column index k");
if (mNames[k].type!=DoubleField)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector<r_8> v) NOT DoubleField type column");
size_t sk = mNames[k].ser;
mDColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector< complex<r_4> > const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector< complex<r_4> > v) out of range column index k");
if (mNames[k].type!=ComplexField)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector< complex<r_4> > v) NOT ComplexField type column");
size_t sk = mNames[k].ser;
mYColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector< complex<r_8> > const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector< complex<r_8> > v) out of range column index k");
if (mNames[k].type!=DoubleComplexField)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector< complex<r_8> > v) NOT DoubleComplexField type column");
size_t sk = mNames[k].ser;
mZColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector< string > const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector< string > v) out of range column index k");
if (mNames[k].type!=StringField)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector< string > v) NOT StringField type column");
size_t sk = mNames[k].ser;
mSColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector< TimeStamp > const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector< TimeStamp > v) out of range column index k");
if (mNames[k].type!=DateTimeField)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector< TimeStamp > v) NOT DateTimeField type column");
size_t sk = mNames[k].ser;
mTColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector<char> const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector<char> v) out of range column index k");
if (mNames[k].type!=CharacterField)
throw RangeCheckError("BaseDataTable::FillColumn(k, vector<char> v) NOT CharacterField type column");
size_t sk = mNames[k].ser;
mCColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector< String16 > const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector< String16 > v) out of range column index k");
if (mNames[k].type!=FMLStr16Field)
throw RangeCheckError("BaseDataTable::FillColumn(k, vector< String16 > v) NOT FMLStr16Field type column");
size_t sk = mNames[k].ser;
mS16ColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector< String64 > const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector< String16 > v) out of range column index k");
if (mNames[k].type!=FMLStr64Field)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector< String16 > v) NOT FMLStr64Field type column");
size_t sk = mNames[k].ser;
mS64ColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector< FlagVector16 > const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector< FlagVector16 > v) out of range column index k");
if (mNames[k].type!=FlagVec16Field)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector< FlagVector16 > v) NOT FlagVec16Field type column");
size_t sk = mNames[k].ser;
mB16ColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
void BaseDataTable::FillColumn(size_t k, vector< FlagVector64 > const & v)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::FillColumn(k, vector< FlagVector16 > v) out of range column index k");
if (mNames[k].type!=FlagVec64Field)
throw TypeMismatchExc("BaseDataTable::FillColumn(k, vector< FlagVector64 > v) NOT FlagVec16Field type column");
size_t sk = mNames[k].ser;
mB64ColsP[sk]->CopyFrom(v);
return;
}
/* --Methode-- */
/*!
\param k : the column index (starting from zero) in the target table (*this)
\param src : the source table from which the data is copied
\param ks : the column index in the source \b src table
\warning the number of data items copied is equal to the minimum of the number of data items in the
source and target tables
\warning a TypeMismatchExc exception is generated if the two columns do not have the same data type or
not same vector size
*/
void BaseDataTable::FillColumn(size_t k, BaseDataTable const& src, size_t ks)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if ((k >= NVar())||(ks >= src.NVar()))
throw RangeCheckError("BaseDataTable::FillColumn(k, BaseDataTable, ks) out of range column index k or ks");
if ((mNames[k].type!=src.mNames[ks].type)||(mNames[k].vecsz!=src.mNames[ks].vecsz))
throw RangeCheckError("BaseDataTable::FillColumn(k, BaseDataTable, ks) different data type or vector size for the two columns");
size_t sk = mNames[k].ser;
size_t sks = src.mNames[ks].ser;
Units ru;
switch (mNames[k].type) {
case IntegerField :
mIColsP[sk]->CopyFrom(*(src.mIColsP[sks]));
break;
case LongField :
mLColsP[sk]->CopyFrom(*(src.mLColsP[sks]));
break;
case FloatField :
mFColsP[sk]->CopyFrom(*(src.mFColsP[sks]));
break;
case DoubleField :
mDColsP[sk]->CopyFrom(*(src.mDColsP[sks]));
break;
case ComplexField :
mYColsP[sk]->CopyFrom(*(src.mYColsP[sks]));
break;
case DoubleComplexField :
mZColsP[sk]->CopyFrom(*(src.mZColsP[sks]));
break;
case StringField :
mSColsP[sk]->CopyFrom(*(src.mSColsP[sks]));
break;
case DateTimeField :
mTColsP[sk]->CopyFrom(*(src.mTColsP[sks]));
break;
case CharacterField :
mCColsP[sk]->CopyFrom(*(src.mCColsP[sks]));
break;
case FMLStr16Field :
mS16ColsP[sk]->CopyFrom(*(src.mS16ColsP[sks]));
break;
case FMLStr64Field :
mS64ColsP[sk]->CopyFrom(*(src.mS64ColsP[sks]));
break;
case FlagVec16Field :
mB16ColsP[sk]->CopyFrom(*(src.mB16ColsP[sks]));
break;
case FlagVec64Field :
mB64ColsP[sk]->CopyFrom(*(src.mB64ColsP[sks]));
break;
default:
break;
}
return;
}
/*!
Fills the input \b row object with the content of row \b n.
Return a reference to the input \b row object.
Generate an exception if the input \b row object has the wrong size.
*/
DataTableRow& BaseDataTable::GetRow(size_t n, DataTableRow& row) const
{
if ( (row.NCols() != NCols()) || (row.Size() != NItems_in_Row()) )
throw SzMismatchError(" BaseDataTable::GetRow(n, DataTableRow& data) - row.NCols() != NCols() OR row.Size() != NItems_in_Row() ");
GetRow(n, row.MTVPtr());
return row;
}
/*!
For thread-safe operation, specify a valid \b mtvp pointer (!= NULL)
*/
MuTyV* BaseDataTable::GetRow(size_t n, MuTyV* mtvp) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (n >= NEntry())
throw RangeCheckError("BaseDataTable::GetRow() out of range line index n");
if (mtvp == NULL) {
if (mVarMTV == NULL) mVarMTV = new MuTyV[NItems_in_Row()];
mtvp = mVarMTV;
}
size_t bid = n/mSegSz;
size_t off = n%mSegSz;
size_t off2 = off;
if (!mFgVecCol) { // Aucune colonne de type vecteur
for(size_t k=0; k<mIColsP.size(); k++)
mtvp[mIColIdx[k]] = mIColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mLColsP.size(); k++)
mtvp[mLColIdx[k]] = mLColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mFColsP.size(); k++)
mtvp[mFColIdx[k]] = mFColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mDColsP.size(); k++)
mtvp[mDColIdx[k]] = mDColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mYColsP.size(); k++)
mtvp[mYColIdx[k]] = mYColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mZColsP.size(); k++)
mtvp[mZColIdx[k]] = mZColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mSColsP.size(); k++)
mtvp[mSColIdx[k]] = mSColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mTColsP.size(); k++)
mtvp[mTColIdx[k]] = mTColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mCColsP.size(); k++)
mtvp[mCColIdx[k]] = mCColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mS16ColsP.size(); k++)
mtvp[mS16ColIdx[k]] = mS16ColsP[k]->GetCstSegment(bid)[off].cbuff_ptr();
for(size_t k=0; k<mS64ColsP.size(); k++)
mtvp[mS64ColIdx[k]] = mS64ColsP[k]->GetCstSegment(bid)[off].cbuff_ptr();
for(size_t k=0; k<mB16ColsP.size(); k++)
mtvp[mB16ColIdx[k]] = mB16ColsP[k]->GetCstSegment(bid)[off].convertToInteger();
for(size_t k=0; k<mB64ColsP.size(); k++)
mtvp[mB64ColIdx[k]] = mB64ColsP[k]->GetCstSegment(bid)[off].convertToInteger();
}
else { // Il y a des colonnes avec contenu vecteur (plusieurs elements)
for(size_t k=0; k<mIColsP.size(); k++) {
size_t nitems = mIColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mIColIdx[k]].item_in_row] = mIColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mIColIdx[k]].item_in_row+i] = mIColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mLColsP.size(); k++) {
size_t nitems = mLColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mLColIdx[k]].item_in_row] = mLColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mLColIdx[k]].item_in_row+i] = mLColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mFColsP.size(); k++) {
size_t nitems = mFColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mFColIdx[k]].item_in_row] = mFColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mFColIdx[k]].item_in_row+i] = mFColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mDColsP.size(); k++) {
size_t nitems = mDColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mDColIdx[k]].item_in_row] = mDColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mDColIdx[k]].item_in_row+i] = mDColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mYColsP.size(); k++) {
size_t nitems = mYColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mYColIdx[k]].item_in_row] = mYColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mYColIdx[k]].item_in_row+i] = mYColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mZColsP.size(); k++) {
size_t nitems = mZColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mZColIdx[k]].item_in_row] = mZColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mZColIdx[k]].item_in_row+i] = mZColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mSColsP.size(); k++) {
size_t nitems = mSColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mSColIdx[k]].item_in_row] = mSColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mSColIdx[k]].item_in_row+i] = mSColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mTColsP.size(); k++) {
size_t nitems = mTColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mTColIdx[k]].item_in_row] = mTColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mTColIdx[k]].item_in_row+i] = mTColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mCColsP.size(); k++) {
size_t nitems = mCColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mCColIdx[k]].item_in_row] = mCColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mCColIdx[k]].item_in_row+i] = mCColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mS16ColsP.size(); k++) {
size_t nitems = mS16ColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mS16ColIdx[k]].item_in_row] = mS16ColsP[k]->GetCstSegment(bid)[off].cbuff_ptr();
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mS16ColIdx[k]].item_in_row+i] = mS16ColsP[k]->GetCstSegment(bid)[off2+i].cbuff_ptr();
}
}
for(size_t k=0; k<mS64ColsP.size(); k++) {
size_t nitems = mS64ColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mS64ColIdx[k]].item_in_row] = mS64ColsP[k]->GetCstSegment(bid)[off].cbuff_ptr();
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mS64ColIdx[k]].item_in_row+i] = mS64ColsP[k]->GetCstSegment(bid)[off2+i].cbuff_ptr();
}
}
for(size_t k=0; k<mB16ColsP.size(); k++) {
size_t nitems = mB16ColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mB16ColIdx[k]].item_in_row] = mB16ColsP[k]->GetCstSegment(bid)[off].convertToInteger();
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mB16ColIdx[k]].item_in_row+i] = mB16ColsP[k]->GetCstSegment(bid)[off2+i].convertToInteger();
}
}
for(size_t k=0; k<mB64ColsP.size(); k++) {
size_t nitems = mB64ColsP[k]->NbItems();
if (nitems == 1)
mtvp[mNames[mB64ColIdx[k]].item_in_row] = mB64ColsP[k]->GetCstSegment(bid)[off].convertToInteger();
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mtvp[mNames[mB64ColIdx[k]].item_in_row+i] = mB64ColsP[k]->GetCstSegment(bid)[off2+i].convertToInteger();
}
}
}
return mtvp;
}
/*!
This method should be used for write access to the data table rows. Use the GetCstRowPtr() method for reading.
No check on the DataTableRowPtr \b rowp object is performed, which should be created by
a call to the EmptyRowPtr() method. return the DataTableRowPtr provided as the argument.
\warning This method is NOT thread-safe
*/
DataTableRowPtr& BaseDataTable::GetRowPtr(size_t n, DataTableRowPtr& rowp)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (n >= NEntry())
throw RangeCheckError("BaseDataTable::GetRowPtr() out of range line index n");
size_t bid = n/mSegSz;
size_t off0 = n%mSegSz;
for(size_t k=0; k<mNames.size(); k++) {
size_t sk = mNames[k].ser;
size_t off = off0*mNames[k].vecsz;
switch (mNames[k].type) {
case IntegerField :
rowp[k].i4 = mIColsP[sk]->GetSegment(bid)+off;
break;
case LongField :
rowp[k].i8 = mLColsP[sk]->GetSegment(bid)+off;
break;
case FloatField :
rowp[k].f4 = mFColsP[sk]->GetSegment(bid)+off;
break;
case DoubleField :
rowp[k].f8 = mDColsP[sk]->GetSegment(bid)+off;
break;
case ComplexField :
rowp[k].z4 = mYColsP[sk]->GetSegment(bid)+off;
break;
case DoubleComplexField :
rowp[k].z8 = mZColsP[sk]->GetSegment(bid)+off;
break;
case StringField :
rowp[k].s = mSColsP[sk]->GetSegment(bid)+off;
break;
case DateTimeField :
rowp[k].tms = mTColsP[sk]->GetSegment(bid)+off;
break;
case CharacterField :
rowp[k].cp = mCColsP[sk]->GetSegment(bid)+off;
break;
case FMLStr16Field :
rowp[k].s16 = mS16ColsP[sk]->GetSegment(bid)+off;
break;
case FMLStr64Field :
rowp[k].s64 = mS64ColsP[sk]->GetSegment(bid)+off;
break;
case FlagVec16Field :
rowp[k].b16 = mB16ColsP[sk]->GetSegment(bid)+off;
break;
case FlagVec64Field :
rowp[k].b64 = mB64ColsP[sk]->GetSegment(bid)+off;
break;
default:
rowp[k].p = NULL;
break;
}
}
return rowp ;
}
/*!
This method should be used for read access to the data table rows. Use the GetRowPtr() method for read/write access.
No check on the DataTableRowPtr \b rowp object is performed, which should be created by
a call to the EmptyRowPtr() method. return the DataTableRowPtr provided as the argument.
\warning This method is NOT thread-safe
*/
DataTableRowPtr& BaseDataTable::GetCstRowPtr(size_t n, DataTableRowPtr& rowp) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (n >= NEntry())
throw RangeCheckError("BaseDataTable::GetCstRowPtr() out of range line index n");
size_t bid = n/mSegSz;
size_t off0 = n%mSegSz;
for(size_t k=0; k<mNames.size(); k++) {
size_t sk = mNames[k].ser;
size_t off = off0*mNames[k].vecsz;
switch (mNames[k].type) {
case IntegerField :
rowp[k].i4 = const_cast<int_4 *>(mIColsP[sk]->GetCstSegment(bid)+off);
break;
case LongField :
rowp[k].i8 = const_cast<int_8 *>(mLColsP[sk]->GetCstSegment(bid)+off);
break;
case FloatField :
rowp[k].f4 = const_cast<r_4 *>(mFColsP[sk]->GetCstSegment(bid)+off);
break;
case DoubleField :
rowp[k].f8 = const_cast<r_8 *>(mDColsP[sk]->GetCstSegment(bid)+off);
break;
case ComplexField :
rowp[k].z4 = const_cast< complex<r_4> *>(mYColsP[sk]->GetCstSegment(bid)+off);
break;
case DoubleComplexField :
rowp[k].z8 = const_cast< complex<r_8> *>(mZColsP[sk]->GetCstSegment(bid)+off);
break;
case StringField :
rowp[k].s = const_cast<std::string *>(mSColsP[sk]->GetCstSegment(bid)+off);
break;
case DateTimeField :
rowp[k].tms = const_cast<TimeStamp *>(mTColsP[sk]->GetCstSegment(bid)+off);
break;
case CharacterField :
rowp[k].cp = const_cast<char *>(mCColsP[sk]->GetCstSegment(bid)+off);
break;
case FMLStr16Field :
rowp[k].s16 = const_cast<String16 *>(mS16ColsP[sk]->GetCstSegment(bid)+off);
break;
case FMLStr64Field :
rowp[k].s64 = const_cast<String64 *>(mS64ColsP[sk]->GetCstSegment(bid)+off);
break;
case FlagVec16Field :
rowp[k].b16 = const_cast<FlagVector16 *>(mB16ColsP[sk]->GetCstSegment(bid)+off);
break;
case FlagVec64Field :
rowp[k].b64 = const_cast<FlagVector64 *>(mB64ColsP[sk]->GetCstSegment(bid)+off);
break;
default:
rowp[k].p = NULL;
break;
}
}
return rowp ;
}
/*!
Adds a row to the table set the data pointers of the DataTableRowPtr \b rowp to the data cells of
row \b n of the table.
No check on the DataTableRowPtr \b rowp object is performed, which should be created by
a call to the EmptyRowPtr() method. return the DataTableRowPtr provided as the argument.
*/
DataTableRowPtr& BaseDataTable::NextRowPtr(DataTableRowPtr& rowp)
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (mNEnt == mSegSz*mNSeg) Extend();
size_t n = mNEnt; mNEnt++;
return GetRowPtr(n, rowp);
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector<int_4> & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector<int_4> v) out of range column index k");
if (mNames[k].type!=IntegerField)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector<int_4> v) NOT IntegerField type column");
size_t sk = mNames[k].ser;
mIColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector<int_8> & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector<int_8> v) out of range column index k");
if (mNames[k].type!=LongField)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector<int_8> v) NOT LongField type column");
size_t sk = mNames[k].ser;
mLColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector<r_4> & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector<r_4> v) out of range column index k");
if (mNames[k].type!=FloatField)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector<r_4> v) NOT FloatField type column");
size_t sk = mNames[k].ser;
mFColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector<r_8> & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector<r_8> v) out of range column index k");
if (mNames[k].type!=DoubleField)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector<r_8> v) NOT DoubleField type column");
size_t sk = mNames[k].ser;
mDColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector< complex<r_4> > & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< complex<r_4> > v) out of range column index k");
if (mNames[k].type!=ComplexField)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< complex<r_4> > v) NOT ComplexField type column");
size_t sk = mNames[k].ser;
mYColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector< complex<r_8> > & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< complex<r_8> > v) out of range column index k");
if (mNames[k].type!=DoubleComplexField)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< complex<r_8> > v) NOT DoubleComplexField type column");
size_t sk = mNames[k].ser;
mZColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector< string > & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< string > v) out of range column index k");
if (mNames[k].type!=StringField)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< string > v) NOT StringField type column");
size_t sk = mNames[k].ser;
mSColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector< TimeStamp > & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< TimeStamp > v) out of range column index k");
if (mNames[k].type!=DateTimeField)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< TimeStamp > v) NOT DateTimeField type column");
size_t sk = mNames[k].ser;
mTColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector<char> & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector<char> v) out of range column index k");
if (mNames[k].type!=CharacterField)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector<char> v) NOT CharacterField type column");
size_t sk = mNames[k].ser;
mCColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector< String16 > & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< String16 > v) out of range column index k");
if (mNames[k].type!=FMLStr16Field)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< String16 > v) NOT FMLStr16Field type column");
size_t sk = mNames[k].ser;
mS16ColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector< String64 > & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< String16 > v) out of range column index k");
if (mNames[k].type!=FMLStr64Field)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< String16 > v) NOT FMLStr64Field type column");
size_t sk = mNames[k].ser;
mS64ColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector< FlagVector16 > & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< FlagVector16 > v) out of range column index k");
if (mNames[k].type!=FlagVec16Field)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< FlagVector16 > v) NOT FlagVec16Field type column");
size_t sk = mNames[k].ser;
mB16ColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
/* --Methode-- */
/*!
For columns with vector content of size vsz, the vector \b v would be resized to NRows()*vsz, otherwise to NRows()
*/
void BaseDataTable::GetColumn(size_t k, vector< FlagVector64 > & v) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< FlagVector64 > v) out of range column index k");
if (mNames[k].type!=FlagVec64Field)
throw RangeCheckError("BaseDataTable::GetColumn(k, vector< FlagVector64 > v) NOT FlagVec64Field type column");
size_t sk = mNames[k].ser;
mB64ColsP[sk]->CopyTo(v);
v.resize(NRows()*mNames[k].vecsz);
return;
}
#define BADVAL -1.e39
TVector<r_8> BaseDataTable::GetColumnD(size_t k) const
{
DT_TSOP_SYNC dttss(mThS); dttss.NOp(); // Thread-safe operation
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetColumnD() out of range column index k");
if (mNames[k].vecsz > 1)
throw ParmError("BaseDataTable::GetColumnD() operation not supported for column with vector content (vsz>1)");
size_t sk = mNames[k].ser;
size_t nelts = NEntry()*mNames[k].vecsz;
size_t i = 0;
TVector<r_8> rv(NEntry());
for (size_t is=0; is<NbSegments(); is++) {
switch (mNames[k].type) {
case IntegerField :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv(i) = mIColsP[sk]->GetCstSegment(is)[j];
break;
case LongField :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv(i) = mLColsP[sk]->GetCstSegment(is)[j];
break;
case FloatField :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv(i) = mFColsP[sk]->GetCstSegment(is)[j];
break;
case DoubleField :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv(i) = mDColsP[sk]->GetCstSegment(is)[j];
break;
case ComplexField :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv(i) = mYColsP[sk]->GetCstSegment(is)[j].real();
break;
case DoubleComplexField :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv(i) = mZColsP[sk]->GetCstSegment(is)[j].real();
break;
case StringField :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv = atof(mSColsP[sk]->GetCstSegment(is)[j].c_str());
break;
case DateTimeField :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv(i) = mTColsP[sk]->GetCstSegment(is)[j].ToDays();
break;
case CharacterField :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv(i) = (double)(mCColsP[sk]->GetCstSegment(is)[j]);
break;
case FMLStr16Field :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv = atof(mS16ColsP[sk]->GetCstSegment(is)[j].cbuff_ptr());
break;
case FMLStr64Field :
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv = atof(mS64ColsP[sk]->GetCstSegment(is)[j].cbuff_ptr());
break;
//---- FlagVec16Field et FlagVec64Field ne peuvent etre convertis en double
default:
for(size_t j=0; (j<SegmentSize())&&(i<nelts); j++,i++)
rv(i) = BADVAL;
break;
}
}
return rv ;
}
/*!
\param src : the source table from which structure and/or data is copied to the target table (*this)
\param ckcp : if true, generates an exception if the target table has already entries
\param pbm : ProgressBarMode (displays or not a progress bar)
if the table is empty, the structure and content of the table \b src are copied to it.
Otherwise, an exception is generated if the two tables have incompatible structures.
Data from table \b src is appended to the target table (*this).
\warning: this method is NOT thread-safe
*/
void BaseDataTable::RowMerge(BaseDataTable const& src, bool ckcp, ProgressBarMode pbm)
{
if (ckcp && (NEntry() > 0) )
throw ParmError("BaseDataTable::RowMerge(src) Target Table (*this) has already entries ");
if (src.NVar() == 0) throw ParmError("BaseDataTable::RowMerge(a) Source Table a has no column");
if (NVar() == 0) CopyStructure(src);
else if (!CompareStructure(src))
throw ParmError("BaseDataTable::RowMerge(src) (this,a) have different table structure");
if (src.NEntry() == 0) {
cout << " BaseDataTable::RowMerge(a)/Warning : table a has zero (0) entry ! " << endl;
return;
}
DataTableRowPtr rdest = EmptyRowPtr();
DataTableRowPtr rsrc = src.EmptyRowPtr();
if (pbm!=ProgBarM_None)
cout << "BaseDataTable::RowMerge() copying "<<src.NEntry()<<" rows ... "<<endl;
ProgressBar prgbar(src.NEntry(), pbm);
for(size_t kk=0; kk<src.NEntry(); kk++) {
NextRowPtr(rdest);
src.GetCstRowPtr(kk,rsrc);
rdest.CopyContentFrom(rsrc);
prgbar.update(kk);
}
return;
}
/*!
If the table has no columns, the table structure is copied from \b src, otherwise
the two tables should have the same structure (column types and order)
The selection of rows identified by the row numbers in the \b rows vector is
copied from table \b src. If the first table (the one on which SelectFrom() is called)
has entries (NRows()>0), the data from the \b src table is appended to the first table.
\warning: this method is NOT thread-safe
*/
void BaseDataTable::CopySelectedRows(BaseDataTable const& src, std::vector<size_t> const & rows, ProgressBarMode pbm)
{
if ((src.NVar() == 0)||(src.NRows() == 0)) {
cout << "BaseDataTable::CopySelectedRows(src,rows)/Warning: src table not initialized or empty" << endl;
return;
}
if (NCols() > 0) {
if (!CompareStructure(src))
throw ParmError("BaseDataTable::CopySelectedRows(src,rows) (this,src) have different table structure");
}
else CopyStructure(src);
DataTableRowPtr rdest = EmptyRowPtr();
DataTableRowPtr rsrc = src.EmptyRowPtr();
if (pbm!=ProgBarM_None)
cout << "BaseDataTable::CopySelectedRows(src,rows) "<<rows.size()<<" rows from a total of "<<src.NRows()<<endl;
ProgressBar prgbar(rows.size(), pbm);
for(size_t k=0; k<rows.size(); k++) {
if (rows[k]>=src.NRows()) continue;
NextRowPtr(rdest);
src.GetCstRowPtr(rows[k],rsrc);
rdest.CopyContentFrom(rsrc);
prgbar.update(k);
}
return;
}
/*!
If the table has no columns, the table structure (columns) is initialized with the
list of columns of the \b src table identified by the column indexes \b cols[i], otherwise the
compatibility of the table structure with the selected columns of table \b src
is checked. An exception is generated if the two structures are different.
The selection of rows identified by the row indexes in the \b rows vector
from table \b src is then copied or appended to the target table (*this).
\warning: this method is NOT thread-safe
*/
void BaseDataTable::CopySelectedRowColumns(BaseDataTable const& src, std::vector<size_t> const & rows, std::vector<size_t> const & cols, ProgressBarMode pbm)
{
if ((src.NVar() == 0)||(src.NRows() == 0)) {
cout << "BaseDataTable::CopySelectedRowColumns(src,rows,cols)/Warning: src table not initialized or empty" << endl;
return;
}
if (NCols()>0) {
bool fgds=false;
if (NCols()!=cols.size()) fgds=true;
for (size_t ii=0; ii<cols.size(); ii++)
if ( (mNames[ii].type != src.mNames[cols[ii]].type) ||
(mNames[ii].vecsz != src.mNames[cols[ii]].vecsz) ) { fgds=true; break; }
if (fgds)
throw ParmError("BaseDataTable::CopySelectedRowColumns(src,rows,cols) incompatible table structure with selected columns");
}
else {
for (size_t ii=0; ii<cols.size(); ii++) {
size_t i = cols[ii];
if (i>=src.NVar()) continue;
AddColumn(src.mNames[i].type, src.mNames[i].nom, src.mNames[i].vecsz);
bool sdone=false;
Units un=src.GetUnits(i,sdone);
if (sdone) SetUnits(ii,un);
}
}
DataTableRowPtr rdest = EmptyRowPtr();
DataTableRowPtr rsrc = src.EmptyRowPtr();
vector< pair<size_t, size_t> > cid;
size_t jd=0;
for (size_t i=0; i<cols.size(); i++) {
if (cols[i]>=src.NVar()) continue;
cid.push_back( pair<size_t, size_t> (cols[i],jd) );
jd++;
}
if (pbm!=ProgBarM_None)
cout << "BaseDataTable::CopySelectedRowColumns(src,rows,cols) "<<rows.size()<<" rows from a total of "<<src.NRows()<<endl;
ProgressBar prgbar(rows.size(), pbm);
for(size_t k=0; k<rows.size(); k++) {
//DBG cout << " *DBG*Select()- k=" << k << " rows[k]= " << rows[k] << endl;
if (rows[k]>=src.NRows()) continue;
NextRowPtr(rdest);
src.GetCstRowPtr(rows[k],rsrc);
rdest.CopyContentFrom(rsrc,cid);
prgbar.update(k);
}
return;
}
/* --Methode-- */
//! \sa BaseDataTable::ColumnMerge(BaseDataTable const& src, std::vector<size_t> const & cols, const char* prefix)
void BaseDataTable::ColumnMerge(BaseDataTable const& src, const char* prefix)
{
if (src.NVar() == 0) {
cout << "BaseDataTable::ColumnMerge(src)/Warning: src table not initialized" << endl;
return;
}
std::vector<size_t> cols(src.NVar());
for(size_t i=0; i<cols.size(); i++) cols[i]=i;
return ColumnMerge(src, cols, prefix);
}
/*!
\param src : Table from which column structure and data is copied to the target object (*this)
\param cols : list of column indices in table \b src to be appended (merged) to the target table (*this)
\param prefix : prefix string, prepended to the \b src column names for columns added to the target table
\warning: this method is NOT thread-safe
*/
void BaseDataTable::ColumnMerge(BaseDataTable const& src, std::vector<size_t> const & cols, const char* prefix)
{
if (src.NVar() == 0) {
cout << "BaseDataTable::ColumnMerge(src)/Warning: src table not initialized" << endl;
return;
}
for (size_t ii=0; ii<cols.size(); ii++) {
size_t i = cols[ii];
if (i>=src.NVar()) {
cout << "BaseDataTable::ColumnMerge(src, cols...)/Warning: column index cols["<<ii<<"]="<<i
<<" out of range (>src.NVar())"<<endl;
continue;
}
string cname = prefix+src.mNames[i].nom;
//DBG cout << " BaseDataTable::ColumnMerge()/DBG - Calling AddColumn(..,name="<<cname<<" , ...)"<<endl;
AddColumn(src.mNames[i].type, cname, src.mNames[i].vecsz, true);
bool sdone=false;
Units un=src.GetUnits(i,sdone);
size_t i0=NVar()-1;
if (sdone) SetUnits(i0,un);
//DBG cout << " BaseDataTable::ColumnMerge()/DBG-2 - Calling FillColumn("<<i0<<"...,"<<i<<")"<<endl;
FillColumn(i0, src, i);
}
return;
}
/* --Methode-- */
//! \sa BaseDataTable::ColumnMerge(BaseDataTable const& src, std::vector<size_t> const & cols, const char* prefix)
void BaseDataTable::ColumnMerge(BaseDataTable const& src, std::vector<std::string> const & colsnm, const char* prefix)
{
if (src.NVar() == 0) {
cout << "BaseDataTable::ColumnMerge(src, vector<string> colsnm)/Warning: src table not initialized" << endl;
return;
}
std::vector<size_t> cols;
for(size_t i=0; i<colsnm.size(); i++) {
int idx = ColumnIndexNIU(colsnm[i]);
if (idx < 0) {
cout << "BaseDataTable::ColumnMerge(src, colsnm...)/Warning: unknown column name colsnm["<<i<<"]="
<<colsnm[i]<<endl;
continue;
}
cols.push_back((size_t)idx);
}
return ColumnMerge(src, cols, prefix);
}
/*!
Merge columns from the \b src table, adding data from selected columns to the target table (*this)
\param src : Table from which column structure and data is copied to the target object (*this)
\param rows : selection of the rows (row indexes) in the \b src table
\param cols : selection of the columns (column indexes) in the \b src added to the target table (*this)
\param prefix : prefix string, prepended to the \b src column names for columns added to the target table
\param defval : default values for missing data (number of selected rows in \b src < this->NRows())
\param defstr : default string value for missing data
\param pbm : ProgressBarMode flag
\warning: this method is NOT thread-safe
*/
void BaseDataTable::ColumnMerge(BaseDataTable const& src, std::vector<size_t> const & rows, std::vector<size_t> const & cols,
const char* prefix, int_8 defval, const char* defstr, ProgressBarMode pbm)
{
if ((src.NVar() == 0)||(src.NRows() == 0)) {
cout << "BaseDataTable::ColumnMerge(src,rows,cols)/Warning: src table not initialized or empty" << endl;
return;
}
size_t nvar0=NVar();
for (size_t ii=0; ii<cols.size(); ii++) {
size_t i = cols[ii];
if (i>=src.NVar()) continue;
string cname = prefix+src.mNames[i].nom;
AddColumn(src.mNames[i].type, cname, src.mNames[i].vecsz, true);
bool sdone=false;
Units un=src.GetUnits(i,sdone);
if (sdone) SetUnits(ii+nvar0,un);
}
DataTableRowPtr rdest = EmptyRowPtr();
DataTableRowPtr rsrc = src.EmptyRowPtr();
vector< pair<size_t, size_t> > cid;
size_t jd=nvar0;
for (size_t i=0; i<cols.size(); i++) {
if (cols[i]>=src.NVar()) continue;
cid.push_back( pair<size_t, size_t> (cols[i],jd) );
jd++;
}
if (pbm!=ProgBarM_None)
cout << "BaseDataTable::ColumnMerge(src,rows,cols) "<<rows.size()<<" rows from a total of "<<src.NRows()<<endl;
ProgressBar prgbar(rows.size(), pbm);
string defs = defstr;
complex<r_8> defz(0.,0.);
TimeStamp defts;
for(size_t k=0; k<rows.size(); k++) {
GetRowPtr(k,rdest);
if (rows[k]<src.NRows()) {
src.GetCstRowPtr(rows[k],rsrc);
rdest.CopyContentFrom(rsrc,cid);
}
else {
for(size_t j=nvar0; j<NVar(); j++) {
for(size_t l=0; l<GetColumnVecSize(j); l++) {
rdest(j,l)=defts; rdest(j,l)=defz;
rdest(j,l)=defs; rdest(j,l)=defval;
}
}
}
prgbar.update(k);
}
return;
}
//! Returns the associated DVList object
DVList& BaseDataTable::Info() const
{
if (mInfo == NULL) mInfo = new DVList;
return(*mInfo);
}
/*!
Formatted (text) output of the table, for lines lstart <= l_index < lend , with step lstep
\param os : output stream (formatted output)
\param lstart : start row (line) index
\param lend : end row (line) index
\param lstep : row index increment
\param qstr : if true, cells with string content will be enclosed in quotes \t 'string_content'
\param sep : character string used to separate fields (cells/column) on each line
\param clm : character string used to mark comment lines (beginning of the line)
*/
ostream& BaseDataTable::Print(ostream& os, size_t lstart, size_t lend, size_t lstep, bool qstr, const char* sep, const char* clm) const
{
os << clm << "#### BaseDataTable::Print() - Table(NRow=" << NEntry() << " , NCol="
<< NVar() << ") ##### " << endl;
os << clm << "! " ;
for (size_t i=0; i<NVar(); i++) {
string nom = mNames[i].nom;
nom += ':'; nom += ColTypeToString(mNames[i].type);
os << setw(12) << nom << " ";
}
os << endl;
os << clm << "##########################################################################" << endl;
if (lend>NRows()) lend=NRows();
if (lstep<1) lstep=1;
for (size_t l=lstart; l<lend; l+=lstep)
os << TableRowToString(l, qstr, sep) << endl;
return os;
}
/*! In addition to printing the number of entries and column names,
this method prints also minimum/maximum value for each column.
This information might be computed when the Show() method is called.
This may take some time for tables with large number of entries (>~ 10^6)
*/
void BaseDataTable::Show(ostream& os) const
{
os << "BaseDataTable: NVar= " << NVar() << " NEnt= " << NEntry()
<< " ( SegSize= " << SegmentSize() << " NbSegments= "
<< NbSegments() << " )" << endl;
if (!mShowMinMaxFg) os << " Warning - min/max values not get/computed ! " << endl;
os << "------------------------------------------------------------------------------" << endl;
os << setw(3) << "i" << ":" << setw(15) << " Name" << " [Sz] (Typ) | "
<< setw(12) << " Min " << " | " << setw(12) << " Max " << " | "
<< setw(12) << " Units" << endl;
os << "------------------------------------------------------------------------------" << endl;
string smin, smax;
smin=smax="-";
for(size_t i = 0 ; i < NVar() ; i++) {
string const& nom=mNames[i].nom;
string vnom="";
char tampon_vsz[32];
bool fglongname=false;
if (nom.length() > 15) fglongname=true;
if (mNames[i].vecsz>1) sprintf(tampon_vsz,"[%2d]",(int)mNames[i].vecsz);
else strcpy(tampon_vsz," ");
string sunits;
bool sdone;
Units un = GetUnits(i, sdone);
if (sdone) sunits=un.ShortName();
if ( (mShowMinMaxFg)&&(mNames[i].type!=StringField)&&(mNames[i].type!=FMLStr16Field)&&(mNames[i].type!=FMLStr64Field)&&
(mNames[i].type!=FlagVec16Field)&&(mNames[i].type!=FlagVec64Field) ) {
MuTyV mtvmin(0.), mtvmax(0.);
if (mNames[i].type==CharacterField) {
char min, max;
GetMinMax(i, min, max) ;
mtvmin=min; mtvmax=max;
//DBG cout<<"\n **DBG**CharacterField min="<<min<<" max="<<max<<" ->int:"<<(int)min<<","<<(int)max<<endl;
}
else if ((mNames[i].type==IntegerField)||(mNames[i].type==LongField)) {
int_8 min, max ;
GetMinMax(i, min, max) ;
mtvmin=min; mtvmax=max;
//DBG cout<<"\n **DBG**Int/LongField min="<<min<<" max="<<max<<endl;
}
else {
r_8 min, max ;
GetMinMax(i, min, max) ;
mtvmin=min; mtvmax=max;
//DBG cout<<"\n **DBG**OtherField min="<<min<<" max="<<max<<endl;
}
mtvmin.Convert(smin); mtvmax.Convert(smax);
}
else {
smin=smax="-";
}
os << setw(3) << i << ": " << setw(15) << (fglongname?nom.substr(0,15):nom) << tampon_vsz
<< " (" << setw(3) << ColTypeToString(mNames[i].type) << ") | "
<< setw(12) << smin << " | " << setw(12) << smax << " | " << setw(14) << sunits
<< (fglongname?nom:vnom) << endl;
}
os << "------------------------------------------------------------------------------" << endl;
return;
}
//! Fills table from an ascii (text) file
/*
Return number of non empty lines (rows added to table)
\param is : input ascii (text) stream
\param sepc : character(s) separator that delimit the different fields (cells/columns) in each line of the file
if no separator specified (sepc=NULL, default) the tab and space characters are used as separators. Up to three
different character separator can be specified.
\param com : comment line marker. Lines starting with one of the comment characters (up to three) are
considered as comment lines and skipped. if no com specified (com=NULL, default) # is the marker of
comment lines.
\warning Provide a null terminated string if you specify \t sepc and/or \t comc
*/
size_t BaseDataTable::FillFromASCIIStream(istream& is, double defval, const char* sepc, const char* com)
{
// defining default separator
const char * sep=" \t";
if ((sepc!=NULL)&&(sepc[0]!='\0')) sep=sepc;
// the comment line marker
char clm[4]={'\0','\0','\0','\0'}; // comment characters
if ((com==NULL)||(com[0]=='\0')) clm[0]='#';
else {
clm[0]=com[0];
if (com[1]!='\0') {
clm[1]=com[1];
if (com[2]!='\0') clm[2]=com[2];
}
}
string str;
if (mVarMTV == NULL) mVarMTV = new MuTyV[NVar()];
size_t iv, nl;
nl = 0;
while (!is.eof()) {
str = "";
getline(is, str);
if (is.good() || is.eof()) {
size_t l = str.length();
if ((l==0)||(str[0]==clm[0])||(str[1]==clm[1])||(str[2]==clm[2])) continue;
for(iv=0; iv<NVar(); iv++) mVarMTV[iv] = defval;
iv = 0;
size_t q = 0;
size_t p = 0;
while ( (q < l) && (iv < NVar()) ) {
p = str.find_first_not_of(sep,q);
if (p >= l) break;
if (str[p] == '\'') { // Decodage d'un string
q = str.find('\'',p+1);
if (q < l) {
mVarMTV[iv] = str.substr(p+1,q-p-1);
q++;
}
else mVarMTV[iv] = str.substr(p+1,l-p-1);
iv++;
}
else {
q = str.find_first_of(sep,p);
if (q > l) q = l;
mVarMTV[iv] = str.substr(p,q-p);
iv++;
}
if (mNames[iv-1].type == DateTimeField) {
string tts = (string)mVarMTV[iv-1];
mVarMTV[iv-1] = TimeStamp(tts);
}
}
AddRow(mVarMTV);
nl++;
}
} // Fin boucle lignes fichier
cout << "BaseDataTable::FillFromASCIIFile()/Info: " << nl << " lines decoded from stream " << endl;
return(nl);
}
/*!
- fgforce == true, force recomputing the values,
- fgforce == false, does not recompute if number of entry has not changed since last call to ComputeMinMaxSum()
*/
void BaseDataTable::ComputeMinMaxSum(size_t k, bool fgforce) const
{
if (k >= NVar())
throw RangeCheckError("BaseDataTable::ComputeMinMaxSum() out of range column index k");
r_8 min=9.e39;
r_8 max=-9.e39;
r_8 sum=0., sumsq=0.;
char minc='\0', maxc='\0';
int_4 mini=0, maxi=0;
int_8 minl=0, maxl=0;
if (mMinMaxNEnt.size() < NVar()) {
mMin.clear();
mMax.clear();
mSum.clear();
mSumSq.clear();
mMinMaxNEnt.clear();
for(size_t kk=0; kk<NVar(); kk++) {
mMin.push_back(9.e39);
mMax.push_back(-9.e39);
mSum.push_back(0.);
mSumSq.push_back(0.);
mMinMaxNEnt.push_back(0);
}
}
if (mMinC.size() < mCColsP.size()) {
mMinC.clear(); mMaxC.clear();
for(size_t kk=0; kk<mCColsP.size(); kk++) {
mMinC.push_back('\0'); mMaxC.push_back('\0');
}
}
if (mMinI.size() < mIColsP.size()) {
mMinI.clear(); mMaxI.clear();
for(size_t kk=0; kk<mIColsP.size(); kk++) {
mMinI.push_back(0); mMaxI.push_back(0);
}
}
if (mMinL.size() < mLColsP.size()) {
mMinL.clear(); mMaxL.clear();
for(size_t kk=0; kk<mLColsP.size(); kk++) {
mMinL.push_back(0); mMaxL.push_back(0);
}
}
if (NRows() < 1) return;
if ((mMinMaxNEnt[k] == NRows()) && !fgforce) return;
// We recompute values
size_t sk = mNames[k].ser;
size_t nitem = mNames[k].vecsz*NEntry();
size_t cnt = 0;
switch (mNames[k].type) {
case IntegerField :
mini=maxi=0;
for(size_t is=0; is<mIColsP[sk]->NbSegments(); is++) {
const int_4* sp = mIColsP[sk]->GetCstSegment(is);
for(size_t n=0; n<mIColsP[sk]->SegmentSize(); n++) {
int_4 ci=sp[n];
if (cnt==0) { mini=maxi=ci; }
if (cnt >= nitem) break;
if (ci > maxi) maxi = ci;
if (ci < mini) mini = ci;
sum += (double)ci; sumsq += (double)ci*(double)ci;
cnt++;
}
}
min = (double)mini; max=(double)maxi;
mMinI[sk]=mini; mMaxI[sk]=maxi;
break;
case LongField :
minl=maxl=0L;
for(size_t is=0; is<mLColsP[sk]->NbSegments(); is++) {
const int_8* sp = mLColsP[sk]->GetCstSegment(is);
for(size_t n=0; n<mLColsP[sk]->SegmentSize(); n++) {
int_8 cl=sp[n];
if (cnt==0) { minl=maxl=cl; }
if (cnt >= nitem) break;
if (cl > maxl) maxl = cl;
if (cl < minl) minl = cl;
sum += (double)cl; sumsq += (double)cl*(double)cl;
cnt++;
}
}
min = (double)mini; max=(double)maxi;
mMinL[sk]=minl; mMaxL[sk]=maxl;
break;
case FloatField :
for(size_t is=0; is<mFColsP[sk]->NbSegments(); is++) {
const r_4* sp = mFColsP[sk]->GetCstSegment(is);
for(size_t n=0; n<mFColsP[sk]->SegmentSize(); n++) {
if (cnt >= nitem) break;
if (sp[n] > max) max = sp[n];
if (sp[n] < min) min = sp[n];
sum += sp[n]; sumsq += sp[n]*sp[n];
cnt++;
}
}
break;
case DoubleField :
for(size_t is=0; is<mDColsP[sk]->NbSegments(); is++) {
const r_8* sp = mDColsP[sk]->GetCstSegment(is);
for(size_t n=0; n<mDColsP[sk]->SegmentSize(); n++) {
if (cnt >= nitem) break;
if (sp[n] > max) max = sp[n];
if (sp[n] < min) min = sp[n];
sum += sp[n]; sumsq += sp[n]*sp[n];
cnt++;
}
}
break;
case ComplexField :
for(size_t is=0; is<mYColsP[sk]->NbSegments(); is++) {
const complex<r_4> * sp = mYColsP[sk]->GetCstSegment(is);
for(size_t n=0; n<mYColsP[sk]->SegmentSize(); n++) {
if (cnt >= nitem) break;
double xr=sp[n].real();
if (xr > max) max = xr;
if (xr < min) min = xr;
sum += xr; sumsq += xr*xr;
cnt++;
}
}
break;
case DoubleComplexField :
for(size_t is=0; is<mZColsP[sk]->NbSegments(); is++) {
const complex<r_8> * sp = mZColsP[sk]->GetCstSegment(is);
for(size_t n=0; n<mZColsP[sk]->SegmentSize(); n++) {
if (cnt >= nitem) break;
double xr=sp[n].real();
if (xr > max) max = xr;
if (xr < min) min = xr;
sum += xr; sumsq += xr*xr;
cnt++;
}
}
break;
case DateTimeField :
for(size_t is=0; is<mTColsP[sk]->NbSegments(); is++) {
const TimeStamp* sp = mTColsP[sk]->GetCstSegment(is);
for(size_t n=0; n<mTColsP[sk]->SegmentSize(); n++) {
double days = sp[n].ToDays();
if (cnt >= nitem) break;
if (days > max) max = days;
if (days < min) min = days;
sum += sp[n]; sumsq += sp[n]*sp[n];
cnt++;
}
}
break;
case CharacterField :
minc=maxc='\0';
for(size_t is=0; is<mCColsP[sk]->NbSegments(); is++) {
const char * cp = mCColsP[sk]->GetCstSegment(is);
for(size_t n=0; n<mCColsP[sk]->SegmentSize(); n++) {
char cc = cp[n];
if (cnt==0) { minc=maxc=cc; }
if (cnt >= nitem) break;
if (cc > maxc) maxc = cc;
if (cc < minc) minc = cc;
sum += (double)cc; sumsq += (double)cc*(double)cc;
cnt++;
}
}
min = (double)minc; max=(double)maxc;
mMinC[sk]=minc; mMaxC[sk]=maxc;
break;
case StringField :
case FMLStr16Field :
case FMLStr64Field :
case FlagVec16Field :
case FlagVec64Field :
return;
break;
default:
return;
break;
}
mMinMaxNEnt[k] = NEntry();
mMin[k] = min;
mMax[k] = max;
mSum[k] = sum;
mSumSq[k] = sumsq;
return ;
}
/*!
- fgforce == true, force recomputing the values,
- fgforce == false, does not recompute if number of entry has not changed since last call to ComputeMinMaxSum()
*/
void BaseDataTable::ComputeMinMaxSumAll(bool fgforce) const
{
for(size_t k=0; k<NVar(); k++) ComputeMinMaxSum(k, fgforce);
return;
}
void BaseDataTable::GetMinMax(size_t k, int_8& min, int_8& max) const
{
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetMinMax(k, int_8&, int_8&) out of range column index k");
if ((mNames[k].type!=IntegerField) && (mNames[k].type!=LongField) && (mNames[k].type!=CharacterField) )
throw RangeCheckError("BaseDataTable::GetMinMaxC(k, int_8&, int_8&) NOT Integer/Long/Character Field type column");
min=max=0L;
ComputeMinMaxSum(k, false);
size_t sk = mNames[k].ser;
if (mNames[k].type==IntegerField) {
min = (int_8)mMinI[sk]; max = (int_8)mMaxI[sk];
}
else if (mNames[k].type==LongField) {
min = mMinL[sk]; max = mMaxL[sk];
}
else if (mNames[k].type==CharacterField) {
min = (int_8)mMinC[sk]; max = (int_8)mMaxC[sk];
}
return;
}
void BaseDataTable::GetMinMax(size_t k, char& minc, char& maxc) const
{
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetMinMax(k, char&, char&) out of range column index k");
if (mNames[k].type!=CharacterField)
throw RangeCheckError("BaseDataTable::GetMinMaxC(k, char&, char&) NOT CharacterField type column");
minc=maxc='\0';
ComputeMinMaxSum(k, false);
size_t sk = mNames[k].ser;
minc = mMinC[sk]; maxc = mMaxC[sk];
return;
}
/*!
\param n : table row index ( 0 ... NEntry()-1)
\param qstr : if true , enclose strings in quotes ''
\param sep : separates fields using \b sep
\param fw : minimum field width
*/
string BaseDataTable::TableRowToString(size_t n, bool qstr,
const char* sep, int fw) const
{
if (n >= NEntry())
throw RangeCheckError("BaseDataTable::TableRowToString() out of range line index n");
string rs;
MuTyV rv;;
size_t bid = n/mSegSz;
for(size_t k=0; k<NVar(); k++) {
size_t off = n%mSegSz;
if (mNames[k].vecsz>1) off = off*mNames[k].vecsz;
size_t sk = mNames[k].ser;
switch (mNames[k].type) {
case IntegerField :
rv = mIColsP[sk]->GetCstSegment(bid)[off];
break;
case LongField :
rv = mLColsP[sk]->GetCstSegment(bid)[off];
break;
case FloatField :
rv = mFColsP[sk]->GetCstSegment(bid)[off];
break;
case DoubleField :
rv = mDColsP[sk]->GetCstSegment(bid)[off];
break;
case ComplexField :
rv = mYColsP[sk]->GetCstSegment(bid)[off];
break;
case DoubleComplexField :
rv = mZColsP[sk]->GetCstSegment(bid)[off];
break;
case StringField :
rv = mSColsP[sk]->GetCstSegment(bid)[off];
break;
case DateTimeField :
rv = TimeStamp(mTColsP[sk]->GetCstSegment(bid)[off]);
break;
case CharacterField :
rv = mCColsP[sk]->GetCstSegment(bid)[off];
break;
case FMLStr16Field :
rv = mS16ColsP[sk]->GetCstSegment(bid)[off].cbuff_ptr();
break;
case FMLStr64Field :
rv = mS64ColsP[sk]->GetCstSegment(bid)[off].cbuff_ptr();
break;
case FlagVec16Field :
rv = mB16ColsP[sk]->GetCstSegment(bid)[off].convertToString();
break;
case FlagVec64Field :
rv = mB64ColsP[sk]->GetCstSegment(bid)[off].convertToString();
break;
default:
rv = " ";
break;
}
string s;
if ( (mNames[k].type == StringField) && (qstr) ) {
s = '\''; s += (string)rv; s += '\'';
}
else s= (string)rv;
size_t l = s.length();
for(size_t ii=l; ii<fw; ii++) s += ' ';
if (k > 0) rs += sep;
rs += s;
}
return rs;
}
//
// ------------------------------------
// ------- Interface NTuple -----------
// ------------------------------------
//
size_t BaseDataTable::NbLines() const
{
return(NEntry());
}
size_t BaseDataTable::NbColumns() const
{
return(NVar());
}
r_8* BaseDataTable::GetLineD(size_t n) const
{
if (n >= NEntry())
throw RangeCheckError("BaseDataTable::GetLineD() out of range line index n");
if (mVarD == NULL) mVarD = new r_8[NItems_in_Row()];
for(size_t i=0; i<NItems_in_Row(); i++) mVarD[i]=BADVAL;
size_t bid = n/mSegSz;
size_t off = n%mSegSz;
size_t off2 = off;
if (!mFgVecCol) { // Aucune colonne de type vecteur
for(size_t k=0; k<mIColsP.size(); k++)
mVarD[mIColIdx[k]] = mIColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mLColsP.size(); k++) {
//DBG cout << " *DBG*BaseDataTable::GetLineD() k=" << k << " bid= " << bid << " off= " << off << endl;
mVarD[mLColIdx[k]] = mLColsP[k]->GetCstSegment(bid)[off];
}
for(size_t k=0; k<mFColsP.size(); k++)
mVarD[mFColIdx[k]] = mFColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mDColsP.size(); k++)
mVarD[mDColIdx[k]] = mDColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mYColsP.size(); k++)
mVarD[mYColIdx[k]] = mYColsP[k]->GetCstSegment(bid)[off].real();
for(size_t k=0; k<mZColsP.size(); k++)
mVarD[mZColIdx[k]] = mZColsP[k]->GetCstSegment(bid)[off].real();
for(size_t k=0; k<mSColsP.size(); k++)
mVarD[mSColIdx[k]] = atof(mSColsP[k]->GetCstSegment(bid)[off].c_str());
for(size_t k=0; k<mTColsP.size(); k++)
mVarD[mTColIdx[k]] = mTColsP[k]->GetCstSegment(bid)[off].ToDays();
for(size_t k=0; k<mCColsP.size(); k++)
mVarD[mCColIdx[k]] = (double)mCColsP[k]->GetCstSegment(bid)[off];
for(size_t k=0; k<mS16ColsP.size(); k++)
mVarD[mS16ColIdx[k]] = atof(mS16ColsP[k]->GetCstSegment(bid)[off].cbuff_ptr());
for(size_t k=0; k<mS64ColsP.size(); k++)
mVarD[mS64ColIdx[k]] = atof(mS64ColsP[k]->GetCstSegment(bid)[off].cbuff_ptr());
}
else { // il y a des colonnes avec contenu vecteur
for(size_t k=0; k<mIColsP.size(); k++) {
size_t nitems = mIColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mIColIdx[k]].item_in_row] = mIColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mIColIdx[k]].item_in_row+i] = mIColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mLColsP.size(); k++) {
size_t nitems = mLColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mLColIdx[k]].item_in_row] = mLColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mLColIdx[k]].item_in_row+i] = mLColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mFColsP.size(); k++) {
size_t nitems = mFColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mFColIdx[k]].item_in_row] = mFColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mFColIdx[k]].item_in_row+i] = mFColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mDColsP.size(); k++) {
size_t nitems = mDColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mDColIdx[k]].item_in_row] = mDColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mDColIdx[k]].item_in_row+i] = mDColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mYColsP.size(); k++) {
size_t nitems = mYColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mYColIdx[k]].item_in_row] = mYColsP[k]->GetCstSegment(bid)[off].real();
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mYColIdx[k]].item_in_row+i] = mYColsP[k]->GetCstSegment(bid)[off2+i].real();
}
}
for(size_t k=0; k<mZColsP.size(); k++) {
size_t nitems = mZColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mZColIdx[k]].item_in_row] = mZColsP[k]->GetCstSegment(bid)[off].real();
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mZColIdx[k]].item_in_row+i] = mZColsP[k]->GetCstSegment(bid)[off2+i].real();
}
}
for(size_t k=0; k<mSColsP.size(); k++) {
size_t nitems = mSColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mSColIdx[k]].item_in_row] = atof(mSColsP[k]->GetCstSegment(bid)[off].c_str());
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mSColIdx[k]].item_in_row+i] = atof(mSColsP[k]->GetCstSegment(bid)[off2+i].c_str());
}
}
for(size_t k=0; k<mTColsP.size(); k++) {
size_t nitems = mTColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mTColIdx[k]].item_in_row] = mTColsP[k]->GetCstSegment(bid)[off].ToDays();
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mTColIdx[k]].item_in_row+i] = mTColsP[k]->GetCstSegment(bid)[off2+i].ToDays();
}
}
for(size_t k=0; k<mCColsP.size(); k++) {
size_t nitems = mCColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mCColIdx[k]].item_in_row] = (double)mCColsP[k]->GetCstSegment(bid)[off];
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mCColIdx[k]].item_in_row+i] = (double)mCColsP[k]->GetCstSegment(bid)[off2+i];
}
}
for(size_t k=0; k<mS16ColsP.size(); k++) {
size_t nitems = mS16ColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mS16ColIdx[k]].item_in_row] = atof(mS16ColsP[k]->GetCstSegment(bid)[off].c_str());
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mS16ColIdx[k]].item_in_row+i] = atof(mS16ColsP[k]->GetCstSegment(bid)[off2+i].c_str());
}
}
for(size_t k=0; k<mS64ColsP.size(); k++) {
size_t nitems = mS64ColsP[k]->NbItems();
if (nitems == 1)
mVarD[mNames[mS64ColIdx[k]].item_in_row] = atof(mS64ColsP[k]->GetCstSegment(bid)[off].c_str());
else {
off2 = off*nitems;
for(size_t i=0; i<nitems; i++)
mVarD[mNames[mS64ColIdx[k]].item_in_row+i] = atof(mS64ColsP[k]->GetCstSegment(bid)[off2+i].c_str());
}
}
}
return mVarD;
}
r_8 BaseDataTable::GetCell(size_t n, size_t k) const
{
if (n >= NEntry())
throw RangeCheckError("BaseDataTable::GetCell() out of range line index n");
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetCell() out of range column index k");
double rv = BADVAL;
size_t sk = mNames[k].ser;
size_t bid = n/mSegSz;
size_t off = n%mSegSz;
if (mNames[k].vecsz>1) off = off*mNames[k].vecsz;
switch (mNames[k].type) {
case IntegerField :
rv = mIColsP[sk]->GetCstSegment(bid)[off];
break;
case LongField :
rv = mLColsP[sk]->GetCstSegment(bid)[off];
break;
case FloatField :
rv = mFColsP[sk]->GetCstSegment(bid)[off];
break;
case DoubleField :
rv = mDColsP[sk]->GetCstSegment(bid)[off];
break;
case ComplexField :
rv = mYColsP[sk]->GetCstSegment(bid)[off].real();
break;
case DoubleComplexField :
rv = mZColsP[sk]->GetCstSegment(bid)[off].real();
break;
case StringField :
rv = atof(mSColsP[sk]->GetCstSegment(bid)[off].c_str());
break;
case DateTimeField :
rv = mTColsP[sk]->GetCstSegment(bid)[off].ToDays();
break;
case CharacterField :
rv = (double)mCColsP[sk]->GetCstSegment(bid)[off];
break;
case FMLStr16Field :
rv = atof(mS16ColsP[sk]->GetCstSegment(bid)[off].cbuff_ptr());
break;
case FMLStr64Field :
rv = atof(mS64ColsP[sk]->GetCstSegment(bid)[off].cbuff_ptr());
break;
default:
rv = BADVAL;
break;
}
return rv ;
}
string BaseDataTable::GetCelltoString(size_t n, size_t k) const
{
if (n >= NEntry())
throw RangeCheckError("BaseDataTable::GetCell() out of range line index n");
if (k >= NVar())
throw RangeCheckError("BaseDataTable::GetCell() out of range column index k");
MuTyV rv;;
size_t sk = mNames[k].ser;
size_t bid = n/mSegSz;
size_t off = n%mSegSz;
if (mNames[k].vecsz>1) off = off*mNames[k].vecsz;
switch (mNames[k].type) {
case IntegerField :
rv = mIColsP[sk]->GetCstSegment(bid)[off];
break;
case LongField :
rv = mLColsP[sk]->GetCstSegment(bid)[off];
break;
case FloatField :
rv = mFColsP[sk]->GetCstSegment(bid)[off];
break;
case DoubleField :
rv = mDColsP[sk]->GetCstSegment(bid)[off];
break;
case ComplexField :
rv = mYColsP[sk]->GetCstSegment(bid)[off];
break;
case DoubleComplexField :
rv = mZColsP[sk]->GetCstSegment(bid)[off];
break;
case StringField :
rv = mSColsP[sk]->GetCstSegment(bid)[off];
break;
case DateTimeField :
rv = TimeStamp(mTColsP[sk]->GetCstSegment(bid)[off]);
break;
case CharacterField :
rv = mCColsP[sk]->GetCstSegment(bid)[off];
break;
case FMLStr16Field :
rv = mS16ColsP[sk]->GetCstSegment(bid)[off].c_str();
break;
case FMLStr64Field :
rv = mS64ColsP[sk]->GetCstSegment(bid)[off].c_str();
break;
case FlagVec16Field :
rv = mB16ColsP[sk]->GetCstSegment(bid)[off].convertToString();
break;
case FlagVec64Field :
rv = mB64ColsP[sk]->GetCstSegment(bid)[off].convertToString();
break;
default:
rv = " ";
break;
}
return (string)rv ;
}
void BaseDataTable::GetMinMax(size_t k, double& min, double& max) const
{
min = 9E39 ; max = -9E39 ;
ComputeMinMaxSum(k, false);
min = mMin[k];
max = mMax[k];
return;
}
void BaseDataTable::GetSum(size_t k, double& sum, double& sumsq) const
{
sum=sumsq=0.;
ComputeMinMaxSum(k, false);
sum = mSum[k];
sumsq = mSumSq[k];
return;
}
size_t BaseDataTable::ColumnIndex(string const& nom) const
{
return IndexNom(nom) ;
}
int BaseDataTable::ColumnIndexNIU(string const & nom) const
{
for(size_t k=0; k<NVar(); k++)
if ( mNames[k].nom == nom ) return (int)k;
// Reza:Avril 2005 : PINtuple se base sur le renvoi de -1 et pas d'une exception
return -1;
}
string BaseDataTable::ColumnName(size_t k) const
{
return NomIndex(k) ;
}
string BaseDataTable::VarList_C(const char* nomx) const
{
string rets="";
size_t i;
for(i=0; i<NVar(); i++) {
if ( (i%5 == 0) && (i > 0) ) rets += ";";
if (i%5 == 0) rets += "\ndouble ";
else rets += ",";
rets += mNames[i].nom;
}
rets += "; \n";
if (nomx) {
char buff[256];
for(i=0; i<NVar(); i++) {
rets += mNames[i].nom;
rets += '=';
sprintf(buff,"%s[%ld]; ", nomx, (long)i);
rets += buff;
if ( (i%3 == 0) && (i > 0) ) rets += "\n";
}
}
return(rets);
}
string BaseDataTable::LineHeaderToString() const
{
string rets,s;
for(int i=0; i<NVar(); i++) {
s = mNames[i].nom;
size_t l = s.length();
for(size_t ii=l; ii<12; ii++) s += ' ';
if (i > 0) rets += ' ';
rets += s;
}
return(rets);
}
/* --Methode-- */
/*!
redefined the base class NTupleInterface method to return true, as this class implements
the methods returning table content and definition as string ( LineHeaderToString() LineToString() ... )
*/
bool BaseDataTable::ImplementsContentStringRepresentation() const
{
return true;
}
/*!
Return a table row (line) as a string
\sa TableRowToString()
*/
string BaseDataTable::LineToString(size_t n) const
{
return TableRowToString(n, false);
}
bool BaseDataTable::ImplementsExtendedInterface() const
{
return true;
}
//! Return a pointer to an array of NTupMTPointer structure, initialized with pointers to cell contents of row \b n of the table
NTupMTPointer * BaseDataTable::GetLineMTP(size_t n) const
{
if (n >= NEntry())
throw RangeCheckError("BaseDataTable::GetLineMTP() out of range line index n");
if (mVarMTP==NULL) { // si les tableaux necessaires n'ont pas ete alloue
mVarMTP = new NTupMTPointer[NVar()];
size_t nsp=0; size_t ntm=0;
for(size_t i=0; i<NVar(); i++) {
FieldType ft=mNames[i].type;
if (ft==DateTimeField) ntm += mNames[i].vecsz;
if ((ft==StringField)||(ft==FMLStr16Field)||(FMLStr64Field)) nsp += mNames[i].vecsz;
}
if (ntm > 0) mVarTMS = new r_8[ntm];
if (nsp > 0) mVarStrP = new const char *[nsp];
}
size_t bid = n/mSegSz;
size_t off0 = n%mSegSz;
size_t idxtms=0;
size_t idxstr=0;
for(size_t k=0; k<mNames.size(); k++) {
size_t sk = mNames[k].ser;
size_t off = off0*mNames[k].vecsz;
switch (mNames[k].type) {
case IntegerField :
mVarMTP[k].i4 = (mIColsP[sk]->GetCstSegment(bid)+off);
break;
case LongField :
mVarMTP[k].i8 = (mLColsP[sk]->GetCstSegment(bid)+off);
break;
case FloatField :
mVarMTP[k].f4 = (mFColsP[sk]->GetCstSegment(bid)+off);
break;
case DoubleField :
mVarMTP[k].f8 = (mDColsP[sk]->GetCstSegment(bid)+off);
break;
case ComplexField :
mVarMTP[k].z4 = (const z_cmplx_f4 *)(mYColsP[sk]->GetCstSegment(bid)+off);
break;
case DoubleComplexField :
mVarMTP[k].z8 = (const z_cmplx_f8 *)(mZColsP[sk]->GetCstSegment(bid)+off);
break;
case StringField :
for(size_t i=0; i<mNames[k].vecsz; i++)
mVarStrP[idxstr+i]=mSColsP[sk]->GetCstSegment(bid)[off+i].c_str();
mVarMTP[k].sp = mVarStrP+idxstr;
idxstr += mNames[k].vecsz;
break;
case DateTimeField :
for(size_t i=0; i<mNames[k].vecsz; i++)
mVarTMS[idxtms+i]=mTColsP[sk]->GetCstSegment(bid)[off+i].ToDays();
mVarMTP[k].f8 = mVarTMS+idxtms;
idxtms += mNames[k].vecsz;
break;
case CharacterField :
mVarMTP[k].s = (mCColsP[sk]->GetCstSegment(bid)+off);
break;
case FMLStr16Field :
for(size_t i=0; i<mNames[k].vecsz; i++)
mVarStrP[idxstr+i]=mS16ColsP[sk]->GetCstSegment(bid)[off+i].c_str();
mVarMTP[k].sp = mVarStrP+idxstr;
idxstr += mNames[k].vecsz;
break;
case FMLStr64Field :
for(size_t i=0; i<mNames[k].vecsz; i++)
mVarStrP[idxstr+i]=mS64ColsP[sk]->GetCstSegment(bid)[off+i].c_str();
mVarMTP[k].sp = mVarStrP+idxstr;
idxstr += mNames[k].vecsz;
break;
case FlagVec16Field :
mVarMTP[k].vp = (mB16ColsP[sk]->GetCstSegment(bid)+off)->bit_array();
break;
case FlagVec64Field :
mVarMTP[k].vp = (mB64ColsP[sk]->GetCstSegment(bid)+off)->bit_array();
break;
default:
mVarMTP[k].vp = NULL;
break;
}
}
return mVarMTP ;
}
/*!
\brief C language declaration of variables for accessing the data of a row of table
Return a string with C language style declaration of variables with column names and corresponding
data types, initialzed from an array of NTupMTPointer, as the one that is returned by GetLineMTP()
*/
string BaseDataTable::VarListMTP_C(const char* nomx) const
{
string rets="";
char tampon[256];
char s1[32], s2[16];
for(size_t k=0; k<NVar(); k++) { // boucle sur les colonnes
switch (mNames[k].type) {
case IntegerField :
strcpy(s1,"const int ");
strcpy(s2,"i4");
break;
case LongField :
strcpy(s1,"const long long ");
strcpy(s2,"i8");
break;
case FloatField :
strcpy(s1,"const float ");
strcpy(s2,"f4");
break;
case DoubleField :
strcpy(s1,"const double ");
strcpy(s2,"f8");
break;
case ComplexField :
strcpy(s1,"const struct z_cmplx_f4 ");
strcpy(s2,"z4");
break;
case DoubleComplexField :
strcpy(s1,"const struct z_cmplx_f8 ");
strcpy(s2,"z8");
break;
case StringField :
case FMLStr16Field :
case FMLStr64Field :
strcpy(s1,"const char * ");
strcpy(s2,"sp");
break;
case DateTimeField :
strcpy(s1,"const double ");
strcpy(s2,"f8");
break;
case CharacterField :
strcpy(s1,"const char ");
strcpy(s2,"s");
break;
case FlagVec16Field :
case FlagVec64Field :
strcpy(s1,"const char * ");
strcpy(s2,"vp");
default:
strcpy(s1,"???? ");
strcpy(s2,"?? ");
break;
}
if (mNames[k].vecsz<2) { // colonne simple - pas de type vecteur
rets += s1; rets += ' '; rets += mNames[k].nom;
if (nomx) sprintf(tampon," = %s[%d].%s[0] ; \n",nomx,(int)k,s2);
else strcpy(tampon," ; \n");
rets += tampon;
}
else { // colonne avec contenu vecteur
rets += s1; rets += "* "; rets += mNames[k].nom;
if (nomx) sprintf(tampon," = %s[%d].%s ; \n",nomx,(int)k,s2);
else strcpy(tampon," ; \n");
rets += tampon;
}
}
return(rets);
}
//
// -------------------------------------
// ------- Protected methods -----------
// -------------------------------------
//
void BaseDataTable::ClearP()
{
if ( (NVar() == 0) && (NEntry() == 0)) return;
mNEnt = 0;
mNSeg = 0;
if (mVarD) delete[] mVarD;
mVarD = NULL;
if (mVarMTV) delete[] mVarMTV;
mVarMTV = NULL;
if (mVarMTP) delete[] mVarMTP;
mVarMTP = NULL;
if (mVarTMS) delete[] mVarTMS;
mVarTMS = NULL;
if (mVarStrP) delete[] mVarStrP;
mVarStrP = NULL;
mNames.clear();
mFgVecCol = false;
if (mInfo) delete mInfo;
mInfo = NULL;
if (mThS) delete mThS;
mThS = NULL;
mMin.clear();
mMax.clear();
mMinC.clear();
mMaxC.clear();
mMinI.clear();
mMaxI.clear();
mMinL.clear();
mMaxL.clear();
mSum.clear();
mSumSq.clear();
mMinMaxNEnt.clear();
mIColsP.clear();
mLColsP.clear();
mFColsP.clear();
mDColsP.clear();
mYColsP.clear();
mZColsP.clear();
mSColsP.clear();
mTColsP.clear();
mCColsP.clear();
mS16ColsP.clear();
mS64ColsP.clear();
mB16ColsP.clear();
mB64ColsP.clear();
mIColIdx.clear();
mLColIdx.clear();
mFColIdx.clear();
mDColIdx.clear();
mYColIdx.clear();
mZColIdx.clear();
mSColIdx.clear();
mTColIdx.clear();
mCColIdx.clear();
mS16ColIdx.clear();
mS64ColIdx.clear();
mB16ColIdx.clear();
mB64ColIdx.clear();
}
size_t BaseDataTable::AddColumnBase(FieldType ft, string const & cnom, size_t vsz, size_t ser)
{
colst col;
col.nom = cnom;
col.type = ft;
col.vecsz = vsz;
col.ser = ser;
col.item_in_row = NItems_in_Row();
// cout << " *DBG* AddColumnBase(" << (int)ft << "," << cnom << " vsz=" << vsz << " item_in_row=" << col.item_in_row << endl;
mNames.push_back(col);
if (col.vecsz>1) mFgVecCol = true;
// Tableaux pour les min,max
mMin.push_back(9.E39);
mMax.push_back(-9.E39);
mSum.push_back(0.);
mSumSq.push_back(0.);
mMinMaxNEnt.push_back(0);
if (NRows() == 0) return NVar();
// If the table is not empty, the SegDataBlock of the newly created column should be resized
size_t k = NVar()-1;
size_t sk = mNames[k].ser;
switch (mNames[k].type) {
case IntegerField :
for(size_t j=0; j<NbSegments(); j++) mIColsP[sk]->Extend();
mMinI.push_back(0);
mMaxI.push_back(0);
break;
case LongField :
for(size_t j=0; j<NbSegments(); j++) mLColsP[sk]->Extend();
mMinL.push_back(0L);
mMaxL.push_back(0L);
break;
case FloatField :
for(size_t j=0; j<NbSegments(); j++) mFColsP[sk]->Extend();
break;
case DoubleField :
for(size_t j=0; j<NbSegments(); j++) mDColsP[sk]->Extend();
break;
case ComplexField :
for(size_t j=0; j<NbSegments(); j++) mYColsP[sk]->Extend();
break;
case DoubleComplexField :
for(size_t j=0; j<NbSegments(); j++) mZColsP[sk]->Extend();
break;
case StringField :
for(size_t j=0; j<NbSegments(); j++) mSColsP[sk]->Extend();
break;
case DateTimeField :
for(size_t j=0; j<NbSegments(); j++) mTColsP[sk]->Extend();
break;
case CharacterField :
for(size_t j=0; j<NbSegments(); j++) mCColsP[sk]->Extend();
mMinC.push_back('\0');
mMaxC.push_back('\0');
break;
case FMLStr16Field :
for(size_t j=0; j<NbSegments(); j++) mS16ColsP[sk]->Extend();
break;
case FMLStr64Field :
for(size_t j=0; j<NbSegments(); j++) mS64ColsP[sk]->Extend();
break;
case FlagVec16Field :
for(size_t j=0; j<NbSegments(); j++) mB16ColsP[sk]->Extend();
break;
case FlagVec64Field :
for(size_t j=0; j<NbSegments(); j++) mB64ColsP[sk]->Extend();
break;
}
return NVar();
}
} // FIN namespace SOPHYA
| [
"guy.barrand@gmail.com"
] | guy.barrand@gmail.com |
da807ece14a1a0bf4e850a9de3ad1575394d0e5b | 57610d90506f9b93d2097067bbe7658e7460c2e6 | /yoketoru-unity/Temp/StagingArea/Data/il2cppOutput/t1041293420.h | 73ed9af7ccb13851d3d049caacc1e8e19ca7dd02 | [] | no_license | GEhikachu/GEhikachu.github.io | 4c10b77020b9face4d27a50e1a9f4a1434f390c1 | b9d6627a3d1145325f2a7b9cf02712fe17c8f334 | refs/heads/master | 2020-07-01T08:16:40.998434 | 2016-12-09T01:22:35 | 2016-12-09T01:22:35 | 74,089,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 687 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "t285998070.h"
#include "t1041293420.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
struct t1041293420
{
public:
int32_t f1;
public:
inline static int32_t fog1() { return static_cast<int32_t>(offsetof(t1041293420, f1)); }
inline int32_t fg1() const { return f1; }
inline int32_t* fag1() { return &f1; }
inline void fs1(int32_t value)
{
f1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"hikapika911@gmail.com"
] | hikapika911@gmail.com |
a3e3752bd40c2f5cce1646dbd05096836aa43711 | f89cca7f64a66eda1233c5b4a865ff788c2d7a18 | /计算智能/提交作业/MyMaxSAT-代码/algorithm/baseSolver.hpp | 116776cc73b8e22174e2be0e88bbb2462ea53a44 | [] | no_license | lyandut/HUST-Invictus | 0981f41a9ebf375f940dbc486f738e8b300d7427 | fa8cc36c75c7f0b426d3d089ec7e695c07ba7dac | refs/heads/master | 2023-01-31T05:44:22.721866 | 2023-01-23T05:56:30 | 2023-01-23T05:56:30 | 232,467,266 | 544 | 149 | null | 2023-01-23T05:56:32 | 2020-01-08T03:14:24 | HTML | UTF-8 | C++ | false | false | 1,127 | hpp | //
// Created by liyan on 2019/10/25.
//
#ifndef MYMAXSAT_BASESOLVER_HPP
#define MYMAXSAT_BASESOLVER_HPP
#include <iostream>
#include <random>
#include <ctime>
#include "../data/formula.hpp"
class BaseSolver {
public:
Formula formula;
private:
std::default_random_engine e;
public:
BaseSolver(const Formula &_formula) : formula(_formula) { e.seed(time(nullptr)); }
BaseSolver() = default;
virtual void solve() = 0;
int getResult(bool weight_soft_only = true, bool print_flag = false) {
int total_weight = 0;
for (const auto &c : formula.getSatisfiedClauses()) {
if (weight_soft_only && c.weight != Cfg::SoftClauseWeight) { continue; }
total_weight += c.weight;
}
if (print_flag) {
std::cout << formula.toString() << std::endl;
for (const auto &v : formula.variables)
std::cout << "X" << v.first << ": " << v.second << std::endl;
std::cout << "Total value: " << total_weight << std::endl;
}
return total_weight;
}
protected:
bool getProbRandomNumber(double __p__ = 0.5) {
std::bernoulli_distribution u(__p__);
return u(e);
}
};
#endif //MYMAXSAT_RANDOMIZEDSOLVER_HPP
| [
"lyan_dut@outlook.com"
] | lyan_dut@outlook.com |
afcfc10e0dbeb5cc83590a5d64caefa82bba39ef | 30078bb84abba95328753dc6dde09bdae012e0ce | /Classes/adReource/AdCross/AdLoadingLayerBase.h | 01ecded908289d64a1fe7f81294434c5aa04134f | [] | no_license | 850176300/AmazeBrick | a5b1baf8f79633eed97dd811a3dbff7e3cadd550 | 3d643f87ebbc3432afc5cee37c81997cc2cc8d53 | refs/heads/master | 2021-01-01T05:36:30.513629 | 2015-07-02T03:55:27 | 2015-07-02T03:55:27 | 37,019,896 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,388 | h | //
// AdLoadingLayerBase.h
//
// Created by tanshoumei on 15/6/10.
//
//
#pragma once
#include <stdio.h>
#include <iostream>
#include "cocos2d.h"
#include "STAds.h"
using namespace cocos2d;
using namespace cocos2d::ui;
class AdLoadingLayerBase: public Layer, public STAdsDelegate
{
public:
//用于判断当前是否有AdLoadingLayer(其子类也算)的实例存在.不为空,则可重复使用。
//注意这不是单例,使用要进行空判断。
//使用场景: 比如正在AdLoading界面,用户点击了后面,再返回,此时回来界面上是有AdLoadingLayer的实例的,可重复使用,当然你也可以选择重新创建,Depends on U.
static AdLoadingLayerBase* s_currentInstance;
CREATE_FUNC(AdLoadingLayerBase);
virtual bool init();
void onExit();
void onEnter() override;
void loadAd(bool abIscross = false);
void setSwallowTouch(bool value);
#pragma mark --ad delegate--
virtual void onInterstitialAdFailed(int errorCode, int type);
virtual void onInterstitialShown(int type);
virtual void onInterstitialAdLoaded(int type);
virtual void onInterstitialDismissed(int type);
#pragma mark --ad delegate end--
protected:
/*
为什么不直接用schedule update(1. update比较常用,如果子类也用,容易产生混乱。2.此处对时效性要求不高,也不需要每帧检测)
**/
virtual void _timeCheckSchedule(float dt);
//广告按时加载出来
virtual void _adLoadInTime();
//广告超时还未加载出来
virtual void _adLoadTimeOut();
//本界面任务完成
virtual void _taskDone();
public:
//
std::function<void()> loadingDoneCallback = nullptr;
public:
//Loading界面最多停留的时间(秒)
CC_SYNTHESIZE(float, _loadingMaxTime, LoadingMaxTime);
CC_SYNTHESIZE(float, _loadingMinTime, LoadingMinTime);
protected:
EventListenerTouchOneByOne* _eventListenerTouch;
timeval _timeEnter;
STAds _ads;
//0第三方 1交叉
int _adLoadType = 0;
//广告是否在显示
bool _adShowing = false;
bool _isRequestingLoadAd = false;
bool _bLoadingCanRemove = false;
//广告加载完成与否(失败成功回调都算完成)
bool _adLoadDone = false;
}; | [
"liuwei@smalltreemedia.com"
] | liuwei@smalltreemedia.com |
ca009f45974ce73fb3c3a1f88b430b96cefa6613 | d1e48ccb62938502f0fbf3d28df400c0fb5b111e | /untitled/cbuilder.cpp | ce4278d2667b2ba470a5b41fb8317ffd06ec0566 | [] | no_license | bartekcios/Elevators | dd326f8de875e4e8d1553d31743b74ba3bbe099a | eb9dd4642ca84d68f35f232a8d1b81896e5887f9 | refs/heads/master | 2021-01-13T14:55:05.579387 | 2016-12-16T22:08:40 | 2016-12-16T22:08:40 | 76,688,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 70 | cpp | #include "cbuilder.h"
CBuilder::CBuilder(int a_iNoElevators, )
{
}
| [
"bartekcios@gmail.com"
] | bartekcios@gmail.com |
5fd1f71a229090c5459340585640498cfda578d7 | 5fb990aec96ab33a096ee03099c64bb5cb46b0ec | /20200508-문제.cpp | 369fe5de8912edb3ebaf6e36eeb6d251bfbdbf2e | [] | no_license | nick0908/C_language | 51aaab03617cf07987c2a4de50eb5f6a29e41d6e | 91d96c4a6490301ade254d3fb3db16cfa456213e | refs/heads/main | 2023-01-13T12:01:11.481472 | 2020-10-28T07:08:48 | 2020-10-28T07:08:48 | 303,909,970 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 223 | cpp | #include <stdio.h>
int main(void)
{
int i,count = 0;
for(i=0;i<=100;i++)
{
if(i%7 == 0)
{
printf("%d \n",i);
count++;
}
}
printf("총 개수는 %d개 입니다.",count);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
79c60be547854980375d00f197defa62b49420a9 | e23db5e995e8611f42833171f048c6381d66b6a6 | /FrameWork/src/multiplayercore/ServerReplicationManager.cpp | 34daa0180e7f41b0da72f5dda6e3bfa65f27f759 | [
"MIT"
] | permissive | alwayssmile11a1/MultiplayerGameServer | 34c618b73764606170733f05255e59cfe3570790 | cd4227ecc5fe1b44d427bcbd76c050a8130d2200 | refs/heads/master | 2020-04-06T23:42:40.516647 | 2020-01-10T14:47:42 | 2020-01-10T14:47:42 | 157,878,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,351 | cpp | #include "ServerReplicationManager.h"
void ServerReplicationManager::ReplicateCreate(NetworkGameObjectPtr gameObject, uint32_t inInitialDirtyState)
{
mNetworkGameObjectToReplicationCommand[gameObject] = ReplicationCommand(inInitialDirtyState);
}
void ServerReplicationManager::ReplicateDestroy(NetworkGameObjectPtr gameObject)
{
mNetworkGameObjectToReplicationCommand[gameObject].SetDestroy();
}
void ServerReplicationManager::AddDirtyState(NetworkGameObjectPtr gameObject, uint32_t inDirtyState)
{
mNetworkGameObjectToReplicationCommand[gameObject].AddDirtyState(inDirtyState);
}
void ServerReplicationManager::Write(OutputMemoryBitStream& inOutputStream)
{
//run through each replication command and do something...
for (auto& pair : mNetworkGameObjectToReplicationCommand)
{
ReplicationCommand& replicationCommand = pair.second;
if (replicationCommand.HasDirtyState() || replicationCommand.GetAction() == ReplicationAction::RA_Create)
{
int networkId = pair.first->GetNetworkId();
//well, first write the network id...
inOutputStream.Write(networkId);
//only need 2 bits for action...
ReplicationAction action = replicationCommand.GetAction();
inOutputStream.Write(action, 2);
uint32_t writtenState = 0;
uint32_t dirtyState = replicationCommand.GetDirtyState();
//write dirtyState
inOutputStream.Write(dirtyState);
//now do what?
switch (action)
{
case RA_Create:
writtenState = WriteCreateAction(inOutputStream, pair.first, dirtyState);
//once the create action is transmitted, future replication
//of this object should be updates instead of creates
replicationCommand.SetAction(RA_Update);
break;
case RA_Update:
writtenState = WriteUpdateAction(inOutputStream, pair.first, dirtyState);
break;
case RA_Destroy:
//don't need anything other than state!
writtenState = WriteDestroyAction(inOutputStream, pair.first, dirtyState);
//add this to the list of replication commands to remove
mNetworkGameObjectsToRemove.emplace_back(pair.first);
break;
}
//let's pretend everything was written- don't make this too hard
replicationCommand.ClearDirtyState(writtenState);
}
}
//remove replication commands for destroyed objects
if (!mNetworkGameObjectsToRemove.empty())
{
for (auto gameObject : mNetworkGameObjectsToRemove)
{
RemoveFromReplication(gameObject);
}
mNetworkGameObjectsToRemove.clear();
}
}
void ServerReplicationManager::RemoveFromReplication(NetworkGameObjectPtr gameObject)
{
mNetworkGameObjectToReplicationCommand.erase(gameObject);
}
uint32_t ServerReplicationManager::WriteCreateAction(OutputMemoryBitStream& inOutputStream, NetworkGameObjectPtr gameObject, uint32_t inDirtyState)
{
inOutputStream.Write(gameObject->GetClassId());
return gameObject->OnNetworkWrite(inOutputStream, inDirtyState);
}
uint32_t ServerReplicationManager::WriteUpdateAction(OutputMemoryBitStream& inOutputStream, NetworkGameObjectPtr gameObject, uint32_t inDirtyState)
{
uint32_t writtenState = gameObject->OnNetworkWrite(inOutputStream, inDirtyState);
return writtenState;
}
uint32_t ServerReplicationManager::WriteDestroyAction(OutputMemoryBitStream& inOutputStream, NetworkGameObjectPtr gameObject, uint32_t inDirtyState)
{
//don't have to do anything- action already written
return inDirtyState;
} | [
"alwayssmile11a1@gmail.com"
] | alwayssmile11a1@gmail.com |
4b98c06fb6c95a96ef9894a2f3fb1e96579fb057 | 0508304aeb1d50db67a090eecb7436b13f06583d | /nemo/src/kits/media/FileInterface.cpp | 6ca5165a05b574fb94e46e267d4a191af5290c66 | [] | no_license | BackupTheBerlios/nemo | 229a7c64901162cf8359f7ddb3a7dd4d05763196 | 1511021681e9efd91e394191bb00313f0112c628 | refs/heads/master | 2016-08-03T16:33:46.947041 | 2004-04-28T01:51:58 | 2004-04-28T01:51:58 | 40,045,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,701 | cpp | /***********************************************************************
* AUTHOR: Marcus Overhagen
* FILE: FileInterface.cpp
* DESCR:
***********************************************************************/
#include <FileInterface.h>
#include "debug.h"
/*************************************************************
* protected BFileInterface
*************************************************************/
BFileInterface::~BFileInterface()
{
UNIMPLEMENTED();
}
/*************************************************************
* public BFileInterface
*************************************************************/
/* nothing */
/*************************************************************
* protected BFileInterface
*************************************************************/
BFileInterface::BFileInterface()
: BMediaNode("XXX fixme")
{
UNIMPLEMENTED();
AddNodeKind(B_FILE_INTERFACE);
}
status_t
BFileInterface::HandleMessage(int32 message,
const void *data,
size_t size)
{
PRINT(4, "BFileInterface::HandleMessage %#lx, node %ld\n", message, ID());
return B_OK;
}
/*************************************************************
* private BFileInterface
*************************************************************/
/*
private unimplemented
BFileInterface::BFileInterface(const BFileInterface &clone)
FileInterface & BFileInterface::operator=(const BFileInterface &clone)
*/
status_t BFileInterface::_Reserved_FileInterface_0(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_1(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_2(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_3(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_4(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_5(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_6(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_7(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_8(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_9(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_10(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_11(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_12(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_13(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_14(void *) { return B_ERROR; }
status_t BFileInterface::_Reserved_FileInterface_15(void *) { return B_ERROR; }
| [
"fadi_edward"
] | fadi_edward |
2eed304146ff2c7a80f68b9eaaf96028424cc8fe | e95433dc0a5bf564ca66bae5862ac98ccaefce4d | /f_Motor_Movement.ino | d50e567df200b9f0d482d06629119dd528947356 | [] | no_license | HengDuang/MDP | 12a634894e4c2ee8067b558c571715c89c83da3c | 388cbd972961198e0a0a1cf15f3d04f09a0c1b97 | refs/heads/main | 2023-03-08T23:08:00.100245 | 2021-02-23T16:31:59 | 2021-02-23T16:31:59 | 338,521,224 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,807 | ino | void MoveRobotForward()
{
//Compute MotorError
ComputeMotorError();
//Compute PID
ComputePID();
//StoreMotorError
ComputePreviousMotorError();
//SumofAllPreviousMotorError
ComputeAllPreviousMotorError();
//Setting Speed
md.setM2Speed(-newRightMotorRPM);
md.setM1Speed(-newLeftMotorRPM);
//Printing Speed
// Serial.print(mrRPM);
// Serial.print(" ");
// Serial.println(mlRPM);
}
void MoveRobotClockWise()
{
//Compute MotorError
ComputeMotorError();
//Compute PID
ComputePID();
//StoreMotorError
ComputePreviousMotorError();
//SumofAllPreviousMotorError
ComputeAllPreviousMotorError();
//Setting Speed
md.setM2Speed(newRightMotorRPM);
md.setM1Speed(-1 * newLeftMotorRPM);
//Printing Speed
// Serial.print(mrRPM);
// Serial.print(" ");
// Serial.println(mlRPM);
}
void MoveRobotAntiClockWise()
{
//Compute MotorError
ComputeMotorError();
//Compute PID
ComputePID();
//StoreMotorError
ComputePreviousMotorError();
//SumofAllPreviousMotorError
ComputeAllPreviousMotorError();
//Setting Speed
md.setM2Speed(-1 * newRightMotorRPM);
md.setM1Speed(newLeftMotorRPM);
//printing Speed
// Serial.print(mrRPM);
// Serial.print(" ");
// Serial.println(mlRPM);
}
void MoveRobotBackward()
{
//Compute MotorError
ComputeMotorError();
//Compute PID
ComputePID();
//StoreMotorError
ComputePreviousMotorError();
//SumofAllPreviousMotorError
ComputeAllPreviousMotorError();
//Setting Speed
md.setM2Speed(newRightMotorRPM);
md.setM1Speed(newLeftMotorRPM);
//Printing Speed
// Serial.print(mrRPM);
// Serial.print(" ");
// Serial.println(mlRPM);
}
void RobotStop()
{
md.setBrakes(400,400);
}
| [
"noreply@github.com"
] | noreply@github.com |
47772bacc742640efbaa693440f16c2cd826c88a | 890faed59377462270eafc9f1f11cdfce90d49df | /audio.cpp | 597c588e2a5c3cb4792e20c86f9c7734d2a10fed | [] | no_license | HenryDane/a-game | e26253422b437b88d875185222176ff9e15063c6 | 8c3375e03d16bb2ec970219a7c21dc1747150093 | refs/heads/master | 2020-04-02T05:48:05.795169 | 2018-12-13T06:34:42 | 2018-12-13T06:34:42 | 154,106,294 | 1 | 0 | null | 2018-12-11T21:47:33 | 2018-10-22T07:57:21 | C++ | UTF-8 | C++ | false | false | 1,686 | cpp | #include <SFML/Audio.hpp>
#include <iostream>
sf::Music music;
/*
0 - title music
1 - silence
2 - music a (slow)
3 - music b (med)
4 - music c (fast)
*/
int current_music_state = 0;
bool load_flag = true;
bool update_sound(void){
if (!load_flag) return true;
int a = 1;
switch (current_music_state){
case 0:
a = music.openFromFile("res/title.wav");
break;
case 1:
music.stop();
break;
case 2:
a = music.openFromFile("res/fast.wav");
break;
case 3:
a = music.openFromFile("res/fast1.wav");
break;
case 4:
a = music.openFromFile("res/fast2.wav");
break;
default:
std::cout << "BAD SOUND STATE!" << std::endl;
return false;
}
if (!a)
return false;
music.play();
return true;
}
void skip_current_song(void){
music.stop();
if (current_music_state == 0) {
current_music_state = 2;
} else {
current_music_state++;
if (current_music_state == 5)
current_music_state = 2;
}
update_sound();
}
bool check_audio_state() {
if (current_music_state == 1) return false;
if (music.getStatus() != sf::Sound::Stopped) return false;
skip_current_song();
return true;
}
void skip_seconds(int s){
music.pause();
auto newPos = music.getPlayingOffset() + sf::seconds(s);
music.setPlayingOffset(std::min(music.getDuration(), sf::Time(newPos)));
music.play();
}
void decrease_volume(int v) {
music.setVolume(std::max(0.0f, music.getVolume() - v));
}
void increase_volume(int v){
music.setVolume(std::min(100.0f, music.getVolume() + v));
}
| [
"aglareb7@gmail.com"
] | aglareb7@gmail.com |
a7ec086ff093b3004008af155b5249209db22d73 | 89154b124ca2ae1b543a9f7b301c3514b59d3e2a | /BasicRayTracer/Scene.h | 8197b9af31eadd88dd324142776abdb6bf5fa9dc | [] | no_license | trevor-m/raytracer | 6fe3648999c2be42bbebc78ec911bc5a5699c44e | d3c8bd41f82a47574596725a883429dbc09a2a23 | refs/heads/master | 2021-05-16T04:53:44.103699 | 2017-10-08T23:51:33 | 2017-10-08T23:51:33 | 106,215,153 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,855 | h | #pragma once
#include "scene_io.h"
#include "Object.h"
#include "Primitive.h"
#include "Material.h"
#include "Shader.h"
#include "LightSource.h"
#include "Camera.h"
#include "KDTree.h"
#include "Timer.h"
#include <vector>
#define FULLY_OPAQUE_THRESHOLD 0.01f
#define ACCELERATION
// Contains all of the information needed to render a scene
class Scene {
// All objects in scene
std::vector<Object*> objects;
// All primitivies in scene
std::vector<Primitive*> primitives;
// All materials in scene - kept track of here for clean up purposes
std::vector<Material*> materials;
// Acceleration structure
KDTree* kdtree;
// Scene loading helper functions
void loadLights(const SceneIO* scene);
void loadObjects(const SceneIO* scene);
// Creates a new Material from a MaterialIO
Material* makeMaterial(const MaterialIO* materialIO);
// Loads a sphere primitive
void loadSphere(const ObjIO* objNode, Object* parent);
// Loads a set of triangle primitives
void loadPolyset(const ObjIO* objNode, Object* parent);
public:
//All lights in the scene
std::vector<LightSource*> lights;
//Camera information to create rays
ThinLensCamera* camera;
// Loads a scene from sceneFile and sets up camera for image dimensions of [width x height]
Scene(const char* sceneFile, int width, int height, float focalLength, float lensRadius);
// Set object properties
void SetObjectShader(int index, ColorShader* color, IntersectionShader* intersect);
void SetObjectBSSRDF(int index, BSSRDF* bssrdf);
void RemoveObject(int index);
~Scene() {
//clean up
delete camera;
//delete objects
for (int i = 0; i < objects.size(); i++) {
delete objects[i];
}
//delete primitives
for (int i = 0; i < primitives.size(); i++) {
delete primitives[i];
}
//delete materials
for (int i = 0; i < materials.size(); i++) {
delete materials[i];
}
//delete lights
for (int i = 0; i < lights.size(); i++) {
delete lights[i];
}
#ifdef ACCELERATION
//delete acceleration structure
delete kdtree;
#endif
}
// Find the closest object the ray intersects with and outputs hit information
bool GetClosestIntersection(const Vector3& origin, const Vector3& direction, HitData& hitData, Object** hitObject) const {
#ifdef ACCELERATION
return kdtree->GetClosestIntersection(origin, direction, hitData, hitObject);
#else
float closest = FLT_MAX;
bool hit = false;
//iterate over all primitives
for (int i = 0; i < primitives.size(); i++) {
HitData thisHitData;
//hit and closer than all the rest?
if (primitives[i]->intersects(origin, direction, thisHitData) && thisHitData.t < closest) {
closest = thisHitData.t;
hit = true;
//put hit data in outputs
*hitObject = primitives[i]->parent;
hitData = thisHitData;
}
}
return hit;
#endif
}
// Trace a shadow ray and output the color attenuation in shadowFactor
void TraceShadowRay(const Vector3& origin, const Vector3& direction, Vector3& shadowFactor, float maxDist) const {
#ifdef ACCELERATION
return kdtree->TraceShadowRay(origin, direction, shadowFactor, maxDist);
#else
//start by allowing all light
shadowFactor = Vector3(1, 1, 1);
for (int i = 0; i < primitives.size(); i++) {
HitData thisHitData;
if (primitives[i]->intersects(origin, direction, thisHitData) && thisHitData.t < maxDist) {
//fully opaque? block all light
if (thisHitData.material.ktran < FULLY_OPAQUE_THRESHOLD) {
shadowFactor = Vector3(0, 0, 0);
return;
}
//normalize Cd
float normFactor = thisHitData.material.diffColor.MaxComponent();
//prevent div by 0
Vector3 normalizedDiffuse = (normFactor > FLT_EPSILON) ? (thisHitData.material.diffColor / normFactor) : Vector3(1, 1, 1);
//attenuate shadowFactor
shadowFactor = shadowFactor * thisHitData.material.ktran * normalizedDiffuse;
}
}
#endif
}
}; | [
"trevorm@sbcglobal.net"
] | trevorm@sbcglobal.net |
84adda483d0feae0baee25aa73fcfa79cad609b5 | 143ea00fb5b8a98ece6faaf8abc43d386cff7ab3 | /StudentEngine/src/util/ref.h | 1de8cda8c26a7e47deaba2b9c43f069798bbde33 | [] | no_license | eXperion17/StudentEngineRetake | 48acf12ac24a6579f1880917e392099d4334263e | 0c564ec8a7e83ccae3267e8753a2f713f5b3da0a | refs/heads/master | 2023-02-26T06:47:19.524387 | 2021-01-26T13:19:59 | 2021-01-26T13:19:59 | 328,646,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,060 | h | #pragma once
#pragma once
template<typename T>
class AssetRef {
private:
T* m_object = nullptr;
public:
AssetRef() {
Set(nullptr);
}
AssetRef(T* object) {
Set(object);
}
AssetRef(const AssetRef& other) {
this->operator=(other);
}
AssetRef& operator=(const AssetRef& other) {
Set(other.Get());
return *this;
}
operator T* () { return m_object; }
operator T* () const { return m_object; }
//operator const T*() { return m_object; }
~AssetRef() {
Set(nullptr);
}
T* Get()const {
return m_object;
}
void Set(T* object) {
m_object = object;
}
T* operator ->() { return m_object; }
const T* operator ->() const { return m_object; }
T& operator *() { return *m_object; }
const T& operator *() const { return *m_object; }
bool operator==(const AssetRef<T>& other) const {
return m_object == other.m_object;
}
};
template<typename T>
class ManagedRef {
private:
shared_ptr<T> m_object = nullptr;
public:
ManagedRef() {
//Set(nullptr);
}
ManagedRef(T* object) {
m_object = shared_ptr<T>(object);
}
//Ref(shared_ptr<T> object) {
// m_object = object;
//}
//Ref(const Ref& other) {
// this->operator=(other);
//}
//
//Ref& operator=(T* other) {
// Set(other);
// return *this;
//}
//
//Ref& operator=(const Ref& other) {
// Set(other.Get());
// return *this;
//}
//
//operator shared_ptr<T>() { return m_object; }
//operator const shared_ptr<T>() const { return m_object; }
//
operator bool() const { return m_object != nullptr; }
//
//~Ref() {
// Set(nullptr);
//}
//
//shared_ptr<T> Get()const {
// return m_object;
//}
//
//void Set(shared_ptr<T> object) {
// m_object = object;
//}
//
//void Set(T* object) {
// m_object = make_shared<T>(object);
//}
//
shared_ptr<T> operator ->() { return m_object; }
const shared_ptr<T> operator ->() const { return m_object; }
//
//T& operator *() { return *m_object; }
//const T& operator *() const { return *m_object; }
//
//bool operator==(const Ref<T>& other) const {
// return m_object == other.m_object;
//}
}; | [
"marc.gomersbach@hva.nl"
] | marc.gomersbach@hva.nl |
d8773ac08060d6b4ee0f914b71845dd77fc60d32 | fae551eb54ab3a907ba13cf38aba1db288708d92 | /chrome/browser/ash/system_extensions/system_extension.h | 382985236857baedf344f973b9a551d00b67c435 | [
"BSD-3-Clause"
] | permissive | xtblock/chromium | d4506722fc6e4c9bc04b54921a4382165d875f9a | 5fe0705b86e692c65684cdb067d9b452cc5f063f | refs/heads/main | 2023-04-26T18:34:42.207215 | 2021-05-27T04:45:24 | 2021-05-27T04:45:24 | 371,258,442 | 2 | 1 | BSD-3-Clause | 2021-05-27T05:36:28 | 2021-05-27T05:36:28 | null | UTF-8 | C++ | false | false | 1,840 | h | // 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.
#ifndef CHROME_BROWSER_ASH_SYSTEM_EXTENSIONS_SYSTEM_EXTENSION_H_
#define CHROME_BROWSER_ASH_SYSTEM_EXTENSIONS_SYSTEM_EXTENSION_H_
#include <array>
#include "url/gurl.h"
#include "url/origin.h"
// TODO(ortuno): This should be longer.
using SystemExtensionId = std::array<uint8_t, 4>;
enum class SystemExtensionType {
kEcho,
};
struct SystemExtension {
SystemExtension();
~SystemExtension();
SystemExtension(const SystemExtension&) = delete;
SystemExtension& operator=(const SystemExtension&) = delete;
SystemExtension& operator=(SystemExtension&&) = default;
static std::string IdToString(const SystemExtensionId& system_extension_id);
// The following fields are specified by the System Extension itself.
// Currently only kEcho is allowed.
SystemExtensionType type;
// Unique identifier for the System Extension.
SystemExtensionId id;
// Display name of the System Extension.
std::string name;
// Display name of the System Extension to be used where
// the number of characters is limited.
std::string short_name;
// Web App that the System Extension is allowed to communicate with.
GURL companion_web_app_url;
// Entry point to the System Extension. For now, we just open a page
// in the background, but we'll change to a Service Worker once
// chrome-untrusted:// supports Service Workers.
GURL service_worker_url;
// The following fields are constructed from the System Extension's manifest.
// The System Extension's base URL derived from the type and the id e.g.
// `chrome-untrusted://system-extension-echo-1234/`
GURL base_url;
};
#endif // CHROME_BROWSER_ASH_SYSTEM_EXTENSIONS_SYSTEM_EXTENSION_H_
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
d6ebdd0ba334b6bda4872b94ccf97f7a2a2829a8 | e0a1a90d3acfff979fac8c95755f86d062996815 | /include/boost/mixin/common_mutation_rules.hpp | f13d3b8c44a4775c10d2c7a113196dfc40c4bdc4 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | iboB/boost.mixin | 58edf53c103cb512018ae39415a74fff656afc06 | 1922feb589ee928ea759014575d3808b5f4eee04 | refs/heads/master | 2021-01-09T20:48:44.249179 | 2016-06-26T18:02:32 | 2016-06-26T18:02:32 | 7,848,098 | 26 | 3 | null | 2015-07-10T14:51:17 | 2013-01-27T04:25:04 | C++ | UTF-8 | C++ | false | false | 3,760 | hpp | //
// Copyright (c) 2013 Borislav Stanimirov, Zahary Karadjov
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#if !defined(_BOOST_MIXIN_COMMON_MUTATION_RULES_HPP_INCLUDED)
#define _BOOST_MIXIN_COMMON_MUTATION_RULES_HPP_INCLUDED
/**
* \file
* Common mutation rules classes.
*/
#include "global.hpp"
#include "mutation_rule.hpp"
#include "mixin_collection.hpp"
namespace boost
{
namespace mixin
{
/**
* A mutation rule for mutually exclusive mixins.
*
* If active, such rule will cause a mutation that adds one of the mutually
* exclusive mixins, to remove all others.
*
* For example, if `a`, `b`, and `c` are mutually exclusive mixins,
* any mutation that adds, say `a`, to an object, will automatically
* remove `b` and `c` from it.
*/
class BOOST_MIXIN_API mutually_exclusive_mixins : public mutation_rule, private mixin_collection
{
public:
using mixin_collection::add;
using mixin_collection::has;
using mixin_collection::remove;
/// Applies the rule to a mutation.
virtual void apply_to(object_type_mutation& mutation) override;
};
namespace internal
{
/// INTERNAL ONLY
class BOOST_MIXIN_API mandatory_mixin_impl : public mutation_rule
{
public:
mandatory_mixin_impl(mixin_id id)
: _id(id)
{
}
virtual void apply_to(object_type_mutation& mutation) override;
protected:
const mixin_id _id;
};
/// INTERNAL ONLY
class BOOST_MIXIN_API deprecated_mixin_impl : public mutation_rule
{
public:
deprecated_mixin_impl(mixin_id id)
: _id(id)
{
}
virtual void apply_to(object_type_mutation& mutation) override;
protected:
const mixin_id _id;
};
/// INTERNAL ONLY
class BOOST_MIXIN_API substitute_mixin_impl : public mutation_rule
{
public:
substitute_mixin_impl(mixin_id src, mixin_id target)
: _source_id(src)
, _target_id(target)
{
}
virtual void apply_to(object_type_mutation& mutation) override;
protected:
const mixin_id _source_id;
const mixin_id _target_id;
};
}
/**
* A mutation rule for a mandatory mixin.
*
* If active, such rule will cause every mutation to always add the mixin
* to an object and will ignore any attempts of a mutation to remove it.
*
* \tparam Mixin The mandatory mixin type
*/
template <typename Mixin>
class mandatory_mixin : public internal::mandatory_mixin_impl
{
public:
mandatory_mixin()
: mandatory_mixin_impl(_boost_get_mixin_type_info((Mixin*)nullptr).id)
{}
};
/**
* A mutation rule for a deprecated mixin.
*
* If active, such rule will cause every mutation to always try to remove
* the mixin from an object and will ignore any attempts of a mutation to
* add it.
*
* \tparam Mixin The deprecated mixin type
*/
template <typename Mixin>
class deprecated_mixin : public internal::deprecated_mixin_impl
{
public:
deprecated_mixin()
: deprecated_mixin_impl(_boost_get_mixin_type_info((Mixin*)nullptr).id)
{}
};
/**
* A mutation rule for a substitute mixin.
*
* If active, such rule will cause any mutation that tries to add
* `SourceMixin` to instead add `TargetMixin`.
*
* \tparam SourceMixin The mixin type to be substituted
* \tparam TargetMixin The mixin type that is the substitute
*/
template <typename SourceMixin, typename TargetMixin>
class substitute_mixin : public internal::substitute_mixin_impl
{
public:
substitute_mixin()
: substitute_mixin_impl(
_boost_get_mixin_type_info((SourceMixin*)nullptr).id,
_boost_get_mixin_type_info((TargetMixin*)nullptr).id)
{}
};
} // namespace mixin
} // namespace boost
#endif // _BOOST_MIXIN_COMMON_MUTATION_RULES_HPP_INCLUDED
| [
"b.stanimirov@abv.bg"
] | b.stanimirov@abv.bg |
ccee69c51ae9c6a9e69e13a8f8cd5e3a1eb2f154 | 95f54d4022ef40ae1e07da4f444041e85df9bbe6 | /bed/pdb.h | 5549be0332aa921d6c5d3fd22b4dba089702068f | [] | no_license | bdodge/bsa | a5530776e1a371e16240faff517e3e7139725987 | 1337b10160ffc1f2c03a0642d3ff7e5222ad14ab | refs/heads/master | 2022-07-07T16:47:45.395651 | 2022-06-28T13:15:17 | 2022-06-28T13:15:17 | 48,489,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,764 | h |
#ifndef _PDB_H_
#define _PDB_H_ 1
typedef enum
{
efInclude,
efFunction, efArgument,
efClass, efInterface,
efTypeName,
efVar,
efSetClass,
efEndClass, efEndInterface
}
EnumFuncsType;
typedef ERRCODE (*EnumFuncsCallback)(LPVOID cookie, LPCTSTR pName, LPCTSTR pTypeName, int isPtr, int line, EnumFuncsType type);
class BpdbInfo;
// binary tree symbol table
//
//***********************************************************************
typedef struct _tag_symbol
{
public:
_tag_symbol(LPCTSTR name, _tag_symbol *pFile, int line);
~_tag_symbol();
void AddMember (LPCTSTR pMember, _tag_symbol* pFile, int line, _tag_symbol* pSym = NULL);
void SetType (_tag_symbol* pSym);
public:
LPTSTR f_name;
int f_line;
bool f_isptr;
BpdbInfo* f_parent;
BpdbInfo* f_members;
struct _tag_symbol* f_type;
struct _tag_symbol* f_file;
struct _tag_symbol* f_left;
struct _tag_symbol* f_right;
}
Bsym, BSYM, *LPBSYM;
//list of args, or members
KEY_VAL_LIST_TEMPLATE(BpdbInfo, LPBSYM, NO_API); // list of member or function info
//**************************************************************************
KEY_ARRYVAL_LIST_TEMPLATE(BpdbTodo, LPTSTR, NO_API); // list of files to work on
KEY_ARRYVAL_LIST_TEMPLATE(BpdbIncls, LPTSTR, NO_API); // list of include file paths
KEY_VAL_LIST_TEMPLATE(BpdbBufs, Bbuffer*, NO_API); // list of buffers to work on
// program data base object
//
//***********************************************************************
class Bpdb : public Bthread
{
public:
Bpdb (LPCTSTR lpRoot);
virtual ~Bpdb ();
public:
virtual ERRCODE AddIncludePath (LPCTSTR pInclPath);
virtual ERRCODE SetIncludePaths (LPCTSTR lpInclPaths, bool inclIncls);
virtual ERRCODE AddSourceTree (LPCTSTR lpRoot, LPCTSTR extensions = _T("*.*"));
virtual ERRCODE AddFile (LPCTSTR lpFilename, bool suppressCheck = false);
virtual ERRCODE AddFile (Bbuffer* pBuf);
virtual bool ExploreBusy (void);
public:
static LPBSYM AddSym (LPBSYM sym, LPBSYM& tree);
static void DumpSym (LPBSYM tree);
static void DeleteSym (LPBSYM sym);
static LPBSYM FindSym (LPCTSTR name, LPBSYM tree);
static LPBSYM FindClassSym (LPCTSTR classname, LPCTSTR name, LPBSYM tree);
static LPBSYM FindMember (LPCTSTR name, LPBSYM tree);
virtual LPBSYM GetTypes (void) { return m_types; }
virtual LPBSYM GetFunctions (void) { return m_functions; }
virtual LPBSYM GetVars (void) { return m_vars; }
virtual LPBSYM GetBaseType (LPCTSTR pTypename);
static ERRCODE OnEnumFuncStub (LPVOID cookie, LPCTSTR pName, LPCTSTR pTypeName, int isPtr, int line, EnumFuncsType type);
static
ERRCODE WINAPI RunStub (LPVOID thisptr);
protected:
virtual ERRCODE Explore (LPCTSTR pFilename, bool checkDone);
virtual ERRCODE Explore (Bbuffer* pBuf, LPBSYM pFileSym);
virtual ERRCODE ExploreThread (void);
virtual ERRCODE OnEnumFunc (LPCTSTR pName, LPCTSTR pTypeName, int isPtr, int line, EnumFuncsType type);
protected:
// list of func, class, etc. decls
LPBSYM m_functions;
LPBSYM m_types;
LPBSYM m_vars;
LPBSYM m_manifests;
// current symbols
LPBSYM m_pSym;
LPBSYM m_pType;
LPBSYM m_pClass;
// sorted list of files already explored
LPBSYM m_files;
// current file being explored (symbol version)
LPBSYM m_filesym;
// list of files to explore
BpdbTodo* m_filestodo;
BpdbTodo* m_filestodonow;
BpdbBufs* m_bufstodo;
// mutex to serialize access to todo list
Bmutex m_todex;
// file currently being explored
TCHAR m_file[MAX_PATH];
// recursion level
int m_level;
// flag that there is a current subscriber
bool m_enumerating;
// list of include file paths to use (in order!)
BpdbIncls* m_inclPaths;
Blog* m_log;
};
#endif /* PDB_H_ */
| [
"bdodge09@gmail.com"
] | bdodge09@gmail.com |
9e81c3e56e9b5fc626de0f8825eeda83dc82fcfc | b8d3c2478cb9e26a1ae9f2413e7dac2e78e8f0d3 | /Unmanaged/HVisionSystem/include/Matrox/MilCircleFind.h | 2b04c137da17d9b8f933f530c671073eb33b4595 | [
"MS-PL",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | wiseants/Varins | 4281ddf31f3cff6b8dc5e62530186d3795e844c7 | 8b9153bc46c669c572f2e56fe313a92cb546c5ae | refs/heads/master | 2022-12-09T20:25:58.574485 | 2020-11-10T07:38:10 | 2020-11-10T07:38:10 | 242,623,978 | 0 | 0 | NOASSERTION | 2022-12-08T02:14:40 | 2020-02-24T01:50:05 | C++ | UTF-8 | C++ | false | false | 828 | h | #pragma once
#include "MatroxClass.h"
#include "MilImage.h"
#include "Utility/Defines.h"
#include <atlcoll.h>
struct MATROXCLASS CircleFindResultInfo
{
TRect m_rect;
double m_lfScore;
};
typedef CAtlList<CircleFindResultInfo> CircleFindResultList;
class MATROXCLASS CMilCircleFind : public MilObject
{
public:
CMilCircleFind();
~CMilCircleFind();
BOOL Alloc();
void Free();
BOOL Calculate(CMilImage* pMilImage);
// Parameter
void SetScore(long nScore);
void SetSearchingNumber(long nNumber);
void SetSearchLevel(long nLevel);
void SetFilterLevel(long nFilterLevel);
void SetRadius(double lfRadius);
void SetMinScale(double nMinScale);
void SetMaxScale(double nMaxScale);
CircleFindResultList* GetResultList(){ return &m_resultList; }
private:
MIL_ID m_milResult;
CircleFindResultList m_resultList;
};
| [
"wiseants@nate.com"
] | wiseants@nate.com |
45a1fe683f2c993b50fcebb3d2c34663c59b76a8 | 0611b1cc08b15d329057595365359947c20fcd59 | /sf/tm/biaoc.cpp | e278e7513c755dfd5bfa7651e543ec036cf39f92 | [] | no_license | Lan-ce-lot/overflow | c9a7167edaeeaa1f9f1e92624726b1d964289798 | ae76120e328a5a2991eb6ef7f1ae5e279374e15c | refs/heads/master | 2023-04-08T04:24:49.614146 | 2021-04-25T05:33:06 | 2021-04-25T05:33:06 | 279,082,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,244 | cpp | #include<bits/stdc++.h>
#define ls (k << 1)
#define rs (ls | 1)
using namespace std;
typedef long long ll;
const int N = 2e3 + 5, M = 2e6 + 5;
int T, n, m, dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
char s[N][N];
int num = 0;
int dfs(int x, int y) {
int sum = 0;
s[x][y] = '*';
for (int i = 0; i < 4; i++) {
int nx = dx[i] + x, ny = dy[i] + y;
if (nx < 0 || nx >= n || ny < 0 || ny >= m)
continue;
if (s[nx][ny] == '.') sum++;
if (s[nx][ny] != '@') continue;
sum += dfs(nx, ny);
}
return sum;
}
int main(){
scanf("%d", &T);
while (T--) {
num = 0;
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++)
scanf("%s", s[i]);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (s[i][j] != '*') continue;
for (int k = 0; k < 4; k++) {
int nx = dx[k] + i, ny = dy[k] + j;
if (nx < 0 || nx >= n || ny < 0 || ny >= m)
continue;
if (s[nx][ny] == '.') {
s[nx][ny] = '@';
num++;
}
}
}
}
if (!num) {
printf("NO\n");
continue;
}
num = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (s[i][j] == '@') {
if (!dfs(i, j))
num++;
}
}
}
if (num > 1)
printf("YES\n");
else
printf("NO\n");
}
}
| [
"1984737645@qq.com"
] | 1984737645@qq.com |
2c3c484a80f9f6a49fb2e5b194ab476393a4bc5e | 8a8ba656b23333cf0c768c351d9046955e4c4c93 | /CPP - 2/Binary Search Tree/test.h | 1bee576e5cba0d5683469c522dec83894e122e6b | [] | no_license | SacredStar/Univesity | bca850906771533d08558f650b392af3929fb98d | 933565697c851d098a04486e1bfa209a0188f514 | refs/heads/master | 2020-06-29T12:27:13.619340 | 2019-08-04T20:32:24 | 2019-08-04T20:32:24 | 200,535,262 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 513 | h | #pragma once
#include "node.h"
#include <vector>
#include <cassert>
//Создание для тестирования Union
Node* create_A();
Node* create_B();
//Создание больших А,B
Node* create_A_test_A();
Node* create_B_test_B();
//Перевод Tree в Vector для Assets
void print_tree_to_vec(const Node*,std::vector<int>&);
//Тесты создания
void test_A();
void test_B();
//Тест соединения
void test_union();
void test();
//Ручное
void tesing_manualy();
| [
"shadowordeath1993@yandex.ru"
] | shadowordeath1993@yandex.ru |
83c17aae610450dfa22a945d4e8affd8c566ecab | c6d2aca1ea7ae30d317c37b63cb61f87e29510c5 | /OpenCVForBarCode/stdafx.cpp | 97720d9ede31e4435bb09f756e091e21f9238042 | [] | no_license | laowanghai/OpenCVForBarCode | b4342a1aa48068c3c5ccd9a2a4ff29e731ba1b9b | 52ea352b249c2aef585071361b80528d6bcfb059 | refs/heads/master | 2020-05-21T06:11:10.773994 | 2019-05-10T07:28:25 | 2019-05-10T07:28:25 | 185,939,268 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 179 | cpp |
// stdafx.cpp : 只包括标准包含文件的源文件
// OpenCVForBarCode.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
| [
"noreply@github.com"
] | noreply@github.com |
7d2cf9cfd8d3fc1814f8ff1ab0e791c99b16072b | 1515fa63742c74ae94305db9e9fddf06b33593c3 | /paintline.h | 67bacdf94bab526000b0187c57e92c625ae3f8ca | [] | no_license | BIoodRaven/modelofGasMedium | fb4f8fffa65cf5989dc48f73f6c3359173d54f07 | 97a3452147fca21c15854c99d69adcfcea83f9bb | refs/heads/master | 2020-04-07T03:02:26.338834 | 2018-11-17T17:20:11 | 2018-11-17T17:20:11 | 157,999,999 | 0 | 0 | null | 2018-11-17T17:20:12 | 2018-11-17T15:54:26 | C++ | UTF-8 | C++ | false | false | 711 | h | #ifndef PAINTLINE_H
#define PAINTLINE_H
#include<iostream>
#include<calculusbody.h>
#include<paintline.h>
#include<mainwidget.h>
#include <QWidget>
#include <QPainter>
#include <QCheckBox>
#include <QPushButton>
#include <QVBoxLayout>
#include <QPixmap>
#include <QHBoxLayout>
#include <QPicture>
#include <QLabel>
#include<QIODevice>
#include<QDebug>
#include<QFile>
#include<QTimer>
class PaintLine : public QWidget
{
Q_OBJECT
private:
int counter;
double Imax;
double h;
public:
PaintLine(QWidget *parent = 0);
~PaintLine();
public slots:
void addCounter();
void paintEvent(QPaintEvent*);
void modEiler(bool);
signals:
void dataChanged();
};
#endif // PAINTLINE_H
| [
"alexander@phystech.edu"
] | alexander@phystech.edu |
41823931d59b97fe36aa40913760a61a18b6786a | 7579d827cb7b50b438dfd9ef6fa80ba2797848c9 | /sources/plug_wx/src/LuaEventHandler.cpp | 10b3f51aaa3184b96916a4556846d37f04dbec9a | [] | no_license | roche-emmanuel/sgt | 809d00b056e36b7799bbb438b8099e3036377377 | ee3a550f6172c7d14179d9d171e0124306495e45 | refs/heads/master | 2021-05-01T12:51:39.983104 | 2014-09-08T03:35:15 | 2014-09-08T03:35:15 | 79,538,908 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,241 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: wxlcallb.cpp
// Purpose: LuaEventHandler and wxLuaWinDestroyCallback
// Author: Francis Irving, John Labenski
// Created: 11/05/2002
// Copyright: (c) 2002 Creature Labs. All rights reserved.
// Licence: wxWidgets licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif // WX_PRECOMP
#include "LuaEventHandler.h"
const char* wx_refs_key = "wxlua_lreg_refs_key : wxLua Lua object refs";
#define ABS_LUA_STKIDX(n, added_items) ((n) > 0 ? (n) : (n)-(added_items))
int wxluaR_ref(lua_State* L, int stack_idx, void* lightuserdata_reg_key)
{
// nothing on stack to insert and don't bother inserting nil
if (lua_isnoneornil(L, stack_idx))
return LUA_REFNIL;
lua_pushlightuserdata(L, lightuserdata_reg_key); // push key
lua_rawget(L, LUA_REGISTRYINDEX); // pop key, push value (table)
if(lua_isnil(L,-1)) {
trINFO("Luna","Creating wx function index table.");
lua_pop(L,1);
lua_pushlightuserdata(L, lightuserdata_reg_key); // push key
lua_newtable(L);
lua_rawset(L, LUA_REGISTRYINDEX); // pop key, push value (table)
lua_pushlightuserdata(L, lightuserdata_reg_key); // push key
lua_rawget(L, LUA_REGISTRYINDEX); // pop key, push value (table)
}
lua_pushvalue(L, ABS_LUA_STKIDX(stack_idx,1)); // push value to store
int ref_idx = luaL_ref(L, -2); // t[ref_idx] = value; pops value
lua_pop(L, 1); // pop table
return ref_idx;
}
bool wxluaR_unref(lua_State* L, int ref_idx, void* lightuserdata_reg_key)
{
if (ref_idx == LUA_REFNIL) // nothing to remove
return false;
lua_pushlightuserdata(L, lightuserdata_reg_key); // push key
lua_rawget(L, LUA_REGISTRYINDEX); // pop key, push value (table)
luaL_unref(L, -1, ref_idx); // remove key and value in refs table
// note: this key will be used for the next wxluaR_ref()
lua_pop(L, 1); // pop table
return true;
}
bool wxluaR_getref(lua_State *L, int ref_idx, void* lightuserdata_reg_key)
{
if (ref_idx == LUA_REFNIL) // nothing to get
return false;
lua_pushlightuserdata(L, lightuserdata_reg_key); // push key
lua_rawget(L, LUA_REGISTRYINDEX); // pop key, push value (table)
lua_rawgeti(L, -1, ref_idx); // get t[ref_idx] = value; push value
if (lua_isnil(L, -1)) // not a valid table key
{
lua_pop(L, 2); // pop nil and table
return false;
}
lua_remove(L, -2); // remove table, leaving value on top
return true; // return if table has a valid value and it's on the stack
}
//-----------------------------------------------------------------------------
// LuaEventHandler
//-----------------------------------------------------------------------------
IMPLEMENT_ABSTRACT_CLASS(LuaEventHandler, wxEvtHandler)
LuaEventHandler::LuaEventHandler()
: wxEvtHandler(),
m_luafunc_ref(LUA_NOREF), m_state(0),
m_evtHandler(NULL), m_id(wxID_ANY), m_last_id(wxID_ANY)
{
}
LuaEventHandler::~LuaEventHandler()
{
// Remove the reference to the Lua function that we call
logDEBUG4("Calling LuaEventHandler destructor with L=" << (const void*)m_state << ", ref="<< m_luafunc_ref);
if (m_state && m_luafunc_ref!=LUA_NOREF)
{
wxluaR_unref(m_state,m_luafunc_ref,&wx_refs_key);
}
}
wxString LuaEventHandler::connect(lua_State* L, int lua_func_stack_idx,
wxWindowID win_id, wxWindowID last_id,
wxEventType eventType, wxEvtHandler *evtHandler)
{
//trINFO("LuaEventHandler","Entering connect(...)");
// Assert too since these errors are serious and not just bad Lua code.
wxCHECK_MSG(evtHandler != NULL, wxT("Invalid wxEvtHandler in LuaEventHandler::Connect()"), wxT("Invalid wxEvtHandler in LuaEventHandler::Connect()"));
wxCHECK_MSG((m_evtHandler == NULL) && (m_luafunc_ref == LUA_NOREF), wxT("Attempting to reconnect a LuaEventHandler"), wxT("Attempting to reconnect a LuaEventHandler"));
wxCHECK_MSG(L, wxT("Invalid wxLuaState"), wxT("Invalid wxLuaState"));
//trINFO("LuaEventHandler","Checking thread...");
// We must always be installed into the main lua_State, never a coroutine
// 1) It will be called only when the lua_State is suspended or dead
// 2) We have no way of tracking when the coroutine state is garbage collected/dead
if (lua_pushthread(L) != 1)
{
lua_pop(L,1);
return wxT("wxLua: Creating a callback function in a coroutine is not allowed since it will only be called when the thread is either suspended or dead.");
}
lua_pop(L,1);
m_state = L;
m_evtHandler = evtHandler;
m_id = win_id;
m_last_id = last_id;
m_eventType = eventType;
//trINFO("LuaEventHandler","Creating ref...");
// create a reference to the Lua event handler function
m_luafunc_ref = wxluaR_ref(L,lua_func_stack_idx, &wx_refs_key);
//trINFO("LuaEventHandler","Performing actual connection...");
// Note: We use the callback userdata and not the event sink since the event sink
// requires a wxEvtHandler object which is a fairly large class.
// The userdata (i.e. this) is also deleted for us which makes our life easier.
m_evtHandler->Connect(win_id, last_id, eventType,
(wxObjectEventFunction)&LuaEventHandler::OnAllEvents,
this);
// m_evtHandler->Bind(eventType,
// &LuaEventHandler::OnAllEvents,
// win_id,
// last_id,
// this);
//trINFO("LuaEventHandler","Leaving connect(...)");
return wxEmptyString;
}
void LuaEventHandler::OnAllEvents(wxEvent& event)
{
wxEventType evtType = event.GetEventType();
// Get the LuaEventHandler instance to use which is NOT "this" since
// "this" is a central event handler function. i.e. this != theCallback
LuaEventHandler *theCallback = (LuaEventHandler *)event.m_callbackUserData;
wxCHECK_RET(theCallback != NULL, wxT("Invalid LuaEventHandler in wxEvent user data"));
if (theCallback != NULL)
{
theCallback->OnEvent(&event);
}
}
void LuaEventHandler::OnEvent(wxEvent *event)
{
lua_State* L = m_state;
int oldTop = lua_gettop(L);
// Retrieve the referenced function:
if (wxluaR_getref(L,m_luafunc_ref, &wx_refs_key))
{
Luna< wxEvent >::push(L,event,false);
int result = lua_pcall(L,1,0,0); // one input no returns
// lua_call(L,1,0); // one input no returns
// int result = 0;
if(result==LUA_ERRRUN) {
trERROR("LuaEventHandler",lua_tostring(L,-1));
}
}
lua_settop(L,oldTop); // pop function and error message from the stack (if they're there)
}
| [
"roche.emmanuel@gmail.com"
] | roche.emmanuel@gmail.com |
55ae3ee284083ef421773e2fbf13276737bfd361 | 1c7755187719039b46aae8400cbd5a4e03d4b7c6 | /Source/Project/PEShow/DosHeaderDlg.cpp | e501d35397298e35210caa9357283027bb162393 | [] | no_license | liujiquan/Work | dc70b3bd67e2618bf5106e341c4b5c13762c6b6b | 12964013329fbab4a233a2ac23bff0e173298026 | refs/heads/master | 2021-01-10T08:12:22.145734 | 2016-02-18T04:44:52 | 2016-02-18T04:44:52 | 51,979,366 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,196 | cpp | // DosHeaderDlg.cpp : implementation file
//
#include "stdafx.h"
#include "PEShow.h"
#include "DosHeaderDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDosHeaderDlg dialog
CDosHeaderDlg::CDosHeaderDlg(CWnd* pParent /*=NULL*/)
{
}
void CDosHeaderDlg::DoDataExchange(CDataExchange* pDX)
{
}
BEGIN_MESSAGE_MAP(CDosHeaderDlg, CDialogBar)
//{{AFX_MSG_MAP(CDosHeaderDlg)
// ON_WM_SIZE()
ON_MESSAGE(WM_INITDIALOG, OnInitDialog)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDosHeaderDlg message handlers
#define SCROLL_WIDTH 20
BOOL CDosHeaderDlg::OnInitDialog(WPARAM wparam, LONG lparam)
{
BOOL bRet = HandleInitDialog(wparam, lparam);
if(!UpdateData(FALSE))
{
}
CRect rect;
GetClientRect(&rect);
int width = rect.Width() - SCROLL_WIDTH;
CListCtrl* pListCtrl = (CListCtrl*)GetDlgItem(IDC_LIST1);
if(pListCtrl == NULL)
{
return FALSE;
}
pListCtrl->SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);
pListCtrl->InsertColumn(0, "Add", LVCFMT_LEFT, width/5);
pListCtrl->InsertColumn(1, "ITEM", LVCFMT_LEFT, width/5);
pListCtrl->InsertColumn(2, "DATA", LVCFMT_LEFT, width/5);
pListCtrl->InsertColumn(4, "DATA", LVCFMT_LEFT, width/5);
pListCtrl->InsertColumn(4, "DES", LVCFMT_LEFT, width/5);
InitListCtrl();
return TRUE;
}
// -----------------------------------------------------------//
// Function : CDosHeaderDlg::SetImageDosHeadeData
// Param : IMAGE_DOS_HEADER* pData
// Return : void
// Comment :
// -----------------------------------------------------------//
void CDosHeaderDlg::SetImageDosHeadeData(IMAGE_DOS_HEADER* pData)
{
if(pData)
{
memcpy(&m_DosheaderData, pData, sizeof(IMAGE_DOS_HEADER));
}
}
// -----------------------------------------------------------//
// Function : CDosHeaderDlg::InitListCtrl
// Return : void
// Comment :
// -----------------------------------------------------------//
void CDosHeaderDlg::InitListCtrl()
{
DWORD dwAddress = 0x00000000;
CString strTemp;
UINT nCount = 0;
CListCtrl* m_m_ListCtrl = (CListCtrl*)GetDlgItem(IDC_LIST1);
if(m_m_ListCtrl == NULL)
{
return;
}
m_m_ListCtrl->DeleteAllItems();
// e_magic
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_magic");
strTemp.Format("%04X", m_DosheaderData.e_magic);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_magic);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Magic number");
nCount++;
// e_cblp
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_cblp");
strTemp.Format("%04X", m_DosheaderData.e_cblp);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_cblp);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Bytes on last page of file");
nCount++;
// e_cp
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_cp");
strTemp.Format("%04X", m_DosheaderData.e_cp);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_cp);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Pages in file");
nCount++;
// e_crlc
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_crlc");
strTemp.Format("%04X", m_DosheaderData.e_crlc);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_crlc);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Relocations");
nCount++;
// e_cparhdr
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_cparhdr");
strTemp.Format("%04X", m_DosheaderData.e_cparhdr);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_cparhdr);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Size of header in paragraphs");
nCount++;
// e_minalloc
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_minalloc");
strTemp.Format("%04X", m_DosheaderData.e_minalloc);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_minalloc);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Minimum extra paragraphs needed");
nCount++;
// e_maxalloc
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_maxalloc");
strTemp.Format("%04X", m_DosheaderData.e_maxalloc);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_maxalloc);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Maximum extra paragraphs needed");
nCount++;
// e_ss
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_ss");
strTemp.Format("%04X", m_DosheaderData.e_ss);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_ss);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Initial (relative) SS value");
nCount++;
// e_sp
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_sp");
strTemp.Format("%04X", m_DosheaderData.e_sp);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_sp);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Initial SP value");
nCount++;
// e_csum
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_csume_cblp");
strTemp.Format("%04X", m_DosheaderData.e_csum);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_csum);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Checksum");
nCount++;
// e_ip
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_ip");
strTemp.Format("%04X", m_DosheaderData.e_ip);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_ip);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Initial IP value");
nCount++;
// e_cs
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_cs");
strTemp.Format("%04X", m_DosheaderData.e_cs);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_cs);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Initial (relative) CS value");
nCount++;
// e_lfarlc
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_lfarlc");
strTemp.Format("%04X", m_DosheaderData.e_lfarlc);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_lfarlc);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "File address of relocation table");
nCount++;
// e_ovno
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_ovno");
strTemp.Format("%04X", m_DosheaderData.e_ovno);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_ovno);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Overlay number");
nCount++;
// e_res[0]
for(int i = 0; i < 4; i++)
{
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
strTemp.Format("e_res[%d]", i);
m_m_ListCtrl->SetItemText(nCount, 1, strTemp);
strTemp.Format("%04X", m_DosheaderData.e_res[i]);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_res[i]);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Reserved words");
nCount++;
}
// e_oemid
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_oemid");
strTemp.Format("%04X", m_DosheaderData.e_oemid);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_oemid);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "OEM identifier (for e_oeminfo)");
nCount++;
// e_oeminfo
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_oeminfo");
strTemp.Format("%04X", m_DosheaderData.e_oeminfo);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_oeminfo);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "OEM information; e_oemid specific");
nCount++;
// e_res2[10]
for(i = 0; i < 10; i++)
{
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
strTemp.Format("e_res2[%d]", i);
m_m_ListCtrl->SetItemText(nCount, 1, strTemp);
strTemp.Format("%04X", m_DosheaderData.e_res2[i]);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_res2[i]);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "Reserved words");
nCount++;
}
// e_lfanew
m_m_ListCtrl->InsertItem(nCount, "0");
strTemp.Format("%08X", dwAddress+nCount*2);
m_m_ListCtrl->SetItemText(nCount, 0, strTemp);
m_m_ListCtrl->SetItemText(nCount, 1, "e_lfanew");
strTemp.Format("%04X", m_DosheaderData.e_lfanew);
m_m_ListCtrl->SetItemText(nCount, 2, strTemp);
strTemp.Format("%s", &m_DosheaderData.e_lfanew);
m_m_ListCtrl->SetItemText(nCount, 3, strTemp);
m_m_ListCtrl->SetItemText(nCount, 4, "File address of new exe header");
}
/*
void CDosHeaderDlg::OnSize(UINT nType, int cx, int cy)
{
CDialogBar::OnSize(nType, cx, cy);
cx -= SCROLL_WIDTH;
CListCtrl* m_m_ListCtrl = (CListCtrl*)GetDlgItem(IDC_LIST1);
if(m_m_ListCtrl == NULL)
{
return ;
}
if(m_m_ListCtrl->m_hWnd)
{
m_m_ListCtrl->MoveWindow(0, 0, cx, cy);
m_m_ListCtrl->SetColumnWidth(0, cx/5);
m_m_ListCtrl->SetColumnWidth(1, cx/5);
m_m_ListCtrl->SetColumnWidth(2, cx/5);
m_m_ListCtrl->SetColumnWidth(4, cx/5);
m_m_ListCtrl->SetColumnWidth(4, cx/5);
}
}*/
| [
"905047424@qq.com"
] | 905047424@qq.com |
470f4bdbc8366641e195c0130f9721299ed22a5e | a5c031981839cc39960058656b668014458a0469 | /Breadth-first search(BFS).cpp | 702fbb5d304c5dd2ec5c6822dc354b91c76bb9e5 | [] | no_license | Shakhaout-Hossain/TEMPLATE | bf938b7155c596e05924260d21bcd63240d85ff0 | 1ec5c5d4473a6bf77426fd59250c1e089fb46d82 | refs/heads/master | 2023-03-17T09:32:46.486796 | 2019-09-12T10:40:41 | 2019-09-12T10:40:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 617 | cpp | #include<bits/stdc++.h>
using namespace std;
vector < int > v[1000];
int vis[1000];
int dist[1000];
int parent[1000];
void BFS(int s, int n)
{
for(int i=0; i<=n; i++)
vis[i]=0;
queue < int > q;
q.push(s);
vis[s]=1;
while(!q.empty())
{
int k = q.front();
q.pop();
for(int i=0; i<v[k].size(); i++)
{
int p = v[k][i];
if(vis[p]==0)
{
vis[p] = 1;
q.push(p);
dist[p] = dist[k]+1;
parent[p]=k;
}
}
}
}
int main()
{
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
439cbba2244be9552e52e44f9d5e3e01e8a8dca1 | 5428a95239868d90c7ab8171c3dedfa982662c97 | /basicBayesV3wComm/basicBayes.h | 8fe525cedaaaa56d0c0efa7fcbf5d699850f8751 | [] | no_license | pbarragan/basicBayes | a5fa35bf2a03665b2f727bea8ba86113a6059594 | c20aeb6eaeb4d97cceb18d496f6566da1ed59849 | refs/heads/master | 2021-01-25T05:57:45.196340 | 2013-07-24T17:01:29 | 2013-07-24T17:01:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,645 | h | /*
* basicBayes.h
* basicBayes
*
* Created by Patrick Barragan on 12/17/12.
* Copyright 2012 MIT. All rights reserved.
*
*/
#include <vector>
#ifndef BASIC_BAYES_H
#define BASIC_BAYES_H
class basicBayes {
public:
std::vector<double> normalizeVector(std::vector<double> probVect);
std::vector<double> stateTransition(std::vector<double> prevState, std::vector<double> action);
//overloaded
void transitionUpdate(std::vector<double> action);
void transitionUpdate(std::vector<double>& probList, std::vector<double> action);
//overloaded
void observationUpdate(std::vector<double> obs);
void observationUpdate(std::vector<double>& probList, std::vector<double> obs);
double probState(std::vector<double> sampleState, std::vector<double> meanState);
double probObs(std::vector<double> obs, std::vector<double> state);
Eigen::Map<Eigen::MatrixXd> convertVect(std::vector<double>& vect);
Eigen::Map<Eigen::MatrixXd> convertCovMat(std::vector<double>& covMat);
double evaluteMVG(std::vector<double>& sampleVecVect, std::vector<double>& meanVecVect, std::vector<double>& covMatVect);
void setCovMats(std::vector<double>& obs,std::vector<double>& trans);
void setupStates();
void filterSetup();
std::vector< std::vector<double> > createValueList(double dimRanges[][2], double dimNums[], int dims);
std::vector< std::vector<double> > recurseList(std::vector< std::vector<double> > totalList, std::vector<double> oldSeq, int level, std::vector< std::vector<double> > valueList);
std::vector<double> obsCovMat;
std::vector<double> transCovMat;
std::vector< std::vector<double> > stateList;
std::vector<double> probList_; //PDF
void printProbList();
void printStateList();
std::vector<double> realPrevState_;
std::vector<double> realCurrentState_;
std::vector<double> realAction_;
//overloaded
std::vector<double> getObs();
std::vector<double> getObs(std::vector<double>& currentState);
double randomDouble();
void runRealWorld();
//stuff added for action selection
std::vector<double> createCDF(std::vector<double> probList);
std::vector<double> getSampleState(std::vector<double>& CDF, std::vector< std::vector<double> >& states);
void chooseAction();
void chooseActionOG();
void setupActions();
double distPoints(std::vector<double> a, std::vector<double> b);
double calcEntropy(std::vector<double> probs);
//overloaded
std::vector<double> calcModelProb();
std::vector<double> calcModelProb(std::vector<double>& probList);
std::vector< std::vector<double> > actionList_;
int numModels_;
//debug printing
bool debug_print_;
};
#endif //BASIC_BAYES_H
| [
"patrick.r.barragan@gmail.com"
] | patrick.r.barragan@gmail.com |
bf5a993f1df6c9bc906163fa17d23c937599369b | 8268c5755f6cde397e908279109c4c57e4c8a9ab | /CeguetaFinal/JsonReader.h | 1cdc594d58b685b386eb7201e55ce43b3a1c56db | [] | no_license | RafaelGSS/cegueta.basic | 8f189c1c69c1ace4086d34d6f4ea284282d57289 | 3c9dd9f8ab78df514c31b283bed304c309130b30 | refs/heads/master | 2021-08-19T14:37:15.198843 | 2017-11-26T16:54:02 | 2017-11-26T16:54:02 | 109,065,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 254 | h | #pragma once
#include "json.hpp"
using Json = nlohmann::json;
namespace cegueta {
namespace reader {
class JsonReader
{
public:
JsonReader();
~JsonReader();
static Json readerFile(std::string);
private:
Json currentJson;
};
}
}
| [
"rafael.nunu@hotmail.com"
] | rafael.nunu@hotmail.com |
e0de14ee474db4bd2156bff7400b94e09b7c71a5 | 33c9b092477c262c1624ebb7a42797fe7dda5b25 | /AnimationViewer/Container/LinkedList .h | 0d2b62b4a47de99580686745081f8ba54f5de0ed | [] | no_license | esthertonks/AnimationViewer | 2623a69b6f5d53b02cc09b40e3068a658d3a4ec1 | 9ef42e0c7a5fa26d1938fed3fc2f972698718772 | refs/heads/master | 2021-01-20T22:29:21.530259 | 2016-06-20T09:30:12 | 2016-06-20T09:30:12 | 59,888,728 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,067 | h | #pragma once
#include <cstdlib>
namespace container
{
template<class TYPE> class LinkedList
{
public:
LinkedList::LinkedList()
{
m_root = NULL;
m_end = NULL;
};
virtual LinkedList::~LinkedList()
{
for(TYPE *type = m_root; type != NULL; )
{
TYPE *temp = type;
type = type->m_next;
delete temp;
}
};
virtual TYPE* GetRoot()
{
return m_root;
}
virtual void Add(
TYPE &node
)
{
if(m_root) // Hierarchy list is not empty - add to the end and move the end to the new node
{
m_end->m_next = &node;
node.m_next = NULL;
node.m_previous = m_end;
m_end = m_end->m_next;
}
else // List is empty - add the new node to the root node
{
m_root = m_end = &node;
node.m_previous = NULL;
node.m_next = NULL;
}
}
TYPE *m_root;
TYPE *m_end;
};
template<class ITEM> class LinkedListItem
{
friend class LinkedList<ITEM>;
public:
LinkedListItem::LinkedListItem()
{
m_next = NULL;
m_previous = NULL;
};
virtual LinkedListItem::~LinkedListItem()
{
};
ITEM *m_next;
ITEM *m_previous;
};
} | [
"esther.tonks@gmail.com"
] | esther.tonks@gmail.com |
eecd00cfa5b9459cbca093aa9ce89f91fe544f87 | 3d50d8f865e53a437cb0ffbf894143665e306208 | /Actividad_8/RandomNumberServer/randomhandler.h | 80c0effcf9d0deeeaae816920cf0fb6ee3704a8d | [] | no_license | S-Bou/Practicas_SII | 4adf8d94cc0211476b1ffe1958d452a6a5cc5bed | c2e7c2015401abaee6e74708627fb0301929f0c7 | refs/heads/master | 2022-05-29T11:47:24.466626 | 2020-05-03T17:21:49 | 2020-05-03T17:21:49 | 247,935,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | h | #ifndef RANDOMHANDLER_H
#define RANDOMHANDLER_H
#include <QObject>
#include <QTcpSocket>
#include <QHostAddress>
class RandomHandler : public QObject
{
Q_OBJECT
public:
explicit RandomHandler(QTcpSocket * socket, QObject *parent = nullptr);
//Métodos del socket TCP
QHostAddress direccionIpLocal();
QHostAddress direccionIpRemota();
quint16 puertoLocal();
quint16 puertoRemoto();
bool estaAbierto();
bool cerrar();
//Métodos del campo _max
int max();
bool setMax(int m);
//Métodos del campo _min
int min();
bool setMin(int m);
signals:
void desconectado();
protected slots:
void datosDisponibles();
private:
QTcpSocket *_socket;
int _max = RAND_MAX;
int _min = 0;
void inicializa_qrand();
int rand();
};
#endif // RANDOMHANDLER_H
| [
"bouyo30@gmail.com"
] | bouyo30@gmail.com |
e5e8888c1b4f9e46eac77568e19ff59e46ae1b41 | 5af6f7e6a2c442581a985a7dba2dbb9a059cea03 | /GameFramework/StruffyLite/Maths/MtLine.cpp | d5687b7421bbdebc929cbbc1ebf62d13ad7f8ad2 | [] | no_license | MORTAL2000/GameFramework | 05b848f2e27e75f5cd2d2112045f5dbce917262e | 2cb7f3b611540f3c737dfa5638edbedbc1860f85 | refs/heads/master | 2021-06-01T07:26:25.919802 | 2016-06-21T11:03:21 | 2016-06-21T11:03:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,481 | cpp | // Includes
#include <math.h>
#include "MtVector3.h"
#include "MtVector2.h"
#include "MtVector4.h"
#include "MtLine.h"
#include "MtTriangle.h"
#include "MtPlane.h"
// Public functions
void MtLine::FindLineRadius()
{
MtVector3 diff = point1 - point2;
m_fRadius = (BtFloat) sqrt( (diff.x * diff.x) + (diff.y * diff.y) + (diff.z * diff.z) );
}
BtBool MtLine::Collide(const MtTriangle &triangle, MtVector3 &intersection)
{
// Calculate the plane of the triangle
MtPlane plane( &triangle );
// Calculate the intersection
BtFloat a = plane.m_v3Normal.x;
BtFloat b = plane.m_v3Normal.y;
BtFloat c = plane.m_v3Normal.z;
BtFloat d = plane.m_fDistance;
BtFloat i = point2.x - point1.x;
BtFloat j = point2.y - point1.y;
BtFloat k = point2.z - point1.z;
BtFloat n_t = -(a * point1.x + b * point1.y + c * point1.z + d);
BtFloat d_t = (a * i + b * j + c * k);
if( !d_t && n_t )
return BtFalse;
if( !d_t && !n_t )
return BtFalse;
BtFloat t = n_t / d_t;
// Check the intersection happens in the line's segment
if( t > 1.0f )
return BtFalse;
if( t < 0.0f )
return BtFalse;
intersection = MtVector3 ( point1.x + i * t, point1.y + j * t, point1.z + k * t );
// is this point inside the triangle
MtVector3 v0 = triangle.a;
MtVector3 v1 = triangle.b;
MtVector3 v2 = triangle.c;
MtVector3 ParPolyv0 = v0 + plane.m_v3Normal;
MtVector3 ParPolyv1 = v1 + plane.m_v3Normal;
MtTriangle edge_poly1 = MtTriangle( v0, ParPolyv0, v1 );
edge_poly1.FindNormal();
MtPlane plane1 = MtPlane( &edge_poly1 );
if( plane1.DistanceTo( intersection ) < 0 )
return BtFalse;
MtTriangle edge_poly2 = MtTriangle( v0, v2, ParPolyv0 );
edge_poly2.FindNormal();
MtPlane plane2 = MtPlane( &edge_poly2 );
if( plane2.DistanceTo( intersection ) < 0 )
return BtFalse;
MtTriangle edge_poly3 = MtTriangle( v1, ParPolyv1, v2 );
edge_poly3.FindNormal();
MtPlane plane3 = MtPlane( &edge_poly3 );
if( plane3.DistanceTo( intersection ) < 0 )
return BtFalse;
return BtTrue;
}
BtBool MtLine::CollideWithPlane(const MtPlane &plane, MtVector3 &intersection)
{
// Calculate the intersection
BtFloat a = plane.m_v3Normal.x;
BtFloat b = plane.m_v3Normal.y;
BtFloat c = plane.m_v3Normal.z;
BtFloat d = plane.m_fDistance;
BtFloat i = point2.x - point1.x;
BtFloat j = point2.y - point1.y;
BtFloat k = point2.z - point1.z;
BtFloat n_t = -(a * point1.x + b * point1.y + c * point1.z + d);
BtFloat d_t = (a * i + b * j + c * k);
if( !d_t && n_t )
return BtFalse;
if( !d_t && !n_t )
return BtFalse;
BtFloat t = n_t / d_t;
// Check the intersection happens in the line's segment
if( t > 1.0f )
return BtFalse;
if( t < 0.0f )
return BtFalse;
intersection = MtVector3 ( point1.x + i * t, point1.y + j * t, point1.z + k * t );
return BtTrue;
}
int CheckTriClockDir( MtVector2 pt1, MtVector2 pt2, MtVector2 pt3)
{
const BtU32 CLOCKWISE = -1;
const BtU32 COUNTER_CLOCKWISE = 1;
const BtU32 LINE = 0;
float test;
test = (((pt2.x - pt1.x)*(pt3.y - pt1.y)) - ((pt3.x - pt1.x)*(pt2.y - pt1.y)));
if (test > 0) return COUNTER_CLOCKWISE;
else if(test < 0) return CLOCKWISE;
else return LINE;
}
////////////////////////////////////////////////////////////////////////////////
// Intersects
BtBool MtLine::Intersects( MtVector2 l1p1, MtVector2 l1p2, MtVector2 l2p1, MtVector2 l2p2)
{
BtU32 test1_a, test1_b, test2_a, test2_b;
test1_a = CheckTriClockDir(l1p1, l1p2, l2p1);
test1_b = CheckTriClockDir(l1p1, l1p2, l2p2);
if( test1_a != test1_b )
{
test2_a = CheckTriClockDir(l2p1, l2p2, l1p1);
test2_b = CheckTriClockDir(l2p1, l2p2, l1p2);
if (test2_a != test2_b)
{
return BtTrue;
}
}
return BtFalse;
}
////////////////////////////////////////////////////////////////////////////////
// IntersectLineCircle
BtBool MtLine::IntersectLineCircle( const MtVector2& c, // center
BtFloat r, // radius
MtLine& line ) // line
{
MtVector2 dir = line.point2 - line.point1;
MtVector2 diff = c - line.point1;
BtFloat t = MtVector2::DotProduct( diff, dir ) / MtVector2::DotProduct( dir, dir );
if(t < 0.0f )
{
t = 0.0f;
}
if( t > 1.0f )
{
t = 1.0f;
}
MtVector2 closest = MtVector2( line.point1 ) + ( dir * t );
MtVector2 d = c - closest;
float distsqr = MtVector2::DotProduct( d, d );
return distsqr <= r * r;
}
| [
"gavin@baawolf.com"
] | gavin@baawolf.com |
d91f47c73a160e30c13bf129b2301e9e926ca462 | 50e034f663391b9832f55e1a9f5fa21d56c3c185 | /third-party/Empirical/include/emp/web/js_utils.hpp | 21b26d1d261e6da376d18f065b0030cfe63d06f2 | [
"MIT"
] | permissive | koellingh/empirical-p53-simulator | 0a269ab35d723b5f98e329a99f04fab9af22a934 | aa6232f661e8fc65852ab6d3e809339557af521b | refs/heads/master | 2023-03-15T08:08:27.135458 | 2021-03-15T22:43:13 | 2021-03-15T22:43:13 | 338,420,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,595 | hpp | /**
* @note This file is part of Empirical, https://github.com/devosoft/Empirical
* @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md
* @date 2015-2018
*
* @file js_utils.hpp
* @brief Tools for passing data between C++ and Javascript.
*/
#ifndef EMP_JS_UTILS_H
#define EMP_JS_UTILS_H
#include <map>
#include <string>
#include <typeinfo>
#include "../base/assert.hpp"
#include "../base/vector.hpp"
#include "../base/array.hpp"
#include "../base/map.hpp"
#include "init.hpp"
namespace emp {
/// This function returns a std::map mapping typeid names to the appropriate
/// strings to describe those types in Javscript. This is useful when using
/// getValue() from within MAIN_THREAD_EM_ASM macros.
///
/// For example, say we have a templated function that takes a pointer to type
/// T. We find out the appropriate string for type T:
/// std::map<const char*, std::string> type_map = GetTypeToStringMap();
/// std::string type_string = type_map[typeid(T).name()];
///
/// Now we can pass type_string.c_str() into MAIN_THREAD_EM_ASM:
/// `MAIN_THREAD_EM_ASM({
/// var value = getValue($0, $1);
/// }, pointer, type_string.c_str();`
std::map<std::string, std::string> get_type_to_string_map() {
// Using typeid().name() could create problems because it varies by
// implementation. All that matters is consistency, but obscure could
// technically be given the same name. So far it seems to not be an issue
// with Emscripten, which is most critical for this code.
std::map<std::string, std::string> map_type_names;
map_type_names[typeid(int8_t).name()] = "i8";
map_type_names[typeid(int16_t).name()] = "i16";
map_type_names[typeid(int32_t).name()] = "i32";
map_type_names[typeid(int64_t).name()] = "i64";
map_type_names[typeid(float).name()] = "float";
map_type_names[typeid(double).name()] = "double";
map_type_names[typeid(int8_t*).name()] = "i8*";
map_type_names[typeid(int16_t*).name()] = "i16*";
map_type_names[typeid(int32_t*).name()] = "i32*";
map_type_names[typeid(int64_t*).name()] = "i64*";
map_type_names[typeid(float*).name()] = "float*";
map_type_names[typeid(double*).name()] = "double*";
map_type_names[typeid(void*).name()] = "*";
map_type_names[typeid(std::string).name()] = "string";
return map_type_names;
}
/// This function can be called to pass an array, vector, or other container with contiguously
/// stored data into Javascript.
/// The array will be stored in emp.__incoming_array. Currently supports
/// arrays containing all of the types defined in get_type_to_string_map, which
/// are also all of the types that emscripten supports getting via pointer.
/// This function also supports nested arrays, and arrays of objects created with
/// introspective tuple structs.
/// @cond TEMPLATES
// This code now works for all containers, as long as they store data contiguously
template<typename C, class = typename C::value_type>
typename std::enable_if<std::is_pod<typename C::value_type>::value, void>::type
pass_array_to_javascript(C values, emp::vector<int> recursive_el)
{
using T = typename C::value_type;
//Figure out what string to use for the type we've been given
std::map<std::string, std::string> map_type_names = get_type_to_string_map();
emp_assert((map_type_names.find(typeid(T).name()) != map_type_names.end()));
int type_size = sizeof(T);
(void) type_size;
std::string type_string = map_type_names[typeid(T).name()];
// Clear array, if this isn't a recursive call
if (recursive_el.size() == 0) {
MAIN_THREAD_EM_ASM({emp_i.__incoming_array = [];});
}
MAIN_THREAD_EM_ASM({
var curr_array = emp_i.__incoming_array;
var depth = 0;
// Make sure that we're at the right depth, in case of recursive call.
while (curr_array.length > 0) {
var next_index = getValue($4+(depth*4), "i32");
depth += 1;
curr_array = curr_array[next_index];
}
// Iterate over array, get values, and add them to incoming array.
for (i=0; i<$1; i++) {
curr_array.push(getValue($0+(i*$2), UTF8ToString($3)));
}
}, &values[0], values.size(), type_size, type_string.c_str(), recursive_el.data());
}
// Specialization for strings
template<typename C, class = typename C::value_type>
typename std::enable_if<std::is_same<typename C::value_type, std::string>::value, void>::type
pass_array_to_javascript(C values, emp::vector<int> recursive_el)
{
// Clear array, if this isn't a recursive call
if (recursive_el.size() == 0) {
MAIN_THREAD_EM_ASM({emp_i.__incoming_array = [];});
};
MAIN_THREAD_EM_ASM({
emp_i.__curr_array = emp_i.__incoming_array;
var depth = 0;
// Make sure that we are at the right depth, in case of recursive call.
while (emp_i.__curr_array.length > 0) {
var next_index = getValue($0+(depth*4), "i32");
depth += 1;
emp_i.__curr_array = emp_i.__curr_array[next_index];
};
}, recursive_el.data());
// Iterate over array, get values, and add them to incoming array.
for (auto val : values) {
(void) val;
MAIN_THREAD_EM_ASM({
emp_i.__curr_array.push(UTF8ToString($0));
}, val.c_str());
};
MAIN_THREAD_EM_ASM({delete emp_i.__curr_array;});
}
// Handle user-defined JSON_TYPE
template<typename C, class = typename C::value_type>
typename std::enable_if<C::value_type::n_fields != -1, void>::type
pass_array_to_javascript(C values, emp::vector<int> recursive_el) {
std::map<std::string, std::string> map_type_names = get_type_to_string_map();
// Initialize array in Javascript
if (recursive_el.size() == 0) {
MAIN_THREAD_EM_ASM({emp_i.__incoming_array = [];});
}
// Initialize objects in Javascript
MAIN_THREAD_EM_ASM({
var curr_array = emp_i.__incoming_array;
var depth = 0;
// Make sure that we're at the right depth, in case of recursive call.
while (curr_array.length > 0) {
var next_index = getValue($1+(depth*4), "i32");
depth += 1;
curr_array = curr_array[next_index];
}
// Append empty objects
for (i=0; i<$0; i++) {
var new_obj = {};
curr_array.push(new_obj);
}
}, values.size(), recursive_el.data());
for (std::size_t j = 0; j<values.size(); j++) { // Iterate over array
for (std::size_t i = 0; i<values[j].var_names.size(); i++) { // Iterate over object members
// Get variable name and type for this member variable
std::string var_name = values[j].var_names[i];
std::string type_string = map_type_names[values[j].var_types[i].name()];
// Make sure member variable is an allowed type
emp_assert((map_type_names.find(values[j].var_types[i].name())
!= map_type_names.end()), values[j].var_types[i].name());
// Load data into array of objects
MAIN_THREAD_EM_ASM({
var curr_array = emp_i.__incoming_array;
var depth = 0;
// Make sure we are at the right depth, in case of recursive call.
while (curr_array[0].length > 0) {
var next_index = getValue($4+(depth*4), "i32");
depth += 1;
curr_array = curr_array[next_index];
}
if (UTF8ToString($1) == "string") {
curr_array[$3][UTF8ToString($2)] = UTF8ToString($0);
} else {
curr_array[$3][UTF8ToString($2)] = getValue($0, UTF8ToString($1));
}
}, values[j].pointers[i], type_string.c_str(), var_name.c_str(),
j, recursive_el.data());
}
}
}
/// @endcond
// This version of the function handles non-nested containers
template<typename C, class = typename C::value_type>
void pass_array_to_javascript(C values) {
pass_array_to_javascript(values, emp::vector<int>(0));
}
/// @cond TEMPLATES
// This version of the function handles nested arrays with recursive calls
// until a non-array type is found.
template<std::size_t SIZE1, std::size_t SIZE2, typename T>
void pass_array_to_javascript(emp::array<emp::array<T, SIZE1>, SIZE2> values,
emp::vector<int> recursive_el = emp::vector<int>()) {
// Initialize if this is the first call to this function
if (recursive_el.size() == 0) {
MAIN_THREAD_EM_ASM({emp_i.__incoming_array = [];});
}
// Append empty arrays to array that we are currently handling in recursion
MAIN_THREAD_EM_ASM({
var curr_array = emp_i.__incoming_array;
var depth = 0;
while (curr_array.length > 0) {
var next_index = getValue($0+(depth*4), "i32");
depth += 1;
curr_array = curr_array[next_index];
}
for (i=0; i<$1; i++) {
curr_array.push([]);
}
}, recursive_el.data(), values.size());
// Make recursive calls - recursive_els specifies coordinates of array we're
// currently operating on
for (std::size_t i = 0; i<values.size(); i++) {
emp::vector<int> new_recursive_el (recursive_el);
new_recursive_el.push_back((int) i);
pass_array_to_javascript(values[i], new_recursive_el);
}
}
// This version of the function handles nested vectors with recursive calls
// until a non-array type is found.
template<typename T>
void pass_array_to_javascript(emp::vector<emp::vector<T> > values,
emp::vector<int> recursive_el = emp::vector<int>()) {
// Initialize if this is the first call to this function
if (recursive_el.size() == 0) {
MAIN_THREAD_EM_ASM({emp_i.__incoming_array = [];});
}
// Append empty arrays to array that we are currently handling in recursion
MAIN_THREAD_EM_ASM({
var curr_array = emp_i.__incoming_array;
var depth = 0;
while (curr_array.length > 0) {
var next_index = getValue($0+(depth*4), "i32");
depth += 1;
curr_array = curr_array[next_index];
}
for (i=0; i<$1; i++) {
curr_array.push([]);
}
}, recursive_el.data(), values.size());
// Make recursive calls - recursive_els specifies coordinates of array we are
// currently operating on
for (std::size_t i = 0; i<values.size(); i++) {
emp::vector<int> new_recursive_el (recursive_el);
new_recursive_el.push_back((int) i);
pass_array_to_javascript(values[i], new_recursive_el);
}
}
/// @endcond
/// This function lets you pass an array from javascript to C++!
/// It takes a reference to the array as an argument and populates it
/// with the contents of emp.__outgoing_array.
///
/// Currently accepts arrays of ints, floats, doubles, chars, and std::strings
/// The size of the passed array must be equal to the size of the array stored
/// in emp.__outgoing_array
//
// Don't worry about the recurse argument - it's for handling nested arrays
// internally
template <std::size_t SIZE, typename T>
void pass_array_to_cpp(emp::array<T, SIZE> & arr, bool recurse = false) {
//Figure out type stuff
std::map<std::string, std::string> map_type_names = get_type_to_string_map();
emp_assert((map_type_names.find(typeid(T).name()) != map_type_names.end()), typeid(T).name());
int type_size = sizeof(T);
(void) type_size;
std::string type_string = map_type_names[typeid(T).name()];
//Make sure arrays have the same length
emp_assert(arr.size() == MAIN_THREAD_EM_ASM_INT({return emp_i.__outgoing_array.length}),
arr.size(), MAIN_THREAD_EM_ASM_INT({return emp_i.__outgoing_array.length}));
//Write emp.__outgoing_array contents to a buffer
T * buffer = (T*) MAIN_THREAD_EM_ASM_INT({
var buffer = Module._malloc(emp_i.__outgoing_array.length*$0);
for (i=0; i<emp_i.__outgoing_array.length; i++) {
setValue(buffer+(i*$0), emp_i.__outgoing_array[i], UTF8ToString($1));
}
return buffer;
}, type_size, type_string.c_str());
// Populate array from buffer
for (std::size_t i=0; i<arr.size(); i++) {
arr[i] = *(buffer + i);
}
// Free the memory we allocated in Javascript
free(buffer);
}
/// Same as pass_array_to_cpp, but lets you store values in a vector instead
template <typename T>
void pass_vector_to_cpp(emp::vector<T> & arr, bool recurse = false) {
// Figure out type stuff
std::map<std::string, std::string> map_type_names = get_type_to_string_map();
emp_assert((map_type_names.find(typeid(T).name()) != map_type_names.end()), typeid(T).name());
int type_size = sizeof(T);
(void) type_size;
std::string type_string = map_type_names[typeid(T).name()];
// Write emp.__outgoing_array contents to a buffer
T * buffer = (T*) MAIN_THREAD_EM_ASM_INT({
var buffer = Module._malloc(emp_i.__outgoing_array.length*$0);
for (i=0; i<emp_i.__outgoing_array.length; i++) {
setValue(buffer+(i*$0), emp_i.__outgoing_array[i], UTF8ToString($1));
}
return buffer;
}, type_size, type_string.c_str());
// Populate array from buffer
for (int i=0; i < MAIN_THREAD_EM_ASM_INT({return emp_i.__outgoing_array.length}); i++) {
arr.push_back(*(buffer + i));
}
//Free the memory we allocated in Javascript
free(buffer);
}
/// @cond TEMPLATES
// template <typename T>
// typename std::enable_if<C::value_type::n_fields != -1, void>::type
// pass_vector_to_cpp(emp::vector<T> & arr, bool recurse = false) {
//
// // Figure out type stuff
// std::map<std::string, std::string> map_type_names = get_type_to_string_map();
// emp_assert((map_type_names.find(typeid(T).name()) != map_type_names.end()), typeid(T).name());
// int type_size = sizeof(T);
// (void) type_size;
// std::string type_string = map_type_names[typeid(T).name()];
//
// // Write emp.__outgoing_array contents to a buffer
// T * buffer = (T*) MAIN_THREAD_EM_ASM_INT({
// var buffer = Module._malloc(emp_i.__outgoing_array.length*$0);
//
// for (i=0; i<emp_i.__outgoing_array.length; i++) {
// setValue(buffer+(i*$0), emp_i.__outgoing_array[i], UTF8ToString($1));
// }
//
// return buffer;
// }, type_size, type_string.c_str());
//
// // Populate array from buffer
// for (int i=0; i < MAIN_THREAD_EM_ASM_INT({return emp_i.__outgoing_array.length}); i++) {
// arr.push_back(*(buffer + i));
// }
//
// //Free the memory we allocated in Javascript
// free(buffer);
// }
// Chars aren't one of the types supported by setValue, but by treating them
// as strings in Javascript we can pass them out to a C++ array
template <std::size_t SIZE>
void pass_array_to_cpp(emp::array<char, SIZE> & arr, bool recurse = false) {
emp_assert(arr.size() == MAIN_THREAD_EM_ASM_INT({return emp_i.__outgoing_array.length}));
char * buffer = (char *) MAIN_THREAD_EM_ASM_INT({
// Since we're treating each char as it's own string, each one
// will be null-termianted. So we malloc length*2 addresses.
var new_length = emp_i.__outgoing_array.length*2;
var buffer = Module._malloc(new_length);
for (i=0; i<emp_i.__outgoing_array.length; i++) {
stringToUTF8(emp_i.__outgoing_array[i], buffer+(i*2),2);
}
return buffer;
});
for (size_t i=0; i<arr.size(); i++) {
arr[i] = *(buffer + i*2);
}
free(buffer);
}
// Chars aren't one of the types supported by setValue, but by treating them
// as strings in Javascript we can pass them out to a C++ array
void pass_vector_to_cpp(emp::vector<char> & arr, bool recurse = false) {
char * buffer = (char *) MAIN_THREAD_EM_ASM_INT({
// Since we're treating each char as it's own string, each one
// will be null-termianted. So we malloc length*2 addresses.
var buffer = Module._malloc(emp_i.__outgoing_array.length*2);
for (i=0; i<emp_i.__outgoing_array.length; i++) {
stringToUTF8(emp_i.__outgoing_array[i], buffer+(i*2),2);
}
return buffer;
});
for (int i=0; i<MAIN_THREAD_EM_ASM_INT({return emp_i.__outgoing_array.length}); i++) {
arr.push_back(*(buffer + i*2));
}
free(buffer);
}
// We can handle strings in a similar way
template <std::size_t SIZE>
void pass_array_to_cpp(emp::array<std::string, SIZE> & arr, bool recurse = false) {
emp_assert(arr.size() == MAIN_THREAD_EM_ASM_INT({return emp_i.__outgoing_array.length}));
char * buffer = (char *) MAIN_THREAD_EM_ASM_INT({
// Figure how much memory to allocate
var arr_size = 0;
for (i=0; i<emp_i.__outgoing_array.length; i++) {
arr_size += emp_i.__outgoing_array[i].length + 1;
}
var buffer = Module._malloc(arr_size);
// Track place in memory to write too
var cumulative_size = 0;
var cur_length = 0;
for (i=0; i<emp_i.__outgoing_array.length; i++) {
cur_length = emp_i.__outgoing_array[i].length + 1;
stringToUTF8(emp_i.__outgoing_array[i], buffer + (cumulative_size), cur_length);
cumulative_size += cur_length;
}
return buffer;
});
// Track place in memory to read from
int cumulative_size = 0;
for (size_t i=0; i<arr.size(); i++) {
// Since std::string constructor reads to null terminator, this just works.
arr[i] = std::string(buffer + cumulative_size);
cumulative_size += arr[i].size() + 1;
}
free(buffer);
}
// We can handle strings in a similar way
void pass_vector_to_cpp(emp::vector<std::string> & arr, bool recurse = false) {
char * buffer = (char *) MAIN_THREAD_EM_ASM_INT({
// Figure how much memory to allocate
var arr_size = 0;
for (i=0; i<emp_i.__outgoing_array.length; i++) {
arr_size += emp_i.__outgoing_array[i].length + 1;
}
var buffer = Module._malloc(arr_size);
// Track place in memory to write too
var cumulative_size = 0;
var cur_length = 0;
for (i=0; i<emp_i.__outgoing_array.length; i++) {
cur_length = emp_i.__outgoing_array[i].length + 1;
stringToUTF8(emp_i.__outgoing_array[i], buffer + (cumulative_size), cur_length);
cumulative_size += cur_length;
}
return buffer;
});
// Track place in memory to read from
int cumulative_size = 0;
for (int i=0; i<MAIN_THREAD_EM_ASM_INT({return emp_i.__outgoing_array.length}); i++) {
// Since std::string constructor reads to null terminator, this just works.
arr.push_back(std::string(buffer + cumulative_size));
cumulative_size += arr[(size_t)i].size() + 1;
}
free(buffer);
}
// We can handle nested arrays through recursive calls on chunks of them
template <std::size_t SIZE, std::size_t SIZE2, typename T>
void pass_array_to_cpp(emp::array<emp::array<T, SIZE2>, SIZE> & arr, bool recurse = false) {
emp_assert(arr.size() == MAIN_THREAD_EM_ASM_INT({return emp_i.__outgoing_array.length}));
// Create temp array to hold whole array while pieces are passed in
if (recurse == 0) {
MAIN_THREAD_EM_ASM({emp_i.__temp_array = [emp_i.__outgoing_array];});
} else {
// This is a little wasteful of space, but the alternatives are
// surprisingly ugly
MAIN_THREAD_EM_ASM({emp_i.__temp_array.push(emp_i.__outgoing_array);});
}
for (size_t i = 0; i < arr.size(); i++) {
MAIN_THREAD_EM_ASM({
emp_i.__outgoing_array = emp_i.__temp_array[emp_i.__temp_array.length - 1][$0];
}, i);
pass_array_to_cpp(arr[i], true);
}
// Clear temp array
if (recurse == 0) { MAIN_THREAD_EM_ASM({emp_i.__temp_array = [];}); }
else { MAIN_THREAD_EM_ASM({emp_i.__temp_array.pop();}); }
}
/// We can handle nested arrays through recursive calls on chunks of them
template <typename T>
void pass_vector_to_cpp(emp::vector<emp::vector<T> > & arr, bool recurse = false) {
// Create temp array to hold whole array while pieces are passed in
int size = MAIN_THREAD_EM_ASM_INT({return emp_i.__outgoing_array.length});
if (recurse == 0) {
MAIN_THREAD_EM_ASM({
emp_i.__temp_array = [emp_i.__outgoing_array];
});
} else {
// This is a little wasteful of space, but the alternatives are
// surprisingly ugly
MAIN_THREAD_EM_ASM({emp_i.__temp_array.push(emp_i.__outgoing_array);});
}
for (int i = 0; i < size; i++) {
MAIN_THREAD_EM_ASM({
emp_i.__outgoing_array = emp_i.__temp_array[emp_i.__temp_array.length - 1][$0];
}, i);
while ((int)arr.size() <= i) {
arr.push_back(emp::vector<T>());
}
pass_vector_to_cpp(arr[i], true);
}
// Clear temp array
if (recurse == 0) {
MAIN_THREAD_EM_ASM({emp_i.__temp_array = [];});
} else {
MAIN_THREAD_EM_ASM({emp_i.__temp_array.pop();});
}
}
/// @endcond
/// This function can be called to pass a map into JavaScript.
/// The resulting JavaScript object will be stored in emp.__incoming_map.
/// @param dict the map being passed into JavaScript
template <typename KEY_T, typename VAL_T>
void pass_map_to_javascript(const emp::map<KEY_T, VAL_T> & dict) {
emp::vector<KEY_T> keys;
emp::vector<VAL_T> values;
// extract keys and values from dict
for (typename std::map<KEY_T, VAL_T>::const_iterator it = dict.begin(); it != dict.end(); ++it) {
keys.push_back(it->first);
values.push_back(it->second);
}
// pass in extracted keys vector to JS
emp::pass_array_to_javascript(keys);
MAIN_THREAD_EM_ASM({
emp_i.__incoming_map_keys = emp_i.__incoming_array;
});
// check to make sure each key is not an object or a function
emp_assert(
MAIN_THREAD_EM_ASM_INT({
emp_i.__incoming_map_keys.forEach(function(key) {
if (typeof key === "object" || typeof key === "function") { return 0; }
});
return 1;
}), "Keys cannot be an object or a function");
// pass in extracted values vector to JS
emp::pass_array_to_javascript(values);
MAIN_THREAD_EM_ASM({
emp_i.__incoming_map_values = emp_i.__incoming_array;
// create dictionary
emp_i.__incoming_map = ( {} );
emp_i.__incoming_map_keys.forEach(function(key, val) {
emp_i.__incoming_map[key] = emp_i.__incoming_map_values[val]
});
// clean up unneeded vars
delete emp_i.__incoming_map_keys;
delete emp_i.__incoming_map_values;
});
}
/// This function can be called to pass two arrays of the same length into JavaScript (where a map is then created)
/// One array should hold keys, and the other should hold values
/// (note that the key-value pairs must line up across the arrays)
/// The resulting JavaScript object will be stored in emp.__incoming_map.
/// @param keys an array holding the keys to the map
/// @param values an array holding the values to the map
template <typename KEY_T, typename VAL_T, size_t SIZE>
void pass_map_to_javascript(const emp::array<KEY_T, SIZE> & keys, const emp::array<VAL_T, SIZE> & values) {
// pass in keys vector to JS
emp::pass_array_to_javascript(keys);
MAIN_THREAD_EM_ASM({
emp_i.__incoming_map_keys = emp_i.__incoming_array;
});
// check to make sure each key is not an object or a function
emp_assert(
MAIN_THREAD_EM_ASM_INT({
emp_i.__incoming_map_keys.forEach(function(key) {
if (typeof key === "object" || typeof key === "function") { return 0; }
});
return 1;
}), "Keys cannot be an object or a function");
// pass in values vector to JS
emp::pass_array_to_javascript(values);
MAIN_THREAD_EM_ASM({
emp_i.__incoming_map_values = emp_i.__incoming_array;
// create dictionary
emp_i.__incoming_map = ( {} );
emp_i.__incoming_map_keys.forEach(function(key, val) {
emp_i.__incoming_map[key] = emp_i.__incoming_map_values[val]
});
// clean up unneeded vars
delete emp_i.__incoming_map_keys;
delete emp_i.__incoming_map_values;
});
}
/// Helper function that returns DOM view port size in pixels.
int GetViewPortSize() {
return MAIN_THREAD_EM_ASM_INT({
return Math.min(
Math.max(
document.documentElement.clientWidth,
$(window).width(),
window.innerWidth || 0
),
Math.max(
document.documentElement.clientHeight,
$(window).height(),
window.innerHeight || 0
)
);
});
}
}
#endif
| [
"koellingh@carleton.edu"
] | koellingh@carleton.edu |
adb0ff5b6d93bf4ad519597d3f2c38504a6b2e20 | 0995c448ad10f024371a99c5a5b872919b586a48 | /Codeforces/Codeforces Round 532 Div 2/d.cpp | 3c1b7e870233710cb09bfd339609e5c33c210b0b | [] | no_license | ChrisMaxheart/Competitive-Programming | fe9ebb079f30f34086ec97efdda2967c5e7c7fe0 | 2c749a3bc87a494da198f2f81f975034a8296f32 | refs/heads/master | 2021-06-14T13:48:39.671292 | 2021-03-27T10:34:46 | 2021-03-27T10:34:46 | 179,540,634 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,956 | cpp | #include <bits/stdc++.h>
using namespace std;
// to minimize
// defines
const double PI = acos(-1);
#define INF 1E9
#define endl '\n'
#define Tloop int T; cin >> T; for(int count_ = 1; count_ < T+1; count_++)
#define Nloop int N; cin >> N; for(int count__ = 0; count__ < N; count__++)
#define printcaseg cout << "Case #" << count_ << ": "
#define printcaseu cout << "Case " << count_ << ": "
#define MOD 1000000007
#define LSOne(S) ((S)&(-S))
#define pb push_back
#define fi first
#define se second
#define eb emplace_back
#define mp make_pair
// A lot of typedefs
typedef long long ll;
typedef unsigned long long ull;
typedef stack<int> si;
typedef stack<long long> sll;
typedef stack<string> ss;
typedef stack<double> sd;
typedef queue<int> qi;
typedef queue<long long> qll;
typedef queue<string> qs;
typedef queue<double> qd;
typedef deque<int> di;
typedef deque<long long> dll;
typedef deque<string> ds;
typedef deque<double> dd;
typedef priority_queue<int> pqi;
typedef priority_queue<long long> pqll;
typedef priority_queue<string> pqs;
typedef priority_queue<double> pqd;
typedef priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pqdijk;
typedef set<int> seti;
typedef set<long long> setll;
typedef set<string> sets;
typedef set<double> setd;
typedef unordered_set<int> useti;
typedef unordered_set<long long> usetll;
typedef unordered_set<string> usets;
typedef unordered_set<double> usetd;
typedef map<int, string> mapis;
typedef map<string, int> mapsi;
typedef map<long long, string> maplls;
typedef map<string, long long> mapsll;
typedef map<int, int> mapii;
typedef map<string, string> mapss;
typedef map<long long, long long> mapllll;
typedef map<long long, double> maplld;
typedef map<double, long long> mapdll;
typedef map<string, double> mapsd;
typedef map<double, string> mapds;
typedef map<int, double> mapid;
typedef map<double, int> mapdi;
typedef unordered_map<int, string> umapis;
typedef unordered_map<string, int> umapsi;
typedef unordered_map<long long, string> umaplls;
typedef unordered_map<string, long long> umapsll;
typedef unordered_map<int, int> umapii;
typedef unordered_map<string, string> umapss;
typedef unordered_map<long long, long long> umapllll;
typedef unordered_map<long long, double> umaplld;
typedef unordered_map<double, long long> umapdll;
typedef unordered_map<string, double> umapsd;
typedef unordered_map<double, string> umapds;
typedef unordered_map<int, double> umapid;
typedef unordered_map<double, int> umapdi;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<vector<pair<int,int>>> vwAL;
typedef vector<vector<int>> vAL;
typedef pair<int, int> pii;
typedef pair<int, string> pis;
typedef pair<long long, long long> pllll;
typedef pair<long long, string> plls;
typedef pair<double, string> pds;
typedef pair<double, double> pdd;
typedef pair<double, int> pdi;
typedef pair<double, long long> pdll;
// struct
struct mystruct {
int counter;
};
//custom hashing
struct custom_hash {
inline std::size_t operator()(const std::pair<int,int> & v) const {
return v.first*31+v.second*7;
}
};
// pq/set custom comparator, will get reversed
class mycomp {
public:
bool operator() (mystruct a, mystruct b) {
return a.counter > b.counter;
}
};
// sort custom comparator
bool customcompare(mystruct a, mystruct b) {
return a.counter > b.counter;
}
map<int, umapii> AL;
map<pii, int> dct;
int curr = -1;
vi ans;
vi visited;
useti temp;
void dfs(int n, vi hist) {
visited[n] = 1;
for (auto x : AL[n]) {
if (!visited[x.fi]) {
if(x.se != 0) {
vi hist2 = hist;
hist2.pb(x.fi);
dfs(x.fi, hist2);
}
} else if (visited[x.fi] == 1) {
int memo = -1;
vi hist2 = hist;
hist2.pb(x.fi);
for (auto x : hist2) {
cout << x << " ";
}
cout << endl;
int mini = 1000000000;
for (int i = 0; i < hist2.size()-1; i++) {
if (mini > AL[hist2[i]][hist2[i+1]]) {
memo = dct[mp(hist2[i],hist2[i+1])];
mini = min(mini, AL[hist2[i]][hist2[i+1]]);
}
}
if (temp.find(memo) != temp.end()) {
continue;
}
temp.insert(memo);
curr = max(curr, mini);
ans.pb(memo);
}
}
visited[n] = 2;
return;
}
int main ()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int v, e;
cin >> v >> e;
for (int i = 0; i < v; i++) {
visited.pb(0);
}
for (int i = 0; i < e; i++) {
int a, b, c;
cin >> a >> b >> c;
dct[mp(a, b)] = i+1;
AL[a][b] = c;
}
for (int i = 0; i < v; i++) {
if (!visited[i]) {
vi emp;
emp.pb(i);
dfs(i, emp);
}
}
cout << curr << " " << ans.size() << endl;
for (auto x : ans) {
cout << x << " ";
} cout << endl;
return 0;
} | [
"samuelhenrykurniawan@yahoo.com"
] | samuelhenrykurniawan@yahoo.com |
7c1384dc17ac2d40261ce838dd98e3f54641ef8e | 5a55209ad40c6f20b8e588ec2c0f731a22d81b06 | /atcoder/abc205/B.cpp | db9042f98794d37a6888717a8d385f079f134029 | [] | no_license | nabil0day/Problem-Solving | f5a5509d746a263cca02dd4af779e6ffa2ee8732 | a2e65bcf958d3bfe9d309575ae31358024785855 | refs/heads/master | 2023-08-19T20:22:11.133469 | 2021-10-22T14:47:00 | 2021-10-24T07:36:26 | 399,927,072 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 410 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int n,ans=0;
cin>>n;
vector<int> a(n);
int b[n];
for(int i=0;i<n;i++){
cin>>a[i];
b[i]=(i+1);
}
sort(a.begin(),a.end());
for(int i=0;i<n;i++){
if(a[i]!=b[i]){
ans+=1;
}
}
if(ans>=1){
cout<<"No"<<endl;
}else{
cout<<"Yes"<<endl;
}
return(0);
} | [
"hadiurrahmannabil@gmail.com"
] | hadiurrahmannabil@gmail.com |
45776bf3b0bf55f0dea190c0f36cc3c7c0c23801 | c2bce3eb1777c1d63d98bb3ffb6d972a02470714 | /Source/Core/MessageHandler.hpp | 76d4e94096c2c001f20dbf5ff036cfad23b318c3 | [] | no_license | adamwych/PlainMQ | 389a2c27ea9799eefc98be690bef92b616812080 | 821d12696bce4ab4592a61a1bd44c0cf7ae712e0 | refs/heads/master | 2023-02-16T18:40:21.750498 | 2021-01-20T20:09:30 | 2021-01-20T20:09:30 | 331,418,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 522 | hpp | #pragma once
#include "../Common.hpp"
namespace PlainMQ {
class Server;
class Client;
class Command;
class MessageHandler {
public:
MessageHandler(Server* server);
/**
* Acts on a message.
* @param client Client, that sent the message.
* @param payload The message.
*/
void OnMessage(Client* client, const std::string& payload);
private:
Command* GetCommandHandler(std::string commandName);
Server* server;
};
} | [
"shoolygl@gmail.com"
] | shoolygl@gmail.com |
5fd7155f637c4a8b50808a4a667c960af20565f9 | 7dd9e33dd493d7d36c39550d1330e2523d445800 | /MapMaker/indexwidget.h | e713e3289fddf36e4fc02d8012a09abb16a788a5 | [] | no_license | timo-e/MobileMaps | ac012d0fd40477b29eb5f559179cc996c3376987 | b6be54cb2a1fd301c60489006cb3b2f365ff8787 | refs/heads/master | 2016-09-06T01:39:02.419352 | 2011-01-01T15:42:47 | 2011-01-01T15:42:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 642 | h | #pragma once
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QLineEdit>
class IndexView : public QGraphicsView
{
Q_OBJECT
public:
IndexView(QWidget* parent = 0);
void setImage(const QImage& im);
void load(const QList<QPair<QString, QPointF> >& pts); // The points should be from (0, 0) at the bottom left to (1, 1) at the top right.
QList<QPair<QString, QPointF> > save() const;
protected:
void wheelEvent(QWheelEvent* e);
void mousePressEvent(QMouseEvent* e);
void contextMenuEvent(QContextMenuEvent* e);
void keyPressEvent(QKeyEvent* e);
private:
QGraphicsScene* scene;
QGraphicsPixmapItem* background;
};
| [
"timo@foo.(none)"
] | timo@foo.(none) |
9a06d5043ec47418eaf83118149a1251e7a4e956 | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_1/ISA2+poonceonce+poonceonce+poacquireacquire.c.cbmc.cpp | f41f696889d9be681e2eb7fc98488fc4caa317c7 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 42,623 | cpp | // 0:vars:3
// 3:atom_1_X0_1:1
// 4:atom_2_X0_1:1
// 5:atom_2_X2_0:1
// 6:thr0:1
// 7:thr1:1
// 8:thr2:1
#define ADDRSIZE 9
#define NPROC 4
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
__LOCALS__
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
buff(0,6) = 0;
pw(0,6) = 0;
cr(0,6) = 0;
iw(0,6) = 0;
cw(0,6) = 0;
cx(0,6) = 0;
is(0,6) = 0;
cs(0,6) = 0;
crmax(0,6) = 0;
buff(0,7) = 0;
pw(0,7) = 0;
cr(0,7) = 0;
iw(0,7) = 0;
cw(0,7) = 0;
cx(0,7) = 0;
is(0,7) = 0;
cs(0,7) = 0;
crmax(0,7) = 0;
buff(0,8) = 0;
pw(0,8) = 0;
cr(0,8) = 0;
iw(0,8) = 0;
cw(0,8) = 0;
cx(0,8) = 0;
is(0,8) = 0;
cs(0,8) = 0;
crmax(0,8) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
buff(1,6) = 0;
pw(1,6) = 0;
cr(1,6) = 0;
iw(1,6) = 0;
cw(1,6) = 0;
cx(1,6) = 0;
is(1,6) = 0;
cs(1,6) = 0;
crmax(1,6) = 0;
buff(1,7) = 0;
pw(1,7) = 0;
cr(1,7) = 0;
iw(1,7) = 0;
cw(1,7) = 0;
cx(1,7) = 0;
is(1,7) = 0;
cs(1,7) = 0;
crmax(1,7) = 0;
buff(1,8) = 0;
pw(1,8) = 0;
cr(1,8) = 0;
iw(1,8) = 0;
cw(1,8) = 0;
cx(1,8) = 0;
is(1,8) = 0;
cs(1,8) = 0;
crmax(1,8) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
buff(2,6) = 0;
pw(2,6) = 0;
cr(2,6) = 0;
iw(2,6) = 0;
cw(2,6) = 0;
cx(2,6) = 0;
is(2,6) = 0;
cs(2,6) = 0;
crmax(2,6) = 0;
buff(2,7) = 0;
pw(2,7) = 0;
cr(2,7) = 0;
iw(2,7) = 0;
cw(2,7) = 0;
cx(2,7) = 0;
is(2,7) = 0;
cs(2,7) = 0;
crmax(2,7) = 0;
buff(2,8) = 0;
pw(2,8) = 0;
cr(2,8) = 0;
iw(2,8) = 0;
cw(2,8) = 0;
cx(2,8) = 0;
is(2,8) = 0;
cs(2,8) = 0;
crmax(2,8) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
buff(3,4) = 0;
pw(3,4) = 0;
cr(3,4) = 0;
iw(3,4) = 0;
cw(3,4) = 0;
cx(3,4) = 0;
is(3,4) = 0;
cs(3,4) = 0;
crmax(3,4) = 0;
buff(3,5) = 0;
pw(3,5) = 0;
cr(3,5) = 0;
iw(3,5) = 0;
cw(3,5) = 0;
cx(3,5) = 0;
is(3,5) = 0;
cs(3,5) = 0;
crmax(3,5) = 0;
buff(3,6) = 0;
pw(3,6) = 0;
cr(3,6) = 0;
iw(3,6) = 0;
cw(3,6) = 0;
cx(3,6) = 0;
is(3,6) = 0;
cs(3,6) = 0;
crmax(3,6) = 0;
buff(3,7) = 0;
pw(3,7) = 0;
cr(3,7) = 0;
iw(3,7) = 0;
cw(3,7) = 0;
cx(3,7) = 0;
is(3,7) = 0;
cs(3,7) = 0;
crmax(3,7) = 0;
buff(3,8) = 0;
pw(3,8) = 0;
cr(3,8) = 0;
iw(3,8) = 0;
cw(3,8) = 0;
cx(3,8) = 0;
is(3,8) = 0;
cs(3,8) = 0;
crmax(3,8) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(0+2,0) = 0;
mem(3+0,0) = 0;
mem(4+0,0) = 0;
mem(5+0,0) = 0;
mem(6+0,0) = 0;
mem(7+0,0) = 0;
mem(8+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
co(6,0) = 0;
delta(6,0) = -1;
co(7,0) = 0;
delta(7,0) = -1;
co(8,0) = 0;
delta(8,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !37, metadata !DIExpression()), !dbg !46
// br label %label_1, !dbg !47
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !45), !dbg !48
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !38, metadata !DIExpression()), !dbg !49
// call void @llvm.dbg.value(metadata i64 1, metadata !41, metadata !DIExpression()), !dbg !49
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !50
// ST: Guess
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
ASSUME(creturn[1] >= cw(1,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !42, metadata !DIExpression()), !dbg !51
// call void @llvm.dbg.value(metadata i64 1, metadata !44, metadata !DIExpression()), !dbg !51
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !52
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// ret i8* null, !dbg !53
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !56, metadata !DIExpression()), !dbg !70
// br label %label_2, !dbg !53
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !69), !dbg !72
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !59, metadata !DIExpression()), !dbg !73
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !56
// LD: Guess
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
// Update
creg_r0 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r0 = buff(2,0);
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r0 = mem(0,cr(2,0));
}
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %0, metadata !61, metadata !DIExpression()), !dbg !73
// %conv = trunc i64 %0 to i32, !dbg !57
// call void @llvm.dbg.value(metadata i32 %conv, metadata !57, metadata !DIExpression()), !dbg !70
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !62, metadata !DIExpression()), !dbg !76
// call void @llvm.dbg.value(metadata i64 1, metadata !64, metadata !DIExpression()), !dbg !76
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !59
// ST: Guess
iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0+2*1);
cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0+2*1)] == 2);
ASSUME(active[cw(2,0+2*1)] == 2);
ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(cw(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cw(2,0+2*1) >= old_cw);
ASSUME(cw(2,0+2*1) >= cr(2,0+2*1));
ASSUME(cw(2,0+2*1) >= cl[2]);
ASSUME(cw(2,0+2*1) >= cisb[2]);
ASSUME(cw(2,0+2*1) >= cdy[2]);
ASSUME(cw(2,0+2*1) >= cdl[2]);
ASSUME(cw(2,0+2*1) >= cds[2]);
ASSUME(cw(2,0+2*1) >= cctrl[2]);
ASSUME(cw(2,0+2*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+2*1) = 1;
mem(0+2*1,cw(2,0+2*1)) = 1;
co(0+2*1,cw(2,0+2*1))+=1;
delta(0+2*1,cw(2,0+2*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+2*1));
// %cmp = icmp eq i32 %conv, 1, !dbg !60
// %conv1 = zext i1 %cmp to i32, !dbg !60
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !65, metadata !DIExpression()), !dbg !70
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !66, metadata !DIExpression()), !dbg !79
// %1 = zext i32 %conv1 to i64
// call void @llvm.dbg.value(metadata i64 %1, metadata !68, metadata !DIExpression()), !dbg !79
// store atomic i64 %1, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !62
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r0,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r0==1);
mem(3,cw(2,3)) = (r0==1);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// ret i8* null, !dbg !63
ret_thread_2 = (- 1);
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !84, metadata !DIExpression()), !dbg !102
// br label %label_3, !dbg !58
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !101), !dbg !104
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !86, metadata !DIExpression()), !dbg !105
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) acquire, align 8, !dbg !61
// LD: Guess
// : Acquire
old_cr = cr(3,0+2*1);
cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM
// Check
ASSUME(active[cr(3,0+2*1)] == 3);
ASSUME(cr(3,0+2*1) >= iw(3,0+2*1));
ASSUME(cr(3,0+2*1) >= 0);
ASSUME(cr(3,0+2*1) >= cdy[3]);
ASSUME(cr(3,0+2*1) >= cisb[3]);
ASSUME(cr(3,0+2*1) >= cdl[3]);
ASSUME(cr(3,0+2*1) >= cl[3]);
ASSUME(cr(3,0+2*1) >= cx(3,0+2*1));
ASSUME(cr(3,0+2*1) >= cs(3,0+0));
ASSUME(cr(3,0+2*1) >= cs(3,0+1));
ASSUME(cr(3,0+2*1) >= cs(3,0+2));
ASSUME(cr(3,0+2*1) >= cs(3,3+0));
ASSUME(cr(3,0+2*1) >= cs(3,4+0));
ASSUME(cr(3,0+2*1) >= cs(3,5+0));
ASSUME(cr(3,0+2*1) >= cs(3,6+0));
ASSUME(cr(3,0+2*1) >= cs(3,7+0));
ASSUME(cr(3,0+2*1) >= cs(3,8+0));
// Update
creg_r1 = cr(3,0+2*1);
crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1));
caddr[3] = max(caddr[3],0);
if(cr(3,0+2*1) < cw(3,0+2*1)) {
r1 = buff(3,0+2*1);
} else {
if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) {
ASSUME(cr(3,0+2*1) >= old_cr);
}
pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1));
r1 = mem(0+2*1,cr(3,0+2*1));
}
cl[3] = max(cl[3],cr(3,0+2*1));
ASSUME(creturn[3] >= cr(3,0+2*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !88, metadata !DIExpression()), !dbg !105
// %conv = trunc i64 %0 to i32, !dbg !62
// call void @llvm.dbg.value(metadata i32 %conv, metadata !85, metadata !DIExpression()), !dbg !102
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !90, metadata !DIExpression()), !dbg !108
// %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) acquire, align 8, !dbg !64
// LD: Guess
// : Acquire
old_cr = cr(3,0+1*1);
cr(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM
// Check
ASSUME(active[cr(3,0+1*1)] == 3);
ASSUME(cr(3,0+1*1) >= iw(3,0+1*1));
ASSUME(cr(3,0+1*1) >= 0);
ASSUME(cr(3,0+1*1) >= cdy[3]);
ASSUME(cr(3,0+1*1) >= cisb[3]);
ASSUME(cr(3,0+1*1) >= cdl[3]);
ASSUME(cr(3,0+1*1) >= cl[3]);
ASSUME(cr(3,0+1*1) >= cx(3,0+1*1));
ASSUME(cr(3,0+1*1) >= cs(3,0+0));
ASSUME(cr(3,0+1*1) >= cs(3,0+1));
ASSUME(cr(3,0+1*1) >= cs(3,0+2));
ASSUME(cr(3,0+1*1) >= cs(3,3+0));
ASSUME(cr(3,0+1*1) >= cs(3,4+0));
ASSUME(cr(3,0+1*1) >= cs(3,5+0));
ASSUME(cr(3,0+1*1) >= cs(3,6+0));
ASSUME(cr(3,0+1*1) >= cs(3,7+0));
ASSUME(cr(3,0+1*1) >= cs(3,8+0));
// Update
creg_r2 = cr(3,0+1*1);
crmax(3,0+1*1) = max(crmax(3,0+1*1),cr(3,0+1*1));
caddr[3] = max(caddr[3],0);
if(cr(3,0+1*1) < cw(3,0+1*1)) {
r2 = buff(3,0+1*1);
} else {
if(pw(3,0+1*1) != co(0+1*1,cr(3,0+1*1))) {
ASSUME(cr(3,0+1*1) >= old_cr);
}
pw(3,0+1*1) = co(0+1*1,cr(3,0+1*1));
r2 = mem(0+1*1,cr(3,0+1*1));
}
cl[3] = max(cl[3],cr(3,0+1*1));
ASSUME(creturn[3] >= cr(3,0+1*1));
// call void @llvm.dbg.value(metadata i64 %1, metadata !92, metadata !DIExpression()), !dbg !108
// %conv4 = trunc i64 %1 to i32, !dbg !65
// call void @llvm.dbg.value(metadata i32 %conv4, metadata !89, metadata !DIExpression()), !dbg !102
// %cmp = icmp eq i32 %conv, 1, !dbg !66
// %conv5 = zext i1 %cmp to i32, !dbg !66
// call void @llvm.dbg.value(metadata i32 %conv5, metadata !93, metadata !DIExpression()), !dbg !102
// call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !94, metadata !DIExpression()), !dbg !112
// %2 = zext i32 %conv5 to i64
// call void @llvm.dbg.value(metadata i64 %2, metadata !96, metadata !DIExpression()), !dbg !112
// store atomic i64 %2, i64* @atom_2_X0_1 seq_cst, align 8, !dbg !68
// ST: Guess
iw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,4);
cw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,4)] == 3);
ASSUME(active[cw(3,4)] == 3);
ASSUME(sforbid(4,cw(3,4))== 0);
ASSUME(iw(3,4) >= max(creg_r1,0));
ASSUME(iw(3,4) >= 0);
ASSUME(cw(3,4) >= iw(3,4));
ASSUME(cw(3,4) >= old_cw);
ASSUME(cw(3,4) >= cr(3,4));
ASSUME(cw(3,4) >= cl[3]);
ASSUME(cw(3,4) >= cisb[3]);
ASSUME(cw(3,4) >= cdy[3]);
ASSUME(cw(3,4) >= cdl[3]);
ASSUME(cw(3,4) >= cds[3]);
ASSUME(cw(3,4) >= cctrl[3]);
ASSUME(cw(3,4) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,4) = (r1==1);
mem(4,cw(3,4)) = (r1==1);
co(4,cw(3,4))+=1;
delta(4,cw(3,4)) = -1;
ASSUME(creturn[3] >= cw(3,4));
// %cmp7 = icmp eq i32 %conv4, 0, !dbg !69
// %conv8 = zext i1 %cmp7 to i32, !dbg !69
// call void @llvm.dbg.value(metadata i32 %conv8, metadata !97, metadata !DIExpression()), !dbg !102
// call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !98, metadata !DIExpression()), !dbg !115
// %3 = zext i32 %conv8 to i64
// call void @llvm.dbg.value(metadata i64 %3, metadata !100, metadata !DIExpression()), !dbg !115
// store atomic i64 %3, i64* @atom_2_X2_0 seq_cst, align 8, !dbg !71
// ST: Guess
iw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,5);
cw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,5)] == 3);
ASSUME(active[cw(3,5)] == 3);
ASSUME(sforbid(5,cw(3,5))== 0);
ASSUME(iw(3,5) >= max(creg_r2,0));
ASSUME(iw(3,5) >= 0);
ASSUME(cw(3,5) >= iw(3,5));
ASSUME(cw(3,5) >= old_cw);
ASSUME(cw(3,5) >= cr(3,5));
ASSUME(cw(3,5) >= cl[3]);
ASSUME(cw(3,5) >= cisb[3]);
ASSUME(cw(3,5) >= cdy[3]);
ASSUME(cw(3,5) >= cdl[3]);
ASSUME(cw(3,5) >= cds[3]);
ASSUME(cw(3,5) >= cctrl[3]);
ASSUME(cw(3,5) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,5) = (r2==0);
mem(5,cw(3,5)) = (r2==0);
co(5,cw(3,5))+=1;
delta(5,cw(3,5)) = -1;
ASSUME(creturn[3] >= cw(3,5));
// ret i8* null, !dbg !72
ret_thread_3 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !125, metadata !DIExpression()), !dbg !165
// call void @llvm.dbg.value(metadata i8** %argv, metadata !126, metadata !DIExpression()), !dbg !165
// %0 = bitcast i64* %thr0 to i8*, !dbg !83
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !83
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !127, metadata !DIExpression()), !dbg !167
// %1 = bitcast i64* %thr1 to i8*, !dbg !85
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !85
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !131, metadata !DIExpression()), !dbg !169
// %2 = bitcast i64* %thr2 to i8*, !dbg !87
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !87
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !132, metadata !DIExpression()), !dbg !171
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !133, metadata !DIExpression()), !dbg !172
// call void @llvm.dbg.value(metadata i64 0, metadata !135, metadata !DIExpression()), !dbg !172
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !90
// ST: Guess
iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+2*1);
cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+2*1)] == 0);
ASSUME(active[cw(0,0+2*1)] == 0);
ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(cw(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cw(0,0+2*1) >= old_cw);
ASSUME(cw(0,0+2*1) >= cr(0,0+2*1));
ASSUME(cw(0,0+2*1) >= cl[0]);
ASSUME(cw(0,0+2*1) >= cisb[0]);
ASSUME(cw(0,0+2*1) >= cdy[0]);
ASSUME(cw(0,0+2*1) >= cdl[0]);
ASSUME(cw(0,0+2*1) >= cds[0]);
ASSUME(cw(0,0+2*1) >= cctrl[0]);
ASSUME(cw(0,0+2*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+2*1) = 0;
mem(0+2*1,cw(0,0+2*1)) = 0;
co(0+2*1,cw(0,0+2*1))+=1;
delta(0+2*1,cw(0,0+2*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !136, metadata !DIExpression()), !dbg !174
// call void @llvm.dbg.value(metadata i64 0, metadata !138, metadata !DIExpression()), !dbg !174
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !92
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !139, metadata !DIExpression()), !dbg !176
// call void @llvm.dbg.value(metadata i64 0, metadata !141, metadata !DIExpression()), !dbg !176
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !94
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !142, metadata !DIExpression()), !dbg !178
// call void @llvm.dbg.value(metadata i64 0, metadata !144, metadata !DIExpression()), !dbg !178
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !96
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !145, metadata !DIExpression()), !dbg !180
// call void @llvm.dbg.value(metadata i64 0, metadata !147, metadata !DIExpression()), !dbg !180
// store atomic i64 0, i64* @atom_2_X0_1 monotonic, align 8, !dbg !98
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !148, metadata !DIExpression()), !dbg !182
// call void @llvm.dbg.value(metadata i64 0, metadata !150, metadata !DIExpression()), !dbg !182
// store atomic i64 0, i64* @atom_2_X2_0 monotonic, align 8, !dbg !100
// ST: Guess
iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,5);
cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,5)] == 0);
ASSUME(active[cw(0,5)] == 0);
ASSUME(sforbid(5,cw(0,5))== 0);
ASSUME(iw(0,5) >= 0);
ASSUME(iw(0,5) >= 0);
ASSUME(cw(0,5) >= iw(0,5));
ASSUME(cw(0,5) >= old_cw);
ASSUME(cw(0,5) >= cr(0,5));
ASSUME(cw(0,5) >= cl[0]);
ASSUME(cw(0,5) >= cisb[0]);
ASSUME(cw(0,5) >= cdy[0]);
ASSUME(cw(0,5) >= cdl[0]);
ASSUME(cw(0,5) >= cds[0]);
ASSUME(cw(0,5) >= cctrl[0]);
ASSUME(cw(0,5) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,5) = 0;
mem(5,cw(0,5)) = 0;
co(5,cw(0,5))+=1;
delta(5,cw(0,5)) = -1;
ASSUME(creturn[0] >= cw(0,5));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !101
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call11 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !102
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call12 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !103
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !104, !tbaa !105
// LD: Guess
old_cr = cr(0,6);
cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,6)] == 0);
ASSUME(cr(0,6) >= iw(0,6));
ASSUME(cr(0,6) >= 0);
ASSUME(cr(0,6) >= cdy[0]);
ASSUME(cr(0,6) >= cisb[0]);
ASSUME(cr(0,6) >= cdl[0]);
ASSUME(cr(0,6) >= cl[0]);
// Update
creg_r4 = cr(0,6);
crmax(0,6) = max(crmax(0,6),cr(0,6));
caddr[0] = max(caddr[0],0);
if(cr(0,6) < cw(0,6)) {
r4 = buff(0,6);
} else {
if(pw(0,6) != co(6,cr(0,6))) {
ASSUME(cr(0,6) >= old_cr);
}
pw(0,6) = co(6,cr(0,6));
r4 = mem(6,cr(0,6));
}
ASSUME(creturn[0] >= cr(0,6));
// %call13 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !109
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !110, !tbaa !105
// LD: Guess
old_cr = cr(0,7);
cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,7)] == 0);
ASSUME(cr(0,7) >= iw(0,7));
ASSUME(cr(0,7) >= 0);
ASSUME(cr(0,7) >= cdy[0]);
ASSUME(cr(0,7) >= cisb[0]);
ASSUME(cr(0,7) >= cdl[0]);
ASSUME(cr(0,7) >= cl[0]);
// Update
creg_r5 = cr(0,7);
crmax(0,7) = max(crmax(0,7),cr(0,7));
caddr[0] = max(caddr[0],0);
if(cr(0,7) < cw(0,7)) {
r5 = buff(0,7);
} else {
if(pw(0,7) != co(7,cr(0,7))) {
ASSUME(cr(0,7) >= old_cr);
}
pw(0,7) = co(7,cr(0,7));
r5 = mem(7,cr(0,7));
}
ASSUME(creturn[0] >= cr(0,7));
// %call14 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !111
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !112, !tbaa !105
// LD: Guess
old_cr = cr(0,8);
cr(0,8) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,8)] == 0);
ASSUME(cr(0,8) >= iw(0,8));
ASSUME(cr(0,8) >= 0);
ASSUME(cr(0,8) >= cdy[0]);
ASSUME(cr(0,8) >= cisb[0]);
ASSUME(cr(0,8) >= cdl[0]);
ASSUME(cr(0,8) >= cl[0]);
// Update
creg_r6 = cr(0,8);
crmax(0,8) = max(crmax(0,8),cr(0,8));
caddr[0] = max(caddr[0],0);
if(cr(0,8) < cw(0,8)) {
r6 = buff(0,8);
} else {
if(pw(0,8) != co(8,cr(0,8))) {
ASSUME(cr(0,8) >= old_cr);
}
pw(0,8) = co(8,cr(0,8));
r6 = mem(8,cr(0,8));
}
ASSUME(creturn[0] >= cr(0,8));
// %call15 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !113
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !152, metadata !DIExpression()), !dbg !197
// %6 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !115
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r7 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r7 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r7 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %6, metadata !154, metadata !DIExpression()), !dbg !197
// %conv = trunc i64 %6 to i32, !dbg !116
// call void @llvm.dbg.value(metadata i32 %conv, metadata !151, metadata !DIExpression()), !dbg !165
// call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !156, metadata !DIExpression()), !dbg !200
// %7 = load atomic i64, i64* @atom_2_X0_1 seq_cst, align 8, !dbg !118
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r8 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r8 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r8 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i64 %7, metadata !158, metadata !DIExpression()), !dbg !200
// %conv19 = trunc i64 %7 to i32, !dbg !119
// call void @llvm.dbg.value(metadata i32 %conv19, metadata !155, metadata !DIExpression()), !dbg !165
// call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !160, metadata !DIExpression()), !dbg !203
// %8 = load atomic i64, i64* @atom_2_X2_0 seq_cst, align 8, !dbg !121
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r9 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r9 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r9 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// call void @llvm.dbg.value(metadata i64 %8, metadata !162, metadata !DIExpression()), !dbg !203
// %conv23 = trunc i64 %8 to i32, !dbg !122
// call void @llvm.dbg.value(metadata i32 %conv23, metadata !159, metadata !DIExpression()), !dbg !165
// %and = and i32 %conv19, %conv23, !dbg !123
creg_r10 = max(creg_r8,creg_r9);
ASSUME(active[creg_r10] == 0);
r10 = r8 & r9;
// call void @llvm.dbg.value(metadata i32 %and, metadata !163, metadata !DIExpression()), !dbg !165
// %and24 = and i32 %conv, %and, !dbg !124
creg_r11 = max(creg_r7,creg_r10);
ASSUME(active[creg_r11] == 0);
r11 = r7 & r10;
// call void @llvm.dbg.value(metadata i32 %and24, metadata !164, metadata !DIExpression()), !dbg !165
// %cmp = icmp eq i32 %and24, 1, !dbg !125
// br i1 %cmp, label %if.then, label %if.end, !dbg !127
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r11);
ASSUME(cctrl[0] >= 0);
if((r11==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([128 x i8], [128 x i8]* @.str.1, i64 0, i64 0), i32 noundef 71, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !128
// unreachable, !dbg !128
r12 = 1;
T0BLOCK2:
// %9 = bitcast i64* %thr2 to i8*, !dbg !131
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !131
// %10 = bitcast i64* %thr1 to i8*, !dbg !131
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !131
// %11 = bitcast i64* %thr0 to i8*, !dbg !131
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !131
// ret i32 0, !dbg !132
ret_thread_0 = 0;
ASSERT(r12== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
e4bf3f1f63214b0778c8901dcbe58f05d7ff0ee4 | c6ac7da6dacdc300d22583ac4ef3b79a54c6f4c2 | /Logowanie.hpp | 22e3686acce8c3e398ce51855fb0e44b5bdba707 | [] | no_license | car-rental-project/car-rental | ddd14924d43c4566c4ce3faa1495e59cc59be09a | 65cf4dd720d7dd857a23c73bffafe49c5aac16a9 | refs/heads/master | 2020-09-27T10:14:17.164744 | 2020-01-16T07:03:23 | 2020-01-16T07:03:23 | 226,493,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | hpp | #ifndef LOGOWANIE
#define LOGOWANIE
#include <iostream>
#include <string>
#include <fstream>
#include "Uzytkownik.hpp"
using namespace std;
class Logowanie
{
private:
string login;
string haslo;
public:
Logowanie() = default;
Logowanie(string l, string h) :login(l), haslo(h) {};
string getLogin();
string getHaslo();
void setLogin(string l);
void setHaslo(string h);
Uzytkownik zaloguj();
};
#endif | [
"noreply@github.com"
] | noreply@github.com |
5a9e3fd07f856fa5af5fc25caab2e44df9ef9fc8 | eabb35e6c2f47b35d1cd9187a3d9ac311fcefe0f | /filter.h | afac18fb674e8c5857f37cde51f2bd785dd8731e | [] | no_license | adrianz261/PublicSpeakerWorkshop | 1ca9aafaceec0f2a7de6f3320d43729fa539a7cf | 1b2a846e02ebbac4d31735dc82092e5dc1f1fa78 | refs/heads/master | 2022-04-25T19:36:23.562361 | 2020-04-25T16:13:27 | 2020-04-25T16:13:27 | 258,802,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,836 | h | // Xform.h : Named Components Class
//
/////////////////////////////////////////////////////////////////////////////
#ifndef CXFILTER
// -------------------------------------------------------------------------
// UNARY TRANSFORMATIONS (in place)
class CXtFilter : public CXunary
{
public:
int m_nShape;
int m_nType;
int m_nOrder;
float m_fLowFreq;
float m_fHiFreq;
float m_fRipple;
private: // the stuff for each section
CDoubleArray *m_pPrevInput; // x(j)'s
CDoubleArray *m_pPrevOutput; // y(j)'s
CDoubleArray *m_pNumerator; // numerators
CDoubleArray *m_pDenominator; // denominators
int m_nSections; // number of sections
public:
virtual UINT DoDialog( void); // xeq dbox
virtual UINT GetDialog(void); // get the dialog id
virtual int DoOperation( void); // do it
UINT GetNameID() { return IDOP_FILTER; }
private:
void Calc_Variables(); // get the vars
int CreateFilter( void);
int CreateBessel( void);
int CreateButter( void);
int CreateCheby( void);
int FilterFrequency( void);
int FilterBessel( ZComplex& zSource, ZComplex& zOmega);
int FilterButter( ZComplex& zSource, ZComplex& zOmega);
int FilterCheby( ZComplex& zSource, ZComplex& zOmega);
int CalcPolynomials( void); // get the polynomials built
int ConvertToNormal( void);
int ConvertBilinear( void);
int FilterTime( void);
int ApplyTimeFilter( void);
public:
CFloatArray m_cPolynomial; // the fir representation (complex variables)
CFloatArray m_cPolyLow; // the iir polynomial portion
ZComplexArray m_cFreqPoly; // the fir representation (complex variables)
ZComplexArray m_cFreqPolyLow; // the iir polynomial portion
public:
CXtFilter( CObject *cTarget, float *ftPoly, int nTotal); // must be named and in the tree
~CXtFilter();
};
#endif
| [
"adrian.zuchowski@outlook.com"
] | adrian.zuchowski@outlook.com |
3d37ee9866659755ff54ee7c32e7ecba498a3421 | 1f1cc05377786cc2aa480cbdfde3736dd3930f73 | /xulrunner-sdk-26/xulrunner-sdk/include/mozilla/dom/SVGDocumentBinding.h | 32cccdaa460e516572bc140969ceffe307fa666b | [
"Apache-2.0"
] | permissive | julianpistorius/gp-revolution-gaia | 84c3ec5e2f3b9e76f19f45badc18d5544bb76e0d | 6e27b83efb0d4fa4222eaf25fb58b062e6d9d49e | refs/heads/master | 2021-01-21T02:49:54.000389 | 2014-03-27T09:58:17 | 2014-03-27T09:58:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,667 | h | /* THIS FILE IS AUTOGENERATED - DO NOT EDIT */
#ifndef mozilla_dom_SVGDocumentBinding_h__
#define mozilla_dom_SVGDocumentBinding_h__
#include "mozilla/ErrorResult.h"
#include "mozilla/dom/BindingDeclarations.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/DOMJSProxyHandler.h"
namespace mozilla {
namespace dom {
class SVGDocument;
} // namespace dom
} // namespace mozilla
namespace mozilla {
namespace dom {
template <>
struct PrototypeTraits<prototypes::id::SVGDocument>
{
enum
{
Depth = 3
};
typedef mozilla::dom::SVGDocument NativeType;
};
template <>
struct PrototypeIDMap<mozilla::dom::SVGDocument>
{
enum
{
PrototypeID = prototypes::id::SVGDocument
};
};
} // namespace dom
} // namespace mozilla
namespace mozilla {
namespace dom {
namespace SVGDocumentBinding {
extern const NativePropertyHooks sNativePropertyHooks;
void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, JS::Heap<JSObject*>* protoAndIfaceArray);
inline JS::Handle<JSObject*> GetProtoObject(JSContext* aCx, JS::Handle<JSObject*> aGlobal)
{
/* Get the interface prototype object for this class. This will create the
object as needed. */
/* Make sure our global is sane. Hopefully we can remove this sometime */
if (!(js::GetObjectClass(aGlobal)->flags & JSCLASS_DOM_GLOBAL)) {
return JS::NullPtr();
}
/* Check to see whether the interface objects are already installed */
JS::Heap<JSObject*>* protoAndIfaceArray = GetProtoAndIfaceArray(aGlobal);
if (!protoAndIfaceArray[prototypes::id::SVGDocument]) {
CreateInterfaceObjects(aCx, aGlobal, protoAndIfaceArray);
}
/*
* The object might _still_ be null, but that's OK.
*
* Calling fromMarkedLocation() is safe because protoAndIfaceArray is
* traced by TraceProtoAndIfaceCache() and its contents are never
* changed after they have been set.
*/
return JS::Handle<JSObject*>::fromMarkedLocation(protoAndIfaceArray[prototypes::id::SVGDocument].address());
}
inline JS::Handle<JSObject*> GetConstructorObject(JSContext* aCx, JS::Handle<JSObject*> aGlobal)
{
/* Get the interface object for this class. This will create the object as
needed. */
/* Make sure our global is sane. Hopefully we can remove this sometime */
if (!(js::GetObjectClass(aGlobal)->flags & JSCLASS_DOM_GLOBAL)) {
return JS::NullPtr();
}
/* Check to see whether the interface objects are already installed */
JS::Heap<JSObject*>* protoAndIfaceArray = GetProtoAndIfaceArray(aGlobal);
if (!protoAndIfaceArray[constructors::id::SVGDocument]) {
CreateInterfaceObjects(aCx, aGlobal, protoAndIfaceArray);
}
/*
* The object might _still_ be null, but that's OK.
*
* Calling fromMarkedLocation() is safe because protoAndIfaceArray is
* traced by TraceProtoAndIfaceCache() and its contents are never
* changed after they have been set.
*/
return JS::Handle<JSObject*>::fromMarkedLocation(protoAndIfaceArray[constructors::id::SVGDocument].address());
}
JSObject*
DefineDOMInterface(JSContext* aCx, JS::Handle<JSObject*> aGlobal, JS::Handle<jsid> id, bool* aEnabled);
extern DOMJSClass Class;
JSObject*
Wrap(JSContext* aCx, JS::Handle<JSObject*> aScope, mozilla::dom::SVGDocument* aObject, nsWrapperCache* aCache);
template <class T>
inline JSObject* Wrap(JSContext* aCx, JS::Handle<JSObject*> aScope, T* aObject)
{
return Wrap(aCx, aScope, aObject, aObject);
}
} // namespace SVGDocumentBinding
} // namespace dom
} // namespace mozilla
#endif // mozilla_dom_SVGDocumentBinding_h__
| [
"luis@geeksphone.com"
] | luis@geeksphone.com |
1c9982f908434b327082b89d02e4f869bae7bc61 | 33181bddaf8d0e08846992adcc437737ff53cec4 | /libapie/event/file_event_impl.cc | 8640cf0844e6a36715afac23afc5c7eba8954c63 | [] | no_license | wuqunyong/APie | da82ade6d4f9a39ca79bcc2029a156d29d74266f | 6eb6a15966ac5bf3c59db71a0cc81f1663ccbc3d | refs/heads/master | 2021-08-17T16:50:38.241899 | 2021-08-03T09:59:27 | 2021-08-03T09:59:27 | 255,871,414 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,272 | cc | #include "../event/file_event_impl.h"
#include <cstdint>
#include <assert.h>
#include "../event/dispatcher_impl.h"
#include "event2/event.h"
namespace APie {
namespace Event {
FileEventImpl::FileEventImpl(DispatcherImpl& dispatcher, int fd, FileReadyCb cb,
FileTriggerType trigger, uint32_t events)
: cb_(cb), base_(&dispatcher.base()), fd_(fd), trigger_(trigger) {
#ifdef WIN32
assert(trigger_ == FileTriggerType::Level);
#endif
assignEvents(events);
event_add(&raw_event_, nullptr);
}
void FileEventImpl::activate(uint32_t events) {
int libevent_events = 0;
if (events & FileReadyType::Read) {
libevent_events |= EV_READ;
}
if (events & FileReadyType::Write) {
libevent_events |= EV_WRITE;
}
//if (events & FileReadyType::Closed) {
// libevent_events |= EV_CLOSED;
//}
assert(libevent_events);
event_active(&raw_event_, libevent_events, 0);
}
void FileEventImpl::assignEvents(uint32_t events) {
//auto eventValue = EV_PERSIST | (trigger_ == FileTriggerType::Level ? 0 : EV_ET) |
// (events & FileReadyType::Read ? EV_READ : 0) |
// (events & FileReadyType::Write ? EV_WRITE : 0) |
// (events & FileReadyType::Write ? EV_CLOSED : 0);
event_assign(&raw_event_, base_, fd_,
EV_PERSIST | (trigger_ == FileTriggerType::Level ? 0 : EV_ET) |
(events & FileReadyType::Read ? EV_READ : 0) |
(events & FileReadyType::Write ? EV_WRITE : 0),
[](evutil_socket_t, short what, void* arg) -> void {
FileEventImpl* event = static_cast<FileEventImpl*>(arg);
uint32_t events = 0;
if (what & EV_READ) {
events |= FileReadyType::Read;
}
if (what & EV_WRITE) {
events |= FileReadyType::Write;
}
//if (what & EV_CLOSED) {
// events |= FileReadyType::Closed;
//}
assert(events);
event->cb_(events);
},
this);
}
void FileEventImpl::setEnabled(uint32_t events) {
event_del(&raw_event_);
assignEvents(events);
event_add(&raw_event_, nullptr);
}
} // namespace Event
} // namespace Envoy
| [
"wuqunyongproxy@gmail.com"
] | wuqunyongproxy@gmail.com |
21044f36e9bc3e0e99e88d04aea59b838e28b92c | e73c5b0e7031f2c7864de97fa749edc491b0c583 | /src/common/mousebutton.hpp | ea8dcc132df03642b9a9e5e86735f0e346c3037e | [] | no_license | thecoshman/peanuts | 19fc298f392eb1dd165dc44c7d44c0c4f0598981 | 44a37485c1dca20d14d2f62d73eb522c22c6a1ee | refs/heads/master | 2021-01-20T08:48:39.359328 | 2017-11-05T13:06:05 | 2017-11-05T13:06:05 | 10,608,472 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 145 | hpp | #pragma once
namespace Peanuts{
enum class MouseButton{
LEFT, MIDDLE, RIGHT, SCROLL_UP, SCROLL_DOWN,
UNKOWN_BUTTON,
};
} | [
"thecoshman@gmail.com"
] | thecoshman@gmail.com |
7bb0a2e14a3c14ba8d0693cd1574315d43faf5f3 | 9518cdbd568b6d9dabf4e2c82460419ac6382fd1 | /C++ Codes/Part 11/3.cpp | 1ea36915d54434b679179a542dfc4c6179640299 | [] | no_license | ssinghakshit/Class_Assignments | e30a31643f01494a18b831cf774e305c9c31a888 | 2e7296f542b5bf3a9c1139cd20045f6141617036 | refs/heads/main | 2023-08-01T18:06:00.023096 | 2021-09-30T12:27:33 | 2021-09-30T12:27:33 | 412,053,583 | 0 | 0 | null | 2021-09-30T12:27:34 | 2021-09-30T12:21:48 | null | UTF-8 | C++ | false | false | 366 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout << "Enter a integer number: ";
cin >> n;
int m = n;
int binary = 0;
int i = 1;
while (n != 0)
{
binary = binary + i * (n % 2);
n /= 2;
i = i * 10;
}
cout << "Binary form of " << m << " is: " << binary << endl;
return 0;
} | [
"anasfarazi0151@gmail.com"
] | anasfarazi0151@gmail.com |
e95ff6e170150d928aea98770e5847585626c6ec | dcb65209364c0075af54d287eb0f3e43cb2a8201 | /ui/FileInfoLoader.cpp | fe7aeeefcc75256f4b05c1af86588c5cef940748 | [] | no_license | freshlife001/foundit | 0f8f35994d90a67a9fdc7c9f6a27c9b613c97083 | e2a60b67df692ebf5682d8c1b3bd60f6afcb2738 | refs/heads/master | 2021-08-11T12:59:02.533883 | 2015-05-16T07:55:51 | 2015-05-16T07:55:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,484 | cpp | #include "StdAfx.h"
#include <iostream>
#include <sstream>
#include <time.h>
#include <boost/bind.hpp>
#include <boost/system/error_code.hpp>
#include <boost/foreach.hpp>
#include "utils/file_ex.h"
#include "uilib/common/utils/ImageEx/ImageEx.h"
#include "FileInfoLoader.h"
#include "logex.h"
CFileInfoLoader::CFileInfoLoader(void): m_running(false)
{
}
CFileInfoLoader::~CFileInfoLoader(void)
{
}
void CFileInfoLoader::Init()
{
LOG_FUNC_SCOPE_C();
m_running = true;
m_ios.reset();
m_work.reset(new boost::asio::io_service::work(m_ios));
start();
}
void CFileInfoLoader::UnInit()
{
LOG_FUNC_SCOPE_C();
m_work.reset();
m_ios.stop();
if (is_started())
{
stop(1000);
}
m_running = false;
std::map<std::wstring, HICON>::iterator it;
for (it = m_IconCache.begin(); it != m_IconCache.end(); it ++)
{
::DestroyIcon(it->second);
}
m_IconCache.clear();
m_fileInfoCache.clear();
}
CFileInfoLoader & CFileInfoLoader::Instance()
{
static CFileInfoLoader s_loader;
return s_loader;
}
bool CFileInfoLoader::LoadFileInfo(LPCTSTR fullPath, unsigned int mask, FileInfo& info)
{
info.fullpath = fullPath;
info.filename = file_ex::get_file_name(std::wstring(fullPath)).c_str();
if (m_running)
{
std::wstring path = fullPath;
m_ios.dispatch(boost::bind(&CFileInfoLoader::load_file_info, this, path, mask));
}
return false;
}
void CFileInfoLoader::load_file_info(const std::wstring &fullpath, unsigned int mask)
{
FileInfo & info = m_fileInfoCache[fullpath];
info.fullpath = fullpath.c_str();
info.filename = file_ex::get_file_name(fullpath).c_str();
if (!info.exists)
{
//check existance
if (file_ex::exists_w(fullpath))
{
info.exists = true;
}
else
{
info.exists = false;
GotFileInfo(info);
return;
}
}
if ( (mask & ICON) || !(info.validmask & ICON ))
{
info.validmask |= ICON;
std::wstring icon_key;
if (file_ex::is_directory(fullpath))
{
icon_key = _T("");
}
else
{
icon_key = file_ex::get_file_ext(fullpath);
}
if (icon_key == _T("exe"))
{
icon_key = fullpath;
}
if (m_IconCache.count(icon_key))
{
info.imgIcon = m_IconCache[icon_key];
}
else
{
if (info.imgIcon == NULL)
{
HICON hIcon =NULL;
if (icon_key == L"")
{
//dir
HMODULE hModule = LoadLibrary(_T("SHELL32.dll"));
if(hModule)
{
hIcon = LoadIcon(hModule, MAKEINTRESOURCE(4));
}
}
else
{
//file
//try load icon
SHFILEINFO shfi;
SHGetFileInfo(fullpath.c_str(),
FILE_ATTRIBUTE_NORMAL,
&shfi, sizeof(SHFILEINFO),
SHGFI_ICON|SHGFI_USEFILEATTRIBUTES);
hIcon = shfi.hIcon;
}
if (hIcon)
{
//draw icon
info.imgIcon = hIcon;
m_IconCache[icon_key] = info.imgIcon;
}
}
}
}
if ( (mask & DATE) || !(info.validmask & DATE ))
{
info.validmask |= DATE;
info.lastmodify = file_ex::get_last_write_time(fullpath);
}
if ( (mask & SIZE) || !(info.validmask & SIZE ))
{
info.validmask |= ICON;
if (file_ex::is_directory(fullpath))
{
info.size = 0;
}
else
{
file_ex::get_file_size(fullpath, info.size);
}
}
GotFileInfo(info);
}
void CFileInfoLoader::thread_proc()
{
LOG_INFO_C("start run");
m_ios.run();
m_running = false;
m_ios.stop();
}
| [
"baoge_pmb@hotmail.com"
] | baoge_pmb@hotmail.com |
978dfd57ff67806696e04d8dbd19db6977217eca | 45552685c92e7ee0d32d55ef2eb4500296598608 | /examples/daemon/daemonizer.cc | 30fed794e8ec559f9cbe234a9002cbcc8f2ca3d9 | [
"BSD-3-Clause"
] | permissive | Hanfee/mpic | ad6e85fe72b469f643816a45b55dd1c936e62f36 | 9f49187ddd7b503604e9ae731e7ff407b1fa5ab1 | refs/heads/master | 2020-11-25T07:46:46.413984 | 2019-12-18T09:14:43 | 2019-12-18T09:14:43 | 228,562,686 | 0 | 0 | BSD-3-Clause | 2019-12-17T07:53:10 | 2019-12-17T07:53:09 | null | UTF-8 | C++ | false | false | 1,700 | cc | #include "daemonizer.h"
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include "libdaemon/daemon.h"
namespace mpic {
Daemonizer::Daemonizer() {
}
Daemonizer::~Daemonizer() {
daemon_log(LOG_INFO, "Process daemon gracefully exited ...");
daemon_retval_send(0);
}
void Daemonizer::Init() {
// Prepare for return value passing from the initialization procedure of the daemon process
pid_t pid = 0;
if (daemon_retval_init() < 0) {
daemon_log(LOG_ERR, "Failed to create pipe.");
}
// Do the fork
if ((pid = daemon_fork()) < 0) {
// Exit on error
daemon_retval_done();
} else if (pid) { // The parent
int ret = 0;
// Wait for 20 seconds for the return value passed from the daemon process
if ((ret = daemon_retval_wait(20)) < 0) {
daemon_log(LOG_ERR, "Could not recieve return value from daemon process: %s", strerror(errno));
exit(0);
}
switch (ret) {
case 0:
daemon_log(LOG_INFO, "Sucessfully started daemon ...");
break;
case 1:
daemon_log(LOG_ERR, "Failed to close all file descriptors: %s", strerror(errno));
break;
default:
daemon_log(ret != 0 ? LOG_ERR : LOG_INFO, "Daemon returned %i as return value.", ret);
break;
}
// exit the parent process
exit(0);
} else { // The daemon
// Close FDs
if (daemon_close_all(-1) < 0) {
// Send the error condition to the parent process
daemon_retval_send(1);
}
// Send OK to parent process
daemon_retval_send(0);
}
}
}
| [
"zieckey@gmail.com"
] | zieckey@gmail.com |
cc6416351441d3c6a58857e192bd9532300883b7 | 8fd46dc426b5eed13bb42d049519ff1016be8e54 | /src/ast/ast.cpp | b6b4baf699c8d48da084589fa766fe3a4e59b90a | [] | no_license | Ghostjs123/toy-python-interpreter | c7f52a768966722135831fdbe28833cc331b5ac7 | 7d80270dd50106ba466f989396b46701587c29b0 | refs/heads/main | 2023-07-20T04:58:12.069461 | 2021-08-28T20:39:49 | 2021-08-28T20:39:49 | 338,213,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 98,187 | cpp | // https://docs.python.org/3/reference/grammar.html
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <cstdlib>
#include <numeric>
#include <typeinfo>
#include "logging.h"
#include "tokenizer.h"
#include "token.h"
#include "util.h"
#include "ast.h"
#include "ast_helpers.h"
#include "pyobject.h"
#include "stack.h"
using namespace std;
void log(string msg, int mode) {
Logger::get_instance()->log(msg, mode);
}
void add_indent(int amt) {
Logger::get_instance()->add_indent(amt);
}
void sub_indent(int amt) {
Logger::get_instance()->sub_indent(amt);
}
//===============================================================
// AST: parent class of all nodes
AST::AST() { }
AST::AST(Tokenizer *tokenizer, string indent) {
this->tokenizer = tokenizer;
this->indent = indent;
}
AST::~AST() {
// log(__FUNCTION__ + (string)" - " + to_string(rewind_amt), DEBUG); // this is spammy
if (rewind_amt > 0) tokenizer->rewind(rewind_amt);
}
Token AST::peek(string func_name) {
try {
return tokenizer->peek();
} catch (exception& e) {
cout << func_name << ": " << e.what() << endl;
}
throw runtime_error("halting after error in peek()");
}
Token AST::lookahead(int amt) {
return tokenizer->lookahead(amt);
}
Token AST::next_token() {
Token t = tokenizer->next_token();
log(": " + t.as_string(), DEBUG);
return t;
}
void AST::eat_value(string exp_value, string func_name) {
Token next = next_token();
if (next.value != exp_value) {
throw runtime_error("ate '" + next.value + "' expected '"
+ exp_value + "' in '" + func_name + "'");
}
rewind_amt++;
}
void AST::eat_type(string exp_type, string func_name) {
Token next = next_token();
if (next.type != exp_type) {
throw runtime_error("ate '" + next.type + "' expected '"
+ exp_type + "' in '" + func_name + "'");
}
rewind_amt++;
}
PyObject AST::evaluate(Stack stack) {
throw runtime_error("Attempted to evaluate an AST - start evaluation at a subclass");
}
ostream& operator<<(ostream& os, const AST& ast) {
return ast.print(os);
}
ostream& AST::print(ostream& os) const {
if (children.size() == 0) {
os << "Empty AST Node";
} else {
for (AST *child : children) {
os << *child;
}
}
return os;
}
//===============================================================
// File: starting non-terminal for file mode
// file: [statements] ENDMARKER
File::File(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
File::~File() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void File::parse() {
children.push_back(new Statements(tokenizer, indent));
eat_type("ENDMARKER", "File");
}
PyObject File::evaluate(Stack stack) {
log("File::evaluate()", DEBUG); add_indent(2);
children.at(0)->evaluate(stack);
sub_indent(2);
return PyObject();
}
ostream& File::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Interactive: starting non-terminal for interactive mode
// interactive: statement_newline
Interactive::Interactive(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Interactive::~Interactive() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Interactive::parse() {
children.push_back(new StatementNewline(tokenizer, indent));
}
PyObject Interactive::evaluate(Stack stack) {
log("Interactive::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& Interactive::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// Statements
// statements: statement+
Statements::Statements(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Statements::~Statements() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Statements::parse() {
while (peek("Statements").type != "ENDMARKER") {
children.push_back(new Statement(tokenizer, indent));
}
}
PyObject Statements::evaluate(Stack stack) {
log("Statements::evaluate()", DEBUG); add_indent(2);
for (AST* child : children) {
child->evaluate(stack);
}
sub_indent(2);
return PyObject();
}
ostream& Statements::print(ostream& os) const {
for (AST* child : children) os << *child;
return os;
}
//===============================================================
// Statement
// NOTE: this attempts to parse a CompoundStmt, falls back to SimpleStmt
// statement: compound_stmt | simple_stmt
Statement::Statement(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Statement::~Statement() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Statement::parse() {
CompoundStmt *temp = new CompoundStmt(tokenizer, indent);
if (temp->children.size() == 0) {
delete temp;
children.push_back(new SimpleStmt(tokenizer, indent));
} else {
children.push_back(temp);
}
}
PyObject Statement::evaluate(Stack stack) {
log("Statement::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& Statement::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// StatementNewline
// NOTE: this node is only used for interactive mode
// I am opting to ignore a lot of the whitespace tokens in favor
// of handling them in the terminal (ncurses) stuff instead
// statement_newline:
// | compound_stmt NEWLINE
// | simple_stmt
// | NEWLINE
// | ENDMARKER
StatementNewline::StatementNewline(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
StatementNewline::~StatementNewline() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void StatementNewline::parse() {
if (peek("StatementNewline").type == "NEWLINE") {
eat_type("NEWLINE", "StatementNewline");
} else if (peek("StatementNewline").type == "NL") {
eat_type("NL", "StatementNewline");
} else if (peek("StatementNewline").type == "ENDMARKER") {
eat_type("ENDMARKER", "StatementNewline");
} else {
CompoundStmt *temp = new CompoundStmt(tokenizer, indent);
if (temp->children.size() == 0) {
delete temp;
children.push_back(new SimpleStmt(tokenizer, indent));
} else {
children.push_back(temp);
eat_type("NEWLINE", "StatementNewline");
}
}
}
PyObject StatementNewline::evaluate(Stack stack) {
log("StatementNewline::evaluate()", DEBUG); add_indent(2);
if (children.size() > 0) {
sub_indent(2);
return children.at(0)->evaluate(stack);
}
sub_indent(2);
return PyObject();
}
ostream& StatementNewline::print(ostream& os) const {
if (children.size() > 0) os << *children.at(0);
return os;
}
//===============================================================
// SimpleStmt
// simple_stmt:
// | small_stmt !';' NEWLINE # Not needed, there for speedup
// | ';'.small_stmt+ [';'] NEWLINE
SimpleStmt::SimpleStmt(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
SimpleStmt::~SimpleStmt() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void SimpleStmt::parse() {
// TODO: grammar needs to support ;
children.push_back(new SmallStmt(tokenizer, indent));
eat_type("NEWLINE", "SimpleStmt");
}
PyObject SimpleStmt::evaluate(Stack stack) {
log("SimpleStmt::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& SimpleStmt::print(ostream& os) const {
// NOTE: these should always have a NEWLINE
os << *children.at(0) << endl;
return os;
}
//===============================================================
// SmallStmt
// NOTE: star_expressions leads to bitwise stuff (only way to get to Atom)
// small_stmt:
// | assignment
// | star_expressions
// | return_stmt
// | import_stmt
// | raise_stmt
// | 'pass'
// | del_stmt
// | yield_stmt
// | assert_stmt
// | 'break'
// | 'continue'
// | global_stmt
// | nonlocal_stmt
SmallStmt::SmallStmt(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
SmallStmt::~SmallStmt() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void SmallStmt::parse() {
if (peek("SmallStmt").value == "return") {
children.push_back(new ReturnStmt(tokenizer, indent));
}
else if (peek("SmallStmt").value == "import") {
throw runtime_error("SmallStmt: 'import' not implemented");
}
else if (peek("SmallStmt").value == "raise") {
throw runtime_error("SmallStmt: 'raise' not implemented");
}
else if (peek("SmallStmt").value == "pass") {
throw runtime_error("SmallStmt: 'pass' not implemented");
}
else if (peek("SmallStmt").value == "del") {
throw runtime_error("SmallStmt: 'del' not implemented");
}
else if (peek("SmallStmt").value == "yield") {
throw runtime_error("SmallStmt: 'yield' not implemented");
}
else if (peek("SmallStmt").value == "assert") {
throw runtime_error("SmallStmt: 'assert' not implemented");
}
else if (peek("SmallStmt").value == "break") {
throw runtime_error("SmallStmt: 'break' not implemented");
}
else if (peek("SmallStmt").value == "continue") {
throw runtime_error("SmallStmt: 'continue' not implemented");
}
else if (peek("SmallStmt").value == "global") {
throw runtime_error("SmallStmt: 'global' not implemented");
}
else if (peek("SmallStmt").value == "nonlocal") {
throw runtime_error("SmallStmt: 'nonlocal' not implemented");
}
else {
// assignment
// star_expressions
children.push_back(new StarExpressions(tokenizer, indent));
}
}
PyObject SmallStmt::evaluate(Stack stack) {
log("SmallStmt::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& SmallStmt::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// CompoundStmt
// compound_stmt:
// | function_def
// | if_stmt
// | class_def
// | with_stmt
// | for_stmt
// | try_stmt
// | while_stmt
CompoundStmt::CompoundStmt(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
CompoundStmt::~CompoundStmt() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void CompoundStmt::parse() {
if (peek("CompoundStmt").value == "if") {
children.push_back(new IfStmt(tokenizer, indent));
}
else if (peek("CompoundStmt").value == "for") {
children.push_back(new ForStmt(tokenizer, indent));
}
else if (peek("CompoundStmt").value == "while") {
children.push_back(new WhileStmt(tokenizer, indent));
}
else if (peek("CompoundStmt").value == "def") {
children.push_back(new FunctionDef(tokenizer, indent));
}
// TODO: class_def, with_stmt, try_stmt
}
PyObject CompoundStmt::evaluate(Stack stack) {
log("CompoundStmt::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& CompoundStmt::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// Assignment
// assignment:
// | NAME ':' expression ['=' annotated_rhs ]
// | ('(' single_target ')'
// | single_subscript_attribute_target) ':' expression ['=' annotated_rhs ]
// | (star_targets '=' )+ (yield_expr | star_expressions) !'=' [TYPE_COMMENT]
// | single_target augassign ~ (yield_expr | star_expressions)
// augassign:
// | '+='
// | '-='
// | '*='
// | '@='
// | '/='
// | '%='
// | '&='
// | '|='
// | '^='
// | '<<='
// | '>>='
// | '**='
// | '//='
Assignment::Assignment(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Assignment::~Assignment() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Assignment::parse() {
// TODO:
}
PyObject Assignment::evaluate(Stack stack) {
// TODO:
log("Assignment::evaluate()", DEBUG); add_indent(2); sub_indent(2);
return PyObject(); // returns None
}
ostream& Assignment::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// IfStmt
// if_stmt:
// | 'if' named_expression ':' block elif_stmt
// | 'if' named_expression ':' block [else_block]
IfStmt::IfStmt(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
IfStmt::~IfStmt() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void IfStmt::parse() {
eat_value("if", "IfStmt");
children.push_back(new NamedExpression(tokenizer, indent));
eat_value(":", "IfStmt");
children.push_back(new Block(tokenizer, indent));
// NOTE: if its an if-elif-else,
// the else block should end up in the ElifStmt production
if (peek("IfStmt").value == "elif") {
children.push_back(new ElifStmt(tokenizer, indent));
}
else if (peek("IfStmt").value == "else") {
children.push_back(new ElseBlock(tokenizer, indent));
}
}
PyObject IfStmt::evaluate(Stack stack) {
log("IfStmt::evaluate()", DEBUG); add_indent(2);
PyObject ret;
if (children.at(0)->evaluate(stack)) {
// if statement is true
ret = children.at(1)->evaluate(stack);
sub_indent(2);
return ret;
}
else if (children.size() == 3) {
// this will either be the elif_stmt or [else_block]
ret = children.at(2)->evaluate(stack);
sub_indent(2);
return ret;
}
// if statement was false and no elif_stmt or [else_block]
sub_indent(2);
return PyObject(); // returns None
}
ostream& IfStmt::print(ostream& os) const {
os << "if " << *(children.at(0)) << ":";
for (int i=1; i < children.size(); i++) {
os << *(children.at(i));
}
return os;
}
//===============================================================
// ElifStmt
// elif_stmt:
// | 'elif' named_expression ':' block elif_stmt
// | 'elif' named_expression ':' block [else_block]
ElifStmt::ElifStmt(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
_else = nullptr;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
ElifStmt::~ElifStmt() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void ElifStmt::parse() {
NamedExpression *t1;
Block *t2;
while (peek("ElifStmt").value == "elif") {
eat_value("elif", "ElifStmt");
t1 = new NamedExpression(tokenizer, indent);
eat_value(":", "ElifStmt");
t2 = new Block(tokenizer, indent);
_elifs[t1] = t2;
}
if (peek("ElifStmt").value == "else") {
_else = new ElseBlock(tokenizer, indent);
}
}
PyObject ElifStmt::evaluate(Stack stack) {
log("ElifStmt::evaluate()", DEBUG); add_indent(2);
PyObject ret;
map<NamedExpression*, Block*>::iterator it;
for (it = _elifs.begin(); it != _elifs.end(); it++) {
if (it->first->evaluate(stack)) {
// an elif was true
ret = it->second->evaluate(stack);
sub_indent(2);
return ret;
}
}
if (_else != nullptr) {
// else_block
ret = _else->evaluate(stack);
sub_indent(2);
return ret;
}
// all elifs were false and no else_block
sub_indent(2);
return PyObject(); // returns None
}
ostream& ElifStmt::print(ostream& os) const {
map<NamedExpression*, Block*>::const_iterator it;
for (it = _elifs.begin(); it != _elifs.end(); it++) {
os << indent << "elif " << *(it->first) << ":";
os << *(it->second);
}
if (_else != nullptr) {
os << *_else;
}
return os;
}
//===============================================================
// ElseBlock
// else_block: 'else' ':' block
ElseBlock::ElseBlock(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
ElseBlock::~ElseBlock() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void ElseBlock::parse() {
eat_value("else", "ElseBlock");
eat_value(":", "ElseBlock");
children.push_back(new Block(tokenizer, indent));
}
PyObject ElseBlock::evaluate(Stack stack) {
log("ElseBlock::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& ElseBlock::print(ostream& os) const {
os << indent << "else:" << *children.at(0);
return os;
}
//===============================================================
// WhileStmt
// while_stmt:
// | 'while' named_expression ':' block [else_block]
WhileStmt::WhileStmt(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
WhileStmt::~WhileStmt() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void WhileStmt::parse() {
// TODO:
}
PyObject WhileStmt::evaluate(Stack stack) {
// TODO:
log("WhileStmt::evaluate()", DEBUG); add_indent(2); sub_indent(2);
return PyObject();
}
ostream& WhileStmt::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// ForStmt
// NOTE: need to unpack
// for [a,b,c] in ["123","def"]: print(a, b, c)
// 1 2 3
// d e f
// NOTE: not block scoped (z prev undefined)
// >>> for z in range(9): pass
// >>> z
// 8
// for_stmt:
// | 'for' star_targets 'in' ~ star_expressions ':' [TYPE_COMMENT] block [else_block]
// | ASYNC 'for' star_targets 'in' ~ star_expressions ':' [TYPE_COMMENT] block [else_block]
ForStmt::ForStmt(Tokenizer *tokenizer, string indent) {
// Loop better: a deeper look at iteration in Python
// https://www.youtube.com/watch?v=V2PkkMS2Ack
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
ForStmt::~ForStmt() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void ForStmt::parse() {
// TODO:
}
PyObject ForStmt::evaluate(Stack stack) {
// TODO:
log("ForStmt::evaluate()", DEBUG); add_indent(2); sub_indent(2);
return PyObject(); // returns None
}
ostream& ForStmt::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// WithStmt
// with_stmt:
// | 'with' '(' ','.with_item+ ','? ')' ':' block
// | 'with' ','.with_item+ ':' [TYPE_COMMENT] block
// | ASYNC 'with' '(' ','.with_item+ ','? ')' ':' block
// | ASYNC 'with' ','.with_item+ ':' [TYPE_COMMENT] block
WithStmt::WithStmt(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
WithStmt::~WithStmt() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void WithStmt::parse() {
// TODO:
}
PyObject WithStmt::evaluate(Stack stack) {
// TODO:
log("WithStmt::evaluate()", DEBUG); add_indent(2); sub_indent(2);
return PyObject();
}
ostream& WithStmt::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// WithItem
// with_item:
// | expression 'as' star_target &(',' | ')' | ':')
// | expression
WithItem::WithItem(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
WithItem::~WithItem() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void WithItem::parse() {
// TODO:
}
PyObject WithItem::evaluate(Stack stack) {
// TODO:
log("WithItem::evaluate()", DEBUG); add_indent(2); sub_indent(2);
return PyObject();
}
ostream& WithItem::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// TryStmt
TryStmt::TryStmt(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
TryStmt::~TryStmt() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void TryStmt::parse() {
// TODO:
}
PyObject TryStmt::evaluate(Stack stack) {
// TODO:
log("TryStmt::evaluate()", DEBUG); add_indent(2); sub_indent(2);
return PyObject();
}
ostream& TryStmt::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// ExceptBlock
// except_block:
// | 'except' expression ['as' NAME ] ':' block
// | 'except' ':' block
ExceptBlock::ExceptBlock(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
ExceptBlock::~ExceptBlock() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void ExceptBlock::parse() {
// TODO:
}
PyObject ExceptBlock::evaluate(Stack stack) {
// TODO:
log("ExceptBlock::evaluate()", DEBUG); add_indent(2); sub_indent(2);
return PyObject();
}
ostream& ExceptBlock::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// FinallyBlock
// finally_block: 'finally' ':' block
FinallyBlock::FinallyBlock(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
FinallyBlock::~FinallyBlock() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void FinallyBlock::parse() {
// TODO:
}
PyObject FinallyBlock::evaluate(Stack stack) {
// TODO:
log("FinallyBlock::evaluate()", DEBUG); add_indent(2); sub_indent(2);
return PyObject();
}
ostream& FinallyBlock::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// ReturnStmt
// return_stmt:
// | 'return' [star_expressions]
ReturnStmt::ReturnStmt(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
ReturnStmt::~ReturnStmt() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void ReturnStmt::parse() {
eat_value("return", "ReturnStmt");
children.push_back(new StarExpressions(tokenizer, indent));
}
PyObject ReturnStmt::evaluate(Stack stack) {
log("ReturnStmt::evaluate()", DEBUG); add_indent(2);
PyObject temp = children.at(0)->evaluate(stack);
this->return_value = temp;
stack.set_return_value(this->return_value);
sub_indent(2);
return PyObject(); // this value doesnt matter
}
ostream& ReturnStmt::print(ostream& os) const {
os << "return " << *children.at(0);
return os;
}
//===============================================================
// FunctionDef
// function_def:
// | decorators function_def_raw
// | function_def_raw
FunctionDef::FunctionDef(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
FunctionDef::~FunctionDef() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
delete this->raw;
}
void FunctionDef::parse() {
this->raw = new FunctionDefRaw(tokenizer, indent);
}
PyObject FunctionDef::evaluate(Stack stack) {
log("FunctionDef::evaluate()", DEBUG); add_indent(2);
// add function definition to stack/frame
stack.add_function(this);
// function definition shouldnt return anything
sub_indent(2);
return PyObject();
}
ostream& FunctionDef::print(ostream& os) const {
os << *this->raw;
return os;
}
//===============================================================
// FunctionDefRaw
// function_def_raw:
// | 'def' NAME '(' [params] ')' ['->' expression ] ':' [func_type_comment] block
// | ASYNC 'def' NAME '(' [params] ')' ['->' expression ] ':' [func_type_comment] block
FunctionDefRaw::FunctionDefRaw(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
FunctionDefRaw::~FunctionDefRaw() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
delete this->body;
delete this->params;
tokenizer->rewind(1); // name
sub_indent(2);
}
void FunctionDefRaw::parse() {
eat_value("def", "FunctionDefRaw");
this->name = next_token().value;
eat_value("(", "FunctionDefRaw");
this->params = new Params(tokenizer, indent);
eat_value(")", "FunctionDefRaw");
eat_value(":", "FunctionDefRaw");
this->body = new Block(tokenizer, indent);
}
PyObject FunctionDefRaw::evaluate(Stack stack) {
log("FunctionDefRaw::evaluate()", DEBUG); add_indent(2); sub_indent(2);
// function definition shouldnt return anything
return PyObject();
}
ostream& FunctionDefRaw::print(ostream& os) const {
os << "def " << name << "(" << *params << "):" << *body;
return os;
}
//===============================================================
// Params
// params:
// | parameters
Params::Params(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Params::~Params() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Params::parse() {
children.push_back(new Parameters(tokenizer, indent));
}
PyObject Params::evaluate(Stack stack) {
log("Params::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return PyObject();
}
ostream& Params::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// Parameters
// NOTE: slash_no_default vs slash_with_default are important
// no_default uses + while with_default uses *
// parameters:
// | slash_no_default param_no_default* param_with_default* [star_etc]
// | slash_with_default param_with_default* [star_etc]
// | param_no_default+ param_with_default* [star_etc]
// | param_with_default+ [star_etc]
// | star_etc
Parameters::Parameters(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Parameters::~Parameters() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Parameters::parse() {
// NOTE: parsing this thing is gonna be weird, my main goal is to determine two things:
// 1. does it need to swap from no_default -> with_default
// 2. did it find a /, to be lazy im gonna lookahead for the / first
// I'm checking these by checking the amount of children in the AST after parsing
// , if 0 then mismatched
int i = 0;
while(lookahead(i).value != "/" && lookahead(i).value != ")") i++;
if (lookahead(i).value == "/" ) {
SlashNoDefault* snd = new SlashNoDefault(tokenizer, indent);
if (snd->children.size() > 0) {
// | slash_no_default param_no_default* param_with_default* [star_etc]
children.push_back(snd);
ParamNoDefault* pnd;
while (1) {
pnd = new ParamNoDefault(tokenizer, indent);
if (pnd->children.size() == 0) {
delete pnd;
break;
}
else { children.push_back(pnd); }
}
while (peek("Parameters").value != "*"
&& peek("Parameters").value != "**" && peek("Parameters").value != ")") {
children.push_back(new ParamWithDefault(tokenizer, indent));
}
}
else {
// | slash_with_default param_with_default* [star_etc]
delete snd;
children.push_back(new SlashWithDefault(tokenizer, indent));
while (peek("Parameters").value != "*"
&& peek("Parameters").value != "**" && peek("Parameters").value != ")") {
children.push_back(new ParamWithDefault(tokenizer, indent));
}
}
}
else {
// | param_no_default+ param_with_default* [star_etc]
// | param_with_default+ [star_etc]
ParamNoDefault* pnd;
while (1) {
pnd = new ParamNoDefault(tokenizer, indent);
if (pnd->children.size() == 0) {
delete pnd;
break;
}
else { children.push_back(pnd); }
}
while (peek("Parameters").value != "*"
&& peek("Parameters").value != "**" && peek("Parameters").value != ")") {
children.push_back(new ParamWithDefault(tokenizer, indent));
}
}
// all productions end with optional star_etc
if (peek("Parameters").value == "*" || peek("Parameters").value == "**") {
children.push_back(new StarEtc(tokenizer, indent));
}
}
PyObject Parameters::evaluate(Stack stack) {
log("Parameters::evaluate()", DEBUG); add_indent(2);
vector<PyObject> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
sub_indent(2);
return PyObject(results, "tuple");
}
ostream& Parameters::print(ostream& os) const {
for (AST* child : children) os << *child;
return os;
}
//===============================================================
// SlashNoDefault
// slash_no_default:
// | param_no_default+ '/' ','
// | param_no_default+ '/' &')'
SlashNoDefault::SlashNoDefault(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
SlashNoDefault::~SlashNoDefault() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void SlashNoDefault::parse() {
// push as many param_no_default's as possible, if any are a with_default, return 0 children
while(peek("SlashNoDefault").value != "="
&& peek("SlashNoDefault").value != "/" && peek("SlashNoDefault").value != ")") {
children.push_back(new ParamNoDefault(tokenizer, indent));
}
if (peek("SlashNoDefault").value == "=") {
// should have been a SlashWithDefault
children.clear();
sub_indent(2);
return;
}
eat_value("/", "SlashNoDefault");
if (peek("SlashNoDefault").value == ",") {
eat_value(",", "SlashNoDefault");
}
else if (peek("SlashNoDefault").value != ")") {
throw runtime_error("SyntaxError: invalid syntax");
}
}
PyObject SlashNoDefault::evaluate(Stack stack) {
log("SlashNoDefault::evaluate()", DEBUG); add_indent(2);
sub_indent(2);
return PyObject();
}
ostream& SlashNoDefault::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// SlashWithDefault
// slash_with_default:
// | param_no_default* param_with_default+ '/' ','
// | param_no_default* param_with_default+ '/' &')'
SlashWithDefault::SlashWithDefault(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
SlashWithDefault::~SlashWithDefault() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void SlashWithDefault::parse() {
ParamNoDefault* pnd;
while (1) {
pnd = new ParamNoDefault(tokenizer, indent);
if (pnd->children.size() == 0) {
delete pnd;
break;
}
else { children.push_back(pnd); }
}
while (peek("SlashWithDefault").value != "/" && peek("SlashWithDefault").value != ")") {
children.push_back(new ParamWithDefault(tokenizer, indent));
}
eat_value("/", "SlashWithDefault");
if (peek("SlashWithDefault").value == ",") {
eat_value(",", "SlashWithDefault");
}
else if (peek("SlashWithDefault").value != ")") {
throw runtime_error("SyntaxError: invalid syntax");
}
}
PyObject SlashWithDefault::evaluate(Stack stack) {
log("SlashWithDefault::evaluate()", DEBUG); add_indent(2);
sub_indent(2);
return PyObject();
}
ostream& SlashWithDefault::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// StarEtc
// star_etc:
// | '*' param_no_default param_maybe_default* [kwds]
// | '*' ',' param_maybe_default+ [kwds]
// | kwds
StarEtc::StarEtc(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
StarEtc::~StarEtc() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void StarEtc::parse() {
if (peek("StarEtc").value == "*") {
eat_value("*", "StarEtc");
if (peek("StarEtc").value == ",") {
// '*' ',' param_maybe_default+ [kwds]
eat_value(",", "StarEtc");
children.push_back(new ParamMaybeDefault(tokenizer, indent));
}
else {
// '*' param_no_default param_maybe_default* [kwds]
children.push_back(new ParamNoDefault(tokenizer, indent));
while(peek("StarEtc").value != "**" && peek("StarEtc").value != ")") {
children.push_back(new ParamMaybeDefault(tokenizer, indent));
}
}
}
// all productions have a potential kwds at the end
if (peek("StarEtc").value == "**") {
children.push_back(new Kwds(tokenizer, indent));
}
if (children.size() == 0) {
throw runtime_error("Reached end of StarEtc with no children");
}
}
PyObject StarEtc::evaluate(Stack stack) {
log("StarEtc::evaluate()", DEBUG); add_indent(2);
vector<PyObject> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
sub_indent(2);
return PyObject(results, "tuple");
}
ostream& StarEtc::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// Kwds
// kwds: '**' param_no_default
Kwds::Kwds(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Kwds::~Kwds() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Kwds::parse() {
eat_value("**", "Kwds");
children.push_back(new ParamNoDefault(tokenizer, indent));
}
PyObject Kwds::evaluate(Stack stack) {
log("Kwds::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& Kwds::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// ParamNoDefault
// param_no_default:
// | param ',' TYPE_COMMENT?
// | param TYPE_COMMENT? &')'
ParamNoDefault::ParamNoDefault(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
ParamNoDefault::~ParamNoDefault() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void ParamNoDefault::parse() {
if (peek("ParamNoDefault").value != ")") {
children.push_back(new Param(tokenizer, indent));
if (peek("ParamNoDefault").value == "=") {
// this actually should have been a with_default,
// signal by returning w/ 0 children
children.pop_back();
return;
}
if (peek("ParamNoDefault").value == ",") {
eat_value(",", "ParamNoDefault");
}
}
}
PyObject ParamNoDefault::evaluate(Stack stack) {
log("ParamNoDefault::evaluate()", DEBUG); add_indent(2);
PyObject param_name = children.at(0)->evaluate(stack);
PyObject arg = stack.next_param();
// if (get<0>(arg) != PyObject() && get<0>(arg) != param_name) {
// string func_name = stack.get_function_name();
// throw runtime_error(
// "TypeError: " + func_name + "() got an unexpected keyword argument '"
// + get<0>(arg).as_string() + "'");
// }
sub_indent(2);
return PyObject();
}
ostream& ParamNoDefault::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// ParamWithDefault
// param_with_default:
// | param default ',' TYPE_COMMENT?
// | param default TYPE_COMMENT? &')'
ParamWithDefault::ParamWithDefault(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
ParamWithDefault::~ParamWithDefault() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void ParamWithDefault::parse() {
if (peek("ParamNoDefault").value != ")") {
children.push_back(new Param(tokenizer, indent));
children.push_back(new Default(tokenizer, indent));
if (peek("ParamNoDefault").value == ",") {
eat_value(",", "ParamNoDefault");
}
}
}
PyObject ParamWithDefault::evaluate(Stack stack) {
log("ParamWithDefault::evaluate()", DEBUG); add_indent(2);
sub_indent(2);
return PyObject();
}
ostream& ParamWithDefault::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// ParamMaybeDefault
// param_maybe_default:
// | param default? ',' TYPE_COMMENT?
// | param default? TYPE_COMMENT? &')'
ParamMaybeDefault::ParamMaybeDefault(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
ParamMaybeDefault::~ParamMaybeDefault() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void ParamMaybeDefault::parse() {
if (peek("ParamMaybeDefault").value != ")") {
children.push_back(new Param(tokenizer, indent));
Default* d = new Default(tokenizer, indent);
if (d->children.size() == 0) {
delete d;
}
else {
children.push_back(d);
}
if (peek("ParamMaybeDefault").value == ",") {
eat_value(",", "ParamMaybeDefault");
}
}
}
PyObject ParamMaybeDefault::evaluate(Stack stack) {
log("ParamMaybeDefault::evaluate()", DEBUG); add_indent(2);
sub_indent(2);
return PyObject();
}
ostream& ParamMaybeDefault::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// Param
// param: NAME annotation?
Param::Param(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Param::~Param() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Param::parse() {
this->name = new Name(tokenizer, indent);
}
PyObject Param::evaluate(Stack stack) {
log("Param::evaluate()", DEBUG);
// NOTE: calling evaluate on the Name* will call get_value()
// on the stack, I just want the actual name of the Param
return PyObject(this->name->token.value, "str");
}
ostream& Param::print(ostream& os) const {
os << this->name->token.value;
return os;
}
//===============================================================
// Default
// default: '=' expression
Default::Default(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Default::~Default() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Default::parse() {
if (peek("Default").value == "=") {
eat_value("=", "Default");
children.push_back(new Expression(tokenizer, indent));
}
// NOTE: if 0 children case is for maybe_default productions
}
PyObject Default::evaluate(Stack stack) {
log("Default::evaluate()", DEBUG); add_indent(2);
return children.at(0)->evaluate(stack);
sub_indent(2);
return PyObject();
}
ostream& Default::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// Block
// NOTE: I am intentionally not calling Statements here, using Statement instead
// block:
// | NEWLINE INDENT statements DEDENT
// | simple_stmt
Block::Block(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Block::~Block() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Block::parse() {
// the NEWLINE can be optional, for instance one liner function like
// def a(): return 1
// if this happens it will also not have an INDENT or DEDENT
// consequently it will only have 1 Statement
if (peek("Block").type == "NEWLINE") {
this->has_newline = true;
eat_type("NEWLINE", "Block");
this->indent = peek("Block").value;
eat_type("INDENT", "Block");
while (peek("Block").type != "DEDENT") {
children.push_back(new Statement(tokenizer, indent));
}
eat_type("DEDENT", "Block");
}
else {
this->has_newline = false;
this->indent = "";
children.push_back(new Statement(tokenizer, indent));
}
}
PyObject Block::evaluate(Stack stack) {
log("Block::evaluate()", DEBUG); add_indent(2);
for (AST* child : children) {
child->evaluate(stack);
if (stack.is_returning()) {
sub_indent(2);
return PyObject();
}
}
sub_indent(2);
return PyObject(); // Blocks dont return anything
}
ostream& Block::print(ostream& os) const {
if (has_newline) {
for (AST *child : children) {
os << endl << indent << *child;
}
}
else {
os << *children.at(0);
}
return os;
}
//===============================================================
// StarExpressions
// NOTE: basically identical to Expressions
// star_expressions:
// | star_expression (',' star_expression )+ [',']
// | star_expression ','
// | star_expression
StarExpressions::StarExpressions(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
StarExpressions::~StarExpressions() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void StarExpressions::parse() {
children.push_back(new StarExpression(tokenizer, indent));
while(peek("StarExpressions").value == ",") {
children.push_back(new StarExpression(tokenizer, indent));
}
}
PyObject StarExpressions::evaluate(Stack stack) {
log("StarExpressions::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<PyObject> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
sub_indent(2);
return PyObject(results, "tuple");
}
ostream& StarExpressions::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// StarExpression
// star_expression:
// | '*' bitwise_or
// | expression
StarExpression::StarExpression(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
StarExpression::~StarExpression() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void StarExpression::parse() {
if (peek("StarExpression").value == "*") {
children.push_back(new Op(tokenizer, indent));
children.push_back(new BitwiseOr(tokenizer, indent));
}
else {
children.push_back(new Expression(tokenizer, indent));
}
}
PyObject StarExpression::evaluate(Stack stack) {
log("StarExpression::evaluate()", DEBUG); add_indent(2);
// TODO: figure out how the * grammar works in practice
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& StarExpression::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// StarNamedExpressions
// star_named_expressions: ','.star_named_expression+ [',']
StarNamedExpressions::StarNamedExpressions(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
StarNamedExpressions::~StarNamedExpressions() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void StarNamedExpressions::parse() {
children.push_back(new StarNamedExpression(tokenizer, indent));
while (peek("StarNamedExpressions").value == ",") {
eat_value(",", "StarNamedExpressions");
children.push_back(new StarNamedExpression(tokenizer, indent));
}
}
PyObject StarNamedExpressions::evaluate(Stack stack) {
log("StarNamedExpressions::evaluate()", DEBUG); add_indent(2);
// NOTE: this always needs to return an iterable
vector<PyObject> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
sub_indent(2);
return PyObject(results, "tuple");
}
ostream& StarNamedExpressions::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// StarNamedExpression
// star_named_expression:
// | '*' bitwise_or
// | named_expression
StarNamedExpression::StarNamedExpression(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
StarNamedExpression::~StarNamedExpression() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void StarNamedExpression::parse() {
log("StarNamedExpression::evaluate()", DEBUG); add_indent(2);
if (peek("StarNamedExpression").value == "*") {
children.push_back(new Op(tokenizer, indent));
children.push_back(new BitwiseOr(tokenizer, indent));
}
else {
children.push_back(new NamedExpression(tokenizer, indent));
}
}
PyObject StarNamedExpression::evaluate(Stack stack) {
// TODO: figure out how the star is gonna work
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& StarNamedExpression::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// NamedExpression
// named_expression:
// | NAME ':=' ~ expression
// | expression !':='
NamedExpression::NamedExpression(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
NamedExpression::~NamedExpression() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void NamedExpression::parse() {
// TODO: handle ':=' case
children.push_back(new Expression(tokenizer, indent));
}
PyObject NamedExpression::evaluate(Stack stack) {
log("NamedExpression::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& NamedExpression::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Expressions
// NOTE: falls back to tuples
// >>> 2+2,1-1
// (4, 0)
// NOTE: basically identical to StarExpressions
// expressions:
// | expression (',' expression )+ [',']
// | expression ','
// | expression
Expressions::Expressions(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Expressions::~Expressions() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Expressions::parse() {
children.push_back(new Expression(tokenizer, indent));
while(peek("Expressions").value == ",") {
children.push_back(new Expression(tokenizer, indent));
}
}
PyObject Expressions::evaluate(Stack stack) {
log("Expressions::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<PyObject> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
sub_indent(2);
return PyObject(results, "tuple");
}
ostream& Expressions::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Expression
// expression:
// | disjunction 'if' disjunction 'else' expression
// | disjunction
// | lambdef
Expression::Expression(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Expression::~Expression() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Expression::parse() {
// NOTE: skipping lambdef
if (lookahead(1).value == "if") {
}
children.push_back(new Disjunction(tokenizer, indent));
}
PyObject Expression::evaluate(Stack stack) {
log("Expression::evaluate()", DEBUG); add_indent(2);
// TODO: implement case (1)
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
throw runtime_error("reached end of Expression::evaluate() without returning");
}
ostream& Expression::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Disjunction
// disjunction:
// | conjunction ('or' conjunction )+
// | conjunction
Disjunction::Disjunction(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Disjunction::~Disjunction() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Disjunction::parse() {
children.push_back(new Conjunction(tokenizer, indent));
while(peek("Disjunction").value == "or") {
eat_value("or", "Disjunction");
children.push_back(new Conjunction(tokenizer, indent));
}
}
PyObject Disjunction::evaluate(Stack stack) {
log("Disjunction::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<bool> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
bool result = accumulate(
results.begin(), results.end(), results.at(0), _boolean_or);
sub_indent(2);
return PyObject(result, "bool");
}
ostream& Disjunction::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Conjunction
// conjunction:
// | inversion ('and' inversion )+
// | inversion
Conjunction::Conjunction(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Conjunction::~Conjunction() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Conjunction::parse() {
children.push_back(new Inversion(tokenizer, indent));
while(peek("Conjunction").value == "and") {
eat_value("and", "Conjunction");
children.push_back(new Inversion(tokenizer, indent));
}
}
PyObject Conjunction::evaluate(Stack stack) {
log("Conjunction::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<bool> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
bool result = accumulate(
results.begin(), results.end(), results.at(0), _boolean_and);
sub_indent(2);
return PyObject(result, "bool");
}
ostream& Conjunction::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Inversion
// inversion:
// | 'not' inversion
// | comparison
Inversion::Inversion(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Inversion::~Inversion() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Inversion::parse() {
if (peek("Inversion").value == "not") {
children.push_back(new Op(tokenizer, indent));
}
children.push_back(new Comparison(tokenizer, indent));
}
PyObject Inversion::evaluate(Stack stack) {
log("Inversion::evaluate()", DEBUG); add_indent(2);
PyObject s = children.at(0)->evaluate(stack);
if (s.type == "str" && s.as_string() == "not") {
bool b = children.at(1)->evaluate(stack);
sub_indent(2);
return PyObject(!b, "bool");
}
sub_indent(2);
return s;
}
ostream& Inversion::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Comparison
// comparison:
// | bitwise_or compare_op_bitwise_or_pair+
// | bitwise_or
// compare_op_bitwise_or_pair:
// | eq_bitwise_or
// | noteq_bitwise_or
// | lte_bitwise_or
// | lt_bitwise_or
// | gte_bitwise_or
// | gt_bitwise_or
// | notin_bitwise_or
// | in_bitwise_or
// | isnot_bitwise_or
// | is_bitwise_or
Comparison::Comparison(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Comparison::~Comparison() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Comparison::parse() {
children.push_back(new BitwiseOr(tokenizer, indent));
while (is_comparison_op(tokenizer)) {
children.push_back(new Op(tokenizer, indent));
children.push_back(new BitwiseOr(tokenizer, indent));
}
}
PyObject Comparison::evaluate(Stack stack) {
log("Comparison::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<PyObject> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
while (results.size() > 1) {
string op = results.at(1);
PyObject right = results.at(2);
results.at(0) = apply_comparison_op(results.at(0), op, right);
results.erase(results.begin()+1, results.begin()+3);
}
sub_indent(2);
return results.front();
}
ostream& Comparison::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// BitwiseOr
// bitwise_or:
// | bitwise_or '|' bitwise_xor
// | bitwise_xor
BitwiseOr::BitwiseOr(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
BitwiseOr::~BitwiseOr() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void BitwiseOr::parse() {
children.push_back(new BitwiseXor(tokenizer, indent));
while (peek("BitwiseOr").value == "|") {
eat_value("|", "BitwiseOr");
children.push_back(new BitwiseXor(tokenizer, indent));
}
}
PyObject BitwiseOr::evaluate(Stack stack) {
log("BitwiseOr::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<int> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
int result = accumulate(
results.begin(), results.end(), results.at(0), _bitwise_or);
sub_indent(2);
return PyObject(result, "int");
}
ostream& BitwiseOr::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// BitwiseXor
// bitwise_xor:
// | bitwise_xor '^' bitwise_and
// | bitwise_and
BitwiseXor::BitwiseXor(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
BitwiseXor::~BitwiseXor() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void BitwiseXor::parse() {
children.push_back(new BitwiseAnd(tokenizer, indent));
while (peek("BitwiseXor").value == "^") {
eat_value("^", "BitwiseXor");
children.push_back(new BitwiseAnd(tokenizer, indent));
}
}
PyObject BitwiseXor::evaluate(Stack stack) {
log("BitwiseXor::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<int> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
int result = accumulate(
results.begin(), results.end(), results.at(0), _bitwise_xor);
sub_indent(2);
return PyObject(result, "int");
}
ostream& BitwiseXor::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// BitwiseAnd
// bitwise_and:
// | bitwise_and '&' shift_expr
// | shift_expr
BitwiseAnd::BitwiseAnd(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
BitwiseAnd::~BitwiseAnd() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void BitwiseAnd::parse() {
children.push_back(new ShiftExpr(tokenizer, indent));
while (peek("BitwiseAnd").value == "&") {
eat_value("&", "BitwiseAnd");
children.push_back(new ShiftExpr(tokenizer, indent));
}
}
PyObject BitwiseAnd::evaluate(Stack stack) {
log("BitwiseAnd::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<int> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
int result = accumulate(
results.begin(), results.end(), results.at(0), _bitwise_and);
sub_indent(2);
return PyObject(result, "int");
}
ostream& BitwiseAnd::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// ShiftExpr
// shift_expr:
// | shift_expr '<<' sum
// | shift_expr '>>' sum
// | sum
ShiftExpr::ShiftExpr(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
ShiftExpr::~ShiftExpr() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void ShiftExpr::parse() {
children.push_back(new Sum(tokenizer, indent));
while (peek("ShiftExpr").value == "<<" || peek("ShiftExpr").value == ">>") {
children.push_back(new Op(tokenizer, indent));
children.push_back(new Sum(tokenizer, indent));
}
}
PyObject ShiftExpr::evaluate(Stack stack) {
log("ShiftExpr::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<PyObject> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
while (results.size() > 1) {
string op = results.at(1);
PyObject right = results.at(2);
results.at(0) = apply_shift_op(results.at(0), op, right);
results.erase(results.begin()+1, results.begin()+3);
}
sub_indent(2);
return results.front();
}
ostream& ShiftExpr::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Sum
// sum:
// | sum '+' term
// | sum '-' term
// | term
Sum::Sum(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Sum::~Sum() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Sum::parse() {
children.push_back(new Term(tokenizer, indent));
while(is_sum_op(peek("Sum").value)) {
children.push_back(new Op(tokenizer, indent));
children.push_back(new Term(tokenizer, indent));
}
}
PyObject Sum::evaluate(Stack stack) {
log("Sum::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<PyObject> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
while (results.size() > 1) {
string op = results.at(1);
PyObject right = results.at(2);
results.at(0) = apply_sum_op(results.at(0), op, right);
results.erase(results.begin()+1, results.begin()+3);
}
sub_indent(2);
return results.front();
}
ostream& Sum::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Term
// term:
// | term '*' factor
// | term '/' factor
// | term '//' factor
// | term '%' factor
// | term '@' factor
// | factor
Term::Term(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Term::~Term() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Term::parse() {
children.push_back(new Factor(tokenizer, indent));
while(is_term_op(peek("Term").value)) {
children.push_back(new Op(tokenizer, indent));
children.push_back(new Factor(tokenizer, indent));
}
}
PyObject Term::evaluate(Stack stack) {
log("Term::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<PyObject> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
while (results.size() > 1) {
string op = results.at(1);
PyObject right = results.at(2);
results.at(0) = apply_term_op(results.at(0), op, right);
results.erase(results.begin()+1, results.begin()+3);
}
sub_indent(2);
return results.front();
}
ostream& Term::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Factor
// factor:
// | '+' factor
// | '-' factor
// | '~' factor
// | power
Factor::Factor(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Factor::~Factor() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Factor::parse() {
if (is_factor_op(peek("Factor").value)) {
if (peek("Factor").value == "+") {
eat_value("+", "Factor"); // the '+' doesn't really do anything
}
children.push_back(new Op(tokenizer, indent));
}
children.push_back(new Power(tokenizer, indent));
}
PyObject Factor::evaluate(Stack stack) {
log("Factor::evaluate()", DEBUG); add_indent(2);
if (children.size() == 1) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
string op = children.at(0)->evaluate(stack);
PyObject val = children.at(1)->evaluate(stack);
sub_indent(2);
if (op == "-") {
if (val.type == "int") {
return PyObject(-(int)val, "int");
}
else if (val.type == "float") {
return PyObject(-(float)val, "float");
}
else if (val.type == "bool") {
return PyObject(-(bool)val, "bool");
}
else {
throw runtime_error("Unsupported PyObject of type \'"
+ val.type + "\' in Factor::evaluate()\n");
}
}
if (op == "~") {
return PyObject((int)(~val), "int");
}
throw runtime_error("reached end of Factor::evaluate() without returning");
}
ostream& Factor::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Power
// power:
// | await_primary '**' factor
// | await_primary
Power::Power(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Power::~Power() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Power::parse() {
children.push_back(new AwaitPrimary(tokenizer, indent));
if (peek("Power").value == "**") {
eat_value("**", "Power");
children.push_back(new Factor(tokenizer, indent));
}
}
PyObject Power::evaluate(Stack stack) {
log("Power::evaluate()", DEBUG); add_indent(2);
PyObject ret;
if (children.size() == 1){
ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ret = children.at(0)->evaluate(stack)._pow(children.at(1)->evaluate(stack));
sub_indent(2);
return ret;
}
ostream& Power::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// AwaitPrimary
// await_primary:
// | AWAIT primary
// | primary
AwaitPrimary::AwaitPrimary(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
AwaitPrimary::~AwaitPrimary() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void AwaitPrimary::parse() {
// TODO: implement this completely
children.push_back(new Primary(tokenizer, indent));
}
PyObject AwaitPrimary::evaluate(Stack stack) {
log("AwaitPrimary::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& AwaitPrimary::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Primary
// primary:
// | invalid_primary # must be before 'primay genexp' because of invalid_genexp
// | primary '.' NAME
// | primary genexp
// | primary '(' [arguments] ')'
// | primary '[' slices ']'
// | atom
Primary::Primary(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Primary::~Primary() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Primary::parse() {
// NOTE: this is supposed to be a left recusive production
// im keeping it simple atm but its likely that a while loop will
// be needed like Term, Sum, etc
children.push_back(new Atom(tokenizer, indent));
if (peek("Primary").value == ".") {
// TODO: implement
throw runtime_error("Primary: '.' not implemented");
} else if(peek("Primary").value == "(") {
children.push_back(new Op(tokenizer, indent)); // (
children.push_back(new Arguments(tokenizer, indent));
children.push_back(new Op(tokenizer, indent)); // )
}
}
PyObject Primary::evaluate(Stack stack) {
log("Primary::evaluate()", DEBUG); add_indent(2);
PyObject ret;
if (children.size() == 1) {
ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
else {
PyObject c1 = children.at(1)->evaluate(stack);
if ((string)c1 == "(") {
PyObject func_name = children.at(0)->evaluate(stack);
PyObject arguments = children.at(2)->evaluate(stack);
PyObject ret = stack.call_function(func_name, arguments);
sub_indent(2);
return ret;
}
}
throw runtime_error("reached end of Primary::evaluate() without returning");
}
ostream& Primary::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// Slices
// slices:
// | slice !','
// | ','.slice+ [',']
Slices::Slices(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Slices::~Slices() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Slices::parse() {
}
PyObject Slices::evaluate(Stack stack) {
throw runtime_error("Slices::evaluate() not implemented");
}
ostream& Slices::print(ostream& os) const {
return os;
}
//===============================================================
// Slice
// slice:
// | [expression] ':' [expression] [':' [expression] ]
// | expression
Slice::Slice(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Slice::~Slice() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Slice::parse() {
}
PyObject Slice::evaluate(Stack stack) {
throw runtime_error("Slice::evaluate() not implemented");
}
ostream& Slice::print(ostream& os) const {
return os;
}
//===============================================================
// Atom
// atom:
// | NAME
// | 'True'
// | 'False'
// | 'None'
// | '__peg_parser__'
// | strings
// | NUMBER
// | (tuple | group | genexp)
// | (list | listcomp)
// | (dict | set | dictcomp | setcomp)
// | '...'
Atom::Atom(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Atom::~Atom() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Atom::parse() {
cout << peek("Atom").value.size() << endl;
if (is_number(peek("Atom").value)) {
children.push_back(new Number(tokenizer, indent));
}
else if (peek("Atom").value == "True" || peek("Atom").value == "False") {
children.push_back(new Bool(tokenizer, indent));
}
else if (peek("Atom").value == "(") {
// TODO: figure out a cleaner way to determine if this should be
// a tuple, group, or genexp
children.push_back(new Tuple(tokenizer, indent));
}
else if (peek("Atom").value == "[") {
// TODO: figure out a cleaner way to determine if this should be
// a list or listcomp
children.push_back(new List(tokenizer, indent));
}
else if (peek("Atom").value.at(0) == '"' || peek("Atom").value.at(0) == '\'') {
children.push_back(new _String(tokenizer, indent));
}
else {
children.push_back(new Name(tokenizer, indent));
}
cout << peek("Atom").value.size() << endl;
}
PyObject Atom::evaluate(Stack stack) {
log("Atom::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
ostream& Atom::print(ostream& os) const {
for (AST *child : children) {
os << *child;
}
return os;
}
//===============================================================
// List
// list:
// | '[' [star_named_expressions] ']'
List::List(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
List::~List() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void List::parse() {
eat_value("[", "List");
children.push_back(new StarNamedExpressions(tokenizer, indent));
eat_value("]", "List");
}
PyObject List::evaluate(Stack stack) {
log("List::evaluate()", DEBUG); add_indent(2);
PyObject ret = PyObject(children.at(0)->evaluate(stack).as_list(), "list");
sub_indent(2);
return ret;
}
ostream& List::print(ostream& os) const {
os << "[";
if (children.size() > 0) {
for (int i=0; i < children.size()-1; i++) {
os << *(children.at(i)) << ",";
}
os << *children.back();
}
os << "]";
return os;
}
//===============================================================
// Tuple
// NOTE: a tuple most contain 1 or more commas
// >>> (1)
// 1
// >>> (1,)
// (1,)
// tuple:
// | '(' [star_named_expression ',' [star_named_expressions] ] ')'
Tuple::Tuple(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Tuple::~Tuple() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Tuple::parse() {
eat_value("(", "Tuple");
if (peek("Tuple").value != ")") {
children.push_back(new StarNamedExpression(tokenizer, indent));
eat_value(",", "Tuple");
}
if (peek("Tuple").value != ")") {
children.push_back(new StarNamedExpressions(tokenizer, indent));
}
eat_value(")", "Tuple");
}
PyObject Tuple::evaluate(Stack stack) {
log("Tuple::evaluate()", DEBUG); add_indent(2);
if (children.size() == 0) {
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return ret;
}
vector<PyObject> results;
for (AST *child : children) {
results.push_back(child->evaluate(stack));
}
sub_indent(2);
return PyObject(results, "tuple");
}
ostream& Tuple::print(ostream& os) const {
os << "(";
if (children.size() > 0) {
for (int i=0; i < children.size()-1; i++) {
os << *(children.at(i)) << ",";
}
os << *children.back();
}
os << ")";
return os;
}
//===============================================================
// Arguments
// arguments:
// | args [','] &')'
Arguments::Arguments(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Arguments::~Arguments() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Arguments::parse() {
children.push_back(new Args(tokenizer, indent));
if (peek("Arguments").value == ",") {
eat_value(",", "Arguments");
}
if (peek("Arguments").value != ")") {
throw runtime_error("SyntaxError: invalid syntax");
}
}
PyObject Arguments::evaluate(Stack stack) {
log("Arguments::evaluate()", DEBUG); add_indent(2);
children.at(0)->evaluate(stack);
sub_indent(2);
return PyObject();
}
ostream& Arguments::print(ostream& os) const {
os << *children.at(0);
return os;
}
//===============================================================
// Args
// NOTE: the negative lookahead ( !'=' ) is the indicator to swap to kwargs
// args:
// | ','.(starred_expression | named_expression !'=')+ [',' kwargs ]
// | kwargs
Args::Args(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Args::~Args() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Args::parse() {
if (peek("Args").value == ")") return;
StarredExpression* se;
NamedExpression* ne;
while (1) {
if (peek("Args").value == "*") {
se = new StarredExpression(tokenizer, indent);
if (peek("Args").value == "=") {
delete se;
break;
}
else { children.push_back(se); }
if (peek("Args").value == ")") {
break;
}
}
else {
ne = new NamedExpression(tokenizer, indent);
if (peek("Args").value == "=") {
delete ne;
break;
} else { children.push_back(ne); }
if (peek("Args").value == ")") {
break;
}
}
if (peek("Args").value == ",") {
eat_value(",", "Args");
}
}
if (peek("Args").value != ")") {
children.push_back(new Kwargs(tokenizer, indent));
}
}
PyObject Args::evaluate(Stack stack) {
log("Args::evaluate()", DEBUG); add_indent(2);
vector<PyObject> arguments;
for (AST* child : children) {
arguments.push_back(child->evaluate(stack));
}
sub_indent(2);
return PyObject(arguments, "list");
}
ostream& Args::print(ostream& os) const {
if (children.size() > 0) {
for (int i=0; i < children.size()-1; i++) {
os << *children.at(i) << ",";
}
os << *children.back();
}
return os;
}
//===============================================================
// Kwargs
// kwargs:
// | ','.kwarg_or_starred+ ',' ','.kwarg_or_double_starred+
// | ','.kwarg_or_starred+
// | ','.kwarg_or_double_starred+
Kwargs::Kwargs(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
Kwargs::~Kwargs() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void Kwargs::parse() {
}
PyObject Kwargs::evaluate(Stack stack) {
log("Kwargs::evaluate()", DEBUG); add_indent(2);
sub_indent(2);
return PyObject();
}
ostream& Kwargs::print(ostream& os) const {
if (children.size() > 0) {
for (int i=0; i < children.size()-1; i++) {
os << *children.at(i) << ",";
}
os << *children.back();
}
return os;
}
//===============================================================
// StarredExpression
// starred_expression:
// | '*' expression
StarredExpression::StarredExpression(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG); add_indent(2);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
sub_indent(2);
log(__FUNCTION__ + (string)" - children.size() == " + to_string(children.size()), DEBUG);
}
StarredExpression::~StarredExpression() {
log(__FUNCTION__, DEBUG); add_indent(2);
for (AST* child : children) delete child;
children.clear();
sub_indent(2);
}
void StarredExpression::parse() {
eat_value("*", "StarredExpression");
children.push_back(new Expression(tokenizer, indent));
}
PyObject StarredExpression::evaluate(Stack stack) {
log("StarredExpression::evaluate()", DEBUG); add_indent(2);
PyObject ret = children.at(0)->evaluate(stack);
sub_indent(2);
return PyObject();
}
ostream& StarredExpression::print(ostream& os) const {
os << "*" << *children.at(0);
return os;
}
//===============================================================
// Op
Op::Op(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
log(__FUNCTION__ + (string)" - token.value == '" + token.value + "'", DEBUG);
}
Op::~Op() {
log(__FUNCTION__, DEBUG);
tokenizer->rewind(1);
}
void Op::parse() {
this->token = tokenizer->next_token();
}
PyObject Op::evaluate(Stack stack) {
log("Op::evaluate() - '" + this->token.value + "'", DEBUG);
return PyObject(this->token.value, "str");
}
ostream& Op::print(ostream& os) const {
os << token.value;
return os;
}
//===============================================================
// String
_String::_String(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
log(__FUNCTION__ + (string)" - this->value == '" + this->value + "'", DEBUG);
}
_String::~_String() {
log(__FUNCTION__, DEBUG);
tokenizer->rewind(1);
}
void _String::parse() {
this->token = tokenizer->next_token();
if (token.value.size() > 0 && token.value.at(0) == '"') {
this->value = token.value.substr(1, token.value.size()-2);
} else {
this->value = token.value;
}
}
PyObject _String::evaluate(Stack stack) {
log("_String::evaluate() - '" + this->value + "'", DEBUG);
return PyObject(this->value, "str");
}
ostream& _String::print(ostream& os) const {
os << token.value;
return os;
}
//===============================================================
// Name
Name::Name(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
log(__FUNCTION__ + (string)" - this->value == '" + this->value + "'", DEBUG);
}
Name::~Name() {
log(__FUNCTION__, DEBUG);
tokenizer->rewind(1);
}
void Name::parse() {
this->token = tokenizer->next_token();
this->value = this->token.value;
}
PyObject Name::evaluate(Stack stack) {
log("Name::evaluate() - '" + this->value + "'", DEBUG);
return stack.get_value(this->value);
}
ostream& Name::print(ostream& os) const {
os << value;
return os;
}
//===============================================================
// Number
Number::Number(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
log(__FUNCTION__ + (string)" - token.value == '" + token.value + "'", DEBUG);
}
Number::~Number() {
log(__FUNCTION__, DEBUG);
tokenizer->rewind(1);
}
void Number::parse() {
this->token = tokenizer->next_token();
this->is_int = this->token.value.find(".") == string::npos;
}
PyObject Number::evaluate(Stack stack) {
log("Number::evaluate() - " + token.value , DEBUG);
if (this->is_int) {
return PyObject(stoi(token.value), "int");
}
return PyObject(stof(token.value), "float");
}
ostream& Number::print(ostream& os) const {
os << token.value;
return os;
}
//===============================================================
// Bool
Bool::Bool(Tokenizer *tokenizer, string indent) {
log(__FUNCTION__, DEBUG);
this->tokenizer = tokenizer;
this->indent = indent;
parse();
log(__FUNCTION__ + (string)" - token.value == '" + token.value + "'", DEBUG);
}
Bool::~Bool() {
log(__FUNCTION__, DEBUG);
tokenizer->rewind(1);
}
void Bool::parse() {
this->token = tokenizer->next_token();
this->bool_value = this->token.value == "True";
}
PyObject Bool::evaluate(Stack stack) {
log("Bool::evaluate() - " + this->bool_value, DEBUG);
PyObject res = PyObject(this->bool_value, "bool");
return res;
}
ostream& Bool::print(ostream& os) const {
os << token.value;
return os;
}
//===============================================================
| [
"1011collin@gmail.com"
] | 1011collin@gmail.com |
f69acfb46b75d8ba1fb197307bec101fbc0e1b9c | f20e965e19b749e84281cb35baea6787f815f777 | /Online/Online/Stomp/js/lhcb.display.evdisp.cpp | c364d7bbe434f85199b7045384cbf87e94064ed9 | [] | no_license | marromlam/lhcb-software | f677abc9c6a27aa82a9b68c062eab587e6883906 | f3a80ecab090d9ec1b33e12b987d3d743884dc24 | refs/heads/master | 2020-12-23T15:26:01.606128 | 2016-04-08T15:48:59 | 2016-04-08T15:48:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,145 | cpp | _loadScript('lhcb.display.items.cpp');
_loadFile('lhcb.display.general','css');
var evdisp = function() {
return document.getElementById('panoramix_display');
};
var EventDisplay = function(msg, id) {
var tr, td, tb, tab;
var table = document.createElement('table');
table.id = id;
table.body = document.createElement('tbody');
table.messages = msg;
table.provider = null;
table.logger = null;
table.cycle = 0;
table.className = table.body.className = 'MonitorOuterFrame';
table.source = 'OFFLINE';
table.BeamMode = '';
table.MachMode = '';
table.timeout = 15000;
table.forceOnline = false;
table.add = function() {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.setAttribute('colSpan',2);
tr.appendChild(td);
this.body.appendChild(tr);
return td;
};
table.display = table.add();
table.logDisplay = table.add();
table.appendChild(table.body);
/// Build table with summary of the LHC
table.LHC_header = function(par) {
var tb, td, tr, tab = document.createElement('table');
tb = document.createElement('tbody');
tab.className = tb.className = 'MonitorSubHeader';
tab.body = tb;
tb.appendChild(tr=document.createElement('tr'));
tab.lhcFillNumber = StyledItem('lbWeb.LHCCOM/LHC.LHC.RunControl.FillNumber',null,'Fill %d');
tr.appendChild(tab.lhcFillNumber);
tab.lhcBeamMode = StyledItem('lbWeb.LHCCOM/LHC.LHC.RunControl.BeamMode','Text-Right',null);
tab.lhcBeamMode.parent = par;
tab.lhcBeamMode.conversion = function(data) {
this.parent.update('BeamMode',data);
return data;
};
tr.appendChild(tab.lhcBeamMode);
tab.lhcMachMode = StyledItem('lbWeb.LHCCOM/LHC.LHC.RunControl.MachineMode','Text-Left',' -- %s');
tab.lhcMachMode.parent = par;
tab.lhcMachMode.conversion = function(data) {
this.parent.update('MachMode',data);
return data;
};
tr.appendChild(tab.lhcMachMode);
tab.appendChild(tb);
tooltips.set(tab,'LHC status information');
/** Subscribe all required data item to receive data from data provider object
*
* @param provider Data provider object
*
* @return On success reference to self, null otherwise
*/
tab.subscribe = function(provider) {
this.lhcBeamMode.subscribe(provider);
this.lhcFillNumber.subscribe(provider);
this.lhcMachMode.subscribe(provider);
return this;
};
return tab;
};
table.button = function(value,onclick) {
var but, cell = document.createElement('td');
if ( _isInternetExplorer() ) {
cell.appendChild(but=document.createElement('button'));
}
else {
cell.appendChild(but=document.createElement('input'));
but.type = 'button';
}
but.value = value;
but.onclick = onclick;
return [cell,but];
};
table.subscribe = function() {
this.LHC_header.subscribe(this.provider);
return this;
};
table.update = function(tag,value) {
if ( value ) this[tag] = value;
if ( this['BeamMode'].toUpperCase() == 'STABLE BEAMS' &&
this['MachMode'].toUpperCase() == 'PROTON PHYSICS' )
this.setInput('ONLINE');
else
this.setInput('ARCHIVE');
};
table.setInput = function(what) {
var src = this.source;
this.source = what;
if ( this.forceOnline ) this.source = 'ONLINE';
this.timeout = (this.source=='ONLINE') ? 25000 : 15000;
this.online_status.innerHTML='Source: '+this.source;
};
table.setState = function(state) {
var s = this.state;
this.status.innerHTML='Display: '+state;
this.state = state;
if ( state == 'RUNNING' && s != 'RUNNING' ) {
this.run();
}
};
table.build = function() {
var td, tr, tb, tab = document.createElement('table');
tab.appendChild(tb=document.createElement('tbody'));
tb.appendChild(tr=document.createElement('tr'));
tr.appendChild(td=document.createElement('td'));
td.colSpan = 4;
td.style.bgColor = 'black';
tab.className = tb.className = 'MonitorInnerFrame';
td.appendChild(this.picture=document.createElement('img'));
this.picture.id = 'panoramix_img';
this.picture.style.width = '1050px';
this.picture.style.height = '600px';
this.picture.style.width = '100%';
this.picture.style.height = '600px';
this.picture.src = '';
this.picture.setOpacity = function(opacity) {
this.opacity = (opacity == 100) ? 99.999 : opacity;
// IE/Win
if ( this.style.filter ) this.style.filter = "alpha(opacity:"+opacity+")";
// Safari<1.2, Konqueror
this.style.KHTMLOpacity = opacity/100;
// Older Mozilla and Firefox
this.style.MozOpacity = opacity/100;
// Safari 1.2, newer Firefox and Mozilla, CSS3
this.style.opacity = opacity/100;
};
this.picture.fadeIn = function(opacity) {
if (opacity <= 100) {
this.setOpacity(opacity);
this.opacity += 3;
window.setTimeout(function(){var i=evdisp().picture;i.fadeIn(i.opacity);}, 25);
}
};
this.picture.setOpacity(0);
tooltips.set(this.picture,'LHCb event display panel.');
tb.appendChild(tr=document.createElement('tr'));
td = this.button('Pause',
function(){evdisp().setState('STOPPED')})[0];
tooltips.set(td,'Click to pause<br>the display refresh.');
td.style.width = '5%';
tr.appendChild(td);
tr.appendChild(this.status = document.createElement('td'));
this.status.style.textAlign = 'Left';
this.status.style.width = '20%';
tooltips.set(this.status,'Display state:<br>RUNNING: Automatic refresh ON<br>STOPPED: Automatice refresh OFF.');
tr.appendChild(td=document.createElement('td'));
td.appendChild(this.LHC_header=this.LHC_header(this));
td.rowSpan = 2;
td.style.width = '75%';
tb.appendChild(tr=document.createElement('tr'));
td = this.button('Play',function(){evdisp().setState('RUNNING')})[0];
tooltips.set(td,'Click to start<br>the automatic display refresh.');
td.style.width = '4%';
tr.appendChild(td);
this.online_status = document.createElement('td');
tooltips.set(this.online_status,'Data source:<br>--Events are displayed from the LHCb ONLINE system or<br>--from the media archive if the DAQ is inactive');
tr.appendChild(this.online_status);
// Finally add suggestions text
tb.appendChild(tr=document.createElement('tr'));
td = this.button('Force Online',function(){var d=evdisp();d.forceOnline=true;d.setInput('ONLINE');d.reload();})[0];
tooltips.set(td,'Force online input.');
tr.appendChild(td);
td = this.button('Reset',function(){var d=evdisp();d.forceOnline=false;d.update(null,null);d.reload();})[0];
tooltips.set(td,'Reload page.');
tr.appendChild(td);
tr.appendChild(td=Cell('Comments and suggestions to M.Frank CERN/LHCb',2,'MonitorTinyHeader'));
td.style.textAlign = 'right';
td.colSpan = 2;
this.display.appendChild(tab);
return this;
};
table.reload = function() {
var arch_img = ["http://lhcb-public.web.cern.ch/lhcb-public/Images2015/jpsipk5p.png",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2015/jpsipk1p.png",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2015/FirstPhysicsLHCb.png",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2015/13TeVLHCb.png",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2015/CMSLHCb_EDfig4.png",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2014/PhotonPol.jpg",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2013/Bs2MuMu2013.png",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2013/Bs2MuMu2013v.png",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2013/BsKpi.jpg",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2013/BsKpiVertex.jpg",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2013/BDpp.jpg",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2014/Images_2012/BsMuMuMay2012.jpg",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2014/Images_2012/BsMuMuMay2012zoomzx_force.png",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2014/Images_2012/pASep_13_12.jpg",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2014/Images_2012/Bd_Kpi.jpg",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2014/Images_2011/BsMuMUPt_b.jpg",
"http://lhcb-public.web.cern.ch/lhcb-public/Images2014/Images_2011/BsMuMu_xz_b.jpg",
"http://marwww.in2p3.fr/~oleroy/pro/firstb/firstBplus2JpsiKplus_LargeOverview.jpg"
];
this.cycle = this.cycle + 1;
this.picture.setOpacity(20);
if ( this.forceOnline || this.source == 'ONLINE' ) this.picture.src = '/Online/Images/evdisp.jpg?'+Math.random();
else this.picture.src = arch_img[this.cycle%arch_img.length];
// this.picture.src = 'http://lbevent.cern.ch/Panoramix/PanoramixEventDisplay_0.jpg?'+Math.random();
this.picture.fadeIn(20);
};
table.run = function() {
var display = evdisp();
if ( display.state == 'RUNNING' ) {
display.reload();
setTimeout(display.run,display.timeout);
}
};
return table;
};
var evdisp_unload = function() {
dataProviderReset();
return 1;
};
var evdisp_body = function() {
var msg = the_displayObject['messages'];
var body = document.getElementsByTagName('body')[0];
var tips = init_tooltips(body);
var selector = EventDisplay(msg,'panoramix_display');
body.appendChild(selector);
body.className = 'MainBody';
setWindowTitle('LHCb Event Display');
if ( msg > 0 )
selector.logger = new OutputLogger(selector.logDisplay, 200, LOG_INFO, 'StatusLogger');
else
selector.logger = new OutputLogger(selector.logDisplay, -1, LOG_INFO, 'StatusLogger');
selector.provider = new DataProvider(selector.logger);
selector.provider.topic = '/topic/status';
selector.build();
selector.subscribe();
selector.setState('RUNNING');
selector.provider.start();
body.style.cursor = 'default';
return selector;
};
if ( _debugLoading ) alert('Script lhcb.display.evdisp.cpp loaded successfully');
| [
"frankb@cern.ch"
] | frankb@cern.ch |
6aeeeb7296376f737954ca8c01aaa2dfde040ed7 | 76224057244f2c3b3d311d71b1b4d0c9a79982a9 | /src/xmlserializer.h | b6cc3ca8b7e16b465e06e3da04af1ce96f5fe3b1 | [] | no_license | HamedMasafi/Serializer | b2f8be74a5e4a8c34e2674649e6e237b5d03ca72 | 355336454c731ac6a594944488f945d0d8b06fef | refs/heads/master | 2023-05-11T02:08:22.962833 | 2023-05-09T16:35:05 | 2023-05-09T16:35:05 | 166,847,735 | 8 | 10 | null | 2020-07-15T06:53:39 | 2019-01-21T16:45:39 | C++ | UTF-8 | C++ | false | false | 1,405 | h | #pragma once
#include "abstractserializer.h"
#include <QDomElement>
class XmlSerializer : public AbstractSerializer
{
public:
XmlSerializer();
// QDomElement toDomElement(const QMetaEnum &en, const QVariant &value);
QDomElement toDomElement(QDomDocument &doc, const QString &name, const QVariant &v) const;
QDomElement toDomElement(QDomDocument &doc, const QString &name, QVariantList list) const;
// QDomElement toDomElement(QStringList list);
// QDomElement toDomElement(QVariantMap map);
QVariant fromDomElement(const QMetaType::Type &type, const QDomElement &element) const;
QString serializeObject(QObject *object);
bool deserializeQObject(QObject *obj, const QString &content);
private:
struct DomWriter {
DomWriter (const QDomElement &element);
void append(const QString &name, int value);
public:
QDomElement el() const;
private:
QDomElement _el;
};
QVariant fromString(const QString &value, const QMetaType::Type &type) const;
QString toString(const QVariant &value) const;
void addToElement(QDomDocument &doc, QDomElement &element, const QString &name, int n) const;
QString elementText(const QDomElement &element) const;
QString elementChildText(const QDomElement &element, const QString &name) const;
// void addToElement(QDomElement &element, cnst QDomElement &child);
};
| [
"hamed.masafi@gmail.com"
] | hamed.masafi@gmail.com |
48d013d7a976cf136fe135d7323093a7e2f7b29b | 5145d166dbb699a8f75c4b9d9614002607ae0597 | /algos_assignment/2nd_grade/박예나_yeana0601/11월3주차/13305.cpp | cc5057096e1ec80e1f223e9f98d50e7c12ae2e23 | [] | no_license | Sookmyung-Algos/2021algos | 8cedfb92d8efaf4f6241dece5bc9b820fc5dc277 | be152912517558f0fc8685574064090e6c175065 | refs/heads/master | 2022-07-21T03:47:38.926142 | 2021-12-02T01:35:13 | 2021-12-02T01:35:13 | 341,102,594 | 11 | 46 | null | 2021-12-02T01:35:14 | 2021-02-22T06:32:53 | C++ | UTF-8 | C++ | false | false | 412 | cpp | #include<iostream>
#include<algorithm>
using namespace std;
long long dist[100001], price[100001];
long long n, sum, greedy;
int main()
{
cin >> n;
for (int i = 1; i <= n - 1; i++)
cin >> dist[i];
for (int i = 1; i <= n; i++)
cin >> price[i];
greedy = 1000000000;
for (int i = 1; i <= n - 1; i++)
{
if (price[i] < greedy)
greedy = price[i];
sum += greedy * dist[i];
}
cout << sum;
}
| [
"noreply@github.com"
] | noreply@github.com |
b977e4ee57d08dc7bc8259c2c16a65a59286a229 | 2c7bc199a67f7572ecb2f7e303a28aad5147a424 | /Questions/Categories/QFunctions.cpp | cdc0868e6a34795796142a3ac8f1be7fccd911ad | [] | no_license | dbgerhard/CS110-Autogenerator | 770359d1845f0c3b0a9fe46042fb89cd1e80c279 | 601ba5575ce9024e028162e03a8d70b6f8f8cc92 | refs/heads/master | 2021-09-15T04:35:17.581461 | 2018-05-26T03:24:46 | 2018-05-26T03:24:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,689 | cpp |
#include "question.h"
#include "QFunctions.h"
//*******************************************************************************************
// FUNCTIONS SUBCLASS DEFINITIONS
//
//*******************************************************************************************
//NOTE FOR FUTURE CONSIDERATION:
//currently, this question only uses variables as int
//but if we decide to use a mixed datatype thing
//where the parameters have multiple datatypes, and so do the
//main scope variables, there needs to be some logic
//to make sure that:
//if a parameter is pass-by-reference, the argument passed to it must be of the same datatype
//otherwise there is a compiler error
//however, pass-by-value parameters may have different datatypes than their arguments
void QFunctions::TypeOne()
{
int num_parameters = 3; //number of parameters in function header
int num_vars = 3; //number of variables declared in main program
bool differentExpressionOrder = false;
int minType = Int;
int maxType = Int; //a range to go from 0 to typeRange
Symbols minOperator = add; //and by the same logic as above, gives a range of 0 to n of what operators to use (see SYMBOLS)
Symbols maxOperator = mod;
int minVal = 2;
int maxVal = 5;
int ref = GenerateRand<int>(0, num_parameters - 1); //choose the element we are referencing (i.e. which one is assigned in the function)
VariablesVec mainScope;
//------------------------------------------------------------------
//-------------------INITIALIZE ALL VALUES--------------------------
//------------------------------------------------------------------
//use temporary array to make unique indicies for identifiers
vector<int> temp_indices(num_vars, -1);
for (int i = 0; i < num_vars; i++)
{
temp_indices[i] = FindUnique(temp_indices, i, IDENTIFIERS.size() - 1);
mainScope.AddVariable(Variable(IDENTIFIERS[temp_indices[i]], GenerateRand<DataTypes>(minType, maxType), GenerateRand<float>(minVal, maxVal)));
}
//then generate the function (with using the variables as a base point for the parameters)
// and use the same datatypes for the parameters
// it also passes the values over to the parameters
Functions funcScope(Void, FUNCTION_IDS[GenerateRand<int>(0, FUNCTION_IDS.size() - 1)], &mainScope);
//and alter the variable position if needed:
//NOTE: this may cause issues if datatypes are nonhomogeneous
if (differentExpressionOrder)
{
mainScope.Randomize();
}
funcScope.PassVariables(mainScope);
//and initialize the assignment statement in the function (using the parameters we just generated)
Expressions refAssignment(num_parameters, 0, &(funcScope.GetParameters()), minOperator, maxOperator, differentExpressionOrder);
//------------------------------------------------------------------
//--------------------PRINT THE QUESTION----------------------------
//------------------------------------------------------------------
prompt += "Given the following function definition:\n";
prompt += "<pre>";
// first, get the id of the parameter we are assigning, then assign the expression to it
string funcBody = funcScope.GetParameters().GetVariable(ref).id + " = " + refAssignment.Print() + ";";
//and print the above in the function definition
prompt += funcScope.PrintDefinition(funcBody);
prompt += "</pre>\n";
prompt += "What value is printed after the following statments?\n";
prompt += "<pre>";
//with the variable declarations
prompt += mainScope.Print();
//and the function call:
prompt += funcScope.PrintCall(mainScope) + ";\n";
//and the final print statement of the referenced variable:
prompt += "cout << " + mainScope.GetVariable(ref).id + " << endl;</pre>\n";
//------------------------------------------------------------------
//-------------------CALCULATE THE ANSWER---------------------------
//------------------------------------------------------------------
vector<float> tempWrong(wrong.size());
float tempCorrect;
tempCorrect = EvalAndReturnReferenceParam(mainScope, funcScope, refAssignment, ref, tempWrong);
//check and make sure the answers are unique:
CheckUniqueAnswers<float, float>(tempCorrect, tempWrong);
//now print answers:
for (size_t i = 0; i < wrong.size(); i++)
{
wrong[i] = FloatToString(tempWrong[i]);
}
correct = FloatToString(tempCorrect);
}
void QFunctions::TypeTwo()
{
int num_params = 2; //number of parameters
int max = 5; //max value for operands
bool differentExpressionOrder = false;
Symbols minOperator = add;
Symbols maxOperator = divide;
//use every datatype except void
DataTypes minType = Int;
DataTypes maxType = Float;
DataTypes returnType = Float; //always use float for this type
//and never use reference parameters:
vector<bool> refs(num_params, false);
//variables used for answer calculation:
float tempCorrect;
vector<float> tempWrong(wrong.size());
VariablesVec params;
//TODO: change uniqueIds to false below
VariablesVec literals; //a vector identitcal to the params vector, but the ids are the literal values
//a temporarily used vector to find unique string for ids
vector<int> temp_ids(num_params);
for (int i = 0; i < num_params; i++)
{
Variable tempVar;
do
{
tempVar.type = GenerateRand<DataTypes>(minType, maxType);
} while (i > 0 && tempVar.type == params.GetVariable(i - 1).type); //and thats different from the previous datatype
do
{
tempVar.val = GenerateRand<float>(2, max, 2);
} while (i > 0 && Operation<bool>(eq, tempVar.val, literals.GetVariable(i - 1).val)); //and use some different values
temp_ids[i] = FindUnique(temp_ids, i, IDENTIFIERS.size() - 1);
tempVar.id = IDENTIFIERS[temp_ids[i]];
//if a number ends in 0.5 (and is Float), only allow addition and subtraction:
if ((maxOperator == divide) && ((int)(Convert(tempVar.type, tempVar.val) / 0.5f) % 2 == 1))
{
maxOperator = sub;
}
params.AddVariable(tempVar);
//and change the id to the literal value for the literals vector:
tempVar.id = FloatToString(tempVar.val, true, 1);
literals.AddVariable(tempVar, false, false);
}
//and create function and expression:
Functions func(returnType, FUNCTION_IDS[GenerateRand<int>(0, FUNCTION_IDS.size() - 1)], ¶ms, refs, false);
//and pass to the function:
func.PassVariables(params, true);
Expressions expr(num_params, 0, &func.GetParameters(), minOperator, maxOperator, differentExpressionOrder);
//now create an expression for wrong answer generation:
vector<string> literalExpression = expr.GetExpr();
int currentLiteral = 0;
for (size_t i = 0; i < literalExpression.size(); i++)
{
if (isalnum(literalExpression[i][0]))
{
//substitute all variables for their original literal value:
literalExpression[i] = literals.GetVariable(currentLiteral++).id;
}
}
//and initialize a new expression with the values:
Expressions wrongExpr(literalExpression, &literals, false, false);
//then print:
prompt += "Given the following function definition:\n";
prompt += "<pre>";
prompt += func.PrintDefinition("return " + expr.Print() + ";");
prompt += "</pre>\n";
prompt += "What is printed from the following call?\n";
prompt += "<pre>";
prompt += "cout << " + func.PrintCall(literals) + " << endl;\n";
prompt += "</pre>\n";
tempCorrect = Convert(returnType, expr.Eval());
//TODO: make a function that is easily able to use float only operations
tempWrong[0] = wrongExpr.EvalNoOrder(false, false);
tempWrong[1] = wrongExpr.EvalNoOrder(false);
tempWrong[2] = expr.EvalNoOrder(false, true);
tempWrong[3] = Convert(Int, tempCorrect);
CheckUniqueAnswers(tempCorrect, tempWrong);
correct = FloatToString(tempCorrect);
for (size_t i = 0; i < tempWrong.size(); i++)
{
wrong[i] = FloatToString(tempWrong[i]);
}
}
void QFunctions::TypeThree()
{
int max = 5; //max value for operands
Symbols minOperator = add;
Symbols maxOperator = divide;
//use every datatype for return
DataTypes returnType = GenerateRand<DataTypes>(Int, Void);
//variables used for answer calculation:
float tempCorrect;
vector<float> tempWrong(2);
int numOperands = 2;
VariablesVec operands; //operands used in the function expression
for (int i = 0; i < numOperands; i++)
{
Variable tempVar;
tempVar.type = Float; //always use float for the operands
do
{
tempVar.val = GenerateRand<float>(2, max, 2); //use min of 0.5 because we aren't checking for / 0 errors
} while (i > 0 && Operation<bool>(eq, tempVar.val, operands.GetVariable(i - 1).val));
//and change the id to the literal value:
tempVar.id = FloatToString(tempVar.val, true, 1);
operands.AddVariable(tempVar, false, true);
}
Functions func(returnType, FUNCTION_IDS[GenerateRand<int>(0, FUNCTION_IDS.size() - 1)]);
Expressions funcExpr(2, 0, &operands);
//then print:
prompt += "Given the following function definition:\n";
prompt += "<pre>";
prompt += func.PrintDefinition("return " + funcExpr.Print() + ";");
prompt += "</pre>\n";
prompt += "What is printed from the following call?\n";
prompt += "<pre>";
prompt += "\tcout << " + func.PrintCall() + " << endl;\n";
prompt += "</pre>\n";
tempWrong[0] = Convert(Float, funcExpr.EvalNoOrder(false, true));
if (returnType == Void)
{
tempCorrect = Convert(Float, funcExpr.Eval());
tempWrong[1] = Convert(Int, funcExpr.Eval());
CheckUniqueAnswers(tempCorrect, tempWrong);
correct = "Compile-time error.";
wrong[3] = FloatToString(tempCorrect);
}
else
{
tempCorrect = Convert(returnType, funcExpr.Eval());
//this wrong answer uses the opposite datatype of the return type:
tempWrong[1] = Convert((DataTypes) (1 - returnType), funcExpr.Eval());
CheckUniqueAnswers(tempCorrect, tempWrong);
correct = FloatToString(tempCorrect);
wrong[3] = "Compile-time error.";
}
wrong[2] = "Run-time error.";
for (size_t i = 0; i < tempWrong.size(); i++)
{
wrong[i] = FloatToString(tempWrong[i]);
}
}
void QFunctions::TypeFour()
{
}
float QFunctions::EvalAndReturnReferenceParam(VariablesVec mainScope, Functions funcScope, Expressions funcExpr, int ref, vector<float>& tempWrong)
{
//TypeOne() calculation:
assert(tempWrong.size() == 4);
//first, evaluate the expression:
float res = funcExpr.Eval();
tempWrong[0] = mainScope.GetVariable(ref).val;
//then swap the values if the parameter was NOT pass-by-reference
if (!funcScope.GetRefs()[ref])
{
float temp = tempWrong[0];
tempWrong[0] = res;
res = temp;
}
tempWrong[1] = funcExpr.EvalNoOrder(); //this disregards order of operations
tempWrong[2] = funcScope.GetParameters().GetVariable((ref + 1) % funcScope.GetParameters().Size()).val;
tempWrong[3] = funcExpr.EvalNoOrder(true, true);
return res;
}
void QFunctions::Tests()
{
//TypeOne() testing
//checking if reference parameter is returned properly
//only Int type for now
VariablesVec mainScope({ Variable("1", Int, 1), Variable("2", Int, 2), Variable("3", Int, 3) });
Expressions funcExpr({ "1", "+", "2", "-", "3" }, &mainScope);
//loop through each position of reference
//only testing for size 3
//there are total of 24 combinations of reference variables and reference values
//that's 2**3 options for reference variables * 3 options for the reference index
//there's 12 cases covered here
for (size_t i = 0; i < 3; i++)
{
vector<float> tempWrong(4);
//no references in each spot:
Functions funcScope1(Void, "tempName", &mainScope, { false, false, false });
funcScope1.PassVariables(mainScope);
assert(EvalAndReturnReferenceParam(mainScope, funcScope1, funcExpr, i, tempWrong) == mainScope.GetVariable(i).val); //the value of the original variable
//references in every spot:
Functions funcScope2(Void, "tempName", &mainScope, { true, true, true });
funcScope2.PassVariables(mainScope);
assert(EvalAndReturnReferenceParam(mainScope, funcScope2, funcExpr, i, tempWrong) == 0); //the value of the evaluated expression
//references only in the spot of the referenced variable:
Functions funcScope3(Void, "tempName", &mainScope, { i == 0, i == 1, i == 2 });
funcScope3.PassVariables(mainScope);
assert(EvalAndReturnReferenceParam(mainScope, funcScope3, funcExpr, i, tempWrong) == 0); //the value of the evaluated expression
//references in every spot BUT of the referenced variable:
Functions funcScope4(Void, "tempName", &mainScope, { i != 0, i != 1, i != 2 });
funcScope4.PassVariables(mainScope);
assert(EvalAndReturnReferenceParam(mainScope, funcScope4, funcExpr, i, tempWrong) == mainScope.GetVariable(i).val); //the value of the original variable
}
//test type two just by testing a combination of Convert, which has already been tested. so we can trust it for now.
// OLD TESTS
//separate each by return type
//so one for void, one for int, one for float
//then for int and for float, make one each for the data types
//thats (int, int), (int, float), (float, int), (float, float)
//and use some vaules that truncate at each step
//like 2.5 / 3.5
//only test questions of type 2
//with these different combination of datatypes:
//{{Int, Int}, {Int, Float}, {Float, Int}, {Float, Float}}
/*
ops = {divide};
unusedVals = {-1, -1};
ids = {"", ""};
vector<bool> refs = {false, false};
//Int return:
//Int(Int(10.6) / Int(1.5))
assert(Convert(Int, PassAndEvalFunc(Parameters({Int, Int}, unusedVals, ids, refs), {float(10.6), 1.5}, ops)) == int(int(10.6) / int(1.5)));
//Int(float(10.5) / Int(2.5))
assert(Convert(Int, PassAndEvalFunc(Parameters({Float, Int}, unusedVals, ids, refs), {10.5, 2.5}, ops)) == int(float(10.5) / int(2.5)));
//int(int(4.5) / float(1.5))
assert(Convert(Int, PassAndEvalFunc(Parameters({Int, Float}, unusedVals, ids, refs), {4.5, 1.5}, ops)) == int(int(4.5) / float(1.5)));
//int(float(10.1) / float(1.5))
assert(Convert(Int, PassAndEvalFunc(Parameters({Float, Float}, unusedVals, ids, refs), {float(10.1), 1.5}, ops)) == int(float(10.1) / float(1.5)));
//Float return:
//Float(Int(1.5) / Int(3.5))
assert(Convert(Float, PassAndEvalFunc(Parameters({Int, Int}, unusedVals, ids, refs), {1.5, 3.5}, ops)) == float(int(1.5) / int(3.5)));
//Float(float(10.5) / Int(2.5))
assert(Convert(Float, PassAndEvalFunc(Parameters({Float, Int}, unusedVals, ids, refs), {10.5, 2.5}, ops)) == float(float(10.5) / int(2.5)));
//Float(int(4.5) / float(1.5))
assert(Convert(Float, PassAndEvalFunc(Parameters({Int, Float}, unusedVals, ids, refs), {4.5, 1.5}, ops)) == float(int(4.5) / float(1.5)));
//Float(float(10.1) / float(1.5))
assert(Convert(Float, PassAndEvalFunc(Parameters({Float, Float}, unusedVals, ids, refs), {float(10.1), 1.5}, ops)) == float(float(10.1) / float(1.5)));
*/
} | [
"noreply@github.com"
] | noreply@github.com |
8727dd3c9d19e2369594170181f4d8fc4c88b9da | 5380c586f6129eebdc2c23c47377e1637a18ac7f | /velox/exec/Values.h | da0bb651970bfefa16ab4fe2145dbf879723aceb | [
"Apache-2.0"
] | permissive | amaliujia/velox | 1bd9ecd83d1c42935ed463dd6de9c8fc0b0d6357 | 648f88dae970858c870acbbb68dbc4c35207042d | refs/heads/main | 2023-08-11T02:40:28.410788 | 2021-10-01T18:16:15 | 2021-10-01T18:16:15 | 409,347,480 | 0 | 0 | Apache-2.0 | 2021-09-22T20:31:04 | 2021-09-22T20:31:04 | null | UTF-8 | C++ | false | false | 1,245 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "velox/core/PlanNode.h"
#include "velox/exec/Operator.h"
namespace facebook::velox::exec {
class Values : public SourceOperator {
public:
Values(
int32_t operatorId,
DriverCtx* driverCtx,
std::shared_ptr<const core::ValuesNode> values);
RowVectorPtr getOutput() override;
BlockingReason isBlocked(ContinueFuture* /* unused */) override {
return BlockingReason::kNotBlocked;
}
void finish() override {
Operator::finish();
close();
}
void close() override;
private:
std::vector<RowVectorPtr> values_;
int32_t current_ = 0;
};
} // namespace facebook::velox::exec
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
87239d9ece3300562c45964c08dd1299200d7710 | 0745606e25e1b6c6dc72a2f4bb81ebdf23b9df9e | /A5CC3K/A5CC3K-master-50c858ec25aff912f0d47906ff55d0f7a4192e67/controller.h | ff55c4ba31a4cf8d24482fd632ab1b54315cd28d | [] | no_license | Jin22/Chamber-Crawler-3000 | 4f3944a534db5511a8a8854062e2e43f6e5ea59e | edf6df4c9a6353885ec67860d81922b8f51b1354 | refs/heads/master | 2020-04-17T06:23:23.702790 | 2019-01-18T03:36:29 | 2019-01-18T03:36:29 | 166,322,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | h | #ifndef __CONTROLLER_H__
#define __CONTROLLER_H__
#include <istream>
#include <string>
class Game;
class Controller {
std::istream ∈
std::string toSend;
public:
Controller(std::istream &i);
void getCommand();
void sendRace(Game &g);
std::string sendCommand(Game &g);
void requestDisplay(Game &g, std::string);
};
#endif
| [
"noreply@github.com"
] | noreply@github.com |
c6a886efea4d91c223093749c3815375233497c4 | 46370ed07ee2250344acd4589b406de42d6e738e | /BatCsvReader/Utils.cpp | 8802fd37718438d12c063d3952ad7199f2c4528c | [] | no_license | suriasif/binLoad_MonetDB | a3d30cc24f1cce3d642389ea07d12a8580197664 | 83b0008c5d7f51b7b9f80f09c5095ae727cfcfcf | refs/heads/master | 2021-01-09T05:23:13.428621 | 2017-02-03T09:44:27 | 2017-02-03T09:44:27 | 80,759,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,374 | cpp | // Utils.cpp : Utility functions.
//
#include "stdafx.h"
typedef __int32 date;
#define date_nil ((date) 0)
int NODAYS[13] = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int CUMDAYS[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
date DATE_MAX, DATE_MIN; /* often used dates; computed once */
#define YEAR_MAX 5867411
#define YEAR_MIN -YEAR_MAX
#define MONTHDAYS(m,y) (((m)!=2)?NODAYS[m]:leapyear(y)?29:28)
#define YEARDAYS(y) (leapyear(y)?366:365)
#define LEAPYEARS(y) (leapyears(y)+((y)>=0))
#define DATE(d,m,y) ((m)>0&&(m)<=12&&(d)>0&&(y)!=0&&(y)>=YEAR_MIN&&(y)<=YEAR_MAX&&(d)<=MONTHDAYS(m,y))
#define TIME(h,m,s,x) ((h)>=0&&(h)<24&&(m)>=0&&(m)<60&&(s)>=0&&(s)<60&&(x)>=0 &&(x)<1000)
#define LOWER(c) (((c) >= 'A' && (c) <= 'Z') ? (c)+'a'-'A' : (c))
int leapyear(int year)
{
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
int leapyears(int year)
{
/* count the 4-fold years that passed since jan-1-0 */
int y4 = year / 4;
/* count the 100-fold years */
int y100 = year / 100;
/* count the 400-fold years */
int y400 = year / 400;
return y4 + y400 - y100; /* may be negative */
}
date todate(int day, int month, int year)
{
date n = 0;
if (DATE(day, month, year)) {
if (year < 0)
year++; /* HACK: hide year 0 */
n = (date) (day-1 );
if ( month > 2 && leapyear(year)) n++;
n+= CUMDAYS[month-1];
;
/* current year does not count as leapyear */
n += 365 * year + LEAPYEARS(year >= 0 ? year - 1 : year);
}
return n;
}
/* multi line comments
chararray
datetime
double
int
long
D8 C1 B3 02 AB 3A 0B 00
F8 9D C6 02 AB 3A 0B 00
00 0b 3a ab 02 b3 c1 d8 = 2014-11-13 12:35:35.000000
00 0b 3a ab 02 c6 9d f8 = 2014-11-13 12:56:11.000000
(00 0b 3a ab :: 02 b3 c1 d8 ) = 735915 :: 45335000 /1000 = 735915 :: 45335
45335 / 3600 = 12
45335 % 3600 = 2135 / 60 = 35
2135 % 60 = 35
12:35:35
02 b3 c1 d8
05 26 5C 00
select (epoch(cast(current_timestamp as timestamp))-epoch(timestamp '2013-04-25 11:49:00')
0b 3a ab 02 b3 c1 d8 = 3160730902970840 / 1000 = 3160730902970
0b 3a ab 02 c6 9d f8 = 3160730904206840 / 1000 = 3160730904206
3160730904206 - 3160730902970 = 1236
2014-11-13 12:56:11.000000 - 2014-11-13 12:35:35.000000 = 1236 seconds
3160730902970 /
*/
| [
"noreply@github.com"
] | noreply@github.com |
b3922d545f0019e56a4d7ac12e0e06927877f16f | a3f3a3120ea0afb8da9a99ce795ea607aec9abf8 | /MyClass.cc | 7fd852660594eae35136e99813b56f9a372cb285 | [
"MIT"
] | permissive | MarlonJrBM/generic.pimpl | 45d3830e8504ab9426feaecdb201d04bfb4323ca | 706fcd4daac690635bbd860c23dd76bc873f3245 | refs/heads/master | 2023-04-20T16:34:03.408199 | 2021-05-08T09:43:38 | 2021-05-08T09:43:38 | 365,475,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 309 | cc | #include "MyClass.hh"
#include <iostream>
class MyClass::MyClassImpl {
public:
void doStuff();
};
MyClass::MyClass() = default;
MyClass::~MyClass() = default;
void MyClass::doStuff() { _impl->doStuff(); }
void MyClass::MyClassImpl::doStuff() { std::cout << "Starting to do stuff !" << std::endl; } | [
"marlonbr1@gmail.com"
] | marlonbr1@gmail.com |
64cde0c0f7ed098a947de1dbabff57e2c0bd0e1f | f231843bc3f91b51a78e8d6908b55d1d96a1c836 | /lib/token/src/h1/State/HeaderVal.cpp | f208c680d3433cb8880f95b815ae61d12432a059 | [
"BSD-3-Clause"
] | permissive | astateful/dyplat | 13581c5040d2987e1e8bf45002a623f6c3f5c950 | 37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44 | refs/heads/master | 2023-03-12T10:16:35.683180 | 2021-03-01T21:14:53 | 2021-03-01T21:14:53 | 343,553,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | cpp | #include "autogen/token/h1/State/HeaderVal.hpp"
#include "astateful/token/h1/Context.hpp"
namespace astateful {
namespace token {
namespace h1 {
state_e StateHeaderVal::operator()( Context& context, uint8_t value ) {
// Do not append the transition char to the header value.
// Usually there is a leading space so we also do not care
// about appending that either.
auto& val = context.header.back().second;
if ( value == ':' || ( value == ' ' && val.size() == 0 ) )
return state_e::HeaderVal;
val += value;
return state_e::HeaderVal;
}
}
}
} | [
"thomas.kovacs@astateful.com"
] | thomas.kovacs@astateful.com |
67c69a626550801e9a3d6d20f969a723336f0df3 | 018b6e6cbecc0bee691fde92c79d48b431bb0f9d | /mine.cpp | e01634327f6a22322ae3fe158bce7e5a24acabd7 | [] | no_license | ICKelin/mine-text | f92e22f1a1bc9d29753ffeae31a89acb178b3148 | e61ffb47095f0d5ac550f3c557901dd1c71e6376 | refs/heads/master | 2021-01-19T17:30:07.474393 | 2017-04-15T04:43:10 | 2017-04-15T04:43:10 | 88,324,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,108 | cpp | #include "mine.h"
// 描述:初始化地雷数据
// 参数:
// n:地雷地图中的行数
// m: 地雷地图中的列数
// 返回值: 无
//
Mine::Mine(unsigned int n, unsigned int m, unsigned int mineCount) {
this->n = n;
this->m = m;
this->mTotalMine = mineCount;
this->mRestMine = mineCount;
this->mRealRestMine = mineCount;
// 生成图
try {
this->mMine = new int*[n+2];
this->mBoxValue = new int*[n+2];
for (int i = 0; i < n + 2; i++) {
this->mMine[i] = new int[m+2];
this->mBoxValue[i] = new int[m+2];
}
} catch(bad_alloc & memExp) {
cerr<<memExp.what()<<endl;
}
// 随机生成地雷,1表示有地雷,0表示没有地雷
vector<int> source;
for(int i = 0; i < mineCount; i++) {
source.push_back(1);
}
for(int j = 0; j < m*n - mineCount; j++) {
source.push_back(0);
}
srand(time(NULL));
random_shuffle(source.begin(), source.end());
// 初始化数据,边界置0
for (int i = 0; i <= n + 1; i++) {
for (int j = 0; j <= m + 1; j++) {
// 保留四周冗余,可以使后续计算方格的值的时候略去边界判断
if (i == 0 || j== 0 || i == n+1 || j == m+1) {
this->mMine[i][j] = 0;
continue;
}
this->mMine[i][j] = source.back();
source.pop_back();
}
}
// 初始化地图所有计数均为0
for (int i = 0; i <= n + 1 ; i++) {
for (int j = 0; j <= m + 1; j++) {
this->mBoxValue[i][j] = 0;
}
}
}
Mine::~Mine() {
for (int i = 0; i < this->n + 2; i++) {
delete []this->mMine[i];
delete []this->mBoxValue[i];
}
delete []this->mMine;
delete []this->mBoxValue;
}
// 描述:判断坐标x,y是否是地雷
// 参数:
// x:所在行
// y:所在列
// 返回值:
// true:点(x, y)是地雷
// false: 不是地雷
//
bool Mine::IsMine(unsigned int x, unsigned int y) {
if (this->IsOutOfBound(x, y)) {
return false;
}
return this->mMine[x][y] == 1 && this->mBoxValue[x][y] == MARK_INIT;
}
// 描述:是否获胜
// 参数: 无
// 返回值:
// true: 获胜
// false:暂时未获胜
//
bool Mine::IsWin() {
return this->mRealRestMine == 0;
}
// 描述:判断坐标x,y是否超出地图边界
// 参数
// x: 横坐标
// y:纵坐标
// 返回值:
// true:超出边界
// false:未超出边界
//
bool Mine::IsOutOfBound(unsigned int x, unsigned int y) {
return (x <=0 || y <= 0 || x > this->n || y > this->m);
}
// 描述:计算点(x,y)周边的地雷数
// 参数:
// x:所在行
// y:所在列
// 返回值:无
// 实现原理:
// 一、求出点(x,y)周边的地雷数
// 二、如果地雷数为0,说明周边可展开,
// 然后对周边的点一次求他们周边的地雷数
// 迭代此过程,直到不存在点周边地雷数为0
//
void Mine::CalculateValues(unsigned int x, unsigned int y) {
if (this->IsOutOfBound(x, y)) {
return;
}
queue<Point> q;
Point p = {x, y};
q.push(p);
// 广度遍历图
while ( !q.empty() ) {
p = q.front();
q.pop();
x = p.x;
y = p.y;
this->mBoxValue[x][y] = this->mMine[x][y-1] + this->mMine[x][y+1] + \
this->mMine[x-1][y] + this->mMine[x-1][y-1] + this->mMine[x-1][y+1] + \
this->mMine[x+1][y] + this->mMine[x+1][y-1] + this->mMine[x+1][y+1];
// 周边没有地雷
if (this->mBoxValue[x][y] == 0) {
this->mBoxValue[x][y] = MARK_OPEN;
// 格子标志为打开状态,防止后续再次重复进行计算
for (int i = x - 1; i <= x+1 ; i++ ) {
// 跳过边界点
if (i < 1 || i > this->n) {
continue;
}
for (int j = y-1; j <= y + 1; j++) {
// 跳过边界点和当前点
if ( (j < 1 || j > this->m) || (i == x && j == y)) {
continue;
}
struct Point p = {i, j};
if (this->mBoxValue[i][j] == MARK_INIT) {
q.push(p);
this->mBoxValue[i][j] = MARK_OPEN;
}
}
}
}
}
}
// 描述:显示当前游戏状态
// 参数:无
// 返回值:无
// 说明:
// debug模式下可以看到当前地雷的分布图
// release模式下可以看到当前游戏进行的状态
// 地雷显示的是五角星,未打开的盒子显示的是实心正方形
// 如果是搜索打开的是空心圆,如果是玩家点开的,是数字
//
void Mine::ShowMap() {
#ifdef DEBUG
cout<<"开发人员调试显示的地雷分配图"<<endl;
for (int i = 1; i <= this->n; i++) {
for (int j = 1; j <= this->m; j++) {
cout<<this->mMine[i][j]<<" ";
}
cout<<endl;
}
cout<<"\n----------------------------"<<endl;
#endif
cout<<"地雷总数 "<<this->mTotalMine<<" 剩余可标识地雷数 "<<this->mRestMine<<endl;
cout<<" |";
for (int i = 1; i <= this->m; i++) {
printf("%-3d", i);
}
cout<<endl;
cout<<"-----------------------------------------------------------------------------"<<endl;
for (int i = 1; i <= this->n; i++) {
printf("%2d|", i);
for (int j = 1; j <= this->m; j++) {
if (this->mBoxValue[i][j] == MARK_INIT) {
cout<<"■ "<<" ";
} else if (this->mBoxValue[i][j] == MARK_MINE) {
cout<<"★ "<<" ";
} else if (this->mBoxValue[i][j] == MARK_UNKNOWN){
cout<<"?"<<" ";
} else if (this->mBoxValue[i][j] == MARK_OPEN) {
cout<<"○ "<<" ";
} else{
cout<<this->mBoxValue[i][j]<<" ";
}
}
cout<<endl;
}
}
void Mine::GetMapString(char *szOutput) {
char temp[100];
for(int i = 1; i <= this->n; i++) {
for(int j = 1; j <= this->m; j++) {
if (i == this->n && j == this->m)
sprintf(temp, "{\"x\":%d,\"y\":%d,\"value\":%d}", i, j, this->mBoxValue[i][j]);
else
sprintf(temp, "{\"x\":%d,\"y\":%d,\"value\":%d},", i, j, this->mBoxValue[i][j]);
//sprintf(temp, "{\"x\":%d,\"y\":%d,\"value\":%d},", i, j, this->mBoxValue[i][j]);
strcat(szOutput, temp);
}
}
}
// 描述:标志地雷
// 参数
// 点的坐标x和y
// 返回值:无
// 说明:
// 如果点是初始化状态,则置为地雷状态,可标志的地雷数加一
// 如果点是地雷状态, 则置为不确定状态,可标志的地雷数减一
// 如果点是不确定状态,则置为初始化状态,可标志的地雷数不变
//
void Mine::SetMine(unsigned int x, unsigned int y) {
if (this->IsOutOfBound(x, y)) {
return;
}
// 初始状态下被标志为地雷
if (this->mBoxValue[x][y] == MARK_INIT) {
if (this->mMine[x][y] == 1)
this->mRealRestMine--;
this->mBoxValue[x][y] = MARK_MINE;
this->mRestMine--;
} else if (this->mBoxValue[x][y] == MARK_MINE) { // 在被标志为地雷的情况下被标志为?
if (this->mMine[x][y] == 1)
this->mRealRestMine++;
this->mBoxValue[x][y] = MARK_UNKNOWN;
this->mRestMine++;
} else if(this->mBoxValue[x][y] == MARK_UNKNOWN) { // 在被标志为?的情况下恢复为盒子
this->mBoxValue[x][y] = MARK_INIT;
}
}
// 描述:点是否被标志过了
// 参数:
// 要判断的点的坐标
// 返回值:
// true:表示被标志过
// false:表示未被标志过
//
bool Mine::IsMark(unsigned int x, unsigned int y) {
if (this->IsOutOfBound(x, y)) {
return false;
}
return this->mBoxValue[x][y] != MARK_INIT;
}
| [
"995139094@qq.com"
] | 995139094@qq.com |
b9477a95629bd2426b4cfafd267d790628afe14f | 78505158b97506dbbd21846035de9d9aa519f985 | /src/init.cpp | c4750edb108d858450c5a0d7ceba7e8d0c81386a | [
"MIT"
] | permissive | zinntikumugai/SanDeGo | 8cde1e042ed5cd436fcd26569021edb44160d228 | 6faac1477c99b38d5747787a9a2f335f8840db56 | refs/heads/master | 2020-03-23T18:29:20.335081 | 2018-07-03T01:17:46 | 2018-07-03T01:17:46 | 141,912,340 | 0 | 0 | MIT | 2019-12-08T03:06:31 | 2018-07-22T16:29:18 | C++ | UTF-8 | C++ | false | false | 36,095 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "checkpoints.h"
#include "zerocoin/ZeroTest.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
bool fConfChange;
bool fEnforceCanonical;
unsigned int nNodeLifespan;
unsigned int nDerivationMethodIndex;
unsigned int nMinerSleep;
bool fUseFastIndex;
enum Checkpoints::CPMode CheckpointsMode;
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
void ExitTimeout(void* parg)
{
#ifdef WIN32
MilliSleep(5000);
ExitProcess(0);
#endif
}
void StartShutdown()
{
#ifdef QT_GUI
// ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
uiInterface.QueueShutdown();
#else
// Without UI, Shutdown() can simply be started in a new thread
NewThread(Shutdown, NULL);
#endif
}
void Shutdown(void* parg)
{
static CCriticalSection cs_Shutdown;
static bool fTaken;
// Make this thread recognisable as the shutdown thread
RenameThread("sandego-shutoff");
bool fFirstThread = false;
{
TRY_LOCK(cs_Shutdown, lockShutdown);
if (lockShutdown)
{
fFirstThread = !fTaken;
fTaken = true;
}
}
static bool fExit;
if (fFirstThread)
{
fShutdown = true;
nTransactionsUpdated++;
// CTxDB().Close();
bitdb.Flush(false);
StopNode();
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
delete pwalletMain;
NewThread(ExitTimeout, NULL);
MilliSleep(50);
printf("SanDeGo exited\n\n");
fExit = true;
#ifndef QT_GUI
// ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
exit(0);
#endif
}
else
{
while (!fExit)
MilliSleep(500);
MilliSleep(100);
ExitThread(0);
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown(NULL);
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("SanDeGo version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" sandegod [options] " + "\n" +
" sandegod [options] <command> [params] " + _("Send command to -server or sandegod") + "\n" +
" sandegod [options] help " + _("List commands") + "\n" +
" sandegod [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "sandego:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
fRet = AppInit2();
}
catch (std::exception& e) {
PrintException(&e, "AppInit()");
} catch (...) {
PrintException(NULL, "AppInit()");
}
if (!fRet)
Shutdown(NULL);
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return 1;
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, _("SanDeGo"), CClientUIInterface::OK | CClientUIInterface::MODAL);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, _("SanDeGo"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
return true;
}
bool static Bind(const CService &addr, bool fError = true) {
if (IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (fError)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: sandego.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: sandegod.pid)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 31932 or testnet: 21873)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -irc " + _("Find peers using internet relay chat (default: 0)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
" -staking " + _("Stake your coins to support network and gain reward (default: 1)") + "\n" +
" -synctime " + _("Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)") + "\n" +
" -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
" -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -testnet " + _("Use the test network") + "\n" +
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 31933 or testnet: 12874)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
" -enforcecanonical " + _("Enforce transaction scripts to use canonical PUSH operators (default: 1)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
/** Sanity checks
* Ensure that Bitcoin is running in a usable environment with all
* necessary library support.
*/
bool InitSanityCheck(void)
{
if(!ECC_InitSanityCheck()) {
InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
"information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
return false;
}
// TODO: remaining sanity checks, see #4081
return true;
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2()
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
nNodeLifespan = GetArg("-addrlifespan", 7);
fUseFastIndex = GetBoolArg("-fastindex", true);
nMinerSleep = GetArg("-minersleep", 500);
CheckpointsMode = Checkpoints::STRICT;
std::string strCpMode = GetArg("-cppolicy", "strict");
if(strCpMode == "strict")
CheckpointsMode = Checkpoints::STRICT;
if(strCpMode == "advisory")
CheckpointsMode = Checkpoints::ADVISORY;
if(strCpMode == "permissive")
CheckpointsMode = Checkpoints::PERMISSIVE;
nDerivationMethodIndex = 0;
fTestNet = GetBoolArg("-testnet");
if (fTestNet) {
SoftSetBoolArg("-irc", true);
}
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
#if !defined(WIN32) && !defined(QT_GUI)
fDaemon = GetBoolArg("-daemon");
#else
fDaemon = false;
#endif
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps");
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
fConfChange = GetBoolArg("-confchange", false);
fEnforceCanonical = GetBoolArg("-enforcecanonical", true);
if (mapArgs.count("-mininput"))
{
if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
// Sanity check
if (!InitSanityCheck())
return InitError(_("Initialization sanity check failed. SanDeGo is shutting down."));
std::string strDataDir = GetDataDir().string();
std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
// strWalletFileName must be a plain filename without a directory
if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. SanDeGo is probably already running."), strDataDir.c_str()));
#if !defined(WIN32) && !defined(QT_GUI)
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0)
{
CreatePidFile(GetPidFile(), pid);
return true;
}
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("SanDeGo version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Used data directory %s\n", strDataDir.c_str());
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "SanDeGo server starting\n");
int64_t nStart;
// ********************************************************* Step 5: verify database integrity
uiInterface.InitMessage(_("Verifying database integrity..."));
if (!bitdb.Open(GetDataDir()))
{
string msg = strprintf(_("Error initializing database environment %s!"
" To recover, BACKUP THAT DIRECTORY, then remove"
" everything from it except for wallet.dat."), strDataDir.c_str());
return InitError(msg);
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
return false;
}
if (filesystem::exists(GetDataDir() / strWalletFileName))
{
CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
uiInterface.ThreadSafeMessageBox(msg, _("SanDeGo"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
#ifdef USE_UPNP
fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
#endif
bool fBound = false;
if (!fNoListen)
{
std::string strError;
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind);
}
} else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
if (!IsLimited(NET_IPV6))
fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
if (!IsLimited(NET_IPV4))
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip"))
{
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
{
if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
{
InitError(_("Invalid amount for -reservebalance=<amount>"));
return false;
}
}
if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
{
if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load blockchain
if (!bitdb.Open(GetDataDir()))
{
string msg = strprintf(_("Error initializing database environment %s!"
" To recover, BACKUP THAT DIRECTORY, then remove"
" everything from it except for wallet.dat."), strDataDir.c_str());
return InitError(msg);
}
if (GetBoolArg("-loadblockindextest"))
{
CTxDB txdb("r");
txdb.LoadBlockIndex();
PrintBlockTree();
return false;
}
uiInterface.InitMessage(_("Loading block index..."));
printf("Loading block index...\n");
nStart = GetTimeMillis();
if (!LoadBlockIndex())
return InitError(_("Error loading blkindex.dat"));
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRId64"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Testing Zerocoin
if (GetBoolArg("-zerotest", false))
{
printf("\n=== ZeroCoin tests start ===\n");
Test_RunAllTests();
printf("=== ZeroCoin tests end ===\n\n");
}
// ********************************************************* Step 8: load wallet
uiInterface.InitMessage(_("Loading wallet..."));
printf("Loading wallet...\n");
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet(strWalletFileName);
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
uiInterface.ThreadSafeMessageBox(msg, _("SanDeGo"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of SanDeGo") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart SanDeGo to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRId64"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb(strWalletFileName);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
}
if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRId64"ms\n", GetTimeMillis() - nStart);
}
// ********************************************************* Step 9: import blocks
if (mapArgs.count("-loadblock"))
{
uiInterface.InitMessage(_("Importing blockchain data file."));
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
{
FILE *file = fopen(strFile.c_str(), "rb");
if (file)
LoadExternalBlockFile(file);
}
exit(0);
}
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
printf("Loading addresses...\n");
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRId64"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
if (!NewThread(StartNode, NULL))
InitError(_("Error: could not start node"));
if (fServer)
NewThread(ThreadRPCServer, NULL);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
printf("Done loading\n");
if (!strErrors.str().empty())
return InitError(strErrors.str());
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
#if !defined(QT_GUI)
// Loop until process is exit()ed from shutdown() function,
// called from ThreadRPCServer thread when a "stop" command is received.
while (1)
MilliSleep(5000);
#endif
return true;
}
| [
"sandego.devs@gmail.com"
] | sandego.devs@gmail.com |
5ea5ed1eac4adbe7422b74f2399f30df6e9f5a02 | 639b83962b2d29f0c6635e4ece354a3cea3bc0d3 | /retinaface/calibrator.cpp | 3f8ff1a0e89e21119e5232a91b15f15087864821 | [
"MIT"
] | permissive | BaofengZan/tensorrtx | eafc4106e848acf39ab87f55ae353d0ba1e82845 | 6aa3d1d421573d150de5c7606f063b5204df9ec9 | refs/heads/master | 2023-06-27T16:36:12.425008 | 2021-07-23T13:16:35 | 2021-07-23T13:16:35 | 299,536,238 | 1 | 0 | MIT | 2020-09-29T07:19:07 | 2020-09-29T07:19:06 | null | UTF-8 | C++ | false | false | 2,790 | cpp | #include <iostream>
#include <iterator>
#include <fstream>
#include <opencv2/dnn/dnn.hpp>
#include "calibrator.h"
#include "cuda_runtime_api.h"
#include "common.hpp"
Int8EntropyCalibrator2::Int8EntropyCalibrator2(int batchsize, int input_w, int input_h, const char* img_dir, const char* calib_table_name, const char* input_blob_name, bool read_cache)
: batchsize_(batchsize)
, input_w_(input_w)
, input_h_(input_h)
, img_idx_(0)
, img_dir_(img_dir)
, calib_table_name_(calib_table_name)
, input_blob_name_(input_blob_name)
, read_cache_(read_cache)
{
input_count_ = 3 * input_w * input_h * batchsize;
CHECK(cudaMalloc(&device_input_, input_count_ * sizeof(float)));
read_files_in_dir(img_dir, img_files_);
}
Int8EntropyCalibrator2::~Int8EntropyCalibrator2()
{
CHECK(cudaFree(device_input_));
}
int Int8EntropyCalibrator2::getBatchSize() const
{
return batchsize_;
}
bool Int8EntropyCalibrator2::getBatch(void* bindings[], const char* names[], int nbBindings)
{
if (img_idx_ + batchsize_ > (int)img_files_.size()) {
return false;
}
std::vector<cv::Mat> input_imgs_;
for (int i = img_idx_; i < img_idx_ + batchsize_; i++) {
std::cout << img_files_[i] << " " << i << std::endl;
cv::Mat temp = cv::imread(img_dir_ + img_files_[i]);
if (temp.empty()){
std::cerr << "Fatal error: image cannot open!" << std::endl;
return false;
}
cv::Mat pr_img = preprocess_img(temp, input_w_, input_h_);
input_imgs_.push_back(pr_img);
}
img_idx_ += batchsize_;
cv::Mat blob = cv::dnn::blobFromImages(input_imgs_, 1.0, cv::Size(input_w_, input_h_), cv::Scalar(104, 117, 123), false, false);
CHECK(cudaMemcpy(device_input_, blob.ptr<float>(0), input_count_ * sizeof(float), cudaMemcpyHostToDevice));
assert(!strcmp(names[0], input_blob_name_));
bindings[0] = device_input_;
return true;
}
const void* Int8EntropyCalibrator2::readCalibrationCache(size_t& length)
{
std::cout << "reading calib cache: " << calib_table_name_ << std::endl;
calib_cache_.clear();
std::ifstream input(calib_table_name_, std::ios::binary);
input >> std::noskipws;
if (read_cache_ && input.good())
{
std::copy(std::istream_iterator<char>(input), std::istream_iterator<char>(), std::back_inserter(calib_cache_));
}
length = calib_cache_.size();
return length ? calib_cache_.data() : nullptr;
}
void Int8EntropyCalibrator2::writeCalibrationCache(const void* cache, size_t length)
{
std::cout << "writing calib cache: " << calib_table_name_ << " size: " << length << std::endl;
std::ofstream output(calib_table_name_, std::ios::binary);
output.write(reinterpret_cast<const char*>(cache), length);
}
| [
"wangxinyu_es@163.com"
] | wangxinyu_es@163.com |
a8218bba12a53f221f2f920fd8a4bcbb36a67fd5 | 587e191159ab12e577940251d14558939e602614 | /verwrite/stockIT/app/src/main/include/Fuse.Controls.NativeTextEditHost.h | 53da705147f6de9e9a85e358ac436f2de7bc4da1 | [] | no_license | hazimayesh/stockIT | cefcaa402e61108294f8db178ee807faf6b14d61 | 809381e7e32df270f0b007a6afc7b394453d1668 | refs/heads/master | 2021-04-09T16:10:23.318883 | 2017-07-31T21:28:05 | 2017-07-31T21:28:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,589 | h | // This file was generated based on 'C:\Users\Emenike pc\AppData\Local\Fusetools\Packages\Fuse.Controls.Primitives\0.43.11\textcontrols\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IResize.h>
#include <Fuse.Binding.h>
#include <Fuse.Controls.NativeViewHost.h>
#include <Fuse.IActualPlacement.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.Actions.ICollapse.h>
#include <Fuse.Triggers.Actions.IHide.h>
#include <Fuse.Triggers.Actions.IShow.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.UX.IPropertyListener.h>
namespace g{namespace Fuse{namespace Controls{struct NativeTextEditHost;}}}
namespace g{
namespace Fuse{
namespace Controls{
// internal sealed class NativeTextEditHost :1435
// {
::g::Fuse::Controls::NativeViewHost_type* NativeTextEditHost_typeof();
void NativeTextEditHost__ctor_8_fn(NativeTextEditHost* __this, uObject* textEdit);
void NativeTextEditHost__CreateNativeViewGroup_fn(NativeTextEditHost* __this, uObject** __retval);
void NativeTextEditHost__New5_fn(uObject* textEdit, NativeTextEditHost** __retval);
void NativeTextEditHost__get_Renderer_fn(NativeTextEditHost* __this, uObject** __retval);
struct NativeTextEditHost : ::g::Fuse::Controls::NativeViewHost
{
uStrong<uObject*> _renderer1;
uStrong<uObject*> _textEdit;
void ctor_8(uObject* textEdit);
static NativeTextEditHost* New5(uObject* textEdit);
};
// }
}}} // ::g::Fuse::Controls
| [
"egaleme@gmail.com"
] | egaleme@gmail.com |
855ac9687ec5c9d85742cac614753c57671cd4d2 | cda4fd3a160a5ee54ac0e4c07cb2761fb2bbc560 | /Simple2D/s2Event/S2CommandEvent.cpp | 8c260845f042477cbe6563c278182a888c72ea51 | [] | no_license | cnscj/Simple2D | 8b1ef2bcb4b543e45c7b6e22a93143c66fba63b8 | 2d3525071da84def66f57efd6d72586aed99b7df | refs/heads/master | 2020-03-18T18:44:17.487513 | 2018-05-28T05:53:54 | 2018-05-28T05:53:54 | 135,111,726 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 737 | cpp | /**
* @Author: cnscj
* @Version: v1.0
* @Date: 2018-05-04 22:31:03
* @Brief:命令事件实现
* @Last Modified by: cnscj
* @Last Modified time: 2018-05-04 22:35:16
* @Last Modified log:
*/
#include "S2CommandEvent.h"
#include "S2EventTable.h"
S2CommandEvent::S2CommandEvent()
:S2BaseEvent(S2EventTable::System::CommandEvent), m_command(0)
{
}
S2CommandEvent::S2CommandEvent(const S2uInt command, void *pSender, void *pUserData)
: S2BaseEvent(S2EventTable::System::CommandEvent, pSender, pUserData), m_command(command)
{
}
S2CommandEvent::~S2CommandEvent()
{
}
void S2CommandEvent::SetCommand(S2uInt command)
{
m_command = command;
}
S2uInt S2CommandEvent::GetCommand() const
{
return m_command;
}
| [
"cnscj@qq.com"
] | cnscj@qq.com |
da1ab5b49266d0073b5b1af7acfa0020cc69872f | 556854947daa06ab8202c9b596099cb1cbbd3746 | /code/Deu2000/SdeSelect.h | fdc66b43d9b500bc0a062ceea00d362091b2fcd6 | [] | no_license | Hyuanwen/ShapFile | d271b22e1f90498f26d5cc690a2571ae2da9d1e8 | 8e070e977ffab61712b042cb11079cf438e56b97 | refs/heads/master | 2021-01-02T09:05:06.625427 | 2019-01-23T03:49:55 | 2019-01-23T03:49:55 | 99,137,521 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 753 | h | #pragma once
#include "afxcmn.h"
#include <string>
#include <vector>
using namespace std;
// CSdeSelect 对话框
class CSdeSelect : public CDialog
{
DECLARE_DYNAMIC(CSdeSelect)
public:
CSdeSelect(const vector<STR_SDEINFO> vecAll, CWnd* pParent = NULL); // 标准构造函数
virtual ~CSdeSelect();
// 对话框数据
enum { IDD = IDD_DLG_SHOW };
protected:
virtual void DoDataExchange(CDataExchange* pDX);
BOOL OnInitDialog();
afx_msg void OnBnClickedOk();
DECLARE_MESSAGE_MAP()
public:
void InitShowData(/*const vector<STR_SDEINFO>& vecRaster*/);
private:
CListCtrl m_ListShow;
vector<STR_SDEINFO> m_vecSelectItem;
vector<STR_SDEINFO> m_vecAll;
public:
vector<STR_SDEINFO> GetSelectItem() const;
};
| [
"742623475@qq.com"
] | 742623475@qq.com |
1d4fb43ef665c77453c24aed52ccf870693bd43d | 78bc09b155f05398ef60dc142545db7ce41e0339 | /C-Programming-Udemy-master/Code/Tutorial 045 - Enumerators/Mac/C Plus Plus Tutorial/C Plus Plus Tutorial/main.cpp | 9fa2e523f5642c9293d21fcc1fba5fc06e6be61e | [
"Unlicense",
"MIT"
] | permissive | PacktPublishing/C-Development-Tutorial-Series---The-Complete-Coding-Guide | 4b17e4aa1eefe6474e3bc30b30f8013ed0109812 | 7b2d3708a052d9ebda3872603f6bef3dc6003560 | refs/heads/master | 2021-06-27T21:43:52.966333 | 2021-01-19T07:59:16 | 2021-01-19T07:59:16 | 185,386,658 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | cpp | //
// main.cpp
// JJJ
//
// Created by Sonar Systems on 03/07/2014.
// Copyright (c) 2014 Sonar Systems. All rights reserved.
//
#include <iostream>
enum Type { hello1 = 90, hello2 = 456, hello3 };
int main(int argc, const char * argv[])
{
std::cout << Type::hello3 << std::endl;
return 0;
}
| [
"asifa@packt.com"
] | asifa@packt.com |
efb11f050a3f0370a97be78970ed53e978bb8ad2 | d324d147e8c414de852b94119bdb130df64096b8 | /sb_jaus/JAUS++/src/jaus/environment/range/ReportRangeSensorCapabilities.h | 11381f245411cbf8fe694488ebc6f7a12e072f2f | [] | no_license | UBC-Snowbots/IGVC2015 | af6ca169e2e4e11b07fa8982d3e6e9ce41a49040 | 18d5274f9b65079ec176e951fdbc6292e1b535f8 | refs/heads/master | 2020-05-15T15:15:24.135949 | 2016-01-09T19:53:43 | 2016-01-09T19:53:43 | 24,005,303 | 1 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 5,446 | h | ////////////////////////////////////////////////////////////////////////////////////
///
/// \file ReportRangeSensorCapabilities.h
/// \brief This file contains the implementation of a JAUS message.
///
/// <br>Author(s): Daniel Barber, Jonathan Harris
/// <br>Created: 15 March 2013
/// <br>Copyright (c) 2013
/// <br>Applied Cognition and Training in Immersive Virtual Environments
/// <br>(ACTIVE) Laboratory
/// <br>Institute for Simulation and Training (IST)
/// <br>University of Central Florida (UCF)
/// <br>All rights reserved.
/// <br>Email: dbarber@ist.ucf.edu, jharris@ist.ucf.edu
/// <br>Web: http://active.ist.ucf.edu
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright
/// notice, this list of conditions and the following disclaimer in the
/// documentation and/or other materials provided with the distribution.
/// * Neither the name of the ACTIVE LAB, IST, UCF, nor the
/// names of its contributors may be used to endorse or promote products
/// derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE ACTIVE LAB''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 UCF 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.
///
////////////////////////////////////////////////////////////////////////////////////
#ifndef __JAUS_ENVIRONMENT_SENSING_REPORT_RANGE_SENSOR_CAPABILITIES__H
#define __JAUS_ENVIRONMENT_SENSING_REPORT_RANGE_SENSOR_CAPABILITIES__H
#include <list>
#include "jaus/core/Message.h"
#include "jaus/environment/range/RangeSensorCapabilities.h"
namespace JAUS
{
////////////////////////////////////////////////////////////////////////////////////
///
/// \class ReportRangeSensorCapabilities
/// \brief This method is used to report the capabilities of a range sensor.
///
////////////////////////////////////////////////////////////////////////////////////
class JAUS_ENVIRONMENT_DLL ReportRangeSensorCapabilities : public Message
{
public:
typedef std::vector<RangeSensorCapabilities> List;
ReportRangeSensorCapabilities(const Address& dest = Address(), const Address& src = Address());
ReportRangeSensorCapabilities(const ReportRangeSensorCapabilities& message);
~ReportRangeSensorCapabilities();
List CopyRangeSensorCapabilitiesList() const
{
List copy(mSensorList);
return copy;
}
//Assignment. Create a copy of the header and all the capability records
ReportRangeSensorCapabilities& operator=(const ReportRangeSensorCapabilities& message)
{
CopyHeaderData(&message);
mSensorList = message.CopyRangeSensorCapabilitiesList();
return *this;
}
void AddSensor(RangeSensorCapabilities sensor) { mSensorList.push_back(sensor); }
//count field for the message
virtual UShort RecordCount() { return (UShort) mSensorList.size(); }
//This is a report message not a command
virtual bool IsCommand() const { return false; }
// Writes message payload data to the packet at the current write position.
virtual int WriteMessageBody(Packet& packet) const;
// Reads message payload data from the packets current read position.
virtual int ReadMessageBody(const Packet& packet);
// Make a copy of the message and returns pointer to it.
Message* Clone() const { return new ReportRangeSensorCapabilities(*this); }
virtual UInt GetPresenceVector() const { return 0; };
virtual UInt GetPresenceVectorSize() const { return (UInt) 0; };
virtual UInt GetPresenceVectorMask() const {return (UInt) 0; }
// Return 0 Because this message is a response type.
virtual UShort GetMessageCodeOfResponse() const { return (UShort) 0; }
// Gets the name of the message in human readable format (for logging, etc.)
virtual std::string GetMessageName() const { return "Report Range Sensor Capabilities"; }
// Clears only message body information.
virtual void ClearMessageBody();
// Return true if payload is greater than maxPaylodSize (payload == message data only).
virtual bool IsLargeDataSet(const unsigned int maxPayloadSize) const;
virtual void PrintMessageBody() const;
protected:
List mSensorList;
};
}
#endif
/* End of File */
| [
"SimonJinaphant@users.noreply.github.com"
] | SimonJinaphant@users.noreply.github.com |
62224eaf8fb6def029c89cb9157cfea0452811fe | 7af93e8c098e212cfb6346fb4a5e36f69464ad54 | /basededatos.h | 6be8f80ebe71891e839621b8164dd3de8fdddf93 | [] | no_license | ander2832/Parcial | e78e1d12ba84990ed07ee2e3390d607979229406 | d6fd4ffee73a93e605aa8f4c7e5bf5deb57aa8e5 | refs/heads/master | 2022-07-16T16:42:59.943001 | 2020-05-15T14:29:50 | 2020-05-15T14:29:50 | 263,198,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,729 | h | #ifndef BASEDEDATOS_H
#define BASEDEDATOS_H
#include <string.h>
#include <map>
#include <vector>
#include <fstream>
#include <iostream>
#include <stdlib.h>
using namespace std;
class basededatos
{
private:
//salas
struct datossala{int filas;int columnas;int tipoasiento;};
map<int,datossala> saladatos;
//tipo de asiento
struct datoasiento{string clasificacion;int costo;};
map<int,datoasiento> datosasiento; //<id:clasificacion,costo>
//cartelera
struct datoscartelera{int idpelicula; string fecha; string hora; int idsala;};
map<int,datoscartelera> Cartelera;// <id:{idpelicula, fecha, hora,id sala}
//pelicula
struct datospelicula{string nombre; string genero; int duracion; int clase;};
map<int,datospelicula> pelidatos; //<id:{nombre, genero, duracion, clase}>
//Usuario
struct userdata{string nombre,clave; int edad;};
map<string,userdata> Usuario; //<cc:{nombre, clave, edad}>
string cc; //id de usuario que inicia sesion
//Reserva
struct datosreserva{int idfuncion; string idusuario; int asientofila; int asientocolumna;};
map<int,datosreserva> reserva;
public:
basededatos();
//Metodos salas y asientos
bool salaisVoid();//retorna true si no hay salas registradas
void Insertsala(int, int, int, int);//Registra una nueva sala
void InsertAsiento();// para insertar un nuevo tipo de asiento
void PrintSalas();
void PrintAsientos();
bool Existsala(int); //retorna true si la sala existe
void Guardarsala(); //Guarda los cambios hechos al archivo sala
void Guardarasiento();
void CambiarPrecioAsiento();//cambiar precio de un asiento
//metodo cartelera
void Insertpeliculacartelera(int,int); //Para ingresar una pelicula a la cartelera
string ValidarFecha();
string ValidarHora();
void Guardarcartelera();
//metodos pelicula
void Guardarpelicula();//guarda los datos en el archivo
void Insertpelicula();//insertar una nueva pelicula
int Printpeliculas();//imprime todas las peliculas retorna la cantidad de peliculas
//metodos usuario
void InsertUser(); //Registrar un usuario
bool Login(); //inicio de sesion, retorna true si el usuario y contraeña es correcta
void Guardarusuario(); //Guarda los datos en el archivo
//metodos reserva
void PrintHorarios(int);
void Newreserva(int); //Hacer una nueva reserva
bool cartelerapelicula(int,int);// verifica si en una funcion esta una pelicula
void pagar(int); //recibe como argumento el tipo de asiento para saber cuanto cobrar
void Guardarreserva();
//Reporte de ventas
void PrintReporte();
bool EdadPelicula(int);
};
#endif // BASEDEDATOS_H
| [
"anderson.aristizabal.2832@gmail.com"
] | anderson.aristizabal.2832@gmail.com |
404c70883ec61790777199a05b4c3f92286abc93 | bca7b0fda68c5eece6b0bbf196f1151e3c40b002 | /clearup.cpp | 865b2a4082d3e3d939151bbf699cd8b89a60f5ad | [] | no_license | NicTian/object_manager | a0b8ad699669fe48242162ddeeee1f6ef5c775f0 | 6c91b7e93c4c72bbf06c2391d918823f6b90ad9a | refs/heads/master | 2020-06-18T16:16:51.035584 | 2019-07-11T09:46:22 | 2019-07-11T09:46:22 | 196,361,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,849 | cpp | #include "clearup.h"
using namespace std;
Clearup::Clearup()
{
}
Clearup::~Clearup()
{
}
void Clearup::cleanup(void *param /* = 0 */)
{
delete this;
}
//------------------------------------------------------------------------------
ClearInfoNode::ClearInfoNode()
{
}
ClearInfoNode::ClearInfoNode(void *object, CLEANUP_FUNC cleanup_hook, void *param)
:object_(object), cleanup_hook_(cleanup_hook), param_(param)
{
}
ClearInfoNode::~ClearInfoNode()
{
}
bool ClearInfoNode::operator==(const ClearInfoNode &o) const
{
return o.object_ == this->object_
&& o.cleanup_hook_ == this->cleanup_hook_
&& o.param_ == this->param_;
}
bool ClearInfoNode::operator!=(const ClearInfoNode &o) const
{
return !(*this == o);
}
extern "C" void cleanupDestroyer(Clearup *object, void *param)
{
object->cleanup(param);
}
//-----------------------------------------------------------------------
ExitInfo::ExitInfo()
{
}
ExitInfo::~ExitInfo()
{
}
int ExitInfo::at_exit_i(void *object, CLEANUP_FUNC cleanup_hook, void *param)
{
ClearInfoNode node(object, cleanup_hook, param);
registered_objects_.push_front(node); //FIFO
return 0;
}
bool ExitInfo::find(void *object)
{
list<ClearInfoNode>::iterator it = registered_objects_.begin();
for (; it != registered_objects_.end(); ++it)
{
if (it->object() == object)
return true;
}
return false;
}
bool ExitInfo::remove(void *object)
{
list<ClearInfoNode>::iterator it = registered_objects_.begin();
for (; it != registered_objects_.end(); ++it)
{
if (it->object() == object)
{
registered_objects_.erase(it);
return true;
}
}
return false;
}
void ExitInfo::call_hooks()
{
list<ClearInfoNode>::iterator it = registered_objects_.begin();
for (; it != registered_objects_.end(); ++it)
{
(*it->cleanup_hook())(it->object(), it->param());
}
registered_objects_.clear();
} | [
"441_bon@163.com"
] | 441_bon@163.com |
0e6be826e7b152f02f48657245f37a662ab56571 | 7faa40ba35aa22f324e5839c36de7ad9bfc3a738 | /src/RcppExports.cpp | b402a276d6fc9e6a42c3d5cc0834d091fc271223 | [] | no_license | rsbivand/PartialNetwork | dbfe2383cfa68935a1d2b2534bda36f6268c58e7 | 617a3c52c7175742e06001cba31f7d03b9c56731 | refs/heads/master | 2023-04-27T07:17:45.753072 | 2021-05-05T04:55:46 | 2021-05-05T04:55:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 71,533 | cpp | // Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <RcppArmadillo.h>
#include <RcppEigen.h>
#include <Rcpp.h>
using namespace Rcpp;
// updateGP
List updateGP(const arma::mat& Y, const arma::mat& trait, const arma::mat& z0, const arma::mat& v0, const arma::vec& d0, const arma::rowvec& b0, const arma::rowvec& eta0, const double& zeta0, const arma::uvec& fixv, const arma::uvec& consb, const double& nsimul, const bool& fdegrees, const bool& fzeta, const NumericVector& hyperparms, const NumericVector& target, const NumericVector& jumpmin, const NumericVector& jumpmax, const int& c, const bool& display_progress);
RcppExport SEXP _PartialNetwork_updateGP(SEXP YSEXP, SEXP traitSEXP, SEXP z0SEXP, SEXP v0SEXP, SEXP d0SEXP, SEXP b0SEXP, SEXP eta0SEXP, SEXP zeta0SEXP, SEXP fixvSEXP, SEXP consbSEXP, SEXP nsimulSEXP, SEXP fdegreesSEXP, SEXP fzetaSEXP, SEXP hyperparmsSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP display_progressSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::mat& >::type Y(YSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type trait(traitSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type z0(z0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type v0(v0SEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type d0(d0SEXP);
Rcpp::traits::input_parameter< const arma::rowvec& >::type b0(b0SEXP);
Rcpp::traits::input_parameter< const arma::rowvec& >::type eta0(eta0SEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const arma::uvec& >::type fixv(fixvSEXP);
Rcpp::traits::input_parameter< const arma::uvec& >::type consb(consbSEXP);
Rcpp::traits::input_parameter< const double& >::type nsimul(nsimulSEXP);
Rcpp::traits::input_parameter< const bool& >::type fdegrees(fdegreesSEXP);
Rcpp::traits::input_parameter< const bool& >::type fzeta(fzetaSEXP);
Rcpp::traits::input_parameter< const NumericVector& >::type hyperparms(hyperparmsSEXP);
Rcpp::traits::input_parameter< const NumericVector& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const NumericVector& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const NumericVector& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const int& >::type c(cSEXP);
Rcpp::traits::input_parameter< const bool& >::type display_progress(display_progressSEXP);
rcpp_result_gen = Rcpp::wrap(updateGP(Y, trait, z0, v0, d0, b0, eta0, zeta0, fixv, consb, nsimul, fdegrees, fzeta, hyperparms, target, jumpmin, jumpmax, c, display_progress));
return rcpp_result_gen;
END_RCPP
}
// dnetwork1
List dnetwork1(const double& T, const double& P, const arma::cube& z, const arma::mat& d, const arma::vec& zeta, const unsigned int& N, const unsigned int& Metrostart, const bool& display_progress);
RcppExport SEXP _PartialNetwork_dnetwork1(SEXP TSEXP, SEXP PSEXP, SEXP zSEXP, SEXP dSEXP, SEXP zetaSEXP, SEXP NSEXP, SEXP MetrostartSEXP, SEXP display_progressSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const double& >::type T(TSEXP);
Rcpp::traits::input_parameter< const double& >::type P(PSEXP);
Rcpp::traits::input_parameter< const arma::cube& >::type z(zSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type d(dSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type zeta(zetaSEXP);
Rcpp::traits::input_parameter< const unsigned int& >::type N(NSEXP);
Rcpp::traits::input_parameter< const unsigned int& >::type Metrostart(MetrostartSEXP);
Rcpp::traits::input_parameter< const bool& >::type display_progress(display_progressSEXP);
rcpp_result_gen = Rcpp::wrap(dnetwork1(T, P, z, d, zeta, N, Metrostart, display_progress));
return rcpp_result_gen;
END_RCPP
}
// dnetwork2
List dnetwork2(const double& T, const double& P, const arma::cube& z, const arma::mat& d, const arma::vec& zeta, const arma::mat& Xard, const arma::mat& Xnonard, const arma::uvec& iARD, const arma::uvec& inonARD, const unsigned int& M, const unsigned int& Metrostart, const bool& display_progress);
RcppExport SEXP _PartialNetwork_dnetwork2(SEXP TSEXP, SEXP PSEXP, SEXP zSEXP, SEXP dSEXP, SEXP zetaSEXP, SEXP XardSEXP, SEXP XnonardSEXP, SEXP iARDSEXP, SEXP inonARDSEXP, SEXP MSEXP, SEXP MetrostartSEXP, SEXP display_progressSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const double& >::type T(TSEXP);
Rcpp::traits::input_parameter< const double& >::type P(PSEXP);
Rcpp::traits::input_parameter< const arma::cube& >::type z(zSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type d(dSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type zeta(zetaSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Xard(XardSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Xnonard(XnonardSEXP);
Rcpp::traits::input_parameter< const arma::uvec& >::type iARD(iARDSEXP);
Rcpp::traits::input_parameter< const arma::uvec& >::type inonARD(inonARDSEXP);
Rcpp::traits::input_parameter< const unsigned int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const unsigned int& >::type Metrostart(MetrostartSEXP);
Rcpp::traits::input_parameter< const bool& >::type display_progress(display_progressSEXP);
rcpp_result_gen = Rcpp::wrap(dnetwork2(T, P, z, d, zeta, Xard, Xnonard, iARD, inonARD, M, Metrostart, display_progress));
return rcpp_result_gen;
END_RCPP
}
// Prob
arma::mat Prob(arma::vec& nu, arma::vec& d, double& zeta, arma::mat& z);
RcppExport SEXP _PartialNetwork_Prob(SEXP nuSEXP, SEXP dSEXP, SEXP zetaSEXP, SEXP zSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec& >::type nu(nuSEXP);
Rcpp::traits::input_parameter< arma::vec& >::type d(dSEXP);
Rcpp::traits::input_parameter< double& >::type zeta(zetaSEXP);
Rcpp::traits::input_parameter< arma::mat& >::type z(zSEXP);
rcpp_result_gen = Rcpp::wrap(Prob(nu, d, zeta, z));
return rcpp_result_gen;
END_RCPP
}
// Graph
arma::umat Graph(arma::mat& prob);
RcppExport SEXP _PartialNetwork_Graph(SEXP probSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat& >::type prob(probSEXP);
rcpp_result_gen = Rcpp::wrap(Graph(prob));
return rcpp_result_gen;
END_RCPP
}
// instruments1
List instruments1(const arma::mat& dnetwork, arma::mat& X, arma::vec& y, const int& S, const int& pow);
RcppExport SEXP _PartialNetwork_instruments1(SEXP dnetworkSEXP, SEXP XSEXP, SEXP ySEXP, SEXP SSEXP, SEXP powSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::mat& >::type dnetwork(dnetworkSEXP);
Rcpp::traits::input_parameter< arma::mat& >::type X(XSEXP);
Rcpp::traits::input_parameter< arma::vec& >::type y(ySEXP);
Rcpp::traits::input_parameter< const int& >::type S(SSEXP);
Rcpp::traits::input_parameter< const int& >::type pow(powSEXP);
rcpp_result_gen = Rcpp::wrap(instruments1(dnetwork, X, y, S, pow));
return rcpp_result_gen;
END_RCPP
}
// instruments2
List instruments2(const arma::mat& dnetwork, arma::mat& X, const int& S, const int& pow);
RcppExport SEXP _PartialNetwork_instruments2(SEXP dnetworkSEXP, SEXP XSEXP, SEXP SSEXP, SEXP powSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::mat& >::type dnetwork(dnetworkSEXP);
Rcpp::traits::input_parameter< arma::mat& >::type X(XSEXP);
Rcpp::traits::input_parameter< const int& >::type S(SSEXP);
Rcpp::traits::input_parameter< const int& >::type pow(powSEXP);
rcpp_result_gen = Rcpp::wrap(instruments2(dnetwork, X, S, pow));
return rcpp_result_gen;
END_RCPP
}
// flistGnorm1
List flistGnorm1(List& dnetwork, arma::vec& y, arma::mat& Xone, arma::mat& X, const int& M);
RcppExport SEXP _PartialNetwork_flistGnorm1(SEXP dnetworkSEXP, SEXP ySEXP, SEXP XoneSEXP, SEXP XSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type dnetwork(dnetworkSEXP);
Rcpp::traits::input_parameter< arma::vec& >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat& >::type Xone(XoneSEXP);
Rcpp::traits::input_parameter< arma::mat& >::type X(XSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(flistGnorm1(dnetwork, y, Xone, X, M));
return rcpp_result_gen;
END_RCPP
}
// flistGnorm2
List flistGnorm2(List& Gnorm, arma::vec& y, arma::mat& Xone, arma::mat& X, const int& M);
RcppExport SEXP _PartialNetwork_flistGnorm2(SEXP GnormSEXP, SEXP ySEXP, SEXP XoneSEXP, SEXP XSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< arma::vec& >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat& >::type Xone(XoneSEXP);
Rcpp::traits::input_parameter< arma::mat& >::type X(XSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(flistGnorm2(Gnorm, y, Xone, X, M));
return rcpp_result_gen;
END_RCPP
}
// flistGnorm1nc
List flistGnorm1nc(List& dnetwork, arma::vec& y, arma::mat& Xone, const int& M);
RcppExport SEXP _PartialNetwork_flistGnorm1nc(SEXP dnetworkSEXP, SEXP ySEXP, SEXP XoneSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type dnetwork(dnetworkSEXP);
Rcpp::traits::input_parameter< arma::vec& >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat& >::type Xone(XoneSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(flistGnorm1nc(dnetwork, y, Xone, M));
return rcpp_result_gen;
END_RCPP
}
// flistGnorm2nc
List flistGnorm2nc(List& Gnorm, arma::vec& y, arma::mat& Xone, const int& M);
RcppExport SEXP _PartialNetwork_flistGnorm2nc(SEXP GnormSEXP, SEXP ySEXP, SEXP XoneSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< arma::vec& >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat& >::type Xone(XoneSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(flistGnorm2nc(Gnorm, y, Xone, M));
return rcpp_result_gen;
END_RCPP
}
// simG
List simG(List& dnetwork, const arma::vec& N, const int& M);
RcppExport SEXP _PartialNetwork_simG(SEXP dnetworkSEXP, SEXP NSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type dnetwork(dnetworkSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(simG(dnetwork, N, M));
return rcpp_result_gen;
END_RCPP
}
// simGnorm
List simGnorm(List& dnetwork, const arma::vec& N, const int& M);
RcppExport SEXP _PartialNetwork_simGnorm(SEXP dnetworkSEXP, SEXP NSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type dnetwork(dnetworkSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(simGnorm(dnetwork, N, M));
return rcpp_result_gen;
END_RCPP
}
// peerMCMCnoc_none
List peerMCMCnoc_none(const List& y, const List& V, List& Gnorm, List& prior, List ListIndex, const int& M, const IntegerVector& N, const int& kbeta, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, const arma::vec& parms0, const int& iteration, const double& target, const double& jumpmin, const double& jumpmax, const double& c, const int& progress);
RcppExport SEXP _PartialNetwork_peerMCMCnoc_none(SEXP ySEXP, SEXP VSEXP, SEXP GnormSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP kbetaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP progressSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type V(VSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const double& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const double& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const double& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMCnoc_none(y, V, Gnorm, prior, ListIndex, M, N, kbeta, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, parms0, iteration, target, jumpmin, jumpmax, c, progress));
return rcpp_result_gen;
END_RCPP
}
// peerMCMCblocknoc_none
List peerMCMCblocknoc_none(const List& y, const List& V, List& Gnorm, List& prior, List ListIndex, const int& M, const IntegerVector& N, const int& kbeta, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, const arma::vec& parms0, const int& iteration, const double& target, const double& jumpmin, const double& jumpmax, const double& c, const int& progress, const int& nupmax);
RcppExport SEXP _PartialNetwork_peerMCMCblocknoc_none(SEXP ySEXP, SEXP VSEXP, SEXP GnormSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP kbetaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP progressSEXP, SEXP nupmaxSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type V(VSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const double& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const double& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const double& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
Rcpp::traits::input_parameter< const int& >::type nupmax(nupmaxSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMCblocknoc_none(y, V, Gnorm, prior, ListIndex, M, N, kbeta, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, parms0, iteration, target, jumpmin, jumpmax, c, progress, nupmax));
return rcpp_result_gen;
END_RCPP
}
// peerMCMC_none
List peerMCMC_none(const List& y, const List& X, const List& Xone, List& Gnorm, List& prior, List ListIndex, const int& M, const IntegerVector& N, const int& kbeta, const int& kgamma, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, const arma::vec& parms0, const int& iteration, const double& target, const double& jumpmin, const double& jumpmax, const double& c, const int& progress);
RcppExport SEXP _PartialNetwork_peerMCMC_none(SEXP ySEXP, SEXP XSEXP, SEXP XoneSEXP, SEXP GnormSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP kbetaSEXP, SEXP kgammaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP progressSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type X(XSEXP);
Rcpp::traits::input_parameter< const List& >::type Xone(XoneSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const int& >::type kgamma(kgammaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const double& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const double& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const double& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMC_none(y, X, Xone, Gnorm, prior, ListIndex, M, N, kbeta, kgamma, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, parms0, iteration, target, jumpmin, jumpmax, c, progress));
return rcpp_result_gen;
END_RCPP
}
// peerMCMCblock_none
List peerMCMCblock_none(const List& y, const List& X, const List& Xone, List& Gnorm, List& prior, List ListIndex, const int& M, const IntegerVector& N, const int& kbeta, const int& kgamma, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, const arma::vec& parms0, const int& iteration, const double& target, const double& jumpmin, const double& jumpmax, const double& c, const int& progress, const int& nupmax);
RcppExport SEXP _PartialNetwork_peerMCMCblock_none(SEXP ySEXP, SEXP XSEXP, SEXP XoneSEXP, SEXP GnormSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP kbetaSEXP, SEXP kgammaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP progressSEXP, SEXP nupmaxSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type X(XSEXP);
Rcpp::traits::input_parameter< const List& >::type Xone(XoneSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const int& >::type kgamma(kgammaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const double& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const double& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const double& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
Rcpp::traits::input_parameter< const int& >::type nupmax(nupmaxSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMCblock_none(y, X, Xone, Gnorm, prior, ListIndex, M, N, kbeta, kgamma, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, parms0, iteration, target, jumpmin, jumpmax, c, progress, nupmax));
return rcpp_result_gen;
END_RCPP
}
// peerMCMCnoc_ard
List peerMCMCnoc_ard(const List& y, const List& V, List& Gnorm, List& G0obs, List& prior, List& ListIndex, const int& M, const Rcpp::IntegerVector& N, const Rcpp::IntegerVector& N1, const int& kbeta, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, List& d, const arma::vec& zetaard, List& murho, List& Vrho, const arma::vec& Krho, List& neighbor, List& weight, List& iARD, List& inonARD, const Rcpp::IntegerVector& P, const arma::vec& parms0, const int& iteration, const arma::vec& target, const arma::vec& jumpmin, const arma::vec& jumpmax, const double& c, const arma::vec& type, const int& progress);
RcppExport SEXP _PartialNetwork_peerMCMCnoc_ard(SEXP ySEXP, SEXP VSEXP, SEXP GnormSEXP, SEXP G0obsSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP N1SEXP, SEXP kbetaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP dSEXP, SEXP zetaardSEXP, SEXP murhoSEXP, SEXP VrhoSEXP, SEXP KrhoSEXP, SEXP neighborSEXP, SEXP weightSEXP, SEXP iARDSEXP, SEXP inonARDSEXP, SEXP PSEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP typeSEXP, SEXP progressSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type V(VSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type G0obs(G0obsSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List& >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N1(N1SEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< List& >::type d(dSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type zetaard(zetaardSEXP);
Rcpp::traits::input_parameter< List& >::type murho(murhoSEXP);
Rcpp::traits::input_parameter< List& >::type Vrho(VrhoSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type Krho(KrhoSEXP);
Rcpp::traits::input_parameter< List& >::type neighbor(neighborSEXP);
Rcpp::traits::input_parameter< List& >::type weight(weightSEXP);
Rcpp::traits::input_parameter< List& >::type iARD(iARDSEXP);
Rcpp::traits::input_parameter< List& >::type inonARD(inonARDSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type P(PSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type type(typeSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMCnoc_ard(y, V, Gnorm, G0obs, prior, ListIndex, M, N, N1, kbeta, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, d, zetaard, murho, Vrho, Krho, neighbor, weight, iARD, inonARD, P, parms0, iteration, target, jumpmin, jumpmax, c, type, progress));
return rcpp_result_gen;
END_RCPP
}
// peerMCMCblocknoc_ard
List peerMCMCblocknoc_ard(const List& y, const List& V, List& Gnorm, List& G0obs, List& prior, List& ListIndex, const int& M, const Rcpp::IntegerVector& N, const Rcpp::IntegerVector& N1, const int& kbeta, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, List& d, const arma::vec& zetaard, List& murho, List& Vrho, const arma::vec& Krho, List& neighbor, List& weight, List& iARD, List& inonARD, const Rcpp::IntegerVector& P, const arma::vec& parms0, const int& iteration, const arma::vec& target, const arma::vec& jumpmin, const arma::vec& jumpmax, const double& c, const arma::vec& type, const int& progress, const int& nupmax);
RcppExport SEXP _PartialNetwork_peerMCMCblocknoc_ard(SEXP ySEXP, SEXP VSEXP, SEXP GnormSEXP, SEXP G0obsSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP N1SEXP, SEXP kbetaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP dSEXP, SEXP zetaardSEXP, SEXP murhoSEXP, SEXP VrhoSEXP, SEXP KrhoSEXP, SEXP neighborSEXP, SEXP weightSEXP, SEXP iARDSEXP, SEXP inonARDSEXP, SEXP PSEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP typeSEXP, SEXP progressSEXP, SEXP nupmaxSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type V(VSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type G0obs(G0obsSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List& >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N1(N1SEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< List& >::type d(dSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type zetaard(zetaardSEXP);
Rcpp::traits::input_parameter< List& >::type murho(murhoSEXP);
Rcpp::traits::input_parameter< List& >::type Vrho(VrhoSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type Krho(KrhoSEXP);
Rcpp::traits::input_parameter< List& >::type neighbor(neighborSEXP);
Rcpp::traits::input_parameter< List& >::type weight(weightSEXP);
Rcpp::traits::input_parameter< List& >::type iARD(iARDSEXP);
Rcpp::traits::input_parameter< List& >::type inonARD(inonARDSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type P(PSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type type(typeSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
Rcpp::traits::input_parameter< const int& >::type nupmax(nupmaxSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMCblocknoc_ard(y, V, Gnorm, G0obs, prior, ListIndex, M, N, N1, kbeta, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, d, zetaard, murho, Vrho, Krho, neighbor, weight, iARD, inonARD, P, parms0, iteration, target, jumpmin, jumpmax, c, type, progress, nupmax));
return rcpp_result_gen;
END_RCPP
}
// peerMCMC_ard
List peerMCMC_ard(const List& y, const List& X, const List& Xone, List& Gnorm, List& G0obs, List& prior, List& ListIndex, const int& M, const Rcpp::IntegerVector& N, const Rcpp::IntegerVector& N1, const int& kbeta, const int& kgamma, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, const List& d, const arma::vec& zetaard, const List& murho, const List& Vrho, const arma::vec& Krho, List& neighbor, List& weight, List& iARD, List& inonARD, const Rcpp::IntegerVector& P, const arma::vec& parms0, const int& iteration, const arma::vec& target, const arma::vec& jumpmin, const arma::vec& jumpmax, const double& c, const arma::vec& type, const int& progress);
RcppExport SEXP _PartialNetwork_peerMCMC_ard(SEXP ySEXP, SEXP XSEXP, SEXP XoneSEXP, SEXP GnormSEXP, SEXP G0obsSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP N1SEXP, SEXP kbetaSEXP, SEXP kgammaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP dSEXP, SEXP zetaardSEXP, SEXP murhoSEXP, SEXP VrhoSEXP, SEXP KrhoSEXP, SEXP neighborSEXP, SEXP weightSEXP, SEXP iARDSEXP, SEXP inonARDSEXP, SEXP PSEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP typeSEXP, SEXP progressSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type X(XSEXP);
Rcpp::traits::input_parameter< const List& >::type Xone(XoneSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type G0obs(G0obsSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List& >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N1(N1SEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const int& >::type kgamma(kgammaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< const List& >::type d(dSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type zetaard(zetaardSEXP);
Rcpp::traits::input_parameter< const List& >::type murho(murhoSEXP);
Rcpp::traits::input_parameter< const List& >::type Vrho(VrhoSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type Krho(KrhoSEXP);
Rcpp::traits::input_parameter< List& >::type neighbor(neighborSEXP);
Rcpp::traits::input_parameter< List& >::type weight(weightSEXP);
Rcpp::traits::input_parameter< List& >::type iARD(iARDSEXP);
Rcpp::traits::input_parameter< List& >::type inonARD(inonARDSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type P(PSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type type(typeSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMC_ard(y, X, Xone, Gnorm, G0obs, prior, ListIndex, M, N, N1, kbeta, kgamma, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, d, zetaard, murho, Vrho, Krho, neighbor, weight, iARD, inonARD, P, parms0, iteration, target, jumpmin, jumpmax, c, type, progress));
return rcpp_result_gen;
END_RCPP
}
// peerMCMCblock_ard
List peerMCMCblock_ard(const List& y, const List& X, const List& Xone, List& Gnorm, List& G0obs, List& prior, List& ListIndex, const int& M, const Rcpp::IntegerVector& N, const Rcpp::IntegerVector& N1, const int& kbeta, const int& kgamma, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, List& d, const arma::vec& zetaard, List& murho, List& Vrho, const arma::vec& Krho, List& neighbor, List& weight, List& iARD, List& inonARD, const Rcpp::IntegerVector& P, const arma::vec& parms0, const int& iteration, const arma::vec& target, const arma::vec& jumpmin, const arma::vec& jumpmax, const double& c, const arma::vec& type, const int& progress, const int& nupmax);
RcppExport SEXP _PartialNetwork_peerMCMCblock_ard(SEXP ySEXP, SEXP XSEXP, SEXP XoneSEXP, SEXP GnormSEXP, SEXP G0obsSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP N1SEXP, SEXP kbetaSEXP, SEXP kgammaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP dSEXP, SEXP zetaardSEXP, SEXP murhoSEXP, SEXP VrhoSEXP, SEXP KrhoSEXP, SEXP neighborSEXP, SEXP weightSEXP, SEXP iARDSEXP, SEXP inonARDSEXP, SEXP PSEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP typeSEXP, SEXP progressSEXP, SEXP nupmaxSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type X(XSEXP);
Rcpp::traits::input_parameter< const List& >::type Xone(XoneSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type G0obs(G0obsSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List& >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N1(N1SEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const int& >::type kgamma(kgammaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< List& >::type d(dSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type zetaard(zetaardSEXP);
Rcpp::traits::input_parameter< List& >::type murho(murhoSEXP);
Rcpp::traits::input_parameter< List& >::type Vrho(VrhoSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type Krho(KrhoSEXP);
Rcpp::traits::input_parameter< List& >::type neighbor(neighborSEXP);
Rcpp::traits::input_parameter< List& >::type weight(weightSEXP);
Rcpp::traits::input_parameter< List& >::type iARD(iARDSEXP);
Rcpp::traits::input_parameter< List& >::type inonARD(inonARDSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type P(PSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type type(typeSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
Rcpp::traits::input_parameter< const int& >::type nupmax(nupmaxSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMCblock_ard(y, X, Xone, Gnorm, G0obs, prior, ListIndex, M, N, N1, kbeta, kgamma, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, d, zetaard, murho, Vrho, Krho, neighbor, weight, iARD, inonARD, P, parms0, iteration, target, jumpmin, jumpmax, c, type, progress, nupmax));
return rcpp_result_gen;
END_RCPP
}
// peerMCMCnoc_pl
List peerMCMCnoc_pl(const List& y, const List& V, List& Gnorm, List& G0obs, List& prior, List& ListIndex, const int& M, const IntegerVector& N, const int& kbeta, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, const arma::mat& dZ, const arma::vec& murho, const arma::mat& Vrho, const int& Krho, Eigen::VectorXd& lFdZrho1, Eigen::VectorXd& lFdZrho0, const arma::vec& parms0, const int& iteration, const arma::vec& target, const arma::vec& jumpmin, const arma::vec& jumpmax, const double& c, const int& progress, const int& type);
RcppExport SEXP _PartialNetwork_peerMCMCnoc_pl(SEXP ySEXP, SEXP VSEXP, SEXP GnormSEXP, SEXP G0obsSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP kbetaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP dZSEXP, SEXP murhoSEXP, SEXP VrhoSEXP, SEXP KrhoSEXP, SEXP lFdZrho1SEXP, SEXP lFdZrho0SEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP progressSEXP, SEXP typeSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type V(VSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type G0obs(G0obsSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List& >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type dZ(dZSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type murho(murhoSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Vrho(VrhoSEXP);
Rcpp::traits::input_parameter< const int& >::type Krho(KrhoSEXP);
Rcpp::traits::input_parameter< Eigen::VectorXd& >::type lFdZrho1(lFdZrho1SEXP);
Rcpp::traits::input_parameter< Eigen::VectorXd& >::type lFdZrho0(lFdZrho0SEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
Rcpp::traits::input_parameter< const int& >::type type(typeSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMCnoc_pl(y, V, Gnorm, G0obs, prior, ListIndex, M, N, kbeta, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, dZ, murho, Vrho, Krho, lFdZrho1, lFdZrho0, parms0, iteration, target, jumpmin, jumpmax, c, progress, type));
return rcpp_result_gen;
END_RCPP
}
// peerMCMCblocknoc_pl
List peerMCMCblocknoc_pl(const List& y, const List& V, List& Gnorm, List& G0obs, List& prior, List& ListIndex, const int& M, const IntegerVector& N, const int& kbeta, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, const arma::mat& dZ, const arma::vec& murho, const arma::mat& Vrho, const int& Krho, Eigen::VectorXd& lFdZrho1, Eigen::VectorXd& lFdZrho0, const arma::vec& parms0, const int& iteration, const arma::vec& target, const arma::vec& jumpmin, const arma::vec& jumpmax, const double& c, const int& progress, const int& nupmax, const int& type);
RcppExport SEXP _PartialNetwork_peerMCMCblocknoc_pl(SEXP ySEXP, SEXP VSEXP, SEXP GnormSEXP, SEXP G0obsSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP kbetaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP dZSEXP, SEXP murhoSEXP, SEXP VrhoSEXP, SEXP KrhoSEXP, SEXP lFdZrho1SEXP, SEXP lFdZrho0SEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP progressSEXP, SEXP nupmaxSEXP, SEXP typeSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type V(VSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type G0obs(G0obsSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List& >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type dZ(dZSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type murho(murhoSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Vrho(VrhoSEXP);
Rcpp::traits::input_parameter< const int& >::type Krho(KrhoSEXP);
Rcpp::traits::input_parameter< Eigen::VectorXd& >::type lFdZrho1(lFdZrho1SEXP);
Rcpp::traits::input_parameter< Eigen::VectorXd& >::type lFdZrho0(lFdZrho0SEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
Rcpp::traits::input_parameter< const int& >::type nupmax(nupmaxSEXP);
Rcpp::traits::input_parameter< const int& >::type type(typeSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMCblocknoc_pl(y, V, Gnorm, G0obs, prior, ListIndex, M, N, kbeta, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, dZ, murho, Vrho, Krho, lFdZrho1, lFdZrho0, parms0, iteration, target, jumpmin, jumpmax, c, progress, nupmax, type));
return rcpp_result_gen;
END_RCPP
}
// peerMCMC_pl
List peerMCMC_pl(const List& y, const List& X, const List& Xone, List& Gnorm, List& G0obs, List& prior, List& ListIndex, const int& M, const IntegerVector& N, const int& kbeta, const int& kgamma, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, const arma::mat& dZ, const arma::vec& murho, const arma::mat& Vrho, const int& Krho, Eigen::VectorXd& lFdZrho1, Eigen::VectorXd& lFdZrho0, const arma::vec& parms0, const int& iteration, const arma::vec& target, const arma::vec& jumpmin, const arma::vec& jumpmax, const double& c, const int& progress, const int& type);
RcppExport SEXP _PartialNetwork_peerMCMC_pl(SEXP ySEXP, SEXP XSEXP, SEXP XoneSEXP, SEXP GnormSEXP, SEXP G0obsSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP kbetaSEXP, SEXP kgammaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP dZSEXP, SEXP murhoSEXP, SEXP VrhoSEXP, SEXP KrhoSEXP, SEXP lFdZrho1SEXP, SEXP lFdZrho0SEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP progressSEXP, SEXP typeSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type X(XSEXP);
Rcpp::traits::input_parameter< const List& >::type Xone(XoneSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type G0obs(G0obsSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List& >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const int& >::type kgamma(kgammaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type dZ(dZSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type murho(murhoSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Vrho(VrhoSEXP);
Rcpp::traits::input_parameter< const int& >::type Krho(KrhoSEXP);
Rcpp::traits::input_parameter< Eigen::VectorXd& >::type lFdZrho1(lFdZrho1SEXP);
Rcpp::traits::input_parameter< Eigen::VectorXd& >::type lFdZrho0(lFdZrho0SEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
Rcpp::traits::input_parameter< const int& >::type type(typeSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMC_pl(y, X, Xone, Gnorm, G0obs, prior, ListIndex, M, N, kbeta, kgamma, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, dZ, murho, Vrho, Krho, lFdZrho1, lFdZrho0, parms0, iteration, target, jumpmin, jumpmax, c, progress, type));
return rcpp_result_gen;
END_RCPP
}
// peerMCMCblock_pl
List peerMCMCblock_pl(const List& y, const List& X, const List& Xone, List& Gnorm, List& G0obs, List& prior, List& ListIndex, const int& M, const IntegerVector& N, const int& kbeta, const int& kgamma, const arma::vec& theta0, const arma::mat& invsigmatheta, const double& zeta0, const double& invsigma2zeta, const double& a, const double& b, const arma::mat& dZ, const arma::vec murho, const arma::mat& Vrho, const int& Krho, Eigen::VectorXd& lFdZrho1, Eigen::VectorXd& lFdZrho0, const arma::vec& parms0, const int& iteration, const arma::vec& target, const arma::vec& jumpmin, const arma::vec& jumpmax, const double& c, const int& progress, const int& nupmax, const int& type);
RcppExport SEXP _PartialNetwork_peerMCMCblock_pl(SEXP ySEXP, SEXP XSEXP, SEXP XoneSEXP, SEXP GnormSEXP, SEXP G0obsSEXP, SEXP priorSEXP, SEXP ListIndexSEXP, SEXP MSEXP, SEXP NSEXP, SEXP kbetaSEXP, SEXP kgammaSEXP, SEXP theta0SEXP, SEXP invsigmathetaSEXP, SEXP zeta0SEXP, SEXP invsigma2zetaSEXP, SEXP aSEXP, SEXP bSEXP, SEXP dZSEXP, SEXP murhoSEXP, SEXP VrhoSEXP, SEXP KrhoSEXP, SEXP lFdZrho1SEXP, SEXP lFdZrho0SEXP, SEXP parms0SEXP, SEXP iterationSEXP, SEXP targetSEXP, SEXP jumpminSEXP, SEXP jumpmaxSEXP, SEXP cSEXP, SEXP progressSEXP, SEXP nupmaxSEXP, SEXP typeSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type X(XSEXP);
Rcpp::traits::input_parameter< const List& >::type Xone(XoneSEXP);
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< List& >::type G0obs(G0obsSEXP);
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List& >::type ListIndex(ListIndexSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const int& >::type kgamma(kgammaSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta0(theta0SEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type invsigmatheta(invsigmathetaSEXP);
Rcpp::traits::input_parameter< const double& >::type zeta0(zeta0SEXP);
Rcpp::traits::input_parameter< const double& >::type invsigma2zeta(invsigma2zetaSEXP);
Rcpp::traits::input_parameter< const double& >::type a(aSEXP);
Rcpp::traits::input_parameter< const double& >::type b(bSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type dZ(dZSEXP);
Rcpp::traits::input_parameter< const arma::vec >::type murho(murhoSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Vrho(VrhoSEXP);
Rcpp::traits::input_parameter< const int& >::type Krho(KrhoSEXP);
Rcpp::traits::input_parameter< Eigen::VectorXd& >::type lFdZrho1(lFdZrho1SEXP);
Rcpp::traits::input_parameter< Eigen::VectorXd& >::type lFdZrho0(lFdZrho0SEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type parms0(parms0SEXP);
Rcpp::traits::input_parameter< const int& >::type iteration(iterationSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type target(targetSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmin(jumpminSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type jumpmax(jumpmaxSEXP);
Rcpp::traits::input_parameter< const double& >::type c(cSEXP);
Rcpp::traits::input_parameter< const int& >::type progress(progressSEXP);
Rcpp::traits::input_parameter< const int& >::type nupmax(nupmaxSEXP);
Rcpp::traits::input_parameter< const int& >::type type(typeSEXP);
rcpp_result_gen = Rcpp::wrap(peerMCMCblock_pl(y, X, Xone, Gnorm, G0obs, prior, ListIndex, M, N, kbeta, kgamma, theta0, invsigmatheta, zeta0, invsigma2zeta, a, b, dZ, murho, Vrho, Krho, lFdZrho1, lFdZrho0, parms0, iteration, target, jumpmin, jumpmax, c, progress, nupmax, type));
return rcpp_result_gen;
END_RCPP
}
// sartpoint
arma::vec sartpoint(List& Gnorm, const int& M, const IntegerVector& N, const int& kbeta, const int& kgamma, const List& y, const List& X, const List& Xone);
RcppExport SEXP _PartialNetwork_sartpoint(SEXP GnormSEXP, SEXP MSEXP, SEXP NSEXP, SEXP kbetaSEXP, SEXP kgammaSEXP, SEXP ySEXP, SEXP XSEXP, SEXP XoneSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const int& >::type kgamma(kgammaSEXP);
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type X(XSEXP);
Rcpp::traits::input_parameter< const List& >::type Xone(XoneSEXP);
rcpp_result_gen = Rcpp::wrap(sartpoint(Gnorm, M, N, kbeta, kgamma, y, X, Xone));
return rcpp_result_gen;
END_RCPP
}
// sartpointnoc
arma::vec sartpointnoc(List& Gnorm, const int& M, const IntegerVector& N, const int& kbeta, const List& y, const List& Xone);
RcppExport SEXP _PartialNetwork_sartpointnoc(SEXP GnormSEXP, SEXP MSEXP, SEXP NSEXP, SEXP kbetaSEXP, SEXP ySEXP, SEXP XoneSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type Gnorm(GnormSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const int& >::type kbeta(kbetaSEXP);
Rcpp::traits::input_parameter< const List& >::type y(ySEXP);
Rcpp::traits::input_parameter< const List& >::type Xone(XoneSEXP);
rcpp_result_gen = Rcpp::wrap(sartpointnoc(Gnorm, M, N, kbeta, y, Xone));
return rcpp_result_gen;
END_RCPP
}
// fListIndex
List fListIndex(List& prior, List& G0obs, const int& M, const IntegerVector& N);
RcppExport SEXP _PartialNetwork_fListIndex(SEXP priorSEXP, SEXP G0obsSEXP, SEXP MSEXP, SEXP NSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type prior(priorSEXP);
Rcpp::traits::input_parameter< List& >::type G0obs(G0obsSEXP);
Rcpp::traits::input_parameter< const int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
rcpp_result_gen = Rcpp::wrap(fListIndex(prior, G0obs, M, N));
return rcpp_result_gen;
END_RCPP
}
// fGnormalise
List fGnormalise(List& u, const double& M);
RcppExport SEXP _PartialNetwork_fGnormalise(SEXP uSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type u(uSEXP);
Rcpp::traits::input_parameter< const double& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(fGnormalise(u, M));
return rcpp_result_gen;
END_RCPP
}
// frVtoM
List frVtoM(const Eigen::VectorXd& u, const Rcpp::IntegerVector& N, const double& M);
RcppExport SEXP _PartialNetwork_frVtoM(SEXP uSEXP, SEXP NSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const Eigen::VectorXd& >::type u(uSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const double& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(frVtoM(u, N, M));
return rcpp_result_gen;
END_RCPP
}
// frVtoMnorm
List frVtoMnorm(const arma::vec& u, const IntegerVector& N, const double& M);
RcppExport SEXP _PartialNetwork_frVtoMnorm(SEXP uSEXP, SEXP NSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::vec& >::type u(uSEXP);
Rcpp::traits::input_parameter< const IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const double& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(frVtoMnorm(u, N, M));
return rcpp_result_gen;
END_RCPP
}
// frMtoV
Eigen::VectorXd frMtoV(List& u, const Rcpp::IntegerVector& N, const double& M);
RcppExport SEXP _PartialNetwork_frMtoV(SEXP uSEXP, SEXP NSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type u(uSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const double& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(frMtoV(u, N, M));
return rcpp_result_gen;
END_RCPP
}
// frMceiltoV
Eigen::VectorXd frMceiltoV(List& u, const Rcpp::IntegerVector& N, const double& M);
RcppExport SEXP _PartialNetwork_frMceiltoV(SEXP uSEXP, SEXP NSEXP, SEXP MSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List& >::type u(uSEXP);
Rcpp::traits::input_parameter< const Rcpp::IntegerVector& >::type N(NSEXP);
Rcpp::traits::input_parameter< const double& >::type M(MSEXP);
rcpp_result_gen = Rcpp::wrap(frMceiltoV(u, N, M));
return rcpp_result_gen;
END_RCPP
}
// flspacerho1
List flspacerho1(const double& T, const double& P, const arma::cube& z, const arma::mat& d, const arma::vec& zeta, const unsigned int& N1, const unsigned int& Metrostart);
RcppExport SEXP _PartialNetwork_flspacerho1(SEXP TSEXP, SEXP PSEXP, SEXP zSEXP, SEXP dSEXP, SEXP zetaSEXP, SEXP N1SEXP, SEXP MetrostartSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const double& >::type T(TSEXP);
Rcpp::traits::input_parameter< const double& >::type P(PSEXP);
Rcpp::traits::input_parameter< const arma::cube& >::type z(zSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type d(dSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type zeta(zetaSEXP);
Rcpp::traits::input_parameter< const unsigned int& >::type N1(N1SEXP);
Rcpp::traits::input_parameter< const unsigned int& >::type Metrostart(MetrostartSEXP);
rcpp_result_gen = Rcpp::wrap(flspacerho1(T, P, z, d, zeta, N1, Metrostart));
return rcpp_result_gen;
END_RCPP
}
// flspacerho2
List flspacerho2(const double& T, const double& P, const arma::cube& z, const arma::mat& d, const arma::vec& zeta, const arma::mat& Xard, const arma::mat& Xnonard, const unsigned int& N1, const unsigned int& N2, const unsigned int& M, const unsigned int& Metrostart);
RcppExport SEXP _PartialNetwork_flspacerho2(SEXP TSEXP, SEXP PSEXP, SEXP zSEXP, SEXP dSEXP, SEXP zetaSEXP, SEXP XardSEXP, SEXP XnonardSEXP, SEXP N1SEXP, SEXP N2SEXP, SEXP MSEXP, SEXP MetrostartSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const double& >::type T(TSEXP);
Rcpp::traits::input_parameter< const double& >::type P(PSEXP);
Rcpp::traits::input_parameter< const arma::cube& >::type z(zSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type d(dSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type zeta(zetaSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Xard(XardSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Xnonard(XnonardSEXP);
Rcpp::traits::input_parameter< const unsigned int& >::type N1(N1SEXP);
Rcpp::traits::input_parameter< const unsigned int& >::type N2(N2SEXP);
Rcpp::traits::input_parameter< const unsigned int& >::type M(MSEXP);
Rcpp::traits::input_parameter< const unsigned int& >::type Metrostart(MetrostartSEXP);
rcpp_result_gen = Rcpp::wrap(flspacerho2(T, P, z, d, zeta, Xard, Xnonard, N1, N2, M, Metrostart));
return rcpp_result_gen;
END_RCPP
}
// fdnetARD
arma::mat fdnetARD(arma::mat& zm, arma::vec& num, arma::vec& dm, const int& N1m, const int& N2m, const int& Nm, const int& Pm, const double& zetam, const double& logCpzetam, const arma::umat& neighborm, const arma::mat& weightm, const arma::uvec& iARDm, const arma::uvec& inonARDm);
RcppExport SEXP _PartialNetwork_fdnetARD(SEXP zmSEXP, SEXP numSEXP, SEXP dmSEXP, SEXP N1mSEXP, SEXP N2mSEXP, SEXP NmSEXP, SEXP PmSEXP, SEXP zetamSEXP, SEXP logCpzetamSEXP, SEXP neighbormSEXP, SEXP weightmSEXP, SEXP iARDmSEXP, SEXP inonARDmSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat& >::type zm(zmSEXP);
Rcpp::traits::input_parameter< arma::vec& >::type num(numSEXP);
Rcpp::traits::input_parameter< arma::vec& >::type dm(dmSEXP);
Rcpp::traits::input_parameter< const int& >::type N1m(N1mSEXP);
Rcpp::traits::input_parameter< const int& >::type N2m(N2mSEXP);
Rcpp::traits::input_parameter< const int& >::type Nm(NmSEXP);
Rcpp::traits::input_parameter< const int& >::type Pm(PmSEXP);
Rcpp::traits::input_parameter< const double& >::type zetam(zetamSEXP);
Rcpp::traits::input_parameter< const double& >::type logCpzetam(logCpzetamSEXP);
Rcpp::traits::input_parameter< const arma::umat& >::type neighborm(neighbormSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type weightm(weightmSEXP);
Rcpp::traits::input_parameter< const arma::uvec& >::type iARDm(iARDmSEXP);
Rcpp::traits::input_parameter< const arma::uvec& >::type inonARDm(inonARDmSEXP);
rcpp_result_gen = Rcpp::wrap(fdnetARD(zm, num, dm, N1m, N2m, Nm, Pm, zetam, logCpzetam, neighborm, weightm, iARDm, inonARDm));
return rcpp_result_gen;
END_RCPP
}
// rvMFcpp
arma::mat rvMFcpp(const int& size, const arma::vec& theta);
RcppExport SEXP _PartialNetwork_rvMFcpp(SEXP sizeSEXP, SEXP thetaSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const int& >::type size(sizeSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta(thetaSEXP);
rcpp_result_gen = Rcpp::wrap(rvMFcpp(size, theta));
return rcpp_result_gen;
END_RCPP
}
// logCpvMFcpp
double logCpvMFcpp(const int& p, const double& k);
RcppExport SEXP _PartialNetwork_logCpvMFcpp(SEXP pSEXP, SEXP kSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const int& >::type p(pSEXP);
Rcpp::traits::input_parameter< const double& >::type k(kSEXP);
rcpp_result_gen = Rcpp::wrap(logCpvMFcpp(p, k));
return rcpp_result_gen;
END_RCPP
}
// dvMFcpp
NumericVector dvMFcpp(const arma::mat& z, const arma::vec& theta, const bool& logp);
RcppExport SEXP _PartialNetwork_dvMFcpp(SEXP zSEXP, SEXP thetaSEXP, SEXP logpSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::mat& >::type z(zSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type theta(thetaSEXP);
Rcpp::traits::input_parameter< const bool& >::type logp(logpSEXP);
rcpp_result_gen = Rcpp::wrap(dvMFcpp(z, theta, logp));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_PartialNetwork_updateGP", (DL_FUNC) &_PartialNetwork_updateGP, 19},
{"_PartialNetwork_dnetwork1", (DL_FUNC) &_PartialNetwork_dnetwork1, 8},
{"_PartialNetwork_dnetwork2", (DL_FUNC) &_PartialNetwork_dnetwork2, 12},
{"_PartialNetwork_Prob", (DL_FUNC) &_PartialNetwork_Prob, 4},
{"_PartialNetwork_Graph", (DL_FUNC) &_PartialNetwork_Graph, 1},
{"_PartialNetwork_instruments1", (DL_FUNC) &_PartialNetwork_instruments1, 5},
{"_PartialNetwork_instruments2", (DL_FUNC) &_PartialNetwork_instruments2, 4},
{"_PartialNetwork_flistGnorm1", (DL_FUNC) &_PartialNetwork_flistGnorm1, 5},
{"_PartialNetwork_flistGnorm2", (DL_FUNC) &_PartialNetwork_flistGnorm2, 5},
{"_PartialNetwork_flistGnorm1nc", (DL_FUNC) &_PartialNetwork_flistGnorm1nc, 4},
{"_PartialNetwork_flistGnorm2nc", (DL_FUNC) &_PartialNetwork_flistGnorm2nc, 4},
{"_PartialNetwork_simG", (DL_FUNC) &_PartialNetwork_simG, 3},
{"_PartialNetwork_simGnorm", (DL_FUNC) &_PartialNetwork_simGnorm, 3},
{"_PartialNetwork_peerMCMCnoc_none", (DL_FUNC) &_PartialNetwork_peerMCMCnoc_none, 21},
{"_PartialNetwork_peerMCMCblocknoc_none", (DL_FUNC) &_PartialNetwork_peerMCMCblocknoc_none, 22},
{"_PartialNetwork_peerMCMC_none", (DL_FUNC) &_PartialNetwork_peerMCMC_none, 23},
{"_PartialNetwork_peerMCMCblock_none", (DL_FUNC) &_PartialNetwork_peerMCMCblock_none, 24},
{"_PartialNetwork_peerMCMCnoc_ard", (DL_FUNC) &_PartialNetwork_peerMCMCnoc_ard, 34},
{"_PartialNetwork_peerMCMCblocknoc_ard", (DL_FUNC) &_PartialNetwork_peerMCMCblocknoc_ard, 35},
{"_PartialNetwork_peerMCMC_ard", (DL_FUNC) &_PartialNetwork_peerMCMC_ard, 36},
{"_PartialNetwork_peerMCMCblock_ard", (DL_FUNC) &_PartialNetwork_peerMCMCblock_ard, 37},
{"_PartialNetwork_peerMCMCnoc_pl", (DL_FUNC) &_PartialNetwork_peerMCMCnoc_pl, 29},
{"_PartialNetwork_peerMCMCblocknoc_pl", (DL_FUNC) &_PartialNetwork_peerMCMCblocknoc_pl, 30},
{"_PartialNetwork_peerMCMC_pl", (DL_FUNC) &_PartialNetwork_peerMCMC_pl, 31},
{"_PartialNetwork_peerMCMCblock_pl", (DL_FUNC) &_PartialNetwork_peerMCMCblock_pl, 32},
{"_PartialNetwork_sartpoint", (DL_FUNC) &_PartialNetwork_sartpoint, 8},
{"_PartialNetwork_sartpointnoc", (DL_FUNC) &_PartialNetwork_sartpointnoc, 6},
{"_PartialNetwork_fListIndex", (DL_FUNC) &_PartialNetwork_fListIndex, 4},
{"_PartialNetwork_fGnormalise", (DL_FUNC) &_PartialNetwork_fGnormalise, 2},
{"_PartialNetwork_frVtoM", (DL_FUNC) &_PartialNetwork_frVtoM, 3},
{"_PartialNetwork_frVtoMnorm", (DL_FUNC) &_PartialNetwork_frVtoMnorm, 3},
{"_PartialNetwork_frMtoV", (DL_FUNC) &_PartialNetwork_frMtoV, 3},
{"_PartialNetwork_frMceiltoV", (DL_FUNC) &_PartialNetwork_frMceiltoV, 3},
{"_PartialNetwork_flspacerho1", (DL_FUNC) &_PartialNetwork_flspacerho1, 7},
{"_PartialNetwork_flspacerho2", (DL_FUNC) &_PartialNetwork_flspacerho2, 11},
{"_PartialNetwork_fdnetARD", (DL_FUNC) &_PartialNetwork_fdnetARD, 13},
{"_PartialNetwork_rvMFcpp", (DL_FUNC) &_PartialNetwork_rvMFcpp, 2},
{"_PartialNetwork_logCpvMFcpp", (DL_FUNC) &_PartialNetwork_logCpvMFcpp, 2},
{"_PartialNetwork_dvMFcpp", (DL_FUNC) &_PartialNetwork_dvMFcpp, 3},
{NULL, NULL, 0}
};
RcppExport void R_init_PartialNetwork(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
| [
"ariel92and@gmail.com"
] | ariel92and@gmail.com |
012cfbeadb96e0a2519592b264d25480c92c119e | da1ba0378e1ed8ff8380afb9072efcd3bbead74e | /google/cloud/storage/internal/openssl_util.cc | 4b1d09f8fac6065980a6204bfff262f69c083c87 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Jseph/google-cloud-cpp | 76894af7ce744cd44304b48bea32d5116ded7497 | fd8e70650ebac0c10bac4b293972e79eef46b128 | refs/heads/master | 2022-10-18T13:07:01.710328 | 2022-10-01T18:16:16 | 2022-10-01T18:16:16 | 192,397,663 | 0 | 0 | null | 2019-06-17T18:22:36 | 2019-06-17T18:22:35 | null | UTF-8 | C++ | false | false | 6,904 | cc | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/internal/openssl_util.h"
#include "google/cloud/internal/base64_transforms.h"
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/evp.h>
#include <openssl/opensslv.h>
#include <openssl/pem.h>
#include <memory>
namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
namespace {
// The name of the function to free an EVP_MD_CTX changed in OpenSSL 1.1.0.
#if (OPENSSL_VERSION_NUMBER < 0x10100000L) // Older than version 1.1.0.
inline std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)>
GetDigestCtx() {
return std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)>(
EVP_MD_CTX_create(), &EVP_MD_CTX_destroy);
};
#else
inline std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> GetDigestCtx() {
return std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
EVP_MD_CTX_new(), &EVP_MD_CTX_free);
};
#endif
} // namespace
StatusOr<std::vector<std::uint8_t>> Base64Decode(std::string const& str) {
return google::cloud::internal::Base64DecodeToBytes(str);
}
std::string Base64Encode(std::string const& str) {
google::cloud::internal::Base64Encoder enc;
for (auto c : str) enc.PushBack(c);
return std::move(enc).FlushAndPad();
}
std::string Base64Encode(absl::Span<std::uint8_t const> bytes) {
google::cloud::internal::Base64Encoder enc;
for (auto c : bytes) enc.PushBack(c);
return std::move(enc).FlushAndPad();
}
StatusOr<std::vector<std::uint8_t>> SignStringWithPem(
std::string const& str, std::string const& pem_contents,
storage::oauth2::JwtSigningAlgorithms alg) {
using ::google::cloud::storage::oauth2::JwtSigningAlgorithms;
auto digest_ctx = GetDigestCtx();
if (!digest_ctx) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not create context for OpenSSL digest. ");
}
EVP_MD const* digest_type = nullptr;
switch (alg) {
case JwtSigningAlgorithms::RS256:
digest_type = EVP_sha256();
break;
}
if (digest_type == nullptr) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not find specified digest in OpenSSL. ");
}
auto pem_buffer = std::unique_ptr<BIO, decltype(&BIO_free)>(
BIO_new_mem_buf(pem_contents.data(),
static_cast<int>(pem_contents.length())),
&BIO_free);
if (!pem_buffer) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not create PEM buffer. ");
}
auto private_key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>(
PEM_read_bio_PrivateKey(
pem_buffer.get(),
nullptr, // EVP_PKEY **x
nullptr, // pem_password_cb *cb -- a custom callback.
// void *u -- this represents the password for the PEM (only
// applicable for formats such as PKCS12 (.p12 files) that use
// a password, which we don't currently support.
nullptr),
&EVP_PKEY_free);
if (!private_key) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not parse PEM to get private key ");
}
int const digest_sign_success_code = 1;
if (digest_sign_success_code !=
EVP_DigestSignInit(digest_ctx.get(),
nullptr, // `EVP_PKEY_CTX **pctx`
digest_type,
nullptr, // `ENGINE *e`
private_key.get())) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not initialize PEM digest. ");
}
if (digest_sign_success_code !=
EVP_DigestSignUpdate(digest_ctx.get(), str.data(), str.length())) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not update PEM digest. ");
}
std::size_t signed_str_size = 0;
// Calling this method with a nullptr buffer will populate our size var
// with the resulting buffer's size. This allows us to then call it again,
// with the correct buffer and size, which actually populates the buffer.
if (digest_sign_success_code !=
EVP_DigestSignFinal(digest_ctx.get(),
nullptr, // unsigned char *sig
&signed_str_size)) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not finalize PEM digest (1/2). ");
}
std::vector<unsigned char> signed_str(signed_str_size);
if (digest_sign_success_code != EVP_DigestSignFinal(digest_ctx.get(),
signed_str.data(),
&signed_str_size)) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not finalize PEM digest (2/2). ");
}
return StatusOr<std::vector<unsigned char>>(
{signed_str.begin(), signed_str.end()});
}
StatusOr<std::vector<std::uint8_t>> UrlsafeBase64Decode(
std::string const& str) {
if (str.empty()) return std::vector<std::uint8_t>{};
std::string b64str = str;
std::replace(b64str.begin(), b64str.end(), '-', '+');
std::replace(b64str.begin(), b64str.end(), '_', '/');
// To restore the padding there are only two cases:
// https://en.wikipedia.org/wiki/Base64#Decoding_Base64_without_padding
if (b64str.length() % 4 == 2) {
b64str.append("==");
} else if (b64str.length() % 4 == 3) {
b64str.append("=");
}
return Base64Decode(b64str);
}
std::vector<std::uint8_t> MD5Hash(std::string const& payload) {
std::array<unsigned char, EVP_MAX_MD_SIZE> digest;
unsigned int size = 0;
EVP_Digest(payload.data(), payload.size(), digest.data(), &size, EVP_md5(),
nullptr);
return std::vector<std::uint8_t>{digest.begin(),
std::next(digest.begin(), size)};
}
} // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace storage
} // namespace cloud
} // namespace google
| [
"noreply@github.com"
] | noreply@github.com |
dccf425ee08cad1a3b4dfc9ff83740b615d82ecf | 80bb02194f8b6d08d9ffa4969cc7e4c28543f065 | /include/logcpp/FileLogger.h | 7d201449be0ea1678a2691ab3f6780898fb62911 | [
"MIT"
] | permissive | mrts/log-cpp | 793d6432747e14f628f1de8d9db4d149782ca7e5 | 6aab25c07e37bf5cc736580cab951bee9abe07dd | refs/heads/master | 2021-01-20T02:16:58.755628 | 2015-01-01T19:32:28 | 2015-01-01T19:32:28 | 28,541,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,763 | h | #ifndef LOGCPP_FILELOGGER_H__
#define LOGCPP_FILELOGGER_H__
#include <logcpp/log.h>
#include <fstream>
#include <sys/stat.h>
namespace logcpp
{
class FileLogger : public Logger
{
public:
FileLogger(const std::string& logfilePath,
const size_t fileSizeLimit = 500000)
: Logger(),
_logfilePath(logfilePath),
_logfile(_logfilePath.c_str(), std::ios::app),
_fileSizeLimit(fileSizeLimit)
{
check();
}
virtual ~FileLogger()
{
// _logfile.close() is implicit
}
private:
virtual void logImpl(const std::string& timestamp, const std::string& label,
const std::string& message) override
{
if (fileSize() > _fileSizeLimit)
rotateLogfile();
_logfile << timestamp << " " << label << ": " << message << std::endl;
check();
// TODO: _logfile.flush(); ?
}
void check() const
{
if (_logfile.fail())
throw std::runtime_error("Failure in log file " + _logfilePath);
}
size_t fileSize() const
{
struct stat stat_buf;
if (stat(_logfilePath.c_str(), &stat_buf) != 0)
return 0;
else
return stat_buf.st_size;
}
void rotateLogfile()
{
_logfile.close();
backupLogFile();
_logfile = std::ofstream(_logfilePath.c_str(), std::ios::trunc);
check();
}
void backupLogFile() const
{
std::ifstream src(_logfilePath, std::ios::binary);
std::ofstream dst(_logfilePath + ".1", std::ios::binary);
dst << src.rdbuf();
}
std::string _logfilePath;
std::ofstream _logfile;
size_t _fileSizeLimit;
};
}
#endif /* LOGCPP_FILELOGGER_H */
| [
"mart.somermaa@cgi.com"
] | mart.somermaa@cgi.com |
eb9c3d54aa847d49ac7b02d3a77d3a31dcdbd981 | 0fc7bf510e8aa2984e9118d39af32b3b8aaedfb9 | /DriverPack/PS2Mouse.cpp | e85d0ac99632d990a4dcfc4e3d2fef1d1bd0fa17 | [] | no_license | Vort/VortOS | 5d2b8efce265b51dd5790c32664a9d9f0fbbb0fd | c5b81a0c3155debc0ff9c85c175e4b4133a358f9 | refs/heads/master | 2022-09-02T14:04:46.009070 | 2013-11-15T07:31:20 | 2013-11-15T07:36:39 | 3,678,751 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,059 | cpp | // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// PS2Mouse.cpp
#include "API.h"
// ----------------------------------------------------------------------------
class CPS2Mouse
{
public:
CPS2Mouse()
{
buttonPressed[0] = false;
buttonPressed[1] = false;
m_Flags = 0;
m_DeltaX = 0;
m_DeltaY = 0;
m_DataIndex = 0;
KeEnableNotification(NfKe_TerminateProcess);
KeEnableNotification(Nfi8043_MouseData);
CNotification<1> N;
for (;;)
{
KeWaitFor(1);
N.Recv();
if (N.GetID() == Nfi8043_MouseData)
{
byte Param = N.GetByte(0);
if (m_DataIndex == 0)
{
byte Flags = Param;
if (Flags & 0x8)
{
m_Flags = Flags;
m_DataIndex++;
}
}
else if (m_DataIndex == 1)
{
m_DeltaX = Param;
m_DataIndex++;
}
else
{
m_DeltaY = Param;
m_DataIndex = 0;
int DeltaX = m_DeltaX;
int DeltaY = m_DeltaY;
DeltaX |= TestBit(m_Flags, 4) * 0xFFFFFF00;
DeltaY |= TestBit(m_Flags, 5) * 0xFFFFFF00;
DeltaY = -DeltaY;
bool buttonPressedNew[2] =
{
TestBit(m_Flags, 0),
TestBit(m_Flags, 1)
};
if ((DeltaX != 0) || (DeltaY != 0))
{
int moveData[2] = {DeltaX, DeltaY};
KeNotify(Nf_MouseDeltaMove, (byte*)moveData, 8);
}
for (int i = 0; i < 2; i++)
{
if (buttonPressed[i] != buttonPressedNew[i])
{
if (buttonPressedNew[i])
KeNotify(Nf_MouseButtonDown, (byte*)(&i), 1);
else
KeNotify(Nf_MouseButtonUp, (byte*)(&i), 1);
buttonPressed[i] = buttonPressedNew[i];
}
}
}
}
else if (N.GetID() == NfKe_TerminateProcess)
{
return;
}
}
}
private:
dword m_DataIndex;
byte m_Flags;
byte m_DeltaX;
byte m_DeltaY;
bool buttonPressed[2];
};
// ----------------------------------------------------------------------------
void Entry()
{
if (!KeSetSymbol(Sm_Lock_Ps2Mouse))
return;
CPS2Mouse M;
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | [
"vvort@yandex.ru"
] | vvort@yandex.ru |
fdeb271297f4f17b7ebc8af96271d5539fbda076 | 9600652f021e3203651bfc8e23009c3976434fee | /img2base64.h | 886d3149975448beeb514997b097bf6329c6cf83 | [] | no_license | Bakirbrkic/KalmanCamera | 5e300e57ca3672dc1e87e98f29cbf9c516423959 | fdd61404701d5d11afde196c874597b8241fb722 | refs/heads/master | 2022-11-24T19:02:23.357695 | 2020-07-28T12:48:28 | 2020-07-28T12:48:28 | 273,534,721 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 478 | h | #ifndef IMG2BASE64_H
#define IMG2BASE64_H
#include <QObject>
#include <QQuickItem>
#include <QImage>
#include <QtXml/QtXml>
class img2base64 : public QObject
{
Q_OBJECT
Q_PROPERTY(QString encode2base64 READ getEncoded WRITE encode NOTIFY encoded)
private:
QString base64result;
public:
explicit img2base64(QObject *parent = nullptr);
void encode(QString path);
QString getEncoded();
signals:
void encoded(QString);
};
#endif // IMG2BASE64_H
| [
"bakirbrkic@hotmail.com"
] | bakirbrkic@hotmail.com |
c4a9c7716fb49ef3f34308bf82c5ffe79b2c36d9 | 4283e8a54ed50dfa88ac9c4dbaf7443e0d527492 | /main.cpp | 6b0abffb9c0cb5d9f13bde9fbb22ee9e4daaf370 | [] | no_license | Far117/Wizard_War | a36f39960f0cbe75aabc70703a0cea74bd891e3f | 4eb5652661b8c3a8928522b4c9eb94918451a00d | refs/heads/master | 2021-01-23T09:28:01.922089 | 2015-03-22T23:49:28 | 2015-03-22T23:49:28 | 21,220,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,995 | cpp | #include <iostream>
#include <cstdlib>
#include <vector>
#include "save.h"
#include "constants.h"
#include "functions.h"
#include "spells.h"
#include "Story.h"
#include "token.h"
using namespace std;
Inf info;
Hero player;
void splash(){
cout << " Wizard War" << endl;
cout << " " << info.type << " " << info.version;
if(info.patch>0){
cout << " Patch #" << info.patch;
}
cout << "\n Press enter...." << endl;
inputS("");
}
//========================================================= Forward Declarations =================
//extern vector<Spell> spell_list;
//extern Spell fireball;
extern Spell punch;
extern Completed story;
void town();
void starting_story();
void stats();
void apothecary();
void hall();
void bank();
void sheriff();
void outside(bool);
void hospital();
void school();
void gym();
void master();
void doctor();
//================================================================= End ==========================
void newCharacter(){
clear_screen();
player.name=inputS("What is your name: ");
player.age=inputI("How old are you: ");
do{
player.boygirl=lower(inputS("Are you a boy or a girl: "));
} while(!(player.boygirl=="boy" || player.boygirl=="girl"));
if(player.boygirl=="boy"){
player.himher="him";
player.hishers="his";
player.sondaughter="son";
} else{
player.himher="her";
player.hishers="hers";
player.sondaughter="daughter";
}
do{
player.element=lower(inputS("Is your preferred power Fire, Water, Earth, Air, Force, Unarmed, or Sword Combat: "));
} while(!(player.element=="fire" ||
player.element=="water" ||
player.element=="earth" ||
player.element=="air" ||
player.element=="force" ||
player.element=="unarmed" ||
player.element=="sword combat"));
if (player.name=="superskip"){
town();
}
starting_story();
}
void starting_story(){
clear_screen();
for (int x=0;x<50;x++) cout << endl;
cout << "=================================================================";
cout << " The Scroll of Beginnings:";
scroll();
cout << "A long, long time ago, in a land far, far away...";
scroll();
cout << "A great wizard lived with his only " << player.sondaughter << ", " << player.name << ".";
scroll();
cout << "His arch-nemisis, [illegible], had just risen to power...";
scroll();
cout << "They fought in an epic clash, destroying entire countries.";
scroll();
cout << "Eventually, the wizard won, and peace remained for years.";
scroll();
cout << "Until one fateful day, on [illegible], [illegible] returned...";
scroll();
cout << "This time, the battle raged for months. Civilization itself hung by a thread...";
scroll();
cout << "Almost all life was extinct, save for the rabid monsters summoned to help the dark wizard..." ;
scroll();
cout << "This time, the wizard lost. Telling " << player.name << " his last wishes, he perished...";
scroll();
cout << "[Wizard]: " << player.name << ", you must gain power. Save humanity... Avenge me! And remember...";
scroll();
cout << "[Wizard]: Just..." << endl;
scroll();
cout << "[Wizard]: Just..." << endl;
scroll();
cout << "[Wizard]: Just..." << endl;
scroll();
cout << "SCROLL BURNED OFF HERE" ;
scroll();
cout << "//////////////////////////////////////////////////////////////////////" << endl;
scroll();
enter();
town();
}
void town(){
clear_screen();
int choice;
cout << "Welcome to Pensor! Population: " << player.pop << endl;
cout << "Would you like to:" << endl;
cout << "View your Stats? (1)" << endl;
cout << "Visit the Apothecary? (2)" << endl;
cout << "Visit Town Hall? (3)" << endl;
cout << "Visit the Police Offices? (4)" << endl;
cout << "Go outside? (5)" << endl;
cout << "Save? (6)" << endl;
cout << "Visit the Wizard School? (7)" << endl;
cout << "Visit the Gym (8)";
if (story.first_power==false){
cout << " Hint: You need to buy your first move, punch, here!!!" << endl;
}else{
cout << endl;
}
cout << "See the Swords Master (9)" << endl;
cout << "Create a Battle Token (10)" << endl;
cout << "Fight a Battle Token (BROKEN)" << endl;
cout << "Or visit the hospital? (12)" << endl;
choice=inputI("["+player.name+"]: ");
if(choice==1){
stats();
} else if (choice==2){
apothecary();
}else if (choice==3){
hall();
} else if(choice==4){
sheriff();
} else if (choice==5){
outside(false);
}else if(choice==6){
save(player);
}else if(choice==117){
player=load(player);
}else if(choice==7){
school();
}else if(choice==8){
gym();
}else if(choice==9){
master();
}else if(choice==10){
save_token(player);
}else if(choice==11){
outside(true);
} else if (choice == 12){
doctor();
}
town();
}
void stats(){
clear_screen();
//float need=player.x*2.5-player.xp;
//if(need<0){need=0;}
cout << "==========Stats========" << endl;
cout << "Name: " << player.name << endl;
cout << "Age: " << player.age << endl;
cout << "Boost: " << player.element << endl;
//cout << "XP: " << player.xp << endl;
//cout << "XP Needed to Level Up: " << need << endl;
cout << "Money: " << player.money << " Vi" << endl;
cout << "Level: " << player.level << endl;
cout << "Health: " << player.health << "/" << player.max_health << endl;
cout << "Power: " << player.power << "/" << player.max_power << endl;
cout << "Defence: " << player.defence << endl;
cout << "==========Records======" << endl;
cout << "Total Attacks Made: " << player.total_attacks << endl;
cout << "Deaths: " << player.deaths << endl;
cout << "Enemies Killed: " << player.killed << endl;
cout << "Total Money Earned: " << player.total_money << endl;
/*
if (need==0){
if (lower(inputS("You have enough XP to level up! Would you like to? "))=="yes"){
player.xp-=(player.x*2.5);
player.x*=2.5;
player.level++;
player.max_health*=1.5;
player.max_power*=1.5;
player.defence*=1.5;
player.clean();
player.reset_health();
player.reset_power();
cout << "Congratulations! You are now 50% stronger!" << endl;
enter();
stats();
}
}
*/
enter();
clear_screen();
cout << "======Stats Page 2=====" << endl;
cout << "Fire Skill: " << player.fire_level << endl;
cout << "Water Skill: " << player.water_level << endl;
cout << "Earth Skill: " << player.earth_level << endl;
cout << "Air Level: " << player.air_level << endl;
cout << "Force Level: " << player.force_level << endl;
cout << "Swordsmanship Level: " << player.sword_level << endl;
cout << "Unarmed Level: " << player.unarmed_level << endl << endl;
enter();
clear_screen();
cout << "======Stats Page 3=====" << endl;
cout << "Fire XP: " << player.fire_xp << endl;
cout << "Fire XP Needed: " << player.fire_need-player.fire_xp << endl << endl;
cout << "Water XP: " << player.water_xp << endl;
cout << "Water XP Needed: " << player.water_need-player.water_xp << endl << endl;
cout << "Earth XP: " << player.earth_xp << endl;
cout << "Earth XP Needed: " << player.earth_need-player.earth_xp << endl << endl;
cout << "Air XP: " << player.air_xp << endl;
cout << "Air XP Needed: " << player.air_need-player.air_xp << endl << endl;
cout << "Force XP: " << player.force_xp << endl;
cout << "Force XP Needed: " << player.force_need-player.force_xp << endl << endl;
cout << "Swordsmanship XP: " << player.sword_xp << endl;
cout << "Swordsmanship XP needed: " << player.sword_need-player.sword_xp << endl << endl;
cout << "Unarmed XP: " << player.unarmed_xp << endl;
cout << "Unarmed XP Needed: " << player.unarmed_need-player.unarmed_xp << endl << endl;
enter();
town();
}
void apothecary(){
clear_screen();
bool bought=true;
cout << "You have " << player.money << " Vi, " << player.health << "/" << player.max_health << " health," << endl;
cout << player.max_power << " power, and " << player.defence << " defence." << endl;
cout << endl;
cout << "[Lyla]: I have lots of high quality potions for sale. Would you like:" << endl;
cout << "Small health potion: Heals 20 hp for 1 Vi? (1)" << endl;
cout << "Medium health potion: Heals 80 hp for 3 Vi? (2)" << endl;
cout << "Large health potion? Heals 150 hp for 5 Vi? (3)" << endl;
cout << "Small upper health potion? Increases max health by 5 for 10 Vi? (4)" << endl;
cout << "Medium upper health potion? Increases max health by 20 for 15 Vi? (5)" << endl;
cout << "Large upper health potion? Increases max health by 50 for 30 Vi? (6)" << endl;
cout << "Defence potion? Increases defence by 20% for 15 Vi? (7)" << endl;
cout << "Or maybe a power potion? Increases your power by 20% for 15 Vi? (8)" << endl;
cout << "\n=====================================================================\n" << endl;
cout << "We also have a very large health potion, heal 300 hp for 9 Vi? (9)" << endl;
cout << "And a huge health potion to heal 500 hp for 14 Vi? (10)" << endl;
cout << "Or you could just get out of here> (11)" << endl;
int choice=inputI("["+player.name+"]: ");
if (choice==1&&player.money>=1){
player.money-=1;
player.health+=20;
}else if (choice==2&&player.money>=3){
player.money-=3;
player.health+=80;
}else if (choice==3&&player.money>=5){
player.money-=5;
player.health+=150;
}else if (choice==4&&player.money>=10){
player.money-=10;
player.max_health+=5;
}else if (choice==5&&player.money>=15){
player.money-=15;
player.max_health+=20;
}else if (choice==6&&player.money>=30){
player.money-=30;
player.max_health+=50;
}else if (choice==7&&player.money>=15){
player.money-=15;
player.defence*=1.2;
} else if (choice==8&&player.money>=15){
player.money-=15;
player.max_power*=1.2;
player.reset_power();
}else if (choice==11){
player.check();
town();
}else if (choice==9 && player.money>=9){
player.money-=9;
player.health+=300;
}else if (choice==10 && player.money>=14){
player.money-=14;
player.health+=500;
}else{
cout << "[Lyla] You don't have that kind of cash!";
bought=false;
}
if(bought){cout << "Thanks for your purchase!" << endl;}
player.check();
player.clean();
enter();
apothecary();
}
void hall(){
clear_screen();
cout << "[Mayor]: Hello, " << player.name << ", is there something you need?" << endl;
cout << "Would you like to use the bank (1), build new homes (2), or leave (3)?" << endl;
int choice=inputI("["+player.name+"]: ");
if (choice==1){
bank();
}else if(choice==2){
if (lower(inputS("Would you like to spend Vi to build new homes? "))=="yes"){
cout << "You have " << player.money << " Vi" << endl;
int percent=inputI("How much would you like to spend? ");
if (percent<=player.money){
player.money-=percent;
player.pop*=(1+percent/100);
cout << "Population increased by " << percent << "%!";
enter();
hall();
}else {
cout << "You don't have that much Vi!";
enter();
hall();
}
}
} else if (choice==3){
town();
}
cout << "Invalid choice!";
enter();
hall();
}
void bank(){
clear_screen();
cout << "You have " << player.money << " Vi in your pocket, and " << player.deposit << " Vi in the bank." << endl;
cout << endl;
cout << "[Banker]: Hello, sir. Would you like to make a deposit or withdrawl? Or would you like to leave?" << endl;
string choice=lower(inputS("["+player.name+"]: "));
if (choice=="leave"){
town();
}else if (choice=="deposit"){
cout << "[Banker] How much would you like to deposit?" << endl;
float amount=inputF(": ");
if (amount>player.money){
cout << "You don't have that kind of cash!!!" << endl;
enter();
bank();
}else{
player.money-=amount;
player.deposit+=amount;
player.clean();
cout << "[Banker]: Thanks for your business!" << endl;
enter();
bank();
}
} else if(choice=="withdraw"||choice=="withdrawl"){
float amount=inputF("How much would you like to withdraw? ");
if (amount>player.deposit){
cout << "You don't have that kind of money!!!" << endl;
enter();
bank();
}else{
player.money+=amount;
player.deposit-=amount;
player.clean();
cout << "[Banker]: Thanks for your business!" << endl;
enter();
bank();
}
}else if(choice=="leave"){
town();
}
}
void sheriff(){
clear_screen();
cout << "[Ray]: Ahm the sheriff 'round these parta. Watcha need?" << endl;
cout << "You can either give him your captured monsters (1)" << endl;
cout << "Or leave (2)" << endl;
cout << endl;
int choice=inputI("["+player.name+"]: ");
if (choice==1&&player.caught>0){
float amount=player.caught*2;
player.money+=amount;
player.caught=0;
cout << "[Ray]: Here yer go!" << endl;
cout << "Received " << amount << " Vi from Ray" << endl;
player.clean();
enter();
town();
}else if (choice==1&&player.caught==0){
cout << "[Ray]: Whadder yer want? Me to uh takun' nothin' but air?" << endl;
enter();
town();
} else {
town();
}
}
void outside(bool tokenfight){
clear_screen();
if (tokenfight){
cout << "Hello, " << player.name <<"." << endl;
scroll();
cout << "Unfortunatly, token fighting is broken. We hope to fix this in a coming release." << endl;
scroll();
cout << "I know this was distracting, but please do not try this until the broken message goes away..." << endl;
enter();
town();
}
monster m;
string choice;
float damage;
bool critical=false;
bool mon_critical=false;
bool auto_fight=false;
int mon_choice;
int selected;
bool found=false;
if(tokenfight){
m=load_token();
}else{
m.health=random_float(player.max_health*0.5,player.max_health*2);
m.power=random_float(player.max_power*0.7,player.max_power*1.5);
m.defence=random_float(player.defence*0.5,player.defence*1.8);
if(rand()%10==0){
m.name=player.name;
m.power=player.max_power;
m.health=player.max_health;
m.defence=player.defence;
cout << "You spotted the Dark Wizard up ahead!" << endl;
enter();
cout << "The Dark Wizard used Mirror Bluff!" << endl;
enter();
cout << "What has he done?!?" << endl;
enter();
}else if (rand()%15==0 && player.level>=5){
m.name="Dark Wizard";
m.power=player.power*1.5;
m.health=player.health*3;
m.defence=player.defence*1.5;
cout << "[???]: Thought you could hide from me?" << endl;
enter();
cout << "[Dark Wizard]: NO ONE HIDES FROM THE DARK WIZARD!" << endl;
enter();
cout << "[Dark Wizard]: NOW DIE! AND ALL HOPE WITH YOU!" << endl;
enter();
cout << "The Dark Wizard used Hypernova!!!" << endl;
enter();
cout << "It caused " << player.max_health-1 << " damage!\nYou have 1 hp left!!!" << endl;
enter();
cout << "The Dark Wizard used Soul Void!\nYou're power level is now 1!" << endl;
enter();
player.health=1;
player.power=0;
if(rand()%2==0){
clear_screen();
cout << "[???]: NO!" << endl;
enter();
cout << "[???]: It will not end this way... listen to me, my " <<player.sondaughter <<"..." << endl;
enter();
cout << "[Father]: Be strong! You CAN defeat him!!!" << endl;
enter();
cout << "The Great Wizard used Giga Heal! You're back to full health!" << endl;
enter();
cout << "[Father]: Now fight! Fight and save us all..." << endl;
enter();
cout << "[Dark Wizard]: Yes... fight! Let's see who is truly all-powerful..." << endl;
enter();
player.reset_health();
player.reset_power();
}else{
cout << "[Dark Wizard]: NOW DIE FOOL!" << endl;
enter();
cout << "The Dark Wizard used Galactic Implosion" << endl;
enter();
cout << "It caused " << player.max_health*1007 << " damage!!!" << endl;
enter();
cout << "You have been wiped from the face of the universe..." << endl;
enter();
cout << "However..." << endl;
enter();
player.reset_power();
player.health=0;
hospital();
}
} else {
m.set_name();
m.set_status();
}
if (m.name==player.name){
m.set_intelligence("player");
}else{
m.set_intelligence("random");
}
m=init_evil_spell(m,player);
m.set_money();
}
m.money+=random_float(m.money-(m.money*2/5),m.money*2/5);
m.clean();
clear_screen();
if(!tokenfight){
cout << "A " << m.name << " jumps out at you!" << endl;
}else{
cout << "You have challenged " << m.name << "!" << endl;
}
enter();
while(m.health>0 && player.health>0){
clear_screen();
cout << "You have " << player.health << "/" << player.max_health << " health" << endl;
cout << "You have " << player.power << "/" << player.max_power << " power" << endl;
cout << endl;
if(!tokenfight){
cout << "The " << m.name << " has " << m.health << " health" << endl << endl;
//cout << "The " << m.name << " has " << m.power << " power" << endl << endl;
}else{
cout << m.name << " has " << m.health << " health" << endl << endl;
}
cout << "How do you want to attack?" << endl;
for(int j=0;j<player.spell_list.size();j++){
if(player.spell_list[j].unlocked){
cout << "Use " << player.spell_list[j].name << "?" << endl;
}
}
cout << "Or try to escape?"<< endl;
choice=inputS(": ");
for(int j=0;j<player.spell_list.size();j++){
if (lower(choice)==lower(player.spell_list[j].name) && player.spell_list[j].unlocked){
found=true;
selected=j;
}
}
if(lower(choice)=="escape"){
if (rand()%(10-(10/(int)(m.power+.5))+2)==0){
clear_screen();
cout << "Escape successful!" << endl;
player.reset_power();
enter();
town();
}else{
cout << "You were followed!" << endl;
found=false;
enter();
}
}else if(found){
if(player.spell_list[selected].power_requirement>player.max_power){
cout << "You aren't skilled enough to use that!" << endl;
found=false;
enter();
}else if (player.spell_list[selected].power_requirement>player.power){
cout << "You're too tired to use that!" << endl;
found=false;
enter();
}else{
found=false;
cout << "You used " << player.spell_list[selected].name << "!" << endl;
damage=player.spell_list[selected].power_requirement+player.power+player.get_multiplier(player.spell_list[selected].type)-m.defence;
damage=floorf(damage*10+.5)/10;
if (damage<1){damage=1;}
player.power-=player.spell_list[selected].power_requirement;
if(rand()%10==0){
damage*=rand()%3+2;
cout << "Critical hit!" << endl;
}
cout << "You caused " << damage << " damage!" << endl;
enter();
cout << endl;
player.gain(player.spell_list[selected].type,player.spell_list[selected].power_requirement);
player.total_attacks++;
m.health-=damage;
if (m.health<=0){
break;
}
}
}else if (!found){
cout << "You tripped!" << endl;
}
while(true){
cout << m.attacks.size() << endl;
mon_choice=rand()%m.attacks.size();
if (m.attacks[mon_choice].power_requirement>0){ //higher chance to use something that requires no power than
if (rand() % 3 == 0){ //a power move. Gotta conserve energy!
if (m.attacks[mon_choice].power_requirement<=m.power){
break;
}
}
} else if (m.attacks[mon_choice].power_requirement==0) {
break;
}
}
/*
damage=m.power-player.defence;
damage=floorf(damage*10+.5)/10;
if (damage<1){damage=1;}
m.power/=1.1;
*/
damage=m.attacks[mon_choice].power_requirement+m.power-player.defence;
damage=floorf(damage*10+.5)/10;
m.power-=m.attacks[mon_choice].power_requirement;
if(damage<1){damage=1;}
if(rand()%10==0){
mon_critical=true;
damage*=rand()%3+2;
}
cout << endl;
if(mon_critical){
cout << "Critical Hit!!!" << endl;
mon_critical=false;
}
if(!tokenfight){
cout << "The " << m.name << " used " << m.attacks[mon_choice].name << " for " << damage << " damage!" << endl;
}else{
cout << m.name << " used " << m.attacks[mon_choice].name << " for " << damage << " damage!" << endl;
}
if (!auto_fight){enter();}
player.health-=damage;
}
player.reset_power();
player.deposit*=1.1; //10% interest
if(player.health<=0){
hospital();
}else{
clear_screen();
if(!tokenfight){
cout << "You beat the " << m.name << "!" << endl;
}else{
cout << "You beat " << m.name << "!" << endl;
}
cout << "You found " << m.money << " Vi on it!" << endl;
player.money+=m.money;
if(!tokenfight){
cout << "You found one " << m.name << " body! The sheriff might buy it..." << endl;
}else{
cout << "You found " << m.name << "'s body! The sheriff might buy it..." << endl;
}
player.caught++;
player.killed++;
player.total_money+=m.money;
enter();
town();
}
}
void hospital(){
clear_screen();
player.deaths++;
bool said_no=false;
cout << "[Nurse]: Oh my. You seem to have died. Don't worry! We brought you back with SCIENCE!" << endl;
cout << "[Nurse]: ... And a lot of tylenol..." << endl;
cout << "[Nurse]: Anyway, to heal you 100% will cost " << player.money/10+2 << " Vi" << endl;
if (player.money>=player.money/10+2){
cout << "[Nurse]: Would you like to pay for that? " << endl;
if (lower(inputS(": "))=="yes"){
player.money-=player.money/10+2;
player.reset_health();
cout << "[Nurse]: Thank you!" << endl;
} else {
said_no=true;
}
} else {
said_no=true;
}
if (said_no){
cout << "[Nurse]: Oh. Dang, I really wanted that cash." << endl;
cout << "[Nurse]: We can charge you in demonic-... I mean other ways though." << endl;
if (lower(inputS("Interested? \n: "))=="yes"){
player.levels--;
player.reset_health();
} else {
player.health=player.max_health/2;
player.clean();
}
}
enter();
clear_screen();
cout << "[Nurse]: We hope to see you again. Very soon. Hehehehe..." << endl;
enter();
town();
}
void school(){
clear_screen();
cout << "[Headmaster]: Hello pupil, we have many fine spells available. Take your pick!" << endl;
cout << "[Headmaster]: Would you like to see:" << endl;
cout << "Fire Spells (1)\nWater Spells (2)\nEarth Spells (3)\nAir Spells (4)\nForce Spells (5)\nOr just leave (6)?" << endl;
int choice;
choice=inputI(": ");
if(choice==6){
cout << "[Headmaster]: Goodbye!" << endl;
enter();
town();
}
if(choice>5||choice<1){
cout << "What is that?" << endl;
enter();
school();
}
clear_screen();
for(int j=0;j<player.spell_list.size();j++){
if(player.spell_list[j].type==choice && !player.spell_list[j].unlocked && player.spell_list[j].power_requirement
<=player.max_power){
if(player.spell_list[j].ultimate){
cout << "***" << player.spell_list[j].name << "*** :\n" << player.spell_list[j].description << "\n\n";
}else{
cout << player.spell_list[j].name << ":\n" << player.spell_list[j].description << "\n\n";
}
cout << "Power Per Use: " << player.spell_list[j].power_requirement << endl;
cout << "Damage With 100 Power at Level 10: "<<player.spell_list[j].power_requirement+100*1.9 << endl;
cout << "Price: " << player.spell_list[j].cost << " Vi\n\n";
cout << "===========================================================================\n\n";
}
}
cout << "\n\n[Headmaster]: Please enter the name of what you would like to buy (none for none)"<< endl;
cout << "You have " << player.max_power << " power and " << player.money << " Vi." << endl;
string s;
s=inputS(": ");
if (lower(s)=="none"){school();}
for(int j=0;j<player.spell_list.size();j++){
if(lower(player.spell_list[j].name)==lower(s)){
clear_screen();
cout << "Are you sure you would like " << player.spell_list[j].name << "?";
s=inputS(": ");
if(lower(s)=="yes" && player.money >= player.spell_list[j].cost){
player.spell_list[j].unlocked=true;
player.money-=player.spell_list[j].cost;
clear_screen();
cout << "You've learned " << player.spell_list[j].name << "!" << endl;
enter();
school();
} else if(lower(s)=="yes" && player.money < player.spell_list[j].cost){
clear_screen();
cout << "[Headmaster]: What are you doing??? You don't have enough money!!!" << endl;
enter();
town();
}else{
school();
}
}
}
cout << "[Headmaster]: I have no idea what you just said..." << endl;
enter();
school();
}
void gym(){
clear_screen();
cout << "[Trainer]: 'Sup. Here to learn some new moves?" << endl;
cout << "[Trainer]: Interested in staying like a man (1) or leaving like a baby (2)?" << endl;
cout << "" << endl;
int choice;
choice=inputI(": ");
if(choice==2){
cout << "[Trainer]: HA! Wimp..." << endl;
enter();
town();
}
if(choice>2||choice<1){
cout << "[Trainer]: What the heck?" << endl;
enter();
gym();
}
clear_screen();
for(int j=0;j<player.spell_list.size();j++){
if(player.spell_list[j].type==100 && !player.spell_list[j].unlocked && player.spell_list[j].power_requirement
<=player.max_power){
if(player.spell_list[j].ultimate){
cout << "***" << player.spell_list[j].name << "*** :\n" << player.spell_list[j].description << "\n\n";
}else{
cout << player.spell_list[j].name << ":\n" << player.spell_list[j].description << "\n\n";
}
cout << "Power Per Use: " << player.spell_list[j].power_requirement << endl;
cout << "Damage With 100 Power at level 10: "<<player.spell_list[j].power_requirement+100*1.9 << endl;
cout << "Price: " << player.spell_list[j].cost << " Vi\n\n";
cout << "===========================================================================\n\n";
}
}
cout << "\n\n[Trainer]: Just tell me which you want bro (none for none)"<< endl;
cout << "You have " << player.max_power << " power and " << player.money << " Vi." << endl;
string s;
s=inputS(": ");
if (lower(s)=="none"){gym();}
for(int j=0;j<player.spell_list.size();j++){
if(lower(player.spell_list[j].name)==lower(s)){
clear_screen();
cout << "[Trainer]: You really want to learn " << player.spell_list[j].name << "?" << endl;
s=inputS(": ");
if(lower(s)=="yes" && player.money >= player.spell_list[j].cost){
player.spell_list[j].unlocked=true;
player.money-=player.spell_list[j].cost;
clear_screen();
cout << "You've learned " << player.spell_list[j].name << "!" << endl;
if(!story.first_power){story.first_power=true;}
enter();
gym();
} else if(lower(s)=="yes" && player.money < player.spell_list[j].cost){
clear_screen();
cout << "[Trainer]: What's wrong wit you??? I don't train poor hobos like you! Get outta here!" << endl;
enter();
town();
}else{
gym();
}
}
}
cout << "[Trainer]: What the..." << endl;
enter();
gym();
}
void master(){
clear_screen();
cout << "[Master]: Welcome. Are you here to discover the art of swordfighting?" << endl;
cout << "[Master]: Yes or no?" << endl;
cout << "" << endl;
string choice;
choice=inputS(": ");
if(lower(choice)=="no"){
cout << "[Master]: Goodbye." << endl;
enter();
town();
}
clear_screen();
for(int j=0;j<player.spell_list.size();j++){
if(player.spell_list[j].type==101 && !player.spell_list[j].unlocked && player.spell_list[j].power_requirement
<=player.max_power){
if(player.spell_list[j].ultimate){
cout << "***" << player.spell_list[j].name << "*** :\n" << player.spell_list[j].description << "\n\n";
}else{
cout << player.spell_list[j].name << ":\n" << player.spell_list[j].description << "\n\n";
}
cout << "Power Per Use: " << player.spell_list[j].power_requirement << endl;
cout << "Damage With 100 Power at level 10: "<<player.spell_list[j].power_requirement+100*1.9 << endl;
cout << "Price: " << player.spell_list[j].cost << " Vi\n\n";
cout << "===========================================================================\n\n";
}
}
cout << "\n\n[Master]: What shall it be? (none for none)"<< endl;
cout << "You have " << player.max_power << " power and " << player.money << " Vi." << endl;
string s;
s=inputS(": ");
if (lower(s)=="none"){master();}
for(int j=0;j<player.spell_list.size();j++){
if(lower(player.spell_list[j].name)==lower(s)){
clear_screen();
cout << "[Master]: Are you really interested in " << player.spell_list[j].name << "?" << endl;
s=inputS(": ");
if(lower(s)=="yes" && player.money >= player.spell_list[j].cost){
player.spell_list[j].unlocked=true;
player.money-=player.spell_list[j].cost;
clear_screen();
cout << "You've learned " << player.spell_list[j].name << "!" << endl;
enter();
master();
} else if(lower(s)=="yes" && player.money < player.spell_list[j].cost){
clear_screen();
cout << "[Master]: You seem to have no Vi. Get out... NOW. I'd hate to cut you in half..." << endl;
enter();
town();
}else{
master();
}
}
}
cout << "[Master]: What..." << endl;
enter();
master();
}
void doctor() {
clear_screen();
int choice;
float amount;
//string s;
float cost;
cout << "[Doctor]: Hello, patient. What can I do for you?" << endl;
cout << "[Doctor]: I am capable of fully healing you (1)" <<
"\nLetting you decide how much to heal (2)" <<
"\nOr showing you to the door (3)" << endl;
choice=inputI(": ");
if (choice==1 && player.health < player.max_health){
clear_screen();
cost=(player.max_health-player.health)/15;
cost=floorf(cost*10+.5)/10;
if(player.money >= cost){
cout << "[Doctor]: That will be " << cost << " Vi. Are you sure?" << endl;
if (lower(inputS(": "))=="yes"){
player.reset_health();
player.money-=cost;
}else {
doctor();
}
}
} else if (choice==2){
clear_screen();
cout << "[Doctor]: Exactly how much would you like me to heal?" << endl;
cout << "[Doctor]: You seems to have " << player.health << "/" << player.max_health << " health." << endl;
amount=inputF(": ");
if (amount > player.max_health-player.health){
amount=player.max_health-player.health;
}
cost=amount/10;
cost=floorf(cost*10+.5)/10;
if (cost>player.money){
cout << "[Doctor]: Your insurance won't cover that!!!" << endl;
enter();
doctor();
}
cout << "That will be " << cost << " Vi. Are you sure?" << endl;
if(lower(inputS(": "))=="yes"){
player.health+=amount;
player.money-=cost;
player.check();
player.clean();
} else {
doctor();
}
} else if (choice==3){
town();
} else {
doctor();
}
}
int main()
{
player=init(player);
player=init_spells(player);
init_story();
//cout << player.earth_need;
splash();
clear_screen();
make("data");
install();
if(exists("data/save.dat")){
if(lower(inputS("Do you want to load a game or start a new one: "))=="new"){
newCharacter();
}else{
player=load(player);
town();
}
}else{
newCharacter();
}
return 0;
}
| [
"farscience@hotmail.com"
] | farscience@hotmail.com |
104a44fea65b2f3bb29b21548bd3dcf30f34678a | b2bb9fe58e38b74177d812d45a7181982e16ad1c | /GTAV_Native_Invoker/prx.cpp | 94007422413ab8c307fcbbe3595febabcd9e9d7f | [] | no_license | fengjixuchui/GTAV_Native_Invoker | 5cf933b4d53b22087171e55fdb2a4e1700201c65 | 48fcc257585a7e696f9f5b3b33ba759193efee9b | refs/heads/master | 2020-09-20T11:27:37.853153 | 2016-01-20T05:13:24 | 2016-01-20T05:13:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 814 | cpp | #include <cellstatus.h>
#include <sys/prx.h>
#include <sys/ppu_thread.h>
#include <string.h>
#include <sys/memory.h>
#include <sys/timer.h>
#include <sys/process.h>
#include <ppu_intrinsics.h>
#include <stdarg.h>
#include <stdio.h>
#include <cstdlib>
#include "Natives.h"
SYS_MODULE_INFO("GTAV_Native_Invoker", 0, 1, 1);
SYS_MODULE_START(PRX_ENTRY);
void HookNative(int native, int dest) {
int FuncBytes[1];
FuncBytes[0] = *(int*)dest;
memcpy((void*)native, FuncBytes, 4);
}
int is_player_online() {
if (*(char*)(0x22322A0) == 0)
return 0;
else return 1337;
}
int Hook()
{
//Call Natives Here
//EX: Player player = PLAYER::PLAYER_ID();
//EX: Ped ped = PLAYER::PLAYER_PED_ID();
return is_player_online();
}
extern "C" int PRX_ENTRY()
{
HookNative(0x01C1BB60, (int)Hook);
return SYS_PRX_RESIDENT;
}
| [
"xdex1337@hotmail.com"
] | xdex1337@hotmail.com |
b238fa6aa926f12dcee0146d3be9d97a2dc6b6c8 | d5bd083dbcacce8cf62ebbd73c77c14c8247e057 | /external/skia/tests/BitmapTest.cpp | f3d8faa967c7ae99c311e63cf4e3d5f73cc260de | [
"BSD-3-Clause",
"SGI-B-2.0"
] | permissive | RetronixTechInc/android-retronix | ab0e10840dab5dc7b0879737953ebf2e1916f2b0 | cd7d794dea51c3b287da0d35ddb18c1bdef00372 | refs/heads/RTX_NXP_Android601 | 2021-11-16T03:58:58.169998 | 2021-11-15T01:51:02 | 2021-11-15T01:51:02 | 198,991,737 | 4 | 5 | null | 2020-03-08T23:21:29 | 2019-07-26T09:49:01 | Java | UTF-8 | C++ | false | false | 3,350 | cpp | /*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmap.h"
#include "SkMallocPixelRef.h"
#include "Test.h"
// https://code.google.com/p/chromium/issues/detail?id=446164
static void test_bigalloc(skiatest::Reporter* reporter) {
const int width = 0x40000001;
const int height = 0x00000096;
const SkImageInfo info = SkImageInfo::MakeN32Premul(width, height);
SkBitmap bm;
REPORTER_ASSERT(reporter, !bm.tryAllocPixels(info));
SkPixelRef* pr = SkMallocPixelRef::NewAllocate(info, info.minRowBytes(), NULL);
REPORTER_ASSERT(reporter, !pr);
}
static void test_allocpixels(skiatest::Reporter* reporter) {
const int width = 10;
const int height = 10;
const SkImageInfo info = SkImageInfo::MakeN32Premul(width, height);
const size_t explicitRowBytes = info.minRowBytes() + 24;
SkBitmap bm;
bm.setInfo(info);
REPORTER_ASSERT(reporter, info.minRowBytes() == bm.rowBytes());
bm.allocPixels();
REPORTER_ASSERT(reporter, info.minRowBytes() == bm.rowBytes());
bm.reset();
bm.allocPixels(info);
REPORTER_ASSERT(reporter, info.minRowBytes() == bm.rowBytes());
bm.setInfo(info, explicitRowBytes);
REPORTER_ASSERT(reporter, explicitRowBytes == bm.rowBytes());
bm.allocPixels();
REPORTER_ASSERT(reporter, explicitRowBytes == bm.rowBytes());
bm.reset();
bm.allocPixels(info, explicitRowBytes);
REPORTER_ASSERT(reporter, explicitRowBytes == bm.rowBytes());
bm.reset();
bm.setInfo(info, 0);
REPORTER_ASSERT(reporter, info.minRowBytes() == bm.rowBytes());
bm.reset();
bm.allocPixels(info, 0);
REPORTER_ASSERT(reporter, info.minRowBytes() == bm.rowBytes());
bm.reset();
bool success = bm.setInfo(info, info.minRowBytes() - 1); // invalid for 32bit
REPORTER_ASSERT(reporter, !success);
REPORTER_ASSERT(reporter, bm.isNull());
}
static void test_bigwidth(skiatest::Reporter* reporter) {
SkBitmap bm;
int width = 1 << 29; // *4 will be the high-bit of 32bit int
SkImageInfo info = SkImageInfo::MakeA8(width, 1);
REPORTER_ASSERT(reporter, bm.setInfo(info));
REPORTER_ASSERT(reporter, bm.setInfo(info.makeColorType(kRGB_565_SkColorType)));
// for a 4-byte config, this width will compute a rowbytes of 0x80000000,
// which does not fit in a int32_t. setConfig should detect this, and fail.
// TODO: perhaps skia can relax this, and only require that rowBytes fit
// in a uint32_t (or larger), but for now this is the constraint.
REPORTER_ASSERT(reporter, !bm.setInfo(info.makeColorType(kN32_SkColorType)));
}
/**
* This test contains basic sanity checks concerning bitmaps.
*/
DEF_TEST(Bitmap, reporter) {
// Zero-sized bitmaps are allowed
for (int width = 0; width < 2; ++width) {
for (int height = 0; height < 2; ++height) {
SkBitmap bm;
bool setConf = bm.setInfo(SkImageInfo::MakeN32Premul(width, height));
REPORTER_ASSERT(reporter, setConf);
if (setConf) {
bm.allocPixels();
}
REPORTER_ASSERT(reporter, SkToBool(width & height) != bm.empty());
}
}
test_bigwidth(reporter);
test_allocpixels(reporter);
test_bigalloc(reporter);
}
| [
"townwang@retronix.com.tw"
] | townwang@retronix.com.tw |
55529dcd6c825136aaef3d8f4b099720b5ce7315 | d15c3f6a4be84d289731b0baa27c409ce6319eab | /Algorithm/HashTable/gena.cpp | 087d97788cb4bdf34050d787e6d0b9c3b703194d | [] | no_license | Vlad-dos/Algorithm | 94ad207cb9707c342d24833619c3490aa3f65945 | 94ecc321592d6b48d3eb844b48b2a650abbb5b93 | refs/heads/master | 2021-01-21T04:40:16.291024 | 2016-06-18T19:29:29 | 2016-06-18T19:29:29 | 54,508,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,127 | cpp | #include "task_selection.h"
#include "checker.h"
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cmath>
#include <fstream>
#include <queue>
#include <stack>
#include <cassert>
#include <complex>
#include <bitset>
#include <deque>
#include <unordered_set>
#include <unordered_map>
#include <list>
#include <forward_list>
#include <numeric>
#include <functional>
#include <initializer_list>
using namespace std;
namespace gena {
#if defined(_DEBUG)
#define debug printf
#define reader scanf
#define error(...) fprintf(stderr,__VA_ARGS__)
void wait() {
fclose(stdin);
fclose(stdout);
freopen("CON", "r", stdin);
freopen("CON", "w", stdout);
system("pause");
}
#else
#define debug ;
#define reader ;
#define error ;
void wait() {}
#endif
typedef long long ll;
typedef long double ld;
#define mp make_pair
#define write(a, c) for (auto i : a) cout << i << c;
#define all(a) (a).begin(), (a).end()
const int K = 18;
const ll MAXN = 2e3 + 10;
const int INF = 2e9 + 1;
const ll LONG_INF = 8e18;
const ll MOD = 1e9 + 7;
const ld e = 1e-9;
const ll C = 500;
const ll dx[4] = { -1, 0, 1, 0 };
const ll dy[4] = { 0, 1, 0, -1 };
int main();
}
using namespace gena;
set<string> used;
string rands() {
if (rand() % 5 == 0 && used.size()) {
int pos = rand() % used.size();
auto a = used.begin();
for (int i = 0; i < pos; i++) {
a++;
}
return *a;
}
int len = rand() % 20 + 1;
string s;
for (int i = 0; i < len; i++) {
s += ('a' + rand() % 20);
}
used.insert(s);
return s;
}
int gena::main() {
for (int i = 0; i < 100; i++) {
int type = rand() % 30;
if (type < 10) {
cout << "put ";
}
else if (type < 25) {
cout << "get ";
} else {
cout << "delete ";
}
if (type < 10) {
cout << rands() << ' ';
}
cout << rands() << endl;
}
return 0;
}
#if defined(gena) && !defined(checker)
int main() {
freopen("input.txt", "w", stdout);
gena::main();
gena::wait();
return 0;
}
#endif | [
"vlad082006@yandex.ru"
] | vlad082006@yandex.ru |
8b5b117d0e4f43f06aa0fbe2d948871af0c95f55 | 66deb611781cae17567efc4fd3717426d7df5e85 | /pcmanager/src/src_bksafe/beikesafe/beikesafevirscanlogdlg.h | 0c408d2b416b4b3d85fb34aa51f8eca9d07e29bd | [
"Apache-2.0"
] | permissive | heguoxing98/knoss-pcmanager | 4671548e14b8b080f2d3a9f678327b06bf9660c9 | 283ca2e3b671caa85590b0f80da2440a3fab7205 | refs/heads/master | 2023-03-19T02:11:01.833194 | 2020-01-03T01:45:24 | 2020-01-03T01:45:24 | 504,422,245 | 1 | 0 | null | 2022-06-17T06:40:03 | 2022-06-17T06:40:02 | null | GB18030 | C++ | false | false | 27,442 | h | #pragma once
#include <wtlhelper/whwindow.h>
#include "kws/ctrls/loglistctrl.h"
#include <comproxy/bkscanfile.h>
#include <winmod/winpath.h>
#include <common/whitelist.h>
#include <comproxy/bkutility.h>
#include <atlcore.h>
#include <atluser.h>
#include "virusscan/kaquaraloader.h"
#define MSG_LOAD_LOG_FINISH (WM_APP + 1)
#define MSG_CLEAR_LOG_FINISH (WM_APP + 2)
#define WM_MSG_LOG_RECOVER (WM_USER+ 678)
class CBeikeSafeVirScanLogDlg
: public CBkDialogImpl<CBeikeSafeVirScanLogDlg>
, public CWHRoundRectFrameHelper<CBeikeSafeVirScanLogDlg>
{
public:
CBeikeSafeVirScanLogDlg()
: CBkDialogImpl<CBeikeSafeVirScanLogDlg>(IDR_BK_VIRSCAN_LOG_DLG)
, m_bShowFileTab(FALSE)
, m_bDoing(FALSE)
, m_hLoadLog(NULL)
{
}
S_REMOVE_HISTORY_RECORD_OPTION m_kwsRemove;
std::vector<std::wstring> m_vecRemove;
void SetShowFileTab( BOOL bFileTab )
{
m_bShowFileTab = bFileTab;
}
protected:
CAtlArray< KWS_SCAN_LOG > m_arrLogs;
CAtlArray< KWS_SCAN_LOG > m_arrFileLogs;
CLogListCtrl m_wndListLog;
CLogListCtrl m_wndFileLog;
BOOL m_bShowFileTab;
BOOL m_bDoing;
KaquaraLoader m_quaLoader;
HANDLE m_hLoadLog;
KLogic m_logic;
void OnBkBtnClose()
{
if( !m_bDoing )
EndDialog(IDCANCEL);
}
BOOL OnBkTabCtrlChange( int nTabItemIDOld, int nTabItemIDNew )
{
SetItemVisible( IDC_LST_VIRSCAN_LOG, nTabItemIDNew == 0 );
SetItemVisible( IDC_ALL_LOG_TEXT, nTabItemIDNew == 0 );
SetItemVisible( IDC_FILE_LOG_TEXT, nTabItemIDNew == 1 );
SetItemVisible( IDC_FILE_VIRUS_LOG_LIST, nTabItemIDNew == 1 );
UpdateBtnAndCheck( );
return TRUE;
}
void UpdateBtnAndCheck( )
{
if( m_wndListLog.IsWindowVisible() )
{
EnableItem( IDC_BTN_VIRSCAN_CLEAR_LOG, m_wndListLog.IsAnyItemChecked() );
SetItemCheck( IDC_VIRUS_LOG_CHECK_ALL, m_wndListLog.IsAllItemChecked() );
}
else if ( m_wndFileLog.IsWindowVisible() )
{
EnableItem( IDC_BTN_VIRSCAN_CLEAR_LOG, m_wndFileLog.IsAnyItemChecked() );
SetItemCheck( IDC_VIRUS_LOG_CHECK_ALL, m_wndFileLog.IsAllItemChecked() );
}
}
void OnBtnVirScanClearLog()
{
CBkSafeMsgBox2 dlg;
dlg.AddButton(TEXT("删除记录"), IDOK);
dlg.AddButton(TEXT("取消"), IDCANCEL);
UINT nID = dlg.ShowMutlLineMsg( L"删除记录后将无法再执行还原操作,\r\n\r\n您是否确定删除选中的查杀历史记录?",
_T("提示"), MB_BK_CUSTOM_BUTTON|MB_ICONINFORMATION, NULL, GetViewHWND() );
if( nID == IDOK )
{
::SetCursor(::LoadCursor(NULL, IDC_WAIT));
MakeRemoveList( );
_EnableButtons(FALSE);
m_hLoadLog = ::CreateThread(NULL, 0, _ClearLogThreadProc, this, 0, NULL);
}
}
void MakeRemoveList( )
{
CLogListCtrl* pList = NULL;
CAtlArray< KWS_SCAN_LOG >* pLog = NULL;
m_vecRemove.clear();
if( m_wndListLog.IsWindowVisible() )
{
pList = &m_wndListLog;
pLog = &m_arrLogs;
}
else
{
pList = &m_wndFileLog;
pLog = &m_arrFileLogs;
}
m_kwsRemove.bClearAll = FALSE;
for ( int i = pLog->GetCount() - 1; i >= 0; i-- )
{
KWS_SCAN_LOG& log = (*pLog)[i];
if( pList->GetCheckState( i ) )
{
if( log.bKwsLog )
{
S_HISTORY_RECORD_ITEM item;
item.dwItemID = (*pLog)[i].dwID;
item.tmTime = (*pLog)[i].tmHistoryTime;
m_kwsRemove.vecRecords.push_back( item );
}
else
{
std::wstring strFile( log.szQuaraName );
m_vecRemove.push_back( strFile );
}
RemoveOtherListView( log );
pLog->RemoveAt( i );
pList->DeleteItem( i );
}
}
}
void RemoveOtherListView( KWS_SCAN_LOG& log )
{
CLogListCtrl* pOtherList = NULL;
CAtlArray< KWS_SCAN_LOG >* pOtherLog = NULL;
if( !m_wndListLog.IsWindowVisible() )
{
pOtherList = &m_wndListLog;
pOtherLog = &m_arrLogs;
}
else
{
pOtherList = &m_wndFileLog;
pOtherLog = &m_arrFileLogs;
}
for ( int i = pOtherLog->GetCount() - 1; i >= 0; i-- )
{
if( log.bKwsLog )
{
if( log.tmHistoryTime == (*pOtherLog)[i].tmHistoryTime &&
log.dwID == (*pOtherLog)[i].dwID )
{
pOtherList->DeleteItem( i );
pOtherLog->RemoveAt( i );
break;
}
}
else
{
UINT uId = (*pOtherLog)[i].dwID;
if( log.dwID == uId )
{
pOtherList->DeleteItem( i );
pOtherLog->RemoveAt( i );
break;
}
}
}
}
void QuaraToLog( QUAR_FILE_INFO& bklog, KWS_SCAN_LOG& log )
{
log.emType = enum_BK_TROJAN_Point;
log.ActionType = enum_PROCESS_TYPE_CLEAN;
log.state = enum_HISTORY_ITEM_STATE_FIXED;
log.emLevel = enum_POINT_LEVEL_TROJAN;
CTime time( bklog.stSTime);
log.tmHistoryTime = time.GetTime();
log.Advice = enum_PROCESS_TYPE_FIX;
log.bKwsLog = FALSE;
log.dwID = bklog.uIndex;
log.uSize = sizeof( KWS_SCAN_LOG );
_tcsncpy_s( log.szItemName, MAX_PATH*2, bklog.szSurFileName, _TRUNCATE);
_tcsncpy_s( log.szVirusName, MAX_PATH*2, bklog.szVirusName, _TRUNCATE);
_tcsncpy_s( log.szQuaraName, MAX_PATH*2, bklog.szQuarFileName, _TRUNCATE);
}
void KwsLogToLog( S_HISTORY_ITEM_EX& item )
{
for( int i = 0; i < item.FixedList.size(); i++ )
{
S_HISTORY_ITEM_INFO& info = item.FixedList[i];
KWS_SCAN_LOG log;
memset( &log, 0, sizeof(KWS_SCAN_LOG) );
log.emType = info.emType;
log.emLevel = info.emLevel;
log.ActionType = info.ActionType;
log.state = info.state;
log.tmHistoryTime = item.tmHistoryTime;
log.Advice = info.Advice;
log.bKwsLog = TRUE;
log.dwID = info.dwID;
log.uSize = sizeof( KWS_SCAN_LOG );
//加入全部历史
if( info.emLevel == enum_POINT_LEVEL_REG_REMAIN )
{
if( info.strItemName.size() == 0 )
_tcsncpy_s( log.szItemName, MAX_PATH*2, TEXT("[(Default)]"), _TRUNCATE);
else
_tcsncpy_s( log.szItemName, MAX_PATH*2, info.strItemName.c_str(), _TRUNCATE);
}
else
_tcsncpy_s( log.szItemName, MAX_PATH*2, info.strItemName.c_str(), _TRUNCATE);
if( info.vecProcessItems.size() > 0 && m_logic.IsRealVirus( info.emType, info.emLevel ) )
{
for ( int j = 0; j < info.vecProcessItems.size(); j++ )
{
S_PROCESS_OBJECT_INFO& objInfo = info.vecProcessItems[j];
if( (objInfo.processType == enum_PROCESS_AT_BOOT_DELETE_FILE ||
objInfo.processType == enum_PROCESS_AT_BOOT_CLEAN_INFECTED_FILE ) )
{
_tcsncpy_s( log.szVirusName, MAX_PATH*2, objInfo.strVirusName.c_str(), _TRUNCATE);
_tcsncpy_s( log.szItemName, MAX_PATH*2, objInfo.strInfo_1.c_str(), _TRUNCATE);
break;
}
}
}
SortAfterAdd( m_arrLogs, log );
//加入文件隔离
for ( int j = 0; j < info.vecProcessItems.size(); j++ )
{
S_PROCESS_OBJECT_INFO& objInfo = info.vecProcessItems[j];
if( (objInfo.processType == enum_PROCESS_AT_BOOT_DELETE_FILE ||
objInfo.processType == enum_PROCESS_AT_BOOT_CLEAN_INFECTED_FILE )
&& info.emLevel != enum_POINT_LEVEL_REG_REMAIN )
{
wmemset( log.szItemName, 0, MAX_PATH*2 );
wmemset( log.szVirusName, 0, MAX_PATH*2 );
_tcsncpy_s( log.szItemName, MAX_PATH*2, objInfo.strInfo_1.c_str(), _TRUNCATE);
if( objInfo.strVirusName.size() > 0 )
_tcsncpy_s( log.szVirusName, MAX_PATH*2, objInfo.strVirusName.c_str(), _TRUNCATE);
else
_tcsncpy_s( log.szVirusName, MAX_PATH*2, TEXT("可疑文件"), _TRUNCATE);
SortAfterAdd( m_arrFileLogs, log );
}
}
}
}
BOOL OnInitDialog(CWindow /*wndFocus*/, LPARAM /*lInitParam*/)
{
m_wndListLog.SetRowHeight(28);
m_wndListLog.Create(
GetViewHWND(), NULL, NULL,
WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_OWNERDATA |LVS_OWNERDRAWFIXED | LVS_SHOWSELALWAYS | LVS_SINGLESEL,
0, IDC_LST_VIRSCAN_LOG);
m_wndListLog.SetLinkIndex( 5 );
m_wndListLog.HeaderSubclassWindow();
m_wndListLog.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER ,
LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER );
m_wndListLog.ShowCheckBox( TRUE );
m_wndListLog.InsertColumn(0, L"时间", LVCFMT_CENTER, 150);
m_wndListLog.InsertColumn(1, L"异常项", LVCFMT_LEFT, 225);
m_wndListLog.InsertColumn(2, L"类型", LVCFMT_LEFT, 115);
m_wndListLog.InsertColumn(3, L"级别", LVCFMT_LEFT, 55);
m_wndListLog.InsertColumn(4, L"处理方式", LVCFMT_CENTER, 60);
m_wndListLog.InsertColumn(5, L"操作", LVCFMT_LEFT, 55);
m_wndFileLog.SetRowHeight(28);
m_wndFileLog.Create(
GetViewHWND(), NULL, NULL,
WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_OWNERDATA |LVS_OWNERDRAWFIXED | LVS_SHOWSELALWAYS | LVS_SINGLESEL,
0, IDC_FILE_VIRUS_LOG_LIST);
m_wndFileLog.HeaderSubclassWindow();
m_wndFileLog.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER ,
LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER );
m_wndFileLog.ShowCheckBox( TRUE );
m_wndFileLog.SetLinkIndex( 4 );
m_wndFileLog.InsertColumn(0, L"时间", LVCFMT_CENTER, 150);
m_wndFileLog.InsertColumn(1, L"文件路径", LVCFMT_LEFT, 280);
m_wndFileLog.InsertColumn(2, L"病毒名称", LVCFMT_LEFT, 115);
m_wndFileLog.InsertColumn(3, L"处理方式", LVCFMT_CENTER, 60);
m_wndFileLog.InsertColumn(4, L"操作", LVCFMT_LEFT, 55);
_EnableButtons(FALSE);
m_quaLoader.Init();
HANDLE hThread = ::CreateThread(NULL, 0, _LoadLogThreadProc, this, 0, NULL);
::CloseHandle(hThread);
hThread = NULL;
return TRUE;
}
LRESULT OnLVNVirScanLogGetDispInfo(LPNMHDR pnmh)
{
NMLVDISPINFO *pdi = (NMLVDISPINFO*)pnmh;
pdi->item.state = 0;
if( pdi->item.iItem < 0 || pdi->item.iItem >= m_arrLogs.GetCount() )
return 0;
KWS_SCAN_LOG &log = m_arrLogs[ pdi->item.iItem ];
if (pdi->item.mask & LVIF_TEXT)
{
CString strItem;
CString strFileName;
CString strVirusName;
strFileName = log.szItemName;
strVirusName = log.szVirusName;
switch (pdi->item.iSubItem)
{
case 0:
{
CTime time( log.tmHistoryTime );
strItem.Format(
L"%4d-%02d-%02d %02d:%02d:%02d",
time.GetYear(),
time.GetMonth(),
time.GetDay(),
time.GetHour(),
time.GetMinute(),
time.GetSecond()
);
}
break;
case 1:
{
WinMod::CWinPath path( strFileName );
strItem = path.GetPathWithoutUnicodePrefix();
}
break;
case 2:
{
m_logic.GetTypeStringEx( log.emType, log.emLevel, strVirusName, strItem );
}
break;
case 3:
if( log.bKwsLog )
{
m_logic.GetLevelString( log.emLevel, strItem );
}
else
{
strItem = L"危险";
}
break;
case 4:
if( log.bKwsLog )
{
m_logic.GetActionString( log.ActionType, strItem );
}
else
{
strItem = L"清除";
}
break;
case 5:
switch( log.state )
{
case enum_HISTORY_ITEM_STATE_FIXED:
strItem = L"还原";
break;
case enum_HISTORY_ITEM_STATE_RESTORED:
strItem = L"已还原";
break;
case enum_HISTORY_ITEM_STATE_CANNOT_BE_RESTORED:
strItem = L"不能还原";
break;
case enum_HISTORY_ITEM_STATE_INVALID:
strItem = L"还原失败";
break;
default:
strItem = L"还原";
break;
}
break;
}
wcsncpy(pdi->item.pszText, strItem, min(strItem.GetLength() + 1, pdi->item.cchTextMax - 1));
}
return 0;
}
LRESULT OnLVNVirScanLogFileGetDispInfo(LPNMHDR pnmh)
{
NMLVDISPINFO *pdi = (NMLVDISPINFO*)pnmh;
pdi->item.state = 0;
if( pdi->item.iItem < 0 || pdi->item.iItem >= m_arrFileLogs.GetCount() )
return 0;
KWS_SCAN_LOG &log = m_arrFileLogs[ pdi->item.iItem ];
if (pdi->item.mask & LVIF_TEXT)
{
CString strItem;
CString strFileName = log.szItemName ;
CString strVirusName = log.szItemName;
switch (pdi->item.iSubItem)
{
case 0:
{
CTime time( log.tmHistoryTime );
strItem.Format(
L"%4d-%02d-%02d %02d:%02d:%02d",
time.GetYear(),
time.GetMonth(),
time.GetDay(),
time.GetHour(),
time.GetMinute(),
time.GetSecond()
);
}
break;
case 1:
{
WinMod::CWinPath path( strFileName );
strItem = path.GetPathWithoutUnicodePrefix();
}
break;
case 2:
strItem = log.szVirusName;
break;
case 3:
if( log.bKwsLog )
{
m_logic.GetActionString( log.ActionType, strItem );
}
else
{
strItem = L"清除";
}
break;
case 4:
switch( log.state )
{
case enum_HISTORY_ITEM_STATE_FIXED:
strItem = L"还原";
break;
case enum_HISTORY_ITEM_STATE_RESTORED:
strItem = L"已还原";
break;
case enum_HISTORY_ITEM_STATE_CANNOT_BE_RESTORED:
strItem = L"不能还原";
break;
case enum_HISTORY_ITEM_STATE_INVALID:
strItem = L"还原失败";
break;
default:
strItem = L"还原";
break;
}
break;
}
wcsncpy(pdi->item.pszText, strItem, min(strItem.GetLength() + 1, pdi->item.cchTextMax - 1));
}
return 0;
}
LRESULT OnLoadLogFinish(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
m_wndListLog.SetItemCount(m_arrLogs.GetCount());
m_wndListLog.SetDataPrt( &m_arrLogs );
m_wndFileLog.SetItemCount( m_arrFileLogs.GetCount());
m_wndFileLog.SetDataPrt( &m_arrFileLogs );
if( m_bShowFileTab == TRUE )
{
SetItemVisible(IDC_FILE_VIRUS_LOG_LIST, TRUE);
SetItemVisible(IDC_FILE_LOG_TEXT, TRUE );
SetItemVisible(IDC_ALL_LOG_TEXT, FALSE );
SetTabCurSel( IDC_VIRUS_LOG_TAB_CTRL, 1 );
}
else
{
SetItemVisible(IDC_LST_VIRSCAN_LOG, TRUE);
SetItemVisible(IDC_ALL_LOG_TEXT, TRUE );
SetItemVisible(IDC_FILE_LOG_TEXT, FALSE );
SetTabCurSel( IDC_VIRUS_LOG_TAB_CTRL, 0 );
}
_EnableButtons(TRUE);
EnableItem( IDC_BTN_VIRSCAN_CLEAR_LOG, FALSE);
return 0;
}
int GetFileLogCount()
{
int nCnt = 0;
}
LRESULT OnClearLogFinish(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
_EnableButtons(TRUE);
UpdateBtnAndCheck( );
return 0;
}
void _EnableButtons(BOOL bEnable)
{
m_bDoing = !bEnable;
EnableItem(IDC_BTN_SYS_CLOSE, bEnable);
EnableItem(IDC_BTN_SYS_MAX, bEnable );
EnableItem(IDCANCEL, bEnable);
EnableItem(IDC_BTN_VIRSCAN_CLEAR_LOG, bEnable );
}
void SortAfterAdd( CAtlArray< KWS_SCAN_LOG >& arrLog, KWS_SCAN_LOG& logItem )
{
BOOL bFind = FALSE;
if( arrLog.GetCount() == 0 )
{
arrLog.Add( logItem );
bFind = TRUE;
}
else
{
for ( int i = 0; i < arrLog.GetCount(); i++ )
{
if( logItem.tmHistoryTime > arrLog[i].tmHistoryTime )
{
arrLog.InsertAt( i, logItem );
bFind = TRUE;
break;
}
}
}
if( bFind == FALSE )
{
arrLog.Add( logItem );
}
}
static DWORD WINAPI _LoadLogThreadProc(LPVOID pvParam)
{
CBeikeSafeVirScanLogDlg* pDlg = (CBeikeSafeVirScanLogDlg*)pvParam;
if( pDlg )
{
pDlg->DoLoadLogThread();
}
return 0;
}
void DoLoadLogThread()
{
CAtlArray<KWS_SCAN_LOG> arrKwsLog;
VEC_QUAR vecFile;
m_quaLoader.LoadQuara( vecFile );
for ( int i = 0 ; i < vecFile.size(); i++ )
{
KWS_SCAN_LOG kwsLog;
memset( &kwsLog, 0, sizeof(KWS_SCAN_LOG) );
QuaraToLog( vecFile[i], kwsLog );
SortAfterAdd( m_arrLogs, kwsLog );
SortAfterAdd( m_arrFileLogs, kwsLog );
}
std::vector<S_HISTORY_ITEM_EX> HisList;
m_logic.QueryHistoryListEx( 10, HisList );
for ( int i = 0; i < HisList.size(); i++ )
{
KwsLogToLog( HisList[i] );
}
if ( IsWindow())
SendMessage( MSG_LOAD_LOG_FINISH, NULL, NULL );
::SetCursor(::LoadCursor(NULL, IDC_ARROW));
}
//
BOOL InIsoRegion( UINT nCleanResult )
{
switch( nCleanResult )
{
case BKENG_CLEAN_RESULT_DISINFECT:
case BKENG_CLEAN_RESULT_DISINFECT_NEED_REBOOT:
case BKENG_CLEAN_RESULT_DELETE_NEED_REBOOT:
case BKENG_CLEAN_RESULT_DELETE:
case BKENG_CLEAN_RESULT_FAILED_TO_DELETE:
case BKENG_CLEAN_RESULT_FAILED_TO_DISINFECT:
case BKENG_CLEAN_RESULT_NEED_DELETE:
case BKENG_CLEAN_RESULT_DISINFECT_NEED_REPLACE:
return TRUE;
break;
default:
return FALSE;
}
return FALSE;
}
static DWORD WINAPI _ClearLogThreadProc(LPVOID pvParam)
{
CBeikeSafeVirScanLogDlg* pDlg = (CBeikeSafeVirScanLogDlg*)pvParam;
if( pDlg )
{
pDlg->_CleanKXELog();
pDlg->_ClearKwsLog();
if (pDlg->IsWindow())
pDlg->SendMessage(MSG_CLEAR_LOG_FINISH, 0, 0);
}
return 0;
}
void _ClearKwsLog()
{
if( m_kwsRemove.vecRecords.size() > 0 )
{
m_logic.RemoveHistoryRecord( m_kwsRemove );
m_kwsRemove.vecRecords.clear();
}
}
void _CleanKXELog()
{
m_quaLoader.DeleteQuarantineFile( m_vecRemove );
}
LRESULT OnRemoveQuarantineItemNotify(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
int nIndex = (int)wParam;
HRESULT hRet = (HRESULT)lParam;
if ( hRet != S_OK)
{
if( nIndex < m_arrLogs.GetCount() )
{
m_arrLogs[nIndex].state = enum_HISTORY_ITEM_STATE_INVALID;
m_wndListLog.RedrawItems( nIndex, nIndex );
}
else
{
ATLASSERT( FALSE );
}
}
return 0;
}
LRESULT OnItemClick(UINT uMsg,WPARAM wParam,LPARAM lParam,BOOL bHandler)
{
::PostMessage( m_hWnd, WM_MSG_LOG_RECOVER, wParam, lParam );
return TRUE;
}
LRESULT OnItemCheckbox(UINT uMsg,WPARAM wParam,LPARAM lParam,BOOL bHandler)
{
int nIndex = (int)wParam;
if( !m_wndListLog.IsWindowVisible() )
{
SetTheSameLogCheck( nIndex );
}
UpdateBtnAndCheck( );
return TRUE;
}
void SetTheSameLogCheck( int nIndex )
{
CAtlArray< KWS_SCAN_LOG >* pCurLog = NULL;
CLogListCtrl* pCurList = NULL;
if( m_wndListLog.IsWindowVisible() )
{
pCurLog = &m_arrLogs;
pCurList = &m_wndListLog;
}
else
{
pCurLog = &m_arrFileLogs;
pCurList = &m_wndFileLog;
}
BOOL bCheck = pCurList->GetCheckState( nIndex );
if( nIndex < pCurLog->GetCount() && nIndex >= 0 )
{
KWS_SCAN_LOG& log = pCurLog->GetAt( nIndex );
if( log.bKwsLog )
{
for ( int i = 0; i < pCurLog->GetCount(); i++ )
{
KWS_SCAN_LOG& item = pCurLog->GetAt( i );
if ( item.bKwsLog && (item.dwID == log.dwID) && ( log.tmHistoryTime == item.tmHistoryTime ) )
{
pCurList->SetCheckState( i, bCheck );
}
}
}
else
{
for ( int i = 0; i < pCurLog->GetCount(); i++ )
{
KWS_SCAN_LOG& item = pCurLog->GetAt( i );
if ( !item.bKwsLog && (item.dwID == log.dwID ) )
{
pCurList->SetCheckState( i, bCheck );
}
}
}
}
}
LRESULT OnRecover(UINT uMsg,WPARAM wParam,LPARAM lParam,BOOL bHandler)
{
int nItem = (int)wParam;
if(nItem<0) return -1;
CAtlArray< KWS_SCAN_LOG >& arrLogs = m_wndListLog.IsWindowVisible() ? m_arrLogs : m_arrFileLogs;
CLogListCtrl& logList = m_wndListLog.IsWindowVisible() ? m_wndListLog : m_wndFileLog;
BOOL bFileLog = !m_wndListLog.IsWindowVisible();
if( nItem <= arrLogs.GetCount() )
{
if( arrLogs[nItem].bKwsLog )
{
UINT_PTR uRet = IDCANCEL;
if( bFileLog )
{
CWHRoundRectDialog<CBkSimpleDialog> dlgNotice;
dlgNotice.Load(IDR_BK_QUARANTINE_RETRIEVE_NOTICE_KWS_DLG);
uRet = dlgNotice.DoModal( );
if( uRet == IDOK )
{
arrLogs[nItem].state = enum_HISTORY_ITEM_STATE_RESTORED;
logList.RedrawItems( nItem, nItem );
RecoverItem( arrLogs[nItem].dwID, arrLogs[nItem].tmHistoryTime );
UpdateTheSameState( arrLogs, nItem, logList );
UpdateOtherLog( arrLogs[nItem] );
}
if (dlgNotice.GetItemCheck(IDC_CHK_MSGBOX_NONOTIFYLATER))
{
AddTheSameFileTrust( arrLogs, nItem );
//AddFileToTrust( arrLogs[nItem].szItemName );
}
}
else
{
CBkSafeMsgBox dlg;
dlg.AddButton(TEXT("确定"), IDOK);
dlg.AddButton(TEXT("取消"), IDCANCEL);
CString strText(TEXT("还原已经修复的威胁项,有可能使电脑感染\r\n\r\n病毒木马!您确定要继续还原吗?"));
uRet = dlg.ShowMsg(
strText, NULL, MB_BK_CUSTOM_BUTTON | MB_ICONWARNING);
if( uRet == IDOK )
{
arrLogs[nItem].state = enum_HISTORY_ITEM_STATE_RESTORED;
logList.RedrawItems( nItem, nItem );
RecoverItem( arrLogs[nItem].dwID, arrLogs[nItem].tmHistoryTime );
UpdateTheSameState( arrLogs, nItem, logList );
UpdateOtherLog( arrLogs[nItem] );
}
}
}
else
{
CWHRoundRectDialog<CBkSimpleDialog> dlgNotice;
dlgNotice.Load(IDR_BK_QUARANTINE_RETRIEVE_NOTICE_DLG);
UINT_PTR uRet = dlgNotice.DoModal( );
if ( uRet == IDOK)
{
HRESULT hr = E_FAIL;
KWS_SCAN_LOG& log = arrLogs[nItem];
std::wstring strFile( log.szItemName );
std::wstring strQuaraName( log.szQuaraName );
hr = m_quaLoader.RestoreQuarantineFile( strFile, strQuaraName );
log.state = SUCCEEDED(hr) ? enum_HISTORY_ITEM_STATE_RESTORED : enum_HISTORY_ITEM_STATE_INVALID;
logList.RedrawItems( nItem, nItem );
if (dlgNotice.GetItemCheck(IDC_CHK_MSGBOX_NONOTIFYLATER))
{
WinMod::CWinPath path( log.szItemName );
AddFileToTrust( path.GetPathWithoutUnicodePrefix() );
}
UpdateOtherLog( log );
}
}
}
return TRUE;
}
void UpdateTheSameState( CAtlArray< KWS_SCAN_LOG >& arrLog, int nItem, CLogListCtrl& logList )
{
KWS_SCAN_LOG& log = arrLog[nItem];
for ( int i = 0; i < arrLog.GetCount(); i++ )
{
KWS_SCAN_LOG& item = arrLog[i];
if( item.bKwsLog &&
item.tmHistoryTime == log.tmHistoryTime &&
item.dwID == log.dwID &&
item.state == enum_HISTORY_ITEM_STATE_FIXED )
{
item.state = enum_HISTORY_ITEM_STATE_RESTORED;
logList.RedrawItems( i, i );
}
}
}
void UpdateOtherLog( KWS_SCAN_LOG& log )
{
CAtlArray< KWS_SCAN_LOG >& arrLogs = !m_wndListLog.IsWindowVisible() ? m_arrLogs : m_arrFileLogs;
for ( int i = 0; i < arrLogs.GetCount(); i++ )
{
KWS_SCAN_LOG& logOther = arrLogs[i];
if( log.bKwsLog )
{
if( log.tmHistoryTime == logOther.tmHistoryTime &&
log.dwID == logOther.dwID )
{
logOther.state = log.state;
break;
}
}
else
{
UINT uId = logOther.dwID;
if( log.dwID == uId )
{
logOther.state = log.state;
break;
}
}
}
}
void AddTheSameFileTrust( CAtlArray< KWS_SCAN_LOG >& arrLog, int nItem )
{
KWS_SCAN_LOG& log = arrLog[nItem];
for ( int i = 0; i < arrLog.GetCount(); i++ )
{
KWS_SCAN_LOG& item = arrLog[i];
if( item.bKwsLog &&
item.tmHistoryTime == log.tmHistoryTime &&
item.dwID == log.dwID )
{
AddFileToTrust( item.szItemName );
}
}
}
void AddFileToTrust( LPCTSTR pszFile )
{
std::wstring szUrl( pszFile );
AddTrustItem( szUrl, enum_TRUST_ITEM_TYPE_FILE );
CSafeMonitorTrayShell::WhiteListLibUpdated();
}
void OnDestroy()
{
m_wndListLog.DestroyWindow();
m_wndFileLog.DestroyWindow();
if( m_hLoadLog )
{
if( WaitForSingleObject(m_hLoadLog, 100 ) != WAIT_OBJECT_0 )
TerminateThread( m_hLoadLog, 0 );
::CloseHandle( m_hLoadLog );
m_hLoadLog = NULL;
}
m_quaLoader.UnInit();
}
void AddTrustItem( std::wstring& strItem, EM_TRUST_ITEM_TYPE nType )
{
S_TRUST_LIST trustList;
trustList.operation = enum_TRUST_LIST_ADD;
trustList.itemType = nType;
trustList.vecItemList.push_back( strItem );
HRESULT hr = m_logic.SetUserTrustList( trustList );
CSafeMonitorTrayShell::WhiteListLibUpdated();
ATLASSERT( SUCCEEDED(hr) );
}
void OnBtnCheckAll()
{
BOOL bCheck = GetItemCheck( IDC_VIRUS_LOG_CHECK_ALL );
if( m_wndFileLog.IsWindowVisible() )
{
m_wndFileLog.CheckAllItems( bCheck );
}
else if ( m_wndListLog.IsWindowVisible() )
{
m_wndListLog.CheckAllItems( bCheck );
}
EnableItem( IDC_BTN_VIRSCAN_CLEAR_LOG, bCheck);
}
void RecoverItem( DWORD dwId, __time64_t time )
{
S_RECOVER_ITEM recoverItem;
recoverItem.tmHistoryTime = time;
recoverItem.vecItemIDs.push_back( dwId );
std::vector<S_RECOVER_ITEM> recoverList;
recoverList.push_back(recoverItem);
HRESULT hr = m_logic.StartRecoverEx(recoverList);
assert( SUCCEEDED(hr) );
}
void OnBkBtnMax()
{
if (WS_MAXIMIZE == (GetStyle() & WS_MAXIMIZE))
{
SendMessage(WM_SYSCOMMAND, SC_RESTORE | HTCAPTION, 0);
//SetItemAttribute(IDC_BTN_SYS_MAX, "skin", "maxbtn");
}
else
{
SendMessage(WM_SYSCOMMAND, SC_MAXIMIZE | HTCAPTION, 0);
//SetItemAttribute(IDC_BTN_SYS_MAX, "skin", "restorebtn");
}
}
void OnListVirusScanLog(CRect rcWnd)
{
m_wndListLog.SetColumnWidth(0, 150 );
m_wndListLog.SetColumnWidth(1, rcWnd.Width() - 435 - ::GetSystemMetrics(SM_CXVSCROLL) - 6 );
m_wndListLog.SetColumnWidth(2, 115 );
m_wndListLog.SetColumnWidth(3, 55 );
m_wndListLog.SetColumnWidth(4, 60 );
m_wndListLog.SetColumnWidth(5, 55 );
m_wndListLog.Invalidate(TRUE);
}
void OnListFileVirusLog(CRect rcWnd)
{
m_wndFileLog.SetColumnWidth(0, 150 );
m_wndFileLog.SetColumnWidth(1, rcWnd.Width() - 380 - ::GetSystemMetrics(SM_CXVSCROLL) - 6 );
m_wndFileLog.SetColumnWidth(2, 115 );
m_wndFileLog.SetColumnWidth(3, 60 );
m_wndFileLog.SetColumnWidth(4, 55 );
m_wndFileLog.Invalidate(TRUE);
}
public:
BK_NOTIFY_MAP(IDC_RICHVIEW_WIN)
BK_NOTIFY_ID_COMMAND(IDC_BTN_SYS_CLOSE, OnBkBtnClose)
BK_NOTIFY_ID_COMMAND(IDC_BTN_SYS_MAX, OnBkBtnMax)
BK_NOTIFY_ID_COMMAND(IDC_BTN_VIRSCAN_CLEAR_LOG, OnBtnVirScanClearLog)
BK_NOTIFY_ID_COMMAND(IDC_VIRUS_LOG_CHECK_ALL, OnBtnCheckAll)
BK_NOTIFY_TAB_SELCHANGE(IDC_VIRUS_LOG_TAB_CTRL,OnBkTabCtrlChange)
BK_NOTIFY_ID_COMMAND(IDCANCEL, OnBkBtnClose)
BK_NOTIFY_REALWND_RESIZED(IDC_LST_VIRSCAN_LOG, OnListVirusScanLog )
BK_NOTIFY_REALWND_RESIZED(IDC_FILE_VIRUS_LOG_LIST, OnListFileVirusLog )
BK_NOTIFY_MAP_END()
BEGIN_MSG_MAP_EX(CBeikeSafeVirScanLogDlg)
MSG_BK_NOTIFY(IDC_RICHVIEW_WIN)
CHAIN_MSG_MAP(CBkDialogImpl<CBeikeSafeVirScanLogDlg>)
CHAIN_MSG_MAP(CWHRoundRectFrameHelper<CBeikeSafeVirScanLogDlg>)
MSG_WM_INITDIALOG(OnInitDialog)
NOTIFY_HANDLER_EX(IDC_LST_VIRSCAN_LOG, LVN_GETDISPINFO, OnLVNVirScanLogGetDispInfo)
NOTIFY_HANDLER_EX(IDC_FILE_VIRUS_LOG_LIST, LVN_GETDISPINFO, OnLVNVirScanLogFileGetDispInfo)
MESSAGE_HANDLER_EX(MSG_LOAD_LOG_FINISH, OnLoadLogFinish)
MESSAGE_HANDLER_EX(MSG_CLEAR_LOG_FINISH, OnClearLogFinish)
MSG_WM_DESTROY(OnDestroy)
MESSAGE_HANDLER(WM_ITEM_BUTTON_CLICK, OnRecover)
MESSAGE_HANDLER(WM_ITEM_CHECKBOX_CLICK, OnItemCheckbox)
MESSAGE_HANDLER_EX(MSG_REMOVE_QUARANTINE_ITEM_NOTIFY, OnRemoveQuarantineItemNotify)
REFLECT_NOTIFICATIONS_EX()
END_MSG_MAP()
}; | [
"dreamsxin@qq.com"
] | dreamsxin@qq.com |
79cc96d755147c2a507c573e49a00a5fe9b7f00b | e7f685c1691a31719368809b5e564c3c91cd6ca2 | /envoy_qatzip/qatzip_filter.cc | 83b2eaf09dc9d5f130a30c1ba6b0f3d9760c433b | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | ailin258/kubernetes-qat-envoy | 3061e24cc9f22f7bcd8e2629af4010a1b375971a | d3b1b38c86c5ef019b6af38ab82ba2b131063c98 | refs/heads/master | 2022-08-23T10:19:17.500067 | 2020-05-25T06:52:00 | 2020-05-25T06:52:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,620 | cc | #include "qatzip_filter.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace Qatzip {
namespace {
// Default qatzip stream buffer size.
const unsigned int DefaultStreamBufferSize = 128 * 1024;
} // namespace
QatzipFilterConfig::QatzipFilterConfig(const qatzip::Qatzip& qatzip,
const std::string& stats_prefix, Stats::Scope& scope,
Runtime::Loader& runtime)
: CompressorFilterConfig(qatzip.compressor(), stats_prefix + "qatzip.", scope, runtime, "gzip"),
compression_level_(compressionLevelUint(qatzip.compression_level().value())),
hardware_buffer_size_(hardwareBufferSizeEnum(qatzip.hardware_buffer_size())),
input_size_threshold_(inputSizeThresholdUint(qatzip.input_size_threshold().value())),
stream_buffer_size_(streamBufferSizeUint(qatzip.stream_buffer_size().value())) {}
unsigned int
QatzipFilterConfig::hardwareBufferSizeEnum(qatzip::Qatzip_HardwareBufferSize hardware_buffer_size) {
switch (hardware_buffer_size) {
case qatzip::Qatzip_HardwareBufferSize::Qatzip_HardwareBufferSize_SZ_4K:
return 4 * 1024;
case qatzip::Qatzip_HardwareBufferSize::Qatzip_HardwareBufferSize_SZ_8K:
return 8 * 1024;
case qatzip::Qatzip_HardwareBufferSize::Qatzip_HardwareBufferSize_SZ_32K:
return 32 * 1024;
case qatzip::Qatzip_HardwareBufferSize::Qatzip_HardwareBufferSize_SZ_64K:
return 64 * 1024;
case qatzip::Qatzip_HardwareBufferSize::Qatzip_HardwareBufferSize_SZ_128K:
return 128 * 1024;
case qatzip::Qatzip_HardwareBufferSize::Qatzip_HardwareBufferSize_SZ_512K:
return 512 * 1024;
default:
return 64 * 1024;
}
}
unsigned int QatzipFilterConfig::compressionLevelUint(Protobuf::uint32 compression_level) {
return compression_level > 0 ? compression_level : QZ_COMP_LEVEL_DEFAULT;
}
unsigned int QatzipFilterConfig::inputSizeThresholdUint(Protobuf::uint32 input_size_threshold) {
return input_size_threshold > 0 ? input_size_threshold : QZ_COMP_THRESHOLD_DEFAULT;
}
unsigned int QatzipFilterConfig::streamBufferSizeUint(Protobuf::uint32 stream_buffer_size) {
return stream_buffer_size > 0 ? stream_buffer_size : DefaultStreamBufferSize;
}
std::unique_ptr<Compressor::Compressor> QatzipFilterConfig::makeCompressor() {
auto compressor = std::make_unique<Compressor::QatzipCompressorImpl>();
compressor->init(compressionLevel(), hardwareBufferSize(), streamBufferSize(),
inputSizeThreshold());
return compressor;
}
} // namespace Qatzip
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
| [
"dmitry.rozhkov@linux.intel.com"
] | dmitry.rozhkov@linux.intel.com |
1aa36c43fb96b1e748f7d6c888639b76b0bef080 | 8153aab69805392429f13c4220df58cf138698b1 | /ALGORITMOS EXEMPLOS/ListaTelefonicaSilvioEutimio.cpp | 20272565e98d28065d75b8d4d29faae7b73d989a | [
"Apache-2.0"
] | permissive | AndersonFCanel/C-PassoAPasso | 95f670ecf01a7f79ace51ada017250c70ab88345 | f91af1db94cfbece27c054180262cfe0eb08fe3b | refs/heads/master | 2021-09-25T17:51:10.750208 | 2018-10-24T19:23:10 | 2018-10-24T19:23:10 | 108,064,020 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,286 | cpp | // /Algoritmo: Ordenação de um vetor A com n elementos. No exemplo foi com 20 elementos.
// Usando C.
#include <stdio.h>
#include <conio.h>
#define N 5
void lervetor(int v[])
{
int i;
i = 0;
while(i < N)
{
printf("Digite um elemento do vetor:");
scanf("%d", &v[i]);
i = i + 1;
}
}
void escrevervetor(int v[])
{
int i;
printf("{");
i = 0;
while(i < N)
{
printf(" %d ", v[i]);
i = i + 1;
}
printf("}\n");
}
main()
{
int i, j, a[N], aux;
lervetor(a);
printf("vetor original = ");
escrevervetor(a);
j = N - 2; /* essa é a penúltima posição do vetor */
while(j >= 0)
{
i = 0;
while(i <= j)
{
if(a[i] > a[i + 1])
{
aux = a[i];
a[i] = a[i + 1];
a[i + 1] = aux;
}
i = i + 1;
}
j = j - 1;
}
printf("\n");
printf("vetor ordenado = ");
escrevervetor(a);
getch();
}
| [
"noreply@github.com"
] | noreply@github.com |
f3873b7d76e8cc5dc7f913dda84f9a51fb0e4ef1 | ae577e7708b74360d9d9d2524b2433531ec07f71 | /server/utils/FileInfo.h | 05e3b653121315bbfa3c6d0d5df236d0a3ff7beb | [] | no_license | OnTheWay2015/blue_test | 53406ee2ab57b7074b6abb9bedf3729fce4e3e75 | 83acd5d2c5d1de3119a13d58029a919d9e7c69af | refs/heads/master | 2023-06-26T13:53:39.591013 | 2023-06-16T02:27:02 | 2023-06-16T02:27:02 | 113,654,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,531 | h | #pragma once
class CFileInfo
{
protected:
bool m_IsOK;
CEasyString m_FilePath;
UINT64 m_FileSize;
UINT m_FileAttributes;
time_t m_CreationTime;
time_t m_LastAccessTime;
time_t m_LastWriteTime;
public:
CFileInfo()
{
m_IsOK = false;
m_FileSize = 0;
m_FileAttributes = 0;
m_CreationTime = 0;
m_LastAccessTime = 0;
m_LastWriteTime = 0;
}
CFileInfo(LPCTSTR szFilePath)
{
m_IsOK = false;
m_FileSize = 0;
m_FileAttributes = 0;
m_CreationTime = 0;
m_LastAccessTime = 0;
m_LastWriteTime = 0;
FetchFileInfo(szFilePath);
}
~CFileInfo()
{
}
inline static CFileInfo GetFileInfo(LPCTSTR szFilePath)
{
return CFileInfo(szFilePath);
}
#ifdef _WIN32
bool FetchFileInfo(LPCTSTR szFilePath)
{
m_IsOK = false;
WIN32_FILE_ATTRIBUTE_DATA FileAttr;
if (GetFileAttributesEx(szFilePath, GetFileExInfoStandard, &FileAttr))
{
m_FilePath = szFilePath;
UINT64_CONVERTER Con;
Con.HighPart = FileAttr.nFileSizeHigh;
Con.LowPart = FileAttr.nFileSizeLow;
m_FileSize = Con.QuadPart;
m_FileAttributes = FileAttr.dwFileAttributes;
CEasyTime Time;
Time.SetTime(FileAttr.ftCreationTime);
m_CreationTime = Time;
Time.SetTime(FileAttr.ftLastAccessTime);
m_LastAccessTime = Time;
Time.SetTime(FileAttr.ftLastWriteTime);
m_LastWriteTime = Time;
m_IsOK = true;
}
return m_IsOK;
}
#else
bool FetchFileInfo(LPCTSTR szFilePath)
{
m_IsOK = false;
struct stat FileStat;
if (stat(szFilePath, &FileStat) == 0)
{
m_FilePath = szFilePath;
m_FileSize = FileStat.st_size;
m_FileAttributes = FileStat.st_mode;
m_CreationTime = FileStat.st_ctime;
m_LastAccessTime = FileStat.st_atime;
m_LastWriteTime = FileStat.st_mtime;
m_IsOK = true;
}
return m_IsOK;
}
#endif
bool IsOK()
{
return m_IsOK;
}
#ifdef _WIN32
bool IsFile()
{
return m_IsOK && ((m_FileAttributes&FILE_ATTRIBUTE_DIRECTORY) == 0);
}
#else
bool IsFile()
{
return m_IsOK && ((m_FileAttributes&S_IFREG) != 0);
}
#endif
#ifdef _WIN32
bool IsDir()
{
return m_IsOK && ((m_FileAttributes&FILE_ATTRIBUTE_DIRECTORY) != 0);
}
#else
bool IsDir()
{
return m_IsOK && ((m_FileAttributes&S_IFDIR) != 0);
}
#endif
UINT64 GetFileSize()
{
return m_FileSize;
}
UINT GetFileAttr()
{
return m_FileAttributes;
}
time_t GetCreateTime()
{
return m_CreationTime;
}
time_t GetLastAccessTime()
{
return m_LastAccessTime;
}
time_t GetLastWriteTime()
{
return m_LastWriteTime;
}
#ifdef _WIN32
bool SetCreateTime(time_t Time)
{
if (m_IsOK)
{
HANDLE hFile = CreateFile(m_FilePath, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CEasyTime FileTime(Time);
FILETIME FTime = FileTime;
if (SetFileTime(hFile, &FTime, NULL, NULL))
{
CloseHandle(hFile);
return true;
}
CloseHandle(hFile);
}
}
return false;
}
#else
bool SetCreateTime(const CEasyTime& Time)
{
return false;
}
#endif
#ifdef _WIN32
bool SetLastAccessTime(time_t Time)
{
if (m_IsOK)
{
HANDLE hFile = CreateFile(m_FilePath, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CEasyTime FileTime(Time);
FILETIME FTime = FileTime;
if (SetFileTime(hFile, NULL, &FTime, NULL))
{
CloseHandle(hFile);
return true;
}
CloseHandle(hFile);
}
}
return false;
}
#else
bool SetLastAccessTime(time_t Time)
{
if (m_IsOK)
{
struct utimbuf FileTimes;
FileTimes.actime = Time;
FileTimes.modtime = m_LastWriteTime;
if (utime(m_FilePath, &FileTimes) == 0)
{
return true;
}
}
return false;
}
#endif
#ifdef _WIN32
bool SetLastWriteTime(time_t Time)
{
if (m_IsOK)
{
HANDLE hFile = CreateFile(m_FilePath, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CEasyTime FileTime(Time);
FILETIME FTime = FileTime;
if (SetFileTime(hFile, NULL, NULL, &FTime))
{
CloseHandle(hFile);
return true;
}
CloseHandle(hFile);
}
}
return false;
}
#else
bool SetLastWriteTime(time_t Time)
{
if (m_IsOK)
{
struct utimbuf FileTimes;
FileTimes.actime = m_LastAccessTime;
FileTimes.modtime = Time;
if (utime(m_FilePath, &FileTimes) == 0)
{
return true;
}
}
return false;
}
#endif
};
| [
"7130458@qq.com"
] | 7130458@qq.com |
fcb698bbc123a341a7059c9b2b968d112f64b380 | c573e050b98c47b1ef3f2ed4a9ae37a961cda66a | /ESP8266 code/radar/ServoDriver.h | 71866521bbb991d4a9012b263a61b9d7375fe42f | [
"MIT"
] | permissive | KarimAshraf1995/CMPN445_ProjectS2019 | 12359558ba5146145dfaf41165703ade479c8e5e | 4c1cae1dcddc0afab482e0a28cdfb2ce706ff23c | refs/heads/master | 2020-04-28T00:55:20.059834 | 2019-05-04T16:08:59 | 2019-05-04T16:08:59 | 174,833,983 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,103 | h | /*
Name: ServoDriver.h
Created: 05/04/2019 13:02:40 PM
Author: karim
*/
#ifndef __SERVODRIVER_H
#define __SERVODRIVER_H
#include <Arduino.h>
#include "core_esp8266_waveform.h"
#define MIN_PULSE_WIDTH 200 // the shortest pulse sent to a servo
#define MAX_PULSE_WIDTH 3000 // the longest pulse sent to a servo
#define DEFAULT_PULSE_WIDTH 1500 // default pulse width when servo is attached
#define REFRESH_INTERVAL 20000 // minumim time to refresh servos in microseconds
// Class for the driving the servo.
class ServoDriver
{
private:
uint8_t _pin;
void write_waveform(int value)
{
startWaveform(_pin, (uint32_t)value, REFRESH_INTERVAL - value, 0);
}
public:
void attach(uint8_t pin)
{
_pin = pin;
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
write(DEFAULT_PULSE_WIDTH);
}
void write(int value)
{
value = constrain(value, 0, 180);
long val = map(value, 0, 180, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
write_waveform(val);
}
};
#endif
| [
"karimashraf1995@gmail.com"
] | karimashraf1995@gmail.com |
1e0dcf241fbdd09f2beae1c4217a0fe7b4479cc5 | 85f25a69ec633477f539385fe7782b03a135c1d1 | /BOJ/11060.cpp | fdf8afef10fcd7ed9fc275c9b711b79318c01e28 | [] | no_license | jeongbbn/Algorithm | e9df157c34888d7dfe1cf3b73274b3ae7d927ea5 | dce6e25ac472929a10d8b2a96575dba1930358a1 | refs/heads/master | 2022-05-11T09:27:41.371463 | 2022-05-04T14:56:52 | 2022-05-04T14:56:52 | 251,317,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | cpp | #include<bits/stdc++.h>
using namespace std;
#define INF 1e9
#define MAX 1000000
typedef pair<int, int>pi;
typedef pair<pair<int, int>, int>pii;
typedef long long ll;
int dp[1005], arr[1005];
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &arr[i]);
dp[i] = INF;
}
dp[1] = 0;
for (int i = 2; i <= n; i++)
{
for (int j = 1; j < i; j++)
{
if (arr[j] + j >= i)
dp[i] = min(dp[j] + 1, dp[i]);
}
}
if (dp[n] == INF) printf("-1");
else printf("%d", dp[n]);
}
| [
"noreply@github.com"
] | noreply@github.com |
fbc9f05559933b17b7dc9455d87eb266713a585f | e9710976665e1f8a7c1f0f75251e19be5d4193e4 | /examples/16_Upload_wireless/16_Upload_wireless.ino | 1177a382a81f69ec8ac9be00c0f43c3486b0ff14 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | PrinceBot-Ratthanin/NKP_ONE | d5a340592cad6c8d08ab03ed73b576a85457109c | a1bbcc38a03bc990dcb8612af6789df686f2b520 | refs/heads/master | 2021-06-20T00:24:22.551232 | 2021-02-20T12:22:48 | 2021-02-20T12:22:48 | 190,286,083 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 372 | ino | #include <NKP_ONE.h>
void setup() {
NKP_ONE();
OTA_Open("PrinceBot","aaaaaaaa"); //ตั้ง Hostpot เป็นชื่อ PrinceBot แล้วตั้ง รหัสผ่านเป็น aaaaaaaa
OTA_SW1(); //รอจนกว่าจะกด SW1 เพื่อทำงาน
}
void loop() {
}
| [
"noreply@github.com"
] | noreply@github.com |
145e96263ba8aca4922ddb148d0068388ea626df | 8481be88f4c563853065bfb26ba88941cc2023d5 | /Src/AmrTask/rts_impls/Perilla/Perilla.H | 03f04871b5afaff23c8edc3c1277e0c6f46795df | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | RemiLehe/amrex | 71fee5216667c584a4c071b890cd28671e4211a2 | d37a266c38092e1174096e245326e9eead1f4e03 | refs/heads/master | 2020-03-31T15:55:46.583820 | 2018-10-01T15:52:00 | 2018-10-01T15:52:00 | 152,356,425 | 0 | 0 | NOASSERTION | 2018-10-10T03:16:09 | 2018-10-10T03:16:08 | null | UTF-8 | C++ | false | false | 5,202 | h | #ifndef _PERILLA_
#define _PERILLA_
#include <AMReX_MultiFab.H>
#include <vector>
#include <map>
#include <RegionGraph.H>
#include <pthread.h>
#include <RGIter.H>
//#define USE_PERILLA_PTHREADS
using namespace std;
namespace amrex{
class Perilla
{
static int tagGen(int src, int dest, int channelID, int nFabs, int nChannels);
public:
static int uTags;
static bool genTags;
static int max_step;
static std::map<int,std::map<int,int>> pTagCnt;
static std::map<int,std::map<int,std::map<int,std::map<int,std::map<int,int>>>>> tagMap;
static std::map<int,std::map<int,std::map<int,std::map<int,int>>>> myTagMap;
static void communicateTags(std::vector<RegionGraph*> ga);
static void registerId(int tid);
static int tid();
static volatile int numTeamsFinished;
static Barrier * globalBarrier;
static void multifabBuildFabCon(RegionGraph* graph, const MultiFab& mf, const Periodicity& period);
static void serviceLocalRequests(RegionGraph *graph, int tg);
static void serviceRemoteRequests(RegionGraph *graph, int graphID, int nGraphs);
static void serviceRemoteRequests(RegionGraph *graph);
static void serviceSingleGraphComm(RegionGraph* graph, int tid);
static void serviceMultipleGraphComm(RegionGraph graphArray[], int nGraphs, bool cpyAcross, int tid);
static void serviceMultipleGraphCommDynamic(std::vector<RegionGraph*> graphArray, bool cpyAcross, int tid);
static void serviceMultipleGraphComm(RegionGraph graphArray[], int nGraphs, int tid);
static void fillBoundaryPush(RegionGraph* graph, MultiFab* mf, int f);
static void fillBoundaryPull(RegionGraph* graph, MultiFab* mf, int f);
static void serviceLocalGridCopyRequests(std::vector<RegionGraph*> graphArray, int g, int tg);
static void serviceRemoteGridCopyRequests(std::vector<RegionGraph*> graphArray, int g, int nGraph, int tg);
static void resetRemoteGridCopyRequests(std::vector<RegionGraph*> graphArray, int g, int nGraph, int tg);
static void fillBoundaryPush(amrex::RGIter& rgi, amrex::MultiFab& mf);
static void fillBoundaryPull(amrex::RGIter& rgi, amrex::MultiFab& mf);
static void fillBoundaryPush(amrex::RGIter& rgi, RegionGraph *graph, amrex::MultiFab& mf);
static void fillBoundaryPull(amrex::RGIter& rgi, RegionGraph *graph, amrex::MultiFab& mf);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void multifabExtractCopyAssoc(void* threadInfo);
static void multifabExtractCopyAssoc(RegionGraph* gDst, RegionGraph* gSrc, const MultiFab& dmf, const MultiFab& smf, int nc, int ng, int ngSrc, const Periodicity& period);
static void multifabExtractCopyAssoc(RegionGraph* gDst, RegionGraph* gSrc, const MultiFab& dmf, const MultiFab& smf, const Periodicity& period);
static void multifabCopyPushAsync(RegionGraph* destGraph, RegionGraph* srcGraph, MultiFab* dmf, MultiFab* smf, int f, int dstcomp, int srccomp, int nc, int ng, int ngsrc, bool singleT);
static void multifabCopyPushAsync(RegionGraph* destGraph, RegionGraph* srcGraph, MultiFab* dmf, MultiFab* smf, int f, bool singleT);
static void multifabCopyPush(RegionGraph* destGraph, RegionGraph* srcGraph, amrex::MultiFab* dmf, amrex::MultiFab* smf, int f, int dstcomp, int srccomp, int nc, int ng, int ngsrc, bool singleT);
static void multifabCopyPush(RegionGraph* destGraph, RegionGraph* srcGraph, amrex::MultiFab* dmf, amrex::MultiFab* smf, int f, bool singleT);
static void multifabCopyPull(RegionGraph* destGraph, RegionGraph* srcGraph, MultiFab* dmf, MultiFab* smf, int f, int dstcomp, int srccomp, int nc, int ng, int ngsrc, bool singleT);
static void multifabCopyPull(RegionGraph* destGraph, RegionGraph* srcGraph, MultiFab* dmf, MultiFab* smf, int f, bool singleT);
#if 0
//static void multifabCopyPull(RegionGraph* destGraph, RegionGraph* srcGraph, MultiFab* dmf, MultiFab* smf, int f, int dstcomp, int srccomp, int nc, int ng, int ngsrc, bool singleT, bool mTeams=true);
//static void multifabCopyPush(RegionGraph* destGraph, RegionGraph* srcGraph, amrex::MultiFab* dmf, amrex::MultiFab* smf, int f, int dstcomp, int srccomp, int nc, int ng, int ngsrc, bool singleT, bool mTeams=true);
//static void multifabCopyPush(RegionGraph* destGraph, RegionGraph* srcGraph, amrex::MultiFab* dmf, amrex::MultiFab* smf, int f, bool singleT, bool mTeams=true);
//static void multifabCopyPull(RegionGraph* destGraph, RegionGraph* srcGraph, MultiFab* dmf, MultiFab* smf, int f, bool singleT, bool mTeams=true);
static void multifabCopyPush_1Team(RegionGraph* destGraph, RegionGraph* srcGraph, amrex::MultiFab* dmf, amrex::MultiFab* smf, int f, int dstcomp, int srccomp, int nc, int ng, int ngsrc, bool singleT);
static void fillBoundaryPush_1Team(RegionGraph *graph, amrex::MultiFab& mf, int f, bool mOneThread=false);
static void multifabCopyPull_1Team(RegionGraph* destGraph, RegionGraph* srcGraph, amrex::MultiFab* dmf, amrex::MultiFab* smf, int f, int dstcomp, int srccomp, int nc, int ng, int ngsrc, bool singleT);
static void fillBoundaryPull_1Team(RegionGraph *graph, amrex::MultiFab& mf, int f);
#endif
}; // class Perilla
}
#endif
| [
"tannguyen@lbl.gov"
] | tannguyen@lbl.gov |
0fc9102def8be7e28cd7a771bd62d22498c600d2 | 16c706bcfe0f8579a21a65e16a73e13517940df0 | /camera/OrthogonalCamera.hpp | ebca6850c61c8d85d07aa467c295e3ca315bc342 | [
"MIT"
] | permissive | stanfortonski/3D-Engine-OpenGL-4 | 9d9217e7e989b75943a77d725814d0e8d3744fa8 | 6086d006b5027bc43169605dc3bb5c9575335f51 | refs/heads/master | 2021-02-24T19:58:18.726310 | 2021-01-31T15:16:36 | 2021-01-31T15:16:36 | 245,439,801 | 34 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 377 | hpp | /* Copyright (c) 2020 by Stan Fortoński */
#ifndef ORTHOGONAL_CAMERA_HPP
#define ORTHOGONAL_CAMERA_HPP 1
#include "BaseCamera.hpp"
namespace Engine
{
class OrthogonalCamera: public BaseCamera
{
public:
using BaseCamera::BaseCamera;
virtual glm::mat4 getProjectionMatrix() const{return glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, getNear(), getFar());}
};
}
#endif
| [
"contact@stanfortonski.dev"
] | contact@stanfortonski.dev |
5fd07aec94f6d7e5c0337753fb5e0cd5db9fda58 | f0066eb1b7136b255d09314939aa7a94f0c7c030 | /arduino/szafkav2/szafkav2.ino | af11e26fd8a1341f0bea5f0aa867c239a33d4d94 | [] | no_license | RobertJaskowski/Closet | a8326c91d3d0ede807865fbbfad77c080be737d2 | 66a0f3579a9744bd0926afa440b033bcd796d033 | refs/heads/master | 2020-04-04T14:09:33.174016 | 2019-02-02T22:55:55 | 2019-02-02T22:55:55 | 155,989,445 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,992 | ino | /*************************************************************
Download latest Blynk library here:
https://github.com/blynkkk/blynk-library/releases/latest
Blynk is a platform with iOS and Android apps to control
Arduino, Raspberry Pi and the likes over the Internet.
You can easily build graphic interfaces for all your
projects by simply dragging and dropping widgets.
Downloads, docs, tutorials: http://www.blynk.cc
Sketch generator: http://examples.blynk.cc
Blynk community: http://community.blynk.cc
Follow us: http://www.fb.com/blynkapp
http://twitter.com/blynk_app
Blynk library is licensed under MIT license
This example code is in public domain.
*************************************************************
WARNING!
It's very tricky to get it working. Please read this article:
http://help.blynk.cc/hardware-and-libraries/arduino/esp8266-with-at-firmware
This example shows how value can be pushed from Arduino to
the Blynk App.
NOTE:
BlynkTimer provides SimpleTimer functionality:
http://playground.arduino.cc/Code/SimpleTimer
App project setup:
Value Display widget attached to Virtual Pin V5
*************************************************************/
/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial
#include <stdlib.h>
#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "e3edddbe8c3d4f65b8e078942aa5f0cc";
// Your WiFi credentials.
// Set password to "" for open networks.
//char ssid[] = "ENERGETYK_MOCNI";
//char pass[] = "qwerty2014";
char ssid[] = "FunBox2-E53D";
char pass[] = "jaskowski";
// Hardware Serial on Mega, Leonardo, Micro...
#define EspSerial Serial1
// or Software Serial on Uno, Nano...
//#include <SoftwareSerial.h>
//SoftwareSerial EspSerial(2, 3); // RX, TX
// Your ESP8266 baud rate:
#define ESP8266_BAUD 115200
ESP8266 wifi(&EspSerial);
BlynkTimer timer;
////my code
//before starting need to define what pins for :
//ss_pin
//rst_pin
//card number in for loop need to be correct when adding another one
//card keys
//check if pin 13 12 is good for rfid reader >> pin 0 opens door for few sec
//servo is attached in setup
//locked starting position
//writing from variable to blynk.virtualWrite(VARIABLE, int) doesnt work need to do manually -||-(V1,int)
#include <Keypad.h>
#include <Servo.h>
Servo ServoMotor;
//rfid
#include <SPI.h>
/* Include the RFID library */
#include <RFID.h>
/* Define the DIO used for the SDA (SS) and RST (reset) pins. */
#define SDA_DIO0 3
#define RESET_DIO0 2
#define SDA_DIO1 5 //9 this is old was working
#define RESET_DIO1 4 //8
#define SDA_DIO2 7
#define RESET_DIO2 6
#define SDA_DIO3 13
#define RESET_DIO3 14
#define SDA_DIO4 11
#define RESET_DIO4 10
/* Create an instance of the RFID library */
RFID RC0(SDA_DIO0, RESET_DIO0);
RFID RC1(SDA_DIO1, RESET_DIO1);
RFID RC2(SDA_DIO2, RESET_DIO2);
RFID RC3(SDA_DIO3, RESET_DIO3);
RFID RC4(SDA_DIO4, RESET_DIO4);
//String pinStr;
//int pinNumber;
String KF = "Free";
String KT = "Taken";
char* password = "123";
int position = 0;
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
int pos = 0;
//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
////testing
RFID rfids[] = {RC0,RC1,RC2,RC3,RC4};
String doorKeys[] = {"427917616197","1052331032229","52127221233127","10519106218","553024537249"}; //when placing rfid runs scan through those
String rfidKeys[] = {"000000","1052331032229","52127221233127","10519106218","553024537249"}; //4 klucze po kolei
//compares position of rfid to position key // if every key can open door , add these to doorKeys
//do blynka jest wysyłane tylko wtedy gdy timer klucza jest na 5, czyli 5 razy nie znalazło karty
int keyTimers[] = {0,0,0,0,0};
// This function sends Arduino's up time every second to Virtual Pin (5).
// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.
void myTimerEvent()
{
// You can send any value at any time.
// Please don't send more that 10 values per second.
//Blynk.virtualWrite(V5, millis() / 1000);
}
void setup()
{
// Debug console
Serial.begin(9600);
SPI.begin();
for(RFID r: rfids){
r.init();
}
//ServoMotor.attach(11);
openDoor(0);
// Set ESP8266 baud rate
EspSerial.begin(ESP8266_BAUD);
delay(10);
Blynk.begin(auth, wifi, ssid, pass);
// You can also specify server:
//Blynk.begin(auth, wifi, ssid, pass, "blynk-cloud.com", 80);
//Blynk.begin(auth, wifi, ssid, pass, IPAddress(192,168,1,100), 8080);
// Setup a function to be called every second
timer.setInterval(1000L, myTimerEvent);
//Blynk.virtualWrite(V1, "openn");
//Blynk.virtualWrite(V2, "closedd");
//Blynk.virtualWrite(V3, 5000);
//Blynk.virtualWrite(V4, 60);
//testing
Blynk.virtualWrite(V1 , 1000);
Blynk.virtualWrite(V2 , 1000);
Blynk.virtualWrite(V3 , 1000);
Blynk.virtualWrite(V4 , 1000);
Serial.println();
Serial.println("Approximate your card to the reader...");
}
void loop()
{
Blynk.run();
timer.run(); // Initiates BlynkTimer
Serial.println("loop");
//Blynk.virtualWrite(V3, 255); this is tested , works
//rfid
if (rfids[0].isCard()){
Serial.println("rc0 is on");
/* If so then get its serial number */
rfids[0].readCardSerial();
String content = "";
Serial.println("Door Card detected:");
for(int i=0;i<5;i++){
Serial.print(rfids[0].serNum[i],DEC);
content.concat(String(rfids[0].serNum[i],DEC));
//Serial.print(RC1.serNum[i],HEX); //to print card detail in Hexa Decimal format
}
Serial.println();
content.toUpperCase();
Serial.println("content: " +content);
for(String key : doorKeys){
if(content == key){
Serial.println("otwieram gl drzwi");
openDoor(1);
return;
}else{
//openDoor(0);
}
}
}
delay(2000); //check for door key every sec , check for all keys every 2 sec
for(int r=1; r<=4;r++){
String pinStr = "V";
pinStr.concat(r);
//int pinNumber = pinStr.toInt();
Serial.println();
Serial.println("searching:");
if(rfids[r].isCard()){
rfids[r].readCardSerial();
String content = "";
Serial.print("Key Card detected:");
for(int i=0;i<5;i++){
Serial.print(rfids[r].serNum[i],DEC);
content.concat(String(rfids[r].serNum[i],DEC));
//Serial.print(RC1.serNum[i],HEX); //to print card detail in Hexa Decimal format
}
content.toUpperCase();
if(validCard(content, r)){
openDoor(1);
lightVLed(pinStr,1000);
keyTimers[r]=0;
}else{
Serial.println("else: "+ pinStr);
delay(1000);
//lightVLed(pinStr,0);//przeniesione nizej
}
}else{//w przypadku gdy w ogóle nie znaleziono karty na danej pozycji sprawdz 'key counter timers' i jesli ==5 wyslij do blynk
Serial.println();
Serial.println("nie znaleniono karty na pozycji: " + String(r));
Serial.println("key timer nr: " + String(r) + " timer: " + String(keyTimers[r]));
if(keyTimers[r]==5){
lightVLed(pinStr, 0);
keyTimers[r]=0;
}else{
keyTimers[r]++;
}
}
}
//Blynk.virtualWrite(V1, test);
//delay(2000);
}
void lightVLed(String value, int turned){
if(value == "V1"){
Blynk.virtualWrite(V1, turned);
}else if(value == "V2"){
Blynk.virtualWrite(V2, turned);
}else if(value == "V3"){
Blynk.virtualWrite(V3, turned);
}else if(value == "V4"){
Blynk.virtualWrite(V4, turned);
}
}
boolean validCard(String key, int rfid){
Serial.println();
Serial.println("klucz: " + key + " key tab: " + rfidKeys[rfid] + " rfid order: " + String(rfid));
if(key == rfidKeys[rfid]){//rfid keys starts with 0
Serial.println("valid key");
return true;
}else{
Serial.println("invalid key");
return false;
}
}
void openDoor(int opens){
if (opens){
//open
// ServoMotor.write(11);
Serial.println("opening");
digitalWrite(40, HIGH);
delay(1000);
digitalWrite(40, LOW);
delay(1000);
}else{
//close
Serial.println("closing");
// ServoMotor.write(90);
}
}
| [
"robertjanjaskowski@gmail.com"
] | robertjanjaskowski@gmail.com |
b88fabde2ab8bbb9f9e77a40e97cc02433d6b5e0 | ee0ac6a7c0d79ab294d54e85a58624b82a367ba5 | /Numbers/find_pi_to_the_nth_digit.cpp | 4701b177bf49afe4e621833f46bdd6a11acd06ed | [
"MIT"
] | permissive | indugh/Projects | fe92de1be28f1c4dc8d7534519543f808b5b4372 | 764c7530161414d2e646734a2cea4ff7ec58cd41 | refs/heads/master | 2020-02-26T13:41:20.575631 | 2016-01-02T02:10:30 | 2016-01-02T02:10:30 | 48,895,472 | 0 | 0 | null | 2016-01-02T02:10:30 | 2016-01-02T01:56:20 | C++ | UTF-8 | C++ | false | false | 206 | cpp | #include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
int main() {
int num_digits = 0;
cin >> num_digits;
cout << std::set_precision(num_digits);
cout << "Here's Pi: " <<endl;
} | [
"indugh@umich.edu"
] | indugh@umich.edu |
ab9df7295b10bfabe9b36cea8438c780144c1c82 | f30757a69ce189b434c998553b549f8f4bf9ebf3 | /position/main/main.cpp | 6027f9877ae8b3d97ede97d112ee20666a3103b3 | [] | no_license | neolu/PositionEstimator | e2ff2a210a1bf7024890cbecdf89d3f3492434c4 | 22b0e785c00b2cc1ba031ad36e9c4b9ed0971a90 | refs/heads/master | 2023-04-10T03:34:16.305954 | 2020-01-27T13:11:21 | 2020-01-27T13:12:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,859 | cpp | #include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "ICM_20948.h"
#include "Fusion.h"
FusionBias fusionBias;
FusionAhrs fusionAhrs;
//float samplePeriod = 0.01f; // replace this value with actual sample period in seconds
float samplePeriod = 1.f; // replace this value with actual sample period in seconds
const float G = 9.807f;
FusionVector3 gyroscopeSensitivity = {
.axis = { 2000.0f/32767.5f * 3.14159265359f/180.0f, 2000.0f/32767.5f * 3.14159265359f/180.0f, 2000.0f/32767.5f * 3.14159265359f/180.0f}
}; // replace these values with actual sensitivity in degrees per second per lsb as specified in gyroscope datasheet
FusionVector3 accelerometerSensitivity = {
.axis = { G * 16.0f/32767.5f, G * 16.0f/32767.5f, G * 16.0f/32767.5f} //TODO check value
}; // replace these values with actual sensitivity in g per lsb as specified in accelerometer datasheet
FusionVector3 accelerometerBias = {
.axis = { 0.f, 0.f, 0.f}
}; // replace these values with actual sensitivity in g per lsb as specified in accelerometer datasheet
FusionVector3 hardIronBias = {
.axis = { 0.0f, 0.0f, 0.0f}
}; // replace these values with actual hard-iron bias in uT if known
static void delay(size_t ms)
{
vTaskDelay(ms / portTICK_RATE_MS);
}
//TODO gérer temps
void delay_microseconds(uint16_t us)
{
if (us <= 100) {
ets_delay_us(us);
} else {
uint32_t tick = portTICK_PERIOD_MS * 1000;
vTaskDelay((us+tick-1)/tick);
}
}
ICM_20948_I2C myICM;
static void periodic_timer_callback(void* arg);
extern "C" void app_main()
{
int r = myICM.begin();
if (r < 0)
printf("No connected %d\n", r);
// Set Gyro and Accelerometer to a particular sample mode
// options: ICM_20948_Sample_Mode_Continuous
// ICM_20948_Sample_Mode_Cycled
myICM.setSampleMode( (ICM_20948_Internal_Acc | ICM_20948_Internal_Gyr), ICM_20948_Sample_Mode_Continuous);
// Set full scale ranges for both acc and gyr
ICM_20948_fss_t myFSS; // This uses a "Full Scale Settings" structure that can contain values for all configurable sensors
myFSS.a = gpm16; // (ICM_20948_ACCEL_CONFIG_FS_SEL_e)
// gpm2
// gpm4
// gpm8
// gpm16
myFSS.g = dps2000; // (ICM_20948_GYRO_CONFIG_1_FS_SEL_e)
// dps250
// dps500
// dps1000
// dps2000
myICM.setFullScale( (ICM_20948_Internal_Acc | ICM_20948_Internal_Gyr), myFSS );
// Set up Digital Low-Pass Filter configuration
ICM_20948_dlpcfg_t myDLPcfg; // Similar to FSS, this uses a configuration structure for the desired sensors
myDLPcfg.a = acc_d246bw_n265bw; // (ICM_20948_ACCEL_CONFIG_DLPCFG_e)
// acc_d246bw_n265bw - means 3db bandwidth is 246 hz and nyquist bandwidth is 265 hz
// acc_d111bw4_n136bw
// acc_d50bw4_n68bw8
// acc_d23bw9_n34bw4
// acc_d11bw5_n17bw
// acc_d5bw7_n8bw3 - means 3 db bandwidth is 5.7 hz and nyquist bandwidth is 8.3 hz
// acc_d473bw_n499bw
myDLPcfg.g = gyr_d361bw4_n376bw5; // (ICM_20948_GYRO_CONFIG_1_DLPCFG_e)
// gyr_d196bw6_n229bw8
// gyr_d151bw8_n187bw6
// gyr_d119bw5_n154bw3
// gyr_d51bw2_n73bw3
// gyr_d23bw9_n35bw9
// gyr_d11bw6_n17bw8
// gyr_d5bw7_n8bw9
// gyr_d361bw4_n376bw5
myICM.setDLPFcfg( (ICM_20948_Internal_Acc | ICM_20948_Internal_Gyr), myDLPcfg );
// Choose whether or not to use DLPF
myICM.enableDLPF( ICM_20948_Internal_Acc, true );
myICM.enableDLPF( ICM_20948_Internal_Gyr, true );
delay(100);
const esp_timer_create_args_t periodic_timer_args = { &periodic_timer_callback, NULL, ESP_TIMER_TASK, "periodic" };
esp_timer_handle_t periodic_timer;
esp_timer_create(&periodic_timer_args, &periodic_timer);
/* The timer has been created but is not running yet */
/* Start the timers */
esp_timer_start_periodic(periodic_timer, 3000);
// Initialise gyroscope bias correction algorithm
FusionBiasInitialise(&fusionBias, 1.5f, 0.003f); // stationary threshold = 0.5 degrees per second
// Initialise AHRS algorithm
FusionAhrsInitialise(&fusionAhrs, 10.f); // gain = 0.5
// Set optional magnetic field limits
FusionAhrsSetMagneticField(&fusionAhrs, 20.0f, 70.0f); // valid magnetic field range = 20 uT to 70 uT
// The contents of this do while loop should be called for each time new sensor measurements are available
// put your main code here, to run repeatedly:
//Groupe 3
do {
delay(10000);
} while(true);
/* Clean up and finish the example */
esp_timer_stop(periodic_timer);
esp_timer_delete(periodic_timer);
}
FusionVector3 velocity;
FusionVector3 position;
static void periodic_timer_callback(void* arg)
{
//printf("\f");
static int n = 0;
static int64_t last_time = esp_timer_get_time();
myICM.getAGMT();
// Calibrate gyroscope
FusionVector3 uncalibratedGyroscope = {
.axis = { myICM.gyrX(), myICM.gyrY(), myICM.gyrZ() } /* replace this value with actual gyroscope x,y,z axis measurement in lsb */
};
FusionVector3 calibratedGyroscope = FusionCalibrationInertial(uncalibratedGyroscope, FUSION_ROTATION_MATRIX_IDENTITY, gyroscopeSensitivity, FUSION_VECTOR3_ZERO);
// Calibrate accelerometer
FusionVector3 uncalibratedAccelerometer = {
.axis = { myICM.accX(), myICM.accY(), myICM.accZ()}/* replace this value with actual accelerometer x,y,z axis measurement in lsb */
};
FusionVector3 calibratedAccelerometer = FusionCalibrationInertial(uncalibratedAccelerometer, FUSION_ROTATION_MATRIX_IDENTITY, accelerometerSensitivity, FUSION_VECTOR3_ZERO);
// Calibrate magnetometer
FusionVector3 uncalibratedMagnetometer = {
.axis = { myICM.magX(), myICM.magY(), myICM.magZ()} /* replace this value with actual magnetometer x axis measurement in uT */
};
/*
if (n >= 0)
{
printf("%f;%f;%f;", uncalibratedGyroscope.axis.x, uncalibratedGyroscope.axis.y, uncalibratedGyroscope.axis.z);
printf("%f;%f;%f;", uncalibratedAccelerometer.axis.x, uncalibratedAccelerometer.axis.y, uncalibratedAccelerometer.axis.z);
printf("%f;%f;%f\n", uncalibratedMagnetometer.axis.x, uncalibratedMagnetometer.axis.y, uncalibratedMagnetometer.axis.z);
n = 0;
}
n++;
*/
FusionVector3 calibratedMagnetometer = FusionCalibrationMagnetic(uncalibratedMagnetometer, FUSION_ROTATION_MATRIX_IDENTITY, hardIronBias);
// Update gyroscope bias correction algorithm
calibratedGyroscope = FusionBiasUpdate(&fusionBias, calibratedGyroscope);
int64_t time_since_boot = esp_timer_get_time();
double time = (time_since_boot - last_time) / 1000000.;
last_time = time_since_boot;
// Update AHRS algorithm
FusionAhrsUpdate(&fusionAhrs, calibratedGyroscope, calibratedAccelerometer, calibratedMagnetometer, time);
// Print Euler angles
FusionEulerAngles eulerAngles = FusionQuaternionToEulerAngles(FusionAhrsGetQuaternion(&fusionAhrs));
//Compute Velocity and Posiiton
FusionVector3 acc = FusionAhrsGetEarthAcceleration(&fusionAhrs);
FusionVector3 at = FusionVectorMultiplyScalar(acc, time);
velocity = FusionVectorAdd(velocity, at);
FusionVector3 att = FusionVectorMultiplyScalar(at, time);
FusionVector3 att2 = FusionVectorMultiplyScalar(att, 0.5f);
position = FusionVectorAdd(position, att2);
FusionVector3 vt = FusionVectorMultiplyScalar(velocity, time);
position = FusionVectorAdd(position, vt);
if (n >= 10)
{
n = 0;
//printf("%f\n", time);
//printf("Roll = %0.1f, Pitch = %0.1f, Yaw = %0.1f\r\n", eulerAngles.angle.roll, eulerAngles.angle.pitch, eulerAngles.angle.yaw);
//printf("ax = %0.1f, ay = %0.1f, Yaw = %f\r\n", acc.axis.x, acc.axis.y, eulerAngles.angle.yaw);
//printf("vx = %f, vy = %f, Yaw = %f\r\n", velocity.axis.x, velocity.axis.y, eulerAngles.angle.yaw);
//printf("x = %f, y = %f, Yaw = %f\r\n", position.axis.x, position.axis.y, eulerAngles.angle.yaw);
printf("%f;%f;%f\n", position.axis.x, position.axis.y, eulerAngles.angle.yaw);
}
n++;
}
| [
"charles.villard@epita.fr"
] | charles.villard@epita.fr |
dc68f83be378bf65a1de72158507a195f660c23e | 520b75c144414d2af5a655e592fa65787ee89aaa | /AOJ/Volume05/0550.cpp | 26404f4270224b3a60285f828e3b9584e54a9ff9 | [] | no_license | arrows-1011/CPro | 4ac069683c672ba685534444412aa2e28026879d | 2e1a9242b2433851f495468e455ee854a8c4dac7 | refs/heads/master | 2020-04-12T09:36:40.846130 | 2017-06-10T08:02:10 | 2017-06-10T08:02:10 | 46,426,455 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 786 | cpp | #include <bits/stdc++.h>
using namespace std;
#define INF (1e9)
int main()
{
int N;
cin >> N;
vector<int> a(N);
for (int i = 0; i < N-1; i++) {
cin >> a[i];
}
int dp[2][5010][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 5010; j++) {
for (int k = 0; k < 2; k++) {
dp[i][j][k] = INF;
}
}
}
dp[0][0][0] = 0;
for (int i = 0; i < N; i++) {
int curr = (i & 1), next = (~i & 1);
for (int j = 0; j <= N/2; j++) {
dp[next][j+1][0] = min(dp[curr][j][0], dp[curr][j][1] + a[i]);
dp[next][j][1] = min(dp[curr][j][1], dp[curr][j][0] + a[i]);
}
dp[curr][0][0] = INF;
}
cout << dp[N%2][N/2][0] << endl;
return 0;
}
| [
"s1210207@gmail.com"
] | s1210207@gmail.com |
4e8ff2d4a80de7e6857819bc3d5fca42de105555 | 08cf0615f2636a14ce9de45de926ccc928dee8b7 | /GlacierFormats/src/PrimRenderPrimitive.cpp | d36f550eeed6280ef40c350f967dc7a378ae456f | [
"MIT"
] | permissive | pawREP/GlacierFormats | 9eee9870997fc6e89abe9a15b5f6eb68486decff | 9eece4541d863e288fc950087c4f6ec111258fe9 | refs/heads/master | 2022-04-24T07:37:16.558037 | 2020-04-21T21:05:14 | 2020-04-21T21:05:14 | 238,701,566 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,466 | cpp | #include <type_traits>
#include <functional>
#include "PrimRenderPrimitive.h"
#include "BinaryReader.hpp"
#include "PrimSerializationTypes.h"
#include "PrimBoundingBox.h"
#include "PrimReusableRecord.h"
#include "PrimRenderPrimitiveSerialization.h"
#include "PrimRenderPrimitiveBuilder.h"
using namespace GlacierFormats;
ZRenderPrimitive::ZRenderPrimitive() {
}
ZRenderPrimitive::ZRenderPrimitive(ZRenderPrimitive&& src) {
remnant = src.remnant;
vertex_buffer = std::move(src.vertex_buffer);
index_buffer = std::move(src.index_buffer);
vertex_data = std::move(src.vertex_data);
bone_weight_buffer = std::move(src.bone_weight_buffer);
vertex_colors = std::move(src.vertex_colors);
collision_data = std::move(src.collision_data);
cloth_data = std::move(src.cloth_data);
bone_info = std::move(src.bone_info);
bone_indices = std::move(src.bone_indices);
}
uint32_t ZRenderPrimitive::serialize(BinaryWriter* bw, std::unordered_map<RecordKey, uint64_t>& buffer_record) const {
RenderPrimitiveSerializer serializer;
return serializer.serialize(bw, this, buffer_record);
}
bool ZRenderPrimitive::isWeightedMesh() const {
return bone_weight_buffer != nullptr;
}
[[nodiscard]] std::string ZRenderPrimitive::name() const noexcept {
//TODO: Replace this with a real hash function or an actual name
//TODO: Experiments show that some submeshes share the same vertex_buffer => same hash. Not good!
size_t hash = 0;
for (const auto& v : *vertex_buffer)
for (const auto& c : v)
hash ^= std::hash<float>{}(c);
std::stringstream ss;
ss << std::hex;
ss << std::uppercase;
ss << std::setfill('0');
ss << "mat_" << std::setw(2) << remnant.material_id;
ss << "_lod_" << std::setw(2) << static_cast<int>(remnant.lod_mask);
ss << "_" << std::setw(8) << static_cast<int>(hash);
return ss.str();
}
[[nodiscard]] int ZRenderPrimitive::materialId() const noexcept
{
return remnant.material_id;
}
[[nodiscard]] size_t ZRenderPrimitive::vertexCount() const
{
return vertex_buffer->size();
}
[[nodiscard]] std::vector<float> ZRenderPrimitive::getVertexBuffer() const
{
return vertex_buffer->getCanonicalForm();
}
[[nodiscard]] std::vector<unsigned short> ZRenderPrimitive::getIndexBuffer() const
{
return index_buffer->getCanonicalForm();
}
[[nodiscard]] std::vector<float> ZRenderPrimitive::getNormals() const
{
return vertex_data->getNormals();
}
std::vector<float> GlacierFormats::ZRenderPrimitive::getTangents() const {
return vertex_data->getTangents();
}
[[nodiscard]] std::vector<float> ZRenderPrimitive::getUVs() const
{
return vertex_data->getUVs();
}
[[nodiscard]] std::vector<IMesh::VertexWeight> ZRenderPrimitive::getBoneWeights() const
{
if (!isWeightedMesh())
return std::vector<IMesh::VertexWeight>();
return bone_weight_buffer->getCanonicalForm();
}
void ZRenderPrimitive::setVertexBuffer(const std::vector<float>& vertex_buffer_) {
vertex_buffer = std::make_unique<VertexBuffer>(vertex_buffer_);
}
void ZRenderPrimitive::setIndexBuffer(const std::vector<unsigned short>& index_buffer_) {
index_buffer = std::make_unique<IndexBuffer>(index_buffer_);
}
void ZRenderPrimitive::setNormals(const std::vector<float>& normal_buffer_) {
//TODO: Having some of the per vertex data in a separate structure like in the serialized PRIM
//layout seems overly cumbersome and more prone to errors and corruption due to user error
//Doesn't seem like it's worth the trouble and performance benefits.
//Refactor this and shift the complexity to (de)serialization.
if (!vertex_data)
vertex_data = std::make_unique<VertexDataBuffer>();
vertex_data->setNormals(normal_buffer_);
}
void GlacierFormats::ZRenderPrimitive::setTangents(const std::vector<float>& tangents_) {
if (!vertex_data)
vertex_data = std::make_unique<VertexDataBuffer>();
vertex_data->setTangents(tangents_);
}
void ZRenderPrimitive::setUVs(const std::vector<float>& uvs) {
if (!vertex_data)
vertex_data = std::make_unique<VertexDataBuffer>();
vertex_data->setUVs(uvs);
}
void ZRenderPrimitive::setBoneWeight(const std::vector<VertexWeight>& weights) {
if (!bone_weight_buffer)
bone_weight_buffer = std::make_unique<VertexWeightBuffer>();
bone_weight_buffer->setFromCanonicalForm(vertex_buffer->size(), weights);
}
void ZRenderPrimitive::setName(const std::string& name) {
//Nothing to do here. name is derived via hashing of members.
}
| [
"pawREP@users.noreply.github.com"
] | pawREP@users.noreply.github.com |
12acf0ab4a3c23a9eaa24f0edb0997325cd72548 | a8d5bc672d965c7f06f6f90932748b0c0e4a1fb0 | /src/target/core/sw/sw_logic.cc | 6c1602a0c7dc3975765cc3458d11a83cbcaa74d0 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | FPGeh/cascade | 2b9f7bc16a82352586d0a134f9f54f5719d84753 | a51b778114b0fedf7037ee7ad765a73e2a479426 | refs/heads/master | 2020-04-26T06:02:57.035139 | 2019-02-21T06:36:03 | 2019-02-21T06:36:03 | 173,352,875 | 2 | 0 | null | 2019-03-01T18:54:18 | 2019-03-01T18:54:17 | null | UTF-8 | C++ | false | false | 14,250 | cc | // Copyright 2017-2019 VMware, Inc.
// SPDX-License-Identifier: BSD-2-Clause
//
// The BSD-2 license (the License) set forth below applies to all parts of the
// Cascade project. You may not use this file except in compliance with the
// License.
//
// BSD-2 License
//
// 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 "src/target/core/sw/sw_logic.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include "src/target/core/sw/monitor.h"
#include "src/target/input.h"
#include "src/target/interface.h"
#include "src/verilog/analyze/evaluate.h"
#include "src/verilog/analyze/module_info.h"
#include "src/verilog/analyze/printf.h"
#include "src/verilog/analyze/resolve.h"
#include "src/verilog/ast/ast.h"
#include "src/verilog/print/text/text_printer.h"
using namespace std;
namespace cascade {
SwLogic::SwLogic(Interface* interface, ModuleDeclaration* md) : Logic(interface), Visitor() {
// Record pointer to source code
src_ = md;
// Initialize monitors
for (auto i = src_->begin_items(), ie = src_->end_items(); i != ie; ++i) {
Monitor().init(*i);
}
// Initial provision for update_pool_:
update_pool_.resize(1);
// Schedule always constructs and continuous assigns.
for (auto i = src_->begin_items(), ie = src_->end_items(); i != ie; ++i) {
if ((*i)->is(Node::Tag::always_construct) || (*i)->is(Node::Tag::continuous_assign)) {
schedule_now(*i);
}
}
// By default, silent mode is off
silent_ = false;
}
SwLogic::~SwLogic() {
delete src_;
}
SwLogic& SwLogic::set_read(const Identifier* id, VId vid) {
if (vid >= reads_.size()) {
reads_.resize(vid+1, nullptr);
}
reads_[vid] = id;
return *this;
}
SwLogic& SwLogic::set_write(const Identifier* id, VId vid) {
writes_.push_back(make_pair(id, vid));
return *this;
}
SwLogic& SwLogic::set_state(const Identifier* id, VId vid) {
state_.insert(make_pair(vid, id));
return *this;
}
State* SwLogic::get_state() {
auto* s = new State();
for (const auto& sv : state_) {
s->insert(sv.first, Evaluate().get_array_value(sv.second));
}
return s;
}
void SwLogic::set_state(const State* s) {
for (const auto& sv : state_) {
const auto itr = s->find(sv.first);
if (itr != s->end()) {
Evaluate().assign_array_value(sv.second, itr->second);
notify(sv.second);
}
}
silent_evaluate();
}
Input* SwLogic::get_input() {
auto* i = new Input();
for (size_t v = 0, ve = reads_.size(); v < ve; ++v) {
const auto* id = reads_[v];
if (id == nullptr) {
continue;
}
i->insert(v, Evaluate().get_value(id));
}
return i;
}
void SwLogic::set_input(const Input* i) {
for (size_t v = 0, ve = reads_.size(); v < ve; ++v) {
const auto* id = reads_[v];
if (id == nullptr) {
continue;
}
const auto itr = i->find(v);
if (itr != i->end()) {
Evaluate().assign_value(id, itr->second);
}
notify(id);
}
silent_evaluate();
}
void SwLogic::finalize() {
// Schedule initial constructs
for (auto i = src_->begin_items(), ie = src_->end_items(); i != ie; ++i) {
if ((*i)->is(Node::Tag::initial_construct)) {
schedule_now(*i);
}
}
}
void SwLogic::read(VId vid, const Bits* b) {
const auto* id = reads_[vid];
Evaluate().assign_value(id, *b);
notify(id);
}
void SwLogic::evaluate() {
// This is a while loop. Active events can generate new active events.
there_were_tasks_ = false;
while (!active_.empty()) {
auto* e = active_.back();
active_.pop_back();
const_cast<Node*>(e)->set_flag<1>(false);
schedule_now(e);
}
for (auto& o : writes_) {
interface()->write(o.second, &Evaluate().get_value(o.first));
}
}
bool SwLogic::there_are_updates() const {
return !updates_.empty();
}
void SwLogic::update() {
// This is a for loop. Updates happen simultaneously
for (size_t i = 0, ie = updates_.size(); i < ie; ++i) {
const auto& val = update_pool_[i];
Evaluate().assign_value(get<0>(updates_[i]), get<1>(updates_[i]), get<2>(updates_[i]), get<3>(updates_[i]), val);
notify(get<0>(updates_[i]));
}
updates_.clear();
// This is while loop. Active events can generate new active events.
there_were_tasks_ = false;
while (!active_.empty()) {
auto* e = active_.back();
active_.pop_back();
const_cast<Node*>(e)->set_flag<1>(false);
schedule_now(e);
}
for (auto& o : writes_) {
interface()->write(o.second, &Evaluate().get_value(o.first));
}
}
bool SwLogic::there_were_tasks() const {
return there_were_tasks_;
}
void SwLogic::schedule_now(const Node* n) {
n->accept(this);
}
void SwLogic::schedule_active(const Node* n) {
if (!n->get_flag<1>()) {
active_.push_back(n);
const_cast<Node*>(n)->set_flag<1>(true);
}
}
void SwLogic::notify(const Node* n) {
if (n->is(Node::Tag::identifier)) {
for (auto* m : static_cast<const Identifier*>(n)->monitor_) {
schedule_active(m);
}
return;
}
const auto* p = n->get_parent();
if (p->is(Node::Tag::case_item)) {
schedule_active(p->get_parent());
} else if (!p->is(Node::Tag::initial_construct)) {
schedule_active(p);
}
}
void SwLogic::silent_evaluate() {
// Turn on silent mode and drain the active queue
silent_ = true;
while (!active_.empty()) {
auto* e = active_.back();
active_.pop_back();
const_cast<Node*>(e)->set_flag<1>(false);
schedule_now(e);
}
silent_ = false;
}
uint8_t& SwLogic::get_state(const Statement* s) {
return const_cast<Statement*>(s)->ctrl_;
}
void SwLogic::visit(const Event* e) {
// TODO(eschkufz) Support for complex expressions here
assert(e->get_expr()->is(Node::Tag::identifier));
const auto* id = static_cast<const Identifier*>(e->get_expr());
const auto* r = Resolve().get_resolution(id);
if (e->get_type() != Event::Type::NEGEDGE && Evaluate().get_value(r).to_bool()) {
notify(e);
} else if (e->get_type() != Event::Type::POSEDGE && !Evaluate().get_value(r).to_bool()) {
notify(e);
}
}
void SwLogic::visit(const AlwaysConstruct* ac) {
schedule_now(ac->get_stmt());
}
void SwLogic::visit(const InitialConstruct* ic) {
const auto* ign = ic->get_attrs()->get<String>("__ignore");
if (ign == nullptr || !ign->eq("true")) {
schedule_active(ic->get_stmt());
}
}
void SwLogic::visit(const ContinuousAssign* ca) {
// TODO(eschkufz) Support for timing control
assert(ca->is_null_ctrl());
schedule_now(ca->get_assign());
}
void SwLogic::visit(const BlockingAssign* ba) {
// TODO(eschkufz) Support for timing control
assert(ba->is_null_ctrl());
schedule_now(ba->get_assign());
notify(ba);
}
void SwLogic::visit(const NonblockingAssign* na) {
// TODO(eschkufz) Support for timing control
assert(na->is_null_ctrl());
if (!silent_) {
const auto* r = Resolve().get_resolution(na->get_assign()->get_lhs());
assert(r != nullptr);
const auto target = Evaluate().dereference(r, na->get_assign()->get_lhs());
const auto& res = Evaluate().get_value(na->get_assign()->get_rhs());
const auto idx = updates_.size();
if (idx >= update_pool_.size()) {
update_pool_.resize(2*update_pool_.size());
}
updates_.push_back(make_tuple(r, get<0>(target), get<1>(target), get<2>(target)));
update_pool_[idx] = res;
}
notify(na);
}
void SwLogic::visit(const ParBlock* pb) {
auto& state = get_state(pb);
assert(state < 255);
switch (state) {
case 0:
state = pb->size_stmts();
for (auto i = pb->begin_stmts(), ie = pb->end_stmts(); i != ie; ++i) {
schedule_now(*i);
}
break;
default:
if (--state == 0) {
notify(pb);
}
break;
}
}
void SwLogic::visit(const SeqBlock* sb) {
auto& state = get_state(sb);
assert(state < 255);
if (state < sb->size_stmts()) {
auto* item = sb->get_stmts(state++);
schedule_now(item);
} else {
state = 0;
notify(sb);
}
}
void SwLogic::visit(const CaseStatement* cs) {
auto& state = get_state(cs);
if (state == 0) {
state = 1;
const auto s = Evaluate().get_value(cs->get_cond()).to_int();
for (auto i = cs->begin_items(), ie = cs->end_items(); i != ie; ++i) {
for (auto j = (*i)->begin_exprs(), je = (*i)->end_exprs(); j != je; ++j) {
const auto c = Evaluate().get_value(*j).to_int();
if (s == c) {
schedule_now((*i)->get_stmt());
return;
}
}
if ((*i)->empty_exprs()) {
schedule_now((*i)->get_stmt());
return;
}
}
// Control should never reach here
assert(false);
} else {
state = 0;
notify(cs);
}
}
void SwLogic::visit(const ConditionalStatement* cs) {
auto& state = get_state(cs);
if (state == 0) {
state = 1;
if (Evaluate().get_value(cs->get_if()).to_bool()) {
schedule_now(cs->get_then());
} else {
schedule_now(cs->get_else());
}
} else {
state = 0;
notify(cs);
}
}
void SwLogic::visit(const ForStatement* fs) {
auto& state = get_state(fs);
switch (state) {
case 0:
++state;
schedule_now(fs->get_init());
// Fallthrough
case 1:
if (!Evaluate().get_value(fs->get_cond()).to_bool()) {
state = 0;
notify(fs);
return;
}
state = 2;
schedule_now(fs->get_stmt());
break;
default:
state = 1;
schedule_now(fs->get_update());
schedule_now(fs);
break;
}
}
void SwLogic::visit(const RepeatStatement* rs) {
auto& state = get_state(rs);
switch (state) {
case 0:
state = Evaluate().get_value(rs->get_cond()).to_int() + 1;
// Fallthrough ...
default:
if (--state == 0) {
notify(rs);
} else {
schedule_now(rs->get_stmt());
}
break;
}
}
void SwLogic::visit(const WhileStatement* ws) {
if (!Evaluate().get_value(ws->get_cond()).to_bool()) {
notify(ws);
return;
}
schedule_now(ws->get_stmt());
}
void SwLogic::visit(const TimingControlStatement* tcs) {
auto& state = get_state(tcs);
switch (state) {
case 0:
state = 1;
// Wait on control
break;
case 1:
state = 2;
schedule_now(tcs->get_stmt());
break;
default:
state = 0;
notify(tcs);
break;
}
}
void SwLogic::visit(const DisplayStatement* ds) {
if (!silent_) {
interface()->display(Printf().format(ds->begin_args(), ds->end_args()));
there_were_tasks_ = true;
}
notify(ds);
}
void SwLogic::visit(const ErrorStatement* es) {
if (!silent_) {
interface()->error(Printf().format(es->begin_args(), es->end_args()));
there_were_tasks_ = true;
}
notify(es);
}
void SwLogic::visit(const FatalStatement* fs) {
if (!silent_) {
interface()->fatal(Evaluate().get_value(fs->get_arg()).to_int(), Printf().format(fs->begin_args(), fs->end_args()));
there_were_tasks_ = true;
}
notify(fs);
}
void SwLogic::visit(const FinishStatement* fs) {
if (!silent_) {
interface()->finish(Evaluate().get_value(fs->get_arg()).to_int());
there_were_tasks_ = true;
}
notify(fs);
}
void SwLogic::visit(const InfoStatement* is) {
if (!silent_) {
interface()->info(Printf().format(is->begin_args(), is->end_args()));
there_were_tasks_ = true;
}
notify(is);
}
void SwLogic::visit(const RestartStatement* rs) {
if (!silent_) {
interface()->restart(rs->get_arg()->get_readable_val());
there_were_tasks_ = true;
}
notify(rs);
}
void SwLogic::visit(const RetargetStatement* rs) {
if (!silent_) {
interface()->retarget(rs->get_arg()->get_readable_val());
there_were_tasks_ = true;
}
notify(rs);
}
void SwLogic::visit(const SaveStatement* ss) {
if (!silent_) {
interface()->save(ss->get_arg()->get_readable_val());
there_were_tasks_ = true;
}
notify(ss);
}
void SwLogic::visit(const WarningStatement* ws) {
if (!silent_) {
interface()->warning(Printf().format(ws->begin_args(), ws->end_args()));
there_were_tasks_ = true;
}
notify(ws);
}
void SwLogic::visit(const WriteStatement* ws) {
if (!silent_) {
interface()->write(Printf().format(ws->begin_args(), ws->end_args()));
there_were_tasks_ = true;
}
notify(ws);
}
void SwLogic::visit(const WaitStatement* ws) {
auto& state = get_state(ws);
if (state == 0) {
if (!Evaluate().get_value(ws->get_cond()).to_bool()) {
return;
}
state = 1;
schedule_now(ws->get_stmt());
} else {
state = 0;
notify(ws);
}
}
void SwLogic::visit(const DelayControl* dc) {
// NOTE: Unsynthesizable verilog
assert(false);
(void) dc;
}
void SwLogic::visit(const EventControl* ec) {
notify(ec);
}
void SwLogic::visit(const VariableAssign* va) {
const auto& res = Evaluate().get_value(va->get_rhs());
Evaluate().assign_value(va->get_lhs(), res);
notify(Resolve().get_resolution(va->get_lhs()));
}
void SwLogic::log(const string& op, const Node* n) {
TextPrinter(cout) << "[" << src_->get_id() << "] " << op << " " << n << "\n";
}
} // namespace cascade
| [
"eric.schkufza@gmail.com"
] | eric.schkufza@gmail.com |
96f3c9f8124f6a4c586e3cabf01cb01eb1762c4f | af013a78b8a4bc750cf0ce293262e236775697a1 | /c++/SeaLevel_ConnectedComponents.hh | 948e6f781a22c22fd674cb04c5a946faf7a3cad7 | [] | no_license | sebhinck/LakeCC | 34affb85dc9e40c0af65211b1c35102f1eeab122 | 6d525391ca95ed5762ad87eed258de01c3b3b255 | refs/heads/master | 2020-04-02T15:30:06.311583 | 2019-11-08T13:41:02 | 2019-11-08T13:41:02 | 154,570,002 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 967 | hh | #ifndef _SEALEVEL_CONNECTEDCOMPONENTS_H_
#define _SEALEVEL_CONNECTEDCOMPONENTS_H_
#include <vector>
#include "FillingAlg_ConnectedComponents.hh"
class SeaLevelCC : public FillingAlgCC {
public:
SeaLevelCC(unsigned int n_rows,
unsigned int n_cols,
double* topo,
double* thk,
double* floatation_level,
double* mask_run,
double drho,
double ice_free_thickness);
~SeaLevelCC();
void fill2SeaLevel(double SeaLevel);
private:
virtual bool SinkCond(unsigned int r, unsigned int c);
virtual void labelMap(double Level,
unsigned int run_number,
std::vector<unsigned int> &rows,
std::vector<unsigned int> &columns,
std::vector<unsigned int> &parents,
std::vector<unsigned int> &lengths,
std::vector<bool> &isOpen);
};
#endif
| [
"sebastian.hinck@awi.de"
] | sebastian.hinck@awi.de |
51b7171faca285148fb4300ef1930f17d9b67f54 | 497ee62b8e9e69624d6865c363a7e49fe5d47c5c | /Uri/for01.cpp | 48d4ed8f97d984fc2a4fb62726c6ee3854426596 | [] | no_license | Dygookada/MeusCodigos | 450ab50d9e743ac6fa2a12ab3fef268dcb8b7b30 | 25b56327f2c75897c739fdabe4ff678775b95720 | refs/heads/master | 2022-06-26T02:11:51.909412 | 2022-05-12T22:24:47 | 2022-05-12T22:24:47 | 246,394,200 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | #include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int bombom,meu,erros,certos;
while( cin>>bombom && bombom!=0)
{
erros=0,certos=0;
for( int i=0; certos<bombom; i++)
{
for( int j=0; j<3; j++)
{
scanf("*%d",&meu);
if(meu==j)
{
certos++;
}
}
erros++;
printf("%d##",erros);
}
printf("%d\n",erros);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
6e6631be22bd42388e851fdf871b783c2d3b5fdc | c3081f8f60de5d36883b38ab789cfc7ad0bc3902 | /Atom/if_else.cpp | eecccd9c7e3f6ab9739f0652de38b97637329ebf | [] | no_license | Arrygon/atomWin7 | 68fe7e799eb1e47a32b8ce9ba354687407c309cc | 10aa418b5cf12640934f3d79bd0e09063e11a663 | refs/heads/master | 2020-03-18T17:53:57.804007 | 2018-06-03T20:36:55 | 2018-06-03T20:36:55 | 135,058,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | cpp | #include <iostream>
#include <windows.h>
using namespace std;
int main(){
system("color 02");
short int a,b,c;
do {
cout << endl << "How long are you programming ? ";
cin >> a;
cout << "Whats the time ? (24h) ";
cin >> b;
if(a < 6 && a >= 0)
if(b <= 4 && b >= 0 )
cout << "You should go to sleep." << endl;
else
cout << "You can do more programing." << endl;
else
cout << "You should stop programing for today." << endl;
}while (a !=100 || b != 100);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
0e4c5f65ccca506a2464c82c2f901e0a3bda51a6 | ca0f40ce5b93083d83ec26f473a3bad432fa173c | /src/server/shared/Dynamic/HashNamespace.h | 5fd1b8eb7d5f7fa8dbcc5860d44a6c4d94748505 | [] | no_license | rynnokung/SunWellCore | 74d48ebfe2b688dd3cacefc2af3dc6203953aeac | 0f464e1847f733fb979116e1bc7b052b2cab14da | refs/heads/master | 2021-01-21T05:23:19.518555 | 2016-07-10T19:59:57 | 2016-07-10T19:59:57 | 58,862,729 | 3 | 0 | null | 2016-07-10T19:59:58 | 2016-05-15T13:22:39 | C++ | UTF-8 | C++ | false | false | 3,089 | h | /*
* Copyright (C)
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITY_HASH_NAMESPACE_H
#define TRINITY_HASH_NAMESPACE_H
#include "Define.h"
#if COMPILER_HAS_CPP11_SUPPORT
# define HASH_NAMESPACE_START namespace std {
# define HASH_NAMESPACE_END }
#elif defined(_STLPORT_VERSION)
# define HASH_NAMESPACE_START namespace std {
# define HASH_NAMESPACE_END }
#elif COMPILER == COMPILER_MICROSOFT && _MSC_VER >= 1600 // VS100
# define HASH_NAMESPACE_START namespace std {
# define HASH_NAMESPACE_END }
#elif COMPILER == COMPILER_MICROSOFT && _MSC_VER >= 1500 && _HAS_TR1
# define HASH_NAMESPACE_START namespace std { namespace tr1 {
# define HASH_NAMESPACE_END } }
#elif COMPILER == COMPILER_MICROSOFT && _MSC_VER >= 1300
# define HASH_NAMESPACE_START namespace stdext {
# define HASH_NAMESPACE_END }
#if !_HAS_TRADITIONAL_STL
#ifndef HASH_NAMESPACE
#define HASH_NAMESPACE
#else
// can be not used by some platforms, so provide fake forward
HASH_NAMESPACE_START
template<class K>
class hash
{
public:
size_t operator() (K const&);
};
HASH_NAMESPACE_END
#endif
#endif
#elif COMPILER == COMPILER_INTEL
# define HASH_NAMESPACE_START namespace std {
# define HASH_NAMESPACE_END }
#elif COMPILER == COMPILER_GNU && defined(__clang__) && defined(_LIBCPP_VERSION)
# define HASH_NAMESPACE_START namespace std {
# define HASH_NAMESPACE_END }
#elif COMPILER == COMPILER_GNU && GCC_VERSION > 40200
# define HASH_NAMESPACE_START namespace std { namespace tr1 {
# define HASH_NAMESPACE_END } }
#elif COMPILER == COMPILER_GNU && GCC_VERSION >= 30000
# define HASH_NAMESPACE_START namespace __gnu_cxx {
# define HASH_NAMESPACE_END }
#include <ext/hash_fun.h>
#include <string>
HASH_NAMESPACE_START
template<>
class hash<unsigned long long>
{
public:
size_t operator()(const unsigned long long &__x) const { return (size_t)__x; }
};
template<typename T>
class hash<T *>
{
public:
size_t operator()(T * const &__x) const { return (size_t)__x; }
};
template<> struct hash<std::string>
{
size_t operator()(const std::string &__x) const
{
return hash<char const*>()(__x.c_str());
}
};
HASH_NAMESPACE_END
#else
# define HASH_NAMESPACE_START namespace std {
# define HASH_NAMESPACE_END }
#endif
#if COMPILER != COMPILER_MICROSOFT
// Visual Studio use non standard hash calculation function, so provide fake forward for other
HASH_NAMESPACE_START
template<class K>
size_t hash_value(K const&);
HASH_NAMESPACE_END
#endif
#endif
| [
"phil19-94@hotmail.fr"
] | phil19-94@hotmail.fr |
bd36adf97c31eeead43b60faf8aac2aa98c29a8a | 15caeb6823ab5dc57aca0b10437400a05e9fe265 | /month/March challenge/Xentask.cpp | 966fdcac16aebe3719f3254700c645fa68170446 | [] | no_license | jaskirat1208/codechef | d444e77bc6d68c8c6cbd86cc9ef6a409e6274234 | 15496043c45a43508f1d52d5aae6f21a074d596f | refs/heads/master | 2021-01-20T06:33:00.581279 | 2017-05-20T16:49:08 | 2017-05-20T16:49:08 | 83,876,266 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 553 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main(int argc, char const *argv[])
{
int t;
cin>>t;
while(t--){
int n,sum1=0,sum2=0;
cin>>n;
int N=n;
while(n>0){
int x,y;
cin>>x;
if(n==1){
sum1+=x;
break;
}
cin>>y;
sum1+=x;
sum2+=y;
n=n-2;
}
while(N>0){
int x,y;
cin>>x;
if(N==1){
sum2+=x;
break;
}
cin>>y;
sum1+=y;
sum2+=x;
N=N-2;
}
if(sum1<sum2) cout<<sum1<<endl;
else cout<<sum2<<endl;
// cout<<sum1<<" "<<sum2<<endl;
}
return 0;
} | [
"jaskiratsingh1208@gmail.com"
] | jaskiratsingh1208@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.