blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a9d50cfe4cea85f4855b6a1934c54976f68e21b4 | 8356e0864dd7d8ba0d290fc43c3acae7e8e9269a | /leti/2304/klimuk/hw3/nodes.h | 3c79ca5e29ff50ce720f114cc92364d4536ddbc7 | [] | no_license | eugenyk/hpcourse | b5231a59a3eed621fce99baabb1b85f4056e441f | d3360d823e464b0bb2e451fc8594b5471beb8455 | refs/heads/master | 2022-12-24T22:52:28.489809 | 2019-07-01T15:37:33 | 2019-07-01T15:37:33 | 46,411,508 | 32 | 319 | null | 2022-12-16T03:40:17 | 2015-11-18T10:26:09 | C++ | UTF-8 | C++ | false | false | 6,939 | h | nodes.h | #ifndef NODES
#define NODES
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
using std::vector;
using std::pair;
using std::ofstream;
struct img {
img(std::string name_, vector<vector<uint>> pixels_): name(name_), pixels(pixels_) {}
std::string name;
vector<vector<uint>> pixels;
};
typedef img image;
//consts
const uint MAX_BRIGHT = 255;
const int MARGIN = 2;
const uint MAX_COUNT_IMAGES = 100;
const uint IMAGE_WIDTH = 100;
const uint IMAGE_HEIGHT = 100;
//Source node
class img_creator {
uint counter;
public:
img_creator(): counter(0) {}
bool operator()(std::shared_ptr<image>& result) {
if (counter < MAX_COUNT_IMAGES)
{
result.reset(new image(std::to_string(counter), vector<vector<uint>> (IMAGE_WIDTH, vector<uint>(IMAGE_HEIGHT))));
image* result_ptr = result.get();
for (int i = 0; i < IMAGE_WIDTH; ++i) {
for (int j = 0; j < IMAGE_HEIGHT; ++j) {
(*result_ptr).pixels[i][j] = rand() % MAX_BRIGHT;
}
}
++counter;
return true;
}
return false;
}
};
//functions_nodes
struct find_max {
vector<pair<int, int>> operator()(std::shared_ptr<image> img) {
//std::cout << "find_max" << std::endl;
uint max = 0;
vector<pair<int, int>> result;
image* img_ptr = img.get();
for(int i = 0; i < IMAGE_WIDTH; ++i) {
for(int j = 0; j < IMAGE_HEIGHT; ++j) {
uint br = (*img_ptr).pixels[i][j];
if(br > max) {
max = br;
}
}
}
for(int i = 0; i < IMAGE_WIDTH; ++i) {
for(int j = 0; j < IMAGE_HEIGHT; ++j) {
uint br = (*img_ptr).pixels[i][j];
if(br == max) {
result.push_back(std::make_pair(i, j));
}
}
}
/*for(int i = 0; i < result.size(); ++i) {
uint br = (*img_ptr).pixels[result[i].first][result[i].second];
std::cout << (*img_ptr).name << ": max at (" << result[i].first << ", " << result[i].second << "): (" << br << ")" << std::endl;
}*/
return result;
}
};
struct find_min {
vector<pair<int, int>> operator()(std::shared_ptr<image> img) {
// std::cout << "find_min" << std::endl;
uint min = 256;
vector<pair<int, int>> result;
image* img_ptr = img.get();
for(int i = 0; i < IMAGE_WIDTH; ++i) {
for(int j = 0; j < IMAGE_HEIGHT; ++j) {
uint br = (*img_ptr).pixels[i][j];
if(br < min) {
min = br;
}
}
}
for(int i = 0; i < IMAGE_WIDTH; ++i) {
for(int j = 0; j < IMAGE_HEIGHT; ++j) {
uint br = (*img_ptr).pixels[i][j];
if(min == br) {
result.push_back(std::make_pair(i, j));
}
}
}
/*for(int i = 0; i < result.size(); ++i) {
uint br = (*img_ptr).pixels[result[i].first][result[i].second];
std::cout << (*img_ptr).name << ": min at (" << result[i].first << ", " << result[i].second << "): (" << br << ")" << std::endl;
}*/
return result;
}
};
class find_val {
int b;
public:
find_val(int a): b(a) {}
vector<pair<int, int>> operator()(std::shared_ptr<image> img) {
//std::cout << "find_val" << std::endl;
vector<pair<int, int>> result;
image* img_ptr = img.get();
for(int i = 0; i < IMAGE_WIDTH; ++i) {
for(int j = 0; j < IMAGE_HEIGHT; ++j) {
uint br = (*img_ptr).pixels[i][j];
if(b == br) {
result.push_back(std::make_pair(i, j));
}
}
}
/* for(int i = 0; i < result.size(); ++i) {
uint br = (*img_ptr).pixels[result[i].first][result[i].second];
std::cout << (*img_ptr).name << ": val " << b << " at (" << result[i].first << ", " << result[i].second << "): (" << br << ")" << std::endl;
}*/
return result;
}
};
struct invert_img {
private:
void invert_img_helper(image* img_ptr, const vector<pair<int, int>>& pixels) {
for(auto p: pixels) {
int pi = p.first;
int pj = p.second;
for(int i = -MARGIN; i <= MARGIN; ++i) {
for(int j = -MARGIN; j <= MARGIN; ++j) {
if(pi + i >= 0 && pi + i < IMAGE_WIDTH && pj + j >= 0 && pj + j < IMAGE_HEIGHT) {
(*img_ptr).pixels[pi + i][pj + j] = MAX_BRIGHT - (*img_ptr).pixels[pi + i][pj + j];
}
}
}
}
}
public:
bool operator()(std::tuple<std::shared_ptr<image>, const vector<pair<int, int>>&, const vector<pair<int, int>>&, const vector<pair<int, int>>&> v) {
//std::cout << "invert_img" << std::endl;
std::shared_ptr<image> img = std::get<0>(v);
image new_img = *img.get();
invert_img_helper(&new_img, std::get<1>(v));
invert_img_helper(&new_img, std::get<2>(v));
invert_img_helper(&new_img, std::get<3>(v));
return true;
}
};
class average_img {
std::string average_img_helper(const image* img_ptr, const vector<pair<int, int>>& pixels) {
for(auto p: pixels) {
int pi = p.first;
int pj = p.second;
double sum = 0;
int cnt = 0;
for(int i = -MARGIN; i <= MARGIN; ++i) {
for(int j = -MARGIN; j <= MARGIN; ++j) {
if(pi + i >= 0 && pi + i < IMAGE_WIDTH && pj + j >= 0 && pj + j < IMAGE_HEIGHT) {
sum += (*img_ptr).pixels[pi + i][pj + j];
++cnt;
}
}
}
sum /= cnt;
std::string str = (*img_ptr).name;
str.append(": average in (");
str.append(std::to_string(pi));
str.append(", ");
str.append(std::to_string(pj));
str.append(") is ");
str.append(std::to_string(sum));
str.append("\n");
std::cout << str;
return str;
}
}
public:
average_img() {}
std::string operator()(std::tuple<std::shared_ptr<image>, const vector<pair<int, int>>&, const vector<pair<int, int>>&, const vector<pair<int, int>>&> v) {
//std::cout << "average_img" << std::endl;
std::shared_ptr<image> img = std::get<0>(v);
std::string output = average_img_helper(img.get(), std::get<1>(v));
output += average_img_helper(img.get(), std::get<2>(v));
output += average_img_helper(img.get(), std::get<3>(v));
output += "\n";
return output;
}
};
class print_log {
ofstream& out;
public:
print_log(ofstream& o) : out(o) {}
bool operator()(std::string str) {
//std::cout << "print" << std::endl;
out << str;
return true;
}
};
#endif
|
5023f22e948ba9ae393556c423b71a53a6987d6a | 596f23f758dd94ed848dd3983093db4550ee18a1 | /bit manipulation/tooglebits.cpp | b2dff6f08947935c82bdbbb2dd9177650f0415bf | [] | no_license | VishalKumarRao123/cpp | 555b588b1ece19961359ab1163fe2753588b4e7b | 61fe0be6ccbdb4a02b7ed21d5cfc49d4bf578abd | refs/heads/main | 2023-09-01T01:05:41.047847 | 2021-10-09T18:05:51 | 2021-10-09T18:05:51 | 409,192,080 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | cpp | tooglebits.cpp | #include<bits/stdc++.h>
using namespace std;
int nob=0;
void binary(int n){
if(!n)
return;
bool b=n&1;
nob++;
binary(n>>1);
cout<<b;
}
int main(int argc, char const *argv[])
{
int n=19;
int m=n;
binary(n);
return 0;
}
|
76264b900c493733badceadc3e4b6a6c962df75e | 02a10a5244d2214e932e54399e4b56b68fe5974b | /headers/UIPackError.h | 1d97e6cef1577f185d3abfc1acbd103000363204 | [] | no_license | inxomnyaa/symbols-auto | 839381c1e83f434b76b2faccadee5e413ac5f376 | 439a1399473cc765badc1b5c438fbf83d9eadf1d | refs/heads/master | 2023-06-21T23:17:07.389321 | 2019-11-16T19:13:05 | 2019-11-16T19:13:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | h | UIPackError.h | #pragma once
class UIPackError : PackError {
virtual ~UIPackError();
virtual ~UIPackError();
virtual void _ZNK9PackError18getLocErrorMessageB5cxx11Ev;
virtual void _ZNK11UIPackError21getLocErrorMessageMapB5cxx11Ev;
virtual void _ZNK11UIPackError23getEventErrorMessageMapB5cxx11Ev;
}
|
09735d06623592e6956f77cc5bbbb2e52214d15b | f1d1b2c25c39f0518e61dbad9a8a69432d4c74cb | /src/Plugins/PluginST/World/ContactListener/ContactListener.cpp | 051c566bb3a2b41a0c71a3e79f3d75ef09b4f7b1 | [] | no_license | SIL3nCe/SteelTraining | 428c9845ece8088fbd684db81b0ff1338d65f049 | 09218167000c1fcb2c8be83cdd25714225611629 | refs/heads/master | 2020-04-05T00:28:55.231616 | 2019-07-27T23:42:21 | 2019-07-27T23:42:21 | 156,398,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,038 | cpp | ContactListener.cpp | #include "ContactListener.h"
#include "../Object.h"
#include "../Projectile/Projectile.h"
/**
* @brief Constructor
*/
ContactListener::ContactListener(void)
{
// ...
}
/**
* @brief Destructor
*/
ContactListener::~ContactListener(void)
{
// ...
}
/**
* @brief BeginContact
*/
void ContactListener::BeginContact(b2Contact* contact)
{
Object * pDataFixtureA = static_cast<Object *>(contact->GetFixtureA()->GetBody()->GetUserData());
Object * pDataFixtureB = static_cast<Object *>(contact->GetFixtureB()->GetBody()->GetUserData());
if (pDataFixtureA && EObjectType::projectile == pDataFixtureA->GetObjectType())
{
if (Projectile * pProj = static_cast<Projectile *>(pDataFixtureA))
{
pProj->OnHit(pDataFixtureB);
}
}
if (pDataFixtureB && EObjectType::projectile == pDataFixtureB->GetObjectType())
{
if (Projectile * pProj = static_cast<Projectile*>(pDataFixtureB))
{
pProj->OnHit(pDataFixtureA);
}
}
}
/**
* @brief EndContact
*/
void ContactListener::EndContact(b2Contact* contact)
{
// Do smthg
}
|
c287e29d3f0c8a31c41196d9a6396f594eb6ae35 | 6456978ebb4921fdb95e699419b85ceade701be0 | /homework/09/ThreadPool.h | 4d740de28e3ac9a348a2c8f1129cf64a16e73486 | [] | no_license | LevKats/msu_cpp_automn_2019 | ba74800a3a1359999e92efac14169ce8f6e28423 | a341e000419beefe5768ede92e60091ea2727727 | refs/heads/master | 2020-08-08T21:07:21.851684 | 2020-01-21T01:09:37 | 2020-01-21T01:09:37 | 213,919,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,236 | h | ThreadPool.h | #pragma once
#include <vector>
#include <exception>
#include <algorithm>
#include <pthread.h>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <queue>
#include <functional>
#include <atomic>
class ThreadPool
{
public:
using Function = std::function<void()>;
explicit ThreadPool(size_t poolSize) {
destroyed.store(false);
while (--poolSize) {
threads.emplace_back([this](){
while (!destroyed.load()) {
std::unique_lock<std::mutex> q_lock(queue_lock);
if (!tasks.empty()) {
auto func = tasks.front();
tasks.pop();
q_lock.unlock();
func();
}
else {
wake_up.wait(q_lock, [this](){ return destroyed.load() ||
!tasks.empty(); });
}
}
});
}
}
~ThreadPool() {
destroyed.store(true);
wake_up.notify_all();
for (auto &thread_ : threads)
thread_.join();
}
template <class Func, class... Args>
auto exec(Func func, Args... args) -> std::future<decltype(func(args...))> {
auto promise = std::make_shared< std::promise<decltype(func(args...))> >();
std::future<decltype(func(args...))> future = promise->get_future();
auto task = [](std::shared_ptr< std::promise<decltype(func(args...))> > p,
Func func, Args... args) {
ThreadPool::wrapper(p, func, args...);
};
{
std::lock_guard<std::mutex> guard(queue_lock);
tasks.push(std::bind(task, promise, func, args...));
}
wake_up.notify_one();
return future;
}
private:
std::vector<std::thread> threads;
std::queue<Function> tasks;
std::atomic<bool> destroyed;
std::condition_variable wake_up;
std::mutex queue_lock;
template <class Func, class... Args>
static void wrapper(std::shared_ptr< std::promise<void> > p,
Func func, Args... args) {
func(args...);
p->set_value();
}
template <class Pointer, class Func, class... Args>
static void wrapper (Pointer p, Func func, Args... args) {
p->set_value(func(args...));
};
};
|
f0512efc59c5154528c8dc5625055b6a1b66d8ac | d6f3668b930770e3d63bfb5c6fbfeeb187f1c607 | /BassZeroVSTi/Source/Application/Files/SynthApplicationFolder.h | 4fb2603b83c5e873e6a681555a3503c8e7002097 | [] | no_license | gorangrubic/imbAVR.ArduinoSynth | 97240e751f1833a2c9fa472143fbb741b1ce07a8 | 45a9d15e64881bf44e50f3567203b5899f49e9d6 | refs/heads/master | 2020-07-09T00:58:50.968308 | 2019-10-28T05:25:54 | 2019-10-28T05:25:54 | 203,828,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 875 | h | SynthApplicationFolder.h | /*
==============================================================================
SynthApplicationFolder.h
Created: 22 Oct 2019 7:30:21pm
Author: gorangrubic
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
#include "../Source/Data/Structures/imbValueSetFile.h"
class SynthApplicationFolder {
public:
std::string name;
std::string description;
std::string parentPath;
File thisDir;
SynthApplicationFolder(std::string _name,std::string _description="", std::string _parentPath = "");
SynthApplicationFolder();
std::string GetFilepath(imbValueSetFile &data, std::string filename="");
std::string GetFilepath(std::string filename);
juce::File GetFile(std::string filename);
std::string GetFolderPath();
void init();
}; |
c114aaba11c7de77db42f22f0f275fc5c52d8386 | 3e59df4e42f95b8bebd4185eb8823c91bf178293 | /include/ImprovedEnum.hxx | 07ff817a95e2a76050831cdf6d20630a9cd61f08 | [
"MIT"
] | permissive | Redchards/ImprovedEnum | 75341b9930a86ff419d238d176b357ccb1a33b98 | 2f662edc54b54eebeaad70d53133646f1659d14f | refs/heads/master | 2021-06-12T22:28:50.035982 | 2021-06-04T01:18:19 | 2021-06-04T01:18:19 | 58,484,544 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 40,592 | hxx | ImprovedEnum.hxx | #ifndef ENUM_UTILS_HXX
#define ENUM_UTILS_HXX
#include <array>
#include <iterator>
#include <tuple>
#include <type_traits>
#include <iostream>
#include <MacroUtils.hxx>
#include <StaticString.hxx>
#include <Range.hxx>
#define TRIM_ENUM_NAME
// Would be better to replace the specialization method by a thing like
// "is_in_list", and a typelist.
namespace Details
{
template<class T>
class AssignmentRemover
{
public:
constexpr AssignmentRemover(const T& obj) : innerObj_{obj}
{}
constexpr AssignmentRemover(T&& obj) : innerObj_{std::move(obj)}
{}
template<class U>
constexpr const AssignmentRemover& operator=(const U&) const &
{
return *this;
}
template<class U>
constexpr const AssignmentRemover& operator=(U&&) const &
{
return *this;
}
template<class U>
constexpr AssignmentRemover&& operator=(const U&) &&
{
return std::move(*this);
}
template<class U>
constexpr AssignmentRemover&& operator=(U&&) &&
{
return std::move(*this);
}
constexpr operator T() const &
{
return innerObj_;
}
constexpr operator T() &&
{
return std::move(innerObj_);
}
private:
T innerObj_;
};
}
#define SANE_LIST_BUILDER_HELPER(x, next) x IF(next)(ADD_COMMA)()
#define ENUM_ASSIGN_REMOVE(type) (const Details::AssignmentRemover<type::Internal##type>)type::SANE_LIST_BUILDER_HELPER
#define ENUM_UPWARD_CONV(type) (type) SANE_LIST_BUILDER_HELPER
#define BRACE_ENCLOSE_INIT(x, next) {x} IF(next)(ADD_COMMA)()
namespace Details
{
/* Usually, returning by const value is pretty useless, but here, it's used to indicate to the compiler that we want to call
* the const version of our 'trim()' function later.
* Without the qualifier, the compiler wants to call the other StaticString<TSize>:trim(), which is not constexpr, because of
* the modifications inside the function.
*/
template<size_t Tsize>
constexpr const StaticString<Tsize> stringifyEnumInitializerHelper(ConstString str) noexcept
{
return {str.begin(), str.find('=')};
}
template<size_t Tsize>
constexpr const StaticString<Tsize> stringifyTrimEnumInitializerHelper(ConstString str) noexcept
{
return stringifyEnumInitializerHelper<Tsize>(str).trim();
}
}
#define STRINGIFY_ENUM_HELPER(string, stringType) stringType{STRINGIFY_ENUM_EQUAL_RANGE(string, stringType)}
#ifdef TRIM_ENUM_NAME
#define STRINGIZE_ENUM_ELEM_NAMES_FCT stringifyTrimEnumInitializerHelper
#else
#define STRINGIZE_ENUM_ELEM_NAMES_FCT stringifyEnumInitializerHelper
#endif
#define STRINGIFY_ENUM(x, next) Details::STRINGIZE_ENUM_ELEM_NAMES_FCT<ConstString{STRINGIFY(x)}.size()>(STRINGIFY(x)) IF(next)(ADD_COMMA)()
#define ENUM_NAME_TUPLE_DECL(x, next) StaticString<ConstString{STRINGIFY(x)}.size()> IF(next)(ADD_COMMA)()
namespace EnumUtils
{
/* Idea : could deducd the size by using the EnumName::tupleType size, instead of the VA_ARGS_COUNT macro.
* Would reduce the time taken to build the enum, even if it's not really an issue right now.
*/
/* http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0031r0.html
* Let's hope this got accepted in the next standard, this would cut a lot of verbose in this code.
*/
/* NOTE : The operator-> reintepret_cast is safe, as the class EnumName will contain only a EnumName::Internal##EnumName value anyway.
* The other members are static constexpr variables, or member functions.
*/
enum class EnumIteratorTag : uint8_t
{
Normal,
Reversed
};
template<class EnumName, EnumIteratorTag tag>
class EnumIterator : public std::conditional_t<tag == EnumIteratorTag::Normal,
typename ArrayIteratorPolicy<typename EnumName::ValuesArrayType>::const_iterator,
typename ArrayIteratorPolicy<typename EnumName::ValuesArrayType>::const_reverse_iterator>
{
public:
using pointer = const EnumName*;
using reference = const EnumName&;
using Base = std::conditional_t<tag == EnumIteratorTag::Normal,
typename ArrayIteratorPolicy<typename EnumName::ValuesArrayType>::const_iterator,
typename ArrayIteratorPolicy<typename EnumName::ValuesArrayType>::const_reverse_iterator>;
friend EnumName;
protected:
struct indexInitFlag{};
constexpr EnumIterator(typename Base::IndexType index, indexInitFlag) : Base{EnumName::values(), index}
{}
public:
using Base::Base;
constexpr EnumIterator(EnumName e) : Base{EnumName::values(), e.get_index()}
{}
constexpr EnumIterator(const EnumIterator& other) = default;
constexpr EnumIterator& operator=(const EnumIterator& other) = default;
constexpr reference operator*() const
{
return reinterpret_cast<reference>(Base::operator*());
}
constexpr pointer operator->() const
{
return reinterpret_cast<pointer>(Base::operator->());
}
};
}
#define ITERABLE_ENUM(EnumName, underlyingType, ...) \
static_assert(std::is_integral<underlyingType>::value, \
"The defined underlying type is not an integral type"); \
class EnumName \
{ \
public: \
enum Internal##EnumName : underlyingType{ __VA_ARGS__ }; \
\
using iterator = EnumUtils::EnumIterator<EnumName, EnumUtils::EnumIteratorTag::Normal>; \
using const_iterator = iterator; \
using reverse_iterator = EnumUtils::EnumIterator<EnumName, EnumUtils::EnumIteratorTag::Reversed>; \
using const_reverse_iterator = reverse_iterator; \
using underlying_type = underlyingType; \
using UnderlyingEnumType = Internal##EnumName; \
using TupleType = std::tuple<MAP2(ENUM_NAME_TUPLE_DECL, __VA_ARGS__)>; \
\
public: \
constexpr EnumName() noexcept : value_{values_[0]} {} \
constexpr EnumName(const EnumName& other) noexcept : value_{other.value_} {} \
constexpr EnumName(Internal##EnumName value) noexcept : value_{value} {} \
constexpr EnumName operator=(const EnumName& other) noexcept { value_ = other.value_; return *this; } \
constexpr EnumName operator=(Internal##EnumName value) noexcept { value_ = value; return *this; } \
\
constexpr bool operator==(EnumName other) const noexcept { return value_ == other.value_; } \
constexpr bool operator!=(EnumName other) const noexcept { return !(*this == other); } \
constexpr bool operator<(EnumName other) const noexcept { return value_ < other.value_; } \
constexpr bool operator>=(EnumName other) const noexcept { return !(*this < other); } \
constexpr bool operator>(EnumName other) const noexcept { return value_ > other.value_; } \
constexpr bool operator<=(EnumName other) const noexcept { return !(*this > other); } \
\
constexpr underlyingType to_value() const noexcept \
{ \
return static_cast<underlyingType>(value_); \
} \
constexpr explicit operator underlyingType() const noexcept \
{ \
return to_value(); \
} \
template<class T> \
static constexpr EnumName from_value(T val) \
{ \
static_assert(std::is_convertible<T, underlying_type>::value, \
"Construction from value require the value to be convertible to the underlying type"); \
\
for(const auto value : values_) \
{ \
if(value == val) \
{ \
return {static_cast<Internal##EnumName>(val)}; \
} \
} \
\
CONSTEXPR_ASSERT(false, "The value to build from is invalid"); \
} \
static constexpr bool is_contiguous() noexcept \
{ \
if(values_.size() == 0) return true; \
underlyingType last = values_[0]; \
for(auto it = values_.cbegin() + 1; it != values_.cend(); ++it, ++last) \
{ \
if(*it != last + 1) return false; \
} \
return true; \
} \
\
static constexpr size_t size() noexcept \
{ \
return size_; \
} \
\
private: \
class IterableHelper \
{ \
public: \
constexpr IterableHelper() : value_{values_[0]}{} \
constexpr IterableHelper(Internal##EnumName value) : value_{value}{} \
\
\
constexpr EnumName::iterator begin() noexcept { return { value_ }; } \
constexpr EnumName::const_iterator cbegin() noexcept { return begin(); } \
constexpr EnumName::iterator end() noexcept { return { size_, EnumName::iterator::indexInitFlag{} }; } \
constexpr EnumName::const_iterator cend() noexcept { return end(); } \
\
constexpr EnumName::reverse_iterator rbegin() noexcept { return end(); } \
constexpr EnumName::const_reverse_iterator crbegin() noexcept { return end(); } \
constexpr EnumName::reverse_iterator rend() noexcept { return begin(); } \
constexpr EnumName::const_reverse_iterator crend() noexcept { return begin(); } \
\
static constexpr EnumName::iterator from(EnumName e) noexcept { return { e }; } \
static constexpr EnumName::const_iterator cfrom(EnumName e) noexcept { return { e }; } \
static constexpr EnumName::reverse_iterator rfrom(EnumName e) noexcept { return { e }; } \
static constexpr EnumName::const_reverse_iterator crfrom(EnumName e) noexcept { return { e }; } \
\
private: \
Internal##EnumName value_; \
}; \
\
public: \
static constexpr IterableHelper iter() noexcept{ return {}; } \
static constexpr IterableHelper iter_from(Internal##EnumName value) noexcept{ return {value}; } \
\
constexpr size_t get_index() const noexcept \
{ \
for(size_t i = 0; i < size_; ++i) \
{ \
if(values_[i] == value_) return i; \
} \
return size_; /* Or error ? */ \
} \
\
private: \
Internal##EnumName value_; \
\
static constexpr size_t size_ = std::tuple_size<TupleType>::value; \
static constexpr const ConstString enum_name() noexcept \
{ \
return #EnumName; \
} \
\
public: \
using ValuesArrayType = std::array<Internal##EnumName, size_>; \
\
static constexpr const ValuesArrayType& values() noexcept { return values_; } \
\
private: \
static constexpr ValuesArrayType values_{{MAP2(ENUM_ASSIGN_REMOVE(EnumName), __VA_ARGS__)}}; \
}; \
/* Declarations like :
* IMPROVED_ENUM(MyEnum, size_t, Hello = 5);
* will produce names like "Hello ".
*/
#define IMPROVED_ENUM(EnumName, underlyingType, ...) \
namespace { using EnumName##TupleType = std::tuple<MAP2(ENUM_NAME_TUPLE_DECL, __VA_ARGS__)>; \
static constexpr EnumName##TupleType EnumName##names_{MAP2(STRINGIFY_ENUM, __VA_ARGS__)};} \
static_assert(std::is_integral<underlyingType>::value, \
"The defined underlying type is not an integral type"); \
class EnumName \
{ \
public: \
enum Internal##EnumName : underlyingType{ __VA_ARGS__ }; \
\
using iterator = EnumUtils::EnumIterator<EnumName, EnumUtils::EnumIteratorTag::Normal>; \
using const_iterator = iterator; \
using reverse_iterator = EnumUtils::EnumIterator<EnumName, EnumUtils::EnumIteratorTag::Reversed>; \
using const_reverse_iterator = reverse_iterator; \
using underlying_type = underlyingType; \
using UnderlyingEnumType = Internal##EnumName; \
\
public: \
constexpr EnumName() noexcept : value_{values_[0]} {} \
constexpr EnumName(const EnumName& other) noexcept : value_{other.value_} {} \
constexpr EnumName(Internal##EnumName value) noexcept : value_{value} {} \
constexpr EnumName operator=(const EnumName& other) noexcept { value_ = other.value_; return *this; } \
constexpr EnumName operator=(Internal##EnumName value) noexcept { value_ = value; return *this; } \
\
constexpr bool operator==(EnumName other) const noexcept { return value_ == other.value_; } \
constexpr bool operator!=(EnumName other) const noexcept { return !(*this == other); } \
constexpr bool operator<(EnumName other) const noexcept { return value_ < other.value_; } \
constexpr bool operator>=(EnumName other) const noexcept { return !(*this < other); } \
constexpr bool operator>(EnumName other) const noexcept { return value_ > other.value_; } \
constexpr bool operator<=(EnumName other) const noexcept { return !(*this > other); } \
\
constexpr underlyingType to_value() const noexcept \
{ \
return static_cast<underlyingType>(value_); \
} \
constexpr explicit operator underlyingType() const noexcept \
{ \
return to_value(); \
} \
template<class T> \
static constexpr EnumName from_value(T val) noexcept \
{ \
static_assert(std::is_convertible<T, underlying_type>::value, \
"Construction from value require the value to be convertible to the underlying type"); \
\
for(const auto value : values_) \
{ \
if(value == static_cast<Internal##EnumName>(val)) \
{ \
return {static_cast<Internal##EnumName>(val)}; \
} \
} \
\
CONSTEXPR_ASSERT(false, "The value to build from is invalid"); \
} \
\
static constexpr bool is_contiguous() noexcept \
{ \
if(values_.size() == 0) return true; \
underlyingType last = values_[0]; \
for(auto it = values_.cbegin() + 1; it != values_.cend(); ++it, ++last) \
{ \
if(*it != last + 1) return false; \
} \
return true; \
} \
\
static constexpr size_t size() noexcept \
{ \
return size_; \
} \
\
private: \
class IterableHelper \
{ \
public: \
constexpr IterableHelper() : value_{values_[0]}{} \
constexpr IterableHelper(Internal##EnumName value) : value_{value}{} \
\
\
constexpr EnumName::iterator begin() noexcept { return { value_ }; } \
constexpr EnumName::const_iterator cbegin() noexcept { return begin(); } \
constexpr EnumName::iterator end() noexcept { return { size_, EnumName::iterator::indexInitFlag{} }; } \
constexpr EnumName::const_iterator cend() noexcept { return end(); } \
\
constexpr EnumName::reverse_iterator rbegin() noexcept { return end(); } \
constexpr EnumName::const_reverse_iterator crbegin() noexcept { return end(); } \
constexpr EnumName::reverse_iterator rend() noexcept { return begin(); } \
constexpr EnumName::const_reverse_iterator crend() noexcept { return begin(); } \
\
static constexpr EnumName::iterator from(EnumName e) noexcept { return { e }; } \
static constexpr EnumName::const_iterator cfrom(EnumName e) noexcept { return { e }; } \
static constexpr EnumName::reverse_iterator rfrom(EnumName e) noexcept { return { e }; } \
static constexpr EnumName::const_reverse_iterator crfrom(EnumName e) noexcept { return { e }; } \
\
private: \
Internal##EnumName value_; \
}; \
\
public: \
static constexpr IterableHelper iter() noexcept{ return {}; } \
static constexpr IterableHelper iter_from(Internal##EnumName value) noexcept{ return {value}; } \
\
constexpr size_t get_index() const noexcept \
{ \
for(size_t i = 0; i < size_; ++i) \
{ \
if(values_[i] == value_) return i; \
} \
return size_; /* Or error ? */ \
} \
\
\
\
public: \
constexpr ConstString to_string() const; \
static constexpr ConstString get_enum_name() noexcept \
{ \
return #EnumName; \
} \
\
private: \
Internal##EnumName value_; \
static constexpr size_t size_ = std::tuple_size<EnumName##TupleType>::value; \
\
template<size_t index> \
struct Looper \
{ \
static constexpr ConstString to_string_impl(const EnumName e) \
{ \
static_assert(index < e.size_, "Out of range !"); \
\
return e.values_[index] == e.value_ ? \
ConstString{std::get<index>(EnumName##names_)} \
: Looper<index + 1>::to_string_impl(e); \
} \
}; \
\
public: \
using ValuesArrayType = std::array<Internal##EnumName, size_>; \
static constexpr const ValuesArrayType& values() noexcept { return values_; } \
\
private: \
static constexpr ValuesArrayType values_{{MAP2(ENUM_ASSIGN_REMOVE(EnumName), __VA_ARGS__)}}; \
}; \
\
template<> \
struct EnumName::Looper<EnumName::size_> \
{ \
static constexpr ConstString to_string_impl(EnumName) \
{ \
return ""; \
} \
}; \
constexpr ConstString EnumName::to_string() const \
{ \
return Looper<0>::to_string_impl(*this); \
} \
#endif // ENUM_UTILS_HXX
|
38cea800c7c99ee302ec6ad36e38f70b124d8d0f | 043182421d07410b8cc8982f9b864d9e9d82a5bf | /Image_Processing/ImageDlg.h | bf7b76bd27c2025db94755dffd6d93dc1f88c434 | [] | no_license | Noligz/Image_Processing | ebf2e5fce114b08b6f7a64e2002199ca035a01ea | 553f975fe5c0f72c10df72482a38efa313acf379 | refs/heads/master | 2016-09-06T14:32:00.189966 | 2013-07-27T02:08:36 | 2013-07-27T02:08:36 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 580 | h | ImageDlg.h | #pragma once
// CImageDlg 对话框
class CImageDlg : public CDialog
{
DECLARE_DYNAMIC(CImageDlg)
public:
CImageDlg(CWnd* pParent = NULL, CImage* pImg = NULL); // 标准构造函数
virtual ~CImageDlg();
// 对话框数据
enum { IDD = IDD_IMAGE };
CImage* m_pImg;
int imgWidth;
int imgHeight;
int ImgOffset;
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnPaint();
virtual BOOL OnInitDialog();
afx_msg void OnBnClickedSave();
};
|
12a0a0c3e87ea4c53b43856d7a10452b83ad1192 | 71c1e89cac41d2fd43a8d569d45e11fe3940e51a | /include/bitmap_header.h | c767ab27e923134e69535f4b4184c14f27e31eed | [] | no_license | sascha432/esp8266-kfc-fw | 3f850a4d72d7b1a9204401aa09deab88b987f79b | 27dddd624b8d69cc2d2aeac08dee679ac1216466 | refs/heads/master | 2023-08-17T00:42:14.852718 | 2023-08-13T18:13:53 | 2023-08-13T18:13:53 | 159,572,123 | 10 | 2 | null | 2021-04-18T02:44:46 | 2018-11-28T22:10:18 | C++ | UTF-8 | C++ | false | false | 1,317 | h | bitmap_header.h | /**
* Author: sascha_lammers@gmx.de
*/
#pragma once
#include <Arduino_compat.h>
#include "push_pack.h"
#if !_MSC_VER
typedef struct __attribute__packed__ {
uint16_t bfType;
uint32_t bfSize;
uint16_t bfReserved1;
uint16_t bfReserved2;
uint32_t bfOffBits;
} BITMAPFILEHEADER;
typedef struct __attribute__packed__ {
uint32_t biSize;
int32_t biWidth;
int32_t biHeight;
uint16_t biPlanes;
uint16_t biBitCount;
uint32_t biCompression;
uint32_t biSizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
uint32_t biClrUsed;
uint32_t biClrImportant;
} BITMAPINFOHEADER;
#endif
namespace GFXCanvas {
union BitmapFileHeaderType {
struct _bitmapHeader {
BITMAPFILEHEADER bfh;
BITMAPINFOHEADER bih;
} h;
uint8_t b[sizeof(struct _bitmapHeader)];
BitmapFileHeaderType() : b{}
{}
};
// check if structures have the correct size
static_assert(sizeof(BITMAPFILEHEADER) == 14, "Invalid size");
static_assert(sizeof(BITMAPINFOHEADER) == 40, "Invalid size");
static_assert(sizeof(BitmapFileHeaderType) == 54, "Invalid size");
}
#include "pop_pack.h"
|
fb3f3b6aa6a06f89242fe78fbc5e7f8b63e6177e | c51febc209233a9160f41913d895415704d2391f | /library/ATF/tagFUNCDESC.hpp | d96e15c4728df162db48b64bf9d63f2f7b2ef2f4 | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 646 | hpp | tagFUNCDESC.hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <tagELEMDESC.hpp>
START_ATF_NAMESPACE
#pragma pack(push, 8)
struct tagFUNCDESC
{
int memid;
int *lprgscode;
tagELEMDESC *lprgelemdescParam;
tagFUNCKIND funckind;
tagINVOKEKIND invkind;
tagCALLCONV callconv;
__int16 cParams;
__int16 cParamsOpt;
__int16 oVft;
__int16 cScodes;
tagELEMDESC elemdescFunc;
unsigned __int16 wFuncFlags;
};
#pragma pack(pop)
END_ATF_NAMESPACE
|
87e1d1c6da0042f402d3196b1409277f52ec4445 | 85f87088bbc2a7426319fdd91109d34efcc4b05b | /src/alib/expressions/detail/virtualmachine.cpp | 936ef0e6c1954e0c1ff58f2526c06d3207351824 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | AlexWorx/ALib-Class-Library | 7c6ea35780fa690864f8e730cee1891ca4aa71d9 | 83e7562fdd43216dcc9b8cff2b774737a40808c0 | refs/heads/master | 2020-03-16T22:55:15.195985 | 2019-12-16T12:28:18 | 2019-12-16T12:28:18 | 133,057,682 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 33,250 | cpp | virtualmachine.cpp | // #################################################################################################
// ALib C++ Library
//
// Copyright 2013-2019 A-Worx GmbH, Germany
// Published under 'Boost Software License' (a free software license, see LICENSE.txt)
// #################################################################################################
#include "alib/alib_precompile.hpp"
#if !defined(ALIB_DOX)
#if !defined (HPP_ALIB_EXPRESSIONS_DETAIL_VIRTUAL_MACHINE)
# include "alib/expressions/detail/virtualmachine.hpp"
#endif
#if !defined (HPP_ALIB_TEXT_PARAGRAPHS)
# include "alib/text/paragraphs.hpp"
#endif
#if !defined (HPP_ALIB_EXPRESSIONS_COMPILERPLUGIN)
# include "alib/expressions/compilerplugin.hpp"
#endif
#if !defined (HPP_ALIB_EXPRESSIONS_DETAIL_PROGRAM)
# include "alib/expressions/detail/program.hpp"
#endif
#if !defined (HPP_ALIB_EXPRESSIONS_DETAIL_AST)
# include "alib/expressions/detail/ast.hpp"
#endif
#endif // !defined(ALIB_DOX)
namespace aworx { namespace lib { namespace expressions { namespace detail {
VirtualMachine::Command::Command( Program* program, const Box& resultType, const String& functionOrOp,
integer idxOriginal, integer idxNormalized )
: opcode ( OpCodes::Subroutine )
, Operation ( program )
, ResultType ( resultType )
, ExpressionPositions( (static_cast<uinteger>(idxNormalized) << (sizeof(integer)/2*8) )
+ static_cast<uinteger>(idxOriginal ) )
, DecompileType ( DecompileInfoType::Subroutine )
, DecompileSymbol ( functionOrOp )
{}
#define POS_IN_EXPR_STR (cmd.ExpressionPositions & ( (1UL << (sizeof(integer) / 2 * 8 - 1) ) -1 ) )
#if ALIB_DEBUG
# define NORMPOS_IN_EXPR_STR (cmd.ExpressionPositions >> (sizeof(integer)/2*8 ) )
#endif
// #################################################################################################
// Run()
// #################################################################################################
Box VirtualMachine::Run( Program& program, Scope& scope )
{
// If the scope.Stack is empty, this indicates, that this is an 'external' call and not a
// subroutine.
scope.Reset();
// attach the compile-time scope to the evaluation scope.
scope.CTScope= program.expression.ctScope;
// run
run( program, scope );
// unset ctscope
scope.CTScope= nullptr;
// Remove top element from the stack and return its result.
Box result= scope.Stack.back();
scope.Stack.pop_back();
return result;
}
void VirtualMachine::run( Program& program, Scope& scope )
{
ALIB_DBG( using DCT= Command::DecompileInfoType; )
ALIB_DBG( auto initialStackSize= scope.Stack.size(); )
auto& stack= scope.Stack;
// check circular calls
for( auto* nestedExpression : scope.NestedExpressions )
if( nestedExpression == &program.expression )
{
Exception e( ALIB_CALLER_NULLED, Exceptions::CircularNestedExpressions );
for( auto it2= scope.NestedExpressions.begin() ; it2!= scope.NestedExpressions.end(); ++it2 )
e.Add ( ALIB_CALLER_NULLED, Exceptions::CircularNestedExpressionsInfo,
(*it2)->Name(),
it2 + 1 != scope.NestedExpressions.end()
? (*(it2+1))->Name()
: nestedExpression->Name() );
throw e;
}
scope.NestedExpressions.emplace_back( &program.expression );
for( integer programCounter= 0; programCounter < program.Length() ; ++ programCounter )
{
const Command& cmd= program.At(programCounter);
ALIB_WARNINGS_ALLOW_BITWISE_SWITCH
switch( cmd.Which() )
{
case Command::OpCodes::Constant:
stack.emplace_back( cmd.Operation.Value );
break;
case Command::OpCodes::Function:
{
try
{
// with no args, we need a new stack object
if( cmd.QtyFunctionArgs <= 0 )
{
stack.emplace_back( cmd.Operation.Callback( scope,
stack.end() ,
stack.end() ) );
ALIB_ASSERT_ERROR( cmd.ResultType.IsSameType(stack.back()),
"Result type mismatch during command execution:\\n"
" In expression: {!Q} {{{}}}\\n"
" Plugin: {}\\n"
" Identifier: {} ({})\\n"
" Expected type: {!Q<>} (aka {})\\n"
" Result type: {!Q<>} (aka {})\\n"
" Result value: {}\\n",
program.expression.Name(),
program.expression.GetNormalizedString(),
cmd.DbgInfo.Plugin->Name,
cmd.DecompileSymbol, cmd.DbgInfo.Callback,
program.compiler.TypeName( cmd.ResultType ), cmd.ResultType.TypeID(),
program.compiler.TypeName( stack.back() ), stack.back() .TypeID(),
stack.back() )
}
// otherwise, we assign the value the position of the first arg in the stack and
// delete the other args after the call
else
{
ALIB_DBG( Box arg1Saved= *(stack.end() - static_cast<ptrdiff_t >( cmd.QtyFunctionArgs ) ); )
*(stack.end() - static_cast<ptrdiff_t>( cmd.QtyFunctionArgs ) )=
cmd.Operation.Callback( scope,
stack.end() - static_cast<ptrdiff_t>( cmd.QtyFunctionArgs ),
stack.end() );
#if ALIB_DEBUG
if( !cmd.ResultType.IsSameType(*(stack.end() - static_cast<ptrdiff_t>( cmd.QtyFunctionArgs ) )) )
{
String128 description;
switch( cmd.DecompileType )
{
case DCT::UnaryOp:
description << "Unary operator '" << cmd.DecompileSymbol << '\'';
break;
case DCT::BinaryOp:
description << "Binary operator '" << cmd.DecompileSymbol << '\'';
break;
case DCT::Function:
if( cmd.QtyFunctionArgs < 0 )
description << "Identifier \"" << cmd.DecompileSymbol << '\"';
else if( cmd.QtyFunctionArgs == 0 )
description << "Function \"" << cmd.DecompileSymbol << "()\"";
else
description << "Function \"" << cmd.DecompileSymbol << "(#"
<< cmd.QtyFunctionArgs << ")\"";
break;
case DCT::AutoCast:
description << "Auto-cast" << cmd.DecompileSymbol << '\'';
break;
case DCT::LiteralConstant: ALIB_FALLTHROUGH
case DCT::OptimizationConstant:
ALIB_ERROR("Must not be set with function calls")
}
String512 msg;
auto fmt= Formatter::AcquireDefault(ALIB_CALLER_PRUNED);
fmt->Format( msg, "Result type mismatch during command execution:\\n"
" In expression: {!Q} {{{}}}\\n"
" Plugin: {}\\n"
" Info: {}\\n"
" Callback: {}\\n"
" Expected type: {!Q<>} (aka {})\\n"
" Result type: {!Q<>} (aka {})\\n"
" Result value: {}\\n"
" Parameter values: ",
program.expression.Name(),
program.expression.GetNormalizedString(),
cmd.DbgInfo.Plugin->Name,
description,
cmd.DbgInfo.Callback,
program.compiler.TypeName( cmd.ResultType ), cmd.ResultType.TypeID(),
program.compiler.TypeName( stack.back() ), stack.back() .TypeID(),
stack.back() );
fmt->Format( msg, "({!Q'} {!Q<>}",
arg1Saved,
program.compiler.TypeName( arg1Saved ) );
for( integer i= cmd.QtyFunctionArgs - 1; i > 0 ; --i )
fmt->Format( msg, ", {!Q'} {!Q<>}",
*(stack.end() - i),
program.compiler.TypeName( *(stack.end()-i)) );
msg << ')';
fmt->Release();
ALIB_ERROR( msg )
}
#endif
for(integer i= 1; i < cmd.QtyFunctionArgs; ++i )
stack.pop_back();
}
}
catch( Exception& e )
{
if( !HasBits(program.compiler.CfgCompilation, Compilation::CallbackExceptionFallThrough) )
{
e.Add( ALIB_CALLER_NULLED, Exceptions::ExceptionInCallback,
program.expression.Name() );
e.Add( ALIB_CALLER_NULLED, Exceptions::ExpressionInfo,
program.expression.GetOriginalString(), POS_IN_EXPR_STR );
}
throw;
}
catch( std::exception& stdException )
{
if( !HasBits(program.compiler.CfgCompilation, Compilation::CallbackExceptionFallThrough) )
{
Exception e( ALIB_CALLER_NULLED, Exceptions::ExceptionInCallback,
program.expression.Name() );
e.Add ( ALIB_CALLER_NULLED, Exceptions::ExpressionInfo,
program.expression.GetOriginalString(), POS_IN_EXPR_STR );
e.Add ( ALIB_CALLER_NULLED, Exceptions::StdExceptionInfo,
stdException.what() );
throw e;
}
throw;
}
}
break;
case Command::OpCodes::JumpIfFalse:
{
if( !stack.back().Call<FIsTrue>() )
programCounter+= cmd.Operation.Distance -1; //-1 due to loop increase
stack.pop_back();
}
break;
case Command::OpCodes::Jump:
programCounter+= cmd.Operation.Distance - 1; //-1 due to loop increase
break;
case Command::OpCodes::Subroutine:
// evaluation time defined nested expression
if( cmd.Operation.NestedProgram == nullptr
|| cmd.Operation.NestedProgram == &program)
{
SPExpression nested;
String nestedExpressionName= (stack.end()-2)->Unbox<String>();
try
{
nested= program.compiler.GetNamed( nestedExpressionName );
}
catch( Exception& e )
{
// 3rd parameter "throw" was not given
if( cmd.Operation.NestedProgram == nullptr )
{
// not found? -> remove name parameter from stack and use result of
// second parameter.
if( e.Type().Integral() == UnderlyingIntegral( Exceptions::NamedExpressionNotFound ) )
{
stack.erase( stack.end() - 2 );
break;
}
e.Add( ALIB_CALLER_NULLED, Exceptions::WhenEvaluatingNestedExpression,
nestedExpressionName );
e.Add( ALIB_CALLER_NULLED, Exceptions::ExpressionInfo,
program.expression.GetOriginalString(), POS_IN_EXPR_STR );
throw;
}
// 3rd parameter "throw" was given
if( e.Type().Integral() == UnderlyingIntegral( Exceptions::NamedExpressionNotFound ) )
e.Add( ALIB_CALLER_NULLED, Exceptions::NestedExpressionNotFoundET,
nestedExpressionName );
else
e.Add( ALIB_CALLER_NULLED, Exceptions::WhenEvaluatingNestedExpression,
nestedExpressionName );
throw;
}
run( * dynamic_cast<Program*>(nested.get()->GetProgram()), scope);
if( !(stack.end()-2)->IsSameType(stack.back()) )
{
Exception e( ALIB_CALLER_NULLED, Exceptions::NestedExpressionResultTypeError,
nestedExpressionName,
program.compiler.TypeName( *(stack.end()-2) ),
program.compiler.TypeName( stack.back() ) );
e.Add ( ALIB_CALLER_NULLED, Exceptions::ExpressionInfo,
program.expression.GetOriginalString(), POS_IN_EXPR_STR );
throw e;
}
stack.erase( stack.end()-3, stack.end() -1 );
}
// compile-time defined nested expression: just call it
else
run( *cmd.Operation.NestedProgram, scope );
break;
}
ALIB_WARNINGS_RESTORE
} // command loop
scope.NestedExpressions.pop_back();
// This assertion should never happen. It indicates rather a library error than an
// erroneous plug-in.
ALIB_ASSERT_ERROR( stack.size() == initialStackSize + 1,
"Internal error: Stack increased by {} (instead of 1) after run of expression program.",
stack.size() - initialStackSize )
// Usually a function did not return what it is defined to return.
ALIB_ASSERT_ERROR( program.ResultType().IsSameType(stack.back()),
"Wrong result type of program execution:\\n"
" Expected Type: {!Q<>} (aka {})\\n"
" Result Type: {!Q<>} (aka {})\\n"
" Result value: {}\\n"
" In expression: {!Q}"
,
program.compiler.TypeName( program.ResultType() ), program.ResultType().TypeID(),
program.compiler.TypeName( stack.back() ), stack.back() .TypeID(),
stack.back(),
program.expression.Name()
)
}
// #################################################################################################
// Decompile()
// #################################################################################################
AST* VirtualMachine::Decompile( Program& program, MonoAllocator& allocator)
{
using DCT= Command::DecompileInfoType;
#define PushNode(node) nodeStack.emplace_back( node )
#define PopNode nodeStack.pop_back()
#define Lhs (*(nodeStack.end() - 2) )
#define Rhs nodeStack.back()
#define Arg nodeStack.back()
std::vector<AST*> nodeStack;
std::stack <PC> conditionalStack; // Stores the target of jump commands behind the T of
// conditional term "Q : T : F". In other words, the
// end of 'F'
for( integer pc= 0 ; pc < program.Length() ; ++pc )
{
const Command& cmd= program.At(pc);
integer positionInExpression= POS_IN_EXPR_STR;
ALIB_WARNINGS_ALLOW_BITWISE_SWITCH
switch( cmd.Which() )
{
case Command::OpCodes::Subroutine:
{
// Function "Expression(name, type, boolean)"
if( cmd.Operation.NestedProgram == nullptr
|| cmd.Operation.NestedProgram == & program )
{
ASTFunction* node= allocator.Emplace<ASTFunction>( cmd.DecompileSymbol, positionInExpression, allocator );
for( integer i= 0 ; i< 2 ; ++i )
{
node->Arguments.Emplace( node->Arguments.begin(), Arg );
PopNode;
}
// if nullptr, third parameter "throw"
if( cmd.Operation.NestedProgram != nullptr )
node->Arguments.EmplaceBack(
allocator.Emplace<ASTIdentifier>( allocator.EmplaceString( program.compiler.CfgNestedExpressionThrowIdentifier ),
positionInExpression ) );
PushNode(node);
break;
}
// constant call (program was given)
ASTIdentifier* name = allocator.Emplace<ASTIdentifier>( allocator.EmplaceString(cmd.Operation.NestedProgram->expression.Name()) ,
positionInExpression );
ASTUnaryOp* nested= allocator.Emplace<ASTUnaryOp>( program.compiler.CfgNestedExpressionOperator,
name,
positionInExpression );
PushNode( nested );
}
break;
case Command::OpCodes::Constant:
{
ASTLiteral* node= allocator.Emplace<ASTLiteral>( static_cast<integer>(0), positionInExpression );
node->Value= cmd.Operation.Value;
PushNode(node);
}
break;
case Command::OpCodes::Function:
{
if( cmd.DecompileType == DCT::UnaryOp )
{
ASTUnaryOp* node= allocator.Emplace<ASTUnaryOp>( cmd.DecompileSymbol, Arg, positionInExpression );
PopNode;
PushNode(node);
break;
}
if( cmd.DecompileType == DCT::BinaryOp )
{
ASTBinaryOp* node= allocator.Emplace<ASTBinaryOp>( cmd.DecompileSymbol, Lhs, Rhs, positionInExpression );
PopNode;
PopNode;
PushNode(node);
break;
}
if( cmd.QtyFunctionArgs < 0 )
{
ASTIdentifier* node= allocator.Emplace<ASTIdentifier>( cmd.DecompileSymbol, positionInExpression );
PushNode(node);
break;
}
ASTFunction* node= allocator.Emplace<ASTFunction>( cmd.DecompileSymbol, positionInExpression, allocator );
for( integer i= 0 ; i< cmd.QtyFunctionArgs ; ++i )
{
node->Arguments.Emplace( node->Arguments.begin(), Arg );
PopNode;
}
PushNode(node);
}
break;
case Command::OpCodes::JumpIfFalse: // '?'
{
}
break;
case Command::OpCodes::Jump: // ':'
{
conditionalStack.emplace( pc + cmd.Operation.Distance -1 );
}
break;
}
ALIB_WARNINGS_RESTORE
while( !conditionalStack.empty() && conditionalStack.top() == pc )
{
AST* F= Arg; PopNode;
AST* T= Arg; PopNode; // F-Pos -2 is a little vague. But we don't care!
Arg= allocator.Emplace<ASTConditional>( Arg, T, F, positionInExpression, F->Position - 2 );
conditionalStack.pop();
}
} // command loop
#undef PushNode
#undef PopNode
#undef Lhs
#undef Rhs
#undef Arg
ALIB_ASSERT_ERROR( nodeStack.size() == 1,
"VM AST generation error: NodeImpl stack must contain one element. Elements: {}", nodeStack.size())
ALIB_ASSERT_ERROR( conditionalStack.size() == 0,
"VM Program List error: Conditional stack after listing not 0 but {}", conditionalStack.size())
return nodeStack.back();
}
// #################################################################################################
// DbgList()
// #################################################################################################
#if ALIB_DEBUG
//! @cond NO_DOX
namespace{
void writeArgPositions(AString& target, std::vector<VirtualMachine::PC>& resultStack, integer qtyArgs )
{
for( integer argNo= qtyArgs ; argNo > 0 ; --argNo )
{
target << (argNo == qtyArgs ? "" : ", ")
<< (qtyArgs-argNo) << "{"
<< ( static_cast<integer>(resultStack.size()) == argNo ? 0
: *(resultStack.end() - argNo - 1) + 1 )
<< ".." << *(resultStack.end() - argNo )
<< "}";
}
}
}
//! @endcond
AString VirtualMachine::DbgList( Program& program )
{
using DCT= Command::DecompileInfoType;
String fmtLine= EXPRESSIONS.GetResource( "ProgListLine" );
String fmtHeader= EXPRESSIONS.GetResource( "ProgListHeader");
Paragraphs text;
text.LineWidth=0;
text.Formatter= program.expression.ctScope->Formatter;
text.Formatter->Acquire( ALIB_CALLER_PRUNED ); // get formatter once to keep autosizes!
// repeat the whole output until its size is stable and all auto-tabs are set
integer lastLineWidth = 0;
while(lastLineWidth == 0 || lastLineWidth != text.DetectedMaxLineWidth)
{
lastLineWidth= text.DetectedMaxLineWidth;
text.Buffer.Reset();
// write headline
text.LineWidth= text.DetectedMaxLineWidth;
text.AddMarked( fmtHeader,
program.expression.Name(),
program.expression.GetNormalizedString() );
text.LineWidth= 0;
NString hdlKey= "ProgListHdl";
Box hdlArgs[10];
hdlArgs[0]= fmtLine;
NString64 hdlKeyNumbered(hdlKey);
for( int i= 0 ; i < 7 ; ++i )
{
hdlArgs[i+1]= EXPRESSIONS.GetResource(hdlKeyNumbered << i );
hdlKeyNumbered.ShortenTo( hdlKey.Length() );
}
hdlArgs[8]= 1;
hdlArgs[9]= program.expression.GetNormalizedString();
text.AddMarked( hdlArgs );
text.LineWidth= text.DetectedMaxLineWidth;
text.AddMarked("@HL-");
text.LineWidth= 0;
#define FMT(qtyArgs) \
{ if( cmd.DbgInfo.Plugin ) description << ", CP=\"" << cmd.DbgInfo.Plugin->Name<< '\"'; \
String256 argpos; writeArgPositions(argpos,resultStack,qtyArgs); \
text.Add( fmtLine, \
pc, \
program.compiler.TypeName( cmd.ResultType ), \
cmd.Which(), \
operation, \
stackSize, \
description, \
argpos, \
NORMPOS_IN_EXPR_STR, "_^_" ); }
#define PushResult resultStack.emplace_back( pc )
#define PopResult resultStack.pop_back()
#define ResultPos resultStack.back()
std::vector<PC> resultStack; // The last command of the current results on the stack
std::stack <PC> conditionalStack; // Stores the target of jump commands behind the T of
// conditional term "Q : T : F". In other words, the
// end of 'F'
PC stackSize = 0;
for( integer pc= 0 ; pc < program.Length() ; ++pc )
{
const Command& cmd= program.At(pc);
String128 operation;
String128 description;
ALIB_WARNINGS_ALLOW_BITWISE_SWITCH
switch( cmd.Which() )
{
case Command::OpCodes::Subroutine:
{
if( cmd.Operation.NestedProgram == nullptr
|| cmd.Operation.NestedProgram == &program )
{
--stackSize;
operation << ( cmd.Operation.NestedProgram == nullptr ? "Expr(name, type)"
: "Expr(name, type, throw)" );
description << "Nested expr. searched at evaluation-time";
PopResult;
}
else
{
++stackSize;
operation << cmd.DecompileSymbol
<< "\"" << cmd.Operation.NestedProgram->expression.Name() << '\"';
description << "Nested expr. searched at compile-time";
PushResult;
}
FMT(0)
}
break;
case Command::OpCodes::Constant:
{
++stackSize;
char uetzelchen= cmd.Operation.Value.IsType<String>() ? '\"' : '\'';
operation << uetzelchen << cmd.Operation.Value << uetzelchen;
description << (cmd.DecompileType == DCT::LiteralConstant ? "Literal constant"
: "Optimization constant" );
PushResult;
FMT(0)
}
break;
case Command::OpCodes::Function:
{
operation << cmd.DbgInfo.Callback
<< "(#" << (cmd.QtyFunctionArgs < 0 ? 0 : cmd.QtyFunctionArgs) << ')';
NString descr= nullptr;
char decSym= '\0';
switch( cmd.DecompileType )
{
case DCT::UnaryOp:
descr = "Unary operator";
decSym= '\'';
break;
case DCT::BinaryOp:
descr = "Binary operator";
decSym= '\'';
break;
case DCT::Function:
if( cmd.QtyFunctionArgs < 0 )
{
descr = "Identifier";
decSym= '"';
break;
}
description << "Function \"";
if( cmd.QtyFunctionArgs == 0 )
description << cmd.DecompileSymbol << "()\"";
else
description << cmd.DecompileSymbol << "(#"
<< cmd.QtyFunctionArgs << ")\"";
break;
case DCT::AutoCast:
descr = "Auto-cast";
decSym= '\'';
break;
case DCT::LiteralConstant: ALIB_FALLTHROUGH
case DCT::OptimizationConstant:
ALIB_ERROR("Must not be set with function calls")
}
if( descr.IsNotNull() )
description << descr << ' ' << decSym << cmd.DecompileSymbol << decSym;
stackSize+= 1 - (cmd.QtyFunctionArgs > 0 ? cmd.QtyFunctionArgs : 0 );
FMT(cmd.QtyFunctionArgs < 0 ? 0 : cmd.QtyFunctionArgs)
for( integer i= 0 ; i< cmd.QtyFunctionArgs ; ++i )
PopResult;
PushResult;
}
break;
case Command::OpCodes::JumpIfFalse: // '?'
{
operation << ( pc + cmd.Operation.Distance ) << " (absolute)" ;
description << "'?'";
FMT( 1 ) // first print Q
++ResultPos; // then have jump be included in T
}
break;
case Command::OpCodes::Jump: // ':'
{
conditionalStack.emplace( pc + cmd.Operation.Distance -1 );
operation << ( pc + cmd.Operation.Distance ) << " (absolute)" ;
description << "':'";
FMT( 1 ) // first print T
++ResultPos; // then have jump be included in T
}
break;
}
ALIB_WARNINGS_RESTORE
while( !conditionalStack.empty() && conditionalStack.top() == pc )
{
PopResult;
PopResult;
ResultPos= pc;
conditionalStack.pop();
stackSize-= 2;
}
} // command loop
#undef PushResult
#undef PopResult
#undef ResultPos
ALIB_ASSERT_ERROR( lastLineWidth!= 0 || stackSize == 1,
"VM Program List error: Stack size after listing not 1 but {}. Listing follows.\\n",
stackSize, text.Buffer )
ALIB_ASSERT_ERROR( lastLineWidth!= 0 || resultStack.size() == 1,
"VM Program List error: Resultstack after listing not 1 but {}. Listing follows.\\n",
resultStack.size(), text.Buffer )
ALIB_ASSERT_ERROR( lastLineWidth!= 0 || conditionalStack.size() == 0,
"VM Program List error: Conditional stack after listing not 0 but {}.Listing follows.\\n",
conditionalStack, text.Buffer )
} // main loop
text.Formatter->Release();
return std::move(text.Buffer);
}
#endif
#undef POS_IN_EXPR_STR
#undef PushResult
#undef PopResult
#undef ResultPos
#undef FMT
#undef PushNode
#undef PopNode
#undef Lhs
#undef Rhs
#undef Arg
}}}} // namespace [aworx::lib::expressions::detail]
|
0a8746bdbac6c2d7a30318e323f504a65e68fb96 | 596baf37a1625ea59f03ede8310bc6839867bf9e | /ArduinoCanbusMonitor/ArduinoCanbusCode/ArduinoCanbusCode.ino | b762fca870f5041033b7575e82644d1ab1507af7 | [] | no_license | sixuerain/Arduino_Canbus_Monitor | d0f5fc28a46dc4e6ca911c862f02ae259ae2a28e | 39af4536a77060e44387e0715e7e1626f32c7cdf | refs/heads/master | 2020-11-28T19:32:40.810417 | 2018-06-12T07:51:40 | 2018-06-12T07:51:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,644 | ino | ArduinoCanbusCode.ino | // Arduino based Canbus monitor
// communicates with host PC program written in C#
#include <SPI.h>
#include "mcp_can.h"
int stringSplit(char *str, const char *delim, int data[]);
// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 10;//9;
MCP_CAN CAN(SPI_CS_PIN); // Set CS pin
void setup()
{
while(!Serial);
delay(1000);
Serial.begin(115200);
delay(1000);
CanbusStart();
}
// start canbus shield
void CanbusStart(void)
{
Serial.println("Canbus monitor");
while (CAN_OK != CAN.begin(CAN_250KBPS)) // init can bus : baudrate = 500k
{
Serial.println("CAN BUS Shield init fail");
Serial.println(" Init CAN BUS Shield again");
delay(100);
}
Serial.println("CAN BUS Shield init ok!");
}
enum CANcommand
{CANBUSspeed=0, CANBUStransmit, Rx0mask, Rx0filter1, Rx0filter2,
Rx1mask, Rx1filter3, Rx1filter4, Rx1filter5, Rx1filter6 };
char str[100]={0};
int strIndex=0;
void loop()
{
// if serial data from PC process it
if(Serial.available())
{
char ch=Serial.read();
if(ch<' ')
{ // end of line parse the text[] for ints
char text[50]={0};
long int result[100]={0};
int i=stringSplit(str, " ", result);
Serial.print(i); Serial.print(" ints found = ");
for(int j=0; j<i;j++)
{/* Serial.print("result["); Serial.print(j); Serial.print("] = ");*/ Serial.print(result[j]); Serial.print(" ");}
Serial.println();
strIndex=0; str[0]=0;
if(i!=0)
switch(result[0]) // result[0] contain the command
{
case CANBUSspeed: Serial.print("canbus speed "); Serial.println(result[1]);
if(result[1]==125) CAN.begin(CAN_125KBPS);
if(result[1]==250) CAN.begin(CAN_250KBPS);
if(result[1]==500) CAN.begin(CAN_500KBPS);
break;
case CANBUStransmit: // transmit RTR or data frame
if(result[2]) strcat(text,">Tx EXT "); else strcat(text,">Tx STD ");
sprintf(&text[strlen(text)],"ID %08lx ", result[1]);
Serial.print(text);
static unsigned char stmp[8] = {0, 0, 0, 0, 0, 0, 0, 0};
if(result[3]) Serial.print(" RTR ");
else
{
Serial.print("data ");
for(int i = 0; i<8; i++) // print the data
{
text[0]=0;;
sprintf(text,"%02X", result[4+i]);
Serial.print(text);
stmp[i]=result[4+i];
}
}
Serial.println();
// byte sendMsgBuf(unsigned long id, byte ext, byte len, const byte *buf, bool wait_sent=true); // send buf
CAN.sendMsgBuf(result[1], result[2], result[3], 8, stmp);
break;
// byte init_Mask(byte num, byte ext, unsigned long ulData); // init Masks
case Rx0mask: CAN.init_Mask(0, result[1], result[2]); break; // there are 2 mask in mcp2515, you need to set both of them
case Rx1mask: CAN.init_Mask(1, result[1], result[2]); break; // there are 2 mask in mcp2515, you need to set both of them
case Rx0filter1: CAN.init_Filt(0,result[1], result[2]); break; // there are 6 filter in mcp2515
case Rx0filter2: CAN.init_Filt(1,result[1], result[2]); break; // there are 6 filter in mcp2515
case Rx1filter3: CAN.init_Filt(2,result[1], result[2]); break; // there are 6 filter in mcp2515
case Rx1filter4: CAN.init_Filt(3,result[1], result[2]); break; // there are 6 filter in mcp2515
case Rx1filter5: CAN.init_Filt(4,result[1], result[2]); break; // there are 6 filter in mcp2515
case Rx1filter6: CAN.init_Filt(5,result[1], result[2]); break; // there are 6 filter in mcp2515
}
}
else
{
if(ch=='>') CanbusStart(); // if line contains > restart canbus
else
{ // add character to text[]
str[strIndex++]=ch;
if(strIndex>99)strIndex=99;
str[strIndex]=0;
}
}
}
// check for received message
unsigned char len = 0;
unsigned char buf[8]={0};
if(CAN_MSGAVAIL == CAN.checkReceive()) // check if data coming
{
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
unsigned long int canId = CAN.getCanId();
char text[50]={0};
// setup standard 11 bit or extended 29 bit frame and add ID value
if(CAN.isExtendedFrame()) strcat(text,">Rx EXT "); else strcat(text,">Rx STD ");
sprintf(&text[strlen(text)],"ID %08lx ", canId);
Serial.print(text);
// check RTR or data frame
if(CAN.isRemoteRequest()) Serial.print(" RTR ");
else
{
Serial.print("data ");
for(int i = 0; i<8; i++) // print the data
{
text[0]=0;;
sprintf(text,"%02X", buf[i]);
Serial.print(text);
// Serial.print(buf[i], HEX);
}
}
Serial.println();
}
}
// split string str into long int values using delimiters
// this version uses atof() and does not return tokens with value 0.0f
// return function result number of floats converted
// return converted values in data[]
int stringSplit(char *str, const char *delim, long int data[])
{
//Serial.print("Splitting string into tokens:\n");
//Serial.println(str);
int i=0;
char *pch = strtok (str,delim); // get first token
while (pch != NULL)
{
float x=999;
//Serial.print("string found '"); Serial.print(pch);Serial.println("'");
// check if token is a int
if(strcmp(pch,"0") == 0)
{data[i]=0; /*Serial.print("int value decoded "); Serial.println(data[i]);*/ data[i++]; }
else
if((data[i]=atol(pch)) != 0) { /*Serial.print("int value decoded "); Serial.println(data[i]);*/ data[i++]; }
else Serial.println(" not a int");
pch = strtok (NULL, delim); // parse next token
}
return i;
}
|
89a17036fcb93ea1029cfdaca1b8837e8edc03ba | 22ecb9fce47102845ff060eadcfa0e04391027e0 | /Projekty Boost C++ Visual 2015/Boost_accumulators/Boost_accumulators/Boost_accumulators.cpp | f214bc04dda7aac31803a59f9e7c98eb2f1b7837 | [] | no_license | piterbuchcic1990/Programming-C-plus-plus | c0073d40678fda6b45f0de933ddabcd0a5458ed5 | d3ecea0e72d77dbd03cf67a6c9f6176cc67e8298 | refs/heads/master | 2021-06-12T12:12:49.021473 | 2017-02-09T15:13:14 | 2017-02-09T15:13:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,244 | cpp | Boost_accumulators.cpp |
#include <iostream>
#include <boost/accumulators/accumulators.hpp> //naglowek dla klasy
#include <boost/accumulators/statistics.hpp> //naglowek dla funkcji obliczajacych
using namespace boost::accumulators;
using namespace std::tr1;
class B { public: int a = 13; };
struct C:B //bez klauzury to dziedziczenie publiczne
{
void func() { a++; } // struktura moze miec metody
};
int main()
{
accumulator_set<double, features<tag::count,tag::mean,tag::variance,tag::moment<3>>> acc; //obiekt akumulatora, funktor()
acc(12.4, weight = 12); //dodanie wartosci do akumulatora, waga 12
acc(5.3,weight = 3);
acc(8.1,weight = 5);
std::cout << count(acc) << std::endl; //licznik danych w akumulatorze
std::cout << mean(acc) << std::endl; //sredia
std::cout << variance(acc) << std::endl; //odchylenie od sredniej
std::cout << moment<3>(acc) << std::endl;
acc(-9,weight = 1);
std::cout << count(acc) << std::endl;
std::cout << mean(acc) << std::endl;
std::cout << variance(acc) << std::endl;
acc(13,weight = 3);
std::cout << count(acc) << std::endl;
std::cout << mean(acc) << std::endl;
std::cout << variance(acc) << std::endl;
C x;
x.a = 15;
std::cout << x.a << std::endl;
x.func();
std::cout << x.a << std::endl;
return 0;
}
|
5955e98d78fd9a78fc88bed78a98df5d57898d8c | 58e54ea868bc75157909ee81db1a190928bb9bbd | /C3/LT-22 Generate ParenthesesL.cpp | e5030d0648177c3d2ea10b1390e94dd7992507d3 | [
"MIT"
] | permissive | yekesit/OA-or-Interview-Questions | 49368aa92ce63a72f2246830a2279b35ca7f7e0b | 89c0a4db10c4ffde6d49835c0621f9ec2e04f141 | refs/heads/master | 2020-06-04T11:27:48.451070 | 2019-08-15T21:21:27 | 2019-08-15T21:21:27 | 192,002,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 887 | cpp | LT-22 Generate ParenthesesL.cpp | //
// Created by Ke Ye on 2019-07-21.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution{
public:
vector<string> generateParenthesis(int n) {
int left = 0, right = 0;
vector<string> res;
string cur;
helper(res, cur, left, right, n);
return res;
}
private:
void helper(vector<string>& res, string& cur, int& left, int& right, int n){
if(left == n && right == n){
res.push_back(cur);
return;
}
if(left < n){
cur += '(';
left++;
helper(res, cur, left, right, n);
cur.pop_back();
left--;
}
if(right < left){
cur += ')';
right++;
helper(res, cur, left, right, n);
cur.pop_back();
right--;
}
}
};
int main(){
} |
5902bc7a24889889647fc14fa8f77c678b620c1f | 20760544859b3963ed8178b19804eaf96e0dc814 | /src/Display.cpp | dbe4cf2bc87cd33389675c8525975988f71b2f64 | [
"MIT"
] | permissive | azadad96/chip8_emulator | aa7f852be657949f5e2a21b936ed2da3082cbda3 | fed45202269fe7d41692f05144c8f04a5c97fb04 | refs/heads/main | 2023-07-03T22:28:40.921340 | 2021-07-11T20:56:50 | 2021-07-11T20:56:50 | 308,472,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,475 | cpp | Display.cpp | #include "Display.hpp"
Display::Display() {
memset(display, 0, sizeof(display));
running = true;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) {
printf("Couldn't initialize SDL\n");
exit(-1);
}
window = SDL_CreateWindow(
"Chip8 emulator",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width * scale, height * scale,
SDL_WINDOW_SHOWN
);
renderer = SDL_CreateRenderer(
window, -1, SDL_RENDERER_ACCELERATED
);
key_was_pressed = false;
memset(keys, false, sizeof(keys));
keytoid[0] = SDLK_x;
keytoid[1] = SDLK_1;
keytoid[2] = SDLK_2;
keytoid[3] = SDLK_3;
keytoid[4] = SDLK_q;
keytoid[5] = SDLK_w;
keytoid[6] = SDLK_e;
keytoid[7] = SDLK_a;
keytoid[8] = SDLK_s;
keytoid[9] = SDLK_d;
keytoid[0xA] = SDLK_y;
keytoid[0xB] = SDLK_c;
keytoid[0xC] = SDLK_4;
keytoid[0xD] = SDLK_r;
keytoid[0xE] = SDLK_f;
keytoid[0xF] = SDLK_v;
}
Display::~Display() {
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
SDL_Quit();
}
void Display::render() {
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
for (int i = 0; i < width * height; i++) {
int x = i % width * scale;
int y = i / width * scale;
if (display[i] != 0) {
SDL_Rect rect = {x, y, scale, scale};
SDL_RenderFillRect(renderer, &rect);
}
}
SDL_RenderPresent(renderer);
}
void Display::events() {
SDL_Event e;
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_QUIT:
running = false;
break;
case SDL_KEYDOWN: {
SDL_Keycode sym = e.key.keysym.sym;
for (int i = 0; i < 16; i++) {
if (keytoid[i] == sym)
keys[i] = true;
}
key_was_pressed = true;
break;
}
case SDL_KEYUP: {
SDL_Keycode sym = e.key.keysym.sym;
for (int i = 0; i < 16; i++) {
if (keytoid[i] == sym)
keys[i] = false;
}
break;
}
}
}
}
bool Display::keyPressed() {
return key_was_pressed;
}
void Display::clearKeyFlag() {
key_was_pressed = false;
} |
1629757c02e87c43b4b3e939370209a2fc3cd997 | c322776b39fd9a7cd993f483a5384b700b0c520e | /cegui.mod/cegui/src/falagard/CEGUIFalPropertyDefinitionBase.cpp | 20da5343e855c4f19f120eebb2c6cc80dfeba5b3 | [
"Zlib",
"BSD-3-Clause",
"MIT"
] | permissive | maxmods/bah.mod | c1af2b009c9f0c41150000aeae3263952787c889 | 6b7b7cb2565820c287eaff049071dba8588b70f7 | refs/heads/master | 2023-04-13T10:12:43.196598 | 2023-04-04T20:54:11 | 2023-04-04T20:54:11 | 14,444,179 | 28 | 26 | null | 2021-11-01T06:50:06 | 2013-11-16T08:29:27 | C++ | UTF-8 | C++ | false | false | 3,490 | cpp | CEGUIFalPropertyDefinitionBase.cpp | /***********************************************************************
filename: CEGUIFalPropertyDefinitionBase.cpp
created: Sat Oct 8 2005
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 "falagard/CEGUIFalPropertyDefinitionBase.h"
#include "CEGUIWindow.h"
// Start of CEGUI namespace section
namespace CEGUI
{
PropertyDefinitionBase::PropertyDefinitionBase(const String& name,
const String& help,
const String& initialValue,
bool redrawOnWrite,
bool layoutOnWrite)
: Property(name, help, initialValue),
d_writeCausesRedraw(redrawOnWrite),
d_writeCausesLayout(layoutOnWrite)
{
}
void PropertyDefinitionBase::set(PropertyReceiver* receiver, const String&)
{
if (d_writeCausesLayout)
static_cast<Window*>(receiver)->performChildWindowLayout();
if (d_writeCausesRedraw)
static_cast<Window*>(receiver)->invalidate();
}
void PropertyDefinitionBase::writeXMLToStream(XMLSerializer& xml_stream) const
{
// write out the element type
writeXMLElementType(xml_stream);
// write attributes
writeXMLAttributes(xml_stream);
// close tag
xml_stream.closeTag();
}
void PropertyDefinitionBase::writeXMLAttributes(XMLSerializer& xml_stream) const
{
// write the name of the property
xml_stream.attribute("name", d_name);
// write initial value, if any
if (!d_default.empty())
xml_stream.attribute("initialValue", d_default);
// write option to redraw when property is written
if (d_writeCausesRedraw)
xml_stream.attribute("redrawOnWrite", "true");
// write option to loayout children when property is written
if (d_writeCausesLayout)
xml_stream.attribute("layoutOnWrite", "true");
}
} // End of CEGUI namespace section
|
a65b0c5e275bd31612238c6f84ecc8c2b3cc4e23 | 501233a217b36ec6c86b50f72b297e00c6c6133c | /src/tests.cpp | 099d2f5e6ce2b08de7dc9de90ce3503dd550b1c8 | [
"MIT"
] | permissive | codr7/ampl | 2a44d9e87b17b80dabcf03e38cf1d2b2ffe41bec | e6adc9416c2d1ba4c421dfda0c2fca5cc65fe947 | refs/heads/main | 2023-08-28T21:03:22.765326 | 2021-11-06T17:35:07 | 2021-11-06T17:35:07 | 413,568,056 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 410 | cpp | tests.cpp | #include <cassert>
#include "ampl/rbuf.hpp"
using namespace ampl;
static void rbuf_tests() {
RBuf<int, 3> buf;
buf.push(1);
buf.push(2);
assert(buf.count == 2);
assert(buf.pop() == 1);
buf.push(3);
buf.push(4);
assert(buf.count == 3);
assert(buf.pop() == 2);
assert(buf.pop() == 3);
assert(buf.pop() == 4);
assert(buf.count == 0);
}
int main() {
rbuf_tests();
return 0;
}
|
fb17d7bc3706328af10e596d7e9079b22ad6bceb | f9ad496cf96e02a690a5f41e5758c92388fb2b76 | /source/server/nanomsg/survey_server.cpp | 0a0d29405b878bc91819fb06cd70d3b348d109e3 | [
"MIT"
] | permissive | coolniu/CppServer | 90b338383e920cf29e56ab5fffccf981b7bd7160 | da272e324a4fb8fb7a85b8bf3bf5758a48ee07ce | refs/heads/master | 2020-12-30T11:28:58.062254 | 2017-05-15T18:17:57 | 2017-05-15T18:17:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,039 | cpp | survey_server.cpp | /*!
\file survey_server.cpp
\brief Nanomsg survey server implementation
\author Ivan Shynkarenka
\date 02.02.2017
\copyright MIT License
*/
#include "server/nanomsg/survey_server.h"
#include "errors/exceptions.h"
namespace CppServer {
namespace Nanomsg {
std::tuple<size_t, bool> SurveyServer::ReceiveSurvey(Message& message)
{
if (!IsStarted())
return std::make_tuple(0, true);
try
{
return socket().ReceiveSurvey(message);
}
catch (CppCommon::SystemException& ex)
{
onError(ex.system_error(), ex.string());
return std::make_tuple(0, true);
}
}
std::tuple<size_t, bool> SurveyServer::TryReceiveSurvey(Message& message)
{
if (!IsStarted())
return std::make_tuple(0, true);
try
{
return socket().TryReceiveSurvey(message);
}
catch (CppCommon::SystemException& ex)
{
onError(ex.system_error(), ex.string());
return std::make_tuple(0, true);
}
}
} // namespace Nanomsg
} // namespace CppServer
|
458f74588d731163c7e8617a53e765098c910741 | 7abbbef9590f9c4b9469adcbae5ea8907478bf03 | /chromium_git/chromium/src/out/Debug/gen/blink/bindings/core/v8/V8AssignedNodesOptions.cpp | 46a6ef25ae4a5c794c9a34e82abbf30dd1eaaa28 | [
"BSD-3-Clause"
] | permissive | GiorgiGagnidze/CEF | 845bdc2f54833254b3454ba8f6c61449431c7884 | fbfc30b5d60f1ea7157da449e34dd9ba9c50f360 | refs/heads/master | 2021-01-10T17:32:27.640882 | 2016-03-23T07:43:04 | 2016-03-23T07:43:04 | 54,463,340 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,713 | cpp | V8AssignedNodesOptions.cpp | // Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "V8AssignedNodesOptions.h"
#include "bindings/core/v8/ExceptionState.h"
namespace blink {
void V8AssignedNodesOptions::toImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, AssignedNodesOptions& impl, ExceptionState& exceptionState)
{
if (isUndefinedOrNull(v8Value)) {
return;
}
if (!v8Value->IsObject()) {
exceptionState.throwTypeError("cannot convert to dictionary.");
return;
}
v8::TryCatch block(isolate);
v8::Local<v8::Object> v8Object;
if (!v8Call(v8Value->ToObject(isolate->GetCurrentContext()), v8Object, block)) {
exceptionState.rethrowV8Exception(block.Exception());
return;
}
{
v8::Local<v8::Value> flattenValue;
if (!v8Object->Get(isolate->GetCurrentContext(), v8String(isolate, "flatten")).ToLocal(&flattenValue)) {
exceptionState.rethrowV8Exception(block.Exception());
return;
}
if (flattenValue.IsEmpty() || flattenValue->IsUndefined()) {
// Do nothing.
} else {
bool flatten = toBoolean(isolate, flattenValue, exceptionState);
if (exceptionState.hadException())
return;
impl.setFlatten(flatten);
}
}
}
v8::Local<v8::Value> toV8(const AssignedNodesOptions& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate)
{
v8::Local<v8::Object> v8Object = v8::Object::New(isolate);
if (!toV8AssignedNodesOptions(impl, v8Object, creationContext, isolate))
return v8::Local<v8::Value>();
return v8Object;
}
bool toV8AssignedNodesOptions(const AssignedNodesOptions& impl, v8::Local<v8::Object> dictionary, v8::Local<v8::Object> creationContext, v8::Isolate* isolate)
{
if (impl.hasFlatten()) {
if (!v8CallBoolean(dictionary->CreateDataProperty(isolate->GetCurrentContext(), v8String(isolate, "flatten"), v8Boolean(impl.flatten(), isolate))))
return false;
} else {
if (!v8CallBoolean(dictionary->CreateDataProperty(isolate->GetCurrentContext(), v8String(isolate, "flatten"), v8Boolean(false, isolate))))
return false;
}
return true;
}
AssignedNodesOptions NativeValueTraits<AssignedNodesOptions>::nativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState)
{
AssignedNodesOptions impl;
V8AssignedNodesOptions::toImpl(isolate, value, impl, exceptionState);
return impl;
}
} // namespace blink
|
a15ef40da8b775456a59b410d06a29d400cd6212 | d81c631cd48d0a9c206d0c27adad7fb929d4b761 | /RoomServer/NetworkManager.cpp | 8f18ee12d68a71d58444ef61f51d11aa6a9af069 | [
"Apache-2.0"
] | permissive | GameForPeople/room-server-framework | 5d90ddb8396b27fac02c1f8c4d0cf8454ed7c6d8 | 369be17c929304a2abfd77257574bbe3e9d1ef64 | refs/heads/master | 2022-04-15T05:21:20.956753 | 2020-04-10T09:49:47 | 2020-04-10T09:49:47 | 250,313,775 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 3,635 | cpp | NetworkManager.cpp | #include "stdafx.h"
#include "MemoryUnit.h"
#include "UserUnit.h"
#include "NetworkManager.h"
#include "Utils.h"
NetworkManager::NetworkManager()
: sendMemoryPool()
{
// Send에 사용할 메모리를 미리 할당합니다.
for (int i = 0; i < SEND_MEMORY_POOL_SIZE; ++i)
{
sendMemoryPool.push(new SendMemoryUnit);
}
#if MULTI_SEND_THREAD_MODE == TRUE
// Send Thread Array의 각 thread를 활성화합니다.
for (auto& thread : sendThreadCont)
{
thread = static_cast<std::thread>([&]() { this->SendThread(); });
}
#endif
}
NetworkManager::~NetworkManager()
{
SendMemoryUnit* memoryUnit{ nullptr };
while (sendMemoryPool.try_pop(memoryUnit))
{
delete memoryUnit;
}
#if MULTI_SEND_THREAD_MODE == TRUE
while (sendMemoryCont.try_pop(memoryUnit))
{
delete memoryUnit;
}
#endif
}
#if MULTI_SEND_THREAD_MODE == TRUE
void NetworkManager::AddSendTask(SOCKET toSocket, std::string packetData)
{
// Send Memory Pool에서 메모리 하나를 뽑아옵니다.
auto sendMemoryUnit = PopSendMemoryUnit();
sendMemoryUnit->toSocket = toSocket;
// 오버랩 구조체를 초기화하고, 데이터를 카피합니다.
ZeroMemory(&(sendMemoryUnit->overlapped), sizeof(sendMemoryUnit->overlapped));
memcpy(sendMemoryUnit->dataBuffer, packetData.c_str(), packetData.length());
sendMemoryUnit->wsaBuffer.len = static_cast<ULONG>(packetData.length());
// Send Thread에게 Send Task를 할당합니다.
sendMemoryCont.push(sendMemoryUnit);
}
#endif
void NetworkManager::SendPacket(SOCKET toSocket, char* packetData)
{
// Send Memory Pool에서 메모리 하나를 뽑아옵니다.
auto sendMemoryUnit = PopSendMemoryUnit();
sendMemoryUnit->toSocket = toSocket;
// 오버랩 구조체를 초기화하고, 데이터를 카피합니다.
ZeroMemory(&(sendMemoryUnit->overlapped), sizeof(sendMemoryUnit->overlapped));
memcpy(sendMemoryUnit->dataBuffer, packetData, static_cast<unsigned char>(static_cast<unsigned char>(packetData[0])));
sendMemoryUnit->wsaBuffer.len = static_cast<ULONG>(static_cast<unsigned char>(packetData[0]));
// 실제 Send를 직접 때립니다.
if (SOCKET_ERROR == WSASend(sendMemoryUnit->toSocket, &(sendMemoryUnit->wsaBuffer), 1, NULL, 0, &(sendMemoryUnit->overlapped), NULL))
{
ERROR_UTIL::ErrorSend();
}
}
SendMemoryUnit* NetworkManager::PopSendMemoryUnit()
{
SendMemoryUnit* retMemoryUnit;
while (!sendMemoryPool.try_pop(retMemoryUnit))
{
asyncAllocateMemoryThread = static_cast<std::thread>([&]()
{
std::cout << "Send Memory Unit를 추가로 할당합니다. 서버 네트워크 부하로 인한 송신 지연이 의심됩니다. \n";
for (int i = 0; i < ADD_SEND_MEMORY_POOL_SIZE; ++i)
{
retMemoryUnit = new SendMemoryUnit();
sendMemoryPool.push(retMemoryUnit);
}
});
}
return retMemoryUnit;
}
void NetworkManager::SetRecvState(UserUnit* pUser)
{
DWORD flag{};
ZeroMemory(&(pUser->memoryUnit.overlapped), sizeof(pUser->memoryUnit.overlapped));
if (SOCKET_ERROR == WSARecv(pUser->socket, &(pUser->memoryUnit.wsaBuffer), 1, NULL, &flag /* NULL*/, &(pUser->memoryUnit.overlapped), NULL))
{
ERROR_UTIL::ErrorRecv();
}
}
void NetworkManager::PushSendMemoryUnit(SendMemoryUnit* const memoryUnit)
{
sendMemoryPool.push(memoryUnit);
}
#if MULTI_SEND_THREAD_MODE == TRUE
void NetworkManager::SendThread()
{
SendMemoryUnit* sendMemoryUnit;
while (7)
{
while(sendMemoryCont.try_pop(sendMemoryUnit))
{
if (SOCKET_ERROR == WSASend(sendMemoryUnit->toSocket, &(sendMemoryUnit->wsaBuffer), 1, NULL, 0, &(sendMemoryUnit->overlapped), NULL))
{
ERROR_UTIL::ErrorSend();
}
}
std::this_thread::yield();
}
}
#endif
|
203172e47d7f14655061a2fe3e55022bca804c5e | bdfca0068ae9b849781add731dbf2ed4e07d6536 | /app/ArmControl.h | 21063f9cbdb4fb4c6571fb740903ff14797cd633 | [] | no_license | mhikichi1969/hackEv3_2019 | 6b8d6ec7a3f96d599efafeeefd656f57cc565449 | 41bbd4e466dc5915d06cb9a1edd3826b4ed99a53 | refs/heads/master | 2023-02-01T14:21:09.258552 | 2019-10-13T00:46:52 | 2019-10-13T00:54:25 | 210,835,000 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | h | ArmControl.h | #ifndef _HARMCONTROL_H_
#define _HARMCONTROL_H_
#include "Motor.h"
#include "HBTtask.h"
#include "HPID.h"
#include "util.h"
//using namespace ev3api;
class ArmControl {
public:
ArmControl(ev3api::Motor& arm,HBTtask *bt);
~ArmControl();
void run();
void lock();
void decAngle();
void incAngle();
void dec10Angle();
void inc10Angle();
void throwBlock();
void setAngle(double ang);
void setLimit(double limit);
void setPID(float t, float p, float i, float d);
void setPwm(double pwm);
void execUndefined();
void execInit();
void execPIDRun();
void execPowRun();
void changeStateRun();
double getAngle();
private:
enum State {
EXEC_UDF,
EXEC_INI,
EXEC_PID,
EXEC_POW
};
ev3api::Motor& mArm;
HBTtask *mBt;
//HPID* mPID; //左右モーターの回転数の差を制御
State mState;
double angle;
double kp;
double bAngle;
};
#endif |
c1a03ae04c01c302b033e96e4790732476a104b9 | c747cfbe51cc24d15e49a888072d34635833d90a | /17_LetterCombinationsOfPhoneNumber.cpp | aec5759a60b8f28dd41a3a94b67f51d3dcf43e93 | [] | no_license | bigship/leetcode_solutions | 18921508a8acba25013ae65864168c4c084bef37 | 45edfab5f1696fa9b3b59b63663aa9524de209cd | refs/heads/master | 2022-08-22T05:42:37.462263 | 2022-08-02T20:14:50 | 2022-08-02T20:14:50 | 13,472,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,250 | cpp | 17_LetterCombinationsOfPhoneNumber.cpp | // 17. Letter Combinations of a Phone Number
/*
* Given a string containing digits from 2-9 inclusive, return all possible letter combinations
* that the number could represent.
*
A mapping of digit to letters (just like on the telephone buttons) is given below.
Note that 1 does not map to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
*/
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> ans;
if (digits.size() != 0)
backtrack(ans, "", digits, 0);
return ans;
}
private:
unordered_map<char, string> m = {
{'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"},
{'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}
};
void backtrack(vector<string>& ans, string tmp, string digits, int start) {
if (digits.size() == tmp.size()) {
ans.push_back(tmp);
return ;
}
string tp = m[digits[start]];
for (int i = 0; i < tp.size(); ++i) {
backtrack(ans, tmp+tp[i], digits, start+1);
}
}
};
|
cc18b768bdd40b03560bc24f6c1c3874593b87cc | 07ba7fde9da83edd3744557972b4b411af1b577d | /src/buzegui/buzegui.cpp | d26ebe58412a02a8c3c9fe3b397e19d2ae8dba46 | [] | no_license | clvn/buze | d10edad5b319ca62c1401e710acedc22897b9027 | 4d7d406e87bda3b57b7631149fe63f9bd2ac3eec | refs/heads/master | 2021-09-16T01:39:40.697834 | 2018-01-06T15:45:28 | 2018-01-06T15:45:28 | 115,177,320 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,687 | cpp | buzegui.cpp | #include "stdafx.h"
#include "resource.h"
#include "ToolbarWindow.h"
#include "ToolbarBands.h"
#include "Configuration.h"
#include <buze/buzesdk.h>
#include <buze/ViewImpl.h>
#include "BuzeConfiguration.h"
#include "AnalyzerView.h"
#include "CpuMeterView.h"
#include "CommentView.h"
#include "FileBrowserView.h"
#include "HelpView.h"
#include "HistoryView.h"
#include "PatternFormatView.h"
#include "PreferencesView.h"
#include "PropertyListView.h"
#include "MachineFolderView.h"
CHostDllModule _Module;
class CBuzeGuiLibrary : public CViewLibrary {
public:
virtual void Initialize(CViewFrame* host) {
_Module.m_hostModule = buze_application_get_host_module(buze_main_frame_get_application(host));
buze_main_frame_register_window_factory(host, new CAnalyzerViewInfo(host));
buze_main_frame_register_window_factory(host, new CCommentViewInfo(host));
buze_main_frame_register_window_factory(host, new CCpuMeterViewInfo(host));
buze_main_frame_register_window_factory(host, new CFileBrowserViewInfo(host));
buze_main_frame_register_window_factory(host, new CHelpViewInfo(host));
buze_main_frame_register_window_factory(host, new CHistoryViewInfo(host));
buze_main_frame_register_window_factory(host, new CPatternFormatViewInfo(host));
buze_main_frame_register_window_factory(host, new CPreferencesViewInfo(host));
buze_main_frame_register_window_factory(host, new CPropertyListViewInfo(host));
buze_main_frame_register_window_factory(host, new CMachineFolderViewInfo(host));
}
void Destroy() {
delete this;
}
int GetVersion() {
return CViewLibrary::version;
}
};
extern "C" CViewLibrary* buze_create_viewlibrary() {
return new CBuzeGuiLibrary();
}
|
7d2767cf042392c93abaeff39eed61191ca215a3 | 690b5a3a48ad1448e8aa9b693be9938a8c695e5c | /knRapid/src/rapidExtTraclabsDds/generated/ExtTraclabsConstants.h | 9246ec5ead0d4bc212b6d711dc882a4b2050ba1b | [
"Apache-2.0"
] | permissive | bcoltin/soraCore | f5e37901d3a975b7086cceab8bc393b9c4d442a4 | cd0624774b7a3b1aac17e0ce3338b8914387f3fc | refs/heads/master | 2021-01-19T04:10:40.940887 | 2017-04-21T20:38:46 | 2017-04-21T20:38:46 | 87,354,301 | 0 | 0 | null | 2017-04-05T20:37:45 | 2017-04-05T20:37:44 | null | UTF-8 | C++ | false | false | 1,365 | h | ExtTraclabsConstants.h |
/*
WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY.
This file was generated from ExtTraclabsConstants.idl using "rtiddsgen".
The rtiddsgen tool is part of the RTI Connext distribution.
For more information, type 'rtiddsgen -help' at a command shell
or consult the RTI Connext manual.
*/
#ifndef ExtTraclabsConstants_884907845_h
#define ExtTraclabsConstants_884907845_h
#ifndef NDDS_STANDALONE_TYPE
#ifdef __cplusplus
#ifndef ndds_cpp_h
#include "ndds/ndds_cpp.h"
#endif
#else
#ifndef ndds_c_h
#include "ndds/ndds_c.h"
#endif
#endif
#else
#include "ndds_standalone_type.h"
#endif
#include "BaseTypes.h"
namespace rapid{
namespace ext{
namespace traclabs{
/**
* A list of commonly used topic names.
* Custom topic names should
* have the standard name as the root, separated from the specialization by the "-" character, e.g.
* <code>rapid_position_sample-relative<code>
*/
static const rapid::String64 NOTICE_CONFIG_TOPIC = "traclabs_notice_config";
static const rapid::String64 NOTICE_STATE_TOPIC = "traclabs_notice_state";
static const rapid::String64 NOTICE_ACK_TOPIC = "traclabs_notice_ack";
} /* namespace traclabs */
} /* namespace ext */
} /* namespace rapid */
#endif /* ExtTraclabsConstants_884907845_h */
|
e0b1464eebba175b06d690c32e09c8c879b5d5c9 | f61f76fe43114ae4cff12ab7836087be254899e5 | /C++/Test/demo/pointer.cpp | f59c3a747f9d64c0f1b2792af0afa542faf3602a | [
"MIT"
] | permissive | MickelZhang/Algorithm | 39d58eb54065f2ec215efc337385aed342a45771 | 5f4cae0d0bc47626b60a9575c7eaec914a2208b1 | refs/heads/main | 2023-02-10T06:56:12.378848 | 2021-01-09T16:44:23 | 2021-01-09T16:44:23 | 319,822,924 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 16,532 | cpp | pointer.cpp | /*----------------------------------------------------------------
// Copyright (C) MickelZhang
// License:MIT
// 文件名:pointer.cpp
// 文件功能描述:
// 创建者:MickelZhang
// 时间:2020/12/16
// 修改人:MickelZhang
// 时间:2020/12/17
// 修改说明:B站中郝斌的C语言指针教程一定要看一下
// 修改人:MickelZhang
// 时间:2020/12/22
// 修改说明:详细说明:指针,引用
// 软件版本:VS2015
//----------------------------------------------------------------*/
#include <iostream>
#include <ctime>
#include <windows.h>
#include "pointer.h"
using namespace std;
/*
什么是指针:
指针是一个变量,其值为另一个变量的地址,即内存地址,就像其他变量或常量一样,您必须在使用指针存储其他变量地址之前,对其进行声明
int* p; // p表示变量的名字,p的数据类型是:int*表示类型, 表示p变量存放的是int类型变量的地址,int*数据类型:存放int变量地址的类型
int i = 3;
p = i; // 错误:类型不一致
p = &i; // 正确,p存放的是地址,&i 表示取地址,两个都是地址,正确
p = 55; // 错误:55也是整形
p = &i; // p保存了i的地址,则说明p指向了i
p不是i,i也不是p。修改p不影响i,修改i不影响p
如果一个指针变量指向了一个普通变量,*P 完全等于i 即*p,i 都是3
*p 和 i 是完全等价的,两个可以相互替换,所有出现i的地方可以换成*p 所有出现*p的地方可以换成i
p指向i,*p就是i,是一个东西。
*p 就是以p的内容为地址(p的内容 = i地址)的变量 等价于 i就是以p的内容为地址的变量 等价于 i就是以i地址为地址的变量
*p 和(&)取地址就是逆运算
指针就是地址,地址就是指针
地址就是内存单元的编号,等价起来指针就是内存中的编号
指针变量就是存放地址的变量,变量又分很多类型
指针和指针变量是不同的概念,但是要主要,通常我们叙述时会把指针变量简称为指针,实际上不一样。
int *ip; //一个整型的指针
double *dp; // 一个 double 型的指针
float *fp; // 一个浮点型的指针
char *ch; // 一个字符型的指针
所有指针的值的实际数据类型,不管是整型、浮点型、字符型,还是其他的数据类型,都是一样的,都是一个代表内存地址的长的十六进制数。
不同数据类型的指针之间唯一的不同是,指针所指向的变量或常量的数据类型不同。
指针的好处(重要性):
表示一些复杂的数据结构
快速的传递数据
是函数返回一个以上的值
直接访问硬件
能够方便的处理字符串
是理解面向对象语言中引用的基础
Null指针:在变量声明的时候,如果没有确切的地址可以赋值,为指针变量赋一个 NULL 值是一个良好的编程习惯。赋为 NULL 值的指针被称为空指针。
int *ptr = NULL;
cout << "ptr 的值是 " << ptr ; // 零 在大多数的操作系统上,程序不允许访问地址为 0 的内存,因为该内存是操作系统保留的。
然而,内存地址 0 有特别重要的意义,它表明该指针不指向一个可访问的内存位置。
但按照惯例,如果指针包含空值(零值),则假定它不指向任何东西。
指针的算术运算:指针是一个用数值表示的地址。因此,您可以对指针执行算术运算。可以对指针进行四种算术运算:++、--、+、-。
递减一个指针
递增一个指针
指针的比较
指针VS数组:指针和数组是密切相关的。事实上,指针和数组在很多情况下是可以互换的。
例如,一个指向数组开头的指针,可以通过使用指针的算术运算或数组索引来访问数组
注:数组名为常量指针,不可更改 // modified by Seventeen
指针数组:
指向指针的指针:是一种多级间接寻址的形式,或者说是一个指针链。通常,一个指针包含一个变量的地址。
当我们定义一个指向指针的指针时,第一个指针包含了第二个指针的地址,第二个指针指向包含实际值的位置。
传递指针给函数:C++ 允许您传递指针给函数,只需要简单地声明函数参数为指针类型即可。
从函数返回指针:见operator.cpp
*/
/*-----------------------------------------------------------------
// 输入:
// 输出:
// 功能描述:测试指针的一些代码
// 作者:MickelZhang
// 日期:2020/12/16
// 修改人:
// 记录:
// 修改人:
// 记录:
// 版本:
-----------------------------------------------------------------*/
void TestForPoint()
{
int var = 20; // 实际变量的声明
int *ip; // 指针变量的声明
ip = &var; // 在指针变量中存储 var 的地址
cout << "Value of var variable: ";
cout << var << endl;
cout << "*ip : "; // *p 也等于20
cout << *ip << endl;
// 输出在指针变量中存储的地址
cout << "Address stored in ip variable: ";
cout << ip << endl;
// 访问指针中地址的值
cout << "Value of *ip variable: ";
cout << *ip << endl;
// 修改ip不会改变var,同样的修改var也不会改变ip,但是var改了之后*P也会跟着变化
var = 35;
cout<<"var:"<<var<<" ip:"<<ip<<" *ip:"<<*ip<<endl;
// 同样的修改*ip,会影响var的数值
*ip = 34;
}
/*-----------------------------------------------------------------
// 输入:
// 输出:
// 功能描述:递增指针对于数组的测试,通过一个指向数组头部的指针来实现对数组的访问
// 作者:MickelZhang
// 日期:2020/12/16
// 修改人:
// 记录:
// 修改人:
// 记录:
// 版本:
-----------------------------------------------------------------*/
void TestForPointerIncreaseToArray()
{
const int MAX = 3;
int var[MAX] = {10, 100, 200};
int *ptr;
// 指针中的数组地址
ptr = var; //ptr指向了数组的开头
for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// 移动到下一个位置
ptr++;
}
}
/*-----------------------------------------------------------------
// 输入:
// 输出:
// 功能描述:指针的比较,可以通过比较运算符进行地址大小的比较
// 作者:MickelZhang
// 日期:2020/12/16
// 修改人:
// 记录:
// 修改人:
// 记录:
// 版本:
-----------------------------------------------------------------*/
void TestForPointerCompare()
{
const int MAX = 3;
int var[MAX] = {10, 100, 200};
int *ptr;
// 指针中第一个元素的地址
ptr = var;
int i = 0;
while ( ptr <= &var[MAX - 1] )
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// 指向上一个位置
ptr++;
i++;
}
}
/*-----------------------------------------------------------------
// 输入:
// 输出:
// 功能描述:指针VS数组 :指针和数组并不是完全的互换
// 作者:MickelZhang
// 日期:2020/12/16
// 修改人:
// 记录:
// 修改人:
// 记录:
// 版本:
-----------------------------------------------------------------*/
void TestForPointerVsArray()
{
const int MAX = 3;
int var[MAX] = {10, 100, 200};
int *ptr;
// 指针中的数组地址
ptr = var;
for (int i = 0; i < MAX; i++)
{
cout << "var[" << i << "]的内存地址为 ";
cout << ptr << endl;
cout << "var[" << i << "] 的值为 ";
cout << *ptr << endl;
*var = i; //正确
// var++; // 错误的。把指针运算符 * 应用到 var 上是完全可以的,但修改 var 的值是非法的,这是因为 var 是一个指向数组开头的常量,不能作为左值。
// 由于一个数组名对应一个指针常量,只要不改变数组的值,仍然可以用指针形式的表达式
*(var + 2) = 500; //正确
// 移动到下一个位置
ptr++;
}
}
/*-----------------------------------------------------------------
// 输入:
// 输出:
// 功能描述:指针数组
// 作者:MickelZhang
// 日期:2020/12/16
// 修改人:
// 记录:
// 修改人:
// 记录:
// 版本:
-----------------------------------------------------------------*/
void TestForPointerArray1()
{
const int MAX = 3;
int var[MAX] = {10, 100, 200};
int *ptr[MAX];
// ptr[] 数组中存放的是var数组中每个值的地址
for (int i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; // 赋值为整数的地址
}
// *ptr[1] 代表了 var[1]
for (int i = 0; i < MAX; i++)
{
cout << "Value of var[" << i << "] = ";
cout << *ptr[i] << endl;
}
}
// 一个指向字符的指针数组来存储一个字符串列表
void TestForPointerArray2()
{
const int MAX = 4;
const char *names[MAX] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali",
};
cout <<"*names:"<<*names<<endl;
cout <<"names:"<<names<<endl;
for (int i = 0; i < MAX; i++)
{
cout << "Value of names[" << i << "] = ";
cout << names[i] << endl;
cout << "Value of *names[" << i << "] = ";
cout << *names[i] << endl; //*****没弄明白
}
}
/*-----------------------------------------------------------------
// 输入:
// 输出:
// 功能描述:指向指针的指针 多级指针 指向问题
// 作者:MickelZhang
// 日期:2020/12/16
// 修改人:
// 记录:
// 修改人:
// 记录:
// 版本:
-----------------------------------------------------------------*/
void TestForPointToPointerOfPointer()
{
int var;
int *ptr;
int **pptr;
var = 3000;
// 获取 var 的地址 ptr指向了var,所*ptr等于var
ptr = &var;
// 使用运算符 & 获取 ptr 的地址 *pptr 等于 ptr 然后**pptr 等于 *ptr 等于 var
pptr = &ptr;
// 使用 pptr 获取值
//cout << "var 值为 :" << var << endl;
//cout << "*ptr 值为:" << *ptr << endl;
//cout << "**pptr 值为:" << **pptr << endl;
//cout << "*pptr 值为:" << *pptr << endl;
//cout << "ptr 值为:" << ptr << endl;
}
/*-----------------------------------------------------------------
// 输入:
// 输出:
// 功能描述:传递指针给函数
// 作者:MickelZhang
// 日期:2020/12/16
// 修改人:
// 记录:
// 修改人:
// 记录:
// 版本:
-----------------------------------------------------------------*/
void TestForGetSeconds(unsigned long *par)
{
/*
调用方式
unsigned long sec;
getSeconds( &sec );
// 输出实际值
cout << "Number of seconds :" << sec << endl;
*/
// 获取当前的秒数
*par = time(NULL);
return;
}
/*-----------------------------------------------------------------
// 输入:数组作为参数传递,直接使用数组名做参数即可,因为数组名就代表了指向该数组的指针,第二个参数为数组长度
// 输出:
// 功能描述:传递指针给函数
// 作者:MickelZhang
// 日期:2020/12/16
// 修改人:Seventeen
// 记录:
// 修改人:
// 记录:
// 版本:
-----------------------------------------------------------------*/
double GetAverage(int *arr, int size)
{
/*
调用方式:
// 带有 5 个元素的整型数组
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// 传递一个指向数组的指针作为参数
avg = getAverage( balance, 5 ) ;
// 输出返回值
cout << "Average value is: " << avg << endl;
*/
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = double(sum) / size;
return avg;
}
/*
引用:引用变量是一个别名,也就是说,它是某个已存在变量的另一个名字。
一旦把引用初始化为某个变量,就可以使用该引用名称或变量名称来指向变量。
引用和指针的区别:
不存在空引用。引用必须连接到一块合法的内存。
一旦引用被初始化为一个对象,就不能被指向到另一个对象。指针可以在任何时候指向到另一个对象。
引用必须在创建时被初始化。指针可以在任何时间被初始化。
参考链接:https://blog.csdn.net/weikangc/article/details/49762929 // modified by Seventeen
创建引用:
int i = 17;
int& r = i; //"r 是一个初始化为 i 的整型引用"
double& s = d; //"s 是一个初始化为 d 的 double 型引用"
// 声明简单的变量
int i;
double d;
// 声明引用变量
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
把引用作为参数:参考function.cpp,传引用
把引用作为函数返回值:
通过使用引用来替代指针,会使 C++ 程序更容易阅读和维护。
C++ 函数可以返回一个引用,方式与返回一个指针类似。
当函数返回一个引用时,则返回一个指向返回值的隐式指针。
这样,函数就可以放在赋值语句的左边
*/
/*-----------------------------------------------------------------
// 输入:
// 输出:
// 功能描述:将引用作为函数的返回值,传引用改变了数组中值
// 作者:MickelZhang
// 日期:2020/12/16
// 修改人:
// 记录:
// 修改人:
// 记录:
// 版本:
-----------------------------------------------------------------*/
// 传引用这个函数命名比较难改,暂时不涉及规范问题
double vals[] = { 10.1, 12.6, 33.1, 24.1, 50.0 };
double& setValues(int i)
{
return vals[i]; // 返回第 i 个元素的引用
}
void TestForSetValues()
{
//cout << "改变前的值" << endl;
//for (int i = 0; i < 5; i++)
//{
// cout << "vals[" << i << "] = ";
// cout << vals[i] << endl;
//}
//setValues(1) = 20.23; // 改变第 2 个元素
//setValues(3) = 70.8; // 改变第 4 个元素
//cout << "改变后的值" << endl;
//for (int i = 0; i < 5; i++)
//{
// cout << "vals[" << i << "] = ";
// cout << vals[i] << endl;
//}
}
/*
日期和时间:关于这一栏,暂时不用学习,后面学习下怎样检测程序运行时间的代码
*/
/*-----------------------------------------------------------------
// 输入:
// 输出:
// 功能描述:程序运行时间测试
// 作者:MickelZhang
// 日期:2020/12/23
// 修改人:
// 记录:参考链接:https://www.cnblogs.com/didiaodidiao/p/9194702.html
// https://zhuanlan.zhihu.com/p/54665895
// https://www.cnblogs.com/jerry-fuyi/p/12723287.html
// https://blog.csdn.net/luoweifu/article/details/51470998 vs2015程序效率分析相关
// 修改人:
// 记录:
// 版本:
-----------------------------------------------------------------*/
void TestForTime()
{
clock_t start = clock();
// codes
clock_t end = clock();
double elapsed_secs = static_cast<double>(end - start) / (CLOCKS_PER_SEC);
cout <<elapsed_secs <<"s"<<endl;
}
//void TestForTime2()
//{
// LARGE_INTEGER t1,t2,tc;
// QueryPerformanceFrequency(&tc);
// QueryPerformanceCounter(&t1);
// //codes
// QueryPerformanceCounter(&t2);
// time=(double)(t2.QuadPart-t1.QuadPart)/(double)tc.QuadPart;
// cout<<"time = "<<time<<endl; //输出时间(单位:s)
//}
/*
输入和输出:
C++ 的 I/O 发生在流中,流是字节序列。
如果字节流是从设备(如键盘、磁盘驱动器、网络连接等)流向内存,这叫做输入操作。
如果字节流是从内存流向设备(如显示屏、打印机、磁盘驱动器、网络连接等),这叫做输出操作。
cerr和clog 通过一个具体的例子进行学习
关于日志:学会使用日志框架 log4cplus,log4cpp,spdlog,G3log,Pantheios.....
参考链接:https://www.cnblogs.com/junqiang-217/p/4347432.html
https://thinkerou.com/post/easyloggingpp/
https://gitbook.cn/gitchat/column/5b2c5b29072e851cae4299f3/topic/5b2c633e072e851cae42a1aa
log4cplus配置: https://blog.csdn.net/xiake001/article/details/79899115
https://www.codetd.com/article/2759894
https://blog.csdn.net/shaozhenged/article/details/51866186
*/
|
b0fec3c8e1e496181115c1736994c6a77ec0bdc7 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_repos_function_706_collectd-5.6.2.cpp | a4b168062b78ceb2c66bc59dc650dfd1103cf4da | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | cpp | collectd_repos_function_706_collectd-5.6.2.cpp | static int mic_read_temps(int mic) {
size_t num_therms = STATIC_ARRAY_SIZE(therm_ids);
for (size_t j = 0; j < num_therms; j++) {
U32 status;
U32 temp_buffer;
U32 buffer_size = (U32)sizeof(temp_buffer);
char const *name = therm_names[j];
if (ignorelist_match(temp_ignore, name) != 0)
continue;
status =
MicGetTemperature(mic_handle, therm_ids[j], &temp_buffer, &buffer_size);
if (status != MIC_ACCESS_API_SUCCESS) {
ERROR("mic plugin: Error reading temperature \"%s\": "
"%s",
name, MicGetErrorString(status));
return (1);
}
mic_submit_temp(mic, name, temp_buffer);
}
return (0);
} |
d8445d44d97fa1bfdde9fde259d61293f4588174 | 5c5a1bb9c5e2a4c695f63d156c161c57c6f6fdc8 | /VulkanPractice/Entities.cpp | d4e131b7befdc0cfc98fa562a506a3ea4a03c459 | [] | no_license | nitvic793/Vulkan-Practice | 2ab9c5bca4d4dc64836678b050167c6b344c77d7 | 94856b65e0706e281809088c795d0156b908d231 | refs/heads/master | 2020-05-27T05:28:40.227040 | 2019-07-14T05:53:06 | 2019-07-14T05:53:06 | 188,500,577 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,960 | cpp | Entities.cpp | #include "Entities.h"
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#define GLM_FORCE_LEFT_HANDED
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/euler_angles.hpp>
const glm::vec3 DefaultScale = glm::vec3(1.f, 1.f, 1.f);
const glm::vec3 DefaultRotation = glm::vec3(0.f, 0.f, 0.f);
const glm::vec3 DefaultUp = glm::vec3(0.f, 1.f, 0.f);
glm::mat4 GetWorldMatrix(const Entity& entity, const glm::mat4& world = glm::mat4(1))
{
auto identity = glm::mat4(1);
auto translation = glm::translate(identity, entity.Position);
auto rotation = glm::eulerAngleXYZ(entity.Rotation.x, entity.Rotation.y, entity.Rotation.z);
auto scale = glm::scale(identity, entity.Scale);
auto transform = translation * rotation * scale;
return transform;
}
EntityManager::EntityManager():
currentEntityIndex(0)
{
entities.reserve(MAX_ENTITIES);
worlds.reserve(MAX_ENTITIES);
}
void EntityManager::UpdateWorldMatrices()
{
for (size_t i = 0; i < currentEntityIndex; ++i)
{
worlds[i] = GetWorldMatrix(entities[i], worlds[i]);
}
}
EntityID EntityManager::CreateEntity(const Mesh& mesh, TextureID textureID, glm::vec3 position)
{
EntityID entityID = currentEntityIndex;
entities.push_back({ position, DefaultRotation, DefaultScale, mesh, textureID });
worlds.push_back(GetWorldMatrix(entities[entityID]));
currentEntityIndex++;
return entityID;
}
void EntityManager::Move(EntityID id, const glm::vec3& offset)
{
entities[id].Position += offset;
}
void EntityManager::SetPosition(const EntityID& id, const glm::vec3& position)
{
entities[id].Position = position;
}
void EntityManager::SetRotation(const EntityID& id, const glm::vec3& rotation)
{
entities[id].Rotation = rotation;
}
const std::vector<glm::mat4>& EntityManager::GetWorldMatrices()
{
return worlds;
}
const std::vector<Entity>& EntityManager::GetEntities()
{
return entities;
}
const glm::vec3& EntityManager::GetPosition(EntityID id)
{
return entities[id].Position;
}
|
35d6f197c3c569adfc75a9b55963dbb33c4cfe83 | cf2c25e93ddbda5f50190b4f2054bac40e81489d | /src/isf_default_imengine.h | 763380ee946254d7f7d035b4a2169b2c47cdba7a | [
"Apache-2.0"
] | permissive | tizenorg/framework.uifw.ise-engine-default | f987dea612f363844bda4356c2456a7d545e99a9 | 59a99fa0d39a20f7f4fa07517ab3ca1da1b1aa7e | refs/heads/master | 2016-09-12T22:08:03.635586 | 2012-08-21T10:00:21 | 2012-08-21T10:00:21 | 56,114,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,095 | h | isf_default_imengine.h | /*
* ise-engine-default
*
* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: Li zhang <li2012.zhang@samsung.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __ISF_DEFAULT_IMENGINE_H__
#define __ISF_DEFAULT_IMENGINE_H__
using namespace scim;
static const int DEFAULT_CMD_KEYPAD = 0x10;
static const int DEFAULT_CMD_LANGUAGE = 0x20;
static const int DEFAULT_CMD_SHIFTMODE = 0x30;
static const int DEFAULT_CMD_STATE = 0x40;
static const int DEFAULT_CMD_INPUTMODE = 0x50;
static const int DEFAULT_CMD_COMPLETION = 0x60;
static const int DEFAULT_CMD_SINGLECOMMIT = 0x70;
typedef enum {
Shift_None,
Shift_Click,
Shift_Click_Lock,
} Mode_Shift;
class DefaultFactory:public IMEngineFactoryBase {
String m_uuid;
String m_name;
String m_lang;
ConfigPointer m_config;
Connection m_reload_signal_connection;
friend void *load_resource_thread_func(void *args);
public:
DefaultFactory(const ConfigPointer & config);
virtual ~DefaultFactory();
/**
* @brief Load resource for ISE.
* @return void.
*/
virtual void load_resource();
/**
* @brief Get the name of this input method engine.
*
* This name should be a localized string.
*
* @return A WideString containing the name.
*/
virtual WideString get_name() const;
/**
* @brief Get the authors information of this input method engine.
*
* This string should be a localized string.
*
* @return A WideString containing a list of the authors' name.
*/
virtual WideString get_authors() const;
/**
* @brief Get the credits information of this input method engine.
*
* This string should be a localized string.
*
* @return A WideString containing the credits information.
*/
virtual WideString get_credits() const;
/**
* @brief Get the help information of this input method engine.
*
* This string should be a localized string.
*
* @return A WideString containing the help information.
*/
virtual WideString get_help() const;
/**
* @brief Get the UUID of this input method engine.
*
* Each input method engine has an unique UUID to
* distinguish itself from other engines.
*
* You may use uuidgen command shipped with e2fsprogs package to generate this UUID.
*
* @return A String containing an unique UUID.
*/
virtual String get_uuid() const;
/**
* @brief Get the icon file path of this input method engine.
*
* @return A String containing the icon file path on the local filesystem.
*/
virtual String get_icon_file() const;
/**
* @brief Create a new IMEngineInstance object.
*
* This method creates a new scim::IMEngineInstanceBase object with the given encoding and id.
*
* @param encoding - the encoding supported by the client.
* @param id - the instance id, should be unique.
* @return A smart pointer points to this new IMEngineInstance object.
*/
virtual IMEngineInstancePointer create_instance(const String & encoding,
int id = -1);
private:
void reload_config(const ConfigPointer & config);
};
class DefaultInstance:public IMEngineInstanceBase {
CommonLookupTable m_lookup_table;
int m_lookup_table_def_page_size;
Mode_Shift m_shift_pressed;
bool m_caps_lock;
static unsigned int m_prevkeyval;
static int m_counter;
unsigned int m_lang;
unsigned int m_precharval;
WideString m_preedit;
public:
DefaultInstance(DefaultFactory * factory,
const String & encoding, int id = -1);
virtual ~DefaultInstance();
/**
* @brief Process a key event.
*
* @param key - the key event to be processed.
* @return true if the event is processed, otherwise the event
* is not processed and should be forward to client application.
*/
virtual bool process_key_event(const KeyEvent & key);
/**
* @brief Move the preedit caret in the preedit string.
*
* @param pos - the new position that user requested.
*/
virtual void move_preedit_caret(unsigned int pos);
/**
* @brief Select a candidate in current lookup table.
*
* When user click a candidate directly,
* this method will be invoked by FrontEnd.
*
* @param index - the index in current page of the selected candidate.
*/
virtual void select_candidate(unsigned int item);
/**
* @brief Update the page size of current lookup table.
*
* In the next time, the lookup table should page down by
* this size.
*
* @param page_size - the new size of current page.
*/
virtual void update_lookup_table_page_size(unsigned int page_size);
/**
* @brief Flip the lookup table to the previous page.
*
* The method will be invoked by FrontEnd when user click
* the lookup table page up button.
*/
virtual void lookup_table_page_up();
/**
* @brief Flip the lookup table to the next page.
*
* The method will be invoked by FrontEnd when user click
* the lookup table page down button.
*/
virtual void lookup_table_page_down();
/**
* @brief Reset this engine instance.
*
* All status of this engine instance should be reset,
* including the working encoding.
*/
virtual void reset();
/**
* @brief Flush this engine instance.
*
* It will hide preedit string, invoke select_canidate function,
* clear xt9 engine, and hide lookup table
*/
virtual void flush();
/**
* @brief Focus in this engine instance.
*/
virtual void focus_in();
/**
* @brief Focus out this engine instance.
*/
virtual void focus_out();
/**
* @brief Trigger a property.
*
* This function should do some action according
* to the triggered property.
* For example toggle the input mode, etc.
*
* @param property the key of the triggered property.
*/
virtual void trigger_property(const String & property);
/**
* @brief Process the events sent from a Client Helper process.
*
* @param helper_uuid The UUID of the Helper process which sent the events.
* @param trans The transaction which contains the events.
*/
virtual void process_helper_event(const String & helper_uuid,
const Transaction & trans);
/**
* @brief invoke by setting.
*/
virtual void reset_option ();
private:
/**
* @brief Process a key release event.
*
* @param key - the key event to be processed.
*/
bool _process_keyrelease(const KeyEvent & key_raw);
/**
* @brief Process a key press event.
*
* @param key - the key event to be processed.
*/
bool _process_keypress(const KeyEvent & key);
/**
* @brief keyboard process
*
* transfer key index to qwerty char set
*/
bool keypad_process_qwerty(KeyEvent & key);
bool special_key_filter(KeyEvent & key);
};
#endif
|
ba932e03e48171382860584f295f35d89c919538 | d74fc793835b2523efdda89744e4fcf3d260e78f | /sw/stride/include/fQ.hpp | 1349b5b68d650062f3946bf58a84b3da9259ed66 | [] | no_license | pouya-haghi/Coyote | c0db500603b71441051e1ef010f83424d036233f | aab360e725c01f8fe283bfcc51a188a8bab7e578 | refs/heads/master | 2023-08-23T18:58:56.823434 | 2021-10-15T17:37:51 | 2021-10-15T17:37:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | hpp | fQ.hpp | #pragma once
#include <cstdint>
#include <string>
#include <cstring>
namespace fpga {
#define MSG_LEN 82
class fQ {
public:
// Queue
uint32_t qpn;
uint32_t psn;
uint32_t rkey;
// Buffer
uint64_t vaddr;
uint32_t size;
// Node
uint32_t region;
// Global ID
char gid[33];
//
fQ() { memset(gid, 0, 33); }
std::string encode();
void decode (char *buf, size_t len);
uint32_t gidToUint(int idx);
void uintToGid(int idx, uint32_t ip_addr);
void print(const char *name);
static uint32_t getLength() { return MSG_LEN; }
};
struct fQPair {
fQ local;
fQ remote;
};
} /* namespace fpga */ |
22ad6750543c7f8d2777a1d8576c26620ac1eca2 | e648832af9954d322b2128afce0bb928841d9c7b | /Lyziari/Pole.h | 9f0c48da99beea74b2a7871f338d85f801373c8b | [] | no_license | flpmko/INF3-skuska-14-1-2021-8-00 | 1d822559717c5009efd67afa23555ae7aed20612 | 6bd4617b2f631df04a04eeeb284cd57e20b61d5e | refs/heads/main | 2023-02-18T02:00:14.834117 | 2021-01-18T19:21:29 | 2021-01-18T19:21:29 | 330,745,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 240 | h | Pole.h | #pragma once
class Pole
{
private:
unsigned aPocet = 0;
int* aPole = nullptr;
public:
Pole(unsigned pocet = 0) : aPocet(pocet), aPole(aPocet != 0 ? new int[aPocet] : nullptr) {}
void pripocitajKonstatnuHodnotu(int cislo);
~Pole();
};
|
6c97a3eed7f60cc8bffb4c632dae0a648ce3dece | 69fe376f63cf4347bbda41d69c2d2964e53188d5 | /FlooringManagerGUI/CustomerPickList.cpp | a473cfad3444087889d3d6fbf3a663f313b57ac6 | [
"Apache-2.0"
] | permissive | radtek/IMClassic | d71875ecb7fcff65383fe56c8512d060ca09c099 | 419721dacda467f796842c1a43a3bb90467f82fc | refs/heads/master | 2020-05-29T14:05:56.423961 | 2018-01-06T14:43:17 | 2018-01-06T14:43:17 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,870 | cpp | CustomerPickList.cpp | /*----------------------------------------------------------------------
Copyright © 2001-2010 JRS Technology, Inc.
-----------------------------------------------------------------------*/
// CustomerPickList.cpp: implementation of the CCustomerPickList class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Flooring.h"
#include "CustomerPickList.h"
#include "SetCustomer.h"
#include "SetOrders.h"
#include "DlgMergeCustomers.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CCustomerPickList::CCustomerPickList()
{
HighlightCurrentRow();
}
CCustomerPickList::~CCustomerPickList()
{
}
void CCustomerPickList::SetCustomerSet(CSetCustomer *pSet)
{
m_pSet = pSet ;
}
void CCustomerPickList::OnSetup()
{
CCFGrid::OnSetup() ;
InitDefaultFont();
AddColumn(" ID ", ID);
AddColumn("Last Name ", LAST_NAME);
AddColumn("First Name", FIRST_NAME);
AddColumn("Address ", ADDRESS);
AddColumn("City ", CITY);
AddColumn("State", STATE);
AddColumn("Zip ", ZIP);
InitColumnHeadings();
EnableMenu(TRUE) ;
SetMultiSelectMode(TRUE);
}
void CCustomerPickList::Update()
{
CWaitCursor cWait ;
EnableUpdate(FALSE);
while (GetNumberRows())
{
DeleteRow(0) ;
}
int iRow = 0;
try
{
m_pSet->MoveFirst() ;
//Add the Row Heading to the grid
while (!m_pSet->IsEOF() && (iRow < 1000))
{
// InsertRow(iRow) ;
AppendRow() ;
iRow = GetNumberRows() - 1 ;
CString strHeading ;
strHeading.Format("%d", m_pSet->m_CustomerID);
QuickSetText(ID, iRow, strHeading);
QuickSetText(LAST_NAME, iRow, m_pSet->m_LastName) ;
QuickSetText(FIRST_NAME, iRow, m_pSet->m_FirstName) ;
QuickSetText(ADDRESS, iRow, m_pSet->m_Address) ;
QuickSetText(CITY, iRow, m_pSet->m_City) ;
QuickSetText(STATE, iRow, m_pSet->m_State) ;
QuickSetText(ZIP, iRow, m_pSet->m_ZipCode) ;
m_pSet->MoveNext() ;
iRow++ ;
}
}
catch(CDBException *pE)
{
pE->Delete() ;
}
EnableUpdate(TRUE);
RedrawAll() ;
}
void CCustomerPickList::OnSH_DClicked(int col,long row, RECT * /* rect */, POINT * /* point */, BOOL /* processed */)
{
SelectCustomer(col, row) ;
}
void CCustomerPickList::OnDClicked(int col,long row, RECT * /* rect */, POINT * /* point */, BOOL /* processed */)
{
SelectCustomer(col, row) ;
}
void CCustomerPickList::OnCharDown(UINT *vcKey, BOOL /* processed */)
{
if ((*vcKey == VK_SPACE) || (*vcKey == VK_RETURN))
{
int col = this->GetCurrentCol() ;
long row = this->GetCurrentRow() ;
SelectCustomer(col, row) ;
}
}
void CCustomerPickList::SelectCustomer(int /* col */, long row)
{
if ((row < this->GetNumberRows()) && (row >= 0))
{
m_pSet->m_strFilter.Format("[CustomerID] = '%d'", int (QuickGetNumber(-1, row))) ;
m_pSet->Requery() ;
::PostMessage((this->GetParent())->m_hWnd, wm_CUSTOMER_SELECT, 0, row) ;
}
}
int CCustomerPickList::OnMenuStart(int /* col */, long row, int section)
{
if (section == UG_GRID)
{
//* Empty the Menu!!
EmptyMenu();
if ((row >= 0) && (row < GetNumberRows()))
{
bool bGrayed = false;
int iNumSelected = GetSelectedCustomers();
AddMenuItem(2000, "Delete", bGrayed) ;
if (iNumSelected == 2)
{
AddMenuItem(2001, "Merge Selected");
}
}
}
return TRUE ;
}
void CCustomerPickList::OnMenuCommand(int col, long row, int section, int item)
{
UNREFERENCED_PARAMETER(col);
UNREFERENCED_PARAMETER(row);
if (section == UG_GRID)
{
if (item == 2000)
{
CString strMessage;
int iNumSelected = m_aiSelectedCustIDs.GetCount();
if ( iNumSelected > 1)
{
strMessage = "You are about to delete the selected customers from the data base. Is this really what you want?";
}
else
{
strMessage = "You are about to delete the customer from the data base. Is this really what you want?";
}
if (MessageBox(strMessage, "Deleting", MB_YESNO) == IDYES)
{
try
{
CString strOrdersFilter = "";
CString strTemp;
for (int iIndex = 0; iIndex < iNumSelected; iIndex++)
{
if (strOrdersFilter.GetLength() > 0)
{
strOrdersFilter += " OR ";
}
strTemp.Format("[CustomerID] = %d", m_aiSelectedCustIDs.GetAt(iIndex));
strOrdersFilter += strTemp;
}
CString strOldFilter = m_pSet->m_strFilter ;
CSetOrders setOrders(&g_dbFlooring);
setOrders.m_strFilter = strOrdersFilter ;
setOrders.Open();
if (!setOrders.IsEOF())
{
if (iNumSelected > 1)
{
MessageBox("At least one of the selected customers is referenced by one or more P.O.s.\nPlease transfer the P.O.s of each selected customer to another customer before trying to delete.", "Error");
}
else
{
MessageBox("This customer is referenced by one or more P.O.s.\nPlease transfer the P.O.s to another customer before trying to delete.", "Error");
}
}
else
{
m_pSet->m_strFilter = strOrdersFilter ;
m_pSet->Requery() ;
m_pSet->Delete() ;
m_pSet->m_strFilter = strOldFilter ;
m_pSet->Requery() ;
Update() ;
}
setOrders.Close();
}
catch(CDBException* e)
{
CString strMessage;
strMessage.Format("There was an error while trying to delete customer(s).\nThe record(s) may or may not have been deleted, therefore please notify an administrator with the following information.\n\nError: %s", e->m_strError);
MessageBox(strMessage, "Error");
}
}
}
else if (item == 2001)
{
MergeCustomers();
m_pSet->Requery() ;
Update() ;
}
}
}
int CCustomerPickList::GetSelectedCustomers()
{
m_aiSelectedCustIDs.RemoveAll();
int iCol ;
long lRow ;
long lLastRow = -1 ;
EnumFirstSelected(&iCol, &lRow);
do
{
if (lRow != lLastRow)
{
m_aiSelectedCustIDs.Add(int(QuickGetNumber(-1, lRow)));
}
lLastRow = lRow ;
} while (EnumNextSelected(&iCol, &lRow) == UG_SUCCESS) ;
return m_aiSelectedCustIDs.GetCount();
}
void CCustomerPickList::MergeCustomers()
{
CDlgMergeCustomers dlg;
if ( dlg.SetCustomerIDs(m_aiSelectedCustIDs.GetAt(0), m_aiSelectedCustIDs.GetAt(1)))
{
dlg.DoModal();
}
}
bool CCustomerPickList::IsRowDirty(long lRow)
{
UNREFERENCED_PARAMETER(lRow);
return false;
}
bool CCustomerPickList::IsColumnDirty(int iCol, long lRow)
{
UNREFERENCED_PARAMETER(lRow);
UNREFERENCED_PARAMETER(iCol);
return false;
} |
2689b2b46f86b4d0d3b791a34c939e1135f6d433 | f3fef60d8da877634b1c6187c3ed973b00328e41 | /base/dof/Field.hpp | ccfbfda16f360505c3e0dec2d8c9870ae2810cb0 | [] | no_license | thrueberg/inSilico | f656c7fadd0eb5b59b1bb46d906aa613cde6f988 | be4d4e016535f259bc9c2973a05d8417bd0431dd | refs/heads/master | 2016-09-05T16:55:51.505462 | 2015-02-04T14:06:53 | 2015-02-04T14:06:53 | 9,344,003 | 0 | 1 | null | 2015-02-04T14:06:53 | 2013-04-10T10:49:39 | C++ | UTF-8 | C++ | false | false | 2,426 | hpp | Field.hpp | //------------------------------------------------------------------------------
// <preamble>
// </preamble>
//------------------------------------------------------------------------------
//! @file dof/Field.hpp
//! @author Thomas Rueberg
//! @date 2012
#ifndef base_dof_field_hpp
#define base_dof_field_hpp
//------------------------------------------------------------------------------
// std includes
#include <vector>
#include <algorithm>
// boost includes
#include <boost/utility.hpp>
// base/fe includes
#include <base/fe/Field.hpp>
// base/dof includes
#include <base/dof/Element.hpp>
//------------------------------------------------------------------------------
namespace base{
namespace dof{
template<typename ELEMENT>
class Field;
}
}
//------------------------------------------------------------------------------
/** Representation for FE solution field.
* \tparam ELEMENT Type of element representing the DoF interpolation
*/
template<typename ELEMENT>
class base::dof::Field
: public base::fe::Field<ELEMENT,typename ELEMENT::DegreeOfFreedom>
{
public:
typedef ELEMENT Element;
//! DoF type defined in basis
typedef typename Element::DegreeOfFreedom DegreeOfFreedom;
//! Basis type as container
typedef typename base::fe::Field<Element,DegreeOfFreedom> Container;
//! @name Container and iterator definitions
//@{
typedef typename Container::CoeffPtrIter DoFPtrIter;
typedef typename Container::CoeffPtrConstIter DoFPtrConstIter;
//@}
//! @name Iterator access functions
//@{
DoFPtrIter doFsBegin() { return Container::coefficientsBegin(); }
DoFPtrIter doFsEnd() { return Container::coefficientsEnd(); }
DoFPtrConstIter doFsBegin() const { return Container::coefficientsBegin(); }
DoFPtrConstIter doFsEnd() const { return Container::coefficientsEnd(); }
//@}
//! @name Random access
//@{
DegreeOfFreedom* doFPtr( const std::size_t& d) const
{
return Container::coefficientPtr( d );
}
//@}
//! @name Add storage of new dofs and elements
//@{
void addDoFs( const std::size_t numNewDofs )
{
Container::addCoefficients_( numNewDofs );
}
void addElements( const std::size_t numNewElements )
{
Container::addElements_( numNewElements );
}
//@}
};
#endif
|
0d6c2a4624c7caa8096764955c5f488c05d75297 | 546654962a755ad29be937de1ea82a20586a1f2b | /book/not_so_basics/testing/HandTest.cpp | ab8cc058a7ae4c60270c095126aa8536d6538399 | [
"MIT"
] | permissive | luanics/cpp-illustrated | c8424937b0dc39b3d1bd522106b3261b2856dbff | 6049de2119a53d656a63b65d9441e680355ef196 | refs/heads/master | 2020-03-27T09:52:51.366497 | 2019-04-07T22:50:18 | 2019-04-07T22:50:18 | 146,379,846 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,995 | cpp | HandTest.cpp | #include "Hand.hpp"
#include <luanics/testing/Unit.hpp>
namespace luanics::cards::blackjack {
BEGIN_TEST_SET(Hand) // test set: "Hand"
TEST(Add) { // test: "Add"
Hand hand;
EXPECT_EQ(0, hand.cards().size()); // test statement
Card const aceOfSpades{Rank::ACE, Suit::SPADES};
hand.add(aceOfSpades);
ASSERT_EQ(1, hand.cards().size()); // test statement
EXPECT_EQ( // test statement
aceOfSpades,
hand.cards().back()
);
}
TEST(ScoreWithoutAces) { // test: "ScoreWithoutAces"
Hand hand;
EXPECT_EQ(0, hand.score());
hand.add(Card{Rank::EIGHT, Suit::HEARTS});
EXPECT_FALSE(hand.isBust()); // test statement
EXPECT_EQ(8, hand.score()); // test statement
hand.add(Card{Rank::KING, Suit::HEARTS});
EXPECT_FALSE(hand.isBust()); // test statement
EXPECT_EQ(18, hand.score()); // test statement
hand.add(Card{Rank::THREE, Suit::HEARTS});
EXPECT_FALSE(hand.isBust()); // test statement
EXPECT_EQ(21, hand.score()); // test statement
hand.add(Card{Rank::TWO, Suit::HEARTS});
EXPECT_TRUE(hand.isBust()); // test statement
EXPECT_EQ(-1, hand.score()); // test statement
}
TEST(ScoreWithAces) { // test: "ScoreWithAces"
Hand hand;
EXPECT_EQ(0, hand.score());
hand.add(Card{Rank::ACE, Suit::HEARTS});
EXPECT_FALSE(hand.isBust()); // test statement
EXPECT_EQ(11, hand.score()); // test statement
hand.add(Card{Rank::KING, Suit::HEARTS});
EXPECT_FALSE(hand.isBust()); // test statement
EXPECT_EQ(21, hand.score()); // test statement
hand.add(Card{Rank::JACK, Suit::HEARTS});
EXPECT_FALSE(hand.isBust()); // test statement
EXPECT_EQ(21, hand.score()); // test statement
hand.add(Card{Rank::TWO, Suit::HEARTS});
EXPECT_TRUE(hand.isBust()); // test statement
EXPECT_EQ(-1, hand.score()); // test statement
}
END_TEST_SET(Hand)
} // namespace luanics::cards::blackjack
|
13e26ae50a19a59e4a65ab108b4f3dd4f9deb793 | 1a551f967d974b5a8d1fb7fa7a5a7234b9ff5329 | /software/packages/ReconstructionNew/src/TReconInput.cc | 39ed35061e35e7b54e82f349de672572f04872ca | [] | no_license | andrea-celentano/OptoTracker | 9f218bd87d9a97e2ea408f6c73b7a2a46ebf5126 | 0b01cc84d6dd53f514f2693827c9bc892f236645 | refs/heads/master | 2021-01-17T08:28:41.795412 | 2017-03-08T16:30:16 | 2017-03-08T16:30:16 | 30,795,123 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,158 | cc | TReconInput.cc | #include "TReconInput.hh"
#include <stdlib.h> /* atof */
TReconInput::TReconInput(string fname){
if (fname.length()==0) return;
ifstream file(fname.c_str());
string line,key,data;
istringstream parser;
int parId;
for (int ii=0;ii<m_nPars;ii++) m_isParConfigured[ii]=0;
cout<<"TReconInput: init with file "<<fname<<endl;
if (!file){
cout<<"Error in TReconInput, file not found: "<<fname<<endl;
exit(1);
}
while(!file.eof()){
getline (file,line);
if (line.size()==0) continue;
parser.clear();
parser.str(line);
parser>>key;
if (key[0]=='#') continue; //comment
if ((key=="FitObject")||(key=="fitObject")){
parser>>key;
if ((key == "null") || (key=="Null")) m_fitObject=k_null;
else if ((key == "point") || (key=="Point")) m_fitObject=k_point;
else if ((key == "track") || (key=="Track")) m_fitObject=k_track;
else {
cerr<<"Error, FitObject "<<key<<" not recognized. Use point or track"<<endl;
exit(1);
}
}
else if ((key=="FitMode")||(key=="fitMode")){
parser>>key;
if ((key == "charge") || (key=="Charge")) m_fitLikelihoodMode=k_onlyCharge;
else if ((key == "time") || (key=="Time")) m_fitLikelihoodMode=k_onlyTime;
else if ((key == "both") || (key=="Both")) m_fitLikelihoodMode=k_both;
else {
cerr<<"Error, FitMode "<<key<<" not recognized. Use point or track"<<endl;
exit(1);
}
}
else if ((key=="Parameter")||(key=="parameter")){
parser>>data;parId=atoi(data.c_str());
m_isParConfigured[parId]=1;
parser>>data;m_parVal[parId]=atof(data.c_str());
parser>>data;m_isParFixed[parId]=atoi(data.c_str());
}
else if ((key=="LowLimit")||(key=="lowLimit")){
parser>>data;m_parLowLimit[parId]=atof(data.c_str());
m_isParLowLimited[parId]=1;
}
else if ((key=="HighLimit")||(key=="highLimit")){
parser>>data;m_parHighLimit[parId]=atof(data.c_str());
m_isParHighLimited[parId]=1;
}
}
}
void TReconInput::Print() const{
printf("TRecon input %s : \n",this->GetName());
for (int ii=0;ii<m_nPars;ii++){
if(m_isParConfigured[ii]==1){
printf("Parameter %i : value is %f . Fixed : %i \n",ii,m_parVal[ii],m_isParFixed[ii]);
}
}
}
|
2e9e2c96e7a9ebe766c08389688c3867bb5e4c13 | 7d0f76a3b69b1841d74dda54cd34e459c7da5aaf | /src/utils/BamTools/src/api/internal/io/RollingBuffer_p.h | 55550c04390c85517409a2dcf9659f1f89ea0372 | [
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | arq5x/lumpy-sv | aa313dd1dc24c5966a4347445180c9bb0fafc24a | f24085f5d7865579e390add664ebbd9383fa0536 | refs/heads/master | 2022-06-23T14:04:51.403033 | 2022-06-07T21:10:43 | 2022-06-07T21:10:43 | 6,121,988 | 285 | 127 | MIT | 2022-06-07T21:10:44 | 2012-10-08T09:09:26 | C | UTF-8 | C++ | false | false | 3,173 | h | RollingBuffer_p.h | // ***************************************************************************
// RollingBuffer_p.h (c) 2011 Derek Barnett
// Marth Lab, Department of Biology, Boston College
// ---------------------------------------------------------------------------
// Last modified: 7 December 2011 (DB)
// ---------------------------------------------------------------------------
// Provides a dynamic I/O FIFO byte queue, which removes bytes as they are
// read from the front of the buffer and grows to accept bytes being written
// to buffer end.
//
// implementation note: basically a 'smart' wrapper around 1..* ByteArrays
// ***************************************************************************
#ifndef ROLLINGBUFFER_P_H
#define ROLLINGBUFFER_P_H
// -------------
// W A R N I N G
// -------------
//
// This file is not part of the BamTools API. It exists purely as an
// implementation detail. This header file may change from version to version
// without notice, or even be removed.
//
// We mean it.
#include "api/api_global.h"
#include "api/internal/io/ByteArray_p.h"
#include <deque>
#include <string>
namespace BamTools {
namespace Internal {
class RollingBuffer {
// ctors & dtor
public:
RollingBuffer(size_t growth);
~RollingBuffer(void);
// RollingBuffer interface
public:
// returns current buffer size
size_t BlockSize(void) const;
// checks buffer for new line
bool CanReadLine(void) const;
// frees @n bytes from end of buffer
void Chop(size_t n);
// clears entire buffer structure
void Clear(void);
// frees @n bytes from front of buffer
void Free(size_t n);
// checks buffer for @c
size_t IndexOf(char c) const;
// returns whether buffer contains data
bool IsEmpty(void) const;
// reads up to @maxLen bytes into @dest
// returns exactly how many bytes were read from buffer
size_t Read(char* dest, size_t max);
// reads until newline (or up to @maxLen bytes)
// returns exactly how many bytes were read from buffer
size_t ReadLine(char* dest, size_t max);
// returns a C-fxn compatible char* to byte data
const char* ReadPointer(void) const;
// ensures that buffer contains space for @n incoming bytes, returns write-able char*
char* Reserve(size_t n);
// returns current number of bytes stored in buffer
size_t Size(void) const;
// reserves space for @n bytes, then appends contents of @src to buffer
void Write(const char* src, size_t n);
// data members
private:
size_t m_head; // index into current data (next char)
size_t m_tail; // index into last data position
size_t m_tailBufferIndex; // m_data::size() - 1
size_t m_totalBufferSize; // total buffer size
size_t m_bufferGrowth; // new buffers are typically initialized with this size
std::deque<ByteArray> m_data; // basic 'buffer of buffers'
};
} // namespace Internal
} // namespace BamTools
#endif // ROLLINGBUFFER_P_H
|
f5b2ce4e28806614645cac8c08da9268fe648252 | b3d49f610f0ce88bda70cd82db289e15f04bffe1 | /agent/src/message/MatrixC/MatrixCLib/message/AddGroup.cpp | 30390baf004902161daeb6e3cb133d102bd1984e | [] | no_license | bellmit/jigsaw-cms | 1c394dbe31eb79de5e27e7c023a15088b124d8f0 | e303222d4558432dea4c64e8be5be24a769c6958 | refs/heads/master | 2022-01-20T06:00:47.745942 | 2017-10-12T15:53:05 | 2017-10-12T15:53:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,262 | cpp | AddGroup.cpp | ///////////////////////////////
// Message definition file
// Generated by lyvc Message
///////////////////////////////
#include "stdafx.h"
#include "AddGroup.h"
string LyvcMessage::AddGroup::toXML()
{
const int BUFFERSIZE=64;
char buffer[BUFFERSIZE];
string xml;
xml = xml + "<lyvcmessage>";
xml = xml + "<id>";
_snprintf(buffer, BUFFERSIZE, "%I32d", id);
xml = xml + buffer;
xml = xml + "</id>";
xml = xml + "<_senderid>";
_snprintf(buffer, BUFFERSIZE, "%I64d", this->_senderId);
xml = xml + buffer;
xml = xml + "</_senderid>";
xml = xml + "<_conferenceid>";
_snprintf(buffer, BUFFERSIZE, "%I64d", this->_conferenceId);
xml = xml + buffer;
xml = xml + "</_conferenceid>";
xml = xml + "<isCommon>";
_snprintf(buffer, BUFFERSIZE, "%d", this->isCommon);
xml = xml + buffer;
xml = xml + "</isCommon>";
xml = xml + "<groupId>";
_snprintf(buffer, BUFFERSIZE, "%I64d", this->groupId);
xml = xml + buffer;
xml = xml + "</groupId>";
xml = xml + "<parentGroupId>";
_snprintf(buffer, BUFFERSIZE, "%I64d", this->parentGroupId);
xml = xml + buffer;
xml = xml + "</parentGroupId>";
xml = xml + "<name>";
xml = xml + BaseMessage::encodeHtmlEscape(this->name);
xml = xml + "</name>";
xml = xml + "</lyvcmessage>";
return xml;
}
bool LyvcMessage::AddGroup::fromXML(string& xmlString)
{
string tagContent;
tagContent = BaseMessage::getStringBetweenTag(xmlString, "_senderid");
if(tagContent == ""){
return false;
}
this->_senderId = _atoi64(tagContent.c_str());
tagContent = BaseMessage::getStringBetweenTag(xmlString, "_conferenceid");
if(tagContent == ""){
return false;
}
this->_conferenceId = _atoi64(tagContent.c_str());
tagContent = BaseMessage::getStringBetweenTag(xmlString, "isCommon");
if(tagContent == ""){
return false;
}
this->isCommon = atoi(tagContent.c_str());
tagContent = BaseMessage::getStringBetweenTag(xmlString, "groupId");
if(tagContent == ""){
return false;
}
this->groupId = _atoi64(tagContent.c_str());
tagContent = BaseMessage::getStringBetweenTag(xmlString, "parentGroupId");
if(tagContent == ""){
return false;
}
this->parentGroupId = _atoi64(tagContent.c_str());
this->name = BaseMessage::decodeHtmlEscape(BaseMessage::getStringBetweenTag(xmlString, "name"));
return true;
}
|
d8f166bee6e7b18c9c26214feaa3ce836f092923 | 9e40149d43bd2b2c9d32fc15e4500e9a387b7154 | /largest.cpp | 710e97ca2f57ed6a4a8eea3b0a28ff3a6ce7489d | [] | no_license | alokahuja82/Cpp_Codes | 89d76d70348f65e696e3e7311dbbb02105976dc9 | aedef2ea9632def1da35a355b6613517211b6311 | refs/heads/main | 2023-08-11T09:50:46.877816 | 2021-10-05T18:48:15 | 2021-10-05T18:48:15 | 413,940,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | cpp | largest.cpp | #include<iostream>
using namespace std;
int main(){
int a,b,c;
cout<<"Enter three numbers:"<<endl;
cin>>a>>b>>c;
if(a>b){
if (a>c)
cout<<a<<" is largest"<<endl;
}else if (b>c){
if(b>a)
cout<<b<<" is the largest"<<endl;
}else
cout<<c << " is the largest"<<endl;
return 0;
}
|
38a0161bf8c7a089db8f1700ce3156f88d07575d | 230d9b4eca78c90aeed314a78242c684d9639970 | /binarytree_main.cpp | dbe9d7b04020aaabe1cbb14f93b8fe187ec70d87 | [] | no_license | revion/binary-tree | 98f59c5581fda841636b5486416ef9c47f4a4991 | fbf560d5e3cd3ffe91761c98e0b08e0adb35a56b | refs/heads/master | 2021-01-22T19:44:57.347074 | 2015-06-17T16:48:07 | 2015-06-17T16:48:07 | 37,142,400 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 106 | cpp | binarytree_main.cpp | #include "node_1.h"
#include "tree_1.h"
main(){
Tree data1("data.txt");
data1.root.traverse(root);
}
|
2e4dedeb17fa1517e2af98fe1dea1f40fbd8580f | 879e3fb8737b9f50630f51e4a34e24cc41bf0cfa | /CodeSignal/growingPlant.cpp | 601f10b566f51f28f274b80881e894ebc432d46e | [] | no_license | haaaziq/problemSolving | 2f1ceb38b409e6a617f1477bca898a150e15a193 | 49d480aafae4197e08cf51c689a51a583e18a668 | refs/heads/master | 2023-07-02T23:56:00.028435 | 2021-07-28T18:44:29 | 2021-07-28T18:44:29 | 352,758,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 383 | cpp | growingPlant.cpp | #include<bits/stdc++.h>
using namespace std;
int growingPlant(int upSpeed, int downSpeed, int desiredHeight) {
int days{0};
int height{0};
while(height<desiredHeight){
days++;
height+=upSpeed;
if(height>=desiredHeight) return days;
height-=downSpeed;
}
return days;
}
int main(){
cout << growingPlant(6,5,10);
return 0;
} |
70596105a32cb59bfee960ed10cd9c38facdbba0 | 78a223b58892f484c71ff127b28ca01289ecbe99 | /hobby_game/src/keyboard.h | e00c083216c90b8f34c5f95656d161ace037f009 | [] | no_license | brucelevis/hobby_game | d3d099278bff871394ba1f4cf5c5b953494c3dcf | 07e74114a6829d096ff50474bdb4369da6a05e0c | refs/heads/master | 2021-01-11T08:34:12.721056 | 2016-09-10T22:24:32 | 2016-09-10T22:24:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,110 | h | keyboard.h | #pragma once
#include "keycode.h"
namespace hg
{
class Game;
class Keyboard
{
public:
Keyboard();
/*
Returns true if the key with this code is being held down.
*/
bool is_key_down(Keycode code) const;
/*
Returns true if the key with this code was immidiately pressed this frame.
*/
bool was_key_pressed(Keycode code) const;
/*
Returns true if the key with this code was immidiately released (unpressed) this frame.
*/
bool was_key_released(Keycode code) const;
protected:
friend class Game;
/*
Called by the Game class when a key is pressed/released (changes state; true = pressed, false = released).
*/
void on_key_change(Keycode code, bool state);
void clear_key_diffs();
private:
bool m_keys[(int)Keycode::num_codes];
bool m_prev_keys[(int)Keycode::num_codes];
static const int MAX_KEYS_DIFF = 512;
Keycode m_keys_diff[MAX_KEYS_DIFF];
int m_num_keys_diff;
};
} |
57d4e1b85398df5b779fdebc3d74ca3575f009b8 | 097a4d9ea1e580b2f4cfeeae5702c7e6bd60cad1 | /source/Client.cpp | 31eba274b6783dd161b38e17e7f32dff026205c1 | [] | no_license | mnassabain/riks-game-server | b0fd22270ca0f42154fb4fcddb3385645dba9f8d | b44872a1550fd8a889ec2d2db3b5ded220d83ffe | refs/heads/master | 2023-02-15T08:07:03.195685 | 2021-01-12T00:27:50 | 2021-01-12T00:27:50 | 328,826,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | cpp | Client.cpp | #include "../header/Client.h"
const int Client::SERVER_HUB = -1;
Client::Client(string name, Connection connection)
{
this->name = name;
this->connection = connection;
this->gameID = SERVER_HUB;
}
Connection Client::getConnection()
{
return this->connection;
}
bool Client::inLobby()
{
return gameID != -1;
}
string Client::getName()
{
return this->name;
}
int Client::getGameID()
{
return this->gameID;
}
void Client::setGameID(int gameID)
{
this->gameID = gameID;
} |
c4acd406b9b9d74906152dc854ece7bfb6f3484d | 1749af9b523b7d9518695ec077840c62ee3c3194 | /Assignment_3/A3_StringReverseUsingRecursion.cpp | e408eec27aa67ad9abe618c860e899086160863a | [] | no_license | Stephenwolf008/OOP | c09cb659d839b77f7847fe80a0c1221eb12825ca | 4297fe159810141b90911fe677b12cfd403a9873 | refs/heads/master | 2022-12-31T22:34:06.598920 | 2020-10-22T16:06:42 | 2020-10-22T16:06:42 | 282,262,517 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 351 | cpp | A3_StringReverseUsingRecursion.cpp | #include<iostream>
#include<stdlib.h>
using namespace std;
void stringReverse(string str,int first){
if(first==str.size())
exit;
if(first!=str.size())
cout<<str[str.size()-first-1];
if(first<str.size())
return stringReverse(str,first+1);
}
int main(){string str;
cout<<"Enter String:";
getline(cin,str);
stringReverse(str,0);
return 0;
}
|
2539b4e9468a61b5d176535b5ace2d698aaf3338 | c57897f505edfbd60fa07d7594034442d2d15f8f | /cell.h | a07726aa453f06bb2da27fbf9cf498750729955f | [] | no_license | Zulukas/sudoku | bb31300f52022742d5d68d3d6ed2f72814b04230 | c3a2b8fa82f368243af97c15e09177b24216bad0 | refs/heads/master | 2021-01-10T14:41:44.824908 | 2016-01-20T16:46:11 | 2016-01-20T16:46:11 | 50,044,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | h | cell.h | #pragma once
#include <iostream>
using std::ostream;
#define OOBE "ERROR: Out of bounds; value must be 0-9.";
#define ROE "ERROR: Cell is read-only.";
class Cell
{
public:
Cell();
Cell(int value, bool readOnly) throw (const char*);
void setValue(int value) throw (const char*);
int getValue() const;
bool isReadOnly() const;
bool isEmpty() const;
bool operator == (const int value) const;
bool operator != (const int value) const;
private:
unsigned short value;
bool readOnly;
};
ostream& operator << (ostream& out, const Cell& c);
|
39963a4ec81652e4371ae201348ad7961919ef0a | 62094db12deab9b0709db0e033d64aa61c3b3c8f | /proximity_views.h | 1fdc666ae4aac787aac217b9710aaa3b8b18524f | [
"MIT"
] | permissive | matth036/dsc | 7e97712d1aaa953d4c833630fbe825653569c91a | 728a5d066788ae6e600495c14bb9a8b4f09eaca5 | refs/heads/master | 2020-04-24T04:35:20.436181 | 2015-10-23T20:26:42 | 2015-10-23T20:26:42 | 32,033,998 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,910 | h | proximity_views.h | #ifndef PROXIMITY_VIEWS_H_
#define PROXIMITY_VIEWS_H_
#include <string>
#include <vector>
#include <memory>
#include "character_reciever.h"
#include "alignment_sight_info.h"
#include "AA2DCoordinate.h"
class CharLCD_STM32F;
constexpr uint32_t PROXIMITY_VIEW_DEFAULT_WIDTH = 20; /* The width of the display in characters */
/*
* Takes a pointer to Simple_Altazimuth_Scope
* (Hope to abstact the concept of "Telescope Mount" eventually.)
*
* Displays nearby stars from the Bright Star Catalog.
*/
class Proximate_Stars_View:Character_Reciever {
public:
Proximate_Stars_View(Simple_Altazimuth_Scope *scope);
~Proximate_Stars_View();
void put_char(char);
std::unique_ptr < CharLCD_STM32F > write_first_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_second_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_third_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_fourth_line(std::unique_ptr <
CharLCD_STM32F >);
void dismiss_action();
inline bool is_finished() {
return finished;
}
inline bool prompt_for_magnitude() {
return _prompt_for_magnitude;
}
char get_first_digit();
void clear_prompts();
void set_magnitude_limit( float mag );
void increment_position();
void decrement_position();
void set_size(uint32_t s);
private:
std::unique_ptr < CharLCD_STM32F > write_line_n(std::unique_ptr <
CharLCD_STM32F >, uint32_t n);
void push_pushto_command();
void run_algorithm();
void request_magnitude( char c );
std::vector < uint32_t > stars;
double JD;
float _magnitude_limit = 6.0;
Character_Reciever *saved_cr;
uint32_t size = 99;
uint32_t position = 0;
uint32_t bsc_selection;
int32_t width_;
Simple_Altazimuth_Scope *telescope;
CAA2DCoordinate RA_and_Dec;
CAA2DCoordinate RA_and_Dec_J2000;
char _first_digit;
bool finished;
bool _prompt_for_magnitude = false;
};
class Proximate_Messier_Objects_View:Character_Reciever {
public:
Proximate_Messier_Objects_View(Simple_Altazimuth_Scope *);
~Proximate_Messier_Objects_View();
void put_char(char);
std::unique_ptr < CharLCD_STM32F > write_first_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_second_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_third_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_fourth_line(std::unique_ptr <
CharLCD_STM32F >);
void dismiss_action();
inline bool is_finished() {
return finished;
}
void increment_position();
void decrement_position();
void set_size(uint32_t s);
private:
std::unique_ptr < CharLCD_STM32F > write_line_n(std::unique_ptr <
CharLCD_STM32F >, uint32_t n);
void run_algorithm();
void push_pushto_command();
std::vector < uint32_t > objects;
double JD;
size_t lambda_size;
Character_Reciever *saved_cr;
uint32_t size = 15;
uint32_t position = 0;
uint32_t messier_selection;
int32_t width_;
Simple_Altazimuth_Scope *telescope;
CAA2DCoordinate RA_and_Dec;
bool finished;
};
class Proximate_Navigation_Stars_View:Character_Reciever {
public:
explicit Proximate_Navigation_Stars_View(Simple_Altazimuth_Scope *scope);
~Proximate_Navigation_Stars_View();
void put_char(char);
std::unique_ptr < CharLCD_STM32F > write_first_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_second_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_third_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_fourth_line(std::unique_ptr <
CharLCD_STM32F >);
void dismiss_action();
inline bool is_finished() {
return finished;
}
void increment_position();
void decrement_position();
void set_size(uint32_t s);
private:
std::unique_ptr < CharLCD_STM32F > write_line_n(std::unique_ptr <
CharLCD_STM32F >, uint32_t n);
void run_algorithm();
void push_pushto_command();
std::vector < uint32_t > stars;
double JD;
size_t lambda_size;
Character_Reciever *saved_cr;
uint32_t size = 58;
uint32_t position = 0;
uint32_t navstar_selection;
int32_t width_;
Simple_Altazimuth_Scope *telescope;
CAA2DCoordinate RA_and_Dec;
CAA2DCoordinate RA_and_Dec_J2000;
bool finished;
};
class Proximate_NGC_View:Character_Reciever {
public:
Proximate_NGC_View(Simple_Altazimuth_Scope *scope);
~Proximate_NGC_View();
void put_char(char);
std::unique_ptr < CharLCD_STM32F > write_first_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_second_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_third_line(std::unique_ptr <
CharLCD_STM32F >);
std::unique_ptr < CharLCD_STM32F > write_fourth_line(std::unique_ptr <
CharLCD_STM32F >);
void dismiss_action();
inline bool is_finished() {
return finished;
}
inline bool prompt_for_magnitude() {
return _prompt_for_magnitude;
}
char get_first_digit();
void clear_prompts();
void set_magnitude_limit( float mag );
void increment_position();
void decrement_position();
void set_size(uint32_t s);
private:
std::unique_ptr < CharLCD_STM32F > write_line_n(std::unique_ptr <
CharLCD_STM32F >, uint32_t n);
void push_pushto_command();
void run_algorithm();
void request_magnitude( char c );
std::vector < uint32_t > ngc_objects;
double JD;
float _magnitude_limit = 9.999;
Character_Reciever *saved_cr;
uint32_t size = 99;
uint32_t position = 0;
uint32_t ngc_selection;
int32_t width_;
Simple_Altazimuth_Scope *telescope;
CAA2DCoordinate RA_and_Dec;
char _first_digit;
bool finished;
bool _prompt_for_magnitude = false;
};
#endif // PROXIMITY_VIEWS_H_
|
9f4b327a965275e5a363c2bde37d117c8382821c | 837f6e6d06a50699b829581fd8681c2c9c942de0 | /SPlisHSPlasH/Utilities/GaussQuadrature.h | bb6c13667a202995710cd4b70897f22f5cd9dc98 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | InteractiveComputerGraphics/SPlisHSPlasH | 75cb0428ed00db48b8720a6c9f7aef8f4b3654d2 | 8454e9f454fef20771dfe98d318904da62764b4c | refs/heads/master | 2023-08-25T00:28:23.170422 | 2023-08-21T10:30:34 | 2023-08-21T10:30:34 | 74,058,995 | 1,376 | 305 | MIT | 2023-08-17T14:36:21 | 2016-11-17T19:14:23 | C++ | UTF-8 | C++ | false | false | 389 | h | GaussQuadrature.h | #ifndef __GaussQuadrature_h__
#define __GaussQuadrature_h__
#include <Eigen/Dense>
namespace SPH
{
class GaussQuadrature
{
public:
using Integrand = std::function<double(Eigen::Vector3d const&)>;
using Domain = Eigen::AlignedBox3d;
static double integrate(Integrand integrand, Domain const& domain, unsigned int p);
static void exportSamples(unsigned int p);
};
}
#endif
|
a337da6bed9f3ad1cd25b347a48e0c0fa349d442 | d5299427e1fa0c70eb2b8bd5beb0e6cb3f822357 | /CSE_241_Object_Oriented_Programming/HW7/BigramMap.cpp | 2dad19a3daf633198748e9b74e97824d4ae56e80 | [] | no_license | erdemduman/Homework | 9139a9ab93835a3ded8059c51af67f565a8b5b59 | fb5f90e7da4529042c6267270eae14883fe849c0 | refs/heads/master | 2020-04-27T19:28:15.441706 | 2019-03-13T10:15:07 | 2019-03-13T10:15:50 | 174,619,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,170 | cpp | BigramMap.cpp | #include "BigramMap.h"
//constructor
template <class T>
BigramMap<T>::BigramMap(int dataType){
numGramsVar = 0; //bigram counter
datatype = dataType;
}
/*this function takes filename as parameter and calculates bigrams*/
template <class T>
void BigramMap<T>::readFile(string filename){
fstream fayl;
fayl.open(filename);
T reader;
/*error check of "is there any file named like this?"*/
if(!fayl){
myExcept obj;
throw obj;
}
else{
/*error check of empty file*/
string isFileEmpty;
fayl >> isFileEmpty;
if(isFileEmpty == ""){
myExcept obj;
throw obj;
}
fayl.close();
/*file closed and opened to find bigram number*/
fayl.open(filename);
while(!fayl.eof()){
fayl >> reader;
/*error check of bad data*/
if(fayl.fail()){
myExcept obj;
throw obj;
}
numGramsVar++;
}
}
//if there is just one element in file, that is an error for me
if(numGramsVar == 1){
myExcept obj;
throw obj;
}
fayl.close();
fayl.open(filename);
/*file closed and opened to find all bigrams*/
/*pair is used for key of map*/
T pairFirst,pairSecond;
typename map<pair<T,T>,int>::iterator it; //iterator of our map
fayl >> pairFirst;
while(!fayl.eof()){
int flag = 0; //if the same bigram is found, this turns to 1
fayl >> pairSecond;
/*this for loop searchs weather there is the same bigram*/
for(it = myMap.begin(); it != myMap.end(); it++){
if(it->first.first == pairFirst && it->first.second == pairSecond){
it->second++;
flag = 1;
}
}
/*if not, the bigram that we found is added to the map*/
if (flag == 0){
myMap.insert(pair<pair<T,T>,int>(pair<T,T>(pairFirst,pairSecond),1));
}
pairFirst = pairSecond;
}
numGramsVar--;
fayl.close();
}
/*this function returns the number of bigram*/
template <class T>
int BigramMap<T>::numGrams()const{return numGramsVar;}
/*this function takes 2 parameters and returns how many bigrams are matched with them*/
template <class T>
int BigramMap<T>::numOfGrams(const T firstVar, const T secondVar){
typename map<pair<T,T>,int>::iterator it;
for(it = myMap.begin(); it != myMap.end(); it++){
if(it->first.first == firstVar && it->first.second == secondVar){
return it->second;
}
}
return 0;
}
/*this function returns the most used bigram with pair*/
template <class T>
pair<T,T> BigramMap<T>::maxGrams(){
int max=0;
T firstVar,secondVar;
typename map<pair<T,T>,int>::iterator it;
for(it = myMap.begin(); it != myMap.end(); it++){
if(it->second >= max){
max = it->second;
firstVar = it->first.first;
secondVar = it->first.second;
}
}
return pair<T,T>(firstVar,secondVar);
}
/*this function prints the bigrams and their values*/
template <class T>
void BigramMap<T>::helperFunc(ostream& output){
typename map<pair<T,T>,int>::iterator it;
for(it = myMap.begin(); it != myMap.end(); it++){
output << "First: " << it->first.first << " Second: " << it->first.second << " Number: " << it->second << endl;
}
}
|
25af596b12e1d1f36965ec025b91e3fb4c9e5cab | b1aef802c0561f2a730ac3125c55325d9c480e45 | /src/ripple/overlay/impl/Tuning.h | 7fc6235063bc27ef1453acad613000673be32853 | [] | no_license | sgy-official/sgy | d3f388cefed7cf20513c14a2a333c839aa0d66c6 | 8c5c356c81b24180d8763d3bbc0763f1046871ac | refs/heads/master | 2021-05-19T07:08:54.121998 | 2020-03-31T11:08:16 | 2020-03-31T11:08:16 | 251,577,856 | 6 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 734 | h | Tuning.h |
#ifndef RIPPLE_OVERLAY_TUNING_H_INCLUDED
#define RIPPLE_OVERLAY_TUNING_H_INCLUDED
#include <chrono>
namespace ripple {
namespace Tuning
{
enum
{
readBufferBytes = 4096,
maxInsaneTime = 60,
maxUnknownTime = 300,
saneLedgerLimit = 24,
insaneLedgerLimit = 128,
maxReplyNodes = 8192,
checkSeconds = 32,
timerSeconds = 8,
sendqIntervals = 4,
noPing = 10,
dropSendQueue = 192,
targetSendQueue = 128,
sendQueueLogFreq = 64,
};
std::chrono::milliseconds constexpr peerHighLatency{300};
}
}
#endif
|
b52bf29db6c37e31f4f7d6892d32767ca5df04be | 2159aa5580cfddad12a8bd80a0c96b0c5598777f | /code/012.cpp | 8f677915bca9570da92aea3e842066b0505f285f | [] | no_license | papamoomin/EulerProjectStudy | 081a03caf52d4a624ddd5ccc2e016a6808860667 | eaaebf8ffee860d6ec55ada87375d5004aa0217b | refs/heads/master | 2020-04-29T16:34:24.710401 | 2019-04-01T12:44:23 | 2019-04-01T12:44:23 | 176,265,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | 012.cpp | #include<iostream>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cout.tie(NULL);
int ans = 0, naturalNum = 1;
bool isFinding = 1;
for (; isFinding; ++naturalNum)
{
ans += naturalNum;
for (int i = 1, count = 0; i*i <= ans; ++i)
{
if (ans%i == 0)
++count;
if (count == 250)
{
isFinding = false;
break;
}
}
}
cout << ans;
} |
91a53066659233a060bd1fae2e29c385a48b79ac | def00dee6c6e726230204754c95d426f3ad06945 | /Strings/anagram.cpp | 3c20c66ac350fe942df2211f49dbe29c6183a1e5 | [] | no_license | Gaurav1401/Data-Structures-and-Algorithms | ebeffcf9e3e1bb97f717fb5892f1c509b26bd81f | bbb6045b35fd5241f8018dde87c031b17155b957 | refs/heads/main | 2023-07-14T15:42:55.110218 | 2021-08-28T08:30:17 | 2021-08-28T08:30:17 | 389,517,973 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 988 | cpp | anagram.cpp | // Given two strings a and b consisting of lowercase characters.
// The task is to check whether two given strings are an anagram of each other or not.
// An anagram of a string is another string that contains the same characters,
// only the order of characters can be different. For example, “act” and “tac” are an anagram of each other.
class Solution
{
public:
//Function is to check whether two strings are anagram of each other or not.
bool isAnagram(string a, string b) {
if (a.length() != b.length())
{
return false;
}
int count[26] = { 0 };
for (int i = 0; i < a.length(); i++)
{
count[a[i] - 'a']++;
}
for (int i = 0; i < b.length(); i++)
{
count[b[i] - 'a']--;
}
for (int j = 0; j < 26; j++)
{
if (count[j] > 0)
{
return false;
}
}
return true;
}
}; |
b8a1038fc3a57de802f2bd0c5b68a39b923e48d2 | b070bb3c98af3e963fca192aeae4ab0a7da70c38 | /main.cpp | 8fe4895cdb198c5feea92cd5f8b1c66aa0f7dcb8 | [
"MIT"
] | permissive | PeterZhouSZ/Gen-Adapt-Ref-for-Hexmeshing | 0d6f2932e243d10c3be9440a3ea9e9621821f81e | d5c37082ebafe901d9d08855537199964026919d | refs/heads/main | 2023-08-19T07:51:53.940057 | 2021-09-22T11:00:55 | 2021-09-22T11:00:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,159 | cpp | main.cpp | /*****************************************************************************************
* MIT License *
* *
* Copyright (c) 2021 Luca Pitzalis, Marco Livesu, Gianmarco Cherchi, Enrico Gobbetti *
* and Riccardo Scateni *
* *
* 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. *
* *
* Authors: *
* Luca Pitzalis (luca.pitzalis94@unica.it) *
* http://cg3hci.dmi.unica.it/lab/en/people/pitzalis.luca/ *
* *
* Marco Livesu (marco.livesu@ge.imati.cnr.it) *
* http://pers.ge.imati.cnr.it/livesu/ *
* *
* Gianmarco Cherchi (g.cherchi@unica.it) *
* https://people.unica.it/gianmarcocherchi/ *
* *
* Encirco Gobbetti (gobbetti@crs4.it) *
* https://www.crs4.it/it/peopledetails/8/enrico-gobbetti/ *
* *
* Riccardo Scateni (riccardo@unica.it) *
* https://people.unica.it/riccardoscateni/ *
* *
* ***************************************************************************************/
#include <stdlib.h>
#include <iostream>
#include <regex>
#include "surface_grid_maker.h"
#include "polycube_grid_maker.h"
int main(int argc, char *argv[]){
std::regex regex_sw_balancing("--strong_balancing|--weak_balancing");
std::regex regex_use_octree("--use_octree");
std::regex regex_max_refinement("--max_refinement=[0-9]+");
std::regex regex_mesh_path("--input_mesh_path=.*");
std::regex regex_pc_mesh_path("--input_pc_mesh_path=.*");
std::regex regex_grid_path("--output_grid_path=.*.mesh");
std::regex regex_sanity_check("--sanity_check=(true|false)");
if(argc > 3){
if(std::string(argv[1]) == "--surface"){
std::string mesh_path;
std::string grid_save_path;
uint min_refinement = 0;
uint max_refinement = 8;
bool weak_balancing = true;
bool use_octree = false;
bool perform_sanity_check = true;
bool mesh_found, grid_found;
for(int i=2;i<argc;i++){
std::string argument(argv[i]);
if(std::regex_match(argument, regex_sw_balancing)){
if(argument == "--strong_balancing") weak_balancing = false;
}
else if(std::regex_match(argument, regex_use_octree)) use_octree = true;
else if(std::regex_match(argument, regex_max_refinement)){
max_refinement = std::stoi(argument.erase(0, argument.find("=") + 1));
}
else if(std::regex_match(argument, regex_mesh_path)){
mesh_path = argument.erase(0, argument.find("=") + 1);
mesh_found = true;
}
else if(std::regex_match(argument, regex_grid_path)){
grid_save_path = argument.erase(0, argument.find("=") + 1);
grid_found = true;
}
else if(std::regex_match(argument, regex_sanity_check)){
std::string bool_string = argument.erase(0, argument.find("=") + 1);
perform_sanity_check = bool_string.front() == 't' ? true : false;
}
}
if(!(mesh_found && grid_found)){
std::cerr<<"Required argument --input_mesh_path or --output_grid_path not found"<<std::endl;
return -1;
}
cinolib::Trimesh<> m(mesh_path.c_str());
cinolib::Hexmesh<> grid;
make_grid(m, grid, min_refinement, max_refinement, weak_balancing, use_octree, sdf_split_metric, perform_sanity_check);
grid.save(grid_save_path.c_str());
}
if(std::string(argv[1]) == "--polycube"){
std::string mesh_path;
std::string pc_mesh_path;
std::string grid_save_path;
uint min_refinement = 5;
uint max_refinement = 8;
bool weak_balancing = true;
bool use_octree = false;
bool perform_sanity_check = true;
bool mesh_found, pc_mesh_found, grid_found;
for(int i=2;i<argc;i++){
std::string argument(argv[i]);
if(std::regex_match(argument, regex_sw_balancing)){
if(argument == "--strong_balancing") weak_balancing = false;
}
else if(std::regex_match(argument, regex_use_octree)) use_octree = true;
else if(std::regex_match(argument, regex_max_refinement)){
max_refinement = std::stoi(argument.erase(0, argument.find("=") + 1));
}
else if(std::regex_match(argument, regex_mesh_path)){
mesh_path = argument.erase(0, argument.find("=") + 1);
mesh_found = true;
}
else if(std::regex_match(argument, regex_pc_mesh_path)){
pc_mesh_path = argument.erase(0, argument.find("=") + 1);
pc_mesh_found = true;
}
else if(std::regex_match(argument, regex_grid_path)){
grid_save_path = argument.erase(0, argument.find("=") + 1);
grid_found = true;
}
else if(std::regex_match(argument, regex_sanity_check)){
std::string bool_string = argument.erase(0, argument.find("=") + 1);
perform_sanity_check = bool_string.front() == 't' ? true : false;
}
}
if(!(mesh_found && grid_found && pc_mesh_found)){
std::cerr<<"Required argument --input_mesh_path or --input_pc_mesh_path or --output_grid_path not found"<<std::endl;
return -1;
}
cinolib::Tetmesh<> m(mesh_path.c_str());
cinolib::Tetmesh<> pc_m(pc_mesh_path.c_str());
cinolib::Hexmesh<> grid;
std::vector<std::string> split = split_string(grid_save_path, '/');
std::string externals_path;
if(grid_save_path[0] == '/') externals_path += "/";
for(uint i=0; i<split.size()-1; i++){
externals_path+= split[i]+"/";
}
externals_path += "external_polys.txt";
grid.mesh_data().filename = externals_path;
make_grid(m, pc_m, grid, min_refinement, max_refinement, weak_balancing, use_octree, polycube_distortion_split_metric, perform_sanity_check);
grid.save(grid_save_path.c_str());
}
}
else if(argc == 2 && std::string(argv[1]) == "--help"){
std::cout<<"usage: ./grid_maker (--surface | --polycube) --input_mesh_path=MESH_PATH --output_grid_path=GRID_PATH [Options]"<<std::endl;
std::cout<<"Options:"<<std::endl;
std::cout<<"--input_pc_mesh_path=PATH (required for polycube). Specify the path of the polycube map"<<std::endl;
std::cout<<"--min_refinement=VALUE (optional, default 0[5 for polycube])"<<std::endl;
std::cout<<"--max_refinement=VALUE (optional, default 8)"<<std::endl;
std::cout<<"--use_octree (optional). Use the algorithmic pairing process"<<std::endl;
std::cout<<"--weak_balancing | --strong_balancing (optional, default weak_balancing)"<<std::endl;
std::cout<<"--sanity_check=BOOL (optional, default truie). Test if the final mesh is paired correctly"<<std::endl;
}
else{
std::cerr<<"Wrong number of parameter. Run with --help for more information";
}
return 0;
}
|
2462872b2bae865c996cc532eb8752b6b647b9f7 | 4c25432a6d82aaebd82fd48e927317b15a6bf6ab | /data/dataset_2017/dataset_2017_8_formatted_macrosremoved/vector310/5304486_5760761888505856_vector310.cpp | abd970115f79ee2bc21126c03ef2a9793e5084a1 | [] | no_license | wzj1988tv/code-imitator | dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933 | 07a461d43e5c440931b6519c8a3f62e771da2fc2 | refs/heads/master | 2020-12-09T05:33:21.473300 | 2020-01-09T15:29:24 | 2020-01-09T15:29:24 | 231,937,335 | 1 | 0 | null | 2020-01-05T15:28:38 | 2020-01-05T15:28:37 | null | UTF-8 | C++ | false | false | 1,338 | cpp | 5304486_5760761888505856_vector310.cpp | #include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
char s[30][30];
int n, m;
void work(int x) {
for (int j = 1; j <= m; ++j) {
if (s[x][j] != '?') {
for (int k = j - 1; k >= 1 && s[x][k] == '?'; --k)
s[x][k] = s[x][j];
for (int k = j + 1; k <= m && s[x][k] == '?'; ++k)
s[x][k] = s[x][j];
}
}
}
int main() {
// freopen("input.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
int T;
cin >> T;
for (int cas = 1; cas <= T; ++cas) {
cin >> n >> m;
for (int i = 1; i <= n; ++i)
scanf("%s", s[i] + 1);
int first = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j)
if (s[i][j] != '?')
first = i;
if (first)
break;
}
work(first);
for (int i = first - 1; i >= 1; --i)
for (int j = 1; j <= m; ++j)
s[i][j] = s[i + 1][j];
for (int i = first + 1; i <= n; ++i) {
bool flag = 0;
for (int j = 1; j <= m; ++j)
if (s[i][j] != '?')
flag = 1;
if (flag)
work(i);
else
for (int j = 1; j <= m; ++j)
s[i][j] = s[i - 1][j];
}
printf("Case #%d:\n", cas);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j)
printf("%c", s[i][j]);
printf("\n");
}
}
return 0;
}
|
25c01705cebf132576d9799a1481b14648e5ec8f | e0ad93c6ccbd1aa645bf42af93e23dc8ed8c9b91 | /mt/evaluation/mutex-locking-test.cc | b625ca3b48d276eeed45a7af88971d472c954b55 | [] | no_license | minuta/grail | 2ff524f084f6dde49f7ae62a095efd1d9b39dbdc | 9cd2b51dfc8e68791e7e0cceb2c96b243a9d5cc2 | refs/heads/master | 2020-04-24T21:28:37.089044 | 2019-03-28T08:33:46 | 2019-03-28T08:33:46 | 172,279,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,329 | cc | mutex-locking-test.cc | /*
* test mutex locking :
* this test spawns 1000 threads, whereby integer variable sharedCounter
* will be increased by the thread id number.
*
* critical section, where sharedCounter will be modified is locked by a
* statically initialized mutex (default mutex attributes)
*/
#include <iostream>
#include <pthread.h>
//#include <chrono>
#include <time.h>
const int NUM_OF_THREADS {1000};
const int NUM_OF_LOOPS_IN_THREAD {10};
int sharedCounter = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *threadFunction(void *threadId){
for (int i=1; i<=NUM_OF_LOOPS_IN_THREAD; i++){
auto msg = "------> THREAD #" + std::to_string(long(threadId)) + ": loop " + std::to_string(i) + "\n";
std::cout << msg;
pthread_mutex_lock(&mutex);
sharedCounter = sharedCounter + long(threadId);
pthread_mutex_unlock(&mutex);
}
// std::cout << "------> hello from THREAD #" << long(threadId) << std::endl;
//pthread_mutex_lock(&mutex);
//sharedCounter = sharedCounter + long(threadId);
//pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
std::cout << ">>> starting NS-3 application..." << std::endl;
pthread_t threads[NUM_OF_THREADS];
for(size_t i = 1; i < NUM_OF_THREADS+1; i++){
std::cout << ">>> creating THREAD #" << i << std::endl;
int threadCreateStatus = pthread_create (&threads[i], NULL, threadFunction, (void *)i);
if (threadCreateStatus) {
std::cout << ">>> error : failed to create a new THREAD #" << i << std::endl;
}
}
// do a pthread_join(), otherwise the main thread can terminate before other threads terminate and thus force them to terminate!
for(size_t i = 1; i <= NUM_OF_THREADS; i++){
if (pthread_join(threads[i], NULL)==0)
std::cout << ">>> THREAD #" << i << " joined successfully" << std::endl;
else
std::cout << ">>> THREAD #" << i << " couldn't be joined successfully" << std::endl;
}
std::cout << "counter : " << sharedCounter << std::endl;
std::cout << ">>> finishing NS-3 application..." << std::endl;
pthread_exit(NULL); // obsolete, due to the return statement in the main()
return EXIT_SUCCESS;
}
|
964edfcee2e0c55a0686692ab972f23beff46585 | 6ff1ea5c8fb7534e1ce0c6d2aac273ffb1c5babd | /lib/Runtime/Types/SimpleDictionaryPropertyDescriptor.h | e26ba1316dda415c595538393cf3eb7709d42734 | [
"MIT"
] | permissive | chakra-core/ChakraCore | 654e775f42e093e1ebbbc066212bbcdfccab15d5 | c3ead3f8a6e0bb8e32e043adc091c68cba5935e9 | refs/heads/master | 2023-09-02T08:10:10.008146 | 2023-03-21T21:22:11 | 2023-03-22T08:47:02 | 49,086,513 | 855 | 185 | MIT | 2023-07-05T00:15:56 | 2016-01-05T19:05:31 | JavaScript | UTF-8 | C++ | false | false | 2,502 | h | SimpleDictionaryPropertyDescriptor.h | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
namespace Js
{
template <typename TPropertyIndex>
class SimpleDictionaryPropertyDescriptor
{
public:
SimpleDictionaryPropertyDescriptor() :
#if ENABLE_FIXED_FIELDS
preventFalseReference(true), isInitialized(false), isFixed(false), usedAsFixed(false),
#endif
propertyIndex(NoSlots), Attributes(PropertyDynamicTypeDefaults) {}
SimpleDictionaryPropertyDescriptor(TPropertyIndex inPropertyIndex) :
#if ENABLE_FIXED_FIELDS
preventFalseReference(true), isInitialized(false), isFixed(false), usedAsFixed(false),
#endif
propertyIndex(inPropertyIndex), Attributes(PropertyDynamicTypeDefaults) {}
SimpleDictionaryPropertyDescriptor(TPropertyIndex inPropertyIndex, PropertyAttributes attributes) :
#if ENABLE_FIXED_FIELDS
preventFalseReference(true), isInitialized(false), isFixed(false), usedAsFixed(false),
#endif
propertyIndex(inPropertyIndex), Attributes(attributes) {}
#if ENABLE_FIXED_FIELDS
// SimpleDictionaryPropertyDescriptor is allocated by a dictionary along with the PropertyRecord
// so it can not allocate as leaf, tag the lower bit to prevent false reference
bool preventFalseReference:1;
bool isInitialized: 1;
bool isFixed:1;
bool usedAsFixed:1;
#endif
PropertyAttributes Attributes;
TPropertyIndex propertyIndex;
bool HasNonLetConstGlobal() const
{
return (this->Attributes & PropertyLetConstGlobal) == 0;
}
bool IsOrMayBecomeFixed() const
{
#if ENABLE_FIXED_FIELDS
return !isInitialized || isFixed;
#else
return false;
#endif
}
private:
static const TPropertyIndex NoSlots = PropertyIndexRanges<TPropertyIndex>::NoSlots;
};
}
namespace JsUtil
{
template <class TPropertyIndex>
struct ClearValue<Js::SimpleDictionaryPropertyDescriptor<TPropertyIndex>>
{
static inline void Clear(Js::SimpleDictionaryPropertyDescriptor<TPropertyIndex>* value)
{
*value = 0;
}
};
}
|
affa954c625ce02cf10795f2ef81de4bfe02644b | c288aa0eeab7a56c485bbfc4f4ce7ae5057bb79c | /spiderman.cpp | 90c02e585f749bdb1bb05949d2256631a241ea6c | [] | no_license | sdurgi17/codechef | 4721bd73c65593c9c521337e7cccf93245e13fac | aadac84326b5bee4c92335b668311394a0b053bc | refs/heads/master | 2020-04-14T23:15:02.090512 | 2015-02-23T17:29:48 | 2015-02-23T17:29:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,665 | cpp | spiderman.cpp | #include <bits/stdc++.h>
using namespace std;
struct cell {
int h;
int d;
cell () {
d = -1;
}
};
struct qCell
{
int x;
int y;
qCell() {
}
qCell(int x, int y) {
this->x = x;
this->y = y;
}
};
bool operator== (qCell a, qCell b) {
return a.x == b.x && a.y == b.y;
}
int main()
{
int t;
cin >> t;
while (t--) {
int m, n, x, y, d;
cin >> m >> n >> x >> y >> d;
cell arr[m][n];
for (int i = 0; i < m; i++ ) {
for (int j = 0; j < n; j++ ) {
cin >> arr[i][j].h;
}
}
qCell tmp;
tmp.x = 0;
tmp.y = 0;
arr[tmp.x][tmp.y].d = 0;
queue<qCell> q;
q.push(tmp);
qCell target;
target.x = x - 1;
target.y = y - 1;
int result = -1;
while(q.size()) {
qCell f = q.front();
q.pop();
if (f == target) {
result = arr[f.x][f.y].d;
}
if (f.x + 1 < m && arr[f.x + 1][f.y].d == -1 && abs(arr[f.x][f.y].h - arr[f.x + 1][f.y].h) <= d ) {
q.push(qCell(f.x + 1, f.y));
arr[f.x + 1][f.y].d = arr[f.x][f.y].d + 1;
}
if (f.x - 1 >= 0 && arr[f.x - 1][f.y].d == -1 && abs(arr[f.x][f.y].h - arr[f.x - 1][f.y].h) <= d ) {
q.push(qCell(f.x - 1, f.y));
arr[f.x - 1][f.y].d = arr[f.x][f.y].d + 1;
}
if (f.y + 1 < n && arr[f.x][f.y + 1].d == -1 && abs(arr[f.x][f.y].h - arr[f.x][f.y + 1].h) <= d ) {
q.push(qCell(f.x, f.y + 1));
arr[f.x][f.y + 1].d = arr[f.x][f.y].d + 1;
}
if (f.y - 1 >= 0 && arr[f.x][f.y - 1].d == -1 && abs(arr[f.x][f.y].h - arr[f.x][f.y - 1].h) <= d ) {
q.push(qCell(f.x, f.y - 1));
arr[f.x][f.y - 1].d = arr[f.x][f.y].d + 1;
}
}
cout << (result == -1 || result == 0 ? result : result - 1) << endl;
}
return 0;
} |
9aee5d4efb13ea2aed9d774256493c3996014e82 | f9f9deed1b29455f75a3986478f828d971d0ec5e | /SDK/PUBGM_bp_lobby_functions.cpp | 055a81f92eb3b16ac7bf05e377ec9a609966f64d | [] | no_license | etsiry/Pubg-mobile-bullet-tracking | ac1c70b06a266878e324f9686ef86557fc5915d8 | eba9f6b914fd3656ae71e02ad96b12dc3e5cafb3 | refs/heads/main | 2023-08-25T04:40:25.154377 | 2021-10-05T09:25:05 | 2021-10-05T09:25:05 | 413,748,508 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,731 | cpp | PUBGM_bp_lobby_functions.cpp | // PlayerUnknown's Battle Ground Mobile (1.4.0) SDK
#include "PUBGM_bp_lobby_parameters.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function bp_lobby.bp_lobby_C.EventFetchInfo_NoFetch
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventFetchInfo_NoFetch()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventFetchInfo_NoFetch");
Abp_lobby_C_EventFetchInfo_NoFetch_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventFetchInfo
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventFetchInfo()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventFetchInfo");
Abp_lobby_C_EventFetchInfo_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventSwitchLobbyCameraByIndex_NoFetch
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventSwitchLobbyCameraByIndex_NoFetch()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventSwitchLobbyCameraByIndex_NoFetch");
Abp_lobby_C_EventSwitchLobbyCameraByIndex_NoFetch_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventSwitchLobbyCameraByIndex
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventSwitchLobbyCameraByIndex()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventSwitchLobbyCameraByIndex");
Abp_lobby_C_EventSwitchLobbyCameraByIndex_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventLobbyAndroidBack_NoFetch
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventLobbyAndroidBack_NoFetch()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventLobbyAndroidBack_NoFetch");
Abp_lobby_C_EventLobbyAndroidBack_NoFetch_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventLobbyAndroidBack
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventLobbyAndroidBack()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventLobbyAndroidBack");
Abp_lobby_C_EventLobbyAndroidBack_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventSetInfo_Push_NoFetch
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventSetInfo_Push_NoFetch()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventSetInfo_Push_NoFetch");
Abp_lobby_C_EventSetInfo_Push_NoFetch_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventSetInfo_Push
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventSetInfo_Push()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventSetInfo_Push");
Abp_lobby_C_EventSetInfo_Push_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventEnterRoleInfo_NoFetch
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventEnterRoleInfo_NoFetch()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventEnterRoleInfo_NoFetch");
Abp_lobby_C_EventEnterRoleInfo_NoFetch_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventEnterRoleInfo
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventEnterRoleInfo()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventEnterRoleInfo");
Abp_lobby_C_EventEnterRoleInfo_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventSimulateTestReConnect_NoFetch
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventSimulateTestReConnect_NoFetch()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventSimulateTestReConnect_NoFetch");
Abp_lobby_C_EventSimulateTestReConnect_NoFetch_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventSimulateTestReConnect
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventSimulateTestReConnect()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventSimulateTestReConnect");
Abp_lobby_C_EventSimulateTestReConnect_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventShowLobbyGM_NoFetch
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventShowLobbyGM_NoFetch()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventShowLobbyGM_NoFetch");
Abp_lobby_C_EventShowLobbyGM_NoFetch_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventShowLobbyGM
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventShowLobbyGM()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventShowLobbyGM");
Abp_lobby_C_EventShowLobbyGM_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventOpenPDDSystem_NoFetch
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventOpenPDDSystem_NoFetch()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventOpenPDDSystem_NoFetch");
Abp_lobby_C_EventOpenPDDSystem_NoFetch_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.EventOpenPDDSystem
// (BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::EventOpenPDDSystem()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.EventOpenPDDSystem");
Abp_lobby_C_EventOpenPDDSystem_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
// Function bp_lobby.bp_lobby_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void Abp_lobby_C::UserConstructionScript()
{
static UFunction *pFunc = 0;
if (!pFunc)
pFunc = UObject::FindObject<UFunction>("Function bp_lobby.bp_lobby_C.UserConstructionScript");
Abp_lobby_C_UserConstructionScript_Params params;
auto flags = pFunc->FunctionFlags;
UObject *currentObj = (UObject *) this;
currentObj->ProcessEvent(pFunc, ¶ms);
pFunc->FunctionFlags = flags;
}
}
|
09ba30f228aaabe5f321a6762b78621ff71be64e | c2c37f9500f41c901ed4792baed5de11cc2abd00 | /src/LevelThemeLoader.cpp | 85eec994b1102097b7489eb7db32667ce740e3a7 | [] | no_license | justy989/MultiFall | 9e72316fdced7f55b1a1c52814736a1ade88a0ff | 0921eccd61349a3349a2d9cebb662d8ec4047889 | refs/heads/master | 2016-09-08T20:21:17.277583 | 2013-10-25T01:32:02 | 2013-10-25T01:32:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,222 | cpp | LevelThemeLoader.cpp | #include "LevelThemeLoader.h"
#include "WorldGenerator.h"
#include "WorldDisplay.h"
#include "Log.h"
#include <fstream>
LevelThemeLoader::LevelThemeLoader()
{
}
bool LevelThemeLoader::loadTheme( char* themePath, ID3D11Device* device, WorldGenerator* worldGen, WorldDisplay* worldDisplay )
{
std::ifstream file( themePath );
char buffer[128];
if( !file.is_open() ){
LOG_ERRO << "Failed to open theme: " << themePath << LOG_ENDL;
return false;
}
WCHAR wallTexturePath[128];
WCHAR floorTexturePath[128];
WCHAR ceilingTexturePath[128];
Fog fog;
float wallTextureClip = 1.0f;
float floorTextureClip = 1.0f;
float ceilingTextureClip = 1.0f;
float objectDrawDistance = 1.0f;
float lightDrawDistance = 1.0f;
float characterDrawDistance = 1.0f;
PointLight candle;
PointLight torch;
PointLight chandelier;
while( !file.eof() ){
file.getline( buffer, 128 );
//Allow Comments
for(int i = 0; i < strlen(buffer); i++){
if( buffer[i] == '#'){
buffer[i] = '\0';
break;
}
}
//Blank lines should be skipped
if( strlen( buffer ) == 0 ){
continue;
}
char* setting = strtok(buffer, " ");
char* equals = strtok(NULL, " ");
char* value = strtok(NULL, " ");
if( strcmp( setting, "WallTexture" ) == 0 ){
wsprintf(wallTexturePath, L"content/textures/");
mbstowcs(wallTexturePath + 17, value, 128);
}else if( strcmp( setting, "WallClip" ) == 0 ){
wallTextureClip = static_cast<float>(atof( value ));
}else if( strcmp( setting, "FloorTexture" ) == 0 ){
wsprintf(floorTexturePath, L"content/textures/");
mbstowcs(floorTexturePath + 17, value, 128);
}else if( strcmp( setting, "FloorClip" ) == 0 ){
floorTextureClip = static_cast<float>(atof( value ));
}else if( strcmp( setting, "CeilingTexture" ) == 0 ){
wsprintf(ceilingTexturePath, L"content/textures/");
mbstowcs(ceilingTexturePath + 17, value, 128);
}else if( strcmp( setting, "CeilingClip" ) == 0 ){
ceilingTextureClip = static_cast<float>(atof( value ));
}else if( strcmp( setting, "FogStart" ) == 0 ){
fog.start = static_cast<float>(atof( value ));
}else if( strcmp( setting, "FogEnd" ) == 0 ){
fog.end = static_cast<float>(atof( value ));
}else if( strcmp( setting, "FogColorRed" ) == 0 ){
fog.color.x = static_cast<float>(atof( value ));
}else if( strcmp( setting, "FogColorGreen" ) == 0 ){
fog.color.y = static_cast<float>(atof( value ));
}else if( strcmp( setting, "FogColorBlue" ) == 0 ){
fog.color.z = static_cast<float>(atof( value ));
}else if( strcmp( setting, "ObjectDrawDistance" ) == 0 ){
objectDrawDistance = static_cast<float>(atof( value ));
}else if( strcmp( setting, "LightDrawDistance" ) == 0 ){
lightDrawDistance = static_cast<float>(atof( value ));
}else if( strcmp( setting, "CharacterDrawDistance" ) == 0 ){
characterDrawDistance = static_cast<float>(atof( value ));
}else if( strcmp( setting, "CandleRadius" ) == 0 ){
candle.set( static_cast<float>(atof( value ) ), candle.getIntensity(), candle.getColor() );
}else if( strcmp( setting, "CandleIntensity" ) == 0 ){
candle.set( candle.getRadius(), static_cast<float>(atof( value ) ), candle.getColor() );
}else if( strcmp( setting, "CandleColorRed" ) == 0 ){
candle.getColor().x = static_cast<float>(atof( value ));
}else if( strcmp( setting, "CandleColorGreen" ) == 0 ){
candle.getColor().y = static_cast<float>(atof( value ));
}else if( strcmp( setting, "CandleColorBlue" ) == 0 ){
candle.getColor().z = static_cast<float>(atof( value ));
}else if( strcmp( setting, "TorchRadius" ) == 0 ){
torch.set( static_cast<float>(atof( value ) ), torch.getIntensity(), torch.getColor() );
}else if( strcmp( setting, "TorchIntensity" ) == 0 ){
torch.set( torch.getRadius(), static_cast<float>(atof( value ) ), torch.getColor() );
}else if( strcmp( setting, "TorchColorRed" ) == 0 ){
torch.getColor().x = static_cast<float>(atof( value ));
}else if( strcmp( setting, "TorchColorGreen" ) == 0 ){
torch.getColor().y = static_cast<float>(atof( value ));
}else if( strcmp( setting, "TorchColorBlue" ) == 0 ){
torch.getColor().z = static_cast<float>(atof( value ));
}else{
LOG_ERRO << "Unknown Theme Configuration Setting: " << setting << LOG_ENDL;
}
}
//Close the file
file.close();
//Calculate the number of rows/collumns in the texture, assuming they are the same
int floorRows = static_cast<int>(1.0f / floorTextureClip);
//Set the worldGen max Tile ID to generate
worldGen->setTileIDMax( floorRows * floorRows );
fog.diff = fog.end - fog.start;
fog.color.w = 1.0f;
LevelDisplay* levelDisplay = &worldDisplay->getLevelDisplay();
//Setup the level display fog
worldDisplay->getLevelDisplay().setFog( fog );
//Setup the draw distances for things
worldDisplay->getLevelDisplay().setDrawRange( objectDrawDistance );
worldDisplay->getLightDisplay().setDrawRange( lightDrawDistance );
worldDisplay->getPopulationDisplay().setDrawRange( characterDrawDistance );
//Set the light values
worldDisplay->getLightDisplay().setPointLight( Level::Light::Candle, candle );
worldDisplay->getLightDisplay().setPointLight( Level::Light::Torch, torch );
//worldDisplay->getLightDisplay().setPointLight( Level::Light::Chandelier, chandelier );
//Set the level display textures and clipping info
return levelDisplay->setTextures( device, floorTexturePath, floorTextureClip,
wallTexturePath, wallTextureClip,
ceilingTexturePath, ceilingTextureClip);
} |
c892c80e6f450145ddde947929be6e3102e1fb57 | 23695d2dc657907d97607d2fd9ff8a62dcb42ee9 | /water/types.hpp | 816d4ec42e4494e4f6438cf6b0dfc824e7c65aea | [
"MIT"
] | permissive | watercpp/water | 3833e1c6e5d86f5dbebc154f733c0955ef71f7e4 | 446af3faf96e2a4daecdb65121b8c9fd0d891df9 | refs/heads/master | 2023-08-22T21:07:42.894764 | 2023-08-20T13:43:28 | 2023-08-20T13:43:28 | 86,233,011 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,688 | hpp | types.hpp | // Copyright 2017-2023 Johan Paulsson
// This file is part of the Water C++ Library. It is licensed under the MIT License.
// See the license.txt file in this distribution or https://watercpp.com/license.txt
//\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_
#ifndef WATER_TYPES_HPP
#define WATER_TYPES_HPP
namespace water {
// Read types.md
using size_t = decltype(sizeof(0));
template<typename type_> type_ make_type();
namespace _ {
template<size_t at_, bool at_less_than_size_, bool at_less_than_4_, typename ...pack_>
struct at_pack_do {
};
template<typename p0_, typename ...p_>
struct at_pack_do<0, true, true, p0_, p_...> {
using result = p0_;
};
template<typename p0_, typename p1_, typename ...p_>
struct at_pack_do<1, true, true, p0_, p1_, p_...> {
using result = p1_;
};
template<typename p0_, typename p1_, typename p2_, typename ...p_>
struct at_pack_do<2, true, true, p0_, p1_, p2_, p_...> {
using result = p2_;
};
template<typename p0_, typename p1_, typename p2_, typename p3_, typename ...p_>
struct at_pack_do<3, true, true, p0_, p1_, p2_, p3_, p_...> {
using result = p3_;
};
template<size_t at_, typename p0_, typename p1_, typename p2_, typename p3_, typename ...p_>
struct at_pack_do<at_, true, false, p0_, p1_, p2_, p3_, p_...> :
at_pack_do<at_ - 4, true, ((at_ - 4) < 4), p_...>
{};
}
template<size_t at_, typename ...pack_>
using at_pack = typename _::at_pack_do<at_, (at_ < sizeof...(pack_)), (at_ < 4), pack_...>::result;
template<typename a_, typename b_>
bool constexpr equal = false;
template<typename a_>
bool constexpr equal<a_, a_> = true;
namespace _ {
struct ifel_nothing;
template<bool if_, typename true_, typename false_>
struct ifel_do {
using result = true_;
};
template<typename true_, typename false_>
struct ifel_do<false, true_, false_> {
using result = false_;
};
template<typename true_>
struct ifel_do<false, true_, ifel_nothing> {
};
}
template<bool if_, typename true_, typename false_ = _::ifel_nothing>
using ifel = typename _::ifel_do<if_, true_, false_>::result;
namespace _ {
template<typename if_, typename else_>
struct if_not_void_do {
using result = if_;
};
template<typename else_>
struct if_not_void_do<void, else_> {
using result = else_;
};
template<>
struct if_not_void_do<void, void> {
};
}
template<typename if_, typename else_ = void>
using if_not_void = typename _::if_not_void_do<if_, else_>::result;
namespace _ {
// this is needed so the template arguments of to_void are used
template<typename ...>
struct to_void_do {
using result = void;
};
}
template<typename ...pack_>
using to_void = typename _::to_void_do<pack_...>::result;
namespace _ {
template<typename ...>
struct first_do {
};
template<typename first_, typename ...pack_>
struct first_do<first_, pack_...> {
using result = first_;
};
}
template<typename ...pack_>
using first = typename _::first_do<pack_...>::result;
// test
namespace _ { namespace types_hpp_test {
static_assert(equal<int, int>, "");
static_assert(!equal<int, bool>, "");
static_assert(equal<int, decltype(make_type<int>())>, "");
template<int> struct at;
static_assert(equal<at<0>, at_pack<0, at<0>, at<1>, at<2>, at<3>, at<4>, at<5>, at<6>, at<7>, at<8>, at<9>>>, "");
static_assert(equal<at<1>, at_pack<1, at<0>, at<1>, at<2>, at<3>, at<4>, at<5>, at<6>, at<7>, at<8>, at<9>>>, "");
static_assert(equal<at<2>, at_pack<2, at<0>, at<1>, at<2>, at<3>, at<4>, at<5>, at<6>, at<7>, at<8>, at<9>>>, "");
static_assert(equal<at<3>, at_pack<3, at<0>, at<1>, at<2>, at<3>, at<4>, at<5>, at<6>, at<7>, at<8>, at<9>>>, "");
static_assert(equal<at<4>, at_pack<4, at<0>, at<1>, at<2>, at<3>, at<4>, at<5>, at<6>, at<7>, at<8>, at<9>>>, "");
static_assert(equal<at<6>, at_pack<6, at<0>, at<1>, at<2>, at<3>, at<4>, at<5>, at<6>, at<7>, at<8>, at<9>>>, "");
static_assert(equal<at<9>, at_pack<9, at<0>, at<1>, at<2>, at<3>, at<4>, at<5>, at<6>, at<7>, at<8>, at<9>>>, "");
static_assert(equal<short, ifel<true, short>>, "");
static_assert(equal<short, ifel<true, short, long>>, "");
static_assert(equal<long, ifel<false, short, long>>, "");
static_assert(equal<int, if_not_void<int>>, "");
static_assert(equal<int, if_not_void<void, int>>, "");
template<typename ...pack_> struct pack;
template<size_t at_, typename pack_, typename = void>
struct at_pack_valid {
static bool constexpr result = false;
};
template<size_t at_, typename ...pack_>
struct at_pack_valid<at_, pack<pack_...>, to_void<at_pack<at_, pack_...>>> {
static bool constexpr result = true;
};
using pack_10 = pack<at<0>, at<1>, at<2>, at<3>, at<4>, at<5>, at<6>, at<7>, at<8>, at<9>>;
static_assert(at_pack_valid<0, pack_10>::result, "");
static_assert(at_pack_valid<9, pack_10>::result, "");
static_assert(!at_pack_valid<10, pack_10>::result, "");
static_assert(!at_pack_valid<0, pack<>>::result, "");
template<bool if_, typename true_, typename = void>
struct ifel_valid {
static bool constexpr result = false;
};
template<bool if_, typename true_>
struct ifel_valid<if_, true_, to_void<ifel<if_, true_>>> {
static bool constexpr result = true;
};
static_assert(ifel_valid<true, int>::result, "");
static_assert(!ifel_valid<false, int>::result, "");
template<typename if_, typename else_, typename = void>
struct if_not_void_valid {
static bool constexpr result = false;
};
template<typename if_, typename else_>
struct if_not_void_valid<if_, else_, to_void<if_not_void<if_, else_>>> {
static bool constexpr result = true;
};
static_assert(if_not_void_valid<int, int>::result, "");
static_assert(if_not_void_valid<int, void>::result, "");
static_assert(if_not_void_valid<void, int>::result, "");
static_assert(!if_not_void_valid<void, void>::result, "");
template<typename a_> first<float, ifel<equal<float, a_>, void>> first_test(a_ const& a);
template<typename a_> first<void, ifel<!equal<float, a_>, void>> first_test(a_ const& a);
static_assert(equal<decltype(first_test(1.23f)), float>, "");
static_assert(equal<decltype(first_test(123)), void>, "");
}}
}
#endif
|
d44ecdad89c8adc3326218c4097f923a6dbd047d | dd32ac77abc3f03447e30b55a0112c146165d83c | /lib11impl/src/main/cpp/lib11implimpl2api1.cpp | 9a7edecbbe2f469f2ffc9a5f155c4c66d00fd5a3 | [] | no_license | big-guy/cpp-demo | 256d6a98f15317d3e9e2c57be41dfaaf1e92d5cf | 7e10e885c250a49ca0355e93a201ad9e8eeca6c1 | refs/heads/master | 2021-08-22T18:47:17.499027 | 2017-12-01T00:49:56 | 2017-12-01T00:49:56 | 112,660,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,033 | cpp | lib11implimpl2api1.cpp | // GENERATED SOURCE FILE
#include "lib11impl_private.h"
#include "lib11impl_impl.h"
#include "lib11core1.h"
#include "lib12api1.h"
#include "lib11core2.h"
#include "lib12api2.h"
#include "lib12api3.h"
#include <iostream>
#include <stdio.h>
/*
* Here is a function.
*/
int lib11implimpl2api11(int a, int b) {
return a + b;
}
/*
* Here is a function.
*/
int lib11implimpl2api12(int a, int b) {
return a + b;
}
/*
* Here is a function.
*/
int lib11implimpl2api13(int a, int b) {
return a + b;
}
/*
* Here is a function.
*/
int lib11implimpl2api14(int a, int b) {
return a + b;
}
/*
* Here is a function.
*/
void Lib11ImplImpl2Api1::doSomething() {
Lib11Core1 lib11core1;
lib11core1.doSomething();
Lib12Api1 lib12api1;
lib12api1.doSomething();
Lib11Core2 lib11core2;
lib11core2.doSomething();
Lib12Api2 lib12api2;
lib12api2.doSomething();
Lib12Api3 lib12api3;
lib12api3.doSomething();
Lib11ImplImpl3Api lib11implimpl3api;
lib11implimpl3api.doSomething();
}
|
ae2727c28d58946412f0d758024e8a02bde2d41c | e7aeb9c49f0d35caa1cea7f416ee1d238c8a2426 | /LeetCode/cpp/LeetCode842-将数组拆分成斐波那契数列.cpp | 9eeddcf30dd6ca916cd4cab745d6cf61b805ae5d | [] | no_license | protectors/ACM | 1ee0c2ade796c5bda80fc0551647661c2b40c65a | a9b33912d8763c6af37fbbae4135b2761a69a2a8 | refs/heads/master | 2022-07-26T13:57:40.590234 | 2022-06-21T03:41:13 | 2022-06-21T03:41:13 | 85,793,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 939 | cpp | LeetCode842-将数组拆分成斐波那契数列.cpp | class Solution {
public:
vector<int> res;
bool check(){
int len = res.size();
if(res.size()<3) return true;
else{
return (long long)res.back()==(long long)res[len-2] + (long long)res[len-3];
}
}
bool dfs(string& s, int index){
if(s.size()<=index) return res.size()>2;
long long cur = 0;
if(s[index]=='0'){
res.push_back(0);
if(check() && dfs(s, index+1)) return true;
res.pop_back();
return false;
}
while(index<s.size()){
cur = cur*10+s[index++]-'0';
if(cur>INT_MAX) return false;
res.push_back(cur);
if(check() && dfs(s, index)) return true;
res.pop_back();
}
return false;
}
vector<int> splitIntoFibonacci(string S) {
if(dfs(S,0)) return res;
return vector<int>();
}
}; |
30b2d019a01ca4b2c3ae37b80b3df9b284d1ee1a | 410eb125042cdfee1a9bb0e5d51cc45a78a019d0 | /shor.cpp | e1684d1743d38d61ad622c28b03af9340178cc38 | [] | no_license | abdavila/D-GM-QC-Simulator | 6daedef674c894ffe9da32ad8471281f4182a09b | 939d4c25c994728a9351cdd3061a3b8dd556a96e | refs/heads/master | 2023-04-09T19:04:56.968775 | 2023-03-29T00:00:37 | 2023-03-29T00:00:37 | 138,344,376 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 23,355 | cpp | shor.cpp | #include "dgm.h"
#include "common.h"
#include "gates.h"
#include <cmath>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define NUM_AMOSTRAS 14
#define EXC_RANGE 2
//////////////////////////////////////////////////////
//string concatena(vector <string> vec, int size, bool rev = false);
string int2str(int number);
long mul_inv(long a, long b);
long modular_pow(long base, long exponent, long modulus);
//////////////////////////////////////////////////////
void ApplyQFT(int qubits, int type, int threads);
vector <string> QFT(int qubits, int reg, int over, int width);
vector <string> QFT2(int qubits, int reg, int width);
vector <string> RQFT(int qubits, int reg, int over, int width);
vector <string> CSwapR(int qubits, int ctrl, int reg1, int reg2, int width);
vector <string> SwapOver(int qubits, int reg, int width);
string genRot(int qubits, int reg, long value);
vector <string> CU(int qubits, int ctrl, int reg1, int reg2, int width, long a, long N);
vector <string> CMultMod(int qubits, int ctrl, int reg1, int reg2, int over, int over_bool, int width, long a, long N);
vector <string> CRMultMod(int qubits, int ctrl, int reg1, int reg2, int over, int over_bool, int width, long a, long N);
vector <string> C2AddMod(int qubits, int ctrl1, int ctrl2, int reg, int over, int over_bool, int width, long a, long N);
vector <string> C2SubMod(int qubits, int ctrl1, int ctrl2, int reg, int over, int over_bool, int width, long a, long N);
vector <string> CAdjust(int qubits, int ctrl, int reg, int width, long N);
string C2AddF(int qubits, int ctrl1, int ctrl2, int reg, int over, long num, int width);
string CAddF(int qubits, int ctrl1, int reg, int over, long num, int width);
string AddF(int qubits, int reg, int over, long num, int width);
vector <string> AddF(int qubits, int reg, int over, long num, int width, bool controlled);
string C2SubF(int qubits, int ctrl1, int ctrl2, int reg, int over, long num, int width);
string CSubF(int qubits, int ctrl1, int reg, int over, long num, int width);
string SubF(int qubits, int reg, int over, long num, int width);
vector <string> SubF(int qubits, int reg, int over, long num, int width, bool controlled);
//string CNot(int qubits, int ctrl, int target, int cv = 1);
//string Toffoli(int qubits, int ctrl1, int ctrl2, int target, int cv = 3);
string Pauly_X(int qubits, int reg, int width);
string HadN(int qubits, int reg, int width);
float print_statistic(vector <float> amostra){
float med, desv;
med = desv = 0;
int number = amostra.size();
sort(amostra.begin(), amostra.end());
for (int i = EXC_RANGE; i < number - EXC_RANGE; i++){
// cout << amostra[i] << endl;
med += amostra[i];
}
med /= (number - EXC_RANGE*2);
for (int i = EXC_RANGE; i < number - EXC_RANGE; i++){
desv += pow((amostra[i] - med),2.0);
}
desv = sqrt(desv/(number-1)) / med * 100.0;
cout << med << "\t" << desv;
return med;
}
int
revert_bits(int res, int n){
int c = 0;
for (int i =0; i < n; i++){
c = (c<<1) | (res&1);
res = res >> 1;
}
return c;
}
int
quantum_ipow(int a, int b)
{
int i;
int r=1;
for(i=0; i<b ;i++)
r*=a;
return r;
}
/* Calculate the greatest common divisor with Euclid's algorithm */
int
quantum_gcd(int u, int v)
{
int r;
while(v)
{
r = v;
v = u % v;
u = r;
//r = u % v;
//u = v;
//v = r;
}
return u;
}
void
quantum_frac_approx(int *a, int *b, int width)
{
float f = (float) *a / *b;
float g=f;
int i, num2=0, den2=1, num1=1, den1=0, num=0, den=0;
do
{
i = (int) (g+0.000005);
g -= i-0.000005;
g = 1.0/g;
if (i * den1 + den2 > 1<<width)
break;
num = i * num1 + num2;
den = i * den1 + den2;
num2 = num1;
den2 = den1;
num1 = num;
den1 = den;
} while(fabs(((double) num / den) - f) > 1.0 / (2 * (1 << width)));
*a = num;
*b = den;
return;
}
void ApplyQFT(int qubits, int type, int multi_gpu, int qbs_region, int coalesc, int tam_block, int rept){
DGM dgm;
dgm.exec_type = type;
dgm.multi_gpu = multi_gpu;
dgm.qbs_region = qbs_region;
dgm.coalesc = coalesc;
dgm.tam_block = tam_block;
dgm.rept = rept;
dgm.qubits = qubits;
dgm.allocateMemory();
dgm.setMemoryValue(0);
vector<string> qft = QFT2(qubits,0,qubits);
dgm.executeFunction(qft);
}
//N - Number to ne factored
//type - Execution Type
//threads - Number of threads to be used in case of a parallel execution on CPU
void Shor(long N, int type, int multi_gpu, int qbs_region, int coalesc, int tam_block, int rept){
long a, n, mod_a, mod_inv_a, aux, m, res;
int qubits, qft_qb, reg1, reg2, over, over_bool;
int f1, f2, factor;
aux = N;
a = n = 0;
while (aux){
n++;
aux = aux >> 1;
}
qubits = 2*n+3;
qft_qb = 0;
reg1 = 1;
reg2 = n+2;
over = n+1;
over_bool = qubits - 1;
while((quantum_gcd(N, a) > 1) || (a < 2)){
a = rand() % N;
}
//cout << "Seed:\t" << a << endl;
DGM dgm;
dgm.exec_type = type;
dgm.multi_gpu = multi_gpu;
dgm.qbs_region = qbs_region;
dgm.coalesc = coalesc;
dgm.tam_block = tam_block;
dgm.rept = rept;
dgm.qubits = qubits;
dgm.allocateMemory();
dgm.setMemoryValue((1<<(n+2)));
string X0 = Pauly_X(qubits, 0, 1);
string H0 = HadN(qubits, qft_qb, 1);
// cout << "AQUI" << endl;
res = 0;
int L = 2*n-1;
long inv_a = mul_inv(a,N);
vector <string> func, f;
for (int i = L; i >= 0; i--){
mod_a = modular_pow(a, pow(2,i), N);
mod_inv_a = modular_pow(inv_a, pow(2,i), N);
// cout << "AQUI " << i << endl;
func.clear();
//cout << mod_a << " " << mod_inv_a << endl;
// cout << "AQUI W" << endl;
//if (mod_a != 1){
func.push_back(H0);
// cout << "AQUI" << endl;
f = CMultMod(qubits, qft_qb, reg1, reg2, over, over_bool, n, mod_a, N);
// cout << "AQUI" << endl;
func.insert(func.end(), f.begin(), f.end());
f = CSwapR(qubits, qft_qb, reg1, reg2, n);
func.insert(func.end(), f.begin(), f.end());
// cout << "AQUI" << endl;
f = CRMultMod(qubits, qft_qb, reg1, reg2, over, over_bool, n, mod_a, N);
func.insert(func.end(), f.begin(), f.end());
func.push_back(H0);
//}
//else cout << 1 << endl;
// cout << "AQUI X" << endl;
//printMemExp(dgm.r_mem, qubits, reg1, reg2, n);
if (res) func.push_back(genRot(qubits, qft_qb, res));
//cout << "Passo " << i << " " << func.size() << endl;
//for (int l = 0; l < func.size(); l++){
// cout << func[l] << endl;
//}
// cout << "AQUI Y" << endl;
dgm.executeFunction(func);
// cout << "AQUI Z" << endl;
m = dgm.measure(qft_qb);
// cout << m << endl;
res = (res << 1) | m;
}
//return;
// cout << "AQUI" << endl;
int c = revert_bits(res, 2*n);
//cout << c << " " << res << endl;
if(c==0)
{
//printf("Fail - Measured Zero.\n");
return;
}
int q = 1<<(2*n);
//printf("Measured %i (%f), ", c, (float)c/q);
quantum_frac_approx(&c, &q, n);
//printf("fractional approximation is %i/%i.\n", c, q);
int r = q;
int i = 1;
while ((r*i) < (1<<n)){
if (modular_pow(a, r*i, N) == 1){
q = r * i;
break;
}
i++;
}
if (q >= N) q = r;
/*
if((q % 2 == 1) && (2*q<(1<<n)))
{
printf("Odd denominator, trying to expand by 2.\n");
q *= 2;
}
if(q % 2 == 1)
{
printf("Odd period, try again.\n");
return;
}
*/
//printf("Possible period is %i.\n", q);
//long modular_pow(long base, long exponent, long modulus)
//f1 = quantum_ipow(a, q/2) + 1 % N;
// f1 = modular_pow(a, q/2, N) + 1;
//f2 = quantum_ipow(a, q/2) - 1 % N;
// f2 = modular_pow(a, q/2, N) - 1;
i = modular_pow(a, q/2, N);
f1 = quantum_gcd(N, i+1);
f2 = quantum_gcd(N, i-1);
if(f1>f2)
factor=f1;
else
factor=f2;
if((factor < N) && (factor > 1))
{
//printf("Sucess\n");
//printf("%ld = %i * %i\n", N, factor, (int)N/factor);
return;
}
if (r!=q){
i = modular_pow(a, r/2, N);
f1 = quantum_gcd(N, i+1);
f2 = quantum_gcd(N, i-1);
if(f1>f2)
factor=f1;
else
factor=f2;
if((factor < N) && (factor > 1)){
//printf("Sucess\n");
//printf("R: %ld = %i * %i\n", N, factor, (int)N/factor);
return;
}
}
//printf("FAIL\n");
}
string genRot(int qubits, int reg, long value){
vector <string> func(qubits, "ID");
string name;
int k = 2;
float complex rot, eps;
eps = M_E;
rot = 1;
while (value){
if (value&1) rot *= cpowf(eps, -2*M_PI*I/pow(2.0, k));
value = value >> 1;
k++;
}
if (rot != 1){
Gates g;
name = "Rot_" + int2str(value);
g.addGate(name, 1.0, 0.0, 0.0, rot);
func[reg] = name;
return concatena(func, qubits);
}
return "";
}
vector <string> CU(int qubits, int ctrl, int reg1, int reg2, int width, long a, long N){
vector <string> m, rm, sw, u;
/*
m = CMultMod(qubits, ctrl, reg1, reg2, width, a, N);
rm = CRMultMod(qubits, ctrl, reg1, reg2, width, mul_inv(a,N), N);
sw = CSwapR(qubits, ctrl, reg1, reg2+1, width);
u = m;
u.insert(u.end(), sw.begin(), sw.end());
u.insert(u.end(), rm.begin(), rm.end());
*/
return u;
}
vector<string> CMultMod(int qubits, int ctrl, int reg1, int reg2, int over, int over_bool, int width, long a, long N){
// cout << "MULT" << endl;
int ctrl2;
vector <string> qft = QFT(qubits, reg2, over, width);
// cout << "MULT" << endl;
string HN = HadN(qubits, reg2, width);
// cout << "MULT" << endl;
vector <string> rqft = RQFT(qubits, reg2, over, width);
// cout << "MULT" << endl;
//////////////////////////////////////////////////////////////
// cout << "MULT" << endl;
vector <string> mult_mod;
vector <string> am;
mult_mod.push_back(HadN(qubits, over, 1));
mult_mod.push_back(HN);
ctrl2 = reg1 + width - 1;
for (int i = 0; i < width; i++){
am = C2AddMod(qubits, ctrl, ctrl2-i, reg2, over, over_bool, width, a, N);
//for (int j = 0; j < am.size(); j++) cout << am[j] << endl;
//exit(1);
mult_mod.insert(mult_mod.end(), am.begin(), am.end());
a = (a*2)%N;
}
// cout << "MULT" << endl;
mult_mod.insert(mult_mod.end(), rqft.begin(), rqft.end());
return mult_mod;
}
vector<string> CRMultMod(int qubits, int ctrl, int reg1, int reg2, int over, int over_bool, int width, long a, long N){
int ctrl2;
vector <string> qft = QFT(qubits, reg2, over, width);
vector <string> rqft = RQFT(qubits, reg2, over, width);
//////////////////////////////////////////////////////////////
vector <string> mult_mod;
vector <string> am;
ctrl2 = reg1 + width - 1;
for (int i = 0; i < width; i++){
am = C2SubMod(qubits, ctrl, ctrl2-i, reg2, over, over_bool, width, a, N);
mult_mod.insert(mult_mod.begin(), am.begin(), am.end());
a = (a*2)%N;
}
mult_mod.insert(mult_mod.begin(), qft.begin(), qft.end());
mult_mod.insert(mult_mod.end(), rqft.begin(), rqft.end());
return mult_mod;
}
vector <string> C2AddMod(int qubits, int ctrl1, int ctrl2, int reg, int over, int over_bool, int width, long a, long N){
vector<string> qft = QFT(qubits, reg, over, width);
vector<string> rqft = RQFT(qubits, reg, over, width);
string c2_add_a = C2AddF(qubits, ctrl1, ctrl2, reg, over, a, width);
string c2_sub_a = C2SubF(qubits, ctrl1, ctrl2, reg, over, a, width);
string sub_N = SubF(qubits, reg, over, N, width);
string c_add_N = CAddF(qubits, over_bool, reg, over, N, width);
string n_over = Pauly_X(qubits, over, 1);
string c_over = CNot(qubits, over, over_bool);
vector <string> func;
func.push_back(c2_add_a);
func.push_back(sub_N);
func.insert(func.end(), rqft.begin(), rqft.end());
func.push_back(c_over);
func.insert(func.end(), qft.begin(), qft.end());
func.push_back(c_add_N);
func.push_back(c2_sub_a);
func.insert(func.end(), rqft.begin(), rqft.end());
func.push_back(n_over);
func.push_back(c_over);
func.push_back(n_over);
func.insert(func.end(), qft.begin(), qft.end());
func.push_back(c2_add_a);
return func;
}
vector <string> C2SubMod(int qubits, int ctrl1, int ctrl2, int reg, int over, int over_bool, int width, long a, long N){
vector <string> qft = QFT(qubits, reg, over, width);
vector <string> rqft = RQFT(qubits, reg, over, width);
string c2_add_a = C2AddF(qubits, ctrl1, ctrl2, reg, over, a, width);
string c2_sub_a = C2SubF(qubits, ctrl1, ctrl2, reg, over, a, width);
string add_N = AddF(qubits, reg, over, N, width);
string c_add_N = CAddF(qubits, over_bool, reg, over, N, width);
string c_sub_N = CSubF(qubits, over_bool, reg, over, N, width);
string n_over = Pauly_X(qubits, over, 1);
string c_over = CNot(qubits, over, over_bool);
vector <string> func;
func.push_back(c2_sub_a);
func.insert(func.end(), rqft.begin(), rqft.end());
func.push_back(n_over);
func.push_back(c_over);
func.push_back(n_over);
func.insert(func.end(), qft.begin(), qft.end());
func.push_back(c2_add_a);
func.push_back(c_sub_N);
func.insert(func.end(), rqft.begin(), rqft.end());
func.push_back(c_over);
func.insert(func.end(), qft.begin(), qft.end());
func.push_back(add_N);
func.push_back(c2_sub_a);
return func;
}
//////////////////////////////////////////////////////////////////////////
/*
string CNot(int qubits, int ctrl, int target, int cv){
vector <string> cn (qubits, "ID");
cn[ctrl] = "Control1(0)";
if (cv) cn[ctrl] = "Control1(1)";
cn[target] = "Target1(X)";
return concatena(cn, qubits);
}
string Toffoli(int qubits, int ctrl1, int ctrl2, int target, int cv){
vector <string> tf (qubits, "ID");
tf[ctrl1] = "Control1(0)";
if (cv>>1) tf[ctrl1] = "Control1(1)";
tf[ctrl2] = "Control1(0)";
if (cv&1) tf[ctrl2] = "Control1(1)";
tf[target] = "Target1(X)";
return concatena(tf, qubits);
}
*/
string Pauly_X(int qubits, int reg, int width){
vector <string> px (qubits, "ID");
for (int i = 0; i < width; i++) px[i+reg] = "X";
return concatena(px, qubits);
}
string HadN(int qubits, int reg, int width){
vector <string> hn (qubits, "ID");
for (int i = 0; i < width; i++) hn[i+reg] = "H";
return concatena(hn, qubits);
}
//////////////////////////////////////////////////////////////////////////
string CAddF(int qubits, int ctrl1, int reg, int over, long num, int width){
vector <string> caf = AddF(qubits, reg, over, num, width, true);
caf[ctrl1] = "Control1(1)";
return concatena(caf, qubits);
}
string C2AddF(int qubits, int ctrl1, int ctrl2, int reg, int over, long num, int width){
vector <string> caf = AddF(qubits, reg, over, num, width, true);
caf[ctrl1] = "Control1(1)";
caf[ctrl2] = "Control1(1)";
return concatena(caf, qubits);
}
string AddF(int qubits, int reg, int over, long num, int width){
return concatena(AddF(qubits, reg, over, num, width, false), qubits);
}
vector <string> AddF(int qubits, int reg, int over, long num, int width, bool controlled){
int size = width+1;
vector <float complex> rot (size, 1);
float complex c;
Gates g;
long aux = num;
float complex eps = M_E;
for (int i = 0; i < size; i++){
if (aux&1)
for (int j = i; j < size; j++)
rot[j] *= cpowf(eps, 2*M_PI*I/pow(2.0, j-i+1));
aux = aux >> 1;
}
vector<string> add(qubits, "ID");
string name;
aux = reg+width-1;
c = 1;
for (int i = 0; i < size; i++){
if (rot[i] != c){
name = "ADD_" + int2str(num) + "_" + int2str(i);
g.addGate(name, 1.0, 0.0, 0.0, rot[i]);
if (controlled) name = "Target1(" + name + ")";
add[aux-i] = name;
}
}
name = add[reg-1];
add[reg-1] = "ID";
add[over] = name;
return add;
}
string CSubF(int qubits, int ctrl1, int reg, int over, long num, int width){
vector <string> csf = SubF(qubits, reg, over, num, width, true);
csf[ctrl1] = "Control1(1)";
return concatena(csf, qubits);
}
string C2SubF(int qubits, int ctrl1, int ctrl2, int reg, int over, long num, int width){
vector <string> csf = SubF(qubits, reg, over, num, width, true);
csf[ctrl1] = "Control1(1)";
csf[ctrl2] = "Control1(1)";
return concatena(csf, qubits);
}
string SubF(int qubits, int reg, int over, long num, int width){
return concatena(SubF(qubits, reg, over, num, width, false), qubits);
}
vector <string> SubF(int qubits, int reg, int over, long num, int width, bool controlled){
long size = width+1;
vector <float complex> rot (size, 1);
float complex c;
Gates g;
long aux = num;
float complex eps = M_E;
for (int i = 0; i < size; i++){
if (aux&1)
for (int j = i; j < size; j++)
rot[j] *= cpowf(eps, -2*M_PI*I/pow(2.0, j-i+1));
aux = aux >> 1;
}
vector<string> sub(qubits, "ID");
string name;
aux = reg+width-1;
c = 1;
for (int i = 0; i < size; i++){
if (rot[i] != c){
name = "SUB_" + int2str(num) + "_" + int2str(i);
g.addGate(name, 1.0, 0.0, 0.0, rot[i]);
if (controlled) name = "Target1(" + name + ")";
sub[aux-i] = name;
}
}
name = sub[reg-1];
sub[reg-1] = "ID";
sub[over] = name;
return sub;
}
vector <string> QFT(int qubits, int reg, int over, int width){
// cout << "QFT" << endl;
string s, name;
vector <string> qft;
Gates g;
float complex c;
for (int i = 1; i <= width+1; i++){
name = "R" + int2str(i);
// cout << "QFT " << i << endl;
c = M_E;
c = cpowf(c, 2*M_PI*I/pow(2.0, i));
// cout << "QFT " << i << endl;
g.addGate(name, 1.0, 0.0, 0.0, c);
// cout << "QFT " << i << endl;
}
// cout << "QFT" << endl;
vector <string> base (qubits, "ID");
qft.push_back(HadN(qubits, over, 1));
for (int j = 0; j < width; j++){
base[j+reg] = "Control1(1)";
base[over] = "Target1(R" + int2str(j+2) + ")";
s = concatena(base, qubits);
qft.push_back(s);
base[j+reg] = "ID";
}
base[over] = "ID";
for (int i = 0; i < width; i++){
qft.push_back(HadN(qubits, i+reg, 1));
for (int j = i+1; j < width; j++){
base[j+reg] = "Control1(1)";
base[i+reg] = "Target1(R" + int2str(j-i+1) + ")";
s = concatena(base, qubits);
qft.push_back(s);
base[j+reg] = "ID";
}
base[i+reg] = "ID";
}
// cout << "QFT" << endl;
return qft;
}
vector <string> QFT2(int qubits, int reg, int width){
string s;
vector <string> qft;
Gates g;
float complex c;
for (int i = 1; i <= width+1; i++){
c = M_E;
c = cpowf(c, 2*M_PI*I/pow(2.0, i));
g.addGate("R-" + int2str(i), 1.0, 0.0, 0.0, c);
}
vector <string> base (qubits, "ID");
for (int i = 0; i < width; i++){
base[i+reg] = "H";
s = concatena(base, qubits);
qft.push_back(s);
for (int j = i+1; j < width; j++){
base[j+reg] = "Control1(1)";
base[i+reg] = "Target1(R-" + int2str(j-i+1) + ")";
s = concatena(base, qubits);
qft.push_back(s);
base[j+reg] = "ID";
}
base[i+reg] = "ID";
}
return qft;
}
vector <string> RQFT(int qubits, int reg, int over, int width){
string s;
vector <string> rqft;
Gates g;
float complex c;
for (int i = 1; i <= width+1; i++){
c = M_E;
c = cpowf(c, -2*M_PI*I/pow(2.0, i));
g.addGate("R'" + int2str(i), 1.0, 0.0, 0.0, c);
}
vector <string> base (qubits, "ID");
rqft.push_back(HadN(qubits, over, 1));
for (int j = 0; j < width; j++){
base[j+reg] = "Control1(1)";
base[over] = "Target1(R'" + int2str(j+2) + ")";
s = concatena(base, qubits);
rqft.push_back(s);
base[j+reg] = "ID";
}
base[over] = "ID";
for (int i = 0; i < width; i++){
base[i+reg] = "H";
s = concatena(base, qubits);
rqft.push_back(s);
for (int j = i+1; j < width; j++){
base[j+reg] = "Control1(1)";
base[i+reg] = "Target1(R'" + int2str(j-i+1) + ")";
s = concatena(base, qubits);
rqft.push_back(s);
base[j+reg] = "ID";
}
base[i+reg] = "ID";
}
reverse(rqft.begin(), rqft.end());
return rqft;
}
vector <string> CSwapR(int qubits, int ctrl, int reg1, int reg2, int width){
vector <string> sw;
vector <string> base (qubits, "ID");
string s1, s2;
for (int i = 0; i < width; i++){
base[ctrl] = "Control1(1)";
base[i+reg1] = "Target1(X)";
base[i+reg2] = "Control1(1)";
s1 = concatena(base, qubits);
base[ctrl] = "ID";
base[i+reg1] = "Control1(1)";
base[i+reg2] = "Target1(X)";
s2 = concatena(base, qubits);
base[i+reg1] = base[i+reg2] = "ID";
sw.push_back(s2);
sw.push_back(s1);
sw.push_back(s2);
}
return sw;
}
vector <string> SwapOver(int qubits, int reg, int width){
vector <string> so;
for(int i=0; i<width/2; i++){
so.push_back(CNot(qubits, reg+width-i-1, reg+i));
so.push_back(CNot(qubits, reg+i, reg+width-i-1));
so.push_back(CNot(qubits, reg+width-i-1, reg+i));
}
return so;
}
/////////////////////////////////////////////////////
/*
string concatena(vector <string> vec, int size, bool rev){
string s;
if (!rev){
s = vec[0];
for (int i = 1; i < size; i++)
s += "," + vec[i];
}
else{
s = vec[size-1];
for (int i = size - 2; i >= 0; i--)
s += "," + vec[i];
}
return s;
}
*/
long mul_inv(long a, long b){
long b0 = b, t, q;
long x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
string int2str(int number){
stringstream ss;
ss << number;
string str = ss.str();
return str;
}
//////////////////////////////////////////////////////
int main(int argc, char** argv){
srand (time(NULL));
struct timeval timev, tvBegin, tvEnd;
float t;
vector <float> amostras;
//QFT
int qbs_region = 9;
int tam_block = 256;
int rept = 4;
int coalesc = 4;
for (int qubits = atoi(argv[1]); qubits <= atoi(argv[2]); qubits++){
for (int a = 0; a < NUM_AMOSTRAS; a++){
gettimeofday(&tvBegin, NULL);
ApplyQFT(qubits, t_GPU, 1, qbs_region, coalesc, tam_block, rept);
gettimeofday(&tvEnd, NULL);
timeval_subtract(&timev, &tvEnd, &tvBegin);
t = timev.tv_sec + (timev.tv_usec / 1000000.0);
amostras.push_back(t);
}
print_statistic(amostras);
cout << "\t";
amostras.clear();
for (int a = 0; a < NUM_AMOSTRAS; a++){
gettimeofday(&tvBegin, NULL);
ApplyQFT(qubits, t_GPU, 2, qbs_region, coalesc, tam_block, rept);
gettimeofday(&tvEnd, NULL);
timeval_subtract(&timev, &tvEnd, &tvBegin);
t = timev.tv_sec + (timev.tv_usec / 1000000.0);
amostras.push_back(t);
}
print_statistic(amostras);
cout << "\n";
amostras.clear();
cout << "####################################" << endl << endl;
}
/* // SHOR
vector <int> vet;
//vet.push_back(57);
//vet.push_back(119);
//vet.push_back(253);
//vet.push_back(485);
vet.push_back(1017);
vet.push_back(2045);
int qbs_region = 9;
int tam_block = 256;
int rept = 4;
for (int pos = 0; pos < vet.size(); pos++){
cout << "VALUE: " << vet[pos] << endl;
for (int coalesc = 4; coalesc <=4; coalesc++){
for (int a = 0; a < NUM_AMOSTRAS; a++){
gettimeofday(&tvBegin, NULL);
Shor(vet[pos], t_GPU, 1, qbs_region, coalesc, tam_block, rept);
gettimeofday(&tvEnd, NULL);
timeval_subtract(&timev, &tvEnd, &tvBegin);
t = timev.tv_sec + (timev.tv_usec / 1000000.0);
amostras.push_back(t);
}
print_statistic(amostras);
cout << "\t";
amostras.clear();
for (int a = 0; a < NUM_AMOSTRAS; a++){
gettimeofday(&tvBegin, NULL);
Shor(vet[pos], t_GPU, 2, qbs_region, coalesc, tam_block, rept);
gettimeofday(&tvEnd, NULL);
timeval_subtract(&timev, &tvEnd, &tvBegin);
t = timev.tv_sec + (timev.tv_usec / 1000000.0);
amostras.push_back(t);
}
print_statistic(amostras);
cout << "\n";
amostras.clear();
}
cout << "####################################" << endl << endl;
}
*/
return 0;
}
|
e43f58087c46d3211d846ce619b483e3947e2108 | c910268a1ca496c239b009fabd640e80fa50df8b | /cplusplus/pthreaddemo.cpp | 6097180f6fd57a5f567527f7789aac5ce6824112 | [] | no_license | leeelei/newprogramme | 30b782cfb69ec0581026d5ff6c7a06362779bc7e | 75edc9179aa1915117cf482f3630a45bee9e7931 | refs/heads/master | 2023-09-05T06:35:21.836457 | 2021-11-05T07:07:39 | 2021-11-05T07:07:39 | 420,669,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | cpp | pthreaddemo.cpp | #include<iostream>
#include<pthread.h>
using namespace std;
#define NUM_THREADS 5
void* say_hello(void* arg){
cout<<"Hello Runoob!"<<endl;
return 0;
}
int main(){
pthread_t tid[NUM_THREADS];
for(int i=0;i<NUM_THREADS;i++){
int ret=pthread_create(&tid[i],NULL,say_hello,NULL);
if(ret!=0)
cout<<"ptread_create error: error_code="<<ret<<endl;
}
pthread_exit(NULL);
}
|
6dd0c27242a4b2a3faf1f80a9be9c20d02782627 | 3390f604b39fe90933bc4e919ba9d6720dc66537 | /src/robocontrol/controller/save/SaveData.cpp | afda87d20fbcbcb6730cf8883c3fac98773521dd | [] | no_license | hiroshi-mikuriya/nxt | 880aa9ebee679797d8b2d5c25054e027857d2263 | edfd585548447117eb3605ef0f451c8bf8346629 | refs/heads/master | 2021-05-09T07:01:44.238374 | 2018-01-29T07:33:58 | 2018-01-29T07:33:58 | 119,347,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,195 | cpp | SaveData.cpp | /*
* SaveData.cpp
*
* Created on: 2012/05/13
* Author: HIROSHI MIKURIYA
*/
#include "SaveData.h"
#include "controller/position/Position.h"
#include "hardware/body/Body.h"
#include "hardware/timer/Timer.h"
namespace controller {
namespace {
utils::RealPoint s_position[SaveData::POSITION_COUNT];
int s_angle[SaveData::ANGLE_COUNT];
U32 s_time[SaveData::TIME_COUNT];
}
SaveData::SaveData()
{
}
SaveData & SaveData::GetInstance()
{
static SaveData saveData;
return saveData;
}
void SaveData::SavePosition(int index)
{
s_position[index % POSITION_COUNT] = controller::Position::GetInstance().GetPosition();
}
void SaveData::SaveAngle(int index)
{
s_angle[index % ANGLE_COUNT] = controller::Position::GetInstance().GetAngle();
}
void SaveData::SaveTime(int index)
{
s_time[index % ANGLE_COUNT] = hardware::Timer::GetInstance().GetTime();
}
utils::RealPoint SaveData::GetPosition(int index) const
{
return s_position[index % POSITION_COUNT];
}
int SaveData::GetAngle(int index) const
{
return s_angle[index % ANGLE_COUNT];
}
int SaveData::GetTime(int index) const
{
return s_time[index % TIME_COUNT];
}
} /* namespace controller */
|
f9e0cccfb0126c27f32cfe771b5468a2390cb4d4 | ccd4a6f230327ae907beb8bd64579a107b3b3b85 | /comm/mtaf_autobuffer.cc | ae81d101deddfcd0b3b018392020c3f757eba400 | [
"MIT"
] | permissive | meitu/MTAppenderFile | d12aa798d4f54f3ae102bf7bb3a24cad6d3169f4 | 40230fce3ffc72ef3f7ed3f12be5e42d90a9b4a0 | refs/heads/develop | 2021-07-04T12:20:27.923563 | 2020-09-29T08:03:52 | 2020-09-29T08:03:52 | 178,398,732 | 48 | 10 | MIT | 2020-09-29T08:03:53 | 2019-03-29T12:09:04 | C++ | UTF-8 | C++ | false | false | 7,586 | cc | mtaf_autobuffer.cc | // Tencent is pleased to support the open source community by making GAutomator available.
// Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
// Licensed under the MIT License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://opensource.org/licenses/MIT
// 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 "mtaf_autobuffer.h"
#include <stdint.h>
#include <stdlib.h>
#include "__mtaf_assert.h"
using namespace MTAppenderFile;
const AutoBuffer KNullAtuoBuffer;
#ifndef max
#define max(a, b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef min
#define min(a, b) (((a) < (b)) ? (a) : (b))
#endif
AutoBuffer::AutoBuffer(size_t _nSize)
: parray_(NULL)
, pos_(0)
, length_(0)
, capacity_(0)
, malloc_unitsize_(_nSize) {}
AutoBuffer::AutoBuffer(void *_pbuffer, size_t _len, size_t _nSize)
: parray_(NULL)
, pos_(0)
, length_(0)
, capacity_(0)
, malloc_unitsize_(_nSize) {
Attach(_pbuffer, _len);
}
AutoBuffer::AutoBuffer(const void *_pbuffer, size_t _len, size_t _nSize)
: parray_(NULL)
, pos_(0)
, length_(0)
, capacity_(0)
, malloc_unitsize_(_nSize) {
Write(0, _pbuffer, _len);
}
AutoBuffer::~AutoBuffer() {
Reset();
}
void AutoBuffer::AllocWrite(size_t _readytowrite, bool _changelength) {
size_t nLen = (size_t)(Pos() + _readytowrite);
__FitSize(nLen);
if (_changelength) length_ = max(nLen, length_);
}
void AutoBuffer::AddCapacity(size_t _len) {
__FitSize(Capacity() + _len);
}
void AutoBuffer::Write(const void *_pbuffer, size_t _len) {
Write(Pos(), _pbuffer, _len);
Seek(_len, ESeekCur);
}
void AutoBuffer::Write(off_t &_pos, const void *_pbuffer, size_t _len) {
Write((const off_t &)_pos, _pbuffer, _len);
_pos += _len;
}
void AutoBuffer::Write(const off_t &_pos, const void *_pbuffer, size_t _len) {
MTAF_ASSERT(NULL != _pbuffer || 0 == _len);
MTAF_ASSERT(0 <= _pos);
MTAF_ASSERT((size_t)_pos <= Length());
size_t nLen = (size_t)(_pos + _len);
__FitSize(nLen);
length_ = max(nLen, length_);
memcpy((unsigned char *)Ptr() + _pos, _pbuffer, _len);
}
void AutoBuffer::Write(TSeek _seek, const void *_pbuffer, size_t _len) {
off_t pos = 0;
switch (_seek) {
case ESeekStart:
pos = 0;
break;
case ESeekCur:
pos = pos_;
break;
case ESeekEnd:
pos = length_;
break;
default:
MTAF_ASSERT(false);
break;
}
Write(pos, _pbuffer, _len);
}
size_t AutoBuffer::Read(void *_pbuffer, size_t _len) {
size_t readlen = Read(Pos(), _pbuffer, _len);
Seek(readlen, ESeekCur);
return readlen;
}
size_t AutoBuffer::Read(AutoBuffer &_rhs, size_t _len) {
size_t readlen = Read(Pos(), _rhs, _len);
Seek(readlen, ESeekCur);
return readlen;
}
size_t AutoBuffer::Read(off_t &_pos, void *_pbuffer, size_t _len) const {
size_t readlen = Read((const off_t &)_pos, _pbuffer, _len);
_pos += readlen;
return readlen;
}
size_t AutoBuffer::Read(off_t &_pos, AutoBuffer &_rhs, size_t _len) const {
size_t readlen = Read((const off_t &)_pos, _rhs, _len);
_pos += readlen;
return readlen;
}
size_t AutoBuffer::Read(const off_t &_pos, void *_pbuffer, size_t _len) const {
MTAF_ASSERT(NULL != _pbuffer);
MTAF_ASSERT(0 <= _pos);
MTAF_ASSERT((size_t)_pos <= Length());
size_t readlen = (size_t)(Length() - _pos);
readlen = min(readlen, _len);
memcpy(_pbuffer, PosPtr(), readlen);
return readlen;
}
size_t AutoBuffer::Read(const off_t &_pos, AutoBuffer &_rhs, size_t _len) const {
size_t readlen = (size_t)(Length() - _pos);
readlen = min(readlen, _len);
_rhs.Write(PosPtr(), readlen);
return readlen;
}
off_t AutoBuffer::Move(off_t _move_len) {
if (0 < _move_len) {
if (__FitSize((size_t)(Length() + _move_len))) {
memmove(parray_ + _move_len, parray_, Length());
memset(parray_, 0, (size_t)_move_len);
Length(Pos() + _move_len, (size_t)(Length() + _move_len));
}
} else {
size_t move_len = (size_t)-_move_len;
if (move_len > Length()) move_len = Length();
memmove(parray_, parray_ + move_len, Length() - move_len);
Length(move_len < (size_t)Pos() ? Pos() - move_len : 0, Length() - move_len);
}
return Length();
}
void AutoBuffer::Seek(off_t _offset, TSeek _eorigin) {
switch (_eorigin) {
case ESeekStart:
pos_ = _offset;
break;
case ESeekCur:
pos_ += _offset;
break;
case ESeekEnd:
pos_ = length_ + _offset;
break;
default:
MTAF_ASSERT(false);
break;
}
if (pos_ < 0)
pos_ = 0;
if ((size_t)pos_ > length_)
pos_ = length_;
}
void AutoBuffer::Length(off_t _pos, size_t _lenght) {
MTAF_ASSERT(0 <= _pos);
MTAF_ASSERT((size_t)_pos <= _lenght);
MTAF_ASSERT(_lenght <= Capacity());
length_ = _lenght;
Seek(_pos, ESeekStart);
}
void *AutoBuffer::Ptr(off_t _offset) {
return (char *)parray_ + _offset;
}
const void *AutoBuffer::Ptr(off_t _offset) const {
return (const char *)parray_ + _offset;
}
void *AutoBuffer::PosPtr() {
return ((unsigned char *)Ptr()) + Pos();
}
const void *AutoBuffer::PosPtr() const {
return ((unsigned char *)Ptr()) + Pos();
}
off_t AutoBuffer::Pos() const {
return pos_;
}
size_t AutoBuffer::PosLength() const {
return (size_t)(length_ - pos_);
}
size_t AutoBuffer::Length() const {
return length_;
}
size_t AutoBuffer::Capacity() const {
return capacity_;
}
void AutoBuffer::Attach(void *_pbuffer, size_t _len) {
Reset();
parray_ = (unsigned char *)_pbuffer;
length_ = _len;
capacity_ = _len;
}
void AutoBuffer::Attach(AutoBuffer &_rhs) {
Reset();
parray_ = _rhs.parray_;
pos_ = _rhs.pos_;
length_ = _rhs.length_;
capacity_ = _rhs.capacity_;
_rhs.parray_ = NULL;
_rhs.Reset();
}
void *AutoBuffer::Detach(size_t *_plen) {
unsigned char *ret = parray_;
parray_ = NULL;
size_t nLen = Length();
if (NULL != _plen)
*_plen = nLen;
Reset();
return ret;
}
void AutoBuffer::Reset() {
if (NULL != parray_)
free(parray_);
parray_ = NULL;
pos_ = 0;
length_ = 0;
capacity_ = 0;
}
bool AutoBuffer::__FitSize(size_t _len) {
if (_len > capacity_) {
size_t mallocsize = ((_len + malloc_unitsize_ - 1) / malloc_unitsize_) * malloc_unitsize_;
void *p = realloc(parray_, mallocsize);
if (NULL == p) {
MTAF_ASSERT2(p, "_len=%lld, m_nMallocUnitSize=%lld, nMallocSize=%lld, m_nCapacity=%lld",
(uint64_t)_len, (uint64_t)malloc_unitsize_, (uint64_t)mallocsize, (uint64_t)capacity_);
free(parray_);
parray_ = NULL;
return false;
}
parray_ = (unsigned char *)p;
MTAF_ASSERT2(_len <= 10 * 1024 * 1024, "%u", (uint32_t)_len);
MTAF_ASSERT(parray_);
memset(parray_ + capacity_, 0, mallocsize - capacity_);
capacity_ = mallocsize;
return true;
}
return true;
}
|
d80f28b012431f386d7e85d046cb9e805733a2b8 | 267c34cd844ff3ead58f654dc04cbf8fef32cdab | /arc029a.cpp | c2f8b098888be26fb61690b9738ddccc06f7e4cc | [] | no_license | m0bec/CP | ee59e01033bdb56f4b0d16a712d3c1fc065b04f1 | 2853cf6d97a69312c75f3d93d9d5c641f0949711 | refs/heads/master | 2021-05-10T17:14:33.676295 | 2019-07-27T11:47:02 | 2019-07-27T11:47:02 | 118,604,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | cpp | arc029a.cpp | #include <bits/stdc++.h>
using namespace std;
int n;
int t[4];
int main(){
cin >> n;
for(int i = 0; i < n; i++){
cin >> t[i];
}
int r,l, mem, ans = 100000;
for(int i = 1; i < 8; i++){
r = l = 0;
for(int j = 0; j < 4; j++){
if(i & (1<<j)){
r += t[j];
}
else{
l += t[j];
}
}
mem = max(r,l);
ans = min(ans, mem);
}
cout << ans <<endl;
} |
bd5e659c27a4ebb76e95b2d9116599296d7ea98a | 1351f48d45c2c05e322c29c5f68da0d4590888c1 | /uva2/Tafhim Vai/534.cpp | b7359f3ce0858ccab41ef2a9b760af6d73891d42 | [] | no_license | laziestcoder/Problem-Solvings | cd2db049c3f6d1c79dfc9fba9250f4e1d8c7b588 | df487904876c748ad87a72a25d2bcee892a4d443 | refs/heads/master | 2023-08-19T09:55:32.144858 | 2021-10-21T20:32:21 | 2021-10-21T20:32:21 | 114,477,726 | 9 | 2 | null | 2021-06-22T15:46:43 | 2017-12-16T17:18:43 | Python | UTF-8 | C++ | false | false | 1,184 | cpp | 534.cpp | Method:
Wasn't much hard as I was told already that it was minimax problem.
Used the Maximin algorithm
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double st[300][2];
double min(double a, double b) {
if (a>b) return a;
else return b;
}
double max(double a, double b) {
if (a<b) return a;
else return b;
}
double w[300][300], d[300][300];
int main() {
int i, j, k, n, sc=1;
while (scanf("%d",&n)!=EOF && n) {
scanf("%lf %lf",&st[1][0],&st[1][1]);
scanf("%lf %lf",&st[n][0],&st[n][1]);
for (i=2 ; i<n ; i++) {
scanf("%lf %lf",&st[i][0],&st[i][1]);
}
for (i=1 ; i<=n ; i++) {
for (j=1 ; j<=n ; j++) {
d[i][j]=w[i][j]=(double)sqrt((double)pow(st[i][0]-st[j][0],2)+(double)pow(st[i][1]-st[j][1],2));
}
d[i][i]=0.000;
}
for (k=1 ; k<=n ; k++) {
for (i=1 ; i<=n ; i++) {
for (j=1 ; j<=n ; j++) {
d[i][j] = max(d[i][j], min(d[i][k], d[k][j]));
}
}
}
printf("Scenario #%d\nFrog Distance = %.3lf\n\n",sc++,d[1][n]);
}
return 0;
}
|
99cfcc4ff92d70d3c0975d1278863d7de13f87c5 | 22f857842ea3db81144385941267b3cb4f0c57d5 | /VST/Host/VSTPluginInterface.cpp | a79c80a01ad02605bfa236a535d1dff18c9e33bb | [] | no_license | eriser/eLibv2 | c1810c8e455a779a1211c20917daa39c751b91cd | ead21b62ba05216c2ed458017219c6340f3ca661 | refs/heads/master | 2021-01-17T08:15:15.534631 | 2015-12-27T09:38:20 | 2015-12-27T09:38:20 | 49,957,461 | 1 | 0 | null | 2016-01-19T14:19:03 | 2016-01-19T14:19:02 | null | UTF-8 | C++ | false | false | 16,176 | cpp | VSTPluginInterface.cpp | #include <VST/Host/VSTPluginInterface.h>
using namespace eLibV2::VST::Host;
bool PluginInterface::Load(const std::string fileName, audioMasterCallback callback)
{
m_FileName = fileName;
m_pHostCallback = callback;
#if WIN32
m_pModule = LoadLibrary(m_FileName.c_str());
#elif TARGET_API_MAC_CARBON
CFStringRef fileNameString = CFStringCreateWithCString(NULL, fileName.c_str(), kCFStringEncodingUTF8);
if (fileNameString == 0)
return false;
CFURLRef url = CFURLCreateWithFileSystemPath(NULL, fileNameString, kCFURLPOSIXPathStyle, false);
CFRelease(fileNameString);
if (url == 0)
return false;
module = CFBundleCreate(NULL, url);
CFRelease(url);
if (module && CFBundleLoadExecutable((CFBundleRef)module) == false)
return false;
#endif
if (m_pModule)
{
if (AttachHostCallback())
{
SetupProcessingMemory();
SetupPlugin();
Open();
return true;
}
}
return false;
}
void PluginInterface::Unload()
{
Close();
FreeProcessingMemory();
if (m_pModule)
{
#if WIN32
FreeLibrary((HMODULE)m_pModule);
#elif TARGET_API_MAC_CARBON
CFBundleUnloadExecutable((CFBundleRef)module);
CFRelease((CFBundleRef)module);
#endif
m_pHostCallback = NULL;
m_pModule = NULL;
}
}
bool PluginInterface::AttachHostCallback()
{
PluginEntryProc mainProc = NULL;
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> Searching for entry function...");
#if WIN32
try
{
mainProc = (PluginEntryProc)GetProcAddress((HMODULE)m_pModule, "VSTPluginMain");
if (!mainProc)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> VSTPluginMain not found. Trying main instead.");
mainProc = (PluginEntryProc)GetProcAddress((HMODULE)m_pModule, "main");
}
#elif TARGET_API_MAC_CARBON
mainProc = (PluginEntryProc)CFBundleGetFunctionPointerForName((CFBundleRef)m_pModule, CFSTR("VSTPluginMain"));
if (!mainProc)
mainProc = (PluginEntryProc)CFBundleGetFunctionPointerForName((CFBundleRef)m_pModule, CFSTR("main_macho"));
#endif
if (mainProc)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> Creating effect instance...");
m_pEffect = mainProc(m_pHostCallback);
if (m_pEffect)
return true;
else
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> Failed to create effect instance!");
}
else
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> %s: VST Plugin entry function not found! Tried 'VSTPluginMain' and 'main'.", m_FileName.c_str());
}
catch (std::bad_alloc)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> %s: MEMORY ERROR: std::bad_alloc occured during plugin initialization", m_FileName.c_str());
}
catch (...)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> Exception: %s: ", m_FileName.c_str());
}
return false;
}
void PluginInterface::SetupPlugin()
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> Setting up plugin...");
m_pEffect->dispatcher(m_pEffect, effSetSampleRate, 0, 0, NULL, m_fSamplerate);
SetBlocksize(m_uiBlocksize);
m_pEffect->dispatcher(m_pEffect, effSetEditKnobMode, 0, 2, NULL, 0.0f);
m_uiVstVersion = (UInt16)m_pEffect->dispatcher(m_pEffect, effGetVstVersion, 0, 0, NULL, 0.0f);
// get plugin id
char pluginID[5] = { 0 };
GetPluginStringFromLong(m_pEffect->uniqueID, pluginID);
m_sPluginID.assign(pluginID);
if (m_pEffect->flags & effFlagsIsSynth)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> This is an instrument plugin...");
m_ePluginType = PluginType::PLUGIN_TYPE_INSTRUMENT;
}
else
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> This is an effect plugin...");
m_ePluginType = PluginType::PLUGIN_TYPE_EFFECT;
}
if (m_pEffect->dispatcher(m_pEffect, effGetPlugCategory, 0, 0, NULL, 0.0f) == kPlugCategShell)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> This is a shell plugin...");
m_ePluginType = PluginType::PLUGIN_TYPE_SHELL;
}
if (m_pEffect->flags & effFlagsHasEditor)
m_bHasEditor = true;
if (m_pEffect->flags & effFlagsCanReplacing)
m_bCanReplacing = true;
const char *canDo = "receiveVstMidiEvent";
if ((VstInt32)m_pEffect->dispatcher(m_pEffect, effCanDo, 0, 0, (void*)canDo, 0.0f) == 1)
m_bCanReceiveMidi = true;
m_uiNumPrograms = m_pEffect->numPrograms;
}
void PluginInterface::SetupProcessingMemory()
{
// get number of inputs/outputs -> hopefully these will NOT change during lifetime
m_uiNumInputs = m_pEffect->numInputs; // > 0 ? m_pEffect->numInputs : 2;
m_uiNumOutputs = m_pEffect->numOutputs;
try
{
if (m_uiNumInputs > 0)
{
m_ppInputs = new float*[m_uiNumInputs];
for (VstInt32 i = 0; i < m_uiNumInputs; i++)
{
m_ppInputs[i] = new float[m_uiBlocksize];
memset(m_ppInputs[i], 0, m_uiBlocksize * sizeof(float));
}
}
if (m_uiNumOutputs > 0)
{
m_ppOutputs = new float*[m_uiNumOutputs];
for (VstInt32 i = 0; i < m_uiNumOutputs; i++)
{
m_ppOutputs[i] = new float[m_uiBlocksize];
memset(m_ppOutputs[i], 0, m_uiBlocksize * sizeof(float));
}
}
}
catch (std::bad_alloc e)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "new failed");
}
}
void PluginInterface::FreeProcessingMemory()
{
if (m_uiNumInputs > 0)
{
if (m_ppInputs)
{
for (VstInt32 i = 0; i < m_uiNumInputs; i++)
delete[] m_ppInputs[i];
delete[] m_ppInputs;
m_ppInputs = NULL;
}
}
if (m_uiNumOutputs > 0)
{
if (m_ppOutputs)
{
for (VstInt32 i = 0; i < m_uiNumOutputs; i++)
delete[] m_ppOutputs[i];
delete[] m_ppOutputs;
m_ppOutputs = NULL;
}
}
}
void PluginInterface::SetBlocksize(VstInt32 blocksize)
{
m_uiBlocksize = blocksize;
m_pEffect->dispatcher(m_pEffect, effSetBlockSize, 0, m_uiBlocksize, NULL, 0.0f);
}
void PluginInterface::Open()
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> %s: Open requested...", m_sPluginID.c_str());
if (m_pEffect)
{
// call open -> empty implementation by default?
m_pEffect->dispatcher(m_pEffect, effOpen, 0, 0, NULL, 0.0f);
}
}
void PluginInterface::Close()
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> %s: Close requested...", m_sPluginID.c_str());
if (m_pEffect)
{
// call close -> empty implementation by default?
m_pEffect->dispatcher(m_pEffect, effClose, 0, 0, NULL, 0.0f);
// m_pEffect = NULL;
}
}
void PluginInterface::Start()
{
try
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> %s: Start requested...", m_sPluginID.c_str());
// call resume
m_pEffect->dispatcher(m_pEffect, effMainsChanged, 0, 1, NULL, 0.0f);
// m_pEffect->dispatcher(m_pEffect, effStartProcess, 0, 0, NULL, 0.0f);
// emulate behaviour of FLStudio after calling resume to get plugin ready
const char *canDo = "receiveVstMidiEvent";
if ((VstInt32)m_pEffect->dispatcher(m_pEffect, effCanDo, 0, 0, (void*)canDo, 0.0f) == 1)
m_bCanReceiveMidi = true;
m_bPluginRunning = true;
}
catch (const std::exception& e)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> exception in Start(): %s", e.what());
}
catch (const std::string& s)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> exception in Start(): %s", s.c_str());
}
catch (...)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> exception in Start()");
}
}
void PluginInterface::Stop()
{
try
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> %s: Stop requested...", m_sPluginID.c_str());
m_bPluginRunning = false;
// call suspend
m_pEffect->dispatcher(m_pEffect, effMainsChanged, 0, 0, NULL, 0.0f);
// m_pEffect->dispatcher(m_pEffect, effStopProcess, 0, 0, NULL, 0.0f);
}
catch (std::exception e)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> exception in Stop(): %s", e.what());
}
catch (const std::string& s)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> exception in Stop(): %s", s.c_str());
}
catch (...)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> exception in Stop()");
}
}
void PluginInterface::OpenEditor(void* window)
{
if (m_bHasEditor)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> %s: Editor Open requested...", m_sPluginID.c_str());
m_pEffect->dispatcher(m_pEffect, effEditOpen, 0, 0, window, 0);
}
}
void PluginInterface::CloseEditor()
{
if (m_bHasEditor)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> %s: Editor Close requested...", m_sPluginID.c_str());
m_pEffect->dispatcher(m_pEffect, effEditClose, 0, 0, NULL, 0);
}
}
void PluginInterface::IdleEditor()
{
if (m_bHasEditor)
m_pEffect->dispatcher(m_pEffect, effEditIdle, 0, 0, NULL, 0.0f);
}
ERect* PluginInterface::GetEditorRect()
{
ERect* eRect = NULL;
if (m_bHasEditor)
m_pEffect->dispatcher(m_pEffect, effEditGetRect, 0, 0, &eRect, 0);
return eRect;
}
std::string PluginInterface::GetEffectName()
{
char effectName[kVstMaxEffectNameLen + 1] = { 0 };
m_pEffect->dispatcher(m_pEffect, effGetEffectName, 0, 0, &effectName, 0);
return std::string(effectName);
}
void PluginInterface::SendMidi(VstInt16 channel, VstInt16 status, VstInt16 data1, VstInt16 data2)
{
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> %s: Receiving Midi message...", m_sPluginID.c_str());
if (status == 0x90)
{
// MIDI Event
midiEvent.byteSize = sizeof(VstMidiEvent);
midiEvent.type = kVstMidiType;
midiEvent.midiData[0] = (data2 == 0x00) ? 0x80 : 0x90;
midiEvent.midiData[0] += channel;
midiEvent.midiData[1] = data1;
midiEvent.midiData[2] = data2;
events.numEvents = 1;
events.events[0] = (VstEvent*)&midiEvent;
}
else if (status == 0xb0)
{
// Sysex Event
}
m_pEffect->dispatcher(m_pEffect, effProcessEvents, 0, 0, &events, 0.0f);
}
void PluginInterface::PrintProperties()
{
std::stringstream ss;
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> Gathering properties...");
char effectName[256] = { 0 };
char vendorString[256] = { 0 };
char productString[256] = { 0 };
VstInt32 vendorVersion;
m_pEffect->dispatcher(m_pEffect, effGetEffectName, 0, 0, effectName, 0.0f);
m_pEffect->dispatcher(m_pEffect, effGetVendorString, 0, 0, vendorString, 0.0f);
vendorVersion = m_pEffect->dispatcher(m_pEffect, effGetVendorVersion, 0, 0, NULL, 0.0f);
m_pEffect->dispatcher(m_pEffect, effGetProductString, 0, 0, productString, 0.0f);
ss << "Name: " << effectName << std::endl;
ss << "Vendor: " << vendorString << std::endl;
ss << "Product: " << productString << std::endl;
ss << "numPrograms: " << m_pEffect->numPrograms << std::endl;
ss << "numParams: " << m_pEffect->numParams << std::endl;
ss << "numInputs: " << m_pEffect->numInputs << std::endl;
ss << "numOutputs: " << m_pEffect->numOutputs << std::endl;
ss << "InitialDelay: " << m_pEffect->initialDelay << " frames" << std::endl;
ModuleLogger::print(LOG_CLASS_PLUGIN, ss.str().c_str());
if (m_ePluginType == PluginType::PLUGIN_TYPE_SHELL)
{
char nameBuffer[kVstMaxProductStrLen];
ss << "Sub-plugins:" << std::endl;
while (true)
{
memset(nameBuffer, 0, sizeof(nameBuffer));
VstInt32 shellPluginId = (VstInt32)m_pEffect->dispatcher(m_pEffect, effShellGetNextPlugin, 0, 0, nameBuffer, 0.0f);
if (shellPluginId == 0 || nameBuffer[0] == '\0')
break;
else
{
char pluginID[5] = { 0 };
GetPluginStringFromLong(shellPluginId, pluginID);
ss << " '" << pluginID << "' (" << nameBuffer << ")" << std::endl;
}
}
ModuleLogger::print(LOG_CLASS_PLUGIN, ss.str().c_str());
}
}
void PluginInterface::PrintPrograms()
{
// Iterate programs...
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> Listing programs...");
for (VstInt32 progIndex = 0; progIndex < m_pEffect->numPrograms; progIndex++)
{
char progName[256] = { 0 };
GetProgramName(progIndex, progName);
ModuleLogger::print(LOG_CLASS_PLUGIN, "Program %li: %s", progIndex, progName);
}
}
void PluginInterface::GetProgramName(VstInt32 progIndex, char* progName)
{
if (!m_pEffect->dispatcher(m_pEffect, effGetProgramNameIndexed, progIndex, 0, progName, 0.0f))
{
SetProgram(progIndex);
m_pEffect->dispatcher(m_pEffect, effGetProgramName, 0, 0, progName, 0.0f);
}
}
void PluginInterface::SetProgram(VstInt32 progIndex)
{
m_pEffect->dispatcher(m_pEffect, effSetProgram, 0, progIndex, NULL, 0.0f); // Note: old program not restored here!
}
void PluginInterface::PrintParameters()
{
// Iterate parameters...
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> Listing parameters...");
for (VstInt32 paramIndex = 0; paramIndex < m_pEffect->numParams; paramIndex++)
{
char paramName[256] = { 0 };
char paramLabel[256] = { 0 };
char paramDisplay[256] = { 0 };
m_pEffect->dispatcher(m_pEffect, effGetParamName, paramIndex, 0, paramName, 0.0f);
m_pEffect->dispatcher(m_pEffect, effGetParamLabel, paramIndex, 0, paramLabel, 0.0f);
m_pEffect->dispatcher(m_pEffect, effGetParamDisplay, paramIndex, 0, paramDisplay, 0.0f);
float value = m_pEffect->getParameter(m_pEffect, paramIndex);
ModuleLogger::print(LOG_CLASS_PLUGIN, "Param %li: %s ['%s' '%s'] (default: %f)", paramIndex, paramName, paramDisplay, paramLabel, value);
}
}
void PluginInterface::PrintCapabilities()
{
// Can-do nonsense...
std::stringstream ss;
ModuleLogger::print(LOG_CLASS_PLUGIN, "Plugin> Listing capabilities...");
static const char* canDos[] =
{
"sendVstEvents",
"sendVstMidiEvent",
"receiveVstEvents",
"receiveVstMidiEvent",
"receiveVstTimeInfo",
"offline",
"midiProgramNames",
"bypass"
};
for (VstInt32 canDoIndex = 0; canDoIndex < sizeof(canDos) / sizeof(canDos[0]); canDoIndex++)
{
ss << "Can do " << canDos[canDoIndex] << "... ";
VstInt32 result = (VstInt32)m_pEffect->dispatcher(m_pEffect, effCanDo, 0, 0, (void*)canDos[canDoIndex], 0.0f);
switch (result)
{
case 0:
ss << "don't know";
break;
case 1:
ss << "yes";
break;
case -1:
ss << "definitely not!";
break;
default:
ss << "w00t?";
break;
}
ss << std::endl;
}
ModuleLogger::print(LOG_CLASS_PLUGIN, ss.str().c_str());
}
void PluginInterface::SyncInputBuffers(ManagedBuffer* managedBuffer, VstInt32 dataSize)
{
if (managedBuffer)
{
for (VstInt16 bufferIndex = 0; bufferIndex < m_uiNumInputs; ++bufferIndex)
managedBuffer->Read(bufferIndex, dataSize, (VstInt16*)m_ppInputs[bufferIndex]);
}
}
void PluginInterface::SyncOutputBuffers(ManagedBuffer* managedBuffer, VstInt32 dataSize)
{
if (managedBuffer)
{
for (VstInt16 bufferIndex = 0; bufferIndex < m_uiNumOutputs; ++bufferIndex)
managedBuffer->Write(bufferIndex, dataSize, (VstInt16*)m_ppOutputs[bufferIndex]);
}
}
void PluginInterface::ProcessReplacing(VstInt32 sampleFrames)
{
if (m_bCanReplacing && m_bPluginRunning)
m_pEffect->processReplacing(m_pEffect, m_ppInputs, m_ppOutputs, sampleFrames);
}
|
a6f835e0c0735b3cacafcfafd687fd680e950ed9 | 4cacaae826960be70072a343223e4ee5c470a151 | /Codeforces-Code/Wund Fund Round 2016/E.cpp | ebf6f4b82ddf08efc475c7dfa514026a817d2c00 | [
"MIT"
] | permissive | PrayStarJirachi/Exercise-Code | 31291127f12312a66a9b21987480318741d437bf | 801a5926eccc971ab2182e5e99e3a0746bd6a7f0 | refs/heads/master | 2021-01-10T16:05:24.954121 | 2016-09-01T01:26:09 | 2016-09-01T01:26:09 | 43,229,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,497 | cpp | E.cpp | #include <bits/stdc++.h>
const int MAXN = 300001;
const long double pi = acos(-1.0);
struct Matrix{
int n, m;
long double a[4][4];
Matrix operator *(const Matrix &rhs)const {
Matrix ret;
ret.n = n;
ret.m = rhs.m;
for (int i = 0; i < n; i++)
for (int j = 0; j < rhs.m; j++) {
ret.a[i][j] = 0;
for (int k = 0; k < m; k++)
ret.a[i][j] += a[i][k] * rhs.a[k][j];
}
return ret;
}
}O;
int n, m, M;
Matrix t[MAXN * 4];
long double length[MAXN], angle[MAXN];
Matrix getRotate(const long double &angle) {
Matrix ret;
ret.n = 4;
ret.m = 4;
ret.a[0][0] = 1; ret.a[0][1] = 0; ret.a[0][2] = 0; ret.a[0][3] = 0;
ret.a[1][0] = 0; ret.a[1][1] = 1; ret.a[1][2] = 0; ret.a[1][3] = 0;
ret.a[2][0] = 0; ret.a[2][1] = 0; ret.a[2][2] = cos(angle); ret.a[2][3] = sin(angle);
ret.a[3][0] = 0; ret.a[3][1] = 0; ret.a[3][2] = -sin(angle); ret.a[3][3] = cos(angle);
return ret;
}
Matrix getMove(const long double &length) {
Matrix ret;
ret.n = 4;
ret.m = 4;
ret.a[0][0] = 1; ret.a[0][1] = 0; ret.a[0][2] = length; ret.a[0][3] = 0;
ret.a[1][0] = 0; ret.a[1][1] = 1; ret.a[1][2] = 0; ret.a[1][3] = length;
ret.a[2][0] = 0; ret.a[2][1] = 0; ret.a[2][2] = 1; ret.a[2][3] = 0;
ret.a[3][0] = 0; ret.a[3][1] = 0; ret.a[3][2] = 0; ret.a[3][3] = 1;
return ret;
}
void modify(int x, const Matrix &data) {
for (t[x += M] = data, x >>= 1; x; x >>= 1) {
t[x] = t[x << 1 ^ 1] * t[x << 1];
}
}
Matrix getProd(int x, int y) {
Matrix left = getRotate(0) * getMove(0);
Matrix right = getRotate(0) * getMove(0);
for (x += M - 1, y += M + 1; x ^ y ^ 1; x >>= 1, y >>= 1) {
if (x & 1 ^ 1) left = t[x ^ 1] * left;
if (y & 1) right = right * t[y ^ 1];
}
return right * left;
}
int main() {
std::cin >> n >> m;
for (M = 1; M <= n + 1; M <<= 1);
for (int i = 1; i <= n; i++) {
t[M + i] = getMove(length[i] = 1) * getRotate(angle[i] = 0);
}
for (int i = M; i >= 1; i--) {
t[i] = t[i << 1] * t[i << 1 ^ 1];
}
O.n = 4; O.m = 1;
O.a[0][0] = 0;
O.a[1][0] = 0;
O.a[2][0] = 1;
O.a[3][0] = 0;
for (int i = 1; i <= m; i++) {
int id, pos;
long double value;
std::cin >> id >> pos >> value;
if (id == 1) {
modify(pos, getMove(length[pos] += value) * getRotate(angle[pos]));
} else {
modify(pos, getMove(length[pos]) * getRotate(angle[pos] += pi * value / 180));
}
Matrix tmp = getProd(1, n) * O;
printf("%.10f %.10f\n", (double)tmp.a[0][0], (double)tmp.a[1][0]);
//std::cout << std::endl;
}
return 0;
}
|
814331ce498cf0ea1a999fe7b9c637548b9dbeac | 7fae527bf3468cd93c7642f176df0b5720fc581f | /Framework/src/GUI.cpp | e7013658f8765df550283a1aaa6f15f13cfba2c9 | [] | no_license | jparimaa/myvk | bf325d6b357ecd87bc7bc54e71835eab503dbdd2 | b52043f2c566863ddbfdb433f2f7b1d301046117 | refs/heads/master | 2021-07-04T08:31:02.515972 | 2019-05-14T09:52:21 | 2019-05-14T09:52:21 | 105,790,146 | 2 | 1 | null | 2018-11-06T17:34:19 | 2017-10-04T16:17:18 | C++ | UTF-8 | C++ | false | false | 5,581 | cpp | GUI.cpp | #include "GUI.h"
#include "API.h"
#include "Command.h"
#include "Common.h"
#include "Context.h"
#include "RenderPass.h"
#include <array>
namespace fw
{
namespace
{
static void imguiVkResult(VkResult r)
{
if (r != VK_SUCCESS)
{
printError("ImGUI Error: ", &r);
}
}
} // unnamed
GUI::~GUI()
{
if (m_initialized)
{
vkDestroyRenderPass(m_logicalDevice, m_renderPass, nullptr);
ImGui_ImplGlfwVulkan_Shutdown();
ImGui::DestroyContext();
}
}
bool GUI::initialize(VkDescriptorPool descriptorPool)
{
m_logicalDevice = Context::getLogicalDevice();
m_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
m_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
bool success = createCommandBuffer() && createRenderPass();
ImGui::CreateContext();
ImGui_ImplGlfwVulkan_Init_Data initData{};
initData.allocator = nullptr;
initData.gpu = Context::getPhysicalDevice();
initData.device = m_logicalDevice;
initData.render_pass = m_renderPass;
initData.pipeline_cache = VK_NULL_HANDLE;
initData.descriptor_pool = descriptorPool;
initData.check_vk_result = imguiVkResult;
bool installCallbacks = false;
success = success && ImGui_ImplGlfwVulkan_Init(API::getGLFWwindow(), installCallbacks, &initData);
VkCommandBuffer singleTimeCommandBuffer = Command::beginSingleTimeCommands();
success = success && ImGui_ImplGlfwVulkan_CreateFontsTexture(singleTimeCommandBuffer);
Command::endSingleTimeCommands(singleTimeCommandBuffer);
ImGui_ImplGlfwVulkan_InvalidateFontUploadObjects();
m_initialized = true;
return success;
}
void GUI::beginPass() const
{
ImGui_ImplGlfwVulkan_NewFrame();
}
bool GUI::render(VkFramebuffer framebuffer) const
{
vkBeginCommandBuffer(m_commandBuffer, &m_info);
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = m_renderPass;
renderPassInfo.framebuffer = framebuffer;
renderPassInfo.renderArea.extent = API::getSwapChainExtent();
renderPassInfo.clearValueCount = 0;
renderPassInfo.pClearValues = nullptr;
vkCmdBeginRenderPass(m_commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
ImGui_ImplGlfwVulkan_Render(m_commandBuffer);
vkCmdEndRenderPass(m_commandBuffer);
if (VkResult r = vkEndCommandBuffer(m_commandBuffer); r != VK_SUCCESS)
{
fw::printError("Failed to record GUI command buffer", &r);
return false;
}
return true;
}
VkCommandBuffer GUI::getCommandBuffer() const
{
return m_commandBuffer;
}
bool GUI::isInitialized() const
{
return m_initialized;
}
bool GUI::createCommandBuffer()
{
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = fw::API::getCommandPool();
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 1;
if (VkResult r = vkAllocateCommandBuffers(m_logicalDevice, &allocInfo, &m_commandBuffer); r != VK_SUCCESS)
{
fw::printError("Failed to allocate GUI command buffer", &r);
return false;
}
return true;
}
bool GUI::createRenderPass()
{
VkAttachmentReference colorAttachmentRef{};
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depthAttachmentRef{};
depthAttachmentRef.attachment = 1;
depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDependency dependency{};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
subpass.pDepthStencilAttachment = &depthAttachmentRef;
VkAttachmentDescription colorAttachment = fw::RenderPass::getColorAttachment();
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentDescription depthAttachment = fw::RenderPass::getDepthAttachment();
depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
depthAttachment.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
std::array<VkAttachmentDescription, 2> attachments = {colorAttachment, depthAttachment};
VkRenderPassCreateInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = fw::ui32size(attachments);
renderPassInfo.pAttachments = attachments.data();
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 1;
renderPassInfo.pDependencies = &dependency;
if (VkResult r = vkCreateRenderPass(m_logicalDevice, &renderPassInfo, nullptr, &m_renderPass); r != VK_SUCCESS)
{
fw::printError("Failed to create a GUI render pass", &r);
return false;
}
return true;
}
} // namespace fw
|
ead08bf0cef2855657cedf0a5dc9de1aa621bf88 | b4dc3314ebc2e8d3ba67fd777802960b4aedd84c | /brix-tools/iab/mfc/LucidApplicationBuilder/port.cpp | 3b8c9c4239c4491891d48ccb8e54a2d259abf0f8 | [] | no_license | kamilWLca/brix | 4c3f504f647a74ba7f51b5ae083bca82f70b9340 | c3f2ad913a383bbb34ee64c0bf54980562661e2f | refs/heads/master | 2021-01-18T04:08:56.435574 | 2012-09-18T16:36:32 | 2012-09-18T16:36:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,259 | cpp | port.cpp | // port.cpp: implementation of the port class.
// Parent is the class ConDat (Icon Data)
// Ports are the positions of Icon ports, each inpout type port can have a line child
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
//#include "DrawProg.h"
#include "port.h"
#include "Porting_Classes/INXGLFont.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
// global variable declared in CDrawProgApp
extern char workDir[WORK_DIR_SIZE];
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Port::Port(int _userdefined)
{
P.x=0;
P.y=0;
porttype = -1;
datatype = -1;
portNum = -1;
description = "";
connected=0;
location =0;
lineID = -1;
funcName = new INXObjArray<INXString>;
funcArg = new INXObjArray<unsigned int>;
xportConnected = 0;
xportID = -1;
initialise = 0;
atomicFlag = 1;
mandatoryFlag = 0;
tag = "";
groupID = 1;
bPortVertical = 0;
line.valueRect = INXRect(P.x-(20*5),P.y,P.x,P.y+2);
userdefined = _userdefined;
r = 0;
g = 0;
b = 0;
}
/*
@todo need New Constructor - new spec for cdf means that funcArg is not known at time of port creation
and is removed from the constructor for this reason
Port::Port(INXPoint _P, UINT _portNum, int _dataType, int _portType, INXString _description, INXObjArray<INXString>* _funcName, CUIntArray* _tempFuncArg, int _atomicFlag, bool bVerticalIn, int _userdefined)
{
Port(_P, _portNum, _dataType, _portType, _description, _funcName, NULL, _atomicFlag, bVerticalIn, _userdefined);
tempFuncArg = _tempFuncArg;
}
*/
/*
Deprecated Constructor - new spec for cdf means that funcArg is not known at time of port creation
and is removed from the constructor for this reason
*/
Port::Port(INXPoint _P, UINT _portNum, int _dataType, int _portType, INXString _description, INXObjArray<INXString>* _funcName, INXObjArray<unsigned int>* _funcArg, int _atomicFlag, bool bVerticalIn, int _userdefined, int _mandatoryFlag)
{
P.x=_P.x;
P.y=_P.y;
porttype = _portType;
datatype = _dataType;
portNum = _portNum;
description = _description;
//funcName = new INXObjArray<INXString>;
//funcArg = new CUIntArray;
funcName = _funcName;
funcArg = _funcArg;
connected=0;
location=0;
lineID = -1;
line.setPortType(porttype);
line.dataType = _dataType;
xportConnected = 0;
xportID = -1;
initialise = 0;
atomicFlag = _atomicFlag;
mandatoryFlag = _mandatoryFlag;
tag = "";
groupID = 1;
bPortVertical = bVerticalIn;
line.valueRect = INXRect(P.x-(20*5),P.y,P.x,P.y+2);
userdefined = _userdefined;
init();
r = 0;
g = 0;
b = 0;
}
Port::Port(UINT _portNum, int _portType, INXObjArray<INXString>* _funcName, INXObjArray<unsigned int>* _funcArg, int _atomicFlag)
{
P.x=0;
P.y=0;
porttype = _portType;
datatype = -1;
portNum = _portNum;
description = "";
//funcName = new INXObjArray<INXString>;
funcName = _funcName;
funcArg = _funcArg;
connected=0;
location =0;
lineID = -1;
line.setPortType(porttype);
xportConnected = 0;
xportID = -1;
initialise = 0;
atomicFlag = _atomicFlag;
tag = "";
groupID = 1;
bPortVertical = 0;
line.valueRect = INXRect(P.x-(20*5),P.y,P.x,P.y+2);
userdefined = 0;
mandatoryFlag = false;
r = 0;
g = 0;
b = 0;
}
Port::~Port()
{
delete funcName;
delete funcArg;
}
void Port::init() {
INXString bitmappath;
INXString csOrientation = "";
if(bPortVertical)
{ csOrientation = "VERT";
}
//select the bitmap according to porttype and datatype
if (porttype == STARTPORT || porttype == FINISHPORT) {
if (initialise) {
bitmappath = workDir + BMPDIR + csOrientation +"INITPORT.bmp";
}
else {
bitmappath = workDir + BMPDIR + csOrientation +"EVENTPORT.bmp";
}
}
else if (porttype == INPUTPORT || porttype == OUTPUTPORT) {
switch(datatype) {
case 0:
bitmappath = workDir + BMPDIR + csOrientation + "BOOLPORT.bmp"; break;
case 1:
bitmappath = workDir + BMPDIR + csOrientation + "INTPORT.bmp"; break;
case 2:
bitmappath = workDir + BMPDIR + csOrientation + "REALPORT.bmp"; break;
case 3:
bitmappath = workDir + BMPDIR + csOrientation + "STRINGPORT.bmp"; break;
default:
AfxMessageBox("Unrecognised Port Type");
return;
}
}
// read in bitmap for port
bitmapSize=bitmap.Init(bitmappath);
// read in bitmap for port
bitmHighSize=bitmHighlight.Init(workDir + BMPDIR + csOrientation +"HIGHLIGHTPORT.bmp");
// position the bitmap
rectangle = GetPortBitmapArea();
}
int Port::addLine(INXPoint* point,long int othericon,int otherPortNum, int otherPortType) {
//PP: Colour in here
//porttype=porttype|
line.SetEndPoints(point,&P,othericon,otherPortNum,otherPortType);
connected=1;
return 0;
}
int Port::RemoveLine() {
if (connected) line.Delete();
connected=0;
return 0;
}
int Port::DisconnectLine() {
if (connected) line.Disconnect();
connected=0;
return 0;
}
void Port::Draw(CDC* theDC) {
Draw(theDC, false, 0);
}
void Port::Draw(CDC* theDC, bool _onlyDrawAnim, int _toggleAnim) {
if (_onlyDrawAnim && ((connected == 1) || !mandatoryFlag)) return;
int descLen, dbgValLen, tagLen;
double nStrOffset=0.0;
COLORREF magenta = RGB(255,0,255);
COLORREF red = RGB(255,83,83);
COLORREF green = RGB(0,255,0);
COLORREF blue = RGB(100,177,255);
COLORREF yellow = RGB(255,255,0);
INXString cropDescript;
CLucidString clsTag, clsCropDescript;
if (!_onlyDrawAnim) {
descLen = description.GetLength();
dbgValLen = line.dbgValue.GetLength();
// define font for port text
LOGFONT logFont;
// pitch size is 7
if (theDC->IsPrinting()) {
logFont.lfHeight = -MulDiv(7, theDC->GetDeviceCaps(LOGPIXELSY), 432);
}
else {
logFont.lfHeight = -MulDiv(7, theDC->GetDeviceCaps(LOGPIXELSY), 72);
}
logFont.lfWidth = 0;
logFont.lfEscapement = 0;
logFont.lfOrientation = 0;
logFont.lfWeight = FW_NORMAL;
logFont.lfItalic = 0;
logFont.lfUnderline = 0;
logFont.lfStrikeOut = 0;
logFont.lfCharSet = ANSI_CHARSET;
logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
logFont.lfQuality = PROOF_QUALITY;
logFont.lfPitchAndFamily = VARIABLE_PITCH | FF_ROMAN;
strcpy_s(logFont.lfFaceName, "Arial");
CFont font;
font.CreateFontIndirect(&logFont);
CFont* oldFont = theDC->SelectObject(&font);
// the negate the ycoords of the rectangle for MM_LOENGLISH mapping mode when printing
if (theDC->IsPrinting()) {
rectangle = INXRect(rectangle.TopLeft().x, -rectangle.TopLeft().y,
rectangle.BottomRight().x, -rectangle.BottomRight().y);
}
theDC->SetBkMode(TRANSPARENT);
if(bPortVertical==false)
{
// limit port names to 6 charaters for userdefined blocks
if (userdefined) {
cropDescript = description.Left(6);
// Maximum length is 6
if (descLen > 6) {
descLen = 6;
}
}
else {
cropDescript = description.Left(10);
// Maximum length is 10
if (descLen > 10) {
descLen = 10;
}
}
clsCropDescript = cropDescript;
for (int i=0; i<descLen; i++) {
nStrOffset = nStrOffset + clsCropDescript.GetWidthAt(i);
}
// Add port description to icon
if (theDC->IsPrinting()) {
if (porttype == STARTPORT || porttype == INPUTPORT) {
theDC->TextOut(P.x+8,-P.y+7,(CString &)cropDescript);
}
else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
theDC->TextOut(P.x-6-((int)nStrOffset), P.y+7, (CString&)cropDescript);
}
}
else {
if (porttype == STARTPORT || porttype == INPUTPORT) {
theDC->TextOut(P.x+8,P.y-7,(CString)cropDescript);
}
else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
theDC->TextOut(P.x-6-((int)nStrOffset), P.y-7, (CString&)cropDescript);
}
}
}
// write out debug values
if (porttype == INPUTPORT && line.getDbgMonitor()) {
theDC->SetBkMode(OPAQUE);
theDC->SetBkColor(RGB(225,225,0));
theDC->TextOut(P.x-(dbgValLen*5),P.y+2,(CString&)line.dbgValue);
theDC->SetBkColor(RGB(255,255,255));
}
// if the port is tagged then write out tag and don't draw line
if (tag != "") {
theDC->SetBkMode(OPAQUE);
tagLen = tag.GetLength();
// set background colour according to datatype
if (porttype == INPUTPORT || porttype == OUTPUTPORT) {
switch (datatype) {
case 0 : theDC->SetBkColor(yellow); break;
case 1 : theDC->SetBkColor(blue); break;
case 2 : theDC->SetBkColor(green); break;
case 3 : theDC->SetBkColor(red); break;
}
}
// write text /
clsTag = tag;
// String offset is 7 for uppercase letters and 5 for lowercase
nStrOffset = 0;
for (int i=0; i<tagLen; i++) {
nStrOffset = nStrOffset + clsTag.GetWidthAt(i);
}
if (tagLen < 5) {
nStrOffset+=2;
}
if (theDC->IsPrinting()) {
if (porttype == STARTPORT || porttype == INPUTPORT) {
theDC->TextOut(P.x-((int)nStrOffset), -1 * (P.y+5), (CString&)tag);
}
else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
theDC->TextOut(P.x+3, -1 * (P.y+5), (CString&)tag);
}
} else {
if (porttype == STARTPORT || porttype == INPUTPORT) {
theDC->TextOut(P.x-((int)nStrOffset), P.y-5, (CString&)tag);
}
else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
theDC->TextOut(P.x+3, P.y-5, (CString&)tag);
}
}
theDC->SetBkColor(RGB(255,255,255));
}
// else {
// line.Draw(theDC);
// }
}
// highlight unconnected, mandatory ports when flagg is set to only draw animations
// but only on every other trigger of the timer, so it flashes on and off
if (_onlyDrawAnim && (_toggleAnim == 1)){
// draw the triangles last to override any messy labelling!
bitmHighlight.Draw(theDC,(INXPoint)(INXPoint)rectangle.TopLeft()); //@ typecast to INXPoint then INXPoint
} else {
// draw the triangles last to override any messy labelling!
bitmap.Draw(theDC,(INXPoint)rectangle.TopLeft());
}
// reset the ycoords of the rectangle
if (theDC->IsPrinting()) {
rectangle = INXRect(rectangle.TopLeft().x, -rectangle.TopLeft().y,
rectangle.BottomRight().x, -rectangle.BottomRight().y);
}
}
void Port::DrawGL(CDC* theDC){
DrawGL(theDC,false,0);
}
void Port::DrawGL(CDC* theDC, bool _onlyDrawAnim, int _toggleAnim){
int _portState = 0;
#define inputGLPort 0
#define outputGLPort 1
#define mfcCode_POR // temporarly disable ports
#ifdef mfcCode_POR
if (_onlyDrawAnim && ((connected == 1) || !mandatoryFlag)) return;
int descLen, dbgValLen, tagLen;
double nStrOffset=0.0;
COLORREF magenta = RGB(255,0,255);
COLORREF red = RGB(255,83,83);
COLORREF green = RGB(0,255,0);
COLORREF blue = RGB(100,177,255);
COLORREF yellow = RGB(255,255,0);
INXString cropDescript;
CLucidString clsTag, clsCropDescript;
if (!_onlyDrawAnim) {
descLen = description.GetLength();
dbgValLen = line.dbgValue.GetLength();
// define font for port text
INXGLFont *fonts = new INXGLFont();
fonts->setFontSize(9);
//fonts->textOut(10,10,"hello World");
LOGFONT logFont;
// pitch size is 7
/*if (theDC->IsPrinting()) {
logFont.lfHeight = -MulDiv(7, theDC->GetDeviceCaps(LOGPIXELSY), 432);
}
else {
logFont.lfHeight = -MulDiv(7, theDC->GetDeviceCaps(LOGPIXELSY), 72);
}
logFont.lfWidth = 0;
logFont.lfEscapement = 0;
logFont.lfOrientation = 0;
logFont.lfWeight = FW_NORMAL;
logFont.lfItalic = 0;
logFont.lfUnderline = 0;
logFont.lfStrikeOut = 0;
logFont.lfCharSet = ANSI_CHARSET;
logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
logFont.lfQuality = PROOF_QUALITY;
logFont.lfPitchAndFamily = VARIABLE_PITCH | FF_ROMAN;
strcpy_s(logFont.lfFaceName, "Arial");
CFont font;
font.CreateFontIndirect(&logFont);
CFont* oldFont = theDC->SelectObject(&font);*/
// the negate the ycoords of the rectangle for MM_LOENGLISH mapping mode when printing
/*if (theDC->IsPrinting()) {
rectangle = INXRect(rectangle.TopLeft().x, -rectangle.TopLeft().y,
rectangle.BottomRight().x, -rectangle.BottomRight().y);
}*/
//theDC->SetBkMode(TRANSPARENT);
if(bPortVertical==false)
{
// limit port names to 6 charaters for userdefined blocks
if (userdefined) {
cropDescript = description.Left(6);
// Maximum length is 6
if (descLen > 6) {
descLen = 6;
}
}
else {
cropDescript = description.Left(10);
// Maximum length is 10
if (descLen > 10) {
descLen = 10;
}
}
clsCropDescript = cropDescript;
for (int i=0; i<descLen; i++) {
nStrOffset = nStrOffset + clsCropDescript.GetWidthAt(i);
}
/*
// Add port description to icon
if (theDC->IsPrinting()) {
if (porttype == STARTPORT || porttype == INPUTPORT) {
//theDC->TextOut(P.x+8,-P.y+7,(CString &)cropDescript);
}
else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
//theDC->TextOut(P.x-6-((int)nStrOffset), P.y+7, (CString&)cropDescript);
}
}
else {*/
if (porttype == STARTPORT || porttype == INPUTPORT) {
//theDC->TextOut(P.x+8,P.y-7,(CString)cropDescript);
fonts->textOut(P.x+8 - 6,P.y-7 + 10,cropDescript);
}
else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
//theDC->TextOut(P.x-6-((int)nStrOffset), P.y-7, (CString&)cropDescript);
fonts->textOut(P.x-6-((int)nStrOffset) + 6, P.y-7 + 10, cropDescript);
}
//}
}
// write out debug values
if (porttype == INPUTPORT && line.getDbgMonitor()) {
//theDC->SetBkMode(OPAQUE);
//theDC->SetBkColor(RGB(225,225,0));
//theDC->TextOut(P.x-(dbgValLen*5),P.y+2,(CString&)line.dbgValue);
//theDC->SetBkColor(RGB(255,255,255));
fonts->textOut(P.x-(dbgValLen*5) - 6,P.y+2 + 10,line.dbgValue);
}
// if the port is tagged then write out tag and don't draw line
if (tag != "") {
//theDC->SetBkMode(OPAQUE);
tagLen = tag.GetLength();
// set background colour according to datatype
if (porttype == INPUTPORT || porttype == OUTPUTPORT) {
switch (datatype) {
case 0 :
//theDC->SetBkColor(yellow);
setGLPortColor(1,1,0);
break;
case 1 :
//theDC->SetBkColor(blue);
setGLPortColor(0,0,1);
break;
case 2 :
//theDC->SetBkColor(green);
setGLPortColor(0,1,0);
break;
case 3 :
//theDC->SetBkColor(red);
setGLPortColor(1,0,0);
break;
}
}
// write text /
clsTag = tag;
// String offset is 7 for uppercase letters and 5 for lowercase
nStrOffset = 0;
for (int i=0; i<tagLen; i++) {
nStrOffset = nStrOffset + clsTag.GetWidthAt(i);
}
if (tagLen < 5) {
nStrOffset+=2;
}
/*if (theDC->IsPrinting()) {
if (porttype == STARTPORT || porttype == INPUTPORT) {
theDC->TextOut(P.x-((int)nStrOffset), -1 * (P.y+5), (CString&)tag);
}
else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
theDC->TextOut(P.x+3, -1 * (P.y+5), (CString&)tag);
}
} else {*/
if (porttype == STARTPORT || porttype == INPUTPORT) {
//theDC->TextOut(P.x-((int)nStrOffset), P.y-5, (CString&)tag);
_portState = inputGLPort;
}
else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
//theDC->TextOut(P.x+3, P.y-5, (CString&)tag);
_portState = outputGLPort;
}
//}
//theDC->SetBkColor(RGB(255,255,255));
}
// else {
// line.Draw(theDC);
// }
}
if (porttype == INPUTPORT || porttype == OUTPUTPORT) {
switch (datatype) {
case 0 :
//theDC->SetBkColor(yellow);
setGLPortColor(1,1,0);
break;
case 1 :
//theDC->SetBkColor(blue);
setGLPortColor(0,0,1);
break;
case 2 :
//theDC->SetBkColor(green);
setGLPortColor(0,1,0);
break;
case 3 :
//theDC->SetBkColor(red);
setGLPortColor(1,0,0);
break;
}
}
// highlight unconnected, mandatory ports when flagg is set to only draw animations
// but only on every other trigger of the timer, so it flashes on and off
if (_onlyDrawAnim && (_toggleAnim == 1)){
// draw the triangles last to override any messy labelling!
//bitmHighlight.Draw(theDC,(INXPoint)rectangle.TopLeft()); //@ typecast to INXPoint then INXPoint
drawGLPort((INXPoint)rectangle.TopLeft(), _portState);
} else {
// draw the triangles last to override any messy labelling!
//bitmap.Draw(theDC,(INXPoint)rectangle.TopLeft());
drawGLPort((INXPoint)rectangle.TopLeft(), _portState);
}
// reset the ycoords of the rectangle
/*if (theDC->IsPrinting()) {
rectangle = INXRect(rectangle.TopLeft().x, -rectangle.TopLeft().y,
rectangle.BottomRight().x, -rectangle.BottomRight().y);
}*/
#endif
}
void Port::drawGLPort(INXPoint _position, int portState){
if (porttype == STARTPORT || porttype == INPUTPORT) {
_position.Offset(-6,5);
}else{
_position.Offset(6,5);
}
float portx = _position.x;
float porty = _position.y;
float sizeA = 5;
float sizeB = 6;
if (portState = 0){
glColor3f(r,g,b);
glBegin(GL_TRIANGLES);
glVertex2f(portx, porty + sizeA);
glVertex2f(portx - sizeA, porty);
glVertex2f(portx, porty - sizeA);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3f(r,g,b);
glVertex2f(portx, porty + sizeA);
glColor3f(1,1,1);
glVertex2f(portx, porty + sizeB);
glColor3f(r,g,b);
glVertex2f(portx - sizeA, porty);
glColor3f(1,1,1);
glVertex2f(portx - sizeB, porty);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3f(r,g,b);
glVertex2f(portx, porty - sizeA);
glColor3f(1,1,1);
glVertex2f(portx, porty - sizeB);
glColor3f(r,g,b);
glVertex2f(portx - sizeA, porty);
glColor3f(1,1,1);
glVertex2f(portx - sizeB, porty);
}else{
glColor3f(r,g,b);
glBegin(GL_TRIANGLES);
glVertex2f(portx, porty + sizeA);
glVertex2f(portx + sizeA, porty);
glVertex2f(portx, porty - sizeA);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3f(r,g,b);
glVertex2f(portx, porty + sizeA);
glColor3f(1,1,1);
glVertex2f(portx, porty + sizeB);
glColor3f(r,g,b);
glVertex2f(portx + sizeA, porty);
glColor3f(1,1,1);
glVertex2f(portx + sizeB, porty);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3f(r,g,b);
glVertex2f(portx, porty - sizeA);
glColor3f(1,1,1);
glVertex2f(portx, porty - sizeB);
glColor3f(r,g,b);
glVertex2f(portx + sizeA, porty);
glColor3f(1,1,1);
glVertex2f(portx + sizeB, porty);
}
glEnd();
}
void Port::setGLPortColor(float red, float green, float blue){
r = red;
g = green;
b = blue;
}
int Port::Move(INXPoint point) {
P = (wxPoint)P - (wxPoint)point;
// renew the port position
if (porttype == STARTPORT || porttype == INPUTPORT) {
// rectangle=INXRect(P.x-5,P.y,P.x+bitmapSize.cx,P.y+bitmapSize.cy-5);
if (line.exist) {
line.Move(point);
}
}
// else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
// rectangle=INXRect(P.x-5,P.y-5,P.x+bitmapSize.cx-5,P.y+bitmapSize.cy-5);
// }
rectangle = GetPortBitmapArea();
return 0;
}
void Port::setLineID(long int _lineID) {
lineID = _lineID;
}
int Port::OnPort(INXPoint point) {
int xdist,ydist;
xdist=labs(point.x-P.x);
ydist=labs(point.y-P.y);
if ( xdist < CLOSENESS && ydist < CLOSENESS) {
return porttype; //0 input, 1 output, 2 Trig input, 3 Trig output
}
return -1;
}
void Port::Save(ostream * file) {
*file <<endl<< porttype << "\t"<< datatype << "\t"<< P.x << "\t"<< P.y << "\t" << portNum << "\t" << initialise << "\t" << atomicFlag<< "\t" << "mandatory= " << mandatoryFlag<< "\t" << bPortVertical << "\t" << groupID << "\n";
*file << (CString)description << endl;
*file << (CString)tag << endl;
for (int i=0; i<funcName->GetSize(); i++) {
*file << (CString)funcName->GetAt(i) << "\t" << funcArg->GetAt(i) << "\t";
}
*file << "EndOfFunc";
*file << endl;
line.Save(file);
}
void Port::Load(istream * file) {
char *cTemp = NULL;
int len;
char temp[255];
char temp2[255];
int tmpInt;
int tmpIntVertical =0;
int i = 0;
long pos;
char testString[255];
char mandatoryString[] = "mandatory=";
*file >> porttype;
*file >> datatype;
*file >> P.x;
*file >> P.y;
*file >> portNum;
*file >> initialise;
*file >> atomicFlag;
// note - added mandatory flag to component spec. This means this flag may not be present when loading older DEPs
// so if no mandatory flag info (indicated by presence of "mandatory=" string),
// reset get pointer to before this read and carry on as if nothing happened
pos = file->tellg();
*file >> testString;
if (strcmp (testString, mandatoryString) == 0) {
*file >> mandatoryFlag;
} else {
mandatoryFlag = 0;
file->seekg(pos, SEEK_SET);
}
*file >> tmpIntVertical;
*file >> groupID;
bPortVertical =(tmpIntVertical == 1);
// cannot use >> operator to retrieve description as it may contain whitespaces
// Use getline. However need to ignore end of line character
file->ignore(1,'\n');
file->getline(temp,254);
// strip out any text in square brackets - this is a unique identifier that used by ICB but not needed in IAB
//note - we are cheating, just assuming that square brackets are at end of string and only keeping chars before '['
cTemp = strstr(temp,"[");
if (cTemp) {
len = strlen(cTemp);
temp[strlen(temp) - len] = '\0';
}
description = temp;
file->getline(temp,254);
tag = temp; //tag is Cstring so this is OK.
// load function name and argument
*file >> temp;
strcpy(temp2,temp);
while (strcmp(temp,"EndOfFunc")) {
*file >> tmpInt;
funcName->SetAtGrow(i, temp);
funcArg->SetAtGrow(i, tmpInt);
i++;
*file >> temp;
}
// read in bitmap for port once the port data has been loaded
if (porttype != INTERNALPORT) {
init();
}
line.Load(file);
// set datatype in line
line.dataType = datatype;
}
INXRect Port::GetPortBitmapArea()
{
INXRect r;
if( bPortVertical == TRUE )
{
if (porttype == STARTPORT || porttype == INPUTPORT) {
r=INXRect(P.x-5,P.y,P.x+bitmapSize.cx,P.y+bitmapSize.cy);
}
else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
r=INXRect(P.x-5,P.y-5,P.x+bitmapSize.cx,P.y+bitmapSize.cy);
}
}
else if( bPortVertical == FALSE )
{
if (porttype == STARTPORT || porttype == INPUTPORT) {
r=INXRect(P.x,P.y-5,P.x+bitmapSize.cx,P.y+bitmapSize.cy);
}
else if (porttype == FINISHPORT || porttype == OUTPUTPORT) {
r=INXRect(P.x-5,P.y-5,P.x+bitmapSize.cx,P.y+bitmapSize.cy);
}
}
return r;
}
|
de300497c020780c247ded795ff3a5fb111b2174 | edcdeb5d18ea16e03176b66b2e36d0b3651d4f9a | /ScaytheEngine/source/Core/Window.cpp | bdb9cfc48b215096c6aefe25abf467318c2e1cb8 | [] | no_license | Einherji/Scaythe | 4b68ce1be6943808007f0974b6a20c8150d2a547 | 973cb2182a9a061bf82be2356bcff543870899c5 | refs/heads/master | 2023-06-04T12:42:58.876885 | 2021-06-11T12:13:31 | 2021-06-11T12:13:31 | 374,066,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 63 | cpp | Window.cpp | //
// Created by matthiaso on 6/10/21.
//
#include "Window.h"
|
23cff829d2a53b7135e92b1a00b638a5b5490c01 | f6602685dbf0ea619fb4379d02410e5d8745a87c | /tools/diVine/vmi/include/ExecutableFile.h | ab981188c56782047b0afa002cd4ac03d1540057 | [] | no_license | helios-ops/vineBAP | f55cfd78793c8e2f144552187a3074d0bdc5c824 | 484da44be9f5bab25e2c699b5315328a1cbfc653 | refs/heads/master | 2022-07-14T21:10:58.529585 | 2020-05-06T16:42:16 | 2020-05-06T16:42:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,973 | h | ExecutableFile.h | ///
/// Copyright (C) 2012-2014, Dependable Systems Laboratory, EPFL
/// Copyright (C) 2014-2015, Cyberhaven
/// All rights reserved.
///
/// Licensed under the Cyberhaven Research License Agreement.
///
#ifndef VMI_EXECUTABLEFILE_H
#define VMI_EXECUTABLEFILE_H
#include <inttypes.h>
#include <llvm/Support/Path.h>
#include <map>
#include <string>
#include <unordered_map>
#include <vector>
#include "FileProvider.h"
namespace vmi {
/**
* Defines some section of memory
*/
struct SectionDescriptor {
enum SectionType { NONE = 0, READ = 1, WRITE = 2, READWRITE = 3, EXECUTE = 4 };
bool loadable;
uint64_t start;
uint64_t size;
bool hasData;
SectionType type;
std::string name;
SectionDescriptor() {
loadable = false;
start = size = 0;
hasData = false;
type = NONE;
}
void setRead(bool b) {
if (b)
type = SectionType(type | READ);
else
type = SectionType(type & (-1 - READ));
}
void setWrite(bool b) {
if (b)
type = SectionType(type | WRITE);
else
type = SectionType(type & (-1 - WRITE));
}
void setExecute(bool b) {
if (b)
type = SectionType(type | EXECUTE);
else
type = SectionType(type & (-1 - EXECUTE));
}
bool isReadable() const {
return type & READ;
}
bool isWritable() const {
return type & WRITE;
}
bool isExecutable() const {
return type & EXECUTE;
}
bool operator<(const SectionDescriptor &s) const {
return start + size <= s.start;
}
};
typedef std::vector<SectionDescriptor> Sections;
// Maps the name of the exported function to its actual address
typedef std::map<std::string, uint64_t> Exports;
/* The actual values may vary depending if the image file
is actually loaded or not */
struct ImportedSymbol {
ImportedSymbol() {
address = importTableLocation = 0;
}
ImportedSymbol(uint64_t _address, uint64_t _importTableLocation) {
address = _address;
importTableLocation = _importTableLocation;
}
/* The actual run-time address of the imported symbol */
uint64_t address;
/* The address of the image that the OS loader has to patch
to actually import the symbol */
uint64_t importTableLocation;
};
// Maps the name of the function to its actual address
typedef std::unordered_map<std::string, ImportedSymbol> ImportedSymbols;
// Maps the library name to the set of functions imported from it
typedef std::unordered_map<std::string, ImportedSymbols> Imports;
// List of virtual addresses whose content needs to be relocated.
typedef std::vector<std::pair<uint64_t, uint64_t>> Relocations;
typedef std::vector<uint64_t> ExceptionHandlers;
typedef std::vector<uint64_t> FunctionAddresses;
class ExecutableFile {
protected:
FileProvider *m_file;
bool m_loaded;
uint64_t m_loadAddress;
ExecutableFile(FileProvider *file, bool loaded, uint64_t loadAddress);
public:
static ExecutableFile *get(FileProvider *file, bool loaded, uint64_t loadAddress);
virtual ~ExecutableFile();
virtual std::string getModuleName() const = 0;
virtual uint64_t getImageBase() const = 0;
virtual uint64_t getImageSize() const = 0;
virtual uint64_t getEntryPoint() const = 0;
virtual bool getSymbolAddress(const std::string &name, uint64_t *address) = 0;
virtual bool getSourceInfo(uint64_t addr, std::string &source, uint64_t &line, std::string &function) = 0;
virtual unsigned getPointerSize() const = 0;
virtual uint32_t getCheckSum() const = 0;
virtual ssize_t read(void *buffer, size_t nbyte, off64_t va) const {
return -1;
}
virtual ssize_t write(void *buffer, size_t nbyte, off64_t va) {
return -1;
}
virtual const Sections &getSections() const = 0;
FileProvider *get() {
return m_file;
}
};
}
#endif
|
a14e5986fb81fd5569d28c21fcf9ef3afcf869b6 | f2d5446b6080df80a03dbaae8937aacabf5c1c60 | /4.cpp | 47ab7e694fbac7710b03ab32f2ca1d37c5ae2dde | [] | no_license | BioQwer/mipt_oop | 07fdc31c3941f893f976cdc777836bb429c332e0 | 1106f1a2721dc45edef57a7c2a0f7545a007914e | refs/heads/master | 2016-09-01T05:58:46.357502 | 2016-03-25T12:27:36 | 2016-03-25T12:27:36 | 54,743,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 879 | cpp | 4.cpp | #include <iostream>
#include <cstdlib>
#include <math.h>
using namespace std;
class Coord {
public:
int x;
int y;
};
// Класс треугольник
class Triangle {
public:
Coord p1, p2, p3;
};
Coord getPoint() {
Coord res;
cin >> res.x >> res.y;
return res;
}
void printPoint(Coord a) {
cout << a.x << " " << a.y;
}
void getTri(Triangle &tri) {
tri.p1 = getPoint();
tri.p2 = getPoint();
tri.p3 = getPoint();
}
int cmp(Triangle a, Triangle b) {
bool isEqual = true;
if ((a.p1.x - a.p2.x != b.p1.x - b.p2.x) || (a.p1.y - a.p2.y != b.p1.y - b.p2.y))
isEqual = false;
if ((a.p2.x - a.p3.x != b.p2.x - b.p3.x) || (a.p2.y - a.p3.y != b.p2.y - b.p3.y))
isEqual = false;
if ((a.p3.x - a.p1.x != b.p3.x - b.p1.x) || (a.p3.y - a.p1.y != b.p3.y - b.p1.y))
isEqual = false;
return isEqual;
} |
ba65b4e6739a047a02320e74ce68c78961ba95fc | dc7ba2a2eb5f6eb721074e25dbf16b5e15a3b298 | /src/cosima/include/MCDriftChamberHit.hh | d69c879b9734a79a07ffa5e045af48a7875ae56e | [] | no_license | markbandstra/megalib | 094fc75debe3cff24a79ba8c3485180c92d70858 | 078f4d23813d8185a75414e1cdb2099d73f17a65 | refs/heads/master | 2021-01-17T08:34:07.177308 | 2013-11-15T22:17:10 | 2013-11-15T22:17:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,477 | hh | MCDriftChamberHit.hh | /*
* MCDriftChamberHit.hh
*
* Copyright (C) by Andreas Zoglauer.
* All rights reserved.
*
* Please see the source-file for the copyright-notice.
*
*/
/******************************************************************************
*
* Class representing a hit in a 2D strip detector.
* The represented data is the position in strip numbers and absolute position
* as well as the energy in ADCounts and keV
*
*/
#ifndef ___MCDriftChamberHit___
#define ___MCDriftChamberHit___
// Geant4:
#include "G4VHit.hh"
#include "G4THitsCollection.hh"
#include "G4Allocator.hh"
#include "G4ThreeVector.hh"
// Cosima:
#include "MC2DStripHit.hh"
/******************************************************************************/
class MCDriftChamberHit : public MC2DStripHit
{
// Public interface:
public:
/// Default constructor
explicit MCDriftChamberHit();
/// Default destructor
~MCDriftChamberHit();
/// Default copy constructor
MCDriftChamberHit(const MCDriftChamberHit&);
/// Default assignment constructor
const MCDriftChamberHit& operator=(const MCDriftChamberHit&);
/// Is-Equal operator
int operator==(MCDriftChamberHit&);
/// Addition operator
const MCDriftChamberHit& operator+=(const MCDriftChamberHit&);
/// Special Geant4 memory allocation
inline void* operator new(size_t);
/// Special Geant4 memory deallocation
inline void operator delete(void*);
/// Return the data as calibrated hit (as position and energy)
MSimHT* GetCalibrated();
/// Set the number of ADCcounts evoked by this hit
inline void SetADCCounts(G4double ADCCounts) { m_ADCCounts = ADCCounts; }
/// Set the location of the hit in the world coordinate system
inline void SetPosition(G4ThreeVector Position) { m_Position = Position; }
/// Set the strip number in x-direction
inline void SetXStrip(G4int XStrip) { m_XStrip = XStrip; }
/// Set the strip number in x-direction
inline G4int GetXStrip() { return m_XStrip; }
/// Set the strip number in y-direction
inline void SetYStrip(G4int YStrip) { m_YStrip = YStrip; }
/// Set the strip number in y-direction
inline G4int GetYStrip() { return m_YStrip; }
/// Return the number of ADCCounts
inline G4double GetADCCounts() { return m_ADCCounts; }
/// Return the position in the world coordinate system
inline G4ThreeVector GetPosition() { return m_Position; }
/// Dump the hit
void Print();
private:
/// Absolute Position of the hit in the world reference frame
G4ThreeVector m_Position;
/// x-Strip of the LAYER (not wafer) where the hit has happend
G4int m_XStrip;
/// y-Strip of the LAYER (not wafer) where the hit has happend
G4int m_YStrip;
/// Number of ADC counts registered in the strips
G4double m_ADCCounts;
/// True, if the strip has depth resolution
G4bool m_Is3D;
};
/******************************************************************************/
typedef G4THitsCollection<MCDriftChamberHit> MCDriftChamberHitsCollection;
extern G4Allocator<MCDriftChamberHit> MCDriftChamberHitAllocator;
inline void* MCDriftChamberHit::operator new(size_t)
{
void* NewHit;
NewHit = (void*) MCDriftChamberHitAllocator.MallocSingle();
return NewHit;
}
inline void MCDriftChamberHit::operator delete(void* Hit)
{
MCDriftChamberHitAllocator.FreeSingle((MCDriftChamberHit*) Hit);
}
#endif
/*
* MCDriftChamberHit.hh: the end...
******************************************************************************/
|
437c00bda7281a9918b073a8ded586f424599296 | 91721781f5c4a02a723ce9dd0d733bffef4a194f | /old_source/svc/host/SVCHostIP.cpp | 4ee958ecd7d16edbb8e9ed7e2ed629530c5ad6a4 | [] | no_license | thongxuan/svc | 557eaf4e109e8afd3d60c535e091868a0e734699 | 29cdba3097b8cc838116d1673f1327a19dd03d22 | refs/heads/master | 2023-01-11T00:57:45.090755 | 2016-09-26T13:07:33 | 2016-09-26T13:07:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | cpp | SVCHostIP.cpp | #include "SVCHostIP.h"
using namespace std;
SVCHostIP::SVCHostIP(string ipAddress){
this->ipAddress = ipAddress;
int result = inet_aton(ipAddress.c_str(), &(this->hostAddr));
if (result == -1)
throw "Invalid IP address";
}
uint32_t SVCHostIP::getHostAddress(){
return (uint32_t)(this->hostAddr.s_addr);
}
|
4bf2410b2ff48147806e8f38e53ca967862b3805 | 646bc0bb7d1e88deb48985d6a15884bc15745980 | /aoc_23_1.cpp | ed57c56e80fff5a665fa56d0dd914073653371dc | [] | no_license | Ruxandra985/aoc-2018 | 682ce70addd73657e412aa6bf5997e866ba837b8 | 96e7c219dde3594efdf347249087ec939f6863e3 | refs/heads/master | 2020-04-10T05:58:13.853474 | 2018-12-27T13:17:47 | 2018-12-27T13:17:47 | 160,842,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,860 | cpp | aoc_23_1.cpp | #include <cstdio>
#include <iostream>
#include <cstring>
#define INF 1000000000
#define DIM 1000
using namespace std;
struct ceva{
long long x,y,z,raza;
};
ceva v[DIM+10];
int f[DIM+10];
long long intersect[DIM+10];
FILE *fin=fopen ("a.in","r");
FILE *fout=fopen ("a.out","w");
inline long long getnr(){
long long nr=0;
int semn=1;
char c;
c=fgetc (fin);
while ('0'>c || '9'<c){
if (c=='-')
semn=-1;
c=fgetc (fin);
}
while ('0'<=c && c<='9'){
nr=nr*10+c-'0';
c=fgetc (fin);
}
return nr*semn;
}
long long modul (long long a){
if (a<0)
return -a;
return a;
}
int main()
{
int i,sol,sc,j,poz,ok;
long long maxi,mini,l,r,xsol,ysol,zsol,k;
maxi=-INF;
for (i=1;i<=DIM;i++){
v[i].x=getnr();
v[i].y=getnr();
v[i].z=getnr();
v[i].raza=getnr();
if (v[i].raza>maxi){
maxi=v[i].raza;
poz=i;
}
//printf ("%lld %lld %lld %lld\n",v[i].x,v[i].y,v[i].z,v[i].raza);
}
sol=0;
for (j=1;j<=DIM;j++){
if (modul(v[poz].z-v[j].z)+modul(v[poz].y-v[j].y)+modul(v[poz].x-v[j].x)<=maxi)
sol++;
}
fprintf (fout,"%d",sol);
/*while(1)
{
memset(intersect,0,sizeof(intersect));
maxi=0;
for(i=1;i<=DIM;i++){
if (!f[i]){
for(j=1;j<=DIM;j++){
if (!f[j])
if(modul (v[i].x-v[j].x) + modul (v[i].y-v[j].y) + modul (v[i].z-v[j].z) >v[i].raza+v[j].raza){
intersect[j]++;
maxi=max(maxi,intersect[j]);
}
}
}
}
if(!maxi)
break;
for(i=1;i<=DIM;i++)
f[i]=(f[i] | (intersect[i]==maxi));
}
l=-INF;
r=INF;
for(i=1;i<=DIM;i++){
if (!f[i]){
l=max(l,v[i].x-v[i].raza);
r=min(r,v[i].x+v[i].raza);
}
}
for(k=l;k<=r;k++){
ok=1;
for(i=1;i<=DIM;i++){
if(!f[i]){
if(v[i].raza<modul(k-v[i].x))
ok=0;
}
}
if (ok){
for(i=1;i<=DIM;i++){
if(!f[i]){
for(j=1;j<=DIM;j++){
if(!f[j] && modul(v[i].z-v[j].z)+modul(v[i].y-v[j].y)>v[i].raza+v[j].raza-modul(k-v[i].x)-modul(k-v[j].x)){
ok=0;
break;
}
}
if(!ok)
break;
}
}
}
if(ok)
break;
}
xsol=k;
for(i=1;i<=DIM;i++){
if(!f[i])
v[i].raza-=modul(xsol-v[i].x);
}
l=-INF;
r=INF;
for(i=1;i<=DIM;i++){
if (!f[i]){
l=max(l,v[i].y-v[i].raza);
r=min(r,v[i].y+v[i].raza);
}
}
//fprintf (fout,"%lld %lld",l,r);
//return 0;
for(k=l;k<=r;k++){
ok=1;
for(i=1;i<=DIM;i++){
if(!f[i]){
if(v[i].raza<modul(k-v[i].y))
ok=0;
}
}
if (ok){
for(i=1;i<=DIM;i++){
if(!f[i]){
for(j=1;j<=DIM;j++){
if(!f[j] && modul(v[i].z-v[j].z)>v[i].raza+v[j].raza-modul(k-v[i].y)-modul(k-v[j].y)){
ok=0;
break;
}
}
if(!ok)
break;
}
}
}
if(ok)
break;
}
ysol=k;
for(i=1;i<=DIM;i++)
if(!f[i])
v[i].raza-=modul(ysol-v[i].y);
l=-INF;
r=INF;
for(i=1;i<=DIM;i++){
if(!f[i]){
l=max(l,v[i].z-v[i].raza);
r=min(r,v[i].z+v[i].raza);
}
}
for(k=l;k<=r;k++){
ok=1;
for(i=1;i<=DIM;i++){
if(!f[i]){
if(v[i].raza<modul(k-v[i].z))
ok=0;
}
}
for(i=1;i<=DIM;i++){
if (!f[i]){
for (j=1;j<=DIM;j++){
if (!f[j]){
if (0>v[i].raza+v[j].raza-modul(k-v[i].x)-modul(k-v[j].x)){
ok=0;
break;
}
}
}
if (!ok)
break;
}
}
if(ok==1)
break;
}
zsol=k;
fprintf (fout,"%lld",xsol+ysol+zsol);*/
return 0;
}
|
8ddef110849ecb640ea46d162beee6cbd0d9d4e6 | 7a01bc08abbc4080a6099028d6b7425554ac19e2 | /Conds-id2.cpp | 266fbc9b6cebbe2349c962d9675fc71febfe17a2 | [] | no_license | llewelld/MATTS | b1c41718192adbd44eeae5d9dc42c04a2d5790cb | bab63710bd31479fddafb19956a36d8d212b18e9 | refs/heads/master | 2021-01-20T07:03:25.222297 | 2018-07-27T13:57:09 | 2018-07-27T13:57:09 | 14,070,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,851 | cpp | Conds-id2.cpp | /*$T MATTS/Conds-id2.cpp GC 1.140 07/01/09 21:12:09 */
/*/
* Pre and Post conditions */
#include "cAnalyse.h"
#include <stdio.h>
/*/
* BUFFER OVERRUN TEST 01 (Sending) Defines
*/
#define BUFFERRECEIVELEN (4)
#define BUFFERRECEIVENUM (64)
#define BUFFERRECEIVEEND (0)
#define BUFFERHEAPSTART (1000)
/*/
* Global variables */
static int gnLink = 0;
/*/
=======================================================================================================================
* Set up the post condition (applied after code has terminated)
=======================================================================================================================
*/
Operation* CreatePostCondition_id2 (void) {
Operation* psPost;
psPost = NULL;
psPost = CreateBinary (OPBINARY_LT, CreateVariable ("chanmax"), CreateVariable ("chantest"));
return psPost;
}
/*/
=======================================================================================================================
* Apply the pre condition (applied before code is executed)
=======================================================================================================================
*/
Operation* ApplyPreCondition_id2 (Operation* psOp) {
Operation* psFind;
Operation* psSub;
psFind = NULL;
psSub = NULL;
/* MOV sc[nM3] 0 */
psFind = CreateVariable ("channel");
/* Should really be dependant on nM3 */
psSub = CreateInteger (0);
psOp = SubstituteOperation (psOp, psFind, psSub);
FreeRecursive (psFind);
psFind = NULL;
FreeRecursive (psSub);
psSub = NULL;
/* MOV chanmax 0 */
psFind = CreateVariable ("chanmax");
psSub = CreateInteger (0);
psOp = SubstituteOperation (psOp, psFind, psSub);
FreeRecursive (psFind);
psFind = NULL;
FreeRecursive (psSub);
psSub = NULL;
/* MOV counter 0 */
psFind = CreateVariable ("counter");
psSub = CreateInteger (0);
psOp = SubstituteOperation (psOp, psFind, psSub);
FreeRecursive (psFind);
psFind = NULL;
FreeRecursive (psSub);
psSub = NULL;
/*
* // MOV chantest 3 ;
* psFind = CreateVariable ("chantest");
* psSub = CreateInteger (5);
* psOp = SubstituteOperation (psOp, psFind, psSub);
* FreeRecursive (psFind);
* psFind = NULL;
* FreeRecursive (psSub);
* psSub = NULL;
*/
return psOp;
}
/*/
=======================================================================================================================
* Apply the mid condition for LIB SendInteger
=======================================================================================================================
*/
void ApplyMidCondition_LibSendInteger_id2 (Operation ** apsOp, int nPC, Operation* psM1, Operation* psM2,
Operation* psM3, Operation* psMem, Operation* psM1set, Operation* psM2set) {
Operation* psTemp;
Operation* psFind;
Operation* psSub;
psTemp = NULL;
psFind = NULL;
psSub = NULL;
/*
* For this one, we have lots to do! ;
* channel = sc[nM3] ;
* send = nM2 ;
* BNE noreset nM3 gnLink ;
* ADD sc[nM3] sc[nM3] 1 ;
* BNE noreset nM2 0 ;
* BLE nomax sc[nM3] chanmax ;
* MOV chanmax sc[nM3] ;
* .nomax ;
* MOV sc[nM3] 0 ;
* .noreset ;
* MOV sc[nM3] 0
*/
psFind = CreateVariable ("channel");
/* Should really be dependant on nM3 */
psSub = CreateInteger (0);
apsOp[nPC] = SubstituteOperation (COPY (apsOp[nPC + 1]), psFind, psSub);
FreeRecursive (psFind);
psFind = NULL;
FreeRecursive (psSub);
psSub = NULL;
psTemp = COPY (apsOp[nPC]);
/* MOV chanmax sc[nM3] */
psFind = CreateVariable ("chanmax");
psSub = CreateVariable ("channel");
apsOp[nPC] = SubstituteOperation (COPY (apsOp[nPC]), psFind, psSub);
FreeRecursive (psFind);
psFind = NULL;
FreeRecursive (psSub);
psSub = NULL;
/*
* BLE nomax sc[nM3] chanmax ;
* Branch forwards
*/
psSub = CreateBinary (OPBINARY_GT, CreateVariable ("channel"), CreateVariable ("chanmax"));
apsOp[nPC] = CreateBinary (OPBINARY_LIMP, psSub, apsOp[nPC]);
psSub = CreateBinary (OPBINARY_LE, CreateVariable ("channel"), CreateVariable ("chanmax"));
psSub = CreateBinary (OPBINARY_LIMP, psSub, psTemp);
apsOp[nPC] = CreateBinary (OPBINARY_LAND, apsOp[nPC], psSub);
psSub = NULL;
psTemp = NULL;
/*
* BNE noreset nM2 0 ;
* Branch forwards
*/
psSub = CreateBinary (OPBINARY_EQ, COPY (psM2), CreateInteger (0));
apsOp[nPC] = CreateBinary (OPBINARY_LIMP, psSub, apsOp[nPC]);
psSub = CreateBinary (OPBINARY_NE, COPY (psM2), CreateInteger (0));
psSub = CreateBinary (OPBINARY_LIMP, psSub, COPY (apsOp[nPC + 1]));
apsOp[nPC] = CreateBinary (OPBINARY_LAND, apsOp[nPC], psSub);
psSub = NULL;
/* ADD sc[nM3] sc[nM3] 1 */
psFind = CreateVariable ("channel");
/* Should really be dependant on nM3 */
psSub = CreateBinary (OPBINARY_ADD, CreateVariable ("channel"), CreateInteger (1));
apsOp[nPC] = SubstituteOperation (apsOp[nPC], psFind, psSub);
FreeRecursive (psFind);
psFind = NULL;
/*
* BNE noreset nM3 gnLink ;
* Branch forwards
*/
psSub = CreateBinary (OPBINARY_EQ, COPY (psM3), CreateInteger (gnLink));
apsOp[nPC] = CreateBinary (OPBINARY_LIMP, psSub, apsOp[nPC]);
psSub = CreateBinary (OPBINARY_NE, COPY (psM3), CreateInteger (gnLink));
psSub = CreateBinary (OPBINARY_LIMP, psSub, COPY (apsOp[nPC + 1]));
apsOp[nPC] = CreateBinary (OPBINARY_LAND, apsOp[nPC], psSub);
psSub = NULL;
}
/*/
=======================================================================================================================
* Apply the mid condition for LIB ReceiveInteger
=======================================================================================================================
*/
void ApplyMidCondition_LibReceiveInteger_id2 (Operation ** apsOp, int nPC, Operation* psM1, Operation* psM2,
Operation* psM3, Operation* psMem, Operation* psM1set,
Operation* psM2set) {
Operation* psTemp;
Operation* psFind;
Operation* psMemSub;
Operation* psSub;
psTemp = NULL;
psFind = NULL;
psMemSub = NULL;
psSub = NULL;
/*
* For this one, we have lots to do as well! ;
* channel = sc[nM3] ;
* receive = nM2 ;
* BNE noreceive nM3 gnLink ;
* ADD counter counter 1 ;
* (((counter MOD BUFFERRECEIVELEN) = 0) ;
* -> MOV *address BUFFERRECEIVEEND) ;
* ^ (((counter MOD BUFFERRECEIVELEN) != 0) ;
* -> MOV *address BUFFERRECEIVENUM) ;
* .noreceive ;
* (((counter MOD BUFFERRECEIVELEN) = 0) ;
* -> MOV *address BUFFERRECEIVEEND) ;
* ^ (((counter MOD BUFFERRECEIVELEN) != 0) ;
* -> MOV *address BUFFERRECEIVENUM)
*/
psSub = CreateInteger (BUFFERRECEIVEEND);
psMemSub = CreateTernary (OPTERNARY_SET, CreateMemory (), COPY (psM2set), CreateInteger (BUFFERRECEIVEEND));
psTemp = SubstituteOperationPair (COPY (apsOp[nPC + 1]), psM2, psSub, psMem, psMemSub);
FreeRecursive (psSub);
psSub = NULL;
FreeRecursive (psMemSub);
psMemSub = NULL;
psSub = CreateInteger (BUFFERRECEIVENUM);
psMemSub = CreateTernary (OPTERNARY_SET, CreateMemory (), COPY (psM2set), CreateInteger (BUFFERRECEIVENUM));
psFind = SubstituteOperationPair (COPY (apsOp[nPC + 1]), psM2, psSub, psMem, psMemSub);
FreeRecursive (psSub);
psSub = NULL;
apsOp[nPC] = CreateBinary (OPBINARY_LAND, CreateBinary (OPBINARY_LIMP, CreateBinary (OPBINARY_EQ,
CreateBinary (OPBINARY_MOD, CreateVariable ("counter"), CreateInteger (BUFFERRECEIVELEN)),
CreateInteger (0)), psTemp), CreateBinary (OPBINARY_LIMP, CreateBinary (OPBINARY_NE,
CreateBinary (OPBINARY_MOD, CreateVariable ("counter"), CreateInteger (BUFFERRECEIVELEN)),
CreateInteger (0)), psFind));
psTemp = NULL;
psFind = NULL;
/* ADD counter counter 1 */
psFind = CreateVariable ("counter");
psSub = CreateBinary (OPBINARY_ADD, CreateVariable ("counter"), CreateInteger (1));
apsOp[nPC] = SubstituteOperation (apsOp[nPC], psFind, psSub);
FreeRecursive (psFind);
psFind = NULL;
/*
* BNE noreceive nM3 gnLink ;
* Branch forwards
*/
psSub = CreateBinary (OPBINARY_EQ, COPY (psM3), CreateInteger (gnLink));
apsOp[nPC] = CreateBinary (OPBINARY_LIMP, psSub, apsOp[nPC]);
psSub = CreateBinary (OPBINARY_NE, COPY (psM3), CreateInteger (gnLink));
psSub = CreateBinary (OPBINARY_LIMP, psSub, COPY (apsOp[nPC + 1]));
apsOp[nPC] = CreateBinary (OPBINARY_LAND, apsOp[nPC], psSub);
psSub = NULL;
}
/*/
=======================================================================================================================
* Apply the mid condition for LIB HeapAlloc
=======================================================================================================================
*/
void ApplyMidCondition_LibHeapAlloc_id2 (Operation ** apsOp, int nPC, Operation* psM1, Operation* psM2,
Operation* psM3, Operation* psMem, Operation* psM1set, Operation* psM2set,
int* pnHeapAllocs) {
Operation* psFind;
Operation* psMemSub;
Operation* psSub;
char szTemp[1024];
psFind = NULL;
psMemSub = NULL;
psSub = NULL;
/*
* Add lots more to do here! ;
* MOV nM2 heap ;
* ADD heap[i] heap nM3 ;
* MOV *heap[i] marker ;
* ADD heap heap[i] 1 ;
* Establish a variable for the marker position for this heap
*/
sprintf (szTemp, "heap[%d]", *pnHeapAllocs);
(*pnHeapAllocs)++;
/* ADD heap heap[i] 1 */
psFind = CreateVariable ("heap");
psSub = CreateBinary (OPBINARY_ADD, CreateVariable (szTemp /* "heap[i] */ ), CreateInteger (1));
apsOp[nPC] = SubstituteOperation (COPY (apsOp[nPC + 1]), psFind, psSub);
FreeRecursive (psFind);
psFind = NULL;
FreeRecursive (psSub);
psSub = NULL;
/* MOV *heap[i] marker */
psMemSub = CreateTernary (OPTERNARY_SET, CreateMemory (), CreateVariable (szTemp /* "heap[i] */ ),
CreateVariable ("marker"));
psFind = CreateBinary (OPBINARY_IND, CreateMemory (), CreateVariable (szTemp /* "heap[i] */ ));
psSub = CreateVariable ("marker");
apsOp[nPC] = SubstituteOperationPair (apsOp[nPC], psFind, psSub, psMem, psMemSub);
FreeRecursive (psMemSub);
psMemSub = NULL;
FreeRecursive (psFind);
psFind = NULL;
FreeRecursive (psSub);
psSub = NULL;
/* ADD heap[i] heap nM3 */
psFind = CreateVariable (szTemp /* "heap[i] */ );
psSub = CreateBinary (OPBINARY_ADD, CreateVariable ("heap"), COPY (psM3));
apsOp[nPC] = SubstituteOperation (apsOp[nPC], psFind, psSub);
FreeRecursive (psFind);
psFind = NULL;
FreeRecursive (psSub);
psSub = NULL;
/* MOV nM2 heap */
psMemSub = CreateTernary (OPTERNARY_SET, CreateMemory (), COPY (psM2set), CreateVariable ("heap"));
psSub = CreateVariable ("heap");
apsOp[nPC] = SubstituteOperationPair (apsOp[nPC], psM2, psSub, psMem, psMemSub);
}
|
2b31eb732c1585ee392f9522208bec5f792cd05d | 9fe4ad1541a190f90c72c6d8024ca2190b714626 | /include/argcv/ml/mldef.h | a5155948aa5e5a61ff9025ef07688c7dfbc50e45 | [
"MIT"
] | permissive | yuikns/cmakes | 7224e33bed4e564c8ca6e31f6e8227d9aceca082 | 2e5cdc5c066ae67ac3072364509de1172fe49b82 | refs/heads/master | 2020-04-21T18:43:03.222633 | 2015-04-10T06:36:09 | 2015-04-10T06:36:09 | 24,749,752 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,828 | h | mldef.h | // Copyright 2014 Yu Jing<yujing5b5d@gmail.com>
#ifndef INCLUDE_ARGCV_ML_MLDEF_H_
#define INCLUDE_ARGCV_ML_MLDEF_H_
#include <stdint.h> // uint64_t
#include <string>
#include <vector>
#include <utility> // std::pair, std::make_pair
namespace argcv {
namespace ml {
template <typename X, typename Y>
class DataSet {
public:
DataSet() {}
std::vector< std::pair <std::vector<X>, Y> > data() { return ds; }
virtual ~DataSet() { }
uint64_t size() {
return ds.size();
}
std::pair <std::vector<X>, Y> & operator[](uint64_t pos) {
return ds[pos];
}
std::pair <std::vector<X>, Y> & at(uint64_t pos) {
return ds.at(pos);
}
std::vector<X> & Xat(uint64_t pos) {
return at(pos).first;
}
X & Xat(uint64_t pos, uint64_t off) {
return Xat(pos).at(off);
}
Y & Yat(uint64_t pos) {
return at(pos).second;
}
void add(std::pair <std::vector<X>, Y> ds_item) {
return ds.push_back(ds_item);
}
void add(std::vector<X> x, Y y) {
std::pair<std::vector<X>, Y> val(x, y);
return ds.push_back(val);
}
void add(X x[], int len, Y y) {
std::pair<std::vector<X>, Y> val(
std::vector<X>(x, x + len), y);
return ds.push_back(val);
}
void rm(uint64_t pos) {
ds.erase(ds.begin() + pos);
}
void rm() {
ds.clear();
}
private:
std::vector< std::pair <std::vector<X>, Y> > ds;
};
typedef DataSet<double, int> DDataSet;
typedef DataSet<double, bool> DBDataSet;
typedef DataSet<double, double> DDDataSet;
typedef DataSet<std::string, int> SDataSet;
typedef DataSet<std::string, bool> SBDataSet;
typedef DataSet<std::string, std::string> SSDataSet;
} // namespace ml
} // namespace argcv
#endif // INCLUDE_ARGCV_ML_MLDEF_H_
|
45d30e3d5bbbe8f931b0d0b22ade1d7dffe4991c | 79c4bbdf1695896f0bfd1ad3a36c605c0449442f | /cf/431C.cpp | 9a154f14d4b5350fdaccefd54b89472405cd823e | [] | no_license | jlgm/Algo | 935c130c7f21d1a8d1a5ab29c9b7a1f73dcb9303 | 19e9b4ef0ae5b0f58bc68bb9dae21354c77829e5 | refs/heads/master | 2022-09-24T15:58:59.522665 | 2022-09-15T17:05:42 | 2022-09-15T17:05:42 | 77,110,537 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 897 | cpp | 431C.cpp | #pragma comment(linker, "/STACK:16777216")
#include <bits/stdc++.h>
using namespace std;
#define ms(ar,a) memset(ar, a, sizeof(ar))
#define fr(i,j,k) for (int (i) = (j); (i) < (k); (i)++)
#define db(x) cout << (#x) << " = " << x << endl;
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define MOD 1000000007
typedef long long ll;
typedef pair<int, int> pii;
template <class _T> inline string tostr(const _T& a) { ostringstream os(""); os << a; return os.str(); }
ll n, d, k;
ll dp[105][2];
ll calc(ll N, ll D) {
if (N == 0 && D) return 1;
if (N < 0) return 0;
if (dp[N][D] != -1) return dp[N][D];
int ret = 0;
fr(i,1,k+1) {
ret += (calc(N-i,(i>=d)||D)%MOD);
ret%=MOD;
}
return dp[N][D] = ret%MOD;
}
int main() {
scanf("%lld%lld%lld", &n, &k, &d);
ms(dp,-1);
printf("%lld\n", calc(n,0));
return 0;
}
|
e6be748dc05977bbb50c70b12435eda9130f2722 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /drv/Extrema/Extrema_HArray1OfPOnCurv_0.cxx | 9311b2b3308aa19e139d67920e18e9dcccdc0a2a | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,727 | cxx | Extrema_HArray1OfPOnCurv_0.cxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#include <Extrema_HArray1OfPOnCurv.hxx>
#ifndef _Standard_Type_HeaderFile
#include <Standard_Type.hxx>
#endif
#ifndef _Standard_RangeError_HeaderFile
#include <Standard_RangeError.hxx>
#endif
#ifndef _Standard_DimensionMismatch_HeaderFile
#include <Standard_DimensionMismatch.hxx>
#endif
#ifndef _Standard_OutOfRange_HeaderFile
#include <Standard_OutOfRange.hxx>
#endif
#ifndef _Standard_OutOfMemory_HeaderFile
#include <Standard_OutOfMemory.hxx>
#endif
#ifndef _Extrema_POnCurv_HeaderFile
#include <Extrema_POnCurv.hxx>
#endif
#ifndef _Extrema_Array1OfPOnCurv_HeaderFile
#include <Extrema_Array1OfPOnCurv.hxx>
#endif
IMPLEMENT_STANDARD_TYPE(Extrema_HArray1OfPOnCurv)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY()
STANDARD_TYPE(MMgt_TShared),
STANDARD_TYPE(Standard_Transient),
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_END()
IMPLEMENT_STANDARD_TYPE_END(Extrema_HArray1OfPOnCurv)
IMPLEMENT_DOWNCAST(Extrema_HArray1OfPOnCurv,Standard_Transient)
IMPLEMENT_STANDARD_RTTI(Extrema_HArray1OfPOnCurv)
#define ItemHArray1 Extrema_POnCurv
#define ItemHArray1_hxx <Extrema_POnCurv.hxx>
#define TheArray1 Extrema_Array1OfPOnCurv
#define TheArray1_hxx <Extrema_Array1OfPOnCurv.hxx>
#define TCollection_HArray1 Extrema_HArray1OfPOnCurv
#define TCollection_HArray1_hxx <Extrema_HArray1OfPOnCurv.hxx>
#define Handle_TCollection_HArray1 Handle_Extrema_HArray1OfPOnCurv
#define TCollection_HArray1_Type_() Extrema_HArray1OfPOnCurv_Type_()
#include <TCollection_HArray1.gxx>
|
b470ed231e08588fe6ab5e6eb8c62f581250a573 | 2beec2ffac86c63e9d15669880c18bdc2beeaa37 | /In_Out_Line.h | c7bc2b2423c9fa2c30521b7c0cc97018e6c13514 | [] | no_license | shaniguttman/CEGAR-based-MMC | 1a1e41c053812ad02775b8cc1678a0333c9ae952 | 5962e697cd88424b7dad4e1678f3c8d566caef51 | refs/heads/main | 2023-05-31T09:28:08.350279 | 2021-06-22T20:17:12 | 2021-06-22T20:17:12 | 379,389,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | h | In_Out_Line.h | #pragma once
#include "Header.h"
class In_Out_Line {
private:
int abstractStateIndex;
vector<int> originalStatesIndex;
public:
In_Out_Line()
{
abstractStateIndex = 0;
originalStatesIndex = {};
}
In_Out_Line(int abstractState_index, int originalState_index)
: abstractStateIndex(abstractState_index)
{
originalStatesIndex.push_back(originalState_index);
}
bool setAnotherOriginalState(int originalState_index);
//function to add new original state index
int getAbstractStateIndex();
vector<int> getOriginalStates();
void setAbstractStateIndex(int abstractState);
void delOriginalState(int indexInVector); // Deleting specific original state
}; |
ca96ca231790621892471116634373a17c3140e1 | d4cf36adc556c6b59af133dcd15b0507da2c1648 | /src/adafruithouses.h | 336e2615fec04a7e9cd7aeb7ca6cff31ffcb559a | [] | no_license | buelowp/village | 94b5514dad09ff7e31a8d58597fda8fcc06f1485 | 572ef0f2e8859adb978588d4dfafc1ad1a9459a7 | refs/heads/master | 2023-01-13T16:09:11.505682 | 2020-11-18T20:15:10 | 2020-11-18T20:15:10 | 127,442,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | h | adafruithouses.h | #pragma once
#include <Particle.h>
#include <neopixel.h>
#include "houses.h"
class AdafruitHouses : public Houses {
public:
AdafruitHouses(int, int);
~AdafruitHouses();
void turnOn() override;
bool turnOn(int) override;
bool turnOn(int, uint8_t) override;
void turnOff() override;
bool turnOff(int) override;
bool isOn(int) override;
void setColors(uint8_t r, uint8_t g, uint8_t b) override;
void setColor(uint8_t pin, uint8_t r, uint8_t g, uint8_t b) override;
void setColors(uint8_t r, uint8_t g, uint8_t b, uint8_t w) override;
void setColor(uint8_t pin, uint8_t r, uint8_t g, uint8_t b, uint8_t w) override;
bool isRGBWCapable() override { return true; }
bool allOn();
private:
Adafruit_NeoPixel *m_houses;
int m_leds;
};
|
307abde7cad3c38874f8741abde5cfc3b199b8c7 | f209717a523d0f8841b640d634285a079f52e15d | /Desktop/QT Files/Lab2/main.cpp | 136009b6334b4c0f393ba0092346769e532df82f | [] | no_license | 1genericusername/CSE4345FALL2018 | 3d498e35ee2c7d856187ba9275ca970d04988d01 | 8b56b0c8b382c7d7ffcc485654ad1f690b3d94ff | refs/heads/master | 2020-04-01T02:38:34.577200 | 2018-09-28T05:56:22 | 2018-09-28T05:56:22 | 152,788,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 474 | cpp | main.cpp | #include <iostream>
#include "merge.h"
#include "bubble.h"
#include <cstdio>
#include "insertion.h"
#include "sort.h"
#include "adjmatrix.h"
#include "adjlist.h"
using namespace std;
int main(int argc, char* argv[])
{
Sort Graphs;
Graphs.GrabUserInput(atoi(argv[1]),atoi(argv[2]));
for(int algorithms=0;algorithms<6;algorithms++)
{
for(int graphs=0;graphs<2;graphs++)
{
Graphs.execute(graphs,algorithms);
}
}
}
|
8a5abef91be7dcf138c93e6578bf56fd38ddc9c9 | 0209433f9cd29acc2e2461871579ad646e7218cd | /include/Mapper.h | f1d4132f71cda66c79686911150eae25cb8b341c | [] | no_license | SuperiorNiels/nes-emulator | 529273341622b3cbf2e71f41ebf66522f8f5f147 | a8f8ac47db6922e994cccd916155ad987b5741aa | refs/heads/master | 2023-04-30T10:01:49.512510 | 2021-05-05T09:18:06 | 2021-05-05T09:18:06 | 195,045,952 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | h | Mapper.h | #ifndef NES_MAPPER
#define NES_MAPPER
#include <stdint-gcc.h>
#include "Debug.h"
class Mapper {
public:
Mapper() {};
Mapper(const uint8_t PRG_size, const uint8_t CHR_size)
: PRG_size(PRG_size), CHR_size(CHR_size) {};
virtual uint16_t getMappedPRG(uint16_t addr) = 0;
virtual uint16_t getMappedCHR(uint16_t addr) = 0;
protected:
uint8_t PRG_size = 1, CHR_size = 1;
};
#endif |
9f8abf02e731259241ecec2cef93f4254d99743a | 26b6b814e74e2ad8f6e84140c0b47f95c5906757 | /example.cpp | 5e737f791e7d49ab7a39e6b6e7cf7a208279aee3 | [
"MIT"
] | permissive | alherit/kd-switch-cpp | fe2f739710d168ebddab99eadbe4354658dd366b | 7b99e9e20eeb06fbd93b149c0bd5c5de47965f6e | refs/heads/master | 2020-09-25T02:37:32.247334 | 2020-09-22T13:49:04 | 2020-09-22T13:49:04 | 225,898,723 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,380 | cpp | example.cpp | using namespace std;
#include <cstddef>
#include <cstdlib>
#include <random>
#include <vector>
#include <list>
#include <iostream>
#include <sstream>
#include <fstream>
#include "kds/LogWeightProb.hpp"
#include <chrono>
#include <math.h>
#include "kds/kds.hpp"
int main()
{
auto start = std::chrono::high_resolution_clock::now();
size_t dim = 50;
size_t alphaSize = 2;
std::mt19937 rnd(12345);
vector<double> theta0 = { .5,.5 };
//vector<double> theta0; //empty
KDSForest kds(50, 12345, dim, alphaSize, false, theta0);
std::cout << "Tree created" << endl;
DistT predDist(alphaSize);
LWPT cumCProb(1.);
CountT n = 0;
PointT previous(dim);
std::normal_distribution<> dnorm{ 0, 1 };
std::uniform_int_distribution<> dunif(0, 1);
PointT point(dim);
LabelT label;
while (n < 20000) {
n++;
for (size_t i = 0; i < dim; i++)
point[i] = dnorm(rnd);
label = dunif(rnd);
kds.predict(predDist, point, false);
LWPT condProb = predDist[label];
cumCProb *= condProb;
kds.update(point, label, false);
previous = point;
}
std::cout << "NLL: " << -cumCProb.getLog2() / (FT)n << endl;
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
std::cout << "Elapsed time: " << elapsed.count() << " s\n";
}
|
c3ce1e5c4dfc9e97b6a59da9b8e033cf21dea32d | c5271b18225b183c54526f13ab968b942c5d1c49 | /interviewBit/graph/minimum_weight_cycle_in_an_undirected_graph.cpp | 4e82fd8e9cb57ab9f55cde844ba3431311268e52 | [] | no_license | coderpen-me/competitive_programming | afbc41e0eed12741ba4dcc2650a02e667506739c | 3d8d00b9099871c1b044e1ac3f25cc1eb17dba64 | refs/heads/master | 2021-06-28T09:48:01.156675 | 2021-03-09T19:01:09 | 2021-03-09T19:01:09 | 220,846,911 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,272 | cpp | minimum_weight_cycle_in_an_undirected_graph.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define vi vector<int>
#define vs vector<string>
#define vvi vector<vector<int>>
#define LP(i, n) for (ll i = 0; i < n; i++)
#define LP1(i, n) for (ll i = 1; i <= n; i++)
#define BLP1(i, n) for (ll i = n; i > 0; i--)
#define BLP(i, n) for (ll i = n; i >= 0; i--)
#define el '\n'
#define IOS() \
ios_base::sync_with_stdio(0); \
cin.tie(0);
#define tc() testcases()
#define pvi(A) printvectorint(A)
#define pvs(A) printvectorstring(A)
#define pvvi(A) printvectorvectorint(A)
#define a1(a) cout << a << " ";
#define a2(a, b) cout << a << " " << b << " ";
#define a3(a, b, c) cout << a << " " << b << " " << c << " ";
#define a4(a, b, c, d) cout << a << " " << b << " " << c << " " << d << " ";
#define a5(a, b, c, d, e) cout << a << " " << b << " " << c << " " << d << " " << e << " ";
#define b1(a) cout << a << "\n";
#define b2(a, b) cout << a << " " << b << "\n";
#define b3(a, b, c) cout << a << " " << b << " " << c << "\n";
#define b4(a, b, c, d) cout << a << " " << b << " " << c << " " << d << "\n";
#define b5(a, b, c, d, e) cout << a << " " << b << " " << c << " " << d << " " << e << "\n";
#define nl cout << "\n"
const ll MAXn = 1e5 + 5, MAXlg = __lg(MAXn) + 2;
const ll MOD = 1000000007;
const ll INF = ll(1e15);
void printvectorint(vector<int> A)
{
nl;
for (auto x : A)
{
a1(x);
}
nl;
}
void printvectorstring(vector<string> A)
{
nl;
for (auto x : A)
{
cout << (x);
}
nl;
}
void printvectorvectorint(vector<vector<int>> A)
{
nl;
for (auto x : A)
{
for (auto y : x)
{
a1(y);
}
nl;
}
nl;
}
ll a[MAXn], b[MAXn], c[MAXn], d[MAXn];
ll t = 0, u = 0, v = 0, w = 0, x = 0, y = 0, z = 0;
ll sum = 0, sum1 = 0, mul = 0, subs = 0, test = 0, num = 0, num1 = 0;
//ll aa=0, bb=0, cc=0, dd=0, ee=0;
//ll count=0, ctl=0, ctrl=0, divi=0, flag=0, cal=0, must=0, test=0;
string in;
int testcases()
{
cin >> test;
return test;
}
struct Edge
{
int v;
int u;
int w;
};
class graph
{
int V;
list<pair<int, int>> *adj;
vector<Edge> edge;
public:
graph(int V)
{
this->V = V;
adj = new list<pair<int, int>>[V];
}
void addEdge(int u, int v, int w)
{
adj[u].push_back(make_pair(v, w));
adj[v].push_back(make_pair(u, w));
Edge e{u, v, w};
edge.push_back(e);
}
void removeEdge(int u, int v, int w)
{
adj[u].remove(make_pair(v, w));
adj[v].remove(make_pair(u, w));
}
int shortestPath(int u, int v)
{
set<pair<int, int>> s;
vector<int> dist(V, INT_MAX);
s.insert(make_pair(0, u));
dist[u] = 0;
while(!s.empty()){
pair<int, int> temp = *s.begin();
s.erase(s.begin());
int u = temp.second;
list<pair<int, int>> :: iterator i;
for(i = adj[u].begin(); i != adj[u].end(); i++){
int v = (*i).first;
int w = (*i).second;
if(dist[v] > dist[u] + w){
if(dist[v] != INT_MAX){
s.erase(s.find(make_pair(dist[v], v)));
}
dist[v] = dist[u]+w;
s.insert(make_pair(dist[v], v));
}
}
}
return dist[v];
}
int findMinCycle()
{
int min_cycle = INT_MAX;
int E = edge.size();
for(int i = 0; i < E; i++){
Edge e = edge[i];
removeEdge(e.u, e.v, e.w);
int path = shortestPath(e.u, e.v);
min_cycle = max(min_cycle, path + e.w);
addEdge(e.u, e.v, e.w);
}
return min_cycle;
}
};
int main()
{
IOS();
//t = tc();
t = 1;
while (t--)
{
int A = 4;
vvi B = {{1, 2, 2},
{2, 3, 3},
{3, 4, 1},
{4, 1, 4},
{1, 3, 15}};
graph g(A);
int E = B.size();
for(int i = 0; i < E; i++){
B[i][0]--;B[i][1]--;
g.addEdge(B[i][0], B[i][1], B[i][2]);
}
b1(g.findMinCycle());
}
return 0;
} |
56091a9feb894051e79f978e5b2e7b99b092aaef | 72ece9c2e9897b8854dae50b289b46e79e293963 | /Source/GASBase/Public/Player/GASPlayerController.h | 573d65f881d59c8ba2aa27575f135e8ad6105a71 | [
"MIT"
] | permissive | nik3122/GASBase | 94f5c93c7c4d12f2c06ac7ebef419cb0f4fdd9a9 | 56196381c6734d20d9f12dfafaab537affa9a0d6 | refs/heads/main | 2023-08-27T21:37:02.062607 | 2021-10-30T14:45:41 | 2021-10-30T14:45:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | h | GASPlayerController.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "GASPlayerController.generated.h"
/**
*
*/
UCLASS()
class GASBASE_API AGASPlayerController : public APlayerController
{
GENERATED_BODY()
public:
protected:
private:
public:
AGASPlayerController();
protected:
// Server only
virtual void OnPossess(APawn* InPawn) override;
private:
};
|
972b7e5d97b312431f20332d505afe1ea9ced143 | a5151597cbee56763b596184395eda9a2d696c87 | /Project1/Command.cpp | b6cac3fb795f0bdc4f2e7129451addb226ffd439 | [] | no_license | valeriuvancea/ERTSAssignment3 | 577a9e5c2990cd1e5d2bc7085c32c4d52596a819 | ea395f45ef2bbe741e926b805437813d859947fb | refs/heads/master | 2020-09-11T02:22:30.856835 | 2019-11-22T17:43:32 | 2019-11-22T17:43:32 | 221,908,979 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | cpp | Command.cpp | #include "Command.h"
Command::Command(std::function<void()> action)
{
_action = action;
}
void Command::Execute()
{
_action();
} |
57ec8b5da894f4a12f6fe193faab2ff356ecc813 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Developer/ShaderCompilerCommon/Private/HlslUtils.h | 90c6ea8d8a6836fdc86aa1298d546555ffe89c39 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 6,679 | h | HlslUtils.h | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
HlslUtils.h - Utilities for Hlsl.
=============================================================================*/
#pragma once
#include "CoreMinimal.h"
#define USE_UNREAL_ALLOCATOR 0
#define USE_PAGE_POOLING 0
namespace CrossCompiler
{
namespace Memory
{
struct FPage
{
int8* Current;
int8* Begin;
int8* End;
FPage(SIZE_T Size)
{
check(Size > 0);
Begin = new int8[Size];
End = Begin + Size;
Current = Begin;
}
~FPage()
{
delete[] Begin;
}
static FPage* AllocatePage(SIZE_T PageSize);
static void FreePage(FPage* Page);
};
enum
{
MinPageSize = 64 * 1024
};
}
struct FLinearAllocator
{
FLinearAllocator()
{
auto* Initial = Memory::FPage::AllocatePage(Memory::MinPageSize);
Pages.Add(Initial);
}
~FLinearAllocator()
{
for (auto* Page : Pages)
{
Memory::FPage::FreePage(Page);
}
}
inline void* Alloc(SIZE_T NumBytes)
{
auto* Page = Pages.Last();
if (Page->Current + NumBytes > Page->End)
{
SIZE_T PageSize = FMath::Max<SIZE_T>(Memory::MinPageSize, NumBytes);
Page = Memory::FPage::AllocatePage(PageSize);
Pages.Add(Page);
}
void* Ptr = Page->Current;
Page->Current += NumBytes;
return Ptr;
}
inline void* Alloc(SIZE_T NumBytes, SIZE_T Align)
{
void* Data = Alloc(NumBytes + Align - 1);
UPTRINT Address = (UPTRINT)Data;
Address += (Align - (Address % (UPTRINT)Align)) % Align;
return (void*)Address;
}
/*inline*/ TCHAR* Strdup(const TCHAR* String)
{
if (!String)
{
return nullptr;
}
const auto Length = FCString::Strlen(String);
const auto Size = (Length + 1) * sizeof(TCHAR);
auto* Data = (TCHAR*)Alloc(Size, sizeof(TCHAR));
FCString::Strcpy(Data, Length, String);
return Data;
}
inline TCHAR* Strdup(const FString& String)
{
return Strdup(*String);
}
TArray<Memory::FPage*, TInlineAllocator<8> > Pages;
};
#if !USE_UNREAL_ALLOCATOR
class FLinearAllocatorPolicy
{
public:
// Unreal allocator magic
enum { NeedsElementType = false };
enum { RequireRangeCheck = true };
template<typename ElementType>
class ForElementType
{
public:
/** Default constructor. */
ForElementType() :
LinearAllocator(nullptr),
Data(nullptr)
{}
// FContainerAllocatorInterface
/*FORCEINLINE*/ ElementType* GetAllocation() const
{
return Data;
}
void ResizeAllocation(int32 PreviousNumElements, int32 NumElements, int32 NumBytesPerElement)
{
void* OldData = Data;
if (NumElements)
{
// Allocate memory from the stack.
Data = (ElementType*)LinearAllocator->Alloc(NumElements * NumBytesPerElement,
FMath::Max((uint32)sizeof(void*), (uint32)alignof(ElementType))
);
// If the container previously held elements, copy them into the new allocation.
if (OldData && PreviousNumElements)
{
const int32 NumCopiedElements = FMath::Min(NumElements, PreviousNumElements);
FMemory::Memcpy(Data, OldData, NumCopiedElements * NumBytesPerElement);
}
}
}
int32 CalculateSlackReserve(int32 NumElements, int32 NumBytesPerElement) const
{
return DefaultCalculateSlackReserve(NumElements, NumBytesPerElement, false);
}
int32 CalculateSlackShrink(int32 NumElements, int32 NumAllocatedElements, int32 NumBytesPerElement) const
{
return DefaultCalculateSlackShrink(NumElements, NumAllocatedElements, NumBytesPerElement, false);
}
int32 CalculateSlackGrow(int32 NumElements, int32 NumAllocatedElements, int32 NumBytesPerElement) const
{
return DefaultCalculateSlackGrow(NumElements, NumAllocatedElements, NumBytesPerElement, false);
}
int32 GetAllocatedSize(int32 NumAllocatedElements, int32 NumBytesPerElement) const
{
return NumAllocatedElements * NumBytesPerElement;
}
bool HasAllocation()
{
return !!Data;
}
FLinearAllocator* LinearAllocator;
private:
/** A pointer to the container's elements. */
ElementType* Data;
};
typedef ForElementType<FScriptContainerElement> ForAnyElementType;
};
class FLinearBitArrayAllocator
: public TInlineAllocator<4, FLinearAllocatorPolicy>
{
};
class FLinearSparseArrayAllocator
: public TSparseArrayAllocator<FLinearAllocatorPolicy, FLinearBitArrayAllocator>
{
};
class FLinearSetAllocator
: public TSetAllocator<FLinearSparseArrayAllocator, TInlineAllocator<1, FLinearAllocatorPolicy> >
{
};
template <typename TType>
class TLinearArray : public TArray<TType, FLinearAllocatorPolicy>
{
public:
TLinearArray(FLinearAllocator* Allocator)
{
TArray<TType, FLinearAllocatorPolicy>::AllocatorInstance.LinearAllocator = Allocator;
}
};
/*
template <typename TType>
struct TLinearSet : public TSet<typename TType, DefaultKeyFuncs<typename TType>, FLinearSetAllocator>
{
TLinearSet(FLinearAllocator* InAllocator)
{
Elements.AllocatorInstance.LinearAllocator = InAllocator;
}
};*/
#endif
struct FSourceInfo
{
FString* Filename;
int32 Line;
int32 Column;
FSourceInfo() : Filename(nullptr), Line(0), Column(0) {}
};
struct FCompilerMessages
{
struct FMessage
{
//FSourceInfo SourceInfo;
bool bIsError;
FString Message;
FMessage(bool bInIsError, const FString& InMessage) :
bIsError(bInIsError),
Message(InMessage)
{
}
};
TArray<FMessage> MessageList;
inline void AddMessage(bool bIsError, const FString& Message)
{
auto* NewMessage = new(MessageList) FMessage(bIsError, Message);
}
inline void SourceError(const FSourceInfo& SourceInfo, const TCHAR* String)
{
if (SourceInfo.Filename)
{
AddMessage(true, FString::Printf(TEXT("%s(%d): (%d) %s\n"), **SourceInfo.Filename, SourceInfo.Line, SourceInfo.Column, String));
}
else
{
AddMessage(true, FString::Printf(TEXT("<unknown>(%d): (%d) %s\n"), SourceInfo.Line, SourceInfo.Column, String));
}
}
inline void SourceError(const TCHAR* String)
{
AddMessage(true, FString::Printf(TEXT("%s\n"), String));
}
inline void SourceWarning(const FSourceInfo& SourceInfo, const TCHAR* String)
{
if (SourceInfo.Filename)
{
AddMessage(false, FString::Printf(TEXT("%s(%d): (%d) %s\n"), **SourceInfo.Filename, SourceInfo.Line, SourceInfo.Column, String));
}
else
{
AddMessage(false, FString::Printf(TEXT("<unknown>(%d): (%d) %s\n"), SourceInfo.Line, SourceInfo.Column, String));
}
}
inline void SourceWarning(const TCHAR* String)
{
AddMessage(false, FString::Printf(TEXT("%s\n"), String));
}
};
}
|
753464579a17b968d03aedb078957baf62322cbf | 655202725f7b5eac7bd45a415b333042cd33ef6b | /GameLogic/DamageDealersContainer.h | 376efd2c6b1a43ee9b1883f3d45e8e63fa9988a1 | [] | no_license | BarabasGitHub/DogDealer | 8c6aac914b1dfa54b6e89b0a3727a83d4ab61706 | 41b7d6bdbc6b9c2690695612ff8828f08b1403c7 | refs/heads/master | 2022-12-08T04:25:50.257398 | 2022-11-19T19:31:07 | 2022-11-19T19:31:07 | 121,017,925 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 488 | h | DamageDealersContainer.h | #pragma once
#include <Conventions\EntityID.h>
#include <Utilities\Range.h>
#include <vector>
namespace Logic
{
struct DamageDealersContainer
{
std::vector<uint32_t> entity_to_data;
std::vector<EntityID> entities;
std::vector<float> damage_values;
};
void Add(EntityID damage_dealer, float damage, DamageDealersContainer & self);
void Remove(Range<EntityID const*> entities_to_be_removed, DamageDealersContainer & self);
} |
dc44e9f685e5b9a9eec2ea72491977cd0f5d6183 | 41fcce0c45ebd593dc3f3f4d086d6653964da3ce | /real Game/heart.cpp | 54e5e4f9466c120cf91bc3b3e6283176a8bb2985 | [] | no_license | It5Me/Cookie-Run-Game | 204ae0819183a4ffa8d64fe07ecb7f518f7b9668 | de66c803831a2576e5d41d4f110d5e8d7a2e9dbe | refs/heads/master | 2022-03-23T07:14:59.417462 | 2019-11-26T19:50:21 | 2019-11-26T19:50:21 | 216,511,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 829 | cpp | heart.cpp | #include "heart.h"
heart::heart()
{
object.loadFromFile("Texture/item/heart.png");
body.setTexture(this->object);
this->body.setOrigin(this->object.getSize().x / 2, this->object.getSize().y / 2);
}
void heart::draw(RenderWindow* window)
{
if (this->body.getPosition().x < -200) {
this->visible = false;
}
if (this->visible == true) {
window->draw(this->body);
}
}
void heart::setposition(Vector2f pos)
{
if (pos.x < -200) {
this->visible = false;
}
else {
this->body.setPosition(pos);
this->visible = true;
}
}
bool heart::getstatus()
{
return this->visible;
}
Vector2f heart::gethalfsize()
{
return Vector2f(this->object.getSize().x / 2, this->object.getSize().y / 2);
}
Vector2f heart::getposition()
{
return this->body.getPosition();
}
void heart::move()
{
this->body.move(-8.0f, 0.0f);
}
|
a26a62f194189f281eff3a4eb636b8644dd4e614 | f4f704f309849a8e476bfeffa68b17ac228df04d | /documentation/test_python/search/search/pybind.cpp | 85f8e3409fb91d7db64d468fb52605152f732500 | [
"MIT"
] | permissive | mosra/m.css | 3d0c3c2f7b93039eb529e154e59ff8d91d45e88d | c34e8608973548c5e3d31d65cbfdd5b2fc42a59e | refs/heads/master | 2023-08-17T09:48:14.652793 | 2023-08-09T15:34:09 | 2023-08-09T15:34:09 | 95,897,280 | 414 | 118 | MIT | 2022-10-03T03:52:50 | 2017-06-30T14:42:14 | Python | UTF-8 | C++ | false | false | 670 | cpp | pybind.cpp | #include <pybind11/pybind11.h>
namespace py = pybind11;
namespace {
void function() {}
void functionWithParams(int, float) {}
struct Foo {
void overloadedMethod1(int, float) {}
void overloadedMethod2(int) {}
void overloadedMethod3(int, Foo) {}
};
}
PYBIND11_MODULE(pybind, m) {
m.def("function", &function)
.def("function_with_params", &functionWithParams, py::arg("first"), py::arg("second"));
py::class_<Foo>{m, "Foo"}
.def("overloaded_method", &Foo::overloadedMethod1, py::arg("first"), py::arg("second"))
.def("overloaded_method", &Foo::overloadedMethod2)
.def("overloaded_method", &Foo::overloadedMethod3);
}
|
71f0c64ad9b2defef5fc02517c1635167efcb06e | 7b8c0ec12ac5a7493aaf8fdbef1eedbd75298b60 | /Forager/Forager_Test/Forager_Test/Singleton.h | 5efd1fb0213c1b6939dd99a53a0b49aedf3503bc | [] | no_license | djqandyd1653/Forager | 13ac52611183b5f72b21cdc75da2aa98ed333205 | 2c5e43e956a7afcd86ad4ed178cbb4f7d9dfe522 | refs/heads/main | 2023-04-20T00:19:42.039295 | 2021-05-03T05:35:52 | 2021-05-03T05:35:52 | 326,485,710 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 787 | h | Singleton.h | #pragma once
template <typename T>
class Singleton
{
protected:
//싱글톤 인스턴스 선언
static T* instance;
Singleton() {}
~Singleton() {}
public:
//싱글톤 가져오기
static T* GetSingleton();
//싱글톤 메모리에서 해제하기
void ReleaseSingleton();
};
//싱글톤 초기화
// static 변수 문법상 {} 영역 밖에서 초기화한다.
template <typename T>
T* Singleton<T>::instance = nullptr;
template<typename T>
inline T * Singleton<T>::GetSingleton()
{
// 싱글톤이 없으면 새로 생성하자
if (!instance)
{
instance = new T;
}
return instance;
}
template<typename T>
inline void Singleton<T>::ReleaseSingleton()
{
//싱글톤이 있다면 메모리에서 해제하자
if (instance)
{
delete instance;
instance = 0;
}
} |
ad2d8860308cb2444ad1e27a79ef327ce897b123 | 19782ae15716e723fbfe7cee6fd425a645b6e0fa | /Packt_CreatingGamesWithAI/PackmanLikeGame/PLG_GameObjects/PLG_CharacterControllers/AI/PLG_EnemyAi.cpp | 2eae661cc624e859d04fb10669c05d7924528b73 | [
"MIT"
] | permissive | PacktPublishing/Hands-On-Game-AI-Development | b91ff950472694b82c53b76a41ba98f4a96debe2 | 27328e4658bfd1606abe51cc14a8adbe8c752d76 | refs/heads/master | 2021-04-26T22:18:45.786513 | 2021-01-14T15:40:01 | 2021-01-14T15:40:01 | 124,068,805 | 9 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 8,232 | cpp | PLG_EnemyAi.cpp | //
// PLG_EnemyAi.cpp
// Packt_CreatingGamesWithAI
//
// Created by Cihan Ozer on 01/10/2018.
// Copyright © 2018 Cihan Ozer. All rights reserved.
//
#include "PLG_EnemyAi.hpp"
#include "PLG_Commons.hpp"
#include "BoxCollider.hpp"
#include "PLG_GameWorldInfo.hpp"
#include "Timer.hpp"
PLG_EnemyAi::PLG_EnemyAi()
: GameCharacterController(), mDoesHavePositionTarget(false), mCanSeePlayer(false), mIsPlayerClose(false), mIsAlarmed(false),
mIsInStoppingProcess(false), mPathPositionIndex(-1), mTimeToStop(0.f), mCurrentStopTime(0.f), mDecisionTimeLimit(0.3f), mCurrentDecisionTime(0.f)
{
mBoundingRadius = 100.f;
mCollider = std::make_unique<BoxCollider>(ePLG_COLLIDER_TYPES::ENEMY, this, getColliderMin(), getColliderMax() );
mStateMachine.initObject(1, this);
mStateMachine.changeState(&mWanderingState);
mMovingObjectReference = &mCharacter;
mPathPlanner.setOwnner(this);
}
PLG_EnemyAi::PLG_EnemyAi(const float pPosX, const float pPosY)
: GameCharacterController(), mDoesHavePositionTarget(false), mCanSeePlayer(false), mIsPlayerClose(false), mIsAlarmed(false),
mIsInStoppingProcess(false), mPathPositionIndex(-1), mTimeToStop(0.f), mCurrentStopTime(0.f), mDecisionTimeLimit(0.3f), mCurrentDecisionTime(0.f)
{
mBoundingRadius = 100.f;
mCharacter.initObject(2, pPosX, pPosY);
mCollider = std::make_unique<BoxCollider>(ePLG_COLLIDER_TYPES::ENEMY, this, getColliderMin(), getColliderMax() );
mStateMachine.initObject(1, this);
mStateMachine.changeState(&mWanderingState);
mCharacter.initObject(2, pPosX, pPosY);
mMovingObjectReference = &mCharacter;
mPathPlanner.setOwnner(this);
}
void PLG_EnemyAi::performInit(const int pArgNumber, va_list args)
{
float posX = va_arg(args, double);
float posY = va_arg(args, double);
mCharacter.initObject(2, posX, posY);
mCollider->setMaxPos( getColliderMax() );
mCollider->setMinPos( getColliderMin() );
}
void PLG_EnemyAi::reset()
{
mDoesHavePositionTarget = false;
mCanSeePlayer = false;
mIsPlayerClose = false;
mIsAlarmed = false;
mIsInStoppingProcess = false;
mTimeToStop = 0.f;
mCurrentStopTime = 0.f;
resetPathTracking();
changeState(eENEMY_STATES::eES_WanderAround);
}
glm::vec2 PLG_EnemyAi::getColliderMin()
{
auto posX = mCharacter.getPosition().x;
auto posY = mCharacter.getPosition().y;
return glm::vec2(posX + 1, posY + 1);
}
glm::vec2 PLG_EnemyAi::getColliderMax()
{
auto posX = mCharacter.getPosition().x;
auto posY = mCharacter.getPosition().y;
return glm::vec2(posX + mCharacter.getWidth() - 1, posY + mCharacter.getHeight() - 1);
}
void PLG_EnemyAi::changeState(const eENEMY_STATES pNewStateRequest)
{
switch (pNewStateRequest)
{
case eENEMY_STATES::eES_WanderAround:
mStateMachine.changeState(&mWanderingState);
break;
case eENEMY_STATES::eES_SearchPlayer:
mStateMachine.changeState(&mSearchPlayerState);
break;
case eENEMY_STATES::eES_AlarmOthers:
mStateMachine.changeState(&mAlarmOthersState);
break;
}
}
void PLG_EnemyAi::callOnFrame()
{
mCollider->clearCollided();
mLastPos = mCharacter.getPosition();
monitorSelf();
mStateMachine.callOnFrame();
mCharacter.callOnFrame();
mCollider->setMaxPos( getColliderMax() );
mCollider->setMinPos( getColliderMin() );
}
void PLG_EnemyAi::callOnRender(std::vector<Texture*>& mTextures)
{
mCharacter.callOnRender(mTextures);
}
void PLG_EnemyAi::onCollision(const Collider* pObject)
{
if(pObject->getType() == ePLG_COLLIDER_TYPES::WALL)
{
rewindPosition();
}
else if(pObject->getType() == ePLG_COLLIDER_TYPES::ALARM && isPlayerSeen() )
{
PLG_GameWorldInfo::getInstance().isAlarmOn = true;
}
}
void PLG_EnemyAi::chooseNewRandomPath()
{
resetPathTracking();
if( mPathPlanner.requestRandomPath(mPathPositions) )
{
handleMovement();
}
}
void PLG_EnemyAi::setPathToAlarm()
{
resetPathTracking();
if( mPathPlanner.requestPathToPosition(PLG_GameInfo.alarmPosition, mPathPositions) )
{
handleMovement();
}
}
void PLG_EnemyAi::setPathToPlayer()
{
resetPathTracking();
if( mPathPlanner.requestPathToPosition(PLG_GameInfo.playerPosition, mPathPositions) )
{
handleMovement();
}
}
void PLG_EnemyAi::resetPathTracking()
{
mIsInStoppingProcess = false;
mPathPositionIndex = -1;
mPathPositions.clear();
mCharacter.getLocomotion()->clearMovement();
}
void PLG_EnemyAi::handleMovement()
{
mPathPositionIndex = 0;
updateMovementDirection();
}
void PLG_EnemyAi::updateMovementDirection()
{
auto dir = glm::normalize( mPathPositions[mPathPositionIndex] - getPosition() );
if(std::fabsf(dir.x) > std::fabsf(dir.y))
{
// Left or right
if(dir.x > MathCommons::EPSILON)
{
// Right
mCharacter.getLocomotion()->setMovement(Locomotion<PLG_CircleCharacter>::eTRANSLATION_DIRECTION::eTD_RIGHT);
}
else
{
// Left
mCharacter.getLocomotion()->setMovement(Locomotion<PLG_CircleCharacter>::eTRANSLATION_DIRECTION::eTD_LEFT);
}
}
else
{
// Up or down, (or equal)
if(dir.y > MathCommons::EPSILON)
{
// Down
mCharacter.getLocomotion()->setMovement(Locomotion<PLG_CircleCharacter>::eTRANSLATION_DIRECTION::eTD_BACKWARD);
}
else
{
// Up
mCharacter.getLocomotion()->setMovement(Locomotion<PLG_CircleCharacter>::eTRANSLATION_DIRECTION::eTD_FORWARD);
}
}
}
void PLG_EnemyAi::monitorSelf()
{
if(PLG_GameWorldInfo::getInstance().isAlarmOn)
{
mIsAlarmed = true;
}
if(mPathPositions.empty())
{
mDoesHavePositionTarget = false;
}
else if( !mDoesHavePositionTarget )
{
mDoesHavePositionTarget = true;
}
// Check whether the agent sees the player
auto dirToPlayer = glm::normalize( ( PLG_GameInfo.playerPosition - mCharacter.getPosition() ) );
auto dot = glm::dot(dirToPlayer, mCharacter.getHeadingVector() );
if( glm::distance(PLG_GameInfo.playerPosition, mCharacter.getPosition()) < (WINDOW_WIDTH / 2) && MathCommons::definitelyGreaterThan(dot, 0.98f) )
{
mCanSeePlayer = true;
}
if(mCanSeePlayer && glm::distance(PLG_GameInfo.playerPosition, mCharacter.getPosition() ) < 200.f)
{
mIsPlayerClose = true;
}
else if(mIsPlayerClose)
{
mIsPlayerClose = false;
}
if(mIsInStoppingProcess)
{
if( mCurrentStopTime > mTimeToStop)
{
mMovingObjectReference->setPosition(mStopPosition);
mIsInStoppingProcess = false;
if(mPathPositionIndex < mPathPositions.size())
{
// Still way to go
updateMovementDirection();
}
else
{
resetPathTracking();
}
}
else
{
mCurrentStopTime += Time.deltaTime;
}
}
else
{
if(mPathPositionIndex > -1)
{
if( isAtThePosition(mPathPositions[mPathPositionIndex], getPosition()) )
{
startStoppingProcess(mPathPositions[mPathPositionIndex]);
mPathPositionIndex++;
}
}
}
}
void PLG_EnemyAi::startStoppingProcess(const glm::vec2& pPosition)
{
mIsInStoppingProcess = true;
mCurrentStopTime = 0.f;
mStopPosition = pPosition;
mTimeToStop = (glm::distance(mStopPosition, getPosition()) / mCharacter.getDefaultSpeed() );
}
bool PLG_EnemyAi::isAtThePosition(const glm::vec2& pPosI, const glm::vec2& pPosII)
{
const float epsilon = 100.f;
auto dist = glm::distance( pPosI, pPosII );
return ( dist < epsilon );
}
void PLG_EnemyAi::rewindPosition()
{
mCharacter.setPosition(mLastPos);
mCollider->setMaxPos( getColliderMax() );
mCollider->setMinPos( getColliderMin() );
}
|
16ba6eabccf19240c37f4aabda552ebba028c0e5 | f80a71a58c3166a6230f76868034632ccd46a68f | /test.cpp | 4e64d67c3569bb0c6a520a0949e9d8409a9e0af9 | [] | no_license | scale/scale-emkt-cpp | e7f91ce9995b14d455b8ad99ba8978b0b994f5a9 | 95064d8bb2624ff8df1655c7921817def79fce38 | refs/heads/master | 2020-04-10T12:20:32.920817 | 2016-01-19T15:02:11 | 2016-01-19T15:02:11 | 620,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,270 | cpp | test.cpp | /***************************************************************************
* Copyright (C) 2003 by eddiedu *
* eddiedu@scale.com.br *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "unistd.h"
#include "global.h"
#include "Pointer.h"
#include "PecaHandler.h"
#include "DNS.h"
#include "Mailer.h"
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
debug.info("Iniciando o PROGRAMA DE ENVIO!");
std::vector<std::string> ddv;
DNS::server = DNS;
DNS _dns;
_dns.GetMX(ddv, "hotmail.com");
for_each( ddv.begin(), ddv.end(), print_string);
return 0;
}
void print_string(const std::string& name) {
cout << name << endl;
}
|
a956fbf2184c9c87dc433db3e0ba0db06518a32e | 445b7ee58c3349e720da93660a98ed8f3b501e5d | /POJ/p1623.cpp | bbf3b7814db780e5f64861396f5a935554730708 | [] | no_license | y761823/ACM-code | d151da28121c55e6c081a371e71d3cdd25453bf9 | d2e0a46d7fd29efacdb92cd3785fbd1962f425a0 | refs/heads/master | 2022-08-08T19:20:55.275233 | 2022-07-31T06:29:19 | 2022-07-31T06:29:19 | 35,432,112 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,094 | cpp | p1623.cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
#define FOR(i, a, b) for(int i = a; i <= b; ++i)
const int MAXN = 128 + 1;
struct Node {
int son[4], sz;
int hash;
} p[MAXN * MAXN * 8];
char mat[MAXN][MAXN];
int ans1, ans2, n, m, pcnt;
void init() {
ans1 = ans2 = pcnt = 0;
memset(mat, 0, sizeof(mat));
}
int check(int x1, int y1, int x2, int y2) {
char t = mat[x1][y1];
FOR(i, x1, x2) FOR(j, y1, y2) if(t != mat[i][j]) return -1;
return t == '1';
}
void dfs(int &r, int x1, int y1, int x2, int y2) {
++ans1;
int res = check(x1, y1, x2, y2);
int s_cnt = p[r = pcnt++].hash = 0;
p[r].sz = 1;
p[r].hash = res;
if(res == -1) {
int midX = (x1 + x2) >> 1, midY = (y1 + y2) >> 1, mid = ((x2 - x1) >> 1) + 1;
FOR(i, 0, 1) FOR(j, 0, 1) {
dfs(p[r].son[s_cnt], x1 + i * mid, y1 + j * mid, midX + i * mid, midY + j * mid);
p[r].sz += p[p[r].son[s_cnt++]].sz;
}
}
}
bool same(int r1, int r2) {
if(p[r1].sz != p[r2].sz || p[r1].hash != p[r2].hash) return false;
if(p[r1].hash != -1) return true;
for(int i = 0; i < 4; ++i) {
if(!same(p[r1].son[i], p[r2].son[i])) return false;
}
return true;
}
bool exist(int r) {
for(int i = 0; i < r; ++i)
if(same(i, r)) return true;
return false;
}
void solve(int r) {
if(p[r].sz == 1) return ;
if(exist(r)) {
ans2 += p[r].sz;
} else {
for(int i = 0; i < 4; ++i) solve(p[r].son[i]);
}
}
int expand(int x) {
for(int i = 1; i <= 128; i <<= 1)
if(x <= i) return i;
return 128;
}
int main() {
while(scanf("%d%d", &n, &m) != EOF) {
if(n == 0 && m == 0) break;
init();
for(int i = 0; i < n; ++i) scanf("%s", mat[i]);
n = expand(max(n, m));
FOR(i, 0, n - 1) FOR(j, 0, n - 1)
if(mat[i][j] == 0) mat[i][j] = '0';
int root;
dfs(root, 0, 0, n - 1, n - 1);
solve(root);
printf("%d %d\n", ans1, ans1 - ans2);
}
}
|
9428f54b7cb734e66cb34b113f3a9b57506c8d61 | 1ec1e5888e720778a7f018b3b170c6a63b37f8e1 | /server/BaseCacheManager.h | 1963cd170fefa3c04f5d01d81710ce430e6b7588 | [] | no_license | 02JanDal/JansGameFramework | f3f9fbb988655946a6e9f74c67bda5dfd22c58c4 | f2bebb60e2688ac3cca315f07e72daccdeacf0d2 | HEAD | 2016-09-06T17:27:23.733773 | 2014-02-23T17:19:43 | 2014-02-23T17:19:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 235 | h | BaseCacheManager.h | #pragma once
#include <QObject>
namespace Cache
{
class BaseCacheManager : public QObject
{
Q_OBJECT
public:
virtual ~BaseCacheManager();
static BaseCacheManager *instance;
protected:
BaseCacheManager(QObject *parent = 0);
};
}
|
6b3d66a8e80b2eeaf47ebab7129e513968185cb5 | 0d55d09d4410d9be81d5f0fc1f3106324a364fc8 | /GameX/Classes/CSensor.cpp | 8d402af0ba20389a632bffbbf6d23a073f9210e2 | [] | no_license | gdmec/GameX | bbcfbb8af78716fddb0876db00f5efcb7116257d | 3ab54fc28df1299653ae577e6150ceb5f94e4bb3 | refs/heads/master | 2020-04-29T08:19:34.528565 | 2014-01-08T03:57:09 | 2014-01-08T03:57:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 987 | cpp | CSensor.cpp | //
// CSensor.cpp
// GameX
//
// Created by 马 俊 on 13-6-10.
//
//
#include "CSensor.h"
#include "CVisibleObject.h"
CSensor::CSensor()
: m_pOwner(nullptr)
, m_TriggerHandler(nullptr)
, m_collisionGroup(0)
{
}
CSensor::~CSensor()
{
}
void CSensor::collideWithObject(TFCollisionProtocol* obj)
{
if (m_pOwner && m_TriggerHandler)
{
(m_pOwner->*m_TriggerHandler)(dynamic_cast<Object*>(obj));
}
}
GBCollisionType CSensor::getCollisionType()
{
return CT_SENSOR;
}
void CSensor::setSensorTargetType(GBCollisionType type)
{
addCollisionHandler(type, collision_handler_selector(CSensor::collideWithObject));
}
void CSensor::setOwnerAndTrigger(CVisibleObject* owner, SEL_CallFuncO trigger)
{
m_pOwner = owner;
m_TriggerHandler = trigger;
if (m_pOwner)
{
m_collisionGroup = m_pOwner->getCollisionGroup();
}
turnOnCollision();
}
int CSensor::getCollisionGroup()
{
return m_collisionGroup;
}
|
9f2edb751dab216ffa16caf62c593302b066c3d2 | 3d07f3247b027a044f90eee1c744e91a98951dde | /humanoid_walking/src/LipWalkNode.cpp | 51acfa41268597cf7192aac6fb885aef8935d5e9 | [] | no_license | murilomend/humanoid_movement | f93d2ab66fbbfaaff7d4cc906df338e36ce36ea3 | e657538b1d239b8df63ff03875155687a93f5d21 | refs/heads/master | 2020-03-26T08:39:47.810954 | 2018-08-14T12:01:07 | 2018-08-14T12:01:07 | 144,714,031 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,013 | cpp | LipWalkNode.cpp | #include "humanoid_walking/LipWalkNode.h"
LipWalkNode::LipWalkNode(ros::NodeHandle nh_,ros::NodeHandle nh_private_,ros::NodeHandle nh_private_params_,ros::NodeHandle nh_private_cmd_,ros::NodeHandle nh_private_ctrl_) : nh(nh_) , nh_private(nh_private_), nh_private_params(nh_private_params_), nh_private_cmd(nh_private_cmd_), nh_private_ctrl(nh_private_ctrl_)
{
//Parameter Server
if (!nh_private_params.getParam("tS", tS))
tS = 0.3; // 0.8 s
if (!nh_private_params.getParam ("tD", tD))
tD = 0.1; // 0.0 s
if (!nh_private_params.getParam ("zCCorr", zCCorr))
zCCorr = 1;
if (!nh_private_params.getParam ("stepH", stepH))
stepH = 0.05; //0.05 m
if (!nh_private_ctrl.getParam ("delayR", delayR))
delayR = 1; // 1
if (!nh_private_ctrl.getParam ("delayL", delayL))
delayL = 1; // 1
if (!nh_private_ctrl.getParam ("delayAll", delayAll))
delayAll = 1; // 1
if (!nh_private_ctrl.getParam ("timeFac", timeFac))
timeFac = 1; // 1
if (!nh_private_params.getParam ("dt", dt))
dt = 0.07; // 0.07 s
if (!nh_private_params.getParam ("lip_dt", lip_dt))
lip_dt = 0.005; // 0.005 s
if (!nh_private_cmd.getParam ("vx", vx))
vx = 0; // 0 m/s
if (!nh_private_cmd.getParam ("vy", vy))
vy = 0; // 0 m/s
if (!nh_private_cmd.getParam ("vz", vz))
vz = 0; // 0 deg/s
if (!nh_private_cmd.getParam ("walk_flag", walk_flag))
walk_flag = false; // false
if (!nh_private_params.getParam ("curve", curve))
curve = SINE_2;
walking_flag = walk_flag;
delayAllChanged = false;
delayRLChanged = false;
//Publisher Stuff
lipTopic = nh.advertise<humanoid_msgs::LipFeedBack>("humanoid_walking/lipFeedback", 1000);
paramsTopic = nh.advertise<humanoid_msgs::LipParamsMsg>("humanoid_walking/walking_params_state", 1000);
endEffTopic = nh.advertise<humanoid_msgs::EndEffStateMsg>("humanoid_model/endEffState", 1000);
//Subscriber Stuff
ctrlSubPtr.reset(new ctrlSub(nh,"humanoid_control/cmd",1));
ctrlSubPtr->registerCallback(&LipWalkNode::ctrlCallback, this);
humanoidPropsSubPtr.reset(new HumanoidPropsSub(nh,"humanoid_model/humanoid_properties",1));
humanoidPropsSubPtr->registerCallback(&LipWalkNode::humanoidPropsCallback, this);
walkingSubPtr.reset(new WalkingSub(nh,"humanoid_walking/cmd",1));
walkingSubPtr->registerCallback(&LipWalkNode::walkingCallback, this);
//Service Stuff
paramsSrv = nh.advertiseService("humanoid_walking/walking_params",&LipWalkNode::updateWalkingParams,this);
cmdSrv = nh.advertiseService("humanoid_walking/walking_cmd",&LipWalkNode::walkingCmd,this);
humanoidPropsCli = nh.serviceClient<humanoid_msgs::LoadHumanoidPropertiesSrv>("humanoid_model/properties");
//Dynamic Reconfigure Server
config_server_params.reset(new HumanoidLipWalkingParamsConfigServer(nh_private_params));
HumanoidLipWalkingParamsConfigServer::CallbackType f_params = boost::bind(&LipWalkNode::reconfigParamsCallback, this, _1, _2);
config_server_params->setCallback(f_params);
config_server_cmd.reset(new HumanoidLipWalkingCmdConfigServer(nh_private_cmd));
HumanoidLipWalkingCmdConfigServer::CallbackType f_cmd = boost::bind(&LipWalkNode::reconfigCmdCallback, this, _1, _2);
config_server_cmd->setCallback(f_cmd);
config_server_ctrl.reset(new HumanoidLipWalkingCtrlConfigServer(nh_private_ctrl));
HumanoidLipWalkingCtrlConfigServer::CallbackType f_ctrl = boost::bind(&LipWalkNode::reconfigCtrlCallback, this, _1, _2);
config_server_ctrl->setCallback(f_ctrl);
footCom = Eigen::Vector3d(0,0,0);
refCom = Eigen::Vector3d(0,0,0);
sinFreq = 1;
sinAmp = 0;
sinPhase = 0;
tSin = 0;
nSin = 0;
tNormSin = 0;
startedLip= false;
lipUpdate = true;
configHumanoidNode(true);
initWalkingSettings();
initPosition();
if(delayR != 1 || delayL != 1) delayRLChanged = true;
if(delayAll != 1) delayAllChanged = true;
//Run Callback
timerLip = nh.createTimer(ros::Duration(lip_dt), &LipWalkNode::runCallBackLip,this);
timerSend = nh.createTimer(ros::Duration(dt), &LipWalkNode::runCallBackSend,this);
}
LipWalkNode::~LipWalkNode()
{
}
void LipWalkNode::initWalkingSettings()
{
//void pointMsgToEigen(const geometry_msgs::Point &m, Eigen::Vector3d &e);
//void pointEigenToMsg(const Eigen::Vector3d &e, geometry_msgs::Point &m);
humanoidPropsMsg.request.calcCOM = true;
humanoidPropsMsg.request.setComAsIkRef = true;
humanoidPropsCli.call(humanoidPropsMsg);
tf::pointMsgToEigen(humanoidPropsMsg.response.footComPoint, footCom);
double zC = MathUtils::absf(footCom(2));
double legDist = MathUtils::absf(footCom(1))*2;
double xOffset = MathUtils::absf(footCom(0));
robotLip = LipWalk(tS,tD,zC,legDist,xOffset,stepH,zCCorr,lip_dt,curve);
rFoot = BodyPointState(RLEG,BP_TOUCHING);
lFoot = BodyPointState(LLEG,BP_TOUCHING);
trunk = BodyPointState(TRUNK,BP_FREE);
vecBody.resize(3);
robotLip.joystick(0,0,0);
//Stabilize LIP
robotLip.stabilize();
tNormSin = robotLip.tNormAll;
ROS_INFO("[LIP_WALK] Walking Parameters Initialized");
ROS_INFO("[LIP_WALK] TS: %4.3f",tS);
ROS_INFO("[LIP_WALK] TD: %4.3f",tD);
ROS_INFO("[LIP_WALK] zC: %4.3f",zC);
ROS_INFO("[LIP_WALK] zCCorr: %4.3f",zCCorr);
ROS_INFO("[LIP_WALK] legDist: %4.3f",legDist);
ROS_INFO("[LIP_WALK] xOffset: %4.3f",xOffset);
ROS_INFO("[LIP_WALK] DT: %4.3f",lip_dt);
ROS_INFO("[LIP_WALK] CURVE: %d",curve);
}
void LipWalkNode::initPosition()
{
robotLip.calcLIP();
robotLip.updateComFoot();
lFoot.pos = robotLip.lFoot;
lFoot.rot = robotLip.lFootTeta;
rFoot.pos = robotLip.rFoot;
rFoot.rot = robotLip.rFootTeta;
vecBody[0] = rFoot;
vecBody[1] = lFoot;
vecBody[2] = trunk;
sendGoal(vecBody,dt);
send2Topic();
}
void LipWalkNode::configHumanoidNode(bool lipBool)
{
conf.bools.clear();
bool_param.name = "calcIK";
bool_param.value = lipBool;
conf.bools.push_back(bool_param);
srv_req.config = conf;
ros::service::call("/humanoid_model/set_parameters", srv_req, srv_resp);
}
void LipWalkNode::reconfigParamsCallback(humanoid_msgs::HumanoidLipWalkingParamsConfig& config, uint32_t level)
{
boost::mutex::scoped_lock lock(mutex_params);
if(tS != config.tS || tD != config.tD || zCCorr != config.zCCorr || stepH != config.stepH || curve != config.stepH)
{
tS = config.tS;
tD = config.tD;
zCCorr = config.zCCorr;
stepH = config.stepH;
curve = config.curve;
lipUpdate = true;
}
sinAmp = config.sinAmp;
sinFreq = config.sinFreq;
sinPhase = config.sinPhase;
dt = config.dt;
lip_dt = config.lip_dt;
timerSend.setPeriod(ros::Duration(dt));
timerLip.setPeriod(ros::Duration(lip_dt));
}
void LipWalkNode::reconfigCmdCallback(humanoid_msgs::HumanoidLipWalkingCmdConfig& config, uint32_t level)
{
boost::mutex::scoped_lock lock(mutex_cmd);
vx = config.vx;
vy = config.vy;
vz = config.vz;
slope = config.slope;
walk_flag = config.walk_flag;
//walking_flag = walk_flag;
ROS_INFO("[LIP_WALK] Walking CMDs Updated");
ROS_INFO("[LIP_WALK] Vx : %4.3f Vy: %4.3f Vz: %4.3f",vx,vy,vz);
}
void LipWalkNode::reconfigCtrlCallback(humanoid_msgs::HumanoidLipWalkingCtrlConfig& config, uint32_t level)
{
boost::mutex::scoped_lock lock(mutex_ctrl);
if(delayR != config.delayR || delayL != config.delayL )
{
delayR = config.delayR;
delayL = config.delayL;
delayRLChanged = true;
delayAllChanged = false;
}
if(delayAll != config.delayAll)
{
delayAll = config.delayAll;
delayAllChanged = true;
delayRLChanged = false;
}
ROS_INFO("[LIP_WALK] Walking CTRL Updated");
ROS_INFO("[LIP_WALK] delayR : %4.3f delayL: %4.3f delayAll: %4.3f",delayR,delayL,delayAll);
}
void LipWalkNode::runCallBackLip(const ros::TimerEvent&)
{
if(walking_flag)
{
if(walk_flag) robotLip.joystick(vx,vy,vz);
else robotLip.joystick(0,0,0);
robotLip.calcLIP();
//std::cout << "TNORM: " << robotLip.tNorm << " TNORMALL: " << robotLip.tNormAll << std::endl;
robotLip.updateComFoot();
if(humanoidCtrlMsg.phase_ctrl_flag == false)
{
humanoidCtrlMsg.phaseFac = 0.;
}
if(robotLip.wState == SINGLE_SUPPORT && delayRLChanged)
{
if(robotLip.footAir == LEFT_FOOT) timeFac = delayL;
if(robotLip.footAir == RIGHT_FOOT) timeFac = delayR;
delayAllChanged = false;
//ROS_WARN("TIMEFAC: %4.3f PHASEFAC: %4.3f",timeFac,humanoidCtrlMsg.phaseFac);
timerLip.setPeriod(ros::Duration(timeFac*lip_dt*(0.5*(humanoidCtrlMsg.phaseFac)/2. + 1.0)));
//send2Topic();
}
if(delayAllChanged)
{
timeFac = delayAll;
delayRLChanged = false;
//ROS_WARN("TIMEFAC: %4.3f PHASEFAC: %4.3f",timeFac,humanoidCtrlMsg.phaseFac);
timerLip.setPeriod(ros::Duration(timeFac*lip_dt*(0.5*(humanoidCtrlMsg.phaseFac)/2. + 1.0)));
//send2Topic();
}
if(humanoidCtrlMsg.slope_ctrl_flag) slope = humanoidCtrlMsg.slope;
robotLip.floorIncl = (slope/180.)*PI;
}
else
{
robotLip.stabilize();
tNormSin = robotLip.tNormAll;
}
if(!walk_flag)
{
if(robotLip.stabilized()) walking_flag = false;
}
else
{
walking_flag = true;
}
if(lipUpdate)
{
double zC = MathUtils::absf(footCom(2));
double legDist = MathUtils::absf(footCom(1))*2;
double xOffset = MathUtils::absf(footCom(0));
robotLip.updateParams(tS,tD,zC,legDist,xOffset,stepH,zCCorr);
robotLip.curve = curve;
robotLip.stabilize();
tNormSin = robotLip.tNormAll;
robotLip.updateComFoot();
ROS_INFO("[LIP_WALK] Walking Parameters Updated");
ROS_INFO("[LIP_WALK] TS: %4.3f",tS);
ROS_INFO("[LIP_WALK] TD: %4.3f",tD);
ROS_INFO("[LIP_WALK] zC: %4.3f",zC);
ROS_INFO("[LIP_WALK] zCCorr: %4.3f",zCCorr);
ROS_INFO("[LIP_WALK] legDist: %4.3f",legDist);
ROS_INFO("[LIP_WALK] xOffset: %4.3f",xOffset);
ROS_INFO("[LIP_WALK] DT: %4.3f",lip_dt);
ROS_INFO("[LIP_WALK] CURVE: %d",curve);
send2Topic();
lipUpdate =false;
}
}
void LipWalkNode::runCallBackSend(const ros::TimerEvent&)
{
lFoot.pos = robotLip.lFoot;
lFoot.rot = robotLip.lFootTeta;
rFoot.pos = robotLip.rFoot;
rFoot.rot = robotLip.rFootTeta;
trunk.rot(1) = sin((robotLip.tNormAll + sinPhase)*3.14159*floor(sinFreq))*sinAmp;
vecBody[2] = trunk;
vecBody[0] = rFoot;
vecBody[1] = lFoot;
if(!walk_flag)
{
/*vecBody[2] = trunk;
vecBody[0].pos = Eigen::Vector3d(rFoot.pos;
vecBody[1] = lFoot;*/
}
sendGoal(vecBody,dt);
send2Topic();
}
bool LipWalkNode::updateWalkingParams(humanoid_msgs::LipParamsSrv::Request ¶ms,
humanoid_msgs::LipParamsSrv::Response &res)
{
if(params.get_params)
{
res.tS = tS;
res.tD = tD;
res.stepH = stepH;
res.zCCorr = zCCorr;
res.delayR = delayR;
res.delayL = delayL;
res.delayAll = delayAll;
res.vx = vx;
res.vy = vy;
res.vz = vz;
}
else
{
tS = params.tS;
tD = params.tD;
stepH = params.stepH;
zCCorr = params.zCCorr;
lipUpdate = true;
}
return true;
}
bool LipWalkNode::walkingCmd(humanoid_msgs::LipCmdSrv::Request &cmd,
humanoid_msgs::LipCmdSrv::Response &res)
{
ROS_INFO("[LIP_WALK] Walking CMDs Updated");
ROS_INFO("[LIP_WALK] Vx : %4.3f Vy: %4.3f Vz: %4.3f",cmd.vx,cmd.vy,cmd.vz);
vx = cmd.vx;
vy = cmd.vy;
vz = cmd.vz;
walk_flag = cmd.walk_flag;
reset_walk = cmd.reset_walk;
return true;
}
void LipWalkNode::ctrlCallback(const humanoid_msgs::HumanoidControlMsgPtr &ctrl)
{
humanoidCtrlMsg = *ctrl;
}
void LipWalkNode::walkingCallback(const humanoid_msgs::WalkingMsgPtr &msg)
{
vx = msg->vx;
vy = msg->vy;
vz = msg->vz;
walk_flag = msg->go;
//walking_flag = walk_flag;
}
void LipWalkNode::sendGoal(const std::vector<BodyPointState> &vecBody,const double& dt)
{
endEffMsg.header.stamp = ros::Time::now();
endEffMsg.endEff.resize(int(vecBody.size()));
for(int i = 0; i < int(vecBody.size());i++)
{
//ROS_INFO("DEBUG: I: %d VEC_SIZE: %d",i,int(vecBody.size()));
tf::pointEigenToMsg(vecBody[i].pos,endEffMsg.endEff[i].pos);
tf::pointEigenToMsg(vecBody[i].rot,endEffMsg.endEff[i].rot);
endEffMsg.endEff[i].type = vecBody[i].type;
endEffMsg.endEff[i].flag = vecBody[i].flag;
endEffMsg.endEff[i].dt = vecBody[i].dt;
}
endEffTopic.publish(endEffMsg);
}
void LipWalkNode::humanoidPropsCallback(const humanoid_msgs::HumanoidPropertiesMsgPtr &msg)
{
tf::pointMsgToEigen(msg->footComPoint, footCom);
lipUpdate = true;
}
void LipWalkNode::send2Topic()
{
Eigen::Vector3d footPosR = (robotLip.footGround == RIGHT_FOOT)?(robotLip.rFootPos):(robotLip.lFootPos);
//Vector3d footPos = lipEvaSim.fIdealSSP;
lipMsg.header.stamp = ros::Time::now();
lipMsg.footStep.x = robotLip.fIdealSSP(0);
lipMsg.footStep.y = robotLip.fIdealSSP(1);
lipMsg.footStep.z = robotLip.fIdealSSP(2);
lipMsg.footStepR.x = footPosR(0);
lipMsg.footStepR.y = footPosR(1);
lipMsg.footStepR.z = footPosR(2);
lipMsg.comPos.x = robotLip.com.pos(0);
lipMsg.comPos.y = robotLip.com.pos(1);
lipMsg.comPos.z = robotLip.com.pos(2);
lipMsg.comVel.x = robotLip.com.vel(0);
lipMsg.comVel.y = robotLip.com.vel(1);
lipMsg.comVel.z = robotLip.com.vel(2);
lipMsg.comAcc.x = robotLip.com.acc(0);
lipMsg.comAcc.y = robotLip.com.acc(1);
lipMsg.comAcc.z = robotLip.com.acc(2);
lipMsg.zmp.x = robotLip.zmp(0);
lipMsg.zmp.y = robotLip.zmp(1);
lipMsg.zmp.z = 0;
lipMsg.footAir = robotLip.footAir*5;
lipMsg.footGround = robotLip.footGround*5;
lipMsg.wState = robotLip.wState*5;
paramsMsg.tS = tS;
paramsMsg.tD = tD;
paramsMsg.stepH = stepH;
paramsMsg.zCCorr = zCCorr;
paramsMsg.vx = vx;
paramsMsg.vy = vy;
paramsMsg.vz = vz;
paramsMsg.delayL = delayL;
paramsMsg.delayR = delayR;
paramsMsg.delayAll = delayAll;
paramsTopic.publish(paramsMsg);
lipTopic.publish(lipMsg);
}
|
c42a9a4686bdb725510bd036d7ada3d916d92e59 | 5ed50bbb321fa88076b8bff19d9747fa90ea65b3 | /grid3d.cpp | 075b03240832b02a4646f40ea0a0207868eaecbe | [] | no_license | AlonsoFloo/School_3D | 43cd59069651e6c1c5e1025eda56ac894da37ea0 | 2b4305eaf92e35f89e44aff8e29f27a8f1feb7d0 | refs/heads/master | 2021-01-13T00:50:08.916428 | 2016-02-19T10:44:54 | 2016-02-19T10:44:54 | 52,006,251 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,295 | cpp | grid3d.cpp | #include "grid3d.h"
#include <QString>
#include <QFile>
#include <QTextStream>
Grid3D::Grid3D(Point3D* newOrigin, int newNumberX, int newNumberY, int newNumberZ, double newBarycentreDefaultUnkownedValue) : origin(newOrigin), numberX(newNumberX), numberY(newNumberY), numberZ(newNumberZ), barycentreDefaultUnkownedValue(newBarycentreDefaultUnkownedValue)
{
for(int indexZ = 0; indexZ < this->numberZ + 1; ++indexZ) {
for(int indexY = 0; indexY < this->numberY + 1; ++indexY) {
for(int indexX = 0; indexX < this->numberX + 1; ++indexX) {
this->nodePropsList.append(1.);
}
}
}
}
void Grid3D::writeMesh(string filepath, bool withGrid) const {
QString filename = QString::fromStdString(filepath);
QFile file( filename );
if ( file.open(QIODevice::ReadWrite|QIODevice::Truncate) )
{
QTextStream stream( &file);
QVector<string> pointList;
if (withGrid) {
for(int indexZ = 0; indexZ < this->numberZ + 1; ++indexZ) {
for(int indexY = 0; indexY < this->numberY + 1; ++indexY) {
for(int indexX = 0; indexX < this->numberX + 1; ++indexX) {
pointList.append(std::to_string(this->origin->x + indexX) + " " + std::to_string(this->origin->y + indexY) + " " + std::to_string(this->origin->z + indexZ) + " 0");
}
}
}
}
QVector<string> hexaheraList;
for(int indexZ = 0; indexZ < this->numberZ; ++indexZ) {
for(int indexY = 0; indexY < this->numberY; ++indexY) {
for(int indexX = 0; indexX < this->numberX; ++indexX) {
Point3D* p = new Point3D(indexX, indexY, indexZ);
int p1 = this->getIndexFor(p->x, p->y, p->z);
int p2 = this->getIndexFor(p->x+1, p->y, p->z);
int p3 = this->getIndexFor(p->x+1, p->y+1, p->z);
int p4 = this->getIndexFor(p->x, p->y+1, p->z);
int p5 = this->getIndexFor(p->x, p->y, p->z+1);
int p6 = this->getIndexFor(p->x+1, p->y, p->z+1);
int p7 = this->getIndexFor(p->x+1, p->y+1, p->z+1);
int p8 = this->getIndexFor(p->x, p->y+1, p->z+1);
if (withGrid) {
hexaheraList.append(std::to_string(p1 + 1) + " " + std::to_string(p2 + 1) + " " + std::to_string(p3 + 1) + " " + std::to_string(p4 + 1) + " " + std::to_string(p5 + 1) + " " + std::to_string(p6 + 1) + " " + std::to_string(p7 + 1) + " " + std::to_string(p8 + 1)+ " 508");
}
Point3D *p13D = new Point3D(this->origin->x + p->x, this->origin->y + p->y, this->origin->z + p->z);
Point3D *p23D = new Point3D(this->origin->x + p->x+1, this->origin->y + p->y, this->origin->z + p->z);
Point3D *p33D = new Point3D(this->origin->x + p->x+1, this->origin->y + p->y+1, this->origin->z + p->z);
Point3D *p43D = new Point3D(this->origin->x + p->x, this->origin->y + p->y+1, this->origin->z + p->z);
Point3D *p53D = new Point3D(this->origin->x + p->x, this->origin->y + p->y, this->origin->z + p->z+1);
Point3D *p63D = new Point3D(this->origin->x + p->x+1, this->origin->y + p->y, this->origin->z + p->z+1);
Point3D *p73D = new Point3D(this->origin->x + p->x+1, this->origin->y + p->y+1, this->origin->z + p->z+1);
Point3D *p83D = new Point3D(this->origin->x + p->x, this->origin->y + p->y+1, this->origin->z + p->z+1);
string value = this->getBarycentreStringForPoint(p13D, this->getPropsForPoint(p1), p23D, this->getPropsForPoint(p2));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p23D, this->getPropsForPoint(p2), p33D, this->getPropsForPoint(p3));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p33D, this->getPropsForPoint(p3), p43D, this->getPropsForPoint(p4));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p43D, this->getPropsForPoint(p4), p13D, this->getPropsForPoint(p1));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p53D, this->getPropsForPoint(p5), p63D, this->getPropsForPoint(p6));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p63D, this->getPropsForPoint(p6), p73D, this->getPropsForPoint(p7));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p73D, this->getPropsForPoint(p7), p83D, this->getPropsForPoint(p8));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p83D, this->getPropsForPoint(p8), p53D, this->getPropsForPoint(p5));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p13D, this->getPropsForPoint(p1), p53D, this->getPropsForPoint(p5));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p23D, this->getPropsForPoint(p2), p63D, this->getPropsForPoint(p6));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p33D, this->getPropsForPoint(p3), p73D, this->getPropsForPoint(p7));
if (value != "") pointList.append(value);
value = this->getBarycentreStringForPoint(p43D, this->getPropsForPoint(p4), p83D, this->getPropsForPoint(p8));
if (value != "") pointList.append(value);
}
}
}
stream << "MeshVersionFormatted 1" << endl;
stream << "Dimension" << endl;
stream << "3" << endl;
stream << "Vertices" << endl;
stream << pointList.length() << endl;
for (int i = 0; i < pointList.length(); ++i) {
stream << QString::fromStdString(pointList.at(i)) << endl;
}
stream << "Hexahedra" << endl;
stream << hexaheraList.length() << endl;
for (int i = 0; i < hexaheraList.length(); ++i) {
stream << QString::fromStdString(hexaheraList.at(i)) << endl;
}
stream << "End" << endl;
file.close();
}
}
Point3D* Grid3D::getBarycentreForPoint(Point3D* p1, double p1Value, Point3D* p2, double p2Value) const {
if ((p1Value > barycentreDefaultUnkownedValue && p2Value > barycentreDefaultUnkownedValue)
|| (p1Value < barycentreDefaultUnkownedValue && p2Value < barycentreDefaultUnkownedValue)
|| (p1Value - p2Value == 0)) {
return nullptr;
}
double t = 1 - ((p1Value - barycentreDefaultUnkownedValue) / (p1Value - p2Value));
return new Point3D(t*p1->x + (1-t)*p2->x, t*p1->y + (1-t)*p2->y, t*p1->z + (1-t)*p2->z);
}
string Grid3D::getBarycentreStringForPoint(Point3D* p1, double p1Value, Point3D* p2, double p2Value) const {
Point3D *b = this->getBarycentreForPoint(p1, p1Value, p2, p2Value);
if (b != nullptr) {
return std::to_string(b->x) + " " + std::to_string(b->y) + " " + std::to_string(b->z) + " 0";
}
return "";
}
void Grid3D::displayData() const {
cout << "Origin point : " << this->origin->x << " " << this->origin->y << " " << this->origin->z << endl;
cout << "Number on X : " << this->numberX << endl;
cout << "Number on Y : " << this->numberY << endl;
cout << "Number on Z : " << this->numberZ << endl;
cout << "Props : [";
for (int i = 0; i < this->nodePropsList.length(); ++i) {
if (i > 0) {
cout << ", ";
}
cout << this->nodePropsList.at(i);
}
cout << "]" << endl;
cout << endl<< endl<< endl;
}
int Grid3D::getIndexFor(int x, int y, int z) const {
return x + (this->numberX + 1) * y + (this->numberX + 1) * (this->numberY + 1) * z;
}
double Grid3D::getPropsForPoint(int x, int y, int z) const {
int index = this->getIndexFor(x, y, z);
return this->getPropsForPoint(index);
}
double Grid3D::getPropsForPoint(int index) const {
return this->nodePropsList.at(index);
}
void Grid3D::setPropsForPoint(int x, int y, int z, double value) {
int index = this->getIndexFor(x, y, z);
this->setPropsForPoint(index, value);
}
void Grid3D::setPropsForPoint(int index, double value) {
this->nodePropsList.replace(index, value);
}
void Grid3D::addImplicitObject(const ImplicitObject* s) {
for(int indexZ = 0; indexZ < numberZ + 1; ++indexZ) {
for(int indexY = 0; indexY < numberY + 1; ++indexY) {
for(int indexX = 0; indexX < numberX + 1; ++indexX) {
Point3D* point = new Point3D(this->origin->x + indexX, this->origin->y + indexY, this->origin->z + indexZ);
double distance = s->getDistance(point);
this->setPropsForPoint(indexX, indexY, indexZ, distance);
}
}
}
}
|
eb219a9cf3d66a06efe5977255d9cd4fd08f956d | 40870b915cfdc683a15581adf8b60b3f9d3ef3df | /eso.h | 271f335baf1694421e1ce28625953f8a02b69812 | [] | no_license | darkain/wasabi-playlist-script | 77952d3e7135d0393cc5902b2bc548ddb774bdca | 80746ef8e20ad88809cfa6d21bb109feb90e3bdd | refs/heads/master | 2020-04-27T05:26:58.823614 | 2019-03-06T05:59:36 | 2019-03-06T05:59:36 | 174,081,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | h | eso.h | #ifndef _ESO_H
#define _ESO_H
#include "../../studio/wac.h"
class WACExampleScriptObject : public WAComponentClient {
public:
WACExampleScriptObject();
virtual const char *getName() { return "Playlist Script Object"; };
virtual GUID getGUID();
virtual void onCreate();
virtual void onDestroy();
private:
};
extern WACExampleScriptObject *esowac;
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.