text
stringlengths 8
6.88M
|
|---|
// OnHScrollThumbTrack.cpp
#include "OnHScrollThumbTrack.h"
OnHScrollThumbTrack::OnHScrollThumbTrack(HorizontalScroll *horizontalScroll)
:ScrollAction() {
this->horizontalScroll = horizontalScroll;
}
OnHScrollThumbTrack::OnHScrollThumbTrack(const OnHScrollThumbTrack& source)
:ScrollAction(source) {
this->horizontalScroll = source.horizontalScroll;
}
OnHScrollThumbTrack::~OnHScrollThumbTrack() {
}
OnHScrollThumbTrack& OnHScrollThumbTrack::operator=(const OnHScrollThumbTrack& source) {
ScrollAction::operator=(source);
this->horizontalScroll = source.horizontalScroll;
return *this;
}
void OnHScrollThumbTrack::Action(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) {
this->horizontalScroll->MoveThumb();
}
|
#include "dialog2.h"
#include "ui_dialog2.h"
Dialog2::Dialog2(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog2)
{
ui->setupUi(this);
}
Dialog2::~Dialog2()
{
delete ui;
}
void Dialog2::on_buttonBox_accepted()
{
cat = new cat_rege;
cat->show();
}
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//template <typename T>
void squares(vector<vector<int>> &ar)
{
for(int i = 0; i<5; ++i)
for(int j = 0; j<5; ++j)
{
ar[i][j] *= ar[i][j];
}
}
int main() {
std::vector<int> vi;
//std::vector<int> :: iterator i;
//std::vector<int> :: reverse_iterator ir;
for(int i = 0; i<5; ++i)
vi.push_back(i);
//for(vector<int>::iterator itr = vi.begin(); itr != vi.end(); ++itr)
//{
// cout<<*itr<<" ";
//}
// for(auto& it : vi)
// cout<<it<<' ';
/*
int arr[5][5];
int even = 0;
*/
std::vector<vector<int>> va;
std::std::vector<int> row;
row.push_back(0);
row.push_back(2);
row.push_back(4);
row.push_back(6);
row.push_back(8);
row.push_back(10);
va.push_back(row);
cout<<va;
//int *p = arr;
// cout<<arr[1][1];
//Output from start to end
//for(i = vi.begin(); i != vi.end(); ++i)
// cout<<*i<<'\t';
//cout<<endl<<endl;
//cout<<"Output of rbegin and rend";
//for(ir = vi.rbegin(); ir != vi.rend(); ++ir)
//cout<<*ir<<'\t';
return 0;
}
|
#include <commentObj.h>
// #include <rose.h>
#include <string>
#include <map>
class DoxygenFile;
class DoxygenGroup;
class DoxygenComment
{
public:
/*! Create a new, blank DoxygenComment attached to the given node. */
DoxygenComment(SgLocatedNode *node);
/*! Create a DoxygenComment associated with an existing comment. */
DoxygenComment(SgLocatedNode *node, PreprocessingInfo *comment);
virtual ~DoxygenComment();
DoxygenEntry entry;
PreprocessingInfo *originalComment;
SgLocatedNode *originalNode;
DoxygenFile *originalFile;
static bool isDoxygenComment(PreprocessingInfo *comm);
void attach(SgLocatedNode *newParent, AttachedPreprocessingInfoType::iterator pos);
void attach(SgLocatedNode *newParent);
void attach(DoxygenFile *newParent);
void attach(DoxygenFile *newParent, DoxygenGroup *newGroup);
/*! Updates the originalComment using information in entry */
void updateComment();
void addUndocumentedParams(SgFunctionDeclaration *fn);
};
class DoxygenFile
{
// DQ: This is used for doxygen comments held in separate files.
public:
DoxygenFile(SgLocatedNode *commentParent);
DoxygenFile(SgProject *prj, std::string filename);
std::string name();
std::string unparse();
bool hasGroup(std::string name);
DoxygenGroup *group(std::string name);
//AS(090707) Support sorting of comments according to a
//user-defined order
void sortComments( bool (*pred)(DoxygenComment*,DoxygenComment*) );
void createGroup(std::string name);
DoxygenGroup *findGroup(DoxygenComment *comm);
private:
SgLocatedNode *commentParent;
std::map<std::string, DoxygenGroup *> groups; // should not be public (needed for building object)
friend class DoxygenComment;
friend struct Doxygen;
};
class DoxygenCommentListAttribute : public AstAttribute
{
// DQ: These are used for where the doxygen comments are held in the source code.
public:
std::list<DoxygenComment *> commentList;
};
struct Doxygen
{
static std::string getProtoName(SgDeclarationStatement *st);
static std::string getDeclStmtName(SgDeclarationStatement *st);
static std::string getQualifiedPrototype(SgNode *node);
static bool isRecognizedDeclaration(SgDeclarationStatement *n);
static SgDeclarationStatement *getDoxygenAttachedDeclaration(SgDeclarationStatement *ds);
static std::list<DoxygenComment *> *getCommentList(SgDeclarationStatement *ds);
static std::map<std::string, DoxygenFile *> *getFileList(SgProject *prj);
static bool isGroupStart(PreprocessingInfo *p);
static bool isGroupEnd(PreprocessingInfo *p);
static void annotate(SgProject *n);
static void unparse(SgProject *p , bool (*shouldBeUnparsed)(DoxygenFile*, std::string& fileName) = NULL );
//The correctAllComments function will update all doxygen comments and generate new doxygen comments for
//constructs that has not been documented. The function provided as the second argument,
// shouldHaveDocumentation, will return false if this should not be performed for a SgNode* or true
//otherwise.
static void correctAllComments(SgProject *prj, bool (*shouldHaveDocumentation)(SgNode*) = NULL );
static void lint(SgNode *n);
static void parseCommandLine(std::vector<std::string>& argvList);
struct DoxygenOptions
{
DoxygenOptions() : outputDirectory(".") {}
std::string classNameTemplate;
std::string functionNameTemplate;
std::string variableNameTemplate;
std::string updateScript;
std::string outputDirectory;
bool createNewFiles;
bool inplace;
};
static DoxygenOptions *options;
static DoxygenFile *destinationFile(SgProject *prj, SgDeclarationStatement *decl);
static std::string destinationFilename(SgDeclarationStatement *decl);
};
class DoxygenGroup
{
// DQ: This is used for doxygen comments held in separate files.
public:
std::string getName();
private:
PreprocessingInfo* groupStart;
PreprocessingInfo* groupEnd;
DoxygenComment *comment;
friend class DoxygenFile;
friend struct Doxygen;
friend class DoxygenComment;
}
;
extern std::map<const PreprocessingInfo*, DoxygenComment* > commentMap;
|
#pragma once
#ifndef _DTL_SIMD_INCLUDED
#error "Never use <dtl/simd/intrin_avx2.hpp> directly; include <dtl/simd.hpp> instead."
#endif
#include "../adept.hpp"
#include <dtl/bits.hpp>
#include "types.hpp"
#include "immintrin.h"
namespace dtl {
namespace simd {
namespace internal {
namespace avx2 {
constexpr dtl::r256 ALL_ONES { .i64 = {-1, -1, -1, -1}};
struct mask4 {
__m256i data;
__forceinline__ u1 all() const { return _mm256_movemask_epi8(data) == -1; };
__forceinline__ u1 any() const { return _mm256_testz_si256(data, ALL_ONES.i) == 0; };
__forceinline__ u1 none() const { return _mm256_testz_si256(data, ALL_ONES.i) != 0; };
__forceinline__ void set(u1 value) {
if (value) {
data = _mm256_set1_epi64x(-1);
} else {
data = _mm256_set1_epi64x(0);
}
}
__forceinline__ void set(u64 idx, u1 value) {
i64 v = value ? -1 : 0;
switch (idx) {
case 0: data = _mm256_insert_epi64(data, v, 0); break;
case 1: data = _mm256_insert_epi64(data, v, 1); break;
case 2: data = _mm256_insert_epi64(data, v, 2); break;
case 3: data = _mm256_insert_epi64(data, v, 3); break;
// default: unreachable();
}
};
__forceinline__ void set_from_int(u64 int_bitmask) {
const dtl::r256 seq = { .i64 = { 1u << 0, 1u << 1, 1u << 2, 1u << 3 } };
const dtl::r256 zero = { .i64 = { 0, 0, 0, 0 } };
const auto t = _mm256_and_si256(_mm256_set1_epi64x(int_bitmask), seq.i) ;
data = _mm256_cmpgt_epi64(t, zero.i);
};
__forceinline__ u1 get(u64 idx) const {
switch (idx) {
case 0: return _mm256_extract_epi64(data, 0) != 0;
case 1: return _mm256_extract_epi64(data, 1) != 0;
case 2: return _mm256_extract_epi64(data, 2) != 0;
case 3: return _mm256_extract_epi64(data, 3) != 0;
// default: unreachable();
}
};
__forceinline__ mask4 bit_and(const mask4& o) const { return mask4 { _mm256_and_si256(data, o.data) }; };
__forceinline__ mask4 bit_or(const mask4& o) const { return mask4 { _mm256_or_si256(data, o.data) }; };
__forceinline__ mask4 bit_xor(const mask4& o) const { return mask4 { _mm256_xor_si256(data, o.data) }; };
__forceinline__ mask4 bit_not() const { return mask4 { _mm256_andnot_si256(data, _mm256_set1_epi64x(-1)) }; };
__forceinline__ $u64
to_positions($u32* positions, $u32 offset) const {
// only makes sence for unselective queries
// const __m256i zero = _mm256_setzero_si256();
// if (_mm256_testc_si256(zero, data)) return 0;
const __m128i offset_vec = _mm_set1_epi32(offset);
i32 bitmask = _mm256_movemask_pd(reinterpret_cast<__m256d>(data));
const dtl::r128 match_pos_vec = { .i = dtl::simd::lut_match_pos_4bit[bitmask].i };
const __m128i pos_vec = _mm_add_epi32(offset_vec, match_pos_vec.i);
_mm_storeu_si128(reinterpret_cast<__m128i*>(positions), pos_vec);
// TODO consider using popcnt instead
return dtl::simd::lut_match_cnt_4bit[bitmask];
}
__forceinline__ $u64
to_int() const {
return _mm256_movemask_pd(reinterpret_cast<__m256d>(data));
}
};
struct mask8 {
__m256i data;
__forceinline__ u1 all() const { return _mm256_movemask_epi8(data) == -1; };
// __forceinline__ u1 any() const { return _mm256_movemask_epi8(data) != 0; };
// __forceinline__ u1 none() const { return _mm256_movemask_epi8(data) == 0; };
__forceinline__ u1 any() const { return _mm256_testz_si256(data, ALL_ONES.i) == 0; };
__forceinline__ u1 none() const { return _mm256_testz_si256(data, ALL_ONES.i) != 0; };
__forceinline__ void set(u1 value) {
if (value) {
data = _mm256_set1_epi64x(-1);
} else {
data = _mm256_set1_epi64x(0);
}
}
__forceinline__ void set(u64 idx, u1 value) {
i32 v = value ? -1 : 0;
switch (idx) {
// TODO support other types than 32-bit integer
case 0: data = _mm256_insert_epi32(data, v, 0); break;
case 1: data = _mm256_insert_epi32(data, v, 1); break;
case 2: data = _mm256_insert_epi32(data, v, 2); break;
case 3: data = _mm256_insert_epi32(data, v, 3); break;
case 4: data = _mm256_insert_epi32(data, v, 4); break;
case 5: data = _mm256_insert_epi32(data, v, 5); break;
case 6: data = _mm256_insert_epi32(data, v, 6); break;
case 7: data = _mm256_insert_epi32(data, v, 7); break;
// default: unreachable();
}
};
__forceinline__ void set_from_int(u64 int_bitmask) {
const dtl::r256 seq = { .i32 = { 1u << 0, 1u << 1, 1u << 2, 1u << 3, 1u << 4, 1u << 5, 1u << 6, 1u << 7 } };
const auto t = _mm256_and_si256(_mm256_set1_epi32(int_bitmask), seq.i) ;
data = _mm256_cmpgt_epi32(t, _mm256_setzero_si256());
};
__forceinline__ u1 get(u64 idx) const {
switch (idx) {
case 0: return _mm256_extract_epi32(data, 0) != 0;
case 1: return _mm256_extract_epi32(data, 1) != 0;
case 2: return _mm256_extract_epi32(data, 2) != 0;
case 3: return _mm256_extract_epi32(data, 3) != 0;
case 4: return _mm256_extract_epi32(data, 4) != 0;
case 5: return _mm256_extract_epi32(data, 5) != 0;
case 6: return _mm256_extract_epi32(data, 6) != 0;
case 7: return _mm256_extract_epi32(data, 7) != 0;
// default: unreachable();
}
};
__forceinline__ mask8 bit_and(const mask8& o) const { return mask8 { _mm256_and_si256(data, o.data) }; };
__forceinline__ mask8 bit_or(const mask8& o) const { return mask8 { _mm256_or_si256(data, o.data) }; };
__forceinline__ mask8 bit_xor(const mask8& o) const { return mask8 { _mm256_xor_si256(data, o.data) }; };
__forceinline__ mask8 bit_not() const { return mask8 { _mm256_andnot_si256(data, _mm256_set1_epi64x(-1)) }; };
__forceinline__ $u64
to_positions($u32* positions, $u32 offset) const {
const __m256i offset_vec = _mm256_set1_epi32(offset);
i32 bitmask = _mm256_movemask_ps(reinterpret_cast<__m256>(data));
dtl::r256 match_pos_vec;
match_pos_vec.i = _mm256_cvtepi16_epi32(dtl::simd::lut_match_pos[bitmask].i);
const __m256i pos_vec = _mm256_add_epi32(offset_vec, match_pos_vec.i);
_mm256_storeu_si256(reinterpret_cast<__m256i*>(positions), pos_vec);
return dtl::simd::lut_match_cnt[bitmask];
}
__forceinline__ $u64
to_int() const {
return _mm256_movemask_ps(reinterpret_cast<__m256>(data));
}
};
} // avx2 namespace
} // internal namespace
namespace {
using mask4 = internal::avx2::mask4;
using mask8 = internal::avx2::mask8;
}
/// Define native vector type for SIMD-256: 8 x i32
template<>
struct vs<$i32, 8> : base<$i32, 8> {
using type = __m256i;
using mask_type = mask8;
type data;
};
template<>
struct vs<$u32, 8> : base<$u32, 8> {
using type = __m256i;
using mask_type = mask8;
type data;
};
/// Define native vector type for SIMD-256: 4 x i64
template<>
struct vs<$i64, 4> : base<$i64, 4> {
using type = __m256i;
using mask_type = mask4;
type data;
};
template<>
struct vs<$u64, 4> : base<$u64, 4> {
using type = __m256i;
using mask_type = mask4;
type data;
};
// --- broadcast / set
#define __GENERATE(Tp, Tv, Ta, IntrinFn, LEN) \
template<> \
struct broadcast<Tp, Tv, Ta> : vector_fn<Tp, Tv, Ta> { \
using fn = vector_fn<Tp, Tv, Ta>; \
__forceinline__ typename fn::vector_type \
operator()(const typename fn::value_type& a) const noexcept { \
return IntrinFn(a); \
} \
__forceinline__ typename fn::vector_type \
operator()(const typename fn::value_type& a, \
const typename fn::vector_type& src, \
const mask##LEN m) const noexcept { \
return _mm256_blendv_epi8(src, IntrinFn(a), m.data); \
} \
};
__GENERATE($i32, __m256i, $i32, _mm256_set1_epi32, 8)
__GENERATE($u32, __m256i, $u32, _mm256_set1_epi32, 8)
__GENERATE($i64, __m256i, $i64, _mm256_set1_epi64x, 4)
__GENERATE($u64, __m256i, $u64, _mm256_set1_epi64x, 4)
#undef __GENERATE
#define __GENERATE_BLEND(Tp, Tv, Ta, IntrinFnMask, LEN) \
template<> \
struct blend<Tp, Tv, Ta> : vector_fn<Tp, Tv, Ta> { \
using fn = vector_fn<Tp, Tv, Ta>; \
__forceinline__ typename fn::vector_type \
operator()(const typename fn::vector_type& a, \
const typename fn::vector_type& b, \
const mask##LEN m) const noexcept { \
return IntrinFnMask(a, b, m.data); \
} \
};
__GENERATE_BLEND($i32, __m256i, __m256i, _mm256_blendv_epi8, 8)
__GENERATE_BLEND($u32, __m256i, __m256i, _mm256_blendv_epi8, 8)
__GENERATE_BLEND($i64, __m256i, __m256i, _mm256_blendv_epi8, 4)
__GENERATE_BLEND($u64, __m256i, __m256i, _mm256_blendv_epi8, 4)
#undef __GENERATE
template<>
struct set<$i32, __m256i, $i32> : vector_fn<$i32, __m256i, $i32> {
__forceinline__ __m256i operator()(const $i32& a) const noexcept {
return _mm256_set1_epi32(a);
}
};
// Load
template<>
struct gather<$i32, __m256i, __m256i> : vector_fn<$i32, __m256i, __m256i, __m256i> {
__forceinline__ __m256i operator()(const i32* const base_addr, const __m256i& idxs) const noexcept {
return _mm256_i32gather_epi32(base_addr, idxs, 4);
}
};
template<>
struct gather<$u32, __m256i, __m256i> : vector_fn<$u32, __m256i, __m256i, __m256i> {
__forceinline__ __m256i operator()(const u32* const base_addr, const __m256i& idxs) const noexcept {
return _mm256_i32gather_epi32(reinterpret_cast<const i32*>(base_addr), idxs, 4);
}
};
template<>
struct gather<$i64, __m256i, __m256i> : vector_fn<$i64, __m256i, __m256i, __m256i> {
__forceinline__ __m256i operator()(const i64* const base_addr, const __m256i& idxs) const noexcept {
const auto b = reinterpret_cast<const long long int *>(base_addr);
return _mm256_i64gather_epi64(b, idxs, 8); // danger!
}
};
template<>
struct gather<$u64, __m256i, __m256i> : vector_fn<$u64, __m256i, __m256i, __m256i> {
__forceinline__ __m256i operator()(const u64* const base_addr, const __m256i& idxs) const noexcept {
const auto b = reinterpret_cast<const long long int *>(base_addr);
return _mm256_i64gather_epi64(b, idxs, 8); // danger!
}
};
// Store
template<>
struct store<$i32, __m256i> : vector_fn<$i32, __m256i> {
__forceinline__ void operator()(__m256i* mem_addr, const __m256i& what) const noexcept {
_mm256_store_si256(mem_addr, what);
}
};
template<>
struct storeu<$i32, __m256i> : vector_fn<$i32, __m256i> {
__forceinline__ void operator()($i32* mem_addr, const __m256i& what) const noexcept {
_mm256_storeu_si256(reinterpret_cast<__m256i*>(mem_addr), what);
}
};
template<>
struct store<$u32, __m256i> : vector_fn<$u32, __m256i> {
__forceinline__ void operator()(__m256i* mem_addr, const __m256i& what) const noexcept {
_mm256_store_si256(mem_addr, what);
}
};
template<>
struct storeu<$u32, __m256i> : vector_fn<$u32, __m256i> {
__forceinline__ void operator()($u32* mem_addr, const __m256i& what) const noexcept {
_mm256_storeu_si256(reinterpret_cast<__m256i*>(mem_addr), what);
}
};
//template<>
//struct scatter<$i32, __m256i, __m256i> : vector_fn<$i32, __m256i, __m256i, __m256i> {
// __forceinline__ __m256i operator()($i32* base_addr, const __m256i& idxs, const __m256i& what) const noexcept {
// i32* i = reinterpret_cast<i32*>(&idxs);
// i32* w = reinterpret_cast<i32*>(&what);
// for ($u64 j = 0; j < 8; j++) {
// base_addr[i[j]] = w[j];
// }
// }
//};
//
//template<>
//struct scatter<$u32, __m256i, __m256i> : vector_fn<$u32, __m256i, __m256i, __m256i> {
// __forceinline__ __m256i operator()($u32* base_addr, const __m256i& idxs, const __m256i& what) const noexcept {
// u32* i = reinterpret_cast<u32*>(&idxs);
// u32* w = reinterpret_cast<u32*>(&what);
// for ($u64 j = 0; j < 8; j++) {
// base_addr[i[j]] = w[j];
// }
// }
//};
//
//template<>
//struct scatter<$i64, __m256i, __m256i> : vector_fn<$i64, __m256i, __m256i, __m256i> {
// __forceinline__ __m256i operator()($i64* base_addr, const __m256i& idxs, const __m256i& what) const noexcept {
// i64* i = reinterpret_cast<i64*>(&idxs);
// i64* w = reinterpret_cast<i64*>(&what);
// for ($u64 j = 0; j < 4; j++) {
// base_addr[i[j]] = w[j];
// }
// }
//};
//
//template<>
//struct scatter<$u64, __m256i, __m256i> : vector_fn<$u64, __m256i, __m256i, __m256i> {
// __forceinline__ __m256i operator()($u64* base_addr, const __m256i& idxs, const __m256i& what) const noexcept {
// u64* i = reinterpret_cast<u64*>(&idxs);
// u64* w = reinterpret_cast<u64*>(&what);
// for ($u64 j = 0; j < 4; j++) {
// base_addr[i[j]] = w[j];
// }
// }
//};
// Compress
template<>
struct compress<$i32, __m256i> : vector_fn<$i32, __m256i> {
// source: https://stackoverflow.com/questions/36932240/avx2-what-is-the-most-efficient-way-to-pack-left-based-on-a-mask
__forceinline__ __m256i operator()(const __m256i& src, const mask8& m) const noexcept {
const uint64_t int_mask = _mm256_movemask_ps((__m256)m.data);
uint64_t expanded_mask = _pdep_u64(int_mask, 0x0101010101010101); // unpack each bit to a byte
expanded_mask *= 0xFF; // mask |= mask<<1 | mask<<2 | ... | mask<<7;
// ABC... -> AAAAAAAABBBBBBBBCCCCCCCC...: replicate each bit to fill its byte
const uint64_t identity_indices = 0x0706050403020100; // the identity shuffle for vpermps, packed to one index per byte
uint64_t wanted_indices = _pext_u64(identity_indices, expanded_mask);
__m128i bytevec = _mm_cvtsi64_si128(wanted_indices);
__m256i shufmask = _mm256_cvtepu8_epi32(bytevec);
return (__m256i)_mm256_permutevar8x32_ps((__m256)src, shufmask);
}
__forceinline__ __m256i operator()(const __m256i& src, const mask8& m, uint32_t& pop_cnt) const noexcept {
const uint32_t int_mask = _mm256_movemask_ps((__m256)m.data);
pop_cnt = dtl::bits::pop_count(int_mask);
uint64_t expanded_mask = _pdep_u64(int_mask, 0x0101010101010101); // unpack each bit to a byte
expanded_mask *= 0xFF; // mask |= mask<<1 | mask<<2 | ... | mask<<7;
// ABC... -> AAAAAAAABBBBBBBBCCCCCCCC...: replicate each bit to fill its byte
const uint64_t identity_indices = 0x0706050403020100; // the identity shuffle for vpermps, packed to one index per byte
uint64_t wanted_indices = _pext_u64(identity_indices, expanded_mask);
__m128i bytevec = _mm_cvtsi64_si128(wanted_indices);
__m256i shufmask = _mm256_cvtepu8_epi32(bytevec);
return (__m256i)_mm256_permutevar8x32_ps((__m256)src, shufmask);
}
};
template<>
struct compress<$u32, __m256i> : vector_fn<$u32, __m256i> {
// source: https://stackoverflow.com/questions/36932240/avx2-what-is-the-most-efficient-way-to-pack-left-based-on-a-mask
__forceinline__ __m256i operator()(const __m256i& src, const mask8& m) const noexcept {
const uint64_t int_mask = _mm256_movemask_ps((__m256)m.data);
uint64_t expanded_mask = _pdep_u64(int_mask, 0x0101010101010101); // unpack each bit to a byte
expanded_mask *= 0xFF; // mask |= mask<<1 | mask<<2 | ... | mask<<7;
// ABC... -> AAAAAAAABBBBBBBBCCCCCCCC...: replicate each bit to fill its byte
const uint64_t identity_indices = 0x0706050403020100; // the identity shuffle for vpermps, packed to one index per byte
uint64_t wanted_indices = _pext_u64(identity_indices, expanded_mask);
__m128i bytevec = _mm_cvtsi64_si128(wanted_indices);
__m256i shufmask = _mm256_cvtepu8_epi32(bytevec);
return (__m256i)_mm256_permutevar8x32_ps((__m256)src, shufmask);
}
__forceinline__ __m256i operator()(const __m256i& src, const mask8& m, uint32_t& pop_cnt) const noexcept {
const uint32_t int_mask = _mm256_movemask_ps((__m256)m.data);
pop_cnt = dtl::bits::pop_count(int_mask);
uint64_t expanded_mask = _pdep_u64(int_mask, 0x0101010101010101); // unpack each bit to a byte
expanded_mask *= 0xFF; // mask |= mask<<1 | mask<<2 | ... | mask<<7;
// ABC... -> AAAAAAAABBBBBBBBCCCCCCCC...: replicate each bit to fill its byte
const uint64_t identity_indices = 0x0706050403020100; // the identity shuffle for vpermps, packed to one index per byte
uint64_t wanted_indices = _pext_u64(identity_indices, expanded_mask);
__m128i bytevec = _mm_cvtsi64_si128(wanted_indices);
__m256i shufmask = _mm256_cvtepu8_epi32(bytevec);
return (__m256i)_mm256_permutevar8x32_ps((__m256)src, shufmask);
}
};
// Arithmetic
template<>
struct plus<$i32, __m256i> : vector_fn<$i32, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_add_epi32(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask8& m) const noexcept {
return _mm256_blendv_epi8(src, _mm256_add_epi32(lhs, rhs), m.data);
}
};
template<>
struct plus<$u32, __m256i> : vector_fn<$u32, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_add_epi32(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask8& m) const noexcept {
return _mm256_blendv_epi8(src, _mm256_add_epi32(lhs, rhs), m.data);
}
};
template<>
struct plus<$i64, __m256i> : vector_fn<$i64, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_add_epi64(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask4& m) const noexcept {
return _mm256_blendv_epi8(src, _mm256_add_epi64(lhs, rhs), m.data);
}
};
template<>
struct plus<$u64, __m256i> : vector_fn<$u64, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_add_epi64(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask4& m) const noexcept {
return _mm256_blendv_epi8(src, _mm256_add_epi64(lhs, rhs), m.data);
}
};
template<>
struct minus<$i32, __m256i> : vector_fn<$i32, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_sub_epi32(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask8& m) const noexcept {
return _mm256_blendv_epi8(src, _mm256_sub_epi32(lhs, rhs), m.data);
}
};
template<>
struct minus<$u32, __m256i> : vector_fn<$u32, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_sub_epi32(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask8& m) const noexcept {
return _mm256_blendv_epi8(src, _mm256_sub_epi32(lhs, rhs), m.data);
}
};
template<>
struct minus<$i64, __m256i> : vector_fn<$i64, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_sub_epi64(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask8& m) const noexcept {
return _mm256_blendv_epi8(src, _mm256_sub_epi64(lhs, rhs), m.data);
}
};
template<>
struct minus<$u64, __m256i> : vector_fn<$u64, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_sub_epi64(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask8& m) const noexcept {
return _mm256_blendv_epi8(src, _mm256_sub_epi64(lhs, rhs), m.data);
}
};
template<>
struct multiplies<$i32, __m256i> : vector_fn<$i32, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_mullo_epi32(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask8& m) const noexcept {
return _mm256_blendv_epi8(src, _mm256_mullo_epi32(lhs, rhs), m.data);
}
};
template<>
struct multiplies<$u32, __m256i> : vector_fn<$u32, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_mullo_epi32(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask8& m) const noexcept {
return _mm256_blendv_epi8(src, _mm256_mullo_epi32(lhs, rhs), m.data);
}
};
template<>
struct multiplies<$i64, __m256i> : vector_fn<$i64, __m256i> {
__forceinline__ __m256i mul(const __m256i& lhs, const __m256i& rhs) const noexcept {
const __m256i hi_lhs = _mm256_srli_epi64(lhs, 32);
const __m256i hi_rhs = _mm256_srli_epi64(rhs, 32);
const __m256i t1 = _mm256_mul_epu32(lhs, hi_rhs);
const __m256i t2 = _mm256_mul_epu32(lhs, rhs);
const __m256i t3 = _mm256_mul_epu32(hi_lhs, rhs);
const __m256i t4 = _mm256_add_epi64(_mm256_slli_epi64(t3, 32), t2);
const __m256i t5 = _mm256_add_epi64(_mm256_slli_epi64(t1, 32), t4);
return t5;
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mul(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask4& m) const noexcept {
return _mm256_blendv_epi8(src, mul(lhs, rhs), m.data);
}
};
template<>
struct multiplies<$u64, __m256i> : vector_fn<$u64, __m256i> {
__forceinline__ __m256i mul(const __m256i& lhs, const __m256i& rhs) const noexcept {
const __m256i hi_lhs = _mm256_srli_epi64(lhs, 32);
const __m256i hi_rhs = _mm256_srli_epi64(rhs, 32);
const __m256i t1 = _mm256_mul_epu32(lhs, hi_rhs);
const __m256i t2 = _mm256_mul_epu32(lhs, rhs);
const __m256i t3 = _mm256_mul_epu32(hi_lhs, rhs);
const __m256i t4 = _mm256_add_epi64(_mm256_slli_epi64(t3, 32), t2);
const __m256i t5 = _mm256_add_epi64(_mm256_slli_epi64(t1, 32), t4);
return t5;
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mul(lhs, rhs);
}
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs,
const __m256i& src, const mask4& m) const noexcept {
return _mm256_blendv_epi8(src, mul(lhs, rhs), m.data);
}
};
// Shift
template<>
struct shift_left<$i32, __m256i, i32> : vector_fn<$i32, __m256i, i32> {
__forceinline__ __m256i operator()(const __m256i& lhs, i32& count) const noexcept {
return _mm256_slli_epi32(lhs, count);
}
};
template<>
struct shift_left_var<$i32, __m256i, __m256i> : vector_fn<$i32, __m256i, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& count) const noexcept {
return _mm256_sllv_epi32(lhs, count);
}
};
template<>
struct shift_left_var<$u32, __m256i, __m256i> : vector_fn<$u32, __m256i, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& count) const noexcept {
return _mm256_sllv_epi32(lhs, count);
}
};
template<>
struct shift_left_var<$u64, __m256i, __m256i> : vector_fn<$u64, __m256i, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& count) const noexcept {
return _mm256_sllv_epi64(lhs, count);
}
};
template<>
struct shift_right<$i32, __m256i, i32> : vector_fn<$i32, __m256i, i32> {
__forceinline__ __m256i operator()(const __m256i& lhs, i32& count) const noexcept {
return _mm256_srli_epi32(lhs, count);
}
};
template<>
struct shift_right_var<$u32, __m256i, __m256i> : vector_fn<$u32, __m256i, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& count) const noexcept {
return _mm256_srlv_epi32(lhs, count);
}
};
template<>
struct shift_right_var<$u64, __m256i, __m256i> : vector_fn<$u64, __m256i, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& count) const noexcept {
return _mm256_srlv_epi64(lhs, count);
}
};
// Bitwise operators
template<typename Tp /* ignored for bitwise operations */>
struct bit_and<Tp, __m256i> : vector_fn<Tp, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_and_si256(lhs, rhs);
}
};
template<typename Tp /* ignored for bitwise operations */>
struct bit_or<Tp, __m256i> : vector_fn<Tp, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_or_si256(lhs, rhs);
}
};
template<typename Tp /* ignored for bitwise operations */>
struct bit_xor<Tp, __m256i> : vector_fn<Tp, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return _mm256_xor_si256(lhs, rhs);
}
};
template<typename Tp /* ignored for bitwise operations */>
struct bit_not<Tp, __m256i> : vector_fn<Tp, __m256i> {
__forceinline__ __m256i operator()(const __m256i& lhs) const noexcept {
return _mm256_andnot_si256(lhs, _mm256_set1_epi64x(-1));
}
};
// Comparison
template<>
struct less<$i32, __m256i, __m256i, mask8> : vector_fn<$i32, __m256i, __m256i, mask8> {
__forceinline__ mask8 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask8 { _mm256_cmpgt_epi32(rhs, lhs) };
}
};
template<>
struct less<$u32, __m256i, __m256i, mask8> : vector_fn<$u32, __m256i, __m256i, mask8> {
__forceinline__ mask8 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask8 { _mm256_cmpgt_epi32(rhs, lhs) };
}
};
template<>
struct less_equal<$i32, __m256i, __m256i, mask8> : vector_fn<$i32, __m256i, __m256i, mask8> {
__forceinline__ mask8 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask8 { _mm256_or_si256(
_mm256_cmpgt_epi32(rhs, lhs),
_mm256_cmpeq_epi32(rhs, lhs))};
}
};
template<>
struct less_equal<$u32, __m256i, __m256i, mask8> : vector_fn<$u32, __m256i, __m256i, mask8> {
__forceinline__ mask8 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask8 { _mm256_or_si256(
_mm256_cmpgt_epi32(rhs, lhs),
_mm256_cmpeq_epi32(rhs, lhs))};
}
};
template<>
struct less<$i64, __m256i, __m256i, mask4> : vector_fn<$i64, __m256i, __m256i, mask4> {
__forceinline__ mask4 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask4 { _mm256_cmpgt_epi64(rhs, lhs) };
}
};
template<>
struct greater<$i32, __m256i, __m256i, mask8> : vector_fn<$i32, __m256i, __m256i, mask8> {
__forceinline__ mask8 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask8 { _mm256_cmpgt_epi32(lhs, rhs) };
}
};
template<>
struct greater<$i64, __m256i, __m256i, mask4> : vector_fn<$i64, __m256i, __m256i, mask4> {
__forceinline__ mask4 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask4 { _mm256_cmpgt_epi64(lhs, rhs) };
}
};
template<>
struct equal<$i32, __m256i, __m256i, mask8> : vector_fn<$i32, __m256i, __m256i, mask8> {
__forceinline__ mask8 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask8 { _mm256_cmpeq_epi32(lhs, rhs) };
}
};
template<>
struct equal<$u32, __m256i, __m256i, mask8> : vector_fn<$u32, __m256i, __m256i, mask8> {
__forceinline__ mask8 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask8 { _mm256_cmpeq_epi32(lhs, rhs) };
}
};
template<>
struct equal<$u64, __m256i, __m256i, mask4> : vector_fn<$u64, __m256i, __m256i, mask4> {
__forceinline__ mask4 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask4 { _mm256_cmpeq_epi64(lhs, rhs) };
}
};
template<>
struct not_equal<$i32, __m256i, __m256i, mask8> : vector_fn<$i32, __m256i, __m256i, mask8> {
__forceinline__ mask8 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask8 { _mm256_andnot_si256(_mm256_cmpeq_epi32(lhs, rhs), _mm256_set1_epi32(-1))};
}
};
template<>
struct not_equal<$u32, __m256i, __m256i, mask8> : vector_fn<$u32, __m256i, __m256i, mask8> {
__forceinline__ mask8 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask8 { _mm256_andnot_si256(_mm256_cmpeq_epi32(lhs, rhs), _mm256_set1_epi32(-1))};
}
};
template<>
struct not_equal<$i64, __m256i, __m256i, mask4> : vector_fn<$i64, __m256i, __m256i, mask4> {
__forceinline__ mask4 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask4 { _mm256_andnot_si256(_mm256_cmpeq_epi64(lhs, rhs), _mm256_set1_epi64x(-1))};
}
};
template<>
struct not_equal<$u64, __m256i, __m256i, mask4> : vector_fn<$u64, __m256i, __m256i, mask4> {
__forceinline__ mask4 operator()(const __m256i& lhs, const __m256i& rhs) const noexcept {
return mask4 { _mm256_andnot_si256(_mm256_cmpeq_epi64(lhs, rhs), _mm256_set1_epi64x(-1))};
}
};
} // namespace simd
} // namespace dtl
|
/*
* SPDX-FileCopyrightText: (C) 2014-2022 Daniel Nicoletti <dantti12@gmail.com>
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef RENDERVIEW_H
#define RENDERVIEW_H
#include <Cutelyst/action.h>
#include <Cutelyst/componentfactory.h>
#include <Cutelyst/cutelyst_global.h>
namespace Cutelyst {
class RenderViewPrivate;
class CUTELYST_PLUGIN_ACTION_RENDERVIEW_EXPORT RenderView final : public Action
{
Q_OBJECT
Q_DECLARE_PRIVATE(RenderView)
public:
/**
* Constructs a RenderView object with the given \arg parent.
*/
explicit RenderView(QObject *parent = nullptr);
/**
* Reimplemented from Plugin::init()
*/
virtual bool init(Application *application, const QVariantHash &args) override;
protected:
virtual bool doExecute(Cutelyst::Context *c) override;
};
class RenderViewFactory final : public QObject
, public ComponentFactory
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.cutelyst.ComponentFactory" FILE "metadata.json")
Q_INTERFACES(Cutelyst::ComponentFactory)
public:
virtual Component *createComponent(QObject *parent) override { return new RenderView(parent); }
};
} // namespace Cutelyst
#endif // RENDERVIEW_H
|
//
// Copyright Jason Rice 2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_WEB_ROUTE_HPP
#define NBDL_WEB_ROUTE_HPP
#include <nbdl/bind_sequence.hpp>
#include <nbdl/concept/String.hpp>
#include <nbdl/fwd/webui/route_map.hpp>
#include <nbdl/string.hpp>
#include <nbdl/variant.hpp>
#include <algorithm>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/list.hpp>
#include <boost/mp11/map.hpp>
#include <boost/hana/ext/std/array.hpp>
#include <boost/hana/unpack.hpp>
#include <boost/hana/type.hpp>
#include <iterator>
#include <mpdef/pair.hpp>
#include <mpdef/utility.hpp>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
namespace nbdl::webui
{
namespace hana = boost::hana;
using namespace boost::mp11;
namespace detail
{
template <typename X>
void append_route_param(std::string& s, X&& x)
{
s += '/';
if constexpr(nbdl::String<X>)
{
s += std::forward<X>(x);
}
else
{
s += std::to_string(std::forward<X>(x));
}
}
// zero is an invalid integral param
inline std::size_t to_integral_param(std::string_view param)
{
std::size_t result = 0;
for (char c : param)
{
std::size_t digit_value = c - '0';
if (digit_value > 9)
{
// invalid character
return 0;
}
result *= 10;
result += digit_value;
}
return result;
}
template <typename Member, typename = void>
struct bind_route_param_impl
{
bool operator()(Member& m, std::string_view param) const
{
m = param;
return m.size() > 0;
};
};
template <typename Member>
struct bind_route_param_impl<Member, std::enable_if_t<std::is_integral<Member>::value>>
{
bool operator()(Member& m, std::string_view param) const
{
m = to_integral_param(param);
return m != 0;
};
};
template <typename Member>
bool bind_route_param(Member& m, std::string_view param)
{
return bind_route_param_impl<Member>{}(m, param);
}
inline std::string_view parse_route_param(std::string_view& s)
{
if (s.size() == 0 || s[0] != '/')
{
return {};
}
// remove leading slash
s.remove_prefix(1);
std::size_t end_pos = std::min(s.find('/'), s.size());
auto* start_ptr = s.data();
s.remove_prefix(end_pos);
return std::string_view{start_ptr, end_pos};
}
template <typename ...Key>
struct route_names_impl
{
static constexpr auto apply()
{
return std::array<std::string_view, sizeof...(Key)>{{
std::string_view{Key{}.c_str(), hana::size(Key{})}...
}};
}
};
template <typename Map>
constexpr auto route_names = mp_apply<route_names_impl, mp_map_keys<Map>>::apply();
}
template <typename Map>
class route_map<Map>
{
// max 10 parameters
using Params = std::array<std::string_view, 10>;
using ReverseMap = mp_transform<mp_reverse, Map>;
using Variant = mp_apply<route_variant, mp_map_keys<ReverseMap>>;
Variant make_from_params(Params const& params, std::size_t params_count) const
{
auto itr = std::find_if(
detail::route_names<Map>.begin()
, detail::route_names<Map>.end()
, [&](auto const& x)
{
return params[0] == x;
}
);
if (itr == detail::route_names<Map>.end())
{
return Variant{};
}
else
{
std::size_t const offset = std::distance(detail::route_names<Map>.begin(), itr);
Variant var{};
mp_with_index<mp_size<Map>::value>(offset, [&](auto index)
{
using T = mp_at<mp_map_keys<ReverseMap>, decltype(index)>;
T value{};
nbdl::bind_sequence(value, [&](auto& ...member)
{
// To match the parameter pack sizes we have to create an
// array of the same amount of elements.
using SubParams = std::array<std::string_view, sizeof...(member) + 1>;
SubParams sub_params = {};
for (std::size_t i = 0; i < sub_params.size(); i++) {
sub_params[i] = params[i];
}
hana::unpack(sub_params, [&](auto&&, auto ...param)
{
if (sizeof...(member) != params_count - 1)
{
var = Variant{};
return;
}
bool is_params_valid = (detail::bind_route_param(member, param) && ...);
if (is_params_valid)
{
var = value;
}
else
{
// a param was invalid
var = Variant{};
}
});
});
});
return var;
}
}
public:
static auto get_type(auto route_name)
{
return hana::type_c<mp_second<mp_map_find<
Map
, decltype(route_name)
>>>;
}
template <typename T>
Variant to_variant(T&& t) const
{
return Variant(std::forward<T>(t));
}
template <typename T>
nbdl::string to_string(T&& t) const
{
using String = mp_second<mp_map_find<ReverseMap, std::decay_t<T>>>;
static_assert(
!std::is_void<String>::value
, "Route string must map to type in route map."
);
nbdl::string temp{};
temp.reserve(50);
temp += '/';
temp += std::string_view(String{}.c_str(), hana::size(String{}));
nbdl::bind_sequence(std::forward<T>(t), [&](auto&& ...xs)
{
(detail::append_route_param(temp, std::forward<decltype(xs)>(xs)), ...);
});
return temp;
}
Variant from_string(nbdl::string const& s) const
{
Variant v{};
if (s.size() < 1 || *s.begin() != '/')
{
return Variant{};
}
// params include the name of the route
Params params{};
std::size_t params_count = 0;
std::string_view view(&(*s.begin()), s.size());
if (s.size() == 1)
{
// root
params_count = 1;
}
else
{
for (auto& x : params)
{
x = detail::parse_route_param(view);
if (x.size() == 0)
{
break;
}
params_count++;
}
// trailing params
if (view.size() != 0)
{
return Variant{};
}
}
return make_from_params(params, params_count);
}
// expose variant type
using variant = Variant;
};
template <typename ...Pairs>
constexpr auto make_route_map_fn::operator()(Pairs ...) const
{
return route_map<mp_list<Pairs...>>{};
}
}
#endif
|
/*
BFS Approach
*/
#include<bits/stdc++.h>
using namespace std;
void bfs(vector<int> &matrix[],int x,int y,int r,int c)
{
if(x<0 || x>=r || y<0 || y>=c || matrix[x][y]!='1') //Boundary case for matrix
return;
//Mark current cell as visited
matrix[x][y] = '2';
//Make recursive call in all 4 adjacent directions
bfs(matrix,x+1,y,r,c); //DOWN
bfs(matrix,x,y+1,r,c); //RIGHT
bfs(matrix,x-1,y,r,c); //TOP
bfs(matrix,x,y-1,r,c); //LEFT
}
int numIslands(vector<int> grid[]){
int rows=grid.size();
if(rows==0){
return 0;
}
int cols=grid[0].size();
int res=0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(grid[i][j]==1){
bfs(grid,i,j,rows,cols);
res+=1
}
}
}
}
int main(){
int r,c;
cin>>r>>c;
vector<int> grid[c];
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
cin>>grid[i][j];
}
}
cout<<numIslands(gird)<<endl;
}
|
#include <string>
#include <QFile>
#ifndef _pfm_h_
#define _pfm_h_
using namespace std;
typedef int RC;
typedef unsigned PageNum;
const int PAGE_SIZE = 4096;
#define PAGED_FILE_HEADER_STRING "PAGED_FILE__"
const int PAGED_FILE_HEADER_STRING_LENGTH = 12;
#define SUCCESS 0
class FileHandle;
class PagedFileManager
{
public:
static PagedFileManager* instance(); // Access to the _pf_manager instance
RC createFile (const char *fileName); // Create a new file
RC destroyFile (const char *fileName); // Destroy a file
RC openFile (const char *fileName, FileHandle &fileHandle); // Open a file
RC closeFile (FileHandle &fileHandle); // Close a file
protected:
PagedFileManager(); // Constructor
~PagedFileManager(); // Destructor
private:
static PagedFileManager *_pf_manager;
// Auxiliary methods.
bool FileExists(string fileName);
};
class FileHandle
{
public:
FileHandle(); // Default constructor
FileHandle(char* fileName); // Overloaded constructor
~FileHandle(); // Destructor
RC readPage(PageNum pageNum, void *&data); // Get a specific page
RC writePage(PageNum pageNum, const void *data); // Write a specific page
RC appendPage(const void *data); // Append a specific page
RC appendEmptyPage(); // Append an empty page
unsigned getNumberOfPages(); // Get the number of pages in the file
// Auxiliary methods.
QFile* getQFile();
private:
QFile _qfile;
};
#endif
|
#include<bits/stdc++.h>
#include<string>
using namespace std;
struct et
{
string value;
et* left, *right;
};
int toInt(string s)
{
int num = 0;
for (int i=0; i<s.length(); i++)
num = num*10 + (int(s[i])-48);
return num;
}
int eval(et* root)
{
if (!root)
return 0;
if (!root->left && !root->right)
return toInt(root->value);
int l_val = eval(root->left);
int r_val = eval(root->right);
string w=root->value;
if (w[0]=='+')
return l_val+r_val;
if (w[0]=='-')
return l_val-r_val;
if (w[0]=='/')
return l_val*r_val;
if (w[0]=='*')
return l_val*r_val;
if(w[0]=='^')
return pow(l_val,r_val);
return l_val/r_val;
}
int isOperator(string s)
{if(s[0]=='+'||s[0]=='*'||s[0]=='-'||s[0]=='/'||s[0]=='^')
return(1);
else
return(0);}
et* newNode(string v)
{
et *temp = new et;
temp->left = temp->right = NULL;
temp->value = v;
return temp;
};
et* constructTree(vector<string> j)
{
stack<et *> st;
et *t, *t1, *t2;
for (int i=0; i<j.size(); i++)
{
if (!isOperator(j[i]))
{
t = newNode(j[i]);
st.push(t);
}
else
{
t = newNode(j[i]);
t1 = st.top();
st.pop();
t2 = st.top();
st.pop();
t->right = t1;
t->left = t2;
st.push(t);
}
}
t = st.top();
st.pop();
return t;
}
int prec(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}
vector <string> intopo(string s)
{ stack<string> st;
string x;
st.push(x);
vector<string> ns;
for(int i = 0; i < s.length(); i++)
{ string q="";
string r;
while(s[i] >= '0' && s[i] <= '9')
{
q.push_back(s[i]);
i++; }
ns.push_back(q);
q.clear();
if(((s[0] >= 'a' && s[0] <= 'z')||(s[0] >= 'A' && s[0] <= 'Z'))&&(s[1]=='='))
{string r="";
for(int d=0;d<s.length();d++){
r.push_back(s[i]);
ns.push_back(r);}}
r.clear();
if(s[i] == '(')
{string r="";
r.push_back(s[i]);
st.push(r);}
r.clear();
string d="(";
if(s[i] == ')')
{
while(st.top() != x && st.top() !=d)
{
string c = st.top();
st.pop();
ns.push_back(c);
}
if(st.top() == d)
{
string c = st.top();
st.pop();
}
}
if(s[i]=='+'||s[i]=='/'||s[i]=='*'||s[i]=='-'||s[i]=='^'){ string f=st.top();
char c=f[0];
while(st.top() != x && prec(s[i]) <= prec(c))
{
string h = st.top();
st.pop();
char c=h[0];
ns.push_back(h);
}
string r="";
r.push_back(s[i]);
st.push(r);
} }
while(st.top() != x)
{
string c = st.top();
st.pop();
ns.push_back(c);
}
return ns;
}
int main()
{ int k,l,a,num;
cin>>k>>a;
string o;
for(l=0;l<k;l++)
{ for(int v=0;v<a;v++)
{
cin>>o;
vector<string> j = intopo(o);
int i;
et* a = constructTree(j) ;
num = eval(a);
cout<<num<<endl;}
}
}
|
#include <set>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char buffer[32];
set<string> values;
for (int i = 0; i < 100; i++) {
snprintf(buffer, sizeof(buffer), "%2.2d", i);
values.insert(buffer);
}
auto it = values.begin();
while (it != values.end()) {
if (it->c_str()[it->length()-1] == '0' ||
it->c_str()[it->length()-1] == '5') {
// set<string>::iterator it2 = it;
// it2++;
values.erase(it);
it++;
// it = it2;
} else {
it++;
}
}
for (it = values.begin(); it != values.end(); it++) {
printf("%s\n", it->c_str());
}
string abc = "abc";
abc += std::to_string(20);
printf("%s\n", abc.c_str());
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
// Function to create new tree node.
Node* newNode(int key)
{
Node* temp = new Node;
temp->data = key;
temp->left = temp->right = NULL;
return temp;
}
int helper(Node* root,int& ans)
{
if(root==NULL)
{
return 0;
}
int left = helper(root->left,ans);
int right = helper(root->right,ans);
int total = root->data + left + right;
ans = max(ans,total);
return total;
}
int solve(Node* root)
{
if(root==NULL)
{
return 0;
}
int ans = INT_MIN;
int temp = helper(root,ans);
return ans;
}
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
cout << solve(root) << endl;
return 0;
}
|
#ifndef MATHTOOLBOX_CLASSICAL_MDS_HPP
#define MATHTOOLBOX_CLASSICAL_MDS_HPP
#include <Eigen/Core>
#include <Eigen/Eigenvalues>
namespace mathtoolbox
{
/// \brief Compute low-dimensional embedding by using classical multi-dimensional scaling (MDS)
///
/// \param D Distance (dissimilarity) matrix
///
/// \param target_dim Target dimensionality
///
/// \return Coordinate matrix whose i-th column corresponds to the embedded coordinates of the i-th entry
Eigen::MatrixXd ComputeClassicalMds(const Eigen::MatrixXd& D, const unsigned taregt_dim);
} // namespace mathtoolbox
#endif // MATHTOOLBOX_CLASSICAL_MDS_HPP
|
#include "StdAfx.h"
#include "About.h"
#include "Resource.h"
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
DDX_Control(pDX, IDC_GIFABOUT, m_Picture);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL CAboutDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
if (m_Picture.Load(MAKEINTRESOURCE(IDR_TYPE),_T("GIF")))
m_Picture.Draw();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
|
/***********************************************************************
created: 27/01/2022
author: Vladimir Orlov
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2022 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 "CEGUI/text/RenderedText.h"
#include "CEGUI/text/RenderedTextParagraph.h"
#include "CEGUI/text/RenderedTextStyle.h"
#include "CEGUI/text/TextParser.h"
#include "CEGUI/text/TextUtils.h"
#ifdef CEGUI_BIDI_SUPPORT
#include "CEGUI/text/BidiVisualMapping.h"
#endif
#ifdef CEGUI_USE_RAQM
#include "CEGUI/text/FreeTypeFont.h"
#include <raqm.h>
#include <algorithm>
#else
#include "CEGUI/text/Font.h"
#include "CEGUI/text/FontGlyph.h"
#endif
namespace CEGUI
{
//----------------------------------------------------------------------------//
RenderedText::RenderedText() = default;
RenderedText::~RenderedText() = default;
RenderedText::RenderedText(RenderedText&&) noexcept = default;
RenderedText& RenderedText::operator =(RenderedText&&) noexcept = default;
//----------------------------------------------------------------------------//
static bool layoutParagraph(RenderedTextParagraph& out, const std::u32string& text,
size_t start, size_t end, DefaultParagraphDirection dir,
const std::vector<uint16_t>& elementIndices,
const std::vector<RenderedTextElementPtr>& elements)
{
// Apply Unicode Bidirectional Algorithm to obtain a string with visual ordering of codepoints
#if defined(CEGUI_BIDI_SUPPORT)
//!!!TODO TEXT: implement partial inplace BIDI, can pass mutable "text" here!
std::vector<int> l2v;
std::vector<int> v2l;
std::u32string textVisual;
if (!BidiVisualMapping::applyBidi(text.c_str() + start, end - start, textVisual, l2v, v2l, dir))
return false;
out.setBidiDirection(dir);
#else
const auto& textVisual = text;
#endif
// Glyph generation
out.glyphs().resize(end - start);
const Font* currFont = nullptr;
const FontGlyph* prevGlyph = nullptr;
for (size_t i = start; i < end; ++i)
{
#if defined(CEGUI_BIDI_SUPPORT)
const size_t visualIndex = i - start;
const size_t logicalIndex = v2l[visualIndex] + start;
#else
const size_t visualIndex = i;
const size_t logicalIndex = i;
#endif
const auto codePoint = textVisual[visualIndex];
auto& renderedGlyph = out.glyphs()[i - start];
const auto elementIndex = (logicalIndex < elementIndices.size()) ?
elementIndices[logicalIndex] :
elements.size() - 1;
// Get a font for the current character
Font* font = elements[elementIndex]->getFont();
if (!font)
return false;
renderedGlyph.fontGlyphIndex = font->getGlyphIndexForCodepoint(codePoint);
auto fontGlyph = font->loadGlyph(renderedGlyph.fontGlyphIndex);
if (fontGlyph)
{
const float kerning = font->getKerning(prevGlyph, *fontGlyph);
renderedGlyph.offset.x = kerning;
renderedGlyph.advance = fontGlyph->getAdvance() + kerning;
}
else
{
renderedGlyph.offset.x = 0.f;
renderedGlyph.advance = 0.f;
}
renderedGlyph.sourceIndex = static_cast<uint32_t>(logicalIndex);
renderedGlyph.sourceLength = 1;
renderedGlyph.offset.y = font->getBaseline();
#if defined(CEGUI_BIDI_SUPPORT)
renderedGlyph.isRightToLeft = (BidiVisualMapping::getBidiCharType(codePoint) == BidiCharType::RIGHT_TO_LEFT);
#else
renderedGlyph.isRightToLeft = false;
#endif
prevGlyph = fontGlyph;
}
return true;
}
//----------------------------------------------------------------------------//
#ifdef CEGUI_USE_RAQM
static bool layoutParagraphWithRaqm(RenderedTextParagraph& out, const std::u32string& text,
size_t start, size_t end, DefaultParagraphDirection dir,
const std::vector<uint16_t>& elementIndices,
const std::vector<RenderedTextElementPtr>& elements, raqm_t*& rq)
{
const size_t elementIdxCount = elementIndices.size();
// Build font ranges an check if we can use raqm before we allocate something big inside it
std::vector<std::pair<FreeTypeFont*, size_t>> fontRanges;
if (start >= elementIdxCount)
{
// Only freetype fonts can be laid out with raqm
auto ftDefaultFont = dynamic_cast<FreeTypeFont*>(elements.back()->getFont());
if (!ftDefaultFont)
return false;
fontRanges.emplace_back(ftDefaultFont, end - start);
}
else
{
fontRanges.reserve(16);
size_t fontLen = 0;
FreeTypeFont* currFont = nullptr;
for (size_t i = start; i < end; ++i)
{
const auto elementIndex = (i < elementIndices.size()) ?
elementIndices[i] :
elements.size() - 1;
// Get a font for the current character
Font* charFont = elements[elementIndex]->getFont();
if (!charFont)
return false;
if (charFont != currFont)
{
// Only freetype fonts can be laid out with raqm
auto ftCharFont = dynamic_cast<FreeTypeFont*>(charFont);
if (!ftCharFont)
return false;
if (fontLen)
fontRanges.emplace_back(currFont, fontLen);
currFont = ftCharFont;
fontLen = 0;
}
++fontLen;
}
// Add the final range
if (fontLen)
fontRanges.emplace_back(currFont, fontLen);
}
// Now we know that we can use raqm for this paragraph
if (rq)
{
raqm_clear_contents(rq);
}
else
{
rq = raqm_create();
const raqm_direction_t raqmParagraphDir =
(dir == DefaultParagraphDirection::RightToLeft) ? RAQM_DIRECTION_RTL :
(dir == DefaultParagraphDirection::Automatic) ? RAQM_DIRECTION_DEFAULT :
RAQM_DIRECTION_LTR;
if (!raqm_set_par_direction(rq, raqmParagraphDir))
return false;
}
// Assign only the paragraph text to raqm object
if (!raqm_set_text(rq, reinterpret_cast<const uint32_t*>(text.c_str() + start), end - start))
return false;
// Assign font ranges to raqm
size_t fontStart = 0;
for (auto& range : fontRanges)
{
if (!raqm_set_freetype_face_range(rq, range.first->getFontFace(), fontStart, range.second))
return false;
if (!raqm_set_freetype_load_flags_range(rq, range.first->getGlyphLoadFlags(), fontStart, range.second))
return false;
fontStart += range.second;
range.second = fontStart; // Change (font, len) into sorted (font, end) for glyph font detection below
}
if (!raqm_layout(rq))
return false;
const raqm_direction_t rqDir = raqm_get_par_resolved_direction(rq);
out.setBidiDirection(
(rqDir == RAQM_DIRECTION_RTL) ? DefaultParagraphDirection::RightToLeft :
(rqDir == RAQM_DIRECTION_DEFAULT) ? DefaultParagraphDirection::Automatic :
DefaultParagraphDirection::LeftToRight);
// Glyph generation
size_t rqGlyphCount = 0;
raqm_glyph_t* rqGlyphs = raqm_get_glyphs(rq, &rqGlyphCount);
out.glyphs().resize(rqGlyphCount);
for (size_t i = 0; i < rqGlyphCount; ++i)
{
const raqm_glyph_t& rqGlyph = rqGlyphs[i];
const raqm_direction_t rqGlyphDir = raqm_get_direction_at_index(rq, i);
auto& renderedGlyph = out.glyphs()[i];
// Find a font for our glyph
auto it = std::upper_bound(fontRanges.begin(), fontRanges.end(), rqGlyph.cluster,
[](uint32_t value, const std::pair<const FreeTypeFont*, size_t>& elm)
{
return value < elm.second;
});
FreeTypeFont* font = (*it).first;
renderedGlyph.fontGlyphIndex = font->getGlyphIndexByFreetypeIndex(rqGlyph.index);
font->loadGlyph(renderedGlyph.fontGlyphIndex);
// A multiplication coefficient to convert 26.6 fixed point values into normal floats
constexpr float s_26dot6_toFloat = (1.0f / 64.f);
renderedGlyph.sourceIndex = static_cast<uint32_t>(rqGlyph.cluster + start);
renderedGlyph.sourceLength = 1;
renderedGlyph.offset.x = rqGlyph.x_offset * s_26dot6_toFloat;
renderedGlyph.offset.y = rqGlyph.y_offset * s_26dot6_toFloat + font->getBaseline();
renderedGlyph.advance = ((rqGlyphDir == RAQM_DIRECTION_TTB) ? rqGlyph.y_advance : rqGlyph.x_advance) * s_26dot6_toFloat;
renderedGlyph.isRightToLeft = (rqGlyphDir == RAQM_DIRECTION_RTL);
}
return true;
}
#endif
//----------------------------------------------------------------------------//
bool RenderedText::renderText(const String& text, TextParser* parser,
Font* defaultFont, DefaultParagraphDirection defaultParagraphDir)
{
d_paragraphs.clear();
d_elements.clear();
d_defaultFont = defaultFont;
if (text.empty())
return true;
// Parse a string and obtain UTF-32 text with embedded object placeholders but without tags
std::u32string utf32Text;
std::vector<size_t> originalIndices;
std::vector<uint16_t> elementIndices;
if (!parser || !parser->parse(text, utf32Text, originalIndices, elementIndices, d_elements))
{
// If no parser specified or parsing failed, render the text verbatim
#if (CEGUI_STRING_CLASS != CEGUI_STRING_CLASS_UTF_32)
utf32Text = String::convertUtf8ToUtf32(text.c_str(), &originalIndices);
#else
originalIndices.clear();
utf32Text = text.getString();
#endif
}
// No text or placeholders left after parsing, there is nothing to render
if (utf32Text.empty())
return true;
const size_t utf32TextLength = utf32Text.size();
// There are characters without associated text style. Add a default one.
if (elementIndices.size() < utf32TextLength)
d_elements.emplace_back(new RenderedTextStyle());
// Characters without an explicit font must use a default font
for (auto& element : d_elements)
{
if (element->getFont())
continue;
if (!defaultFont)
return false;
element->setFont(defaultFont);
}
#ifdef CEGUI_USE_RAQM
raqm_t* rq = nullptr;
#endif
// Perform layouting per paragraph
size_t start = 0;
DefaultParagraphDirection lastBidiDir = DefaultParagraphDirection::LeftToRight;
do
{
size_t end = utf32Text.find_first_of(TextUtils::UTF32_NEWLINE_CHARACTERS, start);
if (end == std::u32string::npos)
end = utf32TextLength;
// Always create a paragraph (new line), even if it is empty
d_paragraphs.emplace_back(static_cast<uint32_t>(start), static_cast<uint32_t>(end));
auto& p = d_paragraphs.back();
if (end > start)
{
// Create and setup a sequence of CEGUI glyphs for this paragraph
#ifdef CEGUI_USE_RAQM
if (!layoutParagraphWithRaqm(p, utf32Text, start, end, defaultParagraphDir, elementIndices, d_elements, rq))
#endif
layoutParagraph(p, utf32Text, start, end, defaultParagraphDir, elementIndices, d_elements);
// Inherit explicit direction from the previous text for direction neutral paragraphs
if (p.getBidiDirection() == DefaultParagraphDirection::Automatic)
p.setBidiDirection(lastBidiDir);
else
lastBidiDir = p.getBidiDirection();
p.setupGlyphs(utf32Text, elementIndices, d_elements);
}
p.remapSourceIndices(originalIndices, text.size());
if (end == utf32TextLength)
break;
// \r\n (CRLF) should be treated as a single newline according to Unicode spec
if (end < utf32TextLength - 1 && utf32Text[end] == '\r' && utf32Text[end + 1] == '\n')
++end;
start = end + 1;
}
while (true);
// Push default formatting to paragraphs
// NB: there should not be early exit when unchanged, paragraphs will handle this
setHorizontalFormatting(d_horzFormatting);
setLastJustifiedLineFormatting(d_lastJustifiedLineFormatting);
setWordWrapEnabled(d_wordWrap);
#if defined(CEGUI_USE_RAQM)
if (rq)
raqm_destroy(rq);
#endif
return true;
}
//----------------------------------------------------------------------------//
void RenderedText::updateDynamicObjectExtents(const Window* hostWindow)
{
// Update metrics of dynamic objects and notify the text about their resizing
for (size_t i = 0; i < d_elements.size(); ++i)
{
const auto diff = d_elements[i]->updateMetrics(hostWindow);
if (diff.d_width)
for (auto& p : d_paragraphs)
p.onElementWidthChanged(i, diff.d_width);
if (diff.d_height)
for (auto& p : d_paragraphs)
p.onElementHeightChanged(i, diff.d_height);
}
}
//----------------------------------------------------------------------------//
bool RenderedText::updateFormatting(float areaWidth)
{
if (areaWidth < 0.f)
return false;
const bool areaWidthChanged = (d_areaWidth != areaWidth);
d_areaWidth = areaWidth;
const float defaultFontHeight = d_defaultFont ? d_defaultFont->getFontHeight() : 0.f;
Rectf extents;
bool fitsIntoAreaWidth = true;
for (auto& p : d_paragraphs)
{
if (areaWidthChanged)
p.onAreaWidthChanged();
p.updateLines(d_elements, areaWidth);
p.updateLineHeights(d_elements, defaultFontHeight);
p.updateHorizontalFormatting(areaWidth);
p.accumulateExtents(extents);
fitsIntoAreaWidth &= p.isFittingIntoAreaWidth();
}
d_extents = extents.getSize();
if (d_paragraphs.empty())
d_extents.d_height = defaultFontHeight;
return fitsIntoAreaWidth;
}
//----------------------------------------------------------------------------//
void RenderedText::createRenderGeometry(std::vector<GeometryBuffer*>& out,
const glm::vec2& position, const ColourRect* modColours, const Rectf* clipRect,
const SelectionInfo* selection) const
{
glm::vec2 penPosition = position;
for (const auto& p : d_paragraphs)
p.createRenderGeometry(out, penPosition, modColours, clipRect, selection, d_elements);
}
//----------------------------------------------------------------------------//
RenderedText RenderedText::clone() const
{
RenderedText copy;
for (const auto& component : d_elements)
copy.d_elements.push_back(component->clone());
copy.d_paragraphs = d_paragraphs;
copy.d_defaultFont = d_defaultFont;
copy.d_areaWidth = d_areaWidth;
copy.d_horzFormatting = d_horzFormatting;
copy.d_lastJustifiedLineFormatting = d_lastJustifiedLineFormatting;
copy.d_wordWrap = d_wordWrap;
return copy;
}
//----------------------------------------------------------------------------//
void RenderedText::setHorizontalFormatting(HorizontalTextFormatting fmt)
{
d_horzFormatting = fmt;
for (auto& p : d_paragraphs)
if (p.isHorzFormattingDefault())
p.setHorizontalFormatting(fmt, false);
}
//----------------------------------------------------------------------------//
void RenderedText::setLastJustifiedLineFormatting(HorizontalTextFormatting fmt)
{
d_lastJustifiedLineFormatting = fmt;
for (auto& p : d_paragraphs)
if (p.isLastJustifiedLineFormattingDefault())
p.setLastJustifiedLineFormatting(fmt, false);
}
//----------------------------------------------------------------------------//
void RenderedText::setWordWrapEnabled(bool wrap)
{
d_wordWrap = wrap;
for (auto& p : d_paragraphs)
if (p.isWordWrapDefault())
p.setWordWrapEnabled(wrap, false);
}
//----------------------------------------------------------------------------//
size_t RenderedText::getLineCount() const
{
size_t count = 0;
for (const auto& p : d_paragraphs)
count += p.getLineCount();
return count;
}
//----------------------------------------------------------------------------//
bool RenderedText::isFittingIntoAreaWidth() const
{
for (const auto& p : d_paragraphs)
if (!p.isFittingIntoAreaWidth())
return false;
return true;
}
//----------------------------------------------------------------------------//
size_t RenderedText::getTextIndexAtPoint(const glm::vec2& pt, float* outRelPos) const
{
if (pt.y < 0.f)
return 0;
if (pt.y > d_extents.d_height)
return npos;
glm::vec2 localPt = pt;
for (size_t i = 0; i < d_paragraphs.size(); ++i)
{
const auto& p = d_paragraphs[i];
// Find the paragraph at the given height range
const float paragraphHeight = p.getHeight();
if (localPt.y > paragraphHeight)
{
localPt.y -= paragraphHeight;
continue;
}
const auto idx = p.getTextIndexAtPoint(localPt, d_areaWidth, outRelPos);
// No text at point means the end of the paragraph
if (idx == RenderedTextParagraph::npos)
return d_paragraphs[i].getSourceEndIndex();
return idx;
}
return npos;
}
//----------------------------------------------------------------------------//
bool RenderedText::getTextIndexBounds(size_t textIndex, Rectf& out, bool* outRtl) const
{
// We still have an empty line when there is no text at all
if (d_paragraphs.empty())
{
switch (d_horzFormatting)
{
case HorizontalTextFormatting::CentreAligned: out.d_min.x = d_areaWidth * 0.5f; break;
case HorizontalTextFormatting::RightAligned: out.d_min.x = d_areaWidth; break;
default: out.d_min.x = 0.f; break;
}
out.d_max.x = out.d_min.x;
out.d_min.y = 0.f;
out.d_max.y = d_defaultFont ? d_defaultFont->getFontHeight() : 0.f;
if (outRtl)
*outRtl = false;
return true;
}
float offsetY;
const auto idx = findParagraphIndex(textIndex, offsetY);
if (!d_paragraphs[idx].getTextIndexBounds(out, outRtl, textIndex, d_elements, d_areaWidth))
return false;
out.d_min.y += offsetY;
out.d_max.y += offsetY;
return true;
}
//----------------------------------------------------------------------------//
size_t RenderedText::nextTextIndex(size_t textIndex) const
{
if (d_paragraphs.empty())
return npos;
float offsetY;
const auto parIdx = findParagraphIndex(textIndex, offsetY);
const auto idx = d_paragraphs[parIdx].nextTextIndex(textIndex);
if (textIndex == d_paragraphs[parIdx].getSourceEndIndex() && parIdx + 1 < d_paragraphs.size())
return d_paragraphs[parIdx + 1].getSourceStartIndex();
return idx;
}
//----------------------------------------------------------------------------//
size_t RenderedText::prevTextIndex(size_t textIndex) const
{
if (d_paragraphs.empty())
return npos;
float offsetY;
const auto parIdx = findParagraphIndex(textIndex, offsetY);
const auto idx = d_paragraphs[parIdx].prevTextIndex(textIndex);
if (textIndex == d_paragraphs[parIdx].getSourceStartIndex() && parIdx > 0)
return d_paragraphs[parIdx - 1].getSourceEndIndex();
return idx;
}
//----------------------------------------------------------------------------//
size_t RenderedText::lineUpTextIndex(size_t textIndex, float desiredOffsetX) const
{
if (d_paragraphs.empty())
return npos;
float offsetY;
const auto parIdx = findParagraphIndex(textIndex, offsetY);
const auto& par = d_paragraphs[parIdx];
const auto lineIdx = par.getLineIndex(textIndex);
if (lineIdx)
return par.getTextIndex(lineIdx - 1, desiredOffsetX, d_areaWidth);
if (!parIdx)
return textIndex;
const auto& prevPar = d_paragraphs[parIdx - 1];
return prevPar.getTextIndex(prevPar.getLineCount() - 1, desiredOffsetX, d_areaWidth);
}
//----------------------------------------------------------------------------//
size_t RenderedText::lineDownTextIndex(size_t textIndex, float desiredOffsetX) const
{
if (d_paragraphs.empty())
return npos;
float offsetY;
const auto parIdx = findParagraphIndex(textIndex, offsetY);
const auto& par = d_paragraphs[parIdx];
const auto lineIdx = par.getLineIndex(textIndex);
if (lineIdx + 1 < par.getLineCount())
return par.getTextIndex(lineIdx + 1, desiredOffsetX, d_areaWidth);
if (parIdx + 1 >= d_paragraphs.size())
return textIndex;
return d_paragraphs[parIdx + 1].getTextIndex(0, desiredOffsetX, d_areaWidth);
}
//----------------------------------------------------------------------------//
size_t RenderedText::pageUpTextIndex(size_t textIndex, float desiredOffsetX, float pageHeight) const
{
if (d_paragraphs.empty())
return npos;
float offsetY;
const auto parIdx = findParagraphIndex(textIndex, offsetY);
const auto& par = d_paragraphs[parIdx];
const auto lineIdx = par.getLineIndex(textIndex);
offsetY += par.getLineOffsetY(lineIdx);
offsetY += par.getLineHeight(lineIdx) * 0.5f;
return getTextIndexAtPoint(glm::vec2(desiredOffsetX, std::max(0.f, offsetY - pageHeight)));
}
//----------------------------------------------------------------------------//
size_t RenderedText::pageDownTextIndex(size_t textIndex, float desiredOffsetX, float pageHeight) const
{
if (d_paragraphs.empty())
return npos;
float offsetY;
const auto parIdx = findParagraphIndex(textIndex, offsetY);
const auto& par = d_paragraphs[parIdx];
const auto lineIdx = par.getLineIndex(textIndex);
offsetY += par.getLineOffsetY(lineIdx);
offsetY += par.getLineHeight(lineIdx) * 0.5f;
return getTextIndexAtPoint(glm::vec2(desiredOffsetX, std::min(d_extents.d_height, offsetY + pageHeight)));
}
//----------------------------------------------------------------------------//
size_t RenderedText::lineStartTextIndex(size_t textIndex) const
{
if (d_paragraphs.empty())
return npos;
float offsetY;
const auto parIdx = findParagraphIndex(textIndex, offsetY);
const auto& par = d_paragraphs[parIdx];
return par.getLineStartTextIndex(par.getLineIndex(textIndex));
}
//----------------------------------------------------------------------------//
size_t RenderedText::lineEndTextIndex(size_t textIndex) const
{
if (d_paragraphs.empty())
return npos;
float offsetY;
const auto parIdx = findParagraphIndex(textIndex, offsetY);
const auto& par = d_paragraphs[parIdx];
return par.getLineEndTextIndex(par.getLineIndex(textIndex));
}
//----------------------------------------------------------------------------//
size_t RenderedText::paragraphStartTextIndex(size_t textIndex) const
{
if (d_paragraphs.empty())
return npos;
float offsetY;
const auto parIdx = findParagraphIndex(textIndex, offsetY);
return d_paragraphs[parIdx].getSourceStartIndex();
}
//----------------------------------------------------------------------------//
size_t RenderedText::paragraphEndTextIndex(size_t textIndex) const
{
if (d_paragraphs.empty())
return npos;
float offsetY;
const auto parIdx = findParagraphIndex(textIndex, offsetY);
return d_paragraphs[parIdx].getSourceEndIndex();
}
//----------------------------------------------------------------------------//
size_t RenderedText::endTextIndex() const
{
return d_paragraphs.empty() ? npos : d_paragraphs.back().getSourceEndIndex();
}
//----------------------------------------------------------------------------//
size_t RenderedText::findParagraphIndex(size_t textIndex, float& offsetY) const
{
offsetY = 0.f;
const auto paragraphCount = d_paragraphs.size();
for (size_t i = 0; i < paragraphCount; ++i)
{
const auto& p = d_paragraphs[i];
if (i + 1 == paragraphCount || d_paragraphs[i + 1].getSourceStartIndex() > textIndex)
return i;
offsetY += p.getHeight();
}
return paragraphCount;
}
}
|
#include <nodelet/nodelet.h>
#include <pluginlib/class_list_macros.h>
#include "test_nodelets/calc_diff_time.h"
namespace calculators{
class DiffTimeNodelet : public nodelet::Nodelet {
public:
DiffTimeNodelet(){}
~DiffTimeNodelet(){}
virtual void onInit()
{
ros::NodeHandle nh = this->getPrivateNodeHandle();
std::string name = nh.getUnresolvedNamespace();
name = name.substr(name.find_last_of('/') + 1);
NODELET_INFO_STREAM("Initialising nodelet... [" << name << "]");
diff_time_.reset(new DiffTimeClass(nh, name));
diff_time_->init();
}
private:
boost::shared_ptr<DiffTimeClass> diff_time_;
};
}
PLUGINLIB_EXPORT_CLASS(calculators::DiffTimeNodelet,
nodelet::Nodelet);
|
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
long long int count=0,x1;
typedef struct AVLNode_t
{
long long int data,check;
long long int arr[100];
struct AVLNode_t *left,*right;
long long int height;
}AVLNode;
typedef struct AVL_t
{
AVLNode *_root;
unsigned int _size;
}AVL;
AVLNode* _avl_createNode(long long int value) {
AVLNode *newNode = (AVLNode*) malloc(sizeof(AVLNode));
newNode->data = value;
newNode->height=1;
newNode->check=0;
long long int flag=0;
for(int test =0; test <newNode->check;test++){
if(x1 == newNode->arr[test]) {
flag=1;
}
}
if( flag == 0){
newNode->arr[newNode->check] = x1;
newNode->check++;
count++;
}
newNode->left = newNode->right = NULL;
return newNode;
}
AVLNode* _search(AVLNode *root, long long int value)
{
while (root != NULL) {
if (value < root->data)
root = root->left;
else if (value > root->data)
root = root->right;
else
{
long long int flag=0;
for(int test =0; test <root->check;test++)
{
if(x1 == root->arr[test])
{
flag=1;
}
}
if( flag == 0)
{
root->arr[root->check] = x1;
root->check++;
count++;
}
return root;
}
}
return root;
}
int _getHeight(AVLNode* node){
if(node==NULL)
return 0;
return node->height;
}
int _max(int a,int b){
return (a > b)? a : b;
}
AVLNode* _rightRotate(AVLNode* pivotNode){
AVLNode* newParrent=pivotNode->left;
pivotNode->left=newParrent->right;
newParrent->right=pivotNode;
pivotNode->height=_max(_getHeight(pivotNode->left),
_getHeight(pivotNode->right))+1;
newParrent->height=_max(_getHeight(newParrent->left),
_getHeight(newParrent->right))+1;
return newParrent;
}
AVLNode* _leftRotate(AVLNode* pivotNode) {
AVLNode* newParrent=pivotNode->right;
pivotNode->right=newParrent->left;
newParrent->left=pivotNode;
pivotNode->height=_max(_getHeight(pivotNode->left),
_getHeight(pivotNode->right))+1;
newParrent->height=_max(_getHeight(newParrent->left),
_getHeight(newParrent->right))+1;
return newParrent;
}
AVLNode* _leftCaseRotate(AVLNode* node){
return _rightRotate(node);
}
AVLNode* _rightCaseRotate(AVLNode* node){
return _leftRotate(node);
}
AVLNode* _leftRightCaseRotate(AVLNode* node){
node->left=_leftRotate(node->left);
return _rightRotate(node);
}
AVLNode* _rightLeftCaseRotate(AVLNode* node){
node->right=_rightRotate(node->right);
return _leftRotate(node);
}
int _getBalanceFactor(AVLNode* node){
if(node==NULL)
return 0;
return _getHeight(node->left)-_getHeight(node->right);
}
AVLNode* _insert_AVL(AVL *avl,AVLNode* node,int value){
if(node==NULL){
return _avl_createNode(value);
}
if(value < node->data)
node->left = _insert_AVL(avl,node->left,value);
else if(value > node->data)
node->right = _insert_AVL(avl,node->right,value);
node->height= 1 + _max(_getHeight(node->left),_getHeight(node->right));
int balanceFactor=_getBalanceFactor(node);
if(balanceFactor > 1 && value < node->left->data)
return _leftCaseRotate(node);
if(balanceFactor > 1 && value > node->left->data)
return _leftRightCaseRotate(node);
if(balanceFactor < -1 && value > node->right->data)
return _rightCaseRotate(node);
if(balanceFactor < -1 && value < node->right->data)
return _rightLeftCaseRotate(node);
return node;
}
AVLNode* _findMinNode(AVLNode *node) {
AVLNode *currNode = node;
while (currNode && currNode->left != NULL)
currNode = currNode->left;
return currNode;
}
AVLNode* _remove_AVL(AVLNode* node,int value){
if(node==NULL)
return node;
if(value > node->data)
node->right=_remove_AVL(node->right,value);
else if(value < node->data)
node->left=_remove_AVL(node->left,value);
else{
AVLNode *temp;
if((node->left==NULL)||(node->right==NULL)){
temp=NULL;
if(node->left==NULL) temp=node->right;
else if(node->right==NULL) temp=node->left;
if(temp==NULL){
temp=node;
node=NULL;
}
else
*node=*temp;
free(temp);
}
else{
temp = _findMinNode(node->right);
node->data=temp->data;
node->right=_remove_AVL(node->right,temp->data);
}
}
if(node==NULL) return node;
node->height=_max(_getHeight(node->left),_getHeight(node->right))+1;
int balanceFactor= _getBalanceFactor(node);
if(balanceFactor>1 && _getBalanceFactor(node->left)>=0)
return _leftCaseRotate(node);
if(balanceFactor>1 && _getBalanceFactor(node->left)<0)
return _leftRightCaseRotate(node);
if(balanceFactor<-1 && _getBalanceFactor(node->right)<=0)
return _rightCaseRotate(node);
if(balanceFactor<-1 && _getBalanceFactor(node->right)>0)
return _rightLeftCaseRotate(node);
return node;
}
void avl_init(AVL *avl) {
avl->_root = NULL;
avl->_size = 0u;
}
bool avl_isEmpty(AVL *avl) {
return avl->_root == NULL;
}
bool avl_find(AVL *avl, int value) {
AVLNode *temp = _search(avl->_root, value);
if (temp == NULL)
return false;
// if (temp->data == value && temp->x == xin && temp->y!=yin)
// {
// count++;
// // printf("\nvalue = %d x in = %d y in %d \n",value,xin,yin);
// return true;
// }
// else if (temp->data == value && temp->x!= xin && temp->y==yin)
// {
// count++;
// // printf("\nvalue = %d x in = %d y in %d \n",value,xin,yin);
// return true;
// }
if (temp->data == value)
{
//printf(" NABRAK \n");
return true;
}
else
return false;
}
void avl_insert(AVL *avl,int value){
if(!avl_find(avl,value)){
avl->_root=_insert_AVL(avl,avl->_root,value);
avl->_size++;
}
}
int main(){
AVL board;
avl_init(&board);
long long int y,x,y1,n,k;
scanf("%lld %lld",&n, &k);
if(n*n == k)
{
printf("%lld",n*n);
}
else {
for(int i=0; i<k; i++)
{
scanf("%lld %lld",&x, &y);
x1=x,y1=y;
avl_insert(&board, x*y);
x1=x-1,y1=y-1;
while(x1>0 && y1>0 && x1<=n && y1 <=n)
{
avl_insert(&board, x1*y1);
x1=x1-1;
y1=y1-1;
// printf("x1 = %d y1 = %d\n",x1,y1);
}
x1=x-1,y1=y+1;
while(x1>0 && y1>0 && x1<=n && y1 <=n)
{
avl_insert(&board, x1*y1);
x1=x1-1;
y1=y1+1;
// printf("x1 = %d y1 = %d\n",x1,y1);
}
x1=x+1,y1=y-1;
while(x1>0 && y1>0 && x1<=n && y1 <=n)
{
avl_insert(&board, x1*y1);
x1=x1+1;
y1=y1-1;
// printf("x1 = %d y1 = %d\n",x1,y1);
}
x1=x+1,y1=y+1;
while(x1>0 && y1>0 && x1<=n && y1 <=n)
{
avl_insert(&board, x1*y1);
x1=x1+1;
y1=y1+1;
// printf("x1 = %d y1 = %d\n",x1,y1);
}
x1=x,y1=y;
}
printf("%lld\n",count);
}
}
|
#include <iostream>
#define R 3
#define C 6
// #define R 4
// #define C 4
using namespace std;
void spiralPrint(int end_row, int end_col, int arr[R][C])
{
int start_row = 0;
int start_col = 0;
int curr_row = 0;
int curr_col = 0;
while (start_row < end_row && start_col < end_col) {
for (; curr_col < end_col; curr_col++) {
cout << arr[curr_row][curr_col] << " ";
}
curr_col--;
start_row++;
curr_row++;
for (; curr_row < end_row; curr_row++) {
cout << arr[curr_row][curr_col] << " ";
}
curr_row--;
end_col--;
curr_col--;
if (start_row < end_row && start_col < end_col) {
for (; curr_col >= start_col; curr_col--) {
cout << arr[curr_row][curr_col] << " ";
}
curr_col++;
end_row--;
curr_row--;
for (; curr_row >= start_row; curr_row--) {
cout << arr[curr_row][curr_col] << " ";
}
curr_row++;
start_col++;
curr_col++;
}
}
}
/* Driver program to test above functions */
int main()
{
int a[3][6] = { {1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18}
};
int b[4][4] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
spiralPrint(R, C, a);
// spiralPrint(4, 4, b);
return 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "../base.h"
#include "Windows.Storage.Provider.0.h"
#include "Windows.Storage.0.h"
#include "Windows.Foundation.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Storage::Provider {
struct __declspec(uuid("9fc90920-7bcf-4888-a81e-102d7034d7ce")) __declspec(novtable) ICachedFileUpdaterStatics : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_SetUpdateInformation(Windows::Storage::IStorageFile * file, hstring contentId, winrt::Windows::Storage::Provider::ReadActivationMode readMode, winrt::Windows::Storage::Provider::WriteActivationMode writeMode, winrt::Windows::Storage::Provider::CachedFileOptions options) = 0;
};
struct __declspec(uuid("9e6f41e6-baf2-4a97-b600-9333f5df80fd")) __declspec(novtable) ICachedFileUpdaterUI : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Title(hstring * value) = 0;
virtual HRESULT __stdcall put_Title(hstring value) = 0;
virtual HRESULT __stdcall get_UpdateTarget(winrt::Windows::Storage::Provider::CachedFileTarget * value) = 0;
virtual HRESULT __stdcall add_FileUpdateRequested(Windows::Foundation::TypedEventHandler<Windows::Storage::Provider::CachedFileUpdaterUI, Windows::Storage::Provider::FileUpdateRequestedEventArgs> * handler, event_token * token) = 0;
virtual HRESULT __stdcall remove_FileUpdateRequested(event_token token) = 0;
virtual HRESULT __stdcall add_UIRequested(Windows::Foundation::TypedEventHandler<Windows::Storage::Provider::CachedFileUpdaterUI, Windows::Foundation::IInspectable> * handler, event_token * token) = 0;
virtual HRESULT __stdcall remove_UIRequested(event_token token) = 0;
virtual HRESULT __stdcall get_UIStatus(winrt::Windows::Storage::Provider::UIStatus * value) = 0;
};
struct __declspec(uuid("8856a21c-8699-4340-9f49-f7cad7fe8991")) __declspec(novtable) ICachedFileUpdaterUI2 : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_UpdateRequest(Windows::Storage::Provider::IFileUpdateRequest ** value) = 0;
virtual HRESULT __stdcall abi_GetDeferral(Windows::Storage::Provider::IFileUpdateRequestDeferral ** value) = 0;
};
struct __declspec(uuid("40c82536-c1fe-4d93-a792-1e736bc70837")) __declspec(novtable) IFileUpdateRequest : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_ContentId(hstring * value) = 0;
virtual HRESULT __stdcall get_File(Windows::Storage::IStorageFile ** value) = 0;
virtual HRESULT __stdcall get_Status(winrt::Windows::Storage::Provider::FileUpdateStatus * value) = 0;
virtual HRESULT __stdcall put_Status(winrt::Windows::Storage::Provider::FileUpdateStatus value) = 0;
virtual HRESULT __stdcall abi_GetDeferral(Windows::Storage::Provider::IFileUpdateRequestDeferral ** value) = 0;
virtual HRESULT __stdcall abi_UpdateLocalFile(Windows::Storage::IStorageFile * value) = 0;
};
struct __declspec(uuid("82484648-bdbe-447b-a2ee-7afe6a032a94")) __declspec(novtable) IFileUpdateRequest2 : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_UserInputNeededMessage(hstring * value) = 0;
virtual HRESULT __stdcall put_UserInputNeededMessage(hstring value) = 0;
};
struct __declspec(uuid("ffcedb2b-8ade-44a5-bb00-164c4e72f13a")) __declspec(novtable) IFileUpdateRequestDeferral : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_Complete() = 0;
};
struct __declspec(uuid("7b0a9342-3905-438d-aaef-78ae265f8dd2")) __declspec(novtable) IFileUpdateRequestedEventArgs : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Request(Windows::Storage::Provider::IFileUpdateRequest ** value) = 0;
};
}
namespace ABI {
template <> struct traits<Windows::Storage::Provider::CachedFileUpdaterUI> { using default_interface = Windows::Storage::Provider::ICachedFileUpdaterUI; };
template <> struct traits<Windows::Storage::Provider::FileUpdateRequest> { using default_interface = Windows::Storage::Provider::IFileUpdateRequest; };
template <> struct traits<Windows::Storage::Provider::FileUpdateRequestDeferral> { using default_interface = Windows::Storage::Provider::IFileUpdateRequestDeferral; };
template <> struct traits<Windows::Storage::Provider::FileUpdateRequestedEventArgs> { using default_interface = Windows::Storage::Provider::IFileUpdateRequestedEventArgs; };
}
namespace Windows::Storage::Provider {
template <typename D>
struct WINRT_EBO impl_ICachedFileUpdaterStatics
{
void SetUpdateInformation(const Windows::Storage::IStorageFile & file, hstring_view contentId, Windows::Storage::Provider::ReadActivationMode readMode, Windows::Storage::Provider::WriteActivationMode writeMode, Windows::Storage::Provider::CachedFileOptions options) const;
};
template <typename D>
struct WINRT_EBO impl_ICachedFileUpdaterUI
{
hstring Title() const;
void Title(hstring_view value) const;
Windows::Storage::Provider::CachedFileTarget UpdateTarget() const;
event_token FileUpdateRequested(const Windows::Foundation::TypedEventHandler<Windows::Storage::Provider::CachedFileUpdaterUI, Windows::Storage::Provider::FileUpdateRequestedEventArgs> & handler) const;
using FileUpdateRequested_revoker = event_revoker<ICachedFileUpdaterUI>;
FileUpdateRequested_revoker FileUpdateRequested(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Storage::Provider::CachedFileUpdaterUI, Windows::Storage::Provider::FileUpdateRequestedEventArgs> & handler) const;
void FileUpdateRequested(event_token token) const;
event_token UIRequested(const Windows::Foundation::TypedEventHandler<Windows::Storage::Provider::CachedFileUpdaterUI, Windows::Foundation::IInspectable> & handler) const;
using UIRequested_revoker = event_revoker<ICachedFileUpdaterUI>;
UIRequested_revoker UIRequested(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Storage::Provider::CachedFileUpdaterUI, Windows::Foundation::IInspectable> & handler) const;
void UIRequested(event_token token) const;
Windows::Storage::Provider::UIStatus UIStatus() const;
};
template <typename D>
struct WINRT_EBO impl_ICachedFileUpdaterUI2
{
Windows::Storage::Provider::FileUpdateRequest UpdateRequest() const;
Windows::Storage::Provider::FileUpdateRequestDeferral GetDeferral() const;
};
template <typename D>
struct WINRT_EBO impl_IFileUpdateRequest
{
hstring ContentId() const;
Windows::Storage::StorageFile File() const;
Windows::Storage::Provider::FileUpdateStatus Status() const;
void Status(Windows::Storage::Provider::FileUpdateStatus value) const;
Windows::Storage::Provider::FileUpdateRequestDeferral GetDeferral() const;
void UpdateLocalFile(const Windows::Storage::IStorageFile & value) const;
};
template <typename D>
struct WINRT_EBO impl_IFileUpdateRequest2
{
hstring UserInputNeededMessage() const;
void UserInputNeededMessage(hstring_view value) const;
};
template <typename D>
struct WINRT_EBO impl_IFileUpdateRequestDeferral
{
void Complete() const;
};
template <typename D>
struct WINRT_EBO impl_IFileUpdateRequestedEventArgs
{
Windows::Storage::Provider::FileUpdateRequest Request() const;
};
}
namespace impl {
template <> struct traits<Windows::Storage::Provider::ICachedFileUpdaterStatics>
{
using abi = ABI::Windows::Storage::Provider::ICachedFileUpdaterStatics;
template <typename D> using consume = Windows::Storage::Provider::impl_ICachedFileUpdaterStatics<D>;
};
template <> struct traits<Windows::Storage::Provider::ICachedFileUpdaterUI>
{
using abi = ABI::Windows::Storage::Provider::ICachedFileUpdaterUI;
template <typename D> using consume = Windows::Storage::Provider::impl_ICachedFileUpdaterUI<D>;
};
template <> struct traits<Windows::Storage::Provider::ICachedFileUpdaterUI2>
{
using abi = ABI::Windows::Storage::Provider::ICachedFileUpdaterUI2;
template <typename D> using consume = Windows::Storage::Provider::impl_ICachedFileUpdaterUI2<D>;
};
template <> struct traits<Windows::Storage::Provider::IFileUpdateRequest>
{
using abi = ABI::Windows::Storage::Provider::IFileUpdateRequest;
template <typename D> using consume = Windows::Storage::Provider::impl_IFileUpdateRequest<D>;
};
template <> struct traits<Windows::Storage::Provider::IFileUpdateRequest2>
{
using abi = ABI::Windows::Storage::Provider::IFileUpdateRequest2;
template <typename D> using consume = Windows::Storage::Provider::impl_IFileUpdateRequest2<D>;
};
template <> struct traits<Windows::Storage::Provider::IFileUpdateRequestDeferral>
{
using abi = ABI::Windows::Storage::Provider::IFileUpdateRequestDeferral;
template <typename D> using consume = Windows::Storage::Provider::impl_IFileUpdateRequestDeferral<D>;
};
template <> struct traits<Windows::Storage::Provider::IFileUpdateRequestedEventArgs>
{
using abi = ABI::Windows::Storage::Provider::IFileUpdateRequestedEventArgs;
template <typename D> using consume = Windows::Storage::Provider::impl_IFileUpdateRequestedEventArgs<D>;
};
template <> struct traits<Windows::Storage::Provider::CachedFileUpdater>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.Storage.Provider.CachedFileUpdater"; }
};
template <> struct traits<Windows::Storage::Provider::CachedFileUpdaterUI>
{
using abi = ABI::Windows::Storage::Provider::CachedFileUpdaterUI;
static constexpr const wchar_t * name() noexcept { return L"Windows.Storage.Provider.CachedFileUpdaterUI"; }
};
template <> struct traits<Windows::Storage::Provider::FileUpdateRequest>
{
using abi = ABI::Windows::Storage::Provider::FileUpdateRequest;
static constexpr const wchar_t * name() noexcept { return L"Windows.Storage.Provider.FileUpdateRequest"; }
};
template <> struct traits<Windows::Storage::Provider::FileUpdateRequestDeferral>
{
using abi = ABI::Windows::Storage::Provider::FileUpdateRequestDeferral;
static constexpr const wchar_t * name() noexcept { return L"Windows.Storage.Provider.FileUpdateRequestDeferral"; }
};
template <> struct traits<Windows::Storage::Provider::FileUpdateRequestedEventArgs>
{
using abi = ABI::Windows::Storage::Provider::FileUpdateRequestedEventArgs;
static constexpr const wchar_t * name() noexcept { return L"Windows.Storage.Provider.FileUpdateRequestedEventArgs"; }
};
}
}
|
#include <bits/stdc++.h>
#include <time.h>
using namespace std;
#define ll long long
#define ld long double
#define uint unsigned int
#define ull unsigned long long
void print(vector<int> &t) {
for (int i = 0; i < (int)t.size(); ++i)
cout << t[i] << " ";
cout << "\n";
}
int dp[5001][5001];
ll MOD = 1e9;
int min_(int a, int b, int c) {
return min(a, min(b, c));
}
int main() {
// freopen("file.in", "r", stdin);
freopen("levenshtein.in", "r", stdin);
freopen("levenshtein.out", "w", stdout);
string s1, s2; cin >> s1 >> s2;
int n = (int)s1.length(), m = (int)s2.length();
dp[0][0] = 0;
for (int i = 1; i <= n; ++i) dp[i][0] = i;
for (int j = 1; j <= m; ++j) dp[0][j] = j;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (s1[i - 1] == s2[j - 1]) dp[i][j] = dp[i - 1][j - 1];
else dp[i][j] = min_(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1;
}
}
cout << dp[n][m] << endl;
return 0;
}
|
// CkCert.h: interface for the CkCert class.
//
//////////////////////////////////////////////////////////////////////
// This header is generated.
#ifndef _CkCert_H
#define _CkCert_H
#include "chilkatDefs.h"
#include "CkString.h"
#include "CkMultiByteBase.h"
class CkByteData;
class CkPrivateKey;
class CkPublicKey;
class CkDateTime;
#ifndef __sun__
#pragma pack (push, 8)
#endif
// CLASS: CkCert
class CkCert : public CkMultiByteBase
{
private:
// Don't allow assignment or copying these objects.
CkCert(const CkCert &);
CkCert &operator=(const CkCert &);
public:
CkCert(void);
virtual ~CkCert(void);
static CkCert *createNew(void);
void inject(void *impl);
// May be called when finished with the object to free/dispose of any
// internal resources held by the object.
void dispose(void);
// BEGIN PUBLIC INTERFACE
// ----------------------
// Properties
// ----------------------
bool get_AvoidWindowsPkAccess(void);
void put_AvoidWindowsPkAccess(bool newVal);
int get_CertVersion(void);
void get_CspName(CkString &str);
const char *cspName(void);
bool get_Expired(void);
bool get_ForClientAuthentication(void);
bool get_ForCodeSigning(void);
bool get_ForSecureEmail(void);
bool get_ForServerAuthentication(void);
bool get_ForTimeStamping(void);
bool get_HasKeyContainer(void);
unsigned long get_IntendedKeyUsage(void);
bool get_IsRoot(void);
void get_IssuerC(CkString &str);
const char *issuerC(void);
void get_IssuerCN(CkString &str);
const char *issuerCN(void);
void get_IssuerDN(CkString &str);
const char *issuerDN(void);
void get_IssuerE(CkString &str);
const char *issuerE(void);
void get_IssuerL(CkString &str);
const char *issuerL(void);
void get_IssuerO(CkString &str);
const char *issuerO(void);
void get_IssuerOU(CkString &str);
const char *issuerOU(void);
void get_IssuerS(CkString &str);
const char *issuerS(void);
void get_KeyContainerName(CkString &str);
const char *keyContainerName(void);
bool get_MachineKeyset(void);
void get_OcspUrl(CkString &str);
const char *ocspUrl(void);
bool get_PrivateKeyExportable(void);
bool get_Revoked(void);
void get_Rfc822Name(CkString &str);
const char *rfc822Name(void);
bool get_SelfSigned(void);
void get_SerialNumber(CkString &str);
const char *serialNumber(void);
void get_Sha1Thumbprint(CkString &str);
const char *sha1Thumbprint(void);
bool get_SignatureVerified(void);
bool get_Silent(void);
void get_SubjectC(CkString &str);
const char *subjectC(void);
void get_SubjectCN(CkString &str);
const char *subjectCN(void);
void get_SubjectDN(CkString &str);
const char *subjectDN(void);
void get_SubjectE(CkString &str);
const char *subjectE(void);
void get_SubjectL(CkString &str);
const char *subjectL(void);
void get_SubjectO(CkString &str);
const char *subjectO(void);
void get_SubjectOU(CkString &str);
const char *subjectOU(void);
void get_SubjectS(CkString &str);
const char *subjectS(void);
bool get_TrustedRoot(void);
void get_ValidFrom(SYSTEMTIME &outSysTime);
void get_ValidFromStr(CkString &str);
const char *validFromStr(void);
void get_ValidTo(SYSTEMTIME &outSysTime);
void get_ValidToStr(CkString &str);
const char *validToStr(void);
// ----------------------
// Methods
// ----------------------
int CheckRevoked(void);
bool ExportCertDer(CkByteData &outData);
bool ExportCertDerFile(const char *path);
bool ExportCertPem(CkString &outStr);
const char *exportCertPem(void);
bool ExportCertPemFile(const char *path);
bool ExportCertXml(CkString &outStr);
const char *exportCertXml(void);
CkPrivateKey *ExportPrivateKey(void);
CkPublicKey *ExportPublicKey(void);
bool ExportToPfxFile(const char *pfxPath, const char *password, bool bIncludeChain);
CkCert *FindIssuer(void);
bool GetEncoded(CkString &outStr);
const char *getEncoded(void);
const char *encoded(void);
bool GetPrivateKeyPem(CkString &outStr);
const char *getPrivateKeyPem(void);
const char *privateKeyPem(void);
CkDateTime *GetValidFromDt(void);
CkDateTime *GetValidToDt(void);
bool HasPrivateKey(void);
#if defined(CK_CRYPTOAPI_INCLUDED)
bool LinkPrivateKey(const char *keyContainerName, bool bMachineKeyset, bool bForSigning);
#endif
bool LoadByCommonName(const char *cn);
bool LoadByEmailAddress(const char *emailAddress);
bool LoadByIssuerAndSerialNumber(const char *issuerCN, const char *serialNum);
bool LoadFromBase64(const char *encodedCert);
bool LoadFromBinary(const CkByteData &data);
#if !defined(CHILKAT_MONO)
bool LoadFromBinary2(const unsigned char *pByteData, unsigned long szByteData);
#endif
bool LoadFromFile(const char *path);
bool LoadPfxData(const CkByteData &pfxData, const char *password);
#if !defined(CHILKAT_MONO)
bool LoadPfxData2(const unsigned char *pByteData, unsigned long szByteData, const char *password);
#endif
bool LoadPfxFile(const char *path, const char *password);
bool PemFileToDerFile(const char *fromPath, const char *toPath);
bool SaveToFile(const char *path);
bool SetFromEncoded(const char *encodedCert);
bool SetPrivateKey(CkPrivateKey &privKey);
bool SetPrivateKeyPem(const char *privKeyPem);
// END PUBLIC INTERFACE
};
#ifndef __sun__
#pragma pack (pop)
#endif
#endif
|
#ifndef _Canvas_h_
#define _Canvas_h_
#include <iostream>
#include "Bitmap.h"
#include "Global.h"
#include "Paint.h"
#include "Manager.h"
#include "RectF.h"
class Canvas
{
public:
Canvas(Bitmap *b);
Canvas(int x, int y);
virtual ~Canvas();
void drawBitmap(Bitmap *bitmap, int left, int top);
void drawColor(int color);
void drawLine(int startX, int startY, int stopX, int stopY, Paint *paint = NULL);
void drawRect(int x, int y, int i, int j, Paint *sBlackPaint = NULL);
void drawRect(RectF *rWithPic, Paint *paint = NULL);
// void drawR(int x, int y, int i, int j, Paint sBlackPaint, Graphics g);
void drawRect(Rect *mRectTop, Paint *mFramePaint);
void drawLines(int pts[],int size, Paint *sBlackPaint);
void setBitmap(Bitmap *bmpArrowDown){ m_bitmap = bmpArrowDown; }
Bitmap *getBitmap()const{ return m_bitmap; }
private:
bool m_need_delete;
//»°åÉϵÄÖ½
Bitmap *m_bitmap;
};
#endif _Canvas_h_
|
#ifndef V2HJSONDATA_H
#define V2HJSONDATA_H
#include <QObject>
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QPixmap>
#include <QProcess>
#include <QDir>
#include <QTime>
#include "cJSON.h"
#define V2H_JSON_DATA_DEBUG
#ifdef V2H_JSON_DATA_DEBUG
#define V2H_Debug qDebug
#else
#define V2H_Debug QT_NO_QDEBUG_MACRO
#endif
#define V2H_Error qWarning
#define V2H_NORMAL_LOG V2H_Debug().noquote().nospace()<<V2H_LOGTAG<<__FUNCTION__<<":"
#define V2H_ERROR_LOG V2H_Debug().noquote().nospace()<<V2H_LOGTAG<<V2H_LOGERROR<<__FUNCTION__<<":"
#define V2H_APPLIANCE_INDEX_MAX (500)
typedef struct
{
QString key;
QString value;
}MappedInfo;
typedef struct
{
QString key;
QStringList values;
}Guideline;
typedef struct
{
MappedInfo incrementAction;
MappedInfo decrementAction;
}ActionBar;
typedef struct
{
QString name;
QString scale;
QList<MappedInfo> range_map;
double range_min;
double range_max;
bool minmax_flag;
}AttributeDetailInfo;
typedef struct
{
QString attributename;
AttributeDetailInfo detail;
QString value;
}AttributeInfo;
typedef struct
{
QString botName;
QString botId;
QString botLogo;
QString num;
QString applianceId;
QStringList applianceTypes;
QString friendlyName;
QString friendlyDescription;
QString groupName;
QList<Guideline> guideline;
QList<MappedInfo> supportActions;
QList<ActionBar> actionBars;
QList<AttributeInfo> attributes;
bool actionturnOnOffSupported;
bool actionsetModeSupported;
}ApplianceInfo;
typedef struct
{
bool geted;
QString service_flag;
QString app_logo_url;
QString app_dl_url;
QString maker_app_dl_url;
int home_link_type;
}ServiceFlag;
typedef struct
{
QString tts;
}OperationResult;
typedef struct
{
QString deviceType;
QString value;
}SetModeParam;
typedef struct
{
QString deviceId;
QString deviceName;
QString groupName;
QString operation;
SetModeParam mode;
}OperationRequest;
class V2HJsonData : public QObject
{
//Q_OBJECT
public:
explicit V2HJsonData(QObject *parent = 0);
~V2HJsonData();
/* Initialize Function */
static void Initialize(void);
static void InitDeviceTypeMap(void);
static void InitAttributeMap(void);
/* Deinitialize Function */
static void Deinitialize(void);
/* Common Internal Function */
static cJSON makecJSONAppliancesListArray(const char *json_buffer);
static bool verifyV2HJsonData(QJsonObject &json_obj);
static QList<ApplianceInfo> makeApplianceInfoListFromJsonArray(QJsonArray &json_array);
static QStringList makeGroupNameList(void);
static QStringList makeApplianceTypeList(void);
static QHash<QString, QStringList> makeDeviceTypeGuidelineMap(void);
static QList<ApplianceInfo> makeFiltedAppliancesInfoList(void);
static QList<ApplianceInfo> makeAppliancesInfoListByGroup(QString &groupname);
static QList<ApplianceInfo> makeAppliancesInfoListByType(QString &appliancetype);
static ServiceFlag makeServiceFlagFromJsonObj(QJsonObject &json_obj);
/* Make Random Guideline strings for VR */
static QStringList makeRandomGuidelineStringlist(int maxstings);
static QStringList makeDeviceTypeRandomGuidelineStringlist(QString &appliancetype, int maxstings);
/* Common Public Function */
static QString convertApplianceType2DeviceType(QString &appliancetype);
static QString convertAction2AttributeName(QString &action);
/* Generate Operation Request Json String Function */
static QByteArray generateGetServiceFlagJson(void);
static QByteArray generateGetAppliancesListJson(void);
static QByteArray generateOperationRequestJson(OperationRequest &operation_req);
/* Set Function for V2H Data */
static void setV2HServiceFlagUpdatedFlag(bool flag);
static void setV2HAppliancesListUpdatedFlag(bool flag);
static void setV2HApplianceOperationUpdatedFlag(bool flag);
static void setV2HServiceFlagGeted(bool geted);
static bool setV2HServiceFlagJsonData(const char *json_buffer);
static bool setV2HAppliancesListJsonData(const char *json_buffer);
static bool setV2HApplianceOperationJsonData(const char *json_buffer);
static bool setGroupNameFilter(QString groupname);
static bool setApplianceTypeFilter(QString appliancetype);
static bool setSelectApplianceID(QString appliance_id);
/* Set Function for V2H Logo Pixmap */
static bool setQRCodeBaiduLogo(QPixmap &logo);
/* Get Function for V2H Data */
static bool getV2HServiceFlagUpdatedFlag(void);
static bool getV2HAppliancesListUpdatedFlag(void);
static bool getV2HApplianceOperationUpdatedFlag(void);
static bool getV2HServiceFlagGeted(void);
static ServiceFlag getV2HServiceFlag(void);
static bool getV2HJsonDataIsEnable(void);
static bool getV2HJsonDataRedDot(void);
static QString getGroupFilter(void);
static QString getTypeFilter(void);
static QString getSelectedApplianceID(void);
static int getSelectedApplianceIndex(void);
static int getTotalAppliances(void);
static QStringList getGroupNameList(void);
static QStringList getApplianceTypeList(void);
static ApplianceInfo getSelectedApplianceInfo(void);
static QStringList getSelectedApplianceTypes(void);
static QList<MappedInfo> getSelectedApplianceModeList(void);
static QString getSelectedApplianceCurrentModeValue(void);
static MappedInfo getSelectedApplianceCurrentMode(void);
static AttributeInfo getSelectedApplianceAttributeInfo(QString attributename);
static QList<ActionBar> getSelectedApplianceActionBars(void);
static QList<Guideline> getSelectedApplianceGuideline(void);
static bool getSelectedApplianceTurnOnOffSupported(void);
static bool getSelectedApplianceSetModeSupported(void);
static int getApplianceInfoFromID(QString &appliance_id, ApplianceInfo &applianceinfo);
static QList<ApplianceInfo> getAppliancesInfoList(void);
static QList<ApplianceInfo> getFiltedAppliancesInfoList(void);
static QStringList getAllGuidelineStrings(void);
/* Get Function for V2H Logo Pixmap */
static QPixmap getQRCodeBaiduLogo(void);
/* Get Function for V2H JsonData */
static QJsonArray getJsonAppliancesArrayFromJsonData(void);
static QJsonArray getJsonAppliancesArray(void);
/* Clear Function for V2H Data */
static bool clearV2HJsonData(void);
static bool clearGroupFilter(void);
static bool clearTypeFilter(void);
static bool clearAllFilters(void);
static bool clearSelectApplianceID(void);
signals:
private:
static QHash<QString, QString> m_DeviceTypeMap;
static QHash<QString, QString> m_AttributeMap;
static QHash<QString, QStringList> m_DeviceTypeGuidelineMap;
static QString m_V2H_AppliancesListJsonString;
static QString m_V2H_ServiceFlagJsonString;
static QString m_V2H_ApplianceOperationJsonString;
static ServiceFlag m_V2H_ServiceFlag;
static QJsonObject m_V2H_JsonData;
static QJsonArray m_V2H_ApplianceArray;
static cJSON m_V2H_cJSONAppliancesArray;
static QList<ApplianceInfo> m_V2H_ApplianceInfoList;
static QList<ApplianceInfo> m_V2H_FiltedApplianceInfoList;
static QList<OperationResult> m_V2H_OperationResults;
static QString m_GroupNameFilter;
static QStringList m_GroupNameList;
static QString m_ApplianceTypeFilter;
static QStringList m_ApplianceTypeList;
static QStringList m_AllGuidelineStrings;
static int m_SelectedApplianceIndex;
static ApplianceInfo m_SelectedApplianceInfo;
static bool m_V2H_AppliancesListIsEnable;
static bool m_V2H_AppliancesListRedDot;
static bool m_V2H_ServiceFlagUpdated;
static bool m_V2H_AppliancesListUpdated;
static bool m_V2H_ApplianceOperationUpdated;
static QPixmap *m_V2H_BaiduLogo;
};
#endif // V2HJSONDATA_H
|
#include "PizzaService.h"
PizzaService::PizzaService()
{
pizzaRepo.init();
}
void PizzaService::makePizza(){
addPizza(pizzaStart());
}
string PizzaService::pizzaStart(){
char input;
string pizzaSize = "";
system("CLS");
while(input != '1' || input != '2' || input != '3'){
orderHeader();
cout <<"What size of Pizza?" << endl;
cout <<"-------------------" << endl;
cout <<"1: Small Pizza" << endl;
cout <<"2: Medium Pizza" << endl;
cout <<"3: Large Pizza" << endl;
cin >> input;
switch(input){
case '1':
pizzaSize = "Small Pizza, ";
pizzaRepo.orderTotal(150);
break;
case '2':
pizzaSize = "Medium Pizza, ";
pizzaRepo.orderTotal(200);
break;
case '3':
pizzaSize = "Large Pizza, ";
pizzaRepo.orderTotal(250);
break;
}
if(input == '1' || input == '2' || input == '3') break;
}
return pizzaType(pizzaSize);
}
string PizzaService::pizzaType(string str){
char input;
string pizzaType = str;
system("CLS");
while(input != '1' || input != '2' || input != '3'){
orderHeader();
cout <<"What type of Pizza-crust?" << endl;
cout <<"-------------------------" << endl;
cout <<"1: Thin Italian" << endl;
cout <<"2: Normal" << endl;
cout <<"3: Deep-dish" << endl;
cin >> input;
switch(input){
case '1':
pizzaType += "Thin Italian: ";
pizzaRepo.orderTotal(125);
break;
case '2':
pizzaType += "Normal: ";
pizzaRepo.orderTotal(150);
break;
case '3':
pizzaType += "Deep-dish: ";
pizzaRepo.orderTotal(250);
break;
}
if(input == '1' || input == '2' || input == '3') break;
}
return pizzaType;
}
void PizzaService::addPizza(string str){
pizzaRepo.input_Toppings(str);
}
void PizzaService::addDrink(){
pizzaRepo.input_Drinks();
}
void PizzaService::addSide(){
pizzaRepo.input_Sides();
}
/*
void PizzaService::deleteItem(){
pizzaRepo.removeItem();
}
*/
void PizzaService::finish_Order(){
system("CLS");
if(pizzaRepo.numOfItems() == 0){
cout << "--------------------------------" << endl;
cout << " Order is finished." << endl;
cout << " - - - - - You have - - - - -" << endl;
cout << "\n\t NOTHING!!!\n" << endl;
cout << "--------------------------------" << endl;
}
else{
cout << "--------------------------------" << endl;
cout << " Order is finished." << endl;
cout << " - - - - - You have - - - - -" << endl;
cout << " " << pizzaRepo.getTotalPizza() << " Pizza/s" << endl;
cout << " " << pizzaRepo.getTotalDrink() << " Drink/s" << endl;
cout << " " << pizzaRepo.getTotalSides() << " Side-dish/es" << endl;
cout << endl;
pizzaRepo.printOrder();
cout << endl;
cout << endl;
cout << " The total is " << pizzaRepo.get_Total() << endl;
cout << "--------------------------------" << endl;
system("pause");
pizzaRepo.saveOrder();
cout << "Save incoming" << endl;
}
system("pause");
}
void PizzaService::orderHeader(){
cout << "-----------------------" << endl;
cout << " Order Pizza" << endl;
cout << "-----------------------" << endl;
}
|
#include "audio\Singularity.Audio.h"
/*
* AdaptiveEnvironment.h
*
* An adaptive environment that fits everything together.
*
* Author: Sela Davis
*
* Created: May 05, 2010 (05/05/10)
* Last modified: May 05, 2010 (05/05/10)
*/
namespace Singularity
{
namespace Audio
{
class AdaptiveEnvironment
{
private:
#pragma region Variables
String m_pName;
DynamicList<AdaptiveSlice*> m_pSlices;
DynamicList<AdaptiveParameter*> m_pParameters;
DynamicList<string> m_pCategories;
bool m_bPlaying;
#pragma endregion
public:
#pragma region Constructors and Finalizers
// Constructor.
AdaptiveEnvironment(String name);
// Destructor.
~AdaptiveEnvironment();
#pragma endregion
#pragma region Methods
DynamicList<Cue*> DetermineCuesToPlay();
AdaptiveSlice* ChooseSlice(String category, float bpm, Vector2 timesig, String rhythm, String keysig);
void LoadEnvironmentFromXml(String path);
void AddSlice(AdaptiveSlice* slice);
void AddParameter(AdaptiveParameter* param);
void AddCategory(String category);
void SetVariable(String variable, float value);
String GetName();
#pragma endregion
};
}
}
|
/**
* Calculate the total luminosity and flux within the specified radius.
*
* Base on 'fit_dbeta_sbp.cpp' and supersede 'calc_lx.cpp'
*
* Author: Junhua Gu
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include "vchisq.hpp"
#include "dbeta.hpp"
#include "beta_cfg.hpp"
#include <data_sets/default_data_set.hpp>
#include <methods/powell/powell_method.hpp>
#include <core/freeze_param.hpp>
#include <error_estimator/error_estimator.hpp>
#include "spline.hpp"
using namespace std;
using namespace opt_utilities;
//double s=5.63136645E20;
const double kpc=3.086E21;//kpc in cm
const double Mpc=kpc*1000;
double dbeta_func(double r, double n01, double rc1, double beta1,
double n02, double rc2, double beta2)
{
double v1 = abs(n01) * pow(1+r*r/rc1/rc1, -3./2.*abs(beta1));
double v2 = abs(n02) * pow(1+r*r/rc2/rc2, -3./2.*abs(beta2));
return v1 + v2;
}
//A class enclosing the spline interpolation method
class spline_func_obj
:public func_obj<double,double>
{
//has an spline object
spline<double> spl;
public:
//This function is used to calculate the intepolated value
double do_eval(const double& x)
{
return spl.get_value(x);
}
//we need this function, when this object is performing a clone of itself
spline_func_obj* do_clone()const
{
return new spline_func_obj(*this);
}
public:
//add points to the spline object, after which the spline will be initialized
void add_point(double x,double y)
{
spl.push_point(x,y);
}
//before getting the intepolated value, the spline should be initialzied by calling this function
void gen_spline()
{
spl.gen_spline(0,0);
}
};
int main(int argc,char* argv[])
{
if(argc<4)
{
cerr<<argv[0]<<" <sbp.conf> <rout_kpc> <cfunc_erg> [cfunc2_erg ...]"<<endl;
return -1;
}
//initialize the parameters list
ifstream cfg_file(argv[1]);
assert(cfg_file.is_open());
cfg_map cfg=parse_cfg_file(cfg_file);
const double z=cfg.z;
//initialize the radius list, sbp list and sbp error list
std::vector<double> radii;
std::vector<double> sbps;
std::vector<double> sbpe;
std::vector<double> radii_all;
std::vector<double> sbps_all;
std::vector<double> sbpe_all;
//prepend the zero point to radius list
radii.push_back(0.0);
radii_all.push_back(0.0);
//read sbp and sbp error data
ifstream ifs(cfg.sbp_data.c_str());
std::string line;
if (ifs.is_open())
{
while(std::getline(ifs, line))
{
if (line.empty())
continue;
std::istringstream iss(line);
double x, xe, y, ye;
if ((iss >> x >> xe >> y >> ye))
{
std::cerr << "sbprofile data: "
<< x << ", " << xe << ", " << y << ", " << ye
<< std::endl;
radii.push_back(x+xe); /* NOTE: use outer radii of regions */
radii_all.push_back(x+xe);
sbps.push_back(y);
sbps_all.push_back(y);
sbpe.push_back(ye);
sbpe_all.push_back(ye);
}
else
{
std::cerr << "skipped line: " << line << std::endl;
}
}
}
else
{
std::cerr << "ERROR: cannot open file: " << cfg.sbp_data.c_str()
<< std::endl;
return 1;
}
//initialize the cm/pixel value
double cm_per_pixel=cfg.cm_per_pixel;
double rmin;
if(cfg.rmin_pixel>0)
{
rmin=cfg.rmin_pixel;
}
else
{
rmin=cfg.rmin_kpc*kpc/cm_per_pixel;
}
cerr<<"rmin="<<rmin<<" (pixel)"<<endl;
std::list<double> radii_tmp,sbps_tmp,sbpe_tmp;
radii_tmp.resize(radii.size());
sbps_tmp.resize(sbps.size());
sbpe_tmp.resize(sbpe.size());
copy(radii.begin(),radii.end(),radii_tmp.begin());
copy(sbps.begin(),sbps.end(),sbps_tmp.begin());
copy(sbpe.begin(),sbpe.end(),sbpe_tmp.begin());
for(list<double>::iterator i=radii_tmp.begin();i!=radii_tmp.end();)
{
if(*i<rmin)
{
radii_tmp.pop_front();
sbps_tmp.pop_front();
sbpe_tmp.pop_front();
i=radii_tmp.begin();
continue;
}
++i;
}
radii.resize(radii_tmp.size());
sbps.resize(sbps_tmp.size());
sbpe.resize(sbpe_tmp.size());
copy(radii_tmp.begin(),radii_tmp.end(),radii.begin());
copy(sbps_tmp.begin(),sbps_tmp.end(),sbps.begin());
copy(sbpe_tmp.begin(),sbpe_tmp.end(),sbpe.begin());
//read cooling function data
spline_func_obj cf;
for(ifstream ifs(cfg.cfunc_profile.c_str());;)
{
assert(ifs.is_open());
double x,y;
ifs>>x>>y;
if(!ifs.good())
{
break;
}
cerr<<x<<"\t"<<y<<endl;
if(x>radii.back())
{
break;
}
cf.add_point(x,y);
}
cf.gen_spline();
//read temperature profile data
spline_func_obj Tprof;
int tcnt=0;
for(ifstream ifs1(cfg.tprofile.c_str());;++tcnt)
{
assert(ifs1.is_open());
double x,y;
ifs1>>x>>y;
if(!ifs1.good())
{
break;
}
cerr<<x<<"\t"<<y<<endl;
#if 0
if(tcnt==0)
{
Tprof.add_point(0,y);
}
#endif
Tprof.add_point(x,y);
}
Tprof.gen_spline();
default_data_set<std::vector<double>,std::vector<double> > ds;
ds.add_data(data<std::vector<double>,std::vector<double> >(radii,sbps,sbpe,sbpe,radii,radii));
//initial fitter
fitter<vector<double>,vector<double>,vector<double>,double> f;
f.load_data(ds);
//initial the object, which is used to calculate projection effect
projector<double> a;
bool tie_beta=false;
if(cfg.param_map.find("beta")!=cfg.param_map.end()
&&cfg.param_map.find("beta1")==cfg.param_map.end()
&&cfg.param_map.find("beta2")==cfg.param_map.end())
{
dbeta2<double> dbetao;
a.attach_model(dbetao);
tie_beta=true;
}
else if((cfg.param_map.find("beta1")!=cfg.param_map.end()
||cfg.param_map.find("beta2")!=cfg.param_map.end())
&&cfg.param_map.find("beta")==cfg.param_map.end())
{
dbeta<double> dbetao;
a.attach_model(dbetao);
tie_beta=false;
}
else
{
cerr<<"Error, cannot decide whether to tie beta together or let them vary freely!"<<endl;
assert(0);
}
//attach the cooling function
a.attach_cfunc(cf);
a.set_cm_per_pixel(cm_per_pixel);
f.set_model(a);
//chi^2 statistic
vchisq<double> c;
c.verbose(true);
c.set_limit();
f.set_statistic(c);
//optimization method
f.set_opt_method(powell_method<double,std::vector<double> >());
//initialize the initial values
/*
double =0;
double rc1=0;
double n02=0;
double rc2=0;
double beta=0;
*/
double bkg_level=0;
if(tie_beta)
{
f.set_param_value("beta",.7);
f.set_param_lower_limit("beta",.3);
f.set_param_upper_limit("beta",1.4);
}
else
{
f.set_param_value("beta1",.7);
f.set_param_lower_limit("beta1",.3);
f.set_param_upper_limit("beta1",1.4);
f.set_param_value("beta2",.7);
f.set_param_lower_limit("beta2",.3);
f.set_param_upper_limit("beta2",1.4);
}
for(std::map<std::string,std::vector<double> >::iterator i=cfg.param_map.begin();
i!=cfg.param_map.end();++i)
{
std::string pname=i->first;
f.set_param_value(pname,i->second.at(0));
if(i->second.size()==3)
{
double a1=i->second[1];
double a2=i->second[2];
double u=std::max(a1,a2);
double l=std::min(a1,a2);
f.set_param_upper_limit(pname,u);
f.set_param_lower_limit(pname,l);
}
else
{
if(pname=="beta"||pname=="beta1"||pname=="beta2")
{
f.set_param_lower_limit(pname,.3);
f.set_param_upper_limit(pname,1.4);
}
}
}
//perform the fitting, first freeze beta1, beta2, rc1, and rc2
if(tie_beta)
{
f.set_param_modifier(freeze_param<std::vector<double>,std::vector<double>,std::vector<double>,std::string>("beta")+
freeze_param<std::vector<double>,std::vector<double>,std::vector<double>,std::string>("rc1")+
freeze_param<std::vector<double>,std::vector<double>,std::vector<double>,std::string>("rc2")
);
}
else
{
f.set_param_modifier(freeze_param<std::vector<double>,std::vector<double>,std::vector<double>,std::string>("beta1")+
freeze_param<std::vector<double>,std::vector<double>,std::vector<double>,std::string>("beta2")+
freeze_param<std::vector<double>,std::vector<double>,std::vector<double>,std::string>("rc1")+
freeze_param<std::vector<double>,std::vector<double>,std::vector<double>,std::string>("rc2")
);
}
f.fit();
f.clear_param_modifier();
//then perform the fitting, freeze beta1 and beta2
//f.set_param_modifier(freeze_param<std::vector<double>,std::vector<double>,std::vector<double>,std::string>("beta"));
//f.set_param_modifier(freeze_param<std::vector<double>,std::vector<double>,std::vector<double>,std::string>("bkg"));
f.fit();
//f.clear_param_modifier();
//finally thaw all parameters
f.fit();
/*
double beta1=0;
double beta2=0;
n01=f.get_param_value("n01");
rc1=f.get_param_value("rc1");
n02=f.get_param_value("n02");
rc2=f.get_param_value("rc2");
if(tie_beta)
{
beta=f.get_param_value("beta");
beta1=beta;
beta2=beta;
}
else
{
beta1=f.get_param_value("beta1");
beta2=f.get_param_value("beta2");
}
*/
//output the params
ofstream param_output("lx_dbeta_param.txt");
//output the datasets and fitting results
for(size_t i=0;i<f.get_num_params();++i)
{
if(f.get_param_info(i).get_name()=="rc1")
{
cerr<<"rc1_kpc"<<"\t"<<abs(f.get_param_info(i).get_value())*cm_per_pixel/kpc<<endl;
param_output<<"rc1_kpc"<<"\t"<<abs(f.get_param_info(i).get_value())*cm_per_pixel/kpc<<endl;
}
if(f.get_param_info(i).get_name()=="rc2")
{
cerr<<"rc2_kpc"<<"\t"<<abs(f.get_param_info(i).get_value())*cm_per_pixel/kpc<<endl;
param_output<<"rc2_kpc"<<"\t"<<abs(f.get_param_info(i).get_value())*cm_per_pixel/kpc<<endl;
}
cerr<<f.get_param_info(i).get_name()<<"\t"<<abs(f.get_param_info(i).get_value())<<endl;
param_output<<f.get_param_info(i).get_name()<<"\t"<<abs(f.get_param_info(i).get_value())<<endl;
}
cerr<<"reduced_chi^2="<<f.get_statistic_value()/(radii.size()-f.get_model().get_num_free_params())<<endl;
param_output<<"reduced_chi^2="<<f.get_statistic_value()/(radii.size()-f.get_model().get_num_free_params())<<endl;
//c.verbose(false);
//f.set_statistic(c);
//f.fit();
std::vector<double> p=f.get_all_params();
f.clear_param_modifier();
std::vector<double> mv=f.eval_model(radii,p);
ofstream ofs_sbp("lx_sbp_fit.qdp");
ofs_sbp<<"read serr 2"<<endl;
ofs_sbp<<"skip single"<<endl;
ofs_sbp<<"line on 2"<<endl;
ofs_sbp<<"line on 3"<<endl;
ofs_sbp<<"line on 4"<<endl;
ofs_sbp<<"line on 5"<<endl;
ofs_sbp<<"line on 7"<<endl;
ofs_sbp<<"ls 2 on 7"<<endl;
ofs_sbp<<"ls 2 on 3"<<endl;
ofs_sbp<<"ls 2 on 4"<<endl;
ofs_sbp<<"ls 2 on 5"<<endl;
ofs_sbp<<"!LAB POS Y 4.00"<<endl;
ofs_sbp<<"!LAB ROT"<<endl;
ofs_sbp<<"win 1"<<endl;
ofs_sbp<<"yplot 1 2 3 4 5"<<endl;
ofs_sbp<<"loc 0 0 1 1"<<endl;
ofs_sbp<<"vie .1 .4 .9 .9"<<endl;
ofs_sbp<<"la y cnt/s/pixel/cm\\u2\\d"<<endl;
ofs_sbp<<"log x"<<endl;
ofs_sbp<<"log y"<<endl;
ofs_sbp<<"r x "<<(radii[1]+radii[0])/2*cm_per_pixel/kpc<<" "<<(radii[sbps.size()-2]+radii[sbps.size()-1])/2*cm_per_pixel/kpc<<endl;
ofs_sbp<<"win 2"<<endl;
ofs_sbp<<"yplot 6 7"<<endl;
ofs_sbp<<"loc 0 0 1 1"<<endl;
ofs_sbp<<"vie .1 .1 .9 .4"<<endl;
ofs_sbp<<"la x radius (kpc)"<<endl;
ofs_sbp<<"la y chi"<<endl;
ofs_sbp<<"log x"<<endl;
ofs_sbp<<"log y off"<<endl;
ofs_sbp<<"r x "<<(radii[1]+radii[0])/2*cm_per_pixel/kpc<<" "<<(radii[sbps.size()-2]+radii[sbps.size()-1])/2*cm_per_pixel/kpc<<endl;
for(size_t i=1;i<sbps.size();++i)
{
double x=(radii[i]+radii[i-1])/2;
double y=sbps[i-1];
double ye=sbpe[i-1];
//double ym=mv[i-1];
ofs_sbp<<x*cm_per_pixel/kpc<<"\t"<<y<<"\t"<<ye<<endl;
}
ofs_sbp<<"no no no"<<endl;
for(size_t i=1;i<sbps.size();++i)
{
double x=(radii[i]+radii[i-1])/2;
//double y=sbps[i-1];
//double ye=sbpe[i-1];
double ym=mv[i-1];
ofs_sbp<<x*cm_per_pixel/kpc<<"\t"<<ym<<"\t"<<0<<endl;
}
//bkg
ofs_sbp<<"no no no"<<endl;
bkg_level=abs(f.get_param_value("bkg"));
for(size_t i=0;i<sbps.size();++i)
{
double x=(radii[i]+radii[i-1])/2;
ofs_sbp<<x*cm_per_pixel/kpc<<"\t"<<bkg_level<<"\t0"<<endl;
}
//rc1
ofs_sbp<<"no no no"<<endl;
double rc1_kpc=abs(f.get_param_value("rc1")*cm_per_pixel/kpc);
double max_sbp=*max_element(sbps.begin(),sbps.end());
double min_sbp=*min_element(sbps.begin(),sbps.end());
for(double x=min_sbp;x<=max_sbp;x+=(max_sbp-min_sbp)/100)
{
ofs_sbp<<rc1_kpc<<"\t"<<x<<"\t"<<"0"<<endl;
}
//rc2
ofs_sbp<<"no no no"<<endl;
double rc2_kpc=abs(f.get_param_value("rc2")*cm_per_pixel/kpc);
for(double x=min_sbp;x<=max_sbp;x+=(max_sbp-min_sbp)/100)
{
ofs_sbp<<rc2_kpc<<"\t"<<x<<"\t"<<"0"<<endl;
}
//resid
ofs_sbp<<"no no no"<<endl;
for(size_t i=1;i<sbps.size();++i)
{
double x=(radii[i]+radii[i-1])/2;
//double y=sbps[i-1];
//double ye=sbpe[i-1];
double ym=mv[i-1];
ofs_sbp<<x*cm_per_pixel/kpc<<"\t"<<(ym-sbps[i-1])/sbpe[i-1]<<"\t"<<1<<endl;
}
//zero level in resid map
ofs_sbp<<"no no no"<<endl;
for(size_t i=1;i<sbps.size();++i)
{
double x=(radii[i]+radii[i-1])/2;
//double y=sbps[i-1];
//double ye=sbpe[i-1];
//double ym=mv[i-1];
ofs_sbp<<x*cm_per_pixel/kpc<<"\t"<<0<<"\t"<<0<<endl;
}
mv=f.eval_model_raw(radii,p);
ofstream ofs_rho("lx_rho_fit.qdp");
ofstream ofs_rho_data("lx_rho_fit.dat");
//ofstream ofs_entropy("entropy.qdp");
ofs_rho<<"la x radius (kpc)"<<endl;
ofs_rho<<"la y density (cm\\u-3\\d)"<<endl;
/*
for(int i=1;i<sbps.size();++i)
{
double x=(radii[i]+radii[i-1])/2;
double ym=mv[i-1];
ofs_rho<<x*cm_per_pixel/kpc<<"\t"<<ym<<endl;
}
*/
p.back()=0;
radii.clear();
double rout=atof(argv[2])*kpc;
for(double r=0;r<rout;r+=1*kpc)//step size=1kpc
{
double r_pix=r/cm_per_pixel;
radii.push_back(r_pix);
}
double Da=cm_per_pixel/(.492/3600./180.*pi);
double Dl=Da*(1+z)*(1+z);
cout<<"dl="<<Dl/kpc<<endl;
for(int n=3;n<argc;++n)
{
spline_func_obj cf_erg;
for(ifstream ifs(argv[n]);;)
{
assert(ifs.is_open());
double x,y;
ifs>>x>>y;
if(!ifs.good())
{
break;
}
//cerr<<x<<"\t"<<y<<endl;
cf_erg.add_point(x,y);//change with source
}
cf_erg.gen_spline();
projector<double>& pj=dynamic_cast<projector<double>&>(f.get_model());
pj.attach_cfunc(cf_erg);
mv=f.eval_model_raw(radii,p);
double flux_erg=0;
for(size_t i=0;i<radii.size()-1;++i)
{
double S=pi*(radii[i+1]+radii[i])*(radii[i+1]-radii[i]);
flux_erg+=S*mv[i];
}
cout<<flux_erg*4*pi*Dl*Dl<<endl;
cout<<flux_erg<<endl;
param_output<<"Lx"<<n-2<<"\t"<<flux_erg*4*pi*Dl*Dl<<endl;
param_output<<"Fx"<<n-2<<"\t"<<flux_erg<<endl;
}
}
|
#include<bits/stdc++.h>
using namespace std;
int NumberOf1Between1AndN_Solution(int n)
{
if(n == 0)
return 0;
int res = 1,s;
for(int i = 10; i <= n; i++) {
s = i;
while(s){
if(s % 10 == 1)
res++;
s /= 10;
}
}
return res;
}
int main()
{
int n;
cin >> n;
while(n--) {
int m;
cin >> m;
cout << NumberOf1Between1AndN_Solution(m) << endl;
}
return 0;
}
|
//stack的基本操作(均可直接使用STL)
//清空
void clear()
{
TOP=-1;
}
//获取栈内元素个数
int size(){
return TOP+1;
}
//判空
bool empty(){
return TOP==-1?true:false;
}
//进栈
void push(int x){
st[++TOP]=x;
}
//出栈
void pop(){
TOP--;
}
//取栈顶元素
int top()
{
return st[TOP];
}
//STL中并没有实现栈的清空,因此需要如下操作
while(!st.empty){
st.pop();
}
|
/*
* Copyright (C) 2020 Open Source Robotics Foundation
*
* 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 PYSHAPE_HPP
#define PYSHAPE_HPP
#include <rmf_traffic/geometry/Shape.hpp>
namespace geometry = rmf_traffic::geometry;
// Trampoline rmf_traffic::geometry::Shape wrapper class
// to allow method overrides from Python and type instantiation
class PyShape : public geometry::Shape
{
public:
// Constructor
using geometry::Shape::Shape;
geometry::FinalShape finalize() const override
{
PYBIND11_OVERLOAD_PURE(
geometry::FinalShape,
geometry::Shape,
finalize, // Trailing comma required to specify no args
);
}
};
// Py class to expose protected constructors
class PyFinalShape : public geometry::FinalShape
{
public:
// Constructor
using geometry::FinalShape::FinalShape;
};
#endif // PYSHAPE_HPP
|
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
#include "faustPM.h"
faustPM faust;
AudioInputI2S in;
AudioOutputI2S out;
//AudioAnalyzeRMS gateRMS;
// gate input
//AudioConnection patchCord1(in, 0, gateRMS, 0);
// outputs
AudioConnection patchCord3(faust, 0, out, 0);
AudioControlSGTL5000 codec;
const int POT0 = 20;
const int POT1 = 21;
void setup() {
Serial.begin(9600);
AudioMemory(10);
codec.enable();
codec.inputSelect(AUDIO_INPUT_LINEIN);
codec.volume(0.82);
codec.adcHighPassFilterDisable();
codec.lineInLevel(0,0);
codec.unmuteHeadphone();
}
bool gateOpen = false;
long int lastGate = millis();
void loop() {
/*
// Hold Length
int pot0 = analogRead(POT0);
float holdLength = map(float(pot0) / 1024, 0, 1, 1, 200);
faust.setParamValue("holdLength", holdLength);
// Strike Position
int pot1 = analogRead(POT1);
int strikePosition = (int)map(float(pot1) / 1024, 0, 1, 0, 5);
faust.setParamValue("strikePosition", strikePosition);
// Gate
if (gateRMS.available()) {
float rmsValue = gateRMS.read();
// Serial.print(rmsValue);
// Serial.print(" ");
// Serial.print(gateOpen);
// Serial.print(" ");
// Serial.println(tap2.read());
// delay(4);
// trigger gate
if (rmsValue > 0.2 && !gateOpen) {
faust.setParamValue("gate", 1);
delay(20);
faust.setParamValue("gate", 0);
gateOpen = true;
} else if (rmsValue < 0.2 && gateOpen) {
gateOpen = false;
}
// TODO: retrigger delay?
}
*/
}
|
#include <iostream>
#include "SecureString.h"
#include "SecureArray.h"
using namespace std;
int main()
{
SecureString str("Hello!", 6);
SecureString cstr(" W0RLD");
str.Append(cstr);
char exc = str.AtIndex(5);
str.Append(SecureString(&exc, 1));
str.Append(exc);
str.Append("\t:D");
str.ReplaceAt(15, "D:");
cout << "Equivalence: " << (str == SecureString("Hello! W0RLD!!\tD:") ? "Pass" : "Fail") << endl;
cout << "Empty Equivalence: " << (SecureString() == SecureString("") ? "Pass" : "Fail") << endl;
str.ReplaceAt(str.GetLength(),
"\n()()()()()*\
\n()()()()*()\
\n()()()*()()\
\n()()*()()()\
\n()*()()()()");
SecureString test("\n*()()()()()");
SecureString pullFrom;
pullFrom << test;
str.Append(pullFrom);
cout << endl << "String: " << str.GetStr() << endl << "String-length to allocated buffer: " << str.GetLength() << " / " << str.GetBufferLength() << endl;
return 0;
}
|
#include <Arduino.h>
#include <credentials.h>
#include <thingDescriptionTemplate.h>
#include <Preferences.h>
#include <ArduinoOTA.h>
#include <analogWrite.h>
#include <DHT.h>
#include <Wire.h>
#include <BH1750.h>
#include <WiFi.h>
#include <driver/adc.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <AsyncJson.h>
#include <ArduinoJson.h>
#include <HTTPClient.h>
HTTPClient http; //for gateway registration
String ipAddr;
String thingTitle;
String thingDescription;
String status = "available";
boolean ledIsOn = true;
int ledStatus = 1;
AsyncWebServer server(80);
AsyncEventSource events("/events/critical-plant-status");
const char* ssid = WIFI_SSID;
const char* password = WIFI_PASSWORD;
#define LED_PIN 32 //GPIO Port of Blue Wifi-Status LED
#define RGB_PIN_RED 16
#define RGB_PIN_GREEN 17
#define RGB_PIN_BLUE 18
int RGBValues [3] = {0, 255, 0}; //initialize RGB LED Green
#define DHT_PIN 4 // Digital pin connected to the DHT sensor
#define DHT_TYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHT_PIN, DHT_TYPE);
#define BH1750_SCL 21
#define BH1750_SDA 22
BH1750 lightMeter;
#define ADCAttenuation ADC_ATTEN_DB_11 //ADC_ATTEN_DB_11 = 0-3,6V? Docs: 2,6V gut Messbar; Dämpung ADC
#define NUM_MOISTURE_READS 10
#define MOISTURE_SENSOR_MIN 1050 //Luft 1050; TODO: trockene Erde Messen
#define MOISTURE_SENSOR_MAX 2540 //max mit Wasser: 2540; frisch gegossen nach paar min 2350
#define HUMIDITY 0
#define TEMPERATURE 1
#define LIGHT_INTENSITY 2
#define MOISTURE 3
float sensorValues [4];
float humidityMin, humidityMax, tempMin, tempMax, lightMin, lightMax, moistureMin, moistureMax;
boolean eventSent= false;
Preferences preferences;
String getStringFromPreferences(const char * key, String defaultValue){
preferences.begin("storage", false);
String value = preferences.getString(key, defaultValue);
preferences.end();
return value;
}
int getIntFromPreferences(const char * key, int defaultValue){
preferences.begin("storage", false);
int value = preferences.getInt(key, defaultValue);
preferences.end();
return value;
}
float getFloatFromPreferences(const char * key, float defaultValue){
preferences.begin("storage", false);
float value = preferences.getFloat(key, defaultValue);
preferences.end();
return value;
}
void putStringIntoPreferences(const char * key, String value){
preferences.begin("storage", false);
preferences.putString(key, value);
preferences.end();
}
void putIntIntoPreferences(const char * key, int value){
preferences.begin("storage", false);
preferences.putInt(key, value);
preferences.end();
}
void putFloatIntoPreferences(const char * key, float value){
preferences.begin("storage", false);
preferences.putFloat(key, value);
preferences.end();
}
void writeRGBValuesToPins(int rgb [3]){
analogWrite (RGB_PIN_RED, rgb[0]);
analogWrite (RGB_PIN_GREEN, rgb[1]);
analogWrite (RGB_PIN_BLUE, rgb[2]);
}
void toggleLedStatus(){
ledIsOn = !ledIsOn;
if (ledIsOn){
digitalWrite(LED_PIN, HIGH); // turn on the LED
}
else{
digitalWrite(LED_PIN, LOW);
}
}
void notFound(AsyncWebServerRequest *request){
if (request->method() == HTTP_OPTIONS) {
request->send(200);
} else {
request->send(404, "application/json", "{\"message\":\"Not found\"}");;
}
}
String createSensorValuesString(){
String sensorValuesString = "";
sensorValuesString += ("Humidity: ");
sensorValuesString += sensorValues[HUMIDITY];
sensorValuesString += ("%, Temperature: ");
sensorValuesString += sensorValues[TEMPERATURE];
sensorValuesString += " Degree Celsius";
sensorValuesString += (" Light Intensity: ");
sensorValuesString += sensorValues[LIGHT_INTENSITY];
sensorValuesString += (" --- Moisture Value: ");
sensorValuesString += sensorValues[MOISTURE];
return sensorValuesString;
}
void checkWifiAndUpdateStatusLED(){
if (WiFi.status() == WL_CONNECTED){
digitalWrite(LED_PIN, HIGH);
}
else{
digitalWrite(LED_PIN, LOW);
}
}
float getMoisturePercentage(float value){
value = value - MOISTURE_SENSOR_MIN;
if (value <= 0){
return 0;
}
int range = MOISTURE_SENSOR_MAX - MOISTURE_SENSOR_MIN;
if (range <= 0){
return 0;
}
value = (value / range) * 100;
if (value >= 100){
return 100;
}
return value;
}
boolean humidityIsCritical(){
return sensorValues[HUMIDITY] > humidityMax || sensorValues[HUMIDITY] < humidityMin;
}
boolean tempIsCritical(){
return sensorValues[TEMPERATURE] > tempMax || sensorValues[TEMPERATURE] < tempMin;
}
boolean lightIsCritical(){
return sensorValues[LIGHT_INTENSITY] > lightMax || sensorValues[LIGHT_INTENSITY] < lightMin;
}
boolean moistureIsCritical(){
return sensorValues[MOISTURE] > moistureMax || sensorValues[MOISTURE] < moistureMin;
}
boolean anyValueIsCritical(){
return humidityIsCritical() || tempIsCritical() || lightIsCritical() || moistureIsCritical();
}
void updateIPGateway(){
// Path to Gateway Thing registration
http.begin("https://plantfriend.ddns.net/gateway/add-thing");
String bearerToken = "Bearer ";
bearerToken += GATEWAY_API_TOKEN;
http.addHeader("Authorization", bearerToken);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST("{\"title\":\"" + thingTitle + "\",\"localIP\":\"http://"+ ipAddr +"\"}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
// Free resources
http.end();
}
// Setup
void setup() {
Serial.begin(9600);
Serial.println("Booting");
status = getStringFromPreferences("status", "available");
ledStatus = getIntFromPreferences("ledStatus", 3);
humidityMin = getFloatFromPreferences("humidityMin", 0.0);
humidityMax = getFloatFromPreferences("humidityMax", 100.0);
tempMin = getFloatFromPreferences("tempMin", 15.0);
tempMax = getFloatFromPreferences("tempMax", 35.0);
lightMin = getFloatFromPreferences("lightMin", 10.0);
lightMax = getFloatFromPreferences("lightMax", 1000.0);
moistureMin = getFloatFromPreferences("moistureMin", 1050);
moistureMax = getFloatFromPreferences("moistureMax", 2540);
writeRGBValuesToPins(RGBValues);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("Connection Failed! Rebooting...");
delay(1000);
ESP.restart();
}
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
ipAddr = WiFi.localIP().toString();
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
thingDescription = String(thingDescriptionTemplate);
thingDescription.replace("&IP_ADDR&", ipAddr);
// Get Thing Title from TD: JSON parsing
DynamicJsonDocument doc(1024);
deserializeJson(doc, thingDescription);
JsonObject TD_json = doc.as<JsonObject>();
// You can use a String to get an element of a JsonObject
// No duplication is done.
thingTitle = TD_json[String("title")].as<String>();
// setup pin 5 as a digital output pin for blue LED
pinMode (LED_PIN, OUTPUT);
dht.begin();
// Initialize the I2C bus (BH1750 library doesn't do this automatically)
Wire.begin(BH1750_SCL, BH1750_SDA);
if (lightMeter.begin()) {
Serial.println(F("BH1750 initialised"));
}
else {
Serial.println(F("Error initialising BH1750"));
// Moisture Sensor
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(ADC1_CHANNEL_6, ADCAttenuation);
}
digitalWrite(LED_PIN, HIGH); // turn on the LED
// HTTP Server Routes
// Properties
// read properties / HTTP GET
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", thingDescription);
request->send(response);
});
server.on("/properties/status", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", status);
request->send(response);
});
server.on("/properties/humidity", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(sensorValues[HUMIDITY]));
request->send(response);
});
server.on("/properties/temperature", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(sensorValues[TEMPERATURE]));
request->send(response);
});
server.on("/properties/light-intensity", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(sensorValues[LIGHT_INTENSITY]));
request->send(response);
});
server.on("/properties/moisture", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(sensorValues[MOISTURE]));
request->send(response);
});
server.on("/properties/humidityMin", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(humidityMin));
request->send(response);
});
server.on("/properties/humidityMax", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(humidityMax));
request->send(response);
});
server.on("/properties/tempMin", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(tempMin));
request->send(response);
});
server.on("/properties/tempMax", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(tempMax));
request->send(response);
});
server.on("/properties/lightMin", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(lightMin));
request->send(response);
});
server.on("/properties/lightMax", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(lightMax));
request->send(response);
});
server.on("/properties/moistureMin", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(moistureMin));
request->send(response);
});
server.on("/properties/moistureMax", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", String(moistureMax));
request->send(response);
});
//write properties / HTTP PUT
AsyncCallbackJsonWebHandler *statusHandler = new AsyncCallbackJsonWebHandler("/properties/status", [](AsyncWebServerRequest *request, JsonVariant &json) {
StaticJsonDocument<200> data;
if (json.is<JsonArray>())
{
data = json.as<JsonArray>();
}
else if (json.is<JsonObject>())
{
data = json.as<JsonObject>();
}
if (data["status"]){
status = data["status"].as<String>();
} else {
status = "default";
}
putStringIntoPreferences("status", status);
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
AsyncCallbackJsonWebHandler *humidityMinHandler = new AsyncCallbackJsonWebHandler("/properties/humidityMin", [](AsyncWebServerRequest *request, JsonVariant &json) {
StaticJsonDocument<200> data;
if (json.is<JsonArray>())
{
data = json.as<JsonArray>();
}
else if (json.is<JsonObject>())
{
data = json.as<JsonObject>();
}
if (data["humidityMin"]){
humidityMin = data["humidityMin"].as<float>();
}
putFloatIntoPreferences("humidityMin", humidityMin);
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
AsyncCallbackJsonWebHandler *humidityMaxHandler = new AsyncCallbackJsonWebHandler("/properties/humidityMax", [](AsyncWebServerRequest *request, JsonVariant &json) {
StaticJsonDocument<200> data;
if (json.is<JsonArray>())
{
data = json.as<JsonArray>();
}
else if (json.is<JsonObject>())
{
data = json.as<JsonObject>();
}
if (data["humidityMax"]){
humidityMax = data["humidityMax"].as<float>();
}
putFloatIntoPreferences("humidityMax", humidityMax);
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
AsyncCallbackJsonWebHandler *tempMinHandler = new AsyncCallbackJsonWebHandler("/properties/tempMin", [](AsyncWebServerRequest *request, JsonVariant &json) {
StaticJsonDocument<200> data;
if (json.is<JsonArray>())
{
data = json.as<JsonArray>();
}
else if (json.is<JsonObject>())
{
data = json.as<JsonObject>();
}
if (data["tempMin"]){
tempMin = data["tempMin"].as<float>();
}
putFloatIntoPreferences("tempMin", tempMin);
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
AsyncCallbackJsonWebHandler *tempMaxHandler = new AsyncCallbackJsonWebHandler("/properties/tempMax", [](AsyncWebServerRequest *request, JsonVariant &json) {
StaticJsonDocument<200> data;
if (json.is<JsonArray>())
{
data = json.as<JsonArray>();
}
else if (json.is<JsonObject>())
{
data = json.as<JsonObject>();
}
if (data["tempMax"]){
tempMax = data["tempMax"].as<float>();
}
putFloatIntoPreferences("tempMax", tempMax);
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
AsyncCallbackJsonWebHandler *lightMinHandler = new AsyncCallbackJsonWebHandler("/properties/lightMin", [](AsyncWebServerRequest *request, JsonVariant &json) {
StaticJsonDocument<200> data;
if (json.is<JsonArray>())
{
data = json.as<JsonArray>();
}
else if (json.is<JsonObject>())
{
data = json.as<JsonObject>();
}
if (data["lightMin"]){
lightMin = data["lightMin"].as<float>();
}
putFloatIntoPreferences("lightMin", lightMin);
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
AsyncCallbackJsonWebHandler *lightMaxHandler = new AsyncCallbackJsonWebHandler("/properties/lightMax", [](AsyncWebServerRequest *request, JsonVariant &json) {
StaticJsonDocument<200> data;
if (json.is<JsonArray>())
{
data = json.as<JsonArray>();
}
else if (json.is<JsonObject>())
{
data = json.as<JsonObject>();
}
if (data["lightMax"]){
lightMax = data["lightMax"].as<float>();
}
putFloatIntoPreferences("lightMax", lightMax);
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
AsyncCallbackJsonWebHandler *moistureMinHandler = new AsyncCallbackJsonWebHandler("/properties/moistureMin", [](AsyncWebServerRequest *request, JsonVariant &json) {
StaticJsonDocument<200> data;
if (json.is<JsonArray>())
{
data = json.as<JsonArray>();
}
else if (json.is<JsonObject>())
{
data = json.as<JsonObject>();
}
if (data["moistureMin"]){
moistureMin = data["moistureMin"].as<float>();
}
putFloatIntoPreferences("moistureMin", moistureMin);
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
AsyncCallbackJsonWebHandler *moistureMaxHandler = new AsyncCallbackJsonWebHandler("/properties/moistureMax", [](AsyncWebServerRequest *request, JsonVariant &json) {
StaticJsonDocument<200> data;
if (json.is<JsonArray>())
{
data = json.as<JsonArray>();
}
else if (json.is<JsonObject>())
{
data = json.as<JsonObject>();
}
if (data["moistureMax"]){
moistureMax = data["moistureMax"].as<float>();
}
putFloatIntoPreferences("moistureMax", moistureMax);
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
server.addHandler(statusHandler);
server.addHandler(humidityMinHandler);
server.addHandler(humidityMaxHandler);
server.addHandler(tempMinHandler);
server.addHandler(tempMaxHandler);
server.addHandler(lightMinHandler);
server.addHandler(lightMaxHandler);
server.addHandler(moistureMinHandler);
server.addHandler(moistureMaxHandler);
// Actions: HTTP POST
server.on("/actions/toggle-led", HTTP_POST, [](AsyncWebServerRequest *request) {
toggleLedStatus();
StaticJsonDocument<100> data;
data["new led-status"] = ledIsOn;
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
server.on("/actions/reset-event", HTTP_POST, [](AsyncWebServerRequest *request) {
eventSent = false;
String response_str = "Critical Event succesfully reset.";
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
server.on("/actions/set-rgb-led", HTTP_POST, [](AsyncWebServerRequest *request) {
if (request->hasParam("red")){
RGBValues[0] = request->getParam("red")->value().toInt();
}
if (request->hasParam("green")){
RGBValues[1] = request->getParam("green")->value().toInt();
}
if (request->hasParam("blue")){
RGBValues[2] = request->getParam("blue")->value().toInt();
}
writeRGBValuesToPins(RGBValues);
StaticJsonDocument<100> data;
data["red:"] = RGBValues[0];
data["green:"] = RGBValues[1];
data["blue:"] = RGBValues[2];
String response_str;
serializeJson(data, response_str);
AsyncWebServerResponse *response = request->beginResponse(200, "application/json", response_str);
request->send(response);
});
// Handle Web Server Events (SSE)
events.onConnect([](AsyncEventSourceClient *client){
//reconnect
if(client->lastId()){
Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
}
//new client
else {
client->send("You are now subscribed to the critical-plant-status.", NULL, millis());
if (anyValueIsCritical()){
client->send("Critical Plant Status! Please check the properties.", NULL, millis());
}
}
});
server.addHandler(&events);
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "append, delete, entries, foreach, get, has, keys, set, values, Authorization, Cache-Control, last-event-id");
server.onNotFound(notFound);
server.begin();
updateIPGateway();
}
void loop() {
ArduinoOTA.handle();
checkWifiAndUpdateStatusLED();
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
sensorValues[HUMIDITY] = dht.readHumidity();
// Read temperature as Celsius (the default)
sensorValues[TEMPERATURE] = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
// float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(sensorValues[HUMIDITY]) || isnan(sensorValues[TEMPERATURE])) {
Serial.println(F("Failed to read from DHT sensor!"));
}
// Compute heat index in Fahrenheit (the default)
// float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
// float hic = dht.computeHeatIndex(t, h, false);
sensorValues[LIGHT_INTENSITY] = lightMeter.readLightLevel();
int moistureSum = 0;
for (int i = 0; i < NUM_MOISTURE_READS; i++) { // Averaging algorithm
moistureSum += adc1_get_raw(ADC1_CHANNEL_6); //Read analog
}
sensorValues[MOISTURE] = getMoisturePercentage(moistureSum / NUM_MOISTURE_READS);
Serial.println(createSensorValuesString());
if (anyValueIsCritical()){
int dangerArray [3] = {255,0,0};
writeRGBValuesToPins(dangerArray);
if (!eventSent){
events.send("Critical Plant Status! Danger!", NULL, millis());
eventSent = true;
}
} else {
writeRGBValuesToPins(RGBValues);
}
updateIPGateway();
// Wait a few seconds between measurements.
delay(5000);
}
|
#include <stdio.h>
#include <algorithm>
using namespace std;
int n,m,cnt;
double camera[200];
double list[20000];
int main()
{
int c;
scanf("%d",&c);
while(c--)
{
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++)
scanf("%lf",&camera[i]);
cnt = 0;
for(int i=0;i<m-1;i++)
for(int j=i+1;j<m;j++)
list[cnt++] = camera[i] - camera[j];
sort(list,list+cnt);
double prev_list = -1;
double value = -1;
int temp = 1;
int cond = 0;
double prev = 0;
for(int i=0;i<cnt;i++)
{
value = -list[i];
if(prev_list == value)
continue;
prev_list = value;
temp = 1;
cond = 0;
prev = camera[0];
for(int i=1;i<m;i++)
{
if((camera[i] - prev) >= value)
{
prev = camera[i];
temp++;
}
if(temp >= n)
{
cond = 1;
break;
}
}
if(cond)
{
printf("%.2lf\n",value);
break;
}
}
}
}
|
#pragma once
#include "AbstractSort.h"
class SelectionSort :
public AbstractSort
{
public:
SelectionSort();
~SelectionSort();
void sort(int arr[], int size) override;
};
|
#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
class Base
{
private:
int n;
public:
Base(int m):n(m){ cout<<"Base is called\n";}
~Base(){}
};
class Other
{
int m;
public:
Other(int a):m(a){ cout<<"Other is called\n";}
};
class Derive:public Base
{
int v;
const int cst;
int &r;
Other obj;
public:
Derive(int a,int b,int c):Base(a),obj(b),cst(c),r(a)
{
v = a;
cout<<"Self is called\n";
}
~Derive(){}
};
int main()
{
Derive dd(3,4,5);
int a = 5; // 声明、定义变量的同时初始化
int b(6); // 声明、定义变量的同时初始化
a = 6; // 赋值操作,用于变量的更新
b = 7; // 赋值操作,用于变量的更新
const int c = 8; // 因为是只读,此后不能再更新,自然需要在声明、定义的同时初始化
// const在C中是只读变量,C++视上下文可以实现为只读变量或常量
int arr[5]; // 虽然arr有常量性质,但其元素却是可写的变量
int &r = a; // 引用可以理解为一个实现了自动解引用的有常量性质的指针
cout<< 1 <<endl;
while(1);
return 0;
}
/*
Base is called
Other is called
Self is called
*/
|
#include<bits/stdc++.h>
using namespace std;
int power(int a,int n)
{
int res=1;
while(n>0)
{
if(n&1)
{
res=res*a; n--; // at least once the power will be odd then we will increase our ans .ans will be correct because a will be changed accordingly
}
n=n/2; // power decrease by power of two as we are increasing base(a) as power of two
a=a*a; // we can write a4=a^2 * a^2 and a^2=a*a
}
return res;
}
int main()
{
int a,n;
cin>>a>>n;
cout<<power(a,n)<<"\n";
}
|
#ifndef FUZZYCORE_CALCULATION_SINGLE_VALUES_VIEW_H
#define FUZZYCORE_CALCULATION_SINGLE_VALUES_VIEW_H
#include "../abstractView/AbstractView.h"
#include "../viewUtils/ViewUtils.h"
class CalculationSingleValuesView : public AbstractView {
public:
CalculationSingleValuesView();
void displayStaticContent() override;
void displayDynamicContent() override;
};
#endif
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.UI.Xaml.Navigation.1.h"
#include "Windows.UI.Xaml.1.h"
#include "Windows.UI.Xaml.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::UI::Xaml::Navigation {
struct LoadCompletedEventHandler : Windows::Foundation::IUnknown
{
LoadCompletedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> LoadCompletedEventHandler(L lambda);
template <typename F> LoadCompletedEventHandler (F * function);
template <typename O, typename M> LoadCompletedEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Navigation::NavigationEventArgs & e) const;
};
struct NavigatedEventHandler : Windows::Foundation::IUnknown
{
NavigatedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> NavigatedEventHandler(L lambda);
template <typename F> NavigatedEventHandler (F * function);
template <typename O, typename M> NavigatedEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Navigation::NavigationEventArgs & e) const;
};
struct NavigatingCancelEventHandler : Windows::Foundation::IUnknown
{
NavigatingCancelEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> NavigatingCancelEventHandler(L lambda);
template <typename F> NavigatingCancelEventHandler (F * function);
template <typename O, typename M> NavigatingCancelEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs & e) const;
};
struct NavigationFailedEventHandler : Windows::Foundation::IUnknown
{
NavigationFailedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> NavigationFailedEventHandler(L lambda);
template <typename F> NavigationFailedEventHandler (F * function);
template <typename O, typename M> NavigationFailedEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Navigation::NavigationFailedEventArgs & e) const;
};
struct NavigationStoppedEventHandler : Windows::Foundation::IUnknown
{
NavigationStoppedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> NavigationStoppedEventHandler(L lambda);
template <typename F> NavigationStoppedEventHandler (F * function);
template <typename O, typename M> NavigationStoppedEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Navigation::NavigationEventArgs & e) const;
};
struct INavigatingCancelEventArgs :
Windows::Foundation::IInspectable,
impl::consume<INavigatingCancelEventArgs>
{
INavigatingCancelEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct INavigatingCancelEventArgs2 :
Windows::Foundation::IInspectable,
impl::consume<INavigatingCancelEventArgs2>
{
INavigatingCancelEventArgs2(std::nullptr_t = nullptr) noexcept {}
};
struct INavigationEventArgs :
Windows::Foundation::IInspectable,
impl::consume<INavigationEventArgs>
{
INavigationEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct INavigationEventArgs2 :
Windows::Foundation::IInspectable,
impl::consume<INavigationEventArgs2>
{
INavigationEventArgs2(std::nullptr_t = nullptr) noexcept {}
};
struct INavigationFailedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<INavigationFailedEventArgs>
{
INavigationFailedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IPageStackEntry :
Windows::Foundation::IInspectable,
impl::consume<IPageStackEntry>
{
IPageStackEntry(std::nullptr_t = nullptr) noexcept {}
};
struct IPageStackEntryFactory :
Windows::Foundation::IInspectable,
impl::consume<IPageStackEntryFactory>
{
IPageStackEntryFactory(std::nullptr_t = nullptr) noexcept {}
};
struct IPageStackEntryStatics :
Windows::Foundation::IInspectable,
impl::consume<IPageStackEntryStatics>
{
IPageStackEntryStatics(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
// Filename: cPetChase.cxx
// Created by: dcranall (15Jul04)
//
////////////////////////////////////////////////////////////////////
#include "cPetChase.h"
#include "cMover.h"
TypeHandle CPetChase::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: CPetChase::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
CPetChase::
CPetChase(NodePath *target, float min_dist, float move_angle) :
_min_dist(min_dist),
_move_angle(move_angle),
_look_at_node("lookatNode"),
_vel(0),
_rot_vel(0)
{
if (target) {
_target = *target;
}
}
////////////////////////////////////////////////////////////////////
// Function: CPetChase::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
CPetChase::
~CPetChase() {
_look_at_node.remove_node();
}
////////////////////////////////////////////////////////////////////
// Function: CPetChase::process
// Access: Public, Virtual
// Description: override this and set your impulse's influence for
// this pass on its mover
////////////////////////////////////////////////////////////////////
void CPetChase::
process(float dt) {
CImpulse::process(dt);
if (_target.is_empty()) {
return;
}
// calc distance to target
LVector3f target_pos = _target.get_pos(_node_path);
float distance = sqrt((target_pos[0]*target_pos[0]) + (target_pos[1]*target_pos[1]));
// calc angle between us and the target
_look_at_node.look_at(_target);
float rel_h = _look_at_node.get_h(_node_path);
rel_h = (fmod((rel_h + 180), 360) - 180);
// turn towards the target
const float epsilon = .005;
const float rot_speed = _mover->get_rot_speed();
float v_h = 0;
if (rel_h < -epsilon) {
v_h = -rot_speed;
} else if (rel_h > epsilon) {
v_h = rot_speed;
}
// don't oversteer
if (fabs(v_h * dt) > fabs(rel_h)) {
v_h = rel_h / dt;
}
float v_forward = 0;
if ((distance > _min_dist) && (fabs(rel_h) < _move_angle)) {
v_forward = _mover->get_fwd_speed();
}
// don't get too close
const float distance_left = distance - _min_dist;
/*
cerr << "distance " << distance << endl;
cerr << "distanceLeft " << distance_left << endl;
*/
if ((distance > _min_dist) && ((v_forward * dt) > distance_left)) {
v_forward = distance_left / dt;
}
if (v_forward) {
_vel.set_y(v_forward);
_mover->add_shove(_vel);
}
if (v_h) {
_rot_vel.set_x(v_h);
_mover->add_rot_shove(_rot_vel);
}
}
////////////////////////////////////////////////////////////////////
// Function: CPetChase::set_mover
// Access: Public, Virtual
// Description: called internally by cMover when we're added
////////////////////////////////////////////////////////////////////
void CPetChase::
set_mover(CMover &mover) {
CImpulse::set_mover(mover);
_look_at_node.reparent_to(_node_path);
_vel = 0;
_rot_vel = 0;
}
|
#include "matrix.h"
#include "stiff.h"
#include <math.h>
int ode_maxlen;
t_numatrix<double> ode_tmp;
vector< vector<double> > ode_dat;
t_LUmatrix<double> ode_jac;
int ode_nstep;
/*
template<class T>
T max(T a, T b)
{
return A > B ? A : B ;
}
template<class T>
T min(T a, T b)
{
return A < B ? A : B ;
}
*/
void rosenbrock_step(vector<double> y, vector<double> dydx, int dim, double x, double dx, vector<double> &yout,
vector<double> &yerr, void (*derivs)(double, const vector<double> &, vector<double> &, int),
void (*jacobn)(double, const vector<double> &, double**, int) )
{
int i,j;
vector<double> err(dim);
vector<double> g1(dim), g2(dim), g3(dim), g4(dim);
vector<double> ysav = y;
double xsav = x;
const double GAM = (1.0/2.0);
const double A21 = 2.0;
const double A31 = (48.0/25.0);
const double A32 = (6.0/25.0);
const double C21 = -8.0;
const double C31 = (372.0/25.0);
const double C32 = (12.0/5.0);
const double C41 = (-112.0/125.0);
const double C42 = (-54.0/125.0);
const double C43 = (-2.0/5.0);
const double B1 = (19.0/9.0);
const double B2 = (1.0/2.0);
const double B3 = (25.0/108.0);
const double B4 = (125.0/108.0);
const double E1 = (17.0/54.0);
const double E2 = (7.0/36.0);
const double E3 = 0.0;
const double E4 = (125.0/108.0);
//const double C1X = (1.0/2.0);
//const double C2X = (-3.0/2.0);
//const double C3X = (121.0/50.0);
//const double C4X = (29.0/250.0);
const double A2X = 1.0;
//const double A3X = (3.0/5.0);
jacobn(x, y, ode_jac, dim);
for(i=0; i<dim; i++)
for(j=0; j<dim; j++)
ode_jac[i][j] *= -1.0;
for(i=0; i<dim; i++)
ode_jac[i][i] += 1.0/(GAM*dx);
ode_jac.decompose();
for(i=0; i<dim; i++)
g1[i] = dydx[i];
ode_jac.LUbksb(g1);
for(i=0; i<dim; i++)
y[i] = ysav[i] + A21*g1[i];
x = xsav + A2X*dx;
derivs(x, y, dydx, dim);
for(i=0; i<dim; i++)
g2[i] = dydx[i] + C21*g1[i]/dx;
ode_jac.LUbksb(g2);
for(i=0; i<dim; i++)
y[i] = ysav[i] + A31*g1[i] + A32*g2[i];
x = xsav + A2X*dx;
derivs(x, y, dydx, dim);
for(i=0; i<dim; i++)
g3[i]=dydx[i] + ( C31*g1[i] + C32*g2[i] )/dx;
ode_jac.LUbksb(g3);
for(i=0; i<dim; i++)
g4[i] = dydx[i] + ( C41*g1[i] + C42*g2[i] + C43*g3[i])/dx;
ode_jac.LUbksb(g4);
for(i=0; i<dim; i++)
{
ode_tmp[i][0] = yout[i] = ysav[i] + B1*g1[i] + B2*g2[i] + B3*g3[i] + B4*g4[i];
yerr[i] = E1*g1[i] + E2*g2[i] + E3*g3[i] + E4*g4[i];
}
}
void euler_implicit_step(vector<double> y, vector<double> dydx, int dim, double x, double dx, double *yout,
double *yerr, void (*derivs)(double, const vector<double> &, vector<double> &, int),
void (*jacobn)(double, const vector<double> &, double**, int) )
{
int i,j;
jacobn(x, y, ode_jac, dim);
for(i=0; i<dim; i++)
for(j=0; j<dim; j++)
ode_jac[i][j] *= -dx;
for(i=0; i<dim; i++)
ode_jac[i][i] += 1.0;
ode_jac.decompose();
ode_jac.LUbksb(dydx);
for(i=0; i<dim; i++)
ode_tmp[i][0] = yout[i] = y[i] + dydx[i]*dx;
}
void euler_step(vector<double> y, vector<double> dydx, int dim, double x, double dx, double *yout,
double *yerr, void (*derivs)(double, const vector<double> &, vector<double> &, int),
void (*jacobn)(double, const vector<double> &, double**, int) )
{
int i;
for(i=0; i<dim; i++)
ode_tmp[i][0] = yout[i] = y[i] + dydx[i]*dx;
}
void euler_3step(vector<double> y, vector<double> dydx, int dim, double x, double dx, vector<double> &yout,
vector<double> &yerr, void (*derivs)(double, const vector<double> &, vector<double> &, int),
void (*jacobn)(double, const vector<double> &, double**, int) )
{
vector<double> C1(dim);
int i;
for(i=0; i<dim; i++)
ode_tmp[i][0] = yout[i] = y[i] + dydx[i]*dx*0.5;
derivs(x+dx*0.5,yout,C1,dim);
for(i=0; i<dim; i++)
ode_tmp[i][1] = yout[i] = yout[i] + C1[i]*dx*0.5;
for(i=0; i<dim; i++)
{
C1[i] = y[i] + dydx[i]*dx;
yerr[i] = fabs(C1[i]-yout[i]);
}
}
void stiffint(vector<double> Y0, double x0, double x_max, double eps, double hi,
void (*derivs)(double,const vector<double> &, vector<double> &, int),
void (*jacobn)(double,const vector<double> &, double**, int),
void (*step)(vector<double>, vector<double>, int, double, double, double*, double*,
void(*)(double, const vector<double> &, vector<double> &, int),
void(*)(double, const vector<double> &, double**, int)),
int order)
{
int i;
double x=x0;
double h=hi;
int dim = Y0.size();
vector<double> Y = Y0;
vector<double> dY(dim);
vector<double> tmp_vec(dim);
ode_nstep = 1;
for(i=0; i<dim; i++)
ode_dat[i].push_back( Y0[i] );
ode_dat[dim].push_back( x0 );
while(x<=x_max)
{
derivs(x,Y,dY,dim);
std::cout << x << " " << dY[0] << " " << dY[1] << std::endl;
(*step)(Y, dY, dim, x, h,&(tmp_vec[0]), NULL, derivs, jacobn);
ode_dat[dim].push_back( x += h );
for(i=0; i<dim; i++)
ode_dat[i].push_back( Y[i] = tmp_vec[i] );
ode_nstep++;
h *= 1.002;
}
}
void stiffint_adpt(vector<double> Y0, double x0, double x_max, double eps, double hi, int &nok, int &nbad,
void (*derivs)(double, const vector<double> &, vector<double> &, int),
void (*jacobn)(double, const vector<double> &, double**, int),
void (*step)(vector<double>, vector<double>, int, double, double, vector<double> &, vector<double> &,
void(*)(double, const vector<double> &, vector<double> &, int),
void(*)(double, const vector<double> &, double**, int)),
int order)
{
const double safety = 0.9;
const double pshrnk = -1.0/order;
const double pgrow = -1.0/(order+1);
const double errcon = pow(5.0/safety,1/pgrow);
int i;
double x=x0;
double h=hi;
double errmax;
double htemp, hnext;
double xnew;
double hdid;
int dim = Y0.size();
vector<double> Y = Y0;
vector<double> dY(dim);
vector<double> tmp_vec(dim);
vector<double> Yerr(dim);
vector<double> Yscal(dim, 0.1);
ode_nstep = 1;
nok=nbad=0;
ode_dat[dim].push_back( x0 );
for(i=0; i<dim; i++)
ode_dat[i].push_back( Y0[i] );
while(x<=x_max)
{
derivs(x,Y,dY,dim);
for(i=0; i<dim; i++)
Yscal[i]=fabs(Y[i])+fabs(dY[i]*h)+YMIN;
hdid = h;
for(;;)
{
step(Y, dY, dim, x, h,tmp_vec, Yerr, derivs, jacobn);
errmax=0.0;
for(i=0;i<dim;i++)
errmax = max(double(errmax),double(fabs(Yerr[i]/Yscal[i])));
errmax /= eps;
if(errmax <= 1.0) break;
htemp = safety*h*pow(errmax,pshrnk);
h = (h >= 0.0 ? max(htemp,0.1*h) : min(htemp,0.1*h));
xnew = x+h;
if (xnew == x) error("stepsize underflow");
}
if (errmax > errcon) hnext=safety*h*pow(errmax,pgrow);
else hnext=5.0*h;//No more than a factor of 5 increase
ode_dat[dim].push_back( x += h );
for(i=0; i<dim; i++)
ode_dat[i].push_back( Y[i] = tmp_vec[i] );
//x += h;
if(h==hdid) nok++; else nbad++;
h=hnext;
if(ode_nstep++ > ode_maxlen)
exit(0);
}
}
void odeint(double *Y0, int dim, double x0, double x_max, double eps, double hi, int *nok, int *nbad,
void (*derivs)(double, double*, double*),
void (*step)(double*, double*, int, double, double, double*, double*,
void (*)(double, double*, double*)), int order)
{
int i;
double x=x0;
double h;
vector<double> Y(dim);
vector<double> dY(dim);
vector<double> tmp_vec(dim);
for(i=0; i<dim; i++)
{
printf("%d\n",i);
Y[i]=Y0[i];
}
h=hi;
ode_nstep = 1;
for(i=0; i<dim; i++)
ode_dat[i][0] = Y0[i];
ode_dat[dim][0] = x0;
while(x<=x_max)
{
derivs(x,&(Y[0]),&(dY[0]));
(*step)(&(Y[0]), &(dY[0]), dim, x, h,&(tmp_vec[0]), NULL, derivs);
ode_dat[dim][ode_nstep] = x += h;
for(i=0; i<dim; i++)
ode_dat[i][ode_nstep] = Y[i] = tmp_vec[i];
ode_nstep++;
}
}
void ode_init(int dim, int maxlen)
{
ode_maxlen = maxlen;
ode_tmp.resize(dim+1,2);
ode_dat.resize(dim+1);
for(int i=0; i<= dim; i++)
ode_dat[i].reserve(maxlen);
ode_jac.resize(dim, dim);
}
|
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef FLUX_WAITCONDITION_H
#define FLUX_WAITCONDITION_H
#include <flux/Mutex>
namespace flux {
/** \brief Wait condition
* \see Channel
*/
class WaitCondition: public Object
{
public:
inline static Ref<WaitCondition> create() { return new WaitCondition; }
~WaitCondition();
void wait(Mutex *mutex);
bool waitUntil(double timeout, Mutex *mutex);
void signal();
void broadcast();
private:
WaitCondition();
pthread_cond_t cond_;
};
} // namespace flux
#endif // FLUX_WAITCONDITION_H
|
#include "Patcher_ItemSplitQuantity.h"
#include "../Addr.h"
#include "../FileSystem.h"
//-----------------------------------------------------------------------------
// Static variable initialization
int CPatcher_ItemSplitQuantity::itemQuantity = 1;
LPBYTE CPatcher_ItemSplitQuantity::addrTargetReturn = NULL;
//-----------------------------------------------------------------------------
// Constructor
CPatcher_ItemSplitQuantity::CPatcher_ItemSplitQuantity(void)
{
patchname = "Item Split Quantity";
vector<WORD> patch;
vector<WORD> backup;
backup +=
0x33, 0xC0, 0x40, 0x8D, 0x4D, 0xA0;
patch +=
0xE9, 0x01FF, 0x01FF, 0x01FF, 0x01FF, 0x90; // NOP => NOP
MemoryPatch mp( NULL, patch, backup);
mp.Search(L"Pleione.dll");
mp.PatchRelativeAddress(0x01, (LPBYTE)ModifyQuantity);
addrTargetReturn = mp.GetAddr() + 0x06;
patches += mp;
if (CheckPatches())
WriteLog("Patch initialization successful: %s.\n", patchname.c_str());
else
WriteLog("Patch initialization failed: %s.\n", patchname.c_str());
}
//-----------------------------------------------------------------------------
// Hook functions
NAKED void CPatcher_ItemSplitQuantity::ModifyQuantity(void) {
_asm {
xor eax, eax
inc eax
lea ecx, [ebp - 60]
mov eax, itemQuantity
jmp addrTargetReturn
}
}
int CPatcher_ItemSplitQuantity::GetQuantity(void)
{
return itemQuantity;
}
// Options
bool CPatcher_ItemSplitQuantity::SetQuantity(int value) {
if (patches.empty()) return false;
itemQuantity = value;
return true;
}
//-----------------------------------------------------------------------------
// INI Functions
bool CPatcher_ItemSplitQuantity::ReadINI(void)
{
if (ReadINI_Bool(L"ItemSplitQuantity")) {
int tempQuantity = ReadINI_Int(L"ItemSplitQuantity", 1, 10);
if (!SetQuantity(tempQuantity))
return false;
return Install();
}
return true;
}
bool CPatcher_ItemSplitQuantity::WriteINI(void)
{
WriteINI_Bool(L"ItemSplitQuantity", IsInstalled());
return true;
}
|
/**********************************************************
* License: The MIT License
* https://www.github.com/doc97/TxtAdv/blob/master/LICENSE
**********************************************************/
#include "LuaResponseHandler.h"
namespace txt
{
LuaResponseHandler::LuaResponseHandler(LuaManager* manager, const std::string& filename,
const std::string& matcher, const std::string& action)
: m_manager(manager), m_filename(filename), m_func_matcher(matcher), m_func_action(action)
{
}
LuaResponseHandler::LuaResponseHandler(const std::string& filename,
const std::string& matcher, const std::string& action)
: LuaResponseHandler(nullptr, filename, matcher, action)
{
}
LuaResponseHandler::~LuaResponseHandler()
{
}
void LuaResponseHandler::SetManager(LuaManager* manager)
{
m_manager = manager;
}
void LuaResponseHandler::HandleInputImpl(const std::string& input)
{
if (Matches(input))
{
std::string err;
std::vector<LuaParam> params = { { LuaParam::String, input.c_str() } };
std::vector<LuaParam> retVal = {};
if (!m_manager->ExecFunc(m_filename.c_str(), m_func_action.c_str(), params, retVal, err))
throw std::runtime_error(err);
}
}
bool LuaResponseHandler::MatchesImpl(const std::string& input)
{
if (!m_manager)
throw std::runtime_error("No LuaManager has been specified!");
std::string err;
std::vector<LuaParam> params = { { LuaParam::String, input.c_str() } };
std::vector<LuaParam> retVal = { { LuaParam::Bool, false } };
if (!m_manager->ExecFunc(m_filename.c_str(), m_func_matcher.c_str(), params, retVal, err))
throw std::runtime_error(err);
return retVal[0].data.b;
}
} // namespace txt
|
#include<iostream>
using namespace std;
int main()
{
char* p = nullptr;
p[10] = '!';
return 0;
}
|
/**
*
* @file main.cpp
* @brief IO module test
*
**/
#include <exception>
#include <bitset>
#include <iostream>
#include <Tools/CommandLineArgumentReader.hpp>
#include <RobotStatus/Information.hpp>
#include "Communicator/TCP.hpp"
#include "Device/Sensor/IMU/VMU931.hpp"
#include "Device/Sensor/IMU/InertialMeasurementUnit.hpp"
#include "Device/ControlBoard/CM730.hpp"
#include "Device/ControlBoard/SerialControlBoard.hpp"
#include "Device/Actuator/ServoMotor/MX28.hpp"
#include "Device/Actuator/ServoMotor/SerialServoMotor.hpp"
#include "Device/Actuator/ServoMotor/B3MSC1170A.cpp"
#include "SerialDeviceSelector.hpp"
#include "Communicator/SerialControlSelector.hpp"
#include "DeviceManager.hpp"
#include "Communicator/Protocols/DynamixelVersion1.hpp"
#include "Communicator/SerialController/Dynamixel.hpp"
#include "Communicator/SerialController/Simple.hpp"
#include "Communicator/SerialController/Kondo.hpp"
#include "Robot.hpp"
void serial_base_test(Tools::Log::LoggerPtr, const std::string &);
int main(int argc, char **argv) {
auto robo_info = std::make_shared<RobotStatus::Information>(argc, argv);
auto logger = robo_info->logger;
logger->start_loger_thread();
try {
logger->message(Tools::Log::MessageLevels::warning, "This is IO test code");
logger->message(Tools::Log::MessageLevels::info, "IO module test start");
logger->message(Tools::Log::MessageLevels::debug, "Starttime access count of " + std::to_string(logger.use_count()));
logger->message(Tools::Log::MessageLevels::info, "");
Tools::CommandLineArgumentReader clar(argc, argv);
std::string imu_port_name = clar.get("--imu");
std::string servo_port_name = clar.get("--servo");
auto robot = std::make_unique<IO::Robot>(robo_info);
if(!servo_port_name.empty()) {
logger->message(Tools::Log::MessageLevels::info, "Servo control device name is " + servo_port_name);
auto command_control_selector = std::make_unique<IO::Communicator::SerialControlSelector>();
//auto device_selector = std::make_unique<IO::SerialDeviceSelector<IO::Device::ControlBoard::SerialControlBoard>>(robo_info);
//auto serial_controller = command_control_selector->choice_shared_object("Dynamixel");
auto serial_controller = command_control_selector->choice_shared_object("Kondo");
//auto control_board = device_selector->choice_object("CM730");
auto serial_servo_motors = std::vector<std::unique_ptr<IO::Device::Actuator::ServoMotor::SerialServoMotor>>();
//control_board->register_controller(serial_controller);
for(auto i = 1; i <= 1; ++ i) {
serial_servo_motors.push_back(
std::make_unique<IO::Device::Actuator::ServoMotor::B3MSC1170A>(i, robo_info)
);
serial_servo_motors.back()->register_controller(serial_controller);
}
serial_controller->port_name(servo_port_name);
serial_controller->baud_rate(1000000);
serial_controller->async_launch();
//control_board->enable_power(true);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
for(auto &&ssm : serial_servo_motors) {
ssm->enable_torque(true);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
for(auto &&ssm : serial_servo_motors) {
ssm->write_gain(1, 1, 1);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
serial_controller->wait_for_send_packets();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
while(true) {
std::stringstream ss;
for(unsigned int i = 0; i < serial_servo_motors.size(); i ++) {
std::string string_angle_of_degree = clar.get("-angular" + std::to_string(i + 1));
if(!string_angle_of_degree.empty()) {
auto angle_of_degree = std::stof(string_angle_of_degree);
ss << "ID" + std::to_string(i + 1) + ": " << angle_of_degree << " ";
serial_servo_motors.at(i)->write_angle(angle_of_degree);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
logger->message(Tools::Log::MessageLevels::debug, ss.str());
}
}
else {
logger->message(Tools::Log::MessageLevels::info, "Unset Servo port name");
}
if(!imu_port_name.empty()) {
logger->message(Tools::Log::MessageLevels::info, "IMU device name is " + imu_port_name);
auto command_control_selector = std::make_unique<IO::Communicator::SerialControlSelector>();
auto device_selector = std::make_unique<IO::SerialDeviceSelector<IO::Device::Sensor::IMU::InertialMeasurementUnit>>(robo_info);
auto command_controller = command_control_selector->choice_shared_object("Simple");
auto imu_device = device_selector->choice_object("VMU931");
imu_device = std::make_unique<IO::Device::Sensor::IMU::VMU931>(robo_info);
command_controller = std::make_shared<IO::Communicator::SerialController::Simple>();
command_controller->port_name(imu_port_name);
imu_device->register_controller(command_controller);
imu_device->enable_all();
logger->message(Tools::Log::MessageLevels::info, "Enable IMU functions");
imu_device->async_launch();
logger->message(Tools::Log::MessageLevels::info, "IMU launch");
while(true) {
RobotStatus::TimeSeriesData<Tools::Math::Vector3<float>> accel, euler, gyro;
RobotStatus::TimeSeriesData<Tools::Math::Vector4<float>> q;
if(robo_info->accelerometers_data) {
const auto current_accel = robo_info->accelerometers_data->latest();
if(current_accel != accel) {
accel = current_accel;
std::stringstream ss;
ss << "acc: " << accel.value.transpose() << "\t" << accel.timestamp << "\t";
logger->message(Tools::Log::MessageLevels::debug, ss.str());
}
}
else {
logger->message(Tools::Log::MessageLevels::debug, "Not found accelerometers");
}
if(robo_info->eulerangles_data) {
const auto current_euler = robo_info->eulerangles_data->latest();
if(current_euler != euler) {
euler = current_euler;
std::stringstream ss;
ss << "ang: " << euler.value.transpose() << "\t" << euler.timestamp << "\t";
logger->message(Tools::Log::MessageLevels::debug, ss.str());
}
}
else {
logger->message(Tools::Log::MessageLevels::debug, "Not found eulerangles");
}
if(robo_info->gyroscopes_data) {
const auto current_gyro = robo_info->gyroscopes_data->latest();
if(current_gyro != gyro) {
gyro = current_gyro;
std::stringstream ss;
ss << "gyr: " << gyro.value.transpose() << "\t" << gyro.timestamp << "\t";
logger->message(Tools::Log::MessageLevels::debug, ss.str());
}
}
else {
logger->message(Tools::Log::MessageLevels::debug, "Not found gyroscopes");
}
if(robo_info->quaternions_data) {
const auto current_q = robo_info->quaternions_data->latest();
if(current_q != q) {
q = current_q;
std::stringstream ss;
ss << "Qua: " << q.value.transpose() << "\t" << q.timestamp << "\t";
logger->message(Tools::Log::MessageLevels::debug, ss.str());
}
}
}
}
else {
logger->message(Tools::Log::MessageLevels::info, "Unset IMU port name");
}
logger->message(Tools::Log::MessageLevels::info, "");
logger->message(Tools::Log::MessageLevels::debug, "Dynamixel pakcet debug");
std::vector<IO::Communicator::Protocols::DynamixelVersion1::Packet> debug_packets;
std::vector<IO::Communicator::Protocols::DynamixelVersion1::ReadBuffer> debug_buffers;
IO::Communicator::Protocols::DynamixelVersion1::Bytes debug_write_bytes;
IO::Communicator::Protocols::DynamixelVersion1::SyncWriteData debug_sync_write_datas;
debug_packets.push_back(IO::Communicator::Protocols::DynamixelVersion1::create_ping_packet(0x01));
debug_write_bytes = static_cast<char>(0x00);
debug_write_bytes += static_cast<char>(0x02);
debug_packets.push_back(IO::Communicator::Protocols::DynamixelVersion1::create_write_packet(0x01, 0x1e, debug_write_bytes));
debug_packets.push_back(IO::Communicator::Protocols::DynamixelVersion1::create_read_packet(0x01, 0x2b, 0x01));
debug_write_bytes = static_cast<char>(0xc8);
debug_write_bytes += static_cast<char>(0x00);
debug_packets.push_back(IO::Communicator::Protocols::DynamixelVersion1::create_reg_write_packet(0x01, 0x1e, debug_write_bytes));
debug_packets.push_back(IO::Communicator::Protocols::DynamixelVersion1::create_action_packet(0x01));
debug_packets.push_back(IO::Communicator::Protocols::DynamixelVersion1::create_reset_packet(0x01));
debug_write_bytes = static_cast<char>(0x20);
debug_write_bytes += static_cast<char>(0x02);
debug_write_bytes += static_cast<char>(0x60);
debug_write_bytes += static_cast<char>(0x03);
debug_sync_write_datas.push_back(debug_write_bytes);
debug_write_bytes = static_cast<char>(0x01);
debug_packets.push_back(IO::Communicator::Protocols::DynamixelVersion1::create_sync_write(debug_write_bytes, 0x1e, debug_sync_write_datas));
for(size_t j = 0; j < debug_packets.size(); ++j) {
debug_buffers.push_back(IO::Communicator::Protocols::DynamixelVersion1::ReadBuffer());
for(auto i = 0; i < IO::Communicator::Protocols::DynamixelVersion1::full_packet_size(debug_packets.at(j)); ++ i) {
debug_buffers.at(j).at(i) = static_cast<uint8_t>(debug_packets.at(j).at(i));
}
}
for(auto &&dp : debug_packets) {
if(IO::Communicator::Protocols::DynamixelVersion1::is_broken_packet(dp)) {
std::stringstream ss;
for(auto &&p : dp) {
ss << std::bitset<8>(p) << "\n";
}
logger->message(Tools::Log::MessageLevels::warning, "Broken packet");
logger->message(Tools::Log::MessageLevels::warning, ss.str());
break;
}
std::stringstream ss;
ss << static_cast<int>(IO::Communicator::Protocols::DynamixelVersion1::packet_id(dp));
logger->message(Tools::Log::MessageLevels::debug, "Success packet ID:" + ss.str());
}
for(auto &&db : debug_buffers) {
if(IO::Communicator::Protocols::DynamixelVersion1::is_broken_packet(db)) {
std::stringstream ss;
for(auto &&b : db) {
ss << std::bitset<8>(b) << "\n";
}
logger->message(Tools::Log::MessageLevels::warning, "Broken packet");
logger->message(Tools::Log::MessageLevels::warning, ss.str());
break;
}
std::stringstream ss;
ss << static_cast<int>(IO::Communicator::Protocols::DynamixelVersion1::packet_id(db));
logger->message(Tools::Log::MessageLevels::debug, "Success packet ID:" + ss.str());
}
logger->message(Tools::Log::MessageLevels::info, "");
logger->message(Tools::Log::MessageLevels::info, "Load RobotConfig debug");
robo_info->set_config_filename<RobotStatus::Information::RobotType::Humanoid>("robot.conf.json");
//robo_info->set_config_filename<RobotStatus::Information::DeviceType::Sensor>("sensor.conf.json");
//robo_info->set_config_filename<RobotStatus::Information::DeviceType::Actuator>("actuator.conf.json");
{
auto device_manager = std::make_unique<IO::DeviceManager>(robo_info, logger);
device_manager->spawn_device();
device_manager->launch_device();
while(true) {
static int i;
if(i > 100000) {
break;
}
i ++;
RobotStatus::TimeSeriesData<Tools::Math::Vector3<float>> accel, euler, gyro;
RobotStatus::TimeSeriesData<Tools::Math::Vector4<float>> q;
if(robo_info->accelerometers_data) {
const auto current_accel = robo_info->accelerometers_data->latest();
if(current_accel != accel) {
accel = current_accel;
std::stringstream ss;
ss << "acc: " << accel.value.transpose() << "\t" << accel.timestamp << "\t";
logger->message(Tools::Log::MessageLevels::debug, ss.str());
}
}
else {
logger->message(Tools::Log::MessageLevels::debug, "Not found accelerometers");
}
if(robo_info->eulerangles_data) {
const auto current_euler = robo_info->eulerangles_data->latest();
if(current_euler != euler) {
euler = current_euler;
std::stringstream ss;
ss << "ang: " << euler.value.transpose() << "\t" << euler.timestamp << "\t";
logger->message(Tools::Log::MessageLevels::debug, ss.str());
}
}
else {
logger->message(Tools::Log::MessageLevels::debug, "Not found eulerangles");
}
if(robo_info->gyroscopes_data) {
const auto current_gyro = robo_info->gyroscopes_data->latest();
if(current_gyro != gyro) {
gyro = current_gyro;
std::stringstream ss;
ss << "gyr: " << gyro.value.transpose() << "\t" << gyro.timestamp << "\t";
logger->message(Tools::Log::MessageLevels::debug, ss.str());
}
}
else {
logger->message(Tools::Log::MessageLevels::debug, "Not found gyroscopes");
}
if(robo_info->quaternions_data) {
const auto current_q = robo_info->quaternions_data->latest();
if(current_q != q) {
q = current_q;
std::stringstream ss;
ss << "Qua: " << q.value.transpose() << "\t" << q.timestamp << "\t";
logger->message(Tools::Log::MessageLevels::debug, ss.str());
}
}
}
}
logger->message(Tools::Log::MessageLevels::info, "");
}
catch(const std::exception &error) {
logger->message(Tools::Log::MessageLevels::fatal, "Throwing error from main try");
std::cerr << error.what() << std::endl;
}
logger->message(Tools::Log::MessageLevels::info, "");
logger->message(Tools::Log::MessageLevels::debug, "Endtime access count of " + std::to_string(logger.use_count()));
logger->message(Tools::Log::MessageLevels::info, "IO module test end");
logger->close_loger_thread();
return 0;
}
void communicator_for_tcp() {
std::cout << "Starting communicator" << std::endl;
IO::Communicator::TCP tcp(5000);
std::cout << "Build client or server" << std::endl;
std::cout << tcp.client("127.0.0.1").message() << std::endl;
//std::cout << tcp.server_v4().message() << std::endl;
std::cout << "Read or Write" << std::endl;
std::cout << tcp.write("I'm client").message() << std::endl;
//std::cout << tcp.read() << std::endl;
std::cout << "End communicator" << std::endl;
}
void serial_base_test(Tools::Log::LoggerPtr logger, const std::string &port_name) {
if(!port_name.empty()) {
logger->message(Tools::Log::MessageLevels::info, "IMU device path is " + port_name);
auto serial_ptr = std::make_shared<IO::Communicator::SerialFlowScheduler>();
if(serial_ptr->open(port_name)) {
logger->message(Tools::Log::MessageLevels::info, "Successful serial port connection");
}
else {
throw std::runtime_error("Can not open serial port " + port_name);
}
IO::Communicator::SerialFlowScheduler::SinglePacket send_packet;
send_packet = "vara";
send_packet += "varg";
serial_ptr->set_send_packet(send_packet);
serial_ptr->register_parse(
[&logger](const IO::Communicator::SerialFlowScheduler::ReadBuffer &read_buffer, const std::size_t &bytes) {
if(*(read_buffer.begin() + 2) == 'a') {
std::stringstream ss;
for(auto itr = read_buffer.begin(), end_itr = read_buffer.begin() + bytes; itr < end_itr; ++itr) {
ss << std::showbase << std::hex << static_cast<int>(*itr) << std::noshowbase;
ss << ",";
}
ss << static_cast<int>(bytes);
logger->message(Tools::Log::MessageLevels::debug, ss.str());
}
return true;
}
);
serial_ptr->launch();
}
}
|
#include <iostream>
#include <vector>
#include "defs.h"
#include "util.h"
using namespace std;
PatternIndex::PatternIndex ( int * x, int l, int sigma )
{
sa = new int [l+3];
isa = new int [l];
lcp = new int [l];
sa[l] = sa[l+1] = sa[l+2] = 0;
suffixArray ( x, sa, l, sigma );
for ( int i = 0; i < l; i++ )
isa[ sa[i] ] = i;
lcp[0] = 0;
int j = 0;
for ( int i = 0; i < l; i++ )
{
if ( isa[i] != 0 )
{
if ( i == 0 ) j = 0;
else j = ( lcp[isa[i-1]] >=2 ) ? lcp[isa[i-1]]-1 : 0;
while ( x[i+j] == x[sa[isa[i]-1]+j] )
j++;
lcp[isa[i]] = j;
}
}
}
int PatternIndex::SA ( int i ) {
return sa[i];
}
int PatternIndex::iSA ( int i ) {
return isa[i];
}
int PatternIndex::LCP ( int i ) {
return lcp[i];
}
|
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node *next;
Node() : val(0), next(NULL){};
Node(int val) : val(val), next(NULL){};
};
Node *insert(vector<int> nums)
{
Node *head = new Node(nums[0]), *temp = head;
int i = 1;
while (temp && i < nums.size())
{
Node *node = new Node(nums[i++]);
temp->next = node;
temp = temp->next;
}
return head;
}
void print(const Node *head)
{
if (!head)
return;
print(head->next);
cout << head->val << " ";
}
Node *fold(Node *head)
{
vector<Node *> nodes;
Node *temp = head;
while (temp)
{
nodes.push_back(temp);
temp = temp->next;
}
int n = nodes.size();
for (size_t i = 0; i < n / 2; i++)
nodes[i]->next = nodes[n - i];
return head;
}
int main()
{
Node *head = insert({1, 2, 3, 4, 5, 6, 7, 8});
// print(head);
auto temp = fold(head);
print(temp);
return 0;
}
|
//#include <iostream>
#include <cstdio>
//#include <cstring>
//#include <algorithm>
//#include <bits/stdc++.h>
#include <queue>
#include <vector>
#include <set>
using namespace std;
typedef long long LL;
const int coeff[3]={2,3,5};
priority_queue<LL, vector<LL>, greater<LL> > mnpq;
set<LL> s;
int main()
{
//freopen("..\\file\\input.txt","r",stdin);
//freopen("..\\file\\output.txt","w",stdout);
//ios::sync_with_stdio(0);
//cin.tie(0);
mnpq.push(1); s.insert(1);
for(int i=1;;++i){
LL x=mnpq.top(); mnpq.pop();
if(i==1500){
printf("The 1500'th ugly number is %d.\n",x);
break;
}
for(int j=0;j!=3;++j){
LL y=x*coeff[j];
if(!s.count(y)){ s.insert(y); mnpq.push(y); }
}
}
return 0;
}
|
#include "audio\Singularity.Audio.h"
/*
* Cue.h
*
* An object allowing access to a single individual sound playing. 3d cue position is handled through AudioEmitters and AudioListeners.
*
* Author: Sela Davis
*
* Created: March 15, 2010 (03/15/10)
* Last modified: March 17, 2010 (03/17/10)
*/
namespace Singularity
{
namespace Audio
{
class Cue
{
private:
#pragma region Variables
// The XACT representation of the cue.
IXACT3Cue* m_pCue;
// The XACT index.
XACTINDEX m_index;
// The name of the cue.
String m_cueName;
// Whether or not the cue is playing.
bool m_bIsPlaying;
// Whether or not the cue is paused.
bool m_bIsPaused;
// Whether or not the cue is looping.
bool m_bIsLooping;
// Whether or not the cue is 3d.
bool m_bIs3d;
// A pointer to the soundbank used for this cue.
SoundBank* m_pSoundBank;
// The cue's DSP settings.
X3DAUDIO_DSP_SETTINGS m_dsp;
// The current state of the cue. (Playing, etc.)
DWORD m_state;
// The volume percentage.
float m_fVolumePercent;
#pragma endregion
public:
#pragma region Constructors and Finalizers
// Constructor.
Cue(SoundBank* soundbank, IXACT3Cue* cue, int index, String cueName = "");
// Destructor.
~Cue();
#pragma endregion
#pragma region Methods
// Initializes the cue.
void Initialize(bool isLooping, bool is3d);
// Updates the cue's state variables.
void UpdateState();
// Applies the 3d positional calculations to the cue.
void Apply3dCalculations(X3DAUDIO_DSP_SETTINGS dsp);
// Resets and reprepares the cue.
void ResetCue();
// Plays the cue.
void PlayCue();
// Pauses/unpauses the cue. (Toggle)
void PauseCue();
// Pauses/unpauses the cue. (Manual)
void PauseCue(bool becomePaused);
// Stops the cue.
void Stop();
#pragma endregion
#pragma region Properties
// Sets the current volume percentage (0-100)
void Set_VolumePercentage(float vol);
// Sets the cue's name.
void Set_CueName(String name);
// Returns the current volume percentage (0-100)
float Get_VolumePercentage();
// Returns the XACT index for this cue.
XACTINDEX Get_Index();
// Returns the XACT friendly name for this cue.
string Get_CueName();
// Whether or not the cue is playing.
bool Get_IsPlaying();
// Whether or not the cue is paused.
bool Get_IsPaused();
// Whether or not the cue is looping.
bool Get_IsLooping();
// Whether or no the cue is 3d positional.
bool Get_Is3d();
#pragma endregion
};
}
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "../base.h"
#include "Windows.ApplicationModel.DataTransfer.DragDrop.Core.0.h"
#include "Windows.ApplicationModel.DataTransfer.0.h"
#include "Windows.ApplicationModel.DataTransfer.DragDrop.0.h"
#include "Windows.Foundation.0.h"
#include "Windows.Graphics.Imaging.0.h"
#include "Windows.ApplicationModel.DataTransfer.1.h"
#include "Windows.Foundation.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core {
struct __declspec(uuid("7d56d344-8464-4faf-aa49-37ea6e2d7bd1")) __declspec(novtable) ICoreDragDropManager : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall add_TargetRequested(Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragDropManager, Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDropOperationTargetRequestedEventArgs> * value, event_token * returnValue) = 0;
virtual HRESULT __stdcall remove_TargetRequested(event_token value) = 0;
virtual HRESULT __stdcall get_AreConcurrentOperationsEnabled(bool * value) = 0;
virtual HRESULT __stdcall put_AreConcurrentOperationsEnabled(bool value) = 0;
};
struct __declspec(uuid("9542fdca-da12-4c1c-8d06-041db29733c3")) __declspec(novtable) ICoreDragDropManagerStatics : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_GetForCurrentView(Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragDropManager ** value) = 0;
};
struct __declspec(uuid("48353a8b-cb50-464e-9575-cd4e3a7ab028")) __declspec(novtable) ICoreDragInfo : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Data(Windows::ApplicationModel::DataTransfer::IDataPackageView ** value) = 0;
virtual HRESULT __stdcall get_Modifiers(winrt::Windows::ApplicationModel::DataTransfer::DragDrop::DragDropModifiers * value) = 0;
virtual HRESULT __stdcall get_Position(Windows::Foundation::Point * value) = 0;
};
struct __declspec(uuid("c54691e5-e6fb-4d74-b4b1-8a3c17f25e9e")) __declspec(novtable) ICoreDragInfo2 : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_AllowedOperations(winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation * value) = 0;
};
struct __declspec(uuid("cc06de4f-6db0-4e62-ab1b-a74a02dc6d85")) __declspec(novtable) ICoreDragOperation : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Data(Windows::ApplicationModel::DataTransfer::IDataPackage ** value) = 0;
virtual HRESULT __stdcall abi_SetPointerId(uint32_t pointerId) = 0;
virtual HRESULT __stdcall abi_SetDragUIContentFromSoftwareBitmap(Windows::Graphics::Imaging::ISoftwareBitmap * softwareBitmap) = 0;
virtual HRESULT __stdcall abi_SetDragUIContentFromSoftwareBitmapWithAnchorPoint(Windows::Graphics::Imaging::ISoftwareBitmap * softwareBitmap, Windows::Foundation::Point anchorPoint) = 0;
virtual HRESULT __stdcall get_DragUIContentMode(winrt::Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragUIContentMode * value) = 0;
virtual HRESULT __stdcall put_DragUIContentMode(winrt::Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragUIContentMode value) = 0;
virtual HRESULT __stdcall abi_StartAsync(Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation> ** value) = 0;
};
struct __declspec(uuid("824b1e2c-d99a-4fc3-8507-6c182f33b46a")) __declspec(novtable) ICoreDragOperation2 : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_AllowedOperations(winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation * value) = 0;
virtual HRESULT __stdcall put_AllowedOperations(winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation value) = 0;
};
struct __declspec(uuid("89a85064-3389-4f4f-8897-7e8a3ffb3c93")) __declspec(novtable) ICoreDragUIOverride : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_SetContentFromSoftwareBitmap(Windows::Graphics::Imaging::ISoftwareBitmap * softwareBitmap) = 0;
virtual HRESULT __stdcall abi_SetContentFromSoftwareBitmapWithAnchorPoint(Windows::Graphics::Imaging::ISoftwareBitmap * softwareBitmap, Windows::Foundation::Point anchorPoint) = 0;
virtual HRESULT __stdcall get_IsContentVisible(bool * value) = 0;
virtual HRESULT __stdcall put_IsContentVisible(bool value) = 0;
virtual HRESULT __stdcall get_Caption(hstring * value) = 0;
virtual HRESULT __stdcall put_Caption(hstring value) = 0;
virtual HRESULT __stdcall get_IsCaptionVisible(bool * value) = 0;
virtual HRESULT __stdcall put_IsCaptionVisible(bool value) = 0;
virtual HRESULT __stdcall get_IsGlyphVisible(bool * value) = 0;
virtual HRESULT __stdcall put_IsGlyphVisible(bool value) = 0;
virtual HRESULT __stdcall abi_Clear() = 0;
};
struct __declspec(uuid("d9126196-4c5b-417d-bb37-76381def8db4")) __declspec(novtable) ICoreDropOperationTarget : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_EnterAsync(Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragInfo * dragInfo, Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragUIOverride * dragUIOverride, Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation> ** returnValue) = 0;
virtual HRESULT __stdcall abi_OverAsync(Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragInfo * dragInfo, Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragUIOverride * dragUIOverride, Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation> ** returnValue) = 0;
virtual HRESULT __stdcall abi_LeaveAsync(Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragInfo * dragInfo, Windows::Foundation::IAsyncAction ** returnValue) = 0;
virtual HRESULT __stdcall abi_DropAsync(Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragInfo * dragInfo, Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation> ** returnValue) = 0;
};
struct __declspec(uuid("2aca929a-5e28-4ea6-829e-29134e665d6d")) __declspec(novtable) ICoreDropOperationTargetRequestedEventArgs : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_SetTarget(Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDropOperationTarget * target) = 0;
};
}
namespace ABI {
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragDropManager> { using default_interface = Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragDropManager; };
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragInfo> { using default_interface = Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragInfo; };
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragOperation> { using default_interface = Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragOperation; };
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragUIOverride> { using default_interface = Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragUIOverride; };
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDropOperationTargetRequestedEventArgs> { using default_interface = Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDropOperationTargetRequestedEventArgs; };
}
namespace Windows::ApplicationModel::DataTransfer::DragDrop::Core {
template <typename D>
struct WINRT_EBO impl_ICoreDragDropManager
{
event_token TargetRequested(const Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragDropManager, Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDropOperationTargetRequestedEventArgs> & value) const;
using TargetRequested_revoker = event_revoker<ICoreDragDropManager>;
TargetRequested_revoker TargetRequested(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragDropManager, Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDropOperationTargetRequestedEventArgs> & value) const;
void TargetRequested(event_token value) const;
bool AreConcurrentOperationsEnabled() const;
void AreConcurrentOperationsEnabled(bool value) const;
};
template <typename D>
struct WINRT_EBO impl_ICoreDragDropManagerStatics
{
Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragDropManager GetForCurrentView() const;
};
template <typename D>
struct WINRT_EBO impl_ICoreDragInfo
{
Windows::ApplicationModel::DataTransfer::DataPackageView Data() const;
Windows::ApplicationModel::DataTransfer::DragDrop::DragDropModifiers Modifiers() const;
Windows::Foundation::Point Position() const;
};
template <typename D>
struct WINRT_EBO impl_ICoreDragInfo2
{
Windows::ApplicationModel::DataTransfer::DataPackageOperation AllowedOperations() const;
};
template <typename D>
struct WINRT_EBO impl_ICoreDragOperation
{
Windows::ApplicationModel::DataTransfer::DataPackage Data() const;
void SetPointerId(uint32_t pointerId) const;
void SetDragUIContentFromSoftwareBitmap(const Windows::Graphics::Imaging::SoftwareBitmap & softwareBitmap) const;
void SetDragUIContentFromSoftwareBitmap(const Windows::Graphics::Imaging::SoftwareBitmap & softwareBitmap, const Windows::Foundation::Point & anchorPoint) const;
Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragUIContentMode DragUIContentMode() const;
void DragUIContentMode(Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragUIContentMode value) const;
Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation> StartAsync() const;
};
template <typename D>
struct WINRT_EBO impl_ICoreDragOperation2
{
Windows::ApplicationModel::DataTransfer::DataPackageOperation AllowedOperations() const;
void AllowedOperations(Windows::ApplicationModel::DataTransfer::DataPackageOperation value) const;
};
template <typename D>
struct WINRT_EBO impl_ICoreDragUIOverride
{
void SetContentFromSoftwareBitmap(const Windows::Graphics::Imaging::SoftwareBitmap & softwareBitmap) const;
void SetContentFromSoftwareBitmap(const Windows::Graphics::Imaging::SoftwareBitmap & softwareBitmap, const Windows::Foundation::Point & anchorPoint) const;
bool IsContentVisible() const;
void IsContentVisible(bool value) const;
hstring Caption() const;
void Caption(hstring_view value) const;
bool IsCaptionVisible() const;
void IsCaptionVisible(bool value) const;
bool IsGlyphVisible() const;
void IsGlyphVisible(bool value) const;
void Clear() const;
};
template <typename D>
struct WINRT_EBO impl_ICoreDropOperationTarget
{
Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation> EnterAsync(const Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragInfo & dragInfo, const Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragUIOverride & dragUIOverride) const;
Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation> OverAsync(const Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragInfo & dragInfo, const Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragUIOverride & dragUIOverride) const;
Windows::Foundation::IAsyncAction LeaveAsync(const Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragInfo & dragInfo) const;
Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::DataTransfer::DataPackageOperation> DropAsync(const Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragInfo & dragInfo) const;
};
template <typename D>
struct WINRT_EBO impl_ICoreDropOperationTargetRequestedEventArgs
{
void SetTarget(const Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDropOperationTarget & target) const;
};
}
namespace impl {
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragDropManager>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragDropManager;
template <typename D> using consume = Windows::ApplicationModel::DataTransfer::DragDrop::Core::impl_ICoreDragDropManager<D>;
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragDropManagerStatics>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragDropManagerStatics;
template <typename D> using consume = Windows::ApplicationModel::DataTransfer::DragDrop::Core::impl_ICoreDragDropManagerStatics<D>;
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragInfo>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragInfo;
template <typename D> using consume = Windows::ApplicationModel::DataTransfer::DragDrop::Core::impl_ICoreDragInfo<D>;
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragInfo2>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragInfo2;
template <typename D> using consume = Windows::ApplicationModel::DataTransfer::DragDrop::Core::impl_ICoreDragInfo2<D>;
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragOperation>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragOperation;
template <typename D> using consume = Windows::ApplicationModel::DataTransfer::DragDrop::Core::impl_ICoreDragOperation<D>;
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragOperation2>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragOperation2;
template <typename D> using consume = Windows::ApplicationModel::DataTransfer::DragDrop::Core::impl_ICoreDragOperation2<D>;
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragUIOverride>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDragUIOverride;
template <typename D> using consume = Windows::ApplicationModel::DataTransfer::DragDrop::Core::impl_ICoreDragUIOverride<D>;
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDropOperationTarget>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDropOperationTarget;
template <typename D> using consume = Windows::ApplicationModel::DataTransfer::DragDrop::Core::impl_ICoreDropOperationTarget<D>;
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDropOperationTargetRequestedEventArgs>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::ICoreDropOperationTargetRequestedEventArgs;
template <typename D> using consume = Windows::ApplicationModel::DataTransfer::DragDrop::Core::impl_ICoreDropOperationTargetRequestedEventArgs<D>;
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragDropManager>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragDropManager;
static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragDropManager"; }
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragInfo>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragInfo;
static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragInfo"; }
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragOperation>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragOperation;
static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragOperation"; }
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragUIOverride>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDragUIOverride;
static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragUIOverride"; }
};
template <> struct traits<Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDropOperationTargetRequestedEventArgs>
{
using abi = ABI::Windows::ApplicationModel::DataTransfer::DragDrop::Core::CoreDropOperationTargetRequestedEventArgs;
static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDropOperationTargetRequestedEventArgs"; }
};
}
}
|
#pragma once
#include <memory>
#include "Game.h"
#include "Session.h"
#include <boost\asio.hpp>
using boost::asio::ip::tcp;
class Server {
public:
Server(boost::asio::io_service& io_service, short port, Game& game);
private:
void do_accept();
tcp::acceptor acceptor_;
tcp::socket socket_;
Game& game_;
};
|
/***********************************************************************
created: Mon Jun 13 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 "CEGUI/falagard/WidgetComponent.h"
#include "CEGUI/falagard/XMLEnumHelper.h"
#include "CEGUI/falagard/XMLHandler.h"
#include "CEGUI/Window.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/XMLSerializer.h"
#include <algorithm>
namespace CEGUI
{
//! Default values
const HorizontalAlignment WidgetComponent::HorizontalAlignmentDefault(HorizontalAlignment::Left);
const VerticalAlignment WidgetComponent::VerticalAlignmentDefault(VerticalAlignment::Top);
WidgetComponent::WidgetComponent(const String& targetType,
const String& suffix,
const String& renderer,
bool autoWindow) :
d_targetType(targetType),
d_name(suffix),
d_rendererType(renderer),
d_autoWindow(autoWindow),
d_vertAlign(VerticalAlignmentDefault),
d_horzAlign(HorizontalAlignmentDefault)
{}
void WidgetComponent::create(Window& parent) const
{
Window* widget = WindowManager::getSingleton().createWindow(d_targetType, d_name);
widget->setAutoWindow(d_autoWindow);
// set the window renderer
if (!d_rendererType.empty())
widget->setWindowRenderer(d_rendererType);
// add the new widget to its parent
parent.addChild(widget);
// set alignment options
widget->setVerticalAlignment(d_vertAlign);
widget->setHorizontalAlignment(d_horzAlign);
// TODO: We still need code to specify position and size. Due to the advanced
// TODO: possibilities, this is better handled via a 'layout' method instead of
// TODO: setting this once and forgetting about it.
// initialise properties. This is done last so that these properties can
// override properties specified in the look assigned to the created widget.
for(PropertyInitialiserList::const_iterator curr = d_propertyInitialisers.begin(); curr != d_propertyInitialisers.end(); ++curr)
{
(*curr).apply(*widget);
}
// link up the event actions
for (EventActionList::const_iterator i = d_eventActions.begin();
i != d_eventActions.end();
++i)
{
(*i).initialiseWidget(*widget);
}
}
void WidgetComponent::cleanup(Window& parent) const
{
Window* widget = parent.findChild(getWidgetName());
if (!widget)
return;
// clean up up the event actions
for (EventActionList::const_iterator i = d_eventActions.begin();
i != d_eventActions.end();
++i)
{
(*i).cleanupWidget(*widget);
}
parent.destroyChild(widget);
}
const ComponentArea& WidgetComponent::getComponentArea() const
{
return d_area;
}
void WidgetComponent::setComponentArea(const ComponentArea& area)
{
d_area = area;
}
const String& WidgetComponent::getTargetType() const
{
return d_targetType;
}
void WidgetComponent::setTargetType(const String& type)
{
d_targetType = type;
}
const String& WidgetComponent::getWidgetName() const
{
return d_name;
}
void WidgetComponent::setWidgetName(const String& name)
{
d_name= name;
}
const String& WidgetComponent::getWindowRendererType() const
{
return d_rendererType;
}
void WidgetComponent::setWindowRendererType(const String& type)
{
d_rendererType = type;
}
VerticalAlignment WidgetComponent::getVerticalWidgetAlignment() const
{
return d_vertAlign;
}
void WidgetComponent::setVerticalWidgetAlignment(VerticalAlignment alignment)
{
d_vertAlign = alignment;
}
HorizontalAlignment WidgetComponent::getHorizontalWidgetAlignment() const
{
return d_horzAlign;
}
void WidgetComponent::setHorizontalWidgetAlignment(HorizontalAlignment alignment)
{
d_horzAlign = alignment;
}
void WidgetComponent::addPropertyInitialiser(const PropertyInitialiser& initialiser)
{
d_propertyInitialisers.push_back(initialiser);
}
void WidgetComponent::removePropertyInitialiser(const String& name)
{
PropertyInitialiserList::iterator f = d_propertyInitialisers.begin();
PropertyInitialiserList::iterator const l = d_propertyInitialisers.end();
// look for any removal candidate
for(; f != l; ++f)
{
if(f->getTargetPropertyName() == name)
{
break;
}
}
if(f == l)
{
// nothing to remove, so done
return;
}
// start moving over any remaining items to keep
for(PropertyInitialiserList::iterator i = f; ++i != l;)
{
if(i->getTargetPropertyName() != name)
{
std::iter_swap(f, i);
++f;
}
}
d_propertyInitialisers.erase(f, l);
}
void WidgetComponent::clearPropertyInitialisers()
{
d_propertyInitialisers.clear();
}
void WidgetComponent::setAutoWindow(bool is_auto)
{
d_autoWindow = is_auto;
}
bool WidgetComponent::isAutoWindow() const
{
return d_autoWindow;
}
void WidgetComponent::addEventAction(const EventAction& event_action)
{
d_eventActions.push_back(event_action);
}
void WidgetComponent::clearEventActions()
{
d_eventActions.clear();
}
bool WidgetComponent::layout(const Window& owner) const
{
try
{
Window* child = owner.getChild(d_name);
const Rectf pixelArea = d_area.getPixelRect(owner);
// TODO: check equality inside Element::setArea?
const URect& currArea = child->getArea();
if (currArea.d_min.d_x.d_scale == 0.f &&
currArea.d_min.d_y.d_scale == 0.f &&
currArea.d_max.d_x.d_scale == 0.f &&
currArea.d_max.d_y.d_scale == 0.f &&
currArea.d_min.d_x.d_offset == pixelArea.left() &&
currArea.d_min.d_y.d_offset == pixelArea.top() &&
currArea.d_max.d_x.d_offset == pixelArea.right() &&
currArea.d_max.d_y.d_offset == pixelArea.bottom())
{
return false;
}
child->setArea(
cegui_absdim(pixelArea.left()),
cegui_absdim(pixelArea.top()),
cegui_absdim(pixelArea.getWidth()),
cegui_absdim(pixelArea.getHeight()));
}
catch (UnknownObjectException&)
{
return false;
}
return true;
}
void WidgetComponent::writeXMLToStream(XMLSerializer& xml_stream) const
{
// output opening tag
xml_stream.openTag(Falagard_xmlHandler::ChildElement)
.attribute(Falagard_xmlHandler::NameSuffixAttribute, d_name)
.attribute(Falagard_xmlHandler::TypeAttribute, d_targetType);
if (!d_rendererType.empty())
xml_stream.attribute(Falagard_xmlHandler::RendererAttribute, d_rendererType);
if (!d_autoWindow)
xml_stream.attribute(Falagard_xmlHandler::AutoWindowAttribute, PropertyHelper<bool>::ValueFalse);
// Output <EventAction> elements
for (EventActionList::const_iterator i = d_eventActions.begin();
i != d_eventActions.end();
++i)
{
(*i).writeXMLToStream(xml_stream);
}
// output target area
d_area.writeXMLToStream(xml_stream);
// output vertical alignment if not-default
if(d_vertAlign != VerticalAlignmentDefault)
{
xml_stream.openTag(Falagard_xmlHandler::VertAlignmentElement);
xml_stream.attribute(Falagard_xmlHandler::TypeAttribute, FalagardXMLHelper<VerticalAlignment>::toString(d_vertAlign));
xml_stream.closeTag();
}
// output horizontal alignment if not-default
if(d_horzAlign != HorizontalAlignmentDefault)
{
xml_stream.openTag(Falagard_xmlHandler::HorzAlignmentElement);
xml_stream.attribute(Falagard_xmlHandler::TypeAttribute, FalagardXMLHelper<HorizontalAlignment>::toString(d_horzAlign));
xml_stream.closeTag();
}
//output property initialisers
for (PropertyInitialiserList::const_iterator prop = d_propertyInitialisers.begin(); prop != d_propertyInitialisers.end(); ++prop)
{
(*prop).writeXMLToStream(xml_stream);
}
// output closing tag
xml_stream.closeTag();
}
const PropertyInitialiser* WidgetComponent::findPropertyInitialiser(const String& propertyName) const
{
PropertyInitialiserList::const_reverse_iterator i = d_propertyInitialisers.rbegin();
while (i != d_propertyInitialisers.rend())
{
if ((*i).getTargetPropertyName() == propertyName)
return &(*i);
++i;
}
return nullptr;
}
bool WidgetComponent::handleFontRenderSizeChange(Window& window,
const Font* font) const
{
if (d_area.handleFontRenderSizeChange(window, font))
{
window.performChildLayout(false, false);
return true;
}
return false;
}
const WidgetComponent::PropertyInitialiserList& WidgetComponent::getPropertyInitialisers() const
{
return d_propertyInitialisers;
}
const WidgetComponent::EventActionList& WidgetComponent::getEventActions() const
{
return d_eventActions;
}
}
|
//
// Created by shimeng on 2021/4/11.
//
#include "common.h"
using namespace std;
/**
* 给你一个整数 n ,请你找出并返回第 n 个 丑数 。
* 丑数 就是只包含质因数 2、3 和/或 5 的正整数。
* @param n 第n个丑数
* @return
*/
int nthUglyNumber(int n) {
if (n <= 0) {
return 0;
}
vector<int> record(n);
record[0] = 1;
int p2 = 0, p3 = 0, p5 = 0;
for (int i = 1; i < n; ++i) {
int num2 = 2*record[p2];
int num3 = 3*record[p3];
int num5 = 5*record[p5];
int min_value = min(min(num2, num3), num5);
if (num2 == min_value) {
++p2;
}
if (num3 == min_value) {
++p3;
}
if (num5 == min_value) {
++p5;
}
record[i] = min_value;
}
return record[n-1];
}
int main() {
assert(nthUglyNumber(1) == 1);
assert(nthUglyNumber(2) == 2);
assert(nthUglyNumber(3) == 3);
assert(nthUglyNumber(10) == 12);
assert(nthUglyNumber(1690) == 2123366400);
return 0;
}
|
#include "stdafx.h"
#include <iostream>
#include <filesystem>
#include <fstream>
#include <string>
#include <sstream>
#include "FbHtmlParser.h"
#include "Conversation.h"
using namespace std;
namespace fs = std::experimental::filesystem;
FbHtmlParser::FbHtmlParser(fs::path msgPathIn)
{
msgPath = msgPathIn;
}
int FbHtmlParser::parse()
{
string token;
ifs.open(msgPath);
vector<string> participants;
string title = readInTag("<title>");
readInTag("<h3>");
//up to participants now
{
stringstream ss;
ifs >> token;
ifs >> token;
while (token.find("<") == string::npos) {
ss << token << ' ';
ifs >> token;
}
ss.str();
}
conv = new Conversation(participants);
ifs.close();
return 1;
}
Conversation* FbHtmlParser::getConversation()
{
return conv;
}
FbHtmlParser::~FbHtmlParser()
{
}
string FbHtmlParser::readInTag(string htmlTag)
{
string closeTag = htmlTag;
closeTag.insert(1, "/");
char token;
stringstream data;
int tagFound = 0;
while (!tagFound) {
token = ifs.get();
for (int i = 0; i < htmlTag.size(); i++) {
if (token != htmlTag[i]) {
tagFound = 0;
break;
}
else
{
tagFound = 1;
}
token = ifs.get();
}
if (ifs.eof()) {
return htmlTag;
}
}
data << token;
tagFound = 0;
while (!tagFound) {
token = ifs.get();
data << token;
for (int i = 0; i < closeTag.size(); i++) {
if (token != closeTag[i]) {
tagFound = 0;
break;
}
else
{
tagFound = 1;
}
token = ifs.get();
}
if (ifs.eof()) {
return htmlTag;
}
}
ifs.unget();
string retVal = data.str();
return retVal.substr(0, retVal.size() - 1);
}
|
#include<iostream>
using namespace std;
class cBase
{
public:
void fun()
{
cout<<"cBase fun1 0para"<<endl;
}
};
class cDerived: cBase
{
public:
void fun(int iNo)
{
cout<<"cDerived fun1 0para";
}
};
int main()
{
cBase bobj;
cDerived dobj;
bobj.fun();
//bobj.fun(20);//not present in base class
//dobj.fun(); //function hiading
dobj.fun(10);
return 0;
}
|
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int left = 0;
int right = 0;
if(nums.size() <= 1) return;
while(left < nums.size())
{
if(nums[left] == 0)
{
while(right < nums.size() && nums[right] == 0)
{
right++;
}
if(right < nums.size())
swap(nums[left], nums[right]);
}
left++;
right++;
}
}
};
|
#ifndef HUMAN_H_
#define HUMAN_H_
#include "alive.h"
#include "../../Items/pill.h"
#include "../../Items/item.h"
#include <string>
#include <map>
#include <stdlib.h> /* srand, rand */
using namespace std;
namespace haunted_house
{
class Ghost;
class Human: public Alive{
public:
Human();
Human(string name);
~Human(){};
Human(const Character& d); //TODO How to copy and assign??
Human& operator=(const Character& h);
virtual bool go(int direction){return false;};
virtual bool eat(Pill& pill);
//virtual bool fight(Character& c);
};
}
#endif
|
/*
* HeaderTrj.h
*
* Created on: May 13, 2012
* Author: marchi
*/
#ifndef HEADERTRJ_H_
#define HEADERTRJ_H_
#include <vector>
#include <string>
#include "FstreamC.h"
#include "FstreamF.h"
using std::vector;
using std::string;
using std::ifstream;
using std::ios;
const int HDIM=4;
const int TDIM=80;
const int FORTRANBYTES=4;
class HeaderTrj {
char hdr[HDIM];
int nfr,istart,natoms;
vector<string> title;
void ReadHeader(FstreamC *);
void ReadHeader(FstreamF *);
void ReadHeader(std::ifstream &);
public:
HeaderTrj();
virtual ~HeaderTrj();
int getNFR(){return nfr;}
int getNatoms(){return natoms;}
bool check(int n){return n==natoms;}
friend Fstream & operator>>(Fstream & fin, HeaderTrj & y){
if(FstreamC * finC=dynamic_cast<FstreamC *> (&fin))
y.ReadHeader(finC);
else if(FstreamF * finF=dynamic_cast<FstreamF *> (&fin))
y.ReadHeader(finF);
return fin;
}
friend std::ifstream & operator>>(std::ifstream & fin, HeaderTrj & y){
y.ReadHeader(fin);
return fin;
}
};
#endif /* HEADERTRJ_H_ */
|
#include <iostream>
#include <cstring>
using namespace std;
class Cd
{ // represents a CD disk
private:
char * performers;
char * label;
int selections; // number of selections
double playtime; // playing time in minutes
public:
Cd(const char * s1, const char * s2, int n, double x);
Cd(const Cd & d);
Cd();
virtual ~Cd();
virtual void Report() const; // reports all CD data
Cd & operator=(const Cd & d);
};
class Classic : public Cd
{
private:
char * primary;
public:
Classic(const char* s1, const char* s2, const char* s3, int n, double x);
Classic(const Classic &c);
Classic();
~Classic();
void Report() const;
Classic & operator=(const Classic &c);
};
Cd::Cd(const char * s1, const char * s2, int n, double x) : selections(n), playtime(x)
{
performers = new char[strlen(s1)+1];
label = new char[strlen(s2)+1];
strcpy(performers, s1);
strcpy(label, s2);
}
Cd::Cd(const Cd & d) : selections(d.selections), playtime(d.playtime)
{
performers = new char[strlen(d.performers)+1];
label = new char[strlen(d.label)+1];
strcpy(performers, d.performers);
strcpy(label, d.label);
}
Cd::Cd() : selections(0), playtime(0)
{
performers = new char[1];
label = new char[1];
performers[0] = label[0] = '\0';
}
Cd::~Cd()
{
delete[] performers; delete[] label;
}
void Cd::Report() const
{
cout << label << ": " << performers << ", selections: "
<< selections << ", playtime: " << playtime << endl;
}
Cd & Cd::operator=(const Cd & d)
{
selections = d.selections;
playtime = d.playtime;
delete[] performers; delete[] label;
performers = new char[strlen(d.performers)+1];
label = new char[strlen(d.label)+1];
strcpy(performers, d.performers);
strcpy(label, d.label);
return *this;
}
Classic::Classic(const char* s1, const char* s2, const char* s3, int n, double x) :
Cd(s2, s3, n, x)
{
primary = new char[strlen(s1)+1];
strcpy(primary, s1);
}
Classic::Classic(const Classic &c) : Cd(c)
{
primary = new char[strlen(c.primary) + 1];
strcpy(primary, c.primary);
}
Classic::Classic() : Cd()
{
primary = new char[1];
primary[0] = '\0';
}
Classic::~Classic()
{
delete[] primary;
}
void Classic::Report() const
{
cout << primary << ": ";
Cd::Report();
}
Classic & Classic::operator=(const Classic &c)
{
Cd::operator=(c);
delete[] primary;
primary = new char[strlen(c.primary) + 1];
strcpy(primary, c.primary);
return *this;
}
void Bravo(const Cd & disk);
int main()
{
Cd c1("Beatles", "Capitol", 14, 35.5);
Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C",
"Alfred Brendel", "Philips", 2, 57.17);
Cd *pcd = &c1;
cout << "Using object directly:\n";
c1.Report(); // use Cd method
c2.Report(); // use Classic method
cout << "Using type cd * pointer to objects:\n";
pcd->Report(); // use Cd method for cd object
pcd = &c2;
pcd->Report(); // use Classic method for classic object
cout << "Calling a function with a Cd reference argument:\n";
Bravo(c1);
Bravo(c2);
cout << "Testing assignment: ";
Classic copy;
copy = c2;
copy.Report();
return 0;
}
void Bravo(const Cd & disk)
{
disk.Report();
}
|
#include <string>
#include <iostream>
using namespace std;
struct hlist {
int flag;
hlist* ptr_next;
union {
char symb;
hlist *ptr_child;
};
};
hlist* r_make(string &mas, int &start, int &err);
hlist* del_x(hlist *now, char &x, string &output,bool info);
void print_list(hlist *now, string &output);
|
#include "catch/catch.hpp"
#include <vector>
#include <iostream>
using namespace std;
class MDimContainer {
private:
vector<int> dims;
vector<int> data;
vector<int> mult;
int& get_at(const vector<int>& adims)
{
int offset = adims.back();
for (int i = 0; i < dims.size()-1; ++i)
{
offset += adims[i] * mult[i];
}
return *(data.data()+offset);
}
public:
MDimContainer(vector<int> adims)
: dims(move(adims))
{
size_t total_size = 1;
for (auto v : dims) total_size *= v;
data.resize(total_size);
// pre-calculate multipliers
mult.resize(dims.size());
int m = 1;
for (int i=dims.size()-1; i>0; --i)
{
m *= dims[i];
mult[i-1] = m;
}
}
void set(const vector<int>& adims, int v)
{
get_at(adims) = v;
}
int get(const vector<int>& adims)
{
return get_at(adims);
}
};
TEST_CASE("MDimContainer")
{
vector<int> dims = {3,4,2,13};
MDimContainer mvec(dims);
int v = 0;
for (int i=0; i<3; ++i)
{
for (int j=0; j<4; ++j)
{
for (int k=0; k<2; ++k)
{
for (int l=0; l<13; ++l)
{
vector<int> adims{i,j,k,l};
mvec.set(adims, v);
++v;
}
}
}
}
v = 0;
for (int i=0; i<3; ++i)
{
for (int j=0; j<4; ++j)
{
for (int k=0; k<2; ++k)
{
for (int l=0; l<13; ++l)
{
vector<int> adims{i,j,k,l};
REQUIRE( v == mvec.get(adims) );
++v;
}
}
}
}
}
|
#ifndef __JFLIB_UBLAS_MATRIX_INVERSION_OPER_HPP__
#define __JFLIB_UBLAS_MATRIX_INVERSION_OPER_HPP__
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/lu.hpp>
namespace boost { namespace numeric { namespace ublas {
/* Matrix inversion routine.
Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */
template<class T, class L, class A>
bool InvertMatrix(const matrix<T,L,A>& input, ublas::matrix<T,L,A>& inverse) {
typedef matrix<T,L,A> matrix_type;
typedef typename matrix_type::size_type size_type;
typedef permutation_matrix<size_type> pmatrix;
// create a working copy of the input
matrix_type Ai(input);
// create a permutation matrix for the LU-factorization
pmatrix pm(Ai.size1());
// perform LU-factorization
int res = lu_factorize(Ai,pm);
if( res != 0 ) return false;
// create identity matrix of "inverse"
inverse.assign(identity_matrix<T>(Ai.size1()));
// backsubstitute to get the inverse
lu_substitute(Ai, pm, inverse);
return true;
}
}}}
#endif // __JFLIB_UBLAS_MATRIX_INVERSION_OPER_HPP__
|
#pragma once
#include "../dxtk/pch.h"
#include "Messages.h"
#include "../capture/all_inc.h"
class Mouse {
public:
using CURSOR = DirectX::SimpleMath::Vector2; // カーソル座標
struct CLICK {
bool l; // 左クリック
bool r; // 右クリック
bool w; // ホイールクリック
CLICK() {
l = 0;
r = 0;
w = 0;
}
};
using WHEEL = DirectX::SimpleMath::Vector2; // ホイール回転量
private:
static CURSOR cursor; // 現在のマウスカーソル座標
static CURSOR cursor_buf; // 1つ前のcursorの状態
static CURSOR cursor_move; // 1フレーム間のカーソルの移動量
static CURSOR drag_from; // 左、右、ホイールのいずれかがクリックされた瞬間のカーソル座標(ドラッグ用)
static CLICK click_a; // 押されている間ずっと1のクリック情報
static CLICK click_b; // 押されたフレームのみ1のクリック情報
static CLICK click_c; // 離されたフレームのみ1のクリック情報
static CLICK double_click; // ダブルクリックフラグ
static WHEEL wheel; // 1フレーム間に発生したホイール回転量
static bool init_flag;
static void init();
public:
static bool loop();
static inline CURSOR getCursor() { return cursor; }
static inline CURSOR getCursorMove() { return cursor_move; }
static inline CURSOR getDragFrom() { return drag_from; }
static inline CLICK getClickA() { return click_a; }
static inline CLICK getClickB() { return click_b; }
static inline CLICK getClickC() { return click_c; }
static inline CLICK getDoubleClick() { return double_click; }
static inline WHEEL getWheel() { return wheel; }
};
|
#pragma once
#include <iostream>
#include <random>
#include <vector>
struct point
{
int x = 0, y = 0;
};
struct rect
{
point ll, ur;
};
struct plane
{
plane(int width, int height) : points(height, std::vector<bool>(width, false)) {}
int height() const { return static_cast<int>(points.size()); }
int width() const { return points.empty() ? 0 : static_cast<int>(points[0].size()); }
bool has_point(const point& p) const { return points[p.y][p.x]; }
void add_point(const point& p) { points[p.y][p.x] = true; }
std::vector<std::vector<bool>> points;
};
struct point_generator
{
std::mt19937 engine;
std::uniform_int_distribution<> dist;
point_generator(int seed, int min, int max)
: engine(seed)
, dist(min, max)
{}
point generate()
{
auto x = dist(engine);
auto y = dist(engine);
return { x, y };
}
};
int area(const rect& rect)
{
return (std::abs(rect.ll.x - rect.ur.x) + 1) * (std::abs(rect.ll.y - rect.ur.y) + 1);
}
plane readPlane(std::istream& stream)
{
int numColumns, numRows;
stream >> numColumns >> numRows;
plane plane{ numColumns, numRows };
for (int row = 0; row < numRows; ++row)
{
for (int col = 0; col < numColumns; ++col)
{
char b;
stream >> b;
if (b == '0')
plane.add_point({ col, row });
}
}
return plane;
}
void writePlane(std::ostream& stream, const plane& plane)
{
const auto numRows = plane.height();
const auto numColumns = plane.width();
stream << numColumns << ' ' << numRows << '\n';
for (int row = 0; row < numRows; ++row)
{
for (int col = 0; col < numColumns; ++col)
{
if (col != 0)
stream << ' ';
stream << plane.has_point({ col, row }) ? '1' : '0';
}
stream << '\n';
}
}
void generatePoints(plane& plane, int seed, int n)
{
point_generator generator{ seed, 1, plane.width() - 1 };
for (int i = 0; i < n; ++i)
plane.add_point(generator.generate());
}
rect findMaximumEmptyRectangle(const plane& plane)
{
rect bestRect;
int bestArea = 0;
const auto numRows = plane.height();
const auto numColumns = plane.width();
std::vector<int> cachedWidths(numColumns + 1);
std::vector<point> stack;
stack.reserve(numColumns + 1);
for (int row = 0; row < numRows; ++row)
{
for (int col = 0; col < numColumns; ++col)
{
if (plane.has_point({ col, row }))
cachedWidths[col] = 0;
else
++cachedWidths[col];
}
int openWidth = 0;
for (int col = 0; col <= numColumns; ++col)
{
const auto cachedWidth = cachedWidths[col];
if (cachedWidth > openWidth)
{
stack.push_back({ col, openWidth });
openWidth = cachedWidth;
}
else if (cachedWidth < openWidth)
{
bool recStartFound = false;
point recStart;
do
{
recStartFound = true;
recStart = stack.back();
stack.pop_back();
const auto area = openWidth * (col - recStart.x);
if (area > bestArea)
{
bestArea = area;
bestRect = rect{ point{ recStart.x, row }, point{ col - 1, row - openWidth + 1 } };
}
openWidth = recStart.y;
} while (cachedWidth < openWidth);
openWidth = cachedWidth;
if (recStartFound)
stack.push_back(recStart);
}
}
}
return bestRect;
}
|
//
// ArmatureManager.cpp
// Boids
//
// Created by Xin Xu on 10/29/14.
//
//
#include "ArmatureManager.h"
#include "Utils.h"
using namespace cocos2d;
ArmatureManager* ArmatureManager::_instance = nullptr;
ArmatureManager *ArmatureManager::getInstance() {
if( _instance == nullptr ) {
_instance = new ArmatureManager();
}
return _instance;
}
ArmatureManager::ArmatureManager() {
}
void ArmatureManager::loadArmatureData(const std::string& resourceName) {
auto it = _collection.find(resourceName);
if (it != _collection.end()) {
return;
}
std::string atlasFile, jsonFile;
atlasFile = Utils::stringFormat("%s/skeleton.atlas", resourceName.c_str());
jsonFile = Utils::stringFormat("%s/skeleton.json", resourceName.c_str());
// binaryFile = Utils::stringFormat("%s/skeleton.skel", resourceName.c_str());
ArmatureData data;
data._atlasData = spAtlas_createFromFile(atlasFile.c_str(), 0);
spSkeletonJson* json = spSkeletonJson_create(data._atlasData);
json->scale = 1;
data._skeletonData = spSkeletonJson_readSkeletonDataFile(json, jsonFile.c_str());
CCASSERT(data._skeletonData, json->error ? json->error : "Error reading skeleton data file.");
spSkeletonJson_dispose(json);
_collection[resourceName] = data;
}
void ArmatureManager::unloadArmatureData(const std::string& resourceName) {
auto it = _collection.find(resourceName);
if (it != _collection.end()) {
spSkeletonData_dispose(it->second._skeletonData);
spAtlas_dispose(it->second._atlasData);
_collection.erase(it);
}
}
void ArmatureManager::clearArmatureData() {
for( auto pair : _collection ) {
spSkeletonData_dispose( pair.second._skeletonData);
spAtlas_dispose( pair.second._atlasData );
}
_collection.clear();
}
spine::SkeletonAnimation *ArmatureManager::createArmature(const std::string& resourceName) {
auto it = _collection.find(resourceName);
if (it == _collection.end()) {
this->loadArmatureData(resourceName);
it = _collection.find(resourceName);
}
auto data = it->second;
return spine::SkeletonAnimation::createWithData(data._skeletonData);
}
Point ArmatureManager::getBonePosition(spine::SkeletonAnimation *animation, const std::string& boneName) {
auto bone = animation->findBone(boneName);
if (bone) {
Vec2 ret( bone->worldX, bone->worldY );
return PointApplyAffineTransform( ret, animation->getNodeToParentAffineTransform() );
}
return Vec2::ZERO;
}
Point ArmatureManager::getSlotPosition(spine::SkeletonAnimation *animation, const std::string& slotName) {
auto slot = animation->findSlot(slotName);
if (slot) {
return Vec2(slot->bone->worldX, slot->bone->worldY);
}
return Vec2::ZERO;
}
|
/***********************************
* Author: Peter Dorich
* Based off code from OSC by Kenny Noble
* Back-end for send/ recieve data between hub/ valve
************************************/
#include <SPI.h>
#include <RH_RF95.h>
#include <RHReliableDatagram.h>
#include <OSCBundle.h>
/* for feather32u4
#define RFM95_CS 8
#define RFM95_RST 4
#define RFM95_INT 7
*/
/* for m0 */
#define RFM95_CS 8
#define RFM95_RST 4
#define RFM95_INT 3
#define SERVER_ADDRESS 1
#define CLIENT_ADDRESS 2
// Change to 434.0 or other frequency, must match RX's freq!
#define RF95_FREQ 915.0
// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS, RFM95_INT);
RHReliableDatagram manager(rf95, SERVER_ADDRESS);
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
void setup() {
Serial.begin(9600);
if (!manager.init())
Serial.println("init failed");
if (!rf95.setFrequency(RF95_FREQ)) {
Serial.println("setFrequency failed");
while (1);
}
rf95.setTxPower(23, false);
}
bool valve_status = false;
void loop() {
// put your main code here, to run repeatedly:
if (manager.available()) {
uint8_t len = sizeof(buf);
uint8_t from;
memset(buf, '\0', RH_RF95_MAX_MESSAGE_LEN);
if (manager.recvfromAck(buf, &len, &from)) {
OSCBundle bndl;
OSCBundle reply_bndl;
get_OSC_bundle((char*)buf, &bndl);
Serial.print("Received message: ");
Serial.println((char*)buf);
get_OSC_bundle(char*)reply_buf, &reply_bndl);
bndl.send(Serial);
Serial.println("");
}
}
}
|
#include "Message.h"
#include <string.h>
CMessage::CMessage( u32 uType )
: m_uType( uType )
{
}
u32 CMessage::GetType() const
{
return m_uType;
}
void CMessage::Pack( i8* pBuffer )
{
memcpy( pBuffer, &m_uType, sizeof( m_uType ) );
}
|
#include <iostream>
using namespace std;
// bubble sort
int main() {
int arr[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 1};
int buf;
for(int i = 0; i < 10-1; i++) {
for (int j = 0; j < (10 - 1 - i); j++) {
if (arr[j] > arr[j + 1]) {
buf = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = buf;
}
}
}
for(int i = 0; i < 10; i++) {
cout << " " << arr[i];
}
return 0;
}
|
#include <iostream>
#include <functional>
// [] () mutable throw() -> int {}
// [=,&] - capture clause
// [=] / [&]
// [&, x]
// () - parameter list (optional)
// mutable / immutable - optional
// throw() - optional
// -> int: trailing-return-type (optional)
// {} - function body
template <typename T = int>
using fn_ptr = T(*) (T); // <return_type> (*) = <function_name> (<parameter_types>)
// template <typename T>
// using fn_l = [](T a) -> T;
// template <typename T>
// using repeated = [&a](int k, fn_l func) {
// if (k == 0) return;
// func(a);
// repeated(k-1, func);
// }
template <typename T = int>
void map(T arr[], size_t arr_size, fn_ptr<T> func) {
for(size_t i = 0; i < arr_size; ++i) {
arr[i] = func(arr[i]);
}
}
int functionToBind(int x, float& y, const char* text) {
return 1;
}
__attribute_pure__ int square(int i) {
return i * i;
}
constexpr int Fibonacci (int k) {
return (k <= 1) ? k : Fibonacci(k - 1) + Fibonacci(k - 2);
}
int factorial(int x) {
if (x == 0) return 1;
return x * factorial(x - 1);
}
int factorial_TR(int x, int acc) {
if (x == 0) return acc;
return factorial_TR(x - 1, x*acc);
}
int factorial_update(int x) {
return factorial_TR(x, 1);
}
void fn_lazy_1() {
std::cout << "This is an implemented function\n";
}
void fn_lazy_2(); // This is a non-implemented function
int main() {
int lambda = [=]() -> int {
std::cout << "Hello, I'm a lambda function!" << std::endl;
return 0;
}();
int a = 5, b = 4;
std::function<int(int)> square = [&a, b](int value) -> int { return a * b; };
int result = square(5);
std::cout << result << std::endl;
int arr[] = {1, 2, 3, 4, 5, 6, 7};
std::cout << "Before isEven:\n";
for(int i= 0; i < 6; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
map<int>(arr, 6, [](int p) -> int {
return (int)(p % 2 == 0);
});
std::cout << "After isEven:\n";
for(int i= 0; i < 6; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// []() noexcept { throw 5; }();
int x = 0, y = 0;
[&x, b, y] (int number) mutable { x = b + number; y++;} (10);
std::cout << "x = " << x << " y = " << y << std::endl;
// float helper = 4.5;
// auto testBind = std::bind(&functionToBind, 10, std::cref(helper), _3); // &<class_name>::<member_function_name> , this
// testBind(4.4, "lalala");
// auto testBind1 = std::bind(&functionToBind, _3, _1, _2); // &<class_name>::<member_function_name> , this
// pure functions:
// pow, sqrt, abs
const int fib_series = Fibonacci(10);
std::cout << fib_series << std::endl;
fn_lazy_1();
return 0;
}
|
#include <iostream>
using namespace std;
enum Colour { WHITE, BLACK };
//enum PieceType { KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN };
char numberToCharConvertor(int);
void alternate(Colour& c);
int convert(int a);
int convert(char a);
bool canMoveBishop(int fromRank, char fromFile, int toRank, char toFile);
string translateColour(Colour c);
class Piece {
public:
const Colour colour;
const char representation;
virtual ~Piece() = 0; // Makes this an abstract (pure virtual?) class.
//PieceType type{};
string name;
//move checker : can move to square method
virtual void print() {};
protected:
Piece(Colour c, char r) :colour(c), representation(r) {};
};
Piece::~Piece() {};
class King : public Piece {
public:
//const char representation = 'K';
//King(Colour c): colour(c) {};
King(Colour c) :Piece(c, 'K') {};
void print() {
cout << numberToCharConvertor(this->colour) << representation << endl;
}
~King() {};
};
class Queen : public Piece {
public:
Queen(Colour c) :Piece(c, 'Q') {};
void print() {
cout << numberToCharConvertor(this->colour) << representation << endl;
}
~Queen() {};
};
class Rook : public Piece {
public:
Rook(Colour c) :Piece(c, 'R') {};
void print() {
cout << numberToCharConvertor(this->colour) << representation << endl;
}
~Rook() {};
};
class Bishop : public Piece {
public:
Bishop(Colour c) :Piece(c, 'B') {};
void print() {
cout << numberToCharConvertor(this->colour) << representation << endl;
}
~Bishop() {};
};
class Knight : public Piece {
public:
Knight(Colour c) :Piece(c, 'N') {};
void print() {
cout <<numberToCharConvertor(this->colour) << representation << endl;
}
~Knight() {};
};
class Pawn : public Piece {
public:
Pawn(Colour c) :Piece(c, 'P') {};
void print() {
cout << numberToCharConvertor(this->colour) << representation << endl;
}
~Pawn() {};
};
class Square {
public:
//members
int rank;
char file;
Colour colour;
Piece* piece = nullptr;
//constructors
Square() {};
Square(int a, char b, Colour c, Piece* p) :rank(a), file(b), colour(c), piece(p)
{
//cout << "parametrized Square constructor with " << rank << " " << file << " and " << endl;
};
//destructor
~Square() {};
//print funtion
void printSquare()
{
if (!piece)
{
if (colour == WHITE)
{
cout << "|##";
}
else
{
cout << "|__";
}
}
else {
cout << "|" << numberToCharConvertor(piece->colour) << piece->representation;
//cout << "|";
//piece->print();
}
}
//piece related functions
Piece* getPiece()
{
return piece;
}
void setPiece(Piece* p)
{
piece = p;
}
void clearPiece()
{
piece = nullptr;
}
};
class Board {
private:
bool checkRookPath(int fromRank, char fromFile, int toRank, char toFile)
{
if (fromFile < toFile) //moving to the right
{
for (int i = (convert(fromFile)) + 1; i < convert(toFile); ++i)
{
if (board[convert(fromRank)][i].getPiece())
{
cout << "There is a piece in the way!" << endl;
cout << "Invalid move!" << endl;
return false;
}
}
return true;
}
else if (fromFile > toFile) // moving to the left
{
for (int i = (convert(fromFile)) - 1; i > convert(toFile); --i)
{
if (board[convert(fromRank)][i].getPiece())
{
cout << "There is a piece in the way!" << endl;
cout << "Invalid move!" << endl;
return false;
}
}
return true;
}
else if (fromRank > toRank) //moving downwards
{
for (int i = (convert(fromRank)) + 1; i < convert(toRank); ++i)
{
if (board[i][convert(fromFile)].getPiece())
{
cout << "There is a piece in the way!" << endl;
cout << "Invalid move!" << endl;
return false;
}
}
return true;
}
else if (fromRank < toRank) //moving upwards
{
for (int i = fromRank - 1; i > toRank; --i)
{
if (board[i][convert(fromFile)].getPiece())
{
cout << "There is a piece in the way!" << endl;
cout << "Invalid move!" << endl;
return false;
}
}
return true;
}
return false;
}
bool checkBishopPath(int fromRank, char fromFile, int toRank, char toFile)
{
if ((toRank > fromRank) && (toFile > fromFile)) //diagonal to top right
{
for (int i{ 1 }; i < abs(toRank - fromRank); ++i)
{
if (board[(convert(fromRank + i)) ][(convert(fromFile )+ i) ].getPiece())
{
cout << "There is a piece in the way!" << endl;
cout << "Invalid move!" << endl;
return false;
}
}
return true;
}
else if ((toRank > fromRank) && (toFile < fromFile)) //diagonal to top left
{
for (int i{ 1 }; i < abs(toRank - fromRank); ++i)
{
if (board[(convert(fromRank+ i)) ][(convert(fromFile)- i) ].getPiece())
{
cout << "There is a piece in the way!" << endl;
cout << "Invalid move!" << endl;
return false;
}
}
return true;
}
else if ((toRank < fromRank) && (toFile > fromFile)) //diagonal to bottom right
{
for (int i{ 1 }; i < abs(toRank - fromRank); ++i)
{
if (board[(convert(fromRank - i))][(convert(fromFile )+ i)].getPiece())
{
cout << "There is a piece in the way!" << endl;
cout << "Invalid move!" << endl;
return false;
}
}
return true;
}
else if ((toRank < fromRank) && (toFile < fromFile)) //diagonal to bottom left
{
for (int i{ 1 }; i < abs(toRank - fromRank); ++i)
{
if (board[(convert(fromRank - i))][(convert(fromFile )- i)].getPiece())
{
cout << "There is a piece in the way!" << endl;
cout << "Invalid move!" << endl;
return false;
}
}
return true;
}
return false;
}
public:
//8x8 array of squares
Square board[8][8];
//variable that shows both kings are still alive
bool neitherKingIsDead{ true };
//inilialize objects for each piece
Rook bR1 = Rook(BLACK);
Knight bN1 = Knight(BLACK);
Bishop bB1 = Bishop(BLACK);
Queen bQ = Queen(BLACK);
King bK = King(BLACK);
Bishop bB2 = Bishop(BLACK);
Knight bN2 = Knight(BLACK);
Rook bR2 = Rook(BLACK);
Pawn bP1 = Pawn(BLACK);
Pawn bP2 = Pawn(BLACK);
Pawn bP3 = Pawn(BLACK);
Pawn bP4 = Pawn(BLACK);
Pawn bP5 = Pawn(BLACK);
Pawn bP6 = Pawn(BLACK);
Pawn bP7 = Pawn(BLACK);
Pawn bP8 = Pawn(BLACK);
Rook wR1 = Rook(WHITE);
Knight wN1 = Knight(WHITE);
Bishop wB1 = Bishop(WHITE);
Queen wQ = Queen(WHITE);
King wK = King(WHITE);
Bishop wB2 = Bishop(WHITE);
Knight wN2 = Knight(WHITE);
Rook wR2 = Rook(WHITE);
Pawn wP1 = Pawn(WHITE);
Pawn wP2 = Pawn(WHITE);
Pawn wP3 = Pawn(WHITE);
Pawn wP4 = Pawn(WHITE);
Pawn wP5 = Pawn(WHITE);
Pawn wP6 = Pawn(WHITE);
Pawn wP7 = Pawn(WHITE);
Pawn wP8 = Pawn(WHITE);
//constructor that initialized the squares on the board with the correct rank and file
Board()
{
Colour c = WHITE;
board[0][0] = Square(8, 'A', WHITE, &bR1);
board[0][1] = Square(8, 'B', BLACK, &bN1);
board[0][2] = Square(8, 'C', WHITE, &bB1);
board[0][3] = Square(8, 'D', BLACK, &bQ);
board[0][4] = Square(8, 'E', WHITE, &bK);
board[0][5] = Square(8, 'F', BLACK, &bB2);
board[0][6] = Square(8, 'G', WHITE, &bN2);
board[0][7] = Square(8, 'H', BLACK, &bR2);
board[1][0] = Square(7, 'A', BLACK, &bP1);
board[1][1] = Square(7, 'B', WHITE, &bP2);
board[1][2] = Square(7, 'C', BLACK, &bP3);
board[1][3] = Square(7, 'D', WHITE, &bP4);
board[1][4] = Square(7, 'E', BLACK, &bP5);
board[1][5] = Square(7, 'F', WHITE, &bP6);
board[1][6] = Square(7, 'G', BLACK, &bP7);
board[1][7] = Square(7, 'H', WHITE, &bP8);
for (int i{ 2 }; i < 6; ++i)
{
for (int j{ 0 }; j < 8; ++j)
{
board[i][j] = Square(8 - i, (char)j + 65, c, nullptr);
alternate(c);
}
alternate(c);
}
board[6][0] = Square(2, 'A', WHITE, &wP1);
board[6][1] = Square(2, 'B', BLACK, &wP2);
board[6][2] = Square(2, 'C', WHITE, &wP3);
board[6][3] = Square(2, 'D', BLACK, &wP4);
board[6][4] = Square(2, 'E', WHITE, &wP5);
board[6][5] = Square(2, 'F', BLACK, &wP6);
board[6][6] = Square(2, 'G', WHITE, &wP7);
board[6][7] = Square(2, 'H', BLACK, &wP8);
board[7][0] = Square(1, 'A', BLACK, &wR1);
board[7][1] = Square(1, 'B', WHITE, &wN1);
board[7][2] = Square(1, 'C', BLACK, &wB1);
board[7][3] = Square(1, 'D', WHITE, &wQ);
board[7][4] = Square(1, 'E', BLACK, &wK);
board[7][5] = Square(1, 'F', WHITE, &wB2);
board[7][6] = Square(1, 'G', BLACK, &wN2);
board[7][7] = Square(1, 'H', WHITE, &wR2);
};
//print method
void printBoard() {
cout << " |A |B |C |D |E |F |G |H |" << endl;
cout << " _________________________" << endl;
for (int i{ 0 }; i < 8; ++i)
{
cout << 8 - i << " "; //prints a column of ints(rank)
for (int j{ 0 }; j < 8; ++j)
{
board[i][j].printSquare(); //calls the Square print function
}
cout << "|" << endl;
}
cout << " _________________________" << endl;
}
//move method
void move(int fromRank, char fromFile, int toRank, char toFile)
{
Square* fromLocation = &board[convert(fromRank)][convert(fromFile)];
Square* toLocation = &board[convert(toRank)][convert(toFile)];
Piece* fromPiece = fromLocation->getPiece();
Piece* toPiece = toLocation->getPiece();
if (fromLocation == toLocation) //check if staring and ending locations are the same
{
cout << " \nInvalid move - you have chosen to move to the same square!" << endl;
return;
}
if (fromPiece) // check if there is a piece on the starting square
{
//cout << "there is a piece in " << fromRank << fromFile << endl;
if (toPiece) //check if there is a piece in the ending square
{
if (toPiece->colour == fromPiece->colour) //check if the two pieces are the same colour
{
cout << "BUT there is a piece in " << toRank << toFile << " with the same colour" << endl;
cout << fromPiece->colour<<fromPiece->representation << endl;
cout << "You can't attempt that!" << endl;
return;
}
else
{
validateMove(fromRank, fromFile, toRank, toFile);
}
}
else
{
validateMove(fromRank, fromFile, toRank, toFile);
//executeMove(fromRank, fromFile, toRank, toFile);
//board[convert(toRank)][convert(toFile)].setPiece(fromPiece);
//board[convert(fromRank)][convert(fromFile)].clearPiece();
}
}
else
{
cout << "there is NO piece in " << fromRank << fromFile << endl;
}
}
//check if move is valid according to rules
void validateMove(int fromRank, char fromFile, int toRank, char toFile)
{
Piece* fromPiece = (board[convert(fromRank)][convert(fromFile)]).getPiece();
Piece* toPiece = (board[convert(toRank)][convert(toFile)]).getPiece();
switch (fromPiece->representation)
{
case 'K':
{
//check to see if the move is legal according to rules
if ((((fromRank == toRank) && (abs(fromFile - toFile) == 1)) ||
((abs(fromRank - toRank) == 1) && (fromFile == toFile))) ||
((abs(toFile - fromFile) == 1) && (abs(toRank - fromRank) == 1)))
{
cout << "valid vorizontal or vertical or diagonal move by 1 (King)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
executeMove(fromRank, fromFile, toRank, toFile);
}
else {
cout << "INVALID vorizontal or vertical or diagonal move by 1 (King)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
}
break;
}
case 'Q':
{
//check to see if the move is legal according to rules
if ((((fromRank == toRank) && (fromFile != toFile))
|| ((fromRank != toRank) && (fromFile == toFile)))
|| (abs(toRank - fromRank) == abs(toFile - fromFile)))
{
//check if path is clear
if (checkPath(fromRank, fromFile, toRank, toFile))
{
cout << "valid vorizontal or vertical or diagonal move (QUEEN)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
executeMove(fromRank, fromFile, toRank, toFile);
}
}
else {
cout << "INVALID vorizontal or vertical or diagonal move (QUEEN)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
}
break;
}
case 'R':
{
if (((fromRank == toRank) && (fromFile != toFile))
|| ((fromRank != toRank) && (fromFile == toFile)))
{
//check path is clear
if (checkPath(fromRank, fromFile, toRank, toFile))
{
cout << "valid vorizontal or vertical move (ROOK)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
executeMove(fromRank, fromFile, toRank, toFile);
}
}
else {
cout << "INVALID vorizontal or vertical move (ROOK)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
}
break;
}
case 'B':
{
//check to see if the move is legal according to rules
if (abs(toRank - fromRank) == abs(toFile - fromFile))
{
//check for pieces in the way
if (checkPath(fromRank, fromFile, toRank, toFile))
{
cout << "valid diagonal move (BISHOP)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
executeMove(fromRank, fromFile, toRank, toFile);
}
}
else {
cout << "INVALID diagonal move (BISHOP)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
//return false;
}
break;
}
case 'N':
{
//check to see if the move is legal according to rules
if (((abs(toRank - fromRank) == 2) && (abs(toFile - fromFile) == 1))
|| ((abs(toRank - fromRank) == 1) && (abs(toFile - fromFile) == 2)))
{
cout << "Valid L-shaped kNight move" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
executeMove(fromRank, fromFile, toRank, toFile);
}
else {
cout << "INVALID L-shaped kNight move" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
}
break;
}
case 'P': //special movement for pawn
{
//single move forward
if (((toFile == fromFile) && (fromPiece->colour == WHITE) && (toRank == fromRank + 1) && (!toPiece))
|| ((toFile == fromFile) && (fromPiece->colour == BLACK) && (toRank == fromRank - 1) && (!toPiece)))
{
cout << "Valid single move (PAWN)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
executeMove(fromRank, fromFile, toRank, toFile);
}
//double move forward
else if (((toFile == fromFile) && (fromPiece->colour == WHITE) && (toRank == 4) &&
(!toPiece) && ((board[convert(toRank - 1)][convert(toFile)]).getPiece() == nullptr))
||
((toFile == fromFile) && (fromPiece->colour == BLACK) && (toRank == 5) &&
(!toPiece) && ((board[convert(toRank + 1)][convert(toFile)]).getPiece() == nullptr)))
{
cout << "Valid double move (PAWN)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
executeMove(fromRank, fromFile, toRank, toFile);
}
//capture move
else if (((toPiece) && ((toFile == fromFile - 1) || (toFile == fromFile + 1)) &&
(fromPiece->colour == WHITE) && (toRank == fromRank+1))
||
((toPiece) && ((toFile == fromFile - 1) || (toFile == fromFile + 1)) &&
(fromPiece->colour == BLACK) && (toRank == fromRank - 1)))
{
cout << "Valid capture move (PAWN)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
executeMove(fromRank, fromFile, toRank, toFile);
}
//if time permits ENPASANT MOVE goes here//else if ()...
else {
cout << "INVALID move (PAWN)" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
}
break;
}
default:
{
cout << "INVALID selection - representation character not recognized" << endl;
}
}
}
//check to see if path is clear
bool checkPath(int fromRank, char fromFile, int toRank, char toFile)
{
Piece* fromPiece = board[convert(fromRank)][convert(fromFile)].getPiece();
Piece* toPiece = board[convert(toRank)][convert(toFile)].getPiece();
Square* fromLocation = &board[convert(fromRank)][convert(fromFile)];
Square* toLocation = &board[convert(toRank)][convert(toFile)];
switch (fromPiece->representation)
{
case 'Q':
{
//check for type of movement before applying check for pieces in the path
//check for diagonal mocement
if (abs(toRank - fromRank) == abs(toFile - fromFile))
{
return checkBishopPath(fromRank, fromFile, toRank, toFile);
}
//otherwise its vertical / horizontal movement
else {
return checkRookPath(fromRank, fromFile, toRank, toFile);
}
}
case 'R':
{
return checkRookPath(fromRank, fromFile, toRank, toFile);
}
case 'B':
{
return checkBishopPath(fromRank, fromFile, toRank, toFile);
}
case 'P':
{
}
default:
{
}
}
}
//EXECUTE MOVE METHOD AND CHECK IF A KING JUST DIED
void executeMove(int fromRank, char fromFile, int toRank, char toFile)
{
Piece* fromPiece = (board[convert(fromRank)][convert(fromFile)]).getPiece();
Piece* toPiece = (board[convert(toRank)][convert(toFile)]).getPiece();
if (toPiece)
{
if (toPiece->representation == 'K')
{
neitherKingIsDead = false;
cout << "King " << toPiece->colour << toPiece->representation << " is dead!" << endl;
cout << "Game Over!" << endl;
}
}
board[convert(toRank)][convert(toFile)].setPiece(fromPiece);
//board[convert(toRank)][convert(toFile)].setPiece(board[convert(fromRank)][convert(fromFile)].getPiece());
board[convert(fromRank)][convert(fromFile)].clearPiece();
}
};
class Game {
public:
Colour currentPlayer;
Board gameBoard;
//new game - initializes a board
//flag of current player
//while cycle that contains the game
// at the end flips the flag
void startGame()
{
currentPlayer = WHITE;
while (gameBoard.neitherKingIsDead)
{
cout << "\n---------------------------------"<< endl;
cout << endl;
gameBoard.printBoard();
input();
}
}
//input function
void input()
{
int fromRank{};
char fromFile{};
int toRank{};
char toFile{};
//explanation what to do
cout << "\ncurrent player is :" << translateColour(currentPlayer) << endl;
cout << "\nfrom: ";
cin >> fromRank >> fromFile;
cout << " \nto: ";
cin >> toRank >> toFile;
if (fromRank > 0 && fromRank < 9)
{
if (toRank > 0 && toRank < 9)
{
if (fromFile >= 'A' && fromFile <= 'H')
{
if (toFile >= 'A' && toFile <= 'H')
{
//check if the player colour corresponds to the piece colour
Piece* fromPiece = (gameBoard.board[convert(fromRank)][convert(fromFile)]).getPiece();
if(fromPiece)
{
if (fromPiece->colour == this->currentPlayer)
{
gameBoard.move(fromRank, fromFile, toRank, toFile);
alternate(this->currentPlayer);
}
else {
cout << "\nYou're trying to move another player's pieces!" << endl;
cout << "Invalid move" << endl;
}
}
else
{
cout << "in \"From: \" You must choose a square that contains a piece that belongs to you!\nIt appears that you've entered an empty square" << endl;
}
}
else {
cout << "\nPlease make sure that you are typing characters A to H" << endl;
}
}
else {
cout << "\nPlease make sure that you are typing characters A to H" << endl;
}
}
else {
cout << "\nPlease make sure that you are typing integers 1 to 8" << endl;
}
}
else {
cout << "\nPlease make sure that you are typing integers 1 to 8" << endl;
}
}
};
int main() {
Game g;
cout << "********************************************************" << endl;
cout << " Please enter your move in the following pattern: " << endl;
cout << "\t1. Input your staring address into 'From' \n\t2. Use an integer from 1 to 8 for row number A.K.A. 'Rank'\n\t3. Use a CAPITAL LETTER for column A.K.A 'File'\n\tEXAMPLE: \n\tFrom: 2D\n\tTo: 4D\n\t\tor\n\tFrom: 2 D\n\tTo:4 D" << endl;
cout << "********************************************************" << endl;
cout << "Be aware that if you use an illegal move - you wont get a redo\nyou'll lose your turn as in real chess" << endl;
cout << "********************************************************" << endl;
cout << "Notice that the game crashes if you enter a LETTER or OTHER CHARACTER first.\nI cant figure out why, so I'm sorry for the inconvenience. " << endl;
g.startGame();
return 0;
}
//Hvarchashti funkcii
void alternate(Colour& c)
{
if (c == WHITE)
{
c = BLACK;
}
else {
c = WHITE;
}
}
char numberToCharConvertor(int a)
{
if (a == 0) {
return 'w';
}
else {
return 'b';
}
}
int convert(int a)
{
if (a >= 1 && a <= 8)
return 8 - a;
/*switch (a)
{
case 8: return 0;
break;
case 7: return 1;
break;
case 6: return 2;
break;
case 5: return 3;
break;
case 4: return 4;
break;
case 3: return 5;
break;
case 2: return 6;
break;
case 1: return 7;
break;
}*/
}
int convert(char a)
{
switch (a)
{
case 'A': return 0;
break;
case 'B': return 1;
break;
case 'C': return 2;
break;
case 'D': return 3;
break;
case 'E': return 4;
break;
case 'F': return 5;
break;
case 'G': return 6;
break;
case 'H': return 7;
break;
}
}
bool canMoveBishop(int fromRank, char fromFile, int toRank, char toFile)
{
if (abs(toRank - fromRank) == abs(toFile - fromFile)) {
cout << "valid diagonal move" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
return true;
}
else {
cout << "INVALID diagonal move" << endl;
cout << fromRank << fromFile << " to " << toRank << toFile << endl;
return false;
}
/*cout << "from: " << fromRank << fromFile << "to: " << toRank << toFile << endl;
cout << "abs(toRank"<<toRank<<" - fromRank"<<fromRank<<") = " << abs(toRank - fromRank) << endl;
cout << "abs(toFile"<<toFile<<" - fromFile"<<fromFile<<") = " << abs(toFile - fromFile) << endl;
cout << endl;*/
}
string translateColour(Colour c)
{
if (c == 0)
return "WHITE";
if (c == 1)
return "BLACK";
else
return "UNKNOWN";
}
|
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/photo.hpp>
#include <opencv2/imgcodecs.hpp>
#include "algorithms.h"
using namespace cv;
using namespace std;
void img_fusion_to_video(Mat &roi_front, Mat &mask, Rect b_roi, int fusion_type){
VideoCapture vcap;
string input_file("1.mp4");
string output_file("out.mp4");
cout << "Handle for video " << input_file << endl;
if(!vcap.open(input_file)){
cout << "ERROR in open file "<< input_file << endl;
}
long total_frame = vcap.get(CV_CAP_PROP_FRAME_COUNT);
int width = vcap.get(CV_CAP_PROP_FRAME_WIDTH);
int height = vcap.get(CV_CAP_PROP_FRAME_HEIGHT);
double rate=vcap.get(CV_CAP_PROP_FPS);
cout << " Total Frame: " << total_frame << " Width:" << width << " Height: " << height << " Frame Rate:" << rate << endl;
Size videoSize(width, height);
VideoWriter writer;
writer.open(output_file, CV_FOURCC('M','J','P','G'), rate, videoSize);
int frame_id = 0;
Mat img;
while(vcap.read(img)){
cout << "Handle for frame [" << frame_id << "/" << total_frame << "]"<<endl;
Mat new_img = getFusionMat(img, roi_front, mask, b_roi, fusion_type);
writer << new_img;
//imshow("img.jpg", new_img);
//imwrite("img.jpg", new_img);
//return;
frame_id += 1;
}
}
int main (int argc, char **argv)
{
Rect b_roi, f_roi;
b_roi = Rect(800, 150, 100, 100);
f_roi = Rect(160, 40, 150, 150);
char back_name[128] = "mountain.jpg";
char front_name[128] = "moon.jpg";
char blend_name[128] = "moon_mountain.jpg";
Mat back = imread(back_name, CV_LOAD_IMAGE_COLOR);
Mat front = imread(front_name, CV_LOAD_IMAGE_COLOR);
if ( !back.data || !front.data ){
cout << "No Image Data!" << endl;
return 0;
}
//resize the roi of the front img
Mat roi_front;
Rect roi(0, 0, b_roi.width, b_roi.height);
front(f_roi).copyTo(roi_front);
resize(roi_front, roi_front, roi.size());
Mat mask = 255 * Mat::ones( roi_front.rows, roi_front.cols, roi_front.depth() );
Mat new_back = getFusionMat(back, roi_front, mask, b_roi, 0);
//imshow("poisson", new_back);
imwrite(blend_name, new_back);
Rect video_b_roi = Rect(200, 500, 100, 100);
img_fusion_to_video(roi_front, mask, video_b_roi, 0);
waitKey(0);
return 0;
}
|
#include <bits/stdc++.h>
#define MAX 1000001
#define M 1000000007
#define ll long long
#define ld long double
#define ESP 0.0001
using namespace std;
int n, a[5001];
int sign(int x) {
if (x<0) return -1;
else return 1;
}
int DP() {
int dp[n+2][n+2];
for (int i=0;i<=n;i++) dp[n+1][i] = 0;
for (int i=n;i>=1;i--) {
for (int prev = i-1;prev>=0;prev--) {
dp[i][prev] = dp[i+1][prev];
if (!prev || (abs(a[i])>abs(a[prev]) && sign(a[i])!=sign(a[prev]))) dp[i][prev] = max(dp[i][prev], dp[i+1][i] + 1);
}
}
return dp[1][0];
}
int main() {
cin >> n;
for (int i=1;i<=n;i++) cin >> a[i];
cout << DP();
return 0;
}
|
//
// Emulator - Simple C64 emulator
// Copyright (C) 2003-2016 Michael Fink
//
/// \file SoundInterfaceDevice.cpp Sound Interface Device
//
// includes
#include "stdafx.h"
#include "SoundInterfaceDevice.hpp"
using C64::SoundInterfaceDevice;
void SoundInterfaceDevice::SetRegister(BYTE bRegister, BYTE bValue)
{
bRegister;
bValue;
}
BYTE SoundInterfaceDevice::ReadRegister(BYTE bRegister)
{
bRegister;
return 0xFF;
}
|
#ifndef CDATETIMEDIRECTOR_H
#define CDATETIMEDIRECTOR_H
#include "cdatetime.h"
#include "cdatetimebuilder.h"
class CDateTimeDirector
{
public:
CDateTimeDirector(CDateTimeBuilder* builder);
virtual ~CDateTimeDirector() {}
virtual void construct();
protected:
CDateTimeBuilder* mBuilder;
};
#endif // CDATETIMEDIRECTOR_H
|
// ==============================================================
// RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC
// Version: 2013.4
// Copyright (C) 2013 Xilinx Inc. All rights reserved.
//
// ===========================================================
#ifndef _cache_module_HH_
#define _cache_module_HH_
#include "systemc.h"
#include "AESL_pkg.h"
#include "cache_module_buff.h"
namespace ap_rtl {
struct cache_module : public sc_module {
// Port declarations 22
sc_in_clk ap_clk;
sc_in< sc_logic > ap_rst;
sc_in< sc_logic > ap_start;
sc_out< sc_logic > ap_done;
sc_out< sc_logic > ap_idle;
sc_out< sc_logic > ap_ready;
sc_out< sc_logic > a_req_din;
sc_in< sc_logic > a_req_full_n;
sc_out< sc_logic > a_req_write;
sc_in< sc_logic > a_rsp_empty_n;
sc_out< sc_logic > a_rsp_read;
sc_out< sc_lv<32> > a_address;
sc_in< sc_lv<32> > a_datain;
sc_out< sc_lv<32> > a_dataout;
sc_out< sc_lv<32> > a_size;
sc_in< sc_lv<32> > applist_base_addr;
sc_out< sc_lv<32> > outAppID;
sc_out< sc_lv<32> > outHWSW;
sc_out< sc_lv<32> > outStateAddr;
sc_out< sc_lv<32> > outLogAddr;
sc_out< sc_lv<32> > outReadIndex;
sc_in< sc_lv<32> > inAppID;
// Module declarations
cache_module(sc_module_name name);
SC_HAS_PROCESS(cache_module);
~cache_module();
sc_trace_file* mVcdFile;
ofstream mHdltvinHandle;
ofstream mHdltvoutHandle;
cache_module_buff* buff_U;
sc_signal< sc_lv<5> > ap_CS_fsm;
sc_signal< sc_lv<32> > applist_base_addr0data_reg;
sc_signal< sc_logic > applist_base_addr0vld_reg;
sc_signal< sc_logic > applist_base_addr0ack_out;
sc_signal< sc_lv<32> > outAppID1data_reg;
sc_signal< sc_logic > outAppID1vld_reg;
sc_signal< sc_logic > outAppID1vld_in;
sc_signal< sc_logic > outAppID1ack_in;
sc_signal< sc_lv<32> > outHWSW1data_reg;
sc_signal< sc_logic > outHWSW1vld_reg;
sc_signal< sc_logic > outHWSW1vld_in;
sc_signal< sc_logic > outHWSW1ack_in;
sc_signal< sc_lv<32> > outStateAddr1data_reg;
sc_signal< sc_logic > outStateAddr1vld_reg;
sc_signal< sc_logic > outStateAddr1vld_in;
sc_signal< sc_logic > outStateAddr1ack_in;
sc_signal< sc_lv<32> > outLogAddr1data_reg;
sc_signal< sc_logic > outLogAddr1vld_reg;
sc_signal< sc_logic > outLogAddr1vld_in;
sc_signal< sc_logic > outLogAddr1ack_in;
sc_signal< sc_lv<32> > outReadIndex1data_reg;
sc_signal< sc_logic > outReadIndex1vld_reg;
sc_signal< sc_logic > outReadIndex1vld_in;
sc_signal< sc_logic > outReadIndex1ack_in;
sc_signal< sc_lv<32> > inAppID0data_reg;
sc_signal< sc_logic > inAppID0vld_reg;
sc_signal< sc_logic > inAppID0ack_out;
sc_signal< sc_lv<3> > indvar_reg_264;
sc_signal< sc_lv<3> > ap_reg_ppstg_indvar_reg_264_pp0_it1;
sc_signal< sc_logic > ap_reg_ppiten_pp0_it0;
sc_signal< sc_logic > ap_reg_ppiten_pp0_it1;
sc_signal< sc_logic > ap_reg_ppiten_pp0_it2;
sc_signal< sc_logic > ap_reg_ppiten_pp0_it3;
sc_signal< sc_logic > ap_reg_ppiten_pp0_it4;
sc_signal< sc_logic > ap_reg_ppiten_pp0_it5;
sc_signal< sc_lv<1> > exitcond2_reg_738;
sc_signal< sc_lv<1> > ap_reg_ppstg_exitcond2_reg_738_pp0_it5;
sc_signal< bool > ap_sig_bdd_252;
sc_signal< sc_logic > ap_reg_ppiten_pp0_it6;
sc_signal< sc_logic > ap_reg_ppiten_pp0_it7;
sc_signal< sc_lv<3> > ap_reg_ppstg_indvar_reg_264_pp0_it2;
sc_signal< sc_lv<3> > ap_reg_ppstg_indvar_reg_264_pp0_it3;
sc_signal< sc_lv<3> > ap_reg_ppstg_indvar_reg_264_pp0_it4;
sc_signal< sc_lv<3> > ap_reg_ppstg_indvar_reg_264_pp0_it5;
sc_signal< sc_lv<3> > ap_reg_ppstg_indvar_reg_264_pp0_it6;
sc_signal< sc_lv<1> > indvar9_reg_276;
sc_signal< sc_lv<1> > ap_reg_ppstg_indvar9_reg_276_pp1_it1;
sc_signal< sc_logic > ap_reg_ppiten_pp1_it0;
sc_signal< sc_logic > ap_reg_ppiten_pp1_it1;
sc_signal< sc_logic > ap_reg_ppiten_pp1_it2;
sc_signal< sc_logic > ap_reg_ppiten_pp1_it3;
sc_signal< sc_logic > ap_reg_ppiten_pp1_it4;
sc_signal< sc_logic > ap_reg_ppiten_pp1_it5;
sc_signal< sc_lv<1> > ap_reg_ppstg_indvar9_reg_276_pp1_it5;
sc_signal< bool > ap_sig_bdd_284;
sc_signal< sc_logic > ap_reg_ppiten_pp1_it6;
sc_signal< sc_lv<1> > ap_reg_ppstg_indvar9_reg_276_pp1_it2;
sc_signal< sc_lv<1> > ap_reg_ppstg_indvar9_reg_276_pp1_it3;
sc_signal< sc_lv<1> > ap_reg_ppstg_indvar9_reg_276_pp1_it4;
sc_signal< sc_lv<32> > read_index_load4_reg_289;
sc_signal< sc_lv<1> > indvar1_reg_313;
sc_signal< sc_lv<1> > ap_reg_ppstg_indvar1_reg_313_pp2_it1;
sc_signal< sc_logic > ap_reg_ppiten_pp2_it0;
sc_signal< sc_logic > ap_reg_ppiten_pp2_it1;
sc_signal< sc_logic > ap_reg_ppiten_pp2_it2;
sc_signal< sc_logic > ap_reg_ppiten_pp2_it3;
sc_signal< sc_logic > ap_reg_ppiten_pp2_it4;
sc_signal< sc_logic > ap_reg_ppiten_pp2_it5;
sc_signal< sc_lv<1> > ap_reg_ppstg_indvar1_reg_313_pp2_it5;
sc_signal< bool > ap_sig_bdd_314;
sc_signal< sc_logic > ap_reg_ppiten_pp2_it6;
sc_signal< sc_lv<1> > ap_reg_ppstg_indvar1_reg_313_pp2_it2;
sc_signal< sc_lv<1> > ap_reg_ppstg_indvar1_reg_313_pp2_it3;
sc_signal< sc_lv<1> > ap_reg_ppstg_indvar1_reg_313_pp2_it4;
sc_signal< sc_lv<32> > temp_outHWSW2_reg_326;
sc_signal< sc_lv<3> > i_2_reg_416;
sc_signal< sc_lv<32> > reg_432;
sc_signal< sc_lv<3> > buff_addr_gep_fu_208_p3;
sc_signal< sc_lv<3> > buff_addr_reg_714;
sc_signal< sc_lv<33> > tmp_3_cast_fu_445_p1;
sc_signal< sc_lv<33> > tmp_3_cast_reg_719;
sc_signal< sc_lv<5> > i_1_fu_455_p2;
sc_signal< sc_lv<5> > i_1_reg_727;
sc_signal< sc_lv<32> > a_addr_reg_732;
sc_signal< sc_lv<1> > tmp_1_fu_449_p2;
sc_signal< sc_lv<1> > exitcond2_fu_516_p2;
sc_signal< sc_lv<1> > ap_reg_ppstg_exitcond2_reg_738_pp0_it1;
sc_signal< sc_lv<1> > ap_reg_ppstg_exitcond2_reg_738_pp0_it2;
sc_signal< sc_lv<1> > ap_reg_ppstg_exitcond2_reg_738_pp0_it3;
sc_signal< sc_lv<1> > ap_reg_ppstg_exitcond2_reg_738_pp0_it4;
sc_signal< sc_lv<1> > ap_reg_ppstg_exitcond2_reg_738_pp0_it6;
sc_signal< sc_lv<3> > indvar_next_fu_522_p2;
sc_signal< sc_lv<3> > indvar_next_reg_742;
sc_signal< sc_lv<1> > isIter0_fu_528_p2;
sc_signal< sc_lv<1> > isIter0_reg_747;
sc_signal< sc_lv<1> > tmp_9_fu_539_p2;
sc_signal< sc_lv<32> > buff_q0;
sc_signal< sc_lv<32> > hb_cache_0_state_addr_reg_759;
sc_signal< sc_lv<32> > hb_cache_0_log_addr_reg_777;
sc_signal< sc_lv<32> > buff_q1;
sc_signal< sc_lv<32> > temp_outReadIndex_reg_785;
sc_signal< sc_lv<32> > a_addr_1_reg_794;
sc_signal< sc_lv<1> > tmp_s_fu_544_p2;
sc_signal< sc_lv<32> > a_addr_2_reg_803;
sc_signal< sc_lv<1> > tmp_4_fu_568_p2;
sc_signal< sc_lv<1> > tmp_13_fu_610_p2;
sc_signal< sc_lv<1> > tmp_13_reg_815;
sc_signal< sc_lv<1> > tmp_14_fu_615_p2;
sc_signal< sc_lv<1> > tmp_14_reg_819;
sc_signal< sc_lv<1> > tmp_15_fu_621_p2;
sc_signal< sc_lv<1> > tmp_15_reg_823;
sc_signal< sc_lv<32> > a_addr_3_reg_827;
sc_signal< sc_lv<1> > exitcond_fu_647_p2;
sc_signal< sc_lv<1> > exitcond_reg_833;
sc_signal< sc_logic > ap_reg_ppiten_pp3_it0;
sc_signal< sc_logic > ap_reg_ppiten_pp3_it1;
sc_signal< sc_lv<1> > ap_reg_ppstg_exitcond_reg_833_pp3_it1;
sc_signal< sc_lv<3> > i_3_fu_653_p2;
sc_signal< sc_lv<3> > i_3_reg_837;
sc_signal< sc_lv<1> > indvar9_phi_fu_280_p4;
sc_signal< sc_lv<1> > indvar1_phi_fu_317_p4;
sc_signal< bool > ap_sig_bdd_454;
sc_signal< sc_lv<3> > buff_address0;
sc_signal< sc_logic > buff_ce0;
sc_signal< sc_logic > buff_we0;
sc_signal< sc_lv<32> > buff_d0;
sc_signal< sc_lv<3> > buff_address1;
sc_signal< sc_logic > buff_ce1;
sc_signal< sc_lv<5> > i_reg_253;
sc_signal< sc_lv<3> > indvar_phi_fu_268_p4;
sc_signal< sc_lv<32> > read_index_load_reg_301;
sc_signal< sc_lv<32> > temp_outAppID1_reg_338;
sc_signal< sc_lv<32> > temp_outStateAddr_reg_353;
sc_signal< sc_lv<32> > temp_outLogAddr_reg_368;
sc_signal< sc_lv<32> > temp_outHWSW1_reg_383;
sc_signal< sc_lv<32> > temp_outReadIndex1_reg_401;
sc_signal< sc_lv<3> > i_2_phi_fu_420_p8;
sc_signal< sc_lv<64> > tmp_fu_534_p1;
sc_signal< sc_lv<64> > tmp_7_cast_fu_506_p1;
sc_signal< sc_lv<64> > tmp_3_fu_558_p1;
sc_signal< sc_lv<64> > tmp_12_fu_600_p1;
sc_signal< sc_lv<64> > tmp_17_fu_637_p1;
sc_signal< sc_lv<64> > tmp_21_fu_695_p1;
sc_signal< bool > ap_sig_bdd_567;
sc_signal< sc_lv<32> > refresher_read_index_1_fu_144;
sc_signal< sc_lv<32> > tmp_2_fu_439_p2;
sc_signal< sc_lv<9> > p_shl_fu_461_p3;
sc_signal< sc_lv<7> > p_shl1_fu_473_p3;
sc_signal< sc_lv<33> > p_shl1_cast_fu_481_p1;
sc_signal< sc_lv<33> > tmp1_fu_485_p2;
sc_signal< sc_lv<33> > p_shl_cast_fu_469_p1;
sc_signal< sc_lv<33> > tmp_6_fu_490_p2;
sc_signal< sc_lv<31> > tmp_7_fu_496_p4;
sc_signal< sc_lv<30> > tmp_8_fu_549_p4;
sc_signal< sc_lv<26> > tmp_5_fu_573_p1;
sc_signal< sc_lv<32> > tmp2_fu_577_p3;
sc_signal< sc_lv<32> > tmp_10_fu_585_p2;
sc_signal< sc_lv<30> > tmp_11_fu_590_p4;
sc_signal< sc_lv<30> > tmp_16_fu_627_p4;
sc_signal< sc_lv<26> > tmp_18_fu_667_p1;
sc_signal< sc_lv<32> > tmp3_fu_671_p3;
sc_signal< sc_lv<32> > tmp_19_fu_679_p2;
sc_signal< sc_lv<30> > tmp_20_fu_685_p4;
sc_signal< bool > ap_sig_bdd_735;
sc_signal< sc_lv<5> > ap_NS_fsm;
static const sc_logic ap_const_logic_1;
static const sc_logic ap_const_logic_0;
static const sc_lv<5> ap_ST_st1_fsm_0;
static const sc_lv<5> ap_ST_st2_fsm_1;
static const sc_lv<5> ap_ST_st3_fsm_2;
static const sc_lv<5> ap_ST_pp0_stg0_fsm_3;
static const sc_lv<5> ap_ST_st12_fsm_4;
static const sc_lv<5> ap_ST_st13_fsm_5;
static const sc_lv<5> ap_ST_st14_fsm_6;
static const sc_lv<5> ap_ST_st15_fsm_7;
static const sc_lv<5> ap_ST_pp1_stg0_fsm_8;
static const sc_lv<5> ap_ST_st23_fsm_9;
static const sc_lv<5> ap_ST_pp2_stg0_fsm_10;
static const sc_lv<5> ap_ST_st31_fsm_11;
static const sc_lv<5> ap_ST_pp3_stg0_fsm_12;
static const sc_lv<5> ap_ST_pp3_stg1_fsm_13;
static const sc_lv<5> ap_ST_pp3_stg2_fsm_14;
static const sc_lv<5> ap_ST_pp3_stg3_fsm_15;
static const sc_lv<5> ap_ST_pp3_stg4_fsm_16;
static const sc_lv<5> ap_ST_pp3_stg5_fsm_17;
static const sc_lv<5> ap_ST_pp3_stg6_fsm_18;
static const sc_lv<5> ap_ST_st45_fsm_19;
static const sc_lv<5> ap_ST_st46_fsm_20;
static const sc_lv<32> ap_const_lv32_0;
static const sc_lv<1> ap_const_lv1_0;
static const sc_lv<5> ap_const_lv5_0;
static const sc_lv<3> ap_const_lv3_0;
static const sc_lv<1> ap_const_lv1_1;
static const sc_lv<64> ap_const_lv64_0;
static const sc_lv<64> ap_const_lv64_2;
static const sc_lv<64> ap_const_lv64_3;
static const sc_lv<64> ap_const_lv64_4;
static const sc_lv<32> ap_const_lv32_5;
static const sc_lv<32> ap_const_lv32_1;
static const sc_lv<32> ap_const_lv32_8;
static const sc_lv<5> ap_const_lv5_14;
static const sc_lv<5> ap_const_lv5_1;
static const sc_lv<4> ap_const_lv4_0;
static const sc_lv<2> ap_const_lv2_0;
static const sc_lv<32> ap_const_lv32_2;
static const sc_lv<32> ap_const_lv32_20;
static const sc_lv<3> ap_const_lv3_5;
static const sc_lv<3> ap_const_lv3_1;
static const sc_lv<32> ap_const_lv32_1F;
static const sc_lv<6> ap_const_lv6_34;
static const sc_lv<3> ap_const_lv3_4;
// Thread declarations
void thread_ap_clk_no_reset_();
void thread_a_address();
void thread_a_dataout();
void thread_a_req_din();
void thread_a_req_write();
void thread_a_rsp_read();
void thread_a_size();
void thread_ap_done();
void thread_ap_idle();
void thread_ap_ready();
void thread_ap_sig_bdd_252();
void thread_ap_sig_bdd_284();
void thread_ap_sig_bdd_314();
void thread_ap_sig_bdd_454();
void thread_ap_sig_bdd_567();
void thread_ap_sig_bdd_735();
void thread_applist_base_addr0ack_out();
void thread_buff_addr_gep_fu_208_p3();
void thread_buff_address0();
void thread_buff_address1();
void thread_buff_ce0();
void thread_buff_ce1();
void thread_buff_d0();
void thread_buff_we0();
void thread_exitcond2_fu_516_p2();
void thread_exitcond_fu_647_p2();
void thread_i_1_fu_455_p2();
void thread_i_2_phi_fu_420_p8();
void thread_i_3_fu_653_p2();
void thread_inAppID0ack_out();
void thread_indvar1_phi_fu_317_p4();
void thread_indvar9_phi_fu_280_p4();
void thread_indvar_next_fu_522_p2();
void thread_indvar_phi_fu_268_p4();
void thread_isIter0_fu_528_p2();
void thread_outAppID();
void thread_outAppID1ack_in();
void thread_outAppID1vld_in();
void thread_outHWSW();
void thread_outHWSW1ack_in();
void thread_outHWSW1vld_in();
void thread_outLogAddr();
void thread_outLogAddr1ack_in();
void thread_outLogAddr1vld_in();
void thread_outReadIndex();
void thread_outReadIndex1ack_in();
void thread_outReadIndex1vld_in();
void thread_outStateAddr();
void thread_outStateAddr1ack_in();
void thread_outStateAddr1vld_in();
void thread_p_shl1_cast_fu_481_p1();
void thread_p_shl1_fu_473_p3();
void thread_p_shl_cast_fu_469_p1();
void thread_p_shl_fu_461_p3();
void thread_tmp1_fu_485_p2();
void thread_tmp2_fu_577_p3();
void thread_tmp3_fu_671_p3();
void thread_tmp_10_fu_585_p2();
void thread_tmp_11_fu_590_p4();
void thread_tmp_12_fu_600_p1();
void thread_tmp_13_fu_610_p2();
void thread_tmp_14_fu_615_p2();
void thread_tmp_15_fu_621_p2();
void thread_tmp_16_fu_627_p4();
void thread_tmp_17_fu_637_p1();
void thread_tmp_18_fu_667_p1();
void thread_tmp_19_fu_679_p2();
void thread_tmp_1_fu_449_p2();
void thread_tmp_20_fu_685_p4();
void thread_tmp_21_fu_695_p1();
void thread_tmp_2_fu_439_p2();
void thread_tmp_3_cast_fu_445_p1();
void thread_tmp_3_fu_558_p1();
void thread_tmp_4_fu_568_p2();
void thread_tmp_5_fu_573_p1();
void thread_tmp_6_fu_490_p2();
void thread_tmp_7_cast_fu_506_p1();
void thread_tmp_7_fu_496_p4();
void thread_tmp_8_fu_549_p4();
void thread_tmp_9_fu_539_p2();
void thread_tmp_fu_534_p1();
void thread_tmp_s_fu_544_p2();
void thread_ap_NS_fsm();
void thread_hdltv_gen();
};
}
using namespace ap_rtl;
#endif
|
// 问题描述
// 小明对类似于 hello 这种单词非常感兴趣,这种单词可以正好分为四段,第一段由一个或多个辅音字母组成,第二段由一个或多个元音字母组成,第三段由一个或多个辅音字母组成,第四段由一个或多个元音字母组成。
// 给定一个单词,请判断这个单词是否也是这种单词,如果是请输出yes,否则请输出no。
// 元音字母包括 a, e, i, o, u,共五个,其他均为辅音字母。
// 输入格式
// 输入一行,包含一个单词,单词中只包含小写英文字母。
// 输出格式
// 输出答案,或者为yes,或者为no。
// 样例输入
// lanqiao
// 样例输出
// yes
// 样例输入
// world
// no
// #include <bits/stdc++.h>
// using namespace std;
// bool isVowel(char a) {
// return a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u';
// }
// int main() {
// set<char> Vowel;
// set<char> consonant;
// string str;
// int a = 0;
// int b = 0;
// int c = 0;
// int d = 0;
// int p = 0;
// for (int i = 'a'; i <= 'z'; ++ i) {
// if (isVowel(i)) Vowel.insert(i);
// else consonant.insert(i);
// }
// cin >> str;
// while (consonant.find(str[p]) != consonant.end()) {
// a = 1;
// ++ p;
// }
// while (Vowel.find(str[p]) != Vowel.end()) {
// b = 1;
// ++ p;
// }
// while (consonant.find(str[p]) != consonant.end()) {
// c = 1;
// ++ p;
// }
// while (Vowel.find(str[p]) != Vowel.end()) {
// d = 1;
// ++ p;
// }
// if(p == str.length() && a==1 && b==1 && c==1 && d==1) cout<<"yes"<<endl;
// else cout<<"no"<<endl;
// return 0;
// }
#include <bits/stdc++.h>
using namespace std;
bool isVowel(char a) {
return a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u';
}
bool solve(stack<char>& s){
int a = 0;
int b = 0;
int c = 0;
int d = 0;
if (s.empty()) return false;
while (!s.empty() && isVowel(s.top())) {
s.pop();
a = 1;
}
while (!s.empty() && !isVowel(s.top())) {
s.pop();
b = 1;
}
while (!s.empty() && isVowel(s.top())) {
s.pop();
c = 1;
}
while (!s.empty() && !isVowel(s.top())) {
s.pop();
d = 1;
}
if (s.empty() && a == 1 && b == 1 && c == 1 && d == 1) return true;
else return false;
}
int main() {
bool flag = true;
string str;
stack<char> S;
cin >> str;
for (int i = 0; i < str.length(); ++ i) {
S.push(str[i]);
}
flag = solve(S);
if (flag) cout << "yes" << endl;
else cout << "no" << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////
// File: MessageBlock.hpp
// Author: 671643387@qq.com
// Date: 2015年12月29日 上午11:24:45
// Description:
///////////////////////////////////////////////////////////////////////////////
#ifndef UTIL_MESSAGEBLOCK_HPP_
#define UTIL_MESSAGEBLOCK_HPP_
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include <memory.h>
#include <vector>
#include <boost/shared_ptr.hpp>
#include <encpp/Typedef.hpp>
namespace encpp
{
namespace util
{
class DLL_API MessageBlock
{
public:
MessageBlock(const BYTE_t *data, std::size_t len)
: data_(len)
, rpos_(0)
{
memcpy(&data_[0], data, len);
}
const BYTE_t *contents(void) const
{
return &data_[rpos_];
}
std::size_t size(void) const
{
return (data_.size() - rpos_);
}
std::size_t rpos(std::size_t pos)
{
rpos_ += pos;
return rpos_;
}
private:
std::vector<BYTE_t> data_;
std::size_t rpos_;
};
typedef boost::shared_ptr<MessageBlock> MessageBlockPtr;
}
}
#endif /* UTIL_MESSAGEBLOCK_HPP_ */
|
/***************************************************************************
Copyright (c) 2020 Philip Fortier
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
***************************************************************************/
#include "stdafx.h"
#include "Components.h"
#include "RasterOperations.h"
#include "View.h"
#include "ResourceEntity.h"
#include "PaletteOperations.h"
#include "AppState.h"
#include "format.h"
#include "ImageUtil.h"
using namespace std;
int g_debugCelRLE;
uint8_t g_egaPaletteMapping[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
uint8_t g_vgaPaletteMapping[256];
bool IsMirror(uint16_t nLoop, uint16_t mask)
{
return (0 != (((mask) >> (nLoop)) & 1));
}
enum class GNPResult
{
Done = 0, // pColor is not set
NewLine = 1,// pColor is set
Ok = 2, // pColor is set
};
void ReadImageData(sci::istream &byteStream, Cel &cel, bool isVGA)
{
ReadImageData(byteStream, cel, isVGA, byteStream);
}
const size_t ReasonableLimit = 640 * 480;
template<typename _TCalcFunc>
void ReadImageDataWorker(sci::istream &byteStreamRLE, Cel &cel, bool isVGA, sci::istream &byteStreamLiteral, _TCalcFunc calcFunc)
{
uint8_t scratchBuffer[128];
uint8_t *scratchPointer = nullptr;
// For some reason, the bitmap width needs to be rounded up to fit on a DWORD boundary.
int cxActual = CX_ACTUAL(cel.size.cx);
int cxRemainingOnThisLine = cel.size.cx;
int cxLine = cel.size.cx;
int cxPadding = cxActual - cxLine;
// Bitmap buffer:
int cBufferSizeRemaining = cxActual * (int)cel.size.cy;
size_t dataSize = cBufferSizeRemaining;
if (dataSize > ReasonableLimit)
{
throw std::exception("Corrupt raster resource.");
}
// The image starts from the bottom left, not the top left:
int y = cel.size.cy - 1;
int x = 0;
calcFunc(y, byteStreamRLE, byteStreamLiteral);
// Create our buffer
cel.Data.allocate(max(1, dataSize));
int cCount = 0;
int cxRemainingForThisCommand = 0;
while (byteStreamRLE.good() && (cBufferSizeRemaining > 0))
{
uint8_t b;
if (cxRemainingForThisCommand == 0)
{
// Read more data.
byteStreamRLE >> b;
if (!isVGA)
{
uint8_t color = (b & 0x0f);
cCount = ((b & 0xf0) >> 4);
memset(scratchBuffer, color, cCount);
scratchPointer = scratchBuffer;
}
else
{
// VGA has some encoding
cCount = (b & 0x3f);
switch (b >> 6)
{
case 0x01:
// Copy next cCount + 64 bytes as is
cCount += 64;
// fall through...
case 0x00:
// Copy next cCount bytes as is
byteStreamLiteral.read_data(scratchBuffer, cCount);
break;
case 0x02:
uint8_t color;
byteStreamLiteral >> color;
// Set next cCount bytes to color
memset(scratchBuffer, color, cCount);
break;
case 0x03:
// Set next cCount bytes to transparent
memset(scratchBuffer, cel.TransparentColor, cCount);
break;
}
}
scratchPointer = scratchBuffer;
cxRemainingForThisCommand = cCount;
}
assert(y >= 0);
int cAmountToFill;
// Fill up to the end of this command.
if (cxRemainingForThisCommand < cxRemainingOnThisLine)
{
cAmountToFill = cxRemainingForThisCommand;
cxRemainingForThisCommand = 0;
int pos = y * cxActual + x;
memcpy(&cel.Data[pos], scratchPointer, cAmountToFill);
x += cAmountToFill;
cxRemainingOnThisLine -= cAmountToFill;
cBufferSizeRemaining -= cAmountToFill;
scratchPointer += cAmountToFill;
}
else
{
// We are going to fill up to the end of the line, and pad the rest
cAmountToFill = cxLine - x;
memcpy(&cel.Data[y * cxActual + x], scratchBuffer, cAmountToFill);
cBufferSizeRemaining -= cAmountToFill;
// Pad:
//fill_n(cel.Data.begin() + , cxPadding, cel.TransparentColor);
cel.Data.fill((y * cxActual + x + cAmountToFill), cxPadding, cel.TransparentColor);
cBufferSizeRemaining -= cxPadding;
// Move to the next line:
x = 0;
y -= 1;
calcFunc(y, byteStreamRLE, byteStreamLiteral);
cxRemainingForThisCommand = cxRemainingForThisCommand - cxRemainingOnThisLine;
// This hits for Laura Bow 2
// assert(cxRemainingForThisCommand == 0); // If this never hits, it turns out we don't need to support filling across scanlines.
cxRemainingOnThisLine = cel.size.cx;
}
}
}
void CalcNothing(int y, sci::istream &byteStreamRLE, sci::istream &byteStreamLiteral) {}
void ReadImageData(sci::istream &byteStreamRLE, Cel &cel, bool isVGA, sci::istream &byteStreamLiteral)
{
ReadImageDataWorker(byteStreamRLE, cel, isVGA, byteStreamLiteral, CalcNothing);
}
// RLE, followed by Literal
void CalculateSCI2RowOffsets(Cel &cel, sci::istream byteStreamRLE, sci::istream byteStreamLiteral, sci::ostream &byteStreamOffsets)
{
uint32_t orig = byteStreamOffsets.tellp();
uint32_t baseRLE = byteStreamRLE.tellg();
uint32_t baseLiteral = byteStreamLiteral.tellg();
sci::istream byteStreamRLE1 = byteStreamRLE;
sci::istream byteStreamLiteral1 = byteStreamLiteral;
ReadImageDataWorker(byteStreamRLE1, cel, true, byteStreamLiteral1,
[&cel, baseRLE, &byteStreamOffsets](int y, sci::istream &byteStreamRLE, sci::istream &byteStreamLiteral)
{
if (y >= 0)
{
byteStreamOffsets << (byteStreamRLE.tellg() - baseRLE);
}
}
);
sci::istream byteStreamRLE2 = byteStreamRLE;
sci::istream byteStreamLiteral2 = byteStreamLiteral;
ReadImageDataWorker(byteStreamRLE2, cel, true, byteStreamLiteral2,
[&cel, baseLiteral, &byteStreamOffsets](int y, sci::istream &byteStreamRLE, sci::istream &byteStreamLiteral)
{
if (y >= 0)
{
byteStreamOffsets << (byteStreamLiteral.tellg() - baseLiteral);
}
}
);
// Assert we write the correct amount of row offsets.
assert((byteStreamOffsets.tellp() - orig) == (cel.size.cy * 2 * 4));
}
const uint16_t ReasonableCelWidth = 320;
const uint16_t ReasonableCelHeight = 200;
void ReadCelFrom(ResourceEntity &resource, sci::istream byteStream, Cel &cel, bool isVGA)
{
// Width and height
byteStream >> cel.size.cx;
byteStream >> cel.size.cy;
// Ensure the size is reasonable (unsure if this is a real limit), so we don't go
// allocating huge amounts of memory.
if (ClampSize(resource.GetComponent<RasterComponent>(), cel.size))
{
appState->LogInfo("Corrupt view resource: (%d,%d).", resource.ResourceNumber, resource.PackageNumber);
throw std::exception("Invalid cel size.");
}
// x and y placement (right, down)
uint16_t placement;
byteStream >> placement;
cel.placement.x = (char)(placement & 0x00ff);
cel.placement.y = (char)((placement & 0xff00) >> 8);
// Transparent colour
byteStream >> cel.TransparentColor;
// There is one more byte here for VGA
if (isVGA)
{
uint8_t unknown;
byteStream >> unknown;
}
g_debugCelRLE = resource.ResourceNumber;
ReadImageData(byteStream, cel, isVGA);
}
const uint16_t ReasonableCelCount = 128;
void ReadLoopFrom(ResourceEntity &resource, sci::istream byteStream, Loop &loop, bool isVGA)
{
assert(loop.Cels.empty());
uint16_t nCels;
byteStream >> nCels;
bool fZeroCels = (nCels == 0);
if (fZeroCels)
{
nCels = 1;
// Handle corrupt views (e.g. LSL2, view 225, loop 3) by
// creating a dummy loop with 1 1x1 cel
}
if (nCels > ReasonableCelCount)
{
throw std::exception("Too many cels.");
}
loop.Cels.assign(nCels, Cel()); // Just a bunch of empty ones.
byteStream >> loop.UnknownData; // Skip 2 bytes (function unknown) - store just in case
if (fZeroCels)
{
CreateDegenerate(loop.Cels[0], loop.Cels[0].TransparentColor);
}
else
{
for (uint16_t i = 0; i < nCels; i++)
{
uint16_t nOffset;
byteStream >> nOffset;
sci::istream byteStreamCel(byteStream);
byteStreamCel.seekg(nOffset);
ReadCelFrom(resource, byteStreamCel, loop.Cels[i], isVGA);
}
}
assert(loop.Cels.size() == nCels); // Ensure cel count is right.
}
uint8_t GetPixel(const uint8_t *p, int x, int y, int cxActual)
{
return (*((p)+((y)* (cxActual)) + (x)));
}
// The sole purpose of this is to ignore the padding at the end of each scanline.
GNPResult GetNextPixel(const uint8_t *pData, int &x, int &y, int cx, uint8_t *pColor)
{
GNPResult iResult = GNPResult::Ok;
if (x >= cx)
{
x = 0;
y--;
iResult = GNPResult::NewLine;
}
if (y < 0)
{
iResult = GNPResult::Done;
}
if (iResult != GNPResult::Done)
{
*pColor = GetPixel(pData, x, y, CX_ACTUAL(cx));
}
++x;
return iResult;
}
const int ValuableIdenticalColorsThreshold = 2;
// Returns the next pixel color, and how many pixels after that are identical
int GetNextIdenticalPixelCount(const uint8_t *pData, int x, int y, int cx, uint8_t *pColor)
{
int count = 0;
if (GetNextPixel(pData, x, y, cx, pColor) == GNPResult::Ok)
{
count++;
uint8_t temp;
while ((GetNextPixel(pData, x, y, cx, &temp) == GNPResult::Ok) && (*pColor == temp) && (count < 0x3f))
{
count++;
}
}
return count;
}
// Sierra actually handles 127 (63 + 64) here, but SV.exe barfs on it, so limit ourselves to 63.
const int MaxDifferentPixelCount = 63;
// The way this works is:
// - sequences of 2 are allowed in these sequences (since it would end up
// costing the same just to keep going), unless they are immediately
// followed by another sequence of 2.
int GetNextDifferentPixelCount(const uint8_t *pData, int x, int y, int cx, uint8_t transparent)
{
int count = 0;
uint8_t previousColor;
if (GetNextPixel(pData, x, y, cx, &previousColor) == GNPResult::Ok)
{
count++;
uint8_t nextColor;
int identicalColorCount = 1;
int previousIdenticalColorCountSequence = 0;
while ((count < MaxDifferentPixelCount) && (GetNextPixel(pData, x, y, cx, &nextColor) == GNPResult::Ok))
{
count++;
if (nextColor == previousColor)
{
identicalColorCount++;
if ((identicalColorCount >= 3) || (identicalColorCount >= 2 && (previousColor == transparent)))
{
// 3 in a row. Time to bail.
count -= identicalColorCount;
assert(count > 0);
break;
}
// Hmm, this makes it a bit worse. I'm close to the "offical size" with this algorithm
// but not quite.
// The remaining difference might just be in palette size.
/*
if ((identicalColorCount >= 2) && (previousIdenticalColorCountSequence >= 2))
{
// 2 in a row right after 2 in a row. Time to bail.
count -= (identicalColorCount + previousIdenticalColorCountSequence);
assert(count > 0);
break;
}*/
}
else
{
previousIdenticalColorCountSequence = identicalColorCount;
identicalColorCount = 1;
previousColor = nextColor;
}
}
}
return count;
}
// Advances x and y by amount, and returns the color at x and y
void AdvanceXY(const uint8_t *pData, int amount, int &x, int &y, int cx, uint8_t *pColor)
{
assert(y >= 0);
*pColor = GetPixel(pData, x, y, CX_ACTUAL(cx));
int lines = amount / cx;
int columns = amount % cx;
y -= (amount / cx);
x += columns;
if (x >= cx)
{
x %= cx;
y--;
}
assert((y >= 0) || ((y == -1) && (x == 0)));
}
void WriteImageData(sci::ostream &byteStream, const Cel &cel, bool isVGA, bool isEmbeddedView)
{
WriteImageData(byteStream, cel, isVGA, byteStream, !isVGA || isEmbeddedView);
}
void WriteImageData(sci::ostream &rleStream, const Cel &cel, bool isVGA, sci::ostream &literalStream, bool writeZero)
{
// Now the image data
// cxActual is how wide our bitmap data is (a boundary of 4 pixels - 32 bits)
int cxActual = CX_ACTUAL(cel.size.cx);
// Start at the bottom
int y = cel.size.cy - 1;
int x = 0;
uint8_t cCount = 0;
uint8_t cColorPrev = 0xff; // invalid colour value (hmm, but not for VGA)
// For some reason, image data always starts with a 0x00
// REVIEW: With VGA1.1 it definitely does not. Still need to check VGA1.0
// REVIEW: I can not find any circumstance in VGA where the image data starts with a zero. So it should always
// be off for VGA.
if (writeZero)
{
rleStream.WriteByte(0);
}
const uint8_t *bits = &cel.Data[0];
if (isVGA)
{
int count = 1; // Anything but zero
while (count)
{
uint8_t identicalColor;
count = GetNextIdenticalPixelCount(bits, x, y, cel.size.cx, &identicalColor);
if (count > 1)
{
assert(count <= 0x3f);
uint8_t byte = (uint8_t)count;
if (identicalColor == cel.TransparentColor)
{
// Sequence of transparent color
byte |= (0x3 << 6);
rleStream.WriteByte(byte);
}
else
{
// Sequence of identical color
byte |= (0x2 << 6);
rleStream.WriteByte(byte);
literalStream.WriteByte(identicalColor);
}
uint8_t dummy;
AdvanceXY(bits, count, x, y, cel.size.cx, &dummy);
}
else
{
count = GetNextDifferentPixelCount(bits, x, y, cel.size.cx, cel.TransparentColor);
if (count > 0x3f)
{
uint8_t byte = (uint8_t)(count - 64);
byte |= (0x1 << 6);
rleStream.WriteByte(byte);
}
else if (count > 0)
{
rleStream.WriteByte((uint8_t)count);
}
// Now copy over that many bits.
for (int i = 0; i < count; i++)
{
uint8_t color;
AdvanceXY(bits, 1, x, y, cel.size.cx, &color);
literalStream.WriteByte(color);
}
}
}
}
else
{
// EGA
GNPResult result = GetNextPixel(bits, x, y, cel.size.cx, &cColorPrev);
cCount = 1;
uint8_t cColor;
while (result != GNPResult::Done)
{
// Look at the next pixel.
result = GetNextPixel(bits, x, y, cel.size.cx, &cColor);
if ((result == GNPResult::Done) || (result == GNPResult::NewLine) || (cCount == 15) || (cColor != cColorPrev))
{
// (It is not valid to test cColor if iResult is GNP_DONE)
assert((result == GNPResult::Done) || (cColor < 16));
assert(cCount < 16);
// Write out our data
uint8_t b = ((cCount << 4) | cColorPrev);
rleStream.WriteByte(b);
cCount = 0;
}
cColorPrev = cColor;
cCount++;
}
}
}
void WriteCelTo(const ResourceEntity &resource, sci::ostream &byteStream, const Cel &cel, bool isVGA)
{
// Preliminary data (size, placement, transparent colour)
byteStream.WriteWord(cel.size.cx);
byteStream.WriteWord(cel.size.cy);
// Convert to uint8_t before converting to uint16_t, to avoid sign extension problems.
uint16_t wPlacement = (uint8_t)cel.placement.x;
wPlacement |= (((uint16_t)(uint8_t)cel.placement.y) << 8);
byteStream.WriteWord(wPlacement);
byteStream.WriteByte(cel.TransparentColor);
if (isVGA)
{
byteStream.WriteByte(0); // Mystery byte in VGA
}
WriteImageData(byteStream, cel, isVGA, false);
}
void WriteLoopTo(const ResourceEntity &resource, sci::ostream &byteStream, const Loop &loop, bool isVGA)
{
// # of cels
int cCels = (int)loop.Cels.size();
byteStream.WriteWord((uint16_t)cCels);
// 2 unknown bytes
byteStream.WriteWord(loop.UnknownData);
// Cel offsets:
uint16_t wOffsets = 0;
std::vector<uint16_t> rgOffsetsDummy(cCels, 0);
// Stash this address for later;
wOffsets = (uint16_t)byteStream.tellp();
byteStream.WriteBytes((uint8_t*)&rgOffsetsDummy[0], sizeof(uint16_t) * rgOffsetsDummy.size());
for (int i = 0; i < cCels; i++)
{
// Set the offset:
// We need to recalc this each time (Based on iIndex), since the pData
// in the serializer can change (be re-alloced).
uint16_t *pOffsets = (uint16_t*)(byteStream.GetInternalPointer() + wOffsets);
pOffsets[i] = ((uint16_t)(byteStream.tellp()));
WriteCelTo(resource, byteStream, loop.Cels[i], isVGA);
}
}
const uint16_t ReasonableLoopCount = 50;
void ReadPalette(ResourceEntity &resource, sci::istream &stream)
{
// TODO: the palette reading code has a limit (bytes remaining) how to enforce
resource.AddComponent(move(make_unique<PaletteComponent>()));
ReadPalette(resource.GetComponent<PaletteComponent>(), stream);
}
void PostReadProcessing(ResourceEntity &resource, RasterComponent &raster)
{
// Validate the view. Ensure that each loops has some cels, and that mirrors are valid loop numbers.
for (size_t i = 0; i < raster.Loops.size(); i++)
{
Loop &loop = raster.Loops[i];
if (loop.Cels.size() == 0)
{
appState->LogInfo("Empty loop found: view: %d, loop %d.", resource.ResourceNumber, i);
// Make degenerate
loop.Cels.push_back(Cel());
CreateDegenerate(loop.Cels[0], loop.Cels[0].TransparentColor);
}
if (loop.IsMirror && (loop.MirrorOf >= (uint8_t)raster.Loops.size()))
{
throw std::exception("Invalid mirror.");
}
}
}
// Helpers for view resources
// We'll assume resource and package number are already taken care of, because they are common to all.
void ViewReadFromVersioned(ResourceEntity &resource, sci::istream &byteStream, bool isVGA)
{
RasterComponent &raster = resource.GetComponent<RasterComponent>();
uint16_t nLoopCountWord;
uint16_t mirrorMask = 0;
byteStream >> nLoopCountWord;
// Perform some adjustments here. Actually, only the lower 8 bits is used for the loop count.
uint16_t nLoops = nLoopCountWord & 0x00ff;
bool hasPalette = (nLoopCountWord & 0x8000) != 0;
bool isCompressed = (nLoopCountWord & 0x4000) != 0;
if ((nLoops == 0) || nLoops > ReasonableLoopCount)
{
throw std::exception("None, or too many loops - corrupt resource?");
}
raster.Loops.assign(nLoops, Loop()); // Just empty ones for now
byteStream >> mirrorMask;
uint16_t viewVersion;
byteStream >> viewVersion;
uint16_t paletteOffset;
byteStream >> paletteOffset;
if (hasPalette)
{
assert(paletteOffset != 0x100 && "Unimplemented");
sci::istream streamPalette(byteStream);
streamPalette.seekg(paletteOffset);
ReadPalette(resource, streamPalette);
}
std::unique_ptr<uint16_t[]> rgOffsets = std::make_unique<uint16_t[]>(nLoops);
for (uint16_t i = 0; i < nLoops; i++)
{
byteStream >> rgOffsets[i]; // Read offset.
if (!IsMirror(i, mirrorMask))
{
// Make a copy of the stream so we don't lose our position in this one.
sci::istream streamLoop(byteStream);
streamLoop.seekg(rgOffsets[i]);
ReadLoopFrom(resource, streamLoop, raster.Loops[i], isVGA);
}
}
// Now that we got the data from all "originals", repeat again for mirrors.
for (uint16_t iMirror = 0; iMirror < nLoops; iMirror++)
{
if (IsMirror(iMirror, mirrorMask))
{
assert(rgOffsets[iMirror]); // Ensure we read an offset.
// Find out of which "original" it is a mirror.
for (uint16_t iOrig = 0; iOrig < nLoops; iOrig++)
{
if (!IsMirror(iOrig, mirrorMask))
{
if (rgOffsets[iOrig] == rgOffsets[iMirror])
{
MirrorLoopFrom(raster.Loops[iMirror], (uint8_t)iOrig, raster.Loops[iOrig]);
break;
}
}
}
}
}
PostReadProcessing(resource, raster);
}
#include <pshpack1.h>
struct LoopHeader_VGA11
{
uint8_t mirrorInfo;
uint8_t isMirror;
uint8_t celCount;
uint8_t dummy1; // 0xff (typical)
uint32_t dummy2, dummy3; // 0x3fffffff, 0x00000000 (typical)
//KAWA: the above are actually
//uint8_t startCel, endingCel, repeatCount, stepSize;
//uint32_t paletteOffset;
//none of that is used.
uint32_t celOffsetAbsolute;
};
enum Sci32ViewNativeResolution : uint8_t
{
Res_320x200 = 0,
Res_640x480 = 1,
Res_640x400 = 2,
};
struct ViewHeader_VGA11
{
uint16_t headerSize;
uint8_t loopCount;
uint8_t scaleFlags;
uint8_t always1;
uint8_t sci32ScaleRes;
uint16_t totalNumberOfCels; // Number of cels for which there is data (e.g. excludes mirrored loops)
uint32_t paletteOffset;
uint8_t loopHeaderSize;
uint8_t celHeaderSize;
size16 nativeResolution; // In SQ6, at least, these are the screen dimensions (640x480). Interesting.
};
#include <poppack.h>
void ReadCelFromVGA11(sci::istream &byteStream, Cel &cel, bool isPic)
{
CelHeader_VGA11 celHeader;
byteStream >> celHeader;
// Investigation
/*
OutputDebugString(fmt::format("something:{:x}\n", celHeader.perRowOffsets).c_str());
{
sci::istream moo(byteStream);
moo.seekg(celHeader.perRowOffsets);
int count = 20;
while (count && moo.getBytesRemaining() > 0)
{
uint32_t byte;
moo >> byte;
OutputDebugString(fmt::format(" 0x{0:x}", byte).c_str());
count--;
}
OutputDebugString("\n");
}*/
// LB_Dagger, view 86 has zero here. It's corrupted. All others have 0xa
// assert(celHeader.always_0xa == 0xa);
//KAWA: Not True! When setting a Magnifier effect, this HAS to be zero.
//View 2823 in Eco2, which is a magnifier just like LB_Dagger view 86, has this.
//offsetRLE will be non-zero in this case, while offsetLiteral will be zero.
bool hasSplitRLEAndLiteral = (celHeader.always_0xa == 0xa) || (celHeader.always_0xa == 0x8a);
if (hasSplitRLEAndLiteral)
{
assert(celHeader.offsetLiteral && celHeader.offsetRLE);
}
else
{
assert(celHeader.offsetRLE && !celHeader.offsetLiteral);
}
cel.size = celHeader.size;
cel.placement = celHeader.placement;
cel.TransparentColor = celHeader.transparentColor;
// RLE are the encoding "instructions", while Literal is the raw data it reads from
assert(celHeader.offsetRLE != 0);
byteStream.seekg(celHeader.offsetRLE);
if (celHeader.offsetLiteral == 0)
{
/*
// Just copy the bits directly. AFAIK this is only for LB_Dagger views 86, 456 and 527
size_t dataSize = celHeader.size.cx * celHeader.size.cy; // Not sure if padding happens?
cel.Data.allocate(max(1, dataSize));
byteStream.read_data(&cel.Data[0], dataSize);
FlipImageData(&cel.Data[0], celHeader.size.cx, celHeader.size.cy, celHeader.size.cx);
*/
sci::istream stream(byteStream, celHeader.offsetLiteral);
cel.Data.allocate(max(1, CX_ACTUAL(celHeader.size.cx) * celHeader.size.cy));
for (int y = cel.size.cy - 1; y >= 0; y--)
{
int pos = y * CX_ACTUAL(cel.size.cx);
byteStream.read_data(&cel.Data[pos], cel.size.cx);
cel.Data.fill(pos + cel.size.cx, CX_ACTUAL(cel.size.cx) - cel.size.cx, cel.TransparentColor);
}
}
else
{
ReadImageData(byteStream, cel, true, sci::istream(byteStream, celHeader.offsetLiteral));
}
}
void ReadLoopFromVGA(ResourceEntity &resource, sci::istream &byteStream, Loop &loop, int nLoop, uint8_t celHeaderSize, bool isSCI2)
{
g_debugCelRLE = resource.ResourceNumber;
LoopHeader_VGA11 loopHeader;
byteStream >> loopHeader;
if (loopHeader.mirrorInfo == 0xff)
{
// Some games violate this assumption, but it's probably just a bug
// Fails for SQ6, 2292, loop 1. Not much we can do, we'll just mark it as not a mirror. View is corrupt.
// assert(loopHeader.isMirror == 0);
}
else
{
// Some games violate this assumption, but it's probably just a bug
// KQ6, 138, loop 4, it's a mirror of 1
// KQ6, 302, loop 1, it's a mirror of 0
//assert(loopHeader.isMirror == 1);
}
loop.IsMirror = (loopHeader.mirrorInfo != 0xff);
if (loop.IsMirror)
{
loop.MirrorOf = loopHeader.mirrorInfo;
}
if (!loop.IsMirror)
{
loop.Cels.assign(loopHeader.celCount, Cel());
for (uint16_t i = 0; i < loopHeader.celCount; i++)
{
sci::istream streamCel(byteStream);
streamCel.seekg(loopHeader.celOffsetAbsolute + celHeaderSize * i);
ReadCelFromVGA11(streamCel, loop.Cels[i], false);
}
}
}
void ViewWriteToVGA11_2_Helper(const ResourceEntity &resource, sci::ostream &byteStream, std::map<BlobKey, uint32_t> &propertyBag, bool isVGA2)
{
const RasterComponent &raster = resource.GetComponent<RasterComponent>();
// The general format we'll be using is like this:
// [ViewHeader]
// [LoopHeader0 ... LoopHeadern]
// [CelHeader0_0 ... CelHeadern_n]
// [palette]
// [CelRLE0 ... CelRLEn]
// [CelLiteral0 ... CelLiteraln]
// Saving is easier if we first just write to different streams, then combine them.
// Palette is easy
sci::ostream paletteStream;
const PaletteComponent *palette = resource.TryGetComponent<PaletteComponent>();
if (palette)
{
//WritePalette(paletteStream, *palette);
WritePaletteShortForm(paletteStream, *palette);
}
uint32_t paletteSize = paletteStream.GetDataSize();
// Now let's calculate how much space is used up by the headers
uint32_t headersSize = sizeof(ViewHeader_VGA11);
headersSize += raster.LoopCount() * sizeof(LoopHeader_VGA11);
for (const Loop &loop : raster.Loops)
{
if (!loop.IsMirror)
{
headersSize += loop.Cels.size() * sizeof(CelHeader_VGA11);
}
}
// We still can't write the headers because we don't know the image data size, and the
// cel headers contain absolute offsets to the litewral image data, which comes after the
// variable size rle data. We'll need to keep track of the offsets.
vector<vector<CelHeader_VGA11>> prelimCelHeaders;
// Now we write the actual data. In VGA1.1, this is split into two separate sections
sci::ostream celRLEData;
sci::ostream celRawData;
std::unique_ptr<sci::ostream> celRowOffsets = isVGA2 ? std::make_unique<sci::ostream>() : nullptr;
uint16_t celDataCount = 0;
for (int nLoop = 0; nLoop < raster.LoopCount(); nLoop++)
{
const Loop &loop = raster.Loops[nLoop];
if (!loop.IsMirror)
{
vector<CelHeader_VGA11> celHeaders;
for (int nCel = 0; nCel < (int)loop.Cels.size(); nCel++)
{
CelHeader_VGA11 celHeader = {};
celHeader.offsetRLE = celRLEData.tellp();
celHeader.offsetLiteral = celRawData.tellp();
WriteImageData(celRLEData, loop.Cels[nCel], true, celRawData, false);
celHeader.rleCelDataSize = celRLEData.tellp() - celHeader.offsetRLE;
celHeader.totalCelDataSize = (celRawData.tellp() - celHeader.offsetLiteral) + celHeader.rleCelDataSize;
celHeaders.push_back(celHeader);
celDataCount++;
}
prelimCelHeaders.push_back(celHeaders);
}
}
// Now we can write the headers.
ViewHeader_VGA11 header = { 0 };
header.headerSize = (uint16_t)sizeof(ViewHeader_VGA11) - 2; // - 2 because headerSize word is not included.
header.loopCount = (uint8_t)raster.LoopCount();
header.scaleFlags = raster.ScaleFlags;
header.always1 = 1;
header.sci32ScaleRes = 0;
header.totalNumberOfCels = celDataCount;
header.paletteOffset = palette ? headersSize : 0; // We will write this right after the headers.
header.loopHeaderSize = (uint8_t)sizeof(LoopHeader_VGA11);
header.celHeaderSize = (uint8_t)sizeof(CelHeader_VGA11);
header.nativeResolution = NativeResolutionToStoredSize(raster.Resolution);
byteStream << header;
// Now the loop headers
uint32_t celHeaderStart = sizeof(ViewHeader_VGA11) + raster.LoopCount() * sizeof(LoopHeader_VGA11);
uint32_t curCelHeaderOffset = celHeaderStart;
for (const Loop &loop : raster.Loops)
{
LoopHeader_VGA11 loopHeader = { 0 };
loopHeader.celCount = (uint8_t)loop.Cels.size();
loopHeader.mirrorInfo = loop.MirrorOf;
loopHeader.isMirror = loop.IsMirror ? 0x1 : 0x0;
loopHeader.celOffsetAbsolute = curCelHeaderOffset;
loopHeader.dummy1 = 0xff; // Don't know what this is, but this is a typical value.
loopHeader.dummy2 = 0x03ffffff; // Again, a typical value
byteStream << loopHeader;
if (!loop.IsMirror)
{
curCelHeaderOffset += sizeof(CelHeader_VGA11) * loop.Cels.size();
}
}
assert(byteStream.tellp() == celHeaderStart); // Assuming our calculations were correct
std::unique_ptr<sci::ostream> rowOffsetStream;
if (isVGA2)
{
rowOffsetStream = std::make_unique<sci::ostream>();
}
// Now the cel headers
uint32_t rleImageDataBaseOffset = headersSize + paletteSize;
uint32_t literalImageDataBaseOffset = rleImageDataBaseOffset + celRLEData.tellp();
uint32_t rowOffsetOffsetBase = literalImageDataBaseOffset + celRawData.tellp();
int realLoopIndex = 0;
for (const Loop &loop : raster.Loops)
{
if (!loop.IsMirror)
{
for (int i = 0; i < (int)loop.Cels.size(); i++)
{
const Cel &cel = loop.Cels[i];
CelHeader_VGA11 celHeader = prelimCelHeaders[realLoopIndex][i];
celHeader.size = cel.size;
//TODO: THIS WILL FUCK UP MAGNIFIER CELS
//They NEED to be 0x00 here and saved RAW.
celHeader.always_0xa = isVGA2 ? 0x8a : 0xa;
celHeader.placement = cel.placement;
celHeader.transparentColor = cel.TransparentColor;
// SCI2 views contain a section at the end of the view that lists,
// for each row of each cel in the view, the (32-bit) relative offsets in
// the rle data and the literal data where this data begins.
//
// For example, if there were two cels, the data would look like:
// offsetA:[C0_R0_offsetRLE][C0_R1_offsetRLE] ... [C0_Rn_offsetRLE]
// [C0_R0_offsetLiteral][C0_R1_offsetLiteral] ... [C0_Rn_offsetLiteral]
// offsetB:[C1_R0_offsetRLE][C1_R1_offsetRLE] ... [C1_Rn_offsetRLE]
// [C1_R0_offsetLiteral][C1_R1_offsetLiteral] ... [C1_Rn_offsetLiteral]
//
// Cel #0's header's perRowOffset field would point to OffsetA, and Cel#1's would
// point to offsetB
//
// For each cel, therefore, there will this extra (celHeight * 4 * 2) bytes of data.
if (isVGA2)
{
// Read our cel data back so as to calculate offsets to the rows.
sci::istream rleData = sci::istream_from_ostream(celRLEData);
rleData.seekg(celHeader.offsetRLE);
sci::istream literalData = sci::istream_from_ostream(celRawData);
literalData.seekg(celHeader.offsetLiteral);
uint32_t rowOffsetOffset = rowOffsetStream->tellp();
// Terrible hack, copying cel!
Cel celTemp = {};
celTemp.size = cel.size;
celTemp.placement = cel.placement;
celTemp.TransparentColor = cel.TransparentColor;
CalculateSCI2RowOffsets(celTemp, rleData, literalData, *rowOffsetStream);
celHeader.perRowOffsets = rowOffsetOffset + rowOffsetOffsetBase;
}
celHeader.offsetRLE += rleImageDataBaseOffset;
celHeader.offsetLiteral += literalImageDataBaseOffset;
byteStream << celHeader;
}
realLoopIndex++;
}
}
// Now the palette
assert(byteStream.tellp() == headersSize); // Since that's where we said we'll write the palette.
sci::transfer(sci::istream_from_ostream(paletteStream), byteStream, paletteSize);
// Now the image data
assert(rleImageDataBaseOffset == byteStream.tellp()); // Since that's where we said we'll write the image data.
sci::transfer(sci::istream_from_ostream(celRLEData), byteStream, celRLEData.GetDataSize());
assert(literalImageDataBaseOffset == byteStream.tellp());
sci::transfer(sci::istream_from_ostream(celRawData), byteStream, celRawData.GetDataSize());
if (isVGA2)
{
sci::transfer(sci::istream_from_ostream(*rowOffsetStream), byteStream, celRawData.GetDataSize());
}
// Done!
}
void ViewWriteToVGA11(const ResourceEntity &resource, sci::ostream &byteStream, std::map<BlobKey, uint32_t> &propertyBag)
{
ViewWriteToVGA11_2_Helper(resource, byteStream, propertyBag, false);
}
void ViewWriteToVGA2(const ResourceEntity &resource, sci::ostream &byteStream, std::map<BlobKey, uint32_t> &propertyBag)
{
ViewWriteToVGA11_2_Helper(resource, byteStream, propertyBag, true);
}
void ViewReadFromVGA11Helper(ResourceEntity &resource, sci::istream &byteStream, const std::map<BlobKey, uint32_t> &propertyBag, bool isSCI2)
{
RasterComponent &raster = resource.GetComponent<RasterComponent>();
// VGA1.1 is quite different from the other versions.
ViewHeader_VGA11 header;
byteStream >> header;
header.headerSize += 2;
assert(header.headerSize >= 16);
// Nope, it appears to be used to identify views with no image data encoding (just raw). e.g. LB_Dagger, view 86
//assert(header.always1 == 0x1);
raster.Resolution = StoredSizeToNativeResolution(header.nativeResolution);
raster.ScaleFlags = header.scaleFlags;
bool isScaleable = (raster.ScaleFlags != 0x01);
// TODO: Turn these into an exception
assert(header.loopHeaderSize >= sizeof(LoopHeader_VGA11)); // 16
assert(header.celHeaderSize >= sizeof(CelHeader_VGA11)); // 32
//KAWA: Detect SCI1.0 views and drop down a version instead. MAYBE FIND A BETTER DIFFERENCE?
if (header.loopHeaderSize > 32)
{
byteStream.seekg(0);
ViewReadFromVersioned(resource, byteStream, true);
return;
}
// 36 is common in SCI1.1, 52 is common in SCI2. But sometimes we'll see 36 in SCI2.
assert((header.celHeaderSize == 36) || (header.celHeaderSize == 52));
if (header.paletteOffset)
{
sci::istream streamPalette(byteStream);
streamPalette.seekg(header.paletteOffset);
ReadPalette(resource, streamPalette);
}
raster.Loops.assign(header.loopCount, Loop()); // Just empty ones for now
for (int i = 0; i < header.loopCount; i++)
{
sci::istream streamLoop(byteStream);
streamLoop.seekg(header.headerSize + (header.loopHeaderSize * i)); // Start of this loop's data
ReadLoopFromVGA(resource, streamLoop, raster.Loops[i], i, header.celHeaderSize, isSCI2);
}
// Now fill in mirrors. They seem setup a little differently than in earlier versions of views,
// so we aren't re-using code.
for (Loop &loop : raster.Loops)
{
if (loop.IsMirror && (loop.MirrorOf < header.loopCount))
{
assert(loop.Cels.empty());
Loop &origLoop = raster.Loops[loop.MirrorOf];
for (size_t i = 0; i < origLoop.Cels.size(); i++)
{
// Make new empty cels, and for each one, do a "sync mirror state" if the original.
loop.Cels.push_back(Cel());
SyncCelMirrorState(loop.Cels[i], origLoop.Cels[i]);
}
}
}
PostReadProcessing(resource, raster);
}
void ViewReadFromVGA11(ResourceEntity &resource, sci::istream &byteStream, const std::map<BlobKey, uint32_t> &propertyBag)
{
ViewReadFromVGA11Helper(resource, byteStream, propertyBag, false);
}
void ViewReadFromVGA2(ResourceEntity &resource, sci::istream &byteStream, const std::map<BlobKey, uint32_t> &propertyBag)
{
ViewReadFromVGA11Helper(resource, byteStream, propertyBag, true);
}
void ViewReadFromEGA(ResourceEntity &resource, sci::istream &byteStream, const std::map<BlobKey, uint32_t> &propertyBag)
{
ViewReadFromVersioned(resource, byteStream, false);
}
void ViewReadFromVGA(ResourceEntity &resource, sci::istream &byteStream, const std::map<BlobKey, uint32_t> &propertyBag)
{
ViewReadFromVersioned(resource, byteStream, true);
}
void ViewWriteTo(const ResourceEntity &resource, sci::ostream &byteStream, bool isVGA)
{
const RasterComponent &raster = resource.GetComponent<RasterComponent>();
uint16_t cLoops = (uint16_t)raster.Loops.size();
// The wMirrorMask is used only during serialization. Update it now.
uint16_t wMirrorMask = 0;
for (uint16_t i = 0; i < cLoops; i++)
{
if (raster.Loops[i].IsMirror)
{
wMirrorMask |= (1 << i);
}
}
const PaletteComponent *palette = resource.TryGetComponent<PaletteComponent>();
assert(isVGA || (palette == nullptr));
// # of loops
uint16_t loopCountWord = (uint16_t)cLoops;
if (palette)
{
loopCountWord |= 0x8000; // Indicate this has a palette
}
byteStream.WriteWord(loopCountWord);
// Mirror mask:
byteStream.WriteWord((uint16_t)wMirrorMask);
//byteStream.WriteBytes((uint8_t*)&raster.UnknownData, sizeof(raster.UnknownData));
//assert(sizeof(raster.UnknownData) == 4);
byteStream.WriteWord(0); // "version", not sure if this is used
uint32_t paletteOffsetPosition = byteStream.tellp();
byteStream.WriteWord(0); // This is where the palette offset might go.
// Loop offsets:
uint16_t wOffsets = 0;
// Just need to take up some space for the time being.
std::unique_ptr<uint16_t[]> rgOffsetsDummy = std::make_unique<uint16_t[]>(cLoops);
// Stash this address for later;
wOffsets = (uint16_t)(byteStream.tellp());
ZeroMemory(rgOffsetsDummy.get(), sizeof(uint16_t) * cLoops);
byteStream.WriteBytes((uint8_t*)rgOffsetsDummy.get(), sizeof(uint16_t) * cLoops);
// First the unmirrored ones:
for (uint16_t i = 0; i < cLoops; i++)
{
if (!raster.Loops[i].IsMirror)
{
// Set the offset:
// (Recalc this each time, since byteStream.pData can change)
uint16_t *pOffsets = (uint16_t*)(byteStream.GetInternalPointer() + wOffsets);
pOffsets[i] = ((uint16_t)(byteStream.tellp()));
// Check if this is a mirrored loop, and if so, ignore it (write the same offset as
// the one which mirrors it.
WriteLoopTo(resource, byteStream, raster.Loops[i], isVGA); // isVGA: false
}
}
// Then their mirrors:
uint16_t *pOffsets = (uint16_t*)(byteStream.GetInternalPointer() + wOffsets);
for (uint16_t i = 0; i < cLoops; i++)
{
if (raster.Loops[i].IsMirror)
{
// Set the offset - use the same offset of the cel of which we are a mirror.
assert(raster.Loops[i].MirrorOf < cLoops);
pOffsets[i] = pOffsets[raster.Loops[i].MirrorOf];
assert(pOffsets[i]);
// That's it, we're done.
}
}
// Write the palette at the end
if (palette)
{
if (byteStream.tellp() > 0xffff)
{
throw std::exception("View resource is too large");
}
// Write the offset to the palette
*(reinterpret_cast<uint16_t*>(byteStream.GetInternalPointer() + paletteOffsetPosition)) = (uint16_t)byteStream.tellp();
WritePalette(byteStream, *palette);
}
}
void ViewWriteToEGA(const ResourceEntity &resource, sci::ostream &byteStream, std::map<BlobKey, uint32_t> &propertyBag)
{
ViewWriteTo(resource, byteStream, false);
}
void ViewWriteToVGA(const ResourceEntity &resource, sci::ostream &byteStream, std::map<BlobKey, uint32_t> &propertyBag)
{
ViewWriteTo(resource, byteStream, true);
}
RasterTraits viewRasterTraits =
{
RasterCaps::Transparency | RasterCaps::Placement | RasterCaps::Mirror | RasterCaps::Reorder | RasterCaps::Resize | RasterCaps::Animate | RasterCaps::EightBitPlacement,
OriginStyle::BottomCenter,
320,
200,
PaletteType::EGA_Sixteen,
g_egaPaletteMapping,
g_egaColors,
0,
nullptr,
false,
0xf, // EGA white
0x0, // EGA black
};
RasterTraits viewRasterTraitsVGA1 =
{
RasterCaps::Transparency | RasterCaps::Placement | RasterCaps::Mirror | RasterCaps::Reorder | RasterCaps::Resize | RasterCaps::Animate | RasterCaps::EightBitPlacement,
OriginStyle::BottomCenter,
320, // These numbers are arbitrary. They are just used to guard against large corrupt cel sizes causing us to allocate tons of memory.
200, // However, some Sierra games have unusually large cels (e.g. Longbow, view 80, is 193 pixels high)
PaletteType::VGA_256,
g_vgaPaletteMapping,
nullptr, // There is no hard-coded palette for VGA.
0,
nullptr,
false,
0x7, // 7th color...
0x0, // Tends to be black
};
RasterTraits viewRasterTraitsVGA1_1 =
{
RasterCaps::Transparency | RasterCaps::Placement | RasterCaps::Mirror | RasterCaps::Reorder | RasterCaps::Resize | RasterCaps::Animate,
OriginStyle::BottomCenter,
320, // These numbers are arbitrary. They are just used to guard against large corrupt cel sizes causing us to allocate tons of memory.
200, // However, some Sierra games have unusually large cels (e.g. Longbow, view 80, is 193 pixels high)
PaletteType::VGA_256,
g_vgaPaletteMapping,
nullptr, // There is no hard-coded palette for VGA.
0,
nullptr,
true,
0x7, // 7th color...
0x0, // Tends to be black
};
RasterSettings viewRasterSettings =
{
4 // Zoom
};
ResourceTraits viewTraitsEGA =
{
ResourceType::View,
&ViewReadFromEGA,
&ViewWriteToEGA,
&NoValidationFunc,
nullptr
};
ResourceTraits viewTraitsVGA =
{
ResourceType::View,
&ViewReadFromVGA,
&ViewWriteToVGA,
&NoValidationFunc,
nullptr
};
ResourceTraits viewTraitsVGA11 =
{
ResourceType::View,
&ViewReadFromVGA11,
&ViewWriteToVGA11,
&NoValidationFunc,
nullptr
};
ResourceTraits viewTraitsVGA2 =
{
ResourceType::View,
&ViewReadFromVGA2,
&ViewWriteToVGA2,
&NoValidationFunc,
nullptr
};
ResourceEntity *CreateViewResource(SCIVersion version)
{
ResourceTraits *ptraits = &viewTraitsEGA;
if (version.ViewFormat == ViewFormat::VGA1)
{
ptraits = &viewTraitsVGA;
}
else if (version.ViewFormat == ViewFormat::VGA1_1)
{
ptraits = &viewTraitsVGA11;
}
else if (version.ViewFormat == ViewFormat::VGA2)
{
ptraits = &viewTraitsVGA2;
}
RasterTraits *prasterTraits = &viewRasterTraits;
if (version.ViewFormat == ViewFormat::VGA1)
{
prasterTraits = &viewRasterTraitsVGA1;
}
else if (version.ViewFormat == ViewFormat::VGA1_1)
{
prasterTraits = &viewRasterTraitsVGA1_1;
}
else if (version.ViewFormat == ViewFormat::VGA2)
{
prasterTraits = &viewRasterTraitsVGA1_1;
}
std::unique_ptr<ResourceEntity> pResource = std::make_unique<ResourceEntity>(*ptraits);
pResource->AddComponent(move(make_unique<RasterComponent>(*prasterTraits, viewRasterSettings)));
return pResource.release();
}
ResourceEntity *CreateDefaultViewResource(SCIVersion version)
{
std::unique_ptr<ResourceEntity> pResource(CreateViewResource(version));
// Make a view with one loop that has one cel.
RasterComponent &raster = pResource->GetComponent<RasterComponent>();
raster.Resolution = version.DefaultResolution;
Loop loop;
Cel cel;
cel.TransparentColor = 0x3;
loop.Cels.push_back(cel);
raster.Loops.push_back(loop);
::FillEmpty(raster, CelIndex(0, 0), size16(16, 16));
return pResource.release();
}
|
class Solution {
public:
int mySqrt(int x) { // 二分法
int l = 0, r = x, ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2; // 防止溢出
if ((long long)mid * mid <= x) { // 小于和等于,两种情况一起考虑
ans = mid; // 等于的情况
l = mid + 1; // 小于的处理
} else {
r = mid - 1; // 大于的情况
}
}
return ans;
}
};
// 其实本题也可以小于,大于,等于,三种情况分开处理。
// 二分法是重要的方法,比起传统的,一个个试过去的方法,二分法显然高效
|
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <boost/random.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/algorithm/hex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/timer/timer.hpp>
#include <math.h> /* pow */
#include <random>
#include <memory>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <chrono>
#include "Log.hpp"
using namespace std;
class IllegalStateException : public logic_error
{
public:
IllegalStateException(const string & msg) : logic_error(msg) {};
};
class NotImplementedException : public logic_error
{
public:
NotImplementedException(const string & msg) : logic_error(msg) {};
};
class InvalidKeyException : public logic_error
{
public:
InvalidKeyException(const string & msg) : logic_error(msg) {};
};
// using boost::multiprecision:cpp_int - Arbitrary precision integer type.
namespace mp = boost::multiprecision; // reduce the typing a bit later...
using biginteger = boost::multiprecision::cpp_int;
typedef unsigned char byte; // put in global namespace to avoid ambiguity with other byte typedefs
int find_log2_floor(biginteger);
int NumberOfBits(biginteger bi);
/*
* Retruns the number of bytes needed to represent a biginteger
* Notice that due to the sign number of byte can exceed log(value)
*/
size_t bytesCount(biginteger value);
mt19937 get_seeded_random();
mt19937_64 get_seeded_random64();
void gen_random_bytes_vector(vector<byte> &v, const int len, mt19937 random = get_seeded_random());
void copy_byte_vector_to_byte_array(const vector<byte> &source_vector, byte * dest, int beginIndex);
void copy_byte_array_to_byte_vector(const byte* src, int src_len, vector<byte>& target_vector, int beginIndex);
/*
* Converting big integer to a byte array. Array must be allocated already
* Number can be postive or negative - the sign will be preserved in the encoding
* Use byteCount(biginteger) method to calculate the number of bytes needed.
*/
void encodeBigInteger(biginteger value, byte* output, size_t length);
/*
* Decodoing big integer from byte array back to a biginteger object
*/
biginteger decodeBigInteger(byte* input, size_t length);
biginteger convert_hex_to_biginteger(const string & hex);
string hexStr(vector<byte> const & data);
void print_elapsed_ms(std::chrono::time_point<std::chrono::system_clock> start, string message);
std::chrono::time_point<std::chrono::system_clock> scapi_now();
/*
* Returns a random biginteger uniformly distributed in [min, max]
*/
biginteger getRandomInRange(biginteger min, biginteger max, std::mt19937 random);
void print_byte_array(byte * arr, int len, string message);
/**
* Abstract market interface that allow serialization and deserialization from byte array and size
*/
class NetworkSerialized {
public:
virtual int getSerializedSize() = 0;
virtual shared_ptr<byte> toByteArray() = 0;
virtual void initFromByteArray(byte* arr, int size) = 0;
virtual void initFromByteVector(vector<byte> * byteVectorPtr) {
initFromByteArray(&(byteVectorPtr->at(0)), byteVectorPtr->size());
}
};
|
#ifndef __SALESDATA_H__
#define __SALESDATA_H__
#include <string>
#include <iostream>
struct SalesData {
std::string Isbn() const {return book_no;}
SalesData &Combine(const SalesData &);
double AvgPrice() const;
std::string book_no; //ISBN No.
unsigned units_sold = 0; //Sold number
double revenue = 0.0; //Sold total money
};
SalesData Add(const SalesData &, const SalesData &);
std::ostream &print(std::ostream &, const SalesData &);
std::istream &read(std::istream &, SalesData &);
#endif
|
#ifndef __FILE_REALMOD__
#define __FILE_REALMOD__
namespace Common
{
template<typename T>
T realmod(T const &x, T const &m)
{
T y = x % m;
return (y < 0 ? y + m : y);
}
}
#endif
|
//
// main.cpp
// c-data
//
// Created by Lawrence Herman on 3/1/19.
// Copyright © 2019 Lawrence Herman. All rights reserved.
//
//#include <iostream>
//// used this for setw(x) on output
//#include <iomanip>
//// directives for reading and writing files
//#include <fstream>
#include "main.h"
int main(int argc, const char * argv[]) {
using namespace std;
// insert code here...
cout << "Hello, World!\n";
// return 0;
int test = 100;
cout<<"The value of test is "<<test<<"\n";
test = 200;
cout<<"Test "<<sizeof(test)<<"\n";
//endl can replace "\n". sometimes they are different
cout<<"int size = "<<sizeof(int)<<"\n";
cout<<"The size of int is "<<sizeof(int)<<"\n";
cout<<"The size of short is "<<sizeof(short)<<"\n";
cout<<"The size of long is "<<sizeof(long)<<"\n";
cout<<"The size of char is "<<sizeof(char)<<"\n";
cout<<"The size of float is "<<sizeof(float)<<"\n";
cout<<"The size of double is "<<sizeof(double)<<"\n";
cout<<"The size of bool is "<<sizeof(bool)<<"\n";
enum Month {
Jan,
Feb,
March,
April,
};
Month testMonth;
testMonth = Jan;
cout<<"Test"<<std::setw(15)<<"Test2\n";
// - Include the <fstream> library
// - Create a stream (input, output, both)
// - ofstream myfile; (for writing to a file)
// - ifstream myfile; (for reading a file)
// - fstream myfile; (for reading and writing a file)
// - Open the file myfile.open(“filename”);
// - Write or read the file
// - Close the file myfile.close();
ofstream testFile ("cTestFile.txt", ios::app);
if (testFile.is_open()) {
testFile << "\nI am adding a line.\n";
} else cout << "Unable to write to file";
// You can determine that directory inside your program via GetCurrentDirectory(), and change it to something else via SetCurrentDirectory().
testFile.close();
// didnt work check later
int a = 54;
cout << &a << "\n";
int * pointToA = &a;
cout << "pointerToA stores " << pointToA << "\n";
cout << "pointerToA points to " << * pointToA << "\n";
}
|
#ifndef ROSE_ESCAPE_H
#define ROSE_ESCAPE_H
#include <string>
std::string escapeString(const std::string& s);
std::string unescapeString(const std::string& s);
#endif // ROSE_ESCAPE_H
|
#pragma once
#include "IState.h"
#include "LockedState.h"
#include "ClosedState.h"
#include "OpenedState.h"
class StateContext
{
public:
StateContext();
void SetState(IState* state);
void Unlock();
void Open();
void Close();
void Lock();
virtual ~StateContext();
private:
IState* m_State;
};
|
//
// ImagePickerView.cpp
// iPet
//
// Created by KimSteve on 2017. 6. 22..
// Copyright © 2017년 KimSteve. All rights reserved.
//
#include "ImagePickerView.h"
#include "GroupSelectView.h"
#include "../Util/ViewUtil.h"
#include "../Util/OSUtil.h"
#include "../Base/ViewAction.h"
#include "../Base/ShaderNode.h"
#include <2d/CCTweenFunction.h>
#include "ThumbImageView.h"
#include "../Const/SMViewConstValue.h"
#define CELL_SIZE (361)
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#define COLUMN_COUNT (3)
#else
#define COLUMN_COUNT (4)
#endif
#define INCELL_SIZE (s.width/COLUMN_COUNT)
#define SCROLL_MARGIN (100)
#define BOTTOM_PRELOAD (200)
// 기동 속도 향상을 위해 처음 읽는 이미지 갯수
#define INIT_REQ_COUNT (100)
#define ACTION_OPEN (SMViewConstValue::Tag::USER+1)
#define THUMB_SIZE 256
#define TOP_MENU_HEIGHT (SMViewConstValue::Size::TOP_MENU_HEIGHT+SMViewConstValue::Size::getStatusHeight())
// open select view action
class ImagePickerView::OpenSelectAction : public ViewAction::DelayBaseAction
{
public:
CREATE_DELAY_ACTION(OpenSelectAction);
virtual void onStart() override
{
auto scene = (ImagePickerView*)_target;
auto target = scene->_groupSelectView;
_from = target->getPositionY();
if (_show) {
_to = 0;
} else {
_to = -target->getContentSize().height;
}
target->setEnabled(false);
}
virtual void onUpdate(float t) override
{
auto scene = (ImagePickerView*)_target;
auto target = scene->_groupSelectView;
if (_show) {
t = cocos2d::tweenfunc::cubicEaseOut(t);
}
target->setPositionY(ViewUtil::interpolation(_from, _to, t));
}
virtual void onEnd() override
{
auto scene = (ImagePickerView*)_target;
auto target = scene->_groupSelectView;
if (!_show) {
target->removeFromParent();
scene->_groupSelectView = nullptr;
} else {
target->setEnabled(true);
}
}
void show(bool show)
{
_show = show;
if (_show) {
setTimeValue(0.3f, 0);
} else {
setTimeValue(0.2f, 0);
}
}
bool _show;
float _from, _to;
};
static DownloadConfig sThumbDownloadConfig;
ImagePickerView::ImagePickerView() :
_listener(nullptr)
, _groupSelectView(nullptr)
, _openSelectAction(nullptr)
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
, _currentGroupIndex(-1)
#endif
, _bGroupSelectViewOpen(false)
{
}
ImagePickerView::~ImagePickerView()
{
releaseImageFetcher();
CC_SAFE_RELEASE(_openSelectAction);
}
ImagePickerView * ImagePickerView::create()
{
ImagePickerView * view = new (std::nothrow)ImagePickerView();
if (view!=nullptr) {
if (view->init()) {
view->autorelease();
} else {
CC_SAFE_DELETE(view);
}
}
return view;
}
bool ImagePickerView::init()
{
if (!SMView::init()) {
return false;
}
auto s = _director->getWinSize();
setContentSize(s);
sThumbDownloadConfig.setResamplePolicy(DownloadConfig::ResamplePolicy::EXACT_CROP, THUMB_SIZE, THUMB_SIZE);
//sThumbDownloadConfig.setCachePolicy(DownloadConfig::CachePolycy::MEMORY_ONLY);
// tableView init
_tableView = SMTableView::createMultiColumn(SMTableView::Orientation::VERTICAL, COLUMN_COUNT, 0, -BOTTOM_PRELOAD, s.width+4, s.height-TOP_MENU_HEIGHT+4+SCROLL_MARGIN+BOTTOM_PRELOAD);
_tableView->setPreloadPaddingSize(300);
_tableView->setScrollMarginSize(SCROLL_MARGIN, BOTTOM_PRELOAD);
// _tableView->hintFixedCellSize(CELL_SIZE);
_tableView->cellForRowAtIndexPath = CC_CALLBACK_1(ImagePickerView::cellForRowAtIndexPath, this);
_tableView->numberOfRowsInSection = CC_CALLBACK_1(ImagePickerView::numberOfRowsInSection, this);
_tableView->setScissorEnable(true);
addChild(_tableView);;
_groupSelectViewStub = SMView::create();
_groupSelectViewStub->setContentSize(_contentSize);
addChild(_groupSelectViewStub);
_initRequest = false;
if (isAccessPermitted()) {
// access 권한이 있냐?... 그러면 미리 읽어둔다.
_initRequest = true;
_scheduler->performFunctionInCocosThread([&]{
// 지금 말고 다음 프레임에...
initImageFetcher();
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
_fetcher->requestGroupList();
#else
_fetcher->onInit();
#endif
});
}
return true;
}
void ImagePickerView::onEnter()
{
SMView::onEnter();
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
if (!_initRequest) {
_initRequest = true;
initImageFetcher();
_fetcher->requestGroupList();
}
#endif
}
void ImagePickerView::onExit()
{
SMView::onExit();
}
void ImagePickerView::finish()
{
releaseImageFetcher();
ImageDownloader::getInstance().clearCache();
_tableView->stop();
}
void ImagePickerView::setOnImagePickerListener(OnImagePickerListener *l)
{
_listener = l;
}
void ImagePickerView::onGroupSelectButtonClick(SMView *view)
{
auto action = getActionByTag(ACTION_OPEN);
if (!action) {
if (_bGroupSelectViewOpen) {
closeGroupSelectView();
} else {
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
openGroupSelectView();
#else
_fetcher->requestAlbumList();
#endif
}
}
}
void ImagePickerView::onClick(SMView *view)
{
int index = view->getTag();
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
if (index >= 0 && index < (int)_itemInfos.size()) {
auto item = _itemInfos.at(view->getTag());
if (_listener) {
_listener->onImageItemClick(view, item);
}
}
#else
auto item = _fetcher->getImageItemInfo(_currentGroupIndex, index);
if (_listener) {
_listener->onImageItemClick(view, item);
}
#endif
}
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
void ImagePickerView::onGroupSelect(const ImageGroupInfo &groupInfo)
{
closeGroupSelectView();
//if (_currentGroup.key.compare(group.key) != 0) {
if (_currentGroup.seq != groupInfo.seq) {
// 다른 그룹이면 바꾼다.
_itemInfos.clear();
_tableView->reloadData();
_currentGroup = groupInfo;
_fetcher->requestPhotoList(groupInfo, 0, INIT_REQ_COUNT);
if (_listener) {
_listener->onGroupSelect(&groupInfo, false);
}
}
}
// 처음 그룹 정보 가져왔을 때
void ImagePickerView::onImageGroupResult(const std::vector<ImageGroupInfo> &groupInfos)
{
for (auto groupInfo : groupInfos) {
_groupInfos.push_back(groupInfo);
if (groupInfo.isDefault) {
_currentGroup = groupInfo;
_fetcher->requestPhotoList(_currentGroup, 0, INIT_REQ_COUNT);
if (_listener) {
_listener->onGroupSelect(&groupInfo, true);
}
}
}
}
void ImagePickerView::onImageItemResult(const std::vector<ImageItemInfo> &itemInfos)
{
if (itemInfos.empty()) { // 비어있으면 패스~
return;
}
_itemInfos.insert(_itemInfos.end(), itemInfos.begin(), itemInfos.end());
_tableView->updateData();
// 다음꺼 읽어온다
_fetcher->requestPhotoList(_currentGroup, (int)_itemInfos.size(), (int)(_currentGroup.numPhotos-_itemInfos.size()));
}
// thumbnail 다 읽었으면
void ImagePickerView::onImageGroupThumbResult(const std::vector<ImageGroupInfo> &groupInfos)
{
_groupInfos = groupInfos;
if (_groupSelectView) {
_groupSelectView->onImageGroupThumbResult(_groupInfos);
}
}
void ImagePickerView::openGroupSelectView()
{
if (_groupSelectView==nullptr) {
_groupSelectView = GroupSelectView::create(_groupInfos);
_groupSelectView->setOnGroupSelectListener(this);
_groupSelectView->setPositionY(-_groupSelectView->getContentSize().height);
_groupSelectViewStub->addChild(_groupSelectView);
_fetcher->requestGroupThumbnail();
}
auto action = getActionByTag(ACTION_OPEN);
if (action) {
stopAction(action);
}
if (_openSelectAction==nullptr) {
_openSelectAction = OpenSelectAction::create(false);
_openSelectAction->setTag(ACTION_OPEN);
}
_openSelectAction->show(true);
runAction(cocos2d::Sequence::create(_openSelectAction, cocos2d::CallFunc::create([&]{
_bGroupSelectViewOpen = true;
}), NULL));
if (_listener) {
_listener->onGroupSelectViewOpen(true);
}
}
void ImagePickerView::closeGroupSelectView()
{
auto action = getActionByTag(ACTION_OPEN);
if (action) {
stopAction(action);
}
_openSelectAction->show(false);
runAction(cocos2d::Sequence::create(_openSelectAction, cocos2d::CallFunc::create([&]{
_bGroupSelectViewOpen = false;
}), NULL));
if (_listener) {
_listener->onGroupSelectViewOpen(false);
}
}
static const cocos2d::Color3B COLOR_ZERO = cocos2d::Color3B(0, 0, 0);
cocos2d::Node * ImagePickerView::cellForRowAtIndexPath(const IndexPath &indexPath)
{
auto s = cocos2d::Director::getInstance()->getWinSize();
ImagePickerCell * cell=nullptr;
cocos2d::Node * convertView = _tableView->dequeueReusableCellWithIdentifier("PICKER_CELL");
if (convertView!=nullptr) {
cell = (ImagePickerCell*)convertView;
} else {
cell = ImagePickerCell::create(0, 0, 0, INCELL_SIZE+4, INCELL_SIZE+4);
cell->_imageView = SMImageView::create();
cell->addChild(cell->_imageView);
cell->setOnClickListener(this);
cell->_imageView->setContentSize(cocos2d::Size(INCELL_SIZE, INCELL_SIZE));
cell->_imageView->setAnchorPoint(cocos2d::Vec2::ZERO);
cell->_imageView->setPosition(cocos2d::Vec2(2, 2));
// cell->setContentSize(cocos2d::Size(INCELL_SIZE-ShaderNode::DEFAULT_ANTI_ALIAS_WIDTH*2, INCELL_SIZE-ShaderNode::DEFAULT_ANTI_ALIAS_WIDTH*2));
cell->_imageView->setLoadingIconColor(COLOR_ZERO);
cell->_imageView->setOnClickListener(this);
cell->_imageView->setDownloadConfig(sThumbDownloadConfig);
// cell->setAnchorPoint(cocos2d::Vec2::ZERO);
// cell->setPosition(cocos2d::Vec2(ShaderNode::DEFAULT_ANTI_ALIAS_WIDTH, ShaderNode::DEFAULT_ANTI_ALIAS_WIDTH));
// auto bottomLine = SMView::create(0, 0, 0, INCELL_SIZE, 2);
// bottomLine->setBackgroundColor4F(cocos2d::Color4F::BLACK);
// cell->addChild(bottomLine);
}
int index = indexPath.getIndex();
cell->_imageView->setTag(index);
cell->setTag(index);
std::string thumbPath = _itemInfos.at(indexPath.getIndex()).url;
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
cell->_imageView->setNSUrlPathForIOS(thumbPath, _isHighSpeed?true:false);
#elif CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
cell->_imageView->setImageFilePath(thumbPath, true);
#endif
cell->_imageView->setScaleType(SMImageView::ScaleType::CENTER_CROP);
cell->_imageView->setScissorEnable(true);
cell->setScissorEnable(true);
// cell->setBackgroundColor4F(cocos2d::Color4F(1, 0, 0, 0.3f));
// cell->setNSUrlPathForIOS(_itemInfos.at(indexPath.getIndex()).url, _isHighSpeed?true:false);
return cell;
}
int ImagePickerView::numberOfRowsInSection(int section)
{
return (int)_itemInfos.size();
}
#include "AlertView.h"
void ImagePickerView::showAccessDeniedPrompt()
{
// alert view call
AlertView::showConfirm("앨범 접근 권한 없음", "앨범 접근 권한이 필요합니다.", "닫기", "설정하기", [&]{
OSUtil::openDeviceSettings();
}, [&]{
});
}
void ImagePickerView::onAlbumAccessDenied()
{
showAccessDeniedPrompt();
}
#else
void ImagePickerView::onGroupSelect(int groupIndex)
{
closeGroupSelectView();
if (groupIndex >= 0 && _currentGroupIndex != groupIndex) {
// 그룹 교체
_currentGroupIndex = groupIndex;
_currentGroupName = _fetcher->getGroupInfo(groupIndex)->name;
_tableView->reloadData();
if (_listener) {
_listener->onGroupSelect(_currentGroupName, true);
}
}
}
// 최초 진입 시 그룹 정보를 가져왔을 때
void ImagePickerView::onImageFetcherInit(const std::vector<ImageGroupInfo>* groupInfos)
{
if (groupInfos == nullptr || groupInfos->empty()) {
// 아무것도 없다..
return;
}
// 첫번째 그룹 (Camera Roll 선택)
onGroupSelect(0);
}
// 폴더 변경 클릭
void ImagePickerView::onImageGroupResult(const std::vector<ImageGroupInfo>* groupInfos)
{
_scheduler->performFunctionInCocosThread([groupInfos, this]{
if (_groupSelectView == nullptr) {
_groupSelectView = GroupSelectView::create(_fetcher.get());
_groupSelectView->setOnGroupSelectListener(this);
_groupSelectView->setPositionY(-_groupSelectView->getContentSize().height);
_groupSelectViewStub->addChild(_groupSelectView);
}
auto action = getActionByTag(ACTION_OPEN);
if (action) {
stopAction(action);
}
if (_openSelectAction == nullptr) {
_openSelectAction = OpenSelectAction::create(false);
_openSelectAction->setTag(ACTION_OPEN);
}
_openSelectAction->show(true);
runAction(cocos2d::Sequence::create(_openSelectAction, cocos2d::CallFunc::create([&]{
_bGroupSelectViewOpen = true;
}), NULL));
if (_listener) {
_listener->onGroupSelectViewOpen(true);
}
});
}
void ImagePickerView::openGroupSelectView()
{
// if (_groupSelectView==nullptr) {
// _groupSelectView = GroupSelectView::create(_groups);
// _groupSelectView->setOnGroupSelectListener(this);
// _groupSelectView->setPositionY(-_groupSelectView->getContentSize().height);
// _groupSelectViewStub->addChild(_groupSelectView);
// _fetcher->requestGroupThumbnail();
// }
//
// auto action = getActionByTag(ACTION_OPEN);
// if (action) {
// stopAction(action);
// }
//
// if (_openSelectAction==nullptr) {
// _openSelectAction = OpenSelectAction::create(false);
// _openSelectAction->setTag(ACTION_OPEN);
// }
//
// _openSelectAction->show(true);
// runAction(cocos2d::Sequence::create(_openSelectAction, cocos2d::CallFunc::create([&]{
// _bGroupSelectViewOpen = true;
// }), NULL));
//
// _bGroupSelectViewOpen = true;
//
// if (_listener) {
// _listener->onGroupSelectViewOpen(true);
// }
}
void ImagePickerView::closeGroupSelectView()
{
if (_groupSelectView) {
auto action = getActionByTag(ACTION_OPEN);
if (action) {
stopAction(action);
}
_openSelectAction->show(false);
runAction(cocos2d::Sequence::create(_openSelectAction, cocos2d::CallFunc::create([&]{
_bGroupSelectViewOpen = false;
}), NULL));
if (_listener) {
_listener->onGroupSelectViewOpen(false);
}
}
}
static const cocos2d::Color3B COLOR_ZERO = cocos2d::Color3B(0, 0, 0);
cocos2d::Node * ImagePickerView::cellForRowAtIndexPath(const IndexPath &indexPath)
{
auto s = cocos2d::Director::getInstance()->getWinSize();
ImagePickerCell * cell=nullptr;
cocos2d::Node * convertView = _tableView->dequeueReusableCellWithIdentifier("PICKER_CELL");
if (convertView!=nullptr) {
cell = (ImagePickerCell*)convertView;
} else {
cell = ImagePickerCell::create(0, 0, 0, INCELL_SIZE+4, INCELL_SIZE+4);
cell->_imageView = SMImageView::create();
cell->addChild(cell->_imageView);
cell->setOnClickListener(this);
cell->_imageView->setContentSize(cocos2d::Size(INCELL_SIZE, INCELL_SIZE));
cell->_imageView->setAnchorPoint(cocos2d::Vec2::ZERO);
cell->_imageView->setPosition(cocos2d::Vec2(2, 2));
// cell->setContentSize(cocos2d::Size(INCELL_SIZE-ShaderNode::DEFAULT_ANTI_ALIAS_WIDTH*2, INCELL_SIZE-ShaderNode::DEFAULT_ANTI_ALIAS_WIDTH*2));
cell->_imageView->setLoadingIconColor(COLOR_ZERO);
cell->_imageView->setOnClickListener(this);
cell->_imageView->setDownloadConfig(sThumbDownloadConfig);
// cell->setAnchorPoint(cocos2d::Vec2::ZERO);
// cell->setPosition(cocos2d::Vec2(ShaderNode::DEFAULT_ANTI_ALIAS_WIDTH, ShaderNode::DEFAULT_ANTI_ALIAS_WIDTH));
// auto bottomLine = SMView::create(0, 0, 0, INCELL_SIZE, 2);
// bottomLine->setBackgroundColor4F(cocos2d::Color4F::BLACK);
// cell->addChild(bottomLine);
}
int index = indexPath.getIndex();
cell->_imageView->setTag(index);
cell->setTag(index);
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
auto phAssetObject = _fetcher->fetchPhotoAssetObject(_currentGroupIndex, indexPath.getIndex());
cell->_imageView->setPHAssetObject(phAssetObject, true);
#elif CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
auto itemInfo = _fetcher->getImageItemInfo(_currentGroupIndex, indexPath.getIndex());
std::string thumbPath = itemInfo.url;
cell->_imageView->setImageFilePath(thumbPath, true);
#endif
cell->_imageView->setScaleType(SMImageView::ScaleType::CENTER_CROP);
cell->_imageView->setScissorEnable(true);
cell->setScissorEnable(true);
// cell->setBackgroundColor4F(cocos2d::Color4F(1, 0, 0, 0.3f));
// cell->setNSUrlPathForIOS(_itemInfos.at(indexPath.getIndex()).url, _isHighSpeed?true:false);
return cell;
}
int ImagePickerView::numberOfRowsInSection(int section)
{
// return (int)_itemInfos.size();
if (_currentGroupIndex >= 0) {
return _fetcher->getGroupInfo(_currentGroupIndex)->numPhotos;
}
return 0;
}
#include "AlertView.h"
void ImagePickerView::showAccessDeniedPrompt()
{
AlertView::showConfirm("앨범 접근 권한 없음", "앨범 접근 권한이 필요합니다.", "닫기", "설정하기", [&]{
OSUtil::openDeviceSettings();
}, [&]{
});
}
void ImagePickerView::onAlbumAccessDenied()
{
showAccessDeniedPrompt();
}
void ImagePickerView::onAlbumAccessAuthorized()
{
}
#endif
|
/*************************************************************
* > File Name : P2672.cpp
* > Author : Tony
* > Created Time : 2019/05/26 15:03:05
* > Algorithm : 贪心
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 100010;
struct Node {
int s, a;
} node[maxn];
bool cmp(Node a, Node b) {
return a.a > b.a;
}
int n, sum[maxn], maxs[maxn], max2spa[maxn];
int main() {
n = read();
for (int i = 1; i <= n; ++i) node[i].s = read();
for (int i = 1; i <= n; ++i) node[i].a = read();
sort(node + 1, node + 1 + n, cmp);
for (int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + node[i].a;
for (int i = 1; i <= n; ++i) maxs[i] = max(maxs[i - 1], node[i].s);
for (int i = n; i >= 1; --i) max2spa[i] = max(max2spa[i + 1], node[i].s * 2 + node[i].a);
for (int i = 1; i <= n; ++i) printf("%d\n", max(sum[i] + 2 * maxs[i], sum[i - 1] + max2spa[i]));
return 0;
}
|
//Jason Strange
//PrintItem inherits from item and is used for storing the item to be printed
#pragma once
#include "Item.h"
#include <string>
using namespace std;
class Item;
class PrintItem : public Item {
private:
string f;
public:
PrintItem (string file);
string getfile ();
};
|
#include <math.h> // only for pow
#include <iostream>
using namespace std;
void toBinary(int *&array,int &size, int n){
// convert decimal to bin
int number = n;
size=0;
while(n/2 >0) {n=n/2; size++;}
size++;
array = new int [size];
for(int i=0; i < size; i++) {array[i] = number %2; number= number/2;}
}
int toDecimal(int *array, int size){
// from binary to decimal
int sum=0;
for(int i=0; i < size; i++) sum=sum + pow(2,i)*array[size-i-1];
return sum;
}
class BinaryNum
{
private:
int* binNum; //integer array to save binary number
int noOfBits; //total no. of bits
public:
//*modified
BinaryNum(){binNum=0; noOfBits=0;}
BinaryNum(const char *str){
int lenth=0;
noOfBits=0;
while(*(str+lenth++)) noOfBits++;
binNum = new int [noOfBits];
//cout << noOfBits << "---------------\n";
for(int i=0; i < noOfBits; i++) binNum[i] = str[noOfBits-i-1]-'0';
}
//------------------- get number of bits
int getNumberOfBits() {return noOfBits;}
int * getBinaryNo() {return binNum;}
BinaryNum operator + (const BinaryNum & obj){
int sum = toDecimal(obj.binNum,obj.noOfBits)+toDecimal(this->binNum,this->noOfBits);
cout << toDecimal(obj.binNum,obj.noOfBits) << endl;
cout << toDecimal(this->binNum,this->noOfBits) << endl;
//cout << "*************** sum ***** " << sum << endl;
BinaryNum temp;
toBinary(temp.binNum, temp.noOfBits,sum);
return temp;
}
//---------------------------------- - operator
BinaryNum operator - (BinaryNum &rhs){
int result = toDecimal(this->binNum,this->noOfBits) - toDecimal(rhs.binNum,rhs.noOfBits);
if(result < 0){
result = result*-1; // making positve to avoid erro
}
BinaryNum temp;
toBinary(temp.binNum,temp.noOfBits,result);
return temp;
}
/*
BinaryNum operator + (const BinaryNum & obj){
BinaryNum *temp = new BinaryNum;
//BinaryNum temp = new BinaryNum;
int max = (this->noOfBits > obj.noOfBits)? this->noOfBits : obj.noOfBits;
temp->binNum= new int [max + 1];
//temp.binNum= new int [noOfBits+1];
int carry =0;
int index =0;
int result;
while(index < this->noOfBits && index < obj.noOfBits){
result = this->binNum[index] + obj.binNum[index]+carry;
if(result ==3){
carry =1;
result =1;
}
else if (result == 2){carry=1; result = 0;}
else{
carry=0;
}
//cout << "*"<< result;
temp->binNum[index] = result;
index++;
//cout << result << "#";
}
//cout<< index << "*************";
if(this->noOfBits > obj.noOfBits){
for(int i=index; i< this->noOfBits; i++){
result = this->binNum[i]+carry;
if(result == 3){carry=1; result = 1;}
else if(result ==2){carry=1; result=0;}
else{carry=0;}
temp->binNum[index++] = result;
// cout << "*"<< result;
}
}
else{
//cout << "#############################3";
for(int i=index; i< obj.noOfBits; i++){
result = obj.binNum[i]+carry;
// cout << result;
if(result == 3){carry=1; result = 1;}
else if(result ==2){carry=1; result=0;}
else{carry=0;}
temp->binNum[index++] = result;
//cout << result;
}
}
if(carry==1){temp->binNum[index++]=1;temp->noOfBits=index;}
else{temp->noOfBits = index;}
//if(carry ==1) {temp->binNum[index]=1;temp->noOfBits=index;}
//else{temp->noOfBits=index-1;}
//int *inverted = new int [index];
//for(int i=0; i < temp->noOfBits; i++) inverted[i]=temp->binNum[temp->noOfBits-i-1];
//delete []temp->binNum;
//temp->binNum = inverted;
// delete []this->binNum;
//cout << "----------" << temp->noOfBits << endl;
return *temp;
}
*/
//------------------------------------ = operator
int &operator [](int val){
if(this->noOfBits > val)
return this->binNum[val];
else if(this->noOfBits == val){
int *temp = new int [this->noOfBits+1];
for(int i=0; i< this->noOfBits; i++) temp[i]=this->binNum[i];
delete []this->binNum;
this->binNum=temp;
this->noOfBits=this->noOfBits+1;
return this->binNum[val];
}
else {return this->binNum[0];}
}
//----------------------------------- A - B
/*
BinaryNum operator - (const BinaryNum &rhs){
BinaryNum temp;
// first take 2's complement and then add
int result =0, carry=0, index=0;
if(this->noOfBits > rhs.noOfBits){
temp.binNum = new int [this->noOfBits];
while(index < this->noOfBits && index < rhs.noOfBits){
if(this->binNum[index]==0){
result = carry + this->binNum[index]-rhs.binNum[index];
}
else{
result = this->binNum[index]-rhs.binNum[index];
carry=0;
}
if(result == -1){carry =1; result=1;}
temp.binNum[index++] = result;
}
for(int i=index; i < this->noOfBits; i++){
if(carry ==1 && this->binNum[i]==1){
result = this->binNum[i]-carry;
carry=0;
}
temp.binNum[index++]=result;
}
}
//-------------------------------- else minuhend is greater
else{
temp.binNum = new int [rhs.noOfBits];
while(index < this->noOfBits && index < rhs.noOfBits){
if(rhs.binNum[index]==0){
result = carry + rhs.binNum[index]-rhs.binNum[index];
}
else{
result = rhs.binNum[index]-rhs.binNum[index];
carry=0;
}
if(result == -1){carry =1; result=1;}
temp.binNum[index++] = result;
//index++;
}
for(int i=index; i < rhs.noOfBits; i++){
if(carry ==1 && rhs.binNum[i]==1){
result = rhs.binNum[i]-carry;
carry=0;
}
temp.binNum[index++]=result;
}
}
temp.noOfBits = index;
return temp;
}
*/
bool operator ==(const BinaryNum &rhs){
int left=toDecimal(this->binNum, this->noOfBits);
int right=toDecimal(rhs.binNum, rhs.noOfBits);
if( left == right ) {return true;}
return false;
}
//--------end of modified
void Print(){
if(binNum != 0){
for(int i = 0 ; i< noOfBits ; i++)
cout<<binNum[i];
}
//out<<endl;
}
//--------------- << operator
friend ostream & operator << (ostream &out, const BinaryNum & obj){
for(int i = 0 ; i< obj.noOfBits; i++){
out << obj.binNum[obj.noOfBits-i-1];
}
out << endl;
return out;
}
//--------------- >>
istream &operator >>(istream &in){
char buffer[50];
in >> buffer;
int size=0;
while(buffer[size++] == '\0');
if(this->noOfBits !=0) this->noOfBits= size-1;
this->binNum = new int [this->noOfBits];
for(int i=0; i< this->noOfBits; i++) this->binNum[i] = buffer[i]-'0';
}
~BinaryNum(){
if(noOfBits !=0) delete []this->binNum;
binNum = 0; // or nullptrx
}
};
int main()
{
BinaryNum b1; //noOfBits = 0, binNum is NULL
BinaryNum b2("1111"); //noOfBits = 3, binNum is {1,0,1}
BinaryNum b3("1111"); //noOfBits = 4, binNum is {1,0,0,
cout << (b3+b2);
cout << (b2-b3);
cout << (b2 == b3);
return 0;
}
|
#ifndef PCBROUTER_GRID_DIFF_PAIR_NETCLASS_H
#define PCBROUTER_GRID_DIFF_PAIR_NETCLASS_H
#include "GridNetclass.h"
class GridDiffPairNetclass : public GridNetclass {
public:
//ctor
GridDiffPairNetclass(const int id = -1,
const int clearance = 0,
const int trace_width = 0,
const int via_dia = 0,
const int via_drill = 0,
const int uvia_dia = 0,
const int uvia_drill = 0,
const int first_base_gnc = -1,
const int second_base_gnc = -1)
: GridNetclass(id, clearance, trace_width, via_dia, via_drill, uvia_dia, uvia_drill),
mFirstBaseGridNetclassId(first_base_gnc),
mSecondBaseGridNetclassId(second_base_gnc) {}
//dtor
~GridDiffPairNetclass() {}
int getFirstBaseGridNetclassId() { return mFirstBaseGridNetclassId; }
int getSecondBaseGridNetclassId() { return mSecondBaseGridNetclassId; }
private:
int mFirstBaseGridNetclassId = -1;
int mSecondBaseGridNetclassId = -1;
};
#endif
|
/**
* Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include "video_sink_surface.h"
#include <multimedia/component.h>
#include "multimedia/mmmsgthread.h"
#include "multimedia/media_attr_str.h"
#include <multimedia/mm_debug.h>
#include "media_surface_utils.h"
#include "media_surface_texture.h"
namespace YUNOS_MM
{
MM_LOG_DEFINE_MODULE_NAME("VideoSinkSurface")
//#define FUNC_TRACK() FuncTracker tracker(MM_LOG_TAG, __FUNCTION__, __LINE__)
#define FUNC_TRACK()
class MediaSurfaceTexureListener : public YunOSMediaCodec::SurfaceTextureListener {
public:
MediaSurfaceTexureListener(VideoSinkSurface *owner) { mOwner = owner; }
virtual ~MediaSurfaceTexureListener() {}
virtual void onMessage(int msg, int param1, int param2) {
if (mOwner) {
mOwner->notify(Component::kEventUpdateTextureImage, param1, param2, nilParam);
}
}
private:
VideoSinkSurface* mOwner;
};
//////////////////////////////////////////////////////////////////////////////////
VideoSinkSurface::VideoSinkSurface()
: mCanvas(NULL),
mSurfaceWrapper(NULL),
mSurfaceTexture(NULL),
mNativeWindow(NULL),
mBQProducer(NULL)
{
FUNC_TRACK();
}
VideoSinkSurface::~VideoSinkSurface()
{
FUNC_TRACK();
}
///////////////////////////////////////// RawVideo render
void VideoSinkSurface::WindowSurfaceRender(YunOSMediaCodec::SurfaceWrapper* winSurface, MediaBufferSP buffer)
{
FUNC_TRACK();
int32_t width = 0, height = 0, format = 0;
uint8_t *buf[3] = {NULL, NULL, NULL};
int32_t offset[3] = {0, 0, 0};
int32_t stride[3] = {0, 0, 0};
int32_t isRgb = 0;
MediaMetaSP meta = buffer->getMediaMeta();
if (!meta) {
ERROR("no meta data");
return;
}
if (buffer->isFlagSet(MediaBuffer::MBFT_EOS) || !(buffer->size())) {
INFO("abort, EOS or buffer size is zero");
return;
}
meta->getInt32(MEDIA_ATTR_WIDTH, width);
meta->getInt32(MEDIA_ATTR_HEIGHT, height);
meta->getInt32(MEDIA_ATTR_COLOR_FORMAT, format);
if (winSurface == NULL || width <= 0 || height <=0/* || format != AV_PIX_FMT_YUV420P*/)
return;
if (!meta->getInt32(MEDIA_ATTR_COLOR_FOURCC, isRgb))
isRgb = 1;
else
isRgb = 0;
DEBUG("width: %d, height: %d, format: %x, rgb: %d", width, height, format, isRgb);
if (!(buffer->getBufferInfo((uintptr_t *)buf, offset, stride, 3))) {
WARNING("fail to retrieve data from mediabuffer");
}
for (int i=0; i<3; i++) {
DEBUG("i: %d, buf: %p, offset: %d, stride: %d", i, buf[i], offset[i], stride[i]);
}
uint32_t flags;
if (winSurface && !mCanvas->isSurfaceCfg) {
int ret = 0;
ret = winSurface->set_buffers_dimensions(width, height, flags);
uint32_t halFormat = FMT_PREF(YV12);
if (isRgb)
halFormat = FMT_PREF(RGBA_8888);
ret |= winSurface->set_buffers_format(halFormat, flags);
ret |= winSurface->set_usage(ALLOC_USAGE_PREF(HW_TEXTURE) |
//ALLOC_USAGE_PREF(EXTERNAL_DISP) |
ALLOC_USAGE_PREF(SW_READ_OFTEN) |
ALLOC_USAGE_PREF(SW_WRITE_OFTEN),
flags);
int bufCnt = 5;
int minUndequeue = 2;
ret |= winSurface->set_buffer_count(bufCnt, flags);
MMNativeBuffer *anb[16] = {NULL,};
for (int i = 0; i < bufCnt; i++)
winSurface->dequeue_buffer_and_wait(&anb[i], flags);
for (int i = 0; i < minUndequeue; i++)
winSurface->cancel_buffer(anb[i], -1, flags);
for (int i = minUndequeue; i < bufCnt; i++) {
fillBufferBlank(winSurface, anb[i]);
winSurface->queueBuffer(anb[i], -1, flags);
winSurface->finishSwap(flags);
}
INFO("config native window, return %d", ret);
mCanvas->isSurfaceCfg = true;
}
int fenceFd = -1;
void* pointer = NULL;
MMNativeBuffer* anb = NULL;
/*
Rect rect;
rect.left = 0;
rect.top = 0;
rect.right = width;
rect.bottom = height;
*/
/*
anw->dequeueBuffer(anw,
&anb, &fenceFd);
*/
winSurface->dequeue_buffer_and_wait(&anb, flags);
if (!anb) {
ERROR("dequeue buffer but get NULL");
return;
}
/*
winSurface->mapBuffer(anb,
GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
rect, &pointer);
*/
winSurface->mapBuffer(anb, 0, 0, width, height, &pointer, flags);
if (!pointer) {
ERROR("fail to map native window buffer");
return;
}
int srcW = width, srcH = height;
int dstW = anb->stride, dstH = anb->height;
int32_t scaleFactor[3] = {1, 2, 2}; // for YV12, W/H scale factor is same
uint8_t *dstY = (uint8_t*)pointer;
uint8_t *dstV = dstY + dstW * dstH;
#ifdef __USEING_UV_STRIDE16__
int uvStride = ((dstW/scaleFactor[2] + 15) & (~15));
#else
int uvStride = dstW/scaleFactor[2];
#endif
//uint8_t *dstU = dstY + dstW * dstH + dstW * dstH / 4;
uint8_t *dstU = dstY + dstW * dstH + uvStride * dstH / 2;
if (isRgb) {
srcW *= 4;
dstW *= 4;
}
for(int j = 0; j < srcH/scaleFactor[0]; j++) {
memcpy(dstY, buf[0]+ j * stride[0], srcW/scaleFactor[0]);
dstY += dstW/scaleFactor[0];
}
if (isRgb)
goto out;
for(int j = 0; j < srcH/scaleFactor[1]; j++) {
memcpy(dstU, buf[1]+ j * stride[1], srcW/scaleFactor[1]);
dstU += uvStride;
}
for(int j = 0; j < srcH/scaleFactor[2]; j++) {
memcpy(dstV, buf[2]+ j * stride[2], srcW/scaleFactor[2]);
dstV += uvStride;
}
out:
#if 0
static FILE *fp = NULL;
if (fp == NULL) {
char name[128];
sprintf(name, "/data/%dx%d.rgb888", width, height);
fp = fopen(name, "wb");
}
fwrite(pointer, srcW, srcH, fp);
#endif
winSurface->unmapBuffer(anb, flags);
winSurface->queueBuffer(anb, fenceFd, flags);
winSurface->finishSwap(flags);
}
mm_status_t VideoSinkSurface::initCanvas()
{
FUNC_TRACK();
mCanvas = new VSSCanvas();
if (!mCanvas){
ERROR("initCanvas new memory failed\n");
return MM_ERROR_NO_MEM;
}
mCanvas->isSurfaceCfg = false;
return MM_ERROR_SUCCESS;
}
mm_status_t VideoSinkSurface::drawCanvas_raw(MediaBufferSP buffer)
{
FUNC_TRACK();
MediaMetaSP meta = buffer->getMediaMeta();
void *surface = NULL;
bool isTexture = false;
if (!meta) {
ERROR("no meta data");
return MM_ERROR_INVALID_PARAM;
}
if (meta) {
if (meta->getPointer(MEDIA_ATTR_VIDEO_SURFACE, (void *&)surface))
isTexture = false;
else if (meta->getPointer("surface-texture", (void *&)surface) && surface)
isTexture = true;
if (surface && !mSurfaceWrapper) {
if (isTexture) {
mSurfaceTexture = (YunOSMediaCodec::MediaSurfaceTexture *)surface;
mSurfaceTextureListener.reset(new MediaSurfaceTexureListener(this));
mSurfaceTexture->setListener(mSurfaceTextureListener.get());
mSurfaceWrapper = new YunOSMediaCodec::SurfaceTextureWrapper(mSurfaceTexture);
} else {
mNativeWindow = (WindowSurface*) surface;
mSurfaceWrapper = new YunOSMediaCodec::WindowSurfaceWrapper(mNativeWindow);
}
}
if (surface && surface != mNativeWindow && surface != mSurfaceTexture) {
ERROR("surface is not consistent");
return MM_ERROR_INVALID_PARAM;
}
}
WindowSurfaceRender(mSurfaceWrapper, buffer);
return MM_ERROR_SUCCESS;
}
mm_status_t VideoSinkSurface::uninitCanvas()
{
FUNC_TRACK();
if (mCanvas) {
delete mCanvas;
mCanvas = NULL;
}
if (mSurfaceTexture) {
mSurfaceTexture->setListener(NULL);
}
if (mSurfaceWrapper)
delete mSurfaceWrapper;
mSurfaceWrapper = NULL;
if (mBQProducer)
mBQProducer->disconnect();
mBQProducer = NULL;
return MM_ERROR_SUCCESS;
}
void VideoSinkSurface::fillBufferBlank(YunOSMediaCodec::SurfaceWrapper* winSurface, MMNativeBuffer *anb) {
void* pointer = NULL;
uint32_t flags;
if (!winSurface || !anb)
return;
winSurface->mapBuffer(anb, 0, 0, anb->width, anb->height, &pointer, flags);
if (!pointer) {
ERROR("fail to map native window buffer");
return;
}
uint8_t *dstY = (uint8_t*)pointer;
int dstW = anb->stride, dstH = anb->height;
uint8_t *dstV = dstY + dstW * dstH;
memset(dstY, 0, anb->stride * anb->height);
memset(dstV, 128, anb->stride * anb->height / 2);
winSurface->unmapBuffer(anb, flags);
}
// ////////////////////// GraphicsBufferHandle typed buffer render
// BQ producer listener
void MyProducerListener::onBufferReleased(YNativeSurfaceBuffer *buffer) {
DEBUG("release buffer: %p", buffer);
nativeBufferDecRef(buffer);
}
mm_status_t VideoSinkSurface::drawCanvas_graphicsBufferHandle(MediaBufferSP buffer)
{
FUNC_TRACK();
uintptr_t buffers[3] = {0};
int32_t offsets[3] = {0};
int32_t strides[3] = {0};
DEBUG();
if (!buffer || buffer->isFlagSet(MediaBuffer::MBFT_EOS) || !mBQProducer)
return MM_ERROR_SUCCESS;
buffer->getBufferInfo((uintptr_t *)buffers, offsets, strides, 3);
MMBufferHandleT target_t = *(MMBufferHandleT*)buffers[0];
ASSERT(target_t);
#ifdef __MM_YUNOS_YUNHAL_BUILD__
int format = FMT_PREF(NV12);
#else
int format = FMT_PREF(YV12);
#endif
NativeWindowBuffer* nwb = new NativeWindowBuffer(mWidth, mHeight, format,
ALLOC_USAGE_PREF(HW_TEXTURE) | ALLOC_USAGE_PREF(HW_RENDER), /*x_stride*/ mWidth, target_t, false);
nwb->bufInit();
nativeBufferIncRef(nwb);
mBQProducer->attachAndPostBuffer((MMNativeBuffer*)nwb);
return MM_ERROR_SUCCESS;
}
mm_status_t VideoSinkSurface::drawCanvas(MediaBufferSP buffer)
{
mm_status_t ret = MM_ERROR_SUCCESS;
MediaBuffer::MediaBufferType type = buffer->type();
DEBUG();
switch (type) {
case MediaBuffer::MBT_RawVideo:
ret = drawCanvas_raw(buffer);
break;
case MediaBuffer::MBT_GraphicBufferHandle:
ret = drawCanvas_graphicsBufferHandle(buffer);
break;
default:
break;
}
return ret;
}
mm_status_t VideoSinkSurface::setParameter(const MediaMetaSP & meta) {
bool ret = true;
void* ptr = NULL;
ret = meta->getPointer(MEDIA_ATTR_VIDEO_BQ_PRODUCER, ptr);
if (ret) {
mBQProducer = (MMBQProducer*)ptr;
mProducerListener.reset(new MyProducerListener());
mBQProducer->connect(mProducerListener);
}
return VideoSink::setParameter(meta);
}
} // YUNOS_MM
/////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
YUNOS_MM::Component* createComponent(const char* mimeType, bool isEncoder)
{
YUNOS_MM::VideoSinkSurface *sinkComponent = new YUNOS_MM::VideoSinkSurface();
if (sinkComponent == NULL) {
return NULL;
}
return static_cast<YUNOS_MM::Component*>(sinkComponent);
}
void releaseComponent(YUNOS_MM::Component *component)
{
// FIXME, uninit()?
delete component;
}
}
|
#include <eosiolib/eosio.hpp>
#include <eosiolib/print.hpp>
using namespace eosio;
class summ : public eosio::contract
{
public:
using contract::contract;
void add(uint32_t a,uint32_t b)
{
uint32_t c=a+b;
print("sum",a,b,c);
}
};
EOSIO_ABI( summ, (add))
|
#ifndef _POINT_CLOUD_MAP_
#define _POINT_CLOUD_MAP_
#include "stdafx.h"
#include "Geometry/include/geometry.h"
#include "PclPointCloud.h"
#include <gtsam/geometry/Pose2.h>
#include <gtsam/nonlinear/Values.h>
#define _RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16)))
using namespace gtsam;
using namespace std;
class CPointCloudMap
{
public:
vector<CPosture> poses;
vector<CPclPointCloud> clouds;
Eigen::Affine3d odompos;
unsigned int input_cloud_count;
unsigned int input_ndtcloud_count;
public:
CPointCloudMap();
bool AddCloudandPose(CPclPointCloud cloud, Eigen::Affine3d odometry, bool loop = false);
void AddCloudandAbsPose(CPclPointCloud cloud, CPosture abspose, bool loop);
void CorrectPoses(Values& cur_estimate);
void Plot(CScreenReference& ScrnRef, CDC* pDC, COLORREF crColorPoint, int nPointSize);
};
#endif
|
#pragma once
#include <iosfwd>
#include <vector>
#include <cmath>
inline bool floatEQ(const float x, const float y) {
return fabsf(x - y) < 0.00001;
}
/** Angle class (high-lvl angle handling)
* - automated normalization and constraining
* - change 'angle' through methods:
* - DO _NOT_ WRITE ::rad and ::deg directly
* - READING from ::rad and ::deg is encouraged and prefered
**/
class Angle {
public:
Angle();
Angle(float rad);
Angle(int deg);
// parse from string, should match operator<<
//static Angle fromString(const std::string& s);
// normalization stuff, static to be used everywhere EXCLUSIVLY!
// radians --> [-pi ... pi]
// degree --> [-180 ... 180]
static float normalize(const float &rad);
static double normalize(const double &rad);
static int normalize(const int °);
// these are NOT TO BE USED, nevertheless it's too late,
// so those are better kept here!
// radians --> [0 ... 2*pi]
// degree --> [0 ... 360]
static float pos_normalize(const float &rad);
static double pos_normalize(const double &rad);
static int pos_normalize(const int °);
// use these to change the underlying angle
Angle &set(const float &rad);
Angle &set(const int °);
Angle &set(const Angle &obj);
Angle &add(const Angle &other);
Angle &sub(const Angle &other);
// TODO NEED THEM TOO TODO
// Angle& add(const float& rad);
// Angle& add(const int& deg);
// Angle& sub(const float& rad);
// Angle& sub(const int& deg);
Angle clamp(float maxVal) const;
// returns new Angle-object with shortest(!) turn dist between this and 'ang'
// for [-180 ... 180] and [-pi ... pi] constrained angles,
// this is always just the _normalized_ difference ;)
Angle dist(const Angle &ang) const;
// (weighted) merge two angles ... this is not as simple as one might think
// nevertheless, it's never used by anyone inside the framework, thus
// mark it here as potential TODO, but don't implement it...
Angle merge(const Angle &other, const float &my_weight = 1.f,
const float &other_weight = 1.f);
Angle operator-(const Angle &other) const;
Angle operator+(const Angle &other) const;
Angle operator*(const Angle &other) const;
// return the (calculated) degree equivalent of this angle
// [-180 .. 180] (left negative)
//int deg() const; TODO FIXME
int deg;
// UNDERLYING DATA ITEM
// [-pi .. pi] (counter-clock wise)
float rad;
};
// TODO: operators should return by-value, by default!
/** Coord class (high-lvl coordinate handling) */
class DirectedCoord;
class Coord {
public:
Coord();
Coord(const float &x, const float &y);
Coord(const int &x, const int &y);
Coord(const std::vector<float> &xy);
Coord(const Angle &); // create unit vector for this angle
float norm2() const;
// parse from string, should match operator<<
//static Coord fromString(const std::string& s);
Coord normalized() const;
Coord clamp(float maxVal) const;
float direction() const;
// get distance from 'target' to this coord
float dist(const Coord &target) const;
// get distance from Coord(0,0) (coords origin) to this coord
float dist() const;
// get angle for this coordinate (from Coord(0,0))
Angle angle() const;
float dot(const Coord &other) const;
// get angle from 'target' arbitrary coordinate to this Coord TODO!!!!
// Angle angle(const Coord& target) const;
// add 'other' to this coordinate
Coord &add(const Coord &other);
// substract 'other' from this coordinate
Coord &sub(const Coord &other);
Coord rotate(const Angle &) const;
Coord operator-(const Coord &other) const;
Coord operator+(const Coord &other) const;
Coord operator*(const Coord &other) const;
inline Coord& operator-=(const Coord &other) {
return *this = *this - other;
}
inline Coord& operator+=(const Coord &other) {
return *this = *this + other;
}
friend Coord operator*(float scalar, const Coord &other);
friend Coord operator*(const Coord &other, float scalar);
friend Coord operator/(float scalar, const Coord &other);
friend Coord operator/(const Coord &other, float scalar);
bool operator==(const Coord &other);
bool operator!=(const Coord &other);
Coord &operator/=(float scalar);
// add 'dist' towards 'dir' to coordinate
Coord &add(const Angle &dir, const float &dist);
// get distance from coord to line with startpoint start and endpoint end
Coord closestPointOnLine(Coord start, Coord end, bool onLine = false) const;
DirectedCoord lookAt(const Coord &other);
float x;
float y;
};
// what belongs together->belongs together ;D
class DirectedCoord {
public:
DirectedCoord();
DirectedCoord(const DirectedCoord &other);
// parse from string, should match operator<<
//static DirectedCoord fromString(const std::string& s);
// TODO / FIXME: STOP USING vector<float> as coord / coord+angle!!!!
// as long as it still exists in the framework, we need this:
DirectedCoord(const std::vector<float> &vals);
DirectedCoord(const Angle &a, const Coord &c);
DirectedCoord(const Coord &c, const Angle &a); // hrhr take them' all ;D
DirectedCoord(const float &x, const float &y, const float &rad);
// DirectedCoord(const float& x, const float& y, const int& deg);
// DirectedCoord(const int& x, const int& y, const float& rad);
// DirectedCoord(const int& x, const int& y, const int& deg);
DirectedCoord &add(const DirectedCoord &other);
DirectedCoord &sub(const DirectedCoord &other);
// TODO: need this badly, this is already somewhere
// Coord get_intersection(const Angle& o_angle);
//DirectedCoord normalized() const;
DirectedCoord clamp(float maxVal) const;
// walkTo goes starts from one coordinate and walks a relative path
// x.walk(y) starts at x with direction x.angle
// and walks by y and turns by angle y.angle
// (same as toRCS but with correct angles)
DirectedCoord walk(const DirectedCoord &delta) const;
// transform to RCS/WCS (UNTESTED=?=)
DirectedCoord toRCS(const DirectedCoord &origin) const;
DirectedCoord toWCS(const DirectedCoord &origin) const;
DirectedCoord operator=(const DirectedCoord &other);
DirectedCoord &operator+=(const DirectedCoord &other);
DirectedCoord operator-(const DirectedCoord &other) const;
DirectedCoord operator+(const DirectedCoord &other) const;
DirectedCoord operator*(const DirectedCoord &other) const;
bool isNull() const;
Angle angle;
Coord coord;
};
std::ostream &operator<<(std::ostream &s, const Angle &obj);
std::ostream &operator<<(std::ostream &s, const Coord &obj);
std::ostream &operator<<(std::ostream &s, const DirectedCoord &obj);
// vim: set ts=4 sw=4 sts=4 expandtab:
|
#include "repositorio_salas.h"
#include <algorithm>
#include <stdexcept>
#include <herramientas/lector_txt/lector_txt.h>
using namespace App_RepositorioSalas;
Repositorio_salas::Repositorio_salas()
{
iniciar_mapa();
}
/**
* Se extrae el primer item de la lista y se le añade un uso.
*/
const std::string Repositorio_salas::obtener_ruta_sala(App_Definiciones::direcciones dir)
{
std::vector<Item_repositorio>& vec=mapa_rutas.at(dir);
auto item=vec.begin();
item->sumar_uso();
std::sort(vec.begin(), vec.end());
return item->acc_ruta();
}
/**
* Inicializa el mapa de rutas creando tantas claves como posibilidades de
* dirección distintas hay y montando dentro un vector de "Item_repositorio".
*/
void Repositorio_salas::iniciar_mapa()
{
using namespace App_Definiciones;
std::vector<direcciones> dr = {
/* 1 */ direcciones::arriba,
/* 2 */ direcciones::derecha,
/* 3 */ direcciones::arriba | direcciones::derecha,
/* 4 */ direcciones::abajo,
/* 5 */ direcciones::arriba | direcciones::abajo,
/* 6 */ direcciones::derecha | direcciones::abajo,
/* 7 */ direcciones::derecha | direcciones::abajo | direcciones::arriba,
/* 8 */ direcciones::izquierda,
/* 9 */ direcciones::izquierda | direcciones::arriba,
/* 10 */ direcciones::izquierda | direcciones::derecha,
/* 11 */ direcciones::izquierda | direcciones::derecha | direcciones::arriba,
/* 12 */ direcciones::izquierda | direcciones::abajo,
/* 13 */ direcciones::izquierda | direcciones::abajo | direcciones::arriba,
/* 14 */ direcciones::izquierda | direcciones::abajo | direcciones::derecha,
/* 15 */ direcciones::izquierda | direcciones::abajo | direcciones::derecha | direcciones::arriba};
for(auto d : dr)
{
std::vector<Item_repositorio> v;
mapa_rutas[d]=v;
}
}
void Repositorio_salas::iniciar(const std::string& r, const App_Lectores::Info_obstaculos_genericos& iog)
{
//Abrir el fichero con la ruta...
DLibH::Lector_txt L(r, '#');
if(!L)
{
LOG<<"ERROR: Imposible localizar repositorio de salas en "<<r<<std::endl;
throw std::runtime_error("Error al iniciar repositorio de salas: repositorio no localizado.");
}
else
{
std::string linea;
while(true)
{
linea=L.leer_linea();
if(!L) break;
LOG<<"Procesando "<<linea<<std::endl;
App_Generador::Parser_salas p;
p.parsear_fichero(linea, iog);
if(!p.comprobar_validez_sala())
{
LOG<<"ERROR: La sala no pasa la validación : "<<linea<<std::endl;
throw std::runtime_error("Error al iniciar repositorio de salas: error de validación.");
}
mapa_rutas[p.acc_direcciones_entradas()].push_back(linea);
}
}
//Comprobamos que hay mapas en todos los tipos y los reordenamos al azar.
int dir=1; //Se usará para llevar la cuenta si falla en un directorio concreto.
for(auto& d : mapa_rutas)
{
auto& v=d.second;
if(! v.size())
{
LOG<<"ERROR: Al menos una posible dirección no tiene salas ["<<dir<<"]"<<std::endl;
throw std::runtime_error("Error al iniciar repositorio de salas: error de integridad.");
}
std::random_shuffle(v.begin(), v.end());
++dir;
}
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/client/audio_decode_scheduler.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "remoting/client/audio_player.h"
#include "remoting/codec/audio_decoder.h"
#include "remoting/proto/audio.pb.h"
namespace remoting {
AudioDecodeScheduler::AudioDecodeScheduler(
scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> audio_decode_task_runner,
scoped_ptr<AudioPlayer> audio_player)
: main_task_runner_(main_task_runner),
audio_decode_task_runner_(audio_decode_task_runner),
audio_player_(audio_player.Pass()) {
}
AudioDecodeScheduler::~AudioDecodeScheduler() {
}
void AudioDecodeScheduler::Initialize(const protocol::SessionConfig& config) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
decoder_.reset(AudioDecoder::CreateAudioDecoder(config).release());
}
void AudioDecodeScheduler::ProcessAudioPacket(scoped_ptr<AudioPacket> packet,
const base::Closure& done) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
audio_decode_task_runner_->PostTask(FROM_HERE, base::Bind(
&AudioDecodeScheduler::DecodePacket, base::Unretained(this),
base::Passed(&packet), done));
}
void AudioDecodeScheduler::DecodePacket(scoped_ptr<AudioPacket> packet,
const base::Closure& done) {
DCHECK(audio_decode_task_runner_->BelongsToCurrentThread());
scoped_ptr<AudioPacket> decoded_packet = decoder_->Decode(packet.Pass());
main_task_runner_->PostTask(FROM_HERE, base::Bind(
&AudioDecodeScheduler::ProcessDecodedPacket, base::Unretained(this),
base::Passed(decoded_packet.Pass()), done));
}
void AudioDecodeScheduler::ProcessDecodedPacket(scoped_ptr<AudioPacket> packet,
const base::Closure& done) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
audio_player_->ProcessAudioPacket(packet.Pass());
done.Run();
}
} // namespace remoting
|
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "optimization.h"
using namespace alglib;
void function1_grad(const real_1d_array &x, double &func, real_1d_array &grad, void *ptr)
{
//
// this callback calculates f(x0,x1) = 100*(x0+3)^4 + (x1-3)^4
// and its derivatives df/d0 and df/dx1
//
func = 100*pow(x[0]+3,4) + pow(x[1]-3,4);
grad[0] = 400*pow(x[0]+3,3);
grad[1] = 4*pow(x[1]-3,3);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "talker");
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
ros::Rate loop_rate(10);
int count = 0;
//
// This example demonstrates minimization of f(x,y) = 100*(x+3)^4+(y-3)^4
// subject to inequality constraints:
// * x>=2 (posed as general linear constraint),
// * x+y>=6
// using BLEIC optimizer.
//
real_1d_array x = "[5,5]";
real_2d_array c = "[[1,0,2],[1,1,6]]";
integer_1d_array ct = "[1,1]";
minbleicstate state;
minbleicreport rep;
//
// These variables define stopping conditions for the optimizer.
//
// We use very simple condition - |g|<=epsg
//
double epsg = 0.000001;
double epsf = 0;
double epsx = 0;
ae_int_t maxits = 0;
//
// Now we are ready to actually optimize something:
// * first we create optimizer
// * we add linear constraints
// * we tune stopping conditions
// * and, finally, optimize and obtain results...
//
minbleiccreate(x, state);
minbleicsetlc(state, c, ct);
minbleicsetcond(state, epsg, epsf, epsx, maxits);
alglib::minbleicoptimize(state, function1_grad);
minbleicresults(state, x, rep);
//
// ...and evaluate these results
//
printf("%d\n", int(rep.terminationtype)); // EXPECTED: 4
printf("%s\n", x.tostring(2).c_str()); // EXPECTED: [2,4]
return 0;
return 0;
}
|
struct event * malloc_flow(int client_id)
{
struct event *temp_event1; // ponteiro para o novo no a inserir
temp_event1 = (event *)malloc(1*sizeof(event));
temp_event1->event_id = FLOW_EVENT;
temp_event1->client_id = client_id;
temp_event1->server_id = 0;
temp_event1->time = INF;
temp_event1->next = NULL;
temp_event1->prev = NULL;
//retorna endereco do evento de fluxo alocado
return temp_event1;
}
struct event * get_next(event *list)
{
return list->next;
}
float get_time(event *temp)
{
if(temp == NULL) return INF;
return temp->time;
}
int get_client_id(event *temp)
{
return temp->client_id;
}
int get_server_id(event *temp)
{
return temp->server_id;
}
int get_event_id(event *temp)
{
return temp->event_id;
}
|
/* NO WARRANTY
*
* BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO
* WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
* LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS
* AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO
* THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD
* THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
* NECESSARY SERVICING, REPAIR OR CORRECTION.
*
* IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
* WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY
* AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES,
* INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
* DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
* (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
* RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES
* OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
* PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGES.
*/
#include "stdafx.h"
#include "resource.h" // Hauptsymbole
#include "BmpFileDialog.h"
#include "Application\i18n\ResourceTranslater.h"
#include "Application\Configuration\ParameterManager.h"
// In order to ease use, these values have been hard coded in bmpdlg.rc
// This avoids the need for another header file.
#define IDC_PREVIEW (5000)
#define IDC_PREVIEWBTN (5001)
#define IDC_WIDTH (5002)
#define IDC_HEIGHT (5003)
#define IDC_DEPTH (5004)
#define IDC_FSIZE (5005)
#define IDC_SHOWPREVIEW (5006)
HBITMAP CBmpDialog::hpreview = NULL;
BOOL CBmpDialog::m_showpreview = TRUE;
// Proprietary Hook function for open dialog
UINT APIENTRY OFNHookProc( HWND hdlg, UINT uiMsg, WPARAM wParam, LPARAM lParam )
{
PROC_TRACE;
LPDRAWITEMSTRUCT lpdis;
BITMAP bm;
LPNMHDR pnmh;
char filename[1024],str[255];
int height,height2,width,width2;
NMHDR nmh;
switch (uiMsg)
{
case WM_COMMAND:
if (LOWORD(wParam) == IDC_SHOWPREVIEW)
{
CBmpDialog::m_showpreview = IsDlgButtonChecked(hdlg,IDC_SHOWPREVIEW);
SetDlgItemText(hdlg,IDC_PREVIEWBTN,"juhu");
if (!CBmpDialog::m_showpreview)
{
if (CBmpDialog::hpreview)
DeleteObject(CBmpDialog::hpreview);
CBmpDialog::hpreview = NULL;
HWND wnd = GetDlgItem(hdlg,IDC_PREVIEWBTN);
InvalidateRect(wnd,NULL,TRUE);
SetDlgItemText(hdlg,IDC_WIDTH,"");
SetDlgItemText(hdlg,IDC_HEIGHT,"");
SetDlgItemText(hdlg,IDC_DEPTH,"");
SetDlgItemText(hdlg,IDC_FSIZE,"");
}
else
{
nmh.code = CDN_SELCHANGE;
OFNHookProc(hdlg, WM_NOTIFY, 0, (LPARAM)&nmh);
}
}
break;
case WM_DRAWITEM:
if (CBmpDialog::hpreview)
{
lpdis = (LPDRAWITEMSTRUCT)lParam;
GetObject(CBmpDialog::hpreview,sizeof(BITMAP),&bm);
CPoint size(bm.bmWidth,bm.bmHeight);
HDC dcmem = CreateCompatibleDC(lpdis->hDC);
HBITMAP old = (HBITMAP)SelectObject(dcmem,CBmpDialog::hpreview);
if (bm.bmWidth > bm.bmHeight)
{
height = lpdis->rcItem.bottom - lpdis->rcItem.top;
float ratio = (float)bm.bmHeight/(float)bm.bmWidth;
lpdis->rcItem.bottom = (long) (lpdis->rcItem.top + (lpdis->rcItem.right-lpdis->rcItem.left)*ratio);
height2 = (height - (lpdis->rcItem.bottom - lpdis->rcItem.top))/2;
lpdis->rcItem.top += height2;
lpdis->rcItem.bottom += height2;
}
else
{
width = lpdis->rcItem.right - lpdis->rcItem.left;
float ratio = (float)bm.bmWidth/(float)bm.bmHeight;
lpdis->rcItem.right = (long) (lpdis->rcItem.left + (lpdis->rcItem.bottom-lpdis->rcItem.top)*ratio);
width2 = (width - (lpdis->rcItem.right - lpdis->rcItem.left))/2;
lpdis->rcItem.left += width2;
lpdis->rcItem.right += width2;
}
StretchBlt(lpdis->hDC,lpdis->rcItem.left,lpdis->rcItem.top,lpdis->rcItem.right-lpdis->rcItem.left,lpdis->rcItem.bottom-lpdis->rcItem.top,dcmem,0,0,bm.bmWidth,bm.bmHeight,SRCCOPY);
SelectObject(dcmem,old);
DeleteDC(dcmem);
}
break;
case WM_NOTIFY:
pnmh = (LPNMHDR) lParam;
if (pnmh->code == CDN_FILEOK)
{
if (CBmpDialog::hpreview)
DeleteObject(CBmpDialog::hpreview);
// This avoids an assert
_AFX_THREAD_STATE* pThreadState = AfxGetThreadState();
pThreadState->m_pAlternateWndInit = NULL;
return 0;
}
if (pnmh->code == CDN_INITDONE)
{
char buffer[200];
if (CBmpDialog::hpreview)
DeleteObject(CBmpDialog::hpreview);
CheckDlgButton(hdlg,IDC_SHOWPREVIEW,CBmpDialog::m_showpreview);
SetDlgItemText(GetParent(hdlg),IDOK,TRANSLATE("Ok"));
SetDlgItemText(GetParent(hdlg),IDCANCEL,TRANSLATE("Abbruch"));
SetDlgItemText(GetParent(hdlg),1090,TRANSLATE("Dateiname:"));
SetDlgItemText(GetParent(hdlg),1089,TRANSLATE("Dateitypen:"));
SetDlgItemText(GetParent(hdlg),1091,TRANSLATE("&Suchen in:"));
SetDlgItemText(hdlg,IDC_PREVIEW_STATIC,TRANSLATE("Vorschau"));
SetDlgItemText(hdlg,IDC_SHOWPREVIEW,TRANSLATE("Vorschau anzeigen"));
GetWindowText(GetParent(hdlg),buffer,sizeof(buffer)-1);
SetWindowText(GetParent(hdlg),TRANSLATE(buffer));
return 0;
}
if (pnmh->code == CDN_SELCHANGE)
{
if (!IsDlgButtonChecked(hdlg,IDC_SHOWPREVIEW))
{
if (CBmpDialog::hpreview)
DeleteObject(CBmpDialog::hpreview);
CBmpDialog::hpreview = NULL;
return 0;
}
SendMessage(GetParent(hdlg),CDM_GETFILEPATH ,1024,(LPARAM)filename);
if (CBmpDialog::hpreview)
DeleteObject(CBmpDialog::hpreview);
CBmpDialog::hpreview = (HBITMAP)LoadImage(AfxGetInstanceHandle(),filename,IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_CREATEDIBSECTION);
HWND wnd = GetDlgItem(hdlg,IDC_PREVIEWBTN);
InvalidateRect(wnd,NULL,TRUE);
if (CBmpDialog::hpreview) {
GetObject(CBmpDialog::hpreview,sizeof(BITMAP),&bm);
wsprintf(str,TRANSLATE("Breite: %d Bildpunkte"),bm.bmWidth);
SetDlgItemText(hdlg,IDC_WIDTH,str);
wsprintf(str,TRANSLATE("Höhe: %d Bildpunkte"),bm.bmHeight);
SetDlgItemText(hdlg,IDC_HEIGHT,str);
switch (bm.bmBitsPixel) {
case 1:
SetDlgItemText(hdlg,IDC_DEPTH,TRANSLATE("2 Farben (monocromatisch)"));
break;
case 4:
SetDlgItemText(hdlg,IDC_DEPTH,TRANSLATE("16 Farben"));
break;
SetDlgItemText(hdlg,IDC_DEPTH,TRANSLATE("256 Farben"));
break;
case 16:
SetDlgItemText(hdlg,IDC_DEPTH,TRANSLATE("65536 Farben"));
break;
case 24:
SetDlgItemText(hdlg,IDC_DEPTH,TRANSLATE("16 Millionen Farben"));
break;
default:
SetDlgItemText(hdlg,IDC_DEPTH,"-");
}
OFSTRUCT o;
HFILE f = OpenFile(filename,&o,OF_READ);
wsprintf(str,TRANSLATE("Grösse: %ld Kb"),GetFileSize((HANDLE)f,NULL)/1024);
SetDlgItemText(hdlg,IDC_FSIZE,str);
_lclose(f);
}
else {
SetDlgItemText(hdlg,IDC_WIDTH,"");
SetDlgItemText(hdlg,IDC_HEIGHT,"");
SetDlgItemText(hdlg,IDC_DEPTH,"");
SetDlgItemText(hdlg,IDC_FSIZE,"");
}
}
}
return 0;
}
IMPLEMENT_DYNAMIC(CBmpDialog, CFileDialog)
BEGIN_MESSAGE_MAP(CBmpDialog, CFileDialog)
//{{AFX_MSG_MAP(CBmpDialog)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
CBmpDialog::CBmpDialog(BOOL bOpenFileDialog,
LPCTSTR lpszDefExt,
LPCTSTR lpszFileName,
LPCTSTR lpstrInitialDir ,
DWORD dwFlags,
LPCTSTR lpszFilter,
CWnd* pParentWnd) :
CFileDialog(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd)
{
PROC_TRACE;
m_ofn.lpstrFilter = "Bitmaps (*.bmp)\0*.bmp\0"\
"All Files (*.*)\0*.*\0\0";
m_ofn.Flags |= (OFN_HIDEREADONLY |OFN_ENABLEHOOK| OFN_EXPLORER |OFN_ENABLETEMPLATE);
m_ofn.lpstrInitialDir = lpstrInitialDir;
m_ofn.hInstance = AfxGetInstanceHandle();
m_ofn.lpTemplateName = MAKEINTRESOURCE(IDC_PREVIEW);
m_ofn.lpfnHook = OFNHookProc;
}
|
#pragma once
#include "Jogador.h"
#include "Inimigo1.h"
class checarcolisao : public Jogador, Inimigo1
{
public:
protected:
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.