hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a8fe3b55761f362b0821ccd9baef02f66e6062de | 2,176 | cpp | C++ | cpp/leetcode/ColorBorder.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/ColorBorder.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/ColorBorder.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | //Leetcode Problem No 1034. Coloring A Border
//Solution written by Xuqiang Fang on 14 May, 2019
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
using namespace std;
class Solution {
public:
vector<vector<int>> colorBorder(vector<vector<int>>& grid, int r0, int c0, int color) {
if(grid[r0][c0] == color){
return grid;
}
const int m = grid.size();
const int n = grid[0].size();
int old = grid[r0][c0];
dfs(grid, r0, c0, old, color, m, n);
vector<vector<int>> ans;
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(grid[i][j] == -1){
if(i==0 || j==0 || i==m-1 || j==n-1 || inborder(grid, i, j, old)){
ans.push_back({i,j});
}
}
}
}
for(auto& a : ans){
grid[a[0]][a[1]] = color;
}
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(grid[i][j] == -1){
grid[i][j] = old;
}
}
}
return grid;
}
private:
vector<vector<int>> dirs{{0,1},{1,0},{0,-1},{-1,0}};
void dfs(vector<vector<int>>& grid, int r0, int c0, int old, int color, int m, int n){
grid[r0][c0] = -1;
for(auto& d : dirs){
int r = r0 + d[0];
int c = c0 + d[1];
if(r>=0&&r<m&&c>=0&&c<n&&grid[r][c]==old){
dfs(grid, r, c, old, color, m, n);
}
}
}
bool inborder(vector<vector<int>>& grid, int i, int j, int old){
for(auto& d : dirs){
int r = i + d[0];
int c = j + d[1];
if(grid[r][c] != old && grid[r][c] != -1)
return true;
}
return false;
}
};
int main(){
Solution s;
vector<vector<int>> grid{{1,1,1},{1,1,1},{1,1,1}};
auto ans = s.colorBorder(grid, 1, 1, 2);
for(auto a : ans){
for(auto b : a){
cout << b << " ";
}
cout << endl;
}
return 0;
}
| 26.536585 | 91 | 0.433364 | danyfang |
a8fe59bc8fe0206488169b2f9639aa2ab4157d20 | 2,530 | cpp | C++ | src/CoreLib/LogSystem/Logger.cpp | AntoineJT/BurgWar | 8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8 | [
"MIT"
] | 1 | 2021-11-13T11:58:07.000Z | 2021-11-13T11:58:07.000Z | src/CoreLib/LogSystem/Logger.cpp | AntoineJT/BurgWar | 8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8 | [
"MIT"
] | null | null | null | src/CoreLib/LogSystem/Logger.cpp | AntoineJT/BurgWar | 8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8 | [
"MIT"
] | null | null | null | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#include <CoreLib/LogSystem/Logger.hpp>
#include <CoreLib/BurgApp.hpp>
#include <CoreLib/LogSystem/LogSink.hpp>
#include <array>
#include <charconv>
#include <sstream>
namespace bw
{
void Logger::Log(const LogContext& context, std::string content) const
{
OverrideContent(context, content);
LogRaw(context, content);
if (m_logParent)
m_logParent->LogRaw(context, content);
}
void Logger::LogRaw(const LogContext& context, std::string_view content) const
{
for (auto& sinkPtr : m_sinks)
sinkPtr->Write(context, content);
}
bool Logger::ShouldLog(const LogContext& context) const
{
if (context.level < m_minimumLogLevel)
return false;
if (m_logParent && !m_logParent->ShouldLog(context))
return false;
return true;
}
LogContext* Logger::NewContext(Nz::MemoryPool& pool) const
{
return AllocateContext<LogContext>(pool);
}
void Logger::InitializeContext(LogContext& context) const
{
context.elapsedTime = m_app.GetAppTime() / 1000.f;
context.side = GetSide();
}
void Logger::OverrideContent(const LogContext& context, std::string& content) const
{
#ifdef _MSC_VER
auto TimePart = [](float elapsedTime) -> std::string
{
std::array<char, 40> buffer;
buffer[0] = '[';
auto result = std::to_chars(buffer.data() + 1, buffer.data() + buffer.size() - 2, elapsedTime, std::chars_format::fixed, 3);
assert(result.ec == std::errc{});
*result.ptr = ']';
return std::string(buffer.data(), result.ptr - buffer.data() + 1);
};
#else
// libstdc++ doesn't support std::to_chars for floating-point values :(
auto TimePart = [](float elapsedTime) -> std::string
{
std::stringstream ss;
ss.setf(std::ios::fixed, std::ios::floatfield);
ss.precision(3);
ss << '[';
ss << elapsedTime;
ss << ']';
return ss.str();
};
#endif
switch (context.side)
{
case LogSide::Irrelevant:
content = TimePart(context.elapsedTime) + content;
break;
case LogSide::Client:
content = TimePart(context.elapsedTime) + " [C] " + content;
break;
case LogSide::Editor:
content = TimePart(context.elapsedTime) + " [E] " + content;
break;
case LogSide::Server:
content = TimePart(context.elapsedTime) + " [S] " + content;
break;
default:
break;
}
}
void Logger::FreeContext(LogContext* context) const
{
m_contextPool.Delete(context);
}
}
| 23 | 127 | 0.673913 | AntoineJT |
a8ff96576a6bf235560f1d82a684460cd2409946 | 3,279 | cpp | C++ | components/script/core/sources/script_library_manager.cpp | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/script/core/sources/script_library_manager.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/script/core/sources/script_library_manager.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #include "shared.h"
using namespace script;
namespace
{
/*
Константы
*/
const char* COMPONENTS_MASK = "script.binds.*"; //маска имён компонентов скриптовых библиотек
/*
Реализация менеджера библиотек
*/
class LibraryManagerImpl
{
public:
typedef LibraryManager::BindHandler BindHandler;
///Регистрация библиотеки
void RegisterLibrary (const char* name, const BindHandler& binder)
{
static const char* METHOD_NAME = "script::LibraryManager::RegisterLibrary";
//проверка корректности аргументов
if (!name)
throw xtl::make_null_argument_exception (METHOD_NAME, "name");
for (LibraryList::iterator iter=libraries.begin (), end=libraries.end (); iter!=end; ++iter)
if (iter->name == name)
throw xtl::make_argument_exception (METHOD_NAME, "name", name, "Library has already registered");
//добавление библиотеки
libraries.push_back (Library (name, binder));
}
///Отмена регистрации библиотеки
void UnregisterLibrary (const char* name)
{
if (!name)
return;
for (LibraryList::iterator iter=libraries.begin (), end=libraries.end (); iter!=end; ++iter)
if (iter->name == name)
{
libraries.erase (iter);
return;
}
}
///Отмена регистрации всех библиотек
void UnregisterAllLibraries ()
{
libraries.clear ();
}
///Биндинг библиотек
void BindLibraries (Environment& environment, const char* library_mask)
{
try
{
if (!library_mask)
throw xtl::make_null_argument_exception ("", "library_mask");
static common::ComponentLoader loader (COMPONENTS_MASK);
for (LibraryList::iterator iter=libraries.begin (), end=libraries.end (); iter!=end; ++iter)
if (common::wcmatch (iter->name.c_str (), library_mask))
iter->binder (environment);
}
catch (xtl::exception& exception)
{
exception.touch ("script::LibraryManager::BindLibraries");
throw;
}
}
private:
///Описание библиотеки
struct Library
{
stl::string name; //имя библиотеки
BindHandler binder; //функтор биндинга библиотеки
Library (const char* in_name, const BindHandler& in_binder) : name (in_name), binder (in_binder) {}
};
typedef stl::list<Library> LibraryList;
private:
LibraryList libraries; //библиотеки
};
typedef common::Singleton<LibraryManagerImpl> LibraryManagerSingleton;
}
/*
Врапперы над вызовами к LibraryManager
*/
void LibraryManager::RegisterLibrary (const char* name, const BindHandler& binder)
{
LibraryManagerSingleton::Instance ()->RegisterLibrary (name, binder);
}
void LibraryManager::UnregisterLibrary (const char* name)
{
LibraryManagerSingleton::Instance ()->UnregisterLibrary (name);
}
void LibraryManager::UnregisterAllLibraries ()
{
LibraryManagerSingleton::Instance ()->UnregisterAllLibraries ();
}
void LibraryManager::BindLibraries (Environment& environment, const char* library_mask)
{
LibraryManagerSingleton::Instance ()->BindLibraries (environment, library_mask);
}
| 26.02381 | 108 | 0.642269 | untgames |
a8ffc21781f7dd9c6cc48c1821e0f9f5ae1ebc29 | 662 | cpp | C++ | problems/letter-combinations-of-a-phone-number/src/Solution.cpp | bbackspace/leetcode | bc3f235fcd42c37800e6ef7eefab4c826d70f3d3 | [
"CC0-1.0"
] | null | null | null | problems/letter-combinations-of-a-phone-number/src/Solution.cpp | bbackspace/leetcode | bc3f235fcd42c37800e6ef7eefab4c826d70f3d3 | [
"CC0-1.0"
] | null | null | null | problems/letter-combinations-of-a-phone-number/src/Solution.cpp | bbackspace/leetcode | bc3f235fcd42c37800e6ef7eefab4c826d70f3d3 | [
"CC0-1.0"
] | null | null | null | class Solution {
const vector<string> keypad = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
string s;
vector<string> ans;
void comb(string &dig, int d) {
if (dig.length() == 0) {
return;
}
if (d == dig.length()) {
ans.push_back(s);
return;
}
for (auto &k : keypad[dig[d] - '0']) {
s.push_back(k);
comb(dig, d + 1);
s.pop_back();
}
}
public:
vector<string> letterCombinations(string digits) {
ans = vector<string>();
s = "";
comb(digits, 0);
return ans;
}
};
| 23.642857 | 101 | 0.432024 | bbackspace |
d100cc31b223afbda5fc9b7bcbbe8c3d2d20ec9e | 4,808 | cpp | C++ | NFIQ2/NFIQ2/NFIQ2Algorithm/src/features/OCLHistogramFeature.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | null | null | null | NFIQ2/NFIQ2/NFIQ2Algorithm/src/features/OCLHistogramFeature.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | null | null | null | NFIQ2/NFIQ2/NFIQ2Algorithm/src/features/OCLHistogramFeature.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | 1 | 2022-02-14T03:16:05.000Z | 2022-02-14T03:16:05.000Z | #include "OCLHistogramFeature.h"
#include "FeatureFunctions.h"
#include "include/NFIQException.h"
#include "include/Timer.hpp"
#include <sstream>
#if defined WINDOWS || defined WIN32
#include <windows.h>
#include <float.h>
#define isnan _isnan // re-define isnan
#else
#ifndef isnan
#define isnan(x) ((x) != (x))
#endif
#endif
using namespace NFIQ;
using namespace cv;
#define HISTOGRAM_FEATURES 1
OCLHistogramFeature::~OCLHistogramFeature()
{
}
std::list<NFIQ::QualityFeatureResult> OCLHistogramFeature::computeFeatureData(
const NFIQ::FingerprintImageData & fingerprintImage)
{
std::list<NFIQ::QualityFeatureResult> featureDataList;
Mat img;
// check if input image has 500 dpi
if (fingerprintImage.m_ImageDPI != NFIQ::e_ImageResolution_500dpi)
throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, "Only 500 dpi fingerprint images are supported!");
try
{
// get matrix from fingerprint image
img = Mat(fingerprintImage.m_ImageHeight, fingerprintImage.m_ImageWidth, CV_8UC1, (void*)fingerprintImage.data());
}
catch (cv::Exception & e)
{
std::stringstream ssErr;
ssErr << "Cannot get matrix from fingerprint image: " << e.what();
throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, ssErr.str());
}
// compute OCL
NFIQ::Timer timerOCL;
double timeOCL = 0.0;
std::vector<double>oclres;
try
{
timerOCL.startTimer();
// divide into blocks
for (int i = 0; i < img.rows; i += BS_OCL)
{
for (int j = 0; j < img.cols; j += BS_OCL)
{
unsigned int actualBS_X = ((img.cols - j) < BS_OCL) ? (img.cols - j) : BS_OCL;
unsigned int actualBS_Y = ((img.rows - i) < BS_OCL) ? (img.rows - i) : BS_OCL;
if (actualBS_X == BS_OCL && actualBS_Y == BS_OCL)
{
// only take blocks of full size
// ignore other blocks
// get current block
Mat bl_img = img(Rect(j, i, actualBS_X, actualBS_Y));
// get OCL value of current block
double bl_ocl = 0.0;
if (!getOCLValueOfBlock(bl_img, bl_ocl))
continue; // block is not used
oclres.push_back(bl_ocl);
}
}
}
#if HISTOGRAM_FEATURES
std::vector<double> histogramBins10;
histogramBins10.push_back(OCLPHISTLIMITS[0]);
histogramBins10.push_back(OCLPHISTLIMITS[1]);
histogramBins10.push_back(OCLPHISTLIMITS[2]);
histogramBins10.push_back(OCLPHISTLIMITS[3]);
histogramBins10.push_back(OCLPHISTLIMITS[4]);
histogramBins10.push_back(OCLPHISTLIMITS[5]);
histogramBins10.push_back(OCLPHISTLIMITS[6]);
histogramBins10.push_back(OCLPHISTLIMITS[7]);
histogramBins10.push_back(OCLPHISTLIMITS[8]);
addHistogramFeatures(featureDataList, "OCL_Bin10_", histogramBins10, oclres, 10);
#endif
timeOCL = timerOCL.endTimerAndGetElapsedTime();
if (m_bOutputSpeed)
{
NFIQ::QualityFeatureSpeed speed;
speed.featureIDGroup = "Orientation certainty";
#if HISTOGRAM_FEATURES
addHistogramFeatureNames(speed.featureIDs, "OCL_Bin10_", 10);
#endif
speed.featureSpeed = timeOCL;
m_lSpeedValues.push_back(speed);
}
}
catch (cv::Exception & e)
{
std::stringstream ssErr;
ssErr << "Cannot compute feature OCL histogram: " << e.what();
throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, ssErr.str());
}
catch (NFIQ::NFIQException & e)
{
throw e;
}
catch (...)
{
throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, "Unknown exception occurred!");
}
return featureDataList;
}
bool OCLHistogramFeature::getOCLValueOfBlock(const cv::Mat & block, double & ocl)
{
double eigv_max = 0.0, eigv_min = 0.0;
// compute the numerical gradients of the block
Mat grad_x, grad_y;
computeNumericalGradients(block, grad_x, grad_y);
// compute covariance matrix
double a = 0.0; double b = 0.0; double c = 0.0;
for (unsigned int k = 0; k < BS_OCL; k++)
{
for (unsigned int l = 0; l < BS_OCL; l++)
{
a += (grad_x.at<double>(l, k) * grad_x.at<double>(l, k));
b += (grad_y.at<double>(l, k) * grad_y.at<double>(l, k));
c += (grad_x.at<double>(l, k) * grad_y.at<double>(l, k));
}
}
// take mean value covariance matrix values
a /= (BS_OCL*BS_OCL);
b /= (BS_OCL*BS_OCL);
c /= (BS_OCL*BS_OCL);
// compute the eigenvalues
eigv_max = ( (a + b) + sqrt( pow(a - b, 2) + 4*pow(c, 2) ) ) / 2.0;
eigv_min = ( (a + b) - sqrt( pow(a - b, 2) + 4*pow(c, 2) ) ) / 2.0;
if (eigv_max == 0)
{
// block is excluded from usage
ocl = 0.0;
return false;
}
// compute the OCL value of the block
ocl = (1.0 - (eigv_min / eigv_max)); // 0 (worst), 1 (best)
return true;
}
std::string OCLHistogramFeature::getModuleID()
{
return "NFIQ2_OCLHistogram";
}
std::list<std::string> OCLHistogramFeature::getAllFeatureIDs()
{
std::list<std::string> featureIDs;
#if HISTOGRAM_FEATURES
addHistogramFeatureNames(featureIDs, "OCL_Bin10_", 10);
#endif
return featureIDs;
}
| 26.130435 | 117 | 0.691764 | mahizhvannan |
d10447f20db2c6868d431b2832d8471f897f020f | 850 | cpp | C++ | tests/Test_ST_Policy_Safe.cpp | wuzhl2018/nano-signal-slot | 051588437938a262b0a9738da024afcab2e8b8e6 | [
"MIT"
] | null | null | null | tests/Test_ST_Policy_Safe.cpp | wuzhl2018/nano-signal-slot | 051588437938a262b0a9738da024afcab2e8b8e6 | [
"MIT"
] | null | null | null | tests/Test_ST_Policy_Safe.cpp | wuzhl2018/nano-signal-slot | 051588437938a262b0a9738da024afcab2e8b8e6 | [
"MIT"
] | null | null | null | #include <list>
#include "CppUnitTest.h"
#include "Test_Base.hpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Nano_Tests
{
TEST_CLASS(Test_ST_Policy_Safe)
{
const int N = 64;
using Moo_T = Moo<Observer_STS>;
using Subject = Signal_Rng_STS;
TEST_METHOD(Test_Global_Signal)
{
Subject subject;
std::size_t count = 0;
Rng rng;
for (; count < N; ++count)
{
std::list<Moo_T> moo(N);
for (auto& moo_instance : moo)
{
subject.connect<&Moo_T::slot_next_random>(moo_instance);
}
subject.fire(rng);
}
Assert::IsTrue(subject.is_empty(), L"A signal was found not empty.");
}
};
}
| 21.25 | 81 | 0.52 | wuzhl2018 |
d1065e8800a4f5fa75e67e4d231f97b5173ee5cf | 4,625 | hpp | C++ | rviz_default_plugins/test/rviz_default_plugins/publishers/odometry_publisher.hpp | EricCousineau-TRI/rviz | 3344a8ed63b134549eeb82682f0dee76f53b7565 | [
"BSD-3-Clause-Clear"
] | null | null | null | rviz_default_plugins/test/rviz_default_plugins/publishers/odometry_publisher.hpp | EricCousineau-TRI/rviz | 3344a8ed63b134549eeb82682f0dee76f53b7565 | [
"BSD-3-Clause-Clear"
] | null | null | null | rviz_default_plugins/test/rviz_default_plugins/publishers/odometry_publisher.hpp | EricCousineau-TRI/rviz | 3344a8ed63b134549eeb82682f0dee76f53b7565 | [
"BSD-3-Clause-Clear"
] | null | null | null | /*
* Copyright (c) 2018, Bosch Software Innovations GmbH.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RVIZ_DEFAULT_PLUGINS__PUBLISHERS__ODOMETRY_PUBLISHER_HPP_
#define RVIZ_DEFAULT_PLUGINS__PUBLISHERS__ODOMETRY_PUBLISHER_HPP_
#define _USE_MATH_DEFINES
#include <cmath>
#include <memory>
#include <string>
#include <vector>
#include "rclcpp/rclcpp.hpp"
#include "rclcpp/clock.hpp"
#include "std_msgs/msg/header.hpp"
#include "geometry_msgs/msg/pose_stamped.hpp"
#include "nav_msgs/msg/odometry.hpp"
#include "tf2_ros/transform_broadcaster.h"
using namespace std::chrono_literals; // NOLINT
namespace nodes
{
class OdometryPublisher : public rclcpp::Node
{
public:
OdometryPublisher()
: Node("odometry_publisher")
{
publisher = this->create_publisher<nav_msgs::msg::Odometry>("odometry");
timer = this->create_wall_timer(200ms, std::bind(&OdometryPublisher::timer_callback, this));
}
// TODO(Martin-Idel-SI): shared_from_this() cannot be used in constructor. Use different
// constructor once available.
void initialize()
{
broadcaster = std::make_shared<tf2_ros::TransformBroadcaster>(shared_from_this());
}
private:
void timer_callback()
{
std::string base_frame("odometry_frame");
std::string child_frame("map");
auto now = rclcpp::Clock().now();
auto id = tf2::Quaternion::getIdentity();
auto transform = geometry_msgs::msg::TransformStamped();
transform.header.frame_id = base_frame;
transform.header.stamp = now;
transform.child_frame_id = child_frame;
transform.transform.translation.x = 0.0f;
transform.transform.translation.y = 0.0f;
transform.transform.translation.z = 0.0f;
transform.transform.rotation.x = id.getX();
transform.transform.rotation.y = id.getY();
transform.transform.rotation.z = id.getZ();
transform.transform.rotation.w = id.getW();
if (broadcaster) {
broadcaster->sendTransform(transform);
}
auto odometry_msg = nav_msgs::msg::Odometry();
odometry_msg.header.frame_id = base_frame;
odometry_msg.header.stamp = now;
odometry_msg.child_frame_id = child_frame;
odometry_msg.pose.pose.position.x = 0.0f;
odometry_msg.pose.pose.position.y = 0.0f;
odometry_msg.pose.pose.position.z = 0.0f;
odometry_msg.pose.pose.orientation.x = id.getX();
odometry_msg.pose.pose.orientation.y = id.getY();
odometry_msg.pose.pose.orientation.z = id.getZ();
odometry_msg.pose.pose.orientation.w = id.getW();
odometry_msg.pose.covariance = std::array<double, 36>{
{0.75, 0.04, 0.1, 0, 0, 0,
0.04, 0.7, 0.4, 0, 0, 0,
0.1, 0.4, 0.5, 0, 0, 0,
0, 0, 0, 0.8, 0.25, 0.06,
0, 0, 0, 0.25, 0.3, 0.22,
0, 0, 0, 0.06, 0.22, 0.6}
};
odometry_msg.twist.twist.linear.x = 0.3f;
publisher->publish(odometry_msg);
}
std::shared_ptr<tf2_ros::TransformBroadcaster> broadcaster;
rclcpp::TimerBase::SharedPtr timer;
rclcpp::Publisher<nav_msgs::msg::Odometry>::SharedPtr publisher;
};
} // namespace nodes
#endif // RVIZ_DEFAULT_PLUGINS__PUBLISHERS__ODOMETRY_PUBLISHER_HPP_
| 36.132813 | 96 | 0.721297 | EricCousineau-TRI |
d106d308a5b4edbed76b7acdca490bd4b5fc0f06 | 2,320 | hpp | C++ | src/utils/lambda/lambda_info.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | 2 | 2021-03-18T16:25:04.000Z | 2021-11-13T00:29:27.000Z | src/utils/lambda/lambda_info.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | null | null | null | src/utils/lambda/lambda_info.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | 1 | 2021-11-13T00:29:30.000Z | 2021-11-13T00:29:30.000Z | /**
* @file
* @author __AUTHOR_NAME__ <mail@host.com>
* @copyright 2021 __COMPANY_LTD__
* @license <a href="https://opensource.org/licenses/MIT">MIT License</a>
*/
#ifndef ZEN_UTILS_LAMBDA_INFO_HPP
#define ZEN_UTILS_LAMBDA_INFO_HPP
#include <tuple>
namespace Zen {
/**
* Source: angeart - https://qiita.com/angeart/items/94734d68999eca575881
*
* This type trait allows one to get the following information about a given
* lambda function:
* - Return type
* - Arity (Number of paramters)
* - Type of each parameter
* - Type of context/instance (In case of member function)
*
* It can be used as follow:
* ```cpp
* auto lambda = [] () { return 5; };
*
* std::cout << "Return type: " << std::is_same<lambda_info<decltype(lambda)>::type, int>::value << std::endl;
*
* std::cout << "Args size: " << lambda_info<decltype(lambda)>::arity << std::endl;
*
* std::cout << "Argument 0 Type: " << std::is_same<lambda_info<decltype(lambda)>::arg<0>::type, int>::value << std::endl;
* ```
*
* @since 0.0.0
*/
/**
* @tparam T The return type of the lambda
* @tparam C -
* @tparam Args The paramter types of the lambda function
*
* @since 0.0.0
*/
template <typename T, typename C, typename... Args>
struct lambda_details
{
using type = T;
enum { arity = sizeof...(Args) };
template<unsigned int i>
struct arg
{
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
};
};
/**
* Interface.
*
* @tparam L The lambda type to make a functor out of.
*
* @since 0.0.0
*/
template <typename L>
struct lambda_info
: lambda_info<decltype(&L::operator())>
{};
/**
* Mutable Specialization.
*
* @tparam T The return type of the lambda
* @tparam C The type of the context of the lambda
* @tparam Args The paramter types of the lambda function
*
* @since 0.0.0
*/
template <typename T, typename C, typename... Args>
struct lambda_info<T (C::*)(Args...)>
: lambda_details<T, C, Args...>
{};
/**
* Constant Specialization.
*
* @tparam T The return type of the lambda
* @tparam C The type of the context of the lambda
* @tparam Args The paramter types of the lambda function
*
* @since 0.0.0
*/
template <typename T, typename C, typename... Args>
struct lambda_info<T (C::*)(Args...) const>
: lambda_details<T, C, Args...>
{};
} // namespace Zen
#endif
| 22.307692 | 122 | 0.656466 | hexoctal |
d107785855feb179e6adb8faafbf64f9988a0a23 | 3,064 | cpp | C++ | Common/MdfParser/IOParameterCollection.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Common/MdfParser/IOParameterCollection.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Common/MdfParser/IOParameterCollection.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | //
// Copyright (C) 2007-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#include "stdafx.h"
#include "IOParameterCollection.h"
#include "IOParameter.h"
#include "IOUnknown.h"
using namespace XERCES_CPP_NAMESPACE;
using namespace MDFMODEL_NAMESPACE;
using namespace MDFPARSER_NAMESPACE;
IOParameterCollection::IOParameterCollection(ParameterCollection* parameterCollection, Version& version) : SAX2ElementHandler(version)
{
this->m_parameterCollection = parameterCollection;
}
void IOParameterCollection::StartElement(const wchar_t* name, HandlerStack* handlerStack)
{
this->m_currElemName = name;
if (this->m_currElemName == L"ParameterDefinition") // NOXLATE
{
this->m_startElemName = name;
}
else if (this->m_currElemName == L"Parameter") // NOXLATE
{
IOParameter* IO = new IOParameter(this->m_parameterCollection, this->m_version);
handlerStack->push(IO);
IO->StartElement(name, handlerStack);
}
else if (this->m_currElemName == L"ExtendedData1") // NOXLATE
{
this->m_procExtData = true;
}
else
{
ParseUnknownXml(name, handlerStack);
}
}
void IOParameterCollection::ElementChars(const wchar_t* ch)
{
}
void IOParameterCollection::EndElement(const wchar_t* name, HandlerStack* handlerStack)
{
if (this->m_startElemName == name)
{
this->m_parameterCollection->SetUnknownXml(this->m_unknownXml);
this->m_parameterCollection = NULL;
this->m_startElemName = L"";
handlerStack->pop();
delete this;
}
else if (::wcscmp(name, L"ExtendedData1") == 0) // NOXLATE
{
this->m_procExtData = false;
}
}
void IOParameterCollection::Write(MdfStream& fd, ParameterCollection* parameterCollection, Version* version, MgTab& tab)
{
// always write the element, even if it has 0 elements
int numElements = parameterCollection->GetCount();
fd << tab.tab() << "<ParameterDefinition>" << std::endl; // NOXLATE
tab.inctab();
for (int i=0; i<numElements; ++i)
{
Parameter* parameter = parameterCollection->GetAt(i);
IOParameter::Write(fd, parameter, version, tab);
}
// Write any unknown XML / extended data
IOUnknown::Write(fd, parameterCollection->GetUnknownXml(), version, tab);
tab.dectab();
fd << tab.tab() << "</ParameterDefinition>" << std::endl; // NOXLATE
}
| 30.336634 | 134 | 0.691906 | achilex |
d107d752afefac53db3abc46d66eb517ebcd3fc4 | 12,688 | cc | C++ | flare/rpc/protocol/protobuf/poppy_protocol.cc | AriCheng/flare | b2c84588fe4ac52f0875791d22284d7e063fd057 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 868 | 2021-05-28T04:00:22.000Z | 2022-03-31T08:57:14.000Z | flare/rpc/protocol/protobuf/poppy_protocol.cc | AriCheng/flare | b2c84588fe4ac52f0875791d22284d7e063fd057 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 33 | 2021-05-28T08:44:47.000Z | 2021-09-26T13:09:21.000Z | flare/rpc/protocol/protobuf/poppy_protocol.cc | AriCheng/flare | b2c84588fe4ac52f0875791d22284d7e063fd057 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 122 | 2021-05-28T08:22:23.000Z | 2022-03-29T09:52:09.000Z | // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "flare/rpc/protocol/protobuf/poppy_protocol.h"
#include <string>
#include "flare/base/buffer/zero_copy_stream.h"
#include "flare/base/down_cast.h"
#include "flare/base/endian.h"
#include "flare/base/string.h"
#include "flare/rpc/protocol/protobuf/call_context.h"
#include "flare/rpc/protocol/protobuf/call_context_factory.h"
#include "flare/rpc/protocol/protobuf/compression.h"
#include "flare/rpc/protocol/protobuf/message.h"
#include "flare/rpc/protocol/protobuf/poppy_rpc_meta.pb.h"
#include "flare/rpc/protocol/protobuf/rpc_meta.pb.h"
#include "flare/rpc/protocol/protobuf/service_method_locator.h"
using namespace std::literals;
namespace flare::protobuf {
FLARE_RPC_REGISTER_CLIENT_SIDE_STREAM_PROTOCOL_ARG("poppy", PoppyProtocol,
false);
FLARE_RPC_REGISTER_SERVER_SIDE_STREAM_PROTOCOL_ARG("poppy", PoppyProtocol,
true);
namespace {
// All members are network byte-order.
struct Header {
std::uint32_t meta_size;
std::uint32_t body_size;
};
constexpr auto kHeaderSize = sizeof(Header);
static_assert(kHeaderSize == 8);
struct OnWireMessage : public Message {
OnWireMessage() { SetRuntimeTypeTo<OnWireMessage>(); }
std::uint64_t GetCorrelationId() const noexcept override {
return meta.sequence_id();
}
Type GetType() const noexcept override { return Type::Single; }
poppy::RpcMeta meta;
NoncontiguousBuffer body;
};
StreamProtocol::Characteristics characteristics = {.name = "Poppy"};
poppy::CompressType GetCompressType(rpc::RpcMeta* meta) {
if (!meta->has_compression_algorithm()) {
return poppy::COMPRESS_TYPE_NONE;
}
auto compression = meta->compression_algorithm();
switch (compression) {
case rpc::COMPRESSION_ALGORITHM_NONE:
return poppy::COMPRESS_TYPE_NONE;
case rpc::COMPRESSION_ALGORITHM_SNAPPY:
return poppy::COMPRESS_TYPE_SNAPPY;
default:
// The compression algorithm specified is not supported by Poppy.
meta->clear_compression_algorithm();
FLARE_LOG_WARNING_ONCE(
"Compression algorithm [{}] is not supported by Poppy. Failing back "
"to no compression.",
rpc::CompressionAlgorithm_Name(compression));
return poppy::COMPRESS_TYPE_NONE;
}
}
bool SetCompressionAlgorithm(rpc::RpcMeta* meta,
google::protobuf::uint32 compress_type) {
auto poppy_compress = static_cast<poppy::CompressType>(compress_type);
switch (poppy_compress) {
case poppy::COMPRESS_TYPE_NONE:
return true;
case poppy::COMPRESS_TYPE_SNAPPY:
meta->set_compression_algorithm(rpc::COMPRESSION_ALGORITHM_SNAPPY);
return true;
default:
FLARE_LOG_WARNING_EVERY_SECOND(
"Unexpected compression algorithm #{} received.", compress_type);
return false;
}
}
} // namespace
const StreamProtocol::Characteristics& PoppyProtocol::GetCharacteristics()
const {
return characteristics;
}
const MessageFactory* PoppyProtocol::GetMessageFactory() const {
return &error_message_factory;
}
const ControllerFactory* PoppyProtocol::GetControllerFactory() const {
return &passive_call_context_factory;
}
PoppyProtocol::MessageCutStatus PoppyProtocol::TryCutMessage(
NoncontiguousBuffer* buffer, std::unique_ptr<Message>* message) {
if (FLARE_UNLIKELY(!handshake_in_done_)) {
auto status = KeepHandshakingIn(buffer);
if (status != MessageCutStatus::Cut) {
return status;
}
// Fall-through otherwise.
}
if (buffer->ByteSize() < kHeaderSize) {
return MessageCutStatus::NeedMore;
}
// Extract the header (and convert the endianness if necessary) first.
Header hdr;
FlattenToSlow(*buffer, &hdr, kHeaderSize);
FromBigEndian(&hdr.meta_size);
FromBigEndian(&hdr.body_size);
if (buffer->ByteSize() < kHeaderSize + hdr.meta_size + hdr.body_size) {
return MessageCutStatus::NeedMore;
}
// `msg_bytes` is not filled. We're going to remove that argument soon.
buffer->Skip(kHeaderSize);
// Parse the meta.
poppy::RpcMeta meta;
{
auto meta_bytes = buffer->Cut(hdr.meta_size);
NoncontiguousBufferInputStream nbis(&meta_bytes);
if (!meta.ParseFromZeroCopyStream(&nbis)) {
FLARE_LOG_WARNING_EVERY_SECOND("Invalid meta received, dropped.");
return MessageCutStatus::Error;
}
}
// We've cut the message then.
auto msg = std::make_unique<OnWireMessage>();
msg->meta = std::move(meta);
msg->body = buffer->Cut(hdr.body_size); // Cut message off.
*message = std::move(msg);
return MessageCutStatus::Cut;
}
bool PoppyProtocol::TryParse(std::unique_ptr<Message>* message,
Controller* controller) {
auto on_wire = cast<OnWireMessage>(message->get());
auto&& poppy_meta = on_wire->meta;
auto meta = object_pool::Get<rpc::RpcMeta>();
MaybeOwning<google::protobuf::Message> unpack_to;
bool accept_msg_in_bytes;
if ((server_side_ && !poppy_meta.has_method()) ||
(!server_side_ && !poppy_meta.has_failed())) {
FLARE_LOG_WARNING_EVERY_SECOND(
"Corrupted message: Essential fields not present. Correlation ID {}.",
poppy_meta.sequence_id());
return false;
}
meta->set_correlation_id(poppy_meta.sequence_id());
meta->set_method_type(rpc::METHOD_TYPE_SINGLE);
// Set compression algorithm.
if (!SetCompressionAlgorithm(meta.Get(), poppy_meta.compress_type())) {
return false;
}
if (server_side_) {
auto&& req_meta = *meta->mutable_request_meta();
req_meta.set_method_name(poppy_meta.method());
auto&& method = meta->request_meta().method_name();
auto desc = ServiceMethodLocator::Instance()->TryGetMethodDesc(
protocol_ids::standard, method);
if (!desc) {
FLARE_LOG_WARNING_EVERY_SECOND("Method [{}] is not found.", method);
*message = std::make_unique<EarlyErrorMessage>(
poppy_meta.sequence_id(), rpc::STATUS_METHOD_NOT_FOUND,
fmt::format("Method [{}] is not implemented.", method));
return true;
}
// Not exactly. TODO(luobogao): Use what we've negotiated in handshaking
// phase.
static constexpr std::uint64_t kAcceptableCompressionAlgorithms =
1 << rpc::COMPRESSION_ALGORITHM_NONE |
1 << rpc::COMPRESSION_ALGORITHM_SNAPPY;
req_meta.set_acceptable_compression_algorithms(
kAcceptableCompressionAlgorithms);
unpack_to = std::unique_ptr<google::protobuf::Message>(
desc->request_prototype->New());
accept_msg_in_bytes = false; // TODO(luobogao): Implementation.
} else {
auto ctx = cast<ProactiveCallContext>(controller);
accept_msg_in_bytes = ctx->accept_response_in_bytes;
if (FLARE_LIKELY(!accept_msg_in_bytes)) {
unpack_to = ctx->GetOrCreateResponse();
}
if (!poppy_meta.failed()) {
meta->mutable_response_meta()->set_status(rpc::STATUS_SUCCESS);
} else {
// FIXME: Error code definition does not match between brpc & flare.
meta->mutable_response_meta()->set_status(poppy_meta.error_code());
if (poppy_meta.has_reason()) {
meta->mutable_response_meta()->set_description(poppy_meta.reason());
}
}
}
auto parsed = std::make_unique<ProtoMessage>();
parsed->meta = std::move(meta);
if (FLARE_UNLIKELY(accept_msg_in_bytes)) {
parsed->msg_or_buffer = std::move(on_wire->body);
} else {
NoncontiguousBuffer* buffer = &on_wire->body;
if (!compression::DecompressBodyIfNeeded(*parsed->meta, on_wire->body,
buffer)) {
FLARE_LOG_WARNING_EVERY_SECOND(
"Failed to decompress message (correlation id {}).",
parsed->meta->correlation_id());
return false;
}
NoncontiguousBufferInputStream nbis(buffer);
if (!unpack_to->ParseFromZeroCopyStream(&nbis)) {
FLARE_LOG_WARNING_EVERY_SECOND(
"Failed to parse message (correlation id {}).",
poppy_meta.sequence_id());
return false;
}
parsed->msg_or_buffer = std::move(unpack_to);
}
*message = std::move(parsed);
return true;
}
// Serialize `message` into `buffer`.
void PoppyProtocol::WriteMessage(const Message& message,
NoncontiguousBuffer* buffer,
Controller* controller) {
NoncontiguousBufferBuilder nbb;
if (FLARE_UNLIKELY(!handeshake_out_done_)) {
KeepHandshakingOut(&nbb);
// Fall-through otherwise.
}
auto msg = cast<ProtoMessage>(&message);
auto&& meta = *msg->meta;
auto reserved_hdr = nbb.Reserve(sizeof(Header));
FLARE_LOG_ERROR_IF_ONCE(!msg->attachment.Empty(),
"Attachment is not supported by Poppy protocol");
FLARE_LOG_ERROR_IF_ONCE(
!controller->GetTracingContext().empty() ||
controller->IsTraceForciblySampled(),
"Passing tracing context is not supported by Poppy protocol.");
Header hdr;
{
NoncontiguousBufferOutputStream nbos(&nbb);
// Translate & serialize rpc meta.
poppy::RpcMeta poppy_meta;
poppy_meta.set_sequence_id(meta.correlation_id());
poppy_meta.set_compress_type(GetCompressType(&meta));
if (server_side_) {
auto&& resp_meta = meta.response_meta();
poppy_meta.set_failed(resp_meta.status() != rpc::STATUS_SUCCESS);
poppy_meta.set_error_code(resp_meta.status()); // FIXME: Translate it.
poppy_meta.set_reason(resp_meta.description());
} else {
auto&& req_meta = meta.request_meta();
poppy_meta.set_method(req_meta.method_name());
poppy_meta.set_timeout(req_meta.timeout());
}
hdr.meta_size = poppy_meta.ByteSizeLong();
FLARE_CHECK(poppy_meta.SerializeToZeroCopyStream(&nbos));
}
hdr.body_size = compression::CompressBodyIfNeeded(meta, *msg, &nbb);
// Fill the header.
ToBigEndian(&hdr.body_size);
ToBigEndian(&hdr.meta_size);
memcpy(reserved_hdr, &hdr, sizeof(hdr));
buffer->Append(nbb.DestructiveGet());
}
// Called in single-threaded environment. Each `PoppyProtocol` is bound to
// exactly one connection, thus we can't be called concurrently.
PoppyProtocol::MessageCutStatus PoppyProtocol::KeepHandshakingIn(
NoncontiguousBuffer* buffer) {
if (server_side_) {
static constexpr auto kSignature = "POST /__rpc_service__ HTTP/1.1\r\n"sv;
if (buffer->ByteSize() < kSignature.size()) {
return MessageCutStatus::NotIdentified;
}
if (FlattenSlow(*buffer, kSignature.size()) != kSignature) {
return MessageCutStatus::ProtocolMismatch;
}
}
// I'm not sure if we need these headers but let's keep them anyway..
auto flatten = FlattenSlowUntil(*buffer, "\r\n\r\n");
if (!EndsWith(flatten, "\r\n\r\n")) {
return MessageCutStatus::NeedMore;
}
buffer->Skip(flatten.size()); // Cut the handshake data off.
auto splited = Split(flatten, "\r\n");
splited.erase(splited.begin()); // Skip Start-Line
for (auto&& e : splited) {
auto kvs = Split(e, ":", true /* Keep empty */);
if (kvs.size() != 2) {
FLARE_LOG_WARNING_EVERY_SECOND(
"Failed to handshake with the remote side: Unexpected HTTP header "
"[{}].",
e);
return MessageCutStatus::Error;
}
conn_headers_[std::string(Trim(kvs[0]))] = std::string(Trim(kvs[1]));
}
handshake_in_done_ = true;
return MessageCutStatus::Cut;
}
// Always called in single-threaded environment.
void PoppyProtocol::KeepHandshakingOut(NoncontiguousBufferBuilder* builder) {
// Well, hard-code here should work adequately well.
if (server_side_) {
builder->Append(
"HTTP/1.1 200 OK\r\n"
"X-Poppy-Compress-Type: 0,1\r\n\r\n"); // No-compression & snappy.
} else {
builder->Append(
"POST /__rpc_service__ HTTP/1.1\r\n"
"Cookie: POPPY_AUTH_TICKET=\r\n" // Allow channel options to override
// this?
"X-Poppy-Compress-Type: 0,1\r\n"
"X-Poppy-Tos: 96\r\n\r\n"); // We don't support TOS.
}
handeshake_out_done_ = true;
}
} // namespace flare::protobuf
| 34.291892 | 80 | 0.686239 | AriCheng |
d1081fc4968b3f1219b9d671908dd0311b4da809 | 30,165 | cxx | C++ | com/ole32/com/class/cerror.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/ole32/com/class/cerror.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/ole32/com/class/cerror.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------
//
// File: cerror.cxx
//
// Contents: Implements COM extended error information.
//
// Classes: CErrorObject - Implements the COM error object.
//
// Functions: CoCreateErrorInfo = CreateErrorInfo
// CoGetErrorInfo = GetErrorInfo
// CoSetErrorInfo = SetErrorInfo
//
// History: 20-Jun-96 MikeHill Added more OleAut32 wrappers.
//
//--------------------------------------------------------------------
#include <ole2int.h>
#include <oleauto.h>
#include <chock.hxx>
#include <privoa.h> // PrivSys* routines
HRESULT NdrStringRead(IStream *pStream, LPWSTR *psz);
SIZE_T NdrStringSize(LPCWSTR psz);
HRESULT NdrStringWrite(IStream *pStream, LPCWSTR psz);
struct ErrorObjectData
{
DWORD dwVersion;
DWORD dwHelpContext;
IID iid;
};
class CErrorObject : public IErrorInfo, public ICreateErrorInfo, public IMarshal
{
private:
long _refCount;
ErrorObjectData _data;
LPWSTR _pszSource;
LPWSTR _pszDescription;
LPWSTR _pszHelpFile;
~CErrorObject();
public:
CErrorObject();
/*** IUnknown methods ***/
HRESULT STDMETHODCALLTYPE QueryInterface(
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppv);
ULONG STDMETHODCALLTYPE AddRef( void);
ULONG STDMETHODCALLTYPE Release( void);
/*** IMarshal methods ***/
HRESULT STDMETHODCALLTYPE GetUnmarshalClass(
/* [in] */ REFIID riid,
/* [unique][in] */ void __RPC_FAR *pv,
/* [in] */ DWORD dwDestContext,
/* [unique][in] */ void __RPC_FAR *pvDestContext,
/* [in] */ DWORD mshlflags,
/* [out] */ CLSID __RPC_FAR *pCid);
HRESULT STDMETHODCALLTYPE GetMarshalSizeMax(
/* [in] */ REFIID riid,
/* [unique][in] */ void __RPC_FAR *pv,
/* [in] */ DWORD dwDestContext,
/* [unique][in] */ void __RPC_FAR *pvDestContext,
/* [in] */ DWORD mshlflags,
/* [out] */ DWORD __RPC_FAR *pSize);
HRESULT STDMETHODCALLTYPE MarshalInterface(
/* [unique][in] */ IStream __RPC_FAR *pStm,
/* [in] */ REFIID riid,
/* [unique][in] */ void __RPC_FAR *pv,
/* [in] */ DWORD dwDestContext,
/* [unique][in] */ void __RPC_FAR *pvDestContext,
/* [in] */ DWORD mshlflags);
HRESULT STDMETHODCALLTYPE UnmarshalInterface(
/* [unique][in] */ IStream __RPC_FAR *pStm,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv);
HRESULT STDMETHODCALLTYPE ReleaseMarshalData(
/* [unique][in] */ IStream __RPC_FAR *pStm);
HRESULT STDMETHODCALLTYPE DisconnectObject(
/* [in] */ DWORD dwReserved);
/*** IErrorInfo methods ***/
HRESULT STDMETHODCALLTYPE GetGUID(
/* [out] */ GUID __RPC_FAR *pGUID);
HRESULT STDMETHODCALLTYPE GetSource(
/* [out] */ BSTR __RPC_FAR *pBstrSource);
HRESULT STDMETHODCALLTYPE GetDescription(
/* [out] */ BSTR __RPC_FAR *pBstrDescription);
HRESULT STDMETHODCALLTYPE GetHelpFile(
/* [out] */ BSTR __RPC_FAR *pBstrHelpFile);
HRESULT STDMETHODCALLTYPE GetHelpContext(
/* [out] */ DWORD __RPC_FAR *pdwHelpContext);
/*** ICreateErrorInfo methods ***/
HRESULT STDMETHODCALLTYPE SetGUID(
/* [in] */ REFGUID rguid);
HRESULT STDMETHODCALLTYPE SetSource(
/* [in] */ LPOLESTR szSource);
HRESULT STDMETHODCALLTYPE SetDescription(
/* [in] */ LPOLESTR szDescription);
HRESULT STDMETHODCALLTYPE SetHelpFile(
/* [in] */ LPOLESTR szHelpFile);
HRESULT STDMETHODCALLTYPE SetHelpContext(
/* [in] */ DWORD dwHelpContext);
};
//+-------------------------------------------------------------------
//
// Function: CoCreateErrorInfo
//
// Synopsis: Creates a COM error object.
//
// Returns: S_OK, E_OUTOFMEMORY, E_INVALIDARG.
//
//--------------------------------------------------------------------
WINOLEAPI
CoCreateErrorInfo(ICreateErrorInfo **ppCreateErrorInfo)
{
HRESULT hr = S_OK;
CErrorObject *pTemp;
__try
{
*ppCreateErrorInfo = NULL;
pTemp = new CErrorObject;
if(pTemp != NULL)
{
*ppCreateErrorInfo = (ICreateErrorInfo *) pTemp;
}
else
{
hr = E_OUTOFMEMORY;
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+-------------------------------------------------------------------
//
// Function: CErrorObjectCF_CreateInstance
//
// Synopsis: Creates a COM error object.
//
// Returns: S_OK, E_OUTOFMEMORY, E_INVALIDARG.
//
//--------------------------------------------------------------------
HRESULT CErrorObjectCF_CreateInstance(IUnknown *pUnkOuter, REFIID riid, void** ppv)
{
Win4Assert(pUnkOuter == NULL);
return CoCreateErrorInfo((ICreateErrorInfo **)ppv);
}
//+-------------------------------------------------------------------
//
// Function: CoGetErrorInfo
//
// Synopsis: Gets the error object for the current thread.
//
// Returns: S_OK, S_FALSE, E_INVALIDARG, E_NOINTERFACE.
//
// Notes: If sucessful, this function clears the error object
// for the current thread.
//
//--------------------------------------------------------------------
WINOLEAPI
CoGetErrorInfo(DWORD dwReserved, IErrorInfo ** ppErrorInfo)
{
HRESULT hr = S_OK;
COleTls tls(hr);
IUnknown *punkError = NULL;
if(FAILED(hr))
{
//Could not access TLS.
return hr;
}
if(dwReserved != 0)
{
return E_INVALIDARG;
}
__try
{
*ppErrorInfo = NULL;
if(tls->punkError != NULL)
{
punkError = tls->punkError;
tls->punkError = NULL;
hr = punkError->QueryInterface(IID_IErrorInfo, (void **) ppErrorInfo);
if(SUCCEEDED(hr))
{
//Clear the error object.
punkError->Release();
hr = S_OK;
}
else
{
ComDebOut((DEB_WARN, "Error object does not implement IID_IErrorInfo"));
tls->punkError = punkError;
}
}
else
{
hr = S_FALSE;
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+-------------------------------------------------------------------
//
// Function: CoSetErrorInfo
//
// Synopsis: Sets the COM extended error information for the
// current thread.
//
// Returns: S_OK, E_OUTOFMEMORY, E_INVALIDARG.
//
//--------------------------------------------------------------------
WINOLEAPI
CoSetErrorInfo(unsigned long dwReserved, IErrorInfo * pErrorInfo)
{
HRESULT hr = S_OK;
COleTls tls(hr);
if(FAILED(hr))
{
//Could not access TLS.
return hr;
}
if(dwReserved != 0)
{
return E_INVALIDARG;
}
__try
{
// Do this first, so that if the Release() reenters,
// we're not pointing at them.
// Some ADO destructor code will, indeed, do just that.
//
IUnknown * punkErrorOld = tls->punkError;
tls->punkError = NULL;
//Release the old error object.
if(punkErrorOld != NULL)
{
punkErrorOld->Release();
}
//AddRef the new error object.
if(pErrorInfo != NULL)
{
pErrorInfo->AddRef();
}
// Set the error object for the current thread.
tls->punkError = pErrorInfo;
hr = S_OK;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::CErrorObject
//
// Synopsis: Constructor for COM error object.
//
//----------------------------------------------------------------------------
CErrorObject::CErrorObject()
: _refCount(1),
_pszSource(NULL),
_pszDescription(NULL),
_pszHelpFile(NULL)
{
_data.dwVersion = 0;
_data.dwHelpContext = 0;
_data.iid = GUID_NULL;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::~CErrorObject
//
// Synopsis: Destructor for COM error object.
//
//----------------------------------------------------------------------------
CErrorObject::~CErrorObject()
{
if(_pszSource != NULL)
PrivMemFree(_pszSource);
if(_pszDescription != NULL)
PrivMemFree(_pszDescription);
if(_pszHelpFile != NULL)
PrivMemFree(_pszHelpFile);
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::QueryInterface
//
// Synopsis: Gets a pointer to the specified interface. The error object
// supports the IErrorInfo, ICreateErrorInfo, IMarshal, and
// IUnknown interfaces.
//
// Returns: S_OK, E_NOINTERFACE, E_INVALIDARG.
//
// Notes: Bad parameters will raise an exception. The exception
// handler catches exceptions and returns E_INVALIDARG.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::QueryInterface(
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppv)
{
HRESULT hr = S_OK;
_try
{
*ppv = NULL;
if (IsEqualIID(riid, IID_IMarshal))
{
AddRef();
*ppv = (IMarshal *) this;
}
else if (IsEqualIID(riid, IID_IUnknown) ||
IsEqualIID(riid, IID_ICreateErrorInfo))
{
AddRef();
*ppv = (ICreateErrorInfo *) this;
}
else if(IsEqualIID(riid, IID_IErrorInfo))
{
AddRef();
*ppv = (IErrorInfo *) this;
}
else
{
hr = E_NOINTERFACE;
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::AddRef
//
// Synopsis: Increments the reference count.
//
// Returns: Reference count.
//
//----------------------------------------------------------------------------
ULONG STDMETHODCALLTYPE CErrorObject::AddRef()
{
Win4Assert(_refCount > 0);
InterlockedIncrement(&_refCount);
return _refCount;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::Release
//
// Synopsis: Decrements the reference count.
//
// Returns: Reference count.
//
//----------------------------------------------------------------------------
ULONG STDMETHODCALLTYPE CErrorObject::Release()
{
ULONG count = _refCount - 1;
Win4Assert(_refCount > 0);
if(0 == InterlockedDecrement(&_refCount))
{
delete this;
count = 0;
}
return count;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::GetUnmarshalClass
//
// Synopsis: Get the CLSID of the COM error object.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::GetUnmarshalClass(
/* [in] */ REFIID riid,
/* [unique][in] */ void __RPC_FAR *pv,
/* [in] */ DWORD dwDestContext,
/* [unique][in] */ void __RPC_FAR *pvDestContext,
/* [in] */ DWORD mshlflags,
/* [out] */ CLSID __RPC_FAR *pClassID)
{
*pClassID = CLSID_ErrorObject;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::GetMarshalSizeMax
//
// Synopsis: Get the size of the marshalled COM error object.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::GetMarshalSizeMax(
/* [in] */ REFIID riid,
/* [unique][in] */ void __RPC_FAR *pv,
/* [in] */ DWORD dwDestContext,
/* [unique][in] */ void __RPC_FAR *pvDestContext,
/* [in] */ DWORD mshlflags,
/* [out] */ DWORD __RPC_FAR *pSize)
{
SIZE_T cb;
cb = sizeof(_data);
cb += NdrStringSize(_pszSource);
cb += NdrStringSize(_pszDescription);
cb += NdrStringSize(_pszHelpFile);
*pSize = (DWORD) cb;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::MarshalInterface
//
// Synopsis: Marshal the COM error object.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::MarshalInterface(
/* [unique][in] */ IStream __RPC_FAR *pStream,
/* [in] */ REFIID riid,
/* [unique][in] */ void __RPC_FAR *pv,
/* [in] */ DWORD dwDestContext,
/* [unique][in] */ void __RPC_FAR *pvDestContext,
/* [in] */ DWORD mshlflags)
{
HRESULT hr;
hr = pStream->Write(&_data, sizeof(_data), NULL);
if(SUCCEEDED(hr))
hr = NdrStringWrite(pStream, _pszSource);
if(SUCCEEDED(hr))
hr = NdrStringWrite(pStream, _pszDescription);
if(SUCCEEDED(hr))
hr = NdrStringWrite(pStream, _pszHelpFile);
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::UnmarshalInterface
//
// Synopsis: Unmarshal the COM error object.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::UnmarshalInterface(
/* [unique][in] */ IStream __RPC_FAR *pStream,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv)
{
HRESULT hr;
*ppv = NULL;
//Clear the error object.
if(_pszSource != NULL)
{
PrivMemFree(_pszSource);
_pszSource = NULL;
}
if(_pszDescription != NULL)
{
PrivMemFree(_pszDescription);
_pszDescription = NULL;
}
if(_pszHelpFile != NULL)
{
PrivMemFree(_pszHelpFile);
_pszHelpFile = NULL;
}
hr = pStream->Read(&_data, sizeof(_data), NULL);
if(SUCCEEDED(hr))
hr = NdrStringRead(pStream, &_pszSource);
if(SUCCEEDED(hr))
hr = NdrStringRead(pStream, &_pszDescription);
if(SUCCEEDED(hr))
hr = NdrStringRead(pStream, &_pszHelpFile);
//Check the version.
if(_data.dwVersion > 0)
{
_data.dwVersion = 0;
}
if(SUCCEEDED(hr))
{
hr = QueryInterface(riid, ppv);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::ReleaseMarshalData
//
// Synopsis: Release a marshalled COM error object.
//
// Notes: Just seek to the end of the marshalled error object.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::ReleaseMarshalData(
/* [unique][in] */ IStream __RPC_FAR *pStm)
{
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::DisconnectObject
//
// Synopsis: Disconnect the object.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::DisconnectObject(
/* [in] */ DWORD dwReserved)
{
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::GetDescription
//
// Synopsis: Gets a textual description of the error.
//
// Returns: S_OK, E_OUTOFMEMORY, E_INVALIDARG.
//
// Notes: Not thread-safe.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::GetDescription(
/* [out] */ BSTR __RPC_FAR *pBstrDescription)
{
HRESULT hr = S_OK;
BSTR pTemp;
__try
{
*pBstrDescription = NULL;
if(_pszDescription != NULL)
{
pTemp = PrivSysAllocString(_pszDescription);
if(pTemp != NULL)
{
*pBstrDescription = pTemp;
}
else
{
hr = E_OUTOFMEMORY;
}
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::GetGUID
//
// Synopsis: Gets the IID of the interface that defined the error.
//
// Returns: S_OK, E_INVALIDARG.
//
// Notes: Not thread-safe.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::GetGUID(
/* [out] */ GUID __RPC_FAR *pGUID)
{
HRESULT hr = S_OK;
__try
{
*pGUID = _data.iid;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::GetHelpContext
//
// Synopsis: Gets the Help context ID for the error.
//
// Returns: S_OK, E_INVALIDARG.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::GetHelpContext(
/* [out] */ DWORD __RPC_FAR *pdwHelpContext)
{
HRESULT hr = S_OK;
__try
{
*pdwHelpContext = _data.dwHelpContext;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::GetHelpFile
//
// Synopsis: Gets the path of the help file that describes the error.
//
// Returns: S_OK, E_OUTOFMEMORY, E_INVALIDARG.
//
// Notes: Not thread-safe.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::GetHelpFile(
/* [out] */ BSTR __RPC_FAR *pBstrHelpFile)
{
HRESULT hr = S_OK;
BSTR pTemp;
__try
{
*pBstrHelpFile = NULL;
if(_pszHelpFile != NULL)
{
pTemp = PrivSysAllocString(_pszHelpFile);
if(pTemp != NULL)
{
*pBstrHelpFile = pTemp;
}
else
{
hr = E_OUTOFMEMORY;
}
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::GetSource
//
// Synopsis: Gets the ProgID of the class that is the source of the error.
//
// Returns: S_OK, E_OUTOFMEMORY, E_INVALIDARG.
//
// Notes: Not thread-safe.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::GetSource(
/* [out] */ BSTR __RPC_FAR *pBstrSource)
{
HRESULT hr = S_OK;
BSTR pTemp;
__try
{
*pBstrSource = NULL;
if(_pszSource != NULL)
{
pTemp = PrivSysAllocString(_pszSource);
if(pTemp != NULL)
{
*pBstrSource = pTemp;
}
else
{
hr = E_OUTOFMEMORY;
}
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::SetDescription
//
// Synopsis: Sets the textual description of the error.
//
// Returns: S_OK, E_OUTOFMEMORY, E_INVALIDARG.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::SetDescription(
/* [in] */ LPOLESTR pszDescription)
{
HRESULT hr = S_OK;
LPOLESTR pTemp = NULL;
SIZE_T cb;
__try
{
if(pszDescription != NULL)
{
cb = (wcslen(pszDescription) + 1) * sizeof(OLECHAR);
pTemp = (LPOLESTR) PrivMemAlloc(cb);
if(pTemp != NULL)
{
memcpy(pTemp, pszDescription, cb);
}
else
{
hr = E_OUTOFMEMORY;
}
}
if(SUCCEEDED(hr))
{
pTemp = (LPOLESTR) InterlockedExchangePointer((PVOID *)&_pszDescription,
(PVOID) pTemp);
if(pTemp != NULL)
{
PrivMemFree(pTemp);
}
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::SetGUID
//
// Synopsis: Sets the IID of the interface that defined the error.
//
// Returns: S_OK, E_INVALIDARG.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::SetGUID(
/* [in] */ REFGUID rguid)
{
HRESULT hr = S_OK;
__try
{
_data.iid = rguid;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::SetHelpContext
//
// Synopsis: Sets the Help context ID for the error.
//
// Returns: S_OK.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::SetHelpContext(
/* [in] */ DWORD dwHelpContext)
{
_data.dwHelpContext = dwHelpContext;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::SetHelpFile
//
// Synopsis: Sets the path of the Help file that describes the error.
//
// Returns: S_OK, E_OUTOFMEMORY, E_INVALIDARG.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::SetHelpFile(
/* [in] */ LPOLESTR pszHelpFile)
{
HRESULT hr = S_OK;
LPOLESTR pTemp = NULL;
SIZE_T cb;
__try
{
if(pszHelpFile != NULL)
{
cb = (wcslen(pszHelpFile) + 1) * sizeof(OLECHAR);
pTemp = (LPOLESTR) PrivMemAlloc(cb);
if(pTemp != NULL)
{
memcpy(pTemp, pszHelpFile, cb);
}
else
{
hr = E_OUTOFMEMORY;
}
}
if(SUCCEEDED(hr))
{
pTemp = (LPOLESTR) InterlockedExchangePointer((PVOID *)&_pszHelpFile,
(PVOID) pTemp);
if(pTemp != NULL)
{
PrivMemFree(pTemp);
}
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CErrorObject::SetSource
//
// Synopsis: Sets the source of the error.
//
// Returns: S_OK, E_OUTOFMEMORY, E_INVALIDARG.
//
//----------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CErrorObject::SetSource(
/* [in] */ LPOLESTR pszSource)
{
HRESULT hr = S_OK;
LPOLESTR pTemp = NULL;
SIZE_T cb;
__try
{
if(pszSource != NULL)
{
cb = (wcslen(pszSource) + 1) * sizeof(OLECHAR);
pTemp = (LPOLESTR) PrivMemAlloc(cb);
if(pTemp != NULL)
{
memcpy(pTemp, pszSource, cb);
}
else
{
hr = E_OUTOFMEMORY;
}
}
if(SUCCEEDED(hr))
{
pTemp = (LPOLESTR) InterlockedExchangePointer((PVOID *)&_pszSource,
(PVOID) pTemp);
if(pTemp != NULL)
{
PrivMemFree(pTemp);
}
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
struct NdrStringHeader
{
DWORD dwMax;
DWORD dwOffset;
DWORD dwActual;
};
struct NdrStringPtrHeader
{
DWORD dwUnique;
DWORD dwMax;
DWORD dwOffset;
DWORD dwActual;
};
// This is the maximum size of a read string. To prevent DOS attacks
// that get us to allocate a whole lot of memory.
#define MAX_STRING_BUFFER_LEN (64 * 1024)
//+---------------------------------------------------------------------------
//
// Function: NdrStringRead
//
// Synopsis: Reads a string from a stream in NDR format.
//
// Notes: The NDR format of a string is the following.
// DWORD - Represents the unique pointer.
// DWORD - Maximum number of elements.
// DWORD - offset.
// DWORD - Actual number of elements.
// NULL terminated UNICODE string.
//
//----------------------------------------------------------------------------
HRESULT NdrStringRead(IStream *pStream, LPWSTR *ppsz)
{
DWORD dwUnique = 0;
ULONG cbRead = 0;
*ppsz = NULL;
//Check for a NULL pointer.
HRESULT hr = pStream->Read(&dwUnique, sizeof(dwUnique), &cbRead);
if (FAILED(hr) || (cbRead != sizeof(dwUnique)))
return RPC_E_INVALID_OBJREF;
if(dwUnique != 0)
{
LPWSTR pTemp = NULL;
NdrStringHeader hdr;
hr = pStream->Read(&hdr, sizeof(hdr), &cbRead);
if ((FAILED(hr)) || (cbRead != sizeof(hdr)))
return RPC_E_INVALID_OBJREF;
// hdr.dwMax is supposed to be the size of the buffer.
//
// I'm not sure what hdr.dwOffset is supposed to mean. But
// we always write 0, and this unmarshaller doesn't know what
// to do with it, so make sure it's 0.
//
// hdr.dwActual is supposed to be the length we copy. One
// might think that hdr.dwActual might not be the same as
// hdr.dwMax, because of dwOffset, but since dwOffset is always
// 0...
if ((hdr.dwMax != hdr.dwActual) || (hdr.dwOffset != 0))
return RPC_E_INVALID_OBJREF;
// Do not honor requests for very large strings here.
if (hdr.dwMax > MAX_STRING_BUFFER_LEN)
return E_OUTOFMEMORY;
pTemp = (LPWSTR) PrivMemAlloc(hdr.dwMax * sizeof(WCHAR));
if(pTemp != NULL)
{
hr = pStream->Read(pTemp,
hdr.dwMax * sizeof(WCHAR),
&cbRead);
if ((FAILED(hr)) ||
(cbRead != hdr.dwMax * sizeof(WCHAR)) ||
(pTemp[hdr.dwMax-1] != L'\0'))
{
PrivMemFree(pTemp);
return RPC_E_INVALID_OBJREF;
}
else
{
*ppsz = pTemp;
}
}
else
{
return E_OUTOFMEMORY;
}
}
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Function: NdrStringSize
//
// Synopsis: Computes the size of a marshalled string.
//
//----------------------------------------------------------------------------
SIZE_T NdrStringSize(LPCWSTR psz)
{
SIZE_T cb;
if(psz != NULL)
{
cb = sizeof(NdrStringPtrHeader);
cb += (wcslen(psz) + 1) * sizeof(WCHAR);
}
else
{
cb = sizeof(DWORD);
}
return cb;
}
//+---------------------------------------------------------------------------
//
// Function: NdrStringWrite
//
// Synopsis: Writes a string to a stream in NDR format.
//
// Notes: The NDR format of a string is shown below.
// DWORD - Represents the unique pointer.
// DWORD - Maximum number of elements.
// DWORD - offset.
// DWORD - Number of elements.
// NULL terminated UNICODE string.
//
//----------------------------------------------------------------------------
HRESULT NdrStringWrite(IStream *pStream, LPCWSTR psz)
{
HRESULT hr = S_OK;
ULONG cbWritten;
//Check for a NULL pointer.
if(psz != NULL)
{
NdrStringPtrHeader hdr;
//Write the header.
hdr.dwUnique = 0xFFFFFFFF;
hdr.dwMax = (DWORD) wcslen(psz) + 1;
hdr.dwOffset = 0;
hdr.dwActual = hdr.dwMax;
hr = pStream->Write(&hdr, sizeof(hdr), &cbWritten);
if(SUCCEEDED(hr))
{
hr = pStream->Write(psz, hdr.dwActual * sizeof(WCHAR), &cbWritten);
}
}
else
{
DWORD dwUnique = 0;
//Write a NULL unique pointer.
hr = pStream->Write(&dwUnique, sizeof(dwUnique), &cbWritten);
}
return hr;
}
| 26.69469 | 85 | 0.459506 | npocmaka |
d109752586cd1d82c191278962f520bf82dba9f4 | 5,117 | cpp | C++ | scene_with_camera/src/scene_with_camera.cpp | Phyllostachys/graphics-demos | bf1f1f10c95e0c9f752117ad23295ce06acdb17c | [
"MIT"
] | 1 | 2015-09-05T11:15:07.000Z | 2015-09-05T11:15:07.000Z | scene_with_camera/src/scene_with_camera.cpp | Phyllostachys/graphics-demos | bf1f1f10c95e0c9f752117ad23295ce06acdb17c | [
"MIT"
] | null | null | null | scene_with_camera/src/scene_with_camera.cpp | Phyllostachys/graphics-demos | bf1f1f10c95e0c9f752117ad23295ce06acdb17c | [
"MIT"
] | null | null | null | #include "cube.h"
#include "shader.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glad/glad.h"
#include "GLFW/glfw3.h"
#include <cstdio>
#include <iostream>
glm::vec3 cameraPos = glm::vec3(0.0, 0.05, 23.0);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
GLfloat cameraSpeed = 0.05f;
bool showNewPosition = false;
switch (key) {
case GLFW_KEY_W: {
cameraPos += cameraSpeed * cameraFront;
showNewPosition = true;
break;
}
case GLFW_KEY_S: {
cameraPos -= cameraSpeed * cameraFront;
showNewPosition = true;
break;
}
case GLFW_KEY_A: {
cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
showNewPosition = true;
break;
}
case GLFW_KEY_D: {
cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
showNewPosition = true;
break;
}
case GLFW_KEY_Q: {
cameraPos += cameraSpeed * cameraUp;
showNewPosition = true;
break;
}
case GLFW_KEY_Z: {
cameraPos -= cameraSpeed * cameraUp;
showNewPosition = true;
break;
}
default: {
break;
}
}
if (showNewPosition) {
printf("%02F,%02F,%02F\n", cameraPos.x, cameraPos.y, cameraPos.z);
}
}
int main(int argc, char** argv)
{
int result;
int width, height;
result = glfwInit();
if (result == GLFW_FALSE) {
printf("Problem initializing GLFW3.");
return -1;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
GLFWwindow* window = glfwCreateWindow(800, 600, "Scene with Camera", nullptr, nullptr);
if (window == nullptr) {
printf("Problem creating window context.");
return -1;
}
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
// Load in OGL functions
if (!gladLoadGL()) {
printf("Failed to initialize OpenGL context");
return -1;
}
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
GLuint VAO;
GLuint vertBufferIndex[2];
glGenVertexArrays(1, &VAO);
glGenBuffers(2, vertBufferIndex);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, vertBufferIndex[0]);
glBufferData(GL_ARRAY_BUFFER, NUM_CUBE_VERTS * sizeof(float), cubeVerts, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertBufferIndex[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_CUBE_IND * sizeof(unsigned int), cubeIndices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
// shaders
Shader s("assets\\basic.vert", "assets\\basic.geom", "assets\\basic.frag");
if(!s.compile()) {
printf("Some error happened while creating shaders\n");
return -1;
}
GLint mvpLoc = glGetUniformLocation(s.getShaderProgram(), "MVP");
GLint timeLoc = glGetUniformLocation(s.getShaderProgram(), "time");
glEnable(GL_DEPTH_TEST);
// main loop
while (!glfwWindowShouldClose(window)) {
/* Poll for and process events */
glfwPollEvents();
glm::mat4 center, scale, rotate, translate;
center = glm::translate(center, glm::vec3(-0.5, -0.5, -0.5));
//scale = glm::scale(scale, glm::vec3(1.6, 1.6, 1.6));
rotate = glm::rotate(rotate, (GLfloat)glfwGetTime() * 1.0f, glm::normalize(glm::vec3(0.0f, 1.0f, 0.0f)));
translate = glm::translate(translate, glm::vec3(0.0, 0.0, 20.0));
glm::mat4 model;
model = translate * rotate * scale * center * model;
glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
glm::mat4 proj = glm::perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 1000.0f);
glm::mat4 mvp = proj * view * model;
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(s.getShaderProgram());
glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, glm::value_ptr(mvp));
glUniform1f(timeLoc, (GLfloat)glfwGetTime() * 1.5);
glUniform3f(glGetUniformLocation(s.getShaderProgram(), "drawColor"), 0.0f, 1.0f, 0.0f);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawElements(GL_TRIANGLES, NUM_CUBE_IND, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
| 30.640719 | 113 | 0.62478 | Phyllostachys |
d109da67c973c23e1cb265405bde37933af512dd | 1,403 | cpp | C++ | src/function/scalar/string/suffix.cpp | AdamKorcz/duckdb | 1cc80b697c879161d3b1ed889b8e3338568edd2a | [
"MIT"
] | null | null | null | src/function/scalar/string/suffix.cpp | AdamKorcz/duckdb | 1cc80b697c879161d3b1ed889b8e3338568edd2a | [
"MIT"
] | null | null | null | src/function/scalar/string/suffix.cpp | AdamKorcz/duckdb | 1cc80b697c879161d3b1ed889b8e3338568edd2a | [
"MIT"
] | null | null | null | #include "duckdb/function/scalar/string_functions.hpp"
#include "duckdb/common/types/string_type.hpp"
#include "duckdb/common/exception.hpp"
using namespace std;
namespace duckdb {
static bool suffix(const string_t &str, const string_t &suffix);
struct SuffixOperator {
template <class TA, class TB, class TR> static inline TR Operation(TA left, TB right) {
return suffix(left, right);
}
};
static bool suffix(const string_t &str, const string_t &suffix) {
auto suffix_size = suffix.GetSize();
auto str_size = str.GetSize();
if (suffix_size > str_size) {
return false;
}
auto suffix_data = suffix.GetDataUnsafe();
auto str_data = str.GetDataUnsafe();
int32_t suf_idx = suffix_size - 1;
idx_t str_idx = str_size - 1;
for (; suf_idx >= 0; --suf_idx, --str_idx) {
if (suffix_data[suf_idx] != str_data[str_idx]) {
return false;
}
}
return true;
}
ScalarFunction SuffixFun::GetFunction() {
return ScalarFunction("suffix", // name of the function
{LogicalType::VARCHAR, LogicalType::VARCHAR}, // argument list
LogicalType::BOOLEAN, // return type
ScalarFunction::BinaryFunction<string_t, string_t, bool, SuffixOperator, true>);
}
void SuffixFun::RegisterFunction(BuiltinFunctions &set) {
set.AddFunction(GetFunction());
}
} // namespace duckdb
| 28.632653 | 103 | 0.665716 | AdamKorcz |
d10aa175883debfa6a2ed2df0f352342fbe3048d | 211 | hpp | C++ | app/AppRunner.hpp | ChristopherCanfield/canfield_ant_simulator | 9ec671fe4936a8ed3a19f2c79a54e420092769fe | [
"MIT"
] | 1 | 2016-01-29T06:25:36.000Z | 2016-01-29T06:25:36.000Z | app/AppRunner.hpp | ChristopherCanfield/canfield_ant_simulator | 9ec671fe4936a8ed3a19f2c79a54e420092769fe | [
"MIT"
] | null | null | null | app/AppRunner.hpp | ChristopherCanfield/canfield_ant_simulator | 9ec671fe4936a8ed3a19f2c79a54e420092769fe | [
"MIT"
] | null | null | null | #pragma once
#include "App.hpp"
// Christopher D. Canfield
// October 2013
// AppRunner.hpp
namespace cdc
{
class AppRunner
{
public:
AppRunner() {}
~AppRunner() {}
void execute(App& app);
};
} | 9.590909 | 26 | 0.630332 | ChristopherCanfield |
d10c1022c5bef0fe89795eefc41779312f3a3d25 | 4,146 | cpp | C++ | tcss/src/v20201101/model/ModifyVirusMonitorSettingRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tcss/src/v20201101/model/ModifyVirusMonitorSettingRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tcss/src/v20201101/model/ModifyVirusMonitorSettingRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tcss/v20201101/model/ModifyVirusMonitorSettingRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Tcss::V20201101::Model;
using namespace std;
ModifyVirusMonitorSettingRequest::ModifyVirusMonitorSettingRequest() :
m_enableScanHasBeenSet(false),
m_scanPathAllHasBeenSet(false),
m_scanPathTypeHasBeenSet(false),
m_scanPathHasBeenSet(false)
{
}
string ModifyVirusMonitorSettingRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_enableScanHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EnableScan";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_enableScan, allocator);
}
if (m_scanPathAllHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ScanPathAll";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_scanPathAll, allocator);
}
if (m_scanPathTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ScanPathType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_scanPathType, allocator);
}
if (m_scanPathHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ScanPath";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_scanPath.begin(); itr != m_scanPath.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
bool ModifyVirusMonitorSettingRequest::GetEnableScan() const
{
return m_enableScan;
}
void ModifyVirusMonitorSettingRequest::SetEnableScan(const bool& _enableScan)
{
m_enableScan = _enableScan;
m_enableScanHasBeenSet = true;
}
bool ModifyVirusMonitorSettingRequest::EnableScanHasBeenSet() const
{
return m_enableScanHasBeenSet;
}
bool ModifyVirusMonitorSettingRequest::GetScanPathAll() const
{
return m_scanPathAll;
}
void ModifyVirusMonitorSettingRequest::SetScanPathAll(const bool& _scanPathAll)
{
m_scanPathAll = _scanPathAll;
m_scanPathAllHasBeenSet = true;
}
bool ModifyVirusMonitorSettingRequest::ScanPathAllHasBeenSet() const
{
return m_scanPathAllHasBeenSet;
}
uint64_t ModifyVirusMonitorSettingRequest::GetScanPathType() const
{
return m_scanPathType;
}
void ModifyVirusMonitorSettingRequest::SetScanPathType(const uint64_t& _scanPathType)
{
m_scanPathType = _scanPathType;
m_scanPathTypeHasBeenSet = true;
}
bool ModifyVirusMonitorSettingRequest::ScanPathTypeHasBeenSet() const
{
return m_scanPathTypeHasBeenSet;
}
vector<string> ModifyVirusMonitorSettingRequest::GetScanPath() const
{
return m_scanPath;
}
void ModifyVirusMonitorSettingRequest::SetScanPath(const vector<string>& _scanPath)
{
m_scanPath = _scanPath;
m_scanPathHasBeenSet = true;
}
bool ModifyVirusMonitorSettingRequest::ScanPathHasBeenSet() const
{
return m_scanPathHasBeenSet;
}
| 27.64 | 104 | 0.733237 | suluner |
d111089c7c015c4b4d0049c87a575b577a2ccebf | 3,841 | hpp | C++ | libraries/eos-vm/include/eosio/vm/opcodes.hpp | pizzachain/pizchain | ba51553e46521ca7b265d7045d678312a32f8140 | [
"MIT"
] | 1,313 | 2018-01-09T01:49:01.000Z | 2022-02-26T11:10:40.000Z | src/vm/wasm/eos-vm/include/eosio/vm/opcodes.hpp | linnbenton/WaykiChain | 91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a | [
"MIT"
] | 32 | 2018-06-07T10:21:21.000Z | 2021-12-07T06:53:42.000Z | src/vm/wasm/eos-vm/include/eosio/vm/opcodes.hpp | linnbenton/WaykiChain | 91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a | [
"MIT"
] | 322 | 2018-02-26T03:41:36.000Z | 2022-02-08T08:12:16.000Z | #pragma once
#include <eosio/vm/opcodes_def.hpp>
#include <eosio/vm/variant.hpp>
#include <map>
namespace eosio { namespace vm {
enum opcodes {
EOS_VM_CONTROL_FLOW_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_BR_TABLE_OP(EOS_VM_CREATE_ENUM)
EOS_VM_RETURN_OP(EOS_VM_CREATE_ENUM)
EOS_VM_CALL_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_CALL_IMM_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_PARAMETRIC_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_VARIABLE_ACCESS_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_MEMORY_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_I32_CONSTANT_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_I64_CONSTANT_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_F32_CONSTANT_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_F64_CONSTANT_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_COMPARISON_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_NUMERIC_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_CONVERSION_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_EXIT_OP(EOS_VM_CREATE_ENUM)
EOS_VM_EMPTY_OPS(EOS_VM_CREATE_ENUM)
EOS_VM_ERROR_OPS(EOS_VM_CREATE_ENUM)
};
struct opcode_utils {
std::map<uint16_t, std::string> opcode_map{
EOS_VM_CONTROL_FLOW_OPS(EOS_VM_CREATE_MAP)
EOS_VM_BR_TABLE_OP(EOS_VM_CREATE_MAP)
EOS_VM_RETURN_OP(EOS_VM_CREATE_MAP)
EOS_VM_CALL_OPS(EOS_VM_CREATE_MAP)
EOS_VM_CALL_IMM_OPS(EOS_VM_CREATE_MAP)
EOS_VM_PARAMETRIC_OPS(EOS_VM_CREATE_MAP)
EOS_VM_VARIABLE_ACCESS_OPS(EOS_VM_CREATE_MAP)
EOS_VM_MEMORY_OPS(EOS_VM_CREATE_MAP)
EOS_VM_I32_CONSTANT_OPS(EOS_VM_CREATE_MAP)
EOS_VM_I64_CONSTANT_OPS(EOS_VM_CREATE_MAP)
EOS_VM_F32_CONSTANT_OPS(EOS_VM_CREATE_MAP)
EOS_VM_F64_CONSTANT_OPS(EOS_VM_CREATE_MAP)
EOS_VM_COMPARISON_OPS(EOS_VM_CREATE_MAP)
EOS_VM_NUMERIC_OPS(EOS_VM_CREATE_MAP)
EOS_VM_CONVERSION_OPS(EOS_VM_CREATE_MAP)
EOS_VM_EXIT_OP(EOS_VM_CREATE_MAP)
EOS_VM_EMPTY_OPS(EOS_VM_CREATE_MAP)
EOS_VM_ERROR_OPS(EOS_VM_CREATE_MAP)
};
};
enum imm_types {
none,
block_imm,
varuint32_imm,
br_table_imm,
};
EOS_VM_CONTROL_FLOW_OPS(EOS_VM_CREATE_CONTROL_FLOW_TYPES)
EOS_VM_BR_TABLE_OP(EOS_VM_CREATE_BR_TABLE_TYPE)
EOS_VM_RETURN_OP(EOS_VM_CREATE_CONTROL_FLOW_TYPES)
EOS_VM_CALL_OPS(EOS_VM_CREATE_CALL_TYPES)
EOS_VM_CALL_IMM_OPS(EOS_VM_CREATE_CALL_IMM_TYPES)
EOS_VM_PARAMETRIC_OPS(EOS_VM_CREATE_TYPES)
EOS_VM_VARIABLE_ACCESS_OPS(EOS_VM_CREATE_VARIABLE_ACCESS_TYPES)
EOS_VM_MEMORY_OPS(EOS_VM_CREATE_MEMORY_TYPES)
EOS_VM_I32_CONSTANT_OPS(EOS_VM_CREATE_I32_CONSTANT_TYPE)
EOS_VM_I64_CONSTANT_OPS(EOS_VM_CREATE_I64_CONSTANT_TYPE)
EOS_VM_F32_CONSTANT_OPS(EOS_VM_CREATE_F32_CONSTANT_TYPE)
EOS_VM_F64_CONSTANT_OPS(EOS_VM_CREATE_F64_CONSTANT_TYPE)
EOS_VM_COMPARISON_OPS(EOS_VM_CREATE_TYPES)
EOS_VM_NUMERIC_OPS(EOS_VM_CREATE_TYPES)
EOS_VM_CONVERSION_OPS(EOS_VM_CREATE_TYPES)
EOS_VM_EXIT_OP(EOS_VM_CREATE_EXIT_TYPE)
EOS_VM_EMPTY_OPS(EOS_VM_CREATE_TYPES)
EOS_VM_ERROR_OPS(EOS_VM_CREATE_TYPES)
using opcode = variant<
EOS_VM_CONTROL_FLOW_OPS(EOS_VM_IDENTITY)
EOS_VM_BR_TABLE_OP(EOS_VM_IDENTITY)
EOS_VM_RETURN_OP(EOS_VM_IDENTITY)
EOS_VM_CALL_OPS(EOS_VM_IDENTITY)
EOS_VM_CALL_IMM_OPS(EOS_VM_IDENTITY)
EOS_VM_PARAMETRIC_OPS(EOS_VM_IDENTITY)
EOS_VM_VARIABLE_ACCESS_OPS(EOS_VM_IDENTITY)
EOS_VM_MEMORY_OPS(EOS_VM_IDENTITY)
EOS_VM_I32_CONSTANT_OPS(EOS_VM_IDENTITY)
EOS_VM_I64_CONSTANT_OPS(EOS_VM_IDENTITY)
EOS_VM_F32_CONSTANT_OPS(EOS_VM_IDENTITY)
EOS_VM_F64_CONSTANT_OPS(EOS_VM_IDENTITY)
EOS_VM_COMPARISON_OPS(EOS_VM_IDENTITY)
EOS_VM_NUMERIC_OPS(EOS_VM_IDENTITY)
EOS_VM_CONVERSION_OPS(EOS_VM_IDENTITY)
EOS_VM_EXIT_OP(EOS_VM_IDENTITY)
EOS_VM_EMPTY_OPS(EOS_VM_IDENTITY)
EOS_VM_ERROR_OPS(EOS_VM_IDENTITY_END)
>;
}} // namespace eosio::vm
| 38.41 | 66 | 0.787555 | pizzachain |
d1112cc9ba8a907848b28fc67ed6bbfbefee1454 | 6,818 | cxx | C++ | Servers/ServerManager/vtkSMLookupTableProxy.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 1 | 2021-07-31T19:38:03.000Z | 2021-07-31T19:38:03.000Z | Servers/ServerManager/vtkSMLookupTableProxy.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | null | null | null | Servers/ServerManager/vtkSMLookupTableProxy.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 2 | 2019-01-22T19:51:40.000Z | 2021-07-31T19:38:05.000Z | /*=========================================================================
Program: ParaView
Module: $RCSfile$
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSMLookupTableProxy.h"
#include "vtkClientServerStream.h"
#include "vtkObjectFactory.h"
#include "vtkProcessModule.h"
#include "vtkSMIntVectorProperty.h"
#include "vtkSMDoubleVectorProperty.h"
#include "vtkMath.h"
vtkStandardNewMacro(vtkSMLookupTableProxy);
vtkCxxRevisionMacro(vtkSMLookupTableProxy, "$Revision$");
//---------------------------------------------------------------------------
vtkSMLookupTableProxy::vtkSMLookupTableProxy()
{
this->SetVTKClassName("vtkLookupTable");
this->ArrayName = 0;
this->LowOutOfRangeColor[0] = this->LowOutOfRangeColor[1] =
this->LowOutOfRangeColor[2] = 0;
this->HighOutOfRangeColor[0] = this->HighOutOfRangeColor[1] =
this->HighOutOfRangeColor[2] = 1;
this->UseLowOutOfRangeColor = 0;
this->UseHighOutOfRangeColor = 0;
}
//---------------------------------------------------------------------------
vtkSMLookupTableProxy::~vtkSMLookupTableProxy()
{
this->SetVTKClassName(0);
this->SetArrayName(0);
}
//---------------------------------------------------------------------------
void vtkSMLookupTableProxy::CreateVTKObjects()
{
if (this->ObjectsCreated)
{
return;
}
this->SetServers(vtkProcessModule::CLIENT |
vtkProcessModule::RENDER_SERVER);
this->Superclass::CreateVTKObjects();
}
//---------------------------------------------------------------------------
void vtkSMLookupTableProxy::UpdateVTKObjects(vtkClientServerStream& stream)
{
this->Superclass::UpdateVTKObjects(stream);
this->Build();
}
//---------------------------------------------------------------------------
void vtkSMLookupTableProxy::Build()
{
vtkClientServerStream stream;
vtkSMProperty* p;
vtkSMIntVectorProperty* intVectProp;
vtkSMDoubleVectorProperty* doubleVectProp;
int numberOfTableValues;
double hueRange[2];
double saturationRange[2];
double valueRange[2];
p = this->GetProperty("NumberOfTableValues");
intVectProp = vtkSMIntVectorProperty::SafeDownCast(p);
numberOfTableValues = intVectProp->GetElement(0);
p = this->GetProperty("HueRange");
doubleVectProp = vtkSMDoubleVectorProperty::SafeDownCast(p);
hueRange[0] = doubleVectProp->GetElement(0);
hueRange[1] = doubleVectProp->GetElement(1);
p = this->GetProperty("ValueRange");
doubleVectProp = vtkSMDoubleVectorProperty::SafeDownCast(p);
valueRange[0] = doubleVectProp->GetElement(0);
valueRange[1] = doubleVectProp->GetElement(1);
p = this->GetProperty("SaturationRange");
doubleVectProp = vtkSMDoubleVectorProperty::SafeDownCast(p);
saturationRange[0] = doubleVectProp->GetElement(0);
saturationRange[1] = doubleVectProp->GetElement(1);
if (hueRange[0]<1.1) // Hack to deal with sandia color map.
{ // not Sandia interpolation.
stream << vtkClientServerStream::Invoke << this->GetID()
<< "ForceBuild" << vtkClientServerStream::End;
int numColors = (numberOfTableValues < 1) ? 1 : numberOfTableValues;
if (this->UseLowOutOfRangeColor)
{
stream << vtkClientServerStream::Invoke
<< this->GetID() << "SetTableValue" << 0
<< this->LowOutOfRangeColor[0] << this->LowOutOfRangeColor[1]
<< this->LowOutOfRangeColor[2] << 1
<< vtkClientServerStream::End;
}
if (this->UseHighOutOfRangeColor)
{
stream << vtkClientServerStream::Invoke << this->GetID()
<< "SetTableValue" << numColors-1
<< this->HighOutOfRangeColor[0] << this->HighOutOfRangeColor[1]
<< this->HighOutOfRangeColor[2]
<< 1 << vtkClientServerStream::End;
}
}
else
{
//now we need to loop through the number of colors setting the colors
//in the table
stream << vtkClientServerStream::Invoke
<< this->GetID() << "SetNumberOfTableValues"
<< numberOfTableValues
<< vtkClientServerStream::End;
int j;
double rgba[4];
double xyz[3];
double lab[3];
//only use opaque colors
rgba[3]=1;
int numColors= numberOfTableValues - 1;
if (numColors<=0) numColors=1;
for (j=0;j<numberOfTableValues;j++)
{
// Get the color
lab[0] = hueRange[0]+(hueRange[1]-hueRange[0])/(numColors)*j;
lab[1] = saturationRange[0]+(saturationRange[1]-saturationRange[0])/
(numColors)*j;
lab[2] = valueRange[0]+(valueRange[1]-valueRange[0])/
(numColors)*j;
vtkMath::LabToXYZ(lab,xyz);
vtkMath::XYZToRGB(xyz,rgba);
stream << vtkClientServerStream::Invoke
<< this->GetID() << "SetTableValue" << j
<< rgba[0] << rgba[1] << rgba[2] << rgba[3]
<< vtkClientServerStream::End;
}
if (this->UseLowOutOfRangeColor)
{
stream << vtkClientServerStream::Invoke << this->GetID()
<< "SetTableValue 0" << this->LowOutOfRangeColor[0]
<< this->LowOutOfRangeColor[1] << this->LowOutOfRangeColor[2]
<< 1 << vtkClientServerStream::End;
}
if (this->UseHighOutOfRangeColor)
{
stream << vtkClientServerStream::Invoke << this->GetID()
<< "SetTableValue" << numColors-1
<< this->HighOutOfRangeColor[0] << this->HighOutOfRangeColor[1]
<< this->HighOutOfRangeColor[2]
<< 1 << vtkClientServerStream::End;
}
}
vtkProcessModule* pm = vtkProcessModule::GetProcessModule();
pm->SendStream(this->ConnectionID, this->Servers, stream);
}
//---------------------------------------------------------------------------
void vtkSMLookupTableProxy::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ArrayName: "
<< (this->ArrayName?this->ArrayName:"(none)") << endl;
os << indent << "LowOutOfRangeColor: " << this->LowOutOfRangeColor[0]
<< " " << this->LowOutOfRangeColor[1] << " "
<< this->LowOutOfRangeColor[2] << endl;
os << indent << "HighOutOfRangeColor: " << this->HighOutOfRangeColor[0]
<< " " << this->HighOutOfRangeColor[1] << " "
<< this->HighOutOfRangeColor[2] << endl;
os << indent << "UseLowOutOfRangeColor: " << this->UseLowOutOfRangeColor
<< endl;
os << indent << "UseHighOutOfRangeColor: " << this->UseHighOutOfRangeColor
<< endl;
}
| 34.09 | 79 | 0.601496 | matthb2 |
d1113b9fefec12a5e6eee6acf59642f0769b9b9f | 7,343 | cpp | C++ | sounddev/SoundDeviceBase.cpp | Wapitiii/openmpt | 339c5f7f7e2c4a522415b42f0b6a9f4b2e2ab3bd | [
"BSD-3-Clause"
] | 4 | 2020-06-15T07:02:08.000Z | 2021-08-01T22:38:46.000Z | sounddev/SoundDeviceBase.cpp | glowcoil/microplug | 5c2708b89837dbc38a1f0e7cd793e5e53838e4a4 | [
"BSD-3-Clause"
] | null | null | null | sounddev/SoundDeviceBase.cpp | glowcoil/microplug | 5c2708b89837dbc38a1f0e7cd793e5e53838e4a4 | [
"BSD-3-Clause"
] | 1 | 2021-06-07T03:14:59.000Z | 2021-06-07T03:14:59.000Z | /*
* SoundDeviceBase.cpp
* -------------------
* Purpose: Sound device drivers base class.
* Notes : (currently none)
* Authors: Olivier Lapicque
* OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "SoundDeviceBase.h"
OPENMPT_NAMESPACE_BEGIN
namespace SoundDevice {
Base::Base(SoundDevice::Info info, SoundDevice::SysInfo sysInfo)
: m_Source(nullptr)
, m_MessageReceiver(nullptr)
, m_Info(info)
, m_SysInfo(sysInfo)
, m_StreamPositionOutputFrames(0)
, m_RequestFlags(0)
{
MPT_TRACE_SCOPE();
m_DeviceUnavailableOnOpen = false;
m_IsPlaying = false;
m_StreamPositionRenderFrames = 0;
m_StreamPositionOutputFrames = 0;
m_RequestFlags.store(0);
}
Base::~Base()
{
MPT_TRACE_SCOPE();
return;
}
SoundDevice::DynamicCaps Base::GetDeviceDynamicCaps(const std::vector<uint32> &baseSampleRates)
{
MPT_TRACE_SCOPE();
SoundDevice::DynamicCaps result;
result.supportedSampleRates = baseSampleRates;
return result;
}
bool Base::Init(const SoundDevice::AppInfo &appInfo)
{
MPT_TRACE_SCOPE();
if(IsInited())
{
return true;
}
m_AppInfo = appInfo;
m_Caps = InternalGetDeviceCaps();
return m_Caps.Available;
}
bool Base::Open(const SoundDevice::Settings &settings)
{
MPT_TRACE_SCOPE();
if(IsOpen())
{
Close();
}
m_Settings = settings;
if(m_Settings.Latency == 0.0) m_Settings.Latency = m_Caps.DefaultSettings.Latency;
if(m_Settings.UpdateInterval == 0.0) m_Settings.UpdateInterval = m_Caps.DefaultSettings.UpdateInterval;
m_Settings.Latency = std::clamp(m_Settings.Latency, m_Caps.LatencyMin, m_Caps.LatencyMax);
m_Settings.UpdateInterval = std::clamp(m_Settings.UpdateInterval, m_Caps.UpdateIntervalMin, m_Caps.UpdateIntervalMax);
m_Flags = SoundDevice::Flags();
m_DeviceUnavailableOnOpen = false;
m_RequestFlags.store(0);
return InternalOpen();
}
bool Base::Close()
{
MPT_TRACE_SCOPE();
if(!IsOpen()) return true;
Stop();
bool result = InternalClose();
m_RequestFlags.store(0);
return result;
}
uint64 Base::SourceGetReferenceClockNowNanoseconds() const
{
MPT_TRACE_SCOPE();
if(!m_Source)
{
return 0;
}
uint64 result = m_Source->SoundSourceGetReferenceClockNowNanoseconds();
//MPT_LOG(LogDebug, "sounddev", mpt::format(U_("clock: %1"))(result));
return result;
}
uint64 Base::SourceLockedGetReferenceClockNowNanoseconds() const
{
MPT_TRACE_SCOPE();
if(!m_Source)
{
return 0;
}
uint64 result = m_Source->SoundSourceLockedGetReferenceClockNowNanoseconds();
//MPT_LOG(LogDebug, "sounddev", mpt::format(U_("clock-rt: %1"))(result));
return result;
}
void Base::SourceNotifyPreStart()
{
MPT_TRACE_SCOPE();
if(m_Source)
{
m_Source->SoundSourcePreStartCallback();
}
}
void Base::SourceNotifyPostStop()
{
MPT_TRACE_SCOPE();
if(m_Source)
{
m_Source->SoundSourcePostStopCallback();
}
}
bool Base::SourceIsLockedByCurrentThread() const
{
MPT_TRACE_SCOPE();
if(!m_Source)
{
return false;
}
return m_Source->SoundSourceIsLockedByCurrentThread();
}
void Base::SourceFillAudioBufferLocked()
{
MPT_TRACE_SCOPE();
if(m_Source)
{
SourceLockedGuard lock(*m_Source);
InternalFillAudioBuffer();
}
}
void Base::SourceLockedAudioReadPrepare(std::size_t numFrames, std::size_t framesLatency)
{
MPT_TRACE_SCOPE();
if(!InternalHasTimeInfo())
{
SoundDevice::TimeInfo timeInfo;
if(InternalHasGetStreamPosition())
{
timeInfo.SyncPointStreamFrames = InternalHasGetStreamPosition();
timeInfo.SyncPointSystemTimestamp = SourceLockedGetReferenceClockNowNanoseconds();
timeInfo.Speed = 1.0;
} else
{
timeInfo.SyncPointStreamFrames = m_StreamPositionRenderFrames + numFrames;
timeInfo.SyncPointSystemTimestamp = SourceLockedGetReferenceClockNowNanoseconds() + mpt::saturate_round<int64>(GetEffectiveBufferAttributes().Latency * 1000000000.0);
timeInfo.Speed = 1.0;
}
timeInfo.RenderStreamPositionBefore = StreamPositionFromFrames(m_StreamPositionRenderFrames);
timeInfo.RenderStreamPositionAfter = StreamPositionFromFrames(m_StreamPositionRenderFrames + numFrames);
timeInfo.Latency = GetEffectiveBufferAttributes().Latency;
SetTimeInfo(timeInfo);
}
m_StreamPositionRenderFrames += numFrames;
if(!InternalHasGetStreamPosition() && !InternalHasTimeInfo())
{
m_StreamPositionOutputFrames = m_StreamPositionRenderFrames - framesLatency;
} else
{
// unused, no locking
m_StreamPositionOutputFrames = 0;
}
if(m_Source)
{
m_Source->SoundSourceLockedReadPrepare(m_TimeInfo);
}
}
void Base::SourceLockedAudioRead(void *buffer, const void *inputBuffer, std::size_t numFrames)
{
MPT_TRACE_SCOPE();
if(numFrames <= 0)
{
return;
}
if(m_Source)
{
m_Source->SoundSourceLockedRead(GetBufferFormat(), numFrames, buffer, inputBuffer);
}
}
void Base::SourceLockedAudioReadDone()
{
MPT_TRACE_SCOPE();
if(m_Source)
{
m_Source->SoundSourceLockedReadDone(m_TimeInfo);
}
}
void Base::SendDeviceMessage(LogLevel level, const mpt::ustring &str)
{
MPT_TRACE_SCOPE();
MPT_LOG(level, "sounddev", str);
if(m_MessageReceiver)
{
m_MessageReceiver->SoundDeviceMessage(level, str);
}
}
bool Base::Start()
{
MPT_TRACE_SCOPE();
if(!IsOpen()) return false;
if(!IsPlaying())
{
m_StreamPositionRenderFrames = 0;
{
m_StreamPositionOutputFrames = 0;
}
SourceNotifyPreStart();
m_RequestFlags.fetch_and((~RequestFlagRestart).as_bits());
if(!InternalStart())
{
SourceNotifyPostStop();
return false;
}
m_IsPlaying = true;
}
return true;
}
void Base::Stop()
{
MPT_TRACE_SCOPE();
if(!IsOpen()) return;
if(IsPlaying())
{
InternalStop();
m_RequestFlags.fetch_and((~RequestFlagRestart).as_bits());
SourceNotifyPostStop();
m_IsPlaying = false;
m_StreamPositionOutputFrames = 0;
m_StreamPositionRenderFrames = 0;
}
}
void Base::StopAndAvoidPlayingSilence()
{
MPT_TRACE_SCOPE();
if(!IsOpen())
{
return;
}
if(!IsPlaying())
{
return;
}
InternalStopAndAvoidPlayingSilence();
m_RequestFlags.fetch_and((~RequestFlagRestart).as_bits());
SourceNotifyPostStop();
m_IsPlaying = false;
m_StreamPositionOutputFrames = 0;
m_StreamPositionRenderFrames = 0;
}
void Base::EndPlayingSilence()
{
MPT_TRACE_SCOPE();
if(!IsOpen())
{
return;
}
if(IsPlaying())
{
return;
}
InternalEndPlayingSilence();
}
SoundDevice::StreamPosition Base::GetStreamPosition() const
{
MPT_TRACE_SCOPE();
if(!IsOpen())
{
return StreamPosition();
}
int64 frames = 0;
if(InternalHasGetStreamPosition())
{
frames = InternalGetStreamPositionFrames();
} else if(InternalHasTimeInfo())
{
const uint64 now = SourceGetReferenceClockNowNanoseconds();
const SoundDevice::TimeInfo timeInfo = GetTimeInfo();
frames = mpt::saturate_round<int64>(
timeInfo.SyncPointStreamFrames + (
static_cast<double>(static_cast<int64>(now - timeInfo.SyncPointSystemTimestamp)) * timeInfo.Speed * m_Settings.Samplerate * (1.0 / (1000.0 * 1000.0))
)
);
} else
{
frames = m_StreamPositionOutputFrames;
}
return StreamPositionFromFrames(frames);
}
SoundDevice::Statistics Base::GetStatistics() const
{
MPT_TRACE_SCOPE();
SoundDevice::Statistics result;
result.InstantaneousLatency = m_Settings.Latency;
result.LastUpdateInterval = m_Settings.UpdateInterval;
result.text = mpt::ustring();
return result;
}
} // namespace SoundDevice
OPENMPT_NAMESPACE_END
| 20.397222 | 169 | 0.74234 | Wapitiii |
d1139d7bdcff4c9e08d8f74bf3d09b42a3febf52 | 1,111 | cpp | C++ | Algorithms/Easy/53.maximum-subarray.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | Algorithms/Easy/53.maximum-subarray.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | Algorithms/Easy/53.maximum-subarray.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=53 lang=cpp
*
* [53] Maximum Subarray
*
* https://leetcode.com/problems/maximum-subarray/description/
*
* algorithms
* Easy (42.60%)
* Total Accepted: 456.2K
* Total Submissions: 1.1M
* Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]'
*
* Given an integer array nums, find the contiguous subarray (containing at
* least one number) which has the largest sum and return its sum.
*
* Example:
*
*
* Input: [-2,1,-3,4,-1,2,1,-5,4],
* Output: 6
* Explanation: [4,-1,2,1] has the largest sum = 6.
*
*
* Follow up:
*
* If you have figured out the O(n) solution, try coding another solution using
* the divide and conquer approach, which is more subtle.
*
*/
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = nums[0];
int smax = nums[0];
pair<int, int> indexes;
for (int i = 1, len = nums.size(); i < len; ++i) {
if (nums[i] > sum + nums[i]) {
sum = nums[i];
indexes.first = i;
}
else {
sum = sum + nums[i];
}
if (sum > smax) {
smax = sum;
indexes.second = i;
}
}
return smax;
}
};
| 20.574074 | 79 | 0.588659 | jtcheng |
d11403f76131eec16664899bfef104119a86aa00 | 6,449 | cpp | C++ | src/Engine/Renderer/RenderTechnique/RenderTechnique.cpp | hoshiryu/Radium-Engine | 2bc3c475a8fb1948dad84d1278bf4d61258f3cda | [
"Apache-2.0"
] | null | null | null | src/Engine/Renderer/RenderTechnique/RenderTechnique.cpp | hoshiryu/Radium-Engine | 2bc3c475a8fb1948dad84d1278bf4d61258f3cda | [
"Apache-2.0"
] | null | null | null | src/Engine/Renderer/RenderTechnique/RenderTechnique.cpp | hoshiryu/Radium-Engine | 2bc3c475a8fb1948dad84d1278bf4d61258f3cda | [
"Apache-2.0"
] | null | null | null | #include <Engine/Renderer/RenderTechnique/RenderTechnique.hpp>
#include <Engine/Renderer/Material/BlinnPhongMaterial.hpp>
#include <Engine/Renderer/RenderTechnique/RenderParameters.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderConfigFactory.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderProgramManager.hpp>
#include <Core/Utils/Log.hpp>
namespace Ra {
namespace Engine {
using namespace Core::Utils; // log
std::shared_ptr<Ra::Engine::RenderTechnique> RadiumDefaultRenderTechnique {nullptr};
RenderTechnique::RenderTechnique() : m_numActivePass {0} {
for ( auto p = Index( 0 ); p < s_maxNbPasses; ++p )
{
m_activePasses[p] = std::move( PassConfiguration( ShaderConfiguration(), nullptr ) );
m_passesParameters[p] = nullptr;
}
}
RenderTechnique::RenderTechnique( const RenderTechnique& o ) :
m_numActivePass {o.m_numActivePass}, m_dirtyBits {o.m_dirtyBits}, m_setPasses {o.m_setPasses} {
for ( auto p = Index( 0 ); p < m_numActivePass; ++p )
{
if ( hasConfiguration( p ) )
{
m_activePasses[p] = o.m_activePasses[p];
m_passesParameters[p] = o.m_passesParameters[p];
}
}
}
RenderTechnique::~RenderTechnique() = default;
void RenderTechnique::setConfiguration( const ShaderConfiguration& newConfig,
Core::Utils::Index pass ) {
m_numActivePass = std::max( m_numActivePass, pass + 1 );
m_activePasses[pass] = std::move( PassConfiguration( newConfig, nullptr ) );
setDirty( pass );
setConfiguration( pass );
}
const ShaderProgram* RenderTechnique::getShader( Core::Utils::Index pass ) const {
if ( hasConfiguration( pass ) ) { return m_activePasses[pass].second; }
return nullptr;
}
void RenderTechnique::setParametersProvider( std::shared_ptr<ShaderParameterProvider> provider,
Core::Utils::Index pass ) {
if ( m_numActivePass == 0 )
{
LOG( logERROR )
<< "Unable to set pass parameters : is passes configured using setConfiguration ? ";
return;
}
if ( pass.isValid() )
{
if ( hasConfiguration( pass ) ) { m_passesParameters[pass] = provider; }
}
else
{
for ( int i = 0; i < m_numActivePass; ++i )
{
if ( hasConfiguration( i ) ) { m_passesParameters[i] = provider; }
}
}
// add the provider specific properties to the configuration
addPassProperties( provider->getPropertyList() );
}
void RenderTechnique::addPassProperties( const std::list<std::string>& props,
Core::Utils::Index pass ) {
if ( m_numActivePass == 0 )
{
LOG( logERROR )
<< "Unable to set pass properties : is passes configured using setConfiguration ? ";
return;
}
if ( pass.isValid() && hasConfiguration( pass ) )
{
m_activePasses[pass].first.addProperties( props );
setDirty( pass );
}
else
{
for ( int i = 0; i < m_numActivePass; ++i )
{
if ( hasConfiguration( i ) )
{
m_activePasses[i].first.addProperties( props );
setDirty( i );
}
}
}
}
const ShaderParameterProvider*
RenderTechnique::getParametersProvider( Core::Utils::Index pass ) const {
if ( hasConfiguration( pass ) ) { return m_passesParameters[pass].get(); }
return nullptr;
}
void RenderTechnique::updateGL() {
for ( auto p = Index( 0 ); p < m_numActivePass; ++p )
{
if ( hasConfiguration( p ) && ( ( nullptr == m_activePasses[p].second ) || isDirty( p ) ) )
{
m_activePasses[p].second =
ShaderProgramManager::getInstance()->getShaderProgram( m_activePasses[p].first );
clearDirty( p );
}
}
for ( auto p = Index( 0 ); p < m_numActivePass; ++p )
{
if ( m_passesParameters[p] ) { m_passesParameters[p]->updateGL(); }
}
}
///////////////////////////////////////////////
Ra::Engine::RenderTechnique RenderTechnique::createDefaultRenderTechnique() {
if ( RadiumDefaultRenderTechnique != nullptr )
{ return *( RadiumDefaultRenderTechnique.get() ); }
std::shared_ptr<Material> mat( new BlinnPhongMaterial( "DefaultGray" ) );
auto rt = new Ra::Engine::RenderTechnique;
auto builder = EngineRenderTechniques::getDefaultTechnique( "BlinnPhong" );
if ( !builder.first )
{
LOG( logERROR ) << "Unable to create the default technique : is the Engine initialized ? ";
}
builder.second( *rt, false );
rt->setParametersProvider( mat );
RadiumDefaultRenderTechnique.reset( rt );
return *( RadiumDefaultRenderTechnique.get() );
}
///////////////////////////////////////////////
//// Radium defined technique ///
///////////////////////////////////////////////
namespace EngineRenderTechniques {
/// Map that stores each technique builder function
static std::map<std::string, DefaultTechniqueBuilder> EngineTechniqueRegistry;
/** register a new default builder for a technique
* @return true if builder added, false else (e.g, a builder with the same name exists)
*/
bool registerDefaultTechnique( const std::string& name, DefaultTechniqueBuilder builder ) {
auto result = EngineTechniqueRegistry.insert( {name, builder} );
return result.second;
}
/** remove a default builder
* @return true if builder removed, false else (e.g, a builder with the same name does't exists)
*/
bool removeDefaultTechnique( const std::string& name ) {
std::size_t removed = EngineTechniqueRegistry.erase( name );
return ( removed == 1 );
}
/**
* @param name name of the technique to construct
* @return a pair containing the search result and, if true, the functor to call to build the
* technique.
*/
std::pair<bool, DefaultTechniqueBuilder> getDefaultTechnique( const std::string& name ) {
auto search = EngineTechniqueRegistry.find( name );
if ( search != EngineTechniqueRegistry.end() ) { return {true, search->second}; }
auto result = std::make_pair( false, [name]( RenderTechnique&, bool ) -> void {
LOG( logERROR ) << "Undefined default technique for " << name << " !";
} );
return result;
}
bool cleanup() {
EngineTechniqueRegistry.clear();
return true;
}
} // namespace EngineRenderTechniques
} // namespace Engine
} // namespace Ra
| 34.486631 | 99 | 0.627849 | hoshiryu |
d1169c4a8f2076df9ce85275cc2e537e6b1b629c | 5,867 | cpp | C++ | VerFI_for_attack/source/ReadCellReportFile.cpp | vinayby/VerFI | 96db0ca218b7c24d43c040745bf921b126a14f13 | [
"BSD-3-Clause"
] | null | null | null | VerFI_for_attack/source/ReadCellReportFile.cpp | vinayby/VerFI | 96db0ca218b7c24d43c040745bf921b126a14f13 | [
"BSD-3-Clause"
] | null | null | null | VerFI_for_attack/source/ReadCellReportFile.cpp | vinayby/VerFI | 96db0ca218b7c24d43c040745bf921b126a14f13 | [
"BSD-3-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////////
// COMPANY: Ruhr University Bochum, Embedded Security
// AUTHOR: Amir Moradi (for the paper: https://eprint.iacr.org/2019/1312 )
//////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019, Amir Moradi
// All rights reserved.
//
// BSD-3-Clause License
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder, their organization nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTERS 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 "ReadCellReportFile.h"
#include "Util.h"
#include <cstring>
#include <cstdio>
#include <cstdlib>
int ReadCellReportFile(HierarchyStruct** &Hierarchy, int &NumberOfHierarchy, char* InputCellReportFileName,
CellTypeStruct** CellTypes, int NumberOfCellTypes)
{
FILE *CellReportFile;
char *StrList[5];
int CellTypeIndex;
int CaseIndex;
char *Str1 = (char *)malloc(Max_Name_Length * sizeof(char));
char ch;
int i;
HierarchyStruct** TempHierarchy;
for (i = 0;i < 5;i++)
StrList[i] = (char *)malloc(Max_Name_Length * sizeof(char));
NumberOfHierarchy = 0;
CellReportFile = fopen(InputCellReportFileName, "rt");
if (CellReportFile == NULL)
{
printf("cell report file ""%s"" not found\n", InputCellReportFileName);
free(Str1);
return 1;
}
StrList[0][0] = 0;
StrList[1][0] = 0;
StrList[2][0] = 0;
StrList[3][0] = 0;
StrList[4][0] = 0;
do {
for (i = 4; i > 0;i--)
strcpy(StrList[i], StrList[i - 1]);
ReadNonCommentFromFile(CellReportFile, StrList[0], "**");
} while ((strcmp(StrList[4], "Cell") != 0|
strcmp(StrList[3], "Reference") != 0|
strcmp(StrList[2], "Library") != 0|
strcmp(StrList[1], "Area") != 0 |
strcmp(StrList[0], "Attributes") !=0 ) && (!feof(CellReportFile)));
if (feof(CellReportFile))
{
printf("cell report file seems not correct\n");
fclose(CellReportFile);
free(Str1);
for (i = 0;i < 5;i++)
free(StrList[i]);
return 1;
}
ReadNonCommentFromFile(CellReportFile, StrList[0], "**");
if (strstr(StrList[0], "--------------------") == NULL)
{
printf("cell report file seems not correct\n");
fclose(CellReportFile);
free(Str1);
for (i = 0;i < 5;i++)
free(StrList[i]);
return 1;
}
do
{
for (i = 0;i < 4;i++)
ReadNonCommentFromFile(CellReportFile, StrList[i], "**");
if (strstr(StrList[0], "--------------------") == NULL)
{
TempHierarchy = (HierarchyStruct **)malloc((NumberOfHierarchy + 1) * sizeof(HierarchyStruct *));
memcpy(TempHierarchy, Hierarchy, NumberOfHierarchy * sizeof(HierarchyStruct *));
free(Hierarchy);
Hierarchy = TempHierarchy;
Hierarchy[NumberOfHierarchy] = (HierarchyStruct *)malloc(sizeof(HierarchyStruct));
Hierarchy[NumberOfHierarchy]->Name = (char *)malloc(strlen(StrList[0]) + 2);
strcpy(Hierarchy[NumberOfHierarchy]->Name, StrList[0]);
strcpy(Str1, StrList[0]);
StrReplaceChar(Str1, '/', '_');
StrReplaceChar(Str1, '[', '_');
StrReplaceChar(Str1, ']', '_');
Hierarchy[NumberOfHierarchy]->CellName = (char *)malloc(strlen(Str1) + 2);
strcpy(Hierarchy[NumberOfHierarchy]->CellName, Str1);
for (CellTypeIndex = 0;CellTypeIndex < NumberOfCellTypes;CellTypeIndex++)
{
for (CaseIndex = 0;CaseIndex < CellTypes[CellTypeIndex]->NumberOfCases;CaseIndex++)
if (!strcmp(StrList[1], CellTypes[CellTypeIndex]->Cases[CaseIndex]))
{
//printf("%s---%s\n", StrList[1], CellTypes[CellTypeIndex]->Cases[CaseIndex]);
CaseIndex = -1;
break;
}
if (CaseIndex == -1)
break;
}
if (CellTypeIndex >= NumberOfCellTypes)
{
printf("type ""%s"" in cell report file not found in the library\n", StrList[1]);
fclose(CellReportFile);
free(Str1);
for (i = 0;i < 5;i++)
free(StrList[i]);
return 1;
}
Hierarchy[NumberOfHierarchy]->Type = CellTypeIndex;
NumberOfHierarchy++;
do {
ch = fgetc(CellReportFile);
} while (ch != '\n');
}
} while ((strstr(StrList[0], "--------------------") == NULL) & (!feof(CellReportFile)));
fclose(CellReportFile);
free(Str1);
if (strstr(StrList[0], "--------------------") == NULL)
{
printf("cell file seems not correct\n");
for(i = 0;i < 5;i++) {
free(StrList[i]);
}
return 1;
}
for (i = 0;i < 5;i++)
free(StrList[i]);
return 0;
}
//***************************************************************************************
| 33.718391 | 107 | 0.626555 | vinayby |
d1172b49c256ce5be60183c366fa7adf6977eaf4 | 479 | hpp | C++ | src/atlas/graphics/Earth.hpp | Groutcho/atlas | b69b7759be0361ffdcbbba64501e07feb79143be | [
"MIT"
] | 5 | 2018-12-13T03:41:12.000Z | 2020-08-27T04:45:11.000Z | src/atlas/graphics/Earth.hpp | Groutcho/atlas | b69b7759be0361ffdcbbba64501e07feb79143be | [
"MIT"
] | 1 | 2020-09-08T07:26:59.000Z | 2020-09-08T09:21:44.000Z | src/atlas/graphics/Earth.hpp | Groutcho/atlas | b69b7759be0361ffdcbbba64501e07feb79143be | [
"MIT"
] | 5 | 2018-12-20T10:31:09.000Z | 2021-09-07T07:38:49.000Z | //#ifndef ATLAS_GRAPHICS_EARTH_HPP
//#define ATLAS_GRAPHICS_EARTH_HPP
//
//#include "AtlasGraphics.hpp"
//#include "Node.hpp"
//#include "SurfaceTile.hpp"
//
//namespace atlas
//{
// namespace graphics
// {
// /**
// * @brief The Earth node manages the rendering of the surface of the earth.
// */
// class Earth : public Node
// {
// public:
// Earth();
// ~Earth();
// };
// }
//}
//
//#endif | 19.958333 | 89 | 0.517745 | Groutcho |
d11818a9e60220e0a8c6ef0f7075d8f9b21b1c69 | 1,184 | hpp | C++ | IcarusDetector/Checkers/ArmorCheckerBase.hpp | RoboPioneers/ProjectIcarus | 85328c0206d77617fe7fbb81b2ca0cda805de849 | [
"MIT"
] | 1 | 2021-10-05T03:43:57.000Z | 2021-10-05T03:43:57.000Z | IcarusDetector/Checkers/ArmorCheckerBase.hpp | RoboPioneers/ProjectIcarus | 85328c0206d77617fe7fbb81b2ca0cda805de849 | [
"MIT"
] | null | null | null | IcarusDetector/Checkers/ArmorCheckerBase.hpp | RoboPioneers/ProjectIcarus | 85328c0206d77617fe7fbb81b2ca0cda805de849 | [
"MIT"
] | null | null | null | #pragma once
#include "../Framework/CheckerBase.hpp"
#include "../Components/PONElement.hpp"
#include <cmath>
namespace Icarus
{
/// Distance scenario based light bar checker base class.
class ArmorCheckerBase : public CheckerBase<PONElement>
{
public:
double MaxLeaningAngle {};
double MaxDeltaAngle {};
ArmorCheckerBase()
{
CheckerBase::PatternTags = {"Armor"};
}
void LoadConfiguration() override
{
MaxLeaningAngle = Configurator->Get<double>("Armor/Base/MaxLeaningAngle").value_or(20);
MaxDeltaAngle = Configurator->Get<double>("Armor/Base/MaxDeltaAngle").value_or(20);
}
protected:
/// Check distance scenario.
bool CheckScenario(PONElement *candidate) override
{
if (candidate->Feature.Angle < (180.0 - MaxLeaningAngle) &&
candidate->Feature.Angle > MaxLeaningAngle)
return false;
if (std::fabs(candidate->ContourA->Feature.Angle - candidate->ContourB->Feature.Angle)
> MaxDeltaAngle)
return false;
return true;
}
};
} | 30.358974 | 99 | 0.597973 | RoboPioneers |
d1182965d6ae73674b0acea284736b76c82b5135 | 9,867 | cc | C++ | test/assimp_test.cc | leonlynch/cortex | 239ece88de004f35ef31ad3c57fb20b0b0d86bde | [
"MIT"
] | 1 | 2017-11-26T08:37:04.000Z | 2017-11-26T08:37:04.000Z | test/assimp_test.cc | leonlynch/cortex | 239ece88de004f35ef31ad3c57fb20b0b0d86bde | [
"MIT"
] | null | null | null | test/assimp_test.cc | leonlynch/cortex | 239ece88de004f35ef31ad3c57fb20b0b0d86bde | [
"MIT"
] | null | null | null | /**
* @file assimp_test.cc
*
* Copyright (c) 2013 Leon Lynch
*
* This file is licensed under the terms of the MIT license.
* See LICENSE file.
*/
#include <assimp/DefaultLogger.hpp>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <iostream>
#include <cstdio>
static void print_node_recursive(const aiNode* node, unsigned int node_depth = 0)
{
for (unsigned int i = 0; i < node_depth; ++i) {
std::printf("\t");
}
std::printf("'%s': mNumMeshes=%u", node->mName.C_Str(), node->mNumMeshes);
if (!node->mTransformation.IsIdentity()) {
std::printf("; mTransformation=present");
}
std::printf("\n");
for (unsigned int i = 0; i < node->mNumChildren; ++i) {
print_node_recursive(node->mChildren[i], node_depth + 1);
}
}
static void print_mesh(const struct aiMesh* mesh)
{
unsigned int mPrimitiveTypes;
unsigned int numColors = 0;
unsigned int numTextureCoords = 0;
std::printf("'%s': ", mesh->mName.C_Str());
std::printf("mPrimitiveTypes=");
mPrimitiveTypes = mesh->mPrimitiveTypes;
for (unsigned int i = 0; i < 4 && mPrimitiveTypes; ++i) {
if (mesh->mPrimitiveTypes & ((1 << i) - 1)) {
std::printf(",");
}
if ((mesh->mPrimitiveTypes & (1 << i)) == aiPrimitiveType_POINT) {
std::printf("POINT");
}
if ((mesh->mPrimitiveTypes & (1 << i)) == aiPrimitiveType_LINE) {
std::printf("LINE");
}
if ((mesh->mPrimitiveTypes & (1 << i)) == aiPrimitiveType_TRIANGLE) {
std::printf("TRIANGLE");
}
if ((mesh->mPrimitiveTypes & (1 << i)) == aiPrimitiveType_POLYGON) {
std::printf("POLYGON");
}
mPrimitiveTypes &= ~(1 << i);
}
std::printf("; ");
std::printf("mNumVertices=%u {%s%s%s}",
mesh->mNumVertices,
mesh->mNormals ? "mNormals" : "",
mesh->mTangents ? " mTangents" : "",
mesh->mBitangents ? " mBitangents" : ""
);
for (std::size_t i = 0; i < sizeof(mesh->mColors) / sizeof(mesh->mColors[0]); ++i) {
if (mesh->mColors[i])
++numColors;
}
if (numColors) {
std::printf("; mColors=%u", numColors);
}
for (std::size_t i = 0; i < sizeof(mesh->mTextureCoords) / sizeof(mesh->mTextureCoords[0]); ++i) {
if (mesh->mTextureCoords[i])
++numTextureCoords;
}
if (numTextureCoords) {
std::printf("; mTextureCoords=%u", numTextureCoords);
}
std::printf("; mNumFaces=%u; mNumBones=%u", mesh->mNumFaces, mesh->mNumBones);
std::printf("; mMaterialIndex=%u\n", mesh->mMaterialIndex);
}
template <typename T>
static void print_material_property_array(const void* data, std::size_t length)
{
const T* value = reinterpret_cast<const T*>(data);
std::size_t count = length / sizeof(T);
std::printf("{ ");
for (std::size_t i = 0; i < count; ++i) {
if (i)
std::printf(", ");
std::cout << value[i];
}
std::printf(" }\n");
}
// #define ASSIMP_TEST_ITERATE_MATERIAL_PROPERTIES
#ifdef ASSIMP_TEST_ITERATE_MATERIAL_PROPERTIES
static void print_material(const struct aiMaterial* material)
{
aiReturn ret;
aiString name;
ret = material->Get(AI_MATKEY_NAME, name);
if (ret == aiReturn_SUCCESS) {
std::printf("'%s':\n", name.C_Str());
} else {
std::printf("(none):\n");
}
for (unsigned int i = 0; i < material->mNumProperties; ++i) {
const struct aiMaterialProperty* property = material->mProperties[i];
std::printf("\t%s = ", property->mKey.C_Str());
if (property->mSemantic == aiTextureType_NONE) {
switch (property->mType) {
case aiPTI_Float:
std::printf("[Float/%u] ", property->mDataLength);
print_material_property_array<float>(property->mData, property->mDataLength);
break;
case aiPTI_Double:
std::printf("[Double/%u] ", property->mDataLength);
print_material_property_array<double>(property->mData, property->mDataLength);
break;
case aiPTI_String: {
aiString s;
ret = material->Get(property->mKey.C_Str(), property->mSemantic, property->mIndex, s);
std::printf("[String] '%s'\n", s.C_Str());
break;
}
case aiPTI_Integer:
std::printf("[Integer/%u] ", property->mDataLength);
print_material_property_array<unsigned int>(property->mData, property->mDataLength);
break;
case aiPTI_Buffer:
std::printf("[Buffer/%u]\n", property->mDataLength);
break;
default:
std::printf("[Unknown/%u]\n", property->mDataLength);
}
} else {
switch (property->mType) {
case aiPTI_String: {
aiString s;
ret = material->Get(property->mKey.C_Str(), property->mSemantic, property->mIndex, s);
std::printf("[Texture] '%s'\n", s.C_Str());
break;
}
case aiPTI_Integer: {
std::printf("[Texture] ");
print_material_property_array<unsigned int>(property->mData, property->mDataLength);
break;
}
default:
std::printf("[Texture/%u]\n", property->mDataLength);
}
}
}
}
#else
static void print_material(const struct aiMaterial* material)
{
aiReturn ret;
aiString name;
int twosided;
enum aiShadingMode shading;
enum aiBlendMode blend;
float opacity;
float shininess;
float shininess_strength;
aiColor3D diffuse;
aiColor3D ambient;
aiColor3D specular;
ret = material->Get(AI_MATKEY_NAME, name);
if (ret == aiReturn_SUCCESS) {
std::printf("'%s':\n", name.C_Str());
} else {
std::printf("'':\n");
}
ret = material->Get(AI_MATKEY_TWOSIDED, twosided);
if (ret == aiReturn_SUCCESS) {
std::printf("\tTwo sided = %s\n", twosided ? "true" : "false");
}
ret = material->Get(AI_MATKEY_SHADING_MODEL, shading);
if (ret == aiReturn_SUCCESS) {
std::printf("\tShading = %d\n", shading);
}
ret = material->Get(AI_MATKEY_BLEND_FUNC, blend);
if (ret == aiReturn_SUCCESS) {
std::printf("\tBlend = %d\n", blend);
}
ret = material->Get(AI_MATKEY_OPACITY, opacity);
if (ret == aiReturn_SUCCESS) {
std::printf("\tOpacity = %f\n", opacity);
}
ret = material->Get(AI_MATKEY_SHININESS, shininess);
if (ret == aiReturn_SUCCESS) {
std::printf("\tShininess = %f\n", shininess);
}
ret = material->Get(AI_MATKEY_SHININESS_STRENGTH, shininess_strength);
if (ret == aiReturn_SUCCESS) {
std::printf("\tShininess strength = %f\n", shininess_strength);
}
ret = material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse);
if (ret == aiReturn_SUCCESS) {
std::printf("\tDiffuse = { %f, %f, %f }\n", diffuse.r, diffuse.g, diffuse.b);
}
ret = material->Get(AI_MATKEY_COLOR_AMBIENT, ambient);
if (ret == aiReturn_SUCCESS) {
std::printf("\tAmbient = { %f, %f, %f }\n", ambient.r, ambient.g, ambient.b);
}
ret = material->Get(AI_MATKEY_COLOR_SPECULAR, specular);
if (ret == aiReturn_SUCCESS) {
std::printf("\tSpecular = { %f, %f, %f }\n", specular.r, specular.g, specular.b);
}
const aiTextureType texture_types[] = {
aiTextureType_NONE,
aiTextureType_DIFFUSE,
aiTextureType_SPECULAR,
aiTextureType_AMBIENT,
aiTextureType_EMISSIVE,
aiTextureType_HEIGHT,
aiTextureType_NORMALS,
aiTextureType_SHININESS,
aiTextureType_OPACITY,
aiTextureType_DISPLACEMENT,
aiTextureType_LIGHTMAP,
aiTextureType_REFLECTION,
aiTextureType_BASE_COLOR,
aiTextureType_NORMAL_CAMERA,
aiTextureType_EMISSION_COLOR,
aiTextureType_METALNESS,
aiTextureType_DIFFUSE_ROUGHNESS,
aiTextureType_AMBIENT_OCCLUSION,
aiTextureType_UNKNOWN
};
for (auto&& texture_type : texture_types) {
ret = AI_SUCCESS;
for (unsigned int idx = 0; ret == AI_SUCCESS; ++idx) {
aiString filename;
ret = material->Get(AI_MATKEY_TEXTURE(texture_type, idx), filename);
if (ret == AI_SUCCESS) {
std::printf("\tTexture(%u,%u) = '%s'\n", texture_type, idx, filename.C_Str());
continue;
}
int texture_idx;
ret = material->Get(AI_MATKEY_TEXTURE(texture_type, idx), texture_idx);
if (ret == AI_SUCCESS) {
std::printf("\tTexture(%u,%u) = #%u\n", texture_type, idx, texture_idx);
continue;
}
};
}
}
#endif
static void print_texture(unsigned int idx, const struct aiTexture* texture)
{
if (texture->mHeight) {
// uncompressed texture
std::printf("\t[%u]: %ux%u, ARGB8888\n", idx, texture->mWidth, texture->mHeight);
} else {
// compressed texture
std::printf("\t[%u]: %u bytes, %s\n", idx, texture->mWidth, texture->achFormatHint);
}
}
static int import_scene(const char* filename)
{
Assimp::Importer importer;
const aiScene* scene;
scene = importer.ReadFile(filename,
aiProcessPreset_TargetRealtime_MaxQuality
// aiProcess_JoinIdenticalVertices |
// aiProcess_Triangulate |
// aiProcess_ValidateDataStructure |
// aiProcess_RemoveRedundantMaterials |
// aiProcess_SortByPType
);
if (!scene) {
Assimp::DefaultLogger::get()->error(importer.GetErrorString());
return -1;
}
std::printf("\n%s summary:\n"
"\tmNumMeshes=%u\n"
"\tmNumMaterials=%u\n"
"\tmNumAnimations=%u\n"
"\tmNumTextures=%u\n"
"\tmNumLights=%u\n"
"\tmNumCameras=%u\n",
filename,
scene->mNumMeshes,
scene->mNumMaterials,
scene->mNumAnimations,
scene->mNumTextures,
scene->mNumLights,
scene->mNumCameras
);
std::printf("\n%s nodes:\n", filename);
print_node_recursive(scene->mRootNode);
std::printf("\n%s meshes[%u]:\n", filename, scene->mNumMeshes);
for (unsigned int i = 0; i < scene->mNumMeshes; ++i) {
print_mesh(scene->mMeshes[i]);
}
std::printf("\n%s materials[%u]:\n", filename, scene->mNumMaterials);
for (unsigned int i = 0; i < scene->mNumMaterials; ++i) {
print_material(scene->mMaterials[i]);
}
std::printf("\n%s textures[%u]:\n", filename, scene->mNumTextures);
for (unsigned int i = 0; i < scene->mNumTextures; ++i) {
print_texture(i, scene->mTextures[i]);
}
return 0;
}
int main(int argc, char** argv)
{
int r;
if (argc != 2) {
std::fprintf(stderr, "No import file specified\n");
return 1;
}
Assimp::DefaultLogger::create(nullptr, Assimp::Logger::VERBOSE, aiDefaultLogStream_STDERR);
r = import_scene(argv[1]);
if (r) {
std::fprintf(stderr, "Failed to import scene from '%s'\n", argv[1]);
}
Assimp::DefaultLogger::kill();
return r;
}
| 26.595687 | 99 | 0.666869 | leonlynch |
d11a5b1a0844f875585961a98af58bfd3e57f57c | 983 | hpp | C++ | app/dml/src/dml/dml_paras.hpp | alexrenz/bosen-2 | c61ac4e892ba2f6e02bd4595632b15f9e53450e2 | [
"BSD-3-Clause"
] | 370 | 2015-06-30T09:46:17.000Z | 2017-01-21T07:14:00.000Z | app/dml/src/dml/dml_paras.hpp | alexrenz/bosen-2 | c61ac4e892ba2f6e02bd4595632b15f9e53450e2 | [
"BSD-3-Clause"
] | 3 | 2016-11-08T19:45:19.000Z | 2016-11-11T13:21:19.000Z | app/dml/src/dml/dml_paras.hpp | alexrenz/bosen-2 | c61ac4e892ba2f6e02bd4595632b15f9e53450e2 | [
"BSD-3-Clause"
] | 159 | 2015-07-03T05:58:31.000Z | 2016-12-29T20:59:01.000Z | #ifndef APPS_DML_SRC_DML_DML_PARAS_H_
#define APPS_DML_SRC_DML_DML_PARAS_H_
struct DmlParas{
// original feature dimension
int src_feat_dim;
// target feature dimension
int dst_feat_dim;
// tradeoff parameter
float lambda;
// distance threshold
float thre;
// learning rate
float learn_rate;
int epoch;
// number of total pts
int num_total_pts;
// number of similar pairs
int num_simi_pairs;
// num of dissimilar pairs
int num_diff_pairs;
// number of total evaluation pts
int num_total_eval_pts;
// size of mini batch
int size_mb;
// num iters to do evaluation
int num_iters_evaluate;
// num smps to evaluate
int num_smps_evaluate;
// uniform initialization range
float unif_x;
float unif_y;
char data_file[512];
char simi_pair_file[512];
char diff_pair_file[512];
};
void LoadDmlParas(DmlParas * para, const char * file_dml_para);
void PrintDmlParas(const DmlParas para);
#endif // APPS_DML_SRC_DML_DML_PARAS_H_
| 22.340909 | 63 | 0.743642 | alexrenz |
d11a707cd6e98882ae3ce8c991b6c3f63662d5ad | 1,953 | cpp | C++ | STL_C++/STL_String.cpp | rsghotra/AbdulBari | 2d2845608840ddda6e5153ec91966110ca7e25f5 | [
"Apache-2.0"
] | 1 | 2020-12-02T09:21:52.000Z | 2020-12-02T09:21:52.000Z | STL_C++/STL_String.cpp | rsghotra/AbdulBari | 2d2845608840ddda6e5153ec91966110ca7e25f5 | [
"Apache-2.0"
] | null | null | null | STL_C++/STL_String.cpp | rsghotra/AbdulBari | 2d2845608840ddda6e5153ec91966110ca7e25f5 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main() {
string s1{"happy"};
string s2{" birthday"};
string s3;
cout << "s1 is \"" << s1 << "\"; s2 is \"" << s2
<< "\"; s3 is \"" << s3 << '\"'
<< "\n\nThe results of comparing s2 and s1:" << boolalpha
<< "\n\nS2==S1 yields " << (s2 == s1)
<< "\n\nS2!=S1 yields " << (s2 != s1)
<< "\n\nS2>S1 yields " << (s2 > s1)
<< "\n\nS2<S1 yields " << (s2 < s1)
<< "\n\nS2>=S1 yields " << (s2 >= s1)
<< "\n\nS2<=S1 yields " << (s2 <= s1);
//test string function emptu
cout << "\n\nTesting s3.empty():\n";
if(s3.empty()) {
cout << "s3 is empty; assigning s1 to s3;\n";
s3 = s1;
cout << "s3 is \"" << s3 << "\"";
}
//string concatenation
cout << "\n\ns1+=s2 yields s1 = ";
s1+=s2;
cout << s1;
//test conatenation with c-string
// test string concatenation with a C string
cout << "\n\ns1 += \" to you\" yields\n";
s1 += " to you";
cout << "s1 = " << s1;
// test string concatenation with a C++14 string-object literal
cout << "\n\ns1 += \", have a great day!\" yields\n";
s1 += ", have a great day!"s;
cout << "s1 = " << s1;
//test substr "to end of string" option
cout << "The substring of s1 starting at\n"
<< "location 15,s1.substr(15), is:\n" << s1.substr(15) << endl;
string s4{s1};
cout << "\ns4 = " << s4 << "\n\n";
cout << "assigning s4 to s4\n";
s4 = s4;
cout << "s4 = " << s4;
// test using overloaded subscript operator to crate lvalue
s1[0] = 'H';
s1[6] = 'B';
cout << "\n\ns1 after s1[0] = 'H' and s1[6] = 'B' is:\n"
<< s1 << "\n\n";
try {
cout << "Attempt to assign 'd' to s1.at(100) yields:\n";
s1.at(100) = 'd';
} catch(out_of_range& ex) {
cout << "An exception occurred: " << ex.what() << endl;
}
}
| 27.507042 | 71 | 0.47363 | rsghotra |
d11e96722b975adf26898b06877c7f42f8abc4ac | 796 | cc | C++ | src/tritonsort/mapreduce/common/PhaseZeroKVPairWriteStrategy.cc | anku94/themis_tritonsort | 68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d | [
"BSD-3-Clause"
] | 11 | 2015-12-14T05:35:17.000Z | 2021-11-08T22:02:32.000Z | src/tritonsort/mapreduce/common/PhaseZeroKVPairWriteStrategy.cc | anku94/themis_tritonsort | 68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d | [
"BSD-3-Clause"
] | null | null | null | src/tritonsort/mapreduce/common/PhaseZeroKVPairWriteStrategy.cc | anku94/themis_tritonsort | 68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d | [
"BSD-3-Clause"
] | 8 | 2015-12-22T19:31:16.000Z | 2020-12-15T12:09:00.000Z | #include "PhaseZeroKVPairWriteStrategy.h"
uint32_t PhaseZeroKVPairWriteStrategy::getOutputKeyLength(
uint32_t inputKeyLength) const {
return inputKeyLength;
}
uint32_t PhaseZeroKVPairWriteStrategy::getOutputValueLength(
uint32_t inputValueLength) const {
return sizeof(uint64_t);
}
void PhaseZeroKVPairWriteStrategy::writeKey(
const uint8_t* inputKey, uint32_t inputKeyLength, uint8_t* outputKey) const {
memcpy(outputKey, inputKey, inputKeyLength);
}
void PhaseZeroKVPairWriteStrategy::writeValue(
const uint8_t* inputValue, uint32_t inputValueLength,
uint32_t inputKeyLength, uint8_t* outputValue) const {
uint64_t newValue = KeyValuePair::tupleSize(inputKeyLength, inputValueLength);
memcpy(outputValue, reinterpret_cast<uint8_t*>(&newValue), sizeof(newValue));
}
| 27.448276 | 80 | 0.809045 | anku94 |
d11f94c143954afbbea823f954593499d5a789a8 | 2,938 | cpp | C++ | AfxHookGoldSrc/Store.cpp | markusforss/advancedfx | 0c427594e23c30b88081139c6b80f2688b7c211f | [
"MIT"
] | 339 | 2018-01-09T13:12:38.000Z | 2022-03-22T21:25:59.000Z | AfxHookGoldSrc/Store.cpp | markusforss/advancedfx | 0c427594e23c30b88081139c6b80f2688b7c211f | [
"MIT"
] | 474 | 2018-01-01T18:58:41.000Z | 2022-03-27T11:09:44.000Z | AfxHookGoldSrc/Store.cpp | markusforss/advancedfx | 0c427594e23c30b88081139c6b80f2688b7c211f | [
"MIT"
] | 77 | 2018-01-24T11:47:04.000Z | 2022-03-30T12:25:59.000Z | #include "stdafx.h"
#include "Store.h"
#include <stdexcept>
using namespace std;
////////////////////////////////////////////////////////////////////////////////
class FrequentStoreItem :
public IStoreItem
{
public:
FrequentStoreItem * NextFree;
FrequentStoreItem(FrequentStoreManager * manager);
~FrequentStoreItem();
void Aquire();
virtual StoreValue GetValue();
virtual void Release();
private:
bool m_Aquired;
FrequentStoreManager * m_Manager;
StoreValue m_Value;
void Delist();
void Enlist();
};
class FrequentStoreManager
{
public:
FrequentStoreItem * FreeItem;
FrequentStoreManager(IStoreFactory * factory);
~FrequentStoreManager();
IStoreItem * Aquire(void);
IStoreFactory * GetFactory();
void Pack(void);
private:
IStoreFactory * m_Factory;
};
// FrequentStore /////////////////////////////////////////////////////////
FrequentStore::FrequentStore(IStoreFactory * factory)
{
m_Manager = new FrequentStoreManager(factory);
}
FrequentStore::~FrequentStore()
{
delete m_Manager;
}
IStoreItem * FrequentStore::Aquire(void)
{
return m_Manager->Aquire();
}
void FrequentStore::Pack(void)
{
m_Manager->Pack();
}
// FrequentStoreManager //////////////////////////////////////////////////
FrequentStoreManager::FrequentStoreManager(IStoreFactory * factory)
{
FreeItem = 0;
m_Factory = factory;
}
FrequentStoreManager::~FrequentStoreManager()
{
while(FreeItem)
delete FreeItem;
}
IStoreItem * FrequentStoreManager::Aquire(void)
{
FrequentStoreItem * item = FreeItem;
if(!item)
item = new FrequentStoreItem(this);
item->Aquire();
return item;
}
IStoreFactory * FrequentStoreManager::GetFactory()
{
return m_Factory;
}
void FrequentStoreManager::Pack(void)
{
while(FreeItem)
delete FreeItem;
}
// FrequentStoreItem /////////////////////////////////////////////////////
FrequentStoreItem::FrequentStoreItem(FrequentStoreManager * manager)
{
NextFree = 0;
m_Aquired = false;
m_Manager = manager;
m_Value = manager->GetFactory()->ConstructValue();
Enlist();
}
FrequentStoreItem::~FrequentStoreItem()
{
//if(m_Aquired)
// throw logic_error("");
Delist();
m_Manager->GetFactory()->DestructValue(m_Value);
}
void FrequentStoreItem::Aquire()
{
if(m_Aquired)
throw logic_error("");
Delist();
m_Aquired = true;
}
void FrequentStoreItem::Delist()
{
m_Manager->FreeItem = NextFree;
NextFree = 0;
}
void FrequentStoreItem::Enlist()
{
NextFree = m_Manager->FreeItem;
m_Manager->FreeItem = this;
}
StoreValue FrequentStoreItem::GetValue()
{
return m_Value;
}
void FrequentStoreItem::Release()
{
if(!m_Aquired)
throw logic_error("");
m_Aquired = false;
Enlist();
}
// Store ///////////////////////////////////////////////////////////////////////
Store::~Store()
{
} | 16.505618 | 81 | 0.607216 | markusforss |
d12413b7256a74a0f415ef8c3464e153bab90b1d | 1,444 | cpp | C++ | C++ Code/Section01/sec01_mt_example.cpp | PacktPublishing/Mastering-Multithreading-with-Cplusplus | 9b0e5a7beeceb4a7262666fa2465fdda0104c9db | [
"MIT"
] | 10 | 2019-10-10T21:03:56.000Z | 2022-03-11T08:06:46.000Z | Section01/sec01_mt_example.cpp | PacktPublishing/Mastering-Multithreading-with-Cplusplus | 9b0e5a7beeceb4a7262666fa2465fdda0104c9db | [
"MIT"
] | null | null | null | Section01/sec01_mt_example.cpp | PacktPublishing/Mastering-Multithreading-with-Cplusplus | 9b0e5a7beeceb4a7262666fa2465fdda0104c9db | [
"MIT"
] | 9 | 2019-09-08T09:15:13.000Z | 2022-01-07T13:12:06.000Z | /*
sec01_mt_example.cpp - main file for the Section01 multithreaded example.
2016/10/30, Maya Posch
*/
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <random>
using namespace std;
// --- Globals
mutex values_mtx;
mutex cout_mtx;
vector<int> values;
int randGen(const int& min, const int& max) {
static thread_local mt19937 generator(hash<thread::id>()(this_thread::get_id()));
uniform_int_distribution<int> distribution(min, max);
return distribution(generator);
}
void threadFnc(int tid) {
// Calculate the result.
cout_mtx.lock();
cout << "Starting thread " << tid << ".\n";
cout_mtx.unlock();
values_mtx.lock();
int val = values[0];
values_mtx.unlock();
int rval = randGen(0, 10);
val += rval;
cout_mtx.lock();
cout << "Thread " << tid << " adding " << rval << ". New value: " << val << ".\n";
cout_mtx.unlock();
values_mtx.lock();
values.push_back(val);
values_mtx.unlock();
}
int main() {
// Set global data in queue.
values.push_back(42);
// Start the threads, wait for them to finish.
thread tr1(threadFnc, 1);
thread tr2(threadFnc, 2);
thread tr3(threadFnc, 3);
thread tr4(threadFnc, 4);
tr1.join();
tr2.join();
tr3.join();
tr4.join();
// Read the calculated values.
cout << "Input: " << values[0] << ", Result 1: " << values[1] << ", Result 2: " << values[2] << ", Result 3: " << values[3] << ", Result 4: " << values[4] << "\n";
return 1;
}
| 21.552239 | 164 | 0.640582 | PacktPublishing |
d125ee08684e41e34c0b31326a809ace45e3b996 | 44,123 | cpp | C++ | lib/Hask/WorkerWrapperPass.cpp | bollu/lz | f5d09b70956072a56c1d9cc0e6907a0261c108a5 | [
"Apache-2.0"
] | 12 | 2020-12-12T17:54:33.000Z | 2022-01-12T00:34:37.000Z | lib/Hask/WorkerWrapperPass.cpp | bollu/lz | f5d09b70956072a56c1d9cc0e6907a0261c108a5 | [
"Apache-2.0"
] | 23 | 2020-11-27T18:53:24.000Z | 2021-12-03T15:29:24.000Z | lib/Hask/WorkerWrapperPass.cpp | bollu/lz | f5d09b70956072a56c1d9cc0e6907a0261c108a5 | [
"Apache-2.0"
] | 1 | 2020-12-12T17:56:56.000Z | 2020-12-12T17:56:56.000Z | #include "Hask/HaskDialect.h"
#include "Hask/HaskOps.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/Types.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/InliningUtils.h"
#include "llvm/ADT/SmallPtrSet.h"
#include <mlir/Parser.h>
#include <sstream>
// Standard dialect
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
// pattern matching
#include "mlir/IR/Matchers.h"
#include "mlir/IR/PatternMatch.h"
// dilect lowering
#include "mlir/Pass/PassRegistry.h"
#include "mlir/Transforms/DialectConversion.h"
// https://github.com/llvm/llvm-project/blob/80d7ac3bc7c04975fd444e9f2806e4db224f2416/mlir/examples/toy/Ch6/toyc.cpp
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
#define DEBUG_TYPE "hask-ops"
#include "llvm/Support/Debug.h"
namespace mlir {
namespace standalone {
// The nonsense that is MLIR only sets the type that is tracked by the
// type *attribute* and not *the type of the entry block arguments.
// This really sets the type of the entry block arguments as well.
void reallySetFunctionType(mlir::FuncOp f, mlir::FunctionType ty) {
f.setType(ty);
assert(f.getNumArguments() == ty.getNumInputs());
for (int i = 0; i < (int)f.getNumArguments(); ++i) {
f.getArgument(i).setType(ty.getInput(i));
}
}
mlir::FlatSymbolRefAttr getConstantFnRefFromOp(mlir::ConstantOp constant) {
return constant.getValue().dyn_cast<FlatSymbolRefAttr>();
}
mlir::FlatSymbolRefAttr getConstantFnRefFromValue(mlir::Value v) {
mlir::ConstantOp constant = v.getDefiningOp<mlir::ConstantOp>();
if (!v) {
return mlir::FlatSymbolRefAttr();
}
return getConstantFnRefFromOp(constant);
}
struct ForceOfKnownApPattern : public mlir::OpRewritePattern<ForceOp> {
ForceOfKnownApPattern(mlir::MLIRContext *context)
: OpRewritePattern<ForceOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(ForceOp force,
mlir::PatternRewriter &rewriter) const override {
// HaskFuncOp fn = force.getParentOfType<HaskFuncOp>();
ApOp ap = force.getOperand().getDefiningOp<ApOp>();
if (!ap) {
return failure();
}
// HaskRefOp ref = ap.getFn().getDefiningOp<HaskRefOp>();
// if (!ref) {
// return failure();
// }
FlatSymbolRefAttr apfnname = getConstantFnRefFromValue(ap.getFn());
if (!apfnname) {
return failure();
}
ModuleOp mod = force->getParentOfType<ModuleOp>();
FuncOp fn = mod.lookupSymbol<FuncOp>(apfnname);
if (!fn) {
return failure();
}
// cannot inline a recursive function. Can replace with
// an apEager
rewriter.setInsertionPoint(ap);
ApEagerOp eager = rewriter.create<ApEagerOp>(ap.getLoc(), ap.getFn(),
fn.getType().getResult(0),
ap.getFnArguments());
rewriter.replaceOp(force, eager.getResult());
return success();
};
};
// outline stuff that occurs after the force of a constructor at the
// top-level of a function.
struct OutlineUknownForcePattern : public mlir::OpRewritePattern<ForceOp> {
OutlineUknownForcePattern(mlir::MLIRContext *context)
: OpRewritePattern<ForceOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(ForceOp force,
mlir::PatternRewriter &rewriter) const override {
// we should not have a force of thunkify, or force of known ap
if (force.getOperand().getDefiningOp<ThunkifyOp>()) {
return failure();
}
// TODO: think about what to do.
if (ApOp ap = force.getOperand().getDefiningOp<ApOp>()) {
FlatSymbolRefAttr apfn = getConstantFnRefFromValue(ap.getFn());
if (!apfn) {
return failure();
}
// how to get dominance information? I should outline everything in the
// region that is dominated by the BB that `force` lives in.
// For now, approximate.
if (force.getOperation()->getBlock() !=
&force->getParentRegion()->front()) {
assert(false && "force not in entry BB");
return failure();
}
// is this going to break *completely*? or only partially?
std::unique_ptr<Region> r = std::make_unique<Region>();
// create a hask func op.
FuncOp parentfn = force->getParentOfType<FuncOp>();
ModuleOp module = parentfn->getParentOfType<ModuleOp>();
rewriter.setInsertionPointToEnd(&module.getBodyRegion().front());
FuncOp outlinedFn = rewriter.create<FuncOp>(
force.getLoc(), parentfn.getName().str() + "_outline_unknown_force",
parentfn.getType());
(void)outlinedFn;
rewriter.eraseOp(force);
return success();
}
return failure();
}
};
struct ForceOfThunkifyPattern : public mlir::OpRewritePattern<ForceOp> {
/// We register this pattern to match every toy.transpose in the IR.
/// The "benefit" is used by the framework to order the patterns and process
/// them in order of profitability.
ForceOfThunkifyPattern(mlir::MLIRContext *context)
: OpRewritePattern<ForceOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(ForceOp force,
mlir::PatternRewriter &rewriter) const override {
// HaskFuncOp fn = force->getParentOfType<HaskFuncOp>();
ThunkifyOp thunkify = force.getOperand().getDefiningOp<ThunkifyOp>();
if (!thunkify) {
return failure();
}
rewriter.replaceOp(force, thunkify.getOperand());
return success();
}
};
struct ThunkifyOfForcePattern : public mlir::OpRewritePattern<ThunkifyOp> {
ThunkifyOfForcePattern(mlir::MLIRContext *context)
: OpRewritePattern<ThunkifyOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(ThunkifyOp thunkify,
mlir::PatternRewriter &rewriter) const override {
// HaskFuncOp fn = force->getParentOfType<HaskFuncOp>();
ForceOp force = thunkify.getOperand().getDefiningOp<ForceOp>();
if (!force) {
return failure();
}
rewriter.replaceOp(thunkify, force.getOperand());
return success();
}
};
struct InlineApEagerPattern : public mlir::OpRewritePattern<ApEagerOp> {
InlineApEagerPattern(mlir::MLIRContext *context)
: OpRewritePattern<ApEagerOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(ApEagerOp ap,
mlir::PatternRewriter &rewriter) const override {
FuncOp parent = ap->getParentOfType<FuncOp>();
ModuleOp mod = ap->getParentOfType<ModuleOp>();
FlatSymbolRefAttr apfn = getConstantFnRefFromValue(ap.getFn());
if (!apfn) {
return failure();
}
if (parent.getName() == apfn.getValue().str()) {
return failure();
}
FuncOp called = mod.lookupSymbol<FuncOp>(apfn);
assert(called && "unable to find called function.");
// TODO: setup mapping for arguments in mapper
// This is not safe! Fuck me x(
// consider f () { stmt; f(); } | g() { f (); }
// this will expand into
// g() { f(); } -> g() { stmt; f(); } -> g { stmt; stmt; f(); } -> ...
InlinerInterface inliner(rewriter.getContext());
if (!HaskDialect::isFunctionRecursive(called)) {
LogicalResult isInlined = inlineRegion(
inliner, &called.getBody(), ap, ap.getFnArguments(), ap.getResult());
return isInlined;
// assert(succeeded(isInlined) && "unable to inline");
return success();
} else {
return failure();
}
}
};
// TODO: we need to know which argument was forced.
FunctionType mkForcedFnType(FunctionType fty) {
SmallVector<Type, 4> forcedTys;
for (Type ty : fty.getInputs()) {
ThunkType thunkty = ty.dyn_cast<ThunkType>();
assert(thunkty);
forcedTys.push_back(thunkty.getElementType());
}
return FunctionType::get(fty.getContext(), forcedTys, fty.getResult(0));
}
// ===IN===
// @f(%int: thunk<V>):
// %inv = force(%int) : V
// -----
// %recw = ... : V
// %rect = thunkify(%recw) : thunk<V>
// %outt = ap(@f, %rect)
// ===OUT===
// @fforced(%inv: V)
// %f = ref @f
// %recw = ... : V
// %rect = thunkify(%recw) : thunk<V>
// %outt = ap(%f, %rect)
// @f(%int: thunk<V>):
// %inv = force(%int) : V
// apEager(@fforced, inv)
// convert ap(thunkify(...)) of a recursive call that is force(...) d
// into an "immediate" function call.
struct OutlineRecursiveApEagerOfThunkPattern
: public mlir::OpRewritePattern<ApEagerOp> {
OutlineRecursiveApEagerOfThunkPattern(mlir::MLIRContext *context)
: OpRewritePattern<ApEagerOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(ApEagerOp ap,
mlir::PatternRewriter &rewriter) const override {
FuncOp parentfn = ap->getParentOfType<FuncOp>();
ModuleOp mod = ap->getParentOfType<ModuleOp>();
FlatSymbolRefAttr apfnname = getConstantFnRefFromValue(ap.getFn());
if (!apfnname) {
return failure();
}
// if the call is not recursive, bail
if (parentfn.getName() != apfnname.getValue().str()) {
return failure();
}
// called == parentfn?
FuncOp called = mod.lookupSymbol<FuncOp>(apfnname);
assert(called && "unable to find called function.");
if (ap.getNumFnArguments() != 1) {
assert(false && "cannot handle functions with multiple args just yet");
}
SmallVector<Value, 4> clonedFnCallArgs;
ThunkifyOp thunkifiedArgument =
ap.getFnArgument(0).getDefiningOp<ThunkifyOp>();
if (!thunkifiedArgument) {
return failure();
}
clonedFnCallArgs.push_back(thunkifiedArgument.getOperand());
// TODO: this is an over-approximation of course, we only need
// a single argument (really, the *same* argument to be reused).
// I've moved the code here to test that the crash isn't because of a
// bail-out.
for (int i = 0; i < (int)called.getBody().getNumArguments(); ++i) {
Value arg = called.getBody().getArgument(i);
if (!arg.hasOneUse()) {
return failure();
}
ForceOp uniqueForceOfArg = dyn_cast<ForceOp>(arg.use_begin().getUser());
if (!uniqueForceOfArg) {
return failure();
}
}
std::string clonedFnName = called.getName().str() + "rec_force_outline";
rewriter.setInsertionPoint(ap);
// ConstantOp original = ap.getFn().getDefiningOp<ConstantOp>();
// original.dump();
// mlir::OpPrintingFlags flags;
// original.print(llvm::errs(), flags.printGenericOpForm());
// assert(original.getValue().isa<mlir::FlatSymbolRefAttr>() &&
// "is a flat symbol ref");
// assert(original.getValue().isa<mlir::SymbolRefAttr>() && "is a symbol
// ref");
ConstantOp clonedFnRef = rewriter.create<ConstantOp>(
rewriter.getUnknownLoc(), mkForcedFnType(called.getType()),
mlir::FlatSymbolRefAttr::get(rewriter.getContext(), clonedFnName));
rewriter.replaceOpWithNewOp<ApEagerOp>(
ap, clonedFnRef, called.getType().getResult(0), clonedFnCallArgs);
// TODO: this disastrous house of cards depends on the order of cloning.
// We first replace the reucrsive call, and *then* clone the function.
FuncOp clonedfn = parentfn.clone();
clonedfn.setName(clonedFnName);
reallySetFunctionType(clonedfn, mkForcedFnType(called.getType()));
// TODO: consider if going forward is more sensible or going back is
// more sensible. Right now I am reaching forward, but perhaps
// it makes sense to reach back.
for (int i = 0; i < (int)clonedfn.getBody().getNumArguments(); ++i) {
Value arg = clonedfn.getBody().getArgument(i);
if (!arg.hasOneUse()) {
assert(false && "this precondition as already been checked!");
}
// This is of course crazy. We should handle the case if we have
// multiple force()s.
ForceOp uniqueForceOfArg = dyn_cast<ForceOp>(arg.use_begin().getUser());
if (!uniqueForceOfArg) {
assert(false && "this precondition has already been checked!");
return failure();
}
// we are safe to create a new function because we have a unique force
// of an argument. We can change the type of the function and we can
// change the argument.
// replace argument.
uniqueForceOfArg.replaceAllUsesWith(arg);
arg.setType(uniqueForceOfArg.getType());
rewriter.eraseOp(uniqueForceOfArg);
}
mod.push_back(clonedfn);
return success();
}
};
// ===INPUT===
// C { MKC(V) }
// @f(%inc: C)
// case inc of {
// C inv -> {
// %inv = extract(@MKC, %inc) : V
// %w = ... : V
// %wc = construct(@MKC, w) : C
// %rec = apEager(@f, wc)
// }
// }
// ===OUTPUT===
// @frec(%inv: V)
// %inv = extract(@MKC, %inc) : V
// %w = ... : V
// %wc = construct(@MKC, w) : C
// %rec = apEager(@f, wc)
// @f(%inc: C)
// %inv = extract(%inc) : V
// apEager(@frec, inv)
struct OutlineRecursiveApEagerOfConstructorPattern
: public mlir::OpRewritePattern<ApEagerOp> {
OutlineRecursiveApEagerOfConstructorPattern(mlir::MLIRContext *context)
: OpRewritePattern<ApEagerOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(ApEagerOp ap,
mlir::PatternRewriter &rewriter) const override {
FuncOp parentfn = ap->getParentOfType<FuncOp>();
ModuleOp mod = ap->getParentOfType<ModuleOp>();
mlir::FlatSymbolRefAttr ref = getConstantFnRefFromValue(ap.getFn());
// auto ref = ap.getFn().getDefiningOp<HaskRefOp>();
if (!ref) {
return failure();
}
// if the call is not recursive, bail
if (parentfn.getName() != ref.getValue().str()) {
return failure();
}
FuncOp called = mod.lookupSymbol<FuncOp>(ref);
assert(called && "unable to find called function.");
if (ap.getNumFnArguments() != 1) {
assert(false && "cannot handle functions with multiple args just yet");
}
HaskConstructOp constructedArgument =
ap.getFnArgument(0).getDefiningOp<HaskConstructOp>();
if (!constructedArgument) {
return failure();
}
// First focus on SimpleInt. Then expand to Maybe.
assert(constructedArgument.getNumOperands() == 1);
SmallVector<Value, 4> improvedFnCallArgs(
{constructedArgument.getOperand(0)});
assert(parentfn.getNumArguments() == 1);
BlockArgument arg = parentfn.getBody().getArgument(0);
// has multiple uses, we can't use this for our purposes.
if (!arg.hasOneUse()) {
return failure();
}
// MLIR TODO: add arg.getSingleUse()
CaseOp caseOfArg = dyn_cast<CaseOp>(arg.getUses().begin().getUser());
if (!caseOfArg) {
return failure();
}
std::string clonedFnName =
called.getName().str() + "_rec_construct_" +
constructedArgument.getDataConstructorName().str() + "_outline";
rewriter.setInsertionPoint(ap);
// 1. Replace the ApEager with a simpler apEager
// that directly passes the parameter
SmallVector<Value, 4> clonedFnCallArgs({constructedArgument.getOperand(0)});
SmallVector<Type, 4> clonedFnCallArgTys{
(constructedArgument.getOperand(0).getType())};
mlir::FunctionType clonedFnTy =
mlir::FunctionType::get(rewriter.getContext(), clonedFnCallArgTys,
called.getType().getResult(0));
ConstantOp clonedFnRef = rewriter.create<ConstantOp>(
ap.getFn().getLoc(), clonedFnTy,
mlir::FlatSymbolRefAttr::get(rewriter.getContext(), clonedFnName));
// HaskRefOp clonedFnRef = rewriter.create<HaskRefOp>(
// ref.getLoc(), clonedFnName,
// FunctionType::get(
// clonedFnCallArgTys,
// parentfn.getType().cast<FunctionType>().getResult(0),
// mod.getContext()));
// HaskFnType::get(mod.getContext(), clonedFnCallArgTys,
// parentfn.getType().cast<FunctionType>().getResult(0)));
rewriter.replaceOpWithNewOp<ApEagerOp>(
ap, clonedFnRef, called.getType().getResult(0), clonedFnCallArgs);
FuncOp clonedfn = parentfn.clone();
// 2. Build the cloned function that is an unboxed version of the
// case. Eliminate the case for the argument RHS.
clonedfn.setName(clonedFnName);
reallySetFunctionType(clonedfn, clonedFnTy);
CaseOp caseClonedFnArg = cast<CaseOp>(
clonedfn.getBody().getArgument(0).getUses().begin().getUser());
int altIx = *caseClonedFnArg.getAltIndexForConstructor(
constructedArgument.getDataConstructorName());
InlinerInterface inliner(rewriter.getContext());
LogicalResult isInlined = inlineRegion(
inliner, &caseClonedFnArg.getAltRHS(altIx), caseClonedFnArg,
clonedfn.getBody().getArgument(0), caseClonedFnArg.getResult());
rewriter.eraseOp(caseClonedFnArg);
assert(succeeded(isInlined) && "unable to inline");
// 3. add the function into the module
mod.push_back(clonedfn);
rewriter.notifyOperationInserted(clonedfn);
return success();
assert(false && "matched against f(arg) { case(arg): ...; apEager(f, "
"construct(...); } ");
}
};
// find the single case op of v that is at the same level as of v.
// We can have other uses of v nested inside the case op that is found.
// If there are multiple uses, then give up.
CaseOp findSingleCaseOpUse(BlockArgument v, Region *r) {
CaseOp c;
for (auto it : v.getUsers()) {
if (!c) {
// the case is not a top-level case. ignored.
if (it->getParentRegion() != r) {
continue;
}
c = mlir::dyn_cast<CaseOp>(*it);
} else {
// we found an operation that is *not* the ancestor of the
// case of we believe is the corret one.
if (c.getOperation()->isAncestor(it)) {
continue;
}
}
}
return c;
}
// ==INPUT==
// data Box { MkBox(int) }
// @f(x: Box):
// <STUFF-BEFORE-CASE>
// case x of ...
// MkBox val ->
// <RHS-OF-CASE-1>
// f(MkBox(y))
// <RHS-OF-CASE-2>
// ==OUTPUT==
// @fBox(val: int):
// case (MkBox val) of ...
// <RHS-OF-CASE-1>
// ...
// fBox(y)
// <RHS-OF-CASE-2>
// ----------
// @f(x):
// <STUFF-BEFORE-CASE>
// case x of
// MkBox val ->
// <RHS-OF-CASE-1>;
// fBox(val) <- here is where the problem comes. the
// |computation of `val` could depend on other
// | random stuff in <stuff-before-case>
// <RHS-OF-CASE-2>;
// ..
// This not so easy! We need to carry all the values that are referenced
// by the RHS *into* the outlined function x(oi2
struct OutlineCaseOfFnInput : public mlir::OpRewritePattern<FuncOp> {
OutlineCaseOfFnInput(mlir::MLIRContext *context)
: OpRewritePattern<FuncOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(FuncOp parentfn,
mlir::PatternRewriter &rewriter) const override {
mlir::ModuleOp mod = parentfn->getParentOfType<ModuleOp>();
if (parentfn.getArguments().size() != 1) {
return failure();
}
// TODO: ACTUALLY CHECK THIS CONDITION!
// The current problem is that something like:
// case x of (1)
// Foo x' -> ...
// default -> use x (2)
// counts as TWO uses!
mlir::standalone::CaseOp caseOfArg =
findSingleCaseOpUse(parentfn.getArgument(0), &parentfn.getRegion());
if (!caseOfArg) {
return failure();
}
// TODO: generalize
if (caseOfArg.getNumAlts() != 1) {
return failure();
}
if (caseOfArg.getAltRHS(0).getNumArguments() != 1) {
return failure();
}
std::string outlinedFnName = parentfn.getName().str() + "_outline_case_arg";
// <original inputs> -> unwrapped output
mlir::FunctionType outlinedFnty = rewriter.getFunctionType(
caseOfArg.getAltRHS(0).getArgument(0).getType(),
parentfn.getType().getResults());
// pass has already run and outlined; fail to indicate we have made no
// progress / have terminated the rewrite system.
if (mod.lookupSymbol<FuncOp>(outlinedFnName)) {
return failure();
}
llvm::SmallVector<ApEagerOp, 2> recursiveCalls;
parentfn.walk([&](ApEagerOp call) {
if (call.getFnName() != parentfn.getName()) {
return WalkResult::advance();
}
recursiveCalls.push_back(call);
return WalkResult::advance();
}); // end walk
// llvm::errs() << "Considering function: |" << parentfn.getName() << "|
// \n";
// llvm::errs() << "region:\n" << caseOfArg;
// llvm::errs() << "\n===\n";
// try to find ops that we need to copy
bool canBeSelfContained = true;
caseOfArg.getAltRHS(0).walk([&](Operation *op) {
for (Value v : op->getOperands()) {
if (caseOfArg.getAltRHS(0).isAncestor(v.getParentRegion())) {
continue;
}
// has different region as owner.
ConstantOp vconst = v.getDefiningOp<ConstantOp>();
if (vconst) {
continue;
}
canBeSelfContained = false;
return WalkResult::interrupt();
}
return WalkResult::advance();
}); // end walk
if (!canBeSelfContained) {
return failure();
}
for (ApEagerOp call : recursiveCalls) {
llvm::SmallVector<Value, 4> callArgs;
// replace call = f(argConstruct = Constructor(v)) with fConstructor(v);
HaskConstructOp argConstruct =
call.getFnArgument(0).getDefiningOp<HaskConstructOp>();
if (!argConstruct) {
continue;
}
callArgs.push_back(argConstruct.getOperand(0));
rewriter.setInsertionPointAfter(call);
ConstantOp outlinedFnNameSymbol = rewriter.create<ConstantOp>(
call.getLoc(), outlinedFnty,
mlir::FlatSymbolRefAttr::get(rewriter.getContext(), outlinedFnName));
ApEagerOp outlinedCall = rewriter.create<ApEagerOp>(
call.getLoc(), outlinedFnNameSymbol,
outlinedFnty.getResult(0), // type of result
callArgs);
rewriter.replaceOp(call, outlinedCall.getResult());
}
// OK, now create the actually outlined function by cloning our function.
// Then fixup the return by removing the constructor around the return.
rewriter.setInsertionPointAfter(parentfn);
mlir::FuncOp outlinedFn = parentfn.clone();
outlinedFn.setName(outlinedFnName);
reallySetFunctionType(outlinedFn, outlinedFnty);
BlockArgument outlinedFnArg = outlinedFn.getArgument(0);
rewriter.setInsertionPointToStart(&outlinedFn.getRegion().front());
HaskConstructOp wrappedOutlinedFnArg = rewriter.create<HaskConstructOp>(
rewriter.getUnknownLoc(), caseOfArg.getAltLHS(0).getValue(),
outlinedFnArg);
llvm::SmallPtrSet<Operation *, 4> except = {
wrappedOutlinedFnArg.getOperation()};
outlinedFnArg.replaceAllUsesExcept(wrappedOutlinedFnArg, except);
llvm::errs() << "===Finished run: CaseOfFnInput===\n";
llvm::errs() << mod;
llvm::errs() << "\n===\n";
mod.push_back(outlinedFn);
rewriter.notifyOperationInserted(outlinedFn);
return success();
}
};
// ===INPUT===
// C { MKC(V) }
// @f(%inc: C)
// ...
// %out = constructor(C, %w)
// lz.return (%out)
struct OutlineReturnOfConstructor : public mlir::OpRewritePattern<FuncOp> {
OutlineReturnOfConstructor(mlir::MLIRContext *context)
: OpRewritePattern<FuncOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(FuncOp parentfn,
mlir::PatternRewriter &rewriter) const override {
// TODO: use postdom info.
llvm::errs() << "parentfn: " << parentfn.getName() << "\n";
if (parentfn.getBlocks().size() != 1) {
return failure();
}
HaskReturnOp ret = mlir::dyn_cast<HaskReturnOp>(
parentfn.getBlocks().front().getTerminator());
if (!ret) {
return failure();
}
ModuleOp mod = parentfn->getParentOfType<ModuleOp>();
HaskConstructOp constructor =
ret.getOperand().getDefiningOp<HaskConstructOp>();
if (!constructor) {
return failure();
}
// currently our functions only support a single argument constructor.
// Will need to generalize by allowing tuple of results.
if (constructor.getNumOperands() != 1) {
return failure();
}
const std::string outlinedFnName =
parentfn.getName().str() + "_outline_ret_cons";
// pass has already run and outlined; fail to indicate we have made no
// progress / have terminated the rewrite system.
if (mod.lookupSymbol<FuncOp>(outlinedFnName)) {
return failure();
}
llvm::SmallVector<ApEagerOp, 2> recursiveCalls;
// replace all recursive calls f() with. constructor(f_outline())
parentfn.walk([&](ApEagerOp call) {
if (call.getFnName() != parentfn.getName()) {
return WalkResult::advance();
}
recursiveCalls.push_back(call);
return WalkResult::advance();
}); // end walk
for (ApEagerOp call : recursiveCalls) {
llvm::SmallVector<Value, 4> callArgs;
for (int i = 0; i < call.getNumFnArguments(); ++i) {
callArgs.push_back(call.getFnArgument(i));
}
rewriter.setInsertionPointAfter(call);
ConstantOp outlinedFnNameSymbol = rewriter.create<ConstantOp>(
call.getLoc(),
rewriter.getFunctionType(parentfn.getType().getInputs(),
constructor.getOperand(0).getType()),
mlir::FlatSymbolRefAttr::get(rewriter.getContext(), outlinedFnName));
ApEagerOp outlinedCall = rewriter.create<ApEagerOp>(
call.getLoc(), outlinedFnNameSymbol,
constructor.getOperand(0).getType(), // type of result
callArgs);
HaskConstructOp outlinedCallWrap = rewriter.create<HaskConstructOp>(
call.getLoc(), constructor.getDataConstructorName(),
outlinedCall.getResult());
rewriter.replaceOp(call, outlinedCallWrap.getResult());
}
// OK, now create the actually outlined function by cloning our function.
// Then fixup the return by removing the constructor around the return.
mlir::FuncOp outlinedFn = parentfn.clone();
outlinedFn.setName(outlinedFnName);
assert(outlinedFn.getBody().getBlocks().size() == 1);
HaskReturnOp clonedRet =
mlir::cast<HaskReturnOp>(outlinedFn.getBody().front().getTerminator());
HaskConstructOp clonedConstructor =
clonedRet.getOperand().getDefiningOp<HaskConstructOp>();
Value clonedConstructorArg = clonedConstructor.getOperand(0);
// <original inputs> -> unwrapped output
mlir::FunctionType outlinedFnty = rewriter.getFunctionType(
parentfn.getType().getInputs(), clonedConstructorArg.getType());
reallySetFunctionType(outlinedFn, outlinedFnty);
// return constructor(val) -> return val
rewriter.setInsertionPointAfter(clonedRet);
rewriter.replaceOpWithNewOp<HaskReturnOp>(clonedRet, clonedConstructorArg);
rewriter.eraseOp(clonedConstructor);
mod.push_back(outlinedFn);
rewriter.notifyOperationInserted(outlinedFn);
return success();
}
};
class AlwaysInlinerInterface : public InlinerInterface {
public:
AlwaysInlinerInterface(MLIRContext *ctx) : InlinerInterface(ctx) {}
virtual void processInlinedBlocks(
iterator_range<Region::iterator> inlinedBlocks) override {}
bool isLegalToInline(Operation *call, Operation *callable,
bool wouldBeCloned) const override {
return true;
};
bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
BlockAndValueMapping &valueMapping) const override {
return true;
}
bool isLegalToInline(Operation *op, Region *dest, bool wouldBeCloned,
BlockAndValueMapping &valueMapping) const override {
return true;
}
bool shouldAnalyzeRecursively(Operation *op) const override { return true; };
};
struct CaseOfKnownConstructorPattern : public mlir::OpRewritePattern<CaseOp> {
CaseOfKnownConstructorPattern(mlir::MLIRContext *context)
: OpRewritePattern<CaseOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(CaseOp caseop,
mlir::PatternRewriter &rewriter) const override {
HaskConstructOp constructor =
caseop.getScrutinee().getDefiningOp<HaskConstructOp>();
if (!constructor) {
return failure();
}
rewriter.setInsertionPoint(caseop);
int altIx =
*caseop.getAltIndexForConstructor(constructor.getDataConstructorName());
AlwaysInlinerInterface inliner(rewriter.getContext());
ModuleOp mod = caseop->getParentOfType<ModuleOp>();
(void)(mod);
FuncOp fn = caseop->getParentOfType<FuncOp>();
llvm::errs() << "===parent func:===\n";
fn.getOperation()->print(llvm::errs(),
mlir::OpPrintingFlags().printGenericOpForm());
llvm::errs() << "\n\n~~~~~~constructor:~~~~~~\n\n";
constructor.getOperation()->print(
llvm::errs(), mlir::OpPrintingFlags().printGenericOpForm());
llvm::errs() << "\n\n~~~~~~case:~~~~~~\n\n";
caseop.getOperation()->print(llvm::errs(),
mlir::OpPrintingFlags().printGenericOpForm());
llvm::errs() << "\n^^^^^^^^^^\n";
LogicalResult isInlined =
inlineRegion(inliner, &caseop.getAltRHS(altIx), caseop,
constructor.getOperands(), caseop.getResult());
assert(succeeded(isInlined) &&
"unable to inline case of known constructor");
return success();
};
};
struct CaseOfKnownIntPattern : public mlir::OpRewritePattern<CaseIntOp> {
CaseOfKnownIntPattern(mlir::MLIRContext *context)
: OpRewritePattern<CaseIntOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(CaseIntOp caseop,
mlir::PatternRewriter &rewriter) const override {
ConstantOp constint = caseop.getScrutinee().getDefiningOp<ConstantOp>();
if (!constint) {
return failure();
}
mlir::IntegerAttr val = constint.value().dyn_cast<mlir::IntegerAttr>();
if (!val) {
return failure();
}
rewriter.setInsertionPoint(caseop);
int altIx = *caseop.getAltIndexForConstInt(val.getInt());
InlinerInterface inliner(rewriter.getContext());
// note that the default alt index DOES NOT HAVE ARGUMENTS!
if (altIx == caseop.getDefaultAltIndex()) {
LogicalResult isInlined =
inlineRegion(inliner, &caseop.getAltRHS(altIx), caseop,
/*inlineOperands=*/{}, caseop.getResult());
assert(succeeded(isInlined) &&
"unable to inline the default case of a caseint of known int ");
} else {
LogicalResult isInlined =
inlineRegion(inliner, &caseop.getAltRHS(altIx), caseop,
constint.getResult(), caseop.getResult());
assert(succeeded(isInlined) && "unable to inline the non-default known "
"branch case of a caseint of known int");
}
return success();
};
}; // namespace standalone
// @f {
// x = ...
// ybox = apEager(@f, x);
// z = case ybox of { Box y -> g(y); };
// return construct(Box, z)
// }
// Convert to:
// @funbox {
// ...
// return z
// }
// @f {
// y = apEager(@funbox, x)
// z = g(y)
// return construct(Box, z)
// }
struct CaseOfBoxedRecursiveApWithFinalConstruct
: public mlir::OpRewritePattern<CaseOp> {
CaseOfBoxedRecursiveApWithFinalConstruct(mlir::MLIRContext *context)
: OpRewritePattern<CaseOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(CaseOp caseop,
mlir::PatternRewriter &rewriter) const override {
FuncOp fn = caseop->getParentOfType<FuncOp>();
// case(ap(..., ))
ApEagerOp apeager = caseop.getScrutinee().getDefiningOp<ApEagerOp>();
if (!apeager) {
return failure();
}
mlir::FlatSymbolRefAttr ref = getConstantFnRefFromValue(apeager.getFn());
// HaskRefOp ref = apeager.getFn().getDefiningOp<HaskRefOp>();
if (!ref) {
return failure();
}
if (ref.getValue() != fn.getName()) {
return failure();
}
// figure out if the return value is always a `hask.construct(...)`
// TODO: generalize
if (fn.getBody().getBlocks().size() != 1) {
return failure();
}
// find the return operations
HaskReturnOp ret = dyn_cast<HaskReturnOp>(
fn.getBody().getBlocks().front().getTerminator());
if (!ret) {
return failure();
}
HaskConstructOp construct =
ret.getOperand().getDefiningOp<HaskConstructOp>();
if (!construct) {
return failure();
}
assert(false && "case of boxed recursive ap eager");
}
};
// ===INPUT===
// @f(box: List) = case List of Nil -> Foo y; Cons x xs -> Foo z
// ===OUTPUT====
// @f(box: List) = Foo (case List of Nil -> y; Cons x xs -> z)
struct PeelConstructorsFromCasePattern : public mlir::OpRewritePattern<CaseOp> {
PeelConstructorsFromCasePattern(mlir::MLIRContext *context)
: OpRewritePattern<CaseOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(CaseOp caseop,
mlir::PatternRewriter &rewriter) const override {
llvm::Optional<std::string> constructorName;
// ret[i](constructors[i](val)) -> ret[i](val)
std::vector<mlir::standalone::HaskReturnOp> rets;
std::vector<mlir::standalone::HaskConstructOp> constructors;
for (int i = 0; i < caseop.getNumAlts(); ++i) {
mlir::Region &rhs = caseop.getAltRHS(i);
if (rhs.getBlocks().size() > 1) {
return failure();
}
mlir::standalone::HaskReturnOp ret =
mlir::dyn_cast<HaskReturnOp>(rhs.getBlocks().front().getTerminator());
if (!ret) {
return failure();
}
rets.push_back(ret);
mlir::standalone::HaskConstructOp constructor =
ret.getOperand().getDefiningOp<HaskConstructOp>();
if (!constructor) {
return failure();
}
constructors.push_back(constructor);
if (!constructorName) {
constructorName = constructor.getDataConstructorName().str();
continue;
}
assert(constructorName);
if (constructorName != constructor.getDataConstructorName().str()) {
return failure();
}
// TODO: handle multi argument constructors. Fuck me.
if (constructor.getNumOperands() != 1) {
return failure();
}
} // end alts loop
assert(constructorName &&
"must have found constructor. Otherwise, the case has zero alts!");
assert(rets.size() == constructors.size());
std::vector<HaskReturnOp> newRets;
// ret[i](constructors[i](val)) -> ret[i](val)
for (int i = 0; i < (int)rets.size(); ++i) {
rewriter.setInsertionPointAfter(rets[i]);
newRets.push_back(rewriter.create<mlir::standalone::HaskReturnOp>(
rets[i].getLoc(), constructors[i].getOperand(0)));
rewriter.eraseOp(rets[i]);
}
assert(newRets.size() > 0);
caseop.getResult().setType(newRets[0].getType());
// OK, so all branches have a constructor. pull constructor out
// after the case.
rewriter.setInsertionPointAfter(caseop);
HaskConstructOp peeledConstructor = rewriter.create<HaskConstructOp>(
rewriter.getUnknownLoc(), *constructorName, caseop.getResult());
// does this *remove* the old op?
llvm::SmallPtrSet<mlir::Operation *, 4> exceptions(
{peeledConstructor.getOperation()});
// replace all uses, except the one by peeledConstructor
caseop.getResult().replaceAllUsesExcept(peeledConstructor.getResult(),
exceptions);
return success();
}
};
// ===INPUT===
// @f(i: i64) = case box of 0 -> Foo y; 1 -> Foo z
// ===OUTPUT====
// @f(i: i64) = Foo (case i of 0 -> y; 1 -> z)
struct PeelConstructorsFromCaseIntPattern
: public mlir::OpRewritePattern<CaseIntOp> {
PeelConstructorsFromCaseIntPattern(mlir::MLIRContext *context)
: OpRewritePattern<CaseIntOp>(context, /*benefit=*/1) {}
mlir::LogicalResult
matchAndRewrite(CaseIntOp caseop,
mlir::PatternRewriter &rewriter) const override {
llvm::Optional<std::string> constructorName;
// ret[i](constructors[i](val)) -> ret[i](val)
std::vector<mlir::standalone::HaskReturnOp> rets;
std::vector<mlir::standalone::HaskConstructOp> constructors;
for (int i = 0; i < caseop.getNumAlts(); ++i) {
mlir::Region &rhs = caseop.getAltRHS(i);
if (rhs.getBlocks().size() > 1) {
return failure();
}
mlir::standalone::HaskReturnOp ret =
mlir::dyn_cast<HaskReturnOp>(rhs.getBlocks().front().getTerminator());
if (!ret) {
return failure();
}
rets.push_back(ret);
mlir::standalone::HaskConstructOp constructor =
ret.getOperand().getDefiningOp<HaskConstructOp>();
if (!constructor) {
return failure();
}
constructors.push_back(constructor);
if (!constructorName) {
constructorName = constructor.getDataConstructorName().str();
continue;
}
assert(constructorName);
if (constructorName != constructor.getDataConstructorName().str()) {
return failure();
}
// TODO: handle multi argument constructors. Fuck me.
if (constructor.getNumOperands() != 1) {
return failure();
}
} // end alts loop
assert(constructorName &&
"must have found constructor. Otherwise, the case has zero alts!");
assert(rets.size() == constructors.size());
std::vector<HaskReturnOp> newRets;
// ret[i](constructors[i](val)) -> ret[i](val)
for (int i = 0; i < (int)rets.size(); ++i) {
rewriter.setInsertionPointAfter(rets[i]);
newRets.push_back(rewriter.create<mlir::standalone::HaskReturnOp>(
rets[i].getLoc(), constructors[i].getOperand(0)));
rewriter.eraseOp(rets[i]);
}
assert(newRets.size() > 0);
caseop.getResult().setType(newRets[0].getType());
// OK, so all branches have a constructor. pull constructor out
// after the case.
rewriter.setInsertionPointAfter(caseop);
HaskConstructOp peeledConstructor = rewriter.create<HaskConstructOp>(
rewriter.getUnknownLoc(), *constructorName, caseop.getResult());
// does this *remove* the old op?
llvm::SmallPtrSet<mlir::Operation *, 4> exceptions(
{peeledConstructor.getOperation()});
// replace all uses, except the one by peeledConstructor
caseop.getResult().replaceAllUsesExcept(peeledConstructor.getResult(),
exceptions);
return success();
}
};
struct WorkerWrapperPass : public Pass {
WorkerWrapperPass() : Pass(mlir::TypeID::get<WorkerWrapperPass>()){};
StringRef getName() const override { return "WorkerWrapperPass"; }
std::unique_ptr<Pass> clonePass() const override {
auto newInst = std::make_unique<WorkerWrapperPass>(
*static_cast<const WorkerWrapperPass *>(this));
newInst->copyOptionValuesFrom(this);
return newInst;
}
void runOnOperation() override {
mlir::OwningRewritePatternList patterns(&getContext());
// force(ap) -> apeager. safe.
patterns.insert<ForceOfKnownApPattern>(&getContext());
// force(thunkify(x)) -> x. safe.
patterns.insert<ForceOfThunkifyPattern>(&getContext());
// apeager(f, x, y, z) -> inlined. safe.
patterns.insert<InlineApEagerPattern>(&getContext());
// f(paramt): paramv = force(paramt); use paramv. Safe-ish, since
// we immediately have a force as the first instruction.
// 1. Write as FuncOp pattern
// 2. Write as closure.
patterns.insert<OutlineRecursiveApEagerOfThunkPattern>(&getContext());
// f(paramConstructor) = case paramConstructor of {
// (Constructor paramValue) -> ..
// }.
// Safe ish, since we immediately expect a case of the first
// instruction.
// 1. Write as FuncOp pattern
// 2. write as closure.
patterns.insert<OutlineRecursiveApEagerOfConstructorPattern>(&getContext());
// same as above?
patterns.insert<OutlineCaseOfFnInput>(&getContext());
// f(x): .. return(Constructor(v)) -> outline the last paer. Safe ish,
// since we only outline the final computation.
patterns.insert<OutlineReturnOfConstructor>(&getContext());
// f: case of {C1 -> D v1; C2 -> D v2; .. Cn -> D vn;} into
// f: D (case v of {C1 -> v1; C2 -> v2; .. Cn -> vn; }
// Safe.
patterns.insert<PeelConstructorsFromCasePattern>(&getContext());
// Same as peel constructor from case for ints. safe.
patterns.insert<PeelConstructorsFromCaseIntPattern>(&getContext());
// f: case (Ci vi) of { C1 w1 -> e1; C2 w2 -> e2 ... Cn wn -> en};
// f: ei[wi := vi].
// safe
patterns.insert<CaseOfKnownConstructorPattern>(&getContext());
// same as Case of known constructor for ints. safe.
patterns.insert<CaseOfKnownIntPattern>(&getContext());
::llvm::DebugFlag = true;
// ConversionTarget target(getContext());
// if (failed(mlir::applyPartialConversion(getOperation(), target,
// std::move(patterns)))) {
if (failed(mlir::applyPatternsAndFoldGreedily(getOperation(),
std::move(patterns)))) {
llvm::errs() << "\n===Worker wrapper failed===\n";
getOperation()->print(llvm::errs());
llvm::errs() << "\n===\n";
signalPassFailure();
} else {
llvm::errs() << "===Worker wrapper succeeded===\n";
getOperation()->print(llvm::errs());
llvm::errs() << "\n===\n";
}
::llvm::DebugFlag = false;
};
};
struct WrapperWorkerPass : public Pass {
WrapperWorkerPass() : Pass(mlir::TypeID::get<WrapperWorkerPass>()){};
StringRef getName() const override { return "WrapperWorkerPass"; }
std::unique_ptr<Pass> clonePass() const override {
auto newInst = std::make_unique<WrapperWorkerPass>(
*static_cast<const WrapperWorkerPass *>(this));
newInst->copyOptionValuesFrom(this);
return newInst;
}
void runOnOperation() override {
mlir::OwningRewritePatternList patterns(&getContext());
patterns.insert<ThunkifyOfForcePattern>(&getContext());
::llvm::DebugFlag = true;
if (failed(mlir::applyPatternsAndFoldGreedily(getOperation(),
std::move(patterns)))) {
llvm::errs() << "\n===Worker wrapper failed===\n";
getOperation()->print(llvm::errs());
llvm::errs() << "\n===\n";
signalPassFailure();
} else {
llvm::errs() << "===Worker wrapper succeeded===\n";
getOperation()->print(llvm::errs());
llvm::errs() << "\n===\n";
}
::llvm::DebugFlag = false;
};
};
std::unique_ptr<mlir::Pass> createWorkerWrapperPass() {
return std::make_unique<WorkerWrapperPass>();
}
std::unique_ptr<mlir::Pass> createWrapperWorkerPass() {
return std::make_unique<WrapperWorkerPass>();
}
void registerWorkerWrapperPass() {
::mlir::registerPass("lz-worker-wrapper",
"Perform worker wrapper transform to expose computation",
[]() -> std::unique_ptr<::mlir::Pass> {
return createWorkerWrapperPass();
});
}
void registerWrapperWorkerPass() {
::mlir::registerPass("lz-wrapper-worker",
"Perform wrapper worker transform to hide computation",
[]() -> std::unique_ptr<::mlir::Pass> {
return createWrapperWorkerPass();
});
}
} // namespace standalone
} // namespace mlir
| 34.552075 | 116 | 0.640233 | bollu |
d1261471d3344588b1edeee41b378ac3b103d969 | 1,522 | cpp | C++ | findLargestWordInDictionary.cpp | harshallgarg/CPP | 4d15c5e5d426bb00d192368d21924ec9f017445f | [
"MIT"
] | 2 | 2020-08-09T02:09:50.000Z | 2020-08-09T07:07:47.000Z | findLargestWordInDictionary.cpp | harshallgarg/CPP | 4d15c5e5d426bb00d192368d21924ec9f017445f | [
"MIT"
] | null | null | null | findLargestWordInDictionary.cpp | harshallgarg/CPP | 4d15c5e5d426bb00d192368d21924ec9f017445f | [
"MIT"
] | 4 | 2020-05-25T10:24:14.000Z | 2021-05-03T07:52:35.000Z | //leetcode solution
class Solution {
public:
bool isSubsequence(string word,string s)
{
int m=word.length(),n=s.length();
int i,j;
for(i=0,j=0;i<m&&j<n;j++)
if(word.at(i)==s.at(j))
i++;
return i==m;
}
string findLongestWord(string s, vector<string>& d)
{
string result="";
for(string word:d)
{
if(result.length()<=word.length()&&isSubsequence(word,s)&&(result>word||result.length()<word.length()))
{
result=word;
}
}
return result;
}
};
//geeksforgeeks solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isSubsequence(string word,string s)
{
int m=word.length(),n=s.length();
int i,j;
for(i=0,j=0;i<m&&j<n;j++)
if(word.at(i)==s.at(j))
i++;
return i==m;
}
string findLongestWord(string s, vector<string>& d)
{
string result;
int length=0;
for(string word:d)
{
if(length<word.length()&&isSubsequence(word,s))
{
result=word;
length=word.length();
}
}
return result;
}
int main()
{
int cases;
cin>>cases;
while(cases--)
{
int n;
cin>>n;
vector<string> dict;
while(n--)
{
string x;
cin>>x;
dict.push_back(x);
}
string s;
cin>>s;
cout<<findLongestWord(s,dict)<<endl;
}
} | 19.766234 | 115 | 0.489488 | harshallgarg |
d1266dd63716968b56af1eec682713c3d8810254 | 15,405 | cpp | C++ | src/ndnSIM/NFD/tests/daemon/mgmt/face-manager.t.cpp | NDNLink/NDN-Chord | cfabf8f56eea2c4ba47052ce145a939ebdc21e57 | [
"MIT"
] | 1 | 2021-09-07T04:12:15.000Z | 2021-09-07T04:12:15.000Z | src/ndnSIM/NFD/tests/daemon/mgmt/face-manager.t.cpp | NDNLink/NDN-Chord | cfabf8f56eea2c4ba47052ce145a939ebdc21e57 | [
"MIT"
] | null | null | null | src/ndnSIM/NFD/tests/daemon/mgmt/face-manager.t.cpp | NDNLink/NDN-Chord | cfabf8f56eea2c4ba47052ce145a939ebdc21e57 | [
"MIT"
] | 1 | 2020-07-15T06:21:03.000Z | 2020-07-15T06:21:03.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2014-2018, Regents of the University of California,
* Arizona Board of Regents,
* Colorado State University,
* University Pierre & Marie Curie, Sorbonne University,
* Washington University in St. Louis,
* Beijing Institute of Technology,
* The University of Memphis.
*
* This file is part of NFD (Named Data Networking Forwarding Daemon).
* See AUTHORS.md for complete list of NFD authors and contributors.
*
* NFD is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* NFD 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
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mgmt/face-manager.hpp"
#include "core/random.hpp"
#include "face/protocol-factory.hpp"
#include "nfd-manager-common-fixture.hpp"
#include "../face/dummy-face.hpp"
#include "../face/dummy-transport.hpp"
#include <ndn-cxx/encoding/tlv.hpp>
#include <ndn-cxx/encoding/tlv-nfd.hpp>
#include <ndn-cxx/mgmt/nfd/channel-status.hpp>
#include <ndn-cxx/net/network-monitor-stub.hpp>
namespace nfd {
namespace tests {
class FaceManagerFixture : public NfdManagerCommonFixture
{
public:
FaceManagerFixture()
: m_faceTable(m_forwarder.getFaceTable())
, m_faceSystem(m_faceTable, make_shared<ndn::net::NetworkMonitorStub>(0))
, m_manager(m_faceSystem, m_dispatcher, *m_authenticator)
{
setTopPrefix();
setPrivilege("faces");
}
public:
enum AddFaceFlags {
REMOVE_LAST_NOTIFICATION = 1 << 0,
SET_SCOPE_LOCAL = 1 << 1,
SET_URI_TEST = 1 << 2,
RANDOMIZE_COUNTERS = 1 << 3,
};
/** \brief adds a face to the FaceTable
* \param options bitwise OR'ed AddFaceFlags
*/
shared_ptr<Face>
addFace(unsigned int flags = 0)
{
std::string uri = "dummy://";
ndn::nfd::FaceScope scope = ndn::nfd::FACE_SCOPE_NON_LOCAL;
if ((flags & SET_SCOPE_LOCAL) != 0) {
scope = ndn::nfd::FACE_SCOPE_LOCAL;
}
if ((flags & SET_URI_TEST) != 0) {
uri = "test://";
}
auto face = make_shared<DummyFace>(uri, uri, scope);
m_faceTable.add(face);
if ((flags & RANDOMIZE_COUNTERS) != 0) {
const face::FaceCounters& counters = face->getCounters();
randomizeCounter(counters.nInInterests);
randomizeCounter(counters.nOutInterests);
randomizeCounter(counters.nInData);
randomizeCounter(counters.nOutData);
randomizeCounter(counters.nInNacks);
randomizeCounter(counters.nOutNacks);
randomizeCounter(counters.nInPackets);
randomizeCounter(counters.nOutPackets);
randomizeCounter(counters.nInBytes);
randomizeCounter(counters.nOutBytes);
}
advanceClocks(time::milliseconds(1), 10); // wait for notification posted
if ((flags & REMOVE_LAST_NOTIFICATION) != 0) {
m_responses.pop_back();
}
return face;
}
private:
template<typename T>
static void
randomizeCounter(const T& counter)
{
static std::uniform_int_distribution<typename T::rep> dist;
const_cast<T&>(counter).set(dist(getGlobalRng()));
}
protected:
FaceTable& m_faceTable;
FaceSystem m_faceSystem;
FaceManager m_manager;
};
BOOST_AUTO_TEST_SUITE(Mgmt)
BOOST_FIXTURE_TEST_SUITE(TestFaceManager, FaceManagerFixture)
BOOST_AUTO_TEST_SUITE(DestroyFace)
BOOST_AUTO_TEST_CASE(Existing)
{
auto addedFace = addFace(REMOVE_LAST_NOTIFICATION | SET_SCOPE_LOCAL); // clear notification for creation
auto parameters = ControlParameters().setFaceId(addedFace->getId());
auto req = makeControlCommandRequest("/localhost/nfd/faces/destroy", parameters);
receiveInterest(req);
BOOST_REQUIRE_EQUAL(m_responses.size(), 2); // one response and one notification
// notification is already tested, so ignore it
BOOST_CHECK_EQUAL(checkResponse(1, req.getName(), makeResponse(200, "OK", parameters)),
CheckResponseResult::OK);
BOOST_CHECK_EQUAL(addedFace->getId(), face::INVALID_FACEID);
}
BOOST_AUTO_TEST_CASE(NonExisting)
{
auto parameters = ControlParameters().setFaceId(65535);
auto req = makeControlCommandRequest("/localhost/nfd/faces/destroy", parameters);
receiveInterest(req);
BOOST_REQUIRE_EQUAL(m_responses.size(), 1);
BOOST_CHECK_EQUAL(checkResponse(0, req.getName(), makeResponse(200, "OK", parameters)),
CheckResponseResult::OK);
}
BOOST_AUTO_TEST_SUITE_END() // DestroyFace
BOOST_AUTO_TEST_SUITE(Datasets)
BOOST_AUTO_TEST_CASE(FaceDataset)
{
const size_t nEntries = 303;
for (size_t i = 0; i < nEntries; ++i) {
addFace(REMOVE_LAST_NOTIFICATION | SET_URI_TEST | RANDOMIZE_COUNTERS);
}
receiveInterest(Interest("/localhost/nfd/faces/list"));
Block content = concatenateResponses();
content.parse();
BOOST_REQUIRE_EQUAL(content.elements().size(), nEntries);
std::set<FaceId> faceIds;
for (size_t idx = 0; idx < nEntries; ++idx) {
ndn::nfd::FaceStatus decodedStatus(content.elements()[idx]);
BOOST_CHECK(m_faceTable.get(decodedStatus.getFaceId()) != nullptr);
faceIds.insert(decodedStatus.getFaceId());
}
BOOST_CHECK_EQUAL(faceIds.size(), nEntries);
// TODO#3325 check dataset contents including counter values
}
BOOST_AUTO_TEST_CASE(FaceQuery)
{
using ndn::nfd::FaceQueryFilter;
auto face1 = addFace(REMOVE_LAST_NOTIFICATION); // dummy://
auto face2 = addFace(REMOVE_LAST_NOTIFICATION | SET_SCOPE_LOCAL); // dummy://, local
auto face3 = addFace(REMOVE_LAST_NOTIFICATION | SET_URI_TEST); // test://
auto generateQueryName = [] (const FaceQueryFilter& filter) {
return Name("/localhost/nfd/faces/query").append(filter.wireEncode());
};
auto querySchemeName = generateQueryName(FaceQueryFilter().setUriScheme("dummy"));
auto queryIdName = generateQueryName(FaceQueryFilter().setFaceId(face1->getId()));
auto queryScopeName = generateQueryName(FaceQueryFilter().setFaceScope(ndn::nfd::FACE_SCOPE_NON_LOCAL));
auto invalidQueryName = Name("/localhost/nfd/faces/query")
.append(ndn::makeStringBlock(tlv::Content, "invalid"));
receiveInterest(Interest(querySchemeName)); // face1 and face2 expected
receiveInterest(Interest(queryIdName)); // face1 expected
receiveInterest(Interest(queryScopeName)); // face1 and face3 expected
receiveInterest(Interest(invalidQueryName)); // nack expected
BOOST_REQUIRE_EQUAL(m_responses.size(), 4);
Block content;
ndn::nfd::FaceStatus status;
content = m_responses[0].getContent();
content.parse();
BOOST_CHECK_EQUAL(content.elements().size(), 2); // face1 and face2
status.wireDecode(content.elements()[0]);
BOOST_CHECK_EQUAL(face1->getId(), status.getFaceId());
status.wireDecode(content.elements()[1]);
BOOST_CHECK_EQUAL(face2->getId(), status.getFaceId());
content = m_responses[1].getContent();
content.parse();
BOOST_CHECK_EQUAL(content.elements().size(), 1); // face1
status.wireDecode(content.elements()[0]);
BOOST_CHECK_EQUAL(face1->getId(), status.getFaceId());
content = m_responses[2].getContent();
content.parse();
BOOST_CHECK_EQUAL(content.elements().size(), 2); // face1 and face3
status.wireDecode(content.elements()[0]);
BOOST_CHECK_EQUAL(face1->getId(), status.getFaceId());
status.wireDecode(content.elements()[1]);
BOOST_CHECK_EQUAL(face3->getId(), status.getFaceId());
ControlResponse expectedResponse(400, "Malformed filter"); // nack, 400, malformed filter
BOOST_CHECK_EQUAL(checkResponse(3, invalidQueryName, expectedResponse, tlv::ContentType_Nack),
CheckResponseResult::OK);
}
class TestChannel : public face::Channel
{
public:
explicit
TestChannel(const std::string& uri)
{
setUri(FaceUri(uri));
}
bool
isListening() const final
{
return false;
}
size_t
size() const final
{
return 0;
}
};
class TestProtocolFactory : public face::ProtocolFactory
{
public:
TestProtocolFactory(const CtorParams& params)
: ProtocolFactory(params)
{
}
void
processConfig(OptionalConfigSection configSection,
FaceSystem::ConfigContext& context) final
{
}
void
createFace(const CreateFaceRequest& req,
const face::FaceCreatedCallback& onCreated,
const face::FaceCreationFailedCallback& onConnectFailed) final
{
}
std::vector<shared_ptr<const face::Channel>>
getChannels() const final
{
return m_channels;
}
public:
shared_ptr<TestChannel>
addChannel(const std::string& channelUri)
{
auto channel = make_shared<TestChannel>(channelUri);
m_channels.push_back(channel);
return channel;
}
private:
std::vector<shared_ptr<const face::Channel>> m_channels;
};
BOOST_AUTO_TEST_CASE(ChannelDataset)
{
m_faceSystem.m_factories["test"] =
make_unique<TestProtocolFactory>(m_faceSystem.makePFCtorParams());
auto factory = static_cast<TestProtocolFactory*>(m_faceSystem.getFactoryById("test"));
const size_t nEntries = 404;
std::map<std::string, shared_ptr<TestChannel>> addedChannels;
for (size_t i = 0; i < nEntries; i++) {
auto channel = factory->addChannel("test" + to_string(i) + "://");
addedChannels[channel->getUri().toString()] = channel;
}
receiveInterest(Interest("/localhost/nfd/faces/channels"));
Block content = concatenateResponses();
content.parse();
BOOST_REQUIRE_EQUAL(content.elements().size(), nEntries);
for (size_t idx = 0; idx < nEntries; ++idx) {
ndn::nfd::ChannelStatus decodedStatus(content.elements()[idx]);
BOOST_CHECK(addedChannels.find(decodedStatus.getLocalUri()) != addedChannels.end());
}
}
BOOST_AUTO_TEST_SUITE_END() // Datasets
BOOST_AUTO_TEST_SUITE(Notifications)
BOOST_AUTO_TEST_CASE(FaceEventCreated)
{
auto face = addFace(); // trigger FACE_EVENT_CREATED notification
BOOST_CHECK_NE(face->getId(), face::INVALID_FACEID);
FaceId faceId = face->getId();
BOOST_CHECK_EQUAL(m_manager.m_faceStateChangeConn.count(faceId), 1);
// check notification
BOOST_REQUIRE_EQUAL(m_responses.size(), 1);
Block payload = m_responses.back().getContent().blockFromValue();
BOOST_CHECK_EQUAL(payload.type(), ndn::tlv::nfd::FaceEventNotification);
ndn::nfd::FaceEventNotification notification(payload);
BOOST_CHECK_EQUAL(notification.getKind(), ndn::nfd::FACE_EVENT_CREATED);
BOOST_CHECK_EQUAL(notification.getFaceId(), faceId);
BOOST_CHECK_EQUAL(notification.getRemoteUri(), face->getRemoteUri().toString());
BOOST_CHECK_EQUAL(notification.getLocalUri(), face->getLocalUri().toString());
BOOST_CHECK_EQUAL(notification.getFaceScope(), ndn::nfd::FACE_SCOPE_NON_LOCAL);
BOOST_CHECK_EQUAL(notification.getFacePersistency(), ndn::nfd::FACE_PERSISTENCY_PERSISTENT);
BOOST_CHECK_EQUAL(notification.getLinkType(), ndn::nfd::LinkType::LINK_TYPE_POINT_TO_POINT);
BOOST_CHECK_EQUAL(notification.getFlags(), 0);
}
BOOST_AUTO_TEST_CASE(FaceEventDownUp)
{
auto face = addFace();
BOOST_CHECK_NE(face->getId(), face::INVALID_FACEID);
FaceId faceId = face->getId();
// trigger FACE_EVENT_DOWN notification
dynamic_cast<face::tests::DummyTransport*>(face->getTransport())->setState(face::FaceState::DOWN);
advanceClocks(time::milliseconds(1), 10);
BOOST_CHECK_EQUAL(face->getState(), face::FaceState::DOWN);
// check notification
{
BOOST_REQUIRE_EQUAL(m_responses.size(), 2);
Block payload = m_responses.back().getContent().blockFromValue();
BOOST_CHECK_EQUAL(payload.type(), ndn::tlv::nfd::FaceEventNotification);
ndn::nfd::FaceEventNotification notification(payload);
BOOST_CHECK_EQUAL(notification.getKind(), ndn::nfd::FACE_EVENT_DOWN);
BOOST_CHECK_EQUAL(notification.getFaceId(), faceId);
BOOST_CHECK_EQUAL(notification.getRemoteUri(), face->getRemoteUri().toString());
BOOST_CHECK_EQUAL(notification.getLocalUri(), face->getLocalUri().toString());
BOOST_CHECK_EQUAL(notification.getFaceScope(), ndn::nfd::FACE_SCOPE_NON_LOCAL);
BOOST_CHECK_EQUAL(notification.getFacePersistency(), ndn::nfd::FACE_PERSISTENCY_PERSISTENT);
BOOST_CHECK_EQUAL(notification.getLinkType(), ndn::nfd::LinkType::LINK_TYPE_POINT_TO_POINT);
BOOST_CHECK_EQUAL(notification.getFlags(), 0);
}
// trigger FACE_EVENT_UP notification
dynamic_cast<face::tests::DummyTransport*>(face->getTransport())->setState(face::FaceState::UP);
advanceClocks(time::milliseconds(1), 10);
BOOST_CHECK_EQUAL(face->getState(), face::FaceState::UP);
// check notification
{
BOOST_REQUIRE_EQUAL(m_responses.size(), 3);
Block payload = m_responses.back().getContent().blockFromValue();
BOOST_CHECK_EQUAL(payload.type(), ndn::tlv::nfd::FaceEventNotification);
ndn::nfd::FaceEventNotification notification(payload);
BOOST_CHECK_EQUAL(notification.getKind(), ndn::nfd::FACE_EVENT_UP);
BOOST_CHECK_EQUAL(notification.getFaceId(), faceId);
BOOST_CHECK_EQUAL(notification.getRemoteUri(), face->getRemoteUri().toString());
BOOST_CHECK_EQUAL(notification.getLocalUri(), face->getLocalUri().toString());
BOOST_CHECK_EQUAL(notification.getFaceScope(), ndn::nfd::FACE_SCOPE_NON_LOCAL);
BOOST_CHECK_EQUAL(notification.getFacePersistency(), ndn::nfd::FACE_PERSISTENCY_PERSISTENT);
BOOST_CHECK_EQUAL(notification.getLinkType(), ndn::nfd::LinkType::LINK_TYPE_POINT_TO_POINT);
BOOST_CHECK_EQUAL(notification.getFlags(), 0);
}
}
BOOST_AUTO_TEST_CASE(FaceEventDestroyed)
{
auto face = addFace();
BOOST_CHECK_NE(face->getId(), face::INVALID_FACEID);
FaceId faceId = face->getId();
BOOST_CHECK_EQUAL(m_manager.m_faceStateChangeConn.count(faceId), 1);
face->close(); // trigger FaceDestroy FACE_EVENT_DESTROYED
advanceClocks(time::milliseconds(1), 10);
// check notification
BOOST_REQUIRE_EQUAL(m_responses.size(), 2);
Block payload = m_responses.back().getContent().blockFromValue();
BOOST_CHECK_EQUAL(payload.type(), ndn::tlv::nfd::FaceEventNotification);
ndn::nfd::FaceEventNotification notification(payload);
BOOST_CHECK_EQUAL(notification.getKind(), ndn::nfd::FACE_EVENT_DESTROYED);
BOOST_CHECK_EQUAL(notification.getFaceId(), faceId);
BOOST_CHECK_EQUAL(notification.getRemoteUri(), face->getRemoteUri().toString());
BOOST_CHECK_EQUAL(notification.getLocalUri(), face->getLocalUri().toString());
BOOST_CHECK_EQUAL(notification.getFaceScope(), ndn::nfd::FACE_SCOPE_NON_LOCAL);
BOOST_CHECK_EQUAL(notification.getFacePersistency(), ndn::nfd::FACE_PERSISTENCY_PERSISTENT);
BOOST_CHECK_EQUAL(notification.getLinkType(), ndn::nfd::LinkType::LINK_TYPE_POINT_TO_POINT);
BOOST_CHECK_EQUAL(notification.getFlags(), 0);
BOOST_CHECK_EQUAL(face->getId(), face::INVALID_FACEID);
BOOST_CHECK_EQUAL(m_manager.m_faceStateChangeConn.count(faceId), 0);
}
BOOST_AUTO_TEST_SUITE_END() // Notifications
BOOST_AUTO_TEST_SUITE_END() // TestFaceManager
BOOST_AUTO_TEST_SUITE_END() // Mgmt
} // namespace tests
} // namespace nfd
| 35.577367 | 106 | 0.727556 | NDNLink |
d1274674e98c07b167b67cc3c6fda955077c5ef6 | 8,592 | cpp | C++ | src/libraries/criterion/cpu/ForceAlignmentCriterion.cpp | lithathampan/wav2letter | 8abf8431d99da147cc4aefc289ad33626e13de6f | [
"BSD-3-Clause"
] | null | null | null | src/libraries/criterion/cpu/ForceAlignmentCriterion.cpp | lithathampan/wav2letter | 8abf8431d99da147cc4aefc289ad33626e13de6f | [
"BSD-3-Clause"
] | null | null | null | src/libraries/criterion/cpu/ForceAlignmentCriterion.cpp | lithathampan/wav2letter | 8abf8431d99da147cc4aefc289ad33626e13de6f | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "libraries/criterion/cpu/ForceAlignmentCriterion.h"
#include <algorithm>
#include <cmath>
#include "libraries/common/Utils.h"
#include "libraries/common/Workspace.h"
#include "libraries/criterion/cpu/CriterionUtils.h"
namespace {
template <class Float>
struct WorkspacePtrs {
WorkspacePtrs(void* workspace, int B, int T, int N, int L) {
w2l::Workspace<> ws(workspace);
ws.request(&scale, B);
ws.request(&alpha, B, T, L);
ws.request(&alphaGrad, B, T, L);
ws.request(&transBatchGrad, B, N, N);
ws.request(&transBuf1, B, L);
ws.request(&transBuf2, B, L);
ws.request(&transBufGrad1, B, L);
ws.request(&transBufGrad2, B, L);
requiredSize = ws.requiredSize();
}
Float* scale;
double* alpha;
double* alphaGrad;
Float* transBatchGrad;
Float* transBuf1;
Float* transBuf2;
Float* transBufGrad1;
Float* transBufGrad2;
size_t requiredSize;
};
} // namespace
namespace w2l {
namespace cpu {
template <class Float>
size_t
ForceAlignmentCriterion<Float>::getWorkspaceSize(int B, int T, int N, int L) {
WorkspacePtrs<Float> dummy(nullptr, B, T, N, L);
return dummy.requiredSize;
}
template <class Float>
void ForceAlignmentCriterion<Float>::forward(
int B,
int T,
int N,
int _L,
CriterionScaleMode scaleMode,
const Float* _input,
const int* _target,
const int* targetSize,
const Float* trans,
Float* loss,
void* workspace) {
WorkspacePtrs<Float> ws(workspace, B, T, N, _L);
CriterionUtils<Float>::computeScale(B, T, N, scaleMode, targetSize, ws.scale);
#pragma omp parallel for num_threads(B)
for (int b = 0; b < B; ++b) {
auto* alpha = &ws.alpha[b * T * _L];
auto* input = &_input[b * T * N];
auto* target = &_target[b * _L];
auto* transBuf1 = &ws.transBuf1[b * _L];
auto* transBuf2 = &ws.transBuf2[b * _L];
int L = targetSize[b];
alpha[0] = input[target[0]];
for (int i = 0; i < L; ++i) {
transBuf1[i] = trans[target[i] * N + target[i]];
transBuf2[i] = i > 0 ? trans[target[i] * N + target[i - 1]] : 0;
}
for (int t = 1; t < T; ++t) {
auto* inputCur = &input[t * N];
auto* alphaPrev = &alpha[(t - 1) * L];
auto* alphaCur = &alpha[t * L];
int high = t < L ? t : L;
int low = T - t < L ? L - (T - t) : 1;
if (T - t >= L) {
alphaCur[0] = alphaPrev[0] + transBuf1[0] + inputCur[target[0]];
}
if (t < L) {
alphaCur[high] =
alphaPrev[high - 1] + transBuf2[high] + inputCur[target[high]];
}
for (int i = low; i < high; ++i) {
double s1 = alphaPrev[i] + transBuf1[i];
double s2 = alphaPrev[i - 1] + transBuf2[i];
// lse = logSumExp(s1, s2)
double lse =
s1 < s2 ? s2 + log1p(exp(s1 - s2)) : s1 + log1p(exp(s2 - s1));
alphaCur[i] = lse + inputCur[target[i]];
}
}
loss[b] = alpha[T * L - 1] * ws.scale[b];
}
}
template <class Float>
void ForceAlignmentCriterion<Float>::backward(
int B,
int T,
int N,
int _L,
const int* _target,
const int* targetSize,
const Float* grad,
Float* _inputGrad,
Float* transGrad,
void* workspace) {
WorkspacePtrs<Float> ws(workspace, B, T, N, _L);
setZero(_inputGrad, B * T * N);
setZero(transGrad, N * N);
setZero(ws.alphaGrad, B * T * _L);
setZero(ws.transBatchGrad, B * N * N);
setZero(ws.transBufGrad1, B * _L);
setZero(ws.transBufGrad2, B * _L);
#pragma omp parallel for num_threads(B)
for (int b = 0; b < B; ++b) {
auto* alpha = &ws.alpha[b * T * _L];
auto* alphaGrad = &ws.alphaGrad[b * T * _L];
auto* inputGrad = &_inputGrad[b * T * N];
auto* target = &_target[b * _L];
auto* transBatchGrad = &ws.transBatchGrad[b * N * N];
auto* transBuf1 = &ws.transBuf1[b * _L];
auto* transBuf2 = &ws.transBuf2[b * _L];
auto* transBufGrad1 = &ws.transBufGrad1[b * _L];
auto* transBufGrad2 = &ws.transBufGrad2[b * _L];
int L = targetSize[b];
alphaGrad[T * L - 1] = 1;
for (int t = T - 1; t > 0; --t) {
auto* inputCurGrad = &inputGrad[t * N];
auto* alphaPrev = &alpha[(t - 1) * L];
auto* alphaCurGrad = &alphaGrad[t * L];
auto* alphaPrevGrad = &alphaGrad[(t - 1) * L];
int high = t < L ? t : L;
int low = T - t < L ? L - (T - t) : 1;
int high1 = t < L ? t + 1 : L;
int low1 = T - t < L ? L - (T - t) : 0;
for (int i = low1; i < high1; ++i) {
inputCurGrad[target[i]] += alphaCurGrad[i];
}
if (T - t >= L) {
alphaPrevGrad[0] += alphaCurGrad[0];
transBufGrad1[0] += alphaCurGrad[0];
}
if (t < L) {
alphaPrevGrad[high - 1] += alphaCurGrad[high];
transBufGrad2[high] += alphaCurGrad[high];
}
for (int i = low; i < high; ++i) {
double s1 = alphaPrev[i] + transBuf1[i];
double s2 = alphaPrev[i - 1] + transBuf2[i];
// d1, d2 = dLogSumExp(s1, s2)
double d1, d2;
if (s1 < s2) {
d2 = 1 / (1 + exp(s1 - s2));
d1 = 1 - d2;
} else {
d1 = 1 / (1 + exp(s2 - s1));
d2 = 1 - d1;
}
alphaPrevGrad[i] += d1 * alphaCurGrad[i];
alphaPrevGrad[i - 1] += d2 * alphaCurGrad[i];
transBufGrad1[i] += d1 * alphaCurGrad[i];
transBufGrad2[i] += d2 * alphaCurGrad[i];
}
}
inputGrad[target[0]] += alphaGrad[0];
auto gradScale = grad[b] * ws.scale[b];
for (int i = 0; i < T * N; ++i) {
inputGrad[i] *= gradScale;
}
for (int i = 0; i < L; ++i) {
transBatchGrad[target[i] * N + target[i]] += transBufGrad1[i];
if (i > 0) {
transBatchGrad[target[i] * N + target[i - 1]] += transBufGrad2[i];
}
}
}
for (int b = 0; b < B; ++b) {
auto transBatchGrad = ws.transBatchGrad + b * N * N;
auto gradScale = grad[b] * ws.scale[b];
for (int i = 0; i < N * N; ++i) {
transGrad[i] += gradScale * transBatchGrad[i];
}
}
}
template <class Float>
void ForceAlignmentCriterion<Float>::viterbi(
int B,
int T,
int N,
int _L,
const Float* _input,
const int* _target,
const int* targetSize,
const Float* trans,
int* bestPaths,
void* workspace) {
WorkspacePtrs<Float> ws(workspace, B, T, N, _L);
#pragma omp parallel for num_threads(B)
for (int b = 0; b < B; ++b) {
double* alpha = &ws.alpha[b * T * _L];
const Float* input = &_input[b * T * N];
const int* target = &_target[b * _L];
Float* transBuf1 = &ws.transBuf1[b * _L];
Float* transBuf2 = &ws.transBuf2[b * _L];
int L = targetSize[b];
alpha[0] = input[target[0]];
for (int i = 0; i < L; ++i) {
transBuf1[i] = trans[target[i] * N + target[i]];
transBuf2[i] = i > 0 ? trans[target[i] * N + target[i - 1]] : 0;
}
for (int t = 1; t < T; ++t) {
const Float* inputCur = &input[t * N];
double* alphaPrev = &alpha[(t - 1) * L];
double* alphaCur = &alpha[t * L];
int high = t < L ? t : L;
int low = T - t < L ? L - (T - t) : 1;
// Handle edge cases.
// If (T - t >= L), then we can conceivably still be at the initial blank
if (T - t >= L) {
alphaCur[0] = alphaPrev[0] + transBuf1[0] + inputCur[target[0]];
}
// If (t < L), then the highest position can only be be computed
// by transitioning. (We couldn't have been at position `high`
// at the previous timestep).
if (t < L) {
alphaCur[high] =
alphaPrev[high - 1] + transBuf2[high] + inputCur[target[high]];
}
for (int i = low; i < high; ++i) {
double s1 = alphaPrev[i] + transBuf1[i];
double s2 = alphaPrev[i - 1] + transBuf2[i];
alphaCur[i] = inputCur[target[i]] + fmax(s1, s2);
}
}
auto ltrIdx = L - 1;
int* bestPath = bestPaths + b * T;
for (auto t = T - 1; t > 0; t--) {
bestPath[t] = target[ltrIdx];
auto* alphaPrev = &alpha[(t - 1) * L];
if (ltrIdx > 0) {
double s1 = alphaPrev[ltrIdx] + transBuf1[ltrIdx];
double s2 = alphaPrev[ltrIdx - 1] + transBuf2[ltrIdx];
if (s2 > s1) {
ltrIdx--;
}
}
}
bestPath[0] = target[ltrIdx];
}
}
template struct ForceAlignmentCriterion<float>;
template struct ForceAlignmentCriterion<double>;
} // namespace cpu
} // namespace w2l
| 28.170492 | 80 | 0.551443 | lithathampan |
d12930a94255a4ec9b44c1f3f3a5906d763baae9 | 1,766 | cpp | C++ | drazy/sieve_phi.cpp | gbuenoandrade/Manual-da-Sarrada | dc44666b8f926428164447997b5ea8363ebd6fda | [
"MIT"
] | null | null | null | drazy/sieve_phi.cpp | gbuenoandrade/Manual-da-Sarrada | dc44666b8f926428164447997b5ea8363ebd6fda | [
"MIT"
] | null | null | null | drazy/sieve_phi.cpp | gbuenoandrade/Manual-da-Sarrada | dc44666b8f926428164447997b5ea8363ebd6fda | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define DEBUG_ON 1
#define INF 0x3f3f3f3f
#define NSYNC ios::sync_with_stdio(false);
#define FOR(i,a,b) for(int i=a; i<(b); ++i)
#define FOR0(i,b) for(int i=0; i<(b); ++i)
#define TRAV(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it)
#define RTRAV(it,c) for(__typeof((c).rbegin()) it=(c).rbegin(); it!=(c).rend(); ++it)
#define DBG(x) if(DEBUG_ON) cout << #x << " == " << x << endl
#define DBGP(x) if(DEBUG_ON) cout << "(" << (x).first << ", " << (x).second << ")" << endl
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define R(x) scanf(" %d",&(x))
#define RR(x,y) scanf(" %d %d",&(x), &(y))
#define RRR(x,y,z) scanf(" %d %d %d",&(x), &(y),&(z))
#define CLR(v) memset(v, 0, sizeof(v))
#define SET(v) memset(v, -1, sizeof(v))
typedef long long ll;
typedef int int_type;
typedef pair<int_type, int_type> pii;
typedef vector<int_type> vi;
typedef vector<vi> vii;
const int MAXN = 10000010;
int pr[MAXN];
int divisor[MAXN];
int phi[MAXN];
void sieve(int n) {
FOR0(i,n+1) pr[i] = true;
pr[0] = pr[1] = false;
for(int i=2; i*i<=n; ++i) {
if(!pr[i]) continue;
int k = i*i;
while(k<=n) {
divisor[k] = i;
pr[k] = false;
k += i;
}
}
}
void calc_phi(int n) {
FOR(i,1,n+1) phi[i] = i;
FOR(i,2,n+1) if(pr[i]) {
for(int j=i; j<=n; j+=i) {
phi[j] -= phi[j]/i;
}
}
}
inline int get_div(int n) {
if(pr[n]) return n;
return divisor[n];
}
int factorize(int v[], int n) {
if(n<=1) return 0;
int sz=0;
while(n>1) {
int p = get_div(n);
v[sz++] = p;
n/=p;
}
return sz;
}
int main() {
sieve(1000);
calc_phi(100);
DBG(phi[80]);
DBG(phi[77]);
DBG(phi[50]);
// DBG(phi(80));
// FOR(i,1,11) cout << "phi(" << i << ") = " << phi[i] << endl;
return 0;
} | 21.277108 | 90 | 0.556059 | gbuenoandrade |
d12954839358b9d5ed89bb220b0da36a5a437e1d | 8,991 | cpp | C++ | MasterControl/screensharing.cpp | CrankZ/ScreenSharing-FileTransfer-in-LAN | a6959e2c9c0ca725cf115d43509250d210bf0f17 | [
"MIT"
] | 87 | 2018-11-12T14:49:27.000Z | 2022-03-13T06:42:28.000Z | MasterControl/screensharing.cpp | 55gY/ScreenSharing-FileTransfer-in-LAN | 4b034b70f3e42f4a66eaf8aae1ebc13ca7886e3c | [
"MIT"
] | 3 | 2018-11-20T06:20:52.000Z | 2019-06-07T17:20:07.000Z | MasterControl/screensharing.cpp | 55gY/ScreenSharing-FileTransfer-in-LAN | 4b034b70f3e42f4a66eaf8aae1ebc13ca7886e3c | [
"MIT"
] | 54 | 2018-11-13T02:11:08.000Z | 2021-12-30T14:30:59.000Z | #include "screensharing.h"
ScreenSharing::ScreenSharing(int num=1)
{
quality = 60;
mutex = new QMutex;
mutex->lock();
flag = 0;
lock = true;
readSettings();
sender = new Sender();
QScreen *src = QApplication::primaryScreen();
QPixmap firstPixmap1 = src->grabWindow(QApplication::desktop()->winId());
img1 = firstPixmap1.toImage();
}
ScreenSharing::~ScreenSharing()
{
}
void ScreenSharing::readSettings()
{
QString readName = "settings.ini";
if(readName.isEmpty()) {
//空字符串不处理,返回
qDebug() << "文件名不能为空!";
return;
} else {
//定义文件对象
QFile fileIn(readName);
if(!fileIn.open(QIODevice::ReadOnly)) {
// qDebug() << "文件不存在!";
return; //不处理文件
}
//读取并解析文件
while(!fileIn.atEnd()) {
//读取一行
QByteArray ba = fileIn.readAll();
QString Settings = QString::fromUtf8(ba);
if(Settings.isEmpty()) {
qDebug() << "文件为空,不读取";
} else {
QStringList SettingsList = Settings.split("quality:");
QStringList temp = SettingsList[1].split("\n");
QString strQuality = temp[0];
if(strQuality.toInt() > 100) {
quality = 100;
} else if (strQuality.toInt() <= 0) {
quality = 1;
} else {
quality = strQuality.toInt();
}
qDebug() << "quality:" << quality;
}
}
}
}
/**
* 图片差异对比
* 对比两张图片的所有像素点x
* @todo 关于两个像素点之间的距离问题,应该还有优化空间
*/
bool ScreenSharing::compareImg(QImage img1,QImage img2)
{
int w = img1.width();
int h = img1.height();
// 两个像素点之间的距离
int distance = 30;
if(!img2.isNull() && !img1.isNull()) {
for(int x = 0;x < w;x += distance) {
for(int y = 0;y < h;y += distance) {
QRgb *rgb1 = (QRgb*)img1.pixel(x,y);
QRgb *rgb2 = (QRgb*)img2.pixel(x,y);
// 如果两张图片,有一个像素点不一样,就说明这两张图片肯定不一样
// 如果两张图片,有一个像素点一样,不一定说明这两个图片相同
if(rgb1 != rgb2) {
qDebug() << "不一样";
return false;
}
}
}
}
// 只有等两张图片,对比完,所有像素点都没有不相同时,才算这两张图片一样
// qDebug() << "一样";
return true;
}
void ScreenSharing::run()
{
while (1) {
if (0 == flag)
mutex->lock();
if (2 == flag)
break;
CURSORINFO cursorInfo;
cursorInfo.cbSize = sizeof(cursorInfo);
GetCursorInfo(&cursorInfo);
// 下面是各种光标的信息
HCURSOR APPSTARTING = LoadCursor(NULL, IDC_APPSTARTING);
HCURSOR ARROW = LoadCursor(NULL, IDC_ARROW);
HCURSOR CROSS = LoadCursor(NULL, IDC_CROSS );
HCURSOR HAND = LoadCursor(NULL, IDC_HAND );
HCURSOR HELP = LoadCursor(NULL, IDC_HELP );
HCURSOR IBEAM = LoadCursor(NULL, IDC_IBEAM );
HCURSOR ICON = LoadCursor(NULL, IDC_ICON );
HCURSOR NO = LoadCursor(NULL, IDC_NO );
HCURSOR SIZE = LoadCursor(NULL, IDC_SIZE );
HCURSOR SIZEALL = LoadCursor(NULL, IDC_SIZEALL);
HCURSOR SIZENESW = LoadCursor(NULL, IDC_SIZENESW);
HCURSOR SIZENS = LoadCursor(NULL, IDC_SIZENS);
HCURSOR SIZENWSE = LoadCursor(NULL, IDC_SIZENWSE);
HCURSOR SIZEWE = LoadCursor(NULL, IDC_SIZEWE);
HCURSOR UPARROW = LoadCursor(NULL, IDC_UPARROW);
HCURSOR WAIT = LoadCursor(NULL, IDC_WAIT);
HCURSOR currentCursorType = cursorInfo.hCursor;
if(currentCursorType == IBEAM) {
cursorType = "IBEAM";
} else {
//其他所有的都用这个来演示
cursorType = "ELSE";
}
QPixmap tempPixmap1;
QScreen *src = QApplication::primaryScreen();
tempPixmap1 = src->grabWindow(QApplication::desktop()->winId());
// QScreen *src = QApplication::screens().last();
// tempPixmap1 = src->grabWindow(0, src->geometry().x(), src->geometry().y(), src->size().width(), src->size().height());
QImage img2 = tempPixmap1.toImage();
// 如果不一样,则发送
// 差异比较
if(!compareImg(img1, img2) || firstScreen) {
// 刚开始的时候,不管有没有变化,都要发一帧。
firstScreen = false;
// matrix.rotate(90);
// QPixmap tempPixmap = pixmap.transformed(matrix);
QBuffer buffer;
tempPixmap1.save(&buffer,"jpg",quality);
//不分包
// udp->writeDatagram(buffer.data().data(), buffer.data().size(),
// QHostAddress(ui->lineEditIP->text()), ui->lineEditPort->text().toInt());
//分包开始+++++++++++++++++++++++++++
// 必须分包,因为UDP对传输大小有限制,不能直接传输整个文件
int dataLength=buffer.data().size();
unsigned char *dataBuffer=(unsigned char *)buffer.data().data();
buffer.close();
int packetNum = 0;
int lastPaketSize = 0;
packetNum = dataLength / UDP_MAX_SIZE;
lastPaketSize = dataLength % UDP_MAX_SIZE;
int currentPacketIndex = 0;
if (lastPaketSize != 0) {
packetNum = packetNum + 1;
}
PackageHeader packageHead;
packageHead.uTransPackageHdrSize = sizeof(packageHead);
packageHead.uDataSize = dataLength;
packageHead.uDataPackageNum = packetNum;
unsigned char frameBuffer[1024];
memset(frameBuffer,0,1024);
QUdpSocket *udp = new QUdpSocket;
while (currentPacketIndex < packetNum) {
int udpMaxSizeTemp = UDP_MAX_SIZE;
if (currentPacketIndex >= (packetNum-1)) {
udpMaxSizeTemp = dataLength-currentPacketIndex*UDP_MAX_SIZE;
}
packageHead.uTransPackageSize = sizeof(PackageHeader)+
udpMaxSizeTemp;
packageHead.uDataPackageCurrIndex = currentPacketIndex+1;
packageHead.uDataPackageOffset = currentPacketIndex*UDP_MAX_SIZE;
memcpy(frameBuffer, &packageHead, sizeof(PackageHeader));
memcpy(frameBuffer+sizeof(PackageHeader),
dataBuffer+packageHead.uDataPackageOffset,
udpMaxSizeTemp);
QByteArray byteArray =
QByteArray((const char*)frameBuffer, packageHead.uTransPackageSize);
//////////
QByteArray bytes; //字节数组
//QDataStream类是将序列化的二进制数据送到io设备,因为其属性为只写
QDataStream out(&bytes, QIODevice::WriteOnly);//out为待发送
int msgType = CM_tScreen1;
out << msgType << byteArray;
// out << getCurrentCursorPos();
////////////
// 压缩level0-9,默认为-1,我也不知道-1啥意思
QByteArray compressedBytes = qCompress(bytes);
// 返回发送成功的bytes大小
int sentSuccessfullyBytesSize =
udp->writeDatagram(
compressedBytes.data(),
compressedBytes.size(),
QHostAddress::Broadcast,
PORT);
// 这个关闭必须有,否则传输会出现问题
udp->close();
// 如果发送成功的bytes大小不等于压缩后的大小,说明发送失败
if(sentSuccessfullyBytesSize != compressedBytes.size()) {
qDebug()<<"Failed to send image";
}
currentPacketIndex++;
}
//分包结束+++++++++++++++++++++++++++
}
img1 = img2;
sendCursorInfo();
}
sender->sendCommand(CM_tOpenScreen);
}
void ScreenSharing::sendCursorInfo()
{
sender->sendCursorInfo(CM_tCursorPos, getCurrentScreenSize(), cursorType, getCurrentCursorPos());
}
/**
* 获取当前屏幕分辨率
*/
QSize ScreenSharing::getCurrentScreenSize()
{
QDesktopWidget *desktop = QApplication::desktop();
QRect screen = desktop->screenGeometry();
int screenWidth = screen.width();
int screenHeight = screen.height();
QSize currentScreenSize;
currentScreenSize.setWidth(screenWidth);
currentScreenSize.setHeight(screenHeight);
return currentScreenSize;
}
/**
* 获得当前鼠标在整个屏幕中的坐标
*/
QPoint ScreenSharing::getCurrentCursorPos()
{
QCoreApplication::processEvents();
QPoint globalCursorPos = QCursor::pos();
int mouseScreen = QApplication::desktop()->screenNumber(globalCursorPos);
QRect mouseScreenGeometry = QApplication::desktop()->screen(mouseScreen)->geometry();
QPoint currentCursorPos = globalCursorPos - mouseScreenGeometry.topLeft();
return currentCursorPos;
}
void ScreenSharing::pause()
{
flag = 0;
}
void ScreenSharing::goOn()
{
readSettings();
flag = 1;
mutex->unlock();
}
void ScreenSharing::down()
{
flag = 2;
mutex->unlock();
}
| 32.225806 | 148 | 0.542987 | CrankZ |
d12db1b8334448197c74b2e31a0fef8b48169f77 | 3,297 | cpp | C++ | src/Server.cpp | sempr-tk/sempr_ros | 55f12bddc2d0d461d9fb0799a85d630e07012c4b | [
"BSD-3-Clause"
] | null | null | null | src/Server.cpp | sempr-tk/sempr_ros | 55f12bddc2d0d461d9fb0799a85d630e07012c4b | [
"BSD-3-Clause"
] | null | null | null | src/Server.cpp | sempr-tk/sempr_ros | 55f12bddc2d0d461d9fb0799a85d630e07012c4b | [
"BSD-3-Clause"
] | null | null | null | #include <sempr/nodes/ECNodeBuilder.hpp>
#include <sempr/component/TextComponent.hpp>
#include <sempr/component/TripleContainer.hpp>
#include <sempr/component/TripleVector.hpp>
#include <sempr/component/TriplePropertyMap.hpp>
#include <sempr/component/AffineTransform.hpp>
#include <sempr/component/GeosGeometry.hpp>
#include <sempr/SeparateFileStorage.hpp>
#include <sempr/Core.hpp>
#include <sempr-gui/DirectConnectionBuilder.hpp>
#include "ROSConnectionServer.hpp"
#include <ros/ros.h>
using namespace sempr;
using namespace sempr::gui;
int main(int argc, char** args)
{
::ros::init(argc, args, "sempr_server");
// Create a "sempr_data" directory in the working dir if it does not
// already exist. This is the place where everything will be stored in.
// TODO: Make this a configuration option/parameter.
//
::ros::NodeHandle nh("~");
std::string dbPath;
nh.param<std::string>("directory", dbPath, "./sempr_data");
if (!fs::exists(dbPath)) fs::create_directory(dbPath);
auto db = std::make_shared<SeparateFileStorage>(dbPath);
// create a sempr-instance
Core sempr(db, db); // use the storage for persistence and id generation
sempr.loadPlugins();
// and load everything that has been persisted previously.
auto savedEntities = db->loadAll();
for (auto& e : savedEntities)
{
sempr.addEntity(e);
}
// Create a mutex to get a lock on when working with sempr.
std::mutex semprMutex;
// create a direct connection implementing the interface for the gui
auto directConnection = std::make_shared<DirectConnection>(&sempr, semprMutex);
// wrap the connection in a ROSConnectionServer to expose it in the network
sempr::ros::ROSConnectionServer connection(directConnection);
// Before the connection fully works we need to insert it into the reasoner.
// Well, also register the node builders we might need.
// TODO: This is tedious, and I probably forgot a whole bunch of builders.
// Maybe a plugin-system to would be cool, to just initialize
// everything that's available on the system?
rete::RuleParser& parser = sempr.parser();
// the next to are used to create a connection between the reasoner and the
// "directConnection" object
parser.registerNodeBuilder<ECNodeBuilder<Component>>();
parser.registerNodeBuilder<DirectConnectionBuilder>(directConnection);
parser.registerNodeBuilder<DirectConnectionTripleBuilder>(directConnection);
// add rules that actually implement the connection into the network
sempr.addRules(
"[connectionEC: EC<Component>(?e ?c) -> DirectConnection(?e ?c)]"
"[connectionTriple: (?s ?p ?o) -> DirectConnectionTriple(?s ?p ?o)]"
);
/*
// add rules that allow you to add new rules as data
sempr.addRules(
"[inferRules: (?a <type> <Rules>), EC<TextComponent>(?a ?c),"
"text:value(?text ?c)"
"->"
"constructRules(?text)]"
"[extractTriples: EC<TripleContainer>(?e ?c) -> ExtractTriples(?c)]"
);
*/
::ros::Rate rate(10);
while (::ros::ok())
{
::ros::spinOnce();
sempr.performInference();
rate.sleep();
}
return 0;
}
| 33.30303 | 83 | 0.672733 | sempr-tk |
d12dcdcf3363f1abcfd99c1d672e582842c059d2 | 311 | cpp | C++ | stl/src/nothrow.cpp | isra-fel/STL | 6ae9a578b4f52193dc523922c943a2214a873577 | [
"Apache-2.0"
] | 8,232 | 2019-09-16T22:51:24.000Z | 2022-03-31T03:55:39.000Z | stl/src/nothrow.cpp | isra-fel/STL | 6ae9a578b4f52193dc523922c943a2214a873577 | [
"Apache-2.0"
] | 2,263 | 2019-09-17T05:19:55.000Z | 2022-03-31T21:05:47.000Z | stl/src/nothrow.cpp | isra-fel/STL | 6ae9a578b4f52193dc523922c943a2214a873577 | [
"Apache-2.0"
] | 1,276 | 2019-09-16T22:51:40.000Z | 2022-03-31T03:30:05.000Z | // Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// define nothrow object
#ifdef CRTDLL2
#undef CRTDLL2
#endif
#ifdef MRTDLL
#undef MRTDLL
#endif
#include <new>
_STD_BEGIN
const nothrow_t nothrow = nothrow_t(); // define nothrow
_STD_END
| 16.368421 | 59 | 0.713826 | isra-fel |
d12f2665d4e92753df196e57c7058703da1c4a9f | 2,477 | cpp | C++ | DRCHEF.cpp | ankiiitraj/questionsSolved | 8452b120935a9c3d808b45f27dcdc05700d902fc | [
"MIT"
] | null | null | null | DRCHEF.cpp | ankiiitraj/questionsSolved | 8452b120935a9c3d808b45f27dcdc05700d902fc | [
"MIT"
] | 1 | 2020-02-24T19:45:57.000Z | 2020-02-24T19:45:57.000Z | DRCHEF.cpp | ankiiitraj/questionsSolved | 8452b120935a9c3d808b45f27dcdc05700d902fc | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
int main()
{
#ifndef ONLINE_JUDGE
freopen("ip.txt", "r", stdin);
freopen("op.txt", "w", stdout);
#endif
int t;
scanf("%d", &t);
for(int test = 0; test < t; ++test)
{
long long n, x, temp;
scanf("%lld%lld", &n, &x);
multiset<long long> s;
for(int itr = 0; itr < n; ++itr)
{
scanf("%lld", &temp);
s.insert(temp);
}
long long cnt = 0;
while(!s.empty()){
// if(cnt > 10)
// break;
auto itr = (s.lower_bound(x));
cnt++;
if(x < *s.begin()){
long long cur = *s.rbegin();
s.erase(s.find(*s.rbegin()));
if((cur - x)*2 > 0)
s.insert(min((cur - x)*2, cur));
x *= 2;
// debug(x, s, '1');
continue;
}
if(itr == s.end()){
itr = s.lower_bound(*s.rbegin());
}else if(*itr != x and itr != s.begin()){
--itr;
}
auto new_itr = s.find(*itr);
temp = *new_itr;
temp = min(max(0LL, (*new_itr - x)*2), temp);
if(x > min(x, *new_itr)*2 and x < *s.rbegin()){
long long cur = *s.rbegin();
s.erase(s.find(*s.rbegin()));
if((cur - x)*2 > 0)
s.insert(min(cur, (cur - x)*2));
x *= 2;
// debug(x, s, '2');
continue;
}
x = min(x, *new_itr)*2;
if(temp != *new_itr){
if(temp != 0)
s.insert(temp);
s.erase(new_itr);
}
// debug(x, s, '3');
}
cout << cnt << endl;
}
} | 24.524752 | 118 | 0.520791 | ankiiitraj |
d131fd6621072f48196c39832098e8eb8011b366 | 113 | cpp | C++ | demo/main.cpp | Nolnocn/Bayesian-Inference | 76ee29171c6e3a4a69b752c1f68ae3fef2526f92 | [
"MIT"
] | 1 | 2021-07-07T02:45:55.000Z | 2021-07-07T02:45:55.000Z | demo/main.cpp | Nolnocn/Bayes-Classifier | 76ee29171c6e3a4a69b752c1f68ae3fef2526f92 | [
"MIT"
] | null | null | null | demo/main.cpp | Nolnocn/Bayes-Classifier | 76ee29171c6e3a4a69b752c1f68ae3fef2526f92 | [
"MIT"
] | null | null | null |
#include "GolfDemo.hpp"
int main( int argc, const char* argv[] )
{
GolfDemo gd;
gd.init();
return 0;
}
| 10.272727 | 40 | 0.60177 | Nolnocn |
d13267976bba1f88a5cf0d2d93181d4877051c04 | 1,334 | cpp | C++ | introduction_examples/main.cpp | baykamsay/cs-201 | e8e2083748643a2bd4eed313ebb73c652d525a50 | [
"MIT"
] | null | null | null | introduction_examples/main.cpp | baykamsay/cs-201 | e8e2083748643a2bd4eed313ebb73c652d525a50 | [
"MIT"
] | null | null | null | introduction_examples/main.cpp | baykamsay/cs-201 | e8e2083748643a2bd4eed313ebb73c652d525a50 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
#include "GradeBook.h" // include definition of class GradeBook
void averageForMultipleSetsOfGrades(GradeBook G){
int cnt;
double avg;
char answer;
cnt = 1;
do{
avg = G.determineCourseAverage();
cout << "\nAverage of course " << cnt++ << " is " << avg << endl << endl;
do{
cout << "Do you want to continue (y or n)?";
cin >> answer;
} while ((answer != 'y') && (answer != 'n') && (answer != 'Y') && (answer != 'N'));
cout << endl << endl;
} while ((answer == 'y') || (answer == 'Y'));
}
// function main begins program execution
int main(){
int no;
GradeBook gb1(101);
GradeBook gb2(201);
cout << endl;
gb1.displayMessage();
cout << "Please enter the new course no: ";
cin >> no;
gb1.setCourseNo(no);
gb1.displayMessage();
cout << endl;
gb2.displayMessage();
cout << endl << endl;
cout << "Course average is " << gb2.determineCourseAverage() << endl << endl;
cout << "Course average is " << gb2.determineCourseAverage(5) << endl << endl;
cout << "Course average is " << gb2.determineCourseAverageWithValidation(5) << endl << endl;
averageForMultipleSetsOfGrades(gb1);
gb1.findLetterGradeDistribution();
gb1.displayLetterGradeReport();
cout << endl;
gb1.findGradeDistribution();
gb1.displayLetterGradeReport();
cout << endl;
return 0;
}
| 24.254545 | 93 | 0.646177 | baykamsay |
d134d5a6294862e54fcc64dcba2e7c16bde8c9dc | 1,289 | hpp | C++ | cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/lognormal_rng.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/lognormal_rng.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/lognormal_rng.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_PRIM_SCAL_PROB_LOGNORMAL_RNG_HPP
#define STAN_MATH_PRIM_SCAL_PROB_LOGNORMAL_RNG_HPP
#include <boost/random/lognormal_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
namespace stan {
namespace math {
template <class RNG>
inline double
lognormal_rng(double mu,
double sigma,
RNG& rng) {
using boost::variate_generator;
using boost::random::lognormal_distribution;
static const char* function("lognormal_rng");
check_finite(function, "Location parameter", mu);
check_positive_finite(function, "Scale parameter", sigma);
variate_generator<RNG&, lognormal_distribution<> >
lognorm_rng(rng, lognormal_distribution<>(mu, sigma));
return lognorm_rng();
}
}
}
#endif
| 32.225 | 64 | 0.73623 | yizhang-cae |
d135a6ff9d3f6c6ec2db5836170015563bfaf28c | 1,297 | hpp | C++ | libadb/include/libadb/api/interactions/data/interaction-data-command-option.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | 1 | 2022-03-10T15:14:13.000Z | 2022-03-10T15:14:13.000Z | libadb/include/libadb/api/interactions/data/interaction-data-command-option.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | 9 | 2022-03-07T21:00:08.000Z | 2022-03-15T23:14:52.000Z | libadb/include/libadb/api/interactions/data/interaction-data-command-option.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <variant>
#include <optional>
#include <cstdint>
#include <vector>
#include <libadb/libadb.hpp>
#include <nlohmann/json_fwd.hpp>
#include <libadb/api/interactions/data/application-command-option-type.hpp>
namespace adb::api
{
/**
* @brief Application Command Interaction Data Option
* @details https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-interaction-data-option-structure
*/
struct InteractionDataCommandOption
{
/// the name of the parameter
std::string name;
/// value of application command option type
ApplicationCommandOptionType type;
/// the value of the option resulting from user input
std::optional<std::variant<int64_t, double, std::string>> value;
/// present if this option is a group or subcommand
std::optional<std::vector<InteractionDataCommandOption>> options;
/// true if this option is the currently focused option for autocomplete
std::optional<bool> focused;
};
LIBADB_API void to_json(nlohmann::json& j, const InteractionDataCommandOption& option);
LIBADB_API void from_json(const nlohmann::json& j, InteractionDataCommandOption& option);
} | 38.147059 | 166 | 0.720123 | faserg1 |
d136cd8109bd2a87c64d24ed66563d217d0f15e5 | 23,064 | cpp | C++ | libraries/eosiolib/tester/tester.cpp | James-Mart/Eden | 0ccc405a94575c5044f6ecfdfbcf65a28ed00f90 | [
"MIT"
] | null | null | null | libraries/eosiolib/tester/tester.cpp | James-Mart/Eden | 0ccc405a94575c5044f6ecfdfbcf65a28ed00f90 | [
"MIT"
] | null | null | null | libraries/eosiolib/tester/tester.cpp | James-Mart/Eden | 0ccc405a94575c5044f6ecfdfbcf65a28ed00f90 | [
"MIT"
] | null | null | null | #include <eosio/abi.hpp>
#include <eosio/from_string.hpp>
#include <eosio/tester.hpp>
namespace
{
using cb_alloc_type = void* (*)(void* cb_alloc_data, size_t size);
extern "C"
{
// clang-format off
[[clang::import_name("tester_create_chain2")]] uint32_t tester_create_chain2(const char* snapshot, uint32_t snapshot_size, uint64_t state_size);
[[clang::import_name("tester_destroy_chain")]] void tester_destroy_chain(uint32_t chain);
[[clang::import_name("tester_exec_deferred")]] bool tester_exec_deferred(uint32_t chain_index, void* cb_alloc_data, cb_alloc_type cb_alloc);
[[clang::import_name("tester_execute")]] int32_t tester_execute(const char* command, uint32_t command_size);
[[clang::import_name("tester_finish_block")]] void tester_finish_block(uint32_t chain_index);
[[clang::import_name("tester_get_chain_path")]] uint32_t tester_get_chain_path(uint32_t chain, char* dest, uint32_t dest_size);
[[clang::import_name("tester_get_head_block_info")]] void tester_get_head_block_info(uint32_t chain_index, void* cb_alloc_data, cb_alloc_type cb_alloc);
[[clang::import_name("tester_push_transaction")]] void tester_push_transaction(uint32_t chain_index, const char* args_packed, uint32_t args_packed_size, void* cb_alloc_data, cb_alloc_type cb_alloc);
[[clang::import_name("tester_read_whole_file")]] bool tester_read_whole_file(const char* filename, uint32_t filename_size, void* cb_alloc_data, cb_alloc_type cb_alloc);
[[clang::import_name("tester_replace_account_keys")]] void tester_replace_account_keys(uint32_t chain_index, uint64_t account, uint64_t permission, const char* key, uint32_t key_size);
[[clang::import_name("tester_replace_producer_keys")]] void tester_replace_producer_keys(uint32_t chain_index, const char* key, uint32_t key_size);
[[clang::import_name("tester_select_chain_for_db")]] void tester_select_chain_for_db(uint32_t chain_index);
[[clang::import_name("tester_shutdown_chain")]] void tester_shutdown_chain(uint32_t chain);
[[clang::import_name("tester_sign")]] uint32_t tester_sign(const void* key, uint32_t keylen, const void* digest, void* sig, uint32_t siglen);
[[clang::import_name("tester_start_block")]] void tester_start_block(uint32_t chain_index, int64_t skip_miliseconds);
[[clang::import_name("tester_get_history")]] uint32_t tester_get_history(uint32_t chain_index, uint32_t block_num, char* dest, uint32_t dest_size);
// clang-format on
}
template <typename Alloc_fn>
inline bool read_whole_file(const char* filename_begin,
uint32_t filename_size,
Alloc_fn alloc_fn)
{
return tester_read_whole_file(filename_begin, filename_size, &alloc_fn,
[](void* cb_alloc_data, size_t size) -> void* { //
return (*reinterpret_cast<Alloc_fn*>(cb_alloc_data))(size);
});
}
template <typename Alloc_fn>
inline void get_head_block_info(uint32_t chain, Alloc_fn alloc_fn)
{
tester_get_head_block_info(chain, &alloc_fn,
[](void* cb_alloc_data, size_t size) -> void* { //
return (*reinterpret_cast<Alloc_fn*>(cb_alloc_data))(size);
});
}
template <typename Alloc_fn>
inline void push_transaction(uint32_t chain,
const char* args_begin,
uint32_t args_size,
Alloc_fn alloc_fn)
{
tester_push_transaction(chain, args_begin, args_size, &alloc_fn,
[](void* cb_alloc_data, size_t size) -> void* { //
return (*reinterpret_cast<Alloc_fn*>(cb_alloc_data))(size);
});
}
template <typename Alloc_fn>
inline bool exec_deferred(uint32_t chain, Alloc_fn alloc_fn)
{
return tester_exec_deferred(chain, &alloc_fn,
[](void* cb_alloc_data, size_t size) -> void* { //
return (*reinterpret_cast<Alloc_fn*>(cb_alloc_data))(size);
});
}
} // namespace
std::vector<char> eosio::read_whole_file(std::string_view filename)
{
std::vector<char> result;
if (!::read_whole_file(filename.data(), filename.size(), [&](size_t size) {
result.resize(size);
return result.data();
}))
check(false, "read " + std::string(filename) + " failed");
return result;
}
int32_t eosio::execute(std::string_view command)
{
return ::tester_execute(command.data(), command.size());
}
eosio::asset eosio::string_to_asset(const char* s)
{
return eosio::convert_from_string<asset>(s);
}
namespace
{
// TODO: move
struct tester_permission_level_weight
{
eosio::permission_level permission = {};
uint16_t weight = {};
};
EOSIO_REFLECT(tester_permission_level_weight, permission, weight);
// TODO: move
struct tester_wait_weight
{
uint32_t wait_sec = {};
uint16_t weight = {};
};
EOSIO_REFLECT(tester_wait_weight, wait_sec, weight);
// TODO: move
struct tester_authority
{
uint32_t threshold = {};
std::vector<eosio::key_weight> keys = {};
std::vector<tester_permission_level_weight> accounts = {};
std::vector<tester_wait_weight> waits = {};
};
EOSIO_REFLECT(tester_authority, threshold, keys, accounts, waits);
} // namespace
/**
* Validates the status of a transaction. If expected_except is nullptr, then the
* transaction should succeed. Otherwise it represents a string which should be
* part of the error message.
*/
void eosio::expect(const transaction_trace& tt, const char* expected_except)
{
if (expected_except)
{
if (tt.status == transaction_status::executed)
eosio::check(false, "transaction succeeded, but was expected to fail with: " +
std::string(expected_except));
if (!tt.except)
eosio::check(false, "transaction has no failure message. expected: " +
std::string(expected_except));
if (tt.except->find(expected_except) == std::string::npos)
eosio::check(false, "transaction failed with <<<" + *tt.except +
">>>, but was expected to fail with: <<<" + expected_except +
">>>");
}
else
{
if (tt.status == transaction_status::executed)
return;
if (tt.except)
eosio::print("transaction has exception: ", *tt.except, "\n");
eosio::check(false, "transaction failed with status " + to_string(tt.status));
}
}
eosio::signature eosio::sign(const eosio::private_key& key, const eosio::checksum256& digest)
{
auto raw_digest = digest.extract_as_byte_array();
auto raw_key = eosio::convert_to_bin(key);
constexpr uint32_t buffer_size = 80;
std::vector<char> buffer(buffer_size);
unsigned sz = ::tester_sign(raw_key.data(), raw_key.size(), raw_digest.data(), buffer.data(),
buffer.size());
buffer.resize(sz);
if (sz > buffer_size)
{
::tester_sign(raw_key.data(), raw_key.size(), raw_digest.data(), buffer.data(),
buffer.size());
}
return eosio::convert_from_bin<eosio::signature>(buffer);
}
void eosio::internal_use_do_not_use::hex(const uint8_t* begin, const uint8_t* end, std::ostream& os)
{
std::ostreambuf_iterator<char> dest(os.rdbuf());
auto nibble = [&dest](uint8_t i) {
if (i <= 9)
*dest++ = '0' + i;
else
*dest++ = 'A' + i - 10;
};
while (begin != end)
{
nibble(((uint8_t)*begin) >> 4);
nibble(((uint8_t)*begin) & 0xf);
++begin;
}
}
std::ostream& eosio::operator<<(std::ostream& os, const block_timestamp& obj)
{
return os << obj.slot;
}
std::ostream& eosio::operator<<(std::ostream& os, const name& obj)
{
return os << obj.to_string();
}
std::ostream& eosio::operator<<(std::ostream& os, const asset& obj)
{
return os << obj.to_string();
}
const eosio::public_key eosio::test_chain::default_pub_key =
public_key_from_string("EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV");
const eosio::private_key eosio::test_chain::default_priv_key =
private_key_from_string("5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3");
// We only allow one chain to exist at a time in the tester.
// If we ever find that we need multiple chains, this will
// need to be kept in sync with whatever updates the native layer.
static eosio::test_chain* current_chain = nullptr;
eosio::test_chain::test_chain(const char* snapshot, uint64_t state_size)
: id{::tester_create_chain2(snapshot ? snapshot : "",
snapshot ? strlen(snapshot) : 0,
state_size)}
{
current_chain = this;
}
eosio::test_chain::~test_chain()
{
current_chain = nullptr;
::tester_destroy_chain(id);
}
void eosio::test_chain::shutdown()
{
::tester_shutdown_chain(id);
}
std::string eosio::test_chain::get_path()
{
size_t len = tester_get_chain_path(id, nullptr, 0);
std::string result(len, 0);
tester_get_chain_path(id, result.data(), len);
return result;
}
void eosio::test_chain::replace_producer_keys(const eosio::public_key& key)
{
std::vector<char> packed = pack(key);
::tester_replace_producer_keys(id, packed.data(), packed.size());
}
void eosio::test_chain::replace_account_keys(name account,
name permission,
const eosio::public_key& key)
{
std::vector<char> packed = pack(key);
::tester_replace_account_keys(id, account.value, permission.value, packed.data(), packed.size());
}
void eosio::test_chain::replace_account_keys(name account, const eosio::public_key& key)
{
std::vector<char> packed = pack(key);
::tester_replace_account_keys(id, account.value, "owner"_n.value, packed.data(), packed.size());
::tester_replace_account_keys(id, account.value, "active"_n.value, packed.data(), packed.size());
}
void eosio::test_chain::start_block(int64_t skip_miliseconds)
{
head_block_info.reset();
if (skip_miliseconds >= 500)
{
// Guarantee that there is a recent block for fill_tapos to use.
::tester_start_block(id, skip_miliseconds - 500);
::tester_start_block(id, 0);
}
else
{
::tester_start_block(id, skip_miliseconds);
}
}
void eosio::test_chain::start_block(std::string_view time)
{
uint64_t value;
check(string_to_utc_microseconds(value, time.data(), time.data() + time.size()), "bad time");
start_block(time_point{microseconds(value)});
}
void eosio::test_chain::start_block(time_point tp)
{
finish_block();
auto head_tp = get_head_block_info().timestamp.to_time_point();
auto skip = (tp - head_tp).count() / 1000 - 500;
start_block(skip);
}
void eosio::test_chain::finish_block()
{
head_block_info.reset();
::tester_finish_block(id);
}
const eosio::block_info& eosio::test_chain::get_head_block_info()
{
if (!head_block_info)
{
std::vector<char> bin;
::get_head_block_info(id, [&](size_t size) {
bin.resize(size);
return bin.data();
});
head_block_info = convert_from_bin<block_info>(bin);
}
return *head_block_info;
}
void eosio::test_chain::fill_tapos(transaction& t, uint32_t expire_sec)
{
auto& info = get_head_block_info();
t.expiration = time_point_sec(info.timestamp) + expire_sec;
t.ref_block_num = info.block_num;
memcpy(&t.ref_block_prefix, info.block_id.extract_as_byte_array().data() + 8,
sizeof(t.ref_block_prefix));
}
eosio::transaction eosio::test_chain::make_transaction(std::vector<action>&& actions,
std::vector<action>&& cfa)
{
transaction t{time_point_sec{}};
fill_tapos(t);
t.actions = std::move(actions);
t.context_free_actions = std::move(cfa);
return t;
}
[[nodiscard]] eosio::transaction_trace eosio::test_chain::push_transaction(
const transaction& trx,
const std::vector<private_key>& keys,
const std::vector<std::vector<char>>& context_free_data,
const std::vector<signature>& signatures)
{
std::vector<char> packed_trx = pack(trx);
std::vector<char> args;
(void)convert_to_bin(packed_trx, args);
(void)convert_to_bin(context_free_data, args);
(void)convert_to_bin(signatures, args);
(void)convert_to_bin(keys, args);
std::vector<char> bin;
::push_transaction(id, args.data(), args.size(), [&](size_t size) {
bin.resize(size);
return bin.data();
});
return convert_from_bin<transaction_trace>(bin);
}
eosio::transaction_trace eosio::test_chain::transact(std::vector<action>&& actions,
const std::vector<private_key>& keys,
const char* expected_except)
{
auto trace = push_transaction(make_transaction(std::move(actions)), keys);
expect(trace, expected_except);
return trace;
}
eosio::transaction_trace eosio::test_chain::transact(std::vector<action>&& actions,
const char* expected_except)
{
return transact(std::move(actions), {default_priv_key}, expected_except);
}
[[nodiscard]] std::optional<eosio::transaction_trace> eosio::test_chain::exec_deferred()
{
std::vector<char> bin;
if (!::exec_deferred(id, [&](size_t size) {
bin.resize(size);
return bin.data();
}))
return {};
return convert_from_bin<transaction_trace>(bin);
}
void build_history_result(eosio::test_chain::get_history_result& history_result,
eosio::ship_protocol::get_blocks_result_v0& blocks_result)
{
history_result.result = blocks_result;
if (blocks_result.block)
{
history_result.block.emplace();
(void)from_bin(*history_result.block, *blocks_result.block);
}
if (blocks_result.traces)
{
(void)from_bin(history_result.traces, *blocks_result.traces);
}
if (blocks_result.deltas)
{
(void)from_bin(history_result.deltas, *blocks_result.deltas);
}
}
#if 0
void build_history_result(eosio::test_chain::get_history_result& history_result,
eosio::ship_protocol::get_blocks_result_v1& blocks_result)
{
history_result.result = blocks_result;
if (blocks_result.block)
{
history_result.block = std::move(*blocks_result.block);
}
if (!blocks_result.traces.empty())
{
blocks_result.traces.unpack(history_result.traces);
}
if (blocks_result.deltas.empty())
{
blocks_result.deltas.unpack(history_result.deltas);
}
}
#endif
template <typename T>
void build_history_result(eosio::test_chain::get_history_result&, const T&)
{
eosio::check(false, "test_chain::get_history: unexpected result type");
}
std::optional<eosio::test_chain::get_history_result> eosio::test_chain::get_history(
uint32_t block_num)
{
std::optional<get_history_result> ret;
auto size = ::tester_get_history(id, block_num, nullptr, 0);
if (!size)
return ret;
ret.emplace();
ret->memory.resize(size);
::tester_get_history(id, block_num, ret->memory.data(), size);
ship_protocol::result r;
(void)convert_from_bin(r, ret->memory);
std::visit([&ret](auto& v) { build_history_result(*ret, v); }, r);
return ret;
}
eosio::transaction_trace eosio::test_chain::create_account(name ac,
const public_key& pub_key,
const char* expected_except)
{
tester_authority simple_auth{
.threshold = 1,
.keys = {{pub_key, 1}},
};
return transact({action{{{"eosio"_n, "active"_n}},
"eosio"_n,
"newaccount"_n,
std::make_tuple("eosio"_n, ac, simple_auth, simple_auth)}},
expected_except);
}
eosio::transaction_trace eosio::test_chain::create_account(name ac, const char* expected_except)
{
return create_account(ac, default_pub_key, expected_except);
}
eosio::transaction_trace eosio::test_chain::create_code_account(name account,
const public_key& pub_key,
bool is_priv,
const char* expected_except)
{
tester_authority simple_auth{
.threshold = 1,
.keys = {{pub_key, 1}},
};
tester_authority code_auth{
.threshold = 1,
.keys = {{pub_key, 1}},
.accounts = {{{account, "eosio.code"_n}, 1}},
};
return transact(
{
action{{{"eosio"_n, "active"_n}},
"eosio"_n,
"newaccount"_n,
std::make_tuple("eosio"_n, account, simple_auth, code_auth)},
action{{{"eosio"_n, "active"_n}},
"eosio"_n,
"setpriv"_n,
std::make_tuple(account, is_priv)},
},
expected_except);
}
eosio::transaction_trace eosio::test_chain::create_code_account(name ac,
const public_key& pub_key,
const char* expected_except)
{
return create_code_account(ac, pub_key, false, expected_except);
}
eosio::transaction_trace eosio::test_chain::create_code_account(name ac,
bool is_priv,
const char* expected_except)
{
return create_code_account(ac, default_pub_key, is_priv, expected_except);
}
eosio::transaction_trace eosio::test_chain::create_code_account(name ac,
const char* expected_except)
{
return create_code_account(ac, default_pub_key, false, expected_except);
}
eosio::transaction_trace eosio::test_chain::set_code(name ac,
const char* filename,
const char* expected_except)
{
return transact({action{{{ac, "active"_n}},
"eosio"_n,
"setcode"_n,
std::make_tuple(ac, uint8_t{0}, uint8_t{0}, read_whole_file(filename))}},
expected_except);
}
eosio::transaction_trace eosio::test_chain::set_abi(name ac,
const char* filename,
const char* expected_except)
{
auto json = read_whole_file(filename);
json.push_back(0);
json_token_stream stream(json.data());
abi_def def{};
from_json(def, stream);
auto bin = convert_to_bin(def);
return transact(
{action{{{ac, "active"_n}}, "eosio"_n, "setabi"_n, std::make_tuple(ac, std::move(bin))}},
expected_except);
}
eosio::transaction_trace eosio::test_chain::create_token(name contract,
name signer,
name issuer,
asset maxsupply,
const char* expected_except)
{
return transact(
{action{{{signer, "active"_n}}, contract, "create"_n, std::make_tuple(issuer, maxsupply)}},
expected_except);
}
eosio::transaction_trace eosio::test_chain::issue(const name& contract,
const name& issuer,
const asset& amount,
const char* expected_except)
{
return transact({action{{{issuer, "active"_n}},
contract,
"issue"_n,
std::make_tuple(issuer, amount, std::string{"issuing"})}},
expected_except);
}
eosio::transaction_trace eosio::test_chain::transfer(const name& contract,
const name& from,
const name& to,
const asset& amount,
const std::string& memo,
const char* expected_except)
{
return transact(
{action{
{{from, "active"_n}}, contract, "transfer"_n, std::make_tuple(from, to, amount, memo)}},
expected_except);
}
eosio::transaction_trace eosio::test_chain::issue_and_transfer(const name& contract,
const name& issuer,
const name& to,
const asset& amount,
const std::string& memo,
const char* expected_except)
{
return transact(
{
action{{{issuer, "active"_n}},
contract,
"issue"_n,
std::make_tuple(issuer, amount, std::string{"issuing"})},
action{{{issuer, "active"_n}},
contract,
"transfer"_n,
std::make_tuple(issuer, to, amount, memo)},
},
expected_except);
}
std::ostream& eosio::ship_protocol::operator<<(std::ostream& os,
eosio::ship_protocol::transaction_status t)
{
return os << to_string(t);
}
std::ostream& eosio::ship_protocol::operator<<(
std::ostream& os,
const eosio::ship_protocol::account_auth_sequence& aas)
{
return os << eosio::convert_to_json(aas);
}
std::ostream& eosio::ship_protocol::operator<<(std::ostream& os,
const eosio::ship_protocol::account_delta& ad)
{
return os << eosio::convert_to_json(ad);
}
extern "C"
{
void send_inline(char* serialized_action, size_t size)
{
eosio::check(current_chain != nullptr, "Cannot send an action without a blockchain");
current_chain->transact({eosio::unpack<eosio::action>(serialized_action, size)});
}
}
| 37.260097 | 219 | 0.588319 | James-Mart |
d13c8b1eb83ddcfc22baa0d4fe0557ae6afd97bf | 986 | cpp | C++ | matrizes/c.cpp | RuthMaria/algoritmo | ec9ebf629598dd75a05e33861706f1a6bc956cd5 | [
"MIT"
] | null | null | null | matrizes/c.cpp | RuthMaria/algoritmo | ec9ebf629598dd75a05e33861706f1a6bc956cd5 | [
"MIT"
] | null | null | null | matrizes/c.cpp | RuthMaria/algoritmo | ec9ebf629598dd75a05e33861706f1a6bc956cd5 | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<conio.h>
main(){
float mat[3][3];
int lin, col, maior = 0, menor = 999, plinha = 0, pcol = 0, plinha1 = 0, pcol1 = 0;
maior = mat[0][0];
for(lin = 0; lin < 3; lin++){
printf("\n");
for(col = 0; col < 3; col++){
printf("Linha %d e coluna %d: ", lin, col);
scanf("%f", &mat[lin][col]);
if (mat[lin][col] > maior){
maior = mat[lin][col];
plinha1 = lin;
pcol1 = col;
}
if(mat[lin][col] < menor){
menor = mat[lin][col];
plinha = lin;
pcol = col;
}
}
}
printf("\n Maior numero:%d, esta na linha:%d e coluna:%d", maior, plinha1, pcol1);
printf("\n Menor numero:%d, esta na linha:%d e coluna:%d", menor, plinha, pcol);
getch();
}
| 29 | 90 | 0.389452 | RuthMaria |
d13f5c6bc6b6719d6f59776a2b84b64e053ddbd9 | 452 | hpp | C++ | vm/os-solaris-x86.64.hpp | erg/factor | 134e416b132a1c4f95b0ae15ab2f9a42893b6b6f | [
"BSD-2-Clause"
] | null | null | null | vm/os-solaris-x86.64.hpp | erg/factor | 134e416b132a1c4f95b0ae15ab2f9a42893b6b6f | [
"BSD-2-Clause"
] | null | null | null | vm/os-solaris-x86.64.hpp | erg/factor | 134e416b132a1c4f95b0ae15ab2f9a42893b6b6f | [
"BSD-2-Clause"
] | null | null | null | #include <ucontext.h>
namespace factor
{
#define UAP_STACK_POINTER(ucontext) (((ucontext_t *)ucontext)->uc_mcontext.gregs[RSP])
#define UAP_PROGRAM_COUNTER(ucontext) (((ucontext_t *)ucontext)->uc_mcontext.gregs[RIP])
#define UAP_SET_TOC_POINTER(uap, ptr) (void)0
#define CODE_TO_FUNCTION_POINTER(code) (void)0
#define CODE_TO_FUNCTION_POINTER_CALLBACK(vm, code) (void)0
#define FUNCTION_CODE_POINTER(ptr) ptr
#define FUNCTION_TOC_POINTER(ptr) ptr
}
| 30.133333 | 88 | 0.794248 | erg |
d141213cb5a0dacb18be219f9b0eadb3e0853b6b | 2,027 | cpp | C++ | core/base/Request.cpp | forrestsong/fpay_demo | 7b254a1389b011c799497ad7d08bb8d8d349e557 | [
"MIT"
] | 1 | 2018-08-12T15:08:49.000Z | 2018-08-12T15:08:49.000Z | core/base/Request.cpp | forrestsong/fpay_demo | 7b254a1389b011c799497ad7d08bb8d8d349e557 | [
"MIT"
] | null | null | null | core/base/Request.cpp | forrestsong/fpay_demo | 7b254a1389b011c799497ad7d08bb8d8d349e557 | [
"MIT"
] | null | null | null | #include <iostream>
#include "Request.h"
using namespace std;
Request::Request()
: up(NULL, 0)
, cmd(NULL)
, parser(NULL)
, cpBuffer(NULL)
, od(NULL)
, os(0)
, protoType(PROTO_NONE)
{
}
Request::Request(const char *data, uint32_t sz, PROTO_T proto)
: up(data, sz)
, cmd(NULL)
, parser(NULL)
, cpBuffer(NULL)
, od(data)
, os(sz)
, protoType(proto)
{
}
Request::Request(const char *data, uint32_t sz, bool copy, PROTO_T proto)
: up(data, sz)
, cmd(NULL)
, parser(NULL)
, cpBuffer(NULL)
, od(data)
, os(sz)
, protoType(proto)
{
if (copy) {
cpBuffer = new char[sz];
memcpy(cpBuffer, data, sz);
up.reset(cpBuffer, sz);
od = cpBuffer;
}
}
#define PROTO_MAGIC_SHIFT 29
#define PROTO_MAGIC_MASK ~(111 << PROTO_MAGIC_SHIFT)
PROTO_T Request::getProtoType(uint32_t len, uint32_t& realLength)
{
uint32_t top3Bit = len >> PROTO_MAGIC_SHIFT;
PROTO_T proto = PROTO_MAX;
switch (top3Bit) {
case PROTO_JSON:
proto = PROTO_JSON;
break;
case PROTO_BIN:
proto = PROTO_BIN;
break;
case PROTO_HTTP:
proto = PROTO_HTTP;
break;
default:
break;
}
realLength = len & PROTO_MAGIC_MASK;
return proto;
}
void Request::popHeader()
{
switch (protoType)
{
case PROTO_BIN:
{
len = up.readUint32();
uri = up.readUint32();
appId = up.readUint16();
}
break;
case PROTO_HTTP:
break;
default:
break;
}
}
Request::~Request()
{
if (parser && cmd) {
parser->destroyForm(cmd);
}
if (cpBuffer != NULL) {
delete[] cpBuffer;
}
}
void Request::setFormHandler(IFormHandle *h)
{
parser = h;
cmd = parser->handlePacket(up);
}
void Request::leftPack(std::string &out)
{
out.assign(up.data(), up.size());
}
| 18.768519 | 73 | 0.537247 | forrestsong |
d144ee97976a4a83d249fb0857560284f9305e0f | 2,015 | cpp | C++ | source/code/programs/system/default_applications/main.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 33 | 2019-05-30T07:43:32.000Z | 2021-12-30T13:12:32.000Z | source/code/programs/system/default_applications/main.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 371 | 2019-05-16T15:23:50.000Z | 2021-09-04T15:45:27.000Z | source/code/programs/system/default_applications/main.cpp | UniLang/compiler | c338ee92994600af801033a37dfb2f1a0c9ca897 | [
"MIT"
] | 6 | 2019-08-22T17:37:36.000Z | 2020-11-07T07:15:32.000Z | #include <iostream>
#include "code/utilities/system/mime/mime_xml_creator.hpp"
#include "code/utilities/system/mime/mime_xml_creation_settings.hpp"
#include "code/utilities/filesystem/paths/lib.hpp"
#include "code/utilities/filesystem/files/creating/lib.hpp"
void Create_Mime_Xml(){
//create mime xml
Mime_Xml_Creation_Settings settings;
settings.mime_type = "application/unilang";
settings.comment = "unilang file";
settings.file_extension = "unilang";
auto xml_contents = Mime_Xml_Creator::Create(settings);
//std::string location = ".local/share/mime/packages/";
//std::string location = "/usr/share/mime/application/";
std::string location = "/usr/share/mime/packages/";
std::string xml_name = "application-unilang.xml";
//auto file_name = Full_Path_To_Home_File(location + xml_name);
auto file_name = location + xml_name;
Create_File_Even_If_The_Path_Doesnt_Exist(file_name);
Write_To_File(file_name,xml_contents);
//execute("update-mime-database ~/.local/share/mime");
//std::cout << execute("sudo update-mime-database /usr/share/mime") << std::endl;
}
void Create_Desktop_File(){
//create desktop file
std::string x;
x += "[Desktop Entry]\n";
x += "Name=Unilang\n";
x += "Exec=gedit\n";
x += "MimeType=application/unilang\n";
x += "Terminal=false\n";
x += "Type=Application\n";
auto file_name = Full_Path_To_Home_File(".local/share/applications/unilang.desktop");
Create_File_Even_If_The_Path_Doesnt_Exist(file_name);
Write_To_File(file_name,x);
execute("update-desktop-database ~/.local/share/applications");
}
int main(){
//https://askubuntu.com/questions/747467/create-new-filetype-with-existing-extension
//https://askubuntu.com/questions/1144302/update-mime-database-deletes-xml-mime-file
//https://github.com/freedesktop/xdg-shared-mime-info/blob/master/src/update-mime-database.c
Create_Mime_Xml();
Create_Desktop_File();
} | 34.741379 | 96 | 0.706203 | luxe |
d14c6abb008fe02142c74237630e9626edcdea4b | 3,960 | cpp | C++ | src/Nokia5110.cpp | intoyuniot/Nokia5110 | 7d240b17aab230b661a8054ed998a256bbd608ca | [
"MIT"
] | null | null | null | src/Nokia5110.cpp | intoyuniot/Nokia5110 | 7d240b17aab230b661a8054ed998a256bbd608ca | [
"MIT"
] | null | null | null | src/Nokia5110.cpp | intoyuniot/Nokia5110 | 7d240b17aab230b661a8054ed998a256bbd608ca | [
"MIT"
] | null | null | null | /*
Adapted for IntoRobot by Robin, Sept 19, 2015
7-17-2011
Spark Fun Electronics 2011
Nathan Seidle
Modified on 03-12-2014 by ionpan
This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).
*/
#include "Nokia5110.h"
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
Nokia5110::Nokia5110(uint8_t _SCE, uint8_t _RESET, uint8_t _DC, uint8_t _SDIN, uint8_t _SCLK)
{
SCE = _SCE;
RESET = _RESET;
DC = _DC;
SDIN = _SDIN;
SCLK = _SCLK;
// configure control pins
pinMode(SCE, OUTPUT);
pinMode(RESET, OUTPUT);
pinMode(DC, OUTPUT);
pinMode(SDIN, OUTPUT);
pinMode(SCLK, OUTPUT);
// set default display values
COLS = 84;
ROWS = 48;
mode = 0x0C; // set to normal
contrast = 0xBC;
}
void Nokia5110::setContrast(uint16_t _contrast)
{
contrast = _contrast;
}
void Nokia5110::setDimensions(int _COLS, int _ROWS)
{
COLS = _COLS;
ROWS = _ROWS;
}
void Nokia5110::invert()
{
if (mode == 0x0C)
{
mode = 0x0D; // change to inverted
}
else if (mode == 0x0D)
{
mode = 0x0C; // change to normal
}
}
void Nokia5110::gotoXY(int _x, int _y)
{
write(0, 0x80 | _x); // column.
write(0, 0x40 | _y); // row. ?
}
// this takes a large array of bits and sends them to the LCD
void Nokia5110::bitmap(char _bitmapArray[])
{
for (int index = 0; index < (COLS * ROWS / 8); index++)
{
write(LCD_DATA, _bitmapArray[index]);
}
}
void Nokia5110::progBitmap(char const _bitmapArray[])
{
for (int index = 0; index < (COLS * ROWS / 8); index++)
{
write(LCD_DATA, pgm_read_byte(& _bitmapArray[index]));
}
}
// This function takes in a character, looks it up in the font table/array
// And writes it to the screen
// Each character is 8 bits tall and 5 bits wide. We pad one blank column of
// pixels on the right side of the character for readability.
void Nokia5110::character(char _character)
{
//LCDWrite(LCD_DATA, 0x00); // blank vertical line padding before character
for (int index = 0; index < 5 ; index++)
{
write(LCD_DATA, pgm_read_byte(&(ASCII[_character - 0x20][index])));
}
//0x20 is the ASCII character for Space (' '). The font table starts with this character
write(LCD_DATA, 0x00); // blank vertical line padding after character
}
// given a string of characters, one by one is passed to the LCD
void Nokia5110::string(char* _characters)
{
while (*_characters)
{
character(*_characters++);
}
}
// clears the LCD by writing zeros to the entire screen
void Nokia5110::clear(void)
{
for (int index = 0; index < (COLS * ROWS / 8); index++)
{
write(LCD_DATA, 0x00);
}
gotoXY(0, 0); // after we clear the display, return to the home position
}
// this sends the magical commands to the PCD8544
void Nokia5110::init(void)
{
// reset the LCD to a known state
digitalWrite(RESET, LOW);
digitalWrite(RESET, HIGH);
write(LCD_COMMAND, 0x21); // tell LCD that extended commands follow
write(LCD_COMMAND, contrast); // set LCD Vop (Contrast): Try 0xB1(good @ 3.3V) or 0xBF if your display is too dark
write(LCD_COMMAND, 0x04); // set Temp coefficent
write(LCD_COMMAND, 0x14); // LCD bias mode 1:48: Try 0x13 or 0x14
write(LCD_COMMAND, 0x20); // we must send 0x20 before modifying the display control mode
write(LCD_COMMAND, mode); // set display control, normal mode. 0x0D for inverse
}
// There are two memory banks in the LCD, data/RAM and commands. This
// function sets the DC pin high or low depending, and then sends
// the data byte
void Nokia5110::write(byte _data_or_command, byte _data)
{
digitalWrite(DC, _data_or_command); // tell the LCD that we are writing either to data or a command
// send the data
digitalWrite(SCE, LOW);
shiftOut(SDIN, SCLK, MSBFIRST, _data);
digitalWrite(SCE, HIGH);
}
| 26.577181 | 118 | 0.658838 | intoyuniot |
d14e08539a79b0f552345691eadb120ea7a6e513 | 52 | hpp | C++ | include/common/firmware/can_task.hpp | sotaoverride/ot3-firmwarre-sota | 0b1d52589c94635da47063468293608f0ed36e32 | [
"Apache-2.0"
] | null | null | null | include/common/firmware/can_task.hpp | sotaoverride/ot3-firmwarre-sota | 0b1d52589c94635da47063468293608f0ed36e32 | [
"Apache-2.0"
] | null | null | null | include/common/firmware/can_task.hpp | sotaoverride/ot3-firmwarre-sota | 0b1d52589c94635da47063468293608f0ed36e32 | [
"Apache-2.0"
] | null | null | null | #pragma once
namespace can_task {
void start();
} | 7.428571 | 20 | 0.692308 | sotaoverride |
d152e81423b8065f9304559d0862c3b60e4a6cee | 7,696 | cpp | C++ | src/abs.cpp | ivision-ufba/depth-face-detection | f70441eb9e72fa3f509458ffc202648c2f3e27d1 | [
"MIT"
] | 15 | 2017-11-01T11:39:32.000Z | 2021-04-02T02:42:59.000Z | src/abs.cpp | ivision-ufba/depth-face-detection | f70441eb9e72fa3f509458ffc202648c2f3e27d1 | [
"MIT"
] | 6 | 2017-07-26T17:55:27.000Z | 2020-11-15T22:04:35.000Z | src/abs.cpp | ivision-ufba/depth-face-detection | f70441eb9e72fa3f509458ffc202648c2f3e27d1 | [
"MIT"
] | 5 | 2018-05-09T13:42:17.000Z | 2020-01-17T06:22:59.000Z | #include <abs.hpp>
#include <cassert>
#include <exception>
#include <fstream>
#include <iostream>
#include <queue>
#include <sstream>
Abs::Abs(const std::string& s) { load(s); }
void Abs::crop(const cv::Rect& roi) {
const int rows = valid.rows;
const int cols = valid.cols;
for (int r = 0; r < rows; ++r)
for (int c = 0; c < cols; ++c) {
cv::Point p(r, c);
if (!roi.contains(p)) valid.at<uchar>(r, c) = false;
}
}
void Abs::crop(const cv::Point3d& center, double dist) {
const int rows = valid.rows;
const int cols = valid.cols;
dist *= dist;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (valid.at<uchar>(i, j) &&
pow(center.x - depth.at<cv::Vec3d>(i, j)[0], 2.0) +
pow(center.y - depth.at<cv::Vec3d>(i, j)[1], 2.0) >
dist)
valid.at<uchar>(i, j) = false;
}
int Abs::read_int(const std::string& str) {
std::stringstream ss;
ss << str;
int num;
ss >> num;
return num;
}
std::vector<cv::Point3d> Abs::to_points() const {
std::vector<cv::Point3d> points;
const int rows = valid.rows;
const int cols = valid.cols;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (valid.at<uchar>(i, j) - '0')
points.emplace_back(depth.at<cv::Vec3d>(i, j));
return points;
}
cv::Mat Abs::to_mat() const {
cv::Mat depth_img(valid.rows, valid.cols, CV_32F);
for (int i = 0; i < valid.rows; i++)
for (int j = 0; j < valid.cols; j++)
if (valid.at<uchar>(i, j) - '0')
depth_img.at<float>(i, j) = depth.at<cv::Vec3d>(i, j)[2];
else
depth_img.at<float>(i, j) = 0;
return depth_img;
}
std::vector<cv::Point2d> Abs::to_pixels() const {
std::vector<cv::Point2d> pixels;
const int rows = valid.rows;
const int cols = valid.cols;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (valid.at<uchar>(i, j) - '0') pixels.emplace_back(i, j);
return pixels;
}
void Abs::print_registered_pcloud(const cv::Mat& img) const {
const int rows = valid.rows;
const int cols = valid.cols;
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
if (valid.at<uchar>(i, j))
printf("v %.4lf %.4lf %.4lf %u %u %u\n", depth.at<cv::Vec3d>(i, j)[0],
depth.at<cv::Vec3d>(i, j)[1], depth.at<cv::Vec3d>(i, j)[2],
(unsigned int)img.at<cv::Vec3b>(i, j)[0],
(unsigned int)img.at<cv::Vec3b>(i, j)[1],
(unsigned int)img.at<cv::Vec3b>(i, j)[2]);
}
void Abs::load(const std::string& filename) {
std::ifstream f(filename);
if (!f) throw std::runtime_error("Unable to open image file.");
// read the headers
std::string l1, l2, l3;
std::getline(f, l1);
std::getline(f, l2);
std::getline(f, l3);
const int rows = read_int(l1);
const int cols = read_int(l2);
// create matrices
depth.create(rows, cols, CV_64FC3);
valid.create(rows, cols, CV_8U);
// read the contents
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) f >> valid.at<uchar>(i, j);
// read x coordinates
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) f >> depth.at<cv::Vec3d>(i, j)[0];
// read y coordinates
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) f >> depth.at<cv::Vec3d>(i, j)[1];
// read z coordinates
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) f >> depth.at<cv::Vec3d>(i, j)[2];
}
cv::Point3d Abs::at(const int i, const int j) const {
if (valid.at<uchar>(i, j) == '0') return cv::Point3d(0, 0, 0);
return cv::Point3d(depth.at<cv::Vec3d>(i, j));
}
cv::Point3d Abs::at(const cv::Point p) const {
if (valid.at<uchar>(p) == '0') return cv::Point3d(0, 0, 0);
return cv::Point3d(depth.at<cv::Vec3d>(p));
}
cv::Point3d Abs::closest_point_to(const int i, const int j) const {
// check input boundaries
if (i < 0 || i >= valid.rows || j < 0 || j >= valid.cols)
throw std::runtime_error("Out of boundaries");
// prepare breadth first search
cv::Mat mask(valid.size(), CV_8U);
mask.setTo(0);
std::queue<int> qi, qj;
qi.push(i);
qj.push(j);
mask.at<uchar>(i, j) = 1;
// breadth first search
while (!qi.empty()) {
const int i = qi.front();
const int j = qj.front();
qi.pop();
qj.pop();
if (valid.at<uchar>(i, j) == '1') return at(i, j);
const std::vector<int> i_neighbor = {1, -1, 0, 0};
const std::vector<int> j_neighbor = {0, 0, 1, -1};
for (int k = 0; k < 4; k++) {
const int next_i = i + i_neighbor[k];
const int next_j = j + j_neighbor[k];
if (next_i >= 0 && next_i < mask.rows && next_j >= 0 &&
next_j < mask.cols && !mask.at<uchar>(next_i, next_j)) {
qi.push(next_i);
qj.push(next_j);
mask.at<uchar>(next_i, next_j) = 1;
}
}
}
throw std::runtime_error("No valid point in entire abs");
}
AbsCalibration::AbsCalibration(const Abs& abs) : abs(abs) {
const std::vector<cv::Point3d> points = abs.to_points();
const std::vector<cv::Point2d> pixels = abs.to_pixels();
// compute mean
mean = cv::Point3d(0, 0, 0);
for (cv::Point3d point : points) mean += point;
mean /= static_cast<double>(points.size());
assert(pixels.size() == points.size());
const int max_points = points.size();
cv::Mat X(max_points * 2, 11, CV_64F), Y(max_points * 2, 1, CV_64F);
int n = 0;
for (int i = 0, len = points.size(); i < len; i++, n += 2) {
Y.at<double>(n, 0) = pixels[i].x;
Y.at<double>(n + 1, 0) = pixels[i].y;
X.at<double>(n, 0) = (points[i].x - mean.x);
X.at<double>(n, 1) = (points[i].y - mean.y);
X.at<double>(n, 2) = (points[i].z - mean.z);
X.at<double>(n, 3) = 1.0;
X.at<double>(n, 4) = 0.0;
X.at<double>(n, 5) = 0.0;
X.at<double>(n, 6) = 0.0;
X.at<double>(n, 7) = 0.0;
X.at<double>(n, 8) = -pixels[i].x * (points[i].x - mean.x);
X.at<double>(n, 9) = -pixels[i].x * (points[i].y - mean.y);
X.at<double>(n, 10) = -pixels[i].x * (points[i].z - mean.z);
X.at<double>(n + 1, 0) = 0.0;
X.at<double>(n + 1, 1) = 0.0;
X.at<double>(n + 1, 2) = 0.0;
X.at<double>(n + 1, 3) = 0.0;
X.at<double>(n + 1, 4) = (points[i].x - mean.x);
X.at<double>(n + 1, 5) = (points[i].y - mean.y);
X.at<double>(n + 1, 6) = (points[i].z - mean.z);
X.at<double>(n + 1, 7) = 1.0;
X.at<double>(n + 1, 8) = -pixels[i].y * (points[i].x - mean.x);
X.at<double>(n + 1, 9) = -pixels[i].y * (points[i].y - mean.y);
X.at<double>(n + 1, 10) = -pixels[i].y * (points[i].z - mean.z);
}
cv::Mat tmp_c = (X.t() * X).inv(cv::DECOMP_LU) * X.t() * Y;
cmatrix.create(3, 4, CV_64F);
for (int i = 0; i < 11; i++)
cmatrix.at<double>(i / 4, i % 4) = tmp_c.at<double>(i, 0);
cmatrix.at<double>(2, 3) = 1.0;
}
cv::Point3d AbsCalibration::depth_to_xyz(const float x, const float y,
const float z) const {
return abs.at(y, x);
}
cv::Point AbsCalibration::xyz_to_depth(const cv::Point3d& p) const {
cv::Point2d ret;
const double q = (p.x - mean.x) * cmatrix.at<double>(2, 0) +
(p.y - mean.y) * cmatrix.at<double>(2, 1) +
(p.z - mean.z) * cmatrix.at<double>(2, 2) +
cmatrix.at<double>(2, 3);
ret.y =
((p.x - mean.x) * cmatrix.at<double>(0, 0) +
(p.y - mean.y) * cmatrix.at<double>(0, 1) +
(p.z - mean.z) * cmatrix.at<double>(0, 2) + cmatrix.at<double>(0, 3)) /
q;
ret.x =
((p.x - mean.x) * cmatrix.at<double>(1, 0) +
(p.y - mean.y) * cmatrix.at<double>(1, 1) +
(p.z - mean.z) * cmatrix.at<double>(1, 2) + cmatrix.at<double>(1, 3)) /
q;
return ret;
}
| 29.829457 | 78 | 0.539891 | ivision-ufba |
d1550f620897a8c18990eeb4ef5a67cab4c5ac81 | 916 | cpp | C++ | LightOJ/1021 - Painful Bases - 1381065.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 5 | 2020-10-03T17:15:26.000Z | 2022-03-29T21:39:22.000Z | LightOJ/1021 - Painful Bases - 1381065.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | null | null | null | LightOJ/1021 - Painful Bases - 1381065.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 1 | 2021-03-01T12:56:50.000Z | 2021-03-01T12:56:50.000Z | #include <bits/stdc++.h>
using namespace std;
#define ll long long
ll k, len, dp[1 << 16][25], base;
char num[20];
ll solve(ll msk, ll rem, ll pos)
{
if(pos == len)
return rem == 0;
ll &ret = dp[msk][rem];
if(ret != -1)
return ret;
ret = 0;
for(ll i = 0; i < len; i++) {
ll n;
if(isalpha(num[i]))
n = num[i] - 'A' + 10;
else
n = num[i] - '0';
if( (msk >> n) & 1)
continue;
ret += solve(msk | (1 << n), (n + rem * base) % k, pos + 1);
}
return ret;
}
int main()
{
//freopen("out.txt", "w", stdout);
ll t, cs = 0;
cin >> t;
while(t--) {
memset(dp, -1, sizeof(dp));
scanf("%lld %lld", &base, &k);
scanf("%s", num);
len = strlen(num);
ll ans = solve(0, 0, 0);
printf("Case %lld: %lld\n", ++cs, ans);
}
return 0;
}
| 21.809524 | 70 | 0.417031 | Shefin-CSE16 |
d155800c646bf56d38af4204b087d19e71754b2c | 1,562 | cpp | C++ | URI/DateDiference.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 1 | 2018-08-28T19:58:40.000Z | 2018-08-28T19:58:40.000Z | URI/DateDiference.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 2 | 2017-04-16T00:48:05.000Z | 2017-08-03T20:12:26.000Z | URI/DateDiference.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 4 | 2016-03-04T19:42:00.000Z | 2018-01-08T11:42:00.000Z | #include <bits/stdc++.h>
template<typename T> T gcd(T a, T b) {
if(!b) return a;
return gcd(b, a % b);
}
template<typename T> T lcm(T a, T b) {
return a * b / gcd(a, b);
}
template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; }
template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; }
int in() { int x; scanf("%d", &x); return x; }
using namespace std;
typedef long long Int;
typedef unsigned uint;
int T;
int sy, sm, sd, ey, em, ed;
int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int dp[35][15][3000];
int leap(int y) {
return (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0);
}
int main(void) {
scanf("%d", &T);
dp[1][1][1970] = 0;
int py = 1970;
int pm = 1;
int pd = 1;
for (int y = 1970; y <= 2014; y++) {
for (int m = 1; m <= 12; m++) {
int day_cnt = days[m];
if (m == 2 && leap(y)) {
day_cnt += 1;
}
for (int d = 1; d <= day_cnt; d++) {
dp[d][m][y] = 1 + dp[pd][pm][py];
py = y;
pm = m;
pd = d;
}
}
}
for ( ; T--; ) {
scanf("%d-%d-%d %d-%d-%d", &ey, &em, &ed, &sy, &sm, &sd);
if (ey < sy || (ey == sy && em < sm) || (ey == sy && em == sm && ed < sd)) {
swap(ey, sy);
swap(em, sm);
swap(ed, sd);
}
int ans = dp[ed][em][ey] - dp[sd][sm][sy];
printf("%d\n", ans);
}
return 0;
}
| 22 | 84 | 0.390525 | aajjbb |
d157d11278b4ad5d4f6eb2aaae0550febace4500 | 1,523 | cpp | C++ | sim/src/esp/sim_main.cpp | mincrmatt12/MSign | 745bd04bc2b38952f5b35cf81f5924bd8f00452e | [
"MIT"
] | 5 | 2019-11-04T17:01:46.000Z | 2020-06-18T07:07:34.000Z | sim/src/esp/sim_main.cpp | mincrmatt12/SignCode | 745bd04bc2b38952f5b35cf81f5924bd8f00452e | [
"MIT"
] | null | null | null | sim/src/esp/sim_main.cpp | mincrmatt12/SignCode | 745bd04bc2b38952f5b35cf81f5924bd8f00452e | [
"MIT"
] | 2 | 2020-06-18T07:07:37.000Z | 2020-10-14T04:41:12.000Z | #include "esp_log.h"
#include <FreeRTOS.h>
#include <stdarg.h>
#include <cstdio>
#include <lwip/netif.h>
#include <task.h>
#include <lwip/init.h>
#include <lwip/tcpip.h>
#include <netif/tapif.h>
#include <lwip/dns.h>
extern "C" void app_main();
void main_start_task(void*) {
app_main();
vTaskDelete(nullptr);
}
extern "C" void vAssertCalled(const char* m, int l) {
ESP_LOGE("assert", "file %s line %d", m, l);
while (1) {}
}
extern "C" void lwip_assert_called(const char *msg) {
ESP_LOGE("lwip", "%s", msg);
while (1) {}
}
extern "C" void lwip_dbg_message(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
struct netif netif;
void finished(void *) {
// DO LWIP NETIF INIT
ip4_addr_t ipaddr, netmask, gw;
const char *ipaddr_str = getenv("SIMESP_IP");
const char *netmask_str = getenv("SIMESP_NETMASK");
const char *gw_str = getenv("SIMESP_GATEWAY");
if (!ipaddr_str || !netmask_str || !gw_str) {
perror("missing ip cfg in env");
}
if (!ip4addr_aton(ipaddr_str, &ipaddr) ||
!ip4addr_aton(netmask_str, &netmask) ||
!ip4addr_aton(gw_str, &gw)) {
perror("invalid ip addr");
}
netif_add(&netif, &ipaddr, &netmask, &gw, NULL, tapif_init, tcpip_input);
netif_set_up(&netif);
netif_set_default(&netif);
ip4_addr_t dns;
IP4_ADDR(&dns, 1, 1, 1, 1);
dns_setserver(0, &dns);
}
int main() {
tcpip_init(finished, NULL);
xTaskCreate(main_start_task, "uiT", 1024, nullptr, 10, nullptr);
vTaskStartScheduler();
}
| 21.757143 | 75 | 0.667761 | mincrmatt12 |
d15c86e8033277075351b291b6c52fe66dbf6480 | 1,055 | cpp | C++ | src/myBox.cpp | Lalaland/PixelPacker | aad646e6ab6beeb9804fcc0ea3b4f70443ffb98e | [
"BSD-2-Clause-FreeBSD"
] | 18 | 2016-05-30T16:52:25.000Z | 2022-01-07T19:09:34.000Z | src/myBox.cpp | Lalaland/PixelPacker | aad646e6ab6beeb9804fcc0ea3b4f70443ffb98e | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2017-01-09T19:06:48.000Z | 2017-01-09T19:06:48.000Z | src/myBox.cpp | Lalaland/PixelPacker | aad646e6ab6beeb9804fcc0ea3b4f70443ffb98e | [
"BSD-2-Clause-FreeBSD"
] | 5 | 2015-03-17T02:24:14.000Z | 2022-01-07T19:09:54.000Z | /*
-------------------------------------------------------------------------
This file is part of PixelPacker, tools to pack textures into as small as space as possible.
PixelPacker version 1 of 6 March 2011
Copyright (C) 2011 Ethan Steinberg <ethan.steinberg@gmail.com>
This program is released under the terms of the license contained
in the file COPYING.
---------------------------------------------------------------------------
*/
#include "myBox.h"
#include <utility>
using namespace std::rel_ops;
t_myBox::t_myBox()
{}
t_myBox::t_myBox(int x,int y, int width, int height) : pos(x,y), size(width,height)
{}
t_myBox::t_myBox(t_myVector2 Pos, t_myVector2 Size) : pos(Pos), size(Size)
{}
bool t_myBox::operator==(const t_myBox &box) const
{
return (box.pos == pos) && (box.size == size);
}
bool t_myBox::operator<(const t_myBox &box) const
{
if (box.pos < pos)
{
return 1;
}
else if (box.pos > pos)
{
return 0;
}
else if (box.size < size)
{
return 1;
}
else
{
return 0;
}
}
| 19.181818 | 92 | 0.55545 | Lalaland |
d15e089d8022b44902a2446ab98a9c680fbefa03 | 4,936 | cpp | C++ | external/bsd/atf/dist/atf-sh/atf-sh.cpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | external/bsd/atf/dist/atf-sh/atf-sh.cpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | external/bsd/atf/dist/atf-sh/atf-sh.cpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | //
// Automated Testing Framework (atf)
//
// Copyright (c) 2010 The NetBSD Foundation, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
//
extern "C" {
#include <unistd.h>
}
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include "atf-c++/config.hpp"
#include "atf-c++/detail/application.hpp"
#include "atf-c++/detail/fs.hpp"
#include "atf-c++/detail/sanity.hpp"
// ------------------------------------------------------------------------
// Auxiliary functions.
// ------------------------------------------------------------------------
namespace {
static
std::string
fix_plain_name(const char *filename)
{
const atf::fs::path filepath(filename);
if (filepath.branch_path().str() == ".")
return std::string("./") + filename;
else
return std::string(filename);
}
static
std::string*
construct_script(const char* filename)
{
const std::string libexecdir = atf::config::get("atf_libexecdir");
const std::string pkgdatadir = atf::config::get("atf_pkgdatadir");
const std::string shell = atf::config::get("atf_shell");
std::string* command = new std::string();
command->reserve(512);
(*command) += ("Atf_Check='" + libexecdir + "/atf-check' ; " +
"Atf_Shell='" + shell + "' ; " +
". " + pkgdatadir + "/libatf-sh.subr ; " +
". " + fix_plain_name(filename) + " ; " +
"main \"${@}\"");
return command;
}
static
const char**
construct_argv(const std::string& shell, const int interpreter_argc,
const char* const* interpreter_argv)
{
PRE(interpreter_argc >= 1);
PRE(interpreter_argv[0] != NULL);
const std::string* script = construct_script(interpreter_argv[0]);
const int count = 4 + (interpreter_argc - 1) + 1;
const char** argv = new const char*[count];
argv[0] = shell.c_str();
argv[1] = "-c";
argv[2] = script->c_str();
argv[3] = interpreter_argv[0];
for (int i = 1; i < interpreter_argc; i++)
argv[4 + i - 1] = interpreter_argv[i];
argv[count - 1] = NULL;
return argv;
}
} // anonymous namespace
// ------------------------------------------------------------------------
// The "atf_sh" class.
// ------------------------------------------------------------------------
class atf_sh : public atf::application::app {
static const char* m_description;
public:
atf_sh(void);
int main(void);
};
const char* atf_sh::m_description =
"atf-sh is a shell interpreter that extends the functionality of the "
"system sh(1) with the atf-sh library.";
atf_sh::atf_sh(void) :
app(m_description, "atf-sh(1)")
{
}
int
atf_sh::main(void)
{
if (m_argc < 1)
throw atf::application::usage_error("No test program provided");
const atf::fs::path script(m_argv[0]);
if (!atf::fs::exists(script))
throw std::runtime_error("The test program '" + script.str() + "' "
"does not exist");
const std::string shell = atf::config::get("atf_shell");
const char** argv = construct_argv(shell, m_argc, m_argv);
// Don't bother keeping track of the memory allocated by construct_argv:
// we are going to exec or die immediately.
#if defined(__minix) && !defined(NDEBUG)
const int ret =
#endif /* defined(__minix) && !defined(NDEBUG) */
execv(shell.c_str(), const_cast< char** >(argv));
INV(ret == -1);
std::cerr << "Failed to execute " << shell << ": " << std::strerror(errno)
<< "\n";
return EXIT_FAILURE;
}
int
main(int argc, char* const* argv)
{
return atf_sh().run(argc, argv);
}
| 30.85 | 78 | 0.613452 | calmsacibis995 |
d15eb14f4636021eddb55409fa343def67c8b30f | 8,216 | cpp | C++ | PrcAlpha/ImageExtractor.cpp | maxirmx/PdfImageExtract | d2714476740cb62fb81f549b9e0a94c1511644e2 | [
"MIT"
] | null | null | null | PrcAlpha/ImageExtractor.cpp | maxirmx/PdfImageExtract | d2714476740cb62fb81f549b9e0a94c1511644e2 | [
"MIT"
] | null | null | null | PrcAlpha/ImageExtractor.cpp | maxirmx/PdfImageExtract | d2714476740cb62fb81f549b9e0a94c1511644e2 | [
"MIT"
] | null | null | null | /******************************************************************************
Copyright (C) 2020 Maxim Samsonov
maxim@samsonov.net
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*******************************************************************************/
#include "stdafx.h"
#include "ImageExtractor.h"
#ifdef _MSC_VER
#define snprintf _snprintf_s
#endif
ImageExtractor::ImageExtractor()
: m_sOutputDirectory(), m_sInputFile(), m_nSuccess( 0 ), m_nCount( 0 ), m_sFName()
{
}
ImageExtractor::~ImageExtractor()
{
}
void ImageExtractor::Init(const char* pszInput, const char* pszOutput)
{
if (!pszOutput || !pszInput)
{
PODOFO_RAISE_ERROR(ePdfError_InvalidHandle);
}
m_sOutputDirectory = pszOutput;
m_sInputFile = pszInput;
DWORD dwGFA = GetFileAttributesA(pszOutput);
if (dwGFA == INVALID_FILE_ATTRIBUTES) {
if (!CreateDirectoryA(pszOutput, NULL)) {
cerr << "Error: " << pszOutput << " does not exist and CreateDirectory failed." << endl << endl;
exit(-1);
}
}
else if (!(dwGFA & FILE_ATTRIBUTE_DIRECTORY)) {
cerr << "Error: " << pszOutput << " exists but is not a directory." << endl << endl;
exit(-1);
}
char drive[MAX_PATH];
char dir[MAX_PATH];
char name[MAX_PATH];
char ext[MAX_PATH];
_splitpath_s(m_sInputFile.c_str(), drive, MAX_PATH, dir, MAX_PATH, name, MAX_PATH, ext, MAX_PATH );
m_sFName = name;
}
void ImageExtractor::Extract()
{
PdfMemDocument document(m_sInputFile.c_str());
int nPages = document.GetPageCount();
const string kwdDo("Do");
const PdfName nameXObject("XObject");
for (int i = 0; i < nPages; i++) {
cout << "Page " << setw(6) << (i + 1) << endl << flush;
PdfPage* pPage = document.GetPage(i);
PdfContentsTokenizer tokenizer(pPage);
EPdfContentsType type;
const char * kwText;
PdfVariant var;
bool bReadToken;
PdfObject* pObj;
PdfObject* pObjType; // XoXo
PdfObject* pObjSubType; // XoXo
PdfObject* pFilter; // XoXo
string theLastNameReadable("undefined");
PdfVariant theLastName;
unsigned int nCount = 0;
// --------------------------------------------------------------------------------------------------------------
// https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf
// p. 201 and beyond
// We are looking for <XObject name> /Do sequences
// --------------------------------------------------------------------------------------------------------------
while ((bReadToken = tokenizer.ReadNext(type, kwText, var)))
{
switch (type) {
case ePdfContentsType_Keyword: /* The token is a PDF keyword. */
if (kwdDo == kwText) {
// Debug output cout << "Do (XObject:\"" << setw(6) << theLastNameReadable << "\")" << endl;
pObj = pPage->GetFromResources(nameXObject, theLastName.GetName());
if (pObj && pObj->IsDictionary()) {
// Debug output cout << "Dictionary ...";
pObjType = pObj->GetDictionary().GetKey(PdfName::KeyType);
pObjSubType = pObj->GetDictionary().GetKey(PdfName::KeySubtype);
if ((pObjType && pObjType->IsName() && (pObjType->GetName().GetName() == "XObject")) ||
(pObjSubType && pObjSubType->IsName() && (pObjSubType->GetName().GetName() == "Image")))
{
// Debug output cout << " " << pObjType->GetName().GetName() << " and " << pObjSubType->GetName().GetName() << " ...";
pFilter = pObj->GetDictionary().GetKey(PdfName::KeyFilter);
if (pFilter && pFilter->IsArray() && pFilter->GetArray().GetSize() == 1 && pFilter->GetArray()[0].IsName())
pFilter = &pFilter->GetArray()[0];
string sFilterName = "";
if (pFilter && pFilter->IsName())
sFilterName = pFilter->GetName().GetName();
if (sFilterName == "DCTDecode")
ExtractImage(pObj, false, "jpg", i, nCount++);
else if (sFilterName == "CCITTFaxDecode")
// https://coderoad.ru/2641770/%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-%D0%B8%D0%B7%D0%BE%D0%B1%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F-%D0%B8%D0%B7-PDF-%D1%81-%D0%BF%D0%BE%D0%BC%D0%BE%D1%89%D1%8C%D1%8E-%D1%84%D0%B8%D0%BB%D1%8C%D1%82%D1%80%D0%B0-CCITTFaxDecode
ExtractImage(pObj, false, "tiff", i, nCount++);
else if (sFilterName == "FlateDecode")
ExtractImage(pObj, false, "ppm", i, nCount++);
else
cout << "* Filter \"" << sFilterName << "\" is not supported" << endl;
document.FreeObjectMemory(pObj);
}
}
}
break;
case ePdfContentsType_Variant: /* The token is a PDF variant. A variant is usually a parameter to a keyword */
// Save the last Name token that can be a parameter for the following Do command
if (var.IsName()) {
theLastName = var;
theLastName.ToString(theLastNameReadable);
// Debug output cout << setw(6) << theLastNameReadable << "\" ... ";
}
break;
case ePdfContentsType_ImageData: /* The "token" is raw inline image data found between ID and EI tags (see PDF ref section 4.8.6) */
cout << "* Raw inline image data is not supported." << endl;
break;
};
}
}
cout << "Done!" << endl << flush;
}
void ImageExtractor::ExtractImage( PdfObject* pObject, bool bDecode, string sExt, unsigned int nPage, unsigned int nCount)
{
ofstream* pFStream = NULL;
try
{
pFStream = OpenFStream(sExt, nPage, nCount);
}
catch (...)
{
PODOFO_RAISE_ERROR( ePdfError_InvalidHandle );
}
if( !bDecode )
{
PdfMemStream* pStream = dynamic_cast<PdfMemStream*>(pObject->GetStream());
pFStream->write(pStream->Get(), pStream->GetLength());
}
else
{
//long lBitsPerComponent = pObject->GetDictionary().GetKey( PdfName("BitsPerComponent" ) )->GetNumber();
// TODO: Handle colorspaces
// Create a ppm image
const char* pszPpmHeader = "P6\n# Image extracted by PoDoFo\n%" PDF_FORMAT_INT64 " %" PDF_FORMAT_INT64 "\n%li\n";
/* fprintf( hFile, pszPpmHeader,
pObject->GetDictionary().GetKey( PdfName("Width" ) )->GetNumber(),
pObject->GetDictionary().GetKey( PdfName("Height" ) )->GetNumber(),
255 );
char* pBuffer;
pdf_long lLen;
pObject->GetStream()->GetFilteredCopy( &pBuffer, &lLen );
fwrite( pBuffer, lLen, sizeof(char), hFile );
free( pBuffer );
*/
}
delete pFStream;
++m_nSuccess;
}
ofstream* ImageExtractor::OpenFStream(string sExt, unsigned int nPage, unsigned int nCount)
{
string sFile;
int nAttempt = 0;
// Do not overwrite existing files:
do {
ostringstream ssFile;
ssFile << m_sOutputDirectory << "/" << m_sFName << "-p-" << setw(3) << setfill('0') << nPage << "-i-" << setw(2) << nCount << "-a-" << setw(3) << nAttempt++ << "." << sExt;
sFile = ssFile.str();
} while (FileExists(sFile.c_str()));
return new ofstream(sFile, ios_base::binary);
}
bool ImageExtractor::FileExists( const char* pszFilename )
{
bool result = true;
// if there is an error, it's probably because the file doesn't yet exist
struct stat stBuf;
if ( stat( pszFilename, &stBuf ) == -1 ) result = false;
return result;
}
| 33.8107 | 283 | 0.615385 | maxirmx |
d1609ecde0285d306a818ae8faf7a136157a2529 | 175 | cpp | C++ | 100000569/B/another.cpp | gongbo2018/codeup_contest | c61cd02f145c764b0eb2728fb2b3405314d522ca | [
"MIT"
] | 1 | 2020-08-14T09:33:51.000Z | 2020-08-14T09:33:51.000Z | 100000569/B/another.cpp | gongbo2018/codeup_contest | c61cd02f145c764b0eb2728fb2b3405314d522ca | [
"MIT"
] | null | null | null | 100000569/B/another.cpp | gongbo2018/codeup_contest | c61cd02f145c764b0eb2728fb2b3405314d522ca | [
"MIT"
] | null | null | null | #include <cstdio>
int main() {
int data[10];
for (int i=0;i<10;i++) {
scanf("%d", &data[i]);
}
for (int j=9; j>=0;j--) {
printf("%d\n", data[j]);
}
return 0;
}
| 10.9375 | 26 | 0.474286 | gongbo2018 |
d163f38fe1ea06fb34d229d3b3c5e5ab722fbd36 | 11,463 | hpp | C++ | include/caffe/loss_layers.hpp | xiaomi646/caffe_2d_mlabel | 912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65 | [
"BSD-2-Clause"
] | 1 | 2015-07-08T15:30:06.000Z | 2015-07-08T15:30:06.000Z | include/caffe/loss_layers.hpp | xiaomi646/caffe_2d_mlabel | 912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65 | [
"BSD-2-Clause"
] | null | null | null | include/caffe/loss_layers.hpp | xiaomi646/caffe_2d_mlabel | 912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2014 BVLC and contributors.
#ifndef CAFFE_LOSS_LAYERS_HPP_
#define CAFFE_LOSS_LAYERS_HPP_
#include <string>
#include <utility>
#include <vector>
#include "leveldb/db.h"
#include "pthread.h"
#include "boost/scoped_ptr.hpp"
#include "hdf5.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layer.hpp"
#include "caffe/neuron_layers.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
const float kLOG_THRESHOLD = 1e-20;
/* LossLayer
Takes two inputs of same num (a and b), and has no output.
The gradient is propagated to a.
*/
template <typename Dtype>
class LossLayer : public Layer<Dtype> {
public:
explicit LossLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top);
virtual void FurtherSetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {}
virtual inline int ExactNumBottomBlobs() const { return 2; }
virtual inline int MaxTopBlobs() const { return 1; }
// We usually cannot backpropagate to the labels; ignore force_backward for
// these inputs.
virtual inline bool AllowForceBackward(const int bottom_index) const {
return bottom_index != 1;
}
};
// Forward declare SoftmaxLayer for use in SoftmaxWithLossLayer.
template <typename Dtype> class SoftmaxLayer;
/* SoftmaxWithLossLayer
Implements softmax and computes the loss.
It is preferred over separate softmax + multinomiallogisticloss
layers due to more numerically stable gradients.
In test, this layer could be replaced by simple softmax layer.
*/
template <typename Dtype>
class SoftmaxWithLossLayer : public Layer<Dtype> {
public:
explicit SoftmaxWithLossLayer(const LayerParameter& param)
: Layer<Dtype>(param), softmax_layer_(new SoftmaxLayer<Dtype>(param)) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_SOFTMAX_LOSS;
}
virtual inline int MaxTopBlobs() const { return 2; }
// We cannot backpropagate to the labels; ignore force_backward for these
// inputs.
virtual inline bool AllowForceBackward(const int bottom_index) const {
return bottom_index != 1;
}
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
shared_ptr<SoftmaxLayer<Dtype> > softmax_layer_;
// prob stores the output probability of the layer.
Blob<Dtype> prob_;
// Vector holders to call the underlying softmax layer forward and backward.
vector<Blob<Dtype>*> softmax_bottom_vec_;
vector<Blob<Dtype>*> softmax_top_vec_;
};
/* SigmoidCrossEntropyLossLayer
*/
template <typename Dtype>
class SigmoidCrossEntropyLossLayer : public LossLayer<Dtype> {
public:
explicit SigmoidCrossEntropyLossLayer(const LayerParameter& param)
: LossLayer<Dtype>(param),
sigmoid_layer_(new SigmoidLayer<Dtype>(param)),
sigmoid_output_(new Blob<Dtype>()) {}
virtual void FurtherSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_SIGMOID_CROSS_ENTROPY_LOSS;
}
virtual inline int MaxTopBlobs() const { return 2; }
// We cannot backpropagate to the labels; ignore force_backward for these
// inputs.
virtual inline bool AllowForceBackward(const int bottom_index) const {
return bottom_index != 1;
}
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
shared_ptr<SigmoidLayer<Dtype> > sigmoid_layer_;
// sigmoid_output stores the output of the sigmoid layer.
shared_ptr<Blob<Dtype> > sigmoid_output_;
// Vector holders to call the underlying sigmoid layer forward and backward.
vector<Blob<Dtype>*> sigmoid_bottom_vec_;
vector<Blob<Dtype>*> sigmoid_top_vec_;
};
/* MultiLabelLossLayer, now it only computes Sigmoid Loss,
but could be extended to use HingeLoss
*/
template <typename Dtype>
class MultiLabelLossLayer : public LossLayer<Dtype> {
public:
explicit MultiLabelLossLayer(const LayerParameter& param)
: LossLayer<Dtype>(param),
sigmoid_layer_(new SigmoidLayer<Dtype>(param)),
sigmoid_output_(new Blob<Dtype>()) {}
virtual void FurtherSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_MULTI_LABEL_LOSS;
}
virtual inline int MaxTopBlobs() const { return 2; }
// We cannot backpropagate to the labels; ignore force_backward for these
// inputs.
virtual inline bool AllowForceBackward(const int bottom_index) const {
return bottom_index != 1;
}
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
shared_ptr<SigmoidLayer<Dtype> > sigmoid_layer_;
// sigmoid_output stores the output of the sigmoid layer.
shared_ptr<Blob<Dtype> > sigmoid_output_;
// Vector holders to call the underlying sigmoid layer forward and backward.
vector<Blob<Dtype>*> sigmoid_bottom_vec_;
vector<Blob<Dtype>*> sigmoid_top_vec_;
};
/* EuclideanLossLayer
Compute the L_2 distance between the two inputs.
loss = (1/2 \sum_i (a_i - b_i)^2)
a' = 1/I (a - b)
*/
template <typename Dtype>
class EuclideanLossLayer : public LossLayer<Dtype> {
public:
explicit EuclideanLossLayer(const LayerParameter& param)
: LossLayer<Dtype>(param), diff_() {}
virtual void FurtherSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_EUCLIDEAN_LOSS;
}
// Unlike most loss layers, in the EuclideanLossLayer we can backpropagate
// to both inputs.
virtual inline bool AllowForceBackward(const int bottom_index) const {
return true;
}
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
Blob<Dtype> diff_;
};
/* InfogainLossLayer
*/
template <typename Dtype>
class InfogainLossLayer : public LossLayer<Dtype> {
public:
explicit InfogainLossLayer(const LayerParameter& param)
: LossLayer<Dtype>(param), infogain_() {}
virtual void FurtherSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_INFOGAIN_LOSS;
}
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
Blob<Dtype> infogain_;
};
/* HingeLossLayer
*/
template <typename Dtype>
class HingeLossLayer : public LossLayer<Dtype> {
public:
explicit HingeLossLayer(const LayerParameter& param)
: LossLayer<Dtype>(param) {}
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_HINGE_LOSS;
}
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
};
/* MultinomialLogisticLossLayer
*/
template <typename Dtype>
class MultinomialLogisticLossLayer : public LossLayer<Dtype> {
public:
explicit MultinomialLogisticLossLayer(const LayerParameter& param)
: LossLayer<Dtype>(param) {}
virtual void FurtherSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_MULTINOMIAL_LOGISTIC_LOSS;
}
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
};
/* AccuracyLayer
Note: not an actual loss layer! Does not implement backwards step.
Computes the accuracy of argmax(a) with respect to b.
*/
template <typename Dtype>
class AccuracyLayer : public Layer<Dtype> {
public:
explicit AccuracyLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_ACCURACY;
}
virtual inline int ExactNumBottomBlobs() const { return 2; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {
NOT_IMPLEMENTED;
}
int top_k_;
};
/* MultiLabelAccuracyLayer
Note: not an actual loss layer! Does not implement backwards step.
Computes the accuracy of a with respect to b.
*/
template <typename Dtype>
class MultiLabelAccuracyLayer : public Layer<Dtype> {
public:
explicit MultiLabelAccuracyLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_MULTI_LABEL_ACCURACY;
}
virtual inline int ExactNumBottomBlobs() const { return 2; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {
NOT_IMPLEMENTED;
}
};
} // namespace caffe
#endif // CAFFE_LOSS_LAYERS_HPP_
| 33.615836 | 78 | 0.730524 | xiaomi646 |
d164bcc51b3bc70b7a3fbab916f75eba623a4f38 | 4,183 | cpp | C++ | MonoNative.Tests/mscorlib/System/Security/Cryptography/mscorlib_System_Security_Cryptography_MACTripleDES_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative.Tests/mscorlib/System/Security/Cryptography/mscorlib_System_Security_Cryptography_MACTripleDES_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative.Tests/mscorlib/System/Security/Cryptography/mscorlib_System_Security_Cryptography_MACTripleDES_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | // Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Security.Cryptography
// Name: MACTripleDES
// C++ Typed Name: mscorlib::System::Security::Cryptography::MACTripleDES
#include <gtest/gtest.h>
#include <mscorlib/System/Security/Cryptography/mscorlib_System_Security_Cryptography_MACTripleDES.h>
#include <mscorlib/System/IO/mscorlib_System_IO_Stream.h>
#include <mscorlib/System/mscorlib_System_Type.h>
namespace mscorlib
{
namespace System
{
namespace Security
{
namespace Cryptography
{
//Constructors Tests
//MACTripleDES()
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,DefaultConstructor)
{
mscorlib::System::Security::Cryptography::MACTripleDES *value = new mscorlib::System::Security::Cryptography::MACTripleDES();
EXPECT_NE(NULL, value->GetNativeObject());
}
//MACTripleDES(std::vector<mscorlib::System::Byte*> rgbKey)
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,Constructor_2)
{
mscorlib::System::Security::Cryptography::MACTripleDES *value = new mscorlib::System::Security::Cryptography::MACTripleDES();
EXPECT_NE(NULL, value->GetNativeObject());
}
//MACTripleDES(mscorlib::System::String strTripleDES, std::vector<mscorlib::System::Byte*> rgbKey)
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,Constructor_3)
{
mscorlib::System::Security::Cryptography::MACTripleDES *value = new mscorlib::System::Security::Cryptography::MACTripleDES();
EXPECT_NE(NULL, value->GetNativeObject());
}
//Public Methods Tests
// Method Initialize
// Signature:
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,Initialize_Test)
{
}
//Public Properties Tests
// Property Padding
// Return Type: mscorlib::System::Security::Cryptography::PaddingMode::__ENUM__
// Property Get Method
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_Padding_Test)
{
}
// Property Padding
// Return Type: mscorlib::System::Security::Cryptography::PaddingMode::__ENUM__
// Property Set Method
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,set_Padding_Test)
{
}
// Property Key
// Return Type: mscorlib::System::Byte*
// Property Get Method
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_Key_Test)
{
}
// Property Key
// Return Type: mscorlib::System::Byte*
// Property Set Method
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,set_Key_Test)
{
}
// Property CanTransformMultipleBlocks
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_CanTransformMultipleBlocks_Test)
{
}
// Property CanReuseTransform
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_CanReuseTransform_Test)
{
}
// Property Hash
// Return Type: mscorlib::System::Byte*
// Property Get Method
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_Hash_Test)
{
}
// Property HashSize
// Return Type: mscorlib::System::Int32
// Property Get Method
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_HashSize_Test)
{
}
// Property InputBlockSize
// Return Type: mscorlib::System::Int32
// Property Get Method
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_InputBlockSize_Test)
{
}
// Property OutputBlockSize
// Return Type: mscorlib::System::Int32
// Property Get Method
TEST(mscorlib_System_Security_Cryptography_MACTripleDES_Fixture,get_OutputBlockSize_Test)
{
}
}
}
}
}
| 25.662577 | 130 | 0.696629 | brunolauze |
d1694b72f720450f38bfa8b0d5c914f6ce7cc91b | 2,128 | cpp | C++ | python/_nimblephysics/realtime/Ticker.cpp | jyf588/nimblephysics | 6c09228f0abcf7aa3526a8dd65cd2541aff32c4a | [
"BSD-2-Clause"
] | 2 | 2021-09-30T06:23:29.000Z | 2022-03-09T09:59:09.000Z | python/_nimblephysics/realtime/Ticker.cpp | jyf588/nimblephysics | 6c09228f0abcf7aa3526a8dd65cd2541aff32c4a | [
"BSD-2-Clause"
] | null | null | null | python/_nimblephysics/realtime/Ticker.cpp | jyf588/nimblephysics | 6c09228f0abcf7aa3526a8dd65cd2541aff32c4a | [
"BSD-2-Clause"
] | 1 | 2021-08-20T13:56:14.000Z | 2021-08-20T13:56:14.000Z | #include <iostream>
#include <Python.h>
#include <dart/realtime/Ticker.hpp>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
namespace py = pybind11;
namespace dart {
namespace python {
void Ticker(py::module& m)
{
::py::class_<dart::realtime::Ticker, std::shared_ptr<dart::realtime::Ticker>>(
m, "Ticker")
.def(::py::init<s_t>(), ::py::arg("secondsPerTick"))
.def(
"registerTickListener",
+[](dart::realtime::Ticker* self,
std::function<void(long)> callback) -> void {
std::function<void(long now)> wrappedCallback
= [callback](long now) {
/* Acquire GIL before calling Python code */
py::gil_scoped_acquire acquire;
try
{
callback(now);
}
catch (::py::error_already_set& e)
{
if (e.matches(PyExc_KeyboardInterrupt))
{
std::cout
<< "Nimble caught a keyboard interrupt in a "
"callback from registerTickListener(). Exiting "
"with code 0."
<< std::endl;
exit(0);
}
else
{
std::cout << "Nimble caught an exception calling "
"callback from registerTickListener():"
<< std::endl
<< std::string(e.what()) << std::endl;
}
}
};
self->registerTickListener(wrappedCallback);
},
::py::arg("listener"))
.def(
"start",
&dart::realtime::Ticker::start,
::py::call_guard<py::gil_scoped_release>())
.def("stop", &dart::realtime::Ticker::stop)
.def("clear", &dart::realtime::Ticker::clear);
}
} // namespace python
} // namespace dart
| 33.777778 | 80 | 0.43797 | jyf588 |
d16aedd116d8d31f861454b4a121c38b77986f1a | 436 | cpp | C++ | Codeforces/746A - Compote.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/746A - Compote.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/746A - Compote.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("files/input.txt", "r", stdin);
freopen("files/output.txt", "w", stdout);
#endif
int a, b, c;
cin >> a >> b >> c;
int count = 0;
while(a >= 1 && b >= 2 && c >= 4) {
a--;
b -= 2;
c -= 4;
count++;
}
cout << count * 7 << endl;
return 0;
}
| 18.166667 | 45 | 0.465596 | naimulcsx |
d17193eb39ee765dc05b44402f92b8fa8d122f89 | 369 | cpp | C++ | src/zip/ZipFileNotOpenException.cpp | qjclinux/DocxFactory | 91131f28f3324d8fad526c7faa1595203cb9a215 | [
"BSD-3-Clause"
] | 116 | 2016-12-22T18:01:41.000Z | 2022-03-29T15:55:59.000Z | src/zip/ZipFileNotOpenException.cpp | qjclinux/DocxFactory | 91131f28f3324d8fad526c7faa1595203cb9a215 | [
"BSD-3-Clause"
] | 16 | 2017-01-30T15:56:15.000Z | 2021-01-13T06:09:28.000Z | src/zip/ZipFileNotOpenException.cpp | qjclinux/DocxFactory | 91131f28f3324d8fad526c7faa1595203cb9a215 | [
"BSD-3-Clause"
] | 49 | 2017-01-16T07:34:47.000Z | 2022-01-25T15:04:12.000Z |
#include "DocxFactory/zip/ZipFileNotOpenException.h"
using namespace DocxFactory;
using namespace std;
ZipFileNotOpenException::ZipFileNotOpenException(
const string& p_file,
const int p_line ) : ZipException( p_file, p_line )
{
m_what = "Zip file not open. Cannot write.";
} // c'tor
ZipFileNotOpenException::~ZipFileNotOpenException() throw()
{
} // d'tor
| 18.45 | 59 | 0.753388 | qjclinux |
d172df46567e2c2e55e3d573eee798a578f58eb0 | 3,500 | hpp | C++ | sources/include/structure/parameter.hpp | sydelity-net/EDACurry | 20cbf9835827e42efeb0b3686bf6b3e9d72417e9 | [
"MIT"
] | null | null | null | sources/include/structure/parameter.hpp | sydelity-net/EDACurry | 20cbf9835827e42efeb0b3686bf6b3e9d72417e9 | [
"MIT"
] | null | null | null | sources/include/structure/parameter.hpp | sydelity-net/EDACurry | 20cbf9835827e42efeb0b3686bf6b3e9d72417e9 | [
"MIT"
] | null | null | null | /// @file parameter.hpp
/// @author Enrico Fraccaroli (enrico.fraccaroli@gmail.com)
/// @copyright Copyright (c) 2021 sydelity.net (info@sydelity.com)
/// Distributed under the MIT License (MIT) (See accompanying LICENSE file or
/// copy at http://opensource.org/licenses/MIT)
#pragma once
#include "features/object_reference.hpp"
#include "features/named_object.hpp"
#include "features/object_list.hpp"
#include "object.hpp"
#include "enums.hpp"
#include "value.hpp"
namespace edacurry::structure
{
/// @brief Represent a parameter.
class Parameter : public Object, public features::ObjectReference {
public:
/// @brief Construct a new Parameter object.
/// @param left the right value of the parameter.
/// @param right the initial right value of the parameter.
/// @param type the parameter's type.
/// @param reference The reference to another parameter.
/// @param hide_left hide the left-hand side value during code generation.
Parameter(Value *left, Value *right, ParameterType type = param_assign, structure::Object *reference = nullptr, bool hide_left = false);
/// @brief Destroy the Parameter object.
~Parameter() override;
/// @brief Returns the initial value of the parameter.
/// @return The initial value of the parameter.
Value *getRight() const;
/// @brief Sets the initial value of the data parameter.
/// @param value the initial value of the data parameter to be set.
/// @return The old initial value of the data parameter if it is
/// different from the new one, nullptr otherwise.
Value *setRight(Value *value);
/// @brief Returns the initial value of the parameter.
/// @return The initial value of the parameter.
Value *getLeft() const;
/// @brief Sets the initial value of the data parameter.
/// @param value the initial value of the data parameter to be set.
/// @return The old initial value of the data parameter if it is
/// different from the new one, nullptr otherwise.
Value *setLeft(Value *value);
/// @brief Sets the type of parameter.
/// @param type the parameter's type.
inline void setType(ParameterType type)
{
_type = type;
}
/// @brief Returns the type of parameter.
/// @return the type of parameter.
inline auto getType() const
{
return _type;
}
/// @brief Sets if the left-hand side value is hidden during code generation.
/// @param hide_left if the left-hand side value should be hidden.
inline void setHideLeft(bool hide_left)
{
_hide_left = hide_left;
}
/// @brief Sets if the left-hand side value is hidden during code generation.
/// @return if the left-hand side value should be hidden.
inline bool getHideLeft() const
{
return _hide_left;
}
/// @brief Provides a string representation of the object for **debugging** purposes.
/// @return the string representation.
std::string toString() const override;
/// @brief Accepts a visitor.
/// @param visitor the visitor.
inline void accept(features::Visitor *visitor) const override
{
visitor->visit(this);
}
private:
/// The value on the left of the parameter.
Value *_left;
/// The value on the right of the parameter.
Value *_right;
/// The type of parameter.
ParameterType _type;
/// Hide the left-hand side value during code generation.
bool _hide_left;
};
} // namespace edacurry::structure
| 33.980583 | 140 | 0.679714 | sydelity-net |
d172fe293b74f8d01aaa49838823c92e67b55d54 | 12,005 | cxx | C++ | PWG/EMCAL/EMCALbase/AliEmcalTrackSelResultPtr.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 114 | 2017-03-03T09:12:23.000Z | 2022-03-03T20:29:42.000Z | PWG/EMCAL/EMCALbase/AliEmcalTrackSelResultPtr.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 19,637 | 2017-01-16T12:34:41.000Z | 2022-03-31T22:02:40.000Z | PWG/EMCAL/EMCALbase/AliEmcalTrackSelResultPtr.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1,021 | 2016-07-14T22:41:16.000Z | 2022-03-31T05:15:51.000Z | /************************************************************************************
* Copyright (C) 2017, Copyright Holders of the ALICE Collaboration *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* * Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* * Neither the name of the <organization> nor the *
* names of its contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND *
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *
* DISCLAIMED. IN NO EVENT SHALL ALICE COLLABORATION 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 <iostream>
#include <TNamed.h> // for user object
#include <TClass.h>
#include "AliEmcalTrackSelResultPtr.h"
#include "AliVTrack.h"
/// \cond CLASSIMP
ClassImp(PWG::EMCAL::AliEmcalTrackSelResultPtr)
ClassImp(PWG::EMCAL::AliEmcalTrackSelResultUserPtr)
ClassImp(PWG::EMCAL::AliEmcalTrackSelResultUserStorage)
ClassImp(PWG::EMCAL::TestAliEmcalTrackSelResultPtr)
/// \endcond
using namespace PWG::EMCAL;
AliEmcalTrackSelResultPtr::AliEmcalTrackSelResultPtr() :
TObject(),
fTrack(nullptr),
fSelectionResult(false),
fUserInfo()
{
}
AliEmcalTrackSelResultPtr::AliEmcalTrackSelResultPtr(AliVTrack *trk, Bool_t selectionStatus, TObject * userinfo) :
TObject(),
fTrack(trk),
fSelectionResult(selectionStatus),
fUserInfo(userinfo)
{
}
AliEmcalTrackSelResultPtr::AliEmcalTrackSelResultPtr(const AliEmcalTrackSelResultPtr &ref) :
TObject(ref),
fTrack(ref.fTrack),
fSelectionResult(ref.fSelectionResult),
fUserInfo(ref.fUserInfo)
{
}
AliEmcalTrackSelResultPtr::AliEmcalTrackSelResultPtr(AliEmcalTrackSelResultPtr &&ref) :
TObject(ref),
fTrack(ref.fTrack),
fSelectionResult(ref.fSelectionResult),
fUserInfo()
{
ref.fTrack = nullptr;
fUserInfo = std::move(ref.fUserInfo);
}
AliEmcalTrackSelResultPtr &AliEmcalTrackSelResultPtr::operator =(const AliEmcalTrackSelResultPtr &ref){
TObject::operator =(ref);
if(this != &ref){
fTrack = ref.fTrack;
fSelectionResult = ref.fSelectionResult;
fUserInfo = ref.fUserInfo;
}
return *this;
}
AliEmcalTrackSelResultPtr &AliEmcalTrackSelResultPtr::operator =(AliEmcalTrackSelResultPtr &&ref){
TObject::operator =(ref);
if(this != &ref){
fTrack = ref.fTrack;
fSelectionResult = ref.fSelectionResult;
fUserInfo = std::move(ref.fUserInfo);
ref.fTrack = nullptr;
}
return *this;
}
Bool_t AliEmcalTrackSelResultPtr::operator ==(const AliEmcalTrackSelResultPtr &other) const {
return fTrack == other.fTrack;
}
Bool_t AliEmcalTrackSelResultPtr::operator <(const AliEmcalTrackSelResultPtr &other) const {
return fTrack < other.fTrack;
}
Bool_t AliEmcalTrackSelResultPtr::IsEqual(const TObject *o) const {
const AliEmcalTrackSelResultPtr *otherobj = static_cast<const AliEmcalTrackSelResultPtr *>(o);
if(!otherobj) return false;
return *this == *otherobj;
}
Int_t AliEmcalTrackSelResultPtr::Compare(const TObject *o) const {
const AliEmcalTrackSelResultPtr *otherobj = static_cast<const AliEmcalTrackSelResultPtr *>(o);
if(!otherobj) return 1;
if (*this == *otherobj) return 0;
if (*this < *otherobj) return -1;
return 1;
}
AliVTrack *AliEmcalTrackSelResultPtr::operator *() const {
return fTrack;
}
AliVTrack *AliEmcalTrackSelResultPtr::operator ->() const {
return fTrack;
}
void AliEmcalTrackSelResultPtr::PrintStream(std::ostream &stream) const {
stream << "Track selection result for track with address " << fTrack
<< ": Selection status: " << (fSelectionResult ? "true" : "false")
<< ", HasUserInfo: " << (fUserInfo.GetData() ? "Yes" : "No");
}
std::ostream &PWG::EMCAL::operator<<(std::ostream &stream, const PWG::EMCAL::AliEmcalTrackSelResultPtr &o){
o.PrintStream(stream);
return stream;
}
/*************************************************************
* *
* Content of class AliEmcalTrackSelResultUserStorage *
* *
*************************************************************/
AliEmcalTrackSelResultUserStorage::AliEmcalTrackSelResultUserStorage():
TObject(),
fData(nullptr),
fReferenceCount(0)
{
}
AliEmcalTrackSelResultUserStorage::AliEmcalTrackSelResultUserStorage(TObject *data):
TObject(),
fData(data),
fReferenceCount(1)
{
}
AliEmcalTrackSelResultUserStorage::~AliEmcalTrackSelResultUserStorage(){
//std::cout << "Destructing user storage with reference count 0" << std::endl;
if(fData) delete fData;
}
void AliEmcalTrackSelResultUserStorage::Connect() {
fReferenceCount++;
}
void AliEmcalTrackSelResultUserStorage::Release(){
fReferenceCount--;
if(!fReferenceCount) delete this;
}
/*************************************************************
* *
* Content of class AliEmcalTrackSelResultUserPtr *
* *
*************************************************************/
AliEmcalTrackSelResultUserPtr::AliEmcalTrackSelResultUserPtr():
TObject(),
fUserStorage(nullptr)
{
}
AliEmcalTrackSelResultUserPtr::AliEmcalTrackSelResultUserPtr(TObject *data):
TObject(),
fUserStorage(nullptr)
{
if(data) fUserStorage = new AliEmcalTrackSelResultUserStorage(data);
}
AliEmcalTrackSelResultUserPtr::AliEmcalTrackSelResultUserPtr(const AliEmcalTrackSelResultUserPtr &ref):
TObject(ref),
fUserStorage(nullptr)
{
if(ref.fUserStorage) {
fUserStorage = ref.fUserStorage;
fUserStorage->Connect();
}
}
AliEmcalTrackSelResultUserPtr::AliEmcalTrackSelResultUserPtr(AliEmcalTrackSelResultUserPtr &&ref):
TObject(ref),
fUserStorage(nullptr)
{
if(ref.fUserStorage) {
// reference count does not change in case of move semantics
fUserStorage = ref.fUserStorage;
ref.fUserStorage = nullptr;
}
}
AliEmcalTrackSelResultUserPtr &AliEmcalTrackSelResultUserPtr::operator=(const AliEmcalTrackSelResultUserPtr &ref){
TObject::operator=(ref);
if(&ref != this){
if(fUserStorage) {
fUserStorage->Release();
// if(fUserStorage->GetReferenceCount() < 1) delete fUserStorage;
}
if(ref.fUserStorage) {
fUserStorage = ref.fUserStorage;
fUserStorage->Connect();
}
}
return *this;
}
AliEmcalTrackSelResultUserPtr &AliEmcalTrackSelResultUserPtr::operator=(AliEmcalTrackSelResultUserPtr &&ref){
TObject::operator=(ref);
if(&ref != this){
if(fUserStorage) {
fUserStorage->Release();
//if(fUserStorage->GetReferenceCount() < 1) delete fUserStorage;
}
if(ref.fUserStorage) {
// reference count does not change in case of move semantics
fUserStorage = ref.fUserStorage;
ref.fUserStorage = nullptr;
}
}
return *this;
}
AliEmcalTrackSelResultUserPtr::~AliEmcalTrackSelResultUserPtr(){
if(fUserStorage) {
fUserStorage->Release();
// The last pointer connected to the storage deletes it
//if(fUserStorage->GetReferenceCount() < 1) delete fUserStorage;
}
}
bool TestAliEmcalTrackSelResultPtr::RunAllTests() const {
return TestOperatorBool() && TestUserInfo() && TestCopyConstructor() && TestOperatorAssign();
}
bool TestAliEmcalTrackSelResultPtr::TestOperatorBool() const {
AliEmcalTrackSelResultPtr testtrue(nullptr, true), testfalse(nullptr, false);
bool testresult(true);
if(!(testtrue == true)) testresult = false;
if(testfalse == true) testresult = false;
return testresult;
}
bool TestAliEmcalTrackSelResultPtr::TestCopyConstructor() const {
int failure(0);
for(int i = 0; i < 10; i++) {
TNamed *payloadTrue = new TNamed("truewith", "true, with object"),
*payloadFalse = new TNamed("falsewith", "false, with user object");
AliEmcalTrackSelResultPtr truewith(nullptr, true, payloadTrue),
truewithout(nullptr, true),
falsewith(nullptr, false, payloadFalse),
falsewithout(nullptr, false);
// make copies
AliEmcalTrackSelResultPtr cpytruewith(truewith), cpyfalsewith(falsewith), cpytruewithout(truewithout), cpyfalsewithout(falsewithout);
if(!(AssertBool(cpytruewith, true) && AssertBool(cpytruewithout, true) && AssertBool(cpyfalsewith, false) && AssertBool(cpyfalsewithout, false))) failure++;
if(!(AssertPayload(cpytruewith, payloadTrue) && AssertPayload(cpytruewithout, nullptr) && AssertPayload(cpyfalsewith, payloadFalse) && AssertPayload(cpyfalsewithout, nullptr))) failure++;
}
return failure == 0;
}
bool TestAliEmcalTrackSelResultPtr::TestOperatorAssign() const {
int failure(0);
for(int i = 0; i < 10; i++) {
TNamed *payloadTrue = new TNamed("truewith", "true, with object"),
*payloadFalse = new TNamed("falsewith", "false, with user object");
AliEmcalTrackSelResultPtr truewith(nullptr, true, payloadTrue),
truewithout(nullptr, true),
falsewith(nullptr, false, payloadFalse),
falsewithout(nullptr, false);
// make assignments
AliEmcalTrackSelResultPtr asgtruewith = truewith, asgfalsewith = falsewith, asgtruewithout = truewithout, asgfalsewithout = falsewithout;
if(!(AssertBool(asgtruewith, true) && AssertBool(asgtruewithout, true) && AssertBool(asgfalsewith, false) && AssertBool(asgfalsewithout, false))) failure++;
if(!(AssertPayload(asgtruewith, payloadTrue) && AssertPayload(asgtruewithout, nullptr) && AssertPayload(asgfalsewith, payloadFalse) && AssertPayload(asgfalsewithout, nullptr))) failure++;
}
return failure == 0;
}
bool TestAliEmcalTrackSelResultPtr::TestUserInfo() const {
int failure(0);
for(int i = 0; i < 10; i++) {
AliEmcalTrackSelResultPtr testwith(nullptr, true, new TNamed("testuserobject", "Test userobject"));
if(!testwith.GetUserInfo()) failure++;
AliEmcalTrackSelResultPtr testwithout(nullptr, true);
if(testwithout.GetUserInfo()) failure++;
}
return failure == 0;
}
bool TestAliEmcalTrackSelResultPtr::AssertBool(const AliEmcalTrackSelResultPtr &test, bool assertval) const {
return test.GetSelectionResult() == assertval;
}
bool TestAliEmcalTrackSelResultPtr::AssertPayload(const AliEmcalTrackSelResultPtr &test, void *payload) const {
return test.GetUserInfo() == reinterpret_cast<const TObject *>(payload);
} | 36.825153 | 191 | 0.662474 | maroozm |
ab6c16aacbe6605846db36584cbe96ea1a14369a | 3,544 | hpp | C++ | test/unit/detail/load_store_matrix_coop_sync.hpp | mkarunan/rocWMMA | 390a2e793699a1e17c18e46d7fe51e245907f012 | [
"MIT"
] | null | null | null | test/unit/detail/load_store_matrix_coop_sync.hpp | mkarunan/rocWMMA | 390a2e793699a1e17c18e46d7fe51e245907f012 | [
"MIT"
] | 1 | 2022-03-16T20:41:26.000Z | 2022-03-16T20:41:26.000Z | test/unit/detail/load_store_matrix_coop_sync.hpp | mkarunan/rocWMMA | 390a2e793699a1e17c18e46d7fe51e245907f012 | [
"MIT"
] | 2 | 2022-03-17T16:47:29.000Z | 2022-03-18T14:12:22.000Z | /*******************************************************************************
*
* MIT License
*
* Copyright 2021-2022 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef ROCWMMA_DETAIL_LOAD_STORE_MATRIX_COOP_SYNC_HPP
#define ROCWMMA_DETAIL_LOAD_STORE_MATRIX_COOP_SYNC_HPP
#include "device/load_store_matrix_coop_sync.hpp"
#include "load_store_matrix_sync.hpp"
namespace rocwmma
{
template <uint32_t BlockM, uint32_t BlockN, typename DataT, typename Layout>
struct LoadStoreMatrixCoopSyncKernelA final
: public LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout>
{
private:
using Base = LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout>;
protected:
typename Base::KernelFunc kernelImpl() const final
{
return
typename Base::KernelFunc(LoadStoreMatrixCoopSyncA<BlockM, BlockN, DataT, Layout>);
}
};
template <uint32_t BlockM, uint32_t BlockN, typename DataT, typename Layout>
struct LoadStoreMatrixCoopSyncKernelB final
: public LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout>
{
private:
using Base = LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout>;
protected:
typename Base::KernelFunc kernelImpl() const final
{
return
typename Base::KernelFunc(LoadStoreMatrixCoopSyncB<BlockM, BlockN, DataT, Layout>);
}
};
template <uint32_t BlockM, uint32_t BlockN, typename DataT, typename Layout>
struct LoadStoreMatrixCoopSyncKernelAcc final
: public LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout>
{
private:
using Base = LoadStoreMatrixSyncKernel<BlockM, BlockN, DataT, Layout>;
protected:
typename Base::KernelFunc kernelImpl() const final
{
return typename Base::KernelFunc(
LoadStoreMatrixCoopSyncAcc<BlockM, BlockN, DataT, Layout>);
}
};
using LoadStoreMatrixCoopSyncGeneratorA
= LoadStoreMatrixSyncGenerator<LoadStoreMatrixCoopSyncKernelA>;
using LoadStoreMatrixCoopSyncGeneratorB
= LoadStoreMatrixSyncGenerator<LoadStoreMatrixCoopSyncKernelB>;
using LoadStoreMatrixCoopSyncGeneratorAcc
= LoadStoreMatrixSyncGenerator<LoadStoreMatrixCoopSyncKernelAcc>;
} // namespace rocwmma
#endif // ROCWMMA_DETAIL_LOAD_STORE_MATRIX_COOP_SYNC_HPP
| 38.945055 | 99 | 0.69921 | mkarunan |
ab6c6cdf53c0c6cc26129c919f5797523bf0f34b | 1,178 | cpp | C++ | Leetcode/WordSearch.cpp | zhanghuanzj/C- | b271de02885466e97d6a2072f4f93f87625834e4 | [
"Apache-2.0"
] | null | null | null | Leetcode/WordSearch.cpp | zhanghuanzj/C- | b271de02885466e97d6a2072f4f93f87625834e4 | [
"Apache-2.0"
] | null | null | null | Leetcode/WordSearch.cpp | zhanghuanzj/C- | b271de02885466e97d6a2072f4f93f87625834e4 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
if(board.empty()) return false;
if(word.empty()) return true;
int m = board.size();
int n = board.front().size();
vector<vector<bool>> visited(m,vector<bool>(n,false));
for(int i=0;i<m;++i){
for(int j=0;j<n;++j){
if(board[i][j]==word[0]&&dfs(board,visited,i,j,1,word)){
return true;
}
}
}
return false;
}
bool dfs(const vector<vector<char> > &board,vector<vector<bool>> &visited,int x,int y,int n,const string& word){
if(n==word.size()) return true;
visited[x][y] = true;
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
for(int i=0;i<4;++i){
int px = x+dx[i];
int py = y+dy[i];
if(px>=0&&px<board.size()&&py>=0&&py<board.front().size()&&word[n]==board[px][py]&&!visited[px][py]){
if(dfs(board,visited,px,py,n+1,word)){
return true;
}
}
}
visited[x][y] = false;
return false;
}
}; | 33.657143 | 116 | 0.457555 | zhanghuanzj |
ab70d04e506d4905bf1c781e7fb60ea91689b458 | 3,432 | hh | C++ | sclasses.hh | kant/simplesocket | 141ef7c522de0751b84dd13dd74c5e94645a6e0f | [
"MIT"
] | 10 | 2018-05-01T04:04:23.000Z | 2020-11-17T09:50:39.000Z | sclasses.hh | kant/simplesocket | 141ef7c522de0751b84dd13dd74c5e94645a6e0f | [
"MIT"
] | 4 | 2017-01-04T19:25:09.000Z | 2018-05-21T22:27:12.000Z | sclasses.hh | kant/simplesocket | 141ef7c522de0751b84dd13dd74c5e94645a6e0f | [
"MIT"
] | 4 | 2017-01-07T11:23:37.000Z | 2021-07-14T22:33:17.000Z | #pragma once
#include "swrappers.hh"
#include <unistd.h>
int SConnectWithTimeout(int sockfd, const ComboAddress& remote, double timeout);
struct Socket
{
Socket(int fd) : d_fd(fd){}
Socket(int domain, int type, int protocol=0)
{
d_fd = SSocket(domain, type, protocol);
}
Socket(const Socket&) = delete;
Socket& operator=(const Socket&) = delete;
Socket(Socket&& rhs)
{
d_fd = rhs.d_fd;
rhs.d_fd = -1;
}
operator int()
{
return d_fd;
}
void release()
{
d_fd=-1;
}
~Socket()
{
if(d_fd >= 0)
close(d_fd);
}
int d_fd;
};
/** Simple buffered reader for use on a non-blocking socket.
Has only one method to access data, getChar() which either gets you a character or it doesn't.
If the internal buffer is empty, SimpleBuffer will attempt to get up to bufsize bytes more in one go.
Optionally, with setTimeout(seconds) a timeout can be set.
WARNING: Only use ReadBuffer on a non-blocking socket! Otherwise it will
block indefinitely to read 'bufsize' bytes, even if you only wanted one!
*/
class ReadBuffer
{
public:
//! Instantiate on a non-blocking filedescriptor, with a given buffer size in bytes
explicit ReadBuffer(int fd, int bufsize=2048) : d_fd(fd), d_buffer(bufsize)
{}
//! Set timeout in seconds
void setTimeout(double timeout)
{
d_timeout = timeout;
}
//! Gets you a character in c, or false in case of EOF
inline bool getChar(char* c)
{
if(d_pos == d_endpos && !getMoreData())
return false;
*c=d_buffer[d_pos++];
return true;
}
inline bool haveData() const
{
return d_pos != d_endpos;
}
private:
bool getMoreData(); //!< returns false on EOF
int d_fd;
std::vector<char> d_buffer;
unsigned int d_pos{0};
unsigned int d_endpos{0};
double d_timeout=-1;
};
/** Convenience class that requires a non-blocking socket as input and supports commonly used operations.
SocketCommunicator will modify your socket to be non-blocking. This class
will not close or otherwise modify your socket.
Note that since SocketCommunicator instantiates a buffered reader on your socket, you should not attempt concurrent reads on the socket as long as SocketCommunicator is active.
*/
class SocketCommunicator
{
public:
//! Instantiate on top of this file descriptor, which will be set to non-blocking
explicit SocketCommunicator(int fd) : d_rb(fd), d_fd(fd)
{
SetNonBlocking(fd);
}
//! Connect to an address, with the default timeout (which may be infinite)
void connect(const ComboAddress& a)
{
SConnectWithTimeout(d_fd, a, d_timeout);
}
//! Get a while line of text. Returns false on EOF. Will return a partial last line. With timeout.
bool getLine(std::string& line);
//! Fully write out a message, even in the face of partial writes. With timeout.
void writen(const std::string& message);
//! Set the timeout (in seconds)
void setTimeout(double timeout) { d_timeout = timeout; }
private:
ReadBuffer d_rb;
int d_fd;
double d_timeout{-1};
};
// returns -1 in case if error, 0 if no data is available, 1 if there is
// negative time = infinity, timeout is in seconds
// should, but does not, decrement timeout
int waitForRWData(int fd, bool waitForRead, double* timeout=0, bool* error=0, bool* disconnected=0);
// should, but does not, decrement timeout. timeout in seconds
int waitForData(int fd, double* timeout=0);
| 27.677419 | 180 | 0.696387 | kant |
ab712ff93691af653b7972ebb552b8eb5f7593b8 | 620 | cpp | C++ | L9/17_JavaCpp_/01Classes/a_Begin/Foo.cpp | DeirdreHegarty/advanced_OOP | e62d8f2274422d3da9064e2576e2adc414eccee1 | [
"MIT"
] | null | null | null | L9/17_JavaCpp_/01Classes/a_Begin/Foo.cpp | DeirdreHegarty/advanced_OOP | e62d8f2274422d3da9064e2576e2adc414eccee1 | [
"MIT"
] | null | null | null | L9/17_JavaCpp_/01Classes/a_Begin/Foo.cpp | DeirdreHegarty/advanced_OOP | e62d8f2274422d3da9064e2576e2adc414eccee1 | [
"MIT"
] | null | null | null | /*
//[Foo.h]
class Foo // declare a class Foo
{
public: // begin the public section
Foo(); // declare a constructor for Foo
void doX();
protected: // begin the protected section
int m_num; // declare an instance variable of type int
};
*/
//[Foo.cpp]
#include <iostream>
#include "Foo.h"
using namespace std;
Foo::Foo() // definition for Foo's constructor
{
m_num = 5; // the constructor initializes the _num
// instance variable
}
void Foo::doX(){
cout<<"doX() running"<<endl;
} | 26.956522 | 66 | 0.532258 | DeirdreHegarty |
ab7130c5aab5368ffa946eba554bcbdeb4c3b3c7 | 1,234 | cpp | C++ | Dynamic Range Sum Queries/sol.cpp | glaucogithub/CSES-Problem-Set | 62e96c5aedf920dac339cf1a5f1ff8665735b766 | [
"MIT"
] | 1 | 2022-01-14T00:42:32.000Z | 2022-01-14T00:42:32.000Z | Dynamic Range Sum Queries/sol.cpp | glaucogithub/CSES-Problem-Set | 62e96c5aedf920dac339cf1a5f1ff8665735b766 | [
"MIT"
] | null | null | null | Dynamic Range Sum Queries/sol.cpp | glaucogithub/CSES-Problem-Set | 62e96c5aedf920dac339cf1a5f1ff8665735b766 | [
"MIT"
] | null | null | null |
// author: glaucoacassioc
// created on: September 22, 2021 1:04 AM
// Problem: Dynamic Range Sum Queries
// URL: https://cses.fi/problemset/task/1648/
// Time Limit: 1000 ms
// Memory Limit: 512 MB
#include <bits/stdc++.h>
using namespace std;
#define LSONE(S) ((S & (-S)))
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
vector<int64_t> ft, v;
void update(int k, int val) {
for (; k < (int)ft.size(); k += LSONE(k)) {
ft[k] += val;
}
}
void build(int n) {
ft.assign(n + 1, 0);
for (int i = 1; i <= n; ++i) {
update(i, v[i]);
}
}
int64_t query(int b) {
int64_t sum = 0;
for (; b; b -= LSONE(b)) {
sum += ft[b];
}
return sum;
}
int64_t query(int l, int r) {
return query(r) - (l == 1 ? 0 : query(l - 1));
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
#ifndef ONLINE_JUDGE
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
#endif
int n, q;
cin >> n >> q;
v.assign(n + 1, 0);
for (int i = 1; i <= n; ++i) {
cin >> v[i];
}
build(n);
while (q--) {
int op;
cin >> op;
if (op == 1) {
int k, u;
cin >> k >> u;
update(k, u - v[k]);
v[k] = u;
} else {
int l, r;
cin >> l >> r;
cout << query(l, r) << '\n';
}
}
}
| 17.138889 | 71 | 0.536467 | glaucogithub |
ab7227a29f7771c4071c5add1a6fffd9112c9102 | 2,671 | cpp | C++ | platforms/gfg/0490_maximum_number_edges_added_tree_stays_bipartite_graph.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | 2 | 2020-09-17T09:04:00.000Z | 2020-11-20T19:43:18.000Z | platforms/gfg/0490_maximum_number_edges_added_tree_stays_bipartite_graph.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | platforms/gfg/0490_maximum_number_edges_added_tree_stays_bipartite_graph.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | #include "../../template.hpp"
using Graph = vvi;
void AddEdge(Graph& graph, int from, int to, int cost = 0) {
graph[from - 1].push_back(to - 1);
graph[to - 1].push_back(from - 1);
// graph.push_back({from, to});
// graph[from].push_back({to, cost});
// graph[to].push_back({from, cost});
// graph.push_back({from, to, cost});
// graph[from][to] = cost;
// graph[to][from] = cost;
}
bool dfs(vvi graph, vi& color, int at) {
for (int adj : graph[at]) {
if (color[adj] == -1) {
color[adj] = 1 - color[at];
if (not dfs(graph, color, adj)) return false;
}
else if (color[at] == color[adj]) {
return false;
}
}
return true;
}
void FindMaxEdgesDFS(vvi graph) {
int n = graph.size();
vi color(n, -1);
for (int at = 0; at < n; ++at) {
if (color[at] == -1) {
color[0] = 0;
if (not dfs(graph,color, at)) {
cout << "Not bipartite" << endl;
return;
}
}
}
int reds = 0;
int blacks = 0;
int redsConnections = 0;
for (int i = 0; i < n; ++i) {
if (color[i] == 0) {
++reds;
redsConnections += graph[i].size();
}
else if (color[i] == 1) {
++blacks;
}
}
cout << reds * blacks - redsConnections << endl;
}
void FindMaxEdgesBFS(vvi graph) {
int n = graph.size();
vi color(n, -1);
color[0] = 0;
deque<int> q;
q.push_back(0);
while (not q.empty()) {
int at = q.front(); q.pop_front();
for (int adj : graph[at]) {
if (color[adj] == -1) {
color[adj] = 1 - color[at];
q.push_back(adj);
}
else if (color[adj] == color[at]) {
cout << "not a bipartite graph" << endl;
return;
}
}
}
int reds = 0;
int blacks = 0;
int redsConnections = 0;
for (int i = 0; i < n; ++i) {
if (color[i] == 0) {
++reds;
redsConnections += graph[i].size();
}
else if (color[i] == 1) {
++blacks;
}
}
cout << reds * blacks - redsConnections << endl;
}
int main() { TimeMeasure _;
{
Graph graph(3);
AddEdge(graph, 1, 2);
AddEdge(graph, 1, 3);
FindMaxEdgesBFS(graph);
FindMaxEdgesDFS(graph);
}
{
Graph graph(5);
AddEdge(graph, 1, 2);
AddEdge(graph, 1, 3);
AddEdge(graph, 2, 4);
AddEdge(graph, 3, 5);
FindMaxEdgesBFS(graph);
FindMaxEdgesDFS(graph);
}
}
| 24.731481 | 60 | 0.452639 | idfumg |
ab730d7d79f157393452fa99ba3c334e8a70b274 | 3,603 | cpp | C++ | onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorMatMul.cpp | MaximKalininMS/onnxruntime | 1d79926d273d01817ce93f001f36f417ab05f8a0 | [
"MIT"
] | 4 | 2019-06-06T23:48:57.000Z | 2021-06-03T11:51:45.000Z | onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorMatMul.cpp | Montaer/onnxruntime | 6dc25a60f8b058a556964801d99d5508641dcf69 | [
"MIT"
] | 10 | 2019-03-25T21:47:46.000Z | 2019-04-30T02:33:05.000Z | onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorMatMul.cpp | Montaer/onnxruntime | 6dc25a60f8b058a556964801d99d5508641dcf69 | [
"MIT"
] | 3 | 2019-05-07T01:29:04.000Z | 2020-08-09T08:36:12.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "precomp.h"
namespace Dml
{
class DmlOperatorMatMul : public DmlOperator
{
enum InputTensors { IN_A, IN_B };
public:
DmlOperatorMatMul(const MLOperatorKernelCreationContext& kernelInfo)
: DmlOperator(kernelInfo)
{
// MatMul has two inputs, but DML GEMM requires 3 input bindings (a null binding for the C Tensor).
ML_CHECK_VALID_ARGUMENT(kernelInfo.GetInputCount() == 2);
std::vector<std::optional<uint32_t>> inputIndices = { 0, 1, std::nullopt };
DmlOperator::Initialize(kernelInfo, inputIndices);
std::vector<DimensionType> inputShape0 = kernelInfo.GetTensorShapeDescription().GetInputTensorShape(0);
std::vector<DimensionType> inputShape1 = kernelInfo.GetTensorShapeDescription().GetInputTensorShape(1);
std::vector<DimensionType> outputShape = kernelInfo.GetTensorShapeDescription().GetOutputTensorShape(0);
// Get the padded input shapes and undo the effect of padding removal from the output shape
if (inputShape1.size() == 1)
{
inputShape1.push_back(1);
outputShape.push_back(1);
}
if (inputShape0.size() == 1)
{
inputShape0.insert(inputShape0.begin(), 1);
outputShape.insert(outputShape.end() - 1, 1);
}
// Remove the batch dimensions from each input, then re-add the broadcasted batch dimensions
// based on the output shape
inputShape0.erase(inputShape0.begin(), inputShape0.end() - 2);
inputShape1.erase(inputShape1.begin(), inputShape1.end() - 2);
inputShape0.insert(inputShape0.begin(), outputShape.begin(), outputShape.end() - 2);
inputShape1.insert(inputShape1.begin(), outputShape.begin(), outputShape.end() - 2);
// Initialize the input descriptions with broadcasting
m_inputTensorDescs[0] = CreateTensorDescFromInput(kernelInfo, 0, TensorAxis::DoNotCoerce, TensorAxis::W, TensorAxis::RightAligned, inputShape0);
m_inputTensorDescs[1] = CreateTensorDescFromInput(kernelInfo, 1, TensorAxis::DoNotCoerce, TensorAxis::W, TensorAxis::RightAligned, inputShape1);
// Initialize the output description while overriding the shape
m_outputTensorDescs[0] = CreateTensorDescFromOutput(kernelInfo, 0, TensorAxis::DoNotCoerce, TensorAxis::W, TensorAxis::RightAligned, outputShape);
std::vector<DML_TENSOR_DESC> inputDescs = GetDmlInputDescs();
std::vector<DML_TENSOR_DESC> outputDescs = GetDmlOutputDescs();
std::optional<ActivationOperatorDesc> fusedActivation = FusionHelpers::TryGetFusedActivationDesc(kernelInfo);
DML_OPERATOR_DESC fusedActivationDmlDesc = fusedActivation ? fusedActivation->GetDmlDesc() : DML_OPERATOR_DESC();
DML_GEMM_OPERATOR_DESC gemmDesc = {};
gemmDesc.ATensor = &inputDescs[0];
gemmDesc.BTensor = &inputDescs[1];
gemmDesc.CTensor = nullptr;
gemmDesc.OutputTensor = &outputDescs[0];
gemmDesc.TransA = DML_MATRIX_TRANSFORM_NONE;
gemmDesc.TransB = DML_MATRIX_TRANSFORM_NONE;
gemmDesc.Alpha = 1.0f;
gemmDesc.Beta = 0.0f;
gemmDesc.FusedActivation = fusedActivation ? &fusedActivationDmlDesc : nullptr;
DML_OPERATOR_DESC opDesc = { DML_OPERATOR_GEMM, &gemmDesc };
SetDmlOperatorDesc(opDesc, kernelInfo);
}
};
DML_OP_DEFINE_CREATION_FUNCTION(MatMul, DmlOperatorMatMul);
DML_OP_DEFINE_CREATION_FUNCTION(FusedMatMul, DmlOperatorMatMul);
} // namespace Dml
| 44.481481 | 154 | 0.706356 | MaximKalininMS |
ab73bc776134f3e88c7e8b1c24b2ba0d167f698b | 1,740 | cpp | C++ | ural/1706.cpp | jffifa/algo-solution | af2400d6071ee8f777f9473d6a34698ceef08355 | [
"MIT"
] | 5 | 2015-07-14T10:29:25.000Z | 2016-10-11T12:45:18.000Z | ural/1706.cpp | jffifa/algo-solution | af2400d6071ee8f777f9473d6a34698ceef08355 | [
"MIT"
] | null | null | null | ural/1706.cpp | jffifa/algo-solution | af2400d6071ee8f777f9473d6a34698ceef08355 | [
"MIT"
] | 3 | 2016-08-23T01:05:26.000Z | 2017-05-28T02:04:20.000Z | #include<iostream>//boj 1178
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxn =10100;
const int maxv =10100;
int a[maxn],sa[maxn],container[maxn],wy[maxn],wv[maxn],wx[maxv],rk[maxn],h[maxn];
int cmp(int *r,int a,int b,int l)
{
return (r[a]==r[b]) &&(r[a+l]==r[b+l]);
}
void suffix(int *r, int n,int *sa,int m)
{
int i,j,*t,*x=wx,*y=wy,p;
memset(container,0,sizeof(int)*m);
for(i=0; i<n; i++) container[x[i]=r[i]]++;
for(i=1; i<m; i++) container[i]+=container[i-1];
for(i=n-1; i>=0; i--) sa[--container[x[i]]]=i;
for(p=0,j=1; p<n; j<<=1, m=p)
{
for(p=0,i=n-j; i<n; i++) y[p++]=i;
for(i=0; i<n; i++) if(sa[i]>=j) y[p++]=sa[i]-j;
for(i=0; i<n; i++) wv[i]=x[y[i]];
memset(container,0,sizeof(int)*m);
for(i=0; i<n; i++) container[wv[i]]++;
for(i=1; i<m; i++) container[i]+=container[i-1];
for(i=n-1;i>=0; i--) sa[--container[wv[i]]]=y[i];
for(t=x,x=y,y=t,x[sa[0]]=0,p=1,i=1;i<n; i++)
x[sa[i]]=cmp(y,sa[i],sa[i-1],j)?p-1:p++;
}
}
void cal(int *r,int *sa,int n)
{
int i,j,k=0;
for(i=1; i<=n; i++) rk[sa[i]]=i;
for(i=0; i<n; h[rk[i++]]=k)
for(k?k--:0,j=sa[rk[i]-1]; r[i+k]==r[j+k]; k++);
}
char ch[10000];
int main()
{
//freopen("in","r",stdin);
//freopen("std","w",stdout);
int i,j,k;
int n,m;
scanf("%d", &k);
scanf("%s",ch);
int len=strlen(ch);
for(i=0,j=len; i<len; i++,j++)
ch[j]=ch[i];
ch[j]=0;
n=len*2;
for(i=0; i<n;i++)
{
a[i]=ch[i];
}
for(i=0; i<len; i++)
{
int tp=a[i+k];
a[i+k]=0;
suffix(&a[i],k+1,sa,300);
cal(&a[i],sa,k);
int ans=0;
for(j=1; j<=k; j++)
ans+=h[j];
ans=k*(k+1)/2-ans;
cout<<ans;
if(i==len-1)
puts("");
else
printf(" ");
a[i+k]=tp;
}
}
| 21.219512 | 81 | 0.520115 | jffifa |
ab772c758b026ba889a5aea1ba4ca80c8e9f811f | 34,224 | hpp | C++ | include/ldaplusplus/utils.hpp | angeloskath/supervised-lda | fe3a39bb0d6c7d0c2a33f069440869ad70774da8 | [
"MIT"
] | 22 | 2017-05-25T11:59:02.000Z | 2021-08-30T08:51:41.000Z | include/ldaplusplus/utils.hpp | angeloskath/supervised-lda | fe3a39bb0d6c7d0c2a33f069440869ad70774da8 | [
"MIT"
] | 22 | 2016-06-30T15:51:18.000Z | 2021-12-06T10:43:16.000Z | include/ldaplusplus/utils.hpp | angeloskath/supervised-lda | fe3a39bb0d6c7d0c2a33f069440869ad70774da8 | [
"MIT"
] | 4 | 2017-09-28T14:58:01.000Z | 2020-12-21T14:22:38.000Z | #ifndef _LDAPLUSPLUS_UTILS_HPP_
#define _LDAPLUSPLUS_UTILS_HPP_
#include <cmath>
#include <memory>
#include <mutex>
#include <array>
#include <Eigen/Core>
namespace ldaplusplus {
namespace math_utils {
static const std::array<double, 1024> exp_lut = {
1.000000000000000000e+00, 1.000977995032110268e+00, 1.001956946538503423e+00,
1.002936855454606535e+00, 1.003917722716761274e+00, 1.004899549262225911e+00,
1.005882336029174207e+00, 1.006866083956698077e+00, 1.007850793984808035e+00,
1.008836467054433639e+00, 1.009823104107424596e+00, 1.010810706086551880e+00,
1.011799273935508392e+00, 1.012788808598910073e+00, 1.013779311022296792e+00,
1.014770782152132789e+00, 1.015763222935808230e+00, 1.016756634321639652e+00,
1.017751017258871515e+00, 1.018746372697675762e+00, 1.019742701589154477e+00,
1.020740004885339447e+00, 1.021738283539193493e+00, 1.022737538504611798e+00,
1.023737770736421915e+00, 1.024738981190385756e+00, 1.025741170823199822e+00,
1.026744340592495863e+00, 1.027748491456842661e+00, 1.028753624375746245e+00,
1.029759740309651228e+00, 1.030766840219941249e+00, 1.031774925068940307e+00,
1.032783995819913647e+00, 1.033794053437068428e+00, 1.034805098885555052e+00,
1.035817133131467616e+00, 1.036830157141844788e+00, 1.037844171884671818e+00,
1.038859178328879640e+00, 1.039875177444347321e+00, 1.040892170201902722e+00,
1.041910157573322726e+00, 1.042929140531334564e+00, 1.043949120049617374e+00,
1.044970097102801754e+00, 1.045992072666471984e+00, 1.047015047717166691e+00,
1.048039023232378630e+00, 1.049064000190557788e+00, 1.050089979571109833e+00,
1.051116962354399220e+00, 1.052144949521748529e+00, 1.053173942055440682e+00,
1.054203940938718942e+00, 1.055234947155788250e+00, 1.056266961691815665e+00,
1.057299985532932585e+00, 1.058334019666233861e+00, 1.059369065079780903e+00,
1.060405122762600127e+00, 1.061442193704686288e+00, 1.062480278897001806e+00,
1.063519379331478110e+00, 1.064559496001017402e+00, 1.065600629899492224e+00,
1.066642782021747449e+00, 1.067685953363600948e+00, 1.068730144921844483e+00,
1.069775357694244589e+00, 1.070821592679543466e+00, 1.071868850877460533e+00,
1.072917133288692426e+00, 1.073966440914914777e+00, 1.075016774758782656e+00,
1.076068135823932126e+00, 1.077120525114980021e+00, 1.078173943637526611e+00,
1.079228392398154712e+00, 1.080283872404432577e+00, 1.081340384664913001e+00,
1.082397930189135327e+00, 1.083456509987626770e+00, 1.084516125071902204e+00,
1.085576776454466152e+00, 1.086638465148812793e+00, 1.087701192169428399e+00,
1.088764958531790450e+00, 1.089829765252370297e+00, 1.090895613348632942e+00,
1.091962503839038812e+00, 1.093030437743044203e+00, 1.094099416081102172e+00,
1.095169439874664308e+00, 1.096240510146180736e+00, 1.097312627919101669e+00,
1.098385794217878519e+00, 1.099460010067964122e+00, 1.100535276495814507e+00,
1.101611594528889571e+00, 1.102688965195653736e+00, 1.103767389525577958e+00,
1.104846868549139272e+00, 1.105927403297823020e+00, 1.107008994804122848e+00,
1.108091644101542705e+00, 1.109175352224596844e+00, 1.110260120208811818e+00,
1.111345949090726037e+00, 1.112432839907892657e+00, 1.113520793698878908e+00,
1.114609811503268100e+00, 1.115699894361659616e+00, 1.116791043315671139e+00,
1.117883259407939311e+00, 1.118976543682119518e+00, 1.120070897182888547e+00,
1.121166320955944595e+00, 1.122262816048008816e+00, 1.123360383506825988e+00,
1.124459024381165184e+00, 1.125558739720821544e+00, 1.126659530576616719e+00,
1.127761398000400428e+00, 1.128864343045050456e+00, 1.129968366764475096e+00,
1.131073470213612486e+00, 1.132179654448433048e+00, 1.133286920525939934e+00,
1.134395269504169912e+00, 1.135504702442194480e+00, 1.136615220400120752e+00,
1.137726824439093010e+00, 1.138839515621292930e+00, 1.139953295009941581e+00,
1.141068163669298974e+00, 1.142184122664666734e+00, 1.143301173062388099e+00,
1.144419315929849024e+00, 1.145538552335479299e+00, 1.146658883348754321e+00,
1.147780310040194429e+00, 1.148902833481367791e+00, 1.150026454744889959e+00,
1.151151174904425867e+00, 1.152276995034690277e+00, 1.153403916211449332e+00,
1.154531939511520555e+00, 1.155661066012775517e+00, 1.156791296794139168e+00,
1.157922632935592278e+00, 1.159055075518171440e+00, 1.160188625623970404e+00,
1.161323284336141404e+00, 1.162459052738896270e+00, 1.163595931917506432e+00,
1.164733922958305579e+00, 1.165873026948688995e+00, 1.167013244977116226e+00,
1.168154578133110855e+00, 1.169297027507261832e+00, 1.170440594191225259e+00,
1.171585279277724378e+00, 1.172731083860551582e+00, 1.173878009034568626e+00,
1.175026055895707744e+00, 1.176175225540974090e+00, 1.177325519068444182e+00,
1.178476937577269901e+00, 1.179629482167676935e+00, 1.180783153940967667e+00,
1.181937953999521618e+00, 1.183093883446795669e+00, 1.184250943387326727e+00,
1.185409134926731500e+00, 1.186568459171707834e+00, 1.187728917230036485e+00,
1.188890510210581342e+00, 1.190053239223290316e+00, 1.191217105379197339e+00,
1.192382109790423028e+00, 1.193548253570175355e+00, 1.194715537832750751e+00,
1.195883963693536112e+00, 1.197053532269008791e+00, 1.198224244676737937e+00,
1.199396102035385825e+00, 1.200569105464708963e+00, 1.201743256085558542e+00,
1.202918555019882207e+00, 1.204095003390724949e+00, 1.205272602322229991e+00,
1.206451352939639676e+00, 1.207631256369297246e+00, 1.208812313738647726e+00,
1.209994526176237706e+00, 1.211177894811718669e+00, 1.212362420775846328e+00,
1.213548105200482397e+00, 1.214734949218595261e+00, 1.215922953964261755e+00,
1.217112120572667600e+00, 1.218302450180108965e+00, 1.219493943923992907e+00,
1.220686602942839150e+00, 1.221880428376280747e+00, 1.223075421365065640e+00,
1.224271583051056878e+00, 1.225468914577234614e+00, 1.226667417087696776e+00,
1.227867091727659954e+00, 1.229067939643461393e+00, 1.230269961982558780e+00,
1.231473159893532010e+00, 1.232677534526085195e+00, 1.233883087031045545e+00,
1.235089818560366925e+00, 1.236297730267128969e+00, 1.237506823305539294e+00,
1.238717098830934837e+00, 1.239928557999781411e+00, 1.241141201969676811e+00,
1.242355031899350593e+00, 1.243570048948665407e+00, 1.244786254278618332e+00,
1.246003649051341977e+00, 1.247222234430105381e+00, 1.248442011579315558e+00,
1.249662981664517947e+00, 1.250885145852397962e+00, 1.252108505310782105e+00,
1.253333061208639077e+00, 1.254558814716080661e+00, 1.255785767004363285e+00,
1.257013919245888234e+00, 1.258243272614204322e+00, 1.259473828284007002e+00,
1.260705587431141694e+00, 1.261938551232603123e+00, 1.263172720866537091e+00,
1.264408097512241813e+00, 1.265644682350168804e+00, 1.266882476561923987e+00,
1.268121481330269251e+00, 1.269361697839122449e+00, 1.270603127273560284e+00,
1.271845770819817423e+00, 1.273089629665289824e+00, 1.274334704998533629e+00,
1.275580998009267830e+00, 1.276828509888375152e+00, 1.278077241827902721e+00,
1.279327195021063623e+00, 1.280578370662237786e+00, 1.281830769946973314e+00,
1.283084394071987600e+00, 1.284339244235168209e+00, 1.285595321635574440e+00,
1.286852627473438426e+00, 1.288111162950165367e+00, 1.289370929268336408e+00,
1.290631927631708420e+00, 1.291894159245215112e+00, 1.293157625314969250e+00,
1.294422327048262655e+00, 1.295688265653568649e+00, 1.296955442340541387e+00,
1.298223858320018742e+00, 1.299493514804022753e+00, 1.300764413005760733e+00,
1.302036554139626157e+00, 1.303309939421200658e+00, 1.304584570067254479e+00,
1.305860447295748017e+00, 1.307137572325832497e+00, 1.308415946377851968e+00,
1.309695570673343301e+00, 1.310976446435038634e+00, 1.312258574886865814e+00,
1.313541957253949288e+00, 1.314826594762612100e+00, 1.316112488640376332e+00,
1.317399640115964887e+00, 1.318688050419302149e+00, 1.319977720781515540e+00,
1.321268652434935964e+00, 1.322560846613100471e+00, 1.323854304550751593e+00,
1.325149027483840003e+00, 1.326445016649525188e+00, 1.327742273286175889e+00,
1.329040798633372544e+00, 1.330340593931907733e+00, 1.331641660423787732e+00,
1.332943999352233400e+00, 1.334247611961681068e+00, 1.335552499497784540e+00,
1.336858663207415976e+00, 1.338166104338666340e+00, 1.339474824140847842e+00,
1.340784823864494379e+00, 1.342096104761362874e+00, 1.343408668084433932e+00,
1.344722515087914516e+00, 1.346037647027237272e+00, 1.347354065159063197e+00,
1.348671770741282527e+00, 1.349990765033014739e+00, 1.351311049294611877e+00,
1.352632624787657667e+00, 1.353955492774970404e+00, 1.355279654520602728e+00,
1.356605111289844068e+00, 1.357931864349220863e+00, 1.359259914966498561e+00,
1.360589264410682508e+00, 1.361919913952018835e+00, 1.363251864861995788e+00,
1.364585118413345954e+00, 1.365919675880045814e+00, 1.367255538537318182e+00,
1.368592707661632879e+00, 1.369931184530708501e+00, 1.371270970423512425e+00,
1.372612066620263693e+00, 1.373954474402432790e+00, 1.375298195052744088e+00,
1.376643229855176065e+00, 1.377989580094962641e+00, 1.379337247058595173e+00,
1.380686232033823124e+00, 1.382036536309655395e+00, 1.383388161176360986e+00,
1.384741107925471670e+00, 1.386095377849781762e+00, 1.387450972243349678e+00,
1.388807892401500377e+00, 1.390166139620824470e+00, 1.391525715199181779e+00,
1.392886620435700218e+00, 1.394248856630779132e+00, 1.395612425086089514e+00,
1.396977327104575117e+00, 1.398343563990454008e+00, 1.399711137049220122e+00,
1.401080047587643707e+00, 1.402450296913773320e+00, 1.403821886336936497e+00,
1.405194817167741750e+00, 1.406569090718078785e+00, 1.407944708301120951e+00,
1.409321671231325457e+00, 1.410699980824435151e+00, 1.412079638397479409e+00,
1.413460645268776350e+00, 1.414843002757932622e+00, 1.416226712185845837e+00,
1.417611774874705466e+00, 1.418998192147993942e+00, 1.420385965330488220e+00,
1.421775095748260442e+00, 1.423165584728680377e+00, 1.424557433600415424e+00,
1.425950643693432385e+00, 1.427345216338999023e+00, 1.428741152869684949e+00,
1.430138454619362953e+00, 1.431537122923210559e+00, 1.432937159117710912e+00,
1.434338564540654337e+00, 1.435741340531139221e+00, 1.437145488429574014e+00,
1.438551009577677897e+00, 1.439957905318482112e+00, 1.441366176996331516e+00,
1.442775825956885694e+00, 1.444186853547120286e+00, 1.445599261115328327e+00,
1.447013050011121349e+00, 1.448428221585431164e+00, 1.449844777190509859e+00,
1.451262718179933353e+00, 1.452682045908600061e+00, 1.454102761732734450e+00,
1.455524867009887036e+00, 1.456948363098935717e+00, 1.458373251360087552e+00,
1.459799533154880313e+00, 1.461227209846182706e+00, 1.462656282798196594e+00,
1.464086753376458105e+00, 1.465518622947838745e+00, 1.466951892880546948e+00,
1.468386564544128747e+00, 1.469822639309470436e+00, 1.471260118548798346e+00,
1.472699003635681070e+00, 1.474139295945030570e+00, 1.475580996853103288e+00,
1.477024107737501923e+00, 1.478468629977176318e+00, 1.479914564952424794e+00,
1.481361914044895922e+00, 1.482810678637589197e+00, 1.484260860114857028e+00,
1.485712459862404966e+00, 1.487165479267294810e+00, 1.488619919717944162e+00,
1.490075782604128651e+00, 1.491533069316983262e+00, 1.492991781249003447e+00,
1.494451919794046457e+00, 1.495913486347332677e+00, 1.497376482305447176e+00,
1.498840909066340599e+00, 1.500306768029331161e+00, 1.501774060595105320e+00,
1.503242788165719546e+00, 1.504712952144601212e+00, 1.506184553936550596e+00,
1.507657594947741764e+00, 1.509132076585724125e+00, 1.510608000259423100e+00,
1.512085367379143008e+00, 1.513564179356566397e+00, 1.515044437604757155e+00,
1.516526143538160953e+00, 1.518009298572606580e+00, 1.519493904125307715e+00,
1.520979961614864262e+00, 1.522467472461262794e+00, 1.523956438085879439e+00,
1.525446859911479880e+00, 1.526938739362221575e+00, 1.528432077863654648e+00,
1.529926876842723216e+00, 1.531423137727767392e+00, 1.532920861948523950e+00,
1.534420050936127655e+00, 1.535920706123113710e+00, 1.537422828943417308e+00,
1.538926420832376962e+00, 1.540431483226734288e+00, 1.541938017564636221e+00,
1.543446025285636569e+00, 1.544955507830696240e+00, 1.546466466642186122e+00,
1.547978903163887310e+00, 1.549492818840993102e+00, 1.551008215120110112e+00,
1.552525093449259819e+00, 1.554043455277879682e+00, 1.555563302056824915e+00,
1.557084635238369597e+00, 1.558607456276208003e+00, 1.560131766625456162e+00,
1.561657567742653185e+00, 1.563184861085763044e+00, 1.564713648114174793e+00,
1.566243930288705677e+00, 1.567775709071600909e+00, 1.569308985926536115e+00,
1.570843762318618220e+00, 1.572380039714387445e+00, 1.573917819581817312e+00,
1.575457103390318192e+00, 1.576997892610736862e+00, 1.578540188715358505e+00,
1.580083993177908486e+00, 1.581629307473553459e+00, 1.583176133078902703e+00,
1.584724471472009455e+00, 1.586274324132372682e+00, 1.587825692540938194e+00,
1.589378578180100199e+00, 1.590932982533702855e+00, 1.592488907087041161e+00,
1.594046353326863175e+00, 1.595605322741370236e+00, 1.597165816820220074e+00,
1.598727837054526590e+00, 1.600291384936862515e+00, 1.601856461961259637e+00,
1.603423069623211461e+00, 1.604991209419673881e+00, 1.606560882849066951e+00,
1.608132091411276221e+00, 1.609704836607653400e+00, 1.611279119941019689e+00,
1.612854942915664891e+00, 1.614432307037350967e+00, 1.616011213813311809e+00,
1.617591664752255909e+00, 1.619173661364366579e+00, 1.620757205161304615e+00,
1.622342297656209409e+00, 1.623928940363699613e+00, 1.625517134799875363e+00,
1.627106882482319827e+00, 1.628698184930099879e+00, 1.630291043663768535e+00,
1.631885460205365623e+00, 1.633481436078419557e+00, 1.635078972807948450e+00,
1.636678071920462774e+00, 1.638278734943964698e+00, 1.639880963407951864e+00,
1.641484758843416936e+00, 1.643090122782850715e+00, 1.644697056760241693e+00,
1.646305562311079607e+00, 1.647915640972355433e+00, 1.649527294282563172e+00,
1.651140523781701841e+00, 1.652755331011276363e+00, 1.654371717514299123e+00,
1.655989684835291964e+00, 1.657609234520286634e+00, 1.659230368116827670e+00,
1.660853087173972398e+00, 1.662477393242293600e+00, 1.664103287873880177e+00,
1.665730772622339151e+00, 1.667359849042796993e+00, 1.668990518691900959e+00,
1.670622783127820865e+00, 1.672256643910250196e+00, 1.673892102600407883e+00,
1.675529160761039638e+00, 1.677167819956419725e+00, 1.678808081752352521e+00,
1.680449947716172732e+00, 1.682093419416749169e+00, 1.683738498424484087e+00,
1.685385186311316064e+00, 1.687033484650720894e+00, 1.688683395017712918e+00,
1.690334918988847468e+00, 1.691988058142221085e+00, 1.693642814057473966e+00,
1.695299188315791517e+00, 1.696957182499905015e+00, 1.698616798194093835e+00,
1.700278036984186558e+00, 1.701940900457563410e+00, 1.703605390203156267e+00,
1.705271507811451093e+00, 1.706939254874489942e+00, 1.708608632985871179e+00,
1.710279643740752142e+00, 1.711952288735850036e+00, 1.713626569569443481e+00,
1.715302487841374512e+00, 1.716980045153049694e+00, 1.718659243107441892e+00,
1.720340083309091384e+00, 1.722022567364107859e+00, 1.723706696880171751e+00,
1.725392473466535792e+00, 1.727079898734026564e+00, 1.728768974295046057e+00,
1.730459701763572999e+00, 1.732152082755164635e+00, 1.733846118886958720e+00,
1.735541811777673971e+00, 1.737239163047612056e+00, 1.738938174318660046e+00,
1.740638847214290630e+00, 1.742341183359564338e+00, 1.744045184381131319e+00,
1.745750851907231782e+00, 1.747458187567699328e+00, 1.749167192993960951e+00,
1.750877869819039478e+00, 1.752590219677554240e+00, 1.754304244205723951e+00,
1.756019945041367158e+00, 1.757737323823904463e+00, 1.759456382194358959e+00,
1.761177121795359790e+00, 1.762899544271141927e+00, 1.764623651267548610e+00,
1.766349444432032456e+00, 1.768076925413657907e+00, 1.769806095863101225e+00,
1.771536957432653825e+00, 1.773269511776222718e+00, 1.775003760549332510e+00,
1.776739705409126735e+00, 1.778477348014370074e+00, 1.780216690025448578e+00,
1.781957733104373443e+00, 1.783700478914779897e+00, 1.785444929121931423e+00,
1.787191085392719092e+00, 1.788938949395664890e+00, 1.790688522800922389e+00,
1.792439807280278741e+00, 1.794192804507155570e+00, 1.795947516156611412e+00,
1.797703943905343493e+00, 1.799462089431687950e+00, 1.801221954415622939e+00,
1.802983540538769303e+00, 1.804746849484392790e+00, 1.806511882937405389e+00,
1.808278642584366214e+00, 1.810047130113484837e+00, 1.811817347214621288e+00,
1.813589295579288496e+00, 1.815362976900653402e+00, 1.817138392873539177e+00,
1.818915545194426331e+00, 1.820694435561454716e+00, 1.822475065674424632e+00,
1.824257437234799051e+00, 1.826041551945704944e+00, 1.827827411511934841e+00,
1.829615017639948382e+00, 1.831404372037874539e+00, 1.833195476415512726e+00,
1.834988332484334128e+00, 1.836782941957484150e+00, 1.838579306549783521e+00,
1.840377427977729852e+00, 1.842177307959500077e+00, 1.843978948214950675e+00,
1.845782350465620780e+00, 1.847587516434733068e+00, 1.849394447847195311e+00,
1.851203146429602153e+00, 1.853013613910237112e+00, 1.854825852019074128e+00,
1.856639862487778458e+00, 1.858455647049709336e+00, 1.860273207439921306e+00,
1.862092545395165555e+00, 1.863913662653891468e+00, 1.865736560956249512e+00,
1.867561242044091241e+00, 1.869387707660971953e+00, 1.871215959552152475e+00,
1.873045999464600042e+00, 1.874877829146990305e+00, 1.876711450349709764e+00,
1.878546864824856444e+00, 1.880384074326241439e+00, 1.882223080609391808e+00,
1.884063885431551011e+00, 1.885906490551681580e+00, 1.887750897730465560e+00,
1.889597108730307617e+00, 1.891445125315335929e+00, 1.893294949251403514e+00,
1.895146582306090899e+00, 1.897000026248707005e+00, 1.898855282850291371e+00,
1.900712353883615258e+00, 1.902571241123184098e+00, 1.904431946345238380e+00,
1.906294471327756090e+00, 1.908158817850454048e+00, 1.910024987694789234e+00,
1.911892982643961236e+00, 1.913762804482913360e+00, 1.915634454998335068e+00,
1.917507935978662870e+00, 1.919383249214082099e+00, 1.921260396496529133e+00,
1.923139379619692946e+00, 1.925020200379016666e+00, 1.926902860571699128e+00,
1.928787361996697314e+00, 1.930673706454727245e+00, 1.932561895748265979e+00,
1.934451931681553383e+00, 1.936343816060594136e+00, 1.938237550693158839e+00,
1.940133137388786233e+00, 1.942030577958784976e+00, 1.943929874216234976e+00,
1.945831027975989169e+00, 1.947734041054675735e+00, 1.949638915270699435e+00,
1.951545652444242940e+00, 1.953454254397269940e+00, 1.955364722953525147e+00,
1.957277059938537400e+00, 1.959191267179620555e+00, 1.961107346505876148e+00,
1.963025299748193842e+00, 1.964945128739254310e+00, 1.966866835313530570e+00,
1.968790421307289762e+00, 1.970715888558594475e+00, 1.972643238907305641e+00,
1.974572474195082972e+00, 1.976503596265387408e+00, 1.978436606963483113e+00,
1.980371508136438585e+00, 1.982308301633128655e+00, 1.984246989304236930e+00,
1.986187573002256235e+00, 1.988130054581491502e+00, 1.990074435898061544e+00,
1.992020718809899504e+00, 1.993968905176756401e+00, 1.995918996860201577e+00,
1.997870995723625365e+00, 1.999824903632240414e+00, 2.001780722453083250e+00,
2.003738454055016494e+00, 2.005698100308730414e+00, 2.007659663086745372e+00,
2.009623144263412708e+00, 2.011588545714916076e+00, 2.013555869319274994e+00,
2.015525116956345730e+00, 2.017496290507822643e+00, 2.019469391857240392e+00,
2.021444422889975279e+00, 2.023421385493248792e+00, 2.025400281556126725e+00,
2.027381112969523613e+00, 2.029363881626201849e+00, 2.031348589420776563e+00,
2.033335238249714294e+00, 2.035323830011336987e+00, 2.037314366605823768e+00,
2.039306849935211385e+00, 2.041301281903396436e+00, 2.043297664416138471e+00,
2.045295999381059993e+00, 2.047296288707649570e+00, 2.049298534307263164e+00,
2.051302738093126798e+00, 2.053308901980336110e+00, 2.055317027885860792e+00,
2.057327117728544597e+00, 2.059339173429108882e+00, 2.061353196910152619e+00,
2.063369190096155492e+00, 2.065387154913478795e+00, 2.067407093290368536e+00,
2.069429007156956324e+00, 2.071452898445260704e+00, 2.073478769089190710e+00,
2.075506621024545861e+00, 2.077536456189019720e+00, 2.079568276522200776e+00,
2.081602083965573780e+00, 2.083637880462522407e+00, 2.085675667958331481e+00,
2.087715448400187856e+00, 2.089757223737183089e+00, 2.091800995920314765e+00,
2.093846766902488277e+00, 2.095894538638519045e+00, 2.097944313085134738e+00,
2.099996092200975717e+00, 2.102049877946599477e+00, 2.104105672284479311e+00,
2.106163477179008314e+00, 2.108223294596501596e+00, 2.110285126505196285e+00,
2.112348974875254637e+00, 2.114414841678765811e+00, 2.116482728889747644e+00,
2.118552638484149320e+00, 2.120624572439850919e+00, 2.122698532736667865e+00,
2.124774521356352253e+00, 2.126852540282593296e+00, 2.128932591501020877e+00,
2.131014676999206436e+00, 2.133098798766665638e+00, 2.135184958794859700e+00,
2.137273159077198059e+00, 2.139363401609037929e+00, 2.141455688387690071e+00,
2.143550021412417461e+00, 2.145646402684438847e+00, 2.147744834206929632e+00,
2.149845317985024540e+00, 2.151947856025819394e+00, 2.154052450338372893e+00,
2.156159102933708827e+00, 2.158267815824817415e+00, 2.160378591026657524e+00,
2.162491430556158889e+00, 2.164606336432223888e+00, 2.166723310675729319e+00,
2.168842355309527736e+00, 2.170963472358450552e+00, 2.173086663849310263e+00,
2.175211931810900001e+00, 2.177339278273997980e+00, 2.179468705271368378e+00,
2.181600214837763563e+00, 2.183733809009925864e+00, 2.185869489826588907e+00,
2.188007259328480725e+00, 2.190147119558325084e+00, 2.192289072560843710e+00,
2.194433120382758062e+00, 2.196579265072790665e+00, 2.198727508681668219e+00,
2.200877853262122930e+00, 2.203030300868894731e+00, 2.205184853558733060e+00,
2.207341513390398191e+00, 2.209500282424664785e+00, 2.211661162724322338e+00,
2.213824156354178285e+00, 2.215989265381058448e+00, 2.218156491873810587e+00,
2.220325837903306176e+00, 2.222497305542441737e+00, 2.224670896866141057e+00,
2.226846613951356524e+00, 2.229024458877072234e+00, 2.231204433724306213e+00,
2.233386540576111301e+00, 2.235570781517576489e+00, 2.237757158635831800e+00,
2.239945674020046962e+00, 2.242136329761435398e+00, 2.244329127953256009e+00,
2.246524070690814501e+00, 2.248721160071466496e+00, 2.250920398194617533e+00,
2.253121787161727507e+00, 2.255325329076311114e+00, 2.257531026043940514e+00,
2.259738880172246223e+00, 2.261948893570921104e+00, 2.264161068351720818e+00,
2.266375406628466482e+00, 2.268591910517046006e+00, 2.270810582135417199e+00,
2.273031423603609102e+00, 2.275254437043724209e+00, 2.277479624579939799e+00,
2.279706988338511042e+00, 2.281936530447773226e+00, 2.284168253038142193e+00,
2.286402158242117455e+00, 2.288638248194284408e+00, 2.290876525031316113e+00,
2.293116990891975071e+00, 2.295359647917114998e+00, 2.297604498249684379e+00,
2.299851544034726469e+00, 2.302100787419383732e+00, 2.304352230552896952e+00,
2.306605875586610122e+00, 2.308861724673969995e+00, 2.311119779970530974e+00,
2.313380043633953775e+00, 2.315642517824010760e+00, 2.317907204702585933e+00,
2.320174106433678052e+00, 2.322443225183401072e+00, 2.324714563119988586e+00,
2.326988122413794269e+00, 2.329263905237294541e+00, 2.331541913765090346e+00,
2.333822150173909371e+00, 2.336104616642608711e+00, 2.338389315352174869e+00,
2.340676248485729083e+00, 2.342965418228526886e+00, 2.345256826767960323e+00,
2.347550476293561950e+00, 2.349846368997005275e+00, 2.352144507072106983e+00,
2.354444892714828708e+00, 2.356747528123281477e+00, 2.359052415497723931e+00,
2.361359557040568546e+00, 2.363668954956380297e+00, 2.365980611451881099e+00,
2.368294528735950255e+00, 2.370610709019628004e+00, 2.372929154516116412e+00,
2.375249867440782925e+00, 2.377572850011160810e+00, 2.379898104446951823e+00,
2.382225632970029761e+00, 2.384555437804440015e+00, 2.386887521176404459e+00,
2.389221885314321003e+00, 2.391558532448767593e+00, 2.393897464812503539e+00,
2.396238684640471295e+00, 2.398582194169800452e+00, 2.400927995639806412e+00,
2.403276091291996597e+00, 2.405626483370069568e+00, 2.407979174119918575e+00,
2.410334165789632888e+00, 2.412691460629500906e+00, 2.415051060892011492e+00,
2.417412968831856190e+00, 2.419777186705932781e+00, 2.422143716773345279e+00,
2.424512561295406599e+00, 2.426883722535642551e+00, 2.429257202759791401e+00,
2.431633004235808748e+00, 2.434011129233866644e+00, 2.436391580026358472e+00,
2.438774358887899840e+00, 2.441159468095329910e+00, 2.443546909927716282e+00,
2.445936686666354110e+00, 2.448328800594770094e+00, 2.450723253998724260e+00,
2.453120049166212180e+00, 2.455519188387466745e+00, 2.457920673954961277e+00,
2.460324508163410417e+00, 2.462730693309773233e+00, 2.465139231693255883e+00,
2.467550125615311618e+00, 2.469963377379646552e+00, 2.472378989292218332e+00,
2.474796963661240135e+00, 2.477217302797182441e+00, 2.479640009012775703e+00,
2.482065084623012119e+00, 2.484492531945147409e+00, 2.486922353298704813e+00,
2.489354551005475091e+00, 2.491789127389519631e+00, 2.494226084777173114e+00,
2.496665425497044843e+00, 2.499107151880022748e+00, 2.501551266259272488e+00,
2.503997770970243231e+00, 2.506446668350667206e+00, 2.508897960740563704e+00,
2.511351650482239517e+00, 2.513807739920292939e+00, 2.516266231401615538e+00,
2.518727127275393052e+00, 2.521190429893109819e+00, 2.523656141608549230e+00,
2.526124264777797279e+00, 2.528594801759243005e+00, 2.531067754913583379e+00,
2.533543126603823303e+00, 2.536020919195279166e+00, 2.538501135055579727e+00,
2.540983776554670559e+00, 2.543468846064813604e+00, 2.545956345960592504e+00,
2.548446278618911709e+00, 2.550938646419000921e+00, 2.553433451742416871e+00,
2.555930696973045091e+00, 2.558430384497103027e+00, 2.560932516703141371e+00,
2.563437095982046721e+00, 2.565944124727044251e+00, 2.568453605333699930e+00,
2.570965540199921850e+00, 2.573479931725964232e+00, 2.575996782314427858e+00,
2.578516094370263190e+00, 2.581037870300773918e+00, 2.583562112515616516e+00,
2.586088823426805128e+00, 2.588618005448712456e+00, 2.591149660998072424e+00,
2.593683792493982843e+00, 2.596220402357906742e+00, 2.598759493013676369e+00,
2.601301066887493185e+00, 2.603845126407932309e+00, 2.606391674005943848e+00,
2.608940712114855121e+00, 2.611492243170373762e+00, 2.614046269610588613e+00,
2.616602793875974164e+00, 2.619161818409390996e+00, 2.621723345656088444e+00,
2.624287378063707266e+00, 2.626853918082283634e+00, 2.629422968164247365e+00,
2.631994530764428575e+00, 2.634568608340057683e+00, 2.637145203350768075e+00,
2.639724318258598323e+00, 2.642305955527996186e+00, 2.644890117625817716e+00,
2.647476807021333478e+00, 2.650066026186227663e+00, 2.652657777594602084e+00,
2.655252063722977951e+00, 2.657848887050299869e+00, 2.660448250057934949e+00,
2.663050155229678140e+00, 2.665654605051753112e+00, 2.668261602012815370e+00,
2.670871148603954914e+00, 2.673483247318696243e+00, 2.676097900653003681e+00,
2.678715111105283153e+00, 2.681334881176383078e+00, 2.683957213369597472e+00,
2.686582110190669503e+00, 2.689209574147792381e+00, 2.691839607751612018e+00,
2.694472213515231029e+00, 2.697107393954207843e+00, 2.699745151586563363e+00,
2.702385488932778745e+00, 2.705028408515801619e+00, 2.707673912861047416e+00,
2.710322004496400261e+00, 2.712972685952216967e+00, 2.715625959761328811e+00,
2.718281828459045091e+00
};
template<typename Scalar>
static inline Scalar fast_exp(Scalar x) {
if (x < 0)
return 1/fast_exp(-x);
if (x > 100)
return std::exp(x);
int cnt = 0;
while (x >= 1) {
x = x/2;
cnt++;
}
x = exp_lut[static_cast<int>(x*1024)];
while (cnt-- > 0) {
x *= x;
}
return x;
}
/**
* @brief This function is used for the calculation of the digamma function,
* which is the logarithmic derivative of the Gamma Function. The digamma
* function is computable via Taylor approximations (Abramowitz and Stegun,
* 1970)
**/
template <typename Scalar>
static inline Scalar digamma(Scalar x) {
Scalar result = 0, xx, xx2, xx4;
for (; x < 7; ++x) {
result -= 1/x;
}
x -= 1.0/2.0;
xx = 1.0/x;
xx2 = xx*xx;
xx4 = xx2*xx2;
result += std::log(x)+(1./24.)*xx2-(7.0/960.0)*xx4+(31.0/8064.0)*xx4*xx2-(127.0/30720.0)*xx4*xx4;
return result;
}
template <typename Scalar>
struct CwiseDigamma
{
const Scalar operator()(const Scalar &x) const {
return digamma(x);
}
};
template <typename Scalar>
struct CwiseLgamma
{
const Scalar operator()(const Scalar &x) const {
return std::lgamma(x);
}
};
template <typename Scalar>
struct CwiseFastExp
{
const Scalar operator()(const Scalar &x) const {
return fast_exp(x);
}
};
template <typename Scalar>
struct CwiseIsNaN
{
const bool operator()(const Scalar &x) const {
return std::isnan(x);
}
};
template <typename Scalar>
struct CwiseIsInf
{
const bool operator()(const Scalar &x) const {
return std::isinf(x);
}
};
template <typename Scalar>
struct CwiseScalarDivideByMatrix
{
CwiseScalarDivideByMatrix(Scalar y) : y_(y) {}
const Scalar operator()(const Scalar &x) const {
if (x != 0)
return y_ / x;
return 0;
}
Scalar y_;
};
/**
* Reshape a matrix into a vector by copying the matrix into the vector in a
* way to avoid errors by Eigen expressions.
*/
template <typename Scalar>
void reshape_into(
const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> &src,
Eigen::Matrix<Scalar, Eigen::Dynamic, 1> &dst
) {
size_t srcR = src.rows();
size_t srcC = src.cols();
for (int c=0; c<srcC; c++) {
dst.segment(c*srcR, srcR) = src.col(c);
}
}
/**
* Reshape a vector into a matrix by copying the vector into the matrix in a
* way to avoid errors by Eigen expressions.
*/
template <typename Scalar>
void reshape_into(
const Eigen::Matrix<Scalar, Eigen::Dynamic, 1> &src,
Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> &dst
) {
size_t dstR = dst.rows();
size_t dstC = dst.cols();
for (int c=0; c<dstC; c++) {
dst.col(c) = src.segment(c*dstR, dstR);
}
}
/**
* Normalize in place a matrix of row vectors so that they sum to 1. Avoid NaN
* by checking for 0 explicitly.
*/
template <typename Derived>
void normalize_rows(Eigen::DenseBase<Derived> &x) {
typename Eigen::DenseBase<Derived>::Scalar s;
for (int i=0; i<x.rows(); i++) {
s = x.row(i).sum();
if (s != 0) {
x.row(i).array() /= s;
}
}
}
/**
* Normalize in place a matrix of column vectors so that they sum to 1. Avoid
* NaN by checking for 0 explicitly.
*/
template <typename Derived>
void normalize_cols(Eigen::DenseBase<Derived> &x) {
typename Eigen::DenseBase<Derived>::Scalar s;
for (int i=0; i<x.cols(); i++) {
s = x.col(i).sum();
if (s != 0) {
x.col(i).array() /= s;
}
}
}
/**
* Compute the product ignoring zeros.
*/
template <typename Derived>
typename Eigen::DenseBase<Derived>::Scalar product_of_nonzeros(
const Eigen::DenseBase<Derived> &x
) {
typename Eigen::DenseBase<Derived>::Scalar p = 1;
for (int j=0; j<x.cols(); j++) {
for (int i=0; i<x.rows(); i++) {
if (x(i, j) != 0)
p *= x(i, j);
}
}
return p;
}
/**
* Sum the rows scaled by another vector
*/
template <typename Derived1, typename Derived2, typename Derived3>
void sum_rows_scaled(
const Eigen::MatrixBase<Derived1> & x,
const Eigen::MatrixBase<Derived2> & y,
Eigen::MatrixBase<Derived3> & result
) {
for (int i=0; i<x.rows(); i++) {
// this is done so that the multiplication can never result in NaN
if (y[i] == 0)
continue;
result += y[i] * x.row(i);
}
}
/**
* Sum the cols scaled by another vector
*/
template <typename Derived1, typename Derived2, typename Derived3>
void sum_cols_scaled(
const Eigen::MatrixBase<Derived1> & x,
const Eigen::MatrixBase<Derived2> & y,
Eigen::MatrixBase<Derived3> & result
) {
for (int i=0; i<x.cols(); i++) {
// this is done so that the multiplication can never result in NaN
if (y[i] == 0)
continue;
result += y[i] * x.col(i);
}
}
/**
* Wrap a PRNG with this class in order to be able to pass it around even
* to other threads and protect its internal state from being corrupted.
*
* see UniformRandomBitGenerator C++ concept
* http://en.cppreference.com/w/cpp/concept/UniformRandomBitGenerator
*/
template <typename PRNG>
class ThreadSafePRNG
{
public:
typedef typename PRNG::result_type result_type;
static constexpr result_type min() { return PRNG::min(); }
static constexpr result_type max() { return PRNG::max(); }
ThreadSafePRNG(int random_state) {
prng_mutex_ = std::make_shared<std::mutex>();
prng_ = std::make_shared<PRNG>(random_state);
}
result_type operator()() {
std::lock_guard<std::mutex> lock(*prng_mutex_);
return (*prng_)();
}
private:
std::shared_ptr<std::mutex> prng_mutex_;
std::shared_ptr<PRNG> prng_;
};
} // namespace math_utils
} // namespace ldaplusplus
#endif // _LDAPLUSPLUS_UTILS_HPP_
| 55.022508 | 101 | 0.769314 | angeloskath |
ab7b47f17b3292e2937294b990f633b91ff24918 | 1,571 | cpp | C++ | lib/smooth/application/network/mqtt/packet/Unsubscribe.cpp | luuvt/lms | 8f53ddeb62e9ca328acb36b922bf72e223ff3753 | [
"Apache-2.0"
] | 283 | 2017-07-18T15:31:42.000Z | 2022-03-30T12:05:03.000Z | lib/smooth/application/network/mqtt/packet/Unsubscribe.cpp | luuvt/lms | 8f53ddeb62e9ca328acb36b922bf72e223ff3753 | [
"Apache-2.0"
] | 131 | 2017-08-23T18:49:03.000Z | 2021-11-29T08:03:21.000Z | lib/smooth/application/network/mqtt/packet/Unsubscribe.cpp | luuvt/lms | 8f53ddeb62e9ca328acb36b922bf72e223ff3753 | [
"Apache-2.0"
] | 53 | 2017-12-31T13:34:21.000Z | 2022-02-04T11:26:49.000Z | /*
Smooth - A C++ framework for embedded programming on top of Espressif's ESP-IDF
Copyright 2019 Per Malmberg (https://gitbub.com/PerMalmberg)
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 "smooth/application/network/mqtt/packet/Unsubscribe.h"
#include "smooth/core/util/advance_iterator.h"
#include "smooth/application/network/mqtt/packet/IPacketReceiver.h"
namespace smooth::application::network::mqtt::packet
{
void Unsubscribe::visit(IPacketReceiver& receiver)
{
receiver.receive(*this);
}
void Unsubscribe::get_topics(std::vector<std::string>& topics) const
{
calculate_remaining_length_and_variable_header_offset();
auto it = get_variable_header_start() + get_variable_header_length();
bool end_reached = false;
do
{
auto s = get_string(it);
topics.push_back(s);
// Move to next string, add two for the length bits
end_reached = !core::util::advance(it, data.end(), s.length() + 2);
}
while (!end_reached && it != data.end());
}
}
| 33.425532 | 79 | 0.703374 | luuvt |
ab7db0307bab208d8d6bca73577fbe6623747b1b | 1,324 | cpp | C++ | Graph/Special Graph (Directed Acyclic Graph)/Counting Paths in DAG/Checkers.cpp | satvik007/uva | 72a763f7ed46a34abfcf23891300d68581adeb44 | [
"MIT"
] | 3 | 2017-08-12T06:09:39.000Z | 2018-09-16T02:31:27.000Z | Graph/Special Graph (Directed Acyclic Graph)/Counting Paths in DAG/Checkers.cpp | satvik007/uva | 72a763f7ed46a34abfcf23891300d68581adeb44 | [
"MIT"
] | null | null | null | Graph/Special Graph (Directed Acyclic Graph)/Counting Paths in DAG/Checkers.cpp | satvik007/uva | 72a763f7ed46a34abfcf23891300d68581adeb44 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector <int> vi;
#define inf (int)1e9
#define modulo (ll)1000007
int tc, n, fx, fy;
vector <string> a;
ll memo[105][105];
ll solve(int x, int y){
if(x == 0) return 1;
if(memo[x][y] != -1) return memo[x][y];
ll ans = 0;
if(y > 0){
if(a[x-1][y-1] == '.') ans += solve(x-1, y-1);
else if(x > 1 && y > 1 && a[x-2][y-2] == '.') ans += solve(x-2, y-2);
}
if(y < n-1){
if(a[x-1][y+1] == '.') ans += solve(x-1, y+1);
else if(x > 1 && y < n-2 && a[x-2][y+2] == '.') ans += solve(x-2, y+2);
}
return memo[x][y] = ans %= modulo;;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
cin >> tc;
int cas = 1;
while(tc--){
memset(memo, -1, sizeof memo);
cin >> n; a.resize(n);
for(int i=0; i<n; i++) cin >> a[i];
int flag = 0;
for(int i=0; i<n && !flag; i++) {
for(int j=0; j<n; j++){
if(a[i][j] == 'W') {
fx = i; fy = j; flag = 1; break;
}
}
}
ll ans = solve(fx, fy);
cout << "Case " << cas++ << ": " << (ans % modulo) << "\n";
}
return 0;
} | 26.48 | 79 | 0.428248 | satvik007 |
ab7e18d51f9318cccc2a369994175e31d0a50100 | 6,819 | cpp | C++ | src/scrollbar/cocScrollbar.cpp | codeoncanvas/coc-ui | d1b6389adba5234254665c07382a028716016dce | [
"MIT"
] | 1 | 2018-01-08T21:37:42.000Z | 2018-01-08T21:37:42.000Z | src/scrollbar/cocScrollbar.cpp | codeoncanvas/coc-ui | d1b6389adba5234254665c07382a028716016dce | [
"MIT"
] | null | null | null | src/scrollbar/cocScrollbar.cpp | codeoncanvas/coc-ui | d1b6389adba5234254665c07382a028716016dce | [
"MIT"
] | 1 | 2020-04-21T00:30:27.000Z | 2020-04-21T00:30:27.000Z | /**
*
* ┌─┐╔═╗┌┬┐┌─┐
* │ ║ ║ ││├┤
* └─┘╚═╝─┴┘└─┘
* ┌─┐┌─┐╔╗╔┬ ┬┌─┐┌─┐
* │ ├─┤║║║└┐┌┘├─┤└─┐
* └─┘┴ ┴╝╚╝ └┘ ┴ ┴└─┘
*
* Copyright (c) 2014-2016 Code on Canvas Pty Ltd, http://CodeOnCanvas.cc
*
* This software is distributed under the MIT license
* https://tldrlegal.com/license/mit-license
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code
*
**/
#include "cocScrollbar.h"
namespace coc {
//--------------------------------------------------------------
Scrollbar::Scrollbar():
type(Type::Vertical),
position(0.0),
contentRatio(0.5),
ease(0.0),
thumbOffset(0.0),
bThumbPressed(false),
bPositionChangeInternal(false),
bPositionChangeExternal(false) {
//
}
Scrollbar::~Scrollbar() {
//
}
//--------------------------------------------------------------
ScrollbarRef Scrollbar::create() {
ScrollbarRef scrollbar = ScrollbarRef(new Scrollbar());
scrollbar->setup();
return scrollbar;
}
void Scrollbar::setup() {
track = initButton();
thumb = initButton();
}
//--------------------------------------------------------------
void Scrollbar::setType(coc::Scrollbar::Type value) {
type = value;
}
coc::Scrollbar::Type Scrollbar::getType() const {
return type;
}
//--------------------------------------------------------------
void Scrollbar::setRect(coc::Rect value) {
rect = value;
}
const coc::Rect & Scrollbar::getRect() const {
return rect;
}
//--------------------------------------------------------------
void Scrollbar::setContentRatio(float value) {
contentRatio = value;
}
float Scrollbar::getContentRatio() const {
return contentRatio;
}
//--------------------------------------------------------------
void Scrollbar::setThumbOffset(float value) {
thumbOffset = value;
}
float Scrollbar::getThumbOffset() const {
return thumbOffset;
}
//--------------------------------------------------------------
void Scrollbar::setEase(float value) {
ease = value;
}
float Scrollbar::getEase() const {
return ease;
}
//--------------------------------------------------------------
void Scrollbar::setPosition(float value) {
bPositionChangeExternal = (position != value);
position = value;
}
float Scrollbar::getPosition() const {
return position;
}
//--------------------------------------------------------------
void Scrollbar::setEnabled(bool value) {
track->setEnabled(value);
thumb->setEnabled(value);
}
//--------------------------------------------------------------
void Scrollbar::update() {
bPositionChangeInternal = false;
const coc::Rect & trackRect = rect;
coc::Rect thumbRect = trackRect;
if(type == Type::Vertical) {
float trackRectY = trackRect.getY();
float trackRectH = trackRect.getH();
float thumbRectH = trackRectH * contentRatio;
float thumbRectY = coc::map(position, 0.0, 1.0, trackRectY - thumbOffset, trackRectY + trackRectH - thumbRectH + thumbOffset, true);
thumbRect.setH(thumbRectH);
thumbRect.setY(thumbRectY);
} else if(type == Type::Horizontal) {
float trackRectX = trackRect.getX();
float trackRectW = trackRect.getW();
float thumbRectW = trackRectW * contentRatio;
float thumbRectX = coc::map(position, 0.0, 1.0, trackRectX - thumbOffset, trackRectX + trackRectW - thumbRectW + thumbOffset, true);
thumbRect.setW(thumbRectW);
thumbRect.setX(thumbRectX);
}
track->setRect(trackRect);
track->update();
thumb->setRect(thumbRect);
thumb->update();
if(thumb->pressedInside()) {
track->reset(); // when thumb is pressed, cancel events going down to the track.
thumbPressStartPos.x = thumb->getRect().getX();
thumbPressStartPos.y = thumb->getRect().getY();
thumbPressInsidePos = thumb->getPointPosLast();
bThumbPressed = true;
} else if(thumb->releasedInside() || thumb->releasedOutside()) {
bThumbPressed = false;
}
bool bTrackPressed = track->pressedInside();
bool bUpdateThumbPos = false;
bUpdateThumbPos = bUpdateThumbPos || bThumbPressed;
bUpdateThumbPos = bUpdateThumbPos || bTrackPressed;
if(bUpdateThumbPos) {
const glm::ivec2 & thumbPressPos = thumb->getPointPosLast();
const glm::ivec2 & trackPressPos = track->getPointPosLast();
coc::Rect thumbRect = thumb->getRect();
int thumbMin = 0;
int thumbMax = 0;
int thumbDrag = 0;
int thumbPos = 0;
float thumbPosNorm = 0;
if(type == coc::Scrollbar::Type::Vertical) {
if(bThumbPressed) {
thumbDrag = thumbPressPos.y - thumbPressInsidePos.y;
thumbPos = thumbPressStartPos.y + thumbDrag;
} else if(bTrackPressed) {
thumbPos = trackPressPos.y - (thumbRect.getH() * 0.5);
}
thumbMin = trackRect.getY();
thumbMax = thumbMin + trackRect.getH() - thumbRect.getH();
thumbPosNorm = coc::map(thumbPos, thumbMin, thumbMax, 0.0, 1.0, true);
thumbPos = coc::map(thumbPosNorm, 0.0, 1.0, thumbMin - thumbOffset, thumbMax + thumbOffset);
thumbRect.setY(thumbPos);
} else if(type == coc::Scrollbar::Type::Horizontal) {
if(bThumbPressed) {
thumbDrag = thumbPressPos.x - thumbPressInsidePos.x;
thumbPos = thumbPressStartPos.x + thumbDrag;
} else if(bTrackPressed) {
thumbPos = trackPressPos.x - (thumbRect.getW() * 0.5);
}
thumbMin = trackRect.getX();
thumbMax = thumbMin + trackRect.getW() - thumbRect.getW();
thumbPosNorm = coc::map(thumbPos, thumbMin, thumbMax, 0.0, 1.0, true);
thumbPos = coc::map(thumbPosNorm, 0.0, 1.0, thumbMin - thumbOffset, thumbMax + thumbOffset);
thumbRect.setX(thumbPos);
}
bPositionChangeInternal = (position != thumbPosNorm);
position = thumbPosNorm;
thumb->setRect(thumbRect);
}
bPositionChangeExternal = false;
}
//--------------------------------------------------------------
void Scrollbar::pointMoved(int x, int y) {
track->pointMoved(x, y);
thumb->pointMoved(x, y);
}
void Scrollbar::pointPressed(int x, int y) {
track->pointPressed(x, y);
thumb->pointPressed(x, y);
}
void Scrollbar::pointDragged(int x, int y) {
track->pointDragged(x, y);
thumb->pointDragged(x, y);
}
void Scrollbar::pointReleased(int x, int y) {
track->pointReleased(x, y);
thumb->pointReleased(x, y);
}
}
| 28.294606 | 140 | 0.543335 | codeoncanvas |
ab7e6cf53dd6368599e33d356bbb80ea1cd4afe1 | 18,144 | cc | C++ | lib/chmpx.cc | ggtakec/chmpx | 2b4e9c4c32b9c82a8b7e1d5805915414ae782a29 | [
"MIT"
] | 16 | 2016-12-09T01:44:45.000Z | 2020-09-11T04:54:02.000Z | lib/chmpx.cc | ggtakec/chmpx | 2b4e9c4c32b9c82a8b7e1d5805915414ae782a29 | [
"MIT"
] | 2 | 2016-12-09T05:42:18.000Z | 2018-12-27T03:54:00.000Z | lib/chmpx.cc | ggtakec/chmpx | 2b4e9c4c32b9c82a8b7e1d5805915414ae782a29 | [
"MIT"
] | 6 | 2016-12-09T01:48:40.000Z | 2020-12-22T03:13:13.000Z | /*
* CHMPX
*
* Copyright 2014 Yahoo Japan Corporation.
*
* CHMPX is inprocess data exchange by MQ with consistent hashing.
* CHMPX is made for the purpose of the construction of
* original messaging system and the offer of the client
* library.
* CHMPX transfers messages between the client and the server/
* slave. CHMPX based servers are dispersed by consistent
* hashing and are automatically laid out. As a result, it
* provides a high performance, a high scalability.
*
* For the full copyright and license information, please view
* the license file that was distributed with this source code.
*
* AUTHOR: Takeshi Nakatani
* CREATE: Tue July 1 2014
* REVISION:
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <k2hash/k2hashfunc.h>
#include "chmcommon.h"
#include "chmutil.h"
#include "chmdbg.h"
#include "chmhash.h"
#include "chmcntrl.h"
#include "chmkvp.h"
#include "chmpx.h"
#include "chmss.h"
using namespace std;
//---------------------------------------------------------
// Functions - Debug
//---------------------------------------------------------
void chmpx_bump_debug_level(void)
{
::BumpupChmDbgMode();
}
void chmpx_set_debug_level_silent(void)
{
::SetChmDbgMode(CHMDBG_SILENT);
}
void chmpx_set_debug_level_error(void)
{
::SetChmDbgMode(CHMDBG_ERR);
}
void chmpx_set_debug_level_warning(void)
{
::SetChmDbgMode(CHMDBG_WARN);
}
void chmpx_set_debug_level_message(void)
{
::SetChmDbgMode(CHMDBG_MSG);
}
void chmpx_set_debug_level_dump(void)
{
::SetChmDbgMode(CHMDBG_DUMP);
}
bool chmpx_set_debug_file(const char* filepath)
{
bool result;
if(CHMEMPTYSTR(filepath)){
result = ::UnsetChmDbgFile();
}else{
result = ::SetChmDbgFile(filepath);
}
return result;
}
bool chmpx_unset_debug_file(void)
{
return ::UnsetChmDbgFile();
}
bool chmpx_load_debug_env(void)
{
return ::LoadChmDbgEnv();
}
//---------------------------------------------------------
// Functions - Load hash library
//---------------------------------------------------------
bool chmpx_load_hash_library(const char* libpath)
{
return ::k2h_load_hash_library(libpath);
}
bool chmpx_unload_hash_library(void)
{
return ::k2h_unload_hash_library();
}
//---------------------------------------------------------
// Functions - Create/Destroy
//---------------------------------------------------------
chmpx_h chmpx_create_ex(const char* conffile, bool is_on_server, bool is_auto_rejoin, chm_merge_get_cb getfp, chm_merge_set_cb setfp, chm_merge_lastts_cb lastupdatefp)
{
if(CHMEMPTYSTR(conffile)){
ERR_CHMPRN("Configuration file path is empty.");
return CHM_INVALID_CHMPXHANDLE;
}
ChmCntrl* pCntrlObj = new ChmCntrl();
bool result;
if(is_on_server){
result = pCntrlObj->InitializeOnServer(conffile, is_auto_rejoin, getfp, setfp, lastupdatefp);
}else{
result = pCntrlObj->InitializeOnSlave(conffile, is_auto_rejoin);
}
if(!result){
return CHM_INVALID_CHMPXHANDLE;
}
return reinterpret_cast<chmpx_h>(pCntrlObj);
}
chmpx_h chmpx_create(const char* conffile, bool is_on_server, bool is_auto_rejoin)
{
return chmpx_create_ex(conffile, is_on_server, is_auto_rejoin, NULL, NULL, NULL);
}
bool chmpx_destroy(chmpx_h handle)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
CHM_Delete(pCntrlObj);
return true;
}
bool chmpx_pkth_destroy(chmpx_pkt_h pckthandle)
{
PCOMPKT pComPkt = reinterpret_cast<PCOMPKT>(pckthandle);
if(!pComPkt){
return false;
}
CHM_Free(pComPkt);
return true;
}
//---------------------------------------------------------
// Functions - Send/Receive for server side
//---------------------------------------------------------
bool chmpx_svr_send(chmpx_h handle, const unsigned char* pbody, size_t blength, chmhash_t hash, bool is_routing)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
return pCntrlObj->Send(pbody, blength, hash, is_routing);
}
bool chmpx_svr_send_kvp(chmpx_h handle, const PCHMKVP pkvp, bool is_routing)
{
return chmpx_svr_send_kvp_ex(handle, pkvp, is_routing, false);
}
bool chmpx_svr_send_kvp_ex(chmpx_h handle, const PCHMKVP pkvp, bool is_routing, bool without_self)
{
if(!pkvp){
ERR_CHMPRN("CHMKVP is NULL.");
return false;
}
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
ChmKVPair kvpair(pkvp, false);
unsigned char* pbody;
size_t length = 0L;
if(NULL == (pbody = kvpair.Put(length))){
ERR_CHMPRN("Could not convert CHMKVP to Object.");
return false;
}
chmhash_t hash = kvpair.GetHash();
bool result = pCntrlObj->Send(pbody, length, hash, is_routing, without_self);
CHM_Free(pbody);
return result;
}
bool chmpx_svr_send_kv(chmpx_h handle, unsigned char* pkey, size_t keylen, unsigned char* pval, size_t vallen, bool is_routing)
{
return chmpx_svr_send_kv_ex(handle, pkey, keylen, pval, vallen, is_routing, false);
}
bool chmpx_svr_send_kv_ex(chmpx_h handle, unsigned char* pkey, size_t keylen, unsigned char* pval, size_t vallen, bool is_routing, bool without_self)
{
if(!pkey || 0L == keylen){
ERR_CHMPRN("Key is invalid.");
return false;
}
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
ChmKVPair kvpair(pkey, keylen, pval, vallen);
unsigned char* pbody;
size_t length = 0L;
if(NULL == (pbody = kvpair.Put(length))){
ERR_CHMPRN("Could not convert CHMKVP to Object.");
return false;
}
chmhash_t hash = kvpair.GetHash();
bool result = pCntrlObj->Send(pbody, length, hash, is_routing, without_self);
CHM_Free(pbody);
return result;
}
bool chmpx_svr_broadcast(chmpx_h handle, const unsigned char* pbody, size_t blength, chmhash_t hash)
{
return chmpx_svr_broadcast_ex(handle, pbody, blength, hash, false);
}
bool chmpx_svr_broadcast_ex(chmpx_h handle, const unsigned char* pbody, size_t blength, chmhash_t hash, bool without_self)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
return pCntrlObj->Broadcast(pbody, blength, hash, without_self);
}
bool chmpx_svr_replicate(chmpx_h handle, const unsigned char* pbody, size_t blength, chmhash_t hash)
{
return chmpx_svr_replicate_ex(handle, pbody, blength, hash, true); // default: without self
}
bool chmpx_svr_replicate_ex(chmpx_h handle, const unsigned char* pbody, size_t blength, chmhash_t hash, bool without_self)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
return pCntrlObj->Replicate(pbody, blength, hash, without_self);
}
bool chmpx_svr_receive(chmpx_h handle, chmpx_pkt_h* ppckthandle, unsigned char** ppbody, size_t* plength, int timeout_ms, bool no_giveup_rejoin)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
PCOMPKT* ppComPkt = reinterpret_cast<PCOMPKT*>(ppckthandle);
if(!ppComPkt){
ERR_CHMPRN("Invalid packet handle pointer.");
return false;
}
return pCntrlObj->Receive(ppComPkt, ppbody, plength, timeout_ms, no_giveup_rejoin);
}
//---------------------------------------------------------
// Functions - Send/Receive for slave side
//---------------------------------------------------------
msgid_t chmpx_open(chmpx_h handle, bool no_giveup_rejoin)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return CHM_INVALID_MSGID;
}
return pCntrlObj->Open(no_giveup_rejoin);
}
bool chmpx_close(chmpx_h handle, msgid_t msgid)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
return pCntrlObj->Close(msgid);
}
bool chmpx_msg_send(chmpx_h handle, msgid_t msgid, const unsigned char* pbody, size_t blength, chmhash_t hash, long* preceivercnt, bool is_routing)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
return pCntrlObj->Send(msgid, pbody, blength, hash, preceivercnt, is_routing);
}
bool chmpx_msg_send_kvp(chmpx_h handle, msgid_t msgid, const PCHMKVP pkvp, long* preceivercnt, bool is_routing)
{
if(!pkvp){
ERR_CHMPRN("CHMKVP is NULL.");
return false;
}
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
ChmKVPair kvpair(pkvp, false);
unsigned char* pbody;
size_t length = 0L;
if(NULL == (pbody = kvpair.Put(length))){
ERR_CHMPRN("Could not convert CHMKVP to Object.");
return false;
}
chmhash_t hash = kvpair.GetHash();
bool result = pCntrlObj->Send(msgid, pbody, length, hash, preceivercnt, is_routing);
CHM_Free(pbody);
return result;
}
bool chmpx_msg_send_kv(chmpx_h handle, msgid_t msgid, unsigned char* pkey, size_t keylen, unsigned char* pval, size_t vallen, long* preceivercnt, bool is_routing)
{
if(!pkey || 0L == keylen){
ERR_CHMPRN("Key is invalid.");
return false;
}
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
ChmKVPair kvpair(pkey, keylen, pval, vallen);
unsigned char* pbody;
size_t length = 0L;
if(NULL == (pbody = kvpair.Put(length))){
ERR_CHMPRN("Could not convert CHMKVP to Object.");
return false;
}
chmhash_t hash = kvpair.GetHash();
bool result = pCntrlObj->Send(msgid, pbody, length, hash, preceivercnt, is_routing);
CHM_Free(pbody);
return result;
}
bool chmpx_msg_broadcast(chmpx_h handle, msgid_t msgid, const unsigned char* pbody, size_t blength, chmhash_t hash, long* preceivercnt)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
return pCntrlObj->Broadcast(msgid, pbody, blength, hash, preceivercnt);
}
bool chmpx_msg_replicate(chmpx_h handle, msgid_t msgid, const unsigned char* pbody, size_t blength, chmhash_t hash, long* preceivercnt)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
return pCntrlObj->Replicate(msgid, pbody, blength, hash, preceivercnt);
}
bool chmpx_msg_receive(chmpx_h handle, msgid_t msgid, chmpx_pkt_h* ppckthandle, unsigned char** ppbody, size_t* plength, int timeout_ms)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
PCOMPKT* ppComPkt = reinterpret_cast<PCOMPKT*>(ppckthandle);
if(!ppComPkt){
ERR_CHMPRN("Invalid packet handle pointer.");
return false;
}
return pCntrlObj->Receive(msgid, ppComPkt, ppbody, plength, timeout_ms);
}
//---------------------------------------------------------
// Functions - Reply for both server and slave side
//---------------------------------------------------------
bool chmpx_msg_reply(chmpx_h handle, chmpx_pkt_h pckthandle, const unsigned char* pbody, size_t blength)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
PCOMPKT pComPkt = reinterpret_cast<PCOMPKT>(pckthandle);
if(!pComPkt){
ERR_CHMPRN("Invalid packet handle.");
return false;
}
return pCntrlObj->Reply(pComPkt, pbody, blength);
}
bool chmpx_msg_reply_kvp(chmpx_h handle, chmpx_pkt_h pckthandle, const PCHMKVP pkvp)
{
if(!pkvp){
ERR_CHMPRN("CHMKVP is NULL.");
return false;
}
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
PCOMPKT pComPkt = reinterpret_cast<PCOMPKT>(pckthandle);
if(!pComPkt){
ERR_CHMPRN("Invalid packet handle.");
return false;
}
ChmKVPair kvpair(pkvp, false);
unsigned char* pbody;
size_t length = 0L;
if(NULL == (pbody = kvpair.Put(length))){
ERR_CHMPRN("Could not convert CHMKVP to Object.");
return false;
}
bool result = pCntrlObj->Reply(pComPkt, pbody, length);
CHM_Free(pbody);
return result;
}
bool chmpx_msg_reply_kv(chmpx_h handle, chmpx_pkt_h pckthandle, unsigned char* pkey, size_t keylen, unsigned char* pval, size_t vallen)
{
if(!pkey || 0L == keylen){
ERR_CHMPRN("Key is invalid.");
return false;
}
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
PCOMPKT pComPkt = reinterpret_cast<PCOMPKT>(pckthandle);
if(!pComPkt){
ERR_CHMPRN("Invalid packet handle.");
return false;
}
ChmKVPair kvpair(pkey, keylen, pval, vallen);
unsigned char* pbody;
size_t length = 0L;
if(NULL == (pbody = kvpair.Put(length))){
ERR_CHMPRN("Could not convert CHMKVP to Object.");
return false;
}
bool result = pCntrlObj->Reply(pComPkt, pbody, length);
CHM_Free(pbody);
return result;
}
//---------------------------------------------------------
// Functions - Chmpx Process exists
//---------------------------------------------------------
bool is_chmpx_proc_exists(chmpx_h handle)
{
ChmCntrl* pCntrlObj = reinterpret_cast<ChmCntrl*>(handle);
if(!pCntrlObj){
ERR_CHMPRN("Invalid chmpx handle.");
return false;
}
return !pCntrlObj->IsChmpxExit();
}
//---------------------------------------------------------
// Functions - Version
//---------------------------------------------------------
extern char chmpx_commit_hash[];
void chmpx_print_version(FILE* stream)
{
static const char format[] =
"\n"
"CHMPX Version %s (commit: %s) with %s\n"
"\n"
"Copyright(C) 2014 Yahoo Japan Corporation.\n"
"\n"
"CHMPX is inprocess data exchange by MQ with consistent hashing.\n"
"CHMPX is made for the purpose of the construction of original\n"
"messaging system and the offer of the client library. CHMPX\n"
"transfers messages between the client and the server/slave. CHMPX\n"
"based servers are dispersed by consistent hashing and are\n"
"automatically laid out. As a result, it provides a high performance,\n"
"a high scalability.\n"
"\n";
fprintf(stream, format, VERSION, chmpx_commit_hash, ChmSecureSock::LibraryName());
}
const char* chmpx_get_version(void)
{
static char stc_version[256];
static bool stc_init = false;
if(!stc_init){
sprintf(stc_version, "Version %s (commit: %s) with %s", VERSION, chmpx_commit_hash, ChmSecureSock::LibraryName());
stc_init = true;
}
return stc_version;
}
const char* chmpx_get_raw_version(bool is_commit_hash)
{
if(is_commit_hash){
return chmpx_commit_hash;
}else{
return VERSION;
}
}
// [NOTE]
// This function converts a version string (period-delimited decimal string) to 64-bit binary.
// For conversion, the decimal number of each part is digitized and converted into 64-bit
// binary in 16-bit units. In other words, the version string is in the range of '0' to
// '65535.65535.65535.65535'.
//
uint64_t chmpx_get_bin_version(void)
{
static uint64_t stc_bin_version = 0;
static bool stc_init = false;
if(!stc_init){
strlst_t strverarr;
if(str_split(VERSION, strverarr, '.', true)){
for(strlst_t::const_iterator iter = strverarr.begin(); strverarr.end() != iter; ++iter){
stc_bin_version *= 0x10000; // shift 16bit
stc_bin_version += cvt_string_to_number(iter->c_str(), true); // decimal
}
}
stc_init = true;
}
return stc_bin_version;
}
//---------------------------------------------------------
// Key Value Pair Utilities
//---------------------------------------------------------
unsigned char* cvt_kvp_bin(const PCHMKVP pkvp, size_t* plength)
{
if(!pkvp || !plength){
ERR_CHMPRN("Parameters are wrong.");
return NULL;
}
*plength = pkvp->key.length + pkvp->val.length + sizeof(size_t) * 2;
unsigned char* pResult;
if(NULL == (pResult = reinterpret_cast<unsigned char*>(malloc(*plength)))){
ERR_CHMPRN("Could not allocate memory.");
return NULL;
}
// set key
size_t setpos = 0;
size_t tmplen = htobe64(pkvp->key.length); // To network byte order
unsigned char* bylen = reinterpret_cast<unsigned char*>(&tmplen);
for(size_t cnt = 0; cnt < sizeof(size_t); ++cnt){
// cppcheck-suppress unmatchedSuppression
// cppcheck-suppress objectIndex
pResult[setpos++] = bylen[cnt];
}
if(0 < pkvp->key.length){
memcpy(&pResult[setpos], pkvp->key.byptr, pkvp->key.length);
setpos += pkvp->key.length;
}
// set value
tmplen = htobe64(pkvp->val.length); // To network byte order
for(size_t cnt = 0; cnt < sizeof(size_t); ++cnt){
// cppcheck-suppress unmatchedSuppression
// cppcheck-suppress objectIndex
pResult[setpos++] = bylen[cnt];
}
if(0 < pkvp->val.length){
memcpy(&pResult[setpos], pkvp->val.byptr, pkvp->val.length);
}
return pResult;
}
bool cvt_bin_kvp(PCHMKVP pkvp, unsigned char* bydata, size_t length)
{
if(!pkvp || !bydata || length < (sizeof(size_t) * 2)){
ERR_CHMPRN("Parameters are wrong.");
return false;
}
// set key
size_t readpos = 0;
size_t* ptmplen = reinterpret_cast<size_t*>(&bydata[readpos]);
pkvp->key.length = be64toh(*ptmplen); // To host byte order
readpos += sizeof(size_t);
if(0 < pkvp->key.length){
pkvp->key.byptr = &bydata[readpos];
readpos += pkvp->key.length;
}else{
pkvp->key.byptr = NULL;
}
// set value
ptmplen = reinterpret_cast<size_t*>(&bydata[readpos]);
pkvp->val.length = be64toh(*ptmplen); // To host byte order
readpos += sizeof(size_t);
if(0 < pkvp->val.length){
pkvp->val.byptr = &bydata[readpos];
}else{
pkvp->val.byptr = NULL;
}
return true;
}
chmhash_t make_chmbin_hash(const PCHMBIN pchmbin)
{
if(!pchmbin){
ERR_CHMPRN("Parameters are wrong.");
return 0L;
}
return K2H_HASH_FUNC(reinterpret_cast<const void*>(pchmbin->byptr), pchmbin->length);
}
chmhash_t make_kvp_hash(const PCHMKVP pkvp)
{
if(!pkvp || !pkvp->key.byptr || 0L == pkvp->key.length){
ERR_CHMPRN("Parameters are wrong.");
return 0L;
}
return make_chmbin_hash(&(pkvp->key));
}
/*
* VIM modelines
*
* vim:set ts=4 fenc=utf-8:
*/
| 27.828221 | 167 | 0.685295 | ggtakec |
ab8185b6c8942cc7c789c30d993bb1a6fda4f1c2 | 795 | hpp | C++ | kernel/meta/compiler.hpp | panix-os/Panix | 1047fc384696684a7583bda035fa580da4adbd5b | [
"MIT"
] | 68 | 2020-10-10T03:56:04.000Z | 2021-07-22T19:15:47.000Z | kernel/meta/compiler.hpp | panix-os/Panix | 1047fc384696684a7583bda035fa580da4adbd5b | [
"MIT"
] | 88 | 2020-10-01T23:36:44.000Z | 2021-07-22T03:11:43.000Z | kernel/meta/compiler.hpp | panix-os/Panix | 1047fc384696684a7583bda035fa580da4adbd5b | [
"MIT"
] | 5 | 2021-06-25T16:56:46.000Z | 2021-07-21T02:38:41.000Z | /**
* @file compiler.hpp
* @author Keeton Feavel (keetonfeavel@cedarville.edu)
* @brief Compiler meta directives
* @version 0.1
* @date 2021-06-17
*
* @copyright Copyright the Xyris Contributors (c) 2021
*
*/
#pragma once
// Function attributes
#define NORET __attribute__((noreturn))
#define OPTIMIZE(x) __attribute__((optimize("O"#x)))
#define ALWAYS_INLINE __attribute__((always_inline))
// Constructors / Destructors
#define CONSTRUCTOR __attribute__ ((constructor))
#define DESTRUCTOR __attribute__ ((destructor))
// Branch prediction
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
// Data attributes
#define USED __attribute__ ((used))
#define PACKED __attribute__ ((__packed__))
#define ALIGN(x) __attribute__ ((aligned ((x))))
| 26.5 | 55 | 0.734591 | panix-os |
ab829bcfdb5e536bd2556c5acd0c195b4e57b807 | 258 | hpp | C++ | DLOCRModel.Calculate/DLOCRModel.Calculate.hpp | Frederisk/DeepLearning-OpticalCharacterRecognition-Model | 52998e877cdf1e849cc2648e7d07dee6ae865cc1 | [
"MIT"
] | null | null | null | DLOCRModel.Calculate/DLOCRModel.Calculate.hpp | Frederisk/DeepLearning-OpticalCharacterRecognition-Model | 52998e877cdf1e849cc2648e7d07dee6ae865cc1 | [
"MIT"
] | 1 | 2020-12-16T03:32:56.000Z | 2020-12-16T03:32:56.000Z | DLOCRModel.Calculate/DLOCRModel.Calculate.hpp | Frederisk/DeepLearning-OpticalCharacterRecognition-Model | 52998e877cdf1e849cc2648e7d07dee6ae865cc1 | [
"MIT"
] | null | null | null | #pragma once
using namespace System;
using MathNet::Numerics::LinearAlgebra::Matrix;
namespace DLOCRModel {
namespace Calculate {
public ref class FeedforwardNetworkPiece sealed {
public:
private:
};
}
} | 14.333333 | 57 | 0.627907 | Frederisk |
ab839c9d1069d6dce421d13fed082e5107abf190 | 4,871 | cpp | C++ | projects/atest/test_context.cpp | agnesoft/adev-alt | 3df0329939e3048bbf5db252efb5f74de9c0f061 | [
"Apache-2.0"
] | null | null | null | projects/atest/test_context.cpp | agnesoft/adev-alt | 3df0329939e3048bbf5db252efb5f74de9c0f061 | [
"Apache-2.0"
] | 136 | 2020-03-29T11:15:38.000Z | 2020-10-14T06:21:23.000Z | projects/atest/test_context.cpp | agnesoft/adev-alt | 3df0329939e3048bbf5db252efb5f74de9c0f061 | [
"Apache-2.0"
] | 1 | 2020-08-04T09:56:53.000Z | 2020-08-04T09:56:53.000Z | #ifndef __clang__
export module atest:test_context;
import :test_suite;
#endif
namespace atest
{
//! \private
export class TestContext
{
struct TestContextWrapper
{
TestContext *context = nullptr;
std::atomic<int> instances{};
};
public:
TestContext() noexcept :
parentContext{TestContext::current().context}
{
this->initialize_global_test_suite();
if (TestContext::current().instances.load() != 0)
{
TestContext::current().context = this;
}
++TestContext::current().instances;
}
TestContext(const TestContext &other) = delete;
TestContext(TestContext &&other) noexcept = delete;
~TestContext()
{
try
{
TestContext::current().context = this->parentContext;
--TestContext::current().instances;
}
catch (...)
{
}
}
auto add_test(const char *name,
auto(*body)()->void,
const std::source_location &sourceLocation) noexcept
{
try
{
this->currentTestSuite->tests.emplace_back(Test{name, body, sourceLocation});
}
catch (...)
{
}
}
auto add_test_suite(const char *name,
auto(*body)()->void,
const std::source_location &sourceLocation) noexcept -> int
{
try
{
try
{
this->currentTestSuite = &this->testSuites.emplace_back(TestSuite{name, sourceLocation});
body();
this->currentTestSuite = &this->testSuites.front();
return 0;
}
catch (const std::exception &exception)
{
std::cout << "ERROR: Exception thrown during registration of '"
<< name
<< "' test suite ("
<< typeid(exception).name()
<< "): " << exception.what()
<< '\n';
}
catch (...)
{
std::cout << "ERROR: Unknown exception thrown during registration of '"
<< name
<< "' test suite.\n";
}
}
catch (...)
{
// Suppress any further exceptions as this
// function is usually run outside of main
// and no exception can be caught. See
// clang-tidy check: cert-err58-cpp.
}
return 1;
}
[[nodiscard]] static auto current() noexcept -> TestContextWrapper &
{
static TestContext globalContext{nullptr};
static TestContextWrapper wrapper{.context = &globalContext};
return wrapper;
}
[[nodiscard]] auto current_test() noexcept -> Test &
{
return *this->currentTest;
}
auto initialize_global_test_suite() noexcept -> void
{
try
{
this->currentTestSuite = &this->testSuites.emplace_back(TestSuite{.name = "Global"});
}
catch (...)
{
}
}
auto reset() -> void
{
for (TestSuite &testSuite : this->testSuites)
{
TestContext::reset_test_suites(testSuite);
}
}
auto set_current_test(Test &test) noexcept -> void
{
this->currentTest = &test;
}
auto sort_test_suites() -> void
{
const auto sorter = [](const TestSuite &left, const TestSuite &right) {
return std::string{left.sourceLocation.file_name()} < std::string{right.sourceLocation.file_name()};
};
std::sort(++this->testSuites.begin(), this->testSuites.end(), sorter);
}
[[nodiscard]] auto test_suites() noexcept -> std::vector<TestSuite> &
{
return this->testSuites;
}
auto operator=(const TestContext &other) -> TestContext & = delete;
auto operator=(TestContext &&other) noexcept -> TestContext & = delete;
private:
TestContext(TestContext *context) noexcept :
parentContext{context}
{
this->initialize_global_test_suite();
}
static auto reset_test(Test &test) -> void
{
test.expectations = 0;
test.failedExpectations = 0;
test.duration = std::chrono::microseconds::zero();
test.failures.clear();
}
static auto reset_test_suites(TestSuite &testSuite) -> void
{
for (Test &test : testSuite.tests)
{
TestContext::reset_test(test);
}
}
std::vector<TestSuite> testSuites;
TestSuite *currentTestSuite = nullptr;
Test *currentTest = nullptr;
TestContext *parentContext = nullptr;
};
//! \private
export [[nodiscard]] auto test_context() -> TestContext &
{
return *TestContext::current().context;
}
}
| 26.048128 | 112 | 0.53295 | agnesoft |
ab84782a2ed3a5dbbd0b2787a88a339b8075a858 | 5,382 | cpp | C++ | base/fs/rdr2/rdpdr/drkdx/kdextlib.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/fs/rdr2/rdpdr/drkdx/kdextlib.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/fs/rdr2/rdpdr/drkdx/kdextlib.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1990 Microsoft Corporation
------------------------------
T H I S F I L E I S O B S O L E T E . I T I S B E I N G K E P T
F O R A W H I L E J U S T T O M A K E S U R E
----------------------------
Module Name:
kdextlib.c
Abstract:
Library routines for dumping data structures given a meta level descrioption
Author:
Balan Sethu Raman (SethuR) 11-May-1994
Notes:
The implementation tends to avoid memory allocation and deallocation as much as possible.
Therefore We have choosen an arbitrary length as the default buffer size. A mechanism will
be provided to modify this buffer length through the debugger extension commands.
Revision History:
11-Nov-1994 SethuR Created
--*/
#ifdef __cplusplus
extern "C" {
#endif
#include "rxovride.h" //common compile flags
#include "ntifs.h"
#include <nt.h>
//#include <ntrtl.h>
#include "ntverp.h"
#ifdef __cplusplus
}
#endif
#define KDEXTMODE
#include <windef.h>
#define NOEXTAPI
#include <wdbgexts.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <kdextlib.h>
#include <ntrxdef.h>
#include <rxtypes.h>
PWINDBG_OUTPUT_ROUTINE lpOutputRoutine;
PWINDBG_GET_EXPRESSION32 lpGetExpressionRoutine;
PWINDBG_GET_SYMBOL32 lpGetSymbolRoutine;
PWINDBG_READ_PROCESS_MEMORY_ROUTINE lpReadMemoryRoutine;
#define PRINTF lpOutputRoutine
#define ERROR lpOutputRoutine
#define NL 1
#define NONL 0
#define SETCALLBACKS() \
lpOutputRoutine = lpExtensionApis->lpOutputRoutine; \
lpGetExpressionRoutine = lpExtensionApis->lpGetExpressionRoutine; \
lpGetSymbolRoutine = lpExtensionApis->lpGetSymbolRoutine; \
lpReadMemoryRoutine = lpExtensionApis->lpReadVirtualMemRoutine;
#define DEFAULT_UNICODE_DATA_LENGTH 512
USHORT s_UnicodeStringDataLength = DEFAULT_UNICODE_DATA_LENGTH;
WCHAR s_UnicodeStringData[DEFAULT_UNICODE_DATA_LENGTH];
WCHAR *s_pUnicodeStringData = s_UnicodeStringData;
#define DEFAULT_ANSI_DATA_LENGTH 512
USHORT s_AnsiStringDataLength = DEFAULT_ANSI_DATA_LENGTH;
CHAR s_AnsiStringData[DEFAULT_ANSI_DATA_LENGTH];
CHAR *s_pAnsiStringData = s_AnsiStringData;
/*
* Fetches the data at the given address
*/
BOOLEAN
GetData( ULONG_PTR dwAddress, PVOID ptr, ULONG size, PSZ type)
{
BOOL b;
ULONG BytesRead;
b = (lpReadMemoryRoutine)(dwAddress, ptr, size, &BytesRead );
if (!b || BytesRead != size ) {
PRINTF( "Unable to read %u bytes at %p, for %s\n", size, dwAddress, type );
return FALSE;
}
return TRUE;
}
/*
* Fetch the null terminated ASCII string at dwAddress into buf
*/
BOOL
GetString( ULONG_PTR dwAddress, PSZ buf )
{
do {
if( !GetData( dwAddress,buf, 1, "..stringfetch") )
return FALSE;
dwAddress++;
buf++;
} while( *buf != '\0' );
return TRUE;
}
/*
* Displays a byte in hexadecimal
*/
VOID
PrintHexChar( UCHAR c )
{
PRINTF( "%c%c", "0123456789abcdef"[ (c>>4)&0xf ], "0123456789abcdef"[ c&0xf ] );
}
/*
* Displays a buffer of data in hexadecimal
*/
VOID
PrintHexBuf( PUCHAR buf, ULONG cbuf )
{
while( cbuf-- ) {
PrintHexChar( *buf++ );
PRINTF( " " );
}
}
/*
* Displays a unicode string
*/
BOOL
PrintStringW(LPSTR msg, PUNICODE_STRING puStr, BOOL nl )
{
UNICODE_STRING UnicodeString;
ANSI_STRING AnsiString;
BOOL b;
if( msg )
PRINTF( msg );
if( puStr->Length == 0 ) {
if( nl )
PRINTF( "\n" );
return TRUE;
}
UnicodeString.Buffer = s_pUnicodeStringData;
UnicodeString.MaximumLength = s_UnicodeStringDataLength;
UnicodeString.Length = (puStr->Length > s_UnicodeStringDataLength)
? s_UnicodeStringDataLength
: puStr->Length;
b = (lpReadMemoryRoutine)(
(ULONG_PTR) puStr->Buffer,
UnicodeString.Buffer,
UnicodeString.Length,
NULL);
if (b) {
RtlUnicodeStringToAnsiString(&AnsiString, puStr, TRUE);
PRINTF("%s%s", AnsiString.Buffer, nl ? "\n" : "" );
RtlFreeAnsiString(&AnsiString);
}
return b;
}
/*
* Displays a ANSI string
*/
BOOL
PrintStringA(LPSTR msg, PANSI_STRING pStr, BOOL nl )
{
ANSI_STRING AnsiString;
BOOL b;
if( msg )
PRINTF( msg );
if( pStr->Length == 0 ) {
if( nl )
PRINTF( "\n" );
return TRUE;
}
AnsiString.Buffer = s_pAnsiStringData;
AnsiString.MaximumLength = s_AnsiStringDataLength;
AnsiString.Length = (pStr->Length > (s_AnsiStringDataLength - 1))
? (s_AnsiStringDataLength - 1)
: pStr->Length;
b = (lpReadMemoryRoutine)(
(ULONG_PTR) pStr->Buffer,
AnsiString.Buffer,
AnsiString.Length,
NULL);
if (b) {
AnsiString.Buffer[ AnsiString.Length ] = '\0';
PRINTF("%s%s", AnsiString.Buffer, nl ? "\n" : "" );
}
return b;
}
| 21.789474 | 95 | 0.590673 | npocmaka |
ab85331c3970fe232bb9914251791c6a4ccd641c | 2,259 | cpp | C++ | segmentation/Ncuts/util/mex_math.cpp | sfikas/sfikasLibrary | b99ac0bf01289c23d46c27bd9003e7891f026eb4 | [
"MIT"
] | 7 | 2016-10-03T12:43:59.000Z | 2020-07-18T08:17:44.000Z | segmentation/Ncuts/util/mex_math.cpp | sfikas/duguepes-matroutines | b99ac0bf01289c23d46c27bd9003e7891f026eb4 | [
"MIT"
] | null | null | null | segmentation/Ncuts/util/mex_math.cpp | sfikas/duguepes-matroutines | b99ac0bf01289c23d46c27bd9003e7891f026eb4 | [
"MIT"
] | null | null | null | /*================================================================
// Timothee Cour, 29-Aug-2006 07:49:15
mex_math = used by a couple of mex functions
*=================================================================*/
# include "math.h"
int round2(double x) {
//return floor(x+0.5);
return x>=0 ? (int)(x+0.5) : (int) (x-0.5);
}
/* Problem: when compiling on opteron, says error: new declaration
int round(double x) {
//return floor(x+0.5);
return x>=0 ? (int)(x+0.5) : (int) (x-0.5);
}*/
double min(double x,double y) {
return x<y?x:y;
}
double max(double x,double y) {
return x>y?x:y;
}
int max(int x,int y) {
return x>y?x:y;
}
int min(int x,int y) {
return x<y?x:y;
}
double vec_max(double *x,int n) {
double res=x[0];
for(int i=1;i<n;i++)
if(res<x[i])
res=x[i];
return res;
}
int vec_max(int *x,int n) {
int res=x[0];
for(int i=1;i<n;i++)
if(res<x[i])
res=x[i];
return res;
}
int vec_min(int *x,int n) {
int res=x[0];
for(int i=1;i<n;i++)
if(res>x[i])
res=x[i];
return res;
}
double vec_min(double *x,int n) {
double res=x[0];
for(int i=1;i<n;i++)
if(res>x[i])
res=x[i];
return res;
}
double dot(double *x,double *y, int n) {
double temp = 0;
for(int i=0;i!=n;i++)
temp+=*x++ * *y++;
return temp;
}
void scalar_times_vec(double a, double *x,double *y, int n) {
// y=a*x
for(int i=0;i!=n;i++)
*y++ = *x++ * a;
}
void scalar_plus_vec_self(int a, int *x, int n) {
// x=a+x
for(int i=0;i!=n;i++)
*x++ += a;
}
void vec_plus_vec(double *x1, double *x2,double *y, int n) {
// y=x1+x2
for(int i=0;i!=n;i++)
y[i] = x1[i] + x2[i];
//*y++ = *x1++ + *x2++;
}
void ind2sub(int*ind,int*indi,int*indj,int p,int q,int n){
//caution: output is in matlab conventions//TODO;correct this [mex_ind2sub
int i;
int*pindi=indi;
int*pindj=indj;
int*pind=ind;
int temp;
for(i=0;i<n;i++){
temp=*pind++-1;
*pindi++=temp%p+1;
*pindj++=temp/p+1;
}
}
//void symmetrize_sparse()
| 21.932039 | 76 | 0.463922 | sfikas |
ab857925febd450c0ad4441b9f5341b548ca54c6 | 2,037 | hpp | C++ | rocsolver/clients/include/rocsolver_test.hpp | LuckyBoyDE/rocSOLVER | 6431459ce3f68b5a4c14b28b4ec35c25d664f0bc | [
"BSD-2-Clause"
] | null | null | null | rocsolver/clients/include/rocsolver_test.hpp | LuckyBoyDE/rocSOLVER | 6431459ce3f68b5a4c14b28b4ec35c25d664f0bc | [
"BSD-2-Clause"
] | null | null | null | rocsolver/clients/include/rocsolver_test.hpp | LuckyBoyDE/rocSOLVER | 6431459ce3f68b5a4c14b28b4ec35c25d664f0bc | [
"BSD-2-Clause"
] | null | null | null | /* ************************************************************************
* Copyright (c) 2018-2020 Advanced Micro Devices, Inc.
* ************************************************************************ */
#ifndef S_TEST_H_
#define S_TEST_H_
#include <boost/format.hpp>
#include <cstdarg>
#include <limits>
#define ROCSOLVER_BENCH_INFORM(case) \
do \
{ \
if(case == 2) \
rocblas_cout << "Invalid value in arguments ..." << std::endl; \
else if(case == 1) \
rocblas_cout << "Invalid size arguments..." << std::endl; \
else \
rocblas_cout << "Quick return..." << std::endl; \
rocblas_cout << "No performance data to collect." << std::endl; \
rocblas_cout << "No computations to verify." << std::endl; \
} while(0)
template <typename T>
constexpr double get_epsilon()
{
using S = decltype(std::real(T{}));
return std::numeric_limits<S>::epsilon();
}
template <typename T>
inline void rocsolver_test_check(double max_error, int tol)
{
#ifdef GOOGLE_TEST
ASSERT_LE(max_error, tol * get_epsilon<T>());
#endif
}
inline void rocsolver_bench_output()
{
// empty version
rocblas_cout << std::endl;
}
template <typename T, typename... Ts>
inline void rocsolver_bench_output(T arg, Ts... args)
{
using boost::format;
format f("%|-15|");
rocblas_cout << f % arg;
rocsolver_bench_output(args...);
}
template <typename T, std::enable_if_t<!is_complex<T>, int> = 0>
inline T sconj(T scalar)
{
return scalar;
}
template <typename T, std::enable_if_t<is_complex<T>, int> = 0>
inline T sconj(T scalar)
{
return std::conj(scalar);
}
#endif
| 29.521739 | 78 | 0.471772 | LuckyBoyDE |
ab883e092c767ce93700444af5a6d7ac99f67dc8 | 4,763 | cc | C++ | extensions/browser/requirements_checker_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | extensions/browser/requirements_checker_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | extensions/browser/requirements_checker_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/browser/requirements_checker.h"
#include <memory>
#include <string>
#include <vector>
#include "base/memory/ref_counted.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/gpu_data_manager.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extensions_test.h"
#include "extensions/browser/preload_check.h"
#include "extensions/browser/preload_check_test_util.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
namespace extensions {
namespace {
// Whether this build supports the window.shape requirement.
const bool kSupportsWindowShape =
#if defined(USE_AURA)
true;
#else
false;
#endif
// Returns true if a WebGL check might not fail immediately.
bool MightSupportWebGL() {
return content::GpuDataManager::GetInstance()->GpuAccessAllowed(nullptr);
}
const char kFeaturesKey[] = "requirements.3D.features";
const char kFeatureWebGL[] = "webgl";
const char kFeatureCSS3d[] = "css3d";
} // namespace
class RequirementsCheckerTest : public ExtensionsTest {
public:
RequirementsCheckerTest() {
manifest_dict_ = std::make_unique<base::DictionaryValue>();
}
~RequirementsCheckerTest() override {}
void CreateExtension() {
manifest_dict_->SetString("name", "dummy name");
manifest_dict_->SetString("version", "1");
manifest_dict_->SetInteger("manifest_version", 2);
std::string error;
extension_ =
Extension::Create(base::FilePath(), mojom::ManifestLocation::kUnpacked,
*manifest_dict_, Extension::NO_FLAGS, &error);
ASSERT_TRUE(extension_.get()) << error;
}
protected:
void StartChecker() {
checker_ = std::make_unique<RequirementsChecker>(extension_);
// TODO(michaelpg): This should normally not have to be async. Use Run()
// instead of RunUntilComplete() after crbug.com/708354 is addressed.
runner_.RunUntilComplete(checker_.get());
}
void RequireWindowShape() {
manifest_dict_->SetBoolean("requirements.window.shape", true);
}
void RequireFeature(const char feature[]) {
if (!manifest_dict_->HasKey(kFeaturesKey))
manifest_dict_->Set(kFeaturesKey, std::make_unique<base::ListValue>());
base::ListValue* features_list = nullptr;
ASSERT_TRUE(manifest_dict_->GetList(kFeaturesKey, &features_list));
features_list->Append(feature);
}
std::unique_ptr<RequirementsChecker> checker_;
PreloadCheckRunner runner_;
private:
scoped_refptr<Extension> extension_;
std::unique_ptr<base::DictionaryValue> manifest_dict_;
};
// Tests no requirements.
TEST_F(RequirementsCheckerTest, RequirementsEmpty) {
CreateExtension();
StartChecker();
EXPECT_TRUE(runner_.called());
EXPECT_EQ(0u, runner_.errors().size());
EXPECT_TRUE(checker_->GetErrorMessage().empty());
}
// Tests fulfilled requirements.
TEST_F(RequirementsCheckerTest, RequirementsSuccess) {
if (kSupportsWindowShape)
RequireWindowShape();
RequireFeature(kFeatureCSS3d);
CreateExtension();
StartChecker();
EXPECT_TRUE(runner_.called());
EXPECT_EQ(0u, runner_.errors().size());
EXPECT_TRUE(checker_->GetErrorMessage().empty());
}
// Tests multiple requirements failing (on some builds).
TEST_F(RequirementsCheckerTest, RequirementsFailMultiple) {
size_t expected_errors = 0u;
if (!kSupportsWindowShape) {
RequireWindowShape();
expected_errors++;
}
if (!MightSupportWebGL()) {
RequireFeature(kFeatureWebGL);
expected_errors++;
}
// css3d should always succeed.
RequireFeature(kFeatureCSS3d);
CreateExtension();
StartChecker();
EXPECT_TRUE(runner_.called());
EXPECT_EQ(expected_errors, runner_.errors().size());
EXPECT_EQ(expected_errors == 0, checker_->GetErrorMessage().empty());
}
// Tests a requirement that might fail asynchronously.
TEST_F(RequirementsCheckerTest, RequirementsFailWebGL) {
content::GpuDataManager::GetInstance()->BlocklistWebGLForTesting();
RequireFeature(kFeatureWebGL);
CreateExtension();
StartChecker();
// TODO(michaelpg): Check that the runner actually finishes, which requires
// waiting for the GPU check to succeed: crbug.com/706204.
if (runner_.errors().size()) {
EXPECT_THAT(runner_.errors(), testing::UnorderedElementsAre(
PreloadCheck::Error::kWebglNotSupported));
EXPECT_FALSE(checker_->GetErrorMessage().empty());
}
}
} // namespace extensions
| 30.33758 | 80 | 0.735881 | zealoussnow |
ab889664886083babd8ffdebf49f7ea22422ce8d | 23,207 | cpp | C++ | font.cpp | Yours3lf/text_game | 32c934a7cb396d2412a3f0847cd7c7da9d46e3c0 | [
"MIT"
] | null | null | null | font.cpp | Yours3lf/text_game | 32c934a7cb396d2412a3f0847cd7c7da9d46e3c0 | [
"MIT"
] | null | null | null | font.cpp | Yours3lf/text_game | 32c934a7cb396d2412a3f0847cd7c7da9d46e3c0 | [
"MIT"
] | null | null | null | #include "font.h"
#include <fstream>
#include "ft2build.h"
#include FT_FREETYPE_H
#define MAX_TEX_SIZE 8192
#define MIN_TEX_SIZE 128
#define FONT_VERTEX 0
#define FONT_TEXCOORD 1
#define FONT_VERTSCALEBIAS 2
#define FONT_TEXSCALEBIAS 3
#define FONT_COLOR 4
#define FONT_FACE 5
#define FONT_TRANSFORM 6
#define FONT_FILTER 7
wchar_t buf[2] = { -1, L'\0' };
std::wstring cachestring = std::wstring( buf ) + L" 0123456789a�bcde�fghi�jklmno���pqrstu���vwxyzA�BCDE�FGHI�JKLMNO���PQRSTU���VWXYZ+!%/=()|$[]<>#&@{},.~-?:_;*`^'\"";
struct glyph
{
float offset_x;
float offset_y;
float w;
float h;
float texcoords[4];
FT_Glyph_Metrics metrics;
FT_Vector advance;
FT_UInt glyphid;
unsigned int cache_index;
};
library::library() : the_library( 0 ), tex( 0 ), texsampler_point( 0 ), texsampler_linear( 0 ), vao( 0 ), the_shader( 0 ), is_set_up( false )
{
for( int c = 0; c < FONT_LIB_VBO_SIZE; ++c )
vbos[c] = 0;
FT_Error error;
error = FT_Init_FreeType( (FT_Library*)&the_library );
if( error )
{
std::cerr << "Error initializing the freetype library." << std::endl;
}
}
void library::destroy()
{
glDeleteSamplers( 1, &texsampler_point );
glDeleteSamplers( 1, &texsampler_linear );
glDeleteTextures( 1, &tex );
glDeleteVertexArrays( 1, &vao );
glDeleteBuffers( FONT_LIB_VBO_SIZE, vbos );
glDeleteProgram( the_shader );
}
library::~library()
{
if( the_library )
{
FT_Error error;
error = FT_Done_FreeType( (FT_Library)the_library );
if( error )
{
std::cerr << "Error destroying the freetype library." << std::endl;
}
}
}
void library::delete_glyphs()
{
texture_pen = mm::uvec2( 1 );
texture_row_h = 0;
texsize = mm::uvec2( 0 );
font_data.clear();
for( auto& c : instances )
{
( *c->the_face->glyphs ).clear();
}
}
void library::set_up()
{
if( is_set_up ) return;
texture_pen = mm::uvec2( 0 );
texsize = mm::uvec2( 0 );
glGenTextures( 1, &tex );
glGenSamplers( 1, &texsampler_point );
glGenSamplers( 1, &texsampler_linear );
glSamplerParameteri( texsampler_point, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glSamplerParameteri( texsampler_point, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glSamplerParameteri( texsampler_point, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glSamplerParameteri( texsampler_point, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glSamplerParameteri( texsampler_linear, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glSamplerParameteri( texsampler_linear, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glSamplerParameteri( texsampler_linear, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glSamplerParameteri( texsampler_linear, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
std::vector<unsigned> faces;
std::vector<float> vertices;
std::vector<float> texcoords;
faces.resize( 2 * 3 );
vertices.resize( 4 * 2 );
texcoords.resize( 4 * 2 );
faces[0 * 3 + 0] = 2;
faces[0 * 3 + 1] = 1;
faces[0 * 3 + 2] = 0;
faces[1 * 3 + 0] = 0;
faces[1 * 3 + 1] = 3;
faces[1 * 3 + 2] = 2;
vertices[0 * 2 + 0] = 0;
vertices[0 * 2 + 1] = 0;
vertices[1 * 2 + 0] = 0;
vertices[1 * 2 + 1] = 1;
vertices[2 * 2 + 0] = 1;
vertices[2 * 2 + 1] = 1;
vertices[3 * 2 + 0] = 1;
vertices[3 * 2 + 1] = 0;
texcoords[0 * 2 + 0] = 0;
texcoords[0 * 2 + 1] = 0;
texcoords[1 * 2 + 0] = 0;
texcoords[1 * 2 + 1] = 1;
texcoords[2 * 2 + 0] = 1;
texcoords[2 * 2 + 1] = 1;
texcoords[3 * 2 + 0] = 1;
texcoords[3 * 2 + 1] = 0;
glGenVertexArrays( 1, &vao );
glBindVertexArray( vao );
glGenBuffers( 1, &vbos[FONT_VERTEX] );
glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_VERTEX] );
glBufferData( GL_ARRAY_BUFFER, sizeof(float)* 2 * vertices.size(), &vertices[0], GL_STATIC_DRAW );
glEnableVertexAttribArray( FONT_VERTEX );
glVertexAttribPointer( FONT_VERTEX, 2, GL_FLOAT, false, 0, 0 );
glGenBuffers( 1, &vbos[FONT_TEXCOORD] );
glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_TEXCOORD] );
glBufferData( GL_ARRAY_BUFFER, sizeof(float)* 2 * texcoords.size(), &texcoords[0], GL_STATIC_DRAW );
glEnableVertexAttribArray( FONT_TEXCOORD );
glVertexAttribPointer( FONT_TEXCOORD, 2, GL_FLOAT, false, 0, 0 );
glGenBuffers( 1, &vbos[FONT_VERTSCALEBIAS] );
glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_VERTSCALEBIAS] );
glEnableVertexAttribArray( FONT_VERTSCALEBIAS );
glVertexAttribPointer( FONT_VERTSCALEBIAS, 4, GL_FLOAT, false, sizeof( mm::vec4 ), 0 );
glVertexAttribDivisor( FONT_VERTSCALEBIAS, 1 );
glGenBuffers( 1, &vbos[FONT_TEXSCALEBIAS] );
glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_TEXSCALEBIAS] );
glEnableVertexAttribArray( FONT_TEXSCALEBIAS );
glVertexAttribPointer( FONT_TEXSCALEBIAS, 4, GL_FLOAT, false, sizeof( mm::vec4 ), 0 );
glVertexAttribDivisor( FONT_TEXSCALEBIAS, 1 );
glGenBuffers( 1, &vbos[FONT_COLOR] );
glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_COLOR] );
glEnableVertexAttribArray( FONT_COLOR );
glVertexAttribPointer( FONT_COLOR, 4, GL_FLOAT, false, sizeof( mm::vec4 ), 0 );
glVertexAttribDivisor( FONT_COLOR, 1 );
glGenBuffers( 1, &vbos[FONT_FACE] );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vbos[FONT_FACE] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)* 3 * faces.size(), &faces[0], GL_STATIC_DRAW );
glGenBuffers( 1, &vbos[FONT_TRANSFORM] );
glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_TRANSFORM] );
for( int c = 0; c < 4; ++c )
{
glEnableVertexAttribArray( FONT_TRANSFORM + c );
glVertexAttribPointer( FONT_TRANSFORM + c, 4, GL_FLOAT, false, sizeof( mm::mat4 ), ( (char*)0 ) + sizeof( mm::vec4 ) * c );
glVertexAttribDivisor( FONT_TRANSFORM + c, 1 );
}
glGenBuffers( 1, &vbos[FONT_FILTER] );
glBindBuffer( GL_ARRAY_BUFFER, vbos[FONT_FILTER] );
glEnableVertexAttribArray( FONT_FILTER + 3 );
glVertexAttribPointer( FONT_FILTER + 3, 1, GL_FLOAT, false, sizeof( float ), 0 );
glVertexAttribDivisor( FONT_FILTER + 3, 1 );
glBindVertexArray( 0 );
is_set_up = true;
}
bool library::expand_tex()
{
glBindTexture( GL_TEXTURE_RECTANGLE, tex );
if( texsize.x == 0 || texsize.y == 0 )
{
texsize.x = MAX_TEX_SIZE;
texsize.y = MIN_TEX_SIZE;
GLubyte* buf = new GLubyte[texsize.x * texsize.y];
memset( buf, 0, texsize.x * texsize.y * sizeof( GLubyte ) );
glTexParameteri( GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
glTexImage2D( GL_TEXTURE_RECTANGLE, 0, GL_R8, texsize.x, texsize.y, 0, GL_RED, GL_UNSIGNED_BYTE, buf );
texture_pen.x = 1;
texture_pen.y = 1;
texture_row_h = 0;
delete[] buf;
}
else
{
GLubyte* buf = new GLubyte[texsize.x * texsize.y];
glGetTexImage( GL_TEXTURE_RECTANGLE, 0, GL_RED, GL_UNSIGNED_BYTE, buf );
int tmp_height = texsize.y;
texsize.y += MIN_TEX_SIZE;
if( texsize.y > MAX_TEX_SIZE ) //can't expand tex further
{
return false;
}
GLubyte* tmpbuf = new GLubyte[texsize.x * texsize.y];
memset( tmpbuf, 0, texsize.x * texsize.y * sizeof( GLubyte ) );
glTexImage2D( GL_TEXTURE_RECTANGLE, 0, GL_R8, texsize.x, texsize.y, 0, GL_RED, GL_UNSIGNED_BYTE, tmpbuf );
glTexSubImage2D( GL_TEXTURE_RECTANGLE, 0, 0, 0, texsize.x, tmp_height, GL_RED, GL_UNSIGNED_BYTE, buf );
delete[] buf;
delete[] tmpbuf;
}
return true;
}
font_inst::face::face() : size( 0 ), the_face( 0 ), glyphs( 0 )
{
}
font_inst::face::face( const std::string& filename, unsigned int index )
{
FT_Error error;
error = FT_New_Face( (FT_Library)library::get().get_library(), filename.c_str(), index, (FT_Face*)&the_face );
upos = 0;
uthick = 0;
FT_Matrix matrix = { (int)( ( 1.0 / 64.0f ) * 0x10000L ),
(int)( ( 0.0 ) * 0x10000L ),
(int)( ( 0.0 ) * 0x10000L ),
(int)( ( 1.0 ) * 0x10000L ) };
FT_Select_Charmap( *(FT_Face*)&the_face, FT_ENCODING_UNICODE );
FT_Set_Transform( *(FT_Face*)&the_face, &matrix, NULL );
glyphs = new std::map< unsigned int, std::map<uint32_t, glyph> >();
if( error )
{
std::cerr << "Error loading font face: " << filename << std::endl;
the_face = 0;
}
}
font_inst::face::~face()
{
//TODO invalidate glyphs in the library, and its tex
FT_Done_Face( (FT_Face)the_face );
delete glyphs;
}
void font_inst::face::set_size( unsigned int val )
{
if( the_face )
{
size = val;
FT_Set_Char_Size( (FT_Face)the_face, size * 100.0f * 64.0f, 0.0f, 72 * 64.0f, 72 );
asc = ( ( (FT_Face)the_face )->size->metrics.ascender / 64.0f ) / 100.0f;
desc = ( ( (FT_Face)the_face )->size->metrics.descender / 64.0f ) / 100.0f;
h = ( ( (FT_Face)the_face )->size->metrics.height / 64.0f ) / 100.0f;
gap = h - asc + desc;
upos = ( (FT_Face)the_face )->underline_position / ( 64.0f*64.0f ) * size;
upos = std::round( upos );
if( upos > -2 )
{
upos = -2;
}
uthick = ( (FT_Face)the_face )->underline_thickness / ( 64.0f*64.0f ) * size;
uthick = std::round( uthick );
if( uthick < 1 )
{
uthick = 1;
}
FT_Set_Char_Size( (FT_Face)the_face, size * 64.0f, 0.0f, 72 * 64.0f, 72 );
}
}
bool font_inst::face::load_glyph( unsigned int val )
{
if( ( *glyphs )[size].count( val ) == 0 && the_face )
{
FT_Error error;
FT_GlyphSlot theglyph = FT_GlyphSlot();
if( val != wchar_t( -1 ) )
{
error = FT_Load_Char( (FT_Face)the_face, (const FT_UInt)val, FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT );
if( error )
{
std::cerr << "Error loading character: " << (wchar_t)val << std::endl;
}
theglyph = ( (FT_Face)the_face )->glyph;
}
else
{
theglyph = new FT_GlyphSlotRec_();
theglyph->advance.x = 0;
theglyph->advance.y = 0;
static unsigned char data[4 * 4 * 3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
theglyph->bitmap.buffer = data;
theglyph->bitmap.rows = 4;
theglyph->bitmap.width = 4;
theglyph->bitmap_left = 0;
theglyph->bitmap_top = 0;
}
auto texsize = library::get().get_texsize();
auto& texpen = library::get().get_texture_pen();
auto& texrowh = library::get().get_tex_row_h();
if( texsize.x == 0 || texsize.y == 0 )
{
library::get().expand_tex();
}
FT_Bitmap* bitmap = &theglyph->bitmap;
if( texpen.x + bitmap->width + 1 > (int)texsize.x )
{
texpen.y += texrowh + 1;
texpen.x = 1;
texrowh = 0;
}
if( texpen.y + bitmap->rows + 1 > (int)texsize.y )
{
if( !library::get().expand_tex() )
{
//tex expansion unsuccessful
return false;
}
}
GLubyte* data;
int glyph_size = bitmap->width * bitmap->rows;
data = new GLubyte[glyph_size];
int c = 0;
for( int y = 0; y < bitmap->rows; y++ )
{
for( int x = 0; x < bitmap->width; x++ )
{
data[x + ( bitmap->rows - 1 - y ) * bitmap->width] = bitmap->buffer[c++];
}
}
GLint uplast;
glGetIntegerv( GL_UNPACK_ALIGNMENT, &uplast );
if( uplast != 1 )
{
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
}
glBindTexture( GL_TEXTURE_RECTANGLE, library::get().get_tex() );
glTexSubImage2D( GL_TEXTURE_RECTANGLE, 0, texpen.x, texpen.y, bitmap->width, bitmap->rows, GL_RED, GL_UNSIGNED_BYTE, data );
delete[] data;
if( uplast != 1 )
{
glPixelStorei( GL_UNPACK_ALIGNMENT, uplast );
}
glyph* g = &( *glyphs )[size][val];
g->glyphid = FT_Get_Char_Index( (FT_Face)the_face, (const FT_ULong)val );
g->offset_x = (float)theglyph->bitmap_left;
g->offset_y = (float)theglyph->bitmap_top;
g->w = (float)bitmap->width;
g->h = (float)bitmap->rows;
if( val != wchar_t( -1 ) )
{
g->texcoords[0] = (float)texpen.x - 0.5f;
g->texcoords[1] = (float)texpen.y - 0.5f;
g->texcoords[2] = (float)texpen.x + (float)bitmap->width + 0.5f;
g->texcoords[3] = (float)texpen.y + (float)bitmap->rows + 0.5f;
}
else
{
g->texcoords[0] = (float)texpen.x;
g->texcoords[1] = (float)texpen.y;
g->texcoords[2] = (float)texpen.x + (float)bitmap->width;
g->texcoords[3] = (float)texpen.y + (float)bitmap->rows;
}
texpen.x += bitmap->width + 1;
if( bitmap->rows > texrowh )
{
texrowh = bitmap->rows;
}
g->advance = theglyph->advance;
}
return true;
}
float font_inst::face::kerning( const uint32_t prev, const uint32_t next )
{
if( the_face )
{
if( next && FT_HAS_KERNING( ( (FT_Face)the_face ) ) )
{
FT_Vector kern;
FT_Get_Kerning( (FT_Face)the_face, prev, next, FT_KERNING_UNFITTED, &kern );
return ( kern.x / ( 64.0f*64.0f ) );
}
else
{
return 0;
}
}
else
{
return 0;
}
}
float font_inst::face::advance( const uint32_t current )
{
return ( ( *glyphs )[size][current].advance.x / 64.0f );
}
float font_inst::face::height()
{
return h;
}
float font_inst::face::linegap()
{
return gap;
}
float font_inst::face::ascender()
{
return asc;
}
float font_inst::face::descender()
{
return desc;
}
float font_inst::face::underline_position()
{
return upos;
}
float font_inst::face::underline_thickness()
{
return uthick;
}
glyph& font_inst::face::get_glyph( uint32_t i )
{
return ( *glyphs )[size][i];
}
bool font_inst::face::has_glyph( uint32_t i )
{
try
{
( *glyphs ).at( size ).at( i );
return true;
}
catch( ... )
{
return false;
}
}
void font::set_size( font_inst& font_ptr, unsigned int s )
{
font_ptr.the_face->set_size( s );
std::for_each( cachestring.begin(), cachestring.end(),
[&]( wchar_t & c )
{
add_glyph( font_ptr, c );
} );
}
void font::add_glyph( font_inst& font_ptr, uint32_t c, int counter )
{
if( font_ptr.the_face->has_glyph( c ) )
return;
if( !font_ptr.the_face->load_glyph( c ) )
{
if( counter > 9 ) //at max 10 tries
{
exit( 1 ); //couldn't get enough memory or something... (extreme case)
}
library::get().delete_glyphs();
add_glyph( font_ptr, c, ++counter );
return;
}
auto& g = font_ptr.the_face->get_glyph( c );
g.cache_index = library::get().get_font_data_size();
mm::vec2 vertbias = mm::vec2( g.offset_x - 0.5f, -0.5f - ( g.h - g.offset_y ) );
mm::vec2 vertscale = mm::vec2( g.offset_x + g.w + 0.5f, 0.5f + g.h - ( g.h - g.offset_y ) ) - vertbias;
//texcoords
mm::vec2 texbias = mm::vec2( g.texcoords[0], g.texcoords[1] );
mm::vec2 texscale = mm::vec2( g.texcoords[2], g.texcoords[3] ) - texbias;
library::get().add_font_data( fontscalebias( vertscale, vertbias, texscale, texbias ) );
}
void font::load_font( const std::string& filename, font_inst& font_ptr, unsigned int size )
{
std::cout << "-Loading: " << filename << std::endl;
std::fstream f( filename.c_str(), std::ios::in );
if( !f )
std::cerr << "Couldn't open file: " << filename << std::endl;
f.close();
library::get().set_up();
resize( screensize );
//load directly from font
font_ptr.the_face = new font_inst::face( filename, 0 );
set_size( font_ptr, size );
library::get().instances.push_back( &font_ptr );
}
void font::resize( const mm::uvec2& ss )
{
screensize = ss;
font_frame.set_ortographic( 0.0f, (float)ss.x, 0.0f, (float)ss.y, 0.0f, 1.0f );
}
static std::vector<mm::vec4> vertscalebias;
static std::vector<mm::vec4> texscalebias;
static std::vector<mm::vec4> fontcolor;
static std::vector<mm::mat4> transform;
static std::vector<float> filter;
//these special unicode characters denote the text markup begin/end
#define FONT_UNDERLINE_BEGIN L'\uE000'
#define FONT_UNDERLINE_END L'\uE001'
#define FONT_OVERLINE_BEGIN L'\uE002'
#define FONT_OVERLINE_END L'\uE003'
#define FONT_STRIKETHROUGH_BEGIN L'\uE004'
#define FONT_STRIKETHROUGH_END L'\uE005'
#define FONT_HIGHLIGHT_BEGIN L'\uE006'
#define FONT_HIGHLIGHT_END L'\uE007'
bool is_special( wchar_t c )
{
return c == FONT_UNDERLINE_BEGIN ||
c == FONT_UNDERLINE_END ||
c == FONT_OVERLINE_BEGIN ||
c == FONT_OVERLINE_END ||
c == FONT_STRIKETHROUGH_BEGIN ||
c == FONT_STRIKETHROUGH_END ||
c == FONT_HIGHLIGHT_BEGIN ||
c == FONT_HIGHLIGHT_END;
}
mm::vec2 font::add_to_render_list( const std::wstring& txt, font_inst& font_ptr, const mm::vec4& color, const mm::mat4& mat, const mm::vec4& highlight_color, float line_height, float f )
{
static bool underline = false;
static bool overline = false;
static bool strikethrough = false;
static bool highlight = false;
float yy = 0;
float xx = 0;
float vert_advance = font_ptr.the_face->height() - font_ptr.the_face->linegap();
vert_advance *= line_height;
yy += vert_advance;
for( int c = 0; c < int( txt.size() ); c++ )
{
char bla = txt[c];
if( txt[c] == L'\n' )
{
yy += vert_advance;
xx = 0;
}
if( c > 0 && txt[c] != L'\n' && !is_special( txt[c] ) )
{
xx += font_ptr.the_face->kerning( txt[c - 1], txt[c] );
}
if( txt[c] == FONT_UNDERLINE_BEGIN )
underline = true;
else if( txt[c] == FONT_UNDERLINE_END )
underline = false;
else if( txt[c] == FONT_OVERLINE_BEGIN )
overline = true;
else if( txt[c] == FONT_OVERLINE_END )
overline = false;
else if( txt[c] == FONT_STRIKETHROUGH_BEGIN )
strikethrough = true;
else if( txt[c] == FONT_STRIKETHROUGH_END )
strikethrough = false;
else if( txt[c] == FONT_HIGHLIGHT_BEGIN )
highlight = true;
else if( txt[c] == FONT_HIGHLIGHT_END )
highlight = false;
float finalx = xx;
mm::vec3 pos = mm::vec3( finalx, (float)screensize.y - yy, 0 );
float advancex = 0;
int i = 0;
for( i = c; i < txt.size(); ++i )
{
if( !is_special( txt[i] ) )
break;
}
advancex = font_ptr.the_face->advance( txt[i] );
if( highlight )
{
unsigned int datapos = font_ptr.the_face->get_glyph( wchar_t( -1 ) ).cache_index;
fontscalebias& fsb = library::get().get_font_data( datapos );
fontscalebias copy = fsb;
//vert bias
copy.vertscalebias.w = font_ptr.the_face->descender();
//hori bias
copy.vertscalebias.z = 0.0f;
//hori scale
copy.vertscalebias.x = advancex;
//vert scale
copy.vertscalebias.y = font_ptr.the_face->height() + font_ptr.the_face->linegap();
vertscalebias.push_back( mm::vec4( copy.vertscalebias.xy, copy.vertscalebias.zw + pos.xy ) );
texscalebias.push_back( copy.texscalebias );
fontcolor.push_back( highlight_color );
transform.push_back( mat );
filter.push_back( f );
}
if( strikethrough )
{
unsigned int datapos = font_ptr.the_face->get_glyph( wchar_t( -1 ) ).cache_index;
fontscalebias& fsb = library::get().get_font_data( datapos );
fontscalebias copy = fsb;
//vert bias
copy.vertscalebias.w = font_ptr.the_face->ascender() * 0.33f;
//hori bias
copy.vertscalebias.z = 0;
//hori scale
copy.vertscalebias.x = advancex;
//vert scale
copy.vertscalebias.y = font_ptr.the_face->underline_thickness();
vertscalebias.push_back( mm::vec4( copy.vertscalebias.xy, copy.vertscalebias.zw + pos.xy ) );
texscalebias.push_back( copy.texscalebias );
fontcolor.push_back( color );
transform.push_back( mat );
filter.push_back( f );
}
if( underline )
{
unsigned int datapos = font_ptr.the_face->get_glyph( wchar_t( -1 ) ).cache_index;
fontscalebias& fsb = library::get().get_font_data( datapos );
fontscalebias copy = fsb;
//vert bias
copy.vertscalebias.w = font_ptr.the_face->underline_position();
//hori bias
copy.vertscalebias.z = 0.0f;
//hori scale
copy.vertscalebias.x = advancex;
//vert scale
copy.vertscalebias.y = font_ptr.the_face->underline_thickness();
vertscalebias.push_back( mm::vec4( copy.vertscalebias.xy, copy.vertscalebias.zw + pos.xy ) );
texscalebias.push_back( copy.texscalebias );
fontcolor.push_back( color );
transform.push_back( mat );
filter.push_back( f );
}
if( overline )
{
unsigned int datapos = font_ptr.the_face->get_glyph( wchar_t( -1 ) ).cache_index;
fontscalebias& fsb = library::get().get_font_data( datapos );
fontscalebias copy = fsb;
//vert bias
copy.vertscalebias.w = font_ptr.the_face->ascender();
//hori bias
copy.vertscalebias.z = 0.0f;
//hori scale
copy.vertscalebias.x = advancex;
//vert scale
copy.vertscalebias.y = font_ptr.the_face->underline_thickness();
vertscalebias.push_back( mm::vec4( copy.vertscalebias.xy, copy.vertscalebias.zw + pos.xy ) );
texscalebias.push_back( copy.texscalebias );
fontcolor.push_back( color );
transform.push_back( mat );
filter.push_back( f );
}
if( c < txt.size() && txt[c] != L' ' && txt[c] != L'\n' && !is_special( txt[c] ) )
{
add_glyph( font_ptr, txt[c] );
unsigned int datapos = font_ptr.the_face->get_glyph( txt[c] ).cache_index;
auto thefsb = library::get().get_font_data( datapos );
vertscalebias.push_back( mm::vec4( thefsb.vertscalebias.xy, thefsb.vertscalebias.zw + pos.xy ) );
texscalebias.push_back( thefsb.texscalebias );
fontcolor.push_back( color );
transform.push_back( mat );
filter.push_back( f );
}
if( !is_special( txt[c] ) )
xx += font_ptr.the_face->advance( txt[c] );
}
yy -= vert_advance;
return mm::vec2( xx, yy );
}
void font::render()
{
glDisable( GL_CULL_FACE );
glDisable( GL_DEPTH_TEST );
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
library::get().bind_shader();
//mvp is now only the projection matrix
mm::mat4 mat = font_frame.projection_matrix;
glUniformMatrix4fv( 0, 1, false, &mat[0].x );
glActiveTexture( GL_TEXTURE0 );
library::get().bind_texture();
library::get().bind_vao();
library::get().update_scalebiascolor( FONT_VERTSCALEBIAS, vertscalebias );
library::get().update_scalebiascolor( FONT_TEXSCALEBIAS, texscalebias );
library::get().update_scalebiascolor( FONT_COLOR, fontcolor );
library::get().update_scalebiascolor( FONT_TRANSFORM, transform );
library::get().update_scalebiascolor( FONT_FILTER, filter );
glDrawElementsInstanced( GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0, vertscalebias.size() );
glBindVertexArray( 0 );
glUseProgram( 0 );
glDisable( GL_BLEND );
glEnable( GL_DEPTH_TEST );
glEnable( GL_CULL_FACE );
vertscalebias.clear();
texscalebias.clear();
fontcolor.clear();
transform.clear();
filter.clear();
}
| 27.302353 | 186 | 0.630887 | Yours3lf |
ab8db9f0f7d107703c0285f716a5c922921b245f | 4,154 | cpp | C++ | unit_test/gtest_cell_index.cpp | Tokumasu-Lab/md_fdps | eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff | [
"MIT"
] | null | null | null | unit_test/gtest_cell_index.cpp | Tokumasu-Lab/md_fdps | eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff | [
"MIT"
] | null | null | null | unit_test/gtest_cell_index.cpp | Tokumasu-Lab/md_fdps | eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff | [
"MIT"
] | null | null | null | //=======================================================================================
// This is unit test of MD_EXT::CellIndex.
// module location: ./generic_ext/cell_index.hpp
//=======================================================================================
#include <gtest/gtest.h>
#include <particle_simulator.hpp>
#include <random>
#include <cell_index.hpp>
//--- unit test definition, CANNOT use "_" in test/test_case name.
TEST(CellIndex, init){
MD_EXT::CellIndex<int> cell_index;
cell_index.initDomain( PS::F32vec{-1.0, -1.0, -1.0},
PS::F32vec{ 2.0, 2.0, 2.0} );
EXPECT_EQ(cell_index.get_domain(), std::make_pair(PS::F32vec{-1.0, -1.0, -1.0},
PS::F32vec{ 2.0, 2.0, 2.0}));
cell_index.initIndex(3, 6, 12);
EXPECT_EQ(cell_index.get_grid_size().x, 3);
EXPECT_EQ(cell_index.get_grid_size().y, 6);
EXPECT_EQ(cell_index.get_grid_size().z, 12);
EXPECT_FLOAT_EQ(cell_index.get_cell_size().x, 1.0);
EXPECT_FLOAT_EQ(cell_index.get_cell_size().y, 0.5);
EXPECT_FLOAT_EQ(cell_index.get_cell_size().z, 0.25);
cell_index.init( PS::F32vec{0.0, 0.0, 0.0},
PS::F32vec{2.0, 4.0, 3.0},
0.24 );
EXPECT_EQ(cell_index.get_grid_size().x, 10);
EXPECT_EQ(cell_index.get_grid_size().y, 18);
EXPECT_EQ(cell_index.get_grid_size().z, 14);
EXPECT_FLOAT_EQ(cell_index.get_cell_size().x, 2.0/10.0);
EXPECT_FLOAT_EQ(cell_index.get_cell_size().y, 4.0/18.0);
EXPECT_FLOAT_EQ(cell_index.get_cell_size().z, 3.0/14.0);
}
TEST(CellIndex, neighborList){
const int seed = 19937;
const int n = 8192;
const double l_domain = 100.0;
const double r_search = 9.0;
std::mt19937 mt;
std::uniform_real_distribution<> dist_real(0.0, l_domain);
mt.seed(seed);
//--- test target
std::vector<PS::F32vec> pos;
MD_EXT::CellIndex<size_t> cell_index;
std::vector<std::vector<size_t>> pair_list_ref;
//--- make pos data
pos.clear();
for(int i=0; i<n; ++i){
pos.push_back( PS::F32vec{ static_cast<PS::F32>(dist_real(mt)),
static_cast<PS::F32>(dist_real(mt)),
static_cast<PS::F32>(dist_real(mt)) } );
}
//--- make 1D pair list (direct method, reference data)
pair_list_ref.clear();
pair_list_ref.resize(n);
const double r2_search = r_search*r_search;
for(int i=0; i<n; ++i){
pair_list_ref.at(i).clear();
for(int j=0; j<n; ++j){
if(j == i) continue;
PS::F32vec r_pos = pos.at(j) - pos.at(i);
PS::F32 r2 = r_pos*r_pos;
if(r2 <= r2_search){
pair_list_ref.at(i).push_back(j);
}
}
}
//--- init cell index
cell_index.init( PS::F32vec{0.0, 0.0, 0.0},
PS::F32vec{l_domain, l_domain, l_domain},
r_search );
//--- make index table in cell
for(int i=0; i<n; ++i){
cell_index.add(pos.at(i), i);
}
//--- compare result (internal buffer)
for(int i=0; i<n; ++i){
const auto& list_ref = pair_list_ref.at(i);
const auto cell_data = cell_index.get_data_list(pos.at(i), r_search);
for(const auto tgt : list_ref){
size_t n_tgt = std::count(cell_data.begin(), cell_data.end(), tgt);
EXPECT_EQ(n_tgt, 1) << " i= " << i << " tgt= " << tgt;
}
}
//--- compare result (const interface for outside buffer)
std::vector<MD_EXT::CellIndex<size_t>::index_type> cell_list;
std::vector<MD_EXT::CellIndex<size_t>::value_type> cell_data;
for(int i=0; i<n; ++i){
const auto& list_ref = pair_list_ref.at(i);
cell_list.clear();
cell_data.clear();
cell_index.get_data_list(pos.at(i), r_search, cell_list, cell_data);
for(const auto tgt : list_ref){
size_t n_tgt = std::count(cell_data.begin(), cell_data.end(), tgt);
EXPECT_EQ(n_tgt, 1) << " i= " << i << " tgt= " << tgt;
}
}
}
#include "gtest_main.hpp"
| 34.907563 | 89 | 0.546221 | Tokumasu-Lab |
ab94cb1579125dcb138ead1aea9e3e76b30621f8 | 4,866 | cpp | C++ | pwiz/analysis/eharmony/PeptideMatcher.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/analysis/eharmony/PeptideMatcher.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/analysis/eharmony/PeptideMatcher.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | //
// $Id$
//
//
// Original author: Kate Hoff <katherine.hoff@proteowizard.org>
//
// Copyright 2009 Center for Applied Molecular Medicine
// University of Southern California, Los Angeles, CA
//
// 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 "PeptideMatcher.hpp"
#include "pwiz/utility/proteome/Ion.hpp"
#include "pwiz/utility/misc/Std.hpp"
using namespace pwiz::cv;
using namespace pwiz::eharmony;
using namespace pwiz::proteome;
struct Compare
{
Compare(){}
bool operator()(const boost::shared_ptr<SpectrumQuery>& a, const boost::shared_ptr<SpectrumQuery>& b)
{
return (a->searchResult.searchHit.peptide < b->searchResult.searchHit.peptide); // sort vector of spectrum queries by sequence
}
};
PeptideMatcher::PeptideMatcher(const PidfPtr _pidf_a, const PidfPtr _pidf_b)
{
vector<boost::shared_ptr<SpectrumQuery> > a = _pidf_a->getAllContents();
sort(a.begin(), a.end(), Compare());
vector<boost::shared_ptr<SpectrumQuery> > b = _pidf_b->getAllContents();
sort(b.begin(), b.end(), Compare());
vector<boost::shared_ptr<SpectrumQuery> >::iterator a_it = a.begin();
vector<boost::shared_ptr<SpectrumQuery> >::iterator b_it = b.begin();
while ( a_it != a.end() && b_it != b.end() )
{
if ((*a_it)->searchResult.searchHit.peptide == (*b_it)->searchResult.searchHit.peptide)
{
if (fabs(Ion::mz((*a_it)->precursorNeutralMass, (*a_it)->assumedCharge) - Ion::mz((*b_it)->precursorNeutralMass, (*b_it)->assumedCharge)) < 1 ) _matches.push_back(make_pair(*a_it, *b_it));
++a_it;
++b_it;
}
else if ((*a_it)->searchResult.searchHit.peptide > (*b_it)->searchResult.searchHit.peptide) ++b_it;
else ++a_it;
}
}
void PeptideMatcher::calculateDeltaRTDistribution()
{
if (_matches.size() == 0)
{
cerr << "[PeptideMatcher::calculateDeltaRTDistribution] No matching MS/MS IDS found. DeltaRT params are both set to 0." << endl;
return;
}
double meanSum = 0;
PeptideMatchContainer::iterator match_it = _matches.begin();
for(; match_it != _matches.end(); ++match_it)
{
meanSum += (match_it->first->retentionTimeSec - match_it->second->retentionTimeSec);
}
_meanDeltaRT = meanSum / _matches.size();
double stdevSum = 0;
PeptideMatchContainer::iterator stdev_it = _matches.begin();
for(; stdev_it != _matches.end(); ++stdev_it)
{
const double& rt_a = stdev_it->first->retentionTimeSec;
const double& rt_b = stdev_it->second->retentionTimeSec;
stdevSum += ((rt_a - rt_b) - _meanDeltaRT)*((rt_a - rt_b) - _meanDeltaRT);
}
_stdevDeltaRT = sqrt(stdevSum / _matches.size());
return;
}
void PeptideMatcher::calculateDeltaMZDistribution()
{
if (_matches.size() == 0)
{
cerr << "[PeptideMatcher::calculateDeltaMZDistribution] No matching MS/MS IDS found. DeltaMZ params are both set to 0." << endl;
return;
}
double meanSum = 0;
PeptideMatchContainer::iterator match_it = _matches.begin();
for(; match_it != _matches.end(); ++match_it)
{
double increment = (Ion::mz(match_it->first->precursorNeutralMass, match_it->first->assumedCharge) - Ion::mz(match_it->second->precursorNeutralMass, match_it->second->assumedCharge));
meanSum += increment;
}
_meanDeltaMZ = meanSum / _matches.size();
double stdevSum = 0;
PeptideMatchContainer::iterator stdev_it = _matches.begin();
for(; stdev_it != _matches.end(); ++stdev_it)
{
const double& mz_a = Ion::mz(stdev_it->first->precursorNeutralMass, stdev_it->first->assumedCharge);
const double& mz_b = Ion::mz(stdev_it->second->precursorNeutralMass, stdev_it->second->assumedCharge);
stdevSum += ((mz_a - mz_b) - _meanDeltaMZ)*((mz_a - mz_b) - _meanDeltaMZ);
}
_stdevDeltaMZ = sqrt(stdevSum / _matches.size());
return;
}
bool PeptideMatcher::operator==(const PeptideMatcher& that)
{
return _matches == that.getMatches() &&
make_pair(_meanDeltaRT, _stdevDeltaRT) == that.getDeltaRTParams();
}
bool PeptideMatcher::operator!=(const PeptideMatcher& that)
{
return !(*this == that);
}
| 31.393548 | 208 | 0.651254 | austinkeller |
ab98f6ac312fbcacc663fe274d93a9abd1679c02 | 75,772 | cpp | C++ | frameworks/proxy/event_handle/test/multimodal_semanager_second_test.cpp | openharmony-gitee-mirror/multimodalinput_input | 17303b7662d0382f27c972ad7d149bee61a14f23 | [
"Apache-2.0"
] | 1 | 2021-12-03T13:56:40.000Z | 2021-12-03T13:56:40.000Z | frameworks/proxy/event_handle/test/multimodal_semanager_second_test.cpp | openharmony-gitee-mirror/multimodalinput_input | 17303b7662d0382f27c972ad7d149bee61a14f23 | [
"Apache-2.0"
] | null | null | null | frameworks/proxy/event_handle/test/multimodal_semanager_second_test.cpp | openharmony-gitee-mirror/multimodalinput_input | 17303b7662d0382f27c972ad7d149bee61a14f23 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:18:23.000Z | 2021-09-13T11:18:23.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 <locale>
#include <codecvt>
#include <gtest/gtest.h>
#include "string_ex.h"
#include "proto.h"
#include "util_ex.h"
#include "define_multimodal.h"
#include "multimodal_standardized_event_manager.h"
#include "multimodal_event_handler.h"
#include "mmi_token.h"
namespace {
using namespace testing::ext;
using namespace OHOS::MMI;
using namespace OHOS;
class MultimodalSemanagerSecondTest : public testing::Test {
public:
static void SetUpTestCase(void) {}
static void TearDownTestCase(void) {}
protected:
const unsigned int g_surFaceId = 10;
};
class MultimodalEventSecondUnitTest : public MultimodalStandardizedEventManager {
public:
bool MakeRegisterHandleUnitTest(MmiMessageId typeId, int32_t windowId, std::string& rhandle)
{
return MakeRegisterHandle(typeId, windowId, rhandle);
}
bool SendMsgUnitTest(NetPacket& pkt)
{
return SendMsg(pkt);
}
bool InsertMapEvent(MmiMessageId typeId, StandEventPtr standardizedEventHandle)
{
const int32_t windowId = 22;
struct StandEventCallBack StandEventInfo = {};
StandEventInfo.windowId = windowId;
StandEventInfo.eventCallBack = standardizedEventHandle;
mapEvents_.insert(std::make_pair(typeId, StandEventInfo));
return true;
}
};
HWTEST_F(MultimodalSemanagerSecondTest, OnNext_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTest;
MultimodalEvent event;
int32_t retResult = multimodalTest.OnNext(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnNext_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::COMMON_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnNext(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnNext_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::COMMON_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnNext(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnNext_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnNext(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnNext_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::COMMON_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnNext(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnNext_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::COMMON_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnNext(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnNext_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnNext(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnNext_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('0');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnNext(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnBack_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTest;
MultimodalEvent event;
int32_t retResult = multimodalTest.OnBack(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnBack_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::COMMON_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnBack(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnBack_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::COMMON_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnBack(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnBack_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnBack(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnBack_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::COMMON_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnBack(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnBack_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::COMMON_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnBack(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnBack_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnBack(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnBack_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('p');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnBack(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPrint_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTest;
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPrint(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPrint_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::COMMON_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPrint(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPrint_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::COMMON_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPrint(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPrint_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPrint(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPrint_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::COMMON_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPrint(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPrint_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::COMMON_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPrint(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPrint_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPrint(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPrint_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('q');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPrint(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPlay_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTest;
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPlay(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPlay_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::MEDIA_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPlay(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPlay_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::MEDIA_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPlay(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPlay_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPlay(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPlay_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::MEDIA_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPlay(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPlay_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::MEDIA_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPlay(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPlay_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPlay(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPlay_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('r');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTest;
multimodalTest.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPlay(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPause_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTest;
MultimodalEvent event;
int32_t retResult = multimodalTest.OnPause(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPause_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::MEDIA_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnPause(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPause_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::MEDIA_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnPause(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPause_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnPause(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPause_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::MEDIA_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnPause(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPause_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::MEDIA_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnPause(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPause_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnPause(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnPause_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('s');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnPause(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnMediaControl_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTest;
MultimodalEvent event;
int32_t retResult = multimodalTest.OnMediaControl(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnMediaControl_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::MEDIA_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnMediaControl(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnMediaControl_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::MEDIA_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnMediaControl(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnMediaControl_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnMediaControl(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnMediaControl_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::MEDIA_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnMediaControl(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnMediaControl_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::MEDIA_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnMediaControl(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnMediaControl_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnMediaControl(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnMediaControl_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('t');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnMediaControl(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenShot_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTest;
MultimodalEvent event;
int32_t retResult = multimodalTest.OnScreenShot(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenShot_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenShot(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenShot_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenShot(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenShot_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenShot(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenShot_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenShot(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenShot_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenShot(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenShot_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenShot(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenShot_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('u');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenShot(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenSplit_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTest;
MultimodalEvent event;
int32_t retResult = multimodalTest.OnScreenSplit(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenSplit_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenSplit(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenSplit_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenSplit(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenSplit_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenSplit(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenSplit_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenSplit(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenSplit_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenSplit(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenSplit_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenSplit(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnScreenSplit_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('v');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnScreenSplit(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStartScreenRecord_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTest;
MultimodalEvent event;
int32_t retResult = multimodalTest.OnStartScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStartScreenRecord_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStartScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStartScreenRecord_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStartScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStartScreenRecord_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStartScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStartScreenRecord_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStartScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStartScreenRecord_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStartScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStartScreenRecord_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStartScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStartScreenRecord_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('w');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStartScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStopScreenRecord_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTest;
MultimodalEvent event;
int32_t retResult = multimodalTest.OnStopScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStopScreenRecord_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStopScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStopScreenRecord_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStopScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStopScreenRecord_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStopScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStopScreenRecord_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStopScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStopScreenRecord_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStopScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStopScreenRecord_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStopScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnStopScreenRecord_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('w');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnStopScreenRecord(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnGotoDesktop_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTestTmp;
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnGotoDesktop(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnGotoDesktop_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnGotoDesktop(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnGotoDesktop_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnGotoDesktop(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnGotoDesktop_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnGotoDesktop(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnGotoDesktop_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnGotoDesktop(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnGotoDesktop_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnGotoDesktop(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnGotoDesktop_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnGotoDesktop(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnGotoDesktop_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('w');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnGotoDesktop(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnRecent_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTestTmp;
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnRecent(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnRecent_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnRecent(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnRecent_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnRecent(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnRecent_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnRecent(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnRecent_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnRecent(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnRecent_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnRecent(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnRecent_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnRecent(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnRecent_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('x');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnRecent(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnShowNotification_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTestTmp;
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnShowNotification(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnShowNotification_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnShowNotification(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnShowNotification_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnShowNotification(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnShowNotification_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnShowNotification(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnShowNotification_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnShowNotification(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnShowNotification_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnShowNotification(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnShowNotification_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnShowNotification(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnShowNotification_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('x');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnShowNotification(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnLockScreen_001, TestSize.Level1)
{
MultimodalEventSecondUnitTest multimodalTestTmp;
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnLockScreen(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnLockScreen_002, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnLockScreen(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnLockScreen_003, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnLockScreen(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnLockScreen_004, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnLockScreen(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnLockScreen_005, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = MmiMessageId::SYSTEM_EVENT_BEGIN;
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnLockScreen(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnLockScreen_006, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = EnumAdd(MmiMessageId::SYSTEM_EVENT_BEGIN, 1);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnLockScreen(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnLockScreen_007, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
MmiMessageId typeNum = static_cast<MmiMessageId>(-1001);
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnLockScreen(event);
EXPECT_TRUE(retResult == RET_OK);
}
HWTEST_F(MultimodalSemanagerSecondTest, OnLockScreen_008, TestSize.Level1)
{
const std::string strDesc = "hello world!";
const std::u16string u16Desc = Str8ToStr16(strDesc);
auto iRemote = MMIToken::Create(u16Desc);
auto typeNum = static_cast<MmiMessageId>('y');
auto tmpObj = StandardizedEventHandler::Create<StandardizedEventHandler>();
tmpObj->SetType(typeNum);
MMIEventHdl.RegisterStandardizedEventHandle(iRemote, g_surFaceId, tmpObj);
MultimodalEventSecondUnitTest multimodalTestTmp;
multimodalTestTmp.InsertMapEvent(typeNum, tmpObj);
MultimodalEvent event;
int32_t retResult = multimodalTestTmp.OnLockScreen(event);
EXPECT_TRUE(retResult == RET_OK);
}
} // namespace
| 41.678768 | 96 | 0.77237 | openharmony-gitee-mirror |
ab9af8c4d401cf7813a4789505c8f92cbd2753ee | 16,385 | cpp | C++ | Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Sensors Geolocation Sample Driver (UMDF Version 1)/C++/RadioManagerGPS/SampleRadioManager.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2022-01-21T01:40:58.000Z | 2022-01-21T01:41:10.000Z | Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Sensors Geolocation Sample Driver (UMDF Version 1)/C++/RadioManagerGPS/SampleRadioManager.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 1 | 2022-03-15T04:21:41.000Z | 2022-03-15T04:21:41.000Z | Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Sensors Geolocation Sample Driver (UMDF Version 1)/C++/RadioManagerGPS/SampleRadioManager.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2020-10-19T23:36:26.000Z | 2020-10-22T12:59:37.000Z | #include "precomp.h"
#pragma hdrstop
CSampleRadioManager::CSampleRadioManager() :
_pSensorManagerEvents(nullptr),
_hPnPEventThread(nullptr),
_hPnPEventThreadEvent(nullptr),
_hPnPEventWindow(nullptr)
{
}
HRESULT CSampleRadioManager::FinalConstruct()
{
HRESULT hr = S_OK;
// Create Sensor Manager to use to connect to sensor
hr = _spSensorManager.CoCreateInstance(CLSID_SensorManager, nullptr, CLSCTX_INPROC_SERVER);
if (SUCCEEDED(hr))
{
// Add the one radio that is managed if it is present
HRESULT hrTemp = S_OK;
{
// Brackets for sensorComm scope
CSensorCommunication sensorComm = CSensorCommunication();
hrTemp = sensorComm.Initialize();
}
if (SUCCEEDED(hrTemp))
{
hr = _AddInstance(SENSOR_GUID_STRING, nullptr);
}
// Listen for sensor add events
if (SUCCEEDED(hr))
{
// Will be deleted in _Cleanup
_pSensorManagerEvents = new CSensorManagerEvents(this, _spSensorManager);
if (nullptr != _pSensorManagerEvents)
{
hr = _pSensorManagerEvents->Initialize();
}
else
{
hr = E_OUTOFMEMORY;
}
}
// Listen for sensor leave events.
// Listen for PnP events instead of subscribing to sensor events as subscribing
// to sensor events will create a persistent connection to the driver.
_InitializeSensorLeaveEvents();
}
if (FAILED(hr))
{
_Cleanup();
}
return hr;
}
HRESULT CSampleRadioManager::_InitializeSensorLeaveEvents()
{
HRESULT hr = S_OK;
// Create an event so we can be notified when the thread is initialized.
_hPnPEventThreadEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
if (nullptr != _hPnPEventThreadEvent)
{
_hPnPEventThread = ::CreateThread(
nullptr,
0,
s_ThreadPnPEvent,
this,
0,
nullptr);
if (nullptr == _hPnPEventThread)
{
hr = GetLastError();
}
else
{
(void)::WaitForSingleObject(_hPnPEventThreadEvent, INFINITE);
}
::CloseHandle(_hPnPEventThreadEvent);
_hPnPEventThreadEvent = nullptr;
}
else
{
hr = GetLastError();
}
return hr;
}
void CSampleRadioManager::FinalRelease()
{
_Cleanup();
}
void CSampleRadioManager::_Cleanup()
{
POSITION p;
while (nullptr != (p = _listRadioInstances.GetHeadPosition()))
{
INSTANCE_LIST_OBJ *pListObj = _listRadioInstances.GetAt(p);
if (nullptr != pListObj)
{
_listRadioInstances.SetAt(p, nullptr);
_listRadioInstances.RemoveHeadNoReturn();
delete pListObj;
}
}
if (nullptr != _pSensorManagerEvents)
{
delete _pSensorManagerEvents;
}
// Destory the window
if (nullptr != _hPnPEventWindow)
{
if (0 != PostMessage(_hPnPEventWindow, WM_DESTROY, 0, 0))
{
_hPnPEventWindow = nullptr;
// Wait for the destroy window to be processed
if (nullptr != _hPnPEventThread)
{
(void)::WaitForSingleObject(_hPnPEventThread, INFINITE);
}
}
}
if (nullptr != _hPnPEventThread)
{
CloseHandle(_hPnPEventThread);
_hPnPEventThread = nullptr;
}
}
IFACEMETHODIMP CSampleRadioManager::GetRadioInstances(_Out_ IRadioInstanceCollection **ppCollection)
{
CAutoVectorPtr<IRadioInstance *> rgpIRadioInstance;
HRESULT hr = S_OK;
DWORD cInstance;
if (nullptr == ppCollection)
{
return E_INVALIDARG;
}
*ppCollection = nullptr;
CComCritSecLock<CComAutoCriticalSection> lock(_criticalSection);
cInstance = static_cast<DWORD>(_listRadioInstances.GetCount());
if (cInstance > 0)
{
if (!rgpIRadioInstance.Allocate(cInstance))
{
hr = E_OUTOFMEMORY;
}
if (SUCCEEDED(hr))
{
ZeroMemory(rgpIRadioInstance, sizeof(rgpIRadioInstance[0]) * cInstance);
DWORD dwIndex = 0;
for (POSITION p = _listRadioInstances.GetHeadPosition(); nullptr != p; _listRadioInstances.GetNext(p))
{
hr = (_listRadioInstances.GetAt(p))->spRadioInstance.QueryInterface(&(rgpIRadioInstance[dwIndex]));
if (FAILED(hr))
{
break;
}
else
{
dwIndex++;
}
}
}
}
if (SUCCEEDED(hr))
{
hr = CRadioInstanceCollection_CreateInstance(cInstance, rgpIRadioInstance, ppCollection);
}
for (DWORD dwIndex = 0; dwIndex < cInstance; dwIndex++)
{
if (nullptr != rgpIRadioInstance[dwIndex])
{
rgpIRadioInstance[dwIndex]->Release();
}
}
return hr;
}
IFACEMETHODIMP CSampleRadioManager::OnSystemRadioStateChange(
_In_ SYSTEM_RADIO_STATE sysRadioState,
_In_ UINT32 uTimeoutSec)
{
HRESULT hr = S_OK;
CAutoPtr<SET_SYS_RADIO_JOB> spSetSysRadioJob;
bool fRefAdded = false;
spSetSysRadioJob.Attach(new SET_SYS_RADIO_JOB);
if (nullptr == spSetSysRadioJob)
{
hr = E_OUTOFMEMORY;
}
if (SUCCEEDED(hr))
{
spSetSysRadioJob->hr = E_FAIL;
spSetSysRadioJob->srsTarget = sysRadioState;
spSetSysRadioJob->pSampleRM = this;
// Add ref to object to avoid object release before working thread return
this->AddRef();
fRefAdded = true;
HANDLE hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
if (nullptr == hEvent)
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
else
{
spSetSysRadioJob->hEvent.Attach(hEvent);
}
}
if (SUCCEEDED(hr))
{
if (!QueueUserWorkItem(CSampleRadioManager::s_ThreadSetSysRadio, spSetSysRadioJob, WT_EXECUTEDEFAULT))
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
}
if (SUCCEEDED(hr))
{
DWORD dwIgnore;
hr = CoWaitForMultipleHandles(0,
uTimeoutSec * 1000,
1,
reinterpret_cast<LPHANDLE>(&(spSetSysRadioJob->hEvent)),
&dwIgnore);
if (RPC_S_CALLPENDING == hr)
{
spSetSysRadioJob.Detach();
}
else
{
hr = spSetSysRadioJob->hr;
}
}
if (fRefAdded)
{
this->Release();
}
return hr;
}
IFACEMETHODIMP CSampleRadioManager::OnInstanceRadioChange(
_In_ BSTR bstrRadioInstanceID,
_In_ DEVICE_RADIO_STATE radioState)
{
return _FireEventOnInstanceRadioChange(bstrRadioInstanceID, radioState);
}
HRESULT CSampleRadioManager::_FireEventOnInstanceAdd(_In_ IRadioInstance *pRadioInstance)
{
HRESULT hr;
Lock();
for (IUnknown** ppUnkSrc = m_vec.begin(); ppUnkSrc < m_vec.end(); ppUnkSrc++)
{
if ((nullptr != ppUnkSrc) && (nullptr != *ppUnkSrc))
{
CComPtr<IMediaRadioManagerNotifySink> spSink;
hr = (*ppUnkSrc)->QueryInterface(IID_PPV_ARGS(&spSink));
if (SUCCEEDED(hr))
{
spSink->OnInstanceAdd(pRadioInstance);
}
}
}
Unlock();
return S_OK;
}
HRESULT CSampleRadioManager::_FireEventOnInstanceRemove(_In_ BSTR bstrRadioInstanceID)
{
HRESULT hr;
Lock();
for (IUnknown** ppUnkSrc = m_vec.begin(); ppUnkSrc < m_vec.end(); ppUnkSrc++)
{
if ((nullptr != ppUnkSrc) && (nullptr != *ppUnkSrc))
{
CComPtr<IMediaRadioManagerNotifySink> spSink;
hr = (*ppUnkSrc)->QueryInterface(IID_PPV_ARGS(&spSink));
if (SUCCEEDED(hr))
{
spSink->OnInstanceRemove(bstrRadioInstanceID);
}
}
}
Unlock();
return S_OK;
}
HRESULT CSampleRadioManager::_FireEventOnInstanceRadioChange(
_In_ BSTR bstrRadioInstanceID,
_In_ DEVICE_RADIO_STATE radioState
)
{
HRESULT hr;
Lock();
for (IUnknown** ppUnkSrc = m_vec.begin(); ppUnkSrc < m_vec.end(); ppUnkSrc++)
{
if ((nullptr != ppUnkSrc) && (nullptr != *ppUnkSrc))
{
CComPtr<IMediaRadioManagerNotifySink> spSink;
hr = (*ppUnkSrc)->QueryInterface(IID_PPV_ARGS(&spSink));
if (SUCCEEDED(hr))
{
spSink->OnInstanceRadioChange(bstrRadioInstanceID, radioState);
}
}
}
Unlock();
return S_OK;
}
HRESULT CSampleRadioManager::_AddInstance(_In_ PCWSTR pszKeyName, _Out_opt_ IRadioInstance **ppRadioInstance)
{
HRESULT hr = S_OK;
CComPtr<ISampleRadioInstanceInternal> spRadioInstance;
CAutoPtr<INSTANCE_LIST_OBJ> spInstanceObj;
CComCritSecLock<CComAutoCriticalSection> lock(_criticalSection);
spInstanceObj.Attach(new INSTANCE_LIST_OBJ);
if (nullptr == spInstanceObj)
{
hr = E_OUTOFMEMORY;
}
if (SUCCEEDED(hr))
{
CComPtr<ISampleRadioManagerInternal> spRMInternal = this;
hr = CSampleRadioInstance_CreateInstance(pszKeyName, spRMInternal, &spRadioInstance);
}
if (SUCCEEDED(hr))
{
spInstanceObj->fExisting = true;
spInstanceObj->spRadioInstance = spRadioInstance;
_ATLTRY
{
spInstanceObj->strRadioInstanceID = pszKeyName;
_listRadioInstances.AddTail(spInstanceObj);
spInstanceObj.Detach();
}
_ATLCATCH(e)
{
hr = e;
}
if (SUCCEEDED(hr))
{
if (ppRadioInstance != nullptr)
{
hr = spRadioInstance->QueryInterface(IID_PPV_ARGS(ppRadioInstance));
}
}
}
return hr;
}
HRESULT CSampleRadioManager::_SetSysRadioState(_In_ SYSTEM_RADIO_STATE sysRadioState)
{
HRESULT hr = S_OK;
CComCritSecLock<CComAutoCriticalSection> lock(_criticalSection);
for (POSITION p = _listRadioInstances.GetHeadPosition(); nullptr != p; _listRadioInstances.GetNext(p))
{
INSTANCE_LIST_OBJ *pInstanceObj = _listRadioInstances.GetAt(p);
hr = pInstanceObj->spRadioInstance->OnSysRadioChange(sysRadioState);
if (FAILED(hr))
{
break;
}
}
return hr;
}
DWORD WINAPI CSampleRadioManager::s_ThreadSetSysRadio(LPVOID pThis)
{
SET_SYS_RADIO_JOB *pJob = reinterpret_cast<SET_SYS_RADIO_JOB *>(pThis);
pJob->hr = pJob->pSampleRM->_SetSysRadioState(pJob->srsTarget);
SetEvent(pJob->hEvent);
return ERROR_SUCCESS;
}
void CSampleRadioManager::SensorAdded()
{
CComPtr<IRadioInstance> spRadioInstance;
HRESULT hr = _AddInstance(SENSOR_GUID_STRING, &spRadioInstance);
if (SUCCEEDED(hr))
{
_FireEventOnInstanceAdd(spRadioInstance);
}
}
void CSampleRadioManager::SensorRemoved()
{
// Remove deleted instance from list
POSITION p = _listRadioInstances.GetHeadPosition();
while (nullptr != p)
{
INSTANCE_LIST_OBJ *pRadioInstanceObj = _listRadioInstances.GetAt(p);
if (pRadioInstanceObj != nullptr && 0 == pRadioInstanceObj->strRadioInstanceID.Compare(SENSOR_GUID_STRING))
{
POSITION pTmp = p;
_listRadioInstances.GetPrev(pTmp);
_listRadioInstances.RemoveAt(p);
CComBSTR bstrTmp = pRadioInstanceObj->strRadioInstanceID.AllocSysString();
if (nullptr != bstrTmp)
{
_FireEventOnInstanceRemove(bstrTmp);
}
delete pRadioInstanceObj;
p = pTmp;
}
if (nullptr != p)
{
_listRadioInstances.GetNext(p);
}
else
{
p = _listRadioInstances.GetHeadPosition();
}
}
}
DWORD WINAPI CSampleRadioManager::s_ThreadPnPEvent(LPVOID pThat)
{
// This thread creates a window that will listen for PnP Events
CSampleRadioManager* pThis = reinterpret_cast<CSampleRadioManager *>(pThat);
CComBSTR bstrClassName = CComBSTR("RadioManger_");
(void)bstrClassName.Append(SENSOR_GUID_STRING);
// Register and create the window.
WNDCLASSEXW wndclass = {0};
wndclass.cbSize = sizeof(wndclass);
wndclass.lpfnWndProc = _PnPEventWndProc;
wndclass.lpszClassName = bstrClassName;
wndclass.hInstance = g_hInstance;
(void)::RegisterClassEx(&wndclass);
pThis->_hPnPEventWindow = ::CreateWindowEx(
0,
bstrClassName,
L"",
0, 0, 0, 0, 0,
nullptr,
nullptr,
g_hInstance,
(LPVOID)(pThis)
);
if (nullptr != pThis->_hPnPEventWindow)
{
// Register for PnP events
DEV_BROADCAST_DEVICEINTERFACE devBroadcastInterface = {0};
devBroadcastInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
devBroadcastInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
devBroadcastInterface.dbcc_name[0] = 0;
devBroadcastInterface.dbcc_classguid = SENSOR_TYPE_LOCATION_GPS;
HDEVNOTIFY hdevNotify = ::RegisterDeviceNotification(
pThis->_hPnPEventWindow,
&devBroadcastInterface,
DEVICE_NOTIFY_WINDOW_HANDLE);
if (nullptr != hdevNotify)
{
// Signal the event so that the main thread knows the HWND is set.
(void)::SetEvent(pThis->_hPnPEventThreadEvent);
MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::UnregisterDeviceNotification(hdevNotify);
}
}
::UnregisterClass(bstrClassName, g_hInstance);
return 0;
}
LRESULT WINAPI CSampleRadioManager::_PnPEventWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
// Window Proc that receives PnP Events. Used to detect when a sensor leaves.
LRESULT lRes = 0;
CSampleRadioManager* pThis = nullptr;
if (WM_CREATE == uMsg)
{
// On first run, give the window access to the parent this pointer
SetLastError(ERROR_SUCCESS); // Required to detect if return value of 0 from SetWindowLongPtr is null or error
pThis = reinterpret_cast<CSampleRadioManager*>(((LPCREATESTRUCT)lParam)->lpCreateParams);
if (0 == SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pThis))
{
// Return value of 0 could be that pervious pointer was null
HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
if (FAILED(hr))
{
lRes = -1;
}
}
}
else if (uMsg == WM_DESTROY)
{
::SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)NULL);
PostQuitMessage(0);
}
else if (uMsg == WM_DEVICECHANGE)
{
// Determine if this device event is the sensor leaving the system
pThis = reinterpret_cast<CSampleRadioManager*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
if (nullptr != pThis && NULL != lParam && DBT_DEVICEREMOVECOMPLETE == wParam)
{
PDEV_BROADCAST_DEVICEINTERFACE pDevIF = reinterpret_cast<PDEV_BROADCAST_DEVICEINTERFACE>(lParam);
if ((DBT_DEVTYP_DEVICEINTERFACE == pDevIF->dbcc_devicetype) &&
(IsEqualGUID(SENSOR_TYPE_LOCATION_GPS, pDevIF->dbcc_classguid)))
{
// Make sure this is the correct sensor by comparing Sensor ID in device path
// Device path is contained in pDevIF->dbcc_name
// Check to see if sensor id matches
WCHAR* pRefString = wcsrchr(pDevIF->dbcc_name, L'\\');
if (nullptr != pRefString)
{
pRefString++; // skip past backslash
if (0 == _wcsicmp(SENSOR_GUID_STRING, pRefString))
{
pThis->SensorRemoved();
}
}
}
}
}
if (0 == lRes)
{
lRes = DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return lRes;
} | 27.724196 | 118 | 0.595606 | zzgchina888 |
ab9d1614d83ef9bcca23fdc89da22a7a64a5c25a | 714 | cpp | C++ | test/algorithm/has_identity.cpp | muqsitnawaz/mate | 0353bb9bd04db0b7b4a547878e76617ed547b337 | [
"MIT"
] | null | null | null | test/algorithm/has_identity.cpp | muqsitnawaz/mate | 0353bb9bd04db0b7b4a547878e76617ed547b337 | [
"MIT"
] | null | null | null | test/algorithm/has_identity.cpp | muqsitnawaz/mate | 0353bb9bd04db0b7b4a547878e76617ed547b337 | [
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include "mate/algorithm/has_identity.hpp"
TEST(IdentityTest, Additive)
{
const mate::Set_type<int> set { 1, 2, 3, 4, 5 };
EXPECT_FALSE(mate::has_identity<mate::Addition>(set));
const mate::Set_type<int> set1 { 0, 1, 2, 3, 4, 5 };
EXPECT_TRUE(mate::has_identity<mate::Addition>(set1));
}
TEST(IdentityTest, Multiplicative)
{
const mate::Set_type<int> set { 2, 3, 4, 5 };
EXPECT_FALSE(mate::has_identity<mate::Multiplication>(set));
const mate::Set_type<int> set1 { 1, 2, 3, 4, 5 };
EXPECT_TRUE(mate::has_identity<mate::Multiplication>(set1));
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 25.5 | 64 | 0.665266 | muqsitnawaz |
aba103dacd5a9d35d1adb833cbfea4d3c88d308e | 7,170 | cpp | C++ | Build/hosEngine/AudioSource.cpp | Game-institute-1st-While-true/hosEngine | 2cc0b464740a976a8b37afd7a9e3479fe7484cf0 | [
"MIT"
] | null | null | null | Build/hosEngine/AudioSource.cpp | Game-institute-1st-While-true/hosEngine | 2cc0b464740a976a8b37afd7a9e3479fe7484cf0 | [
"MIT"
] | null | null | null | Build/hosEngine/AudioSource.cpp | Game-institute-1st-While-true/hosEngine | 2cc0b464740a976a8b37afd7a9e3479fe7484cf0 | [
"MIT"
] | 2 | 2021-07-14T00:14:18.000Z | 2021-07-27T04:16:53.000Z | #include "AudioSource.h"
#include "Transform.h"
#include "GameObject.h"
#include "Scene.h"
#include "AudioListener.h"
using namespace hos;
// FL FR C LFE BL BR SL SR
//Degree(0~360) 334 26 0 360 260 100 217.5 142.5
static float EmitterAngle[] =
{
5.8294f, //Front Left
0.453786f, //Front Right
0.f, //Center
X3DAUDIO_2PI, //Low-frequency effects
3.7960911f, //Back Left
1.74533f, //Back Right
4.53786f, //Surround Left
2.4870942f, //Surround Right
};
hos::com::AudioSource::AudioSource() :
Component(L"AudioSource")
{
Reset();
}
hos::com::AudioSource::~AudioSource()
{
Stop();
SafeDelete(Source);
}
hos::com::AudioSource::AudioSource(const AudioSource& dest) :
Component(dest),
Clip(dest.Clip),
Mute(dest.Mute),
Loop(dest.Loop),
PlayOnAwake(dest.PlayOnAwake),
Volume(dest.Volume),
Is3D(dest.Is3D),
Range(dest.Range),
Source(nullptr)
{
if (Clip && Clip->Sound)
{
dest.Source->Stop();
Source = Clip->Sound->CreateInstance(DirectX::SoundEffectInstance_Use3D | DirectX::SoundEffectInstance_ReverbUseFilters).release();
if (Source)
{
SetVolume(Volume);
if (Is3D)
{
Emitter.ChannelCount = Clip->Sound->GetFormat()->nChannels;
Emitter.pChannelAzimuths = EmitterAngle;
Emitter.CurveDistanceScaler = Range;
Emitter.pVolumeCurve = const_cast<X3DAUDIO_DISTANCE_CURVE*>(&X3DAudioDefault_LinearCurve);
}
}
}
}
void hos::com::AudioSource::SetAudioClip(AudioClip* clip)
{
Stop();
SafeDelete(Source);
Clip = clip;
if (Clip)
{
Source = Clip->Sound->CreateInstance(DirectX::SoundEffectInstance_Use3D | DirectX::SoundEffectInstance_ReverbUseFilters).release();
if (Source)
{
if (Is3D)
{
Emitter.ChannelCount = Clip->Sound->GetFormat()->nChannels;
Emitter.pChannelAzimuths = EmitterAngle;
Emitter.CurveDistanceScaler = Range;
Emitter.pVolumeCurve = const_cast<X3DAUDIO_DISTANCE_CURVE*>(&X3DAudioDefault_LinearCurve);
}
}
}
}
void hos::com::AudioSource::SetAudioClip(string_view name)
{
Stop();
SafeDelete(Source);
AudioClip* _Clip = g_DataManager->GetAudioClip(name);
if (_Clip)
{
Clip = _Clip;
Source = Clip->Sound->CreateInstance(DirectX::SoundEffectInstance_Use3D | DirectX::SoundEffectInstance_ReverbUseFilters).release();
if (Source)
{
if (Is3D)
{
Emitter.ChannelCount = Clip->Sound->GetFormat()->nChannels;
Emitter.pChannelAzimuths = EmitterAngle;
Emitter.CurveDistanceScaler = Range;
Emitter.pVolumeCurve = const_cast<X3DAUDIO_DISTANCE_CURVE*>(&X3DAudioDefault_LinearCurve);
}
}
}
}
void hos::com::AudioSource::SetMute(bool b)
{
Mute = b;
if (Mute)
{
if (Source)
{
Source->SetVolume(0);
}
}
else
{
if (Source)
{
Source->SetVolume(Volume);
}
}
}
void hos::com::AudioSource::SetLoop(bool b)
{
Loop = b;
if (Source)
{
if (Source->GetState() == DirectX::SoundState::PLAYING)
{
Source->Stop();
Source->Play(Loop);
}
}
}
void hos::com::AudioSource::SetPlayOnAwake(bool b)
{
PlayOnAwake = b;
}
void hos::com::AudioSource::SetIs3D(bool b)
{
Is3D = b;
}
void hos::com::AudioSource::SetVolume(float volume)
{
Volume = Max(0.f, Min(volume, 1.f));
if (!Mute)
{
if (Source)
{
Source->SetVolume(Volume);
}
}
}
void hos::com::AudioSource::SetRange(float range)
{
Range = range;
if (Source)
{
Emitter.CurveDistanceScaler = Range;
}
}
bool hos::com::AudioSource::GetMute() const
{
return Mute;
}
bool hos::com::AudioSource::GetLoop() const
{
return Loop;
}
bool hos::com::AudioSource::GetPlayOnAwake() const
{
return PlayOnAwake;
}
bool hos::com::AudioSource::GetIs3D() const
{
return Is3D;
}
float hos::com::AudioSource::GetVolume() const
{
return Volume;
}
float hos::com::AudioSource::GetRange() const
{
return Range;
}
com::AudioSource* hos::com::AudioSource::Clone() const
{
return new AudioSource(*this);
}
void hos::com::AudioSource::Reset()
{
Clip = nullptr;
Stop();
SafeDelete(Source);
Emitter = DirectX::AudioEmitter();
Mute = false;
Loop = false;
PlayOnAwake = true;
Volume = DEFAULT_VOLUME;
Is3D = true;
Range = DEFAULT_RANGE;
}
void hos::com::AudioSource::Awake()
{
if (Clip)
{
if (Mute)
{
Source->SetVolume(0);
}
if(m_GameObject->GetActive() && GetActive())
{
if (PlayOnAwake)
{
Stop();
Play();
}
}
}
Component::Awake();
}
void hos::com::AudioSource::Update()
{
if (Is3D)
{
if (Source)
{
//Emitter.SetPosition(transform->GetPosition());
Emitter.Update(m_GameObject->transform->GetPosition(), m_GameObject->transform->GetUp(), (float)Time->DeltaTime());
Source->Apply3D(m_GameObject->m_Scene->GetAudioListener()->Get(), Emitter, false);
}
}
}
void hos::com::AudioSource::OnEnable()
{
}
void hos::com::AudioSource::OnDisable()
{
Stop();
}
const std::vector<U8> hos::com::AudioSource::Serialize()
{
mbstring name = ut::UTF16ToAnsi(GetName());
mbstring clipName;
if (Clip)
{
clipName = ut::UTF16ToAnsi(Clip->GetName());
}
flexbuffers::Builder builder;
builder.Map([&] {
builder.String("Name", name);
builder.Bool("IsActive", GetActive());
builder.Bool("Mute", Mute);
builder.Bool("Loop", Loop);
builder.Bool("PlayOnAwake", PlayOnAwake);
builder.Bool("Is3D", Is3D);
builder.Float("Volume", Volume);
builder.Float("Range", Range);
builder.String("AudioClip", clipName);
});
builder.Finish();
return builder.GetBuffer();
}
bool hos::com::AudioSource::Deserialize(mbstring_view data)
{
if (data.size() <= 0)
{
return false;
}
auto m = flexbuffers::GetRoot(reinterpret_cast<const uint8_t*>(data.data()), data.size()).AsMap();
mbstring sn = m["Name"].AsString().str();
string name = ut::AnsiToUTF16(sn);
if (name != GetName())
{
Debug->LogConsole(L"DataManager", L"AudioSource try Deserialize to" + name);
return false;
}
bool active = m["IsActive"].AsBool();
SetActive(active);
Mute = m["Mute"].AsBool();
Loop = m["Loop"].AsBool();
PlayOnAwake = m["PlayOnAwake"].AsBool();
Is3D = m["Is3D"].AsBool();
Volume = m["Volume"].AsFloat();
Range = m["Range"].AsFloat();
mbstring t = m["AudioClip"].AsString().str();
string clipName = ut::AnsiToUTF16(t);
Clip = g_DataManager->GetAudioClip(clipName);
if (!Clip)
{
Clip = g_DataManager->LoadAudioClip(g_Path + AudioClip::FILE_PATH + clipName + AudioClip::FILE_EXTENSION);
}
if (Clip)
{
if (Clip->Sound)
Source = Clip->Sound->CreateInstance(DirectX::SoundEffectInstance_Use3D | DirectX::SoundEffectInstance_ReverbUseFilters).release();
}
return true;
}
void hos::com::AudioSource::Play()
{
if (Source)
{
Source->SetVolume(Volume);
if (Source->GetState() != DirectX::PLAYING)
{
Source->Play(Loop);
}
}
}
void hos::com::AudioSource::Stop()
{
if (Source)
{
Source->Stop();
}
}
void hos::com::AudioSource::Pause()
{
if (Source)
{
if (Source->GetState() == DirectX::PLAYING)
{
Source->Pause();
}
}
}
DirectX::SoundState hos::com::AudioSource::GetState()
{
if (Source)
{
return Source->GetState();
}
return DirectX::SoundState::STOPPED;
}
void hos::com::AudioSource::SetPitch(float pitch)
{
if (Source)
{
Source->SetPitch(std::clamp(pitch, -1.f, 1.f));
}
}
| 18.868421 | 134 | 0.665411 | Game-institute-1st-While-true |
aba28b08d7e832242a5481ff7f3f6ef9a524e350 | 7,243 | cpp | C++ | include/cinolib/isocontour.cpp | goodengineer/cinolib | 7de4de6816ed617e76a0517409e3e84c4546685e | [
"MIT"
] | null | null | null | include/cinolib/isocontour.cpp | goodengineer/cinolib | 7de4de6816ed617e76a0517409e3e84c4546685e | [
"MIT"
] | null | null | null | include/cinolib/isocontour.cpp | goodengineer/cinolib | 7de4de6816ed617e76a0517409e3e84c4546685e | [
"MIT"
] | null | null | null | /********************************************************************************
* This file is part of CinoLib *
* Copyright(C) 2016: Marco Livesu *
* *
* The MIT License *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS *
* IN THE SOFTWARE. *
* *
* Author(s): *
* *
* Marco Livesu (marco.livesu@gmail.com) *
* http://pers.ge.imati.cnr.it/livesu/ *
* *
* Italian National Research Council (CNR) *
* Institute for Applied Mathematics and Information Technologies (IMATI) *
* Via de Marini, 6 *
* 16149 Genoa, *
* Italy *
*********************************************************************************/
#include <cinolib/isocontour.h>
#include <cinolib/cino_inline.h>
#include <cinolib/interval.h>
#include <queue>
namespace cinolib
{
template<class M, class V, class E, class P>
CINO_INLINE
Isocontour<M,V,E,P>::Isocontour()
{
iso_value = 0;
}
template<class M, class V, class E, class P>
CINO_INLINE
Isocontour<M,V,E,P>::Isocontour(AbstractPolygonMesh<M,V,E,P> & m, float iso_value) : iso_value(iso_value)
{
for(uint pid=0; pid<m.num_polys(); ++pid)
for(uint i=0; i< m.poly_tessellation(pid).size()/3; ++i)
{
uint vid0 = m.poly_tessellation(pid).at(3*i+0),vid1 = m.poly_tessellation(pid).at(3*i+1),vid2 = m.poly_tessellation(pid).at(3*i+2);
float f0=m.vert_data(vid0).uvw[0],f1=m.vert_data(vid1).uvw[0],f2=m.vert_data(vid2).uvw[0];
// There are seven possible cases:
// 1) the curve coincides with (v0,v1)
// 2) the curve coincides with (v1,v2)
// 3) the curve coincides with (v2,v0)
// 4) the curve enters from (v0,v1) and exits from (v0,v2)
// 5) the curve enters from (v0,v1) and exits from (v1,v2)
// 6) the curve enters from (v1,v2) and exits from (v2,v0)
// 7) the does not pass fromm here
bool through_v0=(iso_value == f0),through_v1=(iso_value==f1),through_v2=(iso_value==f2);
bool crosses_v0_v1 = is_into_interval<float>(iso_value, f0, f1, true),crosses_v1_v2 = is_into_interval<float>(iso_value, f1, f2, true),crosses_v2_v0 = is_into_interval<float>(iso_value, f2, f0, true);
float alpha0 = std::fabs(iso_value - f0)/fabs(f1 - f0),alpha1 = std::fabs(iso_value - f1)/fabs(f2 - f1),alpha3 = std::fabs(iso_value - f2)/fabs(f0 - f2);;
if (through_v0 && through_v1) // case 1) the curve coincides with (v0,v1)
{
segs.push_back(m.vert(vid0));
segs.push_back(m.vert(vid1));
}
else if (through_v1 && through_v2) // case 2) the curve coincides with (v1,v2)
{
segs.push_back(m.vert(vid1));
segs.push_back(m.vert(vid2));
}
else if (through_v2 && through_v0) // 3) the curve coincides with (v2,v0)
{
segs.push_back(m.vert(vid2));
segs.push_back(m.vert(vid0));
}
else if (crosses_v0_v1 && crosses_v1_v2) // case 4) the curve enters from (v0,v1) and exits from (v0,v2)
{
//float alpha0 = std::fabs(iso_value - f0)/fabs(f1 - f0),alpha1 = std::fabs(iso_value - f1)/fabs(f2 - f1);
segs.push_back((1.0-alpha0)*m.vert(vid0) + alpha0*m.vert(vid1));
segs.push_back((1.0-alpha1)*m.vert(vid1) + alpha1*m.vert(vid2));
}
else if (crosses_v0_v1 && crosses_v2_v0) // case 5) the curve enters from (v0,v1) and exits from (v1,v2)
{
//float alpha0 = std::fabs(iso_value - f0)/fabs(f1 - f0),alpha1 = std::fabs(iso_value - f2)/fabs(f0 - f2);
segs.push_back((1.0-alpha0)*m.vert(vid0) + alpha0*m.vert(vid1));
segs.push_back((1.0-alpha3)*m.vert(vid2) + alpha3*m.vert(vid0));
}
else if (crosses_v1_v2 && crosses_v2_v0) // 6) the curve enters from (v1,v2) and exits from (v2,v0)
{
//float alpha0 = std::fabs(iso_value - f1)/fabs(f2 - f1),alpha1 = std::fabs(iso_value - f2)/fabs(f0 - f2);
segs.push_back((1.0-alpha1)*m.vert(vid1) + alpha1*m.vert(vid2));
segs.push_back((1.0-alpha3)*m.vert(vid2) + alpha3*m.vert(vid0));
}
}
}
template<class M, class V, class E, class P>
CINO_INLINE
std::vector<uint> Isocontour<M,V,E,P>::tessellate(Trimesh<M,V,E,P> & m) const
{
typedef std::pair<uint,float> split_data;
std::set<split_data,std::greater<split_data>> edges_to_split; // from highest to lowest id
for(uint eid=0; eid<m.num_edges(); ++eid)
{
float f0 = m.vert_data(m.edge_vert_id(eid,0)).uvw[0],f1 = m.vert_data(m.edge_vert_id(eid,1)).uvw[0];
if (is_into_interval<float>(iso_value, f0, f1))
{
float alpha = std::fabs(iso_value - f0)/fabs(f1 - f0);
edges_to_split.insert(std::make_pair(eid,alpha));
}
}
std::vector<uint> new_vids;
for(auto e : edges_to_split)
{
uint vid = m.edge_split(e.first, e.second);
m.vert_data(vid).uvw[0] = iso_value;
new_vids.push_back(vid);
}
return new_vids;
}
}
| 51.368794 | 208 | 0.510976 | goodengineer |
aba4f22309ddfb0fa9e5a3ee06e917a654ba66ca | 633 | cpp | C++ | GameplayFootball/src/onthepitch/export/base/events.cpp | ElsevierSoftwareX/SOFTX-D-20-00016 | 48c28adb72aa167a251636bc92111b3c43c0be67 | [
"MIT"
] | 8 | 2020-11-10T13:19:15.000Z | 2022-03-15T11:37:00.000Z | GameplayFootball/src/onthepitch/export/base/events.cpp | ElsevierSoftwareX/SOFTX-D-20-00016 | 48c28adb72aa167a251636bc92111b3c43c0be67 | [
"MIT"
] | null | null | null | GameplayFootball/src/onthepitch/export/base/events.cpp | ElsevierSoftwareX/SOFTX-D-20-00016 | 48c28adb72aa167a251636bc92111b3c43c0be67 | [
"MIT"
] | null | null | null | #ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <fstream>
#include <iostream>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry.hpp>
#include "events.hpp"
using namespace std;
using namespace boost::geometry;
using namespace AtomicEvents;
KickingTheBall::KickingTheBall() {}
KickingTheBall::KickingTheBall(
double timestamp,
string playerId,
model::d2::point_xy<double> playerPos) {
this->timestamp = timestamp;
this->playerId = playerId;
this->playerPos = playerPos;
} | 23.444444 | 49 | 0.747235 | ElsevierSoftwareX |
aba6181e7c5734b80cc6e6a560af90fb33a2d409 | 1,725 | cpp | C++ | source/Task.cpp | acs9307/alib-cpp | 56eb3d31d979ef1b412d197e7ea8d10bac686077 | [
"MIT"
] | 1 | 2017-05-02T09:51:05.000Z | 2017-05-02T09:51:05.000Z | source/Task.cpp | acs9307/alib-cpp | 56eb3d31d979ef1b412d197e7ea8d10bac686077 | [
"MIT"
] | null | null | null | source/Task.cpp | acs9307/alib-cpp | 56eb3d31d979ef1b412d197e7ea8d10bac686077 | [
"MIT"
] | null | null | null | #include "includes/Task.h"
namespace alib
{
/****Initializers****/
void Task::init(task_callback callback, void* taskArg, alib_free_value freeArg,
uint8_t loopsPerCallback)
{
tcb = callback;
arg = taskArg;
freeArgCb = freeArg;
loopsPerCall = loopsPerCallback;
/* Default init other members. */
loopCount = 0;
}
/********************/
/****Constructors****/
Task::Task() {}
Task::Task(task_callback callback, void* taskArg, alib_free_value freeArg) :
tcb(callback), arg(taskArg), freeArgCb(freeArg) {}
Task::Task(task_callback callback, void* taskArg, alib_free_value freeArg,
uint8_t loopsPerCallback) :
tcb(callback), arg(taskArg), freeArgCb(freeArg), loopsPerCall(loopsPerCallback) {}
/********************/
/****Getters****/
task_callback Task::getCallback() const { return(tcb); }
void* Task::getArg()const { return(arg); }
alib_free_value Task::getFreeArgCb()const { return(freeArgCb); }
uint8_t Task::getLoopsPerCall() const { return(loopsPerCall); }
/***************/
/****Setters****/
void Task::setCallback(task_callback callback) { tcb = callback; }
void Task::setArg(void* taskArg, alib_free_value freeTaskArg)
{
if (arg && freeArgCb)
freeArgCb(arg);
arg = taskArg;
freeArgCb = freeTaskArg;
}
void Task::setLoopsPerCall(uint8_t loopsPerCallback)
{
loopsPerCall = loopsPerCallback;
if (loopCount > loopsPerCall)
loopCount = loopsPerCall;
}
/***************/
void Task::loop()
{
if (!loopCount)
{
tcb(*this);
loopCount = loopsPerCall;
}
else
--loopCount;
}
void Task::free(void* _task)
{
if(!_task)return;
Task* task = (Task*)_task;
delete(task);
}
Task::~Task()
{
if (arg && freeArgCb)
freeArgCb(arg);
}
}
| 22.402597 | 84 | 0.649275 | acs9307 |
aba6f7ae9aadd6b2bfa8e803f56bce4c0f92a1b1 | 326 | cc | C++ | ultra_fast_mathematician.cc | maximilianbrine/github-slideshow | 76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1 | [
"MIT"
] | null | null | null | ultra_fast_mathematician.cc | maximilianbrine/github-slideshow | 76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1 | [
"MIT"
] | 3 | 2021-01-04T18:33:39.000Z | 2021-01-04T19:37:21.000Z | ultra_fast_mathematician.cc | maximilianbrine/github-slideshow | 76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
int main() {
std::string a, b, c = "";
std::getline(std::cin, a);
std::getline(std::cin, b);
for (int i = 0; i < a.size(); ++i) {
if (a[i] != b[i]) {
c += "1";
} else {
c += "0";
}
}
std::cout << c;
return 0;
} | 19.176471 | 40 | 0.383436 | maximilianbrine |
aba83b2fb430d3a70dcec3c0cc5f05f4a01049cf | 7,381 | hpp | C++ | DT3Core/Scripting/ScriptingRadioButton.hpp | nemerle/DT3 | 801615d507eda9764662f3a34339aa676170e93a | [
"MIT"
] | 3 | 2016-01-27T13:17:18.000Z | 2019-03-19T09:18:25.000Z | DT3Core/Scripting/ScriptingRadioButton.hpp | nemerle/DT3 | 801615d507eda9764662f3a34339aa676170e93a | [
"MIT"
] | 1 | 2016-01-28T14:39:49.000Z | 2016-01-28T22:12:07.000Z | DT3Core/Scripting/ScriptingRadioButton.hpp | adderly/DT3 | e2605be091ec903d3582e182313837cbaf790857 | [
"MIT"
] | 3 | 2016-01-25T16:44:51.000Z | 2021-01-29T19:59:45.000Z | #pragma once
#ifndef DT3_SCRIPTINGPAGEFLIPPER
#define DT3_SCRIPTINGPAGEFLIPPER
//==============================================================================
///
/// File: ScriptingRadioButton.hpp
///
/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DT3Core/Scripting/ScriptingBase.hpp"
//==============================================================================
//==============================================================================
namespace DT3 {
//==============================================================================
/// Forward declarations
//==============================================================================
//==============================================================================
/// Boolean sequencer.
//==============================================================================
class ScriptingRadioButton: public ScriptingBase {
public:
DEFINE_TYPE(ScriptingRadioButton,ScriptingBase)
DEFINE_CREATE_AND_CLONE
DEFINE_PLUG_NODE
ScriptingRadioButton (void);
ScriptingRadioButton (const ScriptingRadioButton &rhs);
ScriptingRadioButton & operator = (const ScriptingRadioButton &rhs);
virtual ~ScriptingRadioButton (void);
virtual void archive (const std::shared_ptr<Archive> &archive);
/// Object was added to a world
/// world world that object was added to
virtual void add_to_world (World *world);
/// Object was removed from a world
virtual void remove_from_world (void);
public:
/// Called to initialize the object
virtual void initialize (void);
// Event handlers for each input
void in1 (PlugNode *sender) { flip(sender,&_in1); }
void in2 (PlugNode *sender) { flip(sender,&_in2); }
void in3 (PlugNode *sender) { flip(sender,&_in3); }
void in4 (PlugNode *sender) { flip(sender,&_in4); }
void in5 (PlugNode *sender) { flip(sender,&_in5); }
void in6 (PlugNode *sender) { flip(sender,&_in6); }
void in7 (PlugNode *sender) { flip(sender,&_in7); }
void in8 (PlugNode *sender) { flip(sender,&_in8); }
void in9 (PlugNode *sender) { flip(sender,&_in9); }
void in10 (PlugNode *sender) { flip(sender,&_in10); }
void in11 (PlugNode *sender) { flip(sender,&_in11); }
void in12 (PlugNode *sender) { flip(sender,&_in12); }
void in13 (PlugNode *sender) { flip(sender,&_in13); }
void in14 (PlugNode *sender) { flip(sender,&_in14); }
void in15 (PlugNode *sender) { flip(sender,&_in15); }
void in16 (PlugNode *sender) { flip(sender,&_in16); }
void in17 (PlugNode *sender) { flip(sender,&_in17); }
void in18 (PlugNode *sender) { flip(sender,&_in18); }
void in19 (PlugNode *sender) { flip(sender,&_in19); }
void in20 (PlugNode *sender) { flip(sender,&_in20); }
private:
void flip (PlugNode *sender, Event *in);
Event _in1;
Event _in2;
Event _in3;
Event _in4;
Event _in5;
Event _in6;
Event _in7;
Event _in8;
Event _in9;
Event _in10;
Event _in11;
Event _in12;
Event _in13;
Event _in14;
Event _in15;
Event _in16;
Event _in17;
Event _in18;
Event _in19;
Event _in20;
Event _set1;
Event _reset1;
Event _set2;
Event _reset2;
Event _set3;
Event _reset3;
Event _set4;
Event _reset4;
Event _set5;
Event _reset5;
Event _set6;
Event _reset6;
Event _set7;
Event _reset7;
Event _set8;
Event _reset8;
Event _set9;
Event _reset9;
Event _set10;
Event _reset10;
Event _set11;
Event _reset11;
Event _set12;
Event _reset12;
Event _set13;
Event _reset13;
Event _set14;
Event _reset14;
Event _set15;
Event _reset15;
Event _set16;
Event _reset16;
Event _set17;
Event _reset17;
Event _set18;
Event _reset18;
Event _set19;
Event _reset19;
Event _set20;
Event _reset20;
};
//==============================================================================
//==============================================================================
} // DT3
#endif
| 49.536913 | 109 | 0.315811 | nemerle |
abaa22d1b64dd6d16d986252c6e8ffd334f2dfbd | 1,098 | cpp | C++ | Patterns/triipaathii.cpp | sanchit781/HACKTOBERFEST2021_PATTERN | c457eb2a1c7b729bdaa26ade7d4c7eb4092291e2 | [
"MIT"
] | 229 | 2021-09-10T13:24:47.000Z | 2022-03-18T16:54:29.000Z | Patterns/triipaathii.cpp | sanchit781/HACKTOBERFEST2021_PATTERN | c457eb2a1c7b729bdaa26ade7d4c7eb4092291e2 | [
"MIT"
] | 164 | 2021-09-10T12:04:39.000Z | 2021-10-29T21:20:42.000Z | Patterns/triipaathii.cpp | sanchit781/HACKTOBERFEST2021_PATTERN | c457eb2a1c7b729bdaa26ade7d4c7eb4092291e2 | [
"MIT"
] | 567 | 2021-09-10T17:35:27.000Z | 2021-12-11T12:45:43.000Z | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cout<<"Enter an integer: ";
cin>>n;
cout<<endl;
//for upper triangle
for(int i=1;i<=n;i++){
for(int j=n-i;j>0;j--){
cout<<"* ";
}
for(int k=i;k>0;k--){
if (k%2==0)
cout<<"| ";
else
cout<<1<<" ";
}
for(int k=2;k<=i;k++){
if (k%2==0)
cout<<"| ";
else
cout<<1<<" ";
}
for(int j=n-i;j>0;j--){
cout<<"* ";
}
cout<<endl;
}
//For lower triangle
for(int i=n-1;i>0;i--){
for(int j=n-i;j>0;j--){
cout<<"* ";
}
for(int k=i;k>0;k--){
if (k%2==0)
cout<<"| ";
else
cout<<1<<" ";
}
for(int k=2;k<=i;k++){
if (k%2==0)
cout<<"| ";
else
cout<<1<<" ";
}
for(int j=n-i;j>0;j--){
cout<<"* ";
}
cout<<endl;
}
cout<<endl;
} | 19.963636 | 31 | 0.303279 | sanchit781 |
abaaca90eeb532ebd9937cf4f79f689e5e51d02b | 1,602 | cpp | C++ | Cpp/Docker/ASM.cpp | lehtojo/Evie | f41b3872f6a1a7da1778c241c7b01823b36ac78d | [
"MIT"
] | 12 | 2020-07-12T06:22:11.000Z | 2022-02-27T13:19:19.000Z | Cpp/Docker/ASM.cpp | lehtojo/Evie | f41b3872f6a1a7da1778c241c7b01823b36ac78d | [
"MIT"
] | 2 | 2020-07-12T06:22:48.000Z | 2021-11-28T01:23:25.000Z | Cpp/Docker/ASM.cpp | lehtojo/Evie | f41b3872f6a1a7da1778c241c7b01823b36ac78d | [
"MIT"
] | 3 | 2021-09-16T19:02:19.000Z | 2021-11-28T00:50:15.000Z | #include "../../H/Docker/ASM.h"
#include "../../H/UI/Safe.h"
void ASM::ASM_Analyzer(vector<string>& Output)
{
//here we will just make an prototype from every label. Parser can analyse wich one is a function, and what is not.
//and after that we want to give Evie Core the "use "filename"" without the preprosessor so that Evie Core can implement an
//post-prosessing include
vector<string> Header_Data = DOCKER::Get_Header(DOCKER::FileName.back());
if (Header_Data.size() < 1)
Header_Data = DOCKER::Get_Header("asm..e");
if (Header_Data.size() < 1)
Header_Data = DOCKER::Default_ASM_Header_Data;
if (Header_Data.size() < 1)
Report(Observation(ERROR, "Docker didn't find Header file for " + DOCKER::FileName.back(), Position()));
//DOCKER::Separate_Identification_Patterns(Header_Data);
vector<uint8_t> tmp = DOCKER::Get_Char_Buffer_From_File(DOCKER::FileName.back(), DOCKER::Working_Dir.back().second);
string buffer = string((char*)tmp.data(), tmp.size());
Section Function_Section = DOCKER::Get_Section_From_String(buffer);
string Tmp = string((char*)Function_Section.start, Function_Section.size);
auto Types = DOCKER::Separate_Identification_Patterns(Header_Data);
vector<pair<string, string>> Raw_Data = DOCKER::Get_Names_Of(Tmp, Types);
for (auto& i : Raw_Data) {
if (i.second.find("global ") != -1)
i.second.erase(i.second.find("global "), 7);
}
DOCKER::Append(Output, Raw_Data);
//
//Syntax_Correcter(Raw_Data);
//now make the obj token for YASM
DOCKER::Assembly_Source_File.push_back(DOCKER::Working_Dir.back().second + DOCKER::FileName.back());
return;
}
| 45.771429 | 124 | 0.730337 | lehtojo |
abb39c4e6463162fa3d0647f590f9a85288fbcb8 | 8,657 | cpp | C++ | sources/data/planet.cpp | n0dev/space-explorer | 87088bbd620128d09467aed7e188b717a19367ab | [
"MIT"
] | null | null | null | sources/data/planet.cpp | n0dev/space-explorer | 87088bbd620128d09467aed7e188b717a19367ab | [
"MIT"
] | null | null | null | sources/data/planet.cpp | n0dev/space-explorer | 87088bbd620128d09467aed7e188b717a19367ab | [
"MIT"
] | null | null | null | #include <math.h>
#include <fstream>
#include <FTGL/ftgl.h>
#include <GL/glew.h>
#include "rapidjson/document.h"
#include "../include/data/planet.h"
#include "../include/gui.h"
#include "../textures/loadpng.h"
#include "../gameplay/observer.h"
using namespace rapidjson;
Planet *mercury;
Planet *venus;
Planet *earth;
Planet *mars;
Planet *jupiter;
Planet *saturn;
Planet *uranus;
Planet *neptune;
Planet *pluto;
const std::string g_planetPath = "planets/";
const std::string g_texturePath = "planets/textures/";
inline double deg2rad(double deg) {
return deg * 3.1415 / 180.0;
}
Planet::Planet(std::string json_file) {
// Open and parse json file
std::string json_path = g_planetPath;
json_path += json_file;
std::ifstream file(json_path);
if (!file.good()) {
std::cerr << "Cannot open " << json_file << std::endl;
exit(1);
}
std::string json((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
Document document;
document.Parse(json.c_str());
// Store all mandatory values
m_name = document["Name"].GetString();
m_radius = document["Radius"].GetDouble();
// Load the ground texture
std::string texturePath = g_texturePath;
texturePath += std::string(document["GroundTexture"].GetString());
if (!(m_ground_texture = loadPNGTexture(texturePath.c_str()))) {
std::cerr << "Failed to load " << texturePath << "! aborting" << std::endl;
exit(1);
}
if (document.HasMember("AxialTilt")) {
m_axialTilt = static_cast<GLfloat>(document["AxialTilt"].GetDouble());
}
// Load orbit information and creates it
if (document.HasMember("Orbit")) {
if (document["Orbit"].HasMember("Aphelion")) {
m_orbit.Aphelion = document["Orbit"]["Aphelion"].GetDouble();
}
if (document["Orbit"].HasMember("Perihelion")) {
m_orbit.Perihelion = document["Orbit"]["Perihelion"].GetDouble();
}
if (document["Orbit"].HasMember("SemiMajorAxis")) {
m_orbit.SemiMajorAxis = document["Orbit"]["SemiMajorAxis"].GetDouble();
}
if (document["Orbit"].HasMember("Eccentricity")) {
m_orbit.Eccentricity = document["Orbit"]["Eccentricity"].GetDouble();
}
if (document["Orbit"].HasMember("Inclination")) {
m_orbit.Inclination = document["Orbit"]["Inclination"].GetDouble();
}
if (document["Orbit"].HasMember("ArgumentOfPeriapsis")) {
m_orbit.ArgumentOfPeriapsis = document["Orbit"]["ArgumentOfPeriapsis"].GetDouble();
}
if (document["Orbit"].HasMember("LongitudeOfAscendingNode")) {
m_orbit.LongitudeOfAscendingNode = document["Orbit"]["LongitudeOfAscendingNode"].GetDouble();
}
if (document["Orbit"].HasMember("MeanAnomaly")) {
m_orbit.MeanAnomaly = document["Orbit"]["MeanAnomaly"].GetDouble();
}
if (document["Orbit"].HasMember("OrbitalPeriod")) {
m_orbit.OrbitalPeriod = document["Orbit"]["OrbitalPeriod"].GetDouble();
}
if (document["Orbit"].HasMember("OrbitalSpeed")) {
m_orbit.OrbitalSpeed = document["Orbit"]["OrbitalSpeed"].GetDouble();
}
createOrbit();
}
// Load rings information and creates it
if (document.HasMember("Rings")) {
m_inner_radius = document["Rings"]["InnerDistance"].GetDouble();
m_outer_radius = document["Rings"]["OuterDistance"].GetDouble();
std::string ringTexturePath = g_texturePath;
ringTexturePath += std::string(document["Rings"]["Texture"].GetString());
if (!(m_ring_texture = loadPNGTexture(ringTexturePath.c_str()))) {
fprintf(stderr, "failed to load saturn! aborting\n");
exit(1);
}
createRings();
}
// Create the planet mesh
GLUquadricObj *sphere = NULL;
sphere = gluNewQuadric();
gluQuadricDrawStyle(sphere, GLU_FILL);
gluQuadricNormals(sphere, GLU_SMOOTH);
gluQuadricTexture(sphere, 1);
list = glGenLists(1);
glNewList(list, GL_COMPILE);
gluSphere(sphere, m_radius, 1000, 1000);
glEndList();
gluDeleteQuadric(sphere);
// Misc
loc = new FTPoint(0.0, 0.0);
// Lights
sunLight = new GLShader("../sources/shaders/sunlight.vert", "../sources/shaders/sunlight.frag");
idGroundMap = glGetUniformLocation(sunLight->program, "tex");
idSunPosition = glGetUniformLocation(sunLight->program, "sunPosition");
}
void draw_disk(double inner_radius, double outer_radius, int slices) {
double theta;
glBegin(GL_QUAD_STRIP);
for (int inc = 0; inc <= slices; inc++) {
theta = inc * 2.0 * M_PI / slices;
glTexCoord2f(1.0, 0.0);
glVertex3d(outer_radius * cos(theta), outer_radius * sin(theta), 0.0);
glTexCoord2f(0.0, 0.0);
glVertex3d(inner_radius * cos(theta), inner_radius * sin(theta), 0.0);
}
glEnd();
}
void Planet::createRings() {
GLUquadricObj *ring = NULL;
ring = gluNewQuadric();
gluQuadricDrawStyle(ring, GLU_FILL);
gluQuadricNormals(ring, GLU_SMOOTH);
gluQuadricTexture(ring, 1);
m_ring_list = glGenLists(2);
glNewList(m_ring_list, GL_COMPILE);
draw_disk(m_inner_radius, m_outer_radius, 800);
glEndList();
gluDeleteQuadric(ring);
m_is_ring = true;
}
double t = 0.0;
void Planet::draw(void) {
const GLdouble a = m_orbit.SemiMajorAxis;
const GLdouble b = a * sqrt(1.0 - m_orbit.Eccentricity * m_orbit.Eccentricity);
glPushMatrix();
glTranslated(-spaceship->pos.x, -spaceship->pos.y, -spaceship->pos.z);
if (m_orbit.LongitudeOfAscendingNode != 0.0) {
glRotated(m_orbit.LongitudeOfAscendingNode, 0, 0, 1);
}
if (m_orbit.ArgumentOfPeriapsis != 0.0) {
glRotated(m_orbit.ArgumentOfPeriapsis, 0, 0, 1);
}
if (m_orbit.Inclination != 0.0) {
glRotated(m_orbit.Inclination, 1, 0, 0);
}
if (m_displayOrbit) {
glCallList(m_orbit_list);
}
// Compute position of the planet
if (m_orbit.OrbitalSpeed > 10.0) {
m_positionX = a * cos(t += 0.00001);
m_positionY = b * sin(t += 0.00001);
} else {
m_positionX = a;
m_positionY = 0.0;
}
glTranslated(m_positionX, m_positionY, 0.0);
if (m_axialTilt != 0) {
glRotatef(m_axialTilt, 1, 0, 0);
}
glPushMatrix();
glTranslated(0.0, 0.0, 1.5 * m_radius);
glRasterPos2f(0, 0);
font->Render(m_name.c_str(), -1, *loc);
glPopMatrix();
sunLight->begin();
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_ground_texture);
glUniform1i(idGroundMap, 1);
const GLfloat vecSunPosition[3] = {(GLfloat) -spaceship->pos.x,
(GLfloat) -spaceship->pos.y,
(GLfloat) -spaceship->pos.z};
glUniform3fv(idSunPosition, 1, vecSunPosition);
glCallList(this->list);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
sunLight->end();
if (m_is_ring) {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_ring_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
glCallList(m_ring_list);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
}
glPopMatrix();
}
void Planet::lookAt() {
spaceship->lookAt(m_positionX - spaceship->pos.x, m_positionY - spaceship->pos.y, m_positionZ - spaceship->pos.z);
}
void Planet::createOrbit() {
// Set information
const int edges = 6000;
// Build the orbit
const GLdouble a = m_orbit.SemiMajorAxis;
const GLdouble b = a * sqrt(1.0 - m_orbit.Eccentricity * m_orbit.Eccentricity);
GLdouble x, y, z, r;
GLUquadricObj *o = NULL;
o = gluNewQuadric();
gluQuadricNormals(o, GLU_SMOOTH);
m_orbit_list = glGenLists(2);
glNewList(m_orbit_list, GL_COMPILE);
glBegin(GL_LINE_LOOP);
for (int t = 0; t <= edges; t += 1) {
r = deg2rad(360.0 * t / edges);
x = a * cos(r);
y = b * sin(r);
z = 0;
glVertex3d(x, y, z);
}
glEnd();
glEndList();
gluDeleteQuadric(o);
// Set the new position of the planet here
m_positionX = m_orbit.SemiMajorAxis;
}
void Planet::displayOrbit(bool b) {
m_displayOrbit = b;
}
| 31.944649 | 118 | 0.631859 | n0dev |
abb49121db4a3b42a0d148e6de2661f6f118a453 | 694 | cpp | C++ | Algorithms/Sorting/insertion_sort.cpp | TeacherManoj0131/HacktoberFest2020-Contributions | c7119202fdf211b8a6fc1eadd0760dbb706a679b | [
"MIT"
] | 256 | 2020-09-30T19:31:34.000Z | 2021-11-20T18:09:15.000Z | Algorithms/Sorting/insertion_sort.cpp | TeacherManoj0131/HacktoberFest2020-Contributions | c7119202fdf211b8a6fc1eadd0760dbb706a679b | [
"MIT"
] | 293 | 2020-09-30T19:14:54.000Z | 2021-06-06T02:34:47.000Z | Algorithms/Sorting/insertion_sort.cpp | TeacherManoj0131/HacktoberFest2020-Contributions | c7119202fdf211b8a6fc1eadd0760dbb706a679b | [
"MIT"
] | 1,620 | 2020-09-30T18:37:44.000Z | 2022-03-03T20:54:22.000Z | #include<iostream>
using namespace std;
void InsertionSort(int A[], int n)
{
int i, j, key;
for (i = 1; i < n; i++)
{
key = A[i];
j = i-1;
while (j >= 0 && A[j] >key)
{
A[j+1] = A[j];
j--;
}
A[j +1] = key;
}
cout << "Sorted Array: \n";
for(i=0; i<n; i++)
{
cout<<A[i]<<endl;
}
}
int main()
{
int *arr, n;
cout<<"Enter the size of the array ";
cin>>n;
arr = new int[n];
cout<<"\n Enter the elements into the array \n";
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
InsertionSort(arr, n);
delete []arr;
return 0;
} | 16.52381 | 52 | 0.400576 | TeacherManoj0131 |